untitled-pixi-live2d-engine 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  ![NPM Version](https://img.shields.io/npm/v/untitled-pixi-live2d-engine?style=flat-square&label=version)
4
4
  ![Cubism version](https://img.shields.io/badge/Cubism-2/3/4/5-ff69b4?style=flat-square)
5
5
 
6
- **English (Current)** | [**简体中文**](README-ZH.md)
6
+ **English (Current)** | [**简体中文**](README-ZH.md) | [**日本語**](README-JA.md)
7
7
 
8
8
  A Live2D rendering and control plugin designed for **[PixiJS v8](https://pixijs.com/)**.
9
9
 
@@ -89,7 +89,7 @@ const config = {
89
89
  preserveExpressionOnMotion: true,
90
90
  cubism: CubismFrameworkConfig
91
91
  };
92
- const VERSION = "1.0.0";
92
+ const VERSION = "1.0.2";
93
93
  const logger = {
94
94
  log(tag, ...messages) {
95
95
  if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
@@ -1956,7 +1956,35 @@ const jsonToSettings = (context, next) => __async(null, null, function* () {
1956
1956
  return next();
1957
1957
  }
1958
1958
  }
1959
- throw new TypeError("Unknown settings format.");
1959
+ const url = context.source && typeof context.source.url === "string" ? context.source.url : void 0;
1960
+ const runtimeVersions = Live2DFactory.runtimes.map((r) => r.version).join(", ");
1961
+ if (Live2DFactory.runtimes.length === 0) {
1962
+ throw new TypeError(
1963
+ [
1964
+ "Unknown settings format: no Live2D runtimes registered.",
1965
+ 'Import a published runtime entry before loading models (e.g. "<package>/cubism" for Cubism 3/4/5, "<package>/cubism-legacy" for Cubism 2).',
1966
+ url ? `Settings URL: ${url}` : void 0
1967
+ ].filter(Boolean).join("\n")
1968
+ );
1969
+ }
1970
+ const topLevelKeys = (() => {
1971
+ try {
1972
+ if (!context.source || typeof context.source !== "object" || Array.isArray(context.source)) {
1973
+ return void 0;
1974
+ }
1975
+ return Object.keys(context.source).slice(0, 30).join(", ");
1976
+ } catch (e) {
1977
+ return void 0;
1978
+ }
1979
+ })();
1980
+ throw new TypeError(
1981
+ [
1982
+ "Unknown settings format: no matching runtime found for the loaded settings JSON.",
1983
+ runtimeVersions ? `Registered runtimes (versions): ${runtimeVersions}` : void 0,
1984
+ topLevelKeys ? `Settings JSON keys: ${topLevelKeys}` : void 0,
1985
+ url ? `Settings URL: ${url}` : void 0
1986
+ ].filter(Boolean).join("\n")
1987
+ );
1960
1988
  });
1961
1989
  const waitUntilReady = (context, next) => {
1962
1990
  if (context.settings) {
@@ -3690,7 +3718,11 @@ class CubismLegacyInternalModel extends InternalModel {
3690
3718
  __publicField(this, "customHitAreas");
3691
3719
  this.coreModel = coreModel;
3692
3720
  this.settings = settings;
3693
- this.options = Object.assign({}, { breathDepth: 1 }, options);
3721
+ this.options = Object.assign(
3722
+ {},
3723
+ { breathDepth: 1, lipSyncGain: 1.5, lipSyncWeight: 0.4 },
3724
+ options
3725
+ );
3694
3726
  this.motionManager = new CubismLegacyMotionManager(this);
3695
3727
  this.parallelMotionManager = [];
3696
3728
  this.eyeBlink = new Live2DEyeBlink(coreModel);
@@ -3824,17 +3856,16 @@ class CubismLegacyInternalModel extends InternalModel {
3824
3856
  this.updateFocus();
3825
3857
  this.updateNaturalMovements(dt, now);
3826
3858
  if (this.lipSync && this.motionManager.currentAudio) {
3827
- const lipSyncGain = 1.5;
3828
- let value = this.motionManager.mouthSync() * lipSyncGain;
3859
+ let value = this.motionManager.mouthSync() * this.options.lipSyncGain;
3829
3860
  const max_ = 1;
3830
- const bias_power = 1.15;
3831
3861
  const min_ = value > 0 ? 0.1 : 0;
3832
- value = Math.pow(value, bias_power);
3862
+ value = Math.pow(value, 1.15);
3833
3863
  value = clamp(value, min_, max_);
3834
3864
  for (let i = 0; i < this.motionManager.lipSyncIds.length; ++i) {
3835
- this.coreModel.setParamFloat(
3865
+ this.coreModel.addToParamFloat(
3836
3866
  this.coreModel.getParamIndex(this.motionManager.lipSyncIds[i]),
3837
- value
3867
+ value,
3868
+ this.options.lipSyncWeight
3838
3869
  );
3839
3870
  }
3840
3871
  }
@@ -91,7 +91,7 @@ var __async = (__this, __arguments, generator) => {
91
91
  preserveExpressionOnMotion: true,
92
92
  cubism: CubismFrameworkConfig
93
93
  };
94
- const VERSION = "1.0.0";
94
+ const VERSION = "1.0.2";
95
95
  const logger = {
96
96
  log(tag, ...messages) {
97
97
  if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
@@ -1958,7 +1958,35 @@ var __async = (__this, __arguments, generator) => {
1958
1958
  return next();
1959
1959
  }
1960
1960
  }
1961
- throw new TypeError("Unknown settings format.");
1961
+ const url = context.source && typeof context.source.url === "string" ? context.source.url : void 0;
1962
+ const runtimeVersions = Live2DFactory.runtimes.map((r) => r.version).join(", ");
1963
+ if (Live2DFactory.runtimes.length === 0) {
1964
+ throw new TypeError(
1965
+ [
1966
+ "Unknown settings format: no Live2D runtimes registered.",
1967
+ 'Import a published runtime entry before loading models (e.g. "<package>/cubism" for Cubism 3/4/5, "<package>/cubism-legacy" for Cubism 2).',
1968
+ url ? `Settings URL: ${url}` : void 0
1969
+ ].filter(Boolean).join("\n")
1970
+ );
1971
+ }
1972
+ const topLevelKeys = (() => {
1973
+ try {
1974
+ if (!context.source || typeof context.source !== "object" || Array.isArray(context.source)) {
1975
+ return void 0;
1976
+ }
1977
+ return Object.keys(context.source).slice(0, 30).join(", ");
1978
+ } catch (e) {
1979
+ return void 0;
1980
+ }
1981
+ })();
1982
+ throw new TypeError(
1983
+ [
1984
+ "Unknown settings format: no matching runtime found for the loaded settings JSON.",
1985
+ runtimeVersions ? `Registered runtimes (versions): ${runtimeVersions}` : void 0,
1986
+ topLevelKeys ? `Settings JSON keys: ${topLevelKeys}` : void 0,
1987
+ url ? `Settings URL: ${url}` : void 0
1988
+ ].filter(Boolean).join("\n")
1989
+ );
1962
1990
  });
1963
1991
  const waitUntilReady = (context, next) => {
1964
1992
  if (context.settings) {
@@ -3692,7 +3720,11 @@ var __async = (__this, __arguments, generator) => {
3692
3720
  __publicField(this, "customHitAreas");
3693
3721
  this.coreModel = coreModel;
3694
3722
  this.settings = settings;
3695
- this.options = Object.assign({}, { breathDepth: 1 }, options);
3723
+ this.options = Object.assign(
3724
+ {},
3725
+ { breathDepth: 1, lipSyncGain: 1.5, lipSyncWeight: 0.4 },
3726
+ options
3727
+ );
3696
3728
  this.motionManager = new CubismLegacyMotionManager(this);
3697
3729
  this.parallelMotionManager = [];
3698
3730
  this.eyeBlink = new Live2DEyeBlink(coreModel);
@@ -3826,17 +3858,16 @@ var __async = (__this, __arguments, generator) => {
3826
3858
  this.updateFocus();
3827
3859
  this.updateNaturalMovements(dt, now);
3828
3860
  if (this.lipSync && this.motionManager.currentAudio) {
3829
- const lipSyncGain = 1.5;
3830
- let value = this.motionManager.mouthSync() * lipSyncGain;
3861
+ let value = this.motionManager.mouthSync() * this.options.lipSyncGain;
3831
3862
  const max_ = 1;
3832
- const bias_power = 1.15;
3833
3863
  const min_ = value > 0 ? 0.1 : 0;
3834
- value = Math.pow(value, bias_power);
3864
+ value = Math.pow(value, 1.15);
3835
3865
  value = clamp(value, min_, max_);
3836
3866
  for (let i = 0; i < this.motionManager.lipSyncIds.length; ++i) {
3837
- this.coreModel.setParamFloat(
3867
+ this.coreModel.addToParamFloat(
3838
3868
  this.coreModel.getParamIndex(this.motionManager.lipSyncIds[i]),
3839
- value
3869
+ value,
3870
+ this.options.lipSyncWeight
3840
3871
  );
3841
3872
  }
3842
3873
  }
@@ -1 +1 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("pixi.js"),require("@pixi/sound")):"function"==typeof define&&define.amd?define(["exports","pixi.js","@pixi/sound"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).PIXI=t.PIXI||{},t.PIXI.live2d=t.PIXI.live2d||{}),t.PIXI,t.PIXI)}(this,function(t,e,i){"use strict";var s=Object.defineProperty,r=Math.pow,n=(t,e,i)=>((t,e,i)=>e in t?s(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i)(t,"symbol"!=typeof e?e+"":e,i),o=(t,e,i)=>new Promise((s,r)=>{var n=t=>{try{a(i.next(t))}catch(e){r(e)}},o=t=>{try{a(i.throw(t))}catch(e){r(e)}},a=t=>t.done?s(t.value):Promise.resolve(t.value).then(n,o);a((i=i.apply(t,e)).next())});const a={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"}))},l={log(t,...e){a.logLevel<=a.LOG_LEVEL_VERBOSE&&console.log(`[${t}]`,...e)},warn(t,...e){a.logLevel<=a.LOG_LEVEL_WARNING&&console.warn(`[${t}]`,...e)},error(t,...e){a.logLevel<=a.LOG_LEVEL_ERROR&&console.error(`[${t}]`,...e)}};function h(t,e,i){return t<e?e:t>i?i:t}function d(t,e){return Math.random()*(e-t)+t}function u(t,e,i,s,r){const n=e[s];null!==n&&typeof n===t&&(i[r]=n)}function c(t,e,i,s,r){const n=e[s];Array.isArray(n)&&(i[r]=n.filter(e=>null!==e&&typeof e===t))}function p(t){let e=t.lastIndexOf("/");return-1!=e&&(t=t.slice(0,e)),e=t.lastIndexOf("/"),-1!==e&&(t=t.slice(e+1)),t}function g(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}const m=/^[a-zA-Z][a-zA-Z0-9+.-]*:/;function f(t,e){if(!e)return t;if(m.test(e))return e;if(e.startsWith("/"))return m.test(t)?new URL(e,t).toString():e;if(m.test(t))return new URL(e,t).toString();const i="http://example.com",s=t.startsWith("/")?i+t:`${i}/${t}`,r=new URL(e,s);let n=r.pathname+r.search+r.hash;return!t.startsWith("/")&&n.startsWith("/")&&(n=n.slice(1)),n}class M extends e.EventEmitter{constructor(t,e){super(),n(this,"expressionDataType","json"),n(this,"tag"),n(this,"settings"),n(this,"expressions",[]),n(this,"defaultExpression"),n(this,"currentExpression"),n(this,"reserveExpressionIndex",-1),n(this,"destroyed",!1),this.settings=t,this.tag=`ExpressionManager(${t.name})`}init(){this.defaultExpression=this.createDefaultExpression(),this.currentExpression=this.defaultExpression,this.stopAllExpressions()}createDefaultExpression(){return this.createExpression({},void 0)}loadExpression(t){return o(this,null,function*(){if(!this.definitions[t])return void l.warn(this.tag,`Undefined expression at [${t}]`);if(null===this.expressions[t])return void l.warn(this.tag,`Cannot set expression at [${t}] because it's already failed in loading.`);if(this.expressions[t])return this.expressions[t];const e=yield this._loadExpression(t);return this.expressions[t]=e,e})}_loadExpression(t){throw new Error("Not implemented.")}setRandomExpression(){return o(this,null,function*(){if(this.definitions.length){const t=[];for(let e=0;e<this.definitions.length;e++)null!==this.expressions[e]&&this.expressions[e]!==this.currentExpression&&e!==this.reserveExpressionIndex&&t.push(e);if(t.length){const e=Math.floor(Math.random()*t.length);return this.setExpression(e)}}return!1})}resetExpression(){this._setExpression(this.defaultExpression)}restoreExpression(){this._setExpression(this.currentExpression)}setExpression(t){return o(this,null,function*(){if("number"!=typeof t&&(t=this.getExpressionIndex(t)),!(t>-1&&t<this.definitions.length))return!1;if(t===this.expressions.indexOf(this.currentExpression))return!1;this.reserveExpressionIndex=t;const e=yield this.loadExpression(t);return!(!e||this.reserveExpressionIndex!==t)&&(this.reserveExpressionIndex=-1,this.currentExpression=e,this._setExpression(e),!0)})}update(t,e){return!this.isFinished()&&this.updateParameters(t,e)}destroy(){this.destroyed=!0,this.emit("destroy");this.definitions=void 0,this.expressions=void 0}}const y=40/7.5,x=1/150;class v{constructor(){n(this,"targetX",0),n(this,"targetY",0),n(this,"x",0),n(this,"y",0),n(this,"vx",0),n(this,"vy",0)}focus(t,e,i=!1){this.targetX=h(t,-1,1),this.targetY=h(e,-1,1),i&&(this.x=this.targetX,this.y=this.targetY)}update(t){const e=this.targetX-this.x,i=this.targetY-this.y;if(Math.abs(e)<.01&&Math.abs(i)<.01)return;const s=Math.sqrt(r(e,2)+r(i,2)),n=y/(1e3/t);let o=n*(e/s)-this.vx,a=n*(i/s)-this.vy;const l=Math.sqrt(r(o,2)+r(a,2)),h=n*x*t;l>h&&(o*=h/l,a*=h/l),this.vx+=o,this.vy+=a;const d=Math.sqrt(r(this.vx,2)+r(this.vy,2)),u=.5*(Math.sqrt(r(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 E{constructor(t){n(this,"json"),n(this,"name"),n(this,"url"),n(this,"pose"),n(this,"physics"),this.json=t,this.url=t.url,this.name=p(this.url)}normalizeName(){this.name&&"name"!==this.name.toLowerCase()||(this.name=p(this.url))}setModelName(...t){for(const e of t){const t="string"==typeof e?e.trim():"";if(t&&"name"!==t.toLowerCase())return void(this.name=t)}this.normalizeName()}getFileStem(t){if(!t)return;const e=t.split(/[/\\]/).filter(Boolean).pop();return null==e?void 0:e.replace(/\.[^.]+$/,"")}resolveURL(t){return f(this.url,t)}replaceFiles(t){this.moc=t(this.moc,"moc"),void 0!==this.pose&&(this.pose=t(this.pose,"pose")),void 0!==this.physics&&(this.physics=t(this.physics,"physics"));for(let e=0;e<this.textures.length;e++)this.textures[e]=t(this.textures[e],`textures[${e}]`)}getDefinedFiles(){const t=[];return this.replaceFiles(e=>(t.push(e),e)),t}validateFiles(t){const e=(e,i)=>{const s=this.resolveURL(e);if(!t.includes(s)){if(i)throw new Error(`File "${e}" is defined in settings, but doesn't exist in given files`);return!1}return!0};[this.moc,...this.textures].forEach(t=>e(t,!0));return this.getDefinedFiles().filter(t=>e(t,!1))}}var P=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(P||{});class b{constructor(){n(this,"tag"),n(this,"debug",!1),n(this,"currentPriority",0),n(this,"reservePriority",0),n(this,"currentGroup"),n(this,"currentIndex"),n(this,"reservedGroup"),n(this,"reservedIndex"),n(this,"reservedIdleGroup"),n(this,"reservedIdleIndex")}reserve(t,e,i){if(i<=0)return l.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(t===this.currentGroup&&e===this.currentIndex)return l.log(this.tag,"Motion is already playing.",this.dump(t,e)),!1;if(t===this.reservedGroup&&e===this.reservedIndex||t===this.reservedIdleGroup&&e===this.reservedIdleIndex)return l.log(this.tag,"Motion is already reserved.",this.dump(t,e)),!1;if(1===i){if(0!==this.currentPriority)return l.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,e)),!1;if(void 0!==this.reservedIdleGroup)return l.log(this.tag,"Cannot start idle motion because another idle motion has reserved.",this.dump(t,e)),!1;this.setReservedIdle(t,e)}else{if(i<3){if(i<=this.currentPriority)return l.log(this.tag,"Cannot start motion because another motion is playing as an equivalent or higher priority.",this.dump(t,e)),!1;if(i<=this.reservePriority)return l.log(this.tag,"Cannot start motion because another motion has reserved as an equivalent or higher priority.",this.dump(t,e)),!1}this.setReserved(t,e,i)}return!0}start(t,e,i,s){if(1===s){if(this.setReservedIdle(void 0,void 0),0!==this.currentPriority)return l.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(e,i)),!1}else{if(e!==this.reservedGroup||i!==this.reservedIndex)return l.log(this.tag,"Cannot start motion because another motion has taken the place.",this.dump(e,i)),!1;this.setReserved(void 0,void 0,0)}return!!t&&(this.setCurrent(e,i,s),!0)}complete(){this.setCurrent(void 0,void 0,0)}setCurrent(t,e,i){this.currentPriority=i,this.currentGroup=t,this.currentIndex=e}setReserved(t,e,i){this.reservePriority=i,this.reservedGroup=t,this.reservedIndex=e}setReservedIdle(t,e){this.reservedIdleGroup=t,this.reservedIdleIndex=e}isActive(t,e){return t===this.currentGroup&&e===this.currentIndex||t===this.reservedGroup&&e===this.reservedIndex||t===this.reservedIdleGroup&&e===this.reservedIdleIndex}reset(){this.setCurrent(void 0,void 0,0),this.setReserved(void 0,void 0,0),this.setReservedIdle(void 0,void 0)}shouldRequestIdleMotion(){return void 0===this.currentGroup&&void 0===this.reservedIdleGroup}shouldOverrideExpression(){return!a.preserveExpressionOnMotion&&this.currentPriority>1}dump(t,e){if(this.debug){return`\n<Requested> group = "${t}", index = ${e}\n`+["currentPriority","reservePriority","currentGroup","currentIndex","reservedGroup","reservedIndex","reservedIdleGroup","reservedIdleIndex"].map(t=>"["+t+"] "+this[t]).join("\n")}return""}}const w="SoundManager",I=.5;i.sound.disableAutoPause=!0;class L{static get volume(){return this._volume}static set volume(t){this._volume=(t>1?1:t<0?0:t)||0,this.audios.forEach(t=>t.volume=this._volume)}static add(t,e){return o(this,null,function*(){try{const e=new Promise((e,s)=>{const r=i.Sound.from({url:t,volume:this._volume,preload:!0,loaded:()=>{r.media instanceof i.webaudio.WebAudioMedia||s(new Error(`Error: ${t} is not WebAudioMedia`)),e(r)}})});return yield e}catch(s){return l.warn(w,`Error occurred on "${t}"`,s),null==e||e(s),null}})}static play(t,e){t.play({singleInstance:!0,complete:()=>{null==e||e(),t.destroy()}})}static addAnalyzer(t,e){const i=t.media,s=e.createBufferSource();s.buffer=i.buffer;const r=e.createAnalyser();return r.fftSize=a.fftSize,r.minDecibels=-90,r.maxDecibels=-10,r.smoothingTimeConstant=.85,s.connect(r),s.start(0),this.analysers.push(r),r}static analyze(t){if(!t)return parseFloat(Math.random().toFixed(1));const e=new Float32Array(t.fftSize);t.getFloatTimeDomainData(e);let i=0;for(let a=0;a<e.length;a++)i+=r(e[a],2);const s=Math.sqrt(i/e.length),n=20*Math.log10(s||r(10,-5)),o=Math.min(Math.max((n-t.minDecibels)/(t.maxDecibels-t.minDecibels),0),1);return parseFloat(o.toFixed(1))}static dispose(t){t.pause(),g(this.audios,t)}static destroy(){for(let t=this.contexts.length-1;t>=0;t--){const e=this.contexts[t];null==e||e.close().catch(t=>{l.warn(w,"Failed to close AudioContext.",t)})}for(let t=this.audios.length-1;t>=0;t--)this.dispose(this.audios[t])}}n(L,"audios",[]),n(L,"analysers",[]),n(L,"contexts",[]),n(L,"_volume",I);var _=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(_||{});class F extends e.EventEmitter{constructor(t){super(),n(this,"tag"),n(this,"settings"),n(this,"motionGroups",{}),n(this,"state",new b),n(this,"currentAudio"),n(this,"currentAnalyzer"),n(this,"currentContext"),n(this,"playing",!1),n(this,"destroyed",!1),n(this,"parent"),this.settings=t.settings,this.tag=`MotionManager(${this.settings.name})`,this.state.tag=this.tag,this.parent=t}init(t){(null==t?void 0:t.idleMotionGroup)&&(this.groups.idle=t.idleMotionGroup),this.setupMotions(t),this.stopAllMotions()}setupMotions(t){if(!this.definitions)return void l.warn(this.tag,"Motion definitions are not initialized.");for(const i of Object.keys(this.definitions))this.motionGroups[i]=[];let e;switch(null==t?void 0:t.motionPreload){case"NONE":return;case"ALL":e=Object.keys(this.definitions);break;default:e=[this.groups.idle]}for(const i of e){const t=this.definitions[i];if(t)for(let e=0;e<t.length;e++)this.loadMotion(i,e)}}loadMotion(t,e){return o(this,null,function*(){var i,s;if(this.destroyed)return;if(!this.getMotionDefinition(t,e))return;const r=null!=(s=(i=this.motionGroups)[t])?s:i[t]=[];if(null===r[e])return void l.warn(this.tag,`Cannot start motion at "${t}"[${e}] because it's already failed in loading.`);if(r[e])return r[e];const n=yield this._loadMotion(t,e);return this.destroyed?void 0:(r[e]=null!=n?n:null,n)})}_loadMotion(t,e){throw new Error("Not implemented.")}initializeAudio(t,e){this.currentAudio=t,L.volume=e,this.currentContext=t.context.audioContext,this.currentAnalyzer=L.addAnalyzer(this.currentAudio,this.currentContext)}speak(t){return o(this,arguments,function*(t,{volume:e=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:n}={}){if(!a.sound)return!1;let o,h;if(this.currentAudio&&this.currentAudio.isPlaying)return!1;const d=t&&t.startsWith("data:");if(t&&!d){const e=document.createElement("a");e.href=t,h=t=e.href}else h="data:audio/";const u=t;if(u)try{o=yield L.add(u,(t,e=this)=>{l.error(this.tag,"Error during audio playback:",t),null==n||n(t),s&&i&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),this.initializeAudio(o,e)}catch(c){return l.warn(this.tag,"Failed to create audio",h,c),!1}if(o){let t=!0;try{a.motionSync&&L.play(o,()=>{null==r||r(),s&&i&&this.expressionManager&&this.expressionManager.resetExpression(),this.currentAudio=void 0})}catch(c){l.warn(this.tag,"Failed to play audio",o.url,c),t=!1}if(!t)return!1}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),i&&this.expressionManager&&(yield this.expressionManager.setExpression(i)),this.playing=!0,!0})}startMotion(t,e){return o(this,arguments,function*(t,e,i=P.NORMAL,{sound:s,volume:r=.5,expression:n,resetExpression:o=!0,onFinish:h,onError:d,ignoreParamIds:u=[]}={}){if(this.destroyed)return!1;if(!this.state.reserve(t,e,i))return!1;if(this.currentAudio&&this.currentAudio.isPlaying&&i!=P.FORCE)return!1;const c=this.getMotionDefinition(t,e);if(!c)return!1;let p,g;this.currentAudio&&L.dispose(this.currentAudio);const m=s&&s.startsWith("data:");if(s&&!m){const t=document.createElement("a");t.href=s,g=s=t.href}else g=this.getSoundFile(c),g&&(g=this.settings.resolveURL(g));const f=g;if(f)try{p=yield L.add(f,(t,e=this)=>{l.error(this.tag,"Error during audio playback:",t),null==d||d(t),o&&n&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),this.initializeAudio(p,r)}catch(y){l.warn(this.tag,"Failed to create audio",g,y)}const M=yield this.loadMotion(t,e);if(p&&a.motionSync)try{L.play(p,(t=this)=>{null==h||h(),o&&n&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0})}catch(y){l.warn(this.tag,"Failed to play audio",p.url,y)}return this.state.start(M,t,e,i)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),l.log(this.tag,"Start motion:",this.getMotionName(c)),this.emit("motionStart",t,e,p),n&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(n)),this.playing=!0,M&&this._startMotion(M,void 0,u),!0):(p&&(L.dispose(p),this.currentAudio=void 0),!1)})}startRandomMotion(t,e){return o(this,arguments,function*(t,e,{sound:i,volume:s=.5,expression:r,resetExpression:n=!0,onFinish:o,onError:a}={}){var l,h;if(this.destroyed)return!1;const d=null==(l=this.definitions)?void 0:l[t];if(null==d?void 0:d.length){const l=[],u=null!=(h=this.motionGroups[t])?h:[];for(let e=0;e<d.length;e++)null===u[e]||this.state.isActive(t,e)||l.push(e);if(l.length){const h=l[Math.floor(Math.random()*l.length)];return this.startMotion(t,h,e,{sound:i,volume:s,expression:r,resetExpression:n,onFinish:o,onError:a})}}return!1})}stopSpeaking(){this.currentAudio&&(L.dispose(this.currentAudio),this.currentAudio=void 0)}stopAllMotions(){this._stopAllMotions(),this.state.reset(),this.stopSpeaking()}update(t,e){var i;return this.isFinished()&&(this.playing&&(this.playing=!1,this.emit("motionFinish")),this.state.shouldOverrideExpression()&&(null==(i=this.expressionManager)||i.restoreExpression()),this.state.complete(),this.state.shouldRequestIdleMotion()&&this.startRandomMotion(this.groups.idle,P.IDLE)),this.updateParameters(t,e)}mouthSync(){return this.currentAnalyzer?L.analyze(this.currentAnalyzer):0}destroy(){var t;this.destroyed=!0,this.emit("destroy"),this.stopAllMotions(),null==(t=this.expressionManager)||t.destroy();this.definitions=void 0,this.motionGroups=void 0}getMotionAndApplyExpression(t,e,i){return o(this,null,function*(){if(this.destroyed)return null;if(!this.state.reserve(t,e,P.FORCE))return null;const s=this.getMotionDefinition(t,e);if(!s)return null;this.currentAudio&&L.dispose(this.currentAudio);const r=yield this.loadMotion(t,e);return this.state.start(r,t,e,P.FORCE)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),l.log(this.tag,"Start motion:",this.getMotionName(s)),this.emit("motionStart",t,e,void 0),i&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(i)),r):null})}getMotionDefinition(t,e){var i,s;const r=null==(s=null==(i=this.definitions)?void 0:i[t])?void 0:s[e];return r||l.warn(this.tag,`Undefined motion at "${t}"[${e}]`),r}}function A(t,e){if(!Array.isArray(t))return[];const i=[];for(const s of t){if(!s||"object"!=typeof s)continue;const t=s,r="string"==typeof t.id?t.id:"string"==typeof t.Id?t.Id:void 0,n="string"==typeof t.name?t.name:"string"==typeof t.Name?t.Name:void 0;r&&n&&i.push({id:r,name:n,index:e(r)})}return i}const O={x:0,y:0,width:0,height:0};class R extends e.EventEmitter{constructor(){super(...arguments),n(this,"focusController",new v),n(this,"pose"),n(this,"physics"),n(this,"originalWidth",0),n(this,"originalHeight",0),n(this,"width",0),n(this,"height",0),n(this,"localTransform",new e.Matrix),n(this,"drawingMatrix",new e.Matrix),n(this,"hitAreas",{}),n(this,"textureFlipY",!1),n(this,"viewport",[0,0,0,0]),n(this,"destroyed",!1)}init(){this.setupLayout(),this.setupHitAreas()}setupLayout(){const t=this,e=this.getSize();t.originalWidth=e[0],t.originalHeight=e[1];const i=Object.assign({width:2,height:2},this.getLayout());this.localTransform.scale(i.width/2,i.height/2),t.width=this.originalWidth*this.localTransform.a,t.height=this.originalHeight*this.localTransform.d;const s=void 0!==i.x&&i.x-i.width/2||void 0!==i.centerX&&i.centerX||void 0!==i.left&&i.left-i.width/2||void 0!==i.right&&i.right+i.width/2||0,r=void 0!==i.y&&i.y-i.height/2||void 0!==i.centerY&&i.centerY||void 0!==i.top&&i.top-i.height/2||void 0!==i.bottom&&i.bottom+i.height/2||0;this.localTransform.translate(this.width*s,-this.height*r)}setupHitAreas(){const t=this.getHitAreaDefs();this.hitAreas={};for(const e of t)e.name&&(this.hitAreas[e.name]=e)}hitTest(t,e){return Object.keys(this.hitAreas).filter(i=>this.isHit(i,t,e))}isHit(t,e,i){const s=this.hitAreas[t];if(!s)return!1;let r=s.index;if(r<0){if(!s.id)return!1;if(r=this.getDrawableIndex(s.id),r<0)return!1;s.index=r}const n=this.getDrawableBounds(r,O);return n.x<=e&&e<=n.x+n.width&&n.y<=i&&i<=n.y+n.height}getDrawableBounds(t,e){const i=this.getDrawableVertices(t);let s=i[0],r=i[0],n=i[1],o=i[1];for(let a=0;a<i.length;a+=2){const t=i[a],e=i[a+1];s=Math.min(t,s),r=Math.max(t,r),n=Math.min(e,n),o=Math.max(e,o)}return null!=e||(e={}),e.x=s,e.y=n,e.width=r-s,e.height=o-n,e}updateTransform(t){this.drawingMatrix.copyFrom(t).append(this.localTransform)}update(t,e){this.focusController.update(t)}destroy(){this.destroyed=!0,this.emit("destroy"),this.motionManager.destroy(),this.motionManager=void 0,this.parallelMotionManager.forEach(t=>t.destroy()),this.parallelMotionManager=[]}updateMotions(t,e){this.emit("beforeMotionUpdate");const i=this.motionManager.update(t,e),s=this.parallelMotionManager.map(i=>i.update(t,e)),r=i||s.reduce((t,e)=>t||e,!1);return this.emit("afterMotionUpdate"),r}}class T extends Error{constructor(t,e,i,s=!1){super(t),this.url=e,this.status=i,this.aborted=s}}const D=class t{static createXHR(e,i,s,r,n){const o=new XMLHttpRequest;if(t.allXhrSet.add(o),e){let i=t.xhrMap.get(e);i?i.add(o):(i=new Set([o]),t.xhrMap.set(e,i))}return o.open("GET",i),o.responseType=s,o.onload=()=>{var t;200!==o.status&&0!==o.status||!o.response?null==(t=o.onerror)||t.call(o,new ProgressEvent("error")):r(o.response)},o.onerror=()=>{l.warn("XHRLoader",`Failed to load resource as ${o.responseType} (Status ${o.status}): ${i}`),n(new T("Network error.",i,o.status))},o.onabort=()=>n(new T("Aborted.",i,o.status,!0)),o.onloadend=()=>{var i;t.allXhrSet.delete(o),e&&(null==(i=t.xhrMap.get(e))||i.delete(o))},o}static cancelXHRs(){var e;null==(e=t.xhrMap.get(this))||e.forEach(e=>{e.abort(),t.allXhrSet.delete(e)}),t.xhrMap.delete(this)}static release(){t.allXhrSet.forEach(t=>t.abort()),t.allXhrSet.clear(),t.xhrMap=new WeakMap}};n(D,"xhrMap",new WeakMap),n(D,"allXhrSet",new Set),n(D,"loader",t=>new Promise((e,i)=>{const s=t.target,r=t.target&&"function"==typeof D.cancelXHRs?D.cancelXHRs.bind(t.target):void 0,n=D.createXHR(t.target,t.settings?t.settings.resolveURL(t.url):t.url,t.type,i=>{t.result=i,e()},i);if(t.target&&r&&"function"==typeof s.listeners&&"function"==typeof s.once){const t=s.listeners("destroy");Array.isArray(t)&&t.includes(r)||s.once("destroy",r)}n.send()}));let S=D;function C(t,e){let i=-1;return function s(r,n){if(n)return Promise.reject(n);if(r<=i)return Promise.reject(new Error("next() called multiple times"));i=r;const o=t[r];if(!o)return Promise.resolve();try{return Promise.resolve(o(e,s.bind(null,r+1)))}catch(a){const t=a instanceof Error?a:new Error(String(a));return Promise.reject(t)}}(0)}class k{static load(t){return o(this,null,function*(){return yield C(this.middlewares,t),t.result})}}n(k,"middlewares",[S.loader]);class N extends E{constructor(t){if(super(t),n(this,"moc"),n(this,"textures"),n(this,"layout"),n(this,"hitAreas"),n(this,"initParams"),n(this,"initOpacities"),n(this,"expressions"),n(this,"motions",{}),!N.isValidJSON(t))throw new TypeError("Invalid JSON.");this.moc=t.model,c("string",t,this,"textures","textures"),this.copy(t)}static isValidJSON(t){if(!t||"object"!=typeof t)return!1;const e=!!Array.isArray(t.textures)&&t.textures.every(t=>"string"==typeof t);return"string"==typeof t.model&&e}copy(t){u("string",t,this,"name","name"),u("string",t,this,"pose","pose"),u("string",t,this,"physics","physics"),u("object",t,this,"layout","layout"),u("object",t,this,"motions","motions"),c("object",t,this,"hit_areas","hitAreas"),c("object",t,this,"expressions","expressions"),c("object",t,this,"init_params","initParams"),c("object",t,this,"init_opacities","initOpacities");const e=this.getFileStem(this.moc);this.setModelName(this.name,e)}replaceFiles(t){super.replaceFiles(t);for(const[e,i]of Object.entries(this.motions))for(let s=0;s<i.length;s++)i[s].file=t(i[s].file,`motions.${e}[${s}].file`),void 0!==i[s].sound&&(i[s].sound=t(i[s].sound,`motions.${e}[${s}].sound`));if(this.expressions)for(let e=0;e<this.expressions.length;e++)this.expressions[e].file=t(this.expressions[e].file,`expressions[${e}].file`)}}function G(){}const j="Live2DFactory",U=(t,e)=>o(null,null,function*(){if("string"==typeof t.source){const e=yield k.load({url:t.source,type:"json",target:t.live2dModel});e.url="string"==typeof e.url?e.url:t.source,t.source=e,t.live2dModel.emit("settingsJSONLoaded",e)}return e()}),H=(t,e)=>o(null,null,function*(){if(t.source instanceof E)return t.settings=t.source,e();if("object"==typeof t.source){const i=J.findRuntime(t.source);if(i){const s=i.createModelSettings(t.source);return t.settings=s,t.live2dModel.emit("settingsLoaded",s),e()}}throw new TypeError("Unknown settings format.")}),X=(t,e)=>{if(t.settings){const i=J.findRuntime(t.settings);if(i)return i.ready().then(()=>e())}return e()},B=(t,e)=>o(null,null,function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=J.findRuntime(e);if(s){const r=[],n=e instanceof N?"json":"arraybuffer";e.pose&&r.push(k.load({settings:e,url:e.pose,type:n,target:i}).then(e=>{i.pose=s.createPose(i.coreModel,e),t.live2dModel.emit("poseLoaded",i.pose)}).catch(e=>{t.live2dModel.emit("poseLoadError",e),l.warn(j,"Failed to load pose.",e)})),e.physics&&r.push(k.load({settings:e,url:e.physics,type:n,target:i}).then(e=>{i.physics=s.createPhysics(i.coreModel,e),t.live2dModel.emit("physicsLoaded",i.physics)}).catch(e=>{t.live2dModel.emit("physicsLoadError",e),l.warn(j,"Failed to load physics.",e)})),r.length&&(yield Promise.all(r))}}}),W=(t,i)=>o(null,null,function*(){if(!t.settings)throw new TypeError("Missing settings.");{const s=t.live2dModel,r={crossOrigin:t.options.crossOrigin};t.settings instanceof N&&(r.preferCreateImageBitmap=!1);const n=Promise.all(t.settings.textures.map(i=>function(t,i={}){const s=e.loadTextures.config,r=null==s?void 0:s.crossOrigin,n=null==s?void 0:s.preferCreateImageBitmap,o=null==s?void 0:s.preferWorkers;return void 0!==i.crossOrigin&&s&&(s.crossOrigin=i.crossOrigin),!1===i.preferCreateImageBitmap&&s&&(s.preferCreateImageBitmap=!1,s.preferWorkers=!1),e.Assets.load(t).catch(t=>{if(t instanceof Error)throw t;throw new Error("Texture loading error",{cause:t})}).finally(()=>{s&&(s.crossOrigin=null!=r?r:s.crossOrigin,!1===i.preferCreateImageBitmap&&(s.preferCreateImageBitmap=null!=n?n:s.preferCreateImageBitmap,s.preferWorkers=null!=o?o:s.preferWorkers))})}(t.settings.resolveURL(i),r)));if(n.catch(G),yield i(),!t.internalModel)throw new TypeError("Missing internal model.");s.internalModel=t.internalModel,s.emit("modelLoaded",t.internalModel),s.textures=yield n,s.emit("textureLoaded",s.textures)}}),$=(t,e)=>o(null,null,function*(){const i=t.settings;if(i instanceof E){const s=J.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield k.load({settings:i,url:i.moc,type:"arraybuffer",target:t.live2dModel});if(!s.isValidMoc(r))throw new Error("Invalid moc data");const n=s.createCoreModel(r);return t.internalModel=s.createInternalModel(n,i,t.options),e()}throw new TypeError("Missing settings.")}),z=class t{static unzip(e,i){return o(this,null,function*(){const s=yield t.getFilePaths(e),r=[];for(const t of i.getDefinedFiles()){const e=decodeURI(f(i.url,t));s.includes(e)&&r.push(e)}const n=yield t.getFiles(e,r);for(let t=0;t<n.length;t++){const e=r[t],i=n[t];Object.defineProperty(i,"webkitRelativePath",{value:e})}return n})}static createSettings(e){return o(this,null,function*(){const i=(yield t.getFilePaths(e)).find(t=>t.endsWith("model.json")||t.endsWith("model3.json"));if(!i)throw new Error("Settings file not found");const s=yield t.readText(e,i);if(!s)throw new Error("Empty settings file: "+i);const r=JSON.parse(s);r.url=i;const n=t.live2dFactory.findRuntime(r);if(!n)throw new Error("Unknown settings JSON");return n.createModelSettings(r)})}static zipReader(t,e){return Promise.reject(new Error("Not implemented"))}static getFilePaths(t){return Promise.reject(new Error("Not implemented"))}static getFiles(t,e){return Promise.reject(new Error("Not implemented"))}static readText(t,e){return Promise.reject(new Error("Not implemented"))}static releaseReader(t){}};n(z,"live2dFactory"),n(z,"ZIP_PROTOCOL","zip://"),n(z,"uid",0),n(z,"factory",(t,e)=>o(null,null,function*(){const i=t.source;let s,r,n;if("string"==typeof i&&(i.endsWith(".zip")||i.startsWith(z.ZIP_PROTOCOL))?(s=i.startsWith(z.ZIP_PROTOCOL)?i.slice(z.ZIP_PROTOCOL.length):i,r=yield k.load({url:s,type:"blob",target:t.live2dModel})):Array.isArray(i)&&1===i.length&&i[0]instanceof File&&i[0].name.endsWith(".zip")&&(r=i[0],s=URL.createObjectURL(r),n=i.settings),r){if(!r.size)throw new Error("Empty zip file");const e=yield z.zipReader(r,s);n||(n=yield z.createSettings(e)),n._objectURL=z.ZIP_PROTOCOL+z.uid+"/"+n.url;const i=yield z.unzip(e,n);i.settings=n,t.source=i,s.startsWith("blob:")&&t.live2dModel.once("modelLoaded",t=>{t.once("destroy",function(){URL.revokeObjectURL(s)})}),z.releaseReader(e)}return e()}));let q=z;const V=class t{static resolveURL(e,i){var s;const r=null==(s=t.filesMap[e])?void 0:s[i];if(void 0===r)throw new Error("Cannot find this file from uploaded files: "+i);return r}static upload(e,i){const s={};for(const t of i.getDefinedFiles()){const r=decodeURI(f(i.url,t)),n=e.find(t=>t.webkitRelativePath===r);n&&(s[t]=URL.createObjectURL(n))}t.filesMap[i._objectURL]=s}static createSettings(e){return o(this,null,function*(){const i=e.find(t=>t.name.endsWith("model.json")||t.name.endsWith("model3.json"));if(!i)throw new TypeError("Settings file not found");const s=yield t.readText(i),r=JSON.parse(s);r.url=i.webkitRelativePath;const n=J.findRuntime(r);if(!n)throw new Error("Unknown settings JSON");const o=n.createModelSettings(r);return o._objectURL=URL.createObjectURL(i),o})}static readText(t){return o(this,null,function*(){return new Promise((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")})})}};n(V,"live2dFactory"),n(V,"filesMap",{}),n(V,"factory",(t,e)=>o(null,null,function*(){if(Array.isArray(t.source)&&t.source[0]instanceof File){const e=t.source;let i=e.settings;if(i){if(!i._objectURL)throw new Error('"_objectURL" must be specified in ModelSettings')}else i=yield V.createSettings(e);i.validateFiles(e.map(t=>encodeURI(t.webkitRelativePath))),V.upload(e,i),i.resolveURL=function(t){return V.resolveURL(this._objectURL,t)},t.source=i,t.live2dModel.once("modelLoaded",t=>{t.once("destroy",function(){const t=this.settings._objectURL;if(URL.revokeObjectURL(t),V.filesMap[t])for(const e of Object.values(V.filesMap[t]))URL.revokeObjectURL(e);delete V.filesMap[t]})})}return e()}));let Y=V;const Z=class t{static registerRuntime(e){t.runtimes.push(e),t.runtimes.sort((t,e)=>e.version-t.version)}static findRuntime(e){for(const i of t.runtimes)if(i.test(e))return i}static setupLive2DModel(e,i,s){return o(this,null,function*(){const r=new Promise(t=>e.once("textureLoaded",t)),n=new Promise(t=>e.once("modelLoaded",t)),o=Promise.all([r,n]).then(()=>e.emit("ready"));yield C(t.live2DModelMiddlewares,{live2dModel:e,source:i,options:s||{}}),yield o,e.emit("load")})}static loadMotion(e,i,s){var r;const n=t=>e.emit("motionLoadError",i,s,t);try{const o=null==(r=e.definitions[i])?void 0:r[s];if(!o)return Promise.resolve(void 0);e.once("destroy",()=>t.releaseMotionTasks(e));let a=t.motionTasksMap.get(e);a||(a={},t.motionTasksMap.set(e,a));let h=a[i];h||(h=[],a[i]=h);const d=e.getMotionFile(o);return null!=h[s]||(h[s]=k.load({url:d,settings:e.settings,type:e.motionDataType,target:e}).then(r=>{var n;const a=null==(n=t.motionTasksMap.get(e))?void 0:n[i];a&&(a[s]=void 0);const l=r,h=e.createMotion(l,i,o);return e.emit("motionLoaded",i,s,h),h}).catch(t=>{l.warn(e.tag,`Failed to load motion: ${d}\n`,t),n(t)})),h[s]}catch(o){l.warn(e.tag,`Failed to load motion at "${i}"[${s}]\n`,o),n(o)}return Promise.resolve(void 0)}static loadExpression(e,i){var s;const r=t=>e.emit("expressionLoadError",i,t);try{const n=e.definitions[i];if(!n)return Promise.resolve(void 0);e.once("destroy",()=>t.releaseExpressionTasks(e));let o=t.expressionTasksMap.get(e);o||(o=[],t.expressionTasksMap.set(e,o));const a=e.getExpressionFile(n),h=null!=(s=e.expressionDataType)?s:"json";return null!=o[i]||(o[i]=k.load({url:a,settings:e.settings,type:h,target:e}).then(s=>{const r=t.expressionTasksMap.get(e);r&&(r[i]=void 0);const o=s,a=e.createExpression(o,n);return e.emit("expressionLoaded",i,a),a}).catch(t=>{l.warn(e.tag,`Failed to load expression: ${a}\n`,t),r(t)})),o[i]}catch(n){l.warn(e.tag,`Failed to load expression at [${i}]\n`,n),r(n)}return Promise.resolve(void 0)}static releaseMotionTasks(e){t.motionTasksMap.delete(e)}static releaseExpressionTasks(e){t.expressionTasksMap.delete(e)}};n(Z,"runtimes",[]),n(Z,"urlToJSON",U),n(Z,"jsonToSettings",H),n(Z,"waitUntilReady",X),n(Z,"setupOptionals",B),n(Z,"setupEssentials",W),n(Z,"createInternalModel",$),n(Z,"live2DModelMiddlewares",[q.factory,Y.factory,U,H,X,B,W,$]),n(Z,"motionTasksMap",new WeakMap),n(Z,"expressionTasksMap",new WeakMap);let J=Z;F.prototype._loadMotion=function(t,e){return J.loadMotion(this,t,e)},M.prototype._loadExpression=function(t){return J.loadExpression(this,t)},Y.live2dFactory=J,q.live2dFactory=J;const Q=class t{constructor(i,{autoUpdate:s=!0,autoHitTest:r=!0,autoFocus:o=!0,autoInteract:a,ticker:h}={}){var d;n(this,"model"),n(this,"destroyed",!1),n(this,"_ticker"),n(this,"_autoUpdate",!1),n(this,"_autoHitTest",!1),n(this,"_autoFocus",!1),null!=h||(h=null!=(d=t.defaultTicker)?d:"undefined"!=typeof PIXI?PIXI.Ticker.shared:e.Ticker.shared),void 0!==a&&(r=a,o=a,l.warn(i.tag,"options.autoInteract is deprecated since v0.5.0, use autoHitTest and autoFocus instead.")),this.model=i,this.ticker=h,this.autoUpdate=s,this.autoHitTest=r,this.autoFocus=o,(r||o)&&(this.model.eventMode="static")}get ticker(){return this._ticker}set ticker(t){var e,i;this._ticker&&this._ticker.remove(tt,this),this._ticker=t,this._autoUpdate&&(null==(e=this._ticker)||e.add(tt,this),null==(i=this._ticker)||i.start())}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){var e;this.destroyed||(t?this._ticker?(this._ticker.add(tt,this),this._autoUpdate=!0):l.warn(this.model.tag,"No Ticker to be used for automatic updates. Either set option.ticker when creating Live2DModel, or expose PIXI to global scope (window.PIXI = PIXI)."):(null==(e=this._ticker)||e.remove(tt,this),this._autoUpdate=!1))}get autoHitTest(){return this._autoHitTest}set autoHitTest(t){t!==this.autoHitTest&&(t?this.model.on("pointertap",et,this):this.model.off("pointertap",et,this),this._autoHitTest=t)}get autoFocus(){return this._autoFocus}set autoFocus(t){t!==this.autoFocus&&(t?(this.model.on("globalpointermove",it,this),this.model.on("pointermove",it,this)):(this.model.off("globalpointermove",it,this),this.model.off("pointermove",it,this)),this._autoFocus=t)}get autoInteract(){return this._autoHitTest&&this._autoFocus}set autoInteract(t){this.autoHitTest=t,this.autoFocus=t}onTickerUpdate(){const t=this.ticker.deltaMS;this.model.update(t)}onTap(t){this.model.tap(t.global.x,t.global.y)}onPointerMove(t){this.model.focus(t.global.x,t.global.y)}destroy(){this.autoFocus=!1,this.autoHitTest=!1,this.autoUpdate=!1,this.ticker=void 0,this.destroyed=!0}};n(Q,"defaultTicker");let K=Q;function tt(){this.onTickerUpdate()}function et(t){this.onTap(t)}function it(t){this.onPointerMove(t)}class st extends e.Transform{}const rt=new e.Point,nt=new e.Matrix,ot=new e.Matrix,at={x:0,y:0,width:0,height:0},lt=new e.Bounds;class ht{constructor(t){this.renderer=t}execute(t){!t.visible||t.alpha<=0||t.renderLive2D(this.renderer)}updateRenderable(){}destroy(){}}class dt extends e.Container{constructor(t){super(),n(this,"renderPipeId","live2d"),n(this,"tag","Live2DModel(uninitialized)"),n(this,"internalModel"),n(this,"textures",[]),n(this,"transform",new st),n(this,"anchor"),n(this,"_bounds",new e.Bounds),n(this,"_boundsDirty",!0),n(this,"_boundsRetryAfterDraw",!1),n(this,"gl",null),n(this,"elapsedTime",0),n(this,"deltaTime",0),n(this,"automator"),n(this,"currentGlId",0),n(this,"renderLive2D",t=>{var i,s,r,n,o;if(!(t instanceof e.WebGLRenderer))throw new Error("Renderer is not supported");t.geometry.resetState(),t.shader.resetState(),t.texture.resetState();let a=!1;this.gl!==t.gl&&(this.gl=t.gl,this.internalModel.updateWebGLContext(t.gl,this.generateUID()),a=!0);for(let e=0;e<this.textures.length;e++){const i=this.textures[e],s=Boolean(i.source._gpuData[t.uid]);!a&&s||(t.gl.pixelStorei(WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL,this.internalModel.textureFlipY),t.texture.bind(i,0)),this.internalModel.bindTexture(e,t.texture.getGlSource(i.source).texture)}const l=t.renderTarget.viewport,h=t.renderTarget.renderTarget;let d=l.y;if(null==h?void 0:h.isRoot){d=h.colorTexture.source.pixelHeight-l.height-l.y}this.internalModel.viewport=[l.x,d,l.width,l.height];const u=this.deltaTime;this.deltaTime=0,u&&this.internalModel.update(u,this.elapsedTime);const{projectionMatrix:c,offset:p}=t.globalUniforms.globalUniformData,g=ot.copyFrom(this.worldTransform);g.tx-=null!=(i=null==p?void 0:p.x)?i:0,g.ty-=null!=(s=null==p?void 0:p.y)?s:0;const m=nt.copyFrom(c).append(g);this.internalModel.updateTransform(m),this.internalModel.draw(t.gl),this._boundsRetryAfterDraw&&this.updateDrawableBounds(),t.state.resetState(),t.texture.resetState();const f=null==(r=t.renderTarget)?void 0:r.defaultClearColor,M=null==(o=null==(n=t.renderTarget)?void 0:n.adaptor)?void 0:o._clearColorCache;f&&(t.gl.clearColor(f[0],f[1],f[2],f[3]),M&&(M[0]=f[0],M[1]=f[1],M[2]=f[2],M[3]=f[3]))}),this.anchor=new e.ObservablePoint({_onUpdate:()=>this.onAnchorChange()},0,0),this.automator=new K(this,t),this.once("modelLoaded",()=>this.initializeOnModelLoad(t))}get isRenderable(){return!0}get canBundle(){return!1}static from(t,e){return o(this,null,function*(){const i=new this(e);return yield J.setupLive2DModel(i,t,e),i})}static fromSync(t,e){const i=new this(e);return J.setupLive2DModel(i,t,e).then(()=>{var t;return null==(t=null==e?void 0:e.onLoad)?void 0:t.call(e)}).catch(t=>{var i;return null==(i=null==e?void 0:e.onError)?void 0:i.call(e,t)}),i}static registerTicker(t){K.defaultTicker=t.shared}get bounds(){return this.internalModel?(this._boundsDirty&&this.updateDrawableBounds(),this._bounds):(this._bounds.set(0,0,0,0),this._bounds)}updateDrawableBounds(){if(!this.internalModel)return this._bounds.set(0,0,0,0),void(this._boundsDirty=!1);const t=this.internalModel.getDrawableIDs();lt.clear();for(let i=0;i<t.length;i++){const s=t[i],r=this.internalModel.getDrawableIndex(s);if(r<0)continue;const n=this.internalModel.getDrawableBounds(r,at);Number.isFinite(n.x)&&Number.isFinite(n.y)&&Number.isFinite(n.width)&&Number.isFinite(n.height)&&lt.addFrame(n.x,n.y,n.x+n.width,n.y+n.height,e.Matrix.IDENTITY)}if(this._bounds.clear(),lt.isValid&&lt.isPositive)this._bounds.addFrame(lt.minX,lt.minY,lt.maxX,lt.maxY,this.internalModel.localTransform),this._boundsRetryAfterDraw=!1;else{const t=this.internalModel.originalWidth||this.internalModel.width,e=this.internalModel.originalHeight||this.internalModel.height;this._bounds.addFrame(0,0,t,e,this.internalModel.localTransform),this._boundsRetryAfterDraw=!0}this._boundsDirty=!1}generateUID(){return++this.currentGlId}collectRenderables(t,e,i){var s,r,n,o;if(this.parentRenderLayer&&this.parentRenderLayer!==i)return;if(this.globalDisplayStatus<7)return;if(!this.includeInBuild)return;this.sortableChildren&&this.sortChildren(),function(t){const e=t;e.renderPipes.live2d||(e.renderPipes.live2d=new ht(t))}(e);const a=e.renderPipes,l=()=>{var e,i;null==(i=null==(e=a.batch)?void 0:e.break)||i.call(e,t),t.add(this)},h=()=>{const s=this.children,r=s.length;for(let n=0;n<r;n++)s[n].collectRenderables(t,e,i)},d=this.effects;if(d){for(let e=0;e<d.length;e++){const i=d[e],n=i.filters;if(n)for(const t of n)t&&"number"==typeof t.resolution&&1===t.resolution&&(t.resolution="inherit");null==(r=null==(s=a[i.pipe])?void 0:s.push)||r.call(s,i,this,t)}l(),h();for(let e=d.length-1;e>=0;e--){const i=d[e];null==(o=null==(n=a[i.pipe])?void 0:n.pop)||o.call(n,i,this,t)}}else l(),h()}initializeOnModelLoad(t){this.tag=`Live2DModel(${this.internalModel.settings.name})`,this.onAnchorChange(),this.updateDrawableBounds()}onAnchorChange(){this.internalModel&&this.pivot&&this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(t,e,i){return o(this,arguments,function*(t,e,i,{sound:s,volume:r=.5,expression:n,resetExpression:o=!0,onFinish:a,onError:l}={}){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i,{sound:s,volume:r,expression:n,resetExpression:o,onFinish:a,onError:l}):this.internalModel.motionManager.startMotion(t,e,i,{sound:s,volume:r,expression:n,resetExpression:o,onFinish:a,onError:l})})}motionLastFrame(t,e){return o(this,arguments,function*(t,e,{expression:i}={}){return this.internalModel.motionManager.motionLastFrame(t,e,{expression:i})})}parallelMotion(t){return o(this,null,function*(){this.internalModel.extendParallelMotionManager(t.length);const e=t.map((t,e)=>this.internalModel.parallelMotionManager[e].startMotion(t.group,t.index,t.priority)),i=[];for(const t of e)i.push(yield t);return i})}parallelLastFrame(t){return o(this,null,function*(){this.internalModel.extendParallelMotionManager(t.length);const e=t.map((t,e)=>this.internalModel.parallelMotionManager[e].playMotionLastFrame(t.group,t.index)),i=[];for(const t of e)i.push(yield t);return i})}stopMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(t,{volume:e=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:n}={}){return this.internalModel.motionManager.speak(t,{volume:e,expression:i,resetExpression:s,onFinish:r,onError:n})}stopSpeaking(){return this.internalModel.motionManager.stopSpeaking()}expression(t){return this.internalModel.motionManager.expressionManager?void 0===t?this.internalModel.motionManager.expressionManager.setRandomExpression():this.internalModel.motionManager.expressionManager.setExpression(t):Promise.resolve(!1)}focus(t,e,i=!1){rt.x=t,rt.y=e,this.toModelPosition(rt,rt,!0);const s=rt.x/this.internalModel.originalWidth*2-1,r=rt.y/this.internalModel.originalHeight*2-1,n=Math.atan2(r,s);this.internalModel.focusController.focus(Math.cos(n),-Math.sin(n),i)}tap(t,e){const i=this.hitTest(t,e);i.length&&this.emit("hit",i)}hitTest(t,e){return rt.x=t,rt.y=e,this.toModelPosition(rt,rt),this.internalModel.hitTest(rt.x,rt.y)}toModelPosition(t,e=t.clone(),i){return i||this.updateLocalTransform(),this.toLocal(t,void 0,e,i),this.internalModel.localTransform.applyInverse(e,e),e}containsPoint(t){return this.bounds.containsPoint(t.x,t.y)}_calculateBounds(){if(!this.internalModel)return void this.getBounds().set(0,0,0,0);const t=this.internalModel.width,e=this.internalModel.height;this.getBounds().addFrame(0,0,t,e,this.transform.matrix)}update(t){this.deltaTime+=t,this.elapsedTime+=t}destroy(t){this.emit("destroy"),(null==t?void 0:t.texture)&&this.textures.forEach(e=>e.destroy(t.baseTexture)),this.automator.destroy(),this.internalModel.destroy(),super.destroy(t)}}if(!("Live2D"in window))throw new Error("Could not find Cubism 2 runtime. This plugin requires live2d.min.js to be loaded.");const ut=Live2DMotion.prototype.updateParam;Live2DMotion.prototype.updateParam=function(t,e){ut.call(this,t,e),e.isFinished()&&this.onFinishHandler&&(this.onFinishHandler(this),delete this.onFinishHandler)};class ct extends AMotion{constructor(t){super(),n(this,"params",[]),this.setFadeIn(t.fade_in>0?t.fade_in:a.expressionFadingDuration),this.setFadeOut(t.fade_out>0?t.fade_out:a.expressionFadingDuration),Array.isArray(t.params)&&t.params.forEach(t=>{const e=t.calc||"add";if("add"===e){const e=t.def||0;t.val-=e}else if("mult"===e){const e=t.def||1;t.val/=e}this.params.push({calc:e,val:t.val,id:t.id})})}updateParamExe(t,e,i,s){this.params.forEach(e=>{t.setParamFloat(e.id,e.val*i)})}}class pt extends M{constructor(t,e){var i;super(t,e),n(this,"queueManager",new MotionQueueManager),n(this,"definitions"),this.definitions=null!=(i=this.settings.expressions)?i:[],this.init()}isFinished(){return this.queueManager.isFinished()}getExpressionIndex(t){return this.definitions.findIndex(e=>e.name===t)}getExpressionFile(t){return t.file}createExpression(t,e){return new ct(t)}_setExpression(t){return this.queueManager.startMotion(t)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}}function gt(t,e,i){const s=i.getDurationMSec(),r=t.startMotion(i,!0),n=t.motions.find(t=>!!t&&t._$sr===r);return!!n&&(i.updateParamExe(e.coreModel,s,1,n),!0)}class mt extends F{constructor(t){super(t),n(this,"definitions"),n(this,"groups",{idle:"idle"}),n(this,"motionDataType","arraybuffer"),n(this,"queueManager",new MotionQueueManager),n(this,"lipSyncIds"),n(this,"expressionManager"),this.definitions=this.settings.motions,this.init(t.options),this.lipSyncIds=["PARAM_MOUTH_OPEN_Y"]}init(t){super.init(t),this.settings.expressions&&(this.expressionManager=new pt(this.settings,t))}isFinished(){return this.queueManager.isFinished()}createMotion(t,e,i){const s=Live2DMotion.loadMotion(t),r=e===this.groups.idle?a.idleMotionFadingDuration:a.motionFadingDuration;return s.setFadeIn(i.fade_in>0?i.fade_in:r),s.setFadeOut(i.fade_out>0?i.fade_out:r),s}getMotionFile(t){return t.file}getMotionName(t){return t.file}getSoundFile(t){return t.sound}_startMotion(t,e,i){return t.onFinishHandler=e,i&&i.length>0&&(t.motions=t.motions.filter(t=>!i.includes(t._$4P))),this.queueManager.stopAllMotions(),this.queueManager.startMotion(t)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}destroy(){super.destroy(),this.queueManager=void 0}motionLastFrame(t,e){return o(this,arguments,function*(t,e,{expression:i}={}){const s=yield this.getMotionAndApplyExpression(t,e,i);return!!s&&(this.playing=!0,gt(this.queueManager,this.parent,s),this.playing=!1,!0)})}}class ft extends e.EventEmitter{constructor(t){super(),n(this,"tag"),n(this,"manager"),n(this,"settings"),n(this,"state",new b),n(this,"playing",!1),n(this,"destroyed",!1),n(this,"parent"),this.settings=t.settings,this.tag=`ParallelMotionManager(${this.settings.name})`,this.state.tag=this.tag,this.manager=t.motionManager,this.parent=t}startMotion(t,e){return o(this,arguments,function*(t,e,i=P.NORMAL,s=[]){var r;if(!this.state.reserve(t,e,i))return!1;const n=null==(r=this.manager.definitions[t])?void 0:r[e];if(!n)return!1;const o=yield this.manager.loadMotion(t,e);return!!this.state.start(o,t,e,i)&&(l.log(this.tag,"Start motion:",this.getMotionName(n)),this.emit("motionStart",t,e,void 0),this.playing=!0,this._startMotion(o,void 0,s),!0)})}startRandomMotion(t,e){return o(this,null,function*(){var i;const s=this.manager.definitions[t];if(null==s?void 0:s.length){const r=[],n=null!=(i=this.manager.motionGroups[t])?i:[];for(let e=0;e<s.length;e++)null===n[e]||this.state.isActive(t,e)||r.push(e);if(r.length){const i=r[Math.floor(Math.random()*r.length)];return this.startMotion(t,i,e)}}return!1})}stopAllMotions(){this._stopAllMotions(),this.state.reset()}update(t,e){return this.isFinished()&&(this.playing&&(this.playing=!1,this.emit("motionFinish")),this.state.complete()),this.updateParameters(t,e)}destroy(){this.destroyed=!0,this.emit("destroy"),this.stopAllMotions()}}class Mt extends ft{constructor(t){super(t),n(this,"queueManager",new MotionQueueManager)}isFinished(){return this.queueManager.isFinished()}getMotionName(t){return t.file}_startMotion(t,e,i){return t.onFinishHandler=e,i&&i.length>0&&(t.motions=t.motions.filter(t=>!i.includes(t._$4P))),this.queueManager.stopAllMotions(),this.queueManager.startMotion(t)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}destroy(){super.destroy(),this.queueManager=void 0}playMotionLastFrame(t,e){return o(this,null,function*(){var i;if(!this.state.reserve(t,e,P.FORCE))return!1;const s=null==(i=this.manager.definitions[t])?void 0:i[e];if(!s)return!1;const r=yield this.manager.loadMotion(t,e);return!!this.state.start(r,t,e,P.FORCE)&&(l.log(this.tag,"Start motion:",this.getMotionName(s)),this.queueManager.stopAllMotions(),this.emit("motionStart",t,e,void 0),this.playing=!0,!!gt(this.queueManager,this.parent,r)&&(this.playing=!1,!0))})}}class yt{constructor(t){n(this,"leftParam"),n(this,"rightParam"),n(this,"blinkInterval",4e3),n(this,"closingDuration",100),n(this,"closedDuration",50),n(this,"openingDuration",150),n(this,"eyeState",0),n(this,"eyeParamValue",1),n(this,"closedTimer",0),n(this,"nextBlinkTimeLeft",this.blinkInterval),this.coreModel=t,this.leftParam=t.getParamIndex("PARAM_EYE_L_OPEN"),this.rightParam=t.getParamIndex("PARAM_EYE_R_OPEN")}setEyeParams(t){this.eyeParamValue=h(t,0,1),this.coreModel.setParamFloat(this.leftParam,this.eyeParamValue),this.coreModel.setParamFloat(this.rightParam,this.eyeParamValue)}update(t){switch(this.eyeState){case 0:this.nextBlinkTimeLeft-=t,this.nextBlinkTimeLeft<0&&(this.eyeState=1,this.nextBlinkTimeLeft=this.blinkInterval+this.closingDuration+this.closedDuration+this.openingDuration+d(0,2e3));break;case 1:this.setEyeParams(this.eyeParamValue+t/this.closingDuration),this.eyeParamValue<=0&&(this.eyeState=2,this.closedTimer=0);break;case 2:this.closedTimer+=t,this.closedTimer>=this.closedDuration&&(this.eyeState=3);break;case 3:this.setEyeParams(this.eyeParamValue+t/this.openingDuration),this.eyeParamValue>=1&&(this.eyeState=0)}}}const xt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class vt extends R{constructor(t,e,i){super(),n(this,"settings"),n(this,"options"),n(this,"coreModel"),n(this,"motionManager"),n(this,"parallelMotionManager"),n(this,"eyeBlink"),n(this,"eyeballXParamIndex"),n(this,"eyeballYParamIndex"),n(this,"angleXParamIndex"),n(this,"angleYParamIndex"),n(this,"angleZParamIndex"),n(this,"bodyAngleXParamIndex"),n(this,"breathParamIndex"),n(this,"textureFlipY",!0),n(this,"lipSync",!0),n(this,"drawDataCount",0),n(this,"disableCulling",!1),n(this,"hasDrawn",!1),n(this,"customHitAreas"),this.coreModel=t,this.settings=e,this.options=Object.assign({},{breathDepth:1},i),this.motionManager=new mt(this),this.parallelMotionManager=[],this.eyeBlink=new yt(t),this.eyeballXParamIndex=t.getParamIndex("PARAM_EYE_BALL_X"),this.eyeballYParamIndex=t.getParamIndex("PARAM_EYE_BALL_Y"),this.angleXParamIndex=t.getParamIndex("PARAM_ANGLE_X"),this.angleYParamIndex=t.getParamIndex("PARAM_ANGLE_Y"),this.angleZParamIndex=t.getParamIndex("PARAM_ANGLE_Z"),this.bodyAngleXParamIndex=t.getParamIndex("PARAM_BODY_ANGLE_X"),this.breathParamIndex=t.getParamIndex("PARAM_BREATH"),this.init()}init(){super.init(),this.settings.initParams&&this.settings.initParams.forEach(({id:t,value:e})=>this.coreModel.setParamFloat(t,e)),this.settings.initOpacities&&this.settings.initOpacities.forEach(({id:t,value:e})=>this.coreModel.setPartsOpacity(t,e)),this.coreModel.saveParam();const t=this.coreModel.getModelContext()._$aS;(null==t?void 0:t.length)&&(this.drawDataCount=t.length);let e=this.coreModel.drawParamWebGL.culling;Object.defineProperty(this.coreModel.drawParamWebGL,"culling",{set:t=>e=t,get:()=>!this.disableCulling&&e});const i=this.coreModel.getModelContext().clipManager,s=i.setupClip.bind(i);i.setupClip=(t,e)=>{s.call(i,t,e),e.gl.viewport(...this.viewport)}}getSize(){return[this.coreModel.getCanvasWidth(),this.coreModel.getCanvasHeight()]}getLayout(){const t={};if(this.settings.layout)for(const[e,i]of Object.entries(this.settings.layout)){let s=e;"center_x"===e?s="centerX":"center_y"===e&&(s="centerY"),"number"==typeof i&&(t[s]=i)}return t}updateWebGLContext(t,e){const i=this.coreModel.drawParamWebGL;i.firstDraw=!0,i.setGL(t),i.glno=e,i._$NT=null,i._$no=null,i._$vS=null;const s=this.coreModel.getModelContext().clipManager;s.curFrameNo=e;const r=t.getParameter(t.FRAMEBUFFER_BINDING);s.getMaskRenderTexture(),t.bindFramebuffer(t.FRAMEBUFFER,r)}bindTexture(t,e){this.coreModel.setTexture(t,e)}getHitAreaDefs(){var t,e,i;const s=this.settings.json;return A(null!=(i=null!=(e=null!=(t=this.settings.hitAreas)?t:s.hit_areas)?e:s.HitAreas)?i:s.hitAreas,t=>this.coreModel.getDrawDataIndex(t))}getDrawableIDs(){const t=this.coreModel.getModelContext(),e=[];for(let i=0;i<this.drawDataCount;i++){const s=t.getDrawData(i);s&&e.push(s.getDrawDataID().id)}return e}getDrawableIndex(t){return this.coreModel.getDrawDataIndex(t)}getDrawableVertices(t){if("string"==typeof t&&-1===(t=this.coreModel.getDrawDataIndex(t)))throw new TypeError("Unable to find drawable ID: "+t);return this.coreModel.getTransformedPoints(t).slice()}hitTest(t,e){this.hasDrawn||l.warn("Trying to hit-test a Cubism 2 model that has not been rendered yet. Drawable hit areas may be empty until the first draw.");const i=super.hitTest(t,e),s=this.hitTestCustom(t,e);return s.length?i.length?[...new Set([...i,...s])]:s:i}update(t,e){var i,s,r,n;super.update(t,e);const o=this.coreModel,a=this.updateMotions(o,e);if(o.saveParam(),null==(i=this.motionManager.expressionManager)||i.update(o,e),a||null==(s=this.eyeBlink)||s.update(t),this.updateFocus(),this.updateNaturalMovements(t,e),this.lipSync&&this.motionManager.currentAudio){const t=1.5;let e=this.motionManager.mouthSync()*t;const i=1,s=1.15,r=e>0?.1:0;e=Math.pow(e,s),e=h(e,r,i);for(let n=0;n<this.motionManager.lipSyncIds.length;++n)this.coreModel.setParamFloat(this.coreModel.getParamIndex(this.motionManager.lipSyncIds[n]),e)}null==(r=this.physics)||r.update(e),null==(n=this.pose)||n.update(t),this.emit("beforeModelUpdate"),o.update(),o.loadParam()}updateFocus(){this.coreModel.addToParamFloat(this.eyeballXParamIndex,this.focusController.x),this.coreModel.addToParamFloat(this.eyeballYParamIndex,this.focusController.y),this.coreModel.addToParamFloat(this.angleXParamIndex,30*this.focusController.x),this.coreModel.addToParamFloat(this.angleYParamIndex,30*this.focusController.y),this.coreModel.addToParamFloat(this.angleZParamIndex,this.focusController.x*this.focusController.y*-30),this.coreModel.addToParamFloat(this.bodyAngleXParamIndex,10*this.focusController.x)}updateNaturalMovements(t,e){const i=e/1e3*2*Math.PI;this.coreModel.addToParamFloat(this.angleXParamIndex,15*this.options.breathDepth*Math.sin(i/6.5345)*.5),this.coreModel.addToParamFloat(this.angleYParamIndex,8*this.options.breathDepth*Math.sin(i/3.5345)*.5),this.coreModel.addToParamFloat(this.angleZParamIndex,10*this.options.breathDepth*Math.sin(i/5.5345)*.5),this.coreModel.addToParamFloat(this.bodyAngleXParamIndex,4*this.options.breathDepth*Math.sin(i/15.5345)*.5),this.coreModel.setParamFloat(this.breathParamIndex,.5+.5*Math.sin(i/3.2345))}draw(t){const e=this.disableCulling;t.getParameter(t.FRAMEBUFFER_BINDING)&&(this.disableCulling=!0);const i=this.drawingMatrix;xt[0]=i.a,xt[1]=i.b,xt[4]=i.c,xt[5]=i.d,xt[12]=i.tx,xt[13]=i.ty,this.coreModel.setMatrix(xt),this.coreModel.draw(),this.hasDrawn=!0,this.disableCulling=e}extendParallelMotionManager(t){for(;this.parallelMotionManager.length<t;)this.parallelMotionManager.push(new Mt(this))}destroy(){super.destroy(),this.coreModel=void 0}hitTestCustom(t,e){const i=this.getCustomHitAreas();if(!i)return[];const s=this.originalWidth||this.width,r=this.originalHeight||this.height;if(!s||!r)return[];const n=t/s*2-1,o=1-e/r*2,a=[];for(const[l,h]of Object.entries(i))n>=h.minX&&n<=h.maxX&&o>=h.minY&&o<=h.maxY&&a.push(l);return a}getCustomHitAreas(){var t,e,i,s,r;if(void 0!==this.customHitAreas)return this.customHitAreas;const n=this.settings.json,o=null!=(i=null!=(e=null!=(t=n.hit_areas_custom)?t:n.hitAreasCustom)?e:n.HitAreasCustom)?i:n.HitAreas_Custom;if(!o||"object"!=typeof o)return this.customHitAreas=null,null;const a=o,l={},h=(t,e,i)=>{if(!t||!Array.isArray(e)||!Array.isArray(i))return;if(e.length<2||i.length<2)return;const s=Number(e[0]),r=Number(e[1]),n=Number(i[0]),o=Number(i[1]);Number.isFinite(s)&&Number.isFinite(r)&&Number.isFinite(n)&&Number.isFinite(o)&&(l[t]={minX:Math.min(s,r),maxX:Math.max(s,r),minY:Math.min(n,o),maxY:Math.max(n,o)})};for(const[d,u]of Object.entries(a)){if(d.endsWith("_x")){const t=d.slice(0,-2);h(t,u,a[`${t}_y`]);continue}if(!d.endsWith("_y")&&(u&&"object"==typeof u)){const t=u;h(d,null!=(s=t.x)?s:t.X,null!=(r=t.y)?r:t.Y)}}return this.customHitAreas=Object.keys(l).length?l:null,this.customHitAreas}}const Et={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE},Pt={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE};class bt{constructor(t,e){n(this,"physicsHairs",[]),this.coreModel=t,e.physics_hair&&(this.physicsHairs=e.physics_hair.map(t=>{const e=new PhysicsHair;return e.setup(t.setup.length,t.setup.regist,t.setup.mass),t.src.forEach(({id:t,ptype:i,scale:s,weight:r})=>{const n=Et[i];n&&e.addSrcParam(n,t,s,r)}),t.targets.forEach(({id:t,ptype:i,scale:s,weight:r})=>{const n=Pt[i];n&&e.addTargetParam(n,t,s,r)}),e}))}update(t){this.physicsHairs.forEach(e=>e.update(this.coreModel,t))}}class wt{constructor(t){n(this,"paramIndex",-1),n(this,"partsIndex",-1),n(this,"link",[]),this.id=t}initIndex(t){this.paramIndex=t.getParamIndex("VISIBLE:"+this.id),this.partsIndex=t.getPartsDataIndex(PartsDataID.getID(this.id)),t.setParamFloat(this.paramIndex,1)}}class It{constructor(t,e){n(this,"opacityAnimDuration",500),n(this,"partsGroups",[]),this.coreModel=t,e.parts_visible&&(this.partsGroups=e.parts_visible.map(({group:t})=>t.map(({id:t,link:e})=>{const i=new wt(t);return e&&(i.link=e.map(t=>new wt(t))),i})),this.init())}init(){this.partsGroups.forEach(t=>{t.forEach(t=>{if(t.initIndex(this.coreModel),t.paramIndex>=0){const e=0!==this.coreModel.getParamFloat(t.paramIndex);this.coreModel.setPartsOpacity(t.partsIndex,e?1:0),this.coreModel.setParamFloat(t.paramIndex,e?1:0),t.link.length>0&&t.link.forEach(t=>t.initIndex(this.coreModel))}})})}normalizePartsOpacityGroup(t,e){const i=this.coreModel,s=.5;let r=1,n=t.findIndex(({paramIndex:t,partsIndex:e})=>e>=0&&0!==i.getParamFloat(t));if(n>=0){const s=i.getPartsOpacity(t[n].partsIndex);r=h(s+e/this.opacityAnimDuration,0,1)}else n=0,r=1;t.forEach(({partsIndex:t},e)=>{if(t>=0)if(n==e)i.setPartsOpacity(t,r);else{let e,n=i.getPartsOpacity(t);e=r<s?-.5*r/s+1:(1-r)*s/.5;(1-e)*(1-r)>.15&&(e=1-.15/(1-r)),n>e&&(n=e),i.setPartsOpacity(t,n)}})}copyOpacity(t){const e=this.coreModel;t.forEach(({partsIndex:t,link:i})=>{if(t>=0&&i){const s=e.getPartsOpacity(t);i.forEach(({partsIndex:t})=>{t>=0&&e.setPartsOpacity(t,s)})}})}update(t){this.partsGroups.forEach(e=>{this.normalizePartsOpacityGroup(e,t),this.copyOpacity(e)})}}J.registerRuntime({version:2,test:t=>t instanceof N||N.isValidJSON(t),ready:()=>Promise.resolve(),isValidMoc(t){if(t.byteLength<3)return!1;const e=new Int8Array(t,0,3);return"moc"===String.fromCharCode(...e)},createModelSettings:t=>new N(t),createCoreModel(t){const e=Live2DModelWebGL.loadModel(t),i=Live2D.getError();if(i){if(i instanceof Error)throw i;const t="string"==typeof i?i:`Live2D error: ${JSON.stringify(i)}`;throw new Error(t)}return e},createInternalModel:(t,e,i)=>new vt(t,e,i),createPose:(t,e)=>new It(t,e),createPhysics:(t,e)=>new bt(t,e)}),t.CubismLegacyExpressionManager=pt,t.CubismLegacyInternalModel=vt,t.CubismLegacyModelSettings=N,t.CubismLegacyMotionManager=mt,t.CubismLegacyParallelMotionManager=Mt,t.ExpressionManager=M,t.FileLoader=Y,t.FocusController=v,t.InternalModel=R,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DExpression=ct,t.Live2DEyeBlink=yt,t.Live2DFactory=J,t.Live2DLoader=k,t.Live2DModel=dt,t.Live2DPhysics=bt,t.Live2DPose=It,t.Live2DTransform=st,t.MBToByte=function(t){return 1024*t*1024},t.ModelSettings=E,t.MotionManager=F,t.MotionPreloadStrategy=_,t.MotionPriority=P,t.MotionState=b,t.SoundManager=L,t.VERSION="1.0.0",t.VOLUME=I,t.XHRLoader=S,t.ZipLoader=q,t.applyMixins=function(t,e){e.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i))})})},t.clamp=h,t.config=a,t.copyArray=c,t.copyProperty=u,t.folderName=p,t.logger=l,t.normalizeHitAreaDefs=A,t.rand=d,t.remove=g,t.resolveURL=f,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("pixi.js"),require("@pixi/sound")):"function"==typeof define&&define.amd?define(["exports","pixi.js","@pixi/sound"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).PIXI=t.PIXI||{},t.PIXI.live2d=t.PIXI.live2d||{}),t.PIXI,t.PIXI)}(this,function(t,e,i){"use strict";var s=Object.defineProperty,r=Math.pow,n=(t,e,i)=>((t,e,i)=>e in t?s(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i)(t,"symbol"!=typeof e?e+"":e,i),o=(t,e,i)=>new Promise((s,r)=>{var n=t=>{try{a(i.next(t))}catch(e){r(e)}},o=t=>{try{a(i.throw(t))}catch(e){r(e)}},a=t=>t.done?s(t.value):Promise.resolve(t.value).then(n,o);a((i=i.apply(t,e)).next())});const a={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"}))},l={log(t,...e){a.logLevel<=a.LOG_LEVEL_VERBOSE&&console.log(`[${t}]`,...e)},warn(t,...e){a.logLevel<=a.LOG_LEVEL_WARNING&&console.warn(`[${t}]`,...e)},error(t,...e){a.logLevel<=a.LOG_LEVEL_ERROR&&console.error(`[${t}]`,...e)}};function h(t,e,i){return t<e?e:t>i?i:t}function d(t,e){return Math.random()*(e-t)+t}function u(t,e,i,s,r){const n=e[s];null!==n&&typeof n===t&&(i[r]=n)}function c(t,e,i,s,r){const n=e[s];Array.isArray(n)&&(i[r]=n.filter(e=>null!==e&&typeof e===t))}function p(t){let e=t.lastIndexOf("/");return-1!=e&&(t=t.slice(0,e)),e=t.lastIndexOf("/"),-1!==e&&(t=t.slice(e+1)),t}function g(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}const m=/^[a-zA-Z][a-zA-Z0-9+.-]*:/;function f(t,e){if(!e)return t;if(m.test(e))return e;if(e.startsWith("/"))return m.test(t)?new URL(e,t).toString():e;if(m.test(t))return new URL(e,t).toString();const i="http://example.com",s=t.startsWith("/")?i+t:`${i}/${t}`,r=new URL(e,s);let n=r.pathname+r.search+r.hash;return!t.startsWith("/")&&n.startsWith("/")&&(n=n.slice(1)),n}class M extends e.EventEmitter{constructor(t,e){super(),n(this,"expressionDataType","json"),n(this,"tag"),n(this,"settings"),n(this,"expressions",[]),n(this,"defaultExpression"),n(this,"currentExpression"),n(this,"reserveExpressionIndex",-1),n(this,"destroyed",!1),this.settings=t,this.tag=`ExpressionManager(${t.name})`}init(){this.defaultExpression=this.createDefaultExpression(),this.currentExpression=this.defaultExpression,this.stopAllExpressions()}createDefaultExpression(){return this.createExpression({},void 0)}loadExpression(t){return o(this,null,function*(){if(!this.definitions[t])return void l.warn(this.tag,`Undefined expression at [${t}]`);if(null===this.expressions[t])return void l.warn(this.tag,`Cannot set expression at [${t}] because it's already failed in loading.`);if(this.expressions[t])return this.expressions[t];const e=yield this._loadExpression(t);return this.expressions[t]=e,e})}_loadExpression(t){throw new Error("Not implemented.")}setRandomExpression(){return o(this,null,function*(){if(this.definitions.length){const t=[];for(let e=0;e<this.definitions.length;e++)null!==this.expressions[e]&&this.expressions[e]!==this.currentExpression&&e!==this.reserveExpressionIndex&&t.push(e);if(t.length){const e=Math.floor(Math.random()*t.length);return this.setExpression(e)}}return!1})}resetExpression(){this._setExpression(this.defaultExpression)}restoreExpression(){this._setExpression(this.currentExpression)}setExpression(t){return o(this,null,function*(){if("number"!=typeof t&&(t=this.getExpressionIndex(t)),!(t>-1&&t<this.definitions.length))return!1;if(t===this.expressions.indexOf(this.currentExpression))return!1;this.reserveExpressionIndex=t;const e=yield this.loadExpression(t);return!(!e||this.reserveExpressionIndex!==t)&&(this.reserveExpressionIndex=-1,this.currentExpression=e,this._setExpression(e),!0)})}update(t,e){return!this.isFinished()&&this.updateParameters(t,e)}destroy(){this.destroyed=!0,this.emit("destroy");this.definitions=void 0,this.expressions=void 0}}const y=40/7.5,x=1/150;class v{constructor(){n(this,"targetX",0),n(this,"targetY",0),n(this,"x",0),n(this,"y",0),n(this,"vx",0),n(this,"vy",0)}focus(t,e,i=!1){this.targetX=h(t,-1,1),this.targetY=h(e,-1,1),i&&(this.x=this.targetX,this.y=this.targetY)}update(t){const e=this.targetX-this.x,i=this.targetY-this.y;if(Math.abs(e)<.01&&Math.abs(i)<.01)return;const s=Math.sqrt(r(e,2)+r(i,2)),n=y/(1e3/t);let o=n*(e/s)-this.vx,a=n*(i/s)-this.vy;const l=Math.sqrt(r(o,2)+r(a,2)),h=n*x*t;l>h&&(o*=h/l,a*=h/l),this.vx+=o,this.vy+=a;const d=Math.sqrt(r(this.vx,2)+r(this.vy,2)),u=.5*(Math.sqrt(r(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 E{constructor(t){n(this,"json"),n(this,"name"),n(this,"url"),n(this,"pose"),n(this,"physics"),this.json=t,this.url=t.url,this.name=p(this.url)}normalizeName(){this.name&&"name"!==this.name.toLowerCase()||(this.name=p(this.url))}setModelName(...t){for(const e of t){const t="string"==typeof e?e.trim():"";if(t&&"name"!==t.toLowerCase())return void(this.name=t)}this.normalizeName()}getFileStem(t){if(!t)return;const e=t.split(/[/\\]/).filter(Boolean).pop();return null==e?void 0:e.replace(/\.[^.]+$/,"")}resolveURL(t){return f(this.url,t)}replaceFiles(t){this.moc=t(this.moc,"moc"),void 0!==this.pose&&(this.pose=t(this.pose,"pose")),void 0!==this.physics&&(this.physics=t(this.physics,"physics"));for(let e=0;e<this.textures.length;e++)this.textures[e]=t(this.textures[e],`textures[${e}]`)}getDefinedFiles(){const t=[];return this.replaceFiles(e=>(t.push(e),e)),t}validateFiles(t){const e=(e,i)=>{const s=this.resolveURL(e);if(!t.includes(s)){if(i)throw new Error(`File "${e}" is defined in settings, but doesn't exist in given files`);return!1}return!0};[this.moc,...this.textures].forEach(t=>e(t,!0));return this.getDefinedFiles().filter(t=>e(t,!1))}}var P=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(P||{});class b{constructor(){n(this,"tag"),n(this,"debug",!1),n(this,"currentPriority",0),n(this,"reservePriority",0),n(this,"currentGroup"),n(this,"currentIndex"),n(this,"reservedGroup"),n(this,"reservedIndex"),n(this,"reservedIdleGroup"),n(this,"reservedIdleIndex")}reserve(t,e,i){if(i<=0)return l.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(t===this.currentGroup&&e===this.currentIndex)return l.log(this.tag,"Motion is already playing.",this.dump(t,e)),!1;if(t===this.reservedGroup&&e===this.reservedIndex||t===this.reservedIdleGroup&&e===this.reservedIdleIndex)return l.log(this.tag,"Motion is already reserved.",this.dump(t,e)),!1;if(1===i){if(0!==this.currentPriority)return l.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,e)),!1;if(void 0!==this.reservedIdleGroup)return l.log(this.tag,"Cannot start idle motion because another idle motion has reserved.",this.dump(t,e)),!1;this.setReservedIdle(t,e)}else{if(i<3){if(i<=this.currentPriority)return l.log(this.tag,"Cannot start motion because another motion is playing as an equivalent or higher priority.",this.dump(t,e)),!1;if(i<=this.reservePriority)return l.log(this.tag,"Cannot start motion because another motion has reserved as an equivalent or higher priority.",this.dump(t,e)),!1}this.setReserved(t,e,i)}return!0}start(t,e,i,s){if(1===s){if(this.setReservedIdle(void 0,void 0),0!==this.currentPriority)return l.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(e,i)),!1}else{if(e!==this.reservedGroup||i!==this.reservedIndex)return l.log(this.tag,"Cannot start motion because another motion has taken the place.",this.dump(e,i)),!1;this.setReserved(void 0,void 0,0)}return!!t&&(this.setCurrent(e,i,s),!0)}complete(){this.setCurrent(void 0,void 0,0)}setCurrent(t,e,i){this.currentPriority=i,this.currentGroup=t,this.currentIndex=e}setReserved(t,e,i){this.reservePriority=i,this.reservedGroup=t,this.reservedIndex=e}setReservedIdle(t,e){this.reservedIdleGroup=t,this.reservedIdleIndex=e}isActive(t,e){return t===this.currentGroup&&e===this.currentIndex||t===this.reservedGroup&&e===this.reservedIndex||t===this.reservedIdleGroup&&e===this.reservedIdleIndex}reset(){this.setCurrent(void 0,void 0,0),this.setReserved(void 0,void 0,0),this.setReservedIdle(void 0,void 0)}shouldRequestIdleMotion(){return void 0===this.currentGroup&&void 0===this.reservedIdleGroup}shouldOverrideExpression(){return!a.preserveExpressionOnMotion&&this.currentPriority>1}dump(t,e){if(this.debug){return`\n<Requested> group = "${t}", index = ${e}\n`+["currentPriority","reservePriority","currentGroup","currentIndex","reservedGroup","reservedIndex","reservedIdleGroup","reservedIdleIndex"].map(t=>"["+t+"] "+this[t]).join("\n")}return""}}const w="SoundManager",I=.5;i.sound.disableAutoPause=!0;class L{static get volume(){return this._volume}static set volume(t){this._volume=(t>1?1:t<0?0:t)||0,this.audios.forEach(t=>t.volume=this._volume)}static add(t,e){return o(this,null,function*(){try{const e=new Promise((e,s)=>{const r=i.Sound.from({url:t,volume:this._volume,preload:!0,loaded:()=>{r.media instanceof i.webaudio.WebAudioMedia||s(new Error(`Error: ${t} is not WebAudioMedia`)),e(r)}})});return yield e}catch(s){return l.warn(w,`Error occurred on "${t}"`,s),null==e||e(s),null}})}static play(t,e){t.play({singleInstance:!0,complete:()=>{null==e||e(),t.destroy()}})}static addAnalyzer(t,e){const i=t.media,s=e.createBufferSource();s.buffer=i.buffer;const r=e.createAnalyser();return r.fftSize=a.fftSize,r.minDecibels=-90,r.maxDecibels=-10,r.smoothingTimeConstant=.85,s.connect(r),s.start(0),this.analysers.push(r),r}static analyze(t){if(!t)return parseFloat(Math.random().toFixed(1));const e=new Float32Array(t.fftSize);t.getFloatTimeDomainData(e);let i=0;for(let a=0;a<e.length;a++)i+=r(e[a],2);const s=Math.sqrt(i/e.length),n=20*Math.log10(s||r(10,-5)),o=Math.min(Math.max((n-t.minDecibels)/(t.maxDecibels-t.minDecibels),0),1);return parseFloat(o.toFixed(1))}static dispose(t){t.pause(),g(this.audios,t)}static destroy(){for(let t=this.contexts.length-1;t>=0;t--){const e=this.contexts[t];null==e||e.close().catch(t=>{l.warn(w,"Failed to close AudioContext.",t)})}for(let t=this.audios.length-1;t>=0;t--)this.dispose(this.audios[t])}}n(L,"audios",[]),n(L,"analysers",[]),n(L,"contexts",[]),n(L,"_volume",I);var _=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(_||{});class A extends e.EventEmitter{constructor(t){super(),n(this,"tag"),n(this,"settings"),n(this,"motionGroups",{}),n(this,"state",new b),n(this,"currentAudio"),n(this,"currentAnalyzer"),n(this,"currentContext"),n(this,"playing",!1),n(this,"destroyed",!1),n(this,"parent"),this.settings=t.settings,this.tag=`MotionManager(${this.settings.name})`,this.state.tag=this.tag,this.parent=t}init(t){(null==t?void 0:t.idleMotionGroup)&&(this.groups.idle=t.idleMotionGroup),this.setupMotions(t),this.stopAllMotions()}setupMotions(t){if(!this.definitions)return void l.warn(this.tag,"Motion definitions are not initialized.");for(const i of Object.keys(this.definitions))this.motionGroups[i]=[];let e;switch(null==t?void 0:t.motionPreload){case"NONE":return;case"ALL":e=Object.keys(this.definitions);break;default:e=[this.groups.idle]}for(const i of e){const t=this.definitions[i];if(t)for(let e=0;e<t.length;e++)this.loadMotion(i,e)}}loadMotion(t,e){return o(this,null,function*(){var i,s;if(this.destroyed)return;if(!this.getMotionDefinition(t,e))return;const r=null!=(s=(i=this.motionGroups)[t])?s:i[t]=[];if(null===r[e])return void l.warn(this.tag,`Cannot start motion at "${t}"[${e}] because it's already failed in loading.`);if(r[e])return r[e];const n=yield this._loadMotion(t,e);return this.destroyed?void 0:(r[e]=null!=n?n:null,n)})}_loadMotion(t,e){throw new Error("Not implemented.")}initializeAudio(t,e){this.currentAudio=t,L.volume=e,this.currentContext=t.context.audioContext,this.currentAnalyzer=L.addAnalyzer(this.currentAudio,this.currentContext)}speak(t){return o(this,arguments,function*(t,{volume:e=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:n}={}){if(!a.sound)return!1;let o,h;if(this.currentAudio&&this.currentAudio.isPlaying)return!1;const d=t&&t.startsWith("data:");if(t&&!d){const e=document.createElement("a");e.href=t,h=t=e.href}else h="data:audio/";const u=t;if(u)try{o=yield L.add(u,(t,e=this)=>{l.error(this.tag,"Error during audio playback:",t),null==n||n(t),s&&i&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),this.initializeAudio(o,e)}catch(c){return l.warn(this.tag,"Failed to create audio",h,c),!1}if(o){let t=!0;try{a.motionSync&&L.play(o,()=>{null==r||r(),s&&i&&this.expressionManager&&this.expressionManager.resetExpression(),this.currentAudio=void 0})}catch(c){l.warn(this.tag,"Failed to play audio",o.url,c),t=!1}if(!t)return!1}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),i&&this.expressionManager&&(yield this.expressionManager.setExpression(i)),this.playing=!0,!0})}startMotion(t,e){return o(this,arguments,function*(t,e,i=P.NORMAL,{sound:s,volume:r=.5,expression:n,resetExpression:o=!0,onFinish:h,onError:d,ignoreParamIds:u=[]}={}){if(this.destroyed)return!1;if(!this.state.reserve(t,e,i))return!1;if(this.currentAudio&&this.currentAudio.isPlaying&&i!=P.FORCE)return!1;const c=this.getMotionDefinition(t,e);if(!c)return!1;let p,g;this.currentAudio&&L.dispose(this.currentAudio);const m=s&&s.startsWith("data:");if(s&&!m){const t=document.createElement("a");t.href=s,g=s=t.href}else g=this.getSoundFile(c),g&&(g=this.settings.resolveURL(g));const f=g;if(f)try{p=yield L.add(f,(t,e=this)=>{l.error(this.tag,"Error during audio playback:",t),null==d||d(t),o&&n&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),this.initializeAudio(p,r)}catch(y){l.warn(this.tag,"Failed to create audio",g,y)}const M=yield this.loadMotion(t,e);if(p&&a.motionSync)try{L.play(p,(t=this)=>{null==h||h(),o&&n&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0})}catch(y){l.warn(this.tag,"Failed to play audio",p.url,y)}return this.state.start(M,t,e,i)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),l.log(this.tag,"Start motion:",this.getMotionName(c)),this.emit("motionStart",t,e,p),n&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(n)),this.playing=!0,M&&this._startMotion(M,void 0,u),!0):(p&&(L.dispose(p),this.currentAudio=void 0),!1)})}startRandomMotion(t,e){return o(this,arguments,function*(t,e,{sound:i,volume:s=.5,expression:r,resetExpression:n=!0,onFinish:o,onError:a}={}){var l,h;if(this.destroyed)return!1;const d=null==(l=this.definitions)?void 0:l[t];if(null==d?void 0:d.length){const l=[],u=null!=(h=this.motionGroups[t])?h:[];for(let e=0;e<d.length;e++)null===u[e]||this.state.isActive(t,e)||l.push(e);if(l.length){const h=l[Math.floor(Math.random()*l.length)];return this.startMotion(t,h,e,{sound:i,volume:s,expression:r,resetExpression:n,onFinish:o,onError:a})}}return!1})}stopSpeaking(){this.currentAudio&&(L.dispose(this.currentAudio),this.currentAudio=void 0)}stopAllMotions(){this._stopAllMotions(),this.state.reset(),this.stopSpeaking()}update(t,e){var i;return this.isFinished()&&(this.playing&&(this.playing=!1,this.emit("motionFinish")),this.state.shouldOverrideExpression()&&(null==(i=this.expressionManager)||i.restoreExpression()),this.state.complete(),this.state.shouldRequestIdleMotion()&&this.startRandomMotion(this.groups.idle,P.IDLE)),this.updateParameters(t,e)}mouthSync(){return this.currentAnalyzer?L.analyze(this.currentAnalyzer):0}destroy(){var t;this.destroyed=!0,this.emit("destroy"),this.stopAllMotions(),null==(t=this.expressionManager)||t.destroy();this.definitions=void 0,this.motionGroups=void 0}getMotionAndApplyExpression(t,e,i){return o(this,null,function*(){if(this.destroyed)return null;if(!this.state.reserve(t,e,P.FORCE))return null;const s=this.getMotionDefinition(t,e);if(!s)return null;this.currentAudio&&L.dispose(this.currentAudio);const r=yield this.loadMotion(t,e);return this.state.start(r,t,e,P.FORCE)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),l.log(this.tag,"Start motion:",this.getMotionName(s)),this.emit("motionStart",t,e,void 0),i&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(i)),r):null})}getMotionDefinition(t,e){var i,s;const r=null==(s=null==(i=this.definitions)?void 0:i[t])?void 0:s[e];return r||l.warn(this.tag,`Undefined motion at "${t}"[${e}]`),r}}function F(t,e){if(!Array.isArray(t))return[];const i=[];for(const s of t){if(!s||"object"!=typeof s)continue;const t=s,r="string"==typeof t.id?t.id:"string"==typeof t.Id?t.Id:void 0,n="string"==typeof t.name?t.name:"string"==typeof t.Name?t.Name:void 0;r&&n&&i.push({id:r,name:n,index:e(r)})}return i}const O={x:0,y:0,width:0,height:0};class R extends e.EventEmitter{constructor(){super(...arguments),n(this,"focusController",new v),n(this,"pose"),n(this,"physics"),n(this,"originalWidth",0),n(this,"originalHeight",0),n(this,"width",0),n(this,"height",0),n(this,"localTransform",new e.Matrix),n(this,"drawingMatrix",new e.Matrix),n(this,"hitAreas",{}),n(this,"textureFlipY",!1),n(this,"viewport",[0,0,0,0]),n(this,"destroyed",!1)}init(){this.setupLayout(),this.setupHitAreas()}setupLayout(){const t=this,e=this.getSize();t.originalWidth=e[0],t.originalHeight=e[1];const i=Object.assign({width:2,height:2},this.getLayout());this.localTransform.scale(i.width/2,i.height/2),t.width=this.originalWidth*this.localTransform.a,t.height=this.originalHeight*this.localTransform.d;const s=void 0!==i.x&&i.x-i.width/2||void 0!==i.centerX&&i.centerX||void 0!==i.left&&i.left-i.width/2||void 0!==i.right&&i.right+i.width/2||0,r=void 0!==i.y&&i.y-i.height/2||void 0!==i.centerY&&i.centerY||void 0!==i.top&&i.top-i.height/2||void 0!==i.bottom&&i.bottom+i.height/2||0;this.localTransform.translate(this.width*s,-this.height*r)}setupHitAreas(){const t=this.getHitAreaDefs();this.hitAreas={};for(const e of t)e.name&&(this.hitAreas[e.name]=e)}hitTest(t,e){return Object.keys(this.hitAreas).filter(i=>this.isHit(i,t,e))}isHit(t,e,i){const s=this.hitAreas[t];if(!s)return!1;let r=s.index;if(r<0){if(!s.id)return!1;if(r=this.getDrawableIndex(s.id),r<0)return!1;s.index=r}const n=this.getDrawableBounds(r,O);return n.x<=e&&e<=n.x+n.width&&n.y<=i&&i<=n.y+n.height}getDrawableBounds(t,e){const i=this.getDrawableVertices(t);let s=i[0],r=i[0],n=i[1],o=i[1];for(let a=0;a<i.length;a+=2){const t=i[a],e=i[a+1];s=Math.min(t,s),r=Math.max(t,r),n=Math.min(e,n),o=Math.max(e,o)}return null!=e||(e={}),e.x=s,e.y=n,e.width=r-s,e.height=o-n,e}updateTransform(t){this.drawingMatrix.copyFrom(t).append(this.localTransform)}update(t,e){this.focusController.update(t)}destroy(){this.destroyed=!0,this.emit("destroy"),this.motionManager.destroy(),this.motionManager=void 0,this.parallelMotionManager.forEach(t=>t.destroy()),this.parallelMotionManager=[]}updateMotions(t,e){this.emit("beforeMotionUpdate");const i=this.motionManager.update(t,e),s=this.parallelMotionManager.map(i=>i.update(t,e)),r=i||s.reduce((t,e)=>t||e,!1);return this.emit("afterMotionUpdate"),r}}class T extends Error{constructor(t,e,i,s=!1){super(t),this.url=e,this.status=i,this.aborted=s}}const D=class t{static createXHR(e,i,s,r,n){const o=new XMLHttpRequest;if(t.allXhrSet.add(o),e){let i=t.xhrMap.get(e);i?i.add(o):(i=new Set([o]),t.xhrMap.set(e,i))}return o.open("GET",i),o.responseType=s,o.onload=()=>{var t;200!==o.status&&0!==o.status||!o.response?null==(t=o.onerror)||t.call(o,new ProgressEvent("error")):r(o.response)},o.onerror=()=>{l.warn("XHRLoader",`Failed to load resource as ${o.responseType} (Status ${o.status}): ${i}`),n(new T("Network error.",i,o.status))},o.onabort=()=>n(new T("Aborted.",i,o.status,!0)),o.onloadend=()=>{var i;t.allXhrSet.delete(o),e&&(null==(i=t.xhrMap.get(e))||i.delete(o))},o}static cancelXHRs(){var e;null==(e=t.xhrMap.get(this))||e.forEach(e=>{e.abort(),t.allXhrSet.delete(e)}),t.xhrMap.delete(this)}static release(){t.allXhrSet.forEach(t=>t.abort()),t.allXhrSet.clear(),t.xhrMap=new WeakMap}};n(D,"xhrMap",new WeakMap),n(D,"allXhrSet",new Set),n(D,"loader",t=>new Promise((e,i)=>{const s=t.target,r=t.target&&"function"==typeof D.cancelXHRs?D.cancelXHRs.bind(t.target):void 0,n=D.createXHR(t.target,t.settings?t.settings.resolveURL(t.url):t.url,t.type,i=>{t.result=i,e()},i);if(t.target&&r&&"function"==typeof s.listeners&&"function"==typeof s.once){const t=s.listeners("destroy");Array.isArray(t)&&t.includes(r)||s.once("destroy",r)}n.send()}));let S=D;function C(t,e){let i=-1;return function s(r,n){if(n)return Promise.reject(n);if(r<=i)return Promise.reject(new Error("next() called multiple times"));i=r;const o=t[r];if(!o)return Promise.resolve();try{return Promise.resolve(o(e,s.bind(null,r+1)))}catch(a){const t=a instanceof Error?a:new Error(String(a));return Promise.reject(t)}}(0)}class k{static load(t){return o(this,null,function*(){return yield C(this.middlewares,t),t.result})}}n(k,"middlewares",[S.loader]);class N extends E{constructor(t){if(super(t),n(this,"moc"),n(this,"textures"),n(this,"layout"),n(this,"hitAreas"),n(this,"initParams"),n(this,"initOpacities"),n(this,"expressions"),n(this,"motions",{}),!N.isValidJSON(t))throw new TypeError("Invalid JSON.");this.moc=t.model,c("string",t,this,"textures","textures"),this.copy(t)}static isValidJSON(t){if(!t||"object"!=typeof t)return!1;const e=!!Array.isArray(t.textures)&&t.textures.every(t=>"string"==typeof t);return"string"==typeof t.model&&e}copy(t){u("string",t,this,"name","name"),u("string",t,this,"pose","pose"),u("string",t,this,"physics","physics"),u("object",t,this,"layout","layout"),u("object",t,this,"motions","motions"),c("object",t,this,"hit_areas","hitAreas"),c("object",t,this,"expressions","expressions"),c("object",t,this,"init_params","initParams"),c("object",t,this,"init_opacities","initOpacities");const e=this.getFileStem(this.moc);this.setModelName(this.name,e)}replaceFiles(t){super.replaceFiles(t);for(const[e,i]of Object.entries(this.motions))for(let s=0;s<i.length;s++)i[s].file=t(i[s].file,`motions.${e}[${s}].file`),void 0!==i[s].sound&&(i[s].sound=t(i[s].sound,`motions.${e}[${s}].sound`));if(this.expressions)for(let e=0;e<this.expressions.length;e++)this.expressions[e].file=t(this.expressions[e].file,`expressions[${e}].file`)}}function G(){}const j="Live2DFactory",U=(t,e)=>o(null,null,function*(){if("string"==typeof t.source){const e=yield k.load({url:t.source,type:"json",target:t.live2dModel});e.url="string"==typeof e.url?e.url:t.source,t.source=e,t.live2dModel.emit("settingsJSONLoaded",e)}return e()}),H=(t,e)=>o(null,null,function*(){if(t.source instanceof E)return t.settings=t.source,e();if("object"==typeof t.source){const i=Z.findRuntime(t.source);if(i){const s=i.createModelSettings(t.source);return t.settings=s,t.live2dModel.emit("settingsLoaded",s),e()}}const i=t.source&&"string"==typeof t.source.url?t.source.url:void 0,s=Z.runtimes.map(t=>t.version).join(", ");if(0===Z.runtimes.length)throw new TypeError(["Unknown settings format: no Live2D runtimes registered.",'Import a published runtime entry before loading models (e.g. "<package>/cubism" for Cubism 3/4/5, "<package>/cubism-legacy" for Cubism 2).',i?`Settings URL: ${i}`:void 0].filter(Boolean).join("\n"));const r=(()=>{try{if(!t.source||"object"!=typeof t.source||Array.isArray(t.source))return;return Object.keys(t.source).slice(0,30).join(", ")}catch(e){return}})();throw new TypeError(["Unknown settings format: no matching runtime found for the loaded settings JSON.",s?`Registered runtimes (versions): ${s}`:void 0,r?`Settings JSON keys: ${r}`:void 0,i?`Settings URL: ${i}`:void 0].filter(Boolean).join("\n"))}),X=(t,e)=>{if(t.settings){const i=Z.findRuntime(t.settings);if(i)return i.ready().then(()=>e())}return e()},B=(t,e)=>o(null,null,function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=Z.findRuntime(e);if(s){const r=[],n=e instanceof N?"json":"arraybuffer";e.pose&&r.push(k.load({settings:e,url:e.pose,type:n,target:i}).then(e=>{i.pose=s.createPose(i.coreModel,e),t.live2dModel.emit("poseLoaded",i.pose)}).catch(e=>{t.live2dModel.emit("poseLoadError",e),l.warn(j,"Failed to load pose.",e)})),e.physics&&r.push(k.load({settings:e,url:e.physics,type:n,target:i}).then(e=>{i.physics=s.createPhysics(i.coreModel,e),t.live2dModel.emit("physicsLoaded",i.physics)}).catch(e=>{t.live2dModel.emit("physicsLoadError",e),l.warn(j,"Failed to load physics.",e)})),r.length&&(yield Promise.all(r))}}}),W=(t,i)=>o(null,null,function*(){if(!t.settings)throw new TypeError("Missing settings.");{const s=t.live2dModel,r={crossOrigin:t.options.crossOrigin};t.settings instanceof N&&(r.preferCreateImageBitmap=!1);const n=Promise.all(t.settings.textures.map(i=>function(t,i={}){const s=e.loadTextures.config,r=null==s?void 0:s.crossOrigin,n=null==s?void 0:s.preferCreateImageBitmap,o=null==s?void 0:s.preferWorkers;return void 0!==i.crossOrigin&&s&&(s.crossOrigin=i.crossOrigin),!1===i.preferCreateImageBitmap&&s&&(s.preferCreateImageBitmap=!1,s.preferWorkers=!1),e.Assets.load(t).catch(t=>{if(t instanceof Error)throw t;throw new Error("Texture loading error",{cause:t})}).finally(()=>{s&&(s.crossOrigin=null!=r?r:s.crossOrigin,!1===i.preferCreateImageBitmap&&(s.preferCreateImageBitmap=null!=n?n:s.preferCreateImageBitmap,s.preferWorkers=null!=o?o:s.preferWorkers))})}(t.settings.resolveURL(i),r)));if(n.catch(G),yield i(),!t.internalModel)throw new TypeError("Missing internal model.");s.internalModel=t.internalModel,s.emit("modelLoaded",t.internalModel),s.textures=yield n,s.emit("textureLoaded",s.textures)}}),$=(t,e)=>o(null,null,function*(){const i=t.settings;if(i instanceof E){const s=Z.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield k.load({settings:i,url:i.moc,type:"arraybuffer",target:t.live2dModel});if(!s.isValidMoc(r))throw new Error("Invalid moc data");const n=s.createCoreModel(r);return t.internalModel=s.createInternalModel(n,i,t.options),e()}throw new TypeError("Missing settings.")}),z=class t{static unzip(e,i){return o(this,null,function*(){const s=yield t.getFilePaths(e),r=[];for(const t of i.getDefinedFiles()){const e=decodeURI(f(i.url,t));s.includes(e)&&r.push(e)}const n=yield t.getFiles(e,r);for(let t=0;t<n.length;t++){const e=r[t],i=n[t];Object.defineProperty(i,"webkitRelativePath",{value:e})}return n})}static createSettings(e){return o(this,null,function*(){const i=(yield t.getFilePaths(e)).find(t=>t.endsWith("model.json")||t.endsWith("model3.json"));if(!i)throw new Error("Settings file not found");const s=yield t.readText(e,i);if(!s)throw new Error("Empty settings file: "+i);const r=JSON.parse(s);r.url=i;const n=t.live2dFactory.findRuntime(r);if(!n)throw new Error("Unknown settings JSON");return n.createModelSettings(r)})}static zipReader(t,e){return Promise.reject(new Error("Not implemented"))}static getFilePaths(t){return Promise.reject(new Error("Not implemented"))}static getFiles(t,e){return Promise.reject(new Error("Not implemented"))}static readText(t,e){return Promise.reject(new Error("Not implemented"))}static releaseReader(t){}};n(z,"live2dFactory"),n(z,"ZIP_PROTOCOL","zip://"),n(z,"uid",0),n(z,"factory",(t,e)=>o(null,null,function*(){const i=t.source;let s,r,n;if("string"==typeof i&&(i.endsWith(".zip")||i.startsWith(z.ZIP_PROTOCOL))?(s=i.startsWith(z.ZIP_PROTOCOL)?i.slice(z.ZIP_PROTOCOL.length):i,r=yield k.load({url:s,type:"blob",target:t.live2dModel})):Array.isArray(i)&&1===i.length&&i[0]instanceof File&&i[0].name.endsWith(".zip")&&(r=i[0],s=URL.createObjectURL(r),n=i.settings),r){if(!r.size)throw new Error("Empty zip file");const e=yield z.zipReader(r,s);n||(n=yield z.createSettings(e)),n._objectURL=z.ZIP_PROTOCOL+z.uid+"/"+n.url;const i=yield z.unzip(e,n);i.settings=n,t.source=i,s.startsWith("blob:")&&t.live2dModel.once("modelLoaded",t=>{t.once("destroy",function(){URL.revokeObjectURL(s)})}),z.releaseReader(e)}return e()}));let q=z;const V=class t{static resolveURL(e,i){var s;const r=null==(s=t.filesMap[e])?void 0:s[i];if(void 0===r)throw new Error("Cannot find this file from uploaded files: "+i);return r}static upload(e,i){const s={};for(const t of i.getDefinedFiles()){const r=decodeURI(f(i.url,t)),n=e.find(t=>t.webkitRelativePath===r);n&&(s[t]=URL.createObjectURL(n))}t.filesMap[i._objectURL]=s}static createSettings(e){return o(this,null,function*(){const i=e.find(t=>t.name.endsWith("model.json")||t.name.endsWith("model3.json"));if(!i)throw new TypeError("Settings file not found");const s=yield t.readText(i),r=JSON.parse(s);r.url=i.webkitRelativePath;const n=Z.findRuntime(r);if(!n)throw new Error("Unknown settings JSON");const o=n.createModelSettings(r);return o._objectURL=URL.createObjectURL(i),o})}static readText(t){return o(this,null,function*(){return new Promise((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")})})}};n(V,"live2dFactory"),n(V,"filesMap",{}),n(V,"factory",(t,e)=>o(null,null,function*(){if(Array.isArray(t.source)&&t.source[0]instanceof File){const e=t.source;let i=e.settings;if(i){if(!i._objectURL)throw new Error('"_objectURL" must be specified in ModelSettings')}else i=yield V.createSettings(e);i.validateFiles(e.map(t=>encodeURI(t.webkitRelativePath))),V.upload(e,i),i.resolveURL=function(t){return V.resolveURL(this._objectURL,t)},t.source=i,t.live2dModel.once("modelLoaded",t=>{t.once("destroy",function(){const t=this.settings._objectURL;if(URL.revokeObjectURL(t),V.filesMap[t])for(const e of Object.values(V.filesMap[t]))URL.revokeObjectURL(e);delete V.filesMap[t]})})}return e()}));let Y=V;const J=class t{static registerRuntime(e){t.runtimes.push(e),t.runtimes.sort((t,e)=>e.version-t.version)}static findRuntime(e){for(const i of t.runtimes)if(i.test(e))return i}static setupLive2DModel(e,i,s){return o(this,null,function*(){const r=new Promise(t=>e.once("textureLoaded",t)),n=new Promise(t=>e.once("modelLoaded",t)),o=Promise.all([r,n]).then(()=>e.emit("ready"));yield C(t.live2DModelMiddlewares,{live2dModel:e,source:i,options:s||{}}),yield o,e.emit("load")})}static loadMotion(e,i,s){var r;const n=t=>e.emit("motionLoadError",i,s,t);try{const o=null==(r=e.definitions[i])?void 0:r[s];if(!o)return Promise.resolve(void 0);e.once("destroy",()=>t.releaseMotionTasks(e));let a=t.motionTasksMap.get(e);a||(a={},t.motionTasksMap.set(e,a));let h=a[i];h||(h=[],a[i]=h);const d=e.getMotionFile(o);return null!=h[s]||(h[s]=k.load({url:d,settings:e.settings,type:e.motionDataType,target:e}).then(r=>{var n;const a=null==(n=t.motionTasksMap.get(e))?void 0:n[i];a&&(a[s]=void 0);const l=r,h=e.createMotion(l,i,o);return e.emit("motionLoaded",i,s,h),h}).catch(t=>{l.warn(e.tag,`Failed to load motion: ${d}\n`,t),n(t)})),h[s]}catch(o){l.warn(e.tag,`Failed to load motion at "${i}"[${s}]\n`,o),n(o)}return Promise.resolve(void 0)}static loadExpression(e,i){var s;const r=t=>e.emit("expressionLoadError",i,t);try{const n=e.definitions[i];if(!n)return Promise.resolve(void 0);e.once("destroy",()=>t.releaseExpressionTasks(e));let o=t.expressionTasksMap.get(e);o||(o=[],t.expressionTasksMap.set(e,o));const a=e.getExpressionFile(n),h=null!=(s=e.expressionDataType)?s:"json";return null!=o[i]||(o[i]=k.load({url:a,settings:e.settings,type:h,target:e}).then(s=>{const r=t.expressionTasksMap.get(e);r&&(r[i]=void 0);const o=s,a=e.createExpression(o,n);return e.emit("expressionLoaded",i,a),a}).catch(t=>{l.warn(e.tag,`Failed to load expression: ${a}\n`,t),r(t)})),o[i]}catch(n){l.warn(e.tag,`Failed to load expression at [${i}]\n`,n),r(n)}return Promise.resolve(void 0)}static releaseMotionTasks(e){t.motionTasksMap.delete(e)}static releaseExpressionTasks(e){t.expressionTasksMap.delete(e)}};n(J,"runtimes",[]),n(J,"urlToJSON",U),n(J,"jsonToSettings",H),n(J,"waitUntilReady",X),n(J,"setupOptionals",B),n(J,"setupEssentials",W),n(J,"createInternalModel",$),n(J,"live2DModelMiddlewares",[q.factory,Y.factory,U,H,X,B,W,$]),n(J,"motionTasksMap",new WeakMap),n(J,"expressionTasksMap",new WeakMap);let Z=J;A.prototype._loadMotion=function(t,e){return Z.loadMotion(this,t,e)},M.prototype._loadExpression=function(t){return Z.loadExpression(this,t)},Y.live2dFactory=Z,q.live2dFactory=Z;const Q=class t{constructor(i,{autoUpdate:s=!0,autoHitTest:r=!0,autoFocus:o=!0,autoInteract:a,ticker:h}={}){var d;n(this,"model"),n(this,"destroyed",!1),n(this,"_ticker"),n(this,"_autoUpdate",!1),n(this,"_autoHitTest",!1),n(this,"_autoFocus",!1),null!=h||(h=null!=(d=t.defaultTicker)?d:"undefined"!=typeof PIXI?PIXI.Ticker.shared:e.Ticker.shared),void 0!==a&&(r=a,o=a,l.warn(i.tag,"options.autoInteract is deprecated since v0.5.0, use autoHitTest and autoFocus instead.")),this.model=i,this.ticker=h,this.autoUpdate=s,this.autoHitTest=r,this.autoFocus=o,(r||o)&&(this.model.eventMode="static")}get ticker(){return this._ticker}set ticker(t){var e,i;this._ticker&&this._ticker.remove(tt,this),this._ticker=t,this._autoUpdate&&(null==(e=this._ticker)||e.add(tt,this),null==(i=this._ticker)||i.start())}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){var e;this.destroyed||(t?this._ticker?(this._ticker.add(tt,this),this._autoUpdate=!0):l.warn(this.model.tag,"No Ticker to be used for automatic updates. Either set option.ticker when creating Live2DModel, or expose PIXI to global scope (window.PIXI = PIXI)."):(null==(e=this._ticker)||e.remove(tt,this),this._autoUpdate=!1))}get autoHitTest(){return this._autoHitTest}set autoHitTest(t){t!==this.autoHitTest&&(t?this.model.on("pointertap",et,this):this.model.off("pointertap",et,this),this._autoHitTest=t)}get autoFocus(){return this._autoFocus}set autoFocus(t){t!==this.autoFocus&&(t?(this.model.on("globalpointermove",it,this),this.model.on("pointermove",it,this)):(this.model.off("globalpointermove",it,this),this.model.off("pointermove",it,this)),this._autoFocus=t)}get autoInteract(){return this._autoHitTest&&this._autoFocus}set autoInteract(t){this.autoHitTest=t,this.autoFocus=t}onTickerUpdate(){const t=this.ticker.deltaMS;this.model.update(t)}onTap(t){this.model.tap(t.global.x,t.global.y)}onPointerMove(t){this.model.focus(t.global.x,t.global.y)}destroy(){this.autoFocus=!1,this.autoHitTest=!1,this.autoUpdate=!1,this.ticker=void 0,this.destroyed=!0}};n(Q,"defaultTicker");let K=Q;function tt(){this.onTickerUpdate()}function et(t){this.onTap(t)}function it(t){this.onPointerMove(t)}class st extends e.Transform{}const rt=new e.Point,nt=new e.Matrix,ot=new e.Matrix,at={x:0,y:0,width:0,height:0},lt=new e.Bounds;class ht{constructor(t){this.renderer=t}execute(t){!t.visible||t.alpha<=0||t.renderLive2D(this.renderer)}updateRenderable(){}destroy(){}}class dt extends e.Container{constructor(t){super(),n(this,"renderPipeId","live2d"),n(this,"tag","Live2DModel(uninitialized)"),n(this,"internalModel"),n(this,"textures",[]),n(this,"transform",new st),n(this,"anchor"),n(this,"_bounds",new e.Bounds),n(this,"_boundsDirty",!0),n(this,"_boundsRetryAfterDraw",!1),n(this,"gl",null),n(this,"elapsedTime",0),n(this,"deltaTime",0),n(this,"automator"),n(this,"currentGlId",0),n(this,"renderLive2D",t=>{var i,s,r,n,o;if(!(t instanceof e.WebGLRenderer))throw new Error("Renderer is not supported");t.geometry.resetState(),t.shader.resetState(),t.texture.resetState();let a=!1;this.gl!==t.gl&&(this.gl=t.gl,this.internalModel.updateWebGLContext(t.gl,this.generateUID()),a=!0);for(let e=0;e<this.textures.length;e++){const i=this.textures[e],s=Boolean(i.source._gpuData[t.uid]);!a&&s||(t.gl.pixelStorei(WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL,this.internalModel.textureFlipY),t.texture.bind(i,0)),this.internalModel.bindTexture(e,t.texture.getGlSource(i.source).texture)}const l=t.renderTarget.viewport,h=t.renderTarget.renderTarget;let d=l.y;if(null==h?void 0:h.isRoot){d=h.colorTexture.source.pixelHeight-l.height-l.y}this.internalModel.viewport=[l.x,d,l.width,l.height];const u=this.deltaTime;this.deltaTime=0,u&&this.internalModel.update(u,this.elapsedTime);const{projectionMatrix:c,offset:p}=t.globalUniforms.globalUniformData,g=ot.copyFrom(this.worldTransform);g.tx-=null!=(i=null==p?void 0:p.x)?i:0,g.ty-=null!=(s=null==p?void 0:p.y)?s:0;const m=nt.copyFrom(c).append(g);this.internalModel.updateTransform(m),this.internalModel.draw(t.gl),this._boundsRetryAfterDraw&&this.updateDrawableBounds(),t.state.resetState(),t.texture.resetState();const f=null==(r=t.renderTarget)?void 0:r.defaultClearColor,M=null==(o=null==(n=t.renderTarget)?void 0:n.adaptor)?void 0:o._clearColorCache;f&&(t.gl.clearColor(f[0],f[1],f[2],f[3]),M&&(M[0]=f[0],M[1]=f[1],M[2]=f[2],M[3]=f[3]))}),this.anchor=new e.ObservablePoint({_onUpdate:()=>this.onAnchorChange()},0,0),this.automator=new K(this,t),this.once("modelLoaded",()=>this.initializeOnModelLoad(t))}get isRenderable(){return!0}get canBundle(){return!1}static from(t,e){return o(this,null,function*(){const i=new this(e);return yield Z.setupLive2DModel(i,t,e),i})}static fromSync(t,e){const i=new this(e);return Z.setupLive2DModel(i,t,e).then(()=>{var t;return null==(t=null==e?void 0:e.onLoad)?void 0:t.call(e)}).catch(t=>{var i;return null==(i=null==e?void 0:e.onError)?void 0:i.call(e,t)}),i}static registerTicker(t){K.defaultTicker=t.shared}get bounds(){return this.internalModel?(this._boundsDirty&&this.updateDrawableBounds(),this._bounds):(this._bounds.set(0,0,0,0),this._bounds)}updateDrawableBounds(){if(!this.internalModel)return this._bounds.set(0,0,0,0),void(this._boundsDirty=!1);const t=this.internalModel.getDrawableIDs();lt.clear();for(let i=0;i<t.length;i++){const s=t[i],r=this.internalModel.getDrawableIndex(s);if(r<0)continue;const n=this.internalModel.getDrawableBounds(r,at);Number.isFinite(n.x)&&Number.isFinite(n.y)&&Number.isFinite(n.width)&&Number.isFinite(n.height)&&lt.addFrame(n.x,n.y,n.x+n.width,n.y+n.height,e.Matrix.IDENTITY)}if(this._bounds.clear(),lt.isValid&&lt.isPositive)this._bounds.addFrame(lt.minX,lt.minY,lt.maxX,lt.maxY,this.internalModel.localTransform),this._boundsRetryAfterDraw=!1;else{const t=this.internalModel.originalWidth||this.internalModel.width,e=this.internalModel.originalHeight||this.internalModel.height;this._bounds.addFrame(0,0,t,e,this.internalModel.localTransform),this._boundsRetryAfterDraw=!0}this._boundsDirty=!1}generateUID(){return++this.currentGlId}collectRenderables(t,e,i){var s,r,n,o;if(this.parentRenderLayer&&this.parentRenderLayer!==i)return;if(this.globalDisplayStatus<7)return;if(!this.includeInBuild)return;this.sortableChildren&&this.sortChildren(),function(t){const e=t;e.renderPipes.live2d||(e.renderPipes.live2d=new ht(t))}(e);const a=e.renderPipes,l=()=>{var e,i;null==(i=null==(e=a.batch)?void 0:e.break)||i.call(e,t),t.add(this)},h=()=>{const s=this.children,r=s.length;for(let n=0;n<r;n++)s[n].collectRenderables(t,e,i)},d=this.effects;if(d){for(let e=0;e<d.length;e++){const i=d[e],n=i.filters;if(n)for(const t of n)t&&"number"==typeof t.resolution&&1===t.resolution&&(t.resolution="inherit");null==(r=null==(s=a[i.pipe])?void 0:s.push)||r.call(s,i,this,t)}l(),h();for(let e=d.length-1;e>=0;e--){const i=d[e];null==(o=null==(n=a[i.pipe])?void 0:n.pop)||o.call(n,i,this,t)}}else l(),h()}initializeOnModelLoad(t){this.tag=`Live2DModel(${this.internalModel.settings.name})`,this.onAnchorChange(),this.updateDrawableBounds()}onAnchorChange(){this.internalModel&&this.pivot&&this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(t,e,i){return o(this,arguments,function*(t,e,i,{sound:s,volume:r=.5,expression:n,resetExpression:o=!0,onFinish:a,onError:l}={}){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i,{sound:s,volume:r,expression:n,resetExpression:o,onFinish:a,onError:l}):this.internalModel.motionManager.startMotion(t,e,i,{sound:s,volume:r,expression:n,resetExpression:o,onFinish:a,onError:l})})}motionLastFrame(t,e){return o(this,arguments,function*(t,e,{expression:i}={}){return this.internalModel.motionManager.motionLastFrame(t,e,{expression:i})})}parallelMotion(t){return o(this,null,function*(){this.internalModel.extendParallelMotionManager(t.length);const e=t.map((t,e)=>this.internalModel.parallelMotionManager[e].startMotion(t.group,t.index,t.priority)),i=[];for(const t of e)i.push(yield t);return i})}parallelLastFrame(t){return o(this,null,function*(){this.internalModel.extendParallelMotionManager(t.length);const e=t.map((t,e)=>this.internalModel.parallelMotionManager[e].playMotionLastFrame(t.group,t.index)),i=[];for(const t of e)i.push(yield t);return i})}stopMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(t,{volume:e=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:n}={}){return this.internalModel.motionManager.speak(t,{volume:e,expression:i,resetExpression:s,onFinish:r,onError:n})}stopSpeaking(){return this.internalModel.motionManager.stopSpeaking()}expression(t){return this.internalModel.motionManager.expressionManager?void 0===t?this.internalModel.motionManager.expressionManager.setRandomExpression():this.internalModel.motionManager.expressionManager.setExpression(t):Promise.resolve(!1)}focus(t,e,i=!1){rt.x=t,rt.y=e,this.toModelPosition(rt,rt,!0);const s=rt.x/this.internalModel.originalWidth*2-1,r=rt.y/this.internalModel.originalHeight*2-1,n=Math.atan2(r,s);this.internalModel.focusController.focus(Math.cos(n),-Math.sin(n),i)}tap(t,e){const i=this.hitTest(t,e);i.length&&this.emit("hit",i)}hitTest(t,e){return rt.x=t,rt.y=e,this.toModelPosition(rt,rt),this.internalModel.hitTest(rt.x,rt.y)}toModelPosition(t,e=t.clone(),i){return i||this.updateLocalTransform(),this.toLocal(t,void 0,e,i),this.internalModel.localTransform.applyInverse(e,e),e}containsPoint(t){return this.bounds.containsPoint(t.x,t.y)}_calculateBounds(){if(!this.internalModel)return void this.getBounds().set(0,0,0,0);const t=this.internalModel.width,e=this.internalModel.height;this.getBounds().addFrame(0,0,t,e,this.transform.matrix)}update(t){this.deltaTime+=t,this.elapsedTime+=t}destroy(t){this.emit("destroy"),(null==t?void 0:t.texture)&&this.textures.forEach(e=>e.destroy(t.baseTexture)),this.automator.destroy(),this.internalModel.destroy(),super.destroy(t)}}if(!("Live2D"in window))throw new Error("Could not find Cubism 2 runtime. This plugin requires live2d.min.js to be loaded.");const ut=Live2DMotion.prototype.updateParam;Live2DMotion.prototype.updateParam=function(t,e){ut.call(this,t,e),e.isFinished()&&this.onFinishHandler&&(this.onFinishHandler(this),delete this.onFinishHandler)};class ct extends AMotion{constructor(t){super(),n(this,"params",[]),this.setFadeIn(t.fade_in>0?t.fade_in:a.expressionFadingDuration),this.setFadeOut(t.fade_out>0?t.fade_out:a.expressionFadingDuration),Array.isArray(t.params)&&t.params.forEach(t=>{const e=t.calc||"add";if("add"===e){const e=t.def||0;t.val-=e}else if("mult"===e){const e=t.def||1;t.val/=e}this.params.push({calc:e,val:t.val,id:t.id})})}updateParamExe(t,e,i,s){this.params.forEach(e=>{t.setParamFloat(e.id,e.val*i)})}}class pt extends M{constructor(t,e){var i;super(t,e),n(this,"queueManager",new MotionQueueManager),n(this,"definitions"),this.definitions=null!=(i=this.settings.expressions)?i:[],this.init()}isFinished(){return this.queueManager.isFinished()}getExpressionIndex(t){return this.definitions.findIndex(e=>e.name===t)}getExpressionFile(t){return t.file}createExpression(t,e){return new ct(t)}_setExpression(t){return this.queueManager.startMotion(t)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}}function gt(t,e,i){const s=i.getDurationMSec(),r=t.startMotion(i,!0),n=t.motions.find(t=>!!t&&t._$sr===r);return!!n&&(i.updateParamExe(e.coreModel,s,1,n),!0)}class mt extends A{constructor(t){super(t),n(this,"definitions"),n(this,"groups",{idle:"idle"}),n(this,"motionDataType","arraybuffer"),n(this,"queueManager",new MotionQueueManager),n(this,"lipSyncIds"),n(this,"expressionManager"),this.definitions=this.settings.motions,this.init(t.options),this.lipSyncIds=["PARAM_MOUTH_OPEN_Y"]}init(t){super.init(t),this.settings.expressions&&(this.expressionManager=new pt(this.settings,t))}isFinished(){return this.queueManager.isFinished()}createMotion(t,e,i){const s=Live2DMotion.loadMotion(t),r=e===this.groups.idle?a.idleMotionFadingDuration:a.motionFadingDuration;return s.setFadeIn(i.fade_in>0?i.fade_in:r),s.setFadeOut(i.fade_out>0?i.fade_out:r),s}getMotionFile(t){return t.file}getMotionName(t){return t.file}getSoundFile(t){return t.sound}_startMotion(t,e,i){return t.onFinishHandler=e,i&&i.length>0&&(t.motions=t.motions.filter(t=>!i.includes(t._$4P))),this.queueManager.stopAllMotions(),this.queueManager.startMotion(t)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}destroy(){super.destroy(),this.queueManager=void 0}motionLastFrame(t,e){return o(this,arguments,function*(t,e,{expression:i}={}){const s=yield this.getMotionAndApplyExpression(t,e,i);return!!s&&(this.playing=!0,gt(this.queueManager,this.parent,s),this.playing=!1,!0)})}}class ft extends e.EventEmitter{constructor(t){super(),n(this,"tag"),n(this,"manager"),n(this,"settings"),n(this,"state",new b),n(this,"playing",!1),n(this,"destroyed",!1),n(this,"parent"),this.settings=t.settings,this.tag=`ParallelMotionManager(${this.settings.name})`,this.state.tag=this.tag,this.manager=t.motionManager,this.parent=t}startMotion(t,e){return o(this,arguments,function*(t,e,i=P.NORMAL,s=[]){var r;if(!this.state.reserve(t,e,i))return!1;const n=null==(r=this.manager.definitions[t])?void 0:r[e];if(!n)return!1;const o=yield this.manager.loadMotion(t,e);return!!this.state.start(o,t,e,i)&&(l.log(this.tag,"Start motion:",this.getMotionName(n)),this.emit("motionStart",t,e,void 0),this.playing=!0,this._startMotion(o,void 0,s),!0)})}startRandomMotion(t,e){return o(this,null,function*(){var i;const s=this.manager.definitions[t];if(null==s?void 0:s.length){const r=[],n=null!=(i=this.manager.motionGroups[t])?i:[];for(let e=0;e<s.length;e++)null===n[e]||this.state.isActive(t,e)||r.push(e);if(r.length){const i=r[Math.floor(Math.random()*r.length)];return this.startMotion(t,i,e)}}return!1})}stopAllMotions(){this._stopAllMotions(),this.state.reset()}update(t,e){return this.isFinished()&&(this.playing&&(this.playing=!1,this.emit("motionFinish")),this.state.complete()),this.updateParameters(t,e)}destroy(){this.destroyed=!0,this.emit("destroy"),this.stopAllMotions()}}class Mt extends ft{constructor(t){super(t),n(this,"queueManager",new MotionQueueManager)}isFinished(){return this.queueManager.isFinished()}getMotionName(t){return t.file}_startMotion(t,e,i){return t.onFinishHandler=e,i&&i.length>0&&(t.motions=t.motions.filter(t=>!i.includes(t._$4P))),this.queueManager.stopAllMotions(),this.queueManager.startMotion(t)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}destroy(){super.destroy(),this.queueManager=void 0}playMotionLastFrame(t,e){return o(this,null,function*(){var i;if(!this.state.reserve(t,e,P.FORCE))return!1;const s=null==(i=this.manager.definitions[t])?void 0:i[e];if(!s)return!1;const r=yield this.manager.loadMotion(t,e);return!!this.state.start(r,t,e,P.FORCE)&&(l.log(this.tag,"Start motion:",this.getMotionName(s)),this.queueManager.stopAllMotions(),this.emit("motionStart",t,e,void 0),this.playing=!0,!!gt(this.queueManager,this.parent,r)&&(this.playing=!1,!0))})}}class yt{constructor(t){n(this,"leftParam"),n(this,"rightParam"),n(this,"blinkInterval",4e3),n(this,"closingDuration",100),n(this,"closedDuration",50),n(this,"openingDuration",150),n(this,"eyeState",0),n(this,"eyeParamValue",1),n(this,"closedTimer",0),n(this,"nextBlinkTimeLeft",this.blinkInterval),this.coreModel=t,this.leftParam=t.getParamIndex("PARAM_EYE_L_OPEN"),this.rightParam=t.getParamIndex("PARAM_EYE_R_OPEN")}setEyeParams(t){this.eyeParamValue=h(t,0,1),this.coreModel.setParamFloat(this.leftParam,this.eyeParamValue),this.coreModel.setParamFloat(this.rightParam,this.eyeParamValue)}update(t){switch(this.eyeState){case 0:this.nextBlinkTimeLeft-=t,this.nextBlinkTimeLeft<0&&(this.eyeState=1,this.nextBlinkTimeLeft=this.blinkInterval+this.closingDuration+this.closedDuration+this.openingDuration+d(0,2e3));break;case 1:this.setEyeParams(this.eyeParamValue+t/this.closingDuration),this.eyeParamValue<=0&&(this.eyeState=2,this.closedTimer=0);break;case 2:this.closedTimer+=t,this.closedTimer>=this.closedDuration&&(this.eyeState=3);break;case 3:this.setEyeParams(this.eyeParamValue+t/this.openingDuration),this.eyeParamValue>=1&&(this.eyeState=0)}}}const xt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class vt extends R{constructor(t,e,i){super(),n(this,"settings"),n(this,"options"),n(this,"coreModel"),n(this,"motionManager"),n(this,"parallelMotionManager"),n(this,"eyeBlink"),n(this,"eyeballXParamIndex"),n(this,"eyeballYParamIndex"),n(this,"angleXParamIndex"),n(this,"angleYParamIndex"),n(this,"angleZParamIndex"),n(this,"bodyAngleXParamIndex"),n(this,"breathParamIndex"),n(this,"textureFlipY",!0),n(this,"lipSync",!0),n(this,"drawDataCount",0),n(this,"disableCulling",!1),n(this,"hasDrawn",!1),n(this,"customHitAreas"),this.coreModel=t,this.settings=e,this.options=Object.assign({},{breathDepth:1,lipSyncGain:1.5,lipSyncWeight:.4},i),this.motionManager=new mt(this),this.parallelMotionManager=[],this.eyeBlink=new yt(t),this.eyeballXParamIndex=t.getParamIndex("PARAM_EYE_BALL_X"),this.eyeballYParamIndex=t.getParamIndex("PARAM_EYE_BALL_Y"),this.angleXParamIndex=t.getParamIndex("PARAM_ANGLE_X"),this.angleYParamIndex=t.getParamIndex("PARAM_ANGLE_Y"),this.angleZParamIndex=t.getParamIndex("PARAM_ANGLE_Z"),this.bodyAngleXParamIndex=t.getParamIndex("PARAM_BODY_ANGLE_X"),this.breathParamIndex=t.getParamIndex("PARAM_BREATH"),this.init()}init(){super.init(),this.settings.initParams&&this.settings.initParams.forEach(({id:t,value:e})=>this.coreModel.setParamFloat(t,e)),this.settings.initOpacities&&this.settings.initOpacities.forEach(({id:t,value:e})=>this.coreModel.setPartsOpacity(t,e)),this.coreModel.saveParam();const t=this.coreModel.getModelContext()._$aS;(null==t?void 0:t.length)&&(this.drawDataCount=t.length);let e=this.coreModel.drawParamWebGL.culling;Object.defineProperty(this.coreModel.drawParamWebGL,"culling",{set:t=>e=t,get:()=>!this.disableCulling&&e});const i=this.coreModel.getModelContext().clipManager,s=i.setupClip.bind(i);i.setupClip=(t,e)=>{s.call(i,t,e),e.gl.viewport(...this.viewport)}}getSize(){return[this.coreModel.getCanvasWidth(),this.coreModel.getCanvasHeight()]}getLayout(){const t={};if(this.settings.layout)for(const[e,i]of Object.entries(this.settings.layout)){let s=e;"center_x"===e?s="centerX":"center_y"===e&&(s="centerY"),"number"==typeof i&&(t[s]=i)}return t}updateWebGLContext(t,e){const i=this.coreModel.drawParamWebGL;i.firstDraw=!0,i.setGL(t),i.glno=e,i._$NT=null,i._$no=null,i._$vS=null;const s=this.coreModel.getModelContext().clipManager;s.curFrameNo=e;const r=t.getParameter(t.FRAMEBUFFER_BINDING);s.getMaskRenderTexture(),t.bindFramebuffer(t.FRAMEBUFFER,r)}bindTexture(t,e){this.coreModel.setTexture(t,e)}getHitAreaDefs(){var t,e,i;const s=this.settings.json;return F(null!=(i=null!=(e=null!=(t=this.settings.hitAreas)?t:s.hit_areas)?e:s.HitAreas)?i:s.hitAreas,t=>this.coreModel.getDrawDataIndex(t))}getDrawableIDs(){const t=this.coreModel.getModelContext(),e=[];for(let i=0;i<this.drawDataCount;i++){const s=t.getDrawData(i);s&&e.push(s.getDrawDataID().id)}return e}getDrawableIndex(t){return this.coreModel.getDrawDataIndex(t)}getDrawableVertices(t){if("string"==typeof t&&-1===(t=this.coreModel.getDrawDataIndex(t)))throw new TypeError("Unable to find drawable ID: "+t);return this.coreModel.getTransformedPoints(t).slice()}hitTest(t,e){this.hasDrawn||l.warn("Trying to hit-test a Cubism 2 model that has not been rendered yet. Drawable hit areas may be empty until the first draw.");const i=super.hitTest(t,e),s=this.hitTestCustom(t,e);return s.length?i.length?[...new Set([...i,...s])]:s:i}update(t,e){var i,s,r,n;super.update(t,e);const o=this.coreModel,a=this.updateMotions(o,e);if(o.saveParam(),null==(i=this.motionManager.expressionManager)||i.update(o,e),a||null==(s=this.eyeBlink)||s.update(t),this.updateFocus(),this.updateNaturalMovements(t,e),this.lipSync&&this.motionManager.currentAudio){let t=this.motionManager.mouthSync()*this.options.lipSyncGain;const e=1,i=t>0?.1:0;t=Math.pow(t,1.15),t=h(t,i,e);for(let s=0;s<this.motionManager.lipSyncIds.length;++s)this.coreModel.addToParamFloat(this.coreModel.getParamIndex(this.motionManager.lipSyncIds[s]),t,this.options.lipSyncWeight)}null==(r=this.physics)||r.update(e),null==(n=this.pose)||n.update(t),this.emit("beforeModelUpdate"),o.update(),o.loadParam()}updateFocus(){this.coreModel.addToParamFloat(this.eyeballXParamIndex,this.focusController.x),this.coreModel.addToParamFloat(this.eyeballYParamIndex,this.focusController.y),this.coreModel.addToParamFloat(this.angleXParamIndex,30*this.focusController.x),this.coreModel.addToParamFloat(this.angleYParamIndex,30*this.focusController.y),this.coreModel.addToParamFloat(this.angleZParamIndex,this.focusController.x*this.focusController.y*-30),this.coreModel.addToParamFloat(this.bodyAngleXParamIndex,10*this.focusController.x)}updateNaturalMovements(t,e){const i=e/1e3*2*Math.PI;this.coreModel.addToParamFloat(this.angleXParamIndex,15*this.options.breathDepth*Math.sin(i/6.5345)*.5),this.coreModel.addToParamFloat(this.angleYParamIndex,8*this.options.breathDepth*Math.sin(i/3.5345)*.5),this.coreModel.addToParamFloat(this.angleZParamIndex,10*this.options.breathDepth*Math.sin(i/5.5345)*.5),this.coreModel.addToParamFloat(this.bodyAngleXParamIndex,4*this.options.breathDepth*Math.sin(i/15.5345)*.5),this.coreModel.setParamFloat(this.breathParamIndex,.5+.5*Math.sin(i/3.2345))}draw(t){const e=this.disableCulling;t.getParameter(t.FRAMEBUFFER_BINDING)&&(this.disableCulling=!0);const i=this.drawingMatrix;xt[0]=i.a,xt[1]=i.b,xt[4]=i.c,xt[5]=i.d,xt[12]=i.tx,xt[13]=i.ty,this.coreModel.setMatrix(xt),this.coreModel.draw(),this.hasDrawn=!0,this.disableCulling=e}extendParallelMotionManager(t){for(;this.parallelMotionManager.length<t;)this.parallelMotionManager.push(new Mt(this))}destroy(){super.destroy(),this.coreModel=void 0}hitTestCustom(t,e){const i=this.getCustomHitAreas();if(!i)return[];const s=this.originalWidth||this.width,r=this.originalHeight||this.height;if(!s||!r)return[];const n=t/s*2-1,o=1-e/r*2,a=[];for(const[l,h]of Object.entries(i))n>=h.minX&&n<=h.maxX&&o>=h.minY&&o<=h.maxY&&a.push(l);return a}getCustomHitAreas(){var t,e,i,s,r;if(void 0!==this.customHitAreas)return this.customHitAreas;const n=this.settings.json,o=null!=(i=null!=(e=null!=(t=n.hit_areas_custom)?t:n.hitAreasCustom)?e:n.HitAreasCustom)?i:n.HitAreas_Custom;if(!o||"object"!=typeof o)return this.customHitAreas=null,null;const a=o,l={},h=(t,e,i)=>{if(!t||!Array.isArray(e)||!Array.isArray(i))return;if(e.length<2||i.length<2)return;const s=Number(e[0]),r=Number(e[1]),n=Number(i[0]),o=Number(i[1]);Number.isFinite(s)&&Number.isFinite(r)&&Number.isFinite(n)&&Number.isFinite(o)&&(l[t]={minX:Math.min(s,r),maxX:Math.max(s,r),minY:Math.min(n,o),maxY:Math.max(n,o)})};for(const[d,u]of Object.entries(a)){if(d.endsWith("_x")){const t=d.slice(0,-2);h(t,u,a[`${t}_y`]);continue}if(!d.endsWith("_y")&&(u&&"object"==typeof u)){const t=u;h(d,null!=(s=t.x)?s:t.X,null!=(r=t.y)?r:t.Y)}}return this.customHitAreas=Object.keys(l).length?l:null,this.customHitAreas}}const Et={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE},Pt={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE};class bt{constructor(t,e){n(this,"physicsHairs",[]),this.coreModel=t,e.physics_hair&&(this.physicsHairs=e.physics_hair.map(t=>{const e=new PhysicsHair;return e.setup(t.setup.length,t.setup.regist,t.setup.mass),t.src.forEach(({id:t,ptype:i,scale:s,weight:r})=>{const n=Et[i];n&&e.addSrcParam(n,t,s,r)}),t.targets.forEach(({id:t,ptype:i,scale:s,weight:r})=>{const n=Pt[i];n&&e.addTargetParam(n,t,s,r)}),e}))}update(t){this.physicsHairs.forEach(e=>e.update(this.coreModel,t))}}class wt{constructor(t){n(this,"paramIndex",-1),n(this,"partsIndex",-1),n(this,"link",[]),this.id=t}initIndex(t){this.paramIndex=t.getParamIndex("VISIBLE:"+this.id),this.partsIndex=t.getPartsDataIndex(PartsDataID.getID(this.id)),t.setParamFloat(this.paramIndex,1)}}class It{constructor(t,e){n(this,"opacityAnimDuration",500),n(this,"partsGroups",[]),this.coreModel=t,e.parts_visible&&(this.partsGroups=e.parts_visible.map(({group:t})=>t.map(({id:t,link:e})=>{const i=new wt(t);return e&&(i.link=e.map(t=>new wt(t))),i})),this.init())}init(){this.partsGroups.forEach(t=>{t.forEach(t=>{if(t.initIndex(this.coreModel),t.paramIndex>=0){const e=0!==this.coreModel.getParamFloat(t.paramIndex);this.coreModel.setPartsOpacity(t.partsIndex,e?1:0),this.coreModel.setParamFloat(t.paramIndex,e?1:0),t.link.length>0&&t.link.forEach(t=>t.initIndex(this.coreModel))}})})}normalizePartsOpacityGroup(t,e){const i=this.coreModel,s=.5;let r=1,n=t.findIndex(({paramIndex:t,partsIndex:e})=>e>=0&&0!==i.getParamFloat(t));if(n>=0){const s=i.getPartsOpacity(t[n].partsIndex);r=h(s+e/this.opacityAnimDuration,0,1)}else n=0,r=1;t.forEach(({partsIndex:t},e)=>{if(t>=0)if(n==e)i.setPartsOpacity(t,r);else{let e,n=i.getPartsOpacity(t);e=r<s?-.5*r/s+1:(1-r)*s/.5;(1-e)*(1-r)>.15&&(e=1-.15/(1-r)),n>e&&(n=e),i.setPartsOpacity(t,n)}})}copyOpacity(t){const e=this.coreModel;t.forEach(({partsIndex:t,link:i})=>{if(t>=0&&i){const s=e.getPartsOpacity(t);i.forEach(({partsIndex:t})=>{t>=0&&e.setPartsOpacity(t,s)})}})}update(t){this.partsGroups.forEach(e=>{this.normalizePartsOpacityGroup(e,t),this.copyOpacity(e)})}}Z.registerRuntime({version:2,test:t=>t instanceof N||N.isValidJSON(t),ready:()=>Promise.resolve(),isValidMoc(t){if(t.byteLength<3)return!1;const e=new Int8Array(t,0,3);return"moc"===String.fromCharCode(...e)},createModelSettings:t=>new N(t),createCoreModel(t){const e=Live2DModelWebGL.loadModel(t),i=Live2D.getError();if(i){if(i instanceof Error)throw i;const t="string"==typeof i?i:`Live2D error: ${JSON.stringify(i)}`;throw new Error(t)}return e},createInternalModel:(t,e,i)=>new vt(t,e,i),createPose:(t,e)=>new It(t,e),createPhysics:(t,e)=>new bt(t,e)}),t.CubismLegacyExpressionManager=pt,t.CubismLegacyInternalModel=vt,t.CubismLegacyModelSettings=N,t.CubismLegacyMotionManager=mt,t.CubismLegacyParallelMotionManager=Mt,t.ExpressionManager=M,t.FileLoader=Y,t.FocusController=v,t.InternalModel=R,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DExpression=ct,t.Live2DEyeBlink=yt,t.Live2DFactory=Z,t.Live2DLoader=k,t.Live2DModel=dt,t.Live2DPhysics=bt,t.Live2DPose=It,t.Live2DTransform=st,t.MBToByte=function(t){return 1024*t*1024},t.ModelSettings=E,t.MotionManager=A,t.MotionPreloadStrategy=_,t.MotionPriority=P,t.MotionState=b,t.SoundManager=L,t.VERSION="1.0.2",t.VOLUME=I,t.XHRLoader=S,t.ZipLoader=q,t.applyMixins=function(t,e){e.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i))})})},t.clamp=h,t.config=a,t.copyArray=c,t.copyProperty=u,t.folderName=p,t.logger=l,t.normalizeHitAreaDefs=F,t.rand=d,t.remove=g,t.resolveURL=f,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
package/dist/cubism.es.js CHANGED
@@ -2757,7 +2757,7 @@ const config = {
2757
2757
  preserveExpressionOnMotion: true,
2758
2758
  cubism: CubismFrameworkConfig
2759
2759
  };
2760
- const VERSION = "1.0.0";
2760
+ const VERSION = "1.0.2";
2761
2761
  const logger = {
2762
2762
  log(tag, ...messages) {
2763
2763
  if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
@@ -4624,7 +4624,35 @@ const jsonToSettings = (context, next) => __async(null, null, function* () {
4624
4624
  return next();
4625
4625
  }
4626
4626
  }
4627
- throw new TypeError("Unknown settings format.");
4627
+ const url = context.source && typeof context.source.url === "string" ? context.source.url : void 0;
4628
+ const runtimeVersions = Live2DFactory.runtimes.map((r) => r.version).join(", ");
4629
+ if (Live2DFactory.runtimes.length === 0) {
4630
+ throw new TypeError(
4631
+ [
4632
+ "Unknown settings format: no Live2D runtimes registered.",
4633
+ 'Import a published runtime entry before loading models (e.g. "<package>/cubism" for Cubism 3/4/5, "<package>/cubism-legacy" for Cubism 2).',
4634
+ url ? `Settings URL: ${url}` : void 0
4635
+ ].filter(Boolean).join("\n")
4636
+ );
4637
+ }
4638
+ const topLevelKeys = (() => {
4639
+ try {
4640
+ if (!context.source || typeof context.source !== "object" || Array.isArray(context.source)) {
4641
+ return void 0;
4642
+ }
4643
+ return Object.keys(context.source).slice(0, 30).join(", ");
4644
+ } catch (e) {
4645
+ return void 0;
4646
+ }
4647
+ })();
4648
+ throw new TypeError(
4649
+ [
4650
+ "Unknown settings format: no matching runtime found for the loaded settings JSON.",
4651
+ runtimeVersions ? `Registered runtimes (versions): ${runtimeVersions}` : void 0,
4652
+ topLevelKeys ? `Settings JSON keys: ${topLevelKeys}` : void 0,
4653
+ url ? `Settings URL: ${url}` : void 0
4654
+ ].filter(Boolean).join("\n")
4655
+ );
4628
4656
  });
4629
4657
  const waitUntilReady = (context, next) => {
4630
4658
  if (context.settings) {
@@ -11203,6 +11231,30 @@ var Live2DCubismFramework$8;
11203
11231
  Live2DCubismFramework2.CubismRenderer_WebGL = CubismRenderer_WebGL;
11204
11232
  })(Live2DCubismFramework$8 || (Live2DCubismFramework$8 = {}));
11205
11233
  const tempMatrix = new CubismMatrix44();
11234
+ const DEFAULT_MASKS_PER_RENDER_TEXTURE = 36;
11235
+ const MASKS_PER_RENDER_TEXTURE = 32;
11236
+ function getRequiredMaskRenderTextureCount(model) {
11237
+ var _a;
11238
+ if (!model.isUsingMasking()) {
11239
+ return 1;
11240
+ }
11241
+ const maskCounts = model.getDrawableMaskCounts();
11242
+ const masks = model.getDrawableMasks();
11243
+ const uniqueMaskSets = /* @__PURE__ */ new Set();
11244
+ for (let i = 0; i < model.getDrawableCount(); i++) {
11245
+ const maskCount = maskCounts[i];
11246
+ if (!maskCount || maskCount <= 0) {
11247
+ continue;
11248
+ }
11249
+ const maskSet = Array.from((_a = masks[i]) != null ? _a : []).slice(0, maskCount).sort((a, b) => a - b).join(",");
11250
+ uniqueMaskSets.add(maskSet);
11251
+ }
11252
+ const clippingContextCount = uniqueMaskSets.size;
11253
+ if (clippingContextCount <= DEFAULT_MASKS_PER_RENDER_TEXTURE) {
11254
+ return 1;
11255
+ }
11256
+ return Math.ceil(clippingContextCount / MASKS_PER_RENDER_TEXTURE);
11257
+ }
11206
11258
  class CubismInternalModel extends InternalModel {
11207
11259
  constructor(coreModel, settings, options) {
11208
11260
  super();
@@ -11234,7 +11286,11 @@ class CubismInternalModel extends InternalModel {
11234
11286
  __publicField(this, "modelTransform", new Matrix());
11235
11287
  this.coreModel = coreModel;
11236
11288
  this.settings = settings;
11237
- this.options = Object.assign({}, { breathDepth: 1 }, options);
11289
+ this.options = Object.assign(
11290
+ {},
11291
+ { breathDepth: 1, lipSyncGain: 1.5, lipSyncWeight: 0.4 },
11292
+ options
11293
+ );
11238
11294
  this.idManager = CubismFramework.getIdManager();
11239
11295
  this.idParamAngleX = this.getIdSafe(CubismDefaultParameterId.ParamAngleX);
11240
11296
  this.idParamAngleY = this.getIdSafe(CubismDefaultParameterId.ParamAngleY);
@@ -11298,7 +11354,7 @@ class CubismInternalModel extends InternalModel {
11298
11354
  );
11299
11355
  breathParams.pushBack(new BreathParameterData(this.idParamBreath, 0, 0.5, 3.2345, 0.5));
11300
11356
  this.breath.setParameters(breathParams);
11301
- this.renderer.initialize(this.coreModel);
11357
+ this.renderer.initialize(this.coreModel, getRequiredMaskRenderTextureCount(this.coreModel));
11302
11358
  this.renderer.setIsPremultipliedAlpha(true);
11303
11359
  }
11304
11360
  getIdSafe(id) {
@@ -11393,15 +11449,13 @@ class CubismInternalModel extends InternalModel {
11393
11449
  this.updateFocus();
11394
11450
  this.updateNaturalMovements(dt * 1e3, now * 1e3);
11395
11451
  if (this.lipSync && this.motionManager.currentAudio) {
11396
- const lipSyncGain = 1.5;
11397
- const smoothing = 0.4;
11398
- let value = this.motionManager.mouthSync() * lipSyncGain;
11452
+ let value = this.motionManager.mouthSync() * this.options.lipSyncGain;
11399
11453
  value = Math.pow(value, 1.15);
11400
11454
  const min_ = value > 0 ? 0.1 : 0;
11401
11455
  const max_ = 1;
11402
11456
  value = clamp(value, min_, max_);
11403
11457
  this.motionManager.lipSyncIds.forEach((lipSyncId) => {
11404
- model.addParameterValueById(this.getIdSafe(lipSyncId), value, smoothing);
11458
+ model.addParameterValueById(this.getIdSafe(lipSyncId), value, this.options.lipSyncWeight);
11405
11459
  });
11406
11460
  }
11407
11461
  (_d = this.physics) == null ? void 0 : _d.evaluate(model, dt);