untitled-pixi-live2d-engine 1.5.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -39,7 +39,7 @@ var __async = (__this, __arguments, generator) => {
39
39
  step((generator = generator.apply(__this, __arguments)).next());
40
40
  });
41
41
  };
42
- import { EventEmitter, Matrix, loadTextures, Assets, Ticker, Transform, Point, Bounds, ExtensionType, Container, ObservablePoint, WebGPURenderer, WebGLRenderer, DOMAdapter, Texture, CanvasSource } from "pixi.js";
42
+ import { EventEmitter, Matrix, loadTextures, Assets, Ticker, Transform, Point, Bounds, ExtensionType, Container, WebGLRenderer, ObservablePoint, WebGPURenderer, DOMAdapter, Texture, CanvasSource } from "pixi.js";
43
43
  const LOGICAL_WIDTH = 2;
44
44
  const LOGICAL_HEIGHT = 2;
45
45
  const CSM_LOG_LEVEL_VERBOSE = 0;
@@ -105,7 +105,7 @@ const config = {
105
105
  preserveExpressionOnMotion: true,
106
106
  cubism: CubismFrameworkConfig
107
107
  };
108
- const VERSION = "1.5.0";
108
+ const VERSION = "1.5.1";
109
109
  const logger = {
110
110
  log(tag, ...messages) {
111
111
  if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
@@ -2941,6 +2941,11 @@ class Live2DModel extends Container {
2941
2941
  * @type {number}
2942
2942
  */
2943
2943
  __publicField(this, "gl", null);
2944
+ /**
2945
+ * Whether textures must be re-uploaded because the GL context was (re)bound
2946
+ * since the last `renderLive2D()`.
2947
+ */
2948
+ __publicField(this, "textureUploadPending", false);
2944
2949
  /**
2945
2950
  * Elapsed time in milliseconds since created.
2946
2951
  * @type {DOMHighResTimeStamp}
@@ -2979,12 +2984,9 @@ class Live2DModel extends Container {
2979
2984
  renderer.geometry.resetState();
2980
2985
  renderer.shader.resetState();
2981
2986
  renderer.texture.resetState();
2982
- let shouldUpdateTexture = false;
2983
- if (this.gl !== renderer.gl) {
2984
- this.gl = renderer.gl;
2985
- this.internalModel.updateWebGLContext(renderer.gl, this.generateUID());
2986
- shouldUpdateTexture = true;
2987
- }
2987
+ this.ensureWebGLContext(renderer);
2988
+ const shouldUpdateTexture = this.textureUploadPending;
2989
+ this.textureUploadPending = false;
2988
2990
  const { projectionMatrix, offset, worldTransformMatrix } = renderer.globalUniforms.globalUniformData;
2989
2991
  const adjustedWorld = tempWorldMatrix.copyFrom(worldTransformMatrix).append(this.groupTransform);
2990
2992
  const effectiveScale = getMatrixMaxScale(adjustedWorld) * renderer.resolution;
@@ -3181,10 +3183,13 @@ class Live2DModel extends Container {
3181
3183
  * Filter pipes collect their framebuffer bounds before the Live2D render pipe runs,
3182
3184
  * so waiting until `renderLive2D()` is too late for animated vertices.
3183
3185
  */
3184
- prepareForRender() {
3186
+ prepareForRender(renderer) {
3185
3187
  if (!this.internalModel) {
3186
3188
  return;
3187
3189
  }
3190
+ if (renderer instanceof WebGLRenderer) {
3191
+ this.ensureWebGLContext(renderer);
3192
+ }
3188
3193
  const frameDelta = this.deltaTime;
3189
3194
  this.deltaTime = 0;
3190
3195
  if (frameDelta) {
@@ -3192,6 +3197,18 @@ class Live2DModel extends Container {
3192
3197
  }
3193
3198
  this.updateDrawableBounds();
3194
3199
  }
3200
+ /**
3201
+ * Binds the renderer's GL context to the internal model if it changed.
3202
+ * Shared by `prepareForRender()` and `renderLive2D()`, whichever runs first.
3203
+ */
3204
+ ensureWebGLContext(renderer) {
3205
+ if (this.gl === renderer.gl) {
3206
+ return;
3207
+ }
3208
+ this.gl = renderer.gl;
3209
+ this.internalModel.updateWebGLContext(renderer.gl, this.generateUID());
3210
+ this.textureUploadPending = true;
3211
+ }
3195
3212
  generateUID() {
3196
3213
  return ++this.currentGlId;
3197
3214
  }
@@ -3227,7 +3244,7 @@ class Live2DModel extends Container {
3227
3244
  const effects = this.effects;
3228
3245
  if (effects) {
3229
3246
  if (effects.length) {
3230
- renderPipes.live2d.addPrepare(() => this.prepareForRender(), instructionSet);
3247
+ renderPipes.live2d.addPrepare(() => this.prepareForRender(renderer), instructionSet);
3231
3248
  }
3232
3249
  for (let i = 0; i < effects.length; i++) {
3233
3250
  const effect = effects[i];
@@ -108,7 +108,7 @@ var __async = (__this, __arguments, generator) => {
108
108
  preserveExpressionOnMotion: true,
109
109
  cubism: CubismFrameworkConfig
110
110
  };
111
- const VERSION = "1.5.0";
111
+ const VERSION = "1.5.1";
112
112
  const logger = {
113
113
  log(tag, ...messages) {
114
114
  if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
@@ -2944,6 +2944,11 @@ var __async = (__this, __arguments, generator) => {
2944
2944
  * @type {number}
2945
2945
  */
2946
2946
  __publicField(this, "gl", null);
2947
+ /**
2948
+ * Whether textures must be re-uploaded because the GL context was (re)bound
2949
+ * since the last `renderLive2D()`.
2950
+ */
2951
+ __publicField(this, "textureUploadPending", false);
2947
2952
  /**
2948
2953
  * Elapsed time in milliseconds since created.
2949
2954
  * @type {DOMHighResTimeStamp}
@@ -2982,12 +2987,9 @@ var __async = (__this, __arguments, generator) => {
2982
2987
  renderer.geometry.resetState();
2983
2988
  renderer.shader.resetState();
2984
2989
  renderer.texture.resetState();
2985
- let shouldUpdateTexture = false;
2986
- if (this.gl !== renderer.gl) {
2987
- this.gl = renderer.gl;
2988
- this.internalModel.updateWebGLContext(renderer.gl, this.generateUID());
2989
- shouldUpdateTexture = true;
2990
- }
2990
+ this.ensureWebGLContext(renderer);
2991
+ const shouldUpdateTexture = this.textureUploadPending;
2992
+ this.textureUploadPending = false;
2991
2993
  const { projectionMatrix, offset, worldTransformMatrix } = renderer.globalUniforms.globalUniformData;
2992
2994
  const adjustedWorld = tempWorldMatrix.copyFrom(worldTransformMatrix).append(this.groupTransform);
2993
2995
  const effectiveScale = getMatrixMaxScale(adjustedWorld) * renderer.resolution;
@@ -3184,10 +3186,13 @@ var __async = (__this, __arguments, generator) => {
3184
3186
  * Filter pipes collect their framebuffer bounds before the Live2D render pipe runs,
3185
3187
  * so waiting until `renderLive2D()` is too late for animated vertices.
3186
3188
  */
3187
- prepareForRender() {
3189
+ prepareForRender(renderer) {
3188
3190
  if (!this.internalModel) {
3189
3191
  return;
3190
3192
  }
3193
+ if (renderer instanceof pixi_js.WebGLRenderer) {
3194
+ this.ensureWebGLContext(renderer);
3195
+ }
3191
3196
  const frameDelta = this.deltaTime;
3192
3197
  this.deltaTime = 0;
3193
3198
  if (frameDelta) {
@@ -3195,6 +3200,18 @@ var __async = (__this, __arguments, generator) => {
3195
3200
  }
3196
3201
  this.updateDrawableBounds();
3197
3202
  }
3203
+ /**
3204
+ * Binds the renderer's GL context to the internal model if it changed.
3205
+ * Shared by `prepareForRender()` and `renderLive2D()`, whichever runs first.
3206
+ */
3207
+ ensureWebGLContext(renderer) {
3208
+ if (this.gl === renderer.gl) {
3209
+ return;
3210
+ }
3211
+ this.gl = renderer.gl;
3212
+ this.internalModel.updateWebGLContext(renderer.gl, this.generateUID());
3213
+ this.textureUploadPending = true;
3214
+ }
3198
3215
  generateUID() {
3199
3216
  return ++this.currentGlId;
3200
3217
  }
@@ -3230,7 +3247,7 @@ var __async = (__this, __arguments, generator) => {
3230
3247
  const effects = this.effects;
3231
3248
  if (effects) {
3232
3249
  if (effects.length) {
3233
- renderPipes.live2d.addPrepare(() => this.prepareForRender(), instructionSet);
3250
+ renderPipes.live2d.addPrepare(() => this.prepareForRender(renderer), instructionSet);
3234
3251
  }
3235
3252
  for (let i = 0; i < effects.length; i++) {
3236
3253
  const effect = effects[i];
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("pixi.js")):"function"==typeof define&&define.amd?define(["exports","pixi.js"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).PIXI=e.PIXI||{},e.PIXI.live2d=e.PIXI.live2d||{}),e.PIXI)}(this,function(e,t){"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=(e,t,s)=>t in e?i(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,d=(e,t)=>{for(var i in t||(t={}))o.call(t,i)&&h(e,i,t[i]);if(n)for(var i of n(t))a.call(t,i)&&h(e,i,t[i]);return e},u=(e,t)=>s(e,r(t)),c=(e,t,i)=>h(e,"symbol"!=typeof t?t+"":t,i),p=(e,t,i)=>new Promise((s,r)=>{var n=e=>{try{a(i.next(e))}catch(t){r(t)}},o=e=>{try{a(i.throw(e))}catch(t){r(t)}},a=e=>e.done?s(e.value):Promise.resolve(e.value).then(n,o);a((i=i.apply(e,t)).next())});const g={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"}))},m={log(e,...t){g.logLevel<=g.LOG_LEVEL_VERBOSE&&console.log(`[${e}]`,...t)},warn(e,...t){g.logLevel<=g.LOG_LEVEL_WARNING&&console.warn(`[${e}]`,...t)},error(e,...t){g.logLevel<=g.LOG_LEVEL_ERROR&&console.error(`[${e}]`,...t)}};function f(e,t,i){return e<t?t:e>i?i:e}function y(e,t){return Math.random()*(t-e)+e}function x(e,t,i,s,r){const n=t[s];null!==n&&typeof n===e&&(i[r]=n)}function M(e,t,i,s,r){const n=t[s];Array.isArray(n)&&(i[r]=n.filter(t=>null!==t&&typeof t===e))}function v(e){let t=e.lastIndexOf("/");return-1!=t&&(e=e.slice(0,t)),t=e.lastIndexOf("/"),-1!==t&&(e=e.slice(t+1)),e}function b(e,t){const i=e.indexOf(t);-1!==i&&e.splice(i,1)}const w=/^[a-zA-Z][a-zA-Z0-9+.-]*:/;function P(e,t){if(!t)return e;if(w.test(t))return t;if(t.startsWith("/"))return w.test(e)?new URL(t,e).toString():t;if(w.test(e))return new URL(t,e).toString();const i="http://example.com",s=e.startsWith("/")?i+e:`${i}/${e}`,r=new URL(t,s);let n=r.pathname+r.search+r.hash;return!e.startsWith("/")&&n.startsWith("/")&&(n=n.slice(1)),n}class E extends t.EventEmitter{constructor(e,t){super(),c(this,"expressionDataType","json"),c(this,"tag"),c(this,"settings"),c(this,"expressions",[]),c(this,"defaultExpression"),c(this,"currentExpression"),c(this,"reserveExpressionIndex",-1),c(this,"destroyed",!1),this.settings=e,this.tag=`ExpressionManager(${e.name})`}init(){this.defaultExpression=this.createDefaultExpression(),this.currentExpression=this.defaultExpression,this.stopAllExpressions()}createDefaultExpression(){return this.createExpression({},void 0)}loadExpression(e){return p(this,null,function*(){if(!this.definitions[e])return void m.warn(this.tag,`Undefined expression at [${e}]`);if(null===this.expressions[e])return void m.warn(this.tag,`Cannot set expression at [${e}] because it's already failed in loading.`);if(this.expressions[e])return this.expressions[e];const t=yield this._loadExpression(e);return this.expressions[e]=t,t})}_loadExpression(e){throw new Error("Not implemented.")}setRandomExpression(){return p(this,null,function*(){if(this.definitions.length){const e=[];for(let t=0;t<this.definitions.length;t++)null!==this.expressions[t]&&this.expressions[t]!==this.currentExpression&&t!==this.reserveExpressionIndex&&e.push(t);if(e.length){const t=Math.floor(Math.random()*e.length);return this.setExpression(t)}}return!1})}resetExpression(){this._setExpression(this.defaultExpression)}restoreExpression(){this._setExpression(this.currentExpression)}setExpression(e){return p(this,null,function*(){if("number"!=typeof e&&(e=this.getExpressionIndex(e)),!(e>-1&&e<this.definitions.length))return!1;if(e===this.expressions.indexOf(this.currentExpression))return!1;this.reserveExpressionIndex=e;const t=yield this.loadExpression(e);return!(!t||this.reserveExpressionIndex!==e)&&(this.reserveExpressionIndex=-1,this.currentExpression=t,this._setExpression(t),!0)})}update(e,t){return!this.isFinished()&&this.updateParameters(e,t)}destroy(){this.destroyed=!0,this.emit("destroy");this.definitions=void 0,this.expressions=void 0}}const L=40/7.5,D=1/150;class I{constructor(){c(this,"targetX",0),c(this,"targetY",0),c(this,"x",0),c(this,"y",0),c(this,"vx",0),c(this,"vy",0)}focus(e,t,i=!1){this.targetX=f(e,-1,1),this.targetY=f(t,-1,1),i&&(this.x=this.targetX,this.y=this.targetY)}update(e){const t=this.targetX-this.x,i=this.targetY-this.y;if(Math.abs(t)<.01&&Math.abs(i)<.01)return;const s=Math.sqrt(l(t,2)+l(i,2)),r=L/(1e3/e);let n=r*(t/s)-this.vx,o=r*(i/s)-this.vy;const a=Math.sqrt(l(n,2)+l(o,2)),h=r*D*e;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 F{constructor(e){c(this,"json"),c(this,"name"),c(this,"url"),c(this,"pose"),c(this,"physics"),this.json=e,this.url=e.url,this.name=v(this.url)}normalizeName(){this.name&&"name"!==this.name.toLowerCase()||(this.name=v(this.url))}setModelName(...e){for(const t of e){const e="string"==typeof t?t.trim():"";if(e&&"name"!==e.toLowerCase())return void(this.name=e)}this.normalizeName()}getFileStem(e){if(!e)return;const t=e.split(/[/\\]/).filter(Boolean).pop();return null==t?void 0:t.replace(/\.[^.]+$/,"")}resolveURL(e){return P(this.url,e)}replaceFiles(e){this.moc=e(this.moc,"moc"),void 0!==this.pose&&(this.pose=e(this.pose,"pose")),void 0!==this.physics&&(this.physics=e(this.physics,"physics"));for(let t=0;t<this.textures.length;t++)this.textures[t]=e(this.textures[t],`textures[${t}]`)}getDefinedFiles(){const e=[];return this.replaceFiles(t=>(e.push(t),t)),e}validateFiles(e){const t=(t,i)=>{const s=this.resolveURL(t);if(!e.includes(s)){if(i)throw new Error(`File "${t}" is defined in settings, but doesn't exist in given files`);return!1}return!0};[this.moc,...this.textures].forEach(e=>t(e,!0));return this.getDefinedFiles().filter(e=>t(e,!1))}}var T=(e=>(e[e.NONE=0]="NONE",e[e.IDLE=1]="IDLE",e[e.NORMAL=2]="NORMAL",e[e.FORCE=3]="FORCE",e))(T||{});class S{constructor(){c(this,"tag"),c(this,"debug",!1),c(this,"currentPriority",0),c(this,"reservePriority",0),c(this,"currentGroup"),c(this,"currentIndex"),c(this,"reservedGroup"),c(this,"reservedIndex"),c(this,"reservedIdleGroup"),c(this,"reservedIdleIndex")}reserve(e,t,i){if(i<=0)return m.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(e===this.currentGroup&&t===this.currentIndex)return m.log(this.tag,"Motion is already playing.",this.dump(e,t)),!1;if(e===this.reservedGroup&&t===this.reservedIndex||e===this.reservedIdleGroup&&t===this.reservedIdleIndex)return m.log(this.tag,"Motion is already reserved.",this.dump(e,t)),!1;if(1===i){if(0!==this.currentPriority)return m.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(e,t)),!1;if(void 0!==this.reservedIdleGroup)return m.log(this.tag,"Cannot start idle motion because another idle motion has reserved.",this.dump(e,t)),!1;this.setReservedIdle(e,t)}else{if(i<3){if(i<=this.currentPriority)return m.log(this.tag,"Cannot start motion because another motion is playing as an equivalent or higher priority.",this.dump(e,t)),!1;if(i<=this.reservePriority)return m.log(this.tag,"Cannot start motion because another motion has reserved as an equivalent or higher priority.",this.dump(e,t)),!1}this.setReserved(e,t,i)}return!0}start(e,t,i,s){if(1===s){if(this.setReservedIdle(void 0,void 0),0!==this.currentPriority)return m.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,i)),!1}else{if(t!==this.reservedGroup||i!==this.reservedIndex)return m.log(this.tag,"Cannot start motion because another motion has taken the place.",this.dump(t,i)),!1;this.setReserved(void 0,void 0,0)}return!!e&&(this.setCurrent(t,i,s),!0)}complete(){this.setCurrent(void 0,void 0,0)}setCurrent(e,t,i){this.currentPriority=i,this.currentGroup=e,this.currentIndex=t}setReserved(e,t,i){this.reservePriority=i,this.reservedGroup=e,this.reservedIndex=t}setReservedIdle(e,t){this.reservedIdleGroup=e,this.reservedIdleIndex=t}isActive(e,t){return e===this.currentGroup&&t===this.currentIndex||e===this.reservedGroup&&t===this.reservedIndex||e===this.reservedIdleGroup&&t===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!g.preserveExpressionOnMotion&&this.currentPriority>1}dump(e,t){if(this.debug){return`\n<Requested> group = "${e}", index = ${t}\n`+["currentPriority","reservePriority","currentGroup","currentIndex","reservedGroup","reservedIndex","reservedIdleGroup","reservedIdleIndex"].map(e=>"["+e+"] "+this[e]).join("\n")}return""}}const _="SoundManager",A=.5;let O,R=0;const C=new WeakSet;function k(e){if(!C.has(e)){try{e.disableAutoPause=!0}catch(t){m.warn(_,"Failed to disable @pixi/sound auto pause.",t)}C.add(e)}return e}function G(){return p(this,null,function*(){const e="undefined"!=typeof PIXI?null==PIXI?void 0:PIXI.sound:void 0;return e?k(e):(null!=O||(O=import("@pixi/sound").then(({sound:e})=>k(e)).catch(e=>(m.warn(_,"@pixi/sound is not available. Load pixi-sound.js before using motion sounds, speak(), or lip sync.",e),null))),O)})}function U(e,t){try{e.remove(t)}catch(i){m.warn(_,`Failed to remove sound "${t}".`,i)}}function N(e){const t=e.media.buffer;if(!t||"object"!=typeof t)return;return"function"==typeof t.getChannelData?t:void 0}class B{static get volume(){return this._volume}static set volume(e){this._volume=(e>1?1:e<0?0:e)||0,this.audios.forEach(e=>e.volume=this._volume)}static add(e,t){return p(this,null,function*(){let i,s=null;try{if(s=yield G(),!s)throw new Error("@pixi/sound is not available");i="live2d-sound-"+R++;const t=s,r=i,n=new Promise((i,s)=>{const n=t.add(r,{url:e,volume:this._volume,preload:!0,loaded:(t,r)=>{if(t)return void s(t);const o=null!=r?r:n;o?N(o)?i(o):s(new Error(`Error: ${e} is not WebAudioMedia`)):s(new Error(`Error: ${e} failed to load`))}})}),o=yield n;return this.aliases.set(o,{alias:r,library:t}),this.audios.push(o),o}catch(r){return s&&i&&U(s,i),m.warn(_,`Error occurred on "${e}"`,r),null==t||t(r),null}})}static play(e,t){e.play({singleInstance:!0,complete:()=>{null==t||t(),this.dispose(e)}})}static addAnalyzer(e,t){const i=N(e);if(!i)return void m.warn(_,"Cannot create audio analyzer because WebAudio media is unavailable.");const s=t.createBufferSource();s.buffer=i;const r=t.createAnalyser();return r.fftSize=g.fftSize,r.minDecibels=-90,r.maxDecibels=-10,r.smoothingTimeConstant=.85,s.connect(r),s.start(0),this.analysers.push(r),r}static analyze(e){if(!e)return parseFloat(Math.random().toFixed(1));const t=new Float32Array(e.fftSize);e.getFloatTimeDomainData(t);let i=0;for(let o=0;o<t.length;o++)i+=l(t[o],2);const s=Math.sqrt(i/t.length),r=20*Math.log10(s||l(10,-5)),n=Math.min(Math.max((r-e.minDecibels)/(e.maxDecibels-e.minDecibels),0),1);return parseFloat(n.toFixed(1))}static dispose(e){try{e.pause()}catch(i){m.warn(_,"Failed to pause audio.",i)}const t=this.aliases.get(e);t?(U(t.library,t.alias),this.aliases.delete(e)):function(e){try{e.destroy()}catch(i){m.warn(_,"Failed to destroy audio.",i)}}(e),b(this.audios,e)}static destroy(){for(let e=this.contexts.length-1;e>=0;e--){const t=this.contexts[e];null==t||t.close().catch(e=>{m.warn(_,"Failed to close AudioContext.",e)})}for(let e=this.audios.length-1;e>=0;e--)this.dispose(this.audios[e])}}c(B,"audios",[]),c(B,"analysers",[]),c(B,"contexts",[]),c(B,"aliases",new WeakMap),c(B,"_volume",A);var j=(e=>(e.ALL="ALL",e.IDLE="IDLE",e.NONE="NONE",e))(j||{});class H extends t.EventEmitter{constructor(e){super(),c(this,"tag"),c(this,"settings"),c(this,"motionGroups",{}),c(this,"state",new S),c(this,"currentAudio"),c(this,"currentAnalyzer"),c(this,"currentContext"),c(this,"playing",!1),c(this,"destroyed",!1),c(this,"parent"),this.settings=e.settings,this.tag=`MotionManager(${this.settings.name})`,this.state.tag=this.tag,this.parent=e}init(e){(null==e?void 0:e.idleMotionGroup)&&(this.groups.idle=e.idleMotionGroup),this.setupMotions(e),this.stopAllMotions()}setupMotions(e){if(!this.definitions)return void m.warn(this.tag,"Motion definitions are not initialized.");for(const i of Object.keys(this.definitions))this.motionGroups[i]=[];let t;switch(null==e?void 0:e.motionPreload){case"NONE":return;case"ALL":t=Object.keys(this.definitions);break;default:t=[this.groups.idle]}for(const i of t){const e=this.definitions[i];if(e)for(let t=0;t<e.length;t++)this.loadMotion(i,t)}}loadMotion(e,t){return p(this,null,function*(){var i,s;if(this.destroyed)return;if(!this.getMotionDefinition(e,t))return;const r=null!=(s=(i=this.motionGroups)[e])?s:i[e]=[];if(null===r[t])return void m.warn(this.tag,`Cannot start motion at "${e}"[${t}] because it's already failed in loading.`);if(r[t])return r[t];const n=yield this._loadMotion(e,t);return this.destroyed?void 0:(r[t]=null!=n?n:null,n)})}_loadMotion(e,t){throw new Error("Not implemented.")}initializeAudio(e,t){this.currentAudio=e,B.volume=t,this.currentContext=e.context.audioContext,this.currentAnalyzer=B.addAnalyzer(this.currentAudio,this.currentContext)}speak(e){return p(this,arguments,function*(e,{volume:t=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:n}={}){if(!g.sound)return!1;let o,a;if(this.currentAudio&&this.currentAudio.isPlaying)return!1;const l=e&&e.startsWith("data:");if(e&&!l){const t=document.createElement("a");t.href=e,a=e=t.href}else a="data:audio/";const h=e;if(h)try{if(o=yield B.add(h,(e,t=this)=>{m.error(this.tag,"Error during audio playback:",e),null==n||n(e),s&&i&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0}),!o)return!1;this.initializeAudio(o,t)}catch(d){return m.warn(this.tag,"Failed to create audio",a,d),!1}if(o){let e=!0;try{g.motionSync&&B.play(o,()=>{null==r||r(),s&&i&&this.expressionManager&&this.expressionManager.resetExpression(),this.currentAudio=void 0})}catch(d){m.warn(this.tag,"Failed to play audio",o.url,d),e=!1}if(!e)return!1}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),i&&this.expressionManager&&(yield this.expressionManager.setExpression(i)),this.playing=!0,!0})}startMotion(e,t){return p(this,arguments,function*(e,t,i=T.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(e,t,i))return!1;if(this.currentAudio&&this.currentAudio.isPlaying&&i!=T.FORCE)return!1;const u=this.getMotionDefinition(e,t);if(!u)return!1;let c,p;this.currentAudio&&B.dispose(this.currentAudio);const f=s&&s.startsWith("data:");if(s&&!f){const e=document.createElement("a");e.href=s,p=s=e.href}else p=this.getSoundFile(u),p&&(p=this.settings.resolveURL(p));const y=p;if(y)try{c=yield B.add(y,(e,t=this)=>{m.error(this.tag,"Error during audio playback:",e),null==l||l(e),o&&n&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0}),c&&this.initializeAudio(c,r)}catch(M){m.warn(this.tag,"Failed to create audio",p,M)}const x=yield this.loadMotion(e,t);if(c&&g.motionSync)try{B.play(c,(e=this)=>{null==a||a(),o&&n&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0})}catch(M){m.warn(this.tag,"Failed to play audio",c.url,M)}return this.state.start(x,e,t,i)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),m.log(this.tag,"Start motion:",this.getMotionName(u)),this.emit("motionStart",e,t,c),n&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(n)),this.playing=!0,x&&this._startMotion(x,void 0,h,d),!0):(c&&(B.dispose(c),this.currentAudio=void 0),!1)})}startRandomMotion(e,t){return p(this,arguments,function*(e,t,{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[e];if(null==u?void 0:u.length){const h=[],c=null!=(d=this.motionGroups[e])?d:[];for(let t=0;t<u.length;t++)null===c[t]||this.state.isActive(e,t)||h.push(t);if(h.length){const d=h[Math.floor(Math.random()*h.length)];return this.startMotion(e,d,t,{sound:i,volume:s,expression:r,resetExpression:n,onFinish:o,onError:a,loop:l})}}return!1})}stopSpeaking(){this.currentAudio&&(B.dispose(this.currentAudio),this.currentAudio=void 0)}stopAllMotions(){this._stopAllMotions(),this.state.reset(),this.stopSpeaking()}update(e,t){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,T.IDLE)),this.updateParameters(e,t)}mouthSync(){return this.currentAnalyzer?B.analyze(this.currentAnalyzer):0}destroy(){var e;this.destroyed=!0,this.emit("destroy"),this.stopAllMotions(),null==(e=this.expressionManager)||e.destroy();this.definitions=void 0,this.motionGroups=void 0}getMotionAndApplyExpression(e,t,i){return p(this,null,function*(){if(this.destroyed)return null;if(!this.state.reserve(e,t,T.FORCE))return null;const s=this.getMotionDefinition(e,t);if(!s)return null;this.currentAudio&&B.dispose(this.currentAudio);const r=yield this.loadMotion(e,t);return this.state.start(r,e,t,T.FORCE)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),m.log(this.tag,"Start motion:",this.getMotionName(s)),this.emit("motionStart",e,t,void 0),i&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(i)),r):null})}getMotionDefinition(e,t){var i,s;const r=null==(s=null==(i=this.definitions)?void 0:i[e])?void 0:s[t];return r||m.warn(this.tag,`Undefined motion at "${e}"[${t}]`),r}}function V(e,t){if(!Array.isArray(e))return[];const i=[];for(const s of e){if(!s||"object"!=typeof s)continue;const e=s,r="string"==typeof e.id?e.id:"string"==typeof e.Id?e.Id:void 0,n="string"==typeof e.name?e.name:"string"==typeof e.Name?e.Name:void 0;r&&n&&i.push({id:r,name:n,index:t(r)})}return i}const $={x:0,y:0,width:0,height:0};class W extends t.EventEmitter{constructor(){super(...arguments),c(this,"focusController",new I),c(this,"pose"),c(this,"physics"),c(this,"originalWidth",0),c(this,"originalHeight",0),c(this,"width",0),c(this,"height",0),c(this,"localTransform",new t.Matrix),c(this,"drawingMatrix",new t.Matrix),c(this,"hitAreas",{}),c(this,"textureFlipY",!1),c(this,"viewport",[0,0,0,0]),c(this,"destroyed",!1)}init(){this.setupLayout(),this.setupHitAreas()}setupLayout(){const e=this,t=this.getSize();e.originalWidth=t[0],e.originalHeight=t[1];const i=function(e,t,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;e.identity(),e.scale(a/2,l/2);const h=t*e.a,u=i*e.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 e.translate(h*c,-u*p),{width:h,height:u}}(this.localTransform,this.originalWidth,this.originalHeight,this.getLayout());e.width=i.width,e.height=i.height}setupHitAreas(){const e=this.getHitAreaDefs();this.hitAreas={};for(const t of e)t.name&&(this.hitAreas[t.name]=t)}hitTest(e,t){return Object.keys(this.hitAreas).filter(i=>this.isHit(i,e,t))}isHit(e,t,i){const s=this.hitAreas[e];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,$);return n.x<=t&&t<=n.x+n.width&&n.y<=i&&i<=n.y+n.height}getDrawableBounds(e,t){const i=this.getDrawableVertices(e);let s=i[0],r=i[0],n=i[1],o=i[1];for(let a=0;a<i.length;a+=2){const e=i[a],t=i[a+1];s=Math.min(e,s),r=Math.max(e,r),n=Math.min(t,n),o=Math.max(t,o)}return null!=t||(t={}),t.x=s,t.y=n,t.width=r-s,t.height=o-n,t}updateTransform(e){this.drawingMatrix.copyFrom(e).append(this.localTransform)}drawWebGPU(e,t,i){throw new Error("This Live2D runtime does not implement WebGPU rendering.")}update(e,t){this.focusController.update(e)}destroy(){this.destroyed=!0,this.emit("destroy"),this.motionManager.destroy(),this.motionManager=void 0,this.parallelMotionManager.forEach(e=>e.destroy()),this.parallelMotionManager=[]}updateMotions(e,t){this.emit("beforeMotionUpdate");const i=this.motionManager.update(e,t),s=this.parallelMotionManager.map(i=>i.update(e,t)),r=i||s.reduce((e,t)=>e||t,!1);return this.emit("afterMotionUpdate"),r}}class X extends Error{constructor(e,t,i,s=!1){super(e),this.url=t,this.status=i,this.aborted=s}}const Y=class e{static createXHR(t,i,s,r,n){const o=new XMLHttpRequest;if(e.allXhrSet.add(o),t){let i=e.xhrMap.get(t);i?i.add(o):(i=new Set([o]),e.xhrMap.set(t,i))}return o.open("GET",i),o.responseType=s,o.onload=()=>{var e;200!==o.status&&0!==o.status||!o.response?null==(e=o.onerror)||e.call(o,new ProgressEvent("error")):r(o.response)},o.onerror=()=>{m.warn("XHRLoader",`Failed to load resource as ${o.responseType} (Status ${o.status}): ${i}`),n(new X("Network error.",i,o.status))},o.onabort=()=>n(new X("Aborted.",i,o.status,!0)),o.onloadend=()=>{var i;e.allXhrSet.delete(o),t&&(null==(i=e.xhrMap.get(t))||i.delete(o))},o}static cancelXHRs(){var t;null==(t=e.xhrMap.get(this))||t.forEach(t=>{t.abort(),e.allXhrSet.delete(t)}),e.xhrMap.delete(this)}static release(){e.allXhrSet.forEach(e=>e.abort()),e.allXhrSet.clear(),e.xhrMap=new WeakMap}};c(Y,"xhrMap",new WeakMap),c(Y,"allXhrSet",new Set),c(Y,"loader",e=>new Promise((t,i)=>{const s=e.target,r=e.target&&"function"==typeof Y.cancelXHRs?Y.cancelXHRs.bind(e.target):void 0,n=Y.createXHR(e.target,e.settings?e.settings.resolveURL(e.url):e.url,e.type,i=>{e.result=i,t()},i);if(e.target&&r&&"function"==typeof s.listeners&&"function"==typeof s.once){const e=s.listeners("destroy");Array.isArray(e)&&e.includes(r)||s.once("destroy",r)}n.send()}));let z=Y;function q(e,t){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=e[r];if(!o)return Promise.resolve();try{return Promise.resolve(o(t,s.bind(null,r+1)))}catch(a){const e=a instanceof Error?a:new Error(String(a));return Promise.reject(e)}}(0)}class J{static load(e){return p(this,null,function*(){return yield q(this.middlewares,e),e.result})}}c(J,"middlewares",[z.loader]);class Z extends F{constructor(e){if(super(e),c(this,"moc"),c(this,"textures"),c(this,"layout"),c(this,"hitAreas"),c(this,"initParams"),c(this,"initOpacities"),c(this,"expressions"),c(this,"motions",{}),!Z.isValidJSON(e))throw new TypeError("Invalid JSON.");this.moc=e.model,M("string",e,this,"textures","textures"),this.copy(e)}static isValidJSON(e){if(!e||"object"!=typeof e)return!1;const t=!!Array.isArray(e.textures)&&e.textures.every(e=>"string"==typeof e);return"string"==typeof e.model&&t}copy(e){x("string",e,this,"name","name"),x("string",e,this,"pose","pose"),x("string",e,this,"physics","physics"),x("object",e,this,"layout","layout"),x("object",e,this,"motions","motions"),M("object",e,this,"hit_areas","hitAreas"),M("object",e,this,"expressions","expressions"),M("object",e,this,"init_params","initParams"),M("object",e,this,"init_opacities","initOpacities");const t=this.getFileStem(this.moc);this.setModelName(this.name,t)}replaceFiles(e){super.replaceFiles(e);for(const[t,i]of Object.entries(this.motions))for(let s=0;s<i.length;s++)i[s].file=e(i[s].file,`motions.${t}[${s}].file`),void 0!==i[s].sound&&(i[s].sound=e(i[s].sound,`motions.${t}[${s}].sound`));if(this.expressions)for(let t=0;t<this.expressions.length;t++)this.expressions[t].file=e(this.expressions[t].file,`expressions[${t}].file`)}}function Q({lod:e,effectiveScale:t,textureWidth:i,textureHeight:s,lodScaleThreshold:r,lodTextureSizeThreshold:n,lodMaxLevel:o}){if("single-auto"!==K(e))return;if(!Number.isFinite(t)||t<=0)return;const a=Math.floor(i),h=Math.floor(s);if(a<=1||h<=1)return;if(t>=te(r,.5))return;const d=te(n,4096);if(Math.max(a,h)<d)return;const u=Math.round(Math.log2(1/t)),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(e,t,i){return Math.min(i,Math.max(t,e))}(Math.max(1,u),1,p),y=l(2,f);return{level:f,width:Math.max(1,Math.round(a/y)),height:Math.max(1,Math.round(h/y))}}function K(e){return!1===e||"single-auto"===e?e:"full"}function ee(e){return"nearest"===e?"nearest":"linear"}function te(e,t){return void 0!==e&&Number.isFinite(e)&&e>0?e:t}function ie(e){const[t=""]=e.split(/[?#]/,1),i=t.slice(t.lastIndexOf("/")+1),s=i.lastIndexOf(".");if(!(s<=0||s===i.length-1))return i.slice(s+1).toLowerCase()}function se(){}const re="Live2DFactory",ne=(e,t)=>p(null,null,function*(){if("string"==typeof e.source){const t=yield J.load({url:e.source,type:"json",target:e.live2dModel});t.url="string"==typeof t.url?t.url:e.source,e.source=t,e.live2dModel.emit("settingsJSONLoaded",t)}return t()}),oe=(e,t)=>p(null,null,function*(){if(e.source instanceof F)return e.settings=e.source,t();if("object"==typeof e.source){const i=ge.findRuntime(e.source);if(i){const s=i.createModelSettings(e.source);return e.settings=s,e.live2dModel.emit("settingsLoaded",s),t()}}const i=e.source&&"string"==typeof e.source.url?e.source.url:void 0,s=ge.runtimes.map(e=>e.version).join(", ");if(0===ge.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(!e.source||"object"!=typeof e.source||Array.isArray(e.source))return;return Object.keys(e.source).slice(0,30).join(", ")}catch(t){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"))}),ae=(e,t)=>{if(e.settings){const i=ge.findRuntime(e.settings);if(i)return i.ready().then(()=>t())}return t()},le=(e,t)=>p(null,null,function*(){yield t();const i=e.internalModel;if(i){const t=e.settings,s=ge.findRuntime(t);if(s){const r=[],n=t instanceof Z?"json":"arraybuffer";t.pose&&r.push(J.load({settings:t,url:t.pose,type:n,target:i}).then(t=>{i.pose=s.createPose(i.coreModel,t),e.live2dModel.emit("poseLoaded",i.pose)}).catch(t=>{e.live2dModel.emit("poseLoadError",t),m.warn(re,"Failed to load pose.",t)})),t.physics&&r.push(J.load({settings:t,url:t.physics,type:n,target:i}).then(t=>{i.physics=s.createPhysics(i.coreModel,t),e.live2dModel.emit("physicsLoaded",i.physics)}).catch(t=>{e.live2dModel.emit("physicsLoadError",t),m.warn(re,"Failed to load physics.",t)})),r.length&&(yield Promise.all(r))}}}),he=(e,i)=>p(null,null,function*(){if(!e.settings)throw new TypeError("Missing settings.");{const s=e.live2dModel,r=d({crossOrigin:e.options.crossOrigin},e.options.textureOptions);e.settings instanceof Z&&(r.preferCreateImageBitmap=!1);const n=Promise.all(e.settings.textures.map(i=>function(e,i={}){const s=t.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),t.Assets.load({src:e,format:i.format,parser:"texture",data:{autoGenerateMipmaps:"full"===K(i.lod)}}).catch(e=>{if(e instanceof Error)throw e;throw new Error("Texture loading error",{cause:e})}).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))})}(e.settings.resolveURL(i),u(d({},r),{format:ie(i)}))));if(n.catch(se),yield i(),!e.internalModel)throw new TypeError("Missing internal model.");s.internalModel=e.internalModel,s.emit("modelLoaded",e.internalModel),s.textures=yield n,s.emit("textureLoaded",s.textures)}}),de=(e,t)=>p(null,null,function*(){const i=e.settings;if(i instanceof F){const s=ge.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield J.load({settings:i,url:i.moc,type:"arraybuffer",target:e.live2dModel});if(!s.isValidMoc(r))throw new Error("Invalid moc data");const n=s.createCoreModel(r);return e.internalModel=s.createInternalModel(n,i,e.options),t()}throw new TypeError("Missing settings.")}),ue=class e{static resolveURL(t,i){var s;const r=null==(s=e.filesMap[t])?void 0:s[i];if(void 0===r)throw new Error("Cannot find this file from uploaded files: "+i);return r}static upload(t,i){const s={};for(const e of i.getDefinedFiles()){const r=decodeURI(P(i.url,e)),n=t.find(e=>e.webkitRelativePath===r);n&&(s[e]=URL.createObjectURL(n))}e.filesMap[i._objectURL]=s}static createSettings(t){return p(this,null,function*(){const i=t.find(e=>e.name.endsWith("model.json")||e.name.endsWith("model3.json"));if(!i)throw new TypeError("Settings file not found");const s=yield e.readText(i),r=JSON.parse(s);r.url=i.webkitRelativePath;const n=ge.findRuntime(r);if(!n)throw new Error("Unknown settings JSON");const o=n.createModelSettings(r);return o._objectURL=URL.createObjectURL(i),o})}static readText(e){return p(this,null,function*(){return new Promise((t,i)=>{const s=new FileReader;s.onload=()=>t(s.result),s.onerror=i,s.readAsText(e,"utf8")})})}};c(ue,"live2dFactory"),c(ue,"filesMap",{}),c(ue,"factory",(e,t)=>p(null,null,function*(){if(Array.isArray(e.source)&&e.source[0]instanceof File){const t=e.source;let i=t.settings;if(i){if(!i._objectURL)throw new Error('"_objectURL" must be specified in ModelSettings')}else i=yield ue.createSettings(t);i.validateFiles(t.map(e=>encodeURI(e.webkitRelativePath))),ue.upload(t,i),i.resolveURL=function(e){return ue.resolveURL(this._objectURL,e)},e.source=i,e.live2dModel.once("modelLoaded",e=>{e.once("destroy",function(){const e=this.settings._objectURL;if(URL.revokeObjectURL(e),ue.filesMap[e])for(const t of Object.values(ue.filesMap[e]))URL.revokeObjectURL(t);delete ue.filesMap[e]})})}return t()}));let ce=ue;const pe=class e{static registerRuntime(t){e.runtimes.push(t),e.runtimes.sort((e,t)=>t.version-e.version)}static findRuntime(t){for(const i of e.runtimes)if(i.test(t))return i}static setupLive2DModel(t,i,s){return p(this,null,function*(){const r=new Promise(e=>t.once("textureLoaded",e)),n=new Promise(e=>t.once("modelLoaded",e)),o=Promise.all([r,n]).then(()=>t.emit("ready"));yield q(e.live2DModelMiddlewares,{live2dModel:t,source:i,options:s||{}}),yield o,t.emit("load")})}static loadMotion(t,i,s){var r;const n=e=>t.emit("motionLoadError",i,s,e);try{const o=null==(r=t.definitions[i])?void 0:r[s];if(!o)return Promise.resolve(void 0);t.once("destroy",()=>e.releaseMotionTasks(t));let a=e.motionTasksMap.get(t);a||(a={},e.motionTasksMap.set(t,a));let l=a[i];l||(l=[],a[i]=l);const h=t.getMotionFile(o);return null!=l[s]||(l[s]=J.load({url:h,settings:t.settings,type:t.motionDataType,target:t}).then(r=>{var n;const a=null==(n=e.motionTasksMap.get(t))?void 0:n[i];a&&(a[s]=void 0);const l=r,h=t.createMotion(l,i,o);return t.emit("motionLoaded",i,s,h),h}).catch(e=>{m.warn(t.tag,`Failed to load motion: ${h}\n`,e),n(e)})),l[s]}catch(o){m.warn(t.tag,`Failed to load motion at "${i}"[${s}]\n`,o),n(o)}return Promise.resolve(void 0)}static loadExpression(t,i){var s;const r=e=>t.emit("expressionLoadError",i,e);try{const n=t.definitions[i];if(!n)return Promise.resolve(void 0);t.once("destroy",()=>e.releaseExpressionTasks(t));let o=e.expressionTasksMap.get(t);o||(o=[],e.expressionTasksMap.set(t,o));const a=t.getExpressionFile(n),l=null!=(s=t.expressionDataType)?s:"json";return null!=o[i]||(o[i]=J.load({url:a,settings:t.settings,type:l,target:t}).then(s=>{const r=e.expressionTasksMap.get(t);r&&(r[i]=void 0);const o=s,a=t.createExpression(o,n);return t.emit("expressionLoaded",i,a),a}).catch(e=>{m.warn(t.tag,`Failed to load expression: ${a}\n`,e),r(e)})),o[i]}catch(n){m.warn(t.tag,`Failed to load expression at [${i}]\n`,n),r(n)}return Promise.resolve(void 0)}static releaseMotionTasks(t){e.motionTasksMap.delete(t)}static releaseExpressionTasks(t){e.expressionTasksMap.delete(t)}};c(pe,"runtimes",[]),c(pe,"urlToJSON",ne),c(pe,"jsonToSettings",oe),c(pe,"waitUntilReady",ae),c(pe,"setupOptionals",le),c(pe,"setupEssentials",he),c(pe,"createInternalModel",de),c(pe,"live2DModelMiddlewares",[ce.factory,ne,oe,ae,le,he,de]),c(pe,"motionTasksMap",new WeakMap),c(pe,"expressionTasksMap",new WeakMap);let ge=pe;H.prototype._loadMotion=function(e,t){return ge.loadMotion(this,e,t)},E.prototype._loadExpression=function(e){return ge.loadExpression(this,e)},ce.live2dFactory=ge;const me=class e{constructor(i,{autoUpdate:s=!0,autoHitTest:r=!0,autoFocus:n=!0,autoInteract:o,ticker:a}={}){var l;c(this,"model"),c(this,"destroyed",!1),c(this,"_ticker"),c(this,"_autoUpdate",!1),c(this,"_autoHitTest",!1),c(this,"_autoFocus",!1),null!=a||(a=null!=(l=e.defaultTicker)?l:"undefined"!=typeof PIXI?PIXI.Ticker.shared:t.Ticker.shared),void 0!==o&&(r=o,n=o,m.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(e){var t,i;this._ticker&&this._ticker.remove(ye,this),this._ticker=e,this._autoUpdate&&(null==(t=this._ticker)||t.add(ye,this),null==(i=this._ticker)||i.start())}get autoUpdate(){return this._autoUpdate}set autoUpdate(e){var t;this.destroyed||(e?this._ticker?(this._ticker.add(ye,this),this._autoUpdate=!0):m.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==(t=this._ticker)||t.remove(ye,this),this._autoUpdate=!1))}get autoHitTest(){return this._autoHitTest}set autoHitTest(e){e!==this.autoHitTest&&(e?this.model.on("pointertap",xe,this):this.model.off("pointertap",xe,this),this._autoHitTest=e)}get autoFocus(){return this._autoFocus}set autoFocus(e){e!==this.autoFocus&&(e?(this.model.on("globalpointermove",Me,this),this.model.on("pointermove",Me,this)):(this.model.off("globalpointermove",Me,this),this.model.off("pointermove",Me,this)),this._autoFocus=e)}get autoInteract(){return this._autoHitTest&&this._autoFocus}set autoInteract(e){this.autoHitTest=e,this.autoFocus=e}onTickerUpdate(){const e=this.ticker.deltaMS;this.model.update(e)}onTap(e){this.model.tap(e.global.x,e.global.y)}onPointerMove(e){this.model.focus(e.global.x,e.global.y)}destroy(){this.autoFocus=!1,this.autoHitTest=!1,this.autoUpdate=!1,this.ticker=void 0,this.destroyed=!0}};c(me,"defaultTicker");let fe=me;function ye(){this.onTickerUpdate()}function xe(e){this.onTap(e)}function Me(e){this.onPointerMove(e)}class ve extends t.Transform{}const be=new t.Point,we=new t.Matrix,Pe=new t.Matrix,Ee={x:0,y:0,width:0,height:0},Le=new t.Bounds;let De=!1,Ie=!1;class Fe{constructor(e){this.renderer=e}addPrepare(e,t){var i,s;null==(s=null==(i=this.renderer.renderPipes.batch)?void 0:i.break)||s.call(i,t),t.add({renderPipeId:"live2d",action:"prepare",canBundle:!1,prepare:e})}addRenderable(e,t){var i,s;null==(s=null==(i=this.renderer.renderPipes.batch)?void 0:i.break)||s.call(i,t),t.add(e)}execute(e){if(!(e instanceof _e))return void e.prepare();const t=e;!t.visible||t.alpha<=0||t.renderLive2D(this.renderer)}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}destroy(){}}c(Fe,"extension",{type:[t.ExtensionType.WebGLPipes,t.ExtensionType.WebGPUPipes],name:"live2d"});const Te=Fe;function Se(e){return Math.max(Math.hypot(e.a,e.b),Math.hypot(e.c,e.d))}class _e extends t.Container{constructor(e){var i;super(),c(this,"renderPipeId","live2d"),c(this,"tag","Live2DModel(uninitialized)"),c(this,"internalModel"),c(this,"textures",[]),c(this,"textureOptions"),c(this,"anchorMode"),c(this,"textureLODStates",[]),c(this,"textureLODFailures",[]),c(this,"textureLODSubmissions",new Set),c(this,"transform",new ve),c(this,"anchor"),c(this,"_bounds",new t.Bounds),c(this,"_boundsDirty",!0),c(this,"_boundsRetryAfterDraw",!1),c(this,"gl",null),c(this,"elapsedTime",0),c(this,"deltaTime",0),c(this,"automator"),c(this,"currentGlId",0),c(this,"renderLive2D",e=>{var i,s,r,n,o;if(e instanceof t.WebGPURenderer)return Ie||(Ie=!0,console.warn("[untitled-pixi-live2d-engine] WebGPU rendering is experimental and may change in minor releases.")),void this.renderWebGPU(e);if(!(e instanceof t.WebGLRenderer))throw new Error("Renderer is not supported");e.geometry.resetState(),e.shader.resetState(),e.texture.resetState();let a=!1;this.gl!==e.gl&&(this.gl=e.gl,this.internalModel.updateWebGLContext(e.gl,this.generateUID()),a=!0);const{projectionMatrix:l,offset:h,worldTransformMatrix:d}=e.globalUniforms.globalUniformData,u=Pe.copyFrom(d).append(this.groupTransform),c=Se(u)*e.resolution;for(let t=0;t<this.textures.length;t++){const i=this.textures[t];let s=this.resolveTextureForRender(t,i,c);try{this.uploadTextureForRender(e,s,a)}catch(v){if(s===i)throw new Error("Failed to upload Live2D texture.");const r=this.textureLODStates[t];(null==r?void 0:r.texture)===s&&(this.markTextureLODFailure(t,i,r.level),this.destroyTextureLODState(t)),s=i,this.uploadTextureForRender(e,s,a)}this.internalModel.bindTexture(t,e.texture.getGlSource(s.source).texture)}const p=e.renderTarget.viewport,g=e.renderTarget.renderTarget;let m=p.y;if(null==g?void 0:g.isRoot){m=g.colorTexture.source.pixelHeight-p.height-p.y}this.internalModel.viewport=[p.x,m,p.width,p.height];const f=this.deltaTime;this.deltaTime=0,f&&this.internalModel.update(f,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=we.copyFrom(l).append(u);this.internalModel.updateTransform(y),this.internalModel.draw(e.gl),this._boundsRetryAfterDraw&&this.updateDrawableBounds(!0),e.state.resetState(),e.texture.resetState();const x=null==(r=e.renderTarget)?void 0:r.defaultClearColor,M=null==(o=null==(n=e.renderTarget)?void 0:n.adaptor)?void 0:o._clearColorCache;x&&(e.gl.clearColor(x[0],x[1],x[2],x[3]),M&&(M[0]=x[0],M[1]=x[1],M[2]=x[2],M[3]=x[3]))}),this.textureOptions=null==e?void 0:e.textureOptions,this.anchorMode=null!=(i=null==e?void 0:e.anchorMode)?i:"canvas",this.anchor=new t.ObservablePoint({_onUpdate:()=>this.onAnchorChange()},0,0),this.automator=new fe(this,e),this.once("modelLoaded",()=>this.initializeOnModelLoad(e))}get isRenderable(){return!0}get canBundle(){return!1}static from(e,t){return p(this,null,function*(){const i=new this(t);return yield ge.setupLive2DModel(i,e,t),i})}static fromSync(e,t){const i=new this(t);return ge.setupLive2DModel(i,e,t).then(()=>{var e;return null==(e=null==t?void 0:t.onLoad)?void 0:e.call(t)}).catch(e=>{var i;return null==(i=null==t?void 0:t.onError)?void 0:i.call(t,e)}),i}static registerTicker(e){fe.defaultTicker=e.shared}get bounds(){return this.internalModel?(this._boundsDirty&&this.updateDrawableBounds(),this._bounds):(this._bounds.set(0,0,0,0),this._bounds)}updateDrawableBounds(e=!1){if(!this.internalModel)return this._bounds.set(0,0,0,0),void(this._boundsDirty=!1);const i=this.internalModel.getDrawableIDs();Le.clear();for(let s=0;s<i.length;s++){const e=i[s],r=this.internalModel.getDrawableIndex(e);if(r<0)continue;const n=this.internalModel.getDrawableBounds(r,Ee);Number.isFinite(n.x)&&Number.isFinite(n.y)&&Number.isFinite(n.width)&&Number.isFinite(n.height)&&Le.addFrame(n.x,n.y,n.x+n.width,n.y+n.height,t.Matrix.IDENTITY)}if(this._bounds.clear(),Le.isValid&&Le.isPositive)this._bounds.addFrame(Le.minX,Le.minY,Le.maxX,Le.maxY,this.internalModel.localTransform),this._boundsRetryAfterDraw=!1;else{const e=this.internalModel.originalWidth||this.internalModel.width,t=this.internalModel.originalHeight||this.internalModel.height;this._bounds.addFrame(0,0,e,t,this.internalModel.localTransform),this._boundsRetryAfterDraw=!0}this._boundsDirty=!1,this._didViewChangeTick++,e&&"drawable"===this.anchorMode&&this.onAnchorChange()}prepareForRender(){if(!this.internalModel)return;const e=this.deltaTime;this.deltaTime=0,e&&this.internalModel.update(e,this.elapsedTime),this.updateDrawableBounds()}generateUID(){return++this.currentGlId}collectRenderables(e,t,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(e){const t=e;t.renderPipes.live2d||(De||(De=!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.")),t.renderPipes.live2d=new Fe(e))}(t);const a=t.renderPipes,l=()=>{a.live2d.addRenderable(this,e)},h=()=>{const s=this.children,r=s.length;for(let n=0;n<r;n++)s[n].collectRenderables(e,t,i)},d=this.effects;if(d){d.length&&a.live2d.addPrepare(()=>this.prepareForRender(),e);for(let t=0;t<d.length;t++){const i=d[t],n=i.filters;if(n)for(const e of n)e&&"number"==typeof e.resolution&&1===e.resolution&&(e.resolution="inherit");null==(r=null==(s=a[i.pipe])?void 0:s.push)||r.call(s,i,this,e)}l(),h();for(let t=d.length-1;t>=0;t--){const i=d[t];null==(o=null==(n=a[i.pipe])?void 0:n.pop)||o.call(n,i,this,e)}}else l(),h()}initializeOnModelLoad(e){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 e=this.bounds;this.pivot.set(e.minX+this.anchor.x*e.width,e.minY+this.anchor.y*e.height)}else this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(e,t,i){return p(this,arguments,function*(e,t,i,{sound:s,volume:r=.5,expression:n,resetExpression:o=!0,onFinish:a,onError:l,loop:h}={}){return void 0===t?this.internalModel.motionManager.startRandomMotion(e,i,{sound:s,volume:r,expression:n,resetExpression:o,onFinish:a,onError:l,loop:h}):this.internalModel.motionManager.startMotion(e,t,i,{sound:s,volume:r,expression:n,resetExpression:o,onFinish:a,onError:l,loop:h})})}motionLastFrame(e,t){return p(this,arguments,function*(e,t,{expression:i}={}){return this.internalModel.motionManager.motionLastFrame(e,t,{expression:i})})}parallelMotion(e){return p(this,null,function*(){this.internalModel.extendParallelMotionManager(e.length);const t=e.map((e,t)=>this.internalModel.parallelMotionManager[t].startMotion(e.group,e.index,e.priority,{ignoreParamIds:e.ignoreParamIds,loop:e.loop})),i=[];for(const e of t)i.push(yield e);return i})}parallelLastFrame(e){return p(this,null,function*(){this.internalModel.extendParallelMotionManager(e.length);const t=e.map((e,t)=>this.internalModel.parallelMotionManager[t].playMotionLastFrame(e.group,e.index)),i=[];for(const e of t)i.push(yield e);return i})}stopMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(e,{volume:t=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:n}={}){return this.internalModel.motionManager.speak(e,{volume:t,expression:i,resetExpression:s,onFinish:r,onError:n})}stopSpeaking(){return this.internalModel.motionManager.stopSpeaking()}expression(e){return this.internalModel.motionManager.expressionManager?void 0===e?this.internalModel.motionManager.expressionManager.setRandomExpression():this.internalModel.motionManager.expressionManager.setExpression(e):Promise.resolve(!1)}focus(e,t,i=!1){be.x=e,be.y=t,this.toModelPosition(be,be,!0);const s=be.x/this.internalModel.originalWidth*2-1,r=be.y/this.internalModel.originalHeight*2-1,n=Math.atan2(r,s);this.internalModel.focusController.focus(Math.cos(n),-Math.sin(n),i)}tap(e,t){const i=this.hitTest(e,t);i.length&&this.emit("hit",i)}hitTest(e,t){return be.x=e,be.y=t,this.toModelPosition(be,be),this.internalModel.hitTest(be.x,be.y)}toModelPosition(e,t=e.clone(),i){return i||this.updateLocalTransform(),this.toLocal(e,void 0,t,i),this.internalModel.localTransform.applyInverse(t,t),t}containsPoint(e){return this.bounds.containsPoint(e.x,e.y)}_calculateBounds(){if(!this.internalModel)return void this.getBounds().set(0,0,0,0);const e=this.bounds;this.getBounds().addFrame(e.minX,e.minY,e.maxX,e.maxY,this.transform.matrix)}update(e){this.deltaTime+=e,this.elapsedTime+=e}resolveTextureForRender(e,i,s){var r;const n=Q(u(d({},this.textureOptions),{effectiveScale:s,textureWidth:i.source.pixelWidth,textureHeight:i.source.pixelHeight}));if(!n)return i;const o=this.textureLODFailures[e];if((null==o?void 0:o.source)===i&&o.levels.has(n.level))return i;const a=this.textureLODStates[e];if((null==a?void 0:a.source)===i&&a.level===n.level&&!a.texture.destroyed)return a.texture;this.destroyTextureLODState(e);const l=function(e,i,s,r,n){var o,a;const l=e.source.resource;if(!function(e){if(!e||"object"!=typeof e)return!1;const{width:t,height:i}=e;return"number"==typeof t&&t>0&&"number"==typeof i&&i>0}(l))return;const h=t.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,e.source.pixelWidth,e.source.pixelHeight,0,0,s,r)}catch(c){return}const u=`${null!=(a=null!=(o=e.label)?o:e.source.label)?a:"Live2DTexture"} LOD ${i}`;return new t.Texture({label:u,source:new t.CanvasSource({resource:h,width:s,height:r,resolution:1,scaleMode:ee(n),autoGenerateMipmaps:!1,label:u})})}(i,n.level,n.width,n.height,null==(r=this.textureOptions)?void 0:r.lodFilter);return l?(this.textureLODStates[e]={source:i,level:n.level,texture:l},l):(this.markTextureLODFailure(e,i,n.level),i)}markTextureLODFailure(e,t,i){let s=this.textureLODFailures[e];(null==s?void 0:s.source)!==t&&(s={source:t,levels:new Set},this.textureLODFailures[e]=s),s.levels.add(i)}destroyTextureLODState(e){const t=this.textureLODStates[e];t&&(this.textureLODStates[e]=void 0,this.textureLODSubmissions.size?Promise.all(this.textureLODSubmissions).then(()=>t.texture.destroy(!0)):t.texture.destroy(!0))}destroyTextureLODStates(){for(let e=0;e<this.textureLODStates.length;e++)this.destroyTextureLODState(e);this.textureLODFailures.length=0}uploadTextureForRender(e,t,i){const s=Boolean(t.source._gpuData[e.uid]);!i&&s||(e.gl.pixelStorei(WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL,this.internalModel.textureFlipY),e.texture.bind(t,0))}renderWebGPU(e){var t,i;const{projectionMatrix:s,offset:r,worldTransformMatrix:n,worldColor:o}=e.globalUniforms.globalUniformData,a=Pe.copyFrom(n).append(this.groupTransform),l=Se(a)*e.resolution,h=this.textures.map((e,t)=>this.resolveTextureForRender(t,e,l));if(h.some((e,t)=>{var i;return(null==(i=this.textureLODStates[t])?void 0:i.texture)===e})){const t=e.encoder.commandFinished;this.textureLODSubmissions.has(t)||(this.textureLODSubmissions.add(t),t.then(()=>this.textureLODSubmissions.delete(t)))}const d=this.deltaTime;this.deltaTime=0,d&&this.internalModel.update(d,this.elapsedTime),a.tx-=null!=(t=null==r?void 0:r.x)?t:0,a.ty-=null!=(i=null==r?void 0:r.y)?i:0,this.internalModel.updateTransform(we.copyFrom(s).append(a));const u=(o>>>24)/255;this.internalModel.drawWebGPU(e,h,this.groupAlpha*u),this._boundsRetryAfterDraw&&this.updateDrawableBounds(!0)}destroy(e){this.emit("destroy"),this.destroyTextureLODStates(),(null==e?void 0:e.texture)&&this.textures.forEach(t=>t.destroy(e.baseTexture)),this.automator.destroy(),this.internalModel.destroy(),super.destroy(e)}}if(!("Live2D"in window))throw new Error("Could not find Cubism 2 runtime. This plugin requires live2d.min.js to be loaded.");const Ae=Live2DMotion.prototype.updateParam;function Oe(e){switch(e){case"add":return{color:{srcFactor:"one",dstFactor:"one",operation:"add"},alpha:{srcFactor:"zero",dstFactor:"one",operation:"add"}};case"multiply":return{color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"zero",dstFactor:"one",operation:"add"}};case"mask":return{color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"},alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"}};default:return{color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}}function Re(e,t){return Math.max(t,Math.ceil(e/t)*t)}function Ce(e){const t=new Uint16Array(Re(e.byteLength,4)/2);return t.set(e),t}function ke(e,t){return Array.from(e.subarray(0,t)).sort((e,t)=>e-t).join(",")}Live2DMotion.prototype.updateParam=function(e,t){Ae.call(this,e,t),t.isFinished()&&this.onFinishHandler&&(this.onFinishHandler(this),delete this.onFinishHandler)};class Ge{constructor(e,t,i){c(this,"device"),c(this,"model"),c(this,"layout"),c(this,"pipelineLayout"),c(this,"shader"),c(this,"uniform"),c(this,"uniformData"),c(this,"uniformStride"),c(this,"maskSampler"),c(this,"meshes",[]),c(this,"masks",new Map),c(this,"drawableMasks",[]),c(this,"atlases",[]),c(this,"atlasSamplers",[]),c(this,"pipelines",new Map),c(this,"white"),c(this,"whiteView"),c(this,"_destroyed",!1),this.renderer=e,this.meshFrontFace=i;const s=e.gpu.device;this.device=s,this.model=t;this.uniformStride=Re(128,s.limits.minUniformBufferOffsetAlignment);const r=t.getDrawableCount();this.uniformData=new Float32Array(r*this.uniformStride/4),this.uniform=s.createBuffer({label:"Live2D per-draw uniform slots",size:Math.max(this.uniformStride,this.uniformData.byteLength),usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.layout=s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform",hasDynamicOffset:!0,minBindingSize:128}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:4,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this.pipelineLayout=s.createPipelineLayout({bindGroupLayouts:[this.layout]}),this.shader=s.createShaderModule({label:"Live2D WGSL",code:"\nstruct Params {\n matrix: mat4x4<f32>,\n multiply: vec4<f32>,\n screen: vec4<f32>,\n options: vec4<f32>,\n tint: vec4<f32>,\n}\n@group(0) @binding(0) var<uniform> params: Params;\n@group(0) @binding(1) var atlasSampler: sampler;\n@group(0) @binding(2) var atlas: texture_2d<f32>;\n@group(0) @binding(3) var maskTexture: texture_2d<f32>;\n@group(0) @binding(4) var maskSampler: sampler;\n\nstruct VertexOut {\n @builtin(position) position: vec4<f32>,\n @location(0) uv: vec2<f32>,\n @location(1) maskUv: vec2<f32>,\n}\n@vertex fn vertexMain(@location(0) position: vec2<f32>, @location(1) uv: vec2<f32>) -> VertexOut {\n var out: VertexOut;\n let clip = params.matrix * vec4<f32>(position, 0.0, 1.0);\n out.position = clip;\n out.uv = vec2<f32>(uv.x, 1.0 - uv.y);\n out.maskUv = vec2<f32>(clip.x * 0.5 + 0.5, 0.5 - clip.y * 0.5);\n return out;\n}\n@fragment fn fragmentMain(in: VertexOut) -> @location(0) vec4<f32> {\n let tex = textureSample(atlas, atlasSampler, in.uv);\n let multiplied = tex.rgb * params.multiply.rgb;\n let screened = multiplied + params.screen.rgb * tex.a - multiplied * params.screen.rgb;\n var color = vec4<f32>(screened, tex.a) * params.tint * params.options.x;\n // Sample unconditionally: derivatives must remain in uniform control flow.\n let inverseCoverage = textureSample(maskTexture, maskSampler, in.maskUv).r;\n if (params.options.y > 1.5) {\n color *= inverseCoverage;\n } else if (params.options.y > 0.5) {\n color *= 1.0 - inverseCoverage;\n }\n return color;\n}\n@fragment fn fragmentMask(in: VertexOut) -> @location(0) vec4<f32> {\n let alpha = textureSample(atlas, atlasSampler, in.uv).a;\n return vec4<f32>(alpha);\n}\n"}),this.maskSampler=s.createSampler({minFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),this.white=this.texture(1,1,"Fallback unmasked texture"),s.queue.writeTexture({texture:this.white},new Uint8Array([255,255,255,255]),{},[1,1]);const n=t.getDrawableMaskCounts(),o=t.getDrawableMasks();for(let a=0;a<r;a++){if(!n[a])continue;const e=ke(o[a],n[a]);let t=this.masks.get(e);if(!t){const i=this.texture(512,512,`Mask ${e}`);t={sources:e.split(",").map(Number),texture:i,view:i.createView()},this.masks.set(e,t)}this.drawableMasks[a]=t}this.whiteView=this.white.createView();for(let a=0;a<r;a++)this.meshes.push({positions:this.buffer(t.getDrawableVertices(a),GPUBufferUsage.VERTEX,"Dynamic positions"),uvs:this.buffer(t.getDrawableVertexUvs(a),GPUBufferUsage.VERTEX,"Static UVs"),indices:this.buffer(Ce(t.getDrawableVertexIndices(a)),GPUBufferUsage.INDEX,"Static indices"),indexCount:t.getDrawableVertexIndexCount(a)})}get destroyed(){return this._destroyed}texture(e,t,i){return this.device.createTexture({label:i,size:[e,t],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC})}buffer(e,t,i){const s=this.device.createBuffer({label:i,size:Re(e.byteLength,4),usage:t|GPUBufferUsage.COPY_DST});return e.byteLength&&this.device.queue.writeBuffer(s,0,e.buffer,e.byteOffset,e.byteLength),s}bind(e,t,i){return this.device.createBindGroup({layout:this.layout,entries:[{binding:0,resource:{buffer:this.uniform,size:128}},{binding:1,resource:i},{binding:2,resource:e},{binding:3,resource:t},{binding:4,resource:this.maskSampler}]})}pipeline(e,t,i,s="rgba8unorm",r=1,n,o=GPUColorWrite.ALL){const a=JSON.stringify([e,t,i,s,r,n,o]);let l=this.pipelines.get(a);return l||(l=this.device.createRenderPipeline({label:`Live2D ${a}`,layout:this.pipelineLayout,vertex:{module:this.shader,entryPoint:"vertexMain",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:8,attributes:[{shaderLocation:1,offset:0,format:"float32x2"}]}]},fragment:{module:this.shader,entryPoint:"mask"===e?"fragmentMask":"fragmentMain",targets:[{format:s,blend:Oe(e),writeMask:o}]},depthStencil:n,multisample:{count:r},primitive:{topology:"triangle-list",cullMode:t?"back":"none",frontFace:i?"cw":"ccw"}}),this.pipelines.set(a,l)),l}render(e,t,i,s={r:1,g:1,b:1,a:1}){var r,n;if(this.destroyed)throw new Error("Live2D WebGPU renderer has been destroyed.");const{renderer:o}=this,a=new Float32Array([e.a,e.b,0,0,e.c,e.d,0,0,0,0,1,0,e.tx,e.ty,0,1]),l=t.map(e=>o.texture.getGpuSource(e.source)),h=t.map(e=>o.texture.getGpuSampler(e.source.style));if(l.some((e,t)=>e!==this.atlases[t])||h.some((e,t)=>e!==this.atlasSamplers[t])){this.atlases=l,this.atlasSamplers=h;const e=l.map(e=>e.createView());for(let t=0;t<this.meshes.length;t++){const i=this.model.getDrawableTextureIndex(t),s=e[i],o=h[i];if(!s)throw new Error(`Drawable ${t} references a missing texture.`);this.meshes[t].mainBinding=this.bind(s,null!=(n=null==(r=this.drawableMasks[t])?void 0:r.view)?n:this.whiteView,o),this.meshes[t].maskBinding=this.bind(s,this.whiteView,o)}}const c=o.renderTarget.renderTarget,p=o.renderTarget.getGpuRenderTarget(c);if(1!==c.colorTextures.length)throw new Error("Live2D WebGPU requires one color attachment.");const g=p.contexts[0]?p.contexts[0].getCurrentTexture().format:o.texture.getGpuSource(c.colorTexture).format,m=o.pipeline,f=c.depthStencilTexture?u(d({},m._stencilState),{format:"depth24plus-stencil8",depthWriteEnabled:!1,depthCompare:"always"}):void 0,y=()=>{o.renderTarget.adaptor.startRenderPass(c,!1,void 0,o.renderTarget.viewport),o.renderTarget.onRenderTargetChange.emit(c)};o.encoder.endRenderPass();const x=o.encoder.commandEncoder,{model:M}=this;for(let d=0;d<this.meshes.length;d++){const e=d*this.uniformStride/4;this.uniformData.set(a,e),this.uniformData.set([s.r,s.g,s.b,1],e+28);const t=M.getMultiplyColor(d),r=M.getScreenColor(d);this.uniformData.set([t.r,t.g,t.b,t.a],e+16),this.uniformData.set([r.r,r.g,r.b,r.a],e+20),this.uniformData.set([M.getDrawableOpacity(d)*i*s.a,this.drawableMasks[d]?M.getDrawableInvertedMaskBit(d)?2:1:0,0,0],e+24)}this.upload(x);const v=a[0]*a[5]-a[1]*a[4]<0,b=(e,t,i)=>{var s;const r=this.meshes[t];if(!r.indexCount)return;const n=i?"mask":null!=(s=["normal","add","multiply"][M.getDrawableBlendMode(t)])?s:"normal";e.setPipeline(this.pipeline(n,M.getDrawableCulling(t),i||!this.meshFrontFace?v:"cw"===this.meshFrontFace,i?"rgba8unorm":g,i?1:p.msaaSamples,i?void 0:f,i?GPUColorWrite.ALL:m._colorMask)),e.setBindGroup(0,i?r.maskBinding:r.mainBinding,[t*this.uniformStride]),e.setVertexBuffer(0,r.positions),e.setVertexBuffer(1,r.uvs),e.setIndexBuffer(r.indices,"uint16"),e.drawIndexed(r.indexCount)};try{for(const s of this.masks.values()){const e=x.beginRenderPass({label:"Live2D mask",colorAttachments:[{view:s.view,clearValue:{r:1,g:1,b:1,a:1},loadOp:"clear",storeOp:"store"}]});for(const t of s.sources)b(e,t,!0);e.end()}y();const e=o.encoder.renderPassEncoder,t=M.getDrawableRenderOrders(),i=this.meshes.map((e,t)=>t).sort((e,i)=>t[e]-t[i]);for(const s of i)M.getDrawableDynamicFlagIsVisible(s)&&M.getDrawableOpacity(s)>0&&b(e,s,!1)}finally{y()}}upload(e){const t=[{buffer:this.uniform,data:this.uniformData},...this.meshes.map((e,t)=>({buffer:e.positions,data:this.model.getDrawableVertices(t)}))].filter(({data:e})=>e.byteLength>0),i=t.reduce((e,{data:t})=>e+t.byteLength,0);if(!i)return;const s=this.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_SRC,mappedAtCreation:!0}),r=new Uint8Array(s.getMappedRange());let n=0;for(const{data:o}of t)r.set(new Uint8Array(o.buffer,o.byteOffset,o.byteLength),n),n+=o.byteLength;s.unmap(),n=0;for(const{buffer:o,data:a}of t)e.copyBufferToBuffer(s,n,o,0,a.byteLength),n+=a.byteLength;this.renderer.encoder.commandFinished.then(()=>s.destroy())}destroy(){if(!this.destroyed){this._destroyed=!0;for(const e of this.meshes)e.positions.destroy(),e.uvs.destroy(),e.indices.destroy();for(const e of this.masks.values())e.texture.destroy();this.uniform.destroy(),this.white.destroy(),this.pipelines.clear()}}}function Ue(e){const t=e.getModelContext();if(!Array.isArray(t._$aS)||"function"!=typeof t.draw||"function"!=typeof t._$C2)throw new Error("Unsupported Cubism 2 Core: drawable access is unavailable.");return t}class Ne{constructor(e){c(this,"context"),c(this,"vertices"),c(this,"uvs"),c(this,"indices"),c(this,"textures"),c(this,"masks"),c(this,"maskCounts"),c(this,"orders"),c(this,"opacities"),c(this,"blends"),c(this,"cullings"),c(this,"visible"),c(this,"contexts",new Map),c(this,"white",{r:1,g:1,b:1,a:1}),c(this,"black",{r:0,g:0,b:0,a:0}),c(this,"currentCulling",!1),c(this,"drawOrder",0),c(this,"disableCulling",!1),c(this,"sink",{_$ZT:()=>{},setClipBufPre_clipContextForDraw:()=>{},_$WP:e=>{this.currentCulling=e},_$Uo:(e,t,i,s,r,n,o,a)=>{const l=this.contexts.get(a);if(void 0===l)throw new Error("Unknown Cubism 2 draw context.");this.orders[l]=this.drawOrder++,this.opacities[l]=n,this.blends[l]=o,this.cullings[l]=this.currentCulling&&!this.disableCulling,this.visible[l]=n>=.01}}),this.model=e,this.context=Ue(e);const t=this.context._$aS;this.vertices=t.map((t,i)=>new Float32Array(e.getTransformedPoints(i).length)),this.uvs=t.map(e=>e._$ZL()),this.indices=t.map(e=>Uint16Array.from(e.getIndexArray())),this.textures=t.map(e=>e.getTextureNo()<0?1:e.getTextureNo()),this.masks=t.map((e,t)=>{var i,s;return new Int32Array(null!=(s=null==(i=this.context._$C2(t).clipBufPre_clipContext)?void 0:i.clippingMaskDrawIndexList)?s:[])}),this.maskCounts=new Int32Array(this.masks.map(e=>e.length)),this.orders=new Int32Array(t.length),this.opacities=new Float32Array(t.length),this.blends=new Uint8Array(t.length),this.cullings=t.map(e=>e.culling),this.visible=t.map(()=>!1),t.forEach((e,t)=>this.contexts.set(this.context._$C2(t),t))}refresh(e=!1){this.disableCulling=e,this.drawOrder=0,this.visible.fill(!1),this.opacities.fill(0);for(let t=0;t<this.vertices.length;t++){this.cullings[t]=this.context._$aS[t].culling&&!e;const i=this.vertices[t];this.context._$C2(t)._$IS[0]?i.fill(0):i.set(this.model.getTransformedPoints(t))}this.context.draw(this.sink)}getDrawableCount(){return this.vertices.length}getDrawableMaskCounts(){return this.maskCounts}getDrawableMasks(){return this.masks}getDrawableTextureIndex(e){return this.textures[e]}getDrawableVertices(e){return this.vertices[e]}getDrawableVertexUvs(e){return this.uvs[e]}getDrawableVertexIndices(e){return this.indices[e]}getDrawableVertexIndexCount(e){return this.indices[e].length}getDrawableRenderOrders(){return this.orders}getDrawableOpacity(e){return this.opacities[e]}getDrawableCulling(e){return this.cullings[e]}getDrawableBlendMode(e){return this.blends[e]}getDrawableDynamicFlagIsVisible(e){return this.visible[e]}getDrawableInvertedMaskBit(){return!1}getMultiplyColor(){return this.white}getScreenColor(){return this.black}}class Be extends AMotion{constructor(e){super(),c(this,"params",[]),this.setFadeIn(e.fade_in>0?e.fade_in:g.expressionFadingDuration),this.setFadeOut(e.fade_out>0?e.fade_out:g.expressionFadingDuration),Array.isArray(e.params)&&e.params.forEach(e=>{const t=e.calc||"add";if("add"===t){const t=e.def||0;e.val-=t}else if("mult"===t){const t=e.def||1;e.val/=t}this.params.push({calc:t,val:e.val,id:e.id})})}updateParamExe(e,t,i,s){this.params.forEach(t=>{e.setParamFloat(t.id,t.val*i)})}}class je extends E{constructor(e,t){var i;super(e,t),c(this,"queueManager",new MotionQueueManager),c(this,"definitions"),this.definitions=null!=(i=this.settings.expressions)?i:[],this.init()}isFinished(){return this.queueManager.isFinished()}getExpressionIndex(e){return this.definitions.findIndex(t=>t.name===e)}getExpressionFile(e){return e.file}createExpression(e,t){return new Be(e)}_setExpression(e){return this.queueManager.startMotion(e)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(e,t){return this.queueManager.updateParam(e)}}function He(e,t,i){const s=i.getDurationMSec(),r=e.startMotion(i,!0),n=e.motions.find(e=>!!e&&e._$sr===r);return!!n&&(i.updateParamExe(t.coreModel,s,1,n),!0)}class Ve extends H{constructor(e){super(e),c(this,"definitions"),c(this,"groups",{idle:"idle"}),c(this,"motionDataType","arraybuffer"),c(this,"queueManager",new MotionQueueManager),c(this,"lipSyncIds"),c(this,"expressionManager"),this.definitions=this.settings.motions,this.init(e.options),this.lipSyncIds=["PARAM_MOUTH_OPEN_Y"]}init(e){super.init(e),this.settings.expressions&&(this.expressionManager=new je(this.settings,e))}isFinished(){return this.queueManager.isFinished()}createMotion(e,t,i){const s=Live2DMotion.loadMotion(e),r=t===this.groups.idle?g.idleMotionFadingDuration:g.motionFadingDuration;return s.setFadeIn(i.fade_in>0?i.fade_in:r),s.setFadeOut(i.fade_out>0?i.fade_out:r),s}getMotionFile(e){return e.file}getMotionName(e){return e.file}getSoundFile(e){return e.sound}_startMotion(e,t,i,s){return e.onFinishHandler=t,i&&i.length>0&&(e.motions=e.motions.filter(e=>!i.includes(e._$4P))),this.queueManager.stopAllMotions(),this.queueManager.startMotion(e)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(e,t){return this.queueManager.updateParam(e)}destroy(){super.destroy(),this.queueManager=void 0}motionLastFrame(e,t){return p(this,arguments,function*(e,t,{expression:i}={}){const s=yield this.getMotionAndApplyExpression(e,t,i);return!!s&&(this.playing=!0,He(this.queueManager,this.parent,s),this.playing=!1,!0)})}}class $e extends t.EventEmitter{constructor(e){super(),c(this,"tag"),c(this,"manager"),c(this,"settings"),c(this,"state",new S),c(this,"playing",!1),c(this,"destroyed",!1),c(this,"parent"),this.settings=e.settings,this.tag=`ParallelMotionManager(${this.settings.name})`,this.state.tag=this.tag,this.manager=e.motionManager,this.parent=e}startMotion(e,t){return p(this,arguments,function*(e,t,i=T.NORMAL,s={}){var r;const{ignoreParamIds:n=[],loop:o}=Array.isArray(s)?{ignoreParamIds:s,loop:void 0}:s;if(!this.state.reserve(e,t,i))return!1;const a=null==(r=this.manager.definitions[e])?void 0:r[t];if(!a)return!1;const l=yield this.manager.loadMotion(e,t);return!!this.state.start(l,e,t,i)&&(m.log(this.tag,"Start motion:",this.getMotionName(a)),this.emit("motionStart",e,t,void 0),this.playing=!0,this._startMotion(l,void 0,n,o),!0)})}startRandomMotion(e,t){return p(this,arguments,function*(e,t,{loop:i}={}){var s;const r=this.manager.definitions[e];if(null==r?void 0:r.length){const n=[],o=null!=(s=this.manager.motionGroups[e])?s:[];for(let t=0;t<r.length;t++)null===o[t]||this.state.isActive(e,t)||n.push(t);if(n.length){const s=n[Math.floor(Math.random()*n.length)];return this.startMotion(e,s,t,{loop:i})}}return!1})}stopAllMotions(){this._stopAllMotions(),this.state.reset()}update(e,t){return this.isFinished()&&(this.playing&&(this.playing=!1,this.emit("motionFinish")),this.state.complete()),this.updateParameters(e,t)}destroy(){this.destroyed=!0,this.emit("destroy"),this.stopAllMotions()}}class We extends $e{constructor(e){super(e),c(this,"queueManager",new MotionQueueManager)}isFinished(){return this.queueManager.isFinished()}getMotionName(e){return e.file}_startMotion(e,t,i,s){return e.onFinishHandler=t,i&&i.length>0&&(e.motions=e.motions.filter(e=>!i.includes(e._$4P))),this.queueManager.stopAllMotions(),this.queueManager.startMotion(e)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(e,t){return this.queueManager.updateParam(e)}destroy(){super.destroy(),this.queueManager=void 0}playMotionLastFrame(e,t){return p(this,null,function*(){var i;if(!this.state.reserve(e,t,T.FORCE))return!1;const s=null==(i=this.manager.definitions[e])?void 0:i[t];if(!s)return!1;const r=yield this.manager.loadMotion(e,t);return!!this.state.start(r,e,t,T.FORCE)&&(m.log(this.tag,"Start motion:",this.getMotionName(s)),this.queueManager.stopAllMotions(),this.emit("motionStart",e,t,void 0),this.playing=!0,!!He(this.queueManager,this.parent,r)&&(this.playing=!1,!0))})}}class Xe{constructor(e){c(this,"leftParam"),c(this,"rightParam"),c(this,"blinkInterval",4e3),c(this,"closingDuration",100),c(this,"closedDuration",50),c(this,"openingDuration",150),c(this,"eyeState",0),c(this,"eyeParamValue",1),c(this,"closedTimer",0),c(this,"nextBlinkTimeLeft",this.blinkInterval),this.coreModel=e,this.leftParam=e.getParamIndex("PARAM_EYE_L_OPEN"),this.rightParam=e.getParamIndex("PARAM_EYE_R_OPEN")}setEyeParams(e){this.eyeParamValue=f(e,0,1),this.coreModel.setParamFloat(this.leftParam,this.eyeParamValue),this.coreModel.setParamFloat(this.rightParam,this.eyeParamValue)}update(e){switch(this.eyeState){case 0:this.nextBlinkTimeLeft-=e,this.nextBlinkTimeLeft<0&&(this.eyeState=1,this.nextBlinkTimeLeft=this.blinkInterval+this.closingDuration+this.closedDuration+this.openingDuration+y(0,2e3));break;case 1:this.setEyeParams(this.eyeParamValue+e/this.closingDuration),this.eyeParamValue<=0&&(this.eyeState=2,this.closedTimer=0);break;case 2:this.closedTimer+=e,this.closedTimer>=this.closedDuration&&(this.eyeState=3);break;case 3:this.setEyeParams(this.eyeParamValue+e/this.openingDuration),this.eyeParamValue>=1&&(this.eyeState=0)}}}const Ye=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class ze extends W{constructor(e,t,i){super(),c(this,"settings"),c(this,"options"),c(this,"coreModel"),c(this,"motionManager"),c(this,"parallelMotionManager"),c(this,"eyeBlink"),c(this,"eyeballXParamIndex"),c(this,"eyeballYParamIndex"),c(this,"angleXParamIndex"),c(this,"angleYParamIndex"),c(this,"angleZParamIndex"),c(this,"bodyAngleXParamIndex"),c(this,"breathParamIndex"),c(this,"textureFlipY",!0),c(this,"lipSync",!0),c(this,"drawDataCount",0),c(this,"disableCulling",!1),c(this,"hasDrawn",!1),c(this,"gpuData"),c(this,"gpuRenderers",new Map),c(this,"customHitAreas"),this.coreModel=e,this.settings=t,this.options=Object.assign({},{breathDepth:1,lipSyncGain:1.5,lipSyncWeight:.4},i),void 0!==(null==i?void 0:i.useHighPrecisionMask)&&!1!==i.useHighPrecisionMask&&m.warn("CubismLegacyInternalModel","`useHighPrecisionMask` is only supported by Cubism 3/4/5 models and will be ignored for Cubism 2 models."),this.motionManager=new Ve(this),this.parallelMotionManager=[],!1!==this.options.eyeBlink&&(this.eyeBlink=new Xe(e)),this.eyeballXParamIndex=e.getParamIndex("PARAM_EYE_BALL_X"),this.eyeballYParamIndex=e.getParamIndex("PARAM_EYE_BALL_Y"),this.angleXParamIndex=e.getParamIndex("PARAM_ANGLE_X"),this.angleYParamIndex=e.getParamIndex("PARAM_ANGLE_Y"),this.angleZParamIndex=e.getParamIndex("PARAM_ANGLE_Z"),this.bodyAngleXParamIndex=e.getParamIndex("PARAM_BODY_ANGLE_X"),this.breathParamIndex=e.getParamIndex("PARAM_BREATH"),this.init()}init(){super.init(),this.settings.initParams&&this.settings.initParams.forEach(({id:e,value:t})=>this.coreModel.setParamFloat(e,t)),this.settings.initOpacities&&this.settings.initOpacities.forEach(({id:e,value:t})=>this.coreModel.setPartsOpacity(e,t)),this.coreModel.saveParam();const e=this.coreModel.getModelContext()._$aS;(null==e?void 0:e.length)&&(this.drawDataCount=e.length);let t=this.coreModel.drawParamWebGL.culling;Object.defineProperty(this.coreModel.drawParamWebGL,"culling",{set:e=>t=e,get:()=>!this.disableCulling&&t});const i=this.coreModel.getModelContext().clipManager,s=i.setupClip.bind(i);i.setupClip=(e,t)=>{s.call(i,e,t),t.gl.viewport(...this.viewport)}}getSize(){return[this.coreModel.getCanvasWidth(),this.coreModel.getCanvasHeight()]}getLayout(){const e={};if(this.settings.layout)for(const[t,i]of Object.entries(this.settings.layout)){let s=t;"center_x"===t?s="centerX":"center_y"===t&&(s="centerY"),"number"==typeof i&&(e[s]=i)}return e}updateWebGLContext(e,t){const i=this.coreModel.drawParamWebGL;i.firstDraw=!0,i.setGL(e),i.glno=t,i._$NT=null,i._$no=null,i._$vS=null;const s=this.coreModel.getModelContext().clipManager;s.curFrameNo=t;const r=e.getParameter(e.FRAMEBUFFER_BINDING);s.getMaskRenderTexture(),e.bindFramebuffer(e.FRAMEBUFFER,r)}bindTexture(e,t){this.coreModel.setTexture(e,t)}getHitAreaDefs(){var e,t,i;const s=this.settings.json;return V(null!=(i=null!=(t=null!=(e=this.settings.hitAreas)?e:s.hit_areas)?t:s.HitAreas)?i:s.hitAreas,e=>this.coreModel.getDrawDataIndex(e))}getDrawableIDs(){const e=this.coreModel.getModelContext(),t=[];for(let i=0;i<this.drawDataCount;i++){const s=e.getDrawData(i);s&&t.push(s.getDrawDataID().id)}return t}getDrawableIndex(e){return this.coreModel.getDrawDataIndex(e)}getDrawableVertices(e){if("string"==typeof e&&-1===(e=this.coreModel.getDrawDataIndex(e)))throw new TypeError("Unable to find drawable ID: "+e);return this.coreModel.getTransformedPoints(e).slice()}hitTest(e,t){this.hasDrawn||m.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(e,t),s=this.hitTestCustom(e,t);return s.length?i.length?[...new Set([...i,...s])]:s:i}update(e,t){var i,s,r,n;super.update(e,t);const o=this.coreModel,a=this.updateMotions(o,t);if(o.saveParam(),null==(i=this.motionManager.expressionManager)||i.update(o,t),a||null==(s=this.eyeBlink)||s.update(e),this.updateFocus(),this.updateNaturalMovements(e,t),this.lipSync&&this.motionManager.currentAudio){let e=this.motionManager.mouthSync()*this.options.lipSyncGain;const t=1,i=e>0?.1:0;e=Math.pow(e,1.15),e=f(e,i,t);for(let s=0;s<this.motionManager.lipSyncIds.length;++s)this.coreModel.addToParamFloat(this.coreModel.getParamIndex(this.motionManager.lipSyncIds[s]),e,this.options.lipSyncWeight)}null==(r=this.physics)||r.update(t),null==(n=this.pose)||n.update(e),this.emit("beforeModelUpdate"),Ue(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(e,t){const i=t/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(e){const t=this.disableCulling;e.getParameter(e.FRAMEBUFFER_BINDING)&&(this.disableCulling=!0);const i=this.drawingMatrix;Ye[0]=i.a,Ye[1]=i.b,Ye[4]=i.c,Ye[5]=i.d,Ye[12]=i.tx,Ye[13]=i.ty,this.coreModel.setMatrix(Ye);try{Ue(this.coreModel).preDraw(this.coreModel.drawParamWebGL),this.coreModel.draw(),this.hasDrawn=!0}finally{this.disableCulling=t}}drawWebGPU(e,t,i){null!=this.gpuData||(this.gpuData=new Ne(this.coreModel));const s=e.renderTarget.getGpuRenderTarget(e.renderTarget.renderTarget);this.gpuData.refresh(this.disableCulling||!s.contexts[0]);let r=this.gpuRenderers.get(e);(null==r?void 0:r.device)!==e.gpu.device&&(r&&(e.runners.destroy.remove(r),r.destroy()),r=new Ge(e,this.gpuData,"cw"),this.gpuRenderers.set(e,r),e.runners.destroy.add(r)),r.render(this.drawingMatrix,t,i),this.hasDrawn=!0}extendParallelMotionManager(e){for(;this.parallelMotionManager.length<e;)this.parallelMotionManager.push(new We(this))}destroy(){for(const[e,t]of this.gpuRenderers)t.destroyed||e.runners.destroy.remove(t),t.destroy();this.gpuRenderers.clear(),this.gpuData=void 0,super.destroy(),this.coreModel=void 0}hitTestCustom(e,t){const i=this.getCustomHitAreas();if(!i)return[];const s=this.originalWidth||this.width,r=this.originalHeight||this.height;if(!s||!r)return[];const n=e/s*2-1,o=1-t/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 e,t,i,s,r;if(void 0!==this.customHitAreas)return this.customHitAreas;const n=this.settings.json,o=null!=(i=null!=(t=null!=(e=n.hit_areas_custom)?e:n.hitAreasCustom)?t:n.HitAreasCustom)?i:n.HitAreas_Custom;if(!o||"object"!=typeof o)return this.customHitAreas=null,null;const a=o,l={},h=(e,t,i)=>{if(!e||!Array.isArray(t)||!Array.isArray(i))return;if(t.length<2||i.length<2)return;const s=Number(t[0]),r=Number(t[1]),n=Number(i[0]),o=Number(i[1]);Number.isFinite(s)&&Number.isFinite(r)&&Number.isFinite(n)&&Number.isFinite(o)&&(l[e]={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 e=d.slice(0,-2);h(e,u,a[`${e}_y`]);continue}if(!d.endsWith("_y")&&(u&&"object"==typeof u)){const e=u;h(d,null!=(s=e.x)?s:e.X,null!=(r=e.y)?r:e.Y)}}return this.customHitAreas=Object.keys(l).length?l:null,this.customHitAreas}}const qe={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE},Je={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE};class Ze{constructor(e,t){c(this,"physicsHairs",[]),this.coreModel=e,t.physics_hair&&(this.physicsHairs=t.physics_hair.map(e=>{const t=new PhysicsHair;return t.setup(e.setup.length,e.setup.regist,e.setup.mass),e.src.forEach(({id:e,ptype:i,scale:s,weight:r})=>{const n=qe[i];n&&t.addSrcParam(n,e,s,r)}),e.targets.forEach(({id:e,ptype:i,scale:s,weight:r})=>{const n=Je[i];n&&t.addTargetParam(n,e,s,r)}),t}))}update(e){this.physicsHairs.forEach(t=>t.update(this.coreModel,e))}}class Qe{constructor(e){c(this,"paramIndex",-1),c(this,"partsIndex",-1),c(this,"link",[]),this.id=e}initIndex(e){this.paramIndex=e.getParamIndex("VISIBLE:"+this.id),this.partsIndex=e.getPartsDataIndex(PartsDataID.getID(this.id)),e.setParamFloat(this.paramIndex,1)}}class Ke{constructor(e,t){c(this,"opacityAnimDuration",500),c(this,"partsGroups",[]),this.coreModel=e,t.parts_visible&&(this.partsGroups=t.parts_visible.map(({group:e})=>e.map(({id:e,link:t})=>{const i=new Qe(e);return t&&(i.link=t.map(e=>new Qe(e))),i})),this.init())}init(){this.partsGroups.forEach(e=>{e.forEach(e=>{if(e.initIndex(this.coreModel),e.paramIndex>=0){const t=0!==this.coreModel.getParamFloat(e.paramIndex);this.coreModel.setPartsOpacity(e.partsIndex,t?1:0),this.coreModel.setParamFloat(e.paramIndex,t?1:0),e.link.length>0&&e.link.forEach(e=>e.initIndex(this.coreModel))}})})}normalizePartsOpacityGroup(e,t){const i=this.coreModel,s=.5;let r=1,n=e.findIndex(({paramIndex:e,partsIndex:t})=>t>=0&&0!==i.getParamFloat(e));if(n>=0){const s=i.getPartsOpacity(e[n].partsIndex);r=f(s+t/this.opacityAnimDuration,0,1)}else n=0,r=1;e.forEach(({partsIndex:e},t)=>{if(e>=0)if(n==t)i.setPartsOpacity(e,r);else{let t,n=i.getPartsOpacity(e);t=r<s?-.5*r/s+1:(1-r)*s/.5;(1-t)*(1-r)>.15&&(t=1-.15/(1-r)),n>t&&(n=t),i.setPartsOpacity(e,n)}})}copyOpacity(e){const t=this.coreModel;e.forEach(({partsIndex:e,link:i})=>{if(e>=0&&i){const s=t.getPartsOpacity(e);i.forEach(({partsIndex:e})=>{e>=0&&t.setPartsOpacity(e,s)})}})}update(e){this.partsGroups.forEach(t=>{this.normalizePartsOpacityGroup(t,e),this.copyOpacity(t)})}}ge.registerRuntime({version:2,test:e=>e instanceof Z||Z.isValidJSON(e),ready:()=>Promise.resolve(),isValidMoc(e){if(e.byteLength<3)return!1;const t=new Int8Array(e,0,3);return"moc"===String.fromCharCode(...t)},createModelSettings:e=>new Z(e),createCoreModel(e){const t=Live2DModelWebGL.loadModel(e),i=Live2D.getError();if(i){if(i instanceof Error)throw i;const e="string"==typeof i?i:`Live2D error: ${JSON.stringify(i)}`;throw new Error(e)}return t},createInternalModel:(e,t,i)=>new ze(e,t,i),createPose:(e,t)=>new Ke(e,t),createPhysics:(e,t)=>new Ze(e,t)}),e.CubismLegacyExpressionManager=je,e.CubismLegacyInternalModel=ze,e.CubismLegacyModelSettings=Z,e.CubismLegacyMotionManager=Ve,e.CubismLegacyParallelMotionManager=We,e.ExpressionManager=E,e.FileLoader=ce,e.FocusController=I,e.InternalModel=W,e.LOGICAL_HEIGHT=2,e.LOGICAL_WIDTH=2,e.Live2DExpression=Be,e.Live2DEyeBlink=Xe,e.Live2DFactory=ge,e.Live2DLoader=J,e.Live2DModel=_e,e.Live2DPhysics=Ze,e.Live2DPlugin=Te,e.Live2DPose=Ke,e.Live2DTransform=ve,e.MBToByte=function(e){return 1024*e*1024},e.ModelSettings=F,e.MotionManager=H,e.MotionPreloadStrategy=j,e.MotionPriority=T,e.MotionState=S,e.SoundManager=B,e.VERSION="1.5.0",e.VOLUME=A,e.XHRLoader=z,e.applyMixins=function(e,t){t.forEach(t=>{Object.getOwnPropertyNames(t.prototype).forEach(i=>{"constructor"!==i&&Object.defineProperty(e.prototype,i,Object.getOwnPropertyDescriptor(t.prototype,i))})})},e.clamp=f,e.config=g,e.copyArray=M,e.copyProperty=x,e.folderName=v,e.logger=m,e.normalizeHitAreaDefs=V,e.rand=y,e.remove=b,e.resolveURL=P,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("pixi.js")):"function"==typeof define&&define.amd?define(["exports","pixi.js"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).PIXI=e.PIXI||{},e.PIXI.live2d=e.PIXI.live2d||{}),e.PIXI)}(this,function(e,t){"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=(e,t,s)=>t in e?i(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,d=(e,t)=>{for(var i in t||(t={}))o.call(t,i)&&h(e,i,t[i]);if(n)for(var i of n(t))a.call(t,i)&&h(e,i,t[i]);return e},u=(e,t)=>s(e,r(t)),c=(e,t,i)=>h(e,"symbol"!=typeof t?t+"":t,i),p=(e,t,i)=>new Promise((s,r)=>{var n=e=>{try{a(i.next(e))}catch(t){r(t)}},o=e=>{try{a(i.throw(e))}catch(t){r(t)}},a=e=>e.done?s(e.value):Promise.resolve(e.value).then(n,o);a((i=i.apply(e,t)).next())});const g={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"}))},m={log(e,...t){g.logLevel<=g.LOG_LEVEL_VERBOSE&&console.log(`[${e}]`,...t)},warn(e,...t){g.logLevel<=g.LOG_LEVEL_WARNING&&console.warn(`[${e}]`,...t)},error(e,...t){g.logLevel<=g.LOG_LEVEL_ERROR&&console.error(`[${e}]`,...t)}};function f(e,t,i){return e<t?t:e>i?i:e}function x(e,t){return Math.random()*(t-e)+e}function y(e,t,i,s,r){const n=t[s];null!==n&&typeof n===e&&(i[r]=n)}function M(e,t,i,s,r){const n=t[s];Array.isArray(n)&&(i[r]=n.filter(t=>null!==t&&typeof t===e))}function v(e){let t=e.lastIndexOf("/");return-1!=t&&(e=e.slice(0,t)),t=e.lastIndexOf("/"),-1!==t&&(e=e.slice(t+1)),e}function b(e,t){const i=e.indexOf(t);-1!==i&&e.splice(i,1)}const w=/^[a-zA-Z][a-zA-Z0-9+.-]*:/;function P(e,t){if(!t)return e;if(w.test(t))return t;if(t.startsWith("/"))return w.test(e)?new URL(t,e).toString():t;if(w.test(e))return new URL(t,e).toString();const i="http://example.com",s=e.startsWith("/")?i+e:`${i}/${e}`,r=new URL(t,s);let n=r.pathname+r.search+r.hash;return!e.startsWith("/")&&n.startsWith("/")&&(n=n.slice(1)),n}class E extends t.EventEmitter{constructor(e,t){super(),c(this,"expressionDataType","json"),c(this,"tag"),c(this,"settings"),c(this,"expressions",[]),c(this,"defaultExpression"),c(this,"currentExpression"),c(this,"reserveExpressionIndex",-1),c(this,"destroyed",!1),this.settings=e,this.tag=`ExpressionManager(${e.name})`}init(){this.defaultExpression=this.createDefaultExpression(),this.currentExpression=this.defaultExpression,this.stopAllExpressions()}createDefaultExpression(){return this.createExpression({},void 0)}loadExpression(e){return p(this,null,function*(){if(!this.definitions[e])return void m.warn(this.tag,`Undefined expression at [${e}]`);if(null===this.expressions[e])return void m.warn(this.tag,`Cannot set expression at [${e}] because it's already failed in loading.`);if(this.expressions[e])return this.expressions[e];const t=yield this._loadExpression(e);return this.expressions[e]=t,t})}_loadExpression(e){throw new Error("Not implemented.")}setRandomExpression(){return p(this,null,function*(){if(this.definitions.length){const e=[];for(let t=0;t<this.definitions.length;t++)null!==this.expressions[t]&&this.expressions[t]!==this.currentExpression&&t!==this.reserveExpressionIndex&&e.push(t);if(e.length){const t=Math.floor(Math.random()*e.length);return this.setExpression(t)}}return!1})}resetExpression(){this._setExpression(this.defaultExpression)}restoreExpression(){this._setExpression(this.currentExpression)}setExpression(e){return p(this,null,function*(){if("number"!=typeof e&&(e=this.getExpressionIndex(e)),!(e>-1&&e<this.definitions.length))return!1;if(e===this.expressions.indexOf(this.currentExpression))return!1;this.reserveExpressionIndex=e;const t=yield this.loadExpression(e);return!(!t||this.reserveExpressionIndex!==e)&&(this.reserveExpressionIndex=-1,this.currentExpression=t,this._setExpression(t),!0)})}update(e,t){return!this.isFinished()&&this.updateParameters(e,t)}destroy(){this.destroyed=!0,this.emit("destroy");this.definitions=void 0,this.expressions=void 0}}const L=40/7.5,D=1/150;class I{constructor(){c(this,"targetX",0),c(this,"targetY",0),c(this,"x",0),c(this,"y",0),c(this,"vx",0),c(this,"vy",0)}focus(e,t,i=!1){this.targetX=f(e,-1,1),this.targetY=f(t,-1,1),i&&(this.x=this.targetX,this.y=this.targetY)}update(e){const t=this.targetX-this.x,i=this.targetY-this.y;if(Math.abs(t)<.01&&Math.abs(i)<.01)return;const s=Math.sqrt(l(t,2)+l(i,2)),r=L/(1e3/e);let n=r*(t/s)-this.vx,o=r*(i/s)-this.vy;const a=Math.sqrt(l(n,2)+l(o,2)),h=r*D*e;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 F{constructor(e){c(this,"json"),c(this,"name"),c(this,"url"),c(this,"pose"),c(this,"physics"),this.json=e,this.url=e.url,this.name=v(this.url)}normalizeName(){this.name&&"name"!==this.name.toLowerCase()||(this.name=v(this.url))}setModelName(...e){for(const t of e){const e="string"==typeof t?t.trim():"";if(e&&"name"!==e.toLowerCase())return void(this.name=e)}this.normalizeName()}getFileStem(e){if(!e)return;const t=e.split(/[/\\]/).filter(Boolean).pop();return null==t?void 0:t.replace(/\.[^.]+$/,"")}resolveURL(e){return P(this.url,e)}replaceFiles(e){this.moc=e(this.moc,"moc"),void 0!==this.pose&&(this.pose=e(this.pose,"pose")),void 0!==this.physics&&(this.physics=e(this.physics,"physics"));for(let t=0;t<this.textures.length;t++)this.textures[t]=e(this.textures[t],`textures[${t}]`)}getDefinedFiles(){const e=[];return this.replaceFiles(t=>(e.push(t),t)),e}validateFiles(e){const t=(t,i)=>{const s=this.resolveURL(t);if(!e.includes(s)){if(i)throw new Error(`File "${t}" is defined in settings, but doesn't exist in given files`);return!1}return!0};[this.moc,...this.textures].forEach(e=>t(e,!0));return this.getDefinedFiles().filter(e=>t(e,!1))}}var T=(e=>(e[e.NONE=0]="NONE",e[e.IDLE=1]="IDLE",e[e.NORMAL=2]="NORMAL",e[e.FORCE=3]="FORCE",e))(T||{});class S{constructor(){c(this,"tag"),c(this,"debug",!1),c(this,"currentPriority",0),c(this,"reservePriority",0),c(this,"currentGroup"),c(this,"currentIndex"),c(this,"reservedGroup"),c(this,"reservedIndex"),c(this,"reservedIdleGroup"),c(this,"reservedIdleIndex")}reserve(e,t,i){if(i<=0)return m.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(e===this.currentGroup&&t===this.currentIndex)return m.log(this.tag,"Motion is already playing.",this.dump(e,t)),!1;if(e===this.reservedGroup&&t===this.reservedIndex||e===this.reservedIdleGroup&&t===this.reservedIdleIndex)return m.log(this.tag,"Motion is already reserved.",this.dump(e,t)),!1;if(1===i){if(0!==this.currentPriority)return m.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(e,t)),!1;if(void 0!==this.reservedIdleGroup)return m.log(this.tag,"Cannot start idle motion because another idle motion has reserved.",this.dump(e,t)),!1;this.setReservedIdle(e,t)}else{if(i<3){if(i<=this.currentPriority)return m.log(this.tag,"Cannot start motion because another motion is playing as an equivalent or higher priority.",this.dump(e,t)),!1;if(i<=this.reservePriority)return m.log(this.tag,"Cannot start motion because another motion has reserved as an equivalent or higher priority.",this.dump(e,t)),!1}this.setReserved(e,t,i)}return!0}start(e,t,i,s){if(1===s){if(this.setReservedIdle(void 0,void 0),0!==this.currentPriority)return m.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,i)),!1}else{if(t!==this.reservedGroup||i!==this.reservedIndex)return m.log(this.tag,"Cannot start motion because another motion has taken the place.",this.dump(t,i)),!1;this.setReserved(void 0,void 0,0)}return!!e&&(this.setCurrent(t,i,s),!0)}complete(){this.setCurrent(void 0,void 0,0)}setCurrent(e,t,i){this.currentPriority=i,this.currentGroup=e,this.currentIndex=t}setReserved(e,t,i){this.reservePriority=i,this.reservedGroup=e,this.reservedIndex=t}setReservedIdle(e,t){this.reservedIdleGroup=e,this.reservedIdleIndex=t}isActive(e,t){return e===this.currentGroup&&t===this.currentIndex||e===this.reservedGroup&&t===this.reservedIndex||e===this.reservedIdleGroup&&t===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!g.preserveExpressionOnMotion&&this.currentPriority>1}dump(e,t){if(this.debug){return`\n<Requested> group = "${e}", index = ${t}\n`+["currentPriority","reservePriority","currentGroup","currentIndex","reservedGroup","reservedIndex","reservedIdleGroup","reservedIdleIndex"].map(e=>"["+e+"] "+this[e]).join("\n")}return""}}const _="SoundManager",A=.5;let O,C=0;const R=new WeakSet;function k(e){if(!R.has(e)){try{e.disableAutoPause=!0}catch(t){m.warn(_,"Failed to disable @pixi/sound auto pause.",t)}R.add(e)}return e}function G(){return p(this,null,function*(){const e="undefined"!=typeof PIXI?null==PIXI?void 0:PIXI.sound:void 0;return e?k(e):(null!=O||(O=import("@pixi/sound").then(({sound:e})=>k(e)).catch(e=>(m.warn(_,"@pixi/sound is not available. Load pixi-sound.js before using motion sounds, speak(), or lip sync.",e),null))),O)})}function U(e,t){try{e.remove(t)}catch(i){m.warn(_,`Failed to remove sound "${t}".`,i)}}function N(e){const t=e.media.buffer;if(!t||"object"!=typeof t)return;return"function"==typeof t.getChannelData?t:void 0}class B{static get volume(){return this._volume}static set volume(e){this._volume=(e>1?1:e<0?0:e)||0,this.audios.forEach(e=>e.volume=this._volume)}static add(e,t){return p(this,null,function*(){let i,s=null;try{if(s=yield G(),!s)throw new Error("@pixi/sound is not available");i="live2d-sound-"+C++;const t=s,r=i,n=new Promise((i,s)=>{const n=t.add(r,{url:e,volume:this._volume,preload:!0,loaded:(t,r)=>{if(t)return void s(t);const o=null!=r?r:n;o?N(o)?i(o):s(new Error(`Error: ${e} is not WebAudioMedia`)):s(new Error(`Error: ${e} failed to load`))}})}),o=yield n;return this.aliases.set(o,{alias:r,library:t}),this.audios.push(o),o}catch(r){return s&&i&&U(s,i),m.warn(_,`Error occurred on "${e}"`,r),null==t||t(r),null}})}static play(e,t){e.play({singleInstance:!0,complete:()=>{null==t||t(),this.dispose(e)}})}static addAnalyzer(e,t){const i=N(e);if(!i)return void m.warn(_,"Cannot create audio analyzer because WebAudio media is unavailable.");const s=t.createBufferSource();s.buffer=i;const r=t.createAnalyser();return r.fftSize=g.fftSize,r.minDecibels=-90,r.maxDecibels=-10,r.smoothingTimeConstant=.85,s.connect(r),s.start(0),this.analysers.push(r),r}static analyze(e){if(!e)return parseFloat(Math.random().toFixed(1));const t=new Float32Array(e.fftSize);e.getFloatTimeDomainData(t);let i=0;for(let o=0;o<t.length;o++)i+=l(t[o],2);const s=Math.sqrt(i/t.length),r=20*Math.log10(s||l(10,-5)),n=Math.min(Math.max((r-e.minDecibels)/(e.maxDecibels-e.minDecibels),0),1);return parseFloat(n.toFixed(1))}static dispose(e){try{e.pause()}catch(i){m.warn(_,"Failed to pause audio.",i)}const t=this.aliases.get(e);t?(U(t.library,t.alias),this.aliases.delete(e)):function(e){try{e.destroy()}catch(i){m.warn(_,"Failed to destroy audio.",i)}}(e),b(this.audios,e)}static destroy(){for(let e=this.contexts.length-1;e>=0;e--){const t=this.contexts[e];null==t||t.close().catch(e=>{m.warn(_,"Failed to close AudioContext.",e)})}for(let e=this.audios.length-1;e>=0;e--)this.dispose(this.audios[e])}}c(B,"audios",[]),c(B,"analysers",[]),c(B,"contexts",[]),c(B,"aliases",new WeakMap),c(B,"_volume",A);var j=(e=>(e.ALL="ALL",e.IDLE="IDLE",e.NONE="NONE",e))(j||{});class H extends t.EventEmitter{constructor(e){super(),c(this,"tag"),c(this,"settings"),c(this,"motionGroups",{}),c(this,"state",new S),c(this,"currentAudio"),c(this,"currentAnalyzer"),c(this,"currentContext"),c(this,"playing",!1),c(this,"destroyed",!1),c(this,"parent"),this.settings=e.settings,this.tag=`MotionManager(${this.settings.name})`,this.state.tag=this.tag,this.parent=e}init(e){(null==e?void 0:e.idleMotionGroup)&&(this.groups.idle=e.idleMotionGroup),this.setupMotions(e),this.stopAllMotions()}setupMotions(e){if(!this.definitions)return void m.warn(this.tag,"Motion definitions are not initialized.");for(const i of Object.keys(this.definitions))this.motionGroups[i]=[];let t;switch(null==e?void 0:e.motionPreload){case"NONE":return;case"ALL":t=Object.keys(this.definitions);break;default:t=[this.groups.idle]}for(const i of t){const e=this.definitions[i];if(e)for(let t=0;t<e.length;t++)this.loadMotion(i,t)}}loadMotion(e,t){return p(this,null,function*(){var i,s;if(this.destroyed)return;if(!this.getMotionDefinition(e,t))return;const r=null!=(s=(i=this.motionGroups)[e])?s:i[e]=[];if(null===r[t])return void m.warn(this.tag,`Cannot start motion at "${e}"[${t}] because it's already failed in loading.`);if(r[t])return r[t];const n=yield this._loadMotion(e,t);return this.destroyed?void 0:(r[t]=null!=n?n:null,n)})}_loadMotion(e,t){throw new Error("Not implemented.")}initializeAudio(e,t){this.currentAudio=e,B.volume=t,this.currentContext=e.context.audioContext,this.currentAnalyzer=B.addAnalyzer(this.currentAudio,this.currentContext)}speak(e){return p(this,arguments,function*(e,{volume:t=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:n}={}){if(!g.sound)return!1;let o,a;if(this.currentAudio&&this.currentAudio.isPlaying)return!1;const l=e&&e.startsWith("data:");if(e&&!l){const t=document.createElement("a");t.href=e,a=e=t.href}else a="data:audio/";const h=e;if(h)try{if(o=yield B.add(h,(e,t=this)=>{m.error(this.tag,"Error during audio playback:",e),null==n||n(e),s&&i&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0}),!o)return!1;this.initializeAudio(o,t)}catch(d){return m.warn(this.tag,"Failed to create audio",a,d),!1}if(o){let e=!0;try{g.motionSync&&B.play(o,()=>{null==r||r(),s&&i&&this.expressionManager&&this.expressionManager.resetExpression(),this.currentAudio=void 0})}catch(d){m.warn(this.tag,"Failed to play audio",o.url,d),e=!1}if(!e)return!1}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),i&&this.expressionManager&&(yield this.expressionManager.setExpression(i)),this.playing=!0,!0})}startMotion(e,t){return p(this,arguments,function*(e,t,i=T.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(e,t,i))return!1;if(this.currentAudio&&this.currentAudio.isPlaying&&i!=T.FORCE)return!1;const u=this.getMotionDefinition(e,t);if(!u)return!1;let c,p;this.currentAudio&&B.dispose(this.currentAudio);const f=s&&s.startsWith("data:");if(s&&!f){const e=document.createElement("a");e.href=s,p=s=e.href}else p=this.getSoundFile(u),p&&(p=this.settings.resolveURL(p));const x=p;if(x)try{c=yield B.add(x,(e,t=this)=>{m.error(this.tag,"Error during audio playback:",e),null==l||l(e),o&&n&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0}),c&&this.initializeAudio(c,r)}catch(M){m.warn(this.tag,"Failed to create audio",p,M)}const y=yield this.loadMotion(e,t);if(c&&g.motionSync)try{B.play(c,(e=this)=>{null==a||a(),o&&n&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0})}catch(M){m.warn(this.tag,"Failed to play audio",c.url,M)}return this.state.start(y,e,t,i)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),m.log(this.tag,"Start motion:",this.getMotionName(u)),this.emit("motionStart",e,t,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&&(B.dispose(c),this.currentAudio=void 0),!1)})}startRandomMotion(e,t){return p(this,arguments,function*(e,t,{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[e];if(null==u?void 0:u.length){const h=[],c=null!=(d=this.motionGroups[e])?d:[];for(let t=0;t<u.length;t++)null===c[t]||this.state.isActive(e,t)||h.push(t);if(h.length){const d=h[Math.floor(Math.random()*h.length)];return this.startMotion(e,d,t,{sound:i,volume:s,expression:r,resetExpression:n,onFinish:o,onError:a,loop:l})}}return!1})}stopSpeaking(){this.currentAudio&&(B.dispose(this.currentAudio),this.currentAudio=void 0)}stopAllMotions(){this._stopAllMotions(),this.state.reset(),this.stopSpeaking()}update(e,t){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,T.IDLE)),this.updateParameters(e,t)}mouthSync(){return this.currentAnalyzer?B.analyze(this.currentAnalyzer):0}destroy(){var e;this.destroyed=!0,this.emit("destroy"),this.stopAllMotions(),null==(e=this.expressionManager)||e.destroy();this.definitions=void 0,this.motionGroups=void 0}getMotionAndApplyExpression(e,t,i){return p(this,null,function*(){if(this.destroyed)return null;if(!this.state.reserve(e,t,T.FORCE))return null;const s=this.getMotionDefinition(e,t);if(!s)return null;this.currentAudio&&B.dispose(this.currentAudio);const r=yield this.loadMotion(e,t);return this.state.start(r,e,t,T.FORCE)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),m.log(this.tag,"Start motion:",this.getMotionName(s)),this.emit("motionStart",e,t,void 0),i&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(i)),r):null})}getMotionDefinition(e,t){var i,s;const r=null==(s=null==(i=this.definitions)?void 0:i[e])?void 0:s[t];return r||m.warn(this.tag,`Undefined motion at "${e}"[${t}]`),r}}function W(e,t){if(!Array.isArray(e))return[];const i=[];for(const s of e){if(!s||"object"!=typeof s)continue;const e=s,r="string"==typeof e.id?e.id:"string"==typeof e.Id?e.Id:void 0,n="string"==typeof e.name?e.name:"string"==typeof e.Name?e.Name:void 0;r&&n&&i.push({id:r,name:n,index:t(r)})}return i}const V={x:0,y:0,width:0,height:0};class $ extends t.EventEmitter{constructor(){super(...arguments),c(this,"focusController",new I),c(this,"pose"),c(this,"physics"),c(this,"originalWidth",0),c(this,"originalHeight",0),c(this,"width",0),c(this,"height",0),c(this,"localTransform",new t.Matrix),c(this,"drawingMatrix",new t.Matrix),c(this,"hitAreas",{}),c(this,"textureFlipY",!1),c(this,"viewport",[0,0,0,0]),c(this,"destroyed",!1)}init(){this.setupLayout(),this.setupHitAreas()}setupLayout(){const e=this,t=this.getSize();e.originalWidth=t[0],e.originalHeight=t[1];const i=function(e,t,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;e.identity(),e.scale(a/2,l/2);const h=t*e.a,u=i*e.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 e.translate(h*c,-u*p),{width:h,height:u}}(this.localTransform,this.originalWidth,this.originalHeight,this.getLayout());e.width=i.width,e.height=i.height}setupHitAreas(){const e=this.getHitAreaDefs();this.hitAreas={};for(const t of e)t.name&&(this.hitAreas[t.name]=t)}hitTest(e,t){return Object.keys(this.hitAreas).filter(i=>this.isHit(i,e,t))}isHit(e,t,i){const s=this.hitAreas[e];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,V);return n.x<=t&&t<=n.x+n.width&&n.y<=i&&i<=n.y+n.height}getDrawableBounds(e,t){const i=this.getDrawableVertices(e);let s=i[0],r=i[0],n=i[1],o=i[1];for(let a=0;a<i.length;a+=2){const e=i[a],t=i[a+1];s=Math.min(e,s),r=Math.max(e,r),n=Math.min(t,n),o=Math.max(t,o)}return null!=t||(t={}),t.x=s,t.y=n,t.width=r-s,t.height=o-n,t}updateTransform(e){this.drawingMatrix.copyFrom(e).append(this.localTransform)}drawWebGPU(e,t,i){throw new Error("This Live2D runtime does not implement WebGPU rendering.")}update(e,t){this.focusController.update(e)}destroy(){this.destroyed=!0,this.emit("destroy"),this.motionManager.destroy(),this.motionManager=void 0,this.parallelMotionManager.forEach(e=>e.destroy()),this.parallelMotionManager=[]}updateMotions(e,t){this.emit("beforeMotionUpdate");const i=this.motionManager.update(e,t),s=this.parallelMotionManager.map(i=>i.update(e,t)),r=i||s.reduce((e,t)=>e||t,!1);return this.emit("afterMotionUpdate"),r}}class X extends Error{constructor(e,t,i,s=!1){super(e),this.url=t,this.status=i,this.aborted=s}}const Y=class e{static createXHR(t,i,s,r,n){const o=new XMLHttpRequest;if(e.allXhrSet.add(o),t){let i=e.xhrMap.get(t);i?i.add(o):(i=new Set([o]),e.xhrMap.set(t,i))}return o.open("GET",i),o.responseType=s,o.onload=()=>{var e;200!==o.status&&0!==o.status||!o.response?null==(e=o.onerror)||e.call(o,new ProgressEvent("error")):r(o.response)},o.onerror=()=>{m.warn("XHRLoader",`Failed to load resource as ${o.responseType} (Status ${o.status}): ${i}`),n(new X("Network error.",i,o.status))},o.onabort=()=>n(new X("Aborted.",i,o.status,!0)),o.onloadend=()=>{var i;e.allXhrSet.delete(o),t&&(null==(i=e.xhrMap.get(t))||i.delete(o))},o}static cancelXHRs(){var t;null==(t=e.xhrMap.get(this))||t.forEach(t=>{t.abort(),e.allXhrSet.delete(t)}),e.xhrMap.delete(this)}static release(){e.allXhrSet.forEach(e=>e.abort()),e.allXhrSet.clear(),e.xhrMap=new WeakMap}};c(Y,"xhrMap",new WeakMap),c(Y,"allXhrSet",new Set),c(Y,"loader",e=>new Promise((t,i)=>{const s=e.target,r=e.target&&"function"==typeof Y.cancelXHRs?Y.cancelXHRs.bind(e.target):void 0,n=Y.createXHR(e.target,e.settings?e.settings.resolveURL(e.url):e.url,e.type,i=>{e.result=i,t()},i);if(e.target&&r&&"function"==typeof s.listeners&&"function"==typeof s.once){const e=s.listeners("destroy");Array.isArray(e)&&e.includes(r)||s.once("destroy",r)}n.send()}));let z=Y;function q(e,t){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=e[r];if(!o)return Promise.resolve();try{return Promise.resolve(o(t,s.bind(null,r+1)))}catch(a){const e=a instanceof Error?a:new Error(String(a));return Promise.reject(e)}}(0)}class J{static load(e){return p(this,null,function*(){return yield q(this.middlewares,e),e.result})}}c(J,"middlewares",[z.loader]);class Z extends F{constructor(e){if(super(e),c(this,"moc"),c(this,"textures"),c(this,"layout"),c(this,"hitAreas"),c(this,"initParams"),c(this,"initOpacities"),c(this,"expressions"),c(this,"motions",{}),!Z.isValidJSON(e))throw new TypeError("Invalid JSON.");this.moc=e.model,M("string",e,this,"textures","textures"),this.copy(e)}static isValidJSON(e){if(!e||"object"!=typeof e)return!1;const t=!!Array.isArray(e.textures)&&e.textures.every(e=>"string"==typeof e);return"string"==typeof e.model&&t}copy(e){y("string",e,this,"name","name"),y("string",e,this,"pose","pose"),y("string",e,this,"physics","physics"),y("object",e,this,"layout","layout"),y("object",e,this,"motions","motions"),M("object",e,this,"hit_areas","hitAreas"),M("object",e,this,"expressions","expressions"),M("object",e,this,"init_params","initParams"),M("object",e,this,"init_opacities","initOpacities");const t=this.getFileStem(this.moc);this.setModelName(this.name,t)}replaceFiles(e){super.replaceFiles(e);for(const[t,i]of Object.entries(this.motions))for(let s=0;s<i.length;s++)i[s].file=e(i[s].file,`motions.${t}[${s}].file`),void 0!==i[s].sound&&(i[s].sound=e(i[s].sound,`motions.${t}[${s}].sound`));if(this.expressions)for(let t=0;t<this.expressions.length;t++)this.expressions[t].file=e(this.expressions[t].file,`expressions[${t}].file`)}}function Q({lod:e,effectiveScale:t,textureWidth:i,textureHeight:s,lodScaleThreshold:r,lodTextureSizeThreshold:n,lodMaxLevel:o}){if("single-auto"!==K(e))return;if(!Number.isFinite(t)||t<=0)return;const a=Math.floor(i),h=Math.floor(s);if(a<=1||h<=1)return;if(t>=te(r,.5))return;const d=te(n,4096);if(Math.max(a,h)<d)return;const u=Math.round(Math.log2(1/t)),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(e,t,i){return Math.min(i,Math.max(t,e))}(Math.max(1,u),1,p),x=l(2,f);return{level:f,width:Math.max(1,Math.round(a/x)),height:Math.max(1,Math.round(h/x))}}function K(e){return!1===e||"single-auto"===e?e:"full"}function ee(e){return"nearest"===e?"nearest":"linear"}function te(e,t){return void 0!==e&&Number.isFinite(e)&&e>0?e:t}function ie(e){const[t=""]=e.split(/[?#]/,1),i=t.slice(t.lastIndexOf("/")+1),s=i.lastIndexOf(".");if(!(s<=0||s===i.length-1))return i.slice(s+1).toLowerCase()}function se(){}const re="Live2DFactory",ne=(e,t)=>p(null,null,function*(){if("string"==typeof e.source){const t=yield J.load({url:e.source,type:"json",target:e.live2dModel});t.url="string"==typeof t.url?t.url:e.source,e.source=t,e.live2dModel.emit("settingsJSONLoaded",t)}return t()}),oe=(e,t)=>p(null,null,function*(){if(e.source instanceof F)return e.settings=e.source,t();if("object"==typeof e.source){const i=ge.findRuntime(e.source);if(i){const s=i.createModelSettings(e.source);return e.settings=s,e.live2dModel.emit("settingsLoaded",s),t()}}const i=e.source&&"string"==typeof e.source.url?e.source.url:void 0,s=ge.runtimes.map(e=>e.version).join(", ");if(0===ge.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(!e.source||"object"!=typeof e.source||Array.isArray(e.source))return;return Object.keys(e.source).slice(0,30).join(", ")}catch(t){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"))}),ae=(e,t)=>{if(e.settings){const i=ge.findRuntime(e.settings);if(i)return i.ready().then(()=>t())}return t()},le=(e,t)=>p(null,null,function*(){yield t();const i=e.internalModel;if(i){const t=e.settings,s=ge.findRuntime(t);if(s){const r=[],n=t instanceof Z?"json":"arraybuffer";t.pose&&r.push(J.load({settings:t,url:t.pose,type:n,target:i}).then(t=>{i.pose=s.createPose(i.coreModel,t),e.live2dModel.emit("poseLoaded",i.pose)}).catch(t=>{e.live2dModel.emit("poseLoadError",t),m.warn(re,"Failed to load pose.",t)})),t.physics&&r.push(J.load({settings:t,url:t.physics,type:n,target:i}).then(t=>{i.physics=s.createPhysics(i.coreModel,t),e.live2dModel.emit("physicsLoaded",i.physics)}).catch(t=>{e.live2dModel.emit("physicsLoadError",t),m.warn(re,"Failed to load physics.",t)})),r.length&&(yield Promise.all(r))}}}),he=(e,i)=>p(null,null,function*(){if(!e.settings)throw new TypeError("Missing settings.");{const s=e.live2dModel,r=d({crossOrigin:e.options.crossOrigin},e.options.textureOptions);e.settings instanceof Z&&(r.preferCreateImageBitmap=!1);const n=Promise.all(e.settings.textures.map(i=>function(e,i={}){const s=t.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),t.Assets.load({src:e,format:i.format,parser:"texture",data:{autoGenerateMipmaps:"full"===K(i.lod)}}).catch(e=>{if(e instanceof Error)throw e;throw new Error("Texture loading error",{cause:e})}).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))})}(e.settings.resolveURL(i),u(d({},r),{format:ie(i)}))));if(n.catch(se),yield i(),!e.internalModel)throw new TypeError("Missing internal model.");s.internalModel=e.internalModel,s.emit("modelLoaded",e.internalModel),s.textures=yield n,s.emit("textureLoaded",s.textures)}}),de=(e,t)=>p(null,null,function*(){const i=e.settings;if(i instanceof F){const s=ge.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield J.load({settings:i,url:i.moc,type:"arraybuffer",target:e.live2dModel});if(!s.isValidMoc(r))throw new Error("Invalid moc data");const n=s.createCoreModel(r);return e.internalModel=s.createInternalModel(n,i,e.options),t()}throw new TypeError("Missing settings.")}),ue=class e{static resolveURL(t,i){var s;const r=null==(s=e.filesMap[t])?void 0:s[i];if(void 0===r)throw new Error("Cannot find this file from uploaded files: "+i);return r}static upload(t,i){const s={};for(const e of i.getDefinedFiles()){const r=decodeURI(P(i.url,e)),n=t.find(e=>e.webkitRelativePath===r);n&&(s[e]=URL.createObjectURL(n))}e.filesMap[i._objectURL]=s}static createSettings(t){return p(this,null,function*(){const i=t.find(e=>e.name.endsWith("model.json")||e.name.endsWith("model3.json"));if(!i)throw new TypeError("Settings file not found");const s=yield e.readText(i),r=JSON.parse(s);r.url=i.webkitRelativePath;const n=ge.findRuntime(r);if(!n)throw new Error("Unknown settings JSON");const o=n.createModelSettings(r);return o._objectURL=URL.createObjectURL(i),o})}static readText(e){return p(this,null,function*(){return new Promise((t,i)=>{const s=new FileReader;s.onload=()=>t(s.result),s.onerror=i,s.readAsText(e,"utf8")})})}};c(ue,"live2dFactory"),c(ue,"filesMap",{}),c(ue,"factory",(e,t)=>p(null,null,function*(){if(Array.isArray(e.source)&&e.source[0]instanceof File){const t=e.source;let i=t.settings;if(i){if(!i._objectURL)throw new Error('"_objectURL" must be specified in ModelSettings')}else i=yield ue.createSettings(t);i.validateFiles(t.map(e=>encodeURI(e.webkitRelativePath))),ue.upload(t,i),i.resolveURL=function(e){return ue.resolveURL(this._objectURL,e)},e.source=i,e.live2dModel.once("modelLoaded",e=>{e.once("destroy",function(){const e=this.settings._objectURL;if(URL.revokeObjectURL(e),ue.filesMap[e])for(const t of Object.values(ue.filesMap[e]))URL.revokeObjectURL(t);delete ue.filesMap[e]})})}return t()}));let ce=ue;const pe=class e{static registerRuntime(t){e.runtimes.push(t),e.runtimes.sort((e,t)=>t.version-e.version)}static findRuntime(t){for(const i of e.runtimes)if(i.test(t))return i}static setupLive2DModel(t,i,s){return p(this,null,function*(){const r=new Promise(e=>t.once("textureLoaded",e)),n=new Promise(e=>t.once("modelLoaded",e)),o=Promise.all([r,n]).then(()=>t.emit("ready"));yield q(e.live2DModelMiddlewares,{live2dModel:t,source:i,options:s||{}}),yield o,t.emit("load")})}static loadMotion(t,i,s){var r;const n=e=>t.emit("motionLoadError",i,s,e);try{const o=null==(r=t.definitions[i])?void 0:r[s];if(!o)return Promise.resolve(void 0);t.once("destroy",()=>e.releaseMotionTasks(t));let a=e.motionTasksMap.get(t);a||(a={},e.motionTasksMap.set(t,a));let l=a[i];l||(l=[],a[i]=l);const h=t.getMotionFile(o);return null!=l[s]||(l[s]=J.load({url:h,settings:t.settings,type:t.motionDataType,target:t}).then(r=>{var n;const a=null==(n=e.motionTasksMap.get(t))?void 0:n[i];a&&(a[s]=void 0);const l=r,h=t.createMotion(l,i,o);return t.emit("motionLoaded",i,s,h),h}).catch(e=>{m.warn(t.tag,`Failed to load motion: ${h}\n`,e),n(e)})),l[s]}catch(o){m.warn(t.tag,`Failed to load motion at "${i}"[${s}]\n`,o),n(o)}return Promise.resolve(void 0)}static loadExpression(t,i){var s;const r=e=>t.emit("expressionLoadError",i,e);try{const n=t.definitions[i];if(!n)return Promise.resolve(void 0);t.once("destroy",()=>e.releaseExpressionTasks(t));let o=e.expressionTasksMap.get(t);o||(o=[],e.expressionTasksMap.set(t,o));const a=t.getExpressionFile(n),l=null!=(s=t.expressionDataType)?s:"json";return null!=o[i]||(o[i]=J.load({url:a,settings:t.settings,type:l,target:t}).then(s=>{const r=e.expressionTasksMap.get(t);r&&(r[i]=void 0);const o=s,a=t.createExpression(o,n);return t.emit("expressionLoaded",i,a),a}).catch(e=>{m.warn(t.tag,`Failed to load expression: ${a}\n`,e),r(e)})),o[i]}catch(n){m.warn(t.tag,`Failed to load expression at [${i}]\n`,n),r(n)}return Promise.resolve(void 0)}static releaseMotionTasks(t){e.motionTasksMap.delete(t)}static releaseExpressionTasks(t){e.expressionTasksMap.delete(t)}};c(pe,"runtimes",[]),c(pe,"urlToJSON",ne),c(pe,"jsonToSettings",oe),c(pe,"waitUntilReady",ae),c(pe,"setupOptionals",le),c(pe,"setupEssentials",he),c(pe,"createInternalModel",de),c(pe,"live2DModelMiddlewares",[ce.factory,ne,oe,ae,le,he,de]),c(pe,"motionTasksMap",new WeakMap),c(pe,"expressionTasksMap",new WeakMap);let ge=pe;H.prototype._loadMotion=function(e,t){return ge.loadMotion(this,e,t)},E.prototype._loadExpression=function(e){return ge.loadExpression(this,e)},ce.live2dFactory=ge;const me=class e{constructor(i,{autoUpdate:s=!0,autoHitTest:r=!0,autoFocus:n=!0,autoInteract:o,ticker:a}={}){var l;c(this,"model"),c(this,"destroyed",!1),c(this,"_ticker"),c(this,"_autoUpdate",!1),c(this,"_autoHitTest",!1),c(this,"_autoFocus",!1),null!=a||(a=null!=(l=e.defaultTicker)?l:"undefined"!=typeof PIXI?PIXI.Ticker.shared:t.Ticker.shared),void 0!==o&&(r=o,n=o,m.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(e){var t,i;this._ticker&&this._ticker.remove(xe,this),this._ticker=e,this._autoUpdate&&(null==(t=this._ticker)||t.add(xe,this),null==(i=this._ticker)||i.start())}get autoUpdate(){return this._autoUpdate}set autoUpdate(e){var t;this.destroyed||(e?this._ticker?(this._ticker.add(xe,this),this._autoUpdate=!0):m.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==(t=this._ticker)||t.remove(xe,this),this._autoUpdate=!1))}get autoHitTest(){return this._autoHitTest}set autoHitTest(e){e!==this.autoHitTest&&(e?this.model.on("pointertap",ye,this):this.model.off("pointertap",ye,this),this._autoHitTest=e)}get autoFocus(){return this._autoFocus}set autoFocus(e){e!==this.autoFocus&&(e?(this.model.on("globalpointermove",Me,this),this.model.on("pointermove",Me,this)):(this.model.off("globalpointermove",Me,this),this.model.off("pointermove",Me,this)),this._autoFocus=e)}get autoInteract(){return this._autoHitTest&&this._autoFocus}set autoInteract(e){this.autoHitTest=e,this.autoFocus=e}onTickerUpdate(){const e=this.ticker.deltaMS;this.model.update(e)}onTap(e){this.model.tap(e.global.x,e.global.y)}onPointerMove(e){this.model.focus(e.global.x,e.global.y)}destroy(){this.autoFocus=!1,this.autoHitTest=!1,this.autoUpdate=!1,this.ticker=void 0,this.destroyed=!0}};c(me,"defaultTicker");let fe=me;function xe(){this.onTickerUpdate()}function ye(e){this.onTap(e)}function Me(e){this.onPointerMove(e)}class ve extends t.Transform{}const be=new t.Point,we=new t.Matrix,Pe=new t.Matrix,Ee={x:0,y:0,width:0,height:0},Le=new t.Bounds;let De=!1,Ie=!1;class Fe{constructor(e){this.renderer=e}addPrepare(e,t){var i,s;null==(s=null==(i=this.renderer.renderPipes.batch)?void 0:i.break)||s.call(i,t),t.add({renderPipeId:"live2d",action:"prepare",canBundle:!1,prepare:e})}addRenderable(e,t){var i,s;null==(s=null==(i=this.renderer.renderPipes.batch)?void 0:i.break)||s.call(i,t),t.add(e)}execute(e){if(!(e instanceof _e))return void e.prepare();const t=e;!t.visible||t.alpha<=0||t.renderLive2D(this.renderer)}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}destroy(){}}c(Fe,"extension",{type:[t.ExtensionType.WebGLPipes,t.ExtensionType.WebGPUPipes],name:"live2d"});const Te=Fe;function Se(e){return Math.max(Math.hypot(e.a,e.b),Math.hypot(e.c,e.d))}class _e extends t.Container{constructor(e){var i;super(),c(this,"renderPipeId","live2d"),c(this,"tag","Live2DModel(uninitialized)"),c(this,"internalModel"),c(this,"textures",[]),c(this,"textureOptions"),c(this,"anchorMode"),c(this,"textureLODStates",[]),c(this,"textureLODFailures",[]),c(this,"textureLODSubmissions",new Set),c(this,"transform",new ve),c(this,"anchor"),c(this,"_bounds",new t.Bounds),c(this,"_boundsDirty",!0),c(this,"_boundsRetryAfterDraw",!1),c(this,"gl",null),c(this,"textureUploadPending",!1),c(this,"elapsedTime",0),c(this,"deltaTime",0),c(this,"automator"),c(this,"currentGlId",0),c(this,"renderLive2D",e=>{var i,s,r,n,o;if(e instanceof t.WebGPURenderer)return Ie||(Ie=!0,console.warn("[untitled-pixi-live2d-engine] WebGPU rendering is experimental and may change in minor releases.")),void this.renderWebGPU(e);if(!(e instanceof t.WebGLRenderer))throw new Error("Renderer is not supported");e.geometry.resetState(),e.shader.resetState(),e.texture.resetState(),this.ensureWebGLContext(e);const a=this.textureUploadPending;this.textureUploadPending=!1;const{projectionMatrix:l,offset:h,worldTransformMatrix:d}=e.globalUniforms.globalUniformData,u=Pe.copyFrom(d).append(this.groupTransform),c=Se(u)*e.resolution;for(let t=0;t<this.textures.length;t++){const i=this.textures[t];let s=this.resolveTextureForRender(t,i,c);try{this.uploadTextureForRender(e,s,a)}catch(v){if(s===i)throw new Error("Failed to upload Live2D texture.");const r=this.textureLODStates[t];(null==r?void 0:r.texture)===s&&(this.markTextureLODFailure(t,i,r.level),this.destroyTextureLODState(t)),s=i,this.uploadTextureForRender(e,s,a)}this.internalModel.bindTexture(t,e.texture.getGlSource(s.source).texture)}const p=e.renderTarget.viewport,g=e.renderTarget.renderTarget;let m=p.y;if(null==g?void 0:g.isRoot){m=g.colorTexture.source.pixelHeight-p.height-p.y}this.internalModel.viewport=[p.x,m,p.width,p.height];const f=this.deltaTime;this.deltaTime=0,f&&this.internalModel.update(f,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 x=we.copyFrom(l).append(u);this.internalModel.updateTransform(x),this.internalModel.draw(e.gl),this._boundsRetryAfterDraw&&this.updateDrawableBounds(!0),e.state.resetState(),e.texture.resetState();const y=null==(r=e.renderTarget)?void 0:r.defaultClearColor,M=null==(o=null==(n=e.renderTarget)?void 0:n.adaptor)?void 0:o._clearColorCache;y&&(e.gl.clearColor(y[0],y[1],y[2],y[3]),M&&(M[0]=y[0],M[1]=y[1],M[2]=y[2],M[3]=y[3]))}),this.textureOptions=null==e?void 0:e.textureOptions,this.anchorMode=null!=(i=null==e?void 0:e.anchorMode)?i:"canvas",this.anchor=new t.ObservablePoint({_onUpdate:()=>this.onAnchorChange()},0,0),this.automator=new fe(this,e),this.once("modelLoaded",()=>this.initializeOnModelLoad(e))}get isRenderable(){return!0}get canBundle(){return!1}static from(e,t){return p(this,null,function*(){const i=new this(t);return yield ge.setupLive2DModel(i,e,t),i})}static fromSync(e,t){const i=new this(t);return ge.setupLive2DModel(i,e,t).then(()=>{var e;return null==(e=null==t?void 0:t.onLoad)?void 0:e.call(t)}).catch(e=>{var i;return null==(i=null==t?void 0:t.onError)?void 0:i.call(t,e)}),i}static registerTicker(e){fe.defaultTicker=e.shared}get bounds(){return this.internalModel?(this._boundsDirty&&this.updateDrawableBounds(),this._bounds):(this._bounds.set(0,0,0,0),this._bounds)}updateDrawableBounds(e=!1){if(!this.internalModel)return this._bounds.set(0,0,0,0),void(this._boundsDirty=!1);const i=this.internalModel.getDrawableIDs();Le.clear();for(let s=0;s<i.length;s++){const e=i[s],r=this.internalModel.getDrawableIndex(e);if(r<0)continue;const n=this.internalModel.getDrawableBounds(r,Ee);Number.isFinite(n.x)&&Number.isFinite(n.y)&&Number.isFinite(n.width)&&Number.isFinite(n.height)&&Le.addFrame(n.x,n.y,n.x+n.width,n.y+n.height,t.Matrix.IDENTITY)}if(this._bounds.clear(),Le.isValid&&Le.isPositive)this._bounds.addFrame(Le.minX,Le.minY,Le.maxX,Le.maxY,this.internalModel.localTransform),this._boundsRetryAfterDraw=!1;else{const e=this.internalModel.originalWidth||this.internalModel.width,t=this.internalModel.originalHeight||this.internalModel.height;this._bounds.addFrame(0,0,e,t,this.internalModel.localTransform),this._boundsRetryAfterDraw=!0}this._boundsDirty=!1,this._didViewChangeTick++,e&&"drawable"===this.anchorMode&&this.onAnchorChange()}prepareForRender(e){if(!this.internalModel)return;e instanceof t.WebGLRenderer&&this.ensureWebGLContext(e);const i=this.deltaTime;this.deltaTime=0,i&&this.internalModel.update(i,this.elapsedTime),this.updateDrawableBounds()}ensureWebGLContext(e){this.gl!==e.gl&&(this.gl=e.gl,this.internalModel.updateWebGLContext(e.gl,this.generateUID()),this.textureUploadPending=!0)}generateUID(){return++this.currentGlId}collectRenderables(e,t,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(e){const t=e;t.renderPipes.live2d||(De||(De=!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.")),t.renderPipes.live2d=new Fe(e))}(t);const a=t.renderPipes,l=()=>{a.live2d.addRenderable(this,e)},h=()=>{const s=this.children,r=s.length;for(let n=0;n<r;n++)s[n].collectRenderables(e,t,i)},d=this.effects;if(d){d.length&&a.live2d.addPrepare(()=>this.prepareForRender(t),e);for(let t=0;t<d.length;t++){const i=d[t],n=i.filters;if(n)for(const e of n)e&&"number"==typeof e.resolution&&1===e.resolution&&(e.resolution="inherit");null==(r=null==(s=a[i.pipe])?void 0:s.push)||r.call(s,i,this,e)}l(),h();for(let t=d.length-1;t>=0;t--){const i=d[t];null==(o=null==(n=a[i.pipe])?void 0:n.pop)||o.call(n,i,this,e)}}else l(),h()}initializeOnModelLoad(e){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 e=this.bounds;this.pivot.set(e.minX+this.anchor.x*e.width,e.minY+this.anchor.y*e.height)}else this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(e,t,i){return p(this,arguments,function*(e,t,i,{sound:s,volume:r=.5,expression:n,resetExpression:o=!0,onFinish:a,onError:l,loop:h}={}){return void 0===t?this.internalModel.motionManager.startRandomMotion(e,i,{sound:s,volume:r,expression:n,resetExpression:o,onFinish:a,onError:l,loop:h}):this.internalModel.motionManager.startMotion(e,t,i,{sound:s,volume:r,expression:n,resetExpression:o,onFinish:a,onError:l,loop:h})})}motionLastFrame(e,t){return p(this,arguments,function*(e,t,{expression:i}={}){return this.internalModel.motionManager.motionLastFrame(e,t,{expression:i})})}parallelMotion(e){return p(this,null,function*(){this.internalModel.extendParallelMotionManager(e.length);const t=e.map((e,t)=>this.internalModel.parallelMotionManager[t].startMotion(e.group,e.index,e.priority,{ignoreParamIds:e.ignoreParamIds,loop:e.loop})),i=[];for(const e of t)i.push(yield e);return i})}parallelLastFrame(e){return p(this,null,function*(){this.internalModel.extendParallelMotionManager(e.length);const t=e.map((e,t)=>this.internalModel.parallelMotionManager[t].playMotionLastFrame(e.group,e.index)),i=[];for(const e of t)i.push(yield e);return i})}stopMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(e,{volume:t=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:n}={}){return this.internalModel.motionManager.speak(e,{volume:t,expression:i,resetExpression:s,onFinish:r,onError:n})}stopSpeaking(){return this.internalModel.motionManager.stopSpeaking()}expression(e){return this.internalModel.motionManager.expressionManager?void 0===e?this.internalModel.motionManager.expressionManager.setRandomExpression():this.internalModel.motionManager.expressionManager.setExpression(e):Promise.resolve(!1)}focus(e,t,i=!1){be.x=e,be.y=t,this.toModelPosition(be,be,!0);const s=be.x/this.internalModel.originalWidth*2-1,r=be.y/this.internalModel.originalHeight*2-1,n=Math.atan2(r,s);this.internalModel.focusController.focus(Math.cos(n),-Math.sin(n),i)}tap(e,t){const i=this.hitTest(e,t);i.length&&this.emit("hit",i)}hitTest(e,t){return be.x=e,be.y=t,this.toModelPosition(be,be),this.internalModel.hitTest(be.x,be.y)}toModelPosition(e,t=e.clone(),i){return i||this.updateLocalTransform(),this.toLocal(e,void 0,t,i),this.internalModel.localTransform.applyInverse(t,t),t}containsPoint(e){return this.bounds.containsPoint(e.x,e.y)}_calculateBounds(){if(!this.internalModel)return void this.getBounds().set(0,0,0,0);const e=this.bounds;this.getBounds().addFrame(e.minX,e.minY,e.maxX,e.maxY,this.transform.matrix)}update(e){this.deltaTime+=e,this.elapsedTime+=e}resolveTextureForRender(e,i,s){var r;const n=Q(u(d({},this.textureOptions),{effectiveScale:s,textureWidth:i.source.pixelWidth,textureHeight:i.source.pixelHeight}));if(!n)return i;const o=this.textureLODFailures[e];if((null==o?void 0:o.source)===i&&o.levels.has(n.level))return i;const a=this.textureLODStates[e];if((null==a?void 0:a.source)===i&&a.level===n.level&&!a.texture.destroyed)return a.texture;this.destroyTextureLODState(e);const l=function(e,i,s,r,n){var o,a;const l=e.source.resource;if(!function(e){if(!e||"object"!=typeof e)return!1;const{width:t,height:i}=e;return"number"==typeof t&&t>0&&"number"==typeof i&&i>0}(l))return;const h=t.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,e.source.pixelWidth,e.source.pixelHeight,0,0,s,r)}catch(c){return}const u=`${null!=(a=null!=(o=e.label)?o:e.source.label)?a:"Live2DTexture"} LOD ${i}`;return new t.Texture({label:u,source:new t.CanvasSource({resource:h,width:s,height:r,resolution:1,scaleMode:ee(n),autoGenerateMipmaps:!1,label:u})})}(i,n.level,n.width,n.height,null==(r=this.textureOptions)?void 0:r.lodFilter);return l?(this.textureLODStates[e]={source:i,level:n.level,texture:l},l):(this.markTextureLODFailure(e,i,n.level),i)}markTextureLODFailure(e,t,i){let s=this.textureLODFailures[e];(null==s?void 0:s.source)!==t&&(s={source:t,levels:new Set},this.textureLODFailures[e]=s),s.levels.add(i)}destroyTextureLODState(e){const t=this.textureLODStates[e];t&&(this.textureLODStates[e]=void 0,this.textureLODSubmissions.size?Promise.all(this.textureLODSubmissions).then(()=>t.texture.destroy(!0)):t.texture.destroy(!0))}destroyTextureLODStates(){for(let e=0;e<this.textureLODStates.length;e++)this.destroyTextureLODState(e);this.textureLODFailures.length=0}uploadTextureForRender(e,t,i){const s=Boolean(t.source._gpuData[e.uid]);!i&&s||(e.gl.pixelStorei(WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL,this.internalModel.textureFlipY),e.texture.bind(t,0))}renderWebGPU(e){var t,i;const{projectionMatrix:s,offset:r,worldTransformMatrix:n,worldColor:o}=e.globalUniforms.globalUniformData,a=Pe.copyFrom(n).append(this.groupTransform),l=Se(a)*e.resolution,h=this.textures.map((e,t)=>this.resolveTextureForRender(t,e,l));if(h.some((e,t)=>{var i;return(null==(i=this.textureLODStates[t])?void 0:i.texture)===e})){const t=e.encoder.commandFinished;this.textureLODSubmissions.has(t)||(this.textureLODSubmissions.add(t),t.then(()=>this.textureLODSubmissions.delete(t)))}const d=this.deltaTime;this.deltaTime=0,d&&this.internalModel.update(d,this.elapsedTime),a.tx-=null!=(t=null==r?void 0:r.x)?t:0,a.ty-=null!=(i=null==r?void 0:r.y)?i:0,this.internalModel.updateTransform(we.copyFrom(s).append(a));const u=(o>>>24)/255;this.internalModel.drawWebGPU(e,h,this.groupAlpha*u),this._boundsRetryAfterDraw&&this.updateDrawableBounds(!0)}destroy(e){this.emit("destroy"),this.destroyTextureLODStates(),(null==e?void 0:e.texture)&&this.textures.forEach(t=>t.destroy(e.baseTexture)),this.automator.destroy(),this.internalModel.destroy(),super.destroy(e)}}if(!("Live2D"in window))throw new Error("Could not find Cubism 2 runtime. This plugin requires live2d.min.js to be loaded.");const Ae=Live2DMotion.prototype.updateParam;function Oe(e){switch(e){case"add":return{color:{srcFactor:"one",dstFactor:"one",operation:"add"},alpha:{srcFactor:"zero",dstFactor:"one",operation:"add"}};case"multiply":return{color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"zero",dstFactor:"one",operation:"add"}};case"mask":return{color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"},alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"}};default:return{color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}}function Ce(e,t){return Math.max(t,Math.ceil(e/t)*t)}function Re(e){const t=new Uint16Array(Ce(e.byteLength,4)/2);return t.set(e),t}function ke(e,t){return Array.from(e.subarray(0,t)).sort((e,t)=>e-t).join(",")}Live2DMotion.prototype.updateParam=function(e,t){Ae.call(this,e,t),t.isFinished()&&this.onFinishHandler&&(this.onFinishHandler(this),delete this.onFinishHandler)};class Ge{constructor(e,t,i){c(this,"device"),c(this,"model"),c(this,"layout"),c(this,"pipelineLayout"),c(this,"shader"),c(this,"uniform"),c(this,"uniformData"),c(this,"uniformStride"),c(this,"maskSampler"),c(this,"meshes",[]),c(this,"masks",new Map),c(this,"drawableMasks",[]),c(this,"atlases",[]),c(this,"atlasSamplers",[]),c(this,"pipelines",new Map),c(this,"white"),c(this,"whiteView"),c(this,"_destroyed",!1),this.renderer=e,this.meshFrontFace=i;const s=e.gpu.device;this.device=s,this.model=t;this.uniformStride=Ce(128,s.limits.minUniformBufferOffsetAlignment);const r=t.getDrawableCount();this.uniformData=new Float32Array(r*this.uniformStride/4),this.uniform=s.createBuffer({label:"Live2D per-draw uniform slots",size:Math.max(this.uniformStride,this.uniformData.byteLength),usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.layout=s.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform",hasDynamicOffset:!0,minBindingSize:128}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:4,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this.pipelineLayout=s.createPipelineLayout({bindGroupLayouts:[this.layout]}),this.shader=s.createShaderModule({label:"Live2D WGSL",code:"\nstruct Params {\n matrix: mat4x4<f32>,\n multiply: vec4<f32>,\n screen: vec4<f32>,\n options: vec4<f32>,\n tint: vec4<f32>,\n}\n@group(0) @binding(0) var<uniform> params: Params;\n@group(0) @binding(1) var atlasSampler: sampler;\n@group(0) @binding(2) var atlas: texture_2d<f32>;\n@group(0) @binding(3) var maskTexture: texture_2d<f32>;\n@group(0) @binding(4) var maskSampler: sampler;\n\nstruct VertexOut {\n @builtin(position) position: vec4<f32>,\n @location(0) uv: vec2<f32>,\n @location(1) maskUv: vec2<f32>,\n}\n@vertex fn vertexMain(@location(0) position: vec2<f32>, @location(1) uv: vec2<f32>) -> VertexOut {\n var out: VertexOut;\n let clip = params.matrix * vec4<f32>(position, 0.0, 1.0);\n out.position = clip;\n out.uv = vec2<f32>(uv.x, 1.0 - uv.y);\n out.maskUv = vec2<f32>(clip.x * 0.5 + 0.5, 0.5 - clip.y * 0.5);\n return out;\n}\n@fragment fn fragmentMain(in: VertexOut) -> @location(0) vec4<f32> {\n let tex = textureSample(atlas, atlasSampler, in.uv);\n let multiplied = tex.rgb * params.multiply.rgb;\n let screened = multiplied + params.screen.rgb * tex.a - multiplied * params.screen.rgb;\n var color = vec4<f32>(screened, tex.a) * params.tint * params.options.x;\n // Sample unconditionally: derivatives must remain in uniform control flow.\n let inverseCoverage = textureSample(maskTexture, maskSampler, in.maskUv).r;\n if (params.options.y > 1.5) {\n color *= inverseCoverage;\n } else if (params.options.y > 0.5) {\n color *= 1.0 - inverseCoverage;\n }\n return color;\n}\n@fragment fn fragmentMask(in: VertexOut) -> @location(0) vec4<f32> {\n let alpha = textureSample(atlas, atlasSampler, in.uv).a;\n return vec4<f32>(alpha);\n}\n"}),this.maskSampler=s.createSampler({minFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),this.white=this.texture(1,1,"Fallback unmasked texture"),s.queue.writeTexture({texture:this.white},new Uint8Array([255,255,255,255]),{},[1,1]);const n=t.getDrawableMaskCounts(),o=t.getDrawableMasks();for(let a=0;a<r;a++){if(!n[a])continue;const e=ke(o[a],n[a]);let t=this.masks.get(e);if(!t){const i=this.texture(512,512,`Mask ${e}`);t={sources:e.split(",").map(Number),texture:i,view:i.createView()},this.masks.set(e,t)}this.drawableMasks[a]=t}this.whiteView=this.white.createView();for(let a=0;a<r;a++)this.meshes.push({positions:this.buffer(t.getDrawableVertices(a),GPUBufferUsage.VERTEX,"Dynamic positions"),uvs:this.buffer(t.getDrawableVertexUvs(a),GPUBufferUsage.VERTEX,"Static UVs"),indices:this.buffer(Re(t.getDrawableVertexIndices(a)),GPUBufferUsage.INDEX,"Static indices"),indexCount:t.getDrawableVertexIndexCount(a)})}get destroyed(){return this._destroyed}texture(e,t,i){return this.device.createTexture({label:i,size:[e,t],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC})}buffer(e,t,i){const s=this.device.createBuffer({label:i,size:Ce(e.byteLength,4),usage:t|GPUBufferUsage.COPY_DST});return e.byteLength&&this.device.queue.writeBuffer(s,0,e.buffer,e.byteOffset,e.byteLength),s}bind(e,t,i){return this.device.createBindGroup({layout:this.layout,entries:[{binding:0,resource:{buffer:this.uniform,size:128}},{binding:1,resource:i},{binding:2,resource:e},{binding:3,resource:t},{binding:4,resource:this.maskSampler}]})}pipeline(e,t,i,s="rgba8unorm",r=1,n,o=GPUColorWrite.ALL){const a=JSON.stringify([e,t,i,s,r,n,o]);let l=this.pipelines.get(a);return l||(l=this.device.createRenderPipeline({label:`Live2D ${a}`,layout:this.pipelineLayout,vertex:{module:this.shader,entryPoint:"vertexMain",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:8,attributes:[{shaderLocation:1,offset:0,format:"float32x2"}]}]},fragment:{module:this.shader,entryPoint:"mask"===e?"fragmentMask":"fragmentMain",targets:[{format:s,blend:Oe(e),writeMask:o}]},depthStencil:n,multisample:{count:r},primitive:{topology:"triangle-list",cullMode:t?"back":"none",frontFace:i?"cw":"ccw"}}),this.pipelines.set(a,l)),l}render(e,t,i,s={r:1,g:1,b:1,a:1}){var r,n;if(this.destroyed)throw new Error("Live2D WebGPU renderer has been destroyed.");const{renderer:o}=this,a=new Float32Array([e.a,e.b,0,0,e.c,e.d,0,0,0,0,1,0,e.tx,e.ty,0,1]),l=t.map(e=>o.texture.getGpuSource(e.source)),h=t.map(e=>o.texture.getGpuSampler(e.source.style));if(l.some((e,t)=>e!==this.atlases[t])||h.some((e,t)=>e!==this.atlasSamplers[t])){this.atlases=l,this.atlasSamplers=h;const e=l.map(e=>e.createView());for(let t=0;t<this.meshes.length;t++){const i=this.model.getDrawableTextureIndex(t),s=e[i],o=h[i];if(!s)throw new Error(`Drawable ${t} references a missing texture.`);this.meshes[t].mainBinding=this.bind(s,null!=(n=null==(r=this.drawableMasks[t])?void 0:r.view)?n:this.whiteView,o),this.meshes[t].maskBinding=this.bind(s,this.whiteView,o)}}const c=o.renderTarget.renderTarget,p=o.renderTarget.getGpuRenderTarget(c);if(1!==c.colorTextures.length)throw new Error("Live2D WebGPU requires one color attachment.");const g=p.contexts[0]?p.contexts[0].getCurrentTexture().format:o.texture.getGpuSource(c.colorTexture).format,m=o.pipeline,f=c.depthStencilTexture?u(d({},m._stencilState),{format:"depth24plus-stencil8",depthWriteEnabled:!1,depthCompare:"always"}):void 0,x=()=>{o.renderTarget.adaptor.startRenderPass(c,!1,void 0,o.renderTarget.viewport),o.renderTarget.onRenderTargetChange.emit(c)};o.encoder.endRenderPass();const y=o.encoder.commandEncoder,{model:M}=this;for(let d=0;d<this.meshes.length;d++){const e=d*this.uniformStride/4;this.uniformData.set(a,e),this.uniformData.set([s.r,s.g,s.b,1],e+28);const t=M.getMultiplyColor(d),r=M.getScreenColor(d);this.uniformData.set([t.r,t.g,t.b,t.a],e+16),this.uniformData.set([r.r,r.g,r.b,r.a],e+20),this.uniformData.set([M.getDrawableOpacity(d)*i*s.a,this.drawableMasks[d]?M.getDrawableInvertedMaskBit(d)?2:1:0,0,0],e+24)}this.upload(y);const v=a[0]*a[5]-a[1]*a[4]<0,b=(e,t,i)=>{var s;const r=this.meshes[t];if(!r.indexCount)return;const n=i?"mask":null!=(s=["normal","add","multiply"][M.getDrawableBlendMode(t)])?s:"normal";e.setPipeline(this.pipeline(n,M.getDrawableCulling(t),i||!this.meshFrontFace?v:"cw"===this.meshFrontFace,i?"rgba8unorm":g,i?1:p.msaaSamples,i?void 0:f,i?GPUColorWrite.ALL:m._colorMask)),e.setBindGroup(0,i?r.maskBinding:r.mainBinding,[t*this.uniformStride]),e.setVertexBuffer(0,r.positions),e.setVertexBuffer(1,r.uvs),e.setIndexBuffer(r.indices,"uint16"),e.drawIndexed(r.indexCount)};try{for(const s of this.masks.values()){const e=y.beginRenderPass({label:"Live2D mask",colorAttachments:[{view:s.view,clearValue:{r:1,g:1,b:1,a:1},loadOp:"clear",storeOp:"store"}]});for(const t of s.sources)b(e,t,!0);e.end()}x();const e=o.encoder.renderPassEncoder,t=M.getDrawableRenderOrders(),i=this.meshes.map((e,t)=>t).sort((e,i)=>t[e]-t[i]);for(const s of i)M.getDrawableDynamicFlagIsVisible(s)&&M.getDrawableOpacity(s)>0&&b(e,s,!1)}finally{x()}}upload(e){const t=[{buffer:this.uniform,data:this.uniformData},...this.meshes.map((e,t)=>({buffer:e.positions,data:this.model.getDrawableVertices(t)}))].filter(({data:e})=>e.byteLength>0),i=t.reduce((e,{data:t})=>e+t.byteLength,0);if(!i)return;const s=this.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_SRC,mappedAtCreation:!0}),r=new Uint8Array(s.getMappedRange());let n=0;for(const{data:o}of t)r.set(new Uint8Array(o.buffer,o.byteOffset,o.byteLength),n),n+=o.byteLength;s.unmap(),n=0;for(const{buffer:o,data:a}of t)e.copyBufferToBuffer(s,n,o,0,a.byteLength),n+=a.byteLength;this.renderer.encoder.commandFinished.then(()=>s.destroy())}destroy(){if(!this.destroyed){this._destroyed=!0;for(const e of this.meshes)e.positions.destroy(),e.uvs.destroy(),e.indices.destroy();for(const e of this.masks.values())e.texture.destroy();this.uniform.destroy(),this.white.destroy(),this.pipelines.clear()}}}function Ue(e){const t=e.getModelContext();if(!Array.isArray(t._$aS)||"function"!=typeof t.draw||"function"!=typeof t._$C2)throw new Error("Unsupported Cubism 2 Core: drawable access is unavailable.");return t}class Ne{constructor(e){c(this,"context"),c(this,"vertices"),c(this,"uvs"),c(this,"indices"),c(this,"textures"),c(this,"masks"),c(this,"maskCounts"),c(this,"orders"),c(this,"opacities"),c(this,"blends"),c(this,"cullings"),c(this,"visible"),c(this,"contexts",new Map),c(this,"white",{r:1,g:1,b:1,a:1}),c(this,"black",{r:0,g:0,b:0,a:0}),c(this,"currentCulling",!1),c(this,"drawOrder",0),c(this,"disableCulling",!1),c(this,"sink",{_$ZT:()=>{},setClipBufPre_clipContextForDraw:()=>{},_$WP:e=>{this.currentCulling=e},_$Uo:(e,t,i,s,r,n,o,a)=>{const l=this.contexts.get(a);if(void 0===l)throw new Error("Unknown Cubism 2 draw context.");this.orders[l]=this.drawOrder++,this.opacities[l]=n,this.blends[l]=o,this.cullings[l]=this.currentCulling&&!this.disableCulling,this.visible[l]=n>=.01}}),this.model=e,this.context=Ue(e);const t=this.context._$aS;this.vertices=t.map((t,i)=>new Float32Array(e.getTransformedPoints(i).length)),this.uvs=t.map(e=>e._$ZL()),this.indices=t.map(e=>Uint16Array.from(e.getIndexArray())),this.textures=t.map(e=>e.getTextureNo()<0?1:e.getTextureNo()),this.masks=t.map((e,t)=>{var i,s;return new Int32Array(null!=(s=null==(i=this.context._$C2(t).clipBufPre_clipContext)?void 0:i.clippingMaskDrawIndexList)?s:[])}),this.maskCounts=new Int32Array(this.masks.map(e=>e.length)),this.orders=new Int32Array(t.length),this.opacities=new Float32Array(t.length),this.blends=new Uint8Array(t.length),this.cullings=t.map(e=>e.culling),this.visible=t.map(()=>!1),t.forEach((e,t)=>this.contexts.set(this.context._$C2(t),t))}refresh(e=!1){this.disableCulling=e,this.drawOrder=0,this.visible.fill(!1),this.opacities.fill(0);for(let t=0;t<this.vertices.length;t++){this.cullings[t]=this.context._$aS[t].culling&&!e;const i=this.vertices[t];this.context._$C2(t)._$IS[0]?i.fill(0):i.set(this.model.getTransformedPoints(t))}this.context.draw(this.sink)}getDrawableCount(){return this.vertices.length}getDrawableMaskCounts(){return this.maskCounts}getDrawableMasks(){return this.masks}getDrawableTextureIndex(e){return this.textures[e]}getDrawableVertices(e){return this.vertices[e]}getDrawableVertexUvs(e){return this.uvs[e]}getDrawableVertexIndices(e){return this.indices[e]}getDrawableVertexIndexCount(e){return this.indices[e].length}getDrawableRenderOrders(){return this.orders}getDrawableOpacity(e){return this.opacities[e]}getDrawableCulling(e){return this.cullings[e]}getDrawableBlendMode(e){return this.blends[e]}getDrawableDynamicFlagIsVisible(e){return this.visible[e]}getDrawableInvertedMaskBit(){return!1}getMultiplyColor(){return this.white}getScreenColor(){return this.black}}class Be extends AMotion{constructor(e){super(),c(this,"params",[]),this.setFadeIn(e.fade_in>0?e.fade_in:g.expressionFadingDuration),this.setFadeOut(e.fade_out>0?e.fade_out:g.expressionFadingDuration),Array.isArray(e.params)&&e.params.forEach(e=>{const t=e.calc||"add";if("add"===t){const t=e.def||0;e.val-=t}else if("mult"===t){const t=e.def||1;e.val/=t}this.params.push({calc:t,val:e.val,id:e.id})})}updateParamExe(e,t,i,s){this.params.forEach(t=>{e.setParamFloat(t.id,t.val*i)})}}class je extends E{constructor(e,t){var i;super(e,t),c(this,"queueManager",new MotionQueueManager),c(this,"definitions"),this.definitions=null!=(i=this.settings.expressions)?i:[],this.init()}isFinished(){return this.queueManager.isFinished()}getExpressionIndex(e){return this.definitions.findIndex(t=>t.name===e)}getExpressionFile(e){return e.file}createExpression(e,t){return new Be(e)}_setExpression(e){return this.queueManager.startMotion(e)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(e,t){return this.queueManager.updateParam(e)}}function He(e,t,i){const s=i.getDurationMSec(),r=e.startMotion(i,!0),n=e.motions.find(e=>!!e&&e._$sr===r);return!!n&&(i.updateParamExe(t.coreModel,s,1,n),!0)}class We extends H{constructor(e){super(e),c(this,"definitions"),c(this,"groups",{idle:"idle"}),c(this,"motionDataType","arraybuffer"),c(this,"queueManager",new MotionQueueManager),c(this,"lipSyncIds"),c(this,"expressionManager"),this.definitions=this.settings.motions,this.init(e.options),this.lipSyncIds=["PARAM_MOUTH_OPEN_Y"]}init(e){super.init(e),this.settings.expressions&&(this.expressionManager=new je(this.settings,e))}isFinished(){return this.queueManager.isFinished()}createMotion(e,t,i){const s=Live2DMotion.loadMotion(e),r=t===this.groups.idle?g.idleMotionFadingDuration:g.motionFadingDuration;return s.setFadeIn(i.fade_in>0?i.fade_in:r),s.setFadeOut(i.fade_out>0?i.fade_out:r),s}getMotionFile(e){return e.file}getMotionName(e){return e.file}getSoundFile(e){return e.sound}_startMotion(e,t,i,s){return e.onFinishHandler=t,i&&i.length>0&&(e.motions=e.motions.filter(e=>!i.includes(e._$4P))),this.queueManager.stopAllMotions(),this.queueManager.startMotion(e)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(e,t){return this.queueManager.updateParam(e)}destroy(){super.destroy(),this.queueManager=void 0}motionLastFrame(e,t){return p(this,arguments,function*(e,t,{expression:i}={}){const s=yield this.getMotionAndApplyExpression(e,t,i);return!!s&&(this.playing=!0,He(this.queueManager,this.parent,s),this.playing=!1,!0)})}}class Ve extends t.EventEmitter{constructor(e){super(),c(this,"tag"),c(this,"manager"),c(this,"settings"),c(this,"state",new S),c(this,"playing",!1),c(this,"destroyed",!1),c(this,"parent"),this.settings=e.settings,this.tag=`ParallelMotionManager(${this.settings.name})`,this.state.tag=this.tag,this.manager=e.motionManager,this.parent=e}startMotion(e,t){return p(this,arguments,function*(e,t,i=T.NORMAL,s={}){var r;const{ignoreParamIds:n=[],loop:o}=Array.isArray(s)?{ignoreParamIds:s,loop:void 0}:s;if(!this.state.reserve(e,t,i))return!1;const a=null==(r=this.manager.definitions[e])?void 0:r[t];if(!a)return!1;const l=yield this.manager.loadMotion(e,t);return!!this.state.start(l,e,t,i)&&(m.log(this.tag,"Start motion:",this.getMotionName(a)),this.emit("motionStart",e,t,void 0),this.playing=!0,this._startMotion(l,void 0,n,o),!0)})}startRandomMotion(e,t){return p(this,arguments,function*(e,t,{loop:i}={}){var s;const r=this.manager.definitions[e];if(null==r?void 0:r.length){const n=[],o=null!=(s=this.manager.motionGroups[e])?s:[];for(let t=0;t<r.length;t++)null===o[t]||this.state.isActive(e,t)||n.push(t);if(n.length){const s=n[Math.floor(Math.random()*n.length)];return this.startMotion(e,s,t,{loop:i})}}return!1})}stopAllMotions(){this._stopAllMotions(),this.state.reset()}update(e,t){return this.isFinished()&&(this.playing&&(this.playing=!1,this.emit("motionFinish")),this.state.complete()),this.updateParameters(e,t)}destroy(){this.destroyed=!0,this.emit("destroy"),this.stopAllMotions()}}class $e extends Ve{constructor(e){super(e),c(this,"queueManager",new MotionQueueManager)}isFinished(){return this.queueManager.isFinished()}getMotionName(e){return e.file}_startMotion(e,t,i,s){return e.onFinishHandler=t,i&&i.length>0&&(e.motions=e.motions.filter(e=>!i.includes(e._$4P))),this.queueManager.stopAllMotions(),this.queueManager.startMotion(e)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(e,t){return this.queueManager.updateParam(e)}destroy(){super.destroy(),this.queueManager=void 0}playMotionLastFrame(e,t){return p(this,null,function*(){var i;if(!this.state.reserve(e,t,T.FORCE))return!1;const s=null==(i=this.manager.definitions[e])?void 0:i[t];if(!s)return!1;const r=yield this.manager.loadMotion(e,t);return!!this.state.start(r,e,t,T.FORCE)&&(m.log(this.tag,"Start motion:",this.getMotionName(s)),this.queueManager.stopAllMotions(),this.emit("motionStart",e,t,void 0),this.playing=!0,!!He(this.queueManager,this.parent,r)&&(this.playing=!1,!0))})}}class Xe{constructor(e){c(this,"leftParam"),c(this,"rightParam"),c(this,"blinkInterval",4e3),c(this,"closingDuration",100),c(this,"closedDuration",50),c(this,"openingDuration",150),c(this,"eyeState",0),c(this,"eyeParamValue",1),c(this,"closedTimer",0),c(this,"nextBlinkTimeLeft",this.blinkInterval),this.coreModel=e,this.leftParam=e.getParamIndex("PARAM_EYE_L_OPEN"),this.rightParam=e.getParamIndex("PARAM_EYE_R_OPEN")}setEyeParams(e){this.eyeParamValue=f(e,0,1),this.coreModel.setParamFloat(this.leftParam,this.eyeParamValue),this.coreModel.setParamFloat(this.rightParam,this.eyeParamValue)}update(e){switch(this.eyeState){case 0:this.nextBlinkTimeLeft-=e,this.nextBlinkTimeLeft<0&&(this.eyeState=1,this.nextBlinkTimeLeft=this.blinkInterval+this.closingDuration+this.closedDuration+this.openingDuration+x(0,2e3));break;case 1:this.setEyeParams(this.eyeParamValue+e/this.closingDuration),this.eyeParamValue<=0&&(this.eyeState=2,this.closedTimer=0);break;case 2:this.closedTimer+=e,this.closedTimer>=this.closedDuration&&(this.eyeState=3);break;case 3:this.setEyeParams(this.eyeParamValue+e/this.openingDuration),this.eyeParamValue>=1&&(this.eyeState=0)}}}const Ye=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class ze extends ${constructor(e,t,i){super(),c(this,"settings"),c(this,"options"),c(this,"coreModel"),c(this,"motionManager"),c(this,"parallelMotionManager"),c(this,"eyeBlink"),c(this,"eyeballXParamIndex"),c(this,"eyeballYParamIndex"),c(this,"angleXParamIndex"),c(this,"angleYParamIndex"),c(this,"angleZParamIndex"),c(this,"bodyAngleXParamIndex"),c(this,"breathParamIndex"),c(this,"textureFlipY",!0),c(this,"lipSync",!0),c(this,"drawDataCount",0),c(this,"disableCulling",!1),c(this,"hasDrawn",!1),c(this,"gpuData"),c(this,"gpuRenderers",new Map),c(this,"customHitAreas"),this.coreModel=e,this.settings=t,this.options=Object.assign({},{breathDepth:1,lipSyncGain:1.5,lipSyncWeight:.4},i),void 0!==(null==i?void 0:i.useHighPrecisionMask)&&!1!==i.useHighPrecisionMask&&m.warn("CubismLegacyInternalModel","`useHighPrecisionMask` is only supported by Cubism 3/4/5 models and will be ignored for Cubism 2 models."),this.motionManager=new We(this),this.parallelMotionManager=[],!1!==this.options.eyeBlink&&(this.eyeBlink=new Xe(e)),this.eyeballXParamIndex=e.getParamIndex("PARAM_EYE_BALL_X"),this.eyeballYParamIndex=e.getParamIndex("PARAM_EYE_BALL_Y"),this.angleXParamIndex=e.getParamIndex("PARAM_ANGLE_X"),this.angleYParamIndex=e.getParamIndex("PARAM_ANGLE_Y"),this.angleZParamIndex=e.getParamIndex("PARAM_ANGLE_Z"),this.bodyAngleXParamIndex=e.getParamIndex("PARAM_BODY_ANGLE_X"),this.breathParamIndex=e.getParamIndex("PARAM_BREATH"),this.init()}init(){super.init(),this.settings.initParams&&this.settings.initParams.forEach(({id:e,value:t})=>this.coreModel.setParamFloat(e,t)),this.settings.initOpacities&&this.settings.initOpacities.forEach(({id:e,value:t})=>this.coreModel.setPartsOpacity(e,t)),this.coreModel.saveParam();const e=this.coreModel.getModelContext()._$aS;(null==e?void 0:e.length)&&(this.drawDataCount=e.length);let t=this.coreModel.drawParamWebGL.culling;Object.defineProperty(this.coreModel.drawParamWebGL,"culling",{set:e=>t=e,get:()=>!this.disableCulling&&t});const i=this.coreModel.getModelContext().clipManager,s=i.setupClip.bind(i);i.setupClip=(e,t)=>{s.call(i,e,t),t.gl.viewport(...this.viewport)}}getSize(){return[this.coreModel.getCanvasWidth(),this.coreModel.getCanvasHeight()]}getLayout(){const e={};if(this.settings.layout)for(const[t,i]of Object.entries(this.settings.layout)){let s=t;"center_x"===t?s="centerX":"center_y"===t&&(s="centerY"),"number"==typeof i&&(e[s]=i)}return e}updateWebGLContext(e,t){const i=this.coreModel.drawParamWebGL;i.firstDraw=!0,i.setGL(e),i.glno=t,i._$NT=null,i._$no=null,i._$vS=null;const s=this.coreModel.getModelContext().clipManager;s.curFrameNo=t;const r=e.getParameter(e.FRAMEBUFFER_BINDING);s.getMaskRenderTexture(),e.bindFramebuffer(e.FRAMEBUFFER,r)}bindTexture(e,t){this.coreModel.setTexture(e,t)}getHitAreaDefs(){var e,t,i;const s=this.settings.json;return W(null!=(i=null!=(t=null!=(e=this.settings.hitAreas)?e:s.hit_areas)?t:s.HitAreas)?i:s.hitAreas,e=>this.coreModel.getDrawDataIndex(e))}getDrawableIDs(){const e=this.coreModel.getModelContext(),t=[];for(let i=0;i<this.drawDataCount;i++){const s=e.getDrawData(i);s&&t.push(s.getDrawDataID().id)}return t}getDrawableIndex(e){return this.coreModel.getDrawDataIndex(e)}getDrawableVertices(e){if("string"==typeof e&&-1===(e=this.coreModel.getDrawDataIndex(e)))throw new TypeError("Unable to find drawable ID: "+e);return this.coreModel.getTransformedPoints(e).slice()}hitTest(e,t){this.hasDrawn||m.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(e,t),s=this.hitTestCustom(e,t);return s.length?i.length?[...new Set([...i,...s])]:s:i}update(e,t){var i,s,r,n;super.update(e,t);const o=this.coreModel,a=this.updateMotions(o,t);if(o.saveParam(),null==(i=this.motionManager.expressionManager)||i.update(o,t),a||null==(s=this.eyeBlink)||s.update(e),this.updateFocus(),this.updateNaturalMovements(e,t),this.lipSync&&this.motionManager.currentAudio){let e=this.motionManager.mouthSync()*this.options.lipSyncGain;const t=1,i=e>0?.1:0;e=Math.pow(e,1.15),e=f(e,i,t);for(let s=0;s<this.motionManager.lipSyncIds.length;++s)this.coreModel.addToParamFloat(this.coreModel.getParamIndex(this.motionManager.lipSyncIds[s]),e,this.options.lipSyncWeight)}null==(r=this.physics)||r.update(t),null==(n=this.pose)||n.update(e),this.emit("beforeModelUpdate"),Ue(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(e,t){const i=t/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(e){const t=this.disableCulling;e.getParameter(e.FRAMEBUFFER_BINDING)&&(this.disableCulling=!0);const i=this.drawingMatrix;Ye[0]=i.a,Ye[1]=i.b,Ye[4]=i.c,Ye[5]=i.d,Ye[12]=i.tx,Ye[13]=i.ty,this.coreModel.setMatrix(Ye);try{Ue(this.coreModel).preDraw(this.coreModel.drawParamWebGL),this.coreModel.draw(),this.hasDrawn=!0}finally{this.disableCulling=t}}drawWebGPU(e,t,i){null!=this.gpuData||(this.gpuData=new Ne(this.coreModel));const s=e.renderTarget.getGpuRenderTarget(e.renderTarget.renderTarget);this.gpuData.refresh(this.disableCulling||!s.contexts[0]);let r=this.gpuRenderers.get(e);(null==r?void 0:r.device)!==e.gpu.device&&(r&&(e.runners.destroy.remove(r),r.destroy()),r=new Ge(e,this.gpuData,"cw"),this.gpuRenderers.set(e,r),e.runners.destroy.add(r)),r.render(this.drawingMatrix,t,i),this.hasDrawn=!0}extendParallelMotionManager(e){for(;this.parallelMotionManager.length<e;)this.parallelMotionManager.push(new $e(this))}destroy(){for(const[e,t]of this.gpuRenderers)t.destroyed||e.runners.destroy.remove(t),t.destroy();this.gpuRenderers.clear(),this.gpuData=void 0,super.destroy(),this.coreModel=void 0}hitTestCustom(e,t){const i=this.getCustomHitAreas();if(!i)return[];const s=this.originalWidth||this.width,r=this.originalHeight||this.height;if(!s||!r)return[];const n=e/s*2-1,o=1-t/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 e,t,i,s,r;if(void 0!==this.customHitAreas)return this.customHitAreas;const n=this.settings.json,o=null!=(i=null!=(t=null!=(e=n.hit_areas_custom)?e:n.hitAreasCustom)?t:n.HitAreasCustom)?i:n.HitAreas_Custom;if(!o||"object"!=typeof o)return this.customHitAreas=null,null;const a=o,l={},h=(e,t,i)=>{if(!e||!Array.isArray(t)||!Array.isArray(i))return;if(t.length<2||i.length<2)return;const s=Number(t[0]),r=Number(t[1]),n=Number(i[0]),o=Number(i[1]);Number.isFinite(s)&&Number.isFinite(r)&&Number.isFinite(n)&&Number.isFinite(o)&&(l[e]={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 e=d.slice(0,-2);h(e,u,a[`${e}_y`]);continue}if(!d.endsWith("_y")&&(u&&"object"==typeof u)){const e=u;h(d,null!=(s=e.x)?s:e.X,null!=(r=e.y)?r:e.Y)}}return this.customHitAreas=Object.keys(l).length?l:null,this.customHitAreas}}const qe={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE},Je={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE};class Ze{constructor(e,t){c(this,"physicsHairs",[]),this.coreModel=e,t.physics_hair&&(this.physicsHairs=t.physics_hair.map(e=>{const t=new PhysicsHair;return t.setup(e.setup.length,e.setup.regist,e.setup.mass),e.src.forEach(({id:e,ptype:i,scale:s,weight:r})=>{const n=qe[i];n&&t.addSrcParam(n,e,s,r)}),e.targets.forEach(({id:e,ptype:i,scale:s,weight:r})=>{const n=Je[i];n&&t.addTargetParam(n,e,s,r)}),t}))}update(e){this.physicsHairs.forEach(t=>t.update(this.coreModel,e))}}class Qe{constructor(e){c(this,"paramIndex",-1),c(this,"partsIndex",-1),c(this,"link",[]),this.id=e}initIndex(e){this.paramIndex=e.getParamIndex("VISIBLE:"+this.id),this.partsIndex=e.getPartsDataIndex(PartsDataID.getID(this.id)),e.setParamFloat(this.paramIndex,1)}}class Ke{constructor(e,t){c(this,"opacityAnimDuration",500),c(this,"partsGroups",[]),this.coreModel=e,t.parts_visible&&(this.partsGroups=t.parts_visible.map(({group:e})=>e.map(({id:e,link:t})=>{const i=new Qe(e);return t&&(i.link=t.map(e=>new Qe(e))),i})),this.init())}init(){this.partsGroups.forEach(e=>{e.forEach(e=>{if(e.initIndex(this.coreModel),e.paramIndex>=0){const t=0!==this.coreModel.getParamFloat(e.paramIndex);this.coreModel.setPartsOpacity(e.partsIndex,t?1:0),this.coreModel.setParamFloat(e.paramIndex,t?1:0),e.link.length>0&&e.link.forEach(e=>e.initIndex(this.coreModel))}})})}normalizePartsOpacityGroup(e,t){const i=this.coreModel,s=.5;let r=1,n=e.findIndex(({paramIndex:e,partsIndex:t})=>t>=0&&0!==i.getParamFloat(e));if(n>=0){const s=i.getPartsOpacity(e[n].partsIndex);r=f(s+t/this.opacityAnimDuration,0,1)}else n=0,r=1;e.forEach(({partsIndex:e},t)=>{if(e>=0)if(n==t)i.setPartsOpacity(e,r);else{let t,n=i.getPartsOpacity(e);t=r<s?-.5*r/s+1:(1-r)*s/.5;(1-t)*(1-r)>.15&&(t=1-.15/(1-r)),n>t&&(n=t),i.setPartsOpacity(e,n)}})}copyOpacity(e){const t=this.coreModel;e.forEach(({partsIndex:e,link:i})=>{if(e>=0&&i){const s=t.getPartsOpacity(e);i.forEach(({partsIndex:e})=>{e>=0&&t.setPartsOpacity(e,s)})}})}update(e){this.partsGroups.forEach(t=>{this.normalizePartsOpacityGroup(t,e),this.copyOpacity(t)})}}ge.registerRuntime({version:2,test:e=>e instanceof Z||Z.isValidJSON(e),ready:()=>Promise.resolve(),isValidMoc(e){if(e.byteLength<3)return!1;const t=new Int8Array(e,0,3);return"moc"===String.fromCharCode(...t)},createModelSettings:e=>new Z(e),createCoreModel(e){const t=Live2DModelWebGL.loadModel(e),i=Live2D.getError();if(i){if(i instanceof Error)throw i;const e="string"==typeof i?i:`Live2D error: ${JSON.stringify(i)}`;throw new Error(e)}return t},createInternalModel:(e,t,i)=>new ze(e,t,i),createPose:(e,t)=>new Ke(e,t),createPhysics:(e,t)=>new Ze(e,t)}),e.CubismLegacyExpressionManager=je,e.CubismLegacyInternalModel=ze,e.CubismLegacyModelSettings=Z,e.CubismLegacyMotionManager=We,e.CubismLegacyParallelMotionManager=$e,e.ExpressionManager=E,e.FileLoader=ce,e.FocusController=I,e.InternalModel=$,e.LOGICAL_HEIGHT=2,e.LOGICAL_WIDTH=2,e.Live2DExpression=Be,e.Live2DEyeBlink=Xe,e.Live2DFactory=ge,e.Live2DLoader=J,e.Live2DModel=_e,e.Live2DPhysics=Ze,e.Live2DPlugin=Te,e.Live2DPose=Ke,e.Live2DTransform=ve,e.MBToByte=function(e){return 1024*e*1024},e.ModelSettings=F,e.MotionManager=H,e.MotionPreloadStrategy=j,e.MotionPriority=T,e.MotionState=S,e.SoundManager=B,e.VERSION="1.5.1",e.VOLUME=A,e.XHRLoader=z,e.applyMixins=function(e,t){t.forEach(t=>{Object.getOwnPropertyNames(t.prototype).forEach(i=>{"constructor"!==i&&Object.defineProperty(e.prototype,i,Object.getOwnPropertyDescriptor(t.prototype,i))})})},e.clamp=f,e.config=g,e.copyArray=M,e.copyProperty=y,e.folderName=v,e.logger=m,e.normalizeHitAreaDefs=W,e.rand=x,e.remove=b,e.resolveURL=P,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});