diff --git a/dist/cubism2.es.js b/dist/cubism2.es.js index cc571236..edb9ad49 100644 --- a/dist/cubism2.es.js +++ b/dist/cubism2.es.js @@ -582,8 +582,8 @@ class MotionManager extends EventEmitter { _loadMotion(group, index) { throw new Error("Not implemented."); } - speakUp(sound, volume, expression) { - return __async(this, null, function* () { + speakUp(_0) { + return __async(this, arguments, function* (sound, { volume = 1, expression, resetExpression = true } = {}) { if (!config.sound) { return false; } @@ -614,10 +614,10 @@ class MotionManager extends EventEmitter { if (file) { try { audio = SoundManager.add(file, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }); this.currentAudio = audio; @@ -651,7 +651,7 @@ class MotionManager extends EventEmitter { }); } startMotion(_0, _1) { - return __async(this, arguments, function* (group, index, priority = MotionPriority.NORMAL, sound, volume, expression) { + return __async(this, arguments, function* (group, index, priority = MotionPriority.NORMAL, { sound = void 0, volume = 1, expression = void 0, resetExpression = true } = {}) { var _a; if (this.currentAudio) { if (!this.currentAudio.ended) { @@ -691,10 +691,10 @@ class MotionManager extends EventEmitter { if (file) { try { audio = SoundManager.add(file, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }); this.currentAudio = audio; @@ -740,8 +740,8 @@ class MotionManager extends EventEmitter { return true; }); } - startRandomMotion(group, priority, sound, volume) { - return __async(this, null, function* () { + startRandomMotion(_0, _1) { + return __async(this, arguments, function* (group, priority, { sound = void 0, volume = 1, expression = void 0, resetExpression = true } = {}) { const groupDefs = this.definitions[group]; if (groupDefs == null ? void 0 : groupDefs.length) { const availableIndices = []; @@ -752,7 +752,12 @@ class MotionManager extends EventEmitter { } if (availableIndices.length) { const index = availableIndices[Math.floor(Math.random() * availableIndices.length)]; - return this.startMotion(group, index, priority, sound, volume); + return this.startMotion(group, index, priority, { + sound, + volume, + expression, + resetExpression + }); } } return false; @@ -1398,14 +1403,28 @@ class Live2DModel extends Container { onAnchorChange() { this.pivot.set(this.anchor.x * this.internalModel.width, this.anchor.y * this.internalModel.height); } - motion(group, index, priority, sound, volume, expression) { - return index === void 0 ? this.internalModel.motionManager.startRandomMotion(group, priority) : this.internalModel.motionManager.startMotion(group, index, priority, sound, volume, expression); + motion(group, index, { priority = 2, sound, volume = 1, expression, resetExpression = true } = {}) { + return index === void 0 ? this.internalModel.motionManager.startRandomMotion(group, priority, { + sound, + volume, + expression, + resetExpression + }) : this.internalModel.motionManager.startMotion(group, index, priority, { + sound, + volume, + expression, + resetExpression + }); } resetMotions() { return this.internalModel.motionManager.stopAllMotions(); } - speak(sound, volume, expression) { - return this.internalModel.motionManager.speakUp(sound, volume, expression); + speak(sound, { volume = 1, expression, resetExpression = true } = {}) { + return this.internalModel.motionManager.speakUp(sound, { + volume, + expression, + resetExpression + }); } stopSpeaking() { return this.internalModel.motionManager.stopSpeaking(); @@ -1790,6 +1809,7 @@ class Cubism2MotionManager extends MotionManager { this.queueManager = new MotionQueueManager(); this.definitions = this.settings.motions; this.init(options); + this.lipSyncIds = ["PARAM_MOUTH_OPEN_Y"]; } init(options) { super.init(options); @@ -1903,6 +1923,7 @@ class Cubism2InternalModel extends InternalModel { constructor(coreModel, settings, options) { super(); this.textureFlipY = true; + this.lipSync = true; this.drawDataCount = 0; this.disableCulling = false; this.coreModel = coreModel; @@ -1916,6 +1937,7 @@ class Cubism2InternalModel extends InternalModel { this.angleZParamIndex = coreModel.getParamIndex("PARAM_ANGLE_Z"); this.bodyAngleXParamIndex = coreModel.getParamIndex("PARAM_BODY_ANGLE_X"); this.breathParamIndex = coreModel.getParamIndex("PARAM_BREATH"); + this.mouthFormIndex = coreModel.getParamIndex("PARAM_MOUTH_FORM"); this.init(); } init() { @@ -2024,6 +2046,19 @@ class Cubism2InternalModel extends InternalModel { } this.updateFocus(); this.updateNaturalMovements(dt, now); + if (this.lipSync && this.motionManager.currentAudio) { + let value = this.motionManager.mouthSync(); + let min_ = 0; + let max_ = 1; + let weight = 1.2; + if (value > 0) { + min_ = 0.4; + } + value = clamp(value * weight, min_, max_); + for (let i = 0; i < this.motionManager.lipSyncIds.length; ++i) { + this.coreModel.setParamFloat(this.coreModel.getParamIndex(this.motionManager.lipSyncIds[i]), value); + } + } (_c = this.physics) == null ? void 0 : _c.update(now); (_d = this.pose) == null ? void 0 : _d.update(dt); this.emit("beforeModelUpdate"); diff --git a/dist/cubism2.js b/dist/cubism2.js index 4e1b5539..638e2b73 100644 --- a/dist/cubism2.js +++ b/dist/cubism2.js @@ -582,8 +582,8 @@ var __async = (__this, __arguments, generator) => { _loadMotion(group, index) { throw new Error("Not implemented."); } - speakUp(sound, volume, expression) { - return __async(this, null, function* () { + speakUp(_0) { + return __async(this, arguments, function* (sound, { volume = 1, expression, resetExpression = true } = {}) { if (!exports2.config.sound) { return false; } @@ -614,10 +614,10 @@ var __async = (__this, __arguments, generator) => { if (file) { try { audio = SoundManager.add(file, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }); this.currentAudio = audio; @@ -651,7 +651,7 @@ var __async = (__this, __arguments, generator) => { }); } startMotion(_0, _1) { - return __async(this, arguments, function* (group, index, priority = MotionPriority.NORMAL, sound, volume, expression) { + return __async(this, arguments, function* (group, index, priority = MotionPriority.NORMAL, { sound = void 0, volume = 1, expression = void 0, resetExpression = true } = {}) { var _a; if (this.currentAudio) { if (!this.currentAudio.ended) { @@ -691,10 +691,10 @@ var __async = (__this, __arguments, generator) => { if (file) { try { audio = SoundManager.add(file, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }); this.currentAudio = audio; @@ -740,8 +740,8 @@ var __async = (__this, __arguments, generator) => { return true; }); } - startRandomMotion(group, priority, sound, volume) { - return __async(this, null, function* () { + startRandomMotion(_0, _1) { + return __async(this, arguments, function* (group, priority, { sound = void 0, volume = 1, expression = void 0, resetExpression = true } = {}) { const groupDefs = this.definitions[group]; if (groupDefs == null ? void 0 : groupDefs.length) { const availableIndices = []; @@ -752,7 +752,12 @@ var __async = (__this, __arguments, generator) => { } if (availableIndices.length) { const index = availableIndices[Math.floor(Math.random() * availableIndices.length)]; - return this.startMotion(group, index, priority, sound, volume); + return this.startMotion(group, index, priority, { + sound, + volume, + expression, + resetExpression + }); } } return false; @@ -1398,14 +1403,28 @@ var __async = (__this, __arguments, generator) => { onAnchorChange() { this.pivot.set(this.anchor.x * this.internalModel.width, this.anchor.y * this.internalModel.height); } - motion(group, index, priority, sound, volume, expression) { - return index === void 0 ? this.internalModel.motionManager.startRandomMotion(group, priority) : this.internalModel.motionManager.startMotion(group, index, priority, sound, volume, expression); + motion(group, index, { priority = 2, sound, volume = 1, expression, resetExpression = true } = {}) { + return index === void 0 ? this.internalModel.motionManager.startRandomMotion(group, priority, { + sound, + volume, + expression, + resetExpression + }) : this.internalModel.motionManager.startMotion(group, index, priority, { + sound, + volume, + expression, + resetExpression + }); } resetMotions() { return this.internalModel.motionManager.stopAllMotions(); } - speak(sound, volume, expression) { - return this.internalModel.motionManager.speakUp(sound, volume, expression); + speak(sound, { volume = 1, expression, resetExpression = true } = {}) { + return this.internalModel.motionManager.speakUp(sound, { + volume, + expression, + resetExpression + }); } stopSpeaking() { return this.internalModel.motionManager.stopSpeaking(); @@ -1790,6 +1809,7 @@ var __async = (__this, __arguments, generator) => { this.queueManager = new MotionQueueManager(); this.definitions = this.settings.motions; this.init(options); + this.lipSyncIds = ["PARAM_MOUTH_OPEN_Y"]; } init(options) { super.init(options); @@ -1903,6 +1923,7 @@ var __async = (__this, __arguments, generator) => { constructor(coreModel, settings, options) { super(); this.textureFlipY = true; + this.lipSync = true; this.drawDataCount = 0; this.disableCulling = false; this.coreModel = coreModel; @@ -1916,6 +1937,7 @@ var __async = (__this, __arguments, generator) => { this.angleZParamIndex = coreModel.getParamIndex("PARAM_ANGLE_Z"); this.bodyAngleXParamIndex = coreModel.getParamIndex("PARAM_BODY_ANGLE_X"); this.breathParamIndex = coreModel.getParamIndex("PARAM_BREATH"); + this.mouthFormIndex = coreModel.getParamIndex("PARAM_MOUTH_FORM"); this.init(); } init() { @@ -2024,6 +2046,19 @@ var __async = (__this, __arguments, generator) => { } this.updateFocus(); this.updateNaturalMovements(dt, now); + if (this.lipSync && this.motionManager.currentAudio) { + let value = this.motionManager.mouthSync(); + let min_ = 0; + let max_ = 1; + let weight = 1.2; + if (value > 0) { + min_ = 0.4; + } + value = clamp(value * weight, min_, max_); + for (let i = 0; i < this.motionManager.lipSyncIds.length; ++i) { + this.coreModel.setParamFloat(this.coreModel.getParamIndex(this.motionManager.lipSyncIds[i]), value); + } + } (_c = this.physics) == null ? void 0 : _c.update(now); (_d = this.pose) == null ? void 0 : _d.update(dt); this.emit("beforeModelUpdate"); diff --git a/dist/cubism2.min.js b/dist/cubism2.min.js index bf8ea022..9a093c2f 100644 --- a/dist/cubism2.min.js +++ b/dist/cubism2.min.js @@ -1 +1 @@ -var __pow=Math.pow,__async=(t,e,s)=>new Promise(((i,r)=>{var o=t=>{try{a(s.next(t))}catch(e){r(e)}},n=t=>{try{a(s.throw(t))}catch(e){r(e)}},a=t=>t.done?i(t.value):Promise.resolve(t.value).then(o,n);a((s=s.apply(t,e)).next())}));!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("@pixi/utils"),require("@pixi/math"),require("@pixi/core"),require("@pixi/display")):"function"==typeof define&&define.amd?define(["exports","@pixi/utils","@pixi/math","@pixi/core","@pixi/display"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).PIXI=t.PIXI||{},t.PIXI.live2d=t.PIXI.live2d||{}),t.PIXI.utils,t.PIXI,t.PIXI,t.PIXI)}(this,(function(t,e,s,i,r){"use strict";var o,n,a;(n=o||(o={})).supportMoreMaskDivisions=!0,n.setOpacityFromMotion=!1,t.config=void 0,(a=t.config||(t.config={})).LOG_LEVEL_VERBOSE=0,a.LOG_LEVEL_WARNING=1,a.LOG_LEVEL_ERROR=2,a.LOG_LEVEL_NONE=999,a.logLevel=a.LOG_LEVEL_WARNING,a.sound=!0,a.motionSync=!0,a.motionFadingDuration=500,a.idleMotionFadingDuration=2e3,a.expressionFadingDuration=500,a.preserveExpressionOnMotion=!0,a.cubism4=o;const l={log(e,...s){t.config.logLevel<=t.config.LOG_LEVEL_VERBOSE&&console.log(`[${e}]`,...s)},warn(e,...s){t.config.logLevel<=t.config.LOG_LEVEL_WARNING&&console.warn(`[${e}]`,...s)},error(e,...s){t.config.logLevel<=t.config.LOG_LEVEL_ERROR&&console.error(`[${e}]`,...s)}};function d(t,e,s){return ts?s:t}function h(t,e){return Math.random()*(e-t)+t}function c(t,e,s,i,r){const o=e[i];null!==o&&typeof o===t&&(s[r]=o)}function u(t,e,s,i,r){const o=e[i];Array.isArray(o)&&(s[r]=o.filter((e=>null!==e&&typeof e===t)))}function p(t,e){e.forEach((e=>{Object.getOwnPropertyNames(e.prototype).forEach((s=>{"constructor"!==s&&Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(e.prototype,s))}))}))}function g(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 m(t,e){const s=t.indexOf(e);-1!==s&&t.splice(s,1)}class f extends e.EventEmitter{constructor(t,e){super(),this.expressions=[],this.reserveExpressionIndex=-1,this.destroyed=!1,this.settings=t,this.tag=`ExpressionManager(${t.name})`}init(){this.defaultExpression=this.createExpression({},void 0),this.currentExpression=this.defaultExpression,this.stopAllExpressions()}loadExpression(t){return __async(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 __async(this,null,(function*(){if(this.definitions.length){const t=[];for(let e=0;e-1&&tl&&(o*=l/a,n*=l/a),this.vx+=o,this.vy+=n;const d=Math.sqrt(__pow(this.vx,2)+__pow(this.vy,2)),h=.5*(Math.sqrt(__pow(l,2)+8*l*i)-l);d>h&&(this.vx*=h/d,this.vy*=h/d),this.x+=this.vx,this.y+=this.vy}}class x{constructor(t){this.json=t;let e=t.url;if("string"!=typeof e)throw new TypeError("The `url` field in settings JSON must be defined as a string.");this.url=e,this.name=g(this.url)}resolveURL(t){return e.url.resolve(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(t.push(e),e))),t}validateFiles(t){const e=(e,s)=>{const i=this.resolveURL(e);if(!t.includes(i)){if(s)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 M=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(M||{});class v{constructor(){this.debug=!1,this.currentPriority=0,this.reservePriority=0}reserve(t,e,s){if(s<=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===s){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(s<3){if(s<=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(s<=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,s)}return!0}start(t,e,s,i){if(1===i){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,s)),!1}else{if(e!==this.reservedGroup||s!==this.reservedIndex)return l.log(this.tag,"Cannot start motion because another motion has taken the place.",this.dump(e,s)),!1;this.setReserved(void 0,void 0,0)}return!!t&&(this.setCurrent(e,s,i),!0)}complete(){this.setCurrent(void 0,void 0,0)}setCurrent(t,e,s){this.currentPriority=s,this.currentGroup=t,this.currentIndex=e}setReserved(t,e,s){this.reservePriority=s,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!t.config.preserveExpressionOnMotion&&this.currentPriority>1}dump(t,e){if(this.debug){return`\n group = "${t}", index = ${e}\n`+["currentPriority","reservePriority","currentGroup","currentIndex","reservedGroup","reservedIndex","reservedIdleGroup","reservedIdleIndex"].map((t=>"["+t+"] "+this[t])).join("\n")}return""}}class w{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,s){const i=new Audio(t);return i.volume=this._volume,i.preload="auto",i.autoplay=!0,i.crossOrigin="anonymous",i.addEventListener("ended",(()=>{this.dispose(i),null==e||e()})),i.addEventListener("error",(e=>{this.dispose(i),l.warn("SoundManager",`Error occurred on "${t}"`,e.error),null==s||s(e.error)})),this.audios.push(i),i}static play(t){return new Promise(((e,s)=>{var i;null==(i=t.play())||i.catch((e=>{t.dispatchEvent(new ErrorEvent("error",{error:e})),s(e)})),t.readyState===t.HAVE_ENOUGH_DATA?e():t.addEventListener("canplaythrough",e)}))}static addContext(t){const e=new AudioContext;return this.contexts.push(e),e}static addAnalyzer(t,e){const s=e.createMediaElementSource(t),i=e.createAnalyser();return i.fftSize=256,i.minDecibels=-90,i.maxDecibels=-10,i.smoothingTimeConstant=.85,s.connect(i),i.connect(e.destination),this.analysers.push(i),i}static analyze(t){if(null!=t){let e=new Float32Array(t.fftSize),s=0;t.getFloatTimeDomainData(e);for(const t of e)s+=t*t;return parseFloat(Math.sqrt(s/e.length*20).toFixed(1))}return parseFloat(Math.random().toFixed(1))}static dispose(t){t.pause(),t.removeAttribute("src"),m(this.audios,t)}static destroy(){for(let t=this.contexts.length-1;t>=0;t--)this.contexts[t].close();for(let t=this.audios.length-1;t>=0;t--)this.dispose(this.audios[t])}}w.audios=[],w.analysers=[],w.contexts=[],w._volume=.9;var E=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(E||{});class P extends e.EventEmitter{constructor(t,e){super(),this.motionGroups={},this.state=new v,this.playing=!1,this.destroyed=!1,this.settings=t,this.tag=`MotionManager(${t.name})`,this.state.tag=this.tag}init(t){(null==t?void 0:t.idleMotionGroup)&&(this.groups.idle=t.idleMotionGroup),this.setupMotions(t),this.stopAllMotions()}setupMotions(t){for(const s of Object.keys(this.definitions))this.motionGroups[s]=[];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 s of e)if(this.definitions[s])for(let t=0;t{i&&u.expressionManager&&u.expressionManager.resetExpression(),u.currentAudio=void 0}),(()=>{i&&u.expressionManager&&u.expressionManager.resetExpression(),u.currentAudio=void 0})),this.currentAudio=r;let t=1;void 0!==s&&(t=s),w.volume=t,n=w.addContext(this.currentAudio),this.currentContext=n,o=w.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=o}catch(p){l.warn(this.tag,"Failed to create audio",a,p)}if(r){const e=w.play(r).catch((t=>l.warn(this.tag,"Failed to play audio",r.src,t)));t.config.motionSync&&(yield e)}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),i&&this.expressionManager&&this.expressionManager.setExpression(i),this.playing=!0,!0}))}startMotion(e,s){return __async(this,arguments,(function*(e,s,i=M.NORMAL,r,o,n){var a;if(this.currentAudio&&!this.currentAudio.ended)return!1;if(!this.state.reserve(e,s,i))return!1;const d=null==(a=this.definitions[e])?void 0:a[s];if(!d)return!1;let h,c,u;if(this.currentAudio&&w.dispose(this.currentAudio),t.config.sound){const t=r&&r.startsWith("data:audio/wav;base64");if(r&&!t){var p=document.createElement("a");p.href=r,r=p.href}const e=r&&(r.startsWith("http")||r.startsWith("blob")),s=this.getSoundFile(d);let i=s;s&&(i=this.settings.resolveURL(s)+"?cache-buster="+(new Date).getTime()),(e||t)&&(i=r);const a=this;if(i)try{h=w.add(i,(()=>{n&&a.expressionManager&&a.expressionManager.resetExpression(),a.currentAudio=void 0}),(()=>{n&&a.expressionManager&&a.expressionManager.resetExpression(),a.currentAudio=void 0})),this.currentAudio=h;let t=1;void 0!==o&&(t=o),w.volume=t,u=w.addContext(this.currentAudio),this.currentContext=u,c=w.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=c}catch(m){l.warn(this.tag,"Failed to create audio",s,m)}}const g=yield this.loadMotion(e,s);if(h){i=3;const e=w.play(h).catch((t=>l.warn(this.tag,"Failed to play audio",h.src,t)));t.config.motionSync&&(yield e)}return this.state.start(g,e,s,i)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),l.log(this.tag,"Start motion:",this.getMotionName(d)),this.emit("motionStart",e,s,h),n&&this.expressionManager&&this.expressionManager.setExpression(n),this.playing=!0,this._startMotion(g),!0):(h&&(w.dispose(h),this.currentAudio=void 0),!1)}))}startRandomMotion(t,e,s,i){return __async(this,null,(function*(){const r=this.definitions[t];if(null==r?void 0:r.length){const o=[];for(let e=0;et.index>=0));for(const e of t)this.hitAreas[e.name]=e}hitTest(t,e){return Object.keys(this.hitAreas).filter((s=>this.isHit(s,t,e)))}isHit(t,e,s){if(!this.hitAreas[t])return!1;const i=this.hitAreas[t].index,r=this.getDrawableBounds(i,_);return r.x<=e&&e<=r.x+r.width&&r.y<=s&&s<=r.y+r.height}getDrawableBounds(t,e){const s=this.getDrawableVertices(t);let i=s[0],r=s[0],o=s[1],n=s[1];for(let a=0;a{200!==o.status&&0!==o.status||!o.response?o.onerror():i(o.response)},o.onerror=()=>{l.warn("XHRLoader",`Failed to load resource as ${o.responseType} (Status ${o.status}): ${e}`),r(new L("Network error.",e,o.status))},o.onabort=()=>r(new L("Aborted.",e,o.status,!0)),o.onloadend=()=>{var e;b.allXhrSet.delete(o),t&&(null==(e=b.xhrMap.get(t))||e.delete(o))},o}static cancelXHRs(){var t;null==(t=b.xhrMap.get(this))||t.forEach((t=>{t.abort(),b.allXhrSet.delete(t)})),b.xhrMap.delete(this)}static release(){b.allXhrSet.forEach((t=>t.abort())),b.allXhrSet.clear(),b.xhrMap=new WeakMap}};let T=b;function O(t,e){let s=-1;return function i(r,o){if(o)return Promise.reject(o);if(r<=s)return Promise.reject(new Error("next() called multiple times"));s=r;const n=t[r];if(!n)return Promise.resolve();try{return Promise.resolve(n(e,i.bind(null,r+1)))}catch(a){return Promise.reject(a)}}(0)}T.xhrMap=new WeakMap,T.allXhrSet=new Set,T.loader=(t,e)=>new Promise(((e,s)=>{b.createXHR(t.target,t.settings?t.settings.resolveURL(t.url):t.url,t.type,(s=>{t.result=s,e()}),s).send()}));class A{static load(t){return O(this.middlewares,t).then((()=>t.result))}}A.middlewares=[T.loader];const R="Live2DFactory",F=(t,e)=>__async(this,null,(function*(){if("string"==typeof t.source){const e=yield A.load({url:t.source,type:"json",target:t.live2dModel});e.url=t.source,t.source=e,t.live2dModel.emit("settingsJSONLoaded",e)}return e()})),D=(t,e)=>__async(this,null,(function*(){if(t.source instanceof x)return t.settings=t.source,e();if("object"==typeof t.source){const s=N.findRuntime(t.source);if(s){const i=s.createModelSettings(t.source);return t.settings=i,t.live2dModel.emit("settingsLoaded",i),e()}}throw new TypeError("Unknown settings format.")})),C=(t,e)=>{if(t.settings){const s=N.findRuntime(t.settings);if(s)return s.ready().then(e)}return e()},S=(t,e)=>__async(this,null,(function*(){yield e();const s=t.internalModel;if(s){const e=t.settings,i=N.findRuntime(e);if(i){const r=[];e.pose&&r.push(A.load({settings:e,url:e.pose,type:"json",target:s}).then((e=>{s.pose=i.createPose(s.coreModel,e),t.live2dModel.emit("poseLoaded",s.pose)})).catch((e=>{t.live2dModel.emit("poseLoadError",e),l.warn(R,"Failed to load pose.",e)}))),e.physics&&r.push(A.load({settings:e,url:e.physics,type:"json",target:s}).then((e=>{s.physics=i.createPhysics(s.coreModel,e),t.live2dModel.emit("physicsLoaded",s.physics)})).catch((e=>{t.live2dModel.emit("physicsLoadError",e),l.warn(R,"Failed to load physics.",e)}))),r.length&&(yield Promise.all(r))}}})),k=(t,e)=>__async(this,null,(function*(){if(!t.settings)throw new TypeError("Missing settings.");{const s=t.live2dModel,r=t.settings.textures.map((e=>function(t,e={}){const s={resourceOptions:{crossorigin:e.crossOrigin}};if(i.Texture.fromURL)return i.Texture.fromURL(t,s).catch((t=>{if(t instanceof Error)throw t;const e=new Error("Texture loading error");throw e.event=t,e}));s.resourceOptions.autoLoad=!1;const r=i.Texture.from(t,s);if(r.baseTexture.valid)return Promise.resolve(r);const o=r.baseTexture.resource;return null!=o._live2d_load||(o._live2d_load=new Promise(((t,e)=>{const s=t=>{o.source.removeEventListener("error",s);const i=new Error("Texture loading error");i.event=t,e(i)};o.source.addEventListener("error",s),o.load().then((()=>t(r))).catch(s)}))),o._live2d_load}(t.settings.resolveURL(e),{crossOrigin:t.options.crossOrigin})));if(yield e(),!t.internalModel)throw new TypeError("Missing internal model.");s.internalModel=t.internalModel,s.emit("modelLoaded",t.internalModel),s.textures=yield Promise.all(r),s.emit("textureLoaded",s.textures)}})),G=(t,e)=>__async(this,null,(function*(){const s=t.settings;if(s instanceof x){const i=N.findRuntime(s);if(!i)throw new TypeError("Unknown model settings.");const r=yield A.load({settings:s,url:s.moc,type:"arraybuffer",target:t.live2dModel});if(!i.isValidMoc(r))throw new Error("Invalid moc data");const o=i.createCoreModel(r);return t.internalModel=i.createInternalModel(o,s,t.options),e()}throw new TypeError("Missing settings.")})),U=class{static registerRuntime(t){U.runtimes.push(t),U.runtimes.sort(((t,e)=>e.version-t.version))}static findRuntime(t){for(const e of U.runtimes)if(e.test(t))return e}static setupLive2DModel(t,e,s){return __async(this,null,(function*(){const i=new Promise((e=>t.once("textureLoaded",e))),r=new Promise((e=>t.once("modelLoaded",e))),o=Promise.all([i,r]).then((()=>t.emit("ready")));yield O(U.live2DModelMiddlewares,{live2dModel:t,source:e,options:s||{}}),yield o,t.emit("load")}))}static loadMotion(t,e,s){var i;const r=i=>t.emit("motionLoadError",e,s,i);try{const o=null==(i=t.definitions[e])?void 0:i[s];if(!o)return Promise.resolve(void 0);t.listeners("destroy").includes(U.releaseTasks)||t.once("destroy",U.releaseTasks);let n=U.motionTasksMap.get(t);n||(n={},U.motionTasksMap.set(t,n));let a=n[e];a||(a=[],n[e]=a);const d=t.getMotionFile(o);return null!=a[s]||(a[s]=A.load({url:d,settings:t.settings,type:t.motionDataType,target:t}).then((i=>{var r;const n=null==(r=U.motionTasksMap.get(t))?void 0:r[e];n&&delete n[s];const a=t.createMotion(i,e,o);return t.emit("motionLoaded",e,s,a),a})).catch((e=>{l.warn(t.tag,`Failed to load motion: ${d}\n`,e),r(e)}))),a[s]}catch(o){l.warn(t.tag,`Failed to load motion at "${e}"[${s}]\n`,o),r(o)}return Promise.resolve(void 0)}static loadExpression(t,e){const s=s=>t.emit("expressionLoadError",e,s);try{const i=t.definitions[e];if(!i)return Promise.resolve(void 0);t.listeners("destroy").includes(U.releaseTasks)||t.once("destroy",U.releaseTasks);let r=U.expressionTasksMap.get(t);r||(r=[],U.expressionTasksMap.set(t,r));const o=t.getExpressionFile(i);return null!=r[e]||(r[e]=A.load({url:o,settings:t.settings,type:"json",target:t}).then((s=>{const r=U.expressionTasksMap.get(t);r&&delete r[e];const o=t.createExpression(s,i);return t.emit("expressionLoaded",e,o),o})).catch((e=>{l.warn(t.tag,`Failed to load expression: ${o}\n`,e),s(e)}))),r[e]}catch(i){l.warn(t.tag,`Failed to load expression at [${e}]\n`,i),s(i)}return Promise.resolve(void 0)}static releaseTasks(){this instanceof P?U.motionTasksMap.delete(this):U.expressionTasksMap.delete(this)}};let N=U;N.runtimes=[],N.urlToJSON=F,N.jsonToSettings=D,N.waitUntilReady=C,N.setupOptionals=S,N.setupEssentials=k,N.createInternalModel=G,N.live2DModelMiddlewares=[F,D,C,S,k,G],N.motionTasksMap=new WeakMap,N.expressionTasksMap=new WeakMap,P.prototype._loadMotion=function(t,e){return N.loadMotion(this,t,e)},f.prototype._loadExpression=function(t){return N.loadExpression(this,t)};class j{constructor(){this._autoInteract=!1}get autoInteract(){return this._autoInteract}set autoInteract(t){t!==this._autoInteract&&(t?this.on("pointertap",X,this):this.off("pointertap",X,this),this._autoInteract=t)}registerInteraction(t){t!==this.interactionManager&&(this.unregisterInteraction(),this._autoInteract&&t&&(this.interactionManager=t,t.on("pointermove",H,this)))}unregisterInteraction(){var t;this.interactionManager&&(null==(t=this.interactionManager)||t.off("pointermove",H,this),this.interactionManager=void 0)}}function X(t){this.tap(t.data.global.x,t.data.global.y)}function H(t){this.focus(t.data.global.x,t.data.global.y)}class W extends s.Transform{}const $=new s.Point,q=new s.Matrix;let V;class z extends r.Container{constructor(t){super(),this.tag="Live2DModel(uninitialized)",this.textures=[],this.transform=new W,this.anchor=new s.ObservablePoint(this.onAnchorChange,this,0,0),this.glContextID=-1,this.elapsedTime=performance.now(),this.deltaTime=0,this._autoUpdate=!1,this.once("modelLoaded",(()=>this.init(t)))}static from(t,e){const s=new this(e);return N.setupLive2DModel(s,t,e).then((()=>s))}static fromSync(t,e){const s=new this(e);return N.setupLive2DModel(s,t,e).then(null==e?void 0:e.onLoad).catch(null==e?void 0:e.onError),s}static registerTicker(t){V=t}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){var e;V||(V=null==(e=window.PIXI)?void 0:e.Ticker),t?this._destroyed||(V?(V.shared.add(this.onTickerUpdate,this),this._autoUpdate=!0):l.warn(this.tag,"No Ticker registered, please call Live2DModel.registerTicker(Ticker).")):(null==V||V.shared.remove(this.onTickerUpdate,this),this._autoUpdate=!1)}init(t){this.tag=`Live2DModel(${this.internalModel.settings.name})`;const e=Object.assign({autoUpdate:!0,autoInteract:!0},t);e.autoInteract&&(this.interactive=!0),this.autoInteract=e.autoInteract,this.autoUpdate=e.autoUpdate}onAnchorChange(){this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(t,e,s,i,r,o){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,s):this.internalModel.motionManager.startMotion(t,e,s,i,r,o)}resetMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(t,e,s){return this.internalModel.motionManager.speakUp(t,e,s)}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,s=!1){$.x=t,$.y=e,this.toModelPosition($,$,!0);let i=$.x/this.internalModel.originalWidth*2-1,r=$.y/this.internalModel.originalHeight*2-1,o=Math.atan2(r,i);this.internalModel.focusController.focus(Math.cos(o),-Math.sin(o),s)}tap(t,e){const s=this.hitTest(t,e);s.length&&(l.log(this.tag,"Hit",s),this.emit("hit",s))}hitTest(t,e){return $.x=t,$.y=e,this.toModelPosition($,$),this.internalModel.hitTest($.x,$.y)}toModelPosition(t,e=t.clone(),s){return s||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.transform.worldTransform.applyInverse(t,e),this.internalModel.localTransform.applyInverse(e,e),e}containsPoint(t){return this.getBounds(!0).contains(t.x,t.y)}_calculateBounds(){this._bounds.addFrame(this.transform,0,0,this.internalModel.width,this.internalModel.height)}onTickerUpdate(){this.update(V.shared.deltaMS)}update(t){this.deltaTime+=t,this.elapsedTime+=t}_render(t){this.registerInteraction(t.plugins.interaction),t.batch.reset(),t.geometry.reset(),t.shader.reset(),t.state.reset();let e=!1;this.glContextID!==t.CONTEXT_UID&&(this.glContextID=t.CONTEXT_UID,this.internalModel.updateWebGLContext(t.gl,this.glContextID),e=!0);for(let r=0;re.destroy(t.baseTexture))),this.internalModel.destroy(),super.destroy(t)}}p(z,[j]);const B=class{static resolveURL(t,e){var s;const i=null==(s=B.filesMap[t])?void 0:s[e];if(void 0===i)throw new Error("Cannot find this file from uploaded files: "+e);return i}static upload(t,s){return __async(this,null,(function*(){const i={};for(const r of s.getDefinedFiles()){const o=decodeURI(e.url.resolve(s.url,r)),n=t.find((t=>t.webkitRelativePath===o));n&&(i[r]=URL.createObjectURL(n))}B.filesMap[s._objectURL]=i}))}static createSettings(t){return __async(this,null,(function*(){const e=t.find((t=>t.name.endsWith("model.json")||t.name.endsWith("model3.json")));if(!e)throw new TypeError("Settings file not found");const s=yield B.readText(e),i=JSON.parse(s);i.url=e.webkitRelativePath;const r=N.findRuntime(i);if(!r)throw new Error("Unknown settings JSON");const o=r.createModelSettings(i);return o._objectURL=URL.createObjectURL(e),o}))}static readText(t){return __async(this,null,(function*(){return new Promise(((e,s)=>{const i=new FileReader;i.onload=()=>e(i.result),i.onerror=s,i.readAsText(t,"utf8")}))}))}};let Y=B;Y.filesMap={},Y.factory=(t,e)=>__async(this,null,(function*(){if(Array.isArray(t.source)&&t.source[0]instanceof File){const e=t.source;let s=e.settings;if(s){if(!s._objectURL)throw new Error('"_objectURL" must be specified in ModelSettings')}else s=yield B.createSettings(e);s.validateFiles(e.map((t=>encodeURI(t.webkitRelativePath)))),yield B.upload(e,s),s.resolveURL=function(t){return B.resolveURL(this._objectURL,t)},t.source=s,t.live2dModel.once("modelLoaded",(t=>{t.once("destroy",(function(){const t=this.settings._objectURL;if(URL.revokeObjectURL(t),B.filesMap[t])for(const e of Object.values(B.filesMap[t]))URL.revokeObjectURL(e);delete B.filesMap[t]}))}))}return e()})),N.live2DModelMiddlewares.unshift(Y.factory);const J=class{static unzip(t,s){return __async(this,null,(function*(){const i=yield J.getFilePaths(t),r=[];for(const t of s.getDefinedFiles()){const o=decodeURI(e.url.resolve(s.url,t));i.includes(o)&&r.push(o)}const o=yield J.getFiles(t,r);for(let t=0;tt.endsWith("model.json")||t.endsWith("model3.json")));if(!e)throw new Error("Settings file not found");const s=yield J.readText(t,e);if(!s)throw new Error("Empty settings file: "+e);const i=JSON.parse(s);i.url=e;const r=N.findRuntime(i);if(!r)throw new Error("Unknown settings JSON");return r.createModelSettings(i)}))}static zipReader(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static getFilePaths(t){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static getFiles(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static readText(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static releaseReader(t){}};let Z=J;if(Z.ZIP_PROTOCOL="zip://",Z.uid=0,Z.factory=(t,e)=>__async(this,null,(function*(){const s=t.source;let i,r,o;if("string"==typeof s&&(s.endsWith(".zip")||s.startsWith(J.ZIP_PROTOCOL))?(i=s.startsWith(J.ZIP_PROTOCOL)?s.slice(J.ZIP_PROTOCOL.length):s,r=yield A.load({url:i,type:"blob",target:t.live2dModel})):Array.isArray(s)&&1===s.length&&s[0]instanceof File&&s[0].name.endsWith(".zip")&&(r=s[0],i=URL.createObjectURL(r),o=s.settings),r){if(!r.size)throw new Error("Empty zip file");const e=yield J.zipReader(r,i);o||(o=yield J.createSettings(e)),o._objectURL=J.ZIP_PROTOCOL+J.uid+"/"+o.url;const s=yield J.unzip(e,o);s.settings=o,t.source=s,i.startsWith("blob:")&&t.live2dModel.once("modelLoaded",(t=>{t.once("destroy",(function(){URL.revokeObjectURL(i)}))})),J.releaseReader(e)}return e()})),N.live2DModelMiddlewares.unshift(Z.factory),!window.Live2D)throw new Error("Could not find Cubism 2 runtime. This plugin requires live2d.min.js to be loaded.");const Q=Live2DMotion.prototype.updateParam;Live2DMotion.prototype.updateParam=function(t,e){Q.call(this,t,e),e.isFinished()&&this.onFinishHandler&&(this.onFinishHandler(this),delete this.onFinishHandler)};class K extends AMotion{constructor(e){super(),this.params=[],this.setFadeIn(e.fade_in>0?e.fade_in:t.config.expressionFadingDuration),this.setFadeOut(e.fade_out>0?e.fade_out:t.config.expressionFadingDuration),Array.isArray(e.params)&&e.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,s,i){this.params.forEach((e=>{t.setParamFloat(e.id,e.val*s)}))}}class tt extends f{constructor(t,e){var s;super(t,e),this.queueManager=new MotionQueueManager,this.definitions=null!=(s=this.settings.expressions)?s:[],this.init()}isFinished(){return this.queueManager.isFinished()}getExpressionIndex(t){return this.definitions.findIndex((e=>e.name===t))}getExpressionFile(t){return t.file}createExpression(t,e){return new K(t)}_setExpression(t){return this.queueManager.startMotion(t)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}}class et extends P{constructor(t,e){super(t,e),this.groups={idle:"idle"},this.motionDataType="arraybuffer",this.queueManager=new MotionQueueManager,this.definitions=this.settings.motions,this.init(e)}init(t){super.init(t),this.settings.expressions&&(this.expressionManager=new tt(this.settings,t))}isFinished(){return this.queueManager.isFinished()}createMotion(e,s,i){const r=Live2DMotion.loadMotion(e),o=s===this.groups.idle?t.config.idleMotionFadingDuration:t.config.motionFadingDuration;return r.setFadeIn(i.fade_in>0?i.fade_in:o),r.setFadeOut(i.fade_out>0?i.fade_out:o),r}getMotionFile(t){return t.file}getMotionName(t){return t.file}getSoundFile(t){return t.sound}_startMotion(t,e){return t.onFinishHandler=e,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}}class st{constructor(t){this.coreModel=t,this.blinkInterval=4e3,this.closingDuration=100,this.closedDuration=50,this.openingDuration=150,this.eyeState=0,this.eyeParamValue=1,this.closedTimer=0,this.nextBlinkTimeLeft=this.blinkInterval,this.leftParam=t.getParamIndex("PARAM_EYE_L_OPEN"),this.rightParam=t.getParamIndex("PARAM_EYE_R_OPEN")}setEyeParams(t){this.eyeParamValue=d(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+h(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 it=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class rt extends I{constructor(t,e,s){super(),this.textureFlipY=!0,this.drawDataCount=0,this.disableCulling=!1,this.coreModel=t,this.settings=e,this.motionManager=new et(e,s),this.eyeBlink=new st(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 s=this.coreModel.getModelContext().clipManager,i=s.setupClip;s.setupClip=(t,e)=>{i.call(s,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 of Object.keys(this.settings.layout)){let s=e;"center_x"===e?s="centerX":"center_y"===e&&(s="centerY"),t[s]=this.settings.layout[e]}return t}updateWebGLContext(t,e){const s=this.coreModel.drawParamWebGL;s.firstDraw=!0,s.setGL(t),s.glno=e;for(const o in s)s.hasOwnProperty(o)&&s[o]instanceof WebGLBuffer&&(s[o]=null);const i=this.coreModel.getModelContext().clipManager;i.curFrameNo=e;const r=t.getParameter(t.FRAMEBUFFER_BINDING);i.getMaskRenderTexture(),t.bindFramebuffer(t.FRAMEBUFFER,r)}bindTexture(t,e){this.coreModel.setTexture(t,e)}getHitAreaDefs(){var t;return(null==(t=this.settings.hitAreas)?void 0:t.map((t=>({id:t.id,name:t.name,index:this.coreModel.getDrawDataIndex(t.id)}))))||[]}getDrawableIDs(){const t=this.coreModel.getModelContext(),e=[];for(let s=0;s0&&t.textures.every((t=>"string"==typeof t))}copy(t){c("string",t,this,"name","name"),c("string",t,this,"pose","pose"),c("string",t,this,"physics","physics"),c("object",t,this,"layout","layout"),c("object",t,this,"motions","motions"),u("object",t,this,"hit_areas","hitAreas"),u("object",t,this,"expressions","expressions"),u("object",t,this,"init_params","initParams"),u("object",t,this,"init_opacities","initOpacities")}replaceFiles(t){super.replaceFiles(t);for(const[e,s]of Object.entries(this.motions))for(let i=0;i{const e=new PhysicsHair;return e.setup(t.setup.length,t.setup.regist,t.setup.mass),t.src.forEach((({id:t,ptype:s,scale:i,weight:r})=>{const o=nt[s];o&&e.addSrcParam(o,t,i,r)})),t.targets.forEach((({id:t,ptype:s,scale:i,weight:r})=>{const o=at[s];o&&e.addTargetParam(o,t,i,r)})),e})))}update(t){this.physicsHairs.forEach((e=>e.update(this.coreModel,t)))}}class dt{constructor(t){this.id=t,this.paramIndex=-1,this.partsIndex=-1,this.link=[]}initIndex(t){this.paramIndex=t.getParamIndex("VISIBLE:"+this.id),this.partsIndex=t.getPartsDataIndex(PartsDataID.getID(this.id)),t.setParamFloat(this.paramIndex,1)}}class ht{constructor(t,e){this.coreModel=t,this.opacityAnimDuration=500,this.partsGroups=[],e.parts_visible&&(this.partsGroups=e.parts_visible.map((({group:t})=>t.map((({id:t,link:e})=>{const s=new dt(t);return e&&(s.link=e.map((t=>new dt(t)))),s})))),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 s=this.coreModel,i=.5;let r=1,o=t.findIndex((({paramIndex:t,partsIndex:e})=>e>=0&&0!==s.getParamFloat(t)));if(o>=0){const i=s.getPartsOpacity(t[o].partsIndex);r=d(i+e/this.opacityAnimDuration,0,1)}else o=0,r=1;t.forEach((({partsIndex:t},e)=>{if(t>=0)if(o==e)s.setPartsOpacity(t,r);else{let e,o=s.getPartsOpacity(t);e=r.15&&(e=1-.15/(1-r)),o>e&&(o=e),s.setPartsOpacity(t,o)}}))}copyOpacity(t){const e=this.coreModel;t.forEach((({partsIndex:t,link:s})=>{if(t>=0&&s){const i=e.getPartsOpacity(t);s.forEach((({partsIndex:t})=>{t>=0&&e.setPartsOpacity(t,i)}))}}))}update(t){this.partsGroups.forEach((e=>{this.normalizePartsOpacityGroup(e,t),this.copyOpacity(e)}))}}N.registerRuntime({version:2,test:t=>t instanceof ot||ot.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 ot(t),createCoreModel(t){const e=Live2DModelWebGL.loadModel(t),s=Live2D.getError();if(s)throw s;return e},createInternalModel:(t,e,s)=>new rt(t,e,s),createPose:(t,e)=>new ht(t,e),createPhysics:(t,e)=>new lt(t,e)}),t.Cubism2ExpressionManager=tt,t.Cubism2InternalModel=rt,t.Cubism2ModelSettings=ot,t.Cubism2MotionManager=et,t.ExpressionManager=f,t.FileLoader=Y,t.FocusController=y,t.InteractionMixin=j,t.InternalModel=I,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DExpression=K,t.Live2DEyeBlink=st,t.Live2DFactory=N,t.Live2DLoader=A,t.Live2DModel=z,t.Live2DPhysics=lt,t.Live2DPose=ht,t.Live2DTransform=W,t.ModelSettings=x,t.MotionManager=P,t.MotionPreloadStrategy=E,t.MotionPriority=M,t.MotionState=v,t.SoundManager=w,t.VERSION="0.4.0",t.XHRLoader=T,t.ZipLoader=Z,t.applyMixins=p,t.clamp=d,t.copyArray=u,t.copyProperty=c,t.folderName=g,t.logger=l,t.rand=h,t.remove=m,Object.defineProperties(t,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})); +var __pow=Math.pow,__async=(e,t,s)=>new Promise(((i,r)=>{var o=e=>{try{a(s.next(e))}catch(t){r(t)}},n=e=>{try{a(s.throw(e))}catch(t){r(t)}},a=e=>e.done?i(e.value):Promise.resolve(e.value).then(o,n);a((s=s.apply(e,t)).next())}));!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@pixi/utils"),require("@pixi/math"),require("@pixi/core"),require("@pixi/display")):"function"==typeof define&&define.amd?define(["exports","@pixi/utils","@pixi/math","@pixi/core","@pixi/display"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).PIXI=e.PIXI||{},e.PIXI.live2d=e.PIXI.live2d||{}),e.PIXI.utils,e.PIXI,e.PIXI,e.PIXI)}(this,(function(e,t,s,i,r){"use strict";var o,n,a;(n=o||(o={})).supportMoreMaskDivisions=!0,n.setOpacityFromMotion=!1,e.config=void 0,(a=e.config||(e.config={})).LOG_LEVEL_VERBOSE=0,a.LOG_LEVEL_WARNING=1,a.LOG_LEVEL_ERROR=2,a.LOG_LEVEL_NONE=999,a.logLevel=a.LOG_LEVEL_WARNING,a.sound=!0,a.motionSync=!0,a.motionFadingDuration=500,a.idleMotionFadingDuration=2e3,a.expressionFadingDuration=500,a.preserveExpressionOnMotion=!0,a.cubism4=o;const l={log(t,...s){e.config.logLevel<=e.config.LOG_LEVEL_VERBOSE&&console.log(`[${t}]`,...s)},warn(t,...s){e.config.logLevel<=e.config.LOG_LEVEL_WARNING&&console.warn(`[${t}]`,...s)},error(t,...s){e.config.logLevel<=e.config.LOG_LEVEL_ERROR&&console.error(`[${t}]`,...s)}};function d(e,t,s){return es?s:e}function h(e,t){return Math.random()*(t-e)+e}function u(e,t,s,i,r){const o=t[i];null!==o&&typeof o===e&&(s[r]=o)}function c(e,t,s,i,r){const o=t[i];Array.isArray(o)&&(s[r]=o.filter((t=>null!==t&&typeof t===e)))}function p(e,t){t.forEach((t=>{Object.getOwnPropertyNames(t.prototype).forEach((s=>{"constructor"!==s&&Object.defineProperty(e.prototype,s,Object.getOwnPropertyDescriptor(t.prototype,s))}))}))}function g(e){let t=e.lastIndexOf("/");return-1!=t&&(e=e.slice(0,t)),t=e.lastIndexOf("/"),-1!==t&&(e=e.slice(t+1)),e}function m(e,t){const s=e.indexOf(t);-1!==s&&e.splice(s,1)}class f extends t.EventEmitter{constructor(e,t){super(),this.expressions=[],this.reserveExpressionIndex=-1,this.destroyed=!1,this.settings=e,this.tag=`ExpressionManager(${e.name})`}init(){this.defaultExpression=this.createExpression({},void 0),this.currentExpression=this.defaultExpression,this.stopAllExpressions()}loadExpression(e){return __async(this,null,(function*(){if(!this.definitions[e])return void l.warn(this.tag,`Undefined expression at [${e}]`);if(null===this.expressions[e])return void l.warn(this.tag,`Cannot set expression at [${e}] because it's already failed in loading.`);if(this.expressions[e])return this.expressions[e];const t=yield this._loadExpression(e);return this.expressions[e]=t,t}))}_loadExpression(e){throw new Error("Not implemented.")}setRandomExpression(){return __async(this,null,(function*(){if(this.definitions.length){const e=[];for(let t=0;t-1&&el&&(o*=l/a,n*=l/a),this.vx+=o,this.vy+=n;const d=Math.sqrt(__pow(this.vx,2)+__pow(this.vy,2)),h=.5*(Math.sqrt(__pow(l,2)+8*l*i)-l);d>h&&(this.vx*=h/d,this.vy*=h/d),this.x+=this.vx,this.y+=this.vy}}class y{constructor(e){this.json=e;let t=e.url;if("string"!=typeof t)throw new TypeError("The `url` field in settings JSON must be defined as a string.");this.url=t,this.name=g(this.url)}resolveURL(e){return t.url.resolve(this.url,e)}replaceFiles(e){this.moc=e(this.moc,"moc"),void 0!==this.pose&&(this.pose=e(this.pose,"pose")),void 0!==this.physics&&(this.physics=e(this.physics,"physics"));for(let t=0;t(e.push(t),t))),e}validateFiles(e){const t=(t,s)=>{const i=this.resolveURL(t);if(!e.includes(i)){if(s)throw new Error(`File "${t}" is defined in settings, but doesn't exist in given files`);return!1}return!0};[this.moc,...this.textures].forEach((e=>t(e,!0)));return this.getDefinedFiles().filter((e=>t(e,!1)))}}var M=(e=>(e[e.NONE=0]="NONE",e[e.IDLE=1]="IDLE",e[e.NORMAL=2]="NORMAL",e[e.FORCE=3]="FORCE",e))(M||{});class v{constructor(){this.debug=!1,this.currentPriority=0,this.reservePriority=0}reserve(e,t,s){if(s<=0)return l.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(e===this.currentGroup&&t===this.currentIndex)return l.log(this.tag,"Motion is already playing.",this.dump(e,t)),!1;if(e===this.reservedGroup&&t===this.reservedIndex||e===this.reservedIdleGroup&&t===this.reservedIdleIndex)return l.log(this.tag,"Motion is already reserved.",this.dump(e,t)),!1;if(1===s){if(0!==this.currentPriority)return l.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(e,t)),!1;if(void 0!==this.reservedIdleGroup)return l.log(this.tag,"Cannot start idle motion because another idle motion has reserved.",this.dump(e,t)),!1;this.setReservedIdle(e,t)}else{if(s<3){if(s<=this.currentPriority)return l.log(this.tag,"Cannot start motion because another motion is playing as an equivalent or higher priority.",this.dump(e,t)),!1;if(s<=this.reservePriority)return l.log(this.tag,"Cannot start motion because another motion has reserved as an equivalent or higher priority.",this.dump(e,t)),!1}this.setReserved(e,t,s)}return!0}start(e,t,s,i){if(1===i){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(t,s)),!1}else{if(t!==this.reservedGroup||s!==this.reservedIndex)return l.log(this.tag,"Cannot start motion because another motion has taken the place.",this.dump(t,s)),!1;this.setReserved(void 0,void 0,0)}return!!e&&(this.setCurrent(t,s,i),!0)}complete(){this.setCurrent(void 0,void 0,0)}setCurrent(e,t,s){this.currentPriority=s,this.currentGroup=e,this.currentIndex=t}setReserved(e,t,s){this.reservePriority=s,this.reservedGroup=e,this.reservedIndex=t}setReservedIdle(e,t){this.reservedIdleGroup=e,this.reservedIdleIndex=t}isActive(e,t){return e===this.currentGroup&&t===this.currentIndex||e===this.reservedGroup&&t===this.reservedIndex||e===this.reservedIdleGroup&&t===this.reservedIdleIndex}reset(){this.setCurrent(void 0,void 0,0),this.setReserved(void 0,void 0,0),this.setReservedIdle(void 0,void 0)}shouldRequestIdleMotion(){return void 0===this.currentGroup&&void 0===this.reservedIdleGroup}shouldOverrideExpression(){return!e.config.preserveExpressionOnMotion&&this.currentPriority>1}dump(e,t){if(this.debug){return`\n group = "${e}", index = ${t}\n`+["currentPriority","reservePriority","currentGroup","currentIndex","reservedGroup","reservedIndex","reservedIdleGroup","reservedIdleIndex"].map((e=>"["+e+"] "+this[e])).join("\n")}return""}}class E{static get volume(){return this._volume}static set volume(e){this._volume=(e>1?1:e<0?0:e)||0,this.audios.forEach((e=>e.volume=this._volume))}static add(e,t,s){const i=new Audio(e);return i.volume=this._volume,i.preload="auto",i.autoplay=!0,i.crossOrigin="anonymous",i.addEventListener("ended",(()=>{this.dispose(i),null==t||t()})),i.addEventListener("error",(t=>{this.dispose(i),l.warn("SoundManager",`Error occurred on "${e}"`,t.error),null==s||s(t.error)})),this.audios.push(i),i}static play(e){return new Promise(((t,s)=>{var i;null==(i=e.play())||i.catch((t=>{e.dispatchEvent(new ErrorEvent("error",{error:t})),s(t)})),e.readyState===e.HAVE_ENOUGH_DATA?t():e.addEventListener("canplaythrough",t)}))}static addContext(e){const t=new AudioContext;return this.contexts.push(t),t}static addAnalyzer(e,t){const s=t.createMediaElementSource(e),i=t.createAnalyser();return i.fftSize=256,i.minDecibels=-90,i.maxDecibels=-10,i.smoothingTimeConstant=.85,s.connect(i),i.connect(t.destination),this.analysers.push(i),i}static analyze(e){if(null!=e){let t=new Float32Array(e.fftSize),s=0;e.getFloatTimeDomainData(t);for(const e of t)s+=e*e;return parseFloat(Math.sqrt(s/t.length*20).toFixed(1))}return parseFloat(Math.random().toFixed(1))}static dispose(e){e.pause(),e.removeAttribute("src"),m(this.audios,e)}static destroy(){for(let e=this.contexts.length-1;e>=0;e--)this.contexts[e].close();for(let e=this.audios.length-1;e>=0;e--)this.dispose(this.audios[e])}}E.audios=[],E.analysers=[],E.contexts=[],E._volume=.9;var w=(e=>(e.ALL="ALL",e.IDLE="IDLE",e.NONE="NONE",e))(w||{});class P extends t.EventEmitter{constructor(e,t){super(),this.motionGroups={},this.state=new v,this.playing=!1,this.destroyed=!1,this.settings=e,this.tag=`MotionManager(${e.name})`,this.state.tag=this.tag}init(e){(null==e?void 0:e.idleMotionGroup)&&(this.groups.idle=e.idleMotionGroup),this.setupMotions(e),this.stopAllMotions()}setupMotions(e){for(const s of Object.keys(this.definitions))this.motionGroups[s]=[];let t;switch(null==e?void 0:e.motionPreload){case"NONE":return;case"ALL":t=Object.keys(this.definitions);break;default:t=[this.groups.idle]}for(const s of t)if(this.definitions[s])for(let e=0;e{r&&i&&p.expressionManager&&p.expressionManager.resetExpression(),p.currentAudio=void 0}),(()=>{r&&i&&p.expressionManager&&p.expressionManager.resetExpression(),p.currentAudio=void 0})),this.currentAudio=o;let e=1;void 0!==s&&(e=s),E.volume=e,a=E.addContext(this.currentAudio),this.currentContext=a,n=E.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=n}catch(g){l.warn(this.tag,"Failed to create audio",d,g)}if(o){const t=E.play(o).catch((e=>l.warn(this.tag,"Failed to play audio",o.src,e)));e.config.motionSync&&(yield t)}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),i&&this.expressionManager&&this.expressionManager.setExpression(i),this.playing=!0,!0}))}startMotion(t,s){return __async(this,arguments,(function*(t,s,i=M.NORMAL,{sound:r,volume:o=1,expression:n,resetExpression:a=!0}={}){var d;if(this.currentAudio&&!this.currentAudio.ended)return!1;if(!this.state.reserve(t,s,i))return!1;const h=null==(d=this.definitions[t])?void 0:d[s];if(!h)return!1;let u,c,p;if(this.currentAudio&&E.dispose(this.currentAudio),e.config.sound){const e=r&&r.startsWith("data:audio/wav;base64");if(r&&!e){var g=document.createElement("a");g.href=r,r=g.href}const t=r&&(r.startsWith("http")||r.startsWith("blob")),s=this.getSoundFile(h);let i=s;s&&(i=this.settings.resolveURL(s)+"?cache-buster="+(new Date).getTime()),(t||e)&&(i=r);const d=this;if(i)try{u=E.add(i,(()=>{a&&n&&d.expressionManager&&d.expressionManager.resetExpression(),d.currentAudio=void 0}),(()=>{a&&n&&d.expressionManager&&d.expressionManager.resetExpression(),d.currentAudio=void 0})),this.currentAudio=u;let e=1;void 0!==o&&(e=o),E.volume=e,p=E.addContext(this.currentAudio),this.currentContext=p,c=E.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=c}catch(f){l.warn(this.tag,"Failed to create audio",s,f)}}const m=yield this.loadMotion(t,s);if(u){i=3;const t=E.play(u).catch((e=>l.warn(this.tag,"Failed to play audio",u.src,e)));e.config.motionSync&&(yield t)}return this.state.start(m,t,s,i)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),l.log(this.tag,"Start motion:",this.getMotionName(h)),this.emit("motionStart",t,s,u),n&&this.expressionManager&&this.expressionManager.setExpression(n),this.playing=!0,this._startMotion(m),!0):(u&&(E.dispose(u),this.currentAudio=void 0),!1)}))}startRandomMotion(e,t){return __async(this,arguments,(function*(e,t,{sound:s,volume:i=1,expression:r,resetExpression:o=!0}={}){const n=this.definitions[e];if(null==n?void 0:n.length){const a=[];for(let t=0;te.index>=0));for(const t of e)this.hitAreas[t.name]=t}hitTest(e,t){return Object.keys(this.hitAreas).filter((s=>this.isHit(s,e,t)))}isHit(e,t,s){if(!this.hitAreas[e])return!1;const i=this.hitAreas[e].index,r=this.getDrawableBounds(i,_);return r.x<=t&&t<=r.x+r.width&&r.y<=s&&s<=r.y+r.height}getDrawableBounds(e,t){const s=this.getDrawableVertices(e);let i=s[0],r=s[0],o=s[1],n=s[1];for(let a=0;a{200!==o.status&&0!==o.status||!o.response?o.onerror():i(o.response)},o.onerror=()=>{l.warn("XHRLoader",`Failed to load resource as ${o.responseType} (Status ${o.status}): ${t}`),r(new L("Network error.",t,o.status))},o.onabort=()=>r(new L("Aborted.",t,o.status,!0)),o.onloadend=()=>{var t;b.allXhrSet.delete(o),e&&(null==(t=b.xhrMap.get(e))||t.delete(o))},o}static cancelXHRs(){var e;null==(e=b.xhrMap.get(this))||e.forEach((e=>{e.abort(),b.allXhrSet.delete(e)})),b.xhrMap.delete(this)}static release(){b.allXhrSet.forEach((e=>e.abort())),b.allXhrSet.clear(),b.xhrMap=new WeakMap}};let T=b;function O(e,t){let s=-1;return function i(r,o){if(o)return Promise.reject(o);if(r<=s)return Promise.reject(new Error("next() called multiple times"));s=r;const n=e[r];if(!n)return Promise.resolve();try{return Promise.resolve(n(t,i.bind(null,r+1)))}catch(a){return Promise.reject(a)}}(0)}T.xhrMap=new WeakMap,T.allXhrSet=new Set,T.loader=(e,t)=>new Promise(((t,s)=>{b.createXHR(e.target,e.settings?e.settings.resolveURL(e.url):e.url,e.type,(s=>{e.result=s,t()}),s).send()}));class A{static load(e){return O(this.middlewares,e).then((()=>e.result))}}A.middlewares=[T.loader];const R="Live2DFactory",F=(e,t)=>__async(this,null,(function*(){if("string"==typeof e.source){const t=yield A.load({url:e.source,type:"json",target:e.live2dModel});t.url=e.source,e.source=t,e.live2dModel.emit("settingsJSONLoaded",t)}return t()})),D=(e,t)=>__async(this,null,(function*(){if(e.source instanceof y)return e.settings=e.source,t();if("object"==typeof e.source){const s=N.findRuntime(e.source);if(s){const i=s.createModelSettings(e.source);return e.settings=i,e.live2dModel.emit("settingsLoaded",i),t()}}throw new TypeError("Unknown settings format.")})),S=(e,t)=>{if(e.settings){const s=N.findRuntime(e.settings);if(s)return s.ready().then(t)}return t()},C=(e,t)=>__async(this,null,(function*(){yield t();const s=e.internalModel;if(s){const t=e.settings,i=N.findRuntime(t);if(i){const r=[];t.pose&&r.push(A.load({settings:t,url:t.pose,type:"json",target:s}).then((t=>{s.pose=i.createPose(s.coreModel,t),e.live2dModel.emit("poseLoaded",s.pose)})).catch((t=>{e.live2dModel.emit("poseLoadError",t),l.warn(R,"Failed to load pose.",t)}))),t.physics&&r.push(A.load({settings:t,url:t.physics,type:"json",target:s}).then((t=>{s.physics=i.createPhysics(s.coreModel,t),e.live2dModel.emit("physicsLoaded",s.physics)})).catch((t=>{e.live2dModel.emit("physicsLoadError",t),l.warn(R,"Failed to load physics.",t)}))),r.length&&(yield Promise.all(r))}}})),k=(e,t)=>__async(this,null,(function*(){if(!e.settings)throw new TypeError("Missing settings.");{const s=e.live2dModel,r=e.settings.textures.map((t=>function(e,t={}){const s={resourceOptions:{crossorigin:t.crossOrigin}};if(i.Texture.fromURL)return i.Texture.fromURL(e,s).catch((e=>{if(e instanceof Error)throw e;const t=new Error("Texture loading error");throw t.event=e,t}));s.resourceOptions.autoLoad=!1;const r=i.Texture.from(e,s);if(r.baseTexture.valid)return Promise.resolve(r);const o=r.baseTexture.resource;return null!=o._live2d_load||(o._live2d_load=new Promise(((e,t)=>{const s=e=>{o.source.removeEventListener("error",s);const i=new Error("Texture loading error");i.event=e,t(i)};o.source.addEventListener("error",s),o.load().then((()=>e(r))).catch(s)}))),o._live2d_load}(e.settings.resolveURL(t),{crossOrigin:e.options.crossOrigin})));if(yield t(),!e.internalModel)throw new TypeError("Missing internal model.");s.internalModel=e.internalModel,s.emit("modelLoaded",e.internalModel),s.textures=yield Promise.all(r),s.emit("textureLoaded",s.textures)}})),U=(e,t)=>__async(this,null,(function*(){const s=e.settings;if(s instanceof y){const i=N.findRuntime(s);if(!i)throw new TypeError("Unknown model settings.");const r=yield A.load({settings:s,url:s.moc,type:"arraybuffer",target:e.live2dModel});if(!i.isValidMoc(r))throw new Error("Invalid moc data");const o=i.createCoreModel(r);return e.internalModel=i.createInternalModel(o,s,e.options),t()}throw new TypeError("Missing settings.")})),G=class{static registerRuntime(e){G.runtimes.push(e),G.runtimes.sort(((e,t)=>t.version-e.version))}static findRuntime(e){for(const t of G.runtimes)if(t.test(e))return t}static setupLive2DModel(e,t,s){return __async(this,null,(function*(){const i=new Promise((t=>e.once("textureLoaded",t))),r=new Promise((t=>e.once("modelLoaded",t))),o=Promise.all([i,r]).then((()=>e.emit("ready")));yield O(G.live2DModelMiddlewares,{live2dModel:e,source:t,options:s||{}}),yield o,e.emit("load")}))}static loadMotion(e,t,s){var i;const r=i=>e.emit("motionLoadError",t,s,i);try{const o=null==(i=e.definitions[t])?void 0:i[s];if(!o)return Promise.resolve(void 0);e.listeners("destroy").includes(G.releaseTasks)||e.once("destroy",G.releaseTasks);let n=G.motionTasksMap.get(e);n||(n={},G.motionTasksMap.set(e,n));let a=n[t];a||(a=[],n[t]=a);const d=e.getMotionFile(o);return null!=a[s]||(a[s]=A.load({url:d,settings:e.settings,type:e.motionDataType,target:e}).then((i=>{var r;const n=null==(r=G.motionTasksMap.get(e))?void 0:r[t];n&&delete n[s];const a=e.createMotion(i,t,o);return e.emit("motionLoaded",t,s,a),a})).catch((t=>{l.warn(e.tag,`Failed to load motion: ${d}\n`,t),r(t)}))),a[s]}catch(o){l.warn(e.tag,`Failed to load motion at "${t}"[${s}]\n`,o),r(o)}return Promise.resolve(void 0)}static loadExpression(e,t){const s=s=>e.emit("expressionLoadError",t,s);try{const i=e.definitions[t];if(!i)return Promise.resolve(void 0);e.listeners("destroy").includes(G.releaseTasks)||e.once("destroy",G.releaseTasks);let r=G.expressionTasksMap.get(e);r||(r=[],G.expressionTasksMap.set(e,r));const o=e.getExpressionFile(i);return null!=r[t]||(r[t]=A.load({url:o,settings:e.settings,type:"json",target:e}).then((s=>{const r=G.expressionTasksMap.get(e);r&&delete r[t];const o=e.createExpression(s,i);return e.emit("expressionLoaded",t,o),o})).catch((t=>{l.warn(e.tag,`Failed to load expression: ${o}\n`,t),s(t)}))),r[t]}catch(i){l.warn(e.tag,`Failed to load expression at [${t}]\n`,i),s(i)}return Promise.resolve(void 0)}static releaseTasks(){this instanceof P?G.motionTasksMap.delete(this):G.expressionTasksMap.delete(this)}};let N=G;N.runtimes=[],N.urlToJSON=F,N.jsonToSettings=D,N.waitUntilReady=S,N.setupOptionals=C,N.setupEssentials=k,N.createInternalModel=U,N.live2DModelMiddlewares=[F,D,S,C,k,U],N.motionTasksMap=new WeakMap,N.expressionTasksMap=new WeakMap,P.prototype._loadMotion=function(e,t){return N.loadMotion(this,e,t)},f.prototype._loadExpression=function(e){return N.loadExpression(this,e)};class j{constructor(){this._autoInteract=!1}get autoInteract(){return this._autoInteract}set autoInteract(e){e!==this._autoInteract&&(e?this.on("pointertap",X,this):this.off("pointertap",X,this),this._autoInteract=e)}registerInteraction(e){e!==this.interactionManager&&(this.unregisterInteraction(),this._autoInteract&&e&&(this.interactionManager=e,e.on("pointermove",H,this)))}unregisterInteraction(){var e;this.interactionManager&&(null==(e=this.interactionManager)||e.off("pointermove",H,this),this.interactionManager=void 0)}}function X(e){this.tap(e.data.global.x,e.data.global.y)}function H(e){this.focus(e.data.global.x,e.data.global.y)}class W extends s.Transform{}const $=new s.Point,q=new s.Matrix;let V;class Y extends r.Container{constructor(e){super(),this.tag="Live2DModel(uninitialized)",this.textures=[],this.transform=new W,this.anchor=new s.ObservablePoint(this.onAnchorChange,this,0,0),this.glContextID=-1,this.elapsedTime=performance.now(),this.deltaTime=0,this._autoUpdate=!1,this.once("modelLoaded",(()=>this.init(e)))}static from(e,t){const s=new this(t);return N.setupLive2DModel(s,e,t).then((()=>s))}static fromSync(e,t){const s=new this(t);return N.setupLive2DModel(s,e,t).then(null==t?void 0:t.onLoad).catch(null==t?void 0:t.onError),s}static registerTicker(e){V=e}get autoUpdate(){return this._autoUpdate}set autoUpdate(e){var t;V||(V=null==(t=window.PIXI)?void 0:t.Ticker),e?this._destroyed||(V?(V.shared.add(this.onTickerUpdate,this),this._autoUpdate=!0):l.warn(this.tag,"No Ticker registered, please call Live2DModel.registerTicker(Ticker).")):(null==V||V.shared.remove(this.onTickerUpdate,this),this._autoUpdate=!1)}init(e){this.tag=`Live2DModel(${this.internalModel.settings.name})`;const t=Object.assign({autoUpdate:!0,autoInteract:!0},e);t.autoInteract&&(this.interactive=!0),this.autoInteract=t.autoInteract,this.autoUpdate=t.autoUpdate}onAnchorChange(){this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(e,t,{priority:s=2,sound:i,volume:r=1,expression:o,resetExpression:n=!0}={}){return void 0===t?this.internalModel.motionManager.startRandomMotion(e,s,{sound:i,volume:r,expression:o,resetExpression:n}):this.internalModel.motionManager.startMotion(e,t,s,{sound:i,volume:r,expression:o,resetExpression:n})}resetMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(e,{volume:t=1,expression:s,resetExpression:i=!0}={}){return this.internalModel.motionManager.speakUp(e,{volume:t,expression:s,resetExpression:i})}stopSpeaking(){return this.internalModel.motionManager.stopSpeaking()}expression(e){return this.internalModel.motionManager.expressionManager?void 0===e?this.internalModel.motionManager.expressionManager.setRandomExpression():this.internalModel.motionManager.expressionManager.setExpression(e):Promise.resolve(!1)}focus(e,t,s=!1){$.x=e,$.y=t,this.toModelPosition($,$,!0);let i=$.x/this.internalModel.originalWidth*2-1,r=$.y/this.internalModel.originalHeight*2-1,o=Math.atan2(r,i);this.internalModel.focusController.focus(Math.cos(o),-Math.sin(o),s)}tap(e,t){const s=this.hitTest(e,t);s.length&&(l.log(this.tag,"Hit",s),this.emit("hit",s))}hitTest(e,t){return $.x=e,$.y=t,this.toModelPosition($,$),this.internalModel.hitTest($.x,$.y)}toModelPosition(e,t=e.clone(),s){return s||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.transform.worldTransform.applyInverse(e,t),this.internalModel.localTransform.applyInverse(t,t),t}containsPoint(e){return this.getBounds(!0).contains(e.x,e.y)}_calculateBounds(){this._bounds.addFrame(this.transform,0,0,this.internalModel.width,this.internalModel.height)}onTickerUpdate(){this.update(V.shared.deltaMS)}update(e){this.deltaTime+=e,this.elapsedTime+=e}_render(e){this.registerInteraction(e.plugins.interaction),e.batch.reset(),e.geometry.reset(),e.shader.reset(),e.state.reset();let t=!1;this.glContextID!==e.CONTEXT_UID&&(this.glContextID=e.CONTEXT_UID,this.internalModel.updateWebGLContext(e.gl,this.glContextID),t=!0);for(let r=0;rt.destroy(e.baseTexture))),this.internalModel.destroy(),super.destroy(e)}}p(Y,[j]);const z=class{static resolveURL(e,t){var s;const i=null==(s=z.filesMap[e])?void 0:s[t];if(void 0===i)throw new Error("Cannot find this file from uploaded files: "+t);return i}static upload(e,s){return __async(this,null,(function*(){const i={};for(const r of s.getDefinedFiles()){const o=decodeURI(t.url.resolve(s.url,r)),n=e.find((e=>e.webkitRelativePath===o));n&&(i[r]=URL.createObjectURL(n))}z.filesMap[s._objectURL]=i}))}static createSettings(e){return __async(this,null,(function*(){const t=e.find((e=>e.name.endsWith("model.json")||e.name.endsWith("model3.json")));if(!t)throw new TypeError("Settings file not found");const s=yield z.readText(t),i=JSON.parse(s);i.url=t.webkitRelativePath;const r=N.findRuntime(i);if(!r)throw new Error("Unknown settings JSON");const o=r.createModelSettings(i);return o._objectURL=URL.createObjectURL(t),o}))}static readText(e){return __async(this,null,(function*(){return new Promise(((t,s)=>{const i=new FileReader;i.onload=()=>t(i.result),i.onerror=s,i.readAsText(e,"utf8")}))}))}};let B=z;B.filesMap={},B.factory=(e,t)=>__async(this,null,(function*(){if(Array.isArray(e.source)&&e.source[0]instanceof File){const t=e.source;let s=t.settings;if(s){if(!s._objectURL)throw new Error('"_objectURL" must be specified in ModelSettings')}else s=yield z.createSettings(t);s.validateFiles(t.map((e=>encodeURI(e.webkitRelativePath)))),yield z.upload(t,s),s.resolveURL=function(e){return z.resolveURL(this._objectURL,e)},e.source=s,e.live2dModel.once("modelLoaded",(e=>{e.once("destroy",(function(){const e=this.settings._objectURL;if(URL.revokeObjectURL(e),z.filesMap[e])for(const t of Object.values(z.filesMap[e]))URL.revokeObjectURL(t);delete z.filesMap[e]}))}))}return t()})),N.live2DModelMiddlewares.unshift(B.factory);const J=class{static unzip(e,s){return __async(this,null,(function*(){const i=yield J.getFilePaths(e),r=[];for(const e of s.getDefinedFiles()){const o=decodeURI(t.url.resolve(s.url,e));i.includes(o)&&r.push(o)}const o=yield J.getFiles(e,r);for(let e=0;ee.endsWith("model.json")||e.endsWith("model3.json")));if(!t)throw new Error("Settings file not found");const s=yield J.readText(e,t);if(!s)throw new Error("Empty settings file: "+t);const i=JSON.parse(s);i.url=t;const r=N.findRuntime(i);if(!r)throw new Error("Unknown settings JSON");return r.createModelSettings(i)}))}static zipReader(e,t){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static getFilePaths(e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static getFiles(e,t){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static readText(e,t){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static releaseReader(e){}};let Z=J;if(Z.ZIP_PROTOCOL="zip://",Z.uid=0,Z.factory=(e,t)=>__async(this,null,(function*(){const s=e.source;let i,r,o;if("string"==typeof s&&(s.endsWith(".zip")||s.startsWith(J.ZIP_PROTOCOL))?(i=s.startsWith(J.ZIP_PROTOCOL)?s.slice(J.ZIP_PROTOCOL.length):s,r=yield A.load({url:i,type:"blob",target:e.live2dModel})):Array.isArray(s)&&1===s.length&&s[0]instanceof File&&s[0].name.endsWith(".zip")&&(r=s[0],i=URL.createObjectURL(r),o=s.settings),r){if(!r.size)throw new Error("Empty zip file");const t=yield J.zipReader(r,i);o||(o=yield J.createSettings(t)),o._objectURL=J.ZIP_PROTOCOL+J.uid+"/"+o.url;const s=yield J.unzip(t,o);s.settings=o,e.source=s,i.startsWith("blob:")&&e.live2dModel.once("modelLoaded",(e=>{e.once("destroy",(function(){URL.revokeObjectURL(i)}))})),J.releaseReader(t)}return t()})),N.live2DModelMiddlewares.unshift(Z.factory),!window.Live2D)throw new Error("Could not find Cubism 2 runtime. This plugin requires live2d.min.js to be loaded.");const Q=Live2DMotion.prototype.updateParam;Live2DMotion.prototype.updateParam=function(e,t){Q.call(this,e,t),t.isFinished()&&this.onFinishHandler&&(this.onFinishHandler(this),delete this.onFinishHandler)};class K extends AMotion{constructor(t){super(),this.params=[],this.setFadeIn(t.fade_in>0?t.fade_in:e.config.expressionFadingDuration),this.setFadeOut(t.fade_out>0?t.fade_out:e.config.expressionFadingDuration),Array.isArray(t.params)&&t.params.forEach((e=>{const t=e.calc||"add";if("add"===t){const t=e.def||0;e.val-=t}else if("mult"===t){const t=e.def||1;e.val/=t}this.params.push({calc:t,val:e.val,id:e.id})}))}updateParamExe(e,t,s,i){this.params.forEach((t=>{e.setParamFloat(t.id,t.val*s)}))}}class ee extends f{constructor(e,t){var s;super(e,t),this.queueManager=new MotionQueueManager,this.definitions=null!=(s=this.settings.expressions)?s:[],this.init()}isFinished(){return this.queueManager.isFinished()}getExpressionIndex(e){return this.definitions.findIndex((t=>t.name===e))}getExpressionFile(e){return e.file}createExpression(e,t){return new K(e)}_setExpression(e){return this.queueManager.startMotion(e)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(e,t){return this.queueManager.updateParam(e)}}class te extends P{constructor(e,t){super(e,t),this.groups={idle:"idle"},this.motionDataType="arraybuffer",this.queueManager=new MotionQueueManager,this.definitions=this.settings.motions,this.init(t),this.lipSyncIds=["PARAM_MOUTH_OPEN_Y"]}init(e){super.init(e),this.settings.expressions&&(this.expressionManager=new ee(this.settings,e))}isFinished(){return this.queueManager.isFinished()}createMotion(t,s,i){const r=Live2DMotion.loadMotion(t),o=s===this.groups.idle?e.config.idleMotionFadingDuration:e.config.motionFadingDuration;return r.setFadeIn(i.fade_in>0?i.fade_in:o),r.setFadeOut(i.fade_out>0?i.fade_out:o),r}getMotionFile(e){return e.file}getMotionName(e){return e.file}getSoundFile(e){return e.sound}_startMotion(e,t){return e.onFinishHandler=t,this.queueManager.stopAllMotions(),this.queueManager.startMotion(e)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(e,t){return this.queueManager.updateParam(e)}destroy(){super.destroy(),this.queueManager=void 0}}class se{constructor(e){this.coreModel=e,this.blinkInterval=4e3,this.closingDuration=100,this.closedDuration=50,this.openingDuration=150,this.eyeState=0,this.eyeParamValue=1,this.closedTimer=0,this.nextBlinkTimeLeft=this.blinkInterval,this.leftParam=e.getParamIndex("PARAM_EYE_L_OPEN"),this.rightParam=e.getParamIndex("PARAM_EYE_R_OPEN")}setEyeParams(e){this.eyeParamValue=d(e,0,1),this.coreModel.setParamFloat(this.leftParam,this.eyeParamValue),this.coreModel.setParamFloat(this.rightParam,this.eyeParamValue)}update(e){switch(this.eyeState){case 0:this.nextBlinkTimeLeft-=e,this.nextBlinkTimeLeft<0&&(this.eyeState=1,this.nextBlinkTimeLeft=this.blinkInterval+this.closingDuration+this.closedDuration+this.openingDuration+h(0,2e3));break;case 1:this.setEyeParams(this.eyeParamValue+e/this.closingDuration),this.eyeParamValue<=0&&(this.eyeState=2,this.closedTimer=0);break;case 2:this.closedTimer+=e,this.closedTimer>=this.closedDuration&&(this.eyeState=3);break;case 3:this.setEyeParams(this.eyeParamValue+e/this.openingDuration),this.eyeParamValue>=1&&(this.eyeState=0)}}}const ie=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class re extends I{constructor(e,t,s){super(),this.textureFlipY=!0,this.lipSync=!0,this.drawDataCount=0,this.disableCulling=!1,this.coreModel=e,this.settings=t,this.motionManager=new te(t,s),this.eyeBlink=new se(e),this.eyeballXParamIndex=e.getParamIndex("PARAM_EYE_BALL_X"),this.eyeballYParamIndex=e.getParamIndex("PARAM_EYE_BALL_Y"),this.angleXParamIndex=e.getParamIndex("PARAM_ANGLE_X"),this.angleYParamIndex=e.getParamIndex("PARAM_ANGLE_Y"),this.angleZParamIndex=e.getParamIndex("PARAM_ANGLE_Z"),this.bodyAngleXParamIndex=e.getParamIndex("PARAM_BODY_ANGLE_X"),this.breathParamIndex=e.getParamIndex("PARAM_BREATH"),this.mouthFormIndex=e.getParamIndex("PARAM_MOUTH_FORM"),this.init()}init(){super.init(),this.settings.initParams&&this.settings.initParams.forEach((({id:e,value:t})=>this.coreModel.setParamFloat(e,t))),this.settings.initOpacities&&this.settings.initOpacities.forEach((({id:e,value:t})=>this.coreModel.setPartsOpacity(e,t))),this.coreModel.saveParam();const e=this.coreModel.getModelContext()._$aS;(null==e?void 0:e.length)&&(this.drawDataCount=e.length);let t=this.coreModel.drawParamWebGL.culling;Object.defineProperty(this.coreModel.drawParamWebGL,"culling",{set:e=>t=e,get:()=>!this.disableCulling&&t});const s=this.coreModel.getModelContext().clipManager,i=s.setupClip;s.setupClip=(e,t)=>{i.call(s,e,t),t.gl.viewport(...this.viewport)}}getSize(){return[this.coreModel.getCanvasWidth(),this.coreModel.getCanvasHeight()]}getLayout(){const e={};if(this.settings.layout)for(const t of Object.keys(this.settings.layout)){let s=t;"center_x"===t?s="centerX":"center_y"===t&&(s="centerY"),e[s]=this.settings.layout[t]}return e}updateWebGLContext(e,t){const s=this.coreModel.drawParamWebGL;s.firstDraw=!0,s.setGL(e),s.glno=t;for(const o in s)s.hasOwnProperty(o)&&s[o]instanceof WebGLBuffer&&(s[o]=null);const i=this.coreModel.getModelContext().clipManager;i.curFrameNo=t;const r=e.getParameter(e.FRAMEBUFFER_BINDING);i.getMaskRenderTexture(),e.bindFramebuffer(e.FRAMEBUFFER,r)}bindTexture(e,t){this.coreModel.setTexture(e,t)}getHitAreaDefs(){var e;return(null==(e=this.settings.hitAreas)?void 0:e.map((e=>({id:e.id,name:e.name,index:this.coreModel.getDrawDataIndex(e.id)}))))||[]}getDrawableIDs(){const e=this.coreModel.getModelContext(),t=[];for(let s=0;s0&&(t=.4),e=d(e*1.2,t,1);for(let s=0;s0&&e.textures.every((e=>"string"==typeof e))}copy(e){u("string",e,this,"name","name"),u("string",e,this,"pose","pose"),u("string",e,this,"physics","physics"),u("object",e,this,"layout","layout"),u("object",e,this,"motions","motions"),c("object",e,this,"hit_areas","hitAreas"),c("object",e,this,"expressions","expressions"),c("object",e,this,"init_params","initParams"),c("object",e,this,"init_opacities","initOpacities")}replaceFiles(e){super.replaceFiles(e);for(const[t,s]of Object.entries(this.motions))for(let i=0;i{const t=new PhysicsHair;return t.setup(e.setup.length,e.setup.regist,e.setup.mass),e.src.forEach((({id:e,ptype:s,scale:i,weight:r})=>{const o=ne[s];o&&t.addSrcParam(o,e,i,r)})),e.targets.forEach((({id:e,ptype:s,scale:i,weight:r})=>{const o=ae[s];o&&t.addTargetParam(o,e,i,r)})),t})))}update(e){this.physicsHairs.forEach((t=>t.update(this.coreModel,e)))}}class de{constructor(e){this.id=e,this.paramIndex=-1,this.partsIndex=-1,this.link=[]}initIndex(e){this.paramIndex=e.getParamIndex("VISIBLE:"+this.id),this.partsIndex=e.getPartsDataIndex(PartsDataID.getID(this.id)),e.setParamFloat(this.paramIndex,1)}}class he{constructor(e,t){this.coreModel=e,this.opacityAnimDuration=500,this.partsGroups=[],t.parts_visible&&(this.partsGroups=t.parts_visible.map((({group:e})=>e.map((({id:e,link:t})=>{const s=new de(e);return t&&(s.link=t.map((e=>new de(e)))),s})))),this.init())}init(){this.partsGroups.forEach((e=>{e.forEach((e=>{if(e.initIndex(this.coreModel),e.paramIndex>=0){const t=0!==this.coreModel.getParamFloat(e.paramIndex);this.coreModel.setPartsOpacity(e.partsIndex,t?1:0),this.coreModel.setParamFloat(e.paramIndex,t?1:0),e.link.length>0&&e.link.forEach((e=>e.initIndex(this.coreModel)))}}))}))}normalizePartsOpacityGroup(e,t){const s=this.coreModel,i=.5;let r=1,o=e.findIndex((({paramIndex:e,partsIndex:t})=>t>=0&&0!==s.getParamFloat(e)));if(o>=0){const i=s.getPartsOpacity(e[o].partsIndex);r=d(i+t/this.opacityAnimDuration,0,1)}else o=0,r=1;e.forEach((({partsIndex:e},t)=>{if(e>=0)if(o==t)s.setPartsOpacity(e,r);else{let t,o=s.getPartsOpacity(e);t=r.15&&(t=1-.15/(1-r)),o>t&&(o=t),s.setPartsOpacity(e,o)}}))}copyOpacity(e){const t=this.coreModel;e.forEach((({partsIndex:e,link:s})=>{if(e>=0&&s){const i=t.getPartsOpacity(e);s.forEach((({partsIndex:e})=>{e>=0&&t.setPartsOpacity(e,i)}))}}))}update(e){this.partsGroups.forEach((t=>{this.normalizePartsOpacityGroup(t,e),this.copyOpacity(t)}))}}N.registerRuntime({version:2,test:e=>e instanceof oe||oe.isValidJSON(e),ready:()=>Promise.resolve(),isValidMoc(e){if(e.byteLength<3)return!1;const t=new Int8Array(e,0,3);return"moc"===String.fromCharCode(...t)},createModelSettings:e=>new oe(e),createCoreModel(e){const t=Live2DModelWebGL.loadModel(e),s=Live2D.getError();if(s)throw s;return t},createInternalModel:(e,t,s)=>new re(e,t,s),createPose:(e,t)=>new he(e,t),createPhysics:(e,t)=>new le(e,t)}),e.Cubism2ExpressionManager=ee,e.Cubism2InternalModel=re,e.Cubism2ModelSettings=oe,e.Cubism2MotionManager=te,e.ExpressionManager=f,e.FileLoader=B,e.FocusController=x,e.InteractionMixin=j,e.InternalModel=I,e.LOGICAL_HEIGHT=2,e.LOGICAL_WIDTH=2,e.Live2DExpression=K,e.Live2DEyeBlink=se,e.Live2DFactory=N,e.Live2DLoader=A,e.Live2DModel=Y,e.Live2DPhysics=le,e.Live2DPose=he,e.Live2DTransform=W,e.ModelSettings=y,e.MotionManager=P,e.MotionPreloadStrategy=w,e.MotionPriority=M,e.MotionState=v,e.SoundManager=E,e.VERSION="0.4.0",e.XHRLoader=T,e.ZipLoader=Z,e.applyMixins=p,e.clamp=d,e.copyArray=c,e.copyProperty=u,e.folderName=g,e.logger=l,e.rand=h,e.remove=m,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})); diff --git a/dist/cubism4.es.js b/dist/cubism4.es.js index 6a7e7d7a..ed97897c 100644 --- a/dist/cubism4.es.js +++ b/dist/cubism4.es.js @@ -5039,8 +5039,8 @@ class MotionManager extends EventEmitter { _loadMotion(group, index) { throw new Error("Not implemented."); } - speakUp(sound, volume, expression) { - return __async(this, null, function* () { + speakUp(_0) { + return __async(this, arguments, function* (sound, { volume = 1, expression, resetExpression = true } = {}) { if (!config.sound) { return false; } @@ -5071,10 +5071,10 @@ class MotionManager extends EventEmitter { if (file) { try { audio = SoundManager.add(file, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }); this.currentAudio = audio; @@ -5108,7 +5108,7 @@ class MotionManager extends EventEmitter { }); } startMotion(_0, _1) { - return __async(this, arguments, function* (group, index, priority = MotionPriority.NORMAL, sound, volume, expression) { + return __async(this, arguments, function* (group, index, priority = MotionPriority.NORMAL, { sound = void 0, volume = 1, expression = void 0, resetExpression = true } = {}) { var _a; if (this.currentAudio) { if (!this.currentAudio.ended) { @@ -5148,10 +5148,10 @@ class MotionManager extends EventEmitter { if (file) { try { audio = SoundManager.add(file, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }); this.currentAudio = audio; @@ -5197,8 +5197,8 @@ class MotionManager extends EventEmitter { return true; }); } - startRandomMotion(group, priority, sound, volume) { - return __async(this, null, function* () { + startRandomMotion(_0, _1) { + return __async(this, arguments, function* (group, priority, { sound = void 0, volume = 1, expression = void 0, resetExpression = true } = {}) { const groupDefs = this.definitions[group]; if (groupDefs == null ? void 0 : groupDefs.length) { const availableIndices = []; @@ -5209,7 +5209,12 @@ class MotionManager extends EventEmitter { } if (availableIndices.length) { const index = availableIndices[Math.floor(Math.random() * availableIndices.length)]; - return this.startMotion(group, index, priority, sound, volume); + return this.startMotion(group, index, priority, { + sound, + volume, + expression, + resetExpression + }); } } return false; @@ -5855,14 +5860,28 @@ class Live2DModel extends Container { onAnchorChange() { this.pivot.set(this.anchor.x * this.internalModel.width, this.anchor.y * this.internalModel.height); } - motion(group, index, priority, sound, volume, expression) { - return index === void 0 ? this.internalModel.motionManager.startRandomMotion(group, priority) : this.internalModel.motionManager.startMotion(group, index, priority, sound, volume, expression); + motion(group, index, { priority = 2, sound, volume = 1, expression, resetExpression = true } = {}) { + return index === void 0 ? this.internalModel.motionManager.startRandomMotion(group, priority, { + sound, + volume, + expression, + resetExpression + }) : this.internalModel.motionManager.startMotion(group, index, priority, { + sound, + volume, + expression, + resetExpression + }); } resetMotions() { return this.internalModel.motionManager.stopAllMotions(); } - speak(sound, volume, expression) { - return this.internalModel.motionManager.speakUp(sound, volume, expression); + speak(sound, { volume = 1, expression, resetExpression = true } = {}) { + return this.internalModel.motionManager.speakUp(sound, { + volume, + expression, + resetExpression + }); } stopSpeaking() { return this.internalModel.motionManager.stopSpeaking(); @@ -6310,6 +6329,7 @@ class Cubism4InternalModel extends InternalModel { this.idParamEyeBallY = ParamEyeBallY; this.idParamBodyAngleX = ParamBodyAngleX; this.idParamBreath = ParamBreath; + this.idParamMouthForm = ParamMouthForm; this.pixelsPerUnit = 1; this.centeringTransform = new Matrix(); this.coreModel = coreModel; @@ -6412,6 +6432,19 @@ class Cubism4InternalModel extends InternalModel { } this.updateFocus(); this.updateNaturalMovements(dt * 1e3, now * 1e3); + if (this.lipSync && this.motionManager.currentAudio) { + let value = this.motionManager.mouthSync(); + let min_ = 0; + let max_ = 1; + let weight = 1.2; + if (value > 0) { + min_ = 0.4; + } + value = clamp(value * weight, min_, max_); + for (let i = 0; i < this.motionManager.lipSyncIds.length; ++i) { + model.addParameterValueById(this.motionManager.lipSyncIds[i], value, 0.8); + } + } (_c = this.physics) == null ? void 0 : _c.evaluate(model, dt); (_d = this.pose) == null ? void 0 : _d.updateParameters(model, dt); this.emit("beforeModelUpdate"); @@ -6426,6 +6459,9 @@ class Cubism4InternalModel extends InternalModel { this.coreModel.addParameterValueById(this.idParamAngleZ, this.focusController.x * this.focusController.y * -30); this.coreModel.addParameterValueById(this.idParamBodyAngleX, this.focusController.x * 10); } + updateFacialEmotion(mouthForm) { + this.coreModel.addParameterValueById(this.idParamMouthForm, mouthForm); + } updateNaturalMovements(dt, now) { var _a; (_a = this.breath) == null ? void 0 : _a.updateParameters(this.coreModel, dt / 1e3); diff --git a/dist/cubism4.js b/dist/cubism4.js index 1034a6e8..2d4a79b0 100644 --- a/dist/cubism4.js +++ b/dist/cubism4.js @@ -5039,8 +5039,8 @@ var __async = (__this, __arguments, generator) => { _loadMotion(group, index) { throw new Error("Not implemented."); } - speakUp(sound, volume, expression) { - return __async(this, null, function* () { + speakUp(_0) { + return __async(this, arguments, function* (sound, { volume = 1, expression, resetExpression = true } = {}) { if (!exports2.config.sound) { return false; } @@ -5071,10 +5071,10 @@ var __async = (__this, __arguments, generator) => { if (file) { try { audio = SoundManager.add(file, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }); this.currentAudio = audio; @@ -5108,7 +5108,7 @@ var __async = (__this, __arguments, generator) => { }); } startMotion(_0, _1) { - return __async(this, arguments, function* (group, index, priority = MotionPriority.NORMAL, sound, volume, expression) { + return __async(this, arguments, function* (group, index, priority = MotionPriority.NORMAL, { sound = void 0, volume = 1, expression = void 0, resetExpression = true } = {}) { var _a; if (this.currentAudio) { if (!this.currentAudio.ended) { @@ -5148,10 +5148,10 @@ var __async = (__this, __arguments, generator) => { if (file) { try { audio = SoundManager.add(file, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }); this.currentAudio = audio; @@ -5197,8 +5197,8 @@ var __async = (__this, __arguments, generator) => { return true; }); } - startRandomMotion(group, priority, sound, volume) { - return __async(this, null, function* () { + startRandomMotion(_0, _1) { + return __async(this, arguments, function* (group, priority, { sound = void 0, volume = 1, expression = void 0, resetExpression = true } = {}) { const groupDefs = this.definitions[group]; if (groupDefs == null ? void 0 : groupDefs.length) { const availableIndices = []; @@ -5209,7 +5209,12 @@ var __async = (__this, __arguments, generator) => { } if (availableIndices.length) { const index = availableIndices[Math.floor(Math.random() * availableIndices.length)]; - return this.startMotion(group, index, priority, sound, volume); + return this.startMotion(group, index, priority, { + sound, + volume, + expression, + resetExpression + }); } } return false; @@ -5855,14 +5860,28 @@ var __async = (__this, __arguments, generator) => { onAnchorChange() { this.pivot.set(this.anchor.x * this.internalModel.width, this.anchor.y * this.internalModel.height); } - motion(group, index, priority, sound, volume, expression) { - return index === void 0 ? this.internalModel.motionManager.startRandomMotion(group, priority) : this.internalModel.motionManager.startMotion(group, index, priority, sound, volume, expression); + motion(group, index, { priority = 2, sound, volume = 1, expression, resetExpression = true } = {}) { + return index === void 0 ? this.internalModel.motionManager.startRandomMotion(group, priority, { + sound, + volume, + expression, + resetExpression + }) : this.internalModel.motionManager.startMotion(group, index, priority, { + sound, + volume, + expression, + resetExpression + }); } resetMotions() { return this.internalModel.motionManager.stopAllMotions(); } - speak(sound, volume, expression) { - return this.internalModel.motionManager.speakUp(sound, volume, expression); + speak(sound, { volume = 1, expression, resetExpression = true } = {}) { + return this.internalModel.motionManager.speakUp(sound, { + volume, + expression, + resetExpression + }); } stopSpeaking() { return this.internalModel.motionManager.stopSpeaking(); @@ -6310,6 +6329,7 @@ var __async = (__this, __arguments, generator) => { this.idParamEyeBallY = ParamEyeBallY; this.idParamBodyAngleX = ParamBodyAngleX; this.idParamBreath = ParamBreath; + this.idParamMouthForm = ParamMouthForm; this.pixelsPerUnit = 1; this.centeringTransform = new math.Matrix(); this.coreModel = coreModel; @@ -6412,6 +6432,19 @@ var __async = (__this, __arguments, generator) => { } this.updateFocus(); this.updateNaturalMovements(dt * 1e3, now * 1e3); + if (this.lipSync && this.motionManager.currentAudio) { + let value = this.motionManager.mouthSync(); + let min_ = 0; + let max_ = 1; + let weight = 1.2; + if (value > 0) { + min_ = 0.4; + } + value = clamp(value * weight, min_, max_); + for (let i = 0; i < this.motionManager.lipSyncIds.length; ++i) { + model.addParameterValueById(this.motionManager.lipSyncIds[i], value, 0.8); + } + } (_c = this.physics) == null ? void 0 : _c.evaluate(model, dt); (_d = this.pose) == null ? void 0 : _d.updateParameters(model, dt); this.emit("beforeModelUpdate"); @@ -6426,6 +6459,9 @@ var __async = (__this, __arguments, generator) => { this.coreModel.addParameterValueById(this.idParamAngleZ, this.focusController.x * this.focusController.y * -30); this.coreModel.addParameterValueById(this.idParamBodyAngleX, this.focusController.x * 10); } + updateFacialEmotion(mouthForm) { + this.coreModel.addParameterValueById(this.idParamMouthForm, mouthForm); + } updateNaturalMovements(dt, now) { var _a; (_a = this.breath) == null ? void 0 : _a.updateParameters(this.coreModel, dt / 1e3); diff --git a/dist/cubism4.min.js b/dist/cubism4.min.js index 4f1c6e1f..b50a93be 100644 --- a/dist/cubism4.min.js +++ b/dist/cubism4.min.js @@ -1 +1 @@ -var __pow=Math.pow,__async=(t,e,i)=>new Promise(((s,r)=>{var o=t=>{try{n(i.next(t))}catch(e){r(e)}},a=t=>{try{n(i.throw(t))}catch(e){r(e)}},n=t=>t.done?s(t.value):Promise.resolve(t.value).then(o,a);n((i=i.apply(t,e)).next())}));!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("@pixi/utils"),require("@pixi/math"),require("@pixi/core"),require("@pixi/display")):"function"==typeof define&&define.amd?define(["exports","@pixi/utils","@pixi/math","@pixi/core","@pixi/display"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).PIXI=t.PIXI||{},t.PIXI.live2d=t.PIXI.live2d||{}),t.PIXI.utils,t.PIXI,t.PIXI,t.PIXI)}(this,(function(t,e,i,s,r){"use strict";class o{constructor(){this._breathParameters=[],this._currentTime=0}static create(){return new o}setParameters(t){this._breathParameters=t}getParameters(){return this._breathParameters}updateParameters(t,e){this._currentTime+=e;const i=2*this._currentTime*3.14159;for(let s=0;s=1&&(s=1,this._blinkingState=h.EyeState_Closed,this._stateStartTimeSeconds=this._userTimeSeconds),i=1-s;break;case h.EyeState_Closed:s=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._closedSeconds,s>=1&&(this._blinkingState=h.EyeState_Opening,this._stateStartTimeSeconds=this._userTimeSeconds),i=0;break;case h.EyeState_Opening:s=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._openingSeconds,s>=1&&(s=1,this._blinkingState=h.EyeState_Interval,this._nextBlinkingTime=this.determinNextBlinkingTiming()),i=s;break;case h.EyeState_Interval:this._nextBlinkingTime(t[t.EyeState_First=0]="EyeState_First",t[t.EyeState_Interval=1]="EyeState_Interval",t[t.EyeState_Closing=2]="EyeState_Closing",t[t.EyeState_Closed=3]="EyeState_Closed",t[t.EyeState_Opening=4]="EyeState_Opening",t))(h||{});class u{static create(t){const e=new u;"number"==typeof t.FadeInTime&&(e._fadeTimeSeconds=t.FadeInTime,e._fadeTimeSeconds<=0&&(e._fadeTimeSeconds=.5));const i=t.Groups,s=i.length;for(let r=0;r.001){if(r>=0)break;r=n,o=t.getPartOpacityByIndex(i),o+=e/this._fadeTimeSeconds,o>1&&(o=1)}}r<0&&(r=0,o=1);for(let n=i;n.15&&(i=1-.15/(1-o)),s>i&&(s=i),t.setPartOpacityByIndex(e,s)}}}constructor(){this._fadeTimeSeconds=.5,this._lastModel=void 0,this._partGroups=[],this._partGroupCounts=[]}}class d{constructor(t){this.parameterIndex=0,this.partIndex=0,this.partId="",this.link=[],null!=t&&this.assignment(t)}assignment(t){return this.partId=t.partId,this.link=t.link.map((t=>t.clone())),this}initialize(t){this.parameterIndex=t.getParameterIndex(this.partId),this.partIndex=t.getPartIndex(this.partId),t.setParameterValueByIndex(this.parameterIndex,1)}clone(){const t=new d;return t.partId=this.partId,t.parameterIndex=this.parameterIndex,t.partIndex=this.partIndex,t.link=this.link.map((t=>t.clone())),t}}class c{constructor(t,e){this.x=t||0,this.y=e||0}add(t){const e=new c(0,0);return e.x=this.x+t.x,e.y=this.y+t.y,e}substract(t){const e=new c(0,0);return e.x=this.x-t.x,e.y=this.y-t.y,e}multiply(t){const e=new c(0,0);return e.x=this.x*t.x,e.y=this.y*t.y,e}multiplyByScaler(t){return this.multiply(new c(t,t))}division(t){const e=new c(0,0);return e.x=this.x/t.x,e.y=this.y/t.y,e}divisionByScalar(t){return this.division(new c(t,t))}getLength(){return Math.sqrt(this.x*this.x+this.y*this.y)}getDistanceWith(t){return Math.sqrt((this.x-t.x)*(this.x-t.x)+(this.y-t.y)*(this.y-t.y))}dot(t){return this.x*t.x+this.y*t.y}normalize(){const t=Math.pow(this.x*this.x+this.y*this.y,.5);this.x=this.x/t,this.y=this.y/t}isEqual(t){return this.x==t.x&&this.y==t.y}isNotEqual(t){return!this.isEqual(t)}}const g=class{static range(t,e,i){return ti&&(t=i),t}static sin(t){return Math.sin(t)}static cos(t){return Math.cos(t)}static abs(t){return Math.abs(t)}static sqrt(t){return Math.sqrt(t)}static cbrt(t){if(0===t)return t;let e=t;const i=e<0;let s;return i&&(e=-e),e===1/0?s=1/0:(s=Math.exp(Math.log(e)/3),s=(e/(s*s)+2*s)/3),i?-s:s}static getEasingSine(t){return t<0?0:t>1?1:.5-.5*this.cos(t*Math.PI)}static max(t,e){return t>e?t:e}static min(t,e){return t>e?e:t}static degreesToRadian(t){return t/180*Math.PI}static radianToDegrees(t){return 180*t/Math.PI}static directionToRadian(t,e){let i=Math.atan2(e.y,e.x)-Math.atan2(t.y,t.x);for(;i<-Math.PI;)i+=2*Math.PI;for(;i>Math.PI;)i-=2*Math.PI;return i}static directionToDegrees(t,e){const i=this.directionToRadian(t,e);let s=this.radianToDegrees(i);return e.x-t.x>0&&(s=-s),s}static radianToDirection(t){const e=new c;return e.x=this.sin(t),e.y=this.cos(t),e}static quadraticEquation(t,e,i){return this.abs(t)1&&(t=1),e<0?e=0:e>1&&(e=1),i<0?i=0:i>1&&(i=1),s<0?s=0:s>1&&(s=1),this._modelColor.R=t,this._modelColor.G=e,this._modelColor.B=i,this._modelColor.A=s}getModelColor(){return Object.assign({},this._modelColor)}setIsPremultipliedAlpha(t){this._isPremultipliedAlpha=t}isPremultipliedAlpha(){return this._isPremultipliedAlpha}setIsCulling(t){this._isCulling=t}isCulling(){return this._isCulling}setAnisotropy(t){this._anisotropy=t}getAnisotropy(){return this._anisotropy}getModel(){return this._model}useHighPrecisionMask(t){this._useHighPrecisionMask=t}isUsingHighPrecisionMask(){return this._useHighPrecisionMask}constructor(){this._isCulling=!1,this._isPremultipliedAlpha=!1,this._anisotropy=0,this._modelColor=new y,this._useHighPrecisionMask=!1,this._mvpMatrix4x4=new _,this._mvpMatrix4x4.loadIdentity()}}var f=(t=>(t[t.CubismBlendMode_Normal=0]="CubismBlendMode_Normal",t[t.CubismBlendMode_Additive=1]="CubismBlendMode_Additive",t[t.CubismBlendMode_Multiplicative=2]="CubismBlendMode_Multiplicative",t))(f||{});class y{constructor(t=1,e=1,i=1,s=1){this.R=t,this.G=e,this.B=i,this.A=s}}let C,x=!1,M=!1;const v={vertexOffset:0,vertexStep:2};class P{static startUp(t){if(x)return T("CubismFramework.startUp() is already done."),x;if(Live2DCubismCore._isStarted)return x=!0,!0;if(Live2DCubismCore._isStarted=!0,C=t,C&&Live2DCubismCore.Logging.csmSetLogFunction(C.logFunction),x=!0,x){const t=Live2DCubismCore.Version.csmGetVersion(),e=(16711680&t)>>16,i=65535&t,s=t;T("Live2D Cubism Core version: {0}.{1}.{2} ({3})",("00"+((4278190080&t)>>24)).slice(-2),("00"+e).slice(-2),("0000"+i).slice(-4),s)}return T("CubismFramework.startUp() is complete."),x}static cleanUp(){x=!1,M=!1,C=void 0}static initialize(t=0){x?M?I("CubismFramework.initialize() skipped, already initialized."):(Live2DCubismCore.Memory.initializeAmountOfMemory(t),M=!0,T("CubismFramework.initialize() is complete.")):I("CubismFramework is not started.")}static dispose(){x?M?(p.staticRelease(),M=!1,T("CubismFramework.dispose() is complete.")):I("CubismFramework.dispose() skipped, not initialized."):I("CubismFramework is not started.")}static isStarted(){return x}static isInitialized(){return M}static coreLogFunction(t){Live2DCubismCore.Logging.csmGetLogFunction()&&Live2DCubismCore.Logging.csmGetLogFunction()(t)}static getLoggingLevel(){return null!=C?C.loggingLevel:b.LogLevel_Off}constructor(){}}var b=(t=>(t[t.LogLevel_Verbose=0]="LogLevel_Verbose",t[t.LogLevel_Debug=1]="LogLevel_Debug",t[t.LogLevel_Info=2]="LogLevel_Info",t[t.LogLevel_Warning=3]="LogLevel_Warning",t[t.LogLevel_Error=4]="LogLevel_Error",t[t.LogLevel_Off=5]="LogLevel_Off",t))(b||{});const S=()=>{};function w(t,...e){E.print(b.LogLevel_Debug,"[CSM][D]"+t+"\n",e)}function T(t,...e){E.print(b.LogLevel_Info,"[CSM][I]"+t+"\n",e)}function I(t,...e){E.print(b.LogLevel_Warning,"[CSM][W]"+t+"\n",e)}function L(t,...e){E.print(b.LogLevel_Error,"[CSM][E]"+t+"\n",e)}class E{static print(t,e,i){if(ti[e])))}static dumpBytes(t,e,i){for(let s=0;s0?this.print(t,"\n"):s%8==0&&s>0&&this.print(t," "),this.print(t,"{0} ",[255&e[s]]);this.print(t,"\n")}constructor(){}}class A{constructor(t=!1,e=new y){this.isOverwritten=t,this.Color=e}}class F{constructor(t=!1,e=new y){this.isOverwritten=t,this.Color=e}}class D{constructor(t=!1,e=!1){this.isOverwritten=t,this.isCulling=e}}class B{update(){this._model.update(),this._model.drawables.resetDynamicFlags()}getPixelsPerUnit(){return null==this._model?0:this._model.canvasinfo.PixelsPerUnit}getCanvasWidth(){return null==this._model?0:this._model.canvasinfo.CanvasWidth/this._model.canvasinfo.PixelsPerUnit}getCanvasHeight(){return null==this._model?0:this._model.canvasinfo.CanvasHeight/this._model.canvasinfo.PixelsPerUnit}saveParameters(){const t=this._model.parameters.count,e=this._savedParameters.length;for(let i=0;ie&&(e=this._model.parameters.minimumValues[t]),this._parameterValues[t]=1==i?e:this._parameterValues[t]=this._parameterValues[t]*(1-i)+e*i)}setParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.setParameterValueByIndex(s,e,i)}addParameterValueByIndex(t,e,i=1){this.setParameterValueByIndex(t,this.getParameterValueByIndex(t)+e*i)}addParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.addParameterValueByIndex(s,e,i)}multiplyParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.multiplyParameterValueByIndex(s,e,i)}multiplyParameterValueByIndex(t,e,i=1){this.setParameterValueByIndex(t,this.getParameterValueByIndex(t)*(1+(e-1)*i))}getDrawableIds(){return this._drawableIds.slice()}getDrawableIndex(t){const e=this._model.drawables.count;for(let i=0;ie&&(t=e);for(let i=0;i=0&&this._partChildDrawables[n].push(t)}}}constructor(t){this._model=t,this._savedParameters=[],this._parameterIds=[],this._drawableIds=[],this._partIds=[],this._isOverwrittenModelMultiplyColors=!1,this._isOverwrittenModelScreenColors=!1,this._isOverwrittenCullings=!1,this._modelOpacity=1,this._userMultiplyColors=[],this._userScreenColors=[],this._userCullings=[],this._userPartMultiplyColors=[],this._userPartScreenColors=[],this._partChildDrawables=[],this._notExistPartId={},this._notExistParameterId={},this._notExistParameterValues={},this._notExistPartOpacities={},this.initialize()}release(){this._model.release(),this._model=void 0}}class R{static create(t,e){if(e){if(!this.hasMocConsistency(t))throw new Error("Inconsistent MOC3.")}const i=Live2DCubismCore.Moc.fromArrayBuffer(t);if(i){const e=new R(i);return e._mocVersion=Live2DCubismCore.Version.csmGetMocVersion(i,t),e}throw new Error("Failed to CubismMoc.create().")}createModel(){let t;const e=Live2DCubismCore.Model.fromMoc(this._moc);if(e)return t=new B(e),++this._modelCount,t;throw new Error("Unknown error")}deleteModel(t){null!=t&&--this._modelCount}constructor(t){this._moc=t,this._modelCount=0,this._mocVersion=0}release(){this._moc._release(),this._moc=void 0}getLatestMocVersion(){return Live2DCubismCore.Version.csmGetLatestMocVersion()}getMocVersion(){return this._mocVersion}static hasMocConsistency(t){return 1===Live2DCubismCore.Moc.prototype.hasMocConsistency(t)}}class O{constructor(t,e){this._json=t}release(){this._json=void 0}getUserDataCount(){return this._json.Meta.UserDataCount}getTotalUserDataSize(){return this._json.Meta.TotalUserDataSize}getUserDataTargetType(t){return this._json.UserData[t].Target}getUserDataId(t){return this._json.UserData[t].Id}getUserDataValue(t){return this._json.UserData[t].Value}}class k{static create(t,e){const i=new k;return i.parseUserData(t,e),i}getArtMeshUserDatas(){return this._artMeshUserDataNode}parseUserData(t,e){const i=new O(t,e),s=i.getUserDataCount();for(let r=0;r0&&e.getEndTime()(t[t.ExpressionBlendType_Add=0]="ExpressionBlendType_Add",t[t.ExpressionBlendType_Multiply=1]="ExpressionBlendType_Multiply",t[t.ExpressionBlendType_Overwrite=2]="ExpressionBlendType_Overwrite",t))(G||{});t.CubismConfig=void 0,(N=t.CubismConfig||(t.CubismConfig={})).supportMoreMaskDivisions=!0,N.setOpacityFromMotion=!1;var X=(t=>(t[t.CubismMotionCurveTarget_Model=0]="CubismMotionCurveTarget_Model",t[t.CubismMotionCurveTarget_Parameter=1]="CubismMotionCurveTarget_Parameter",t[t.CubismMotionCurveTarget_PartOpacity=2]="CubismMotionCurveTarget_PartOpacity",t))(X||{}),z=(t=>(t[t.CubismMotionSegmentType_Linear=0]="CubismMotionSegmentType_Linear",t[t.CubismMotionSegmentType_Bezier=1]="CubismMotionSegmentType_Bezier",t[t.CubismMotionSegmentType_Stepped=2]="CubismMotionSegmentType_Stepped",t[t.CubismMotionSegmentType_InverseStepped=3]="CubismMotionSegmentType_InverseStepped",t))(z||{});class j{constructor(t=0,e=0){this.time=t,this.value=e}}class W{constructor(){this.basePointIndex=0,this.segmentType=0}}class H{constructor(){this.id="",this.type=0,this.segmentCount=0,this.baseSegmentIndex=0,this.fadeInTime=0,this.fadeOutTime=0}}class Y{constructor(){this.fireTime=0,this.value=""}}class q{constructor(){this.duration=0,this.loop=!1,this.curveCount=0,this.eventCount=0,this.fps=0,this.curves=[],this.segments=[],this.points=[],this.events=[]}}class ${constructor(t){this._json=t}release(){this._json=void 0}getMotionDuration(){return this._json.Meta.Duration}isMotionLoop(){return this._json.Meta.Loop||!1}getEvaluationOptionFlag(t){return J.EvaluationOptionFlag_AreBeziersRistricted==t&&!!this._json.Meta.AreBeziersRestricted}getMotionCurveCount(){return this._json.Meta.CurveCount}getMotionFps(){return this._json.Meta.Fps}getMotionTotalSegmentCount(){return this._json.Meta.TotalSegmentCount}getMotionTotalPointCount(){return this._json.Meta.TotalPointCount}getMotionFadeInTime(){return this._json.Meta.FadeInTime}getMotionFadeOutTime(){return this._json.Meta.FadeOutTime}getMotionCurveTarget(t){return this._json.Curves[t].Target}getMotionCurveId(t){return this._json.Curves[t].Id}getMotionCurveFadeInTime(t){return this._json.Curves[t].FadeInTime}getMotionCurveFadeOutTime(t){return this._json.Curves[t].FadeOutTime}getMotionCurveSegmentCount(t){return this._json.Curves[t].Segments.length}getMotionCurveSegment(t,e){return this._json.Curves[t].Segments[e]}getEventCount(){return this._json.Meta.UserDataCount||0}getTotalEventValueSize(){return this._json.Meta.TotalUserDataSize}getEventTime(t){return this._json.UserData[t].Time}getEventValue(t){return this._json.UserData[t].Value}}var J=(t=>(t[t.EvaluationOptionFlag_AreBeziersRistricted=0]="EvaluationOptionFlag_AreBeziersRistricted",t))(J||{});const Z="Opacity";function Q(t,e,i){const s=new j;return s.time=t.time+(e.time-t.time)*i,s.value=t.value+(e.value-t.value)*i,s}function K(t,e){let i=(e-t[0].time)/(t[1].time-t[0].time);return i<0&&(i=0),t[0].value+(t[1].value-t[0].value)*i}function tt(t,e){let i=(e-t[0].time)/(t[3].time-t[0].time);i<0&&(i=0);const s=Q(t[0],t[1],i),r=Q(t[1],t[2],i),o=Q(t[2],t[3],i),a=Q(s,r,i),n=Q(r,o,i);return Q(a,n,i).value}function et(t,e){const i=e,s=t[0].time,r=t[3].time,o=t[1].time,a=t[2].time,n=r-3*a+3*o-s,l=3*a-6*o+3*s,h=3*o-3*s,u=s-i,d=m.cardanoAlgorithmForBezier(n,l,h,u),c=Q(t[0],t[1],d),g=Q(t[1],t[2],d),_=Q(t[2],t[3],d),p=Q(c,g,d),f=Q(g,_,d);return Q(p,f,d).value}function it(t,e){return t[0].value}function st(t,e){return t[1].value}function rt(t,e,i){const s=t.curves[e];let r=-1;const o=s.baseSegmentIndex+s.segmentCount;let a=0;for(let l=s.baseSegmentIndex;li){r=l;break}if(-1==r)return t.points[a].value;const n=t.segments[r];return n.evaluate(t.points.slice(n.basePointIndex),i)}class ot extends U{constructor(){super(),this._eyeBlinkParameterIds=[],this._lipSyncParameterIds=[],this._sourceFrameRate=30,this._loopDurationSeconds=-1,this._isLoop=!1,this._isLoopFadeIn=!0,this._lastWeight=0,this._modelOpacity=1}static create(t,e){const i=new ot;return i.parse(t),i._sourceFrameRate=i._motionData.fps,i._loopDurationSeconds=i._motionData.duration,i._onFinishedMotion=e,i}doUpdateParameters(e,i,s,r){null==this._modelCurveIdEyeBlink&&(this._modelCurveIdEyeBlink="EyeBlink"),null==this._modelCurveIdLipSync&&(this._modelCurveIdLipSync="LipSync"),null==this._modelCurveIdOpacity&&(this._modelCurveIdOpacity=Z);let o=i-r.getStartTime();o<0&&(o=0);let a=Number.MAX_VALUE,n=Number.MAX_VALUE;const l=64;let h=0,u=0;this._eyeBlinkParameterIds.length>l&&w("too many eye blink targets : {0}",this._eyeBlinkParameterIds.length),this._lipSyncParameterIds.length>l&&w("too many lip sync targets : {0}",this._lipSyncParameterIds.length);const d=this._fadeInSeconds<=0?1:m.getEasingSine((i-r.getFadeInStartTime())/this._fadeInSeconds),c=this._fadeOutSeconds<=0||r.getEndTime()<0?1:m.getEasingSine((r.getEndTime()-i)/this._fadeOutSeconds);let g,_,p,f=o;if(this._isLoop)for(;f>this._motionData.duration;)f-=this._motionData.duration;const y=this._motionData.curves;for(_=0;_>t&1)continue;const r=i+(n-i)*s;e.setParameterValueById(this._eyeBlinkParameterIds[t],r)}if(a!=Number.MAX_VALUE)for(let t=0;t>t&1)continue;const r=i+(a-i)*s;e.setParameterValueById(this._lipSyncParameterIds[t],r)}for(;_=this._motionData.duration&&(this._isLoop?(r.setStartTime(i),this._isLoopFadeIn&&r.setFadeInStartTime(i)):(this._onFinishedMotion&&this._onFinishedMotion(this),r.setIsFinished(!0))),this._lastWeight=s}setIsLoop(t){this._isLoop=t}isLoop(){return this._isLoop}setIsLoopFadeIn(t){this._isLoopFadeIn=t}isLoopFadeIn(){return this._isLoopFadeIn}getDuration(){return this._isLoop?-1:this._loopDurationSeconds}getLoopDuration(){return this._loopDurationSeconds}setParameterFadeInTime(t,e){const i=this._motionData.curves;for(let s=0;snew H)),this._motionData.segments=Array.from({length:e.getMotionTotalSegmentCount()}).map((()=>new W)),this._motionData.events=Array.from({length:this._motionData.eventCount}).map((()=>new Y)),this._motionData.points=[];let o=0,a=0;for(let n=0;nt&&this._motionData.events[i].fireTime<=e&&this._firedEventValues.push(this._motionData.events[i].value);return this._firedEventValues}isExistModelOpacity(){for(let t=0;tnull!=e&&e._motionQueueEntryHandle==t))}setEventCallback(t,e=null){this._eventCallBack=t,this._eventCustomData=e}doUpdateMotion(t,e){let i=!1,s=0;for(;s(t[t.CubismPhysicsTargetType_Parameter=0]="CubismPhysicsTargetType_Parameter",t))(ht||{}),ut=(t=>(t[t.CubismPhysicsSource_X=0]="CubismPhysicsSource_X",t[t.CubismPhysicsSource_Y=1]="CubismPhysicsSource_Y",t[t.CubismPhysicsSource_Angle=2]="CubismPhysicsSource_Angle",t))(ut||{});class dt{constructor(){this.initialPosition=new c(0,0),this.position=new c(0,0),this.lastPosition=new c(0,0),this.lastGravity=new c(0,0),this.force=new c(0,0),this.velocity=new c(0,0)}}class ct{constructor(){this.normalizationPosition={},this.normalizationAngle={}}}class gt{constructor(){this.source={}}}class mt{constructor(){this.destination={},this.translationScale=new c(0,0)}}class _t{constructor(){this.settings=[],this.inputs=[],this.outputs=[],this.particles=[],this.gravity=new c(0,0),this.wind=new c(0,0),this.fps=0}}class pt{constructor(t){this._json=t}release(){this._json=void 0}getGravity(){const t=new c(0,0);return t.x=this._json.Meta.EffectiveForces.Gravity.X,t.y=this._json.Meta.EffectiveForces.Gravity.Y,t}getWind(){const t=new c(0,0);return t.x=this._json.Meta.EffectiveForces.Wind.X,t.y=this._json.Meta.EffectiveForces.Wind.Y,t}getFps(){return this._json.Meta.Fps||0}getSubRigCount(){return this._json.Meta.PhysicsSettingCount}getTotalInputCount(){return this._json.Meta.TotalInputCount}getTotalOutputCount(){return this._json.Meta.TotalOutputCount}getVertexCount(){return this._json.Meta.VertexCount}getNormalizationPositionMinimumValue(t){return this._json.PhysicsSettings[t].Normalization.Position.Minimum}getNormalizationPositionMaximumValue(t){return this._json.PhysicsSettings[t].Normalization.Position.Maximum}getNormalizationPositionDefaultValue(t){return this._json.PhysicsSettings[t].Normalization.Position.Default}getNormalizationAngleMinimumValue(t){return this._json.PhysicsSettings[t].Normalization.Angle.Minimum}getNormalizationAngleMaximumValue(t){return this._json.PhysicsSettings[t].Normalization.Angle.Maximum}getNormalizationAngleDefaultValue(t){return this._json.PhysicsSettings[t].Normalization.Angle.Default}getInputCount(t){return this._json.PhysicsSettings[t].Input.length}getInputWeight(t,e){return this._json.PhysicsSettings[t].Input[e].Weight}getInputReflect(t,e){return this._json.PhysicsSettings[t].Input[e].Reflect}getInputType(t,e){return this._json.PhysicsSettings[t].Input[e].Type}getInputSourceId(t,e){return this._json.PhysicsSettings[t].Input[e].Source.Id}getOutputCount(t){return this._json.PhysicsSettings[t].Output.length}getOutputVertexIndex(t,e){return this._json.PhysicsSettings[t].Output[e].VertexIndex}getOutputAngleScale(t,e){return this._json.PhysicsSettings[t].Output[e].Scale}getOutputWeight(t,e){return this._json.PhysicsSettings[t].Output[e].Weight}getOutputDestinationId(t,e){return this._json.PhysicsSettings[t].Output[e].Destination.Id}getOutputType(t,e){return this._json.PhysicsSettings[t].Output[e].Type}getOutputReflect(t,e){return this._json.PhysicsSettings[t].Output[e].Reflect}getParticleCount(t){return this._json.PhysicsSettings[t].Vertices.length}getParticleMobility(t,e){return this._json.PhysicsSettings[t].Vertices[e].Mobility}getParticleDelay(t,e){return this._json.PhysicsSettings[t].Vertices[e].Delay}getParticleAcceleration(t,e){return this._json.PhysicsSettings[t].Vertices[e].Acceleration}getParticleRadius(t,e){return this._json.PhysicsSettings[t].Vertices[e].Radius}getParticlePosition(t,e){const i=new c(0,0);return i.x=this._json.PhysicsSettings[t].Vertices[e].Position.X,i.y=this._json.PhysicsSettings[t].Vertices[e].Position.Y,i}}const ft="Angle";class yt{static create(t){const e=new yt;return e.parse(t),e._physicsRig.gravity.y=0,e}static delete(t){null!=t&&t.release()}parse(t){this._physicsRig=new _t;const e=new pt(t);this._physicsRig.gravity=e.getGravity(),this._physicsRig.wind=e.getWind(),this._physicsRig.subRigCount=e.getSubRigCount(),this._physicsRig.fps=e.getFps(),this._currentRigOutputs=[],this._previousRigOutputs=[];let i=0,s=0,r=0;for(let o=0;o=u.particleCount)continue;let s=new c;s=_[i].position.substract(_[i-1].position),l=g[e].getValue(s,_,i,g[e].reflect,this._options.gravity),this._currentRigOutputs[x].outputs[e]=l,this._previousRigOutputs[x].outputs[e]=l;const r=g[e].destinationParameterIndex,o=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(p.subarray(r))):p.slice(r);Dt(o,y[r],f[r],l,g[e]);for(let t=r,e=0;t=e)return;if(this._currentRemainTime+=e,this._currentRemainTime>5&&(this._currentRemainTime=0),f=t.getModel().parameters.values,y=t.getModel().parameters.maximumValues,C=t.getModel().parameters.minimumValues,x=t.getModel().parameters.defaultValues,(null!=(s=null==(i=this._parameterCaches)?void 0:i.length)?s:0)0?1/this._physicsRig.fps:e;this._currentRemainTime>=M;){for(let t=0;t=d.particleCount)continue;const r=new c;r.x=p[s].position.x-p[s-1].position.x,r.y=p[s].position.y-p[s-1].position.y,h=_[e].getValue(r,p,s,_[e].reflect,this._options.gravity),this._currentRigOutputs[i].outputs[e]=h;const o=_[e].destinationParameterIndex,a=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(this._parameterCaches.subarray(o))):this._parameterCaches.slice(o);Dt(a,C[o],y[o],h,_[e]);for(let t=o,e=0;t=2?e[i-1].position.substract(e[i-2].position):r.multiplyByScaler(-1),o=m.directionToRadian(r,t),s&&(o*=-1),o}function Tt(t,e){return Math.min(t,e)+function(t,e){return Math.abs(Math.max(t,e)-Math.min(t,e))}(t,e)/2}function It(t,e){return t.x}function Lt(t,e){return t.y}function Et(t,e){return e}function At(t,e,i,s,r,o,a,n){let l,h,u,d,g=new c(0,0),_=new c(0,0),p=new c(0,0),f=new c(0,0);t[0].position=new c(i.x,i.y),l=m.degreesToRadian(s),d=m.radianToDirection(l),d.normalize();for(let y=1;yi&&(a>r.valueExceededMaximum&&(r.valueExceededMaximum=a),a=i),n=r.weight/100,n>=1||(a=t[0]*(1-n)+a*n),t[0]=a}function Bt(t,e,i,s,r,o,a,n){let l=0;const h=m.max(i,e);ht&&(t=u);const d=m.min(r,o),c=m.max(r,o),g=a,_=Tt(u,h),p=t-_;switch(Math.sign(p)){case 1:{const t=c-g,e=h-_;0!=e&&(l=p*(t/e),l+=g);break}case-1:{const t=d-g,e=u-_;0!=e&&(l=p*(t/e),l+=g);break}case 0:l=g}return n?l:-1*l}class Rt{constructor(t=0,e=0,i=0,s=0){this.x=t,this.y=e,this.width=i,this.height=s}getCenterX(){return this.x+.5*this.width}getCenterY(){return this.y+.5*this.height}getRight(){return this.x+this.width}getBottom(){return this.y+this.height}setRect(t){this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height}expand(t,e){this.x-=t,this.y-=e,this.width+=2*t,this.height+=2*e}}let Ot,kt,Ut;class Vt{getChannelFlagAsColor(t){return this._channelColors[t]}getMaskRenderTexture(){if(this._maskTexture&&null!=this._maskTexture.textures)this._maskTexture.frameNo=this._currentFrameNo;else{this._maskRenderTextures=[],this._maskColorBuffers=[];const t=this._clippingMaskBufferSize;for(let e=0;ec&&(c=e),ig&&(g=i)}if(u!=Number.MAX_VALUE)if(ur&&(r=c),g>o&&(o=g),i==Number.MAX_VALUE)e._allClippedDrawRect.x=0,e._allClippedDrawRect.y=0,e._allClippedDrawRect.width=0,e._allClippedDrawRect.height=0,e._isUsing=!1;else{e._isUsing=!0;const t=r-i,a=o-s;e._allClippedDrawRect.x=i,e._allClippedDrawRect.y=s,e._allClippedDrawRect.width=t,e._allClippedDrawRect.height=a}}}constructor(){this._currentMaskRenderTexture=null,this._currentFrameNo=0,this._renderTextureCount=0,this._clippingMaskBufferSize=256,this._clippingContextListForMask=[],this._clippingContextListForDraw=[],this._channelColors=[],this._tmpBoundsOnModel=new Rt,this._tmpMatrix=new _,this._tmpMatrixForMask=new _,this._tmpMatrixForDraw=new _;let t=new y;t.R=1,t.G=0,t.B=0,t.A=0,this._channelColors.push(t),t=new y,t.R=0,t.G=1,t.B=0,t.A=0,this._channelColors.push(t),t=new y,t.R=0,t.G=0,t.B=1,t.A=0,this._channelColors.push(t),t=new y,t.R=0,t.G=0,t.B=0,t.A=1,this._channelColors.push(t)}release(){var t;const e=this;for(let i=0;i0){this.setupLayoutBounds(e.isUsingHighPrecisionMask()?0:i),e.isUsingHighPrecisionMask()||(this.gl.viewport(0,0,this._clippingMaskBufferSize,this._clippingMaskBufferSize),this._currentMaskRenderTexture=this.getMaskRenderTexture()[0],e.preDraw(),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this._currentMaskRenderTexture)),this._clearedFrameBufferflags||(this._clearedFrameBufferflags=[]);for(let t=0;th?(this._tmpBoundsOnModel.expand(r.width*a,0),n=o.width/this._tmpBoundsOnModel.width):n=e/h,this._tmpBoundsOnModel.height*e>u?(this._tmpBoundsOnModel.expand(0,r.height*a),l=o.height/this._tmpBoundsOnModel.height):l=e/u}else this._tmpBoundsOnModel.setRect(r),this._tmpBoundsOnModel.expand(r.width*a,r.height*a),n=o.width/this._tmpBoundsOnModel.width,l=o.height/this._tmpBoundsOnModel.height;if(this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(-1,-1),this._tmpMatrix.scaleRelative(2,2),this._tmpMatrix.translateRelative(o.x,o.y),this._tmpMatrix.scaleRelative(n,l),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForMask.setMatrix(this._tmpMatrix.getArray()),this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(o.x,o.y),this._tmpMatrix.scaleRelative(n,l),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForDraw.setMatrix(this._tmpMatrix.getArray()),s._matrixForMask.setMatrix(this._tmpMatrixForMask.getArray()),s._matrixForDraw.setMatrix(this._tmpMatrixForDraw.getArray()),!e.isUsingHighPrecisionMask()){const i=s._clippingIdCount;for(let r=0;ri){e>i&&L("not supported mask count : {0}\n[Details] render texture count : {1}, mask count : {2}",e-i,this._renderTextureCount,e);for(let t=0;t=4?0:n+1;if(u(t[t.ShaderNames_SetupMask=0]="ShaderNames_SetupMask",t[t.ShaderNames_NormalPremultipliedAlpha=1]="ShaderNames_NormalPremultipliedAlpha",t[t.ShaderNames_NormalMaskedPremultipliedAlpha=2]="ShaderNames_NormalMaskedPremultipliedAlpha",t[t.ShaderNames_NomralMaskedInvertedPremultipliedAlpha=3]="ShaderNames_NomralMaskedInvertedPremultipliedAlpha",t[t.ShaderNames_AddPremultipliedAlpha=4]="ShaderNames_AddPremultipliedAlpha",t[t.ShaderNames_AddMaskedPremultipliedAlpha=5]="ShaderNames_AddMaskedPremultipliedAlpha",t[t.ShaderNames_AddMaskedPremultipliedAlphaInverted=6]="ShaderNames_AddMaskedPremultipliedAlphaInverted",t[t.ShaderNames_MultPremultipliedAlpha=7]="ShaderNames_MultPremultipliedAlpha",t[t.ShaderNames_MultMaskedPremultipliedAlpha=8]="ShaderNames_MultMaskedPremultipliedAlpha",t[t.ShaderNames_MultMaskedPremultipliedAlphaInverted=9]="ShaderNames_MultMaskedPremultipliedAlphaInverted",t))(jt||{});const Wt="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_myPos;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_clipMatrix * a_position; v_myPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",Ht="precision mediump float;varying vec2 v_texCoord;varying vec4 v_myPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;void main(){ float isInside = step(u_baseColor.x, v_myPos.x/v_myPos.w) * step(u_baseColor.y, v_myPos.y/v_myPos.w) * step(v_myPos.x/v_myPos.w, u_baseColor.z) * step(v_myPos.y/v_myPos.w, u_baseColor.w); gl_FragColor = u_channelFlag * texture2D(s_texture0, v_texCoord).a * isInside;}",Yt="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;uniform mat4 u_matrix;void main(){ gl_Position = u_matrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",qt="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform mat4 u_matrix;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_matrix * a_position; v_clipPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",$t="precision mediump float;varying vec2 v_texCoord;uniform vec4 u_baseColor;uniform sampler2D s_texture0;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 color = texColor * u_baseColor; gl_FragColor = vec4(color.rgb, color.a);}",Jt="precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;uniform sampler2D s_texture1;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 col_formask = texColor * u_baseColor; vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag; float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a; col_formask = col_formask * maskVal; gl_FragColor = col_formask;}",Zt="precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform sampler2D s_texture0;uniform sampler2D s_texture1;uniform vec4 u_channelFlag;uniform vec4 u_baseColor;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 col_formask = texColor * u_baseColor; vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag; float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a; col_formask = col_formask * (1.0 - maskVal); gl_FragColor = col_formask;}";class Qt extends p{constructor(){super(),this._clippingContextBufferForMask=null,this._clippingContextBufferForDraw=null,this._rendererProfile=new Xt,this.firstDraw=!0,this._textures={},this._sortedDrawableIndexList=[],this._bufferData={vertex:null,uv:null,index:null}}initialize(t,e=1){t.isUsingMasking()&&(this._clippingManager=new Vt,this._clippingManager.initialize(t,t.getDrawableCount(),t.getDrawableMasks(),t.getDrawableMaskCounts(),e));for(let i=t.getDrawableCount()-1;i>=0;i--)this._sortedDrawableIndexList[i]=0;super.initialize(t)}bindTexture(t,e){this._textures[t]=e}getBindedTextures(){return this._textures}setClippingMaskBufferSize(t){if(!this._model.isUsingMasking())return;const e=this._clippingManager.getRenderTextureCount();this._clippingManager.release(),this._clippingManager=new Vt,this._clippingManager.setClippingMaskBufferSize(t),this._clippingManager.initialize(this.getModel(),this.getModel().getDrawableCount(),this.getModel().getDrawableMasks(),this.getModel().getDrawableMaskCounts(),e)}getClippingMaskBufferSize(){return this._model.isUsingMasking()?this._clippingManager.getClippingMaskBufferSize():-1}getRenderTextureCount(){return this._model.isUsingMasking()?this._clippingManager.getRenderTextureCount():-1}release(){var t,e,i;const s=this;this._clippingManager.release(),s._clippingManager=void 0,null==(t=this.gl)||t.deleteBuffer(this._bufferData.vertex),this._bufferData.vertex=null,null==(e=this.gl)||e.deleteBuffer(this._bufferData.uv),this._bufferData.uv=null,null==(i=this.gl)||i.deleteBuffer(this._bufferData.index),this._bufferData.index=null,s._bufferData=void 0,s._textures=void 0}doDrawModel(){if(null==this.gl)return void L("'gl' is null. WebGLRenderingContext is required.\nPlease call 'CubimRenderer_WebGL.startUp' function.");null!=this._clippingManager&&(this.preDraw(),this._clippingManager.setupClippingContext(this.getModel(),this)),this.preDraw();const t=this.getModel().getDrawableCount(),e=this.getModel().getDrawableRenderOrders();for(let i=0;i0&&this._extension)for(const t of Object.entries(this._textures))this.gl.bindTexture(this.gl.TEXTURE_2D,t),this.gl.texParameterf(this.gl.TEXTURE_2D,this._extension.TEXTURE_MAX_ANISOTROPY_EXT,this.getAnisotropy())}setClippingContextBufferForMask(t){this._clippingContextBufferForMask=t}getClippingContextBufferForMask(){return this._clippingContextBufferForMask}setClippingContextBufferForDraw(t){this._clippingContextBufferForDraw=t}getClippingContextBufferForDraw(){return this._clippingContextBufferForDraw}startUp(t){this.gl=t,this._clippingManager&&this._clippingManager.setGL(t),zt.getInstance().setGl(t),this._rendererProfile.setGl(t),this._extension=this.gl.getExtension("EXT_texture_filter_anisotropic")||this.gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this.gl.getExtension("MOZ_EXT_texture_filter_anisotropic")}}p.staticRelease=()=>{Qt.doStaticRelease()};class Kt{constructor(t){this.groups=t.Groups,this.hitAreas=t.HitAreas,this.layout=t.Layout,this.moc=t.FileReferences.Moc,this.expressions=t.FileReferences.Expressions,this.motions=t.FileReferences.Motions,this.textures=t.FileReferences.Textures,this.physics=t.FileReferences.Physics,this.pose=t.FileReferences.Pose}getEyeBlinkParameters(){var t,e;return null==(e=null==(t=this.groups)?void 0:t.find((t=>"EyeBlink"===t.Name)))?void 0:e.Ids}getLipSyncParameters(){var t,e;return null==(e=null==(t=this.groups)?void 0:t.find((t=>"LipSync"===t.Name)))?void 0:e.Ids}}const te="ParamAngleX",ee="ParamAngleY",ie="ParamAngleZ",se="ParamEyeBallX",re="ParamEyeBallY",oe="ParamBodyAngleX",ae="ParamBreath";var ne;t.config=void 0,(ne=t.config||(t.config={})).LOG_LEVEL_VERBOSE=0,ne.LOG_LEVEL_WARNING=1,ne.LOG_LEVEL_ERROR=2,ne.LOG_LEVEL_NONE=999,ne.logLevel=ne.LOG_LEVEL_WARNING,ne.sound=!0,ne.motionSync=!0,ne.motionFadingDuration=500,ne.idleMotionFadingDuration=2e3,ne.expressionFadingDuration=500,ne.preserveExpressionOnMotion=!0,ne.cubism4=t.CubismConfig;const le={log(e,...i){t.config.logLevel<=t.config.LOG_LEVEL_VERBOSE&&console.log(`[${e}]`,...i)},warn(e,...i){t.config.logLevel<=t.config.LOG_LEVEL_WARNING&&console.warn(`[${e}]`,...i)},error(e,...i){t.config.logLevel<=t.config.LOG_LEVEL_ERROR&&console.error(`[${e}]`,...i)}};function he(t,e,i){return ti?i:t}function ue(t,e){e.forEach((e=>{Object.getOwnPropertyNames(e.prototype).forEach((i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i))}))}))}function de(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 ce(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}class ge extends e.EventEmitter{constructor(t,e){super(),this.expressions=[],this.reserveExpressionIndex=-1,this.destroyed=!1,this.settings=t,this.tag=`ExpressionManager(${t.name})`}init(){this.defaultExpression=this.createExpression({},void 0),this.currentExpression=this.defaultExpression,this.stopAllExpressions()}loadExpression(t){return __async(this,null,(function*(){if(!this.definitions[t])return void le.warn(this.tag,`Undefined expression at [${t}]`);if(null===this.expressions[t])return void le.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 __async(this,null,(function*(){if(this.definitions.length){const t=[];for(let e=0;e-1&&tl&&(o*=l/n,a*=l/n),this.vx+=o,this.vy+=a;const h=Math.sqrt(__pow(this.vx,2)+__pow(this.vy,2)),u=.5*(Math.sqrt(__pow(l,2)+8*l*s)-l);h>u&&(this.vx*=u/h,this.vy*=u/h),this.x+=this.vx,this.y+=this.vy}}class _e{constructor(t){this.json=t;let e=t.url;if("string"!=typeof e)throw new TypeError("The `url` field in settings JSON must be defined as a string.");this.url=e,this.name=de(this.url)}resolveURL(t){return e.url.resolve(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(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 pe=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(pe||{});class fe{constructor(){this.debug=!1,this.currentPriority=0,this.reservePriority=0}reserve(t,e,i){if(i<=0)return le.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(t===this.currentGroup&&e===this.currentIndex)return le.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 le.log(this.tag,"Motion is already reserved.",this.dump(t,e)),!1;if(1===i){if(0!==this.currentPriority)return le.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,e)),!1;if(void 0!==this.reservedIdleGroup)return le.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 le.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 le.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 le.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 le.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!t.config.preserveExpressionOnMotion&&this.currentPriority>1}dump(t,e){if(this.debug){return`\n group = "${t}", index = ${e}\n`+["currentPriority","reservePriority","currentGroup","currentIndex","reservedGroup","reservedIndex","reservedIdleGroup","reservedIdleIndex"].map((t=>"["+t+"] "+this[t])).join("\n")}return""}}class ye{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,i){const s=new Audio(t);return s.volume=this._volume,s.preload="auto",s.autoplay=!0,s.crossOrigin="anonymous",s.addEventListener("ended",(()=>{this.dispose(s),null==e||e()})),s.addEventListener("error",(e=>{this.dispose(s),le.warn("SoundManager",`Error occurred on "${t}"`,e.error),null==i||i(e.error)})),this.audios.push(s),s}static play(t){return new Promise(((e,i)=>{var s;null==(s=t.play())||s.catch((e=>{t.dispatchEvent(new ErrorEvent("error",{error:e})),i(e)})),t.readyState===t.HAVE_ENOUGH_DATA?e():t.addEventListener("canplaythrough",e)}))}static addContext(t){const e=new AudioContext;return this.contexts.push(e),e}static addAnalyzer(t,e){const i=e.createMediaElementSource(t),s=e.createAnalyser();return s.fftSize=256,s.minDecibels=-90,s.maxDecibels=-10,s.smoothingTimeConstant=.85,i.connect(s),s.connect(e.destination),this.analysers.push(s),s}static analyze(t){if(null!=t){let e=new Float32Array(t.fftSize),i=0;t.getFloatTimeDomainData(e);for(const t of e)i+=t*t;return parseFloat(Math.sqrt(i/e.length*20).toFixed(1))}return parseFloat(Math.random().toFixed(1))}static dispose(t){t.pause(),t.removeAttribute("src"),ce(this.audios,t)}static destroy(){for(let t=this.contexts.length-1;t>=0;t--)this.contexts[t].close();for(let t=this.audios.length-1;t>=0;t--)this.dispose(this.audios[t])}}ye.audios=[],ye.analysers=[],ye.contexts=[],ye._volume=.9;var Ce=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(Ce||{});class xe extends e.EventEmitter{constructor(t,e){super(),this.motionGroups={},this.state=new fe,this.playing=!1,this.destroyed=!1,this.settings=t,this.tag=`MotionManager(${t.name})`,this.state.tag=this.tag}init(t){(null==t?void 0:t.idleMotionGroup)&&(this.groups.idle=t.idleMotionGroup),this.setupMotions(t),this.stopAllMotions()}setupMotions(t){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)if(this.definitions[i])for(let t=0;t{s&&d.expressionManager&&d.expressionManager.resetExpression(),d.currentAudio=void 0}),(()=>{s&&d.expressionManager&&d.expressionManager.resetExpression(),d.currentAudio=void 0})),this.currentAudio=r;let t=1;void 0!==i&&(t=i),ye.volume=t,a=ye.addContext(this.currentAudio),this.currentContext=a,o=ye.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=o}catch(c){le.warn(this.tag,"Failed to create audio",n,c)}if(r){const e=ye.play(r).catch((t=>le.warn(this.tag,"Failed to play audio",r.src,t)));t.config.motionSync&&(yield e)}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),s&&this.expressionManager&&this.expressionManager.setExpression(s),this.playing=!0,!0}))}startMotion(e,i){return __async(this,arguments,(function*(e,i,s=pe.NORMAL,r,o,a){var n;if(this.currentAudio&&!this.currentAudio.ended)return!1;if(!this.state.reserve(e,i,s))return!1;const l=null==(n=this.definitions[e])?void 0:n[i];if(!l)return!1;let h,u,d;if(this.currentAudio&&ye.dispose(this.currentAudio),t.config.sound){const t=r&&r.startsWith("data:audio/wav;base64");if(r&&!t){var c=document.createElement("a");c.href=r,r=c.href}const e=r&&(r.startsWith("http")||r.startsWith("blob")),i=this.getSoundFile(l);let s=i;i&&(s=this.settings.resolveURL(i)+"?cache-buster="+(new Date).getTime()),(e||t)&&(s=r);const n=this;if(s)try{h=ye.add(s,(()=>{a&&n.expressionManager&&n.expressionManager.resetExpression(),n.currentAudio=void 0}),(()=>{a&&n.expressionManager&&n.expressionManager.resetExpression(),n.currentAudio=void 0})),this.currentAudio=h;let t=1;void 0!==o&&(t=o),ye.volume=t,d=ye.addContext(this.currentAudio),this.currentContext=d,u=ye.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=u}catch(m){le.warn(this.tag,"Failed to create audio",i,m)}}const g=yield this.loadMotion(e,i);if(h){s=3;const e=ye.play(h).catch((t=>le.warn(this.tag,"Failed to play audio",h.src,t)));t.config.motionSync&&(yield e)}return this.state.start(g,e,i,s)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),le.log(this.tag,"Start motion:",this.getMotionName(l)),this.emit("motionStart",e,i,h),a&&this.expressionManager&&this.expressionManager.setExpression(a),this.playing=!0,this._startMotion(g),!0):(h&&(ye.dispose(h),this.currentAudio=void 0),!1)}))}startRandomMotion(t,e,i,s){return __async(this,null,(function*(){const r=this.definitions[t];if(null==r?void 0:r.length){const o=[];for(let e=0;et.index>=0));for(const e of t)this.hitAreas[e.name]=e}hitTest(t,e){return Object.keys(this.hitAreas).filter((i=>this.isHit(i,t,e)))}isHit(t,e,i){if(!this.hitAreas[t])return!1;const s=this.hitAreas[t].index,r=this.getDrawableBounds(s,Me);return r.x<=e&&e<=r.x+r.width&&r.y<=i&&i<=r.y+r.height}getDrawableBounds(t,e){const i=this.getDrawableVertices(t);let s=i[0],r=i[0],o=i[1],a=i[1];for(let n=0;n{200!==o.status&&0!==o.status||!o.response?o.onerror():s(o.response)},o.onerror=()=>{le.warn("XHRLoader",`Failed to load resource as ${o.responseType} (Status ${o.status}): ${e}`),r(new Pe("Network error.",e,o.status))},o.onabort=()=>r(new Pe("Aborted.",e,o.status,!0)),o.onloadend=()=>{var e;be.allXhrSet.delete(o),t&&(null==(e=be.xhrMap.get(t))||e.delete(o))},o}static cancelXHRs(){var t;null==(t=be.xhrMap.get(this))||t.forEach((t=>{t.abort(),be.allXhrSet.delete(t)})),be.xhrMap.delete(this)}static release(){be.allXhrSet.forEach((t=>t.abort())),be.allXhrSet.clear(),be.xhrMap=new WeakMap}};let Se=be;function we(t,e){let i=-1;return function s(r,o){if(o)return Promise.reject(o);if(r<=i)return Promise.reject(new Error("next() called multiple times"));i=r;const a=t[r];if(!a)return Promise.resolve();try{return Promise.resolve(a(e,s.bind(null,r+1)))}catch(n){return Promise.reject(n)}}(0)}Se.xhrMap=new WeakMap,Se.allXhrSet=new Set,Se.loader=(t,e)=>new Promise(((e,i)=>{be.createXHR(t.target,t.settings?t.settings.resolveURL(t.url):t.url,t.type,(i=>{t.result=i,e()}),i).send()}));class Te{static load(t){return we(this.middlewares,t).then((()=>t.result))}}Te.middlewares=[Se.loader];const Ie="Live2DFactory",Le=(t,e)=>__async(this,null,(function*(){if("string"==typeof t.source){const e=yield Te.load({url:t.source,type:"json",target:t.live2dModel});e.url=t.source,t.source=e,t.live2dModel.emit("settingsJSONLoaded",e)}return e()})),Ee=(t,e)=>__async(this,null,(function*(){if(t.source instanceof _e)return t.settings=t.source,e();if("object"==typeof t.source){const i=Oe.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.")})),Ae=(t,e)=>{if(t.settings){const i=Oe.findRuntime(t.settings);if(i)return i.ready().then(e)}return e()},Fe=(t,e)=>__async(this,null,(function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=Oe.findRuntime(e);if(s){const r=[];e.pose&&r.push(Te.load({settings:e,url:e.pose,type:"json",target:i}).then((e=>{i.pose=s.createPose(i.coreModel,e),t.live2dModel.emit("poseLoaded",i.pose)})).catch((e=>{t.live2dModel.emit("poseLoadError",e),le.warn(Ie,"Failed to load pose.",e)}))),e.physics&&r.push(Te.load({settings:e,url:e.physics,type:"json",target:i}).then((e=>{i.physics=s.createPhysics(i.coreModel,e),t.live2dModel.emit("physicsLoaded",i.physics)})).catch((e=>{t.live2dModel.emit("physicsLoadError",e),le.warn(Ie,"Failed to load physics.",e)}))),r.length&&(yield Promise.all(r))}}})),De=(t,e)=>__async(this,null,(function*(){if(!t.settings)throw new TypeError("Missing settings.");{const i=t.live2dModel,r=t.settings.textures.map((e=>function(t,e={}){const i={resourceOptions:{crossorigin:e.crossOrigin}};if(s.Texture.fromURL)return s.Texture.fromURL(t,i).catch((t=>{if(t instanceof Error)throw t;const e=new Error("Texture loading error");throw e.event=t,e}));i.resourceOptions.autoLoad=!1;const r=s.Texture.from(t,i);if(r.baseTexture.valid)return Promise.resolve(r);const o=r.baseTexture.resource;return null!=o._live2d_load||(o._live2d_load=new Promise(((t,e)=>{const i=t=>{o.source.removeEventListener("error",i);const s=new Error("Texture loading error");s.event=t,e(s)};o.source.addEventListener("error",i),o.load().then((()=>t(r))).catch(i)}))),o._live2d_load}(t.settings.resolveURL(e),{crossOrigin:t.options.crossOrigin})));if(yield e(),!t.internalModel)throw new TypeError("Missing internal model.");i.internalModel=t.internalModel,i.emit("modelLoaded",t.internalModel),i.textures=yield Promise.all(r),i.emit("textureLoaded",i.textures)}})),Be=(t,e)=>__async(this,null,(function*(){const i=t.settings;if(i instanceof _e){const s=Oe.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield Te.load({settings:i,url:i.moc,type:"arraybuffer",target:t.live2dModel});if(!s.isValidMoc(r))throw new Error("Invalid moc data");const o=s.createCoreModel(r);return t.internalModel=s.createInternalModel(o,i,t.options),e()}throw new TypeError("Missing settings.")})),Re=class{static registerRuntime(t){Re.runtimes.push(t),Re.runtimes.sort(((t,e)=>e.version-t.version))}static findRuntime(t){for(const e of Re.runtimes)if(e.test(t))return e}static setupLive2DModel(t,e,i){return __async(this,null,(function*(){const s=new Promise((e=>t.once("textureLoaded",e))),r=new Promise((e=>t.once("modelLoaded",e))),o=Promise.all([s,r]).then((()=>t.emit("ready")));yield we(Re.live2DModelMiddlewares,{live2dModel:t,source:e,options:i||{}}),yield o,t.emit("load")}))}static loadMotion(t,e,i){var s;const r=s=>t.emit("motionLoadError",e,i,s);try{const o=null==(s=t.definitions[e])?void 0:s[i];if(!o)return Promise.resolve(void 0);t.listeners("destroy").includes(Re.releaseTasks)||t.once("destroy",Re.releaseTasks);let a=Re.motionTasksMap.get(t);a||(a={},Re.motionTasksMap.set(t,a));let n=a[e];n||(n=[],a[e]=n);const l=t.getMotionFile(o);return null!=n[i]||(n[i]=Te.load({url:l,settings:t.settings,type:t.motionDataType,target:t}).then((s=>{var r;const a=null==(r=Re.motionTasksMap.get(t))?void 0:r[e];a&&delete a[i];const n=t.createMotion(s,e,o);return t.emit("motionLoaded",e,i,n),n})).catch((e=>{le.warn(t.tag,`Failed to load motion: ${l}\n`,e),r(e)}))),n[i]}catch(o){le.warn(t.tag,`Failed to load motion at "${e}"[${i}]\n`,o),r(o)}return Promise.resolve(void 0)}static loadExpression(t,e){const i=i=>t.emit("expressionLoadError",e,i);try{const s=t.definitions[e];if(!s)return Promise.resolve(void 0);t.listeners("destroy").includes(Re.releaseTasks)||t.once("destroy",Re.releaseTasks);let r=Re.expressionTasksMap.get(t);r||(r=[],Re.expressionTasksMap.set(t,r));const o=t.getExpressionFile(s);return null!=r[e]||(r[e]=Te.load({url:o,settings:t.settings,type:"json",target:t}).then((i=>{const r=Re.expressionTasksMap.get(t);r&&delete r[e];const o=t.createExpression(i,s);return t.emit("expressionLoaded",e,o),o})).catch((e=>{le.warn(t.tag,`Failed to load expression: ${o}\n`,e),i(e)}))),r[e]}catch(s){le.warn(t.tag,`Failed to load expression at [${e}]\n`,s),i(s)}return Promise.resolve(void 0)}static releaseTasks(){this instanceof xe?Re.motionTasksMap.delete(this):Re.expressionTasksMap.delete(this)}};let Oe=Re;Oe.runtimes=[],Oe.urlToJSON=Le,Oe.jsonToSettings=Ee,Oe.waitUntilReady=Ae,Oe.setupOptionals=Fe,Oe.setupEssentials=De,Oe.createInternalModel=Be,Oe.live2DModelMiddlewares=[Le,Ee,Ae,Fe,De,Be],Oe.motionTasksMap=new WeakMap,Oe.expressionTasksMap=new WeakMap,xe.prototype._loadMotion=function(t,e){return Oe.loadMotion(this,t,e)},ge.prototype._loadExpression=function(t){return Oe.loadExpression(this,t)};class ke{constructor(){this._autoInteract=!1}get autoInteract(){return this._autoInteract}set autoInteract(t){t!==this._autoInteract&&(t?this.on("pointertap",Ue,this):this.off("pointertap",Ue,this),this._autoInteract=t)}registerInteraction(t){t!==this.interactionManager&&(this.unregisterInteraction(),this._autoInteract&&t&&(this.interactionManager=t,t.on("pointermove",Ve,this)))}unregisterInteraction(){var t;this.interactionManager&&(null==(t=this.interactionManager)||t.off("pointermove",Ve,this),this.interactionManager=void 0)}}function Ue(t){this.tap(t.data.global.x,t.data.global.y)}function Ve(t){this.focus(t.data.global.x,t.data.global.y)}class Ne extends i.Transform{}const Ge=new i.Point,Xe=new i.Matrix;let ze;class je extends r.Container{constructor(t){super(),this.tag="Live2DModel(uninitialized)",this.textures=[],this.transform=new Ne,this.anchor=new i.ObservablePoint(this.onAnchorChange,this,0,0),this.glContextID=-1,this.elapsedTime=performance.now(),this.deltaTime=0,this._autoUpdate=!1,this.once("modelLoaded",(()=>this.init(t)))}static from(t,e){const i=new this(e);return Oe.setupLive2DModel(i,t,e).then((()=>i))}static fromSync(t,e){const i=new this(e);return Oe.setupLive2DModel(i,t,e).then(null==e?void 0:e.onLoad).catch(null==e?void 0:e.onError),i}static registerTicker(t){ze=t}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){var e;ze||(ze=null==(e=window.PIXI)?void 0:e.Ticker),t?this._destroyed||(ze?(ze.shared.add(this.onTickerUpdate,this),this._autoUpdate=!0):le.warn(this.tag,"No Ticker registered, please call Live2DModel.registerTicker(Ticker).")):(null==ze||ze.shared.remove(this.onTickerUpdate,this),this._autoUpdate=!1)}init(t){this.tag=`Live2DModel(${this.internalModel.settings.name})`;const e=Object.assign({autoUpdate:!0,autoInteract:!0},t);e.autoInteract&&(this.interactive=!0),this.autoInteract=e.autoInteract,this.autoUpdate=e.autoUpdate}onAnchorChange(){this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(t,e,i,s,r,o){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i):this.internalModel.motionManager.startMotion(t,e,i,s,r,o)}resetMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(t,e,i){return this.internalModel.motionManager.speakUp(t,e,i)}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){Ge.x=t,Ge.y=e,this.toModelPosition(Ge,Ge,!0);let s=Ge.x/this.internalModel.originalWidth*2-1,r=Ge.y/this.internalModel.originalHeight*2-1,o=Math.atan2(r,s);this.internalModel.focusController.focus(Math.cos(o),-Math.sin(o),i)}tap(t,e){const i=this.hitTest(t,e);i.length&&(le.log(this.tag,"Hit",i),this.emit("hit",i))}hitTest(t,e){return Ge.x=t,Ge.y=e,this.toModelPosition(Ge,Ge),this.internalModel.hitTest(Ge.x,Ge.y)}toModelPosition(t,e=t.clone(),i){return i||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.transform.worldTransform.applyInverse(t,e),this.internalModel.localTransform.applyInverse(e,e),e}containsPoint(t){return this.getBounds(!0).contains(t.x,t.y)}_calculateBounds(){this._bounds.addFrame(this.transform,0,0,this.internalModel.width,this.internalModel.height)}onTickerUpdate(){this.update(ze.shared.deltaMS)}update(t){this.deltaTime+=t,this.elapsedTime+=t}_render(t){this.registerInteraction(t.plugins.interaction),t.batch.reset(),t.geometry.reset(),t.shader.reset(),t.state.reset();let e=!1;this.glContextID!==t.CONTEXT_UID&&(this.glContextID=t.CONTEXT_UID,this.internalModel.updateWebGLContext(t.gl,this.glContextID),e=!0);for(let r=0;re.destroy(t.baseTexture))),this.internalModel.destroy(),super.destroy(t)}}ue(je,[ke]);const We=class{static resolveURL(t,e){var i;const s=null==(i=We.filesMap[t])?void 0:i[e];if(void 0===s)throw new Error("Cannot find this file from uploaded files: "+e);return s}static upload(t,i){return __async(this,null,(function*(){const s={};for(const r of i.getDefinedFiles()){const o=decodeURI(e.url.resolve(i.url,r)),a=t.find((t=>t.webkitRelativePath===o));a&&(s[r]=URL.createObjectURL(a))}We.filesMap[i._objectURL]=s}))}static createSettings(t){return __async(this,null,(function*(){const e=t.find((t=>t.name.endsWith("model.json")||t.name.endsWith("model3.json")));if(!e)throw new TypeError("Settings file not found");const i=yield We.readText(e),s=JSON.parse(i);s.url=e.webkitRelativePath;const r=Oe.findRuntime(s);if(!r)throw new Error("Unknown settings JSON");const o=r.createModelSettings(s);return o._objectURL=URL.createObjectURL(e),o}))}static readText(t){return __async(this,null,(function*(){return new Promise(((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")}))}))}};let He=We;He.filesMap={},He.factory=(t,e)=>__async(this,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 We.createSettings(e);i.validateFiles(e.map((t=>encodeURI(t.webkitRelativePath)))),yield We.upload(e,i),i.resolveURL=function(t){return We.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),We.filesMap[t])for(const e of Object.values(We.filesMap[t]))URL.revokeObjectURL(e);delete We.filesMap[t]}))}))}return e()})),Oe.live2DModelMiddlewares.unshift(He.factory);const Ye=class{static unzip(t,i){return __async(this,null,(function*(){const s=yield Ye.getFilePaths(t),r=[];for(const t of i.getDefinedFiles()){const o=decodeURI(e.url.resolve(i.url,t));s.includes(o)&&r.push(o)}const o=yield Ye.getFiles(t,r);for(let t=0;tt.endsWith("model.json")||t.endsWith("model3.json")));if(!e)throw new Error("Settings file not found");const i=yield Ye.readText(t,e);if(!i)throw new Error("Empty settings file: "+e);const s=JSON.parse(i);s.url=e;const r=Oe.findRuntime(s);if(!r)throw new Error("Unknown settings JSON");return r.createModelSettings(s)}))}static zipReader(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static getFilePaths(t){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static getFiles(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static readText(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static releaseReader(t){}};let qe=Ye;if(qe.ZIP_PROTOCOL="zip://",qe.uid=0,qe.factory=(t,e)=>__async(this,null,(function*(){const i=t.source;let s,r,o;if("string"==typeof i&&(i.endsWith(".zip")||i.startsWith(Ye.ZIP_PROTOCOL))?(s=i.startsWith(Ye.ZIP_PROTOCOL)?i.slice(Ye.ZIP_PROTOCOL.length):i,r=yield Te.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),o=i.settings),r){if(!r.size)throw new Error("Empty zip file");const e=yield Ye.zipReader(r,s);o||(o=yield Ye.createSettings(e)),o._objectURL=Ye.ZIP_PROTOCOL+Ye.uid+"/"+o.url;const i=yield Ye.unzip(e,o);i.settings=o,t.source=i,s.startsWith("blob:")&&t.live2dModel.once("modelLoaded",(t=>{t.once("destroy",(function(){URL.revokeObjectURL(s)}))})),Ye.releaseReader(e)}return e()})),Oe.live2DModelMiddlewares.unshift(qe.factory),!window.Live2DCubismCore)throw new Error("Could not find Cubism 4 runtime. This plugin requires live2dcubismcore.js to be loaded.");class $e extends ge{constructor(t,e){var i;super(t,e),this.queueManager=new nt,this.definitions=null!=(i=t.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 V.create(t)}_setExpression(t){return this.queueManager.startMotion(t,!1,performance.now())}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.doUpdateMotion(t,e)}}class Je extends _e{constructor(t){if(super(t),!Je.isValidJSON(t))throw new TypeError("Invalid JSON.");Object.assign(this,new Kt(t))}static isValidJSON(t){var e;return!!(null==t?void 0:t.FileReferences)&&"string"==typeof t.FileReferences.Moc&&(null==(e=t.FileReferences.Textures)?void 0:e.length)>0&&t.FileReferences.Textures.every((t=>"string"==typeof t))}replaceFiles(t){if(super.replaceFiles(t),this.motions)for(const[e,i]of Object.entries(this.motions))for(let s=0;s{this.emit("motion:"+e)}))}isFinished(){return this.queueManager.isFinished()}_startMotion(t,e){return t.setFinishedMotionHandler(e),this.queueManager.stopAllMotions(),this.queueManager.startMotion(t,!1,performance.now())}_stopAllMotions(){this.queueManager.stopAllMotions()}createMotion(e,i,s){const r=ot.create(e),o=new $(e),a=(i===this.groups.idle?t.config.idleMotionFadingDuration:t.config.motionFadingDuration)/1e3;return void 0===o.getMotionFadeInTime()&&r.setFadeInTime(s.FadeInTime>0?s.FadeInTime:a),void 0===o.getMotionFadeOutTime()&&r.setFadeOutTime(s.FadeOutTime>0?s.FadeOutTime:a),r.setEffectIds(this.eyeBlinkIds,this.lipSyncIds),r}getMotionFile(t){return t.File}getMotionName(t){return t.File}getSoundFile(t){return t.Sound}updateParameters(t,e){return this.queueManager.doUpdateMotion(t,e)}destroy(){super.destroy(),this.queueManager.release(),this.queueManager=void 0}}const Qe=new _;class Ke extends ve{constructor(t,e,s){super(),this.lipSync=!0,this.breath=o.create(),this.renderer=new Qt,this.idParamAngleX=te,this.idParamAngleY=ee,this.idParamAngleZ=ie,this.idParamEyeBallX=se,this.idParamEyeBallY=re,this.idParamBodyAngleX=oe,this.idParamBreath=ae,this.pixelsPerUnit=1,this.centeringTransform=new i.Matrix,this.coreModel=t,this.settings=e,this.motionManager=new Ze(e,s),this.init()}init(){var t;super.init(),(null==(t=this.settings.getEyeBlinkParameters())?void 0:t.length)>0&&(this.eyeBlink=l.create(this.settings)),this.breath.setParameters([new a(this.idParamAngleX,0,15,6.5345,.5),new a(this.idParamAngleY,0,8,3.5345,.5),new a(this.idParamAngleZ,0,10,5.5345,.5),new a(this.idParamBodyAngleX,0,4,15.5345,.5),new a(this.idParamBreath,0,.5,3.2345,.5)]),this.renderer.initialize(this.coreModel),this.renderer.setIsPremultipliedAlpha(!0)}getSize(){return[this.coreModel.getModel().canvasinfo.CanvasWidth,this.coreModel.getModel().canvasinfo.CanvasHeight]}getLayout(){const t={};if(this.settings.layout)for(const e of Object.keys(this.settings.layout)){t[e.charAt(0).toLowerCase()+e.slice(1)]=this.settings.layout[e]}return t}setupLayout(){super.setupLayout(),this.pixelsPerUnit=this.coreModel.getModel().canvasinfo.PixelsPerUnit,this.centeringTransform.scale(this.pixelsPerUnit,this.pixelsPerUnit).translate(this.originalWidth/2,this.originalHeight/2)}updateWebGLContext(t,e){this.renderer.firstDraw=!0,this.renderer._bufferData={vertex:null,uv:null,index:null},this.renderer.startUp(t),this.renderer._clippingManager._currentFrameNo=e,this.renderer._clippingManager._maskTexture=void 0,zt.getInstance()._shaderSets=[]}bindTexture(t,e){this.renderer.bindTexture(t,e)}getHitAreaDefs(){var t,e;return null!=(e=null==(t=this.settings.hitAreas)?void 0:t.map((t=>({id:t.Id,name:t.Name,index:this.coreModel.getDrawableIndex(t.Id)}))))?e:[]}getDrawableIDs(){return this.coreModel.getDrawableIds()}getDrawableIndex(t){return this.coreModel.getDrawableIndex(t)}getDrawableVertices(t){if("string"==typeof t&&-1===(t=this.coreModel.getDrawableIndex(t)))throw new TypeError("Unable to find drawable ID: "+t);const e=this.coreModel.getDrawableVertices(t).slice();for(let i=0;i{!function i(){try{si(),t()}catch(s){if(ei--,ei<0){const t=new Error("Failed to start up Cubism 4 framework.");return t.cause=s,void e(t)}le.log("Cubism4","Startup failed, retrying 10ms later..."),setTimeout(i,10)}}()}))),ti)}function si(t){t=Object.assign({logFunction:console.log,loggingLevel:b.LogLevel_Verbose},t),P.startUp(t),P.initialize()}function ri(){var t;null==(t=this.__moc)||t.release()}Oe.registerRuntime({version:4,ready:ii,test:t=>t instanceof Je||Je.isValidJSON(t),isValidMoc(t){if(t.byteLength<4)return!1;const e=new Int8Array(t,0,4);return"MOC3"===String.fromCharCode(...e)},createModelSettings:t=>new Je(t),createCoreModel(t,e){const i=R.create(t,!!(null==e?void 0:e.checkMocConsistency));try{const t=i.createModel();return t.__moc=i,t}catch(s){try{i.release()}catch(r){}throw s}},createInternalModel(t,e,i){const s=new Ke(t,e,i),r=t;return r.__moc&&(s.__moc=r.__moc,delete r.__moc,s.once("destroy",ri)),s},createPhysics:(t,e)=>yt.create(e),createPose:(t,e)=>u.create(e)}),t.ACubismMotion=U,t.BreathParameterData=a,t.CSM_ASSERT=S,t.Constant=v,t.Cubism4ExpressionManager=$e,t.Cubism4InternalModel=Ke,t.Cubism4ModelSettings=Je,t.Cubism4MotionManager=Ze,t.CubismBlendMode=f,t.CubismBreath=o,t.CubismClippingContext=Gt,t.CubismClippingManager_WebGL=Vt,t.CubismDebug=E,t.CubismExpressionMotion=V,t.CubismEyeBlink=l,t.CubismFramework=P,t.CubismLogDebug=w,t.CubismLogError=L,t.CubismLogInfo=T,t.CubismLogVerbose=function(t,...e){E.print(b.LogLevel_Verbose,"[CSM][V]"+t+"\n",e)},t.CubismLogWarning=I,t.CubismMath=m,t.CubismMatrix44=_,t.CubismMoc=R,t.CubismModel=B,t.CubismModelSettingsJson=Kt,t.CubismModelUserData=k,t.CubismModelUserDataJson=O,t.CubismMotion=ot,t.CubismMotionCurve=H,t.CubismMotionCurveTarget=X,t.CubismMotionData=q,t.CubismMotionEvent=Y,t.CubismMotionJson=$,t.CubismMotionManager=class extends nt{constructor(){super(),this._currentPriority=0,this._reservePriority=0}getCurrentPriority(){return this._currentPriority}getReservePriority(){return this._reservePriority}setReservePriority(t){this._reservePriority=t}startMotionPriority(t,e,i){return i==this._reservePriority&&(this._reservePriority=0),this._currentPriority=i,super.startMotion(t,e,this._userTimeSeconds)}updateMotion(t,e){this._userTimeSeconds+=e;const i=super.doUpdateMotion(t,this._userTimeSeconds);return this.isFinished()&&(this._currentPriority=0),i}reserveMotion(t){return!(t<=this._reservePriority||t<=this._currentPriority)&&(this._reservePriority=t,!0)}},t.CubismMotionPoint=j,t.CubismMotionQueueEntry=at,t.CubismMotionQueueManager=nt,t.CubismMotionSegment=W,t.CubismMotionSegmentType=z,t.CubismPhysics=yt,t.CubismPhysicsInput=gt,t.CubismPhysicsJson=pt,t.CubismPhysicsOutput=mt,t.CubismPhysicsParticle=dt,t.CubismPhysicsRig=_t,t.CubismPhysicsSource=ut,t.CubismPhysicsSubRig=ct,t.CubismPhysicsTargetType=ht,t.CubismPose=u,t.CubismRenderTextureResource=Nt,t.CubismRenderer=p,t.CubismRendererProfile_WebGL=Xt,t.CubismRenderer_WebGL=Qt,t.CubismShader_WebGL=zt,t.CubismTextureColor=y,t.CubismVector2=c,t.DrawableColorData=A,t.DrawableCullingData=D,t.EvaluationOptionFlag=J,t.ExpressionBlendType=G,t.ExpressionManager=ge,t.EyeState=h,t.FileLoader=He,t.FocusController=me,t.HitAreaBody="Body",t.HitAreaHead="Head",t.HitAreaPrefix="HitArea",t.InteractionMixin=ke,t.InternalModel=ve,t.InvalidMotionQueueEntryHandleValue=lt,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DFactory=Oe,t.Live2DLoader=Te,t.Live2DModel=je,t.Live2DTransform=Ne,t.LogLevel=b,t.ModelSettings=_e,t.MotionManager=xe,t.MotionPreloadStrategy=Ce,t.MotionPriority=pe,t.MotionState=fe,t.Options=Ct,t.ParamAngleX=te,t.ParamAngleY=ee,t.ParamAngleZ=ie,t.ParamArmLA="ParamArmLA",t.ParamArmLB="ParamArmLB",t.ParamArmRA="ParamArmRA",t.ParamArmRB="ParamArmRB",t.ParamBaseX="ParamBaseX",t.ParamBaseY="ParamBaseY",t.ParamBodyAngleX=oe,t.ParamBodyAngleY="ParamBodyAngleY",t.ParamBodyAngleZ="ParamBodyAngleZ",t.ParamBreath=ae,t.ParamBrowLAngle="ParamBrowLAngle",t.ParamBrowLForm="ParamBrowLForm",t.ParamBrowLX="ParamBrowLX",t.ParamBrowLY="ParamBrowLY",t.ParamBrowRAngle="ParamBrowRAngle",t.ParamBrowRForm="ParamBrowRForm",t.ParamBrowRX="ParamBrowRX",t.ParamBrowRY="ParamBrowRY",t.ParamBustX="ParamBustX",t.ParamBustY="ParamBustY",t.ParamCheek="ParamCheek",t.ParamEyeBallForm="ParamEyeBallForm",t.ParamEyeBallX=se,t.ParamEyeBallY=re,t.ParamEyeLOpen="ParamEyeLOpen",t.ParamEyeLSmile="ParamEyeLSmile",t.ParamEyeROpen="ParamEyeROpen",t.ParamEyeRSmile="ParamEyeRSmile",t.ParamHairBack="ParamHairBack",t.ParamHairFluffy="ParamHairFluffy",t.ParamHairFront="ParamHairFront",t.ParamHairSide="ParamHairSide",t.ParamHandL="ParamHandL",t.ParamHandR="ParamHandR",t.ParamMouthForm="ParamMouthForm",t.ParamMouthOpenY="ParamMouthOpenY",t.ParamNONE="NONE:",t.ParamShoulderY="ParamShoulderY",t.PartColorData=F,t.PartData=d,t.PartsArmLPrefix="Parts01ArmL_",t.PartsArmPrefix="Parts01Arm_",t.PartsArmRPrefix="Parts01ArmR_",t.PartsIdCore="Parts01Core",t.PhysicsJsonEffectiveForces=class{constructor(){this.gravity=new c(0,0),this.wind=new c(0,0)}},t.PhysicsOutput=xt,t.ShaderNames=jt,t.SoundManager=ye,t.VERSION="0.4.0",t.XHRLoader=Se,t.ZipLoader=qe,t.applyMixins=ue,t.clamp=he,t.copyArray=function(t,e,i,s,r){const o=e[s];Array.isArray(o)&&(i[r]=o.filter((e=>null!==e&&typeof e===t)))},t.copyProperty=function(t,e,i,s,r){const o=e[s];null!==o&&typeof o===t&&(i[r]=o)},t.csmRect=Rt,t.cubism4Ready=ii,t.folderName=de,t.fragmentShaderSrcMaskInvertedPremultipliedAlpha=Zt,t.fragmentShaderSrcMaskPremultipliedAlpha=Jt,t.fragmentShaderSrcPremultipliedAlpha=$t,t.fragmentShaderSrcsetupMask=Ht,t.logger=le,t.rand=function(t,e){return Math.random()*(e-t)+t},t.remove=ce,t.startUpCubism4=si,t.vertexShaderSrc=Yt,t.vertexShaderSrcMasked=qt,t.vertexShaderSrcSetupMask=Wt,Object.defineProperties(t,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})); +var __pow=Math.pow,__async=(t,e,i)=>new Promise(((s,r)=>{var o=t=>{try{n(i.next(t))}catch(e){r(e)}},a=t=>{try{n(i.throw(t))}catch(e){r(e)}},n=t=>t.done?s(t.value):Promise.resolve(t.value).then(o,a);n((i=i.apply(t,e)).next())}));!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("@pixi/utils"),require("@pixi/math"),require("@pixi/core"),require("@pixi/display")):"function"==typeof define&&define.amd?define(["exports","@pixi/utils","@pixi/math","@pixi/core","@pixi/display"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).PIXI=t.PIXI||{},t.PIXI.live2d=t.PIXI.live2d||{}),t.PIXI.utils,t.PIXI,t.PIXI,t.PIXI)}(this,(function(t,e,i,s,r){"use strict";class o{constructor(){this._breathParameters=[],this._currentTime=0}static create(){return new o}setParameters(t){this._breathParameters=t}getParameters(){return this._breathParameters}updateParameters(t,e){this._currentTime+=e;const i=2*this._currentTime*3.14159;for(let s=0;s=1&&(s=1,this._blinkingState=h.EyeState_Closed,this._stateStartTimeSeconds=this._userTimeSeconds),i=1-s;break;case h.EyeState_Closed:s=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._closedSeconds,s>=1&&(this._blinkingState=h.EyeState_Opening,this._stateStartTimeSeconds=this._userTimeSeconds),i=0;break;case h.EyeState_Opening:s=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._openingSeconds,s>=1&&(s=1,this._blinkingState=h.EyeState_Interval,this._nextBlinkingTime=this.determinNextBlinkingTiming()),i=s;break;case h.EyeState_Interval:this._nextBlinkingTime(t[t.EyeState_First=0]="EyeState_First",t[t.EyeState_Interval=1]="EyeState_Interval",t[t.EyeState_Closing=2]="EyeState_Closing",t[t.EyeState_Closed=3]="EyeState_Closed",t[t.EyeState_Opening=4]="EyeState_Opening",t))(h||{});class u{static create(t){const e=new u;"number"==typeof t.FadeInTime&&(e._fadeTimeSeconds=t.FadeInTime,e._fadeTimeSeconds<=0&&(e._fadeTimeSeconds=.5));const i=t.Groups,s=i.length;for(let r=0;r.001){if(r>=0)break;r=n,o=t.getPartOpacityByIndex(i),o+=e/this._fadeTimeSeconds,o>1&&(o=1)}}r<0&&(r=0,o=1);for(let n=i;n.15&&(i=1-.15/(1-o)),s>i&&(s=i),t.setPartOpacityByIndex(e,s)}}}constructor(){this._fadeTimeSeconds=.5,this._lastModel=void 0,this._partGroups=[],this._partGroupCounts=[]}}class d{constructor(t){this.parameterIndex=0,this.partIndex=0,this.partId="",this.link=[],null!=t&&this.assignment(t)}assignment(t){return this.partId=t.partId,this.link=t.link.map((t=>t.clone())),this}initialize(t){this.parameterIndex=t.getParameterIndex(this.partId),this.partIndex=t.getPartIndex(this.partId),t.setParameterValueByIndex(this.parameterIndex,1)}clone(){const t=new d;return t.partId=this.partId,t.parameterIndex=this.parameterIndex,t.partIndex=this.partIndex,t.link=this.link.map((t=>t.clone())),t}}class c{constructor(t,e){this.x=t||0,this.y=e||0}add(t){const e=new c(0,0);return e.x=this.x+t.x,e.y=this.y+t.y,e}substract(t){const e=new c(0,0);return e.x=this.x-t.x,e.y=this.y-t.y,e}multiply(t){const e=new c(0,0);return e.x=this.x*t.x,e.y=this.y*t.y,e}multiplyByScaler(t){return this.multiply(new c(t,t))}division(t){const e=new c(0,0);return e.x=this.x/t.x,e.y=this.y/t.y,e}divisionByScalar(t){return this.division(new c(t,t))}getLength(){return Math.sqrt(this.x*this.x+this.y*this.y)}getDistanceWith(t){return Math.sqrt((this.x-t.x)*(this.x-t.x)+(this.y-t.y)*(this.y-t.y))}dot(t){return this.x*t.x+this.y*t.y}normalize(){const t=Math.pow(this.x*this.x+this.y*this.y,.5);this.x=this.x/t,this.y=this.y/t}isEqual(t){return this.x==t.x&&this.y==t.y}isNotEqual(t){return!this.isEqual(t)}}const g=class{static range(t,e,i){return ti&&(t=i),t}static sin(t){return Math.sin(t)}static cos(t){return Math.cos(t)}static abs(t){return Math.abs(t)}static sqrt(t){return Math.sqrt(t)}static cbrt(t){if(0===t)return t;let e=t;const i=e<0;let s;return i&&(e=-e),e===1/0?s=1/0:(s=Math.exp(Math.log(e)/3),s=(e/(s*s)+2*s)/3),i?-s:s}static getEasingSine(t){return t<0?0:t>1?1:.5-.5*this.cos(t*Math.PI)}static max(t,e){return t>e?t:e}static min(t,e){return t>e?e:t}static degreesToRadian(t){return t/180*Math.PI}static radianToDegrees(t){return 180*t/Math.PI}static directionToRadian(t,e){let i=Math.atan2(e.y,e.x)-Math.atan2(t.y,t.x);for(;i<-Math.PI;)i+=2*Math.PI;for(;i>Math.PI;)i-=2*Math.PI;return i}static directionToDegrees(t,e){const i=this.directionToRadian(t,e);let s=this.radianToDegrees(i);return e.x-t.x>0&&(s=-s),s}static radianToDirection(t){const e=new c;return e.x=this.sin(t),e.y=this.cos(t),e}static quadraticEquation(t,e,i){return this.abs(t)1&&(t=1),e<0?e=0:e>1&&(e=1),i<0?i=0:i>1&&(i=1),s<0?s=0:s>1&&(s=1),this._modelColor.R=t,this._modelColor.G=e,this._modelColor.B=i,this._modelColor.A=s}getModelColor(){return Object.assign({},this._modelColor)}setIsPremultipliedAlpha(t){this._isPremultipliedAlpha=t}isPremultipliedAlpha(){return this._isPremultipliedAlpha}setIsCulling(t){this._isCulling=t}isCulling(){return this._isCulling}setAnisotropy(t){this._anisotropy=t}getAnisotropy(){return this._anisotropy}getModel(){return this._model}useHighPrecisionMask(t){this._useHighPrecisionMask=t}isUsingHighPrecisionMask(){return this._useHighPrecisionMask}constructor(){this._isCulling=!1,this._isPremultipliedAlpha=!1,this._anisotropy=0,this._modelColor=new y,this._useHighPrecisionMask=!1,this._mvpMatrix4x4=new p,this._mvpMatrix4x4.loadIdentity()}}var f=(t=>(t[t.CubismBlendMode_Normal=0]="CubismBlendMode_Normal",t[t.CubismBlendMode_Additive=1]="CubismBlendMode_Additive",t[t.CubismBlendMode_Multiplicative=2]="CubismBlendMode_Multiplicative",t))(f||{});class y{constructor(t=1,e=1,i=1,s=1){this.R=t,this.G=e,this.B=i,this.A=s}}let x,C=!1,M=!1;const v={vertexOffset:0,vertexStep:2};class P{static startUp(t){if(C)return T("CubismFramework.startUp() is already done."),C;if(Live2DCubismCore._isStarted)return C=!0,!0;if(Live2DCubismCore._isStarted=!0,x=t,x&&Live2DCubismCore.Logging.csmSetLogFunction(x.logFunction),C=!0,C){const t=Live2DCubismCore.Version.csmGetVersion(),e=(16711680&t)>>16,i=65535&t,s=t;T("Live2D Cubism Core version: {0}.{1}.{2} ({3})",("00"+((4278190080&t)>>24)).slice(-2),("00"+e).slice(-2),("0000"+i).slice(-4),s)}return T("CubismFramework.startUp() is complete."),C}static cleanUp(){C=!1,M=!1,x=void 0}static initialize(t=0){C?M?I("CubismFramework.initialize() skipped, already initialized."):(Live2DCubismCore.Memory.initializeAmountOfMemory(t),M=!0,T("CubismFramework.initialize() is complete.")):I("CubismFramework is not started.")}static dispose(){C?M?(_.staticRelease(),M=!1,T("CubismFramework.dispose() is complete.")):I("CubismFramework.dispose() skipped, not initialized."):I("CubismFramework is not started.")}static isStarted(){return C}static isInitialized(){return M}static coreLogFunction(t){Live2DCubismCore.Logging.csmGetLogFunction()&&Live2DCubismCore.Logging.csmGetLogFunction()(t)}static getLoggingLevel(){return null!=x?x.loggingLevel:b.LogLevel_Off}constructor(){}}var b=(t=>(t[t.LogLevel_Verbose=0]="LogLevel_Verbose",t[t.LogLevel_Debug=1]="LogLevel_Debug",t[t.LogLevel_Info=2]="LogLevel_Info",t[t.LogLevel_Warning=3]="LogLevel_Warning",t[t.LogLevel_Error=4]="LogLevel_Error",t[t.LogLevel_Off=5]="LogLevel_Off",t))(b||{});const S=()=>{};function w(t,...e){L.print(b.LogLevel_Debug,"[CSM][D]"+t+"\n",e)}function T(t,...e){L.print(b.LogLevel_Info,"[CSM][I]"+t+"\n",e)}function I(t,...e){L.print(b.LogLevel_Warning,"[CSM][W]"+t+"\n",e)}function E(t,...e){L.print(b.LogLevel_Error,"[CSM][E]"+t+"\n",e)}class L{static print(t,e,i){if(ti[e])))}static dumpBytes(t,e,i){for(let s=0;s0?this.print(t,"\n"):s%8==0&&s>0&&this.print(t," "),this.print(t,"{0} ",[255&e[s]]);this.print(t,"\n")}constructor(){}}class A{constructor(t=!1,e=new y){this.isOverwritten=t,this.Color=e}}class F{constructor(t=!1,e=new y){this.isOverwritten=t,this.Color=e}}class D{constructor(t=!1,e=!1){this.isOverwritten=t,this.isCulling=e}}class B{update(){this._model.update(),this._model.drawables.resetDynamicFlags()}getPixelsPerUnit(){return null==this._model?0:this._model.canvasinfo.PixelsPerUnit}getCanvasWidth(){return null==this._model?0:this._model.canvasinfo.CanvasWidth/this._model.canvasinfo.PixelsPerUnit}getCanvasHeight(){return null==this._model?0:this._model.canvasinfo.CanvasHeight/this._model.canvasinfo.PixelsPerUnit}saveParameters(){const t=this._model.parameters.count,e=this._savedParameters.length;for(let i=0;ie&&(e=this._model.parameters.minimumValues[t]),this._parameterValues[t]=1==i?e:this._parameterValues[t]=this._parameterValues[t]*(1-i)+e*i)}setParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.setParameterValueByIndex(s,e,i)}addParameterValueByIndex(t,e,i=1){this.setParameterValueByIndex(t,this.getParameterValueByIndex(t)+e*i)}addParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.addParameterValueByIndex(s,e,i)}multiplyParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.multiplyParameterValueByIndex(s,e,i)}multiplyParameterValueByIndex(t,e,i=1){this.setParameterValueByIndex(t,this.getParameterValueByIndex(t)*(1+(e-1)*i))}getDrawableIds(){return this._drawableIds.slice()}getDrawableIndex(t){const e=this._model.drawables.count;for(let i=0;ie&&(t=e);for(let i=0;i=0&&this._partChildDrawables[n].push(t)}}}constructor(t){this._model=t,this._savedParameters=[],this._parameterIds=[],this._drawableIds=[],this._partIds=[],this._isOverwrittenModelMultiplyColors=!1,this._isOverwrittenModelScreenColors=!1,this._isOverwrittenCullings=!1,this._modelOpacity=1,this._userMultiplyColors=[],this._userScreenColors=[],this._userCullings=[],this._userPartMultiplyColors=[],this._userPartScreenColors=[],this._partChildDrawables=[],this._notExistPartId={},this._notExistParameterId={},this._notExistParameterValues={},this._notExistPartOpacities={},this.initialize()}release(){this._model.release(),this._model=void 0}}class R{static create(t,e){if(e){if(!this.hasMocConsistency(t))throw new Error("Inconsistent MOC3.")}const i=Live2DCubismCore.Moc.fromArrayBuffer(t);if(i){const e=new R(i);return e._mocVersion=Live2DCubismCore.Version.csmGetMocVersion(i,t),e}throw new Error("Failed to CubismMoc.create().")}createModel(){let t;const e=Live2DCubismCore.Model.fromMoc(this._moc);if(e)return t=new B(e),++this._modelCount,t;throw new Error("Unknown error")}deleteModel(t){null!=t&&--this._modelCount}constructor(t){this._moc=t,this._modelCount=0,this._mocVersion=0}release(){this._moc._release(),this._moc=void 0}getLatestMocVersion(){return Live2DCubismCore.Version.csmGetLatestMocVersion()}getMocVersion(){return this._mocVersion}static hasMocConsistency(t){return 1===Live2DCubismCore.Moc.prototype.hasMocConsistency(t)}}class O{constructor(t,e){this._json=t}release(){this._json=void 0}getUserDataCount(){return this._json.Meta.UserDataCount}getTotalUserDataSize(){return this._json.Meta.TotalUserDataSize}getUserDataTargetType(t){return this._json.UserData[t].Target}getUserDataId(t){return this._json.UserData[t].Id}getUserDataValue(t){return this._json.UserData[t].Value}}class k{static create(t,e){const i=new k;return i.parseUserData(t,e),i}getArtMeshUserDatas(){return this._artMeshUserDataNode}parseUserData(t,e){const i=new O(t,e),s=i.getUserDataCount();for(let r=0;r0&&e.getEndTime()(t[t.ExpressionBlendType_Add=0]="ExpressionBlendType_Add",t[t.ExpressionBlendType_Multiply=1]="ExpressionBlendType_Multiply",t[t.ExpressionBlendType_Overwrite=2]="ExpressionBlendType_Overwrite",t))(G||{});t.CubismConfig=void 0,(N=t.CubismConfig||(t.CubismConfig={})).supportMoreMaskDivisions=!0,N.setOpacityFromMotion=!1;var X=(t=>(t[t.CubismMotionCurveTarget_Model=0]="CubismMotionCurveTarget_Model",t[t.CubismMotionCurveTarget_Parameter=1]="CubismMotionCurveTarget_Parameter",t[t.CubismMotionCurveTarget_PartOpacity=2]="CubismMotionCurveTarget_PartOpacity",t))(X||{}),z=(t=>(t[t.CubismMotionSegmentType_Linear=0]="CubismMotionSegmentType_Linear",t[t.CubismMotionSegmentType_Bezier=1]="CubismMotionSegmentType_Bezier",t[t.CubismMotionSegmentType_Stepped=2]="CubismMotionSegmentType_Stepped",t[t.CubismMotionSegmentType_InverseStepped=3]="CubismMotionSegmentType_InverseStepped",t))(z||{});class j{constructor(t=0,e=0){this.time=t,this.value=e}}class W{constructor(){this.basePointIndex=0,this.segmentType=0}}class H{constructor(){this.id="",this.type=0,this.segmentCount=0,this.baseSegmentIndex=0,this.fadeInTime=0,this.fadeOutTime=0}}class Y{constructor(){this.fireTime=0,this.value=""}}class q{constructor(){this.duration=0,this.loop=!1,this.curveCount=0,this.eventCount=0,this.fps=0,this.curves=[],this.segments=[],this.points=[],this.events=[]}}class ${constructor(t){this._json=t}release(){this._json=void 0}getMotionDuration(){return this._json.Meta.Duration}isMotionLoop(){return this._json.Meta.Loop||!1}getEvaluationOptionFlag(t){return J.EvaluationOptionFlag_AreBeziersRistricted==t&&!!this._json.Meta.AreBeziersRestricted}getMotionCurveCount(){return this._json.Meta.CurveCount}getMotionFps(){return this._json.Meta.Fps}getMotionTotalSegmentCount(){return this._json.Meta.TotalSegmentCount}getMotionTotalPointCount(){return this._json.Meta.TotalPointCount}getMotionFadeInTime(){return this._json.Meta.FadeInTime}getMotionFadeOutTime(){return this._json.Meta.FadeOutTime}getMotionCurveTarget(t){return this._json.Curves[t].Target}getMotionCurveId(t){return this._json.Curves[t].Id}getMotionCurveFadeInTime(t){return this._json.Curves[t].FadeInTime}getMotionCurveFadeOutTime(t){return this._json.Curves[t].FadeOutTime}getMotionCurveSegmentCount(t){return this._json.Curves[t].Segments.length}getMotionCurveSegment(t,e){return this._json.Curves[t].Segments[e]}getEventCount(){return this._json.Meta.UserDataCount||0}getTotalEventValueSize(){return this._json.Meta.TotalUserDataSize}getEventTime(t){return this._json.UserData[t].Time}getEventValue(t){return this._json.UserData[t].Value}}var J=(t=>(t[t.EvaluationOptionFlag_AreBeziersRistricted=0]="EvaluationOptionFlag_AreBeziersRistricted",t))(J||{});const Z="Opacity";function Q(t,e,i){const s=new j;return s.time=t.time+(e.time-t.time)*i,s.value=t.value+(e.value-t.value)*i,s}function K(t,e){let i=(e-t[0].time)/(t[1].time-t[0].time);return i<0&&(i=0),t[0].value+(t[1].value-t[0].value)*i}function tt(t,e){let i=(e-t[0].time)/(t[3].time-t[0].time);i<0&&(i=0);const s=Q(t[0],t[1],i),r=Q(t[1],t[2],i),o=Q(t[2],t[3],i),a=Q(s,r,i),n=Q(r,o,i);return Q(a,n,i).value}function et(t,e){const i=e,s=t[0].time,r=t[3].time,o=t[1].time,a=t[2].time,n=r-3*a+3*o-s,l=3*a-6*o+3*s,h=3*o-3*s,u=s-i,d=m.cardanoAlgorithmForBezier(n,l,h,u),c=Q(t[0],t[1],d),g=Q(t[1],t[2],d),p=Q(t[2],t[3],d),_=Q(c,g,d),f=Q(g,p,d);return Q(_,f,d).value}function it(t,e){return t[0].value}function st(t,e){return t[1].value}function rt(t,e,i){const s=t.curves[e];let r=-1;const o=s.baseSegmentIndex+s.segmentCount;let a=0;for(let l=s.baseSegmentIndex;li){r=l;break}if(-1==r)return t.points[a].value;const n=t.segments[r];return n.evaluate(t.points.slice(n.basePointIndex),i)}class ot extends U{constructor(){super(),this._eyeBlinkParameterIds=[],this._lipSyncParameterIds=[],this._sourceFrameRate=30,this._loopDurationSeconds=-1,this._isLoop=!1,this._isLoopFadeIn=!0,this._lastWeight=0,this._modelOpacity=1}static create(t,e){const i=new ot;return i.parse(t),i._sourceFrameRate=i._motionData.fps,i._loopDurationSeconds=i._motionData.duration,i._onFinishedMotion=e,i}doUpdateParameters(e,i,s,r){null==this._modelCurveIdEyeBlink&&(this._modelCurveIdEyeBlink="EyeBlink"),null==this._modelCurveIdLipSync&&(this._modelCurveIdLipSync="LipSync"),null==this._modelCurveIdOpacity&&(this._modelCurveIdOpacity=Z);let o=i-r.getStartTime();o<0&&(o=0);let a=Number.MAX_VALUE,n=Number.MAX_VALUE;const l=64;let h=0,u=0;this._eyeBlinkParameterIds.length>l&&w("too many eye blink targets : {0}",this._eyeBlinkParameterIds.length),this._lipSyncParameterIds.length>l&&w("too many lip sync targets : {0}",this._lipSyncParameterIds.length);const d=this._fadeInSeconds<=0?1:m.getEasingSine((i-r.getFadeInStartTime())/this._fadeInSeconds),c=this._fadeOutSeconds<=0||r.getEndTime()<0?1:m.getEasingSine((r.getEndTime()-i)/this._fadeOutSeconds);let g,p,_,f=o;if(this._isLoop)for(;f>this._motionData.duration;)f-=this._motionData.duration;const y=this._motionData.curves;for(p=0;p>t&1)continue;const r=i+(n-i)*s;e.setParameterValueById(this._eyeBlinkParameterIds[t],r)}if(a!=Number.MAX_VALUE)for(let t=0;t>t&1)continue;const r=i+(a-i)*s;e.setParameterValueById(this._lipSyncParameterIds[t],r)}for(;p=this._motionData.duration&&(this._isLoop?(r.setStartTime(i),this._isLoopFadeIn&&r.setFadeInStartTime(i)):(this._onFinishedMotion&&this._onFinishedMotion(this),r.setIsFinished(!0))),this._lastWeight=s}setIsLoop(t){this._isLoop=t}isLoop(){return this._isLoop}setIsLoopFadeIn(t){this._isLoopFadeIn=t}isLoopFadeIn(){return this._isLoopFadeIn}getDuration(){return this._isLoop?-1:this._loopDurationSeconds}getLoopDuration(){return this._loopDurationSeconds}setParameterFadeInTime(t,e){const i=this._motionData.curves;for(let s=0;snew H)),this._motionData.segments=Array.from({length:e.getMotionTotalSegmentCount()}).map((()=>new W)),this._motionData.events=Array.from({length:this._motionData.eventCount}).map((()=>new Y)),this._motionData.points=[];let o=0,a=0;for(let n=0;nt&&this._motionData.events[i].fireTime<=e&&this._firedEventValues.push(this._motionData.events[i].value);return this._firedEventValues}isExistModelOpacity(){for(let t=0;tnull!=e&&e._motionQueueEntryHandle==t))}setEventCallback(t,e=null){this._eventCallBack=t,this._eventCustomData=e}doUpdateMotion(t,e){let i=!1,s=0;for(;s(t[t.CubismPhysicsTargetType_Parameter=0]="CubismPhysicsTargetType_Parameter",t))(ht||{}),ut=(t=>(t[t.CubismPhysicsSource_X=0]="CubismPhysicsSource_X",t[t.CubismPhysicsSource_Y=1]="CubismPhysicsSource_Y",t[t.CubismPhysicsSource_Angle=2]="CubismPhysicsSource_Angle",t))(ut||{});class dt{constructor(){this.initialPosition=new c(0,0),this.position=new c(0,0),this.lastPosition=new c(0,0),this.lastGravity=new c(0,0),this.force=new c(0,0),this.velocity=new c(0,0)}}class ct{constructor(){this.normalizationPosition={},this.normalizationAngle={}}}class gt{constructor(){this.source={}}}class mt{constructor(){this.destination={},this.translationScale=new c(0,0)}}class pt{constructor(){this.settings=[],this.inputs=[],this.outputs=[],this.particles=[],this.gravity=new c(0,0),this.wind=new c(0,0),this.fps=0}}class _t{constructor(t){this._json=t}release(){this._json=void 0}getGravity(){const t=new c(0,0);return t.x=this._json.Meta.EffectiveForces.Gravity.X,t.y=this._json.Meta.EffectiveForces.Gravity.Y,t}getWind(){const t=new c(0,0);return t.x=this._json.Meta.EffectiveForces.Wind.X,t.y=this._json.Meta.EffectiveForces.Wind.Y,t}getFps(){return this._json.Meta.Fps||0}getSubRigCount(){return this._json.Meta.PhysicsSettingCount}getTotalInputCount(){return this._json.Meta.TotalInputCount}getTotalOutputCount(){return this._json.Meta.TotalOutputCount}getVertexCount(){return this._json.Meta.VertexCount}getNormalizationPositionMinimumValue(t){return this._json.PhysicsSettings[t].Normalization.Position.Minimum}getNormalizationPositionMaximumValue(t){return this._json.PhysicsSettings[t].Normalization.Position.Maximum}getNormalizationPositionDefaultValue(t){return this._json.PhysicsSettings[t].Normalization.Position.Default}getNormalizationAngleMinimumValue(t){return this._json.PhysicsSettings[t].Normalization.Angle.Minimum}getNormalizationAngleMaximumValue(t){return this._json.PhysicsSettings[t].Normalization.Angle.Maximum}getNormalizationAngleDefaultValue(t){return this._json.PhysicsSettings[t].Normalization.Angle.Default}getInputCount(t){return this._json.PhysicsSettings[t].Input.length}getInputWeight(t,e){return this._json.PhysicsSettings[t].Input[e].Weight}getInputReflect(t,e){return this._json.PhysicsSettings[t].Input[e].Reflect}getInputType(t,e){return this._json.PhysicsSettings[t].Input[e].Type}getInputSourceId(t,e){return this._json.PhysicsSettings[t].Input[e].Source.Id}getOutputCount(t){return this._json.PhysicsSettings[t].Output.length}getOutputVertexIndex(t,e){return this._json.PhysicsSettings[t].Output[e].VertexIndex}getOutputAngleScale(t,e){return this._json.PhysicsSettings[t].Output[e].Scale}getOutputWeight(t,e){return this._json.PhysicsSettings[t].Output[e].Weight}getOutputDestinationId(t,e){return this._json.PhysicsSettings[t].Output[e].Destination.Id}getOutputType(t,e){return this._json.PhysicsSettings[t].Output[e].Type}getOutputReflect(t,e){return this._json.PhysicsSettings[t].Output[e].Reflect}getParticleCount(t){return this._json.PhysicsSettings[t].Vertices.length}getParticleMobility(t,e){return this._json.PhysicsSettings[t].Vertices[e].Mobility}getParticleDelay(t,e){return this._json.PhysicsSettings[t].Vertices[e].Delay}getParticleAcceleration(t,e){return this._json.PhysicsSettings[t].Vertices[e].Acceleration}getParticleRadius(t,e){return this._json.PhysicsSettings[t].Vertices[e].Radius}getParticlePosition(t,e){const i=new c(0,0);return i.x=this._json.PhysicsSettings[t].Vertices[e].Position.X,i.y=this._json.PhysicsSettings[t].Vertices[e].Position.Y,i}}const ft="Angle";class yt{static create(t){const e=new yt;return e.parse(t),e._physicsRig.gravity.y=0,e}static delete(t){null!=t&&t.release()}parse(t){this._physicsRig=new pt;const e=new _t(t);this._physicsRig.gravity=e.getGravity(),this._physicsRig.wind=e.getWind(),this._physicsRig.subRigCount=e.getSubRigCount(),this._physicsRig.fps=e.getFps(),this._currentRigOutputs=[],this._previousRigOutputs=[];let i=0,s=0,r=0;for(let o=0;o=u.particleCount)continue;let s=new c;s=p[i].position.substract(p[i-1].position),l=g[e].getValue(s,p,i,g[e].reflect,this._options.gravity),this._currentRigOutputs[C].outputs[e]=l,this._previousRigOutputs[C].outputs[e]=l;const r=g[e].destinationParameterIndex,o=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(_.subarray(r))):_.slice(r);Dt(o,y[r],f[r],l,g[e]);for(let t=r,e=0;t=e)return;if(this._currentRemainTime+=e,this._currentRemainTime>5&&(this._currentRemainTime=0),f=t.getModel().parameters.values,y=t.getModel().parameters.maximumValues,x=t.getModel().parameters.minimumValues,C=t.getModel().parameters.defaultValues,(null!=(s=null==(i=this._parameterCaches)?void 0:i.length)?s:0)0?1/this._physicsRig.fps:e;this._currentRemainTime>=M;){for(let t=0;t=d.particleCount)continue;const r=new c;r.x=_[s].position.x-_[s-1].position.x,r.y=_[s].position.y-_[s-1].position.y,h=p[e].getValue(r,_,s,p[e].reflect,this._options.gravity),this._currentRigOutputs[i].outputs[e]=h;const o=p[e].destinationParameterIndex,a=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(this._parameterCaches.subarray(o))):this._parameterCaches.slice(o);Dt(a,x[o],y[o],h,p[e]);for(let t=o,e=0;t=2?e[i-1].position.substract(e[i-2].position):r.multiplyByScaler(-1),o=m.directionToRadian(r,t),s&&(o*=-1),o}function Tt(t,e){return Math.min(t,e)+function(t,e){return Math.abs(Math.max(t,e)-Math.min(t,e))}(t,e)/2}function It(t,e){return t.x}function Et(t,e){return t.y}function Lt(t,e){return e}function At(t,e,i,s,r,o,a,n){let l,h,u,d,g=new c(0,0),p=new c(0,0),_=new c(0,0),f=new c(0,0);t[0].position=new c(i.x,i.y),l=m.degreesToRadian(s),d=m.radianToDirection(l),d.normalize();for(let y=1;yi&&(a>r.valueExceededMaximum&&(r.valueExceededMaximum=a),a=i),n=r.weight/100,n>=1||(a=t[0]*(1-n)+a*n),t[0]=a}function Bt(t,e,i,s,r,o,a,n){let l=0;const h=m.max(i,e);ht&&(t=u);const d=m.min(r,o),c=m.max(r,o),g=a,p=Tt(u,h),_=t-p;switch(Math.sign(_)){case 1:{const t=c-g,e=h-p;0!=e&&(l=_*(t/e),l+=g);break}case-1:{const t=d-g,e=u-p;0!=e&&(l=_*(t/e),l+=g);break}case 0:l=g}return n?l:-1*l}class Rt{constructor(t=0,e=0,i=0,s=0){this.x=t,this.y=e,this.width=i,this.height=s}getCenterX(){return this.x+.5*this.width}getCenterY(){return this.y+.5*this.height}getRight(){return this.x+this.width}getBottom(){return this.y+this.height}setRect(t){this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height}expand(t,e){this.x-=t,this.y-=e,this.width+=2*t,this.height+=2*e}}let Ot,kt,Ut;class Vt{getChannelFlagAsColor(t){return this._channelColors[t]}getMaskRenderTexture(){if(this._maskTexture&&null!=this._maskTexture.textures)this._maskTexture.frameNo=this._currentFrameNo;else{this._maskRenderTextures=[],this._maskColorBuffers=[];const t=this._clippingMaskBufferSize;for(let e=0;ec&&(c=e),ig&&(g=i)}if(u!=Number.MAX_VALUE)if(ur&&(r=c),g>o&&(o=g),i==Number.MAX_VALUE)e._allClippedDrawRect.x=0,e._allClippedDrawRect.y=0,e._allClippedDrawRect.width=0,e._allClippedDrawRect.height=0,e._isUsing=!1;else{e._isUsing=!0;const t=r-i,a=o-s;e._allClippedDrawRect.x=i,e._allClippedDrawRect.y=s,e._allClippedDrawRect.width=t,e._allClippedDrawRect.height=a}}}constructor(){this._currentMaskRenderTexture=null,this._currentFrameNo=0,this._renderTextureCount=0,this._clippingMaskBufferSize=256,this._clippingContextListForMask=[],this._clippingContextListForDraw=[],this._channelColors=[],this._tmpBoundsOnModel=new Rt,this._tmpMatrix=new p,this._tmpMatrixForMask=new p,this._tmpMatrixForDraw=new p;let t=new y;t.R=1,t.G=0,t.B=0,t.A=0,this._channelColors.push(t),t=new y,t.R=0,t.G=1,t.B=0,t.A=0,this._channelColors.push(t),t=new y,t.R=0,t.G=0,t.B=1,t.A=0,this._channelColors.push(t),t=new y,t.R=0,t.G=0,t.B=0,t.A=1,this._channelColors.push(t)}release(){var t;const e=this;for(let i=0;i0){this.setupLayoutBounds(e.isUsingHighPrecisionMask()?0:i),e.isUsingHighPrecisionMask()||(this.gl.viewport(0,0,this._clippingMaskBufferSize,this._clippingMaskBufferSize),this._currentMaskRenderTexture=this.getMaskRenderTexture()[0],e.preDraw(),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this._currentMaskRenderTexture)),this._clearedFrameBufferflags||(this._clearedFrameBufferflags=[]);for(let t=0;th?(this._tmpBoundsOnModel.expand(r.width*a,0),n=o.width/this._tmpBoundsOnModel.width):n=e/h,this._tmpBoundsOnModel.height*e>u?(this._tmpBoundsOnModel.expand(0,r.height*a),l=o.height/this._tmpBoundsOnModel.height):l=e/u}else this._tmpBoundsOnModel.setRect(r),this._tmpBoundsOnModel.expand(r.width*a,r.height*a),n=o.width/this._tmpBoundsOnModel.width,l=o.height/this._tmpBoundsOnModel.height;if(this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(-1,-1),this._tmpMatrix.scaleRelative(2,2),this._tmpMatrix.translateRelative(o.x,o.y),this._tmpMatrix.scaleRelative(n,l),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForMask.setMatrix(this._tmpMatrix.getArray()),this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(o.x,o.y),this._tmpMatrix.scaleRelative(n,l),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForDraw.setMatrix(this._tmpMatrix.getArray()),s._matrixForMask.setMatrix(this._tmpMatrixForMask.getArray()),s._matrixForDraw.setMatrix(this._tmpMatrixForDraw.getArray()),!e.isUsingHighPrecisionMask()){const i=s._clippingIdCount;for(let r=0;ri){e>i&&E("not supported mask count : {0}\n[Details] render texture count : {1}, mask count : {2}",e-i,this._renderTextureCount,e);for(let t=0;t=4?0:n+1;if(u(t[t.ShaderNames_SetupMask=0]="ShaderNames_SetupMask",t[t.ShaderNames_NormalPremultipliedAlpha=1]="ShaderNames_NormalPremultipliedAlpha",t[t.ShaderNames_NormalMaskedPremultipliedAlpha=2]="ShaderNames_NormalMaskedPremultipliedAlpha",t[t.ShaderNames_NomralMaskedInvertedPremultipliedAlpha=3]="ShaderNames_NomralMaskedInvertedPremultipliedAlpha",t[t.ShaderNames_AddPremultipliedAlpha=4]="ShaderNames_AddPremultipliedAlpha",t[t.ShaderNames_AddMaskedPremultipliedAlpha=5]="ShaderNames_AddMaskedPremultipliedAlpha",t[t.ShaderNames_AddMaskedPremultipliedAlphaInverted=6]="ShaderNames_AddMaskedPremultipliedAlphaInverted",t[t.ShaderNames_MultPremultipliedAlpha=7]="ShaderNames_MultPremultipliedAlpha",t[t.ShaderNames_MultMaskedPremultipliedAlpha=8]="ShaderNames_MultMaskedPremultipliedAlpha",t[t.ShaderNames_MultMaskedPremultipliedAlphaInverted=9]="ShaderNames_MultMaskedPremultipliedAlphaInverted",t))(jt||{});const Wt="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_myPos;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_clipMatrix * a_position; v_myPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",Ht="precision mediump float;varying vec2 v_texCoord;varying vec4 v_myPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;void main(){ float isInside = step(u_baseColor.x, v_myPos.x/v_myPos.w) * step(u_baseColor.y, v_myPos.y/v_myPos.w) * step(v_myPos.x/v_myPos.w, u_baseColor.z) * step(v_myPos.y/v_myPos.w, u_baseColor.w); gl_FragColor = u_channelFlag * texture2D(s_texture0, v_texCoord).a * isInside;}",Yt="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;uniform mat4 u_matrix;void main(){ gl_Position = u_matrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",qt="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform mat4 u_matrix;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_matrix * a_position; v_clipPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",$t="precision mediump float;varying vec2 v_texCoord;uniform vec4 u_baseColor;uniform sampler2D s_texture0;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 color = texColor * u_baseColor; gl_FragColor = vec4(color.rgb, color.a);}",Jt="precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;uniform sampler2D s_texture1;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 col_formask = texColor * u_baseColor; vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag; float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a; col_formask = col_formask * maskVal; gl_FragColor = col_formask;}",Zt="precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform sampler2D s_texture0;uniform sampler2D s_texture1;uniform vec4 u_channelFlag;uniform vec4 u_baseColor;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 col_formask = texColor * u_baseColor; vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag; float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a; col_formask = col_formask * (1.0 - maskVal); gl_FragColor = col_formask;}";class Qt extends _{constructor(){super(),this._clippingContextBufferForMask=null,this._clippingContextBufferForDraw=null,this._rendererProfile=new Xt,this.firstDraw=!0,this._textures={},this._sortedDrawableIndexList=[],this._bufferData={vertex:null,uv:null,index:null}}initialize(t,e=1){t.isUsingMasking()&&(this._clippingManager=new Vt,this._clippingManager.initialize(t,t.getDrawableCount(),t.getDrawableMasks(),t.getDrawableMaskCounts(),e));for(let i=t.getDrawableCount()-1;i>=0;i--)this._sortedDrawableIndexList[i]=0;super.initialize(t)}bindTexture(t,e){this._textures[t]=e}getBindedTextures(){return this._textures}setClippingMaskBufferSize(t){if(!this._model.isUsingMasking())return;const e=this._clippingManager.getRenderTextureCount();this._clippingManager.release(),this._clippingManager=new Vt,this._clippingManager.setClippingMaskBufferSize(t),this._clippingManager.initialize(this.getModel(),this.getModel().getDrawableCount(),this.getModel().getDrawableMasks(),this.getModel().getDrawableMaskCounts(),e)}getClippingMaskBufferSize(){return this._model.isUsingMasking()?this._clippingManager.getClippingMaskBufferSize():-1}getRenderTextureCount(){return this._model.isUsingMasking()?this._clippingManager.getRenderTextureCount():-1}release(){var t,e,i;const s=this;this._clippingManager.release(),s._clippingManager=void 0,null==(t=this.gl)||t.deleteBuffer(this._bufferData.vertex),this._bufferData.vertex=null,null==(e=this.gl)||e.deleteBuffer(this._bufferData.uv),this._bufferData.uv=null,null==(i=this.gl)||i.deleteBuffer(this._bufferData.index),this._bufferData.index=null,s._bufferData=void 0,s._textures=void 0}doDrawModel(){if(null==this.gl)return void E("'gl' is null. WebGLRenderingContext is required.\nPlease call 'CubimRenderer_WebGL.startUp' function.");null!=this._clippingManager&&(this.preDraw(),this._clippingManager.setupClippingContext(this.getModel(),this)),this.preDraw();const t=this.getModel().getDrawableCount(),e=this.getModel().getDrawableRenderOrders();for(let i=0;i0&&this._extension)for(const t of Object.entries(this._textures))this.gl.bindTexture(this.gl.TEXTURE_2D,t),this.gl.texParameterf(this.gl.TEXTURE_2D,this._extension.TEXTURE_MAX_ANISOTROPY_EXT,this.getAnisotropy())}setClippingContextBufferForMask(t){this._clippingContextBufferForMask=t}getClippingContextBufferForMask(){return this._clippingContextBufferForMask}setClippingContextBufferForDraw(t){this._clippingContextBufferForDraw=t}getClippingContextBufferForDraw(){return this._clippingContextBufferForDraw}startUp(t){this.gl=t,this._clippingManager&&this._clippingManager.setGL(t),zt.getInstance().setGl(t),this._rendererProfile.setGl(t),this._extension=this.gl.getExtension("EXT_texture_filter_anisotropic")||this.gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this.gl.getExtension("MOZ_EXT_texture_filter_anisotropic")}}_.staticRelease=()=>{Qt.doStaticRelease()};class Kt{constructor(t){this.groups=t.Groups,this.hitAreas=t.HitAreas,this.layout=t.Layout,this.moc=t.FileReferences.Moc,this.expressions=t.FileReferences.Expressions,this.motions=t.FileReferences.Motions,this.textures=t.FileReferences.Textures,this.physics=t.FileReferences.Physics,this.pose=t.FileReferences.Pose}getEyeBlinkParameters(){var t,e;return null==(e=null==(t=this.groups)?void 0:t.find((t=>"EyeBlink"===t.Name)))?void 0:e.Ids}getLipSyncParameters(){var t,e;return null==(e=null==(t=this.groups)?void 0:t.find((t=>"LipSync"===t.Name)))?void 0:e.Ids}}const te="ParamAngleX",ee="ParamAngleY",ie="ParamAngleZ",se="ParamEyeBallX",re="ParamEyeBallY",oe="ParamMouthForm",ae="ParamBodyAngleX",ne="ParamBreath";var le;t.config=void 0,(le=t.config||(t.config={})).LOG_LEVEL_VERBOSE=0,le.LOG_LEVEL_WARNING=1,le.LOG_LEVEL_ERROR=2,le.LOG_LEVEL_NONE=999,le.logLevel=le.LOG_LEVEL_WARNING,le.sound=!0,le.motionSync=!0,le.motionFadingDuration=500,le.idleMotionFadingDuration=2e3,le.expressionFadingDuration=500,le.preserveExpressionOnMotion=!0,le.cubism4=t.CubismConfig;const he={log(e,...i){t.config.logLevel<=t.config.LOG_LEVEL_VERBOSE&&console.log(`[${e}]`,...i)},warn(e,...i){t.config.logLevel<=t.config.LOG_LEVEL_WARNING&&console.warn(`[${e}]`,...i)},error(e,...i){t.config.logLevel<=t.config.LOG_LEVEL_ERROR&&console.error(`[${e}]`,...i)}};function ue(t,e,i){return ti?i:t}function de(t,e){e.forEach((e=>{Object.getOwnPropertyNames(e.prototype).forEach((i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i))}))}))}function ce(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 ge(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}class me extends e.EventEmitter{constructor(t,e){super(),this.expressions=[],this.reserveExpressionIndex=-1,this.destroyed=!1,this.settings=t,this.tag=`ExpressionManager(${t.name})`}init(){this.defaultExpression=this.createExpression({},void 0),this.currentExpression=this.defaultExpression,this.stopAllExpressions()}loadExpression(t){return __async(this,null,(function*(){if(!this.definitions[t])return void he.warn(this.tag,`Undefined expression at [${t}]`);if(null===this.expressions[t])return void he.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 __async(this,null,(function*(){if(this.definitions.length){const t=[];for(let e=0;e-1&&tl&&(o*=l/n,a*=l/n),this.vx+=o,this.vy+=a;const h=Math.sqrt(__pow(this.vx,2)+__pow(this.vy,2)),u=.5*(Math.sqrt(__pow(l,2)+8*l*s)-l);h>u&&(this.vx*=u/h,this.vy*=u/h),this.x+=this.vx,this.y+=this.vy}}class _e{constructor(t){this.json=t;let e=t.url;if("string"!=typeof e)throw new TypeError("The `url` field in settings JSON must be defined as a string.");this.url=e,this.name=ce(this.url)}resolveURL(t){return e.url.resolve(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(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 fe=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(fe||{});class ye{constructor(){this.debug=!1,this.currentPriority=0,this.reservePriority=0}reserve(t,e,i){if(i<=0)return he.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(t===this.currentGroup&&e===this.currentIndex)return he.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 he.log(this.tag,"Motion is already reserved.",this.dump(t,e)),!1;if(1===i){if(0!==this.currentPriority)return he.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,e)),!1;if(void 0!==this.reservedIdleGroup)return he.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 he.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 he.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 he.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 he.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!t.config.preserveExpressionOnMotion&&this.currentPriority>1}dump(t,e){if(this.debug){return`\n group = "${t}", index = ${e}\n`+["currentPriority","reservePriority","currentGroup","currentIndex","reservedGroup","reservedIndex","reservedIdleGroup","reservedIdleIndex"].map((t=>"["+t+"] "+this[t])).join("\n")}return""}}class xe{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,i){const s=new Audio(t);return s.volume=this._volume,s.preload="auto",s.autoplay=!0,s.crossOrigin="anonymous",s.addEventListener("ended",(()=>{this.dispose(s),null==e||e()})),s.addEventListener("error",(e=>{this.dispose(s),he.warn("SoundManager",`Error occurred on "${t}"`,e.error),null==i||i(e.error)})),this.audios.push(s),s}static play(t){return new Promise(((e,i)=>{var s;null==(s=t.play())||s.catch((e=>{t.dispatchEvent(new ErrorEvent("error",{error:e})),i(e)})),t.readyState===t.HAVE_ENOUGH_DATA?e():t.addEventListener("canplaythrough",e)}))}static addContext(t){const e=new AudioContext;return this.contexts.push(e),e}static addAnalyzer(t,e){const i=e.createMediaElementSource(t),s=e.createAnalyser();return s.fftSize=256,s.minDecibels=-90,s.maxDecibels=-10,s.smoothingTimeConstant=.85,i.connect(s),s.connect(e.destination),this.analysers.push(s),s}static analyze(t){if(null!=t){let e=new Float32Array(t.fftSize),i=0;t.getFloatTimeDomainData(e);for(const t of e)i+=t*t;return parseFloat(Math.sqrt(i/e.length*20).toFixed(1))}return parseFloat(Math.random().toFixed(1))}static dispose(t){t.pause(),t.removeAttribute("src"),ge(this.audios,t)}static destroy(){for(let t=this.contexts.length-1;t>=0;t--)this.contexts[t].close();for(let t=this.audios.length-1;t>=0;t--)this.dispose(this.audios[t])}}xe.audios=[],xe.analysers=[],xe.contexts=[],xe._volume=.9;var Ce=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(Ce||{});class Me extends e.EventEmitter{constructor(t,e){super(),this.motionGroups={},this.state=new ye,this.playing=!1,this.destroyed=!1,this.settings=t,this.tag=`MotionManager(${t.name})`,this.state.tag=this.tag}init(t){(null==t?void 0:t.idleMotionGroup)&&(this.groups.idle=t.idleMotionGroup),this.setupMotions(t),this.stopAllMotions()}setupMotions(t){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)if(this.definitions[i])for(let t=0;t{r&&s&&c.expressionManager&&c.expressionManager.resetExpression(),c.currentAudio=void 0}),(()=>{r&&s&&c.expressionManager&&c.expressionManager.resetExpression(),c.currentAudio=void 0})),this.currentAudio=o;let t=1;void 0!==i&&(t=i),xe.volume=t,n=xe.addContext(this.currentAudio),this.currentContext=n,a=xe.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=a}catch(g){he.warn(this.tag,"Failed to create audio",l,g)}if(o){const e=xe.play(o).catch((t=>he.warn(this.tag,"Failed to play audio",o.src,t)));t.config.motionSync&&(yield e)}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),s&&this.expressionManager&&this.expressionManager.setExpression(s),this.playing=!0,!0}))}startMotion(e,i){return __async(this,arguments,(function*(e,i,s=fe.NORMAL,{sound:r,volume:o=1,expression:a,resetExpression:n=!0}={}){var l;if(this.currentAudio&&!this.currentAudio.ended)return!1;if(!this.state.reserve(e,i,s))return!1;const h=null==(l=this.definitions[e])?void 0:l[i];if(!h)return!1;let u,d,c;if(this.currentAudio&&xe.dispose(this.currentAudio),t.config.sound){const t=r&&r.startsWith("data:audio/wav;base64");if(r&&!t){var g=document.createElement("a");g.href=r,r=g.href}const e=r&&(r.startsWith("http")||r.startsWith("blob")),i=this.getSoundFile(h);let s=i;i&&(s=this.settings.resolveURL(i)+"?cache-buster="+(new Date).getTime()),(e||t)&&(s=r);const l=this;if(s)try{u=xe.add(s,(()=>{n&&a&&l.expressionManager&&l.expressionManager.resetExpression(),l.currentAudio=void 0}),(()=>{n&&a&&l.expressionManager&&l.expressionManager.resetExpression(),l.currentAudio=void 0})),this.currentAudio=u;let t=1;void 0!==o&&(t=o),xe.volume=t,c=xe.addContext(this.currentAudio),this.currentContext=c,d=xe.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=d}catch(p){he.warn(this.tag,"Failed to create audio",i,p)}}const m=yield this.loadMotion(e,i);if(u){s=3;const e=xe.play(u).catch((t=>he.warn(this.tag,"Failed to play audio",u.src,t)));t.config.motionSync&&(yield e)}return this.state.start(m,e,i,s)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),he.log(this.tag,"Start motion:",this.getMotionName(h)),this.emit("motionStart",e,i,u),a&&this.expressionManager&&this.expressionManager.setExpression(a),this.playing=!0,this._startMotion(m),!0):(u&&(xe.dispose(u),this.currentAudio=void 0),!1)}))}startRandomMotion(t,e){return __async(this,arguments,(function*(t,e,{sound:i,volume:s=1,expression:r,resetExpression:o=!0}={}){const a=this.definitions[t];if(null==a?void 0:a.length){const n=[];for(let e=0;et.index>=0));for(const e of t)this.hitAreas[e.name]=e}hitTest(t,e){return Object.keys(this.hitAreas).filter((i=>this.isHit(i,t,e)))}isHit(t,e,i){if(!this.hitAreas[t])return!1;const s=this.hitAreas[t].index,r=this.getDrawableBounds(s,ve);return r.x<=e&&e<=r.x+r.width&&r.y<=i&&i<=r.y+r.height}getDrawableBounds(t,e){const i=this.getDrawableVertices(t);let s=i[0],r=i[0],o=i[1],a=i[1];for(let n=0;n{200!==o.status&&0!==o.status||!o.response?o.onerror():s(o.response)},o.onerror=()=>{he.warn("XHRLoader",`Failed to load resource as ${o.responseType} (Status ${o.status}): ${e}`),r(new be("Network error.",e,o.status))},o.onabort=()=>r(new be("Aborted.",e,o.status,!0)),o.onloadend=()=>{var e;Se.allXhrSet.delete(o),t&&(null==(e=Se.xhrMap.get(t))||e.delete(o))},o}static cancelXHRs(){var t;null==(t=Se.xhrMap.get(this))||t.forEach((t=>{t.abort(),Se.allXhrSet.delete(t)})),Se.xhrMap.delete(this)}static release(){Se.allXhrSet.forEach((t=>t.abort())),Se.allXhrSet.clear(),Se.xhrMap=new WeakMap}};let we=Se;function Te(t,e){let i=-1;return function s(r,o){if(o)return Promise.reject(o);if(r<=i)return Promise.reject(new Error("next() called multiple times"));i=r;const a=t[r];if(!a)return Promise.resolve();try{return Promise.resolve(a(e,s.bind(null,r+1)))}catch(n){return Promise.reject(n)}}(0)}we.xhrMap=new WeakMap,we.allXhrSet=new Set,we.loader=(t,e)=>new Promise(((e,i)=>{Se.createXHR(t.target,t.settings?t.settings.resolveURL(t.url):t.url,t.type,(i=>{t.result=i,e()}),i).send()}));class Ie{static load(t){return Te(this.middlewares,t).then((()=>t.result))}}Ie.middlewares=[we.loader];const Ee="Live2DFactory",Le=(t,e)=>__async(this,null,(function*(){if("string"==typeof t.source){const e=yield Ie.load({url:t.source,type:"json",target:t.live2dModel});e.url=t.source,t.source=e,t.live2dModel.emit("settingsJSONLoaded",e)}return e()})),Ae=(t,e)=>__async(this,null,(function*(){if(t.source instanceof _e)return t.settings=t.source,e();if("object"==typeof t.source){const i=ke.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.")})),Fe=(t,e)=>{if(t.settings){const i=ke.findRuntime(t.settings);if(i)return i.ready().then(e)}return e()},De=(t,e)=>__async(this,null,(function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=ke.findRuntime(e);if(s){const r=[];e.pose&&r.push(Ie.load({settings:e,url:e.pose,type:"json",target:i}).then((e=>{i.pose=s.createPose(i.coreModel,e),t.live2dModel.emit("poseLoaded",i.pose)})).catch((e=>{t.live2dModel.emit("poseLoadError",e),he.warn(Ee,"Failed to load pose.",e)}))),e.physics&&r.push(Ie.load({settings:e,url:e.physics,type:"json",target:i}).then((e=>{i.physics=s.createPhysics(i.coreModel,e),t.live2dModel.emit("physicsLoaded",i.physics)})).catch((e=>{t.live2dModel.emit("physicsLoadError",e),he.warn(Ee,"Failed to load physics.",e)}))),r.length&&(yield Promise.all(r))}}})),Be=(t,e)=>__async(this,null,(function*(){if(!t.settings)throw new TypeError("Missing settings.");{const i=t.live2dModel,r=t.settings.textures.map((e=>function(t,e={}){const i={resourceOptions:{crossorigin:e.crossOrigin}};if(s.Texture.fromURL)return s.Texture.fromURL(t,i).catch((t=>{if(t instanceof Error)throw t;const e=new Error("Texture loading error");throw e.event=t,e}));i.resourceOptions.autoLoad=!1;const r=s.Texture.from(t,i);if(r.baseTexture.valid)return Promise.resolve(r);const o=r.baseTexture.resource;return null!=o._live2d_load||(o._live2d_load=new Promise(((t,e)=>{const i=t=>{o.source.removeEventListener("error",i);const s=new Error("Texture loading error");s.event=t,e(s)};o.source.addEventListener("error",i),o.load().then((()=>t(r))).catch(i)}))),o._live2d_load}(t.settings.resolveURL(e),{crossOrigin:t.options.crossOrigin})));if(yield e(),!t.internalModel)throw new TypeError("Missing internal model.");i.internalModel=t.internalModel,i.emit("modelLoaded",t.internalModel),i.textures=yield Promise.all(r),i.emit("textureLoaded",i.textures)}})),Re=(t,e)=>__async(this,null,(function*(){const i=t.settings;if(i instanceof _e){const s=ke.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield Ie.load({settings:i,url:i.moc,type:"arraybuffer",target:t.live2dModel});if(!s.isValidMoc(r))throw new Error("Invalid moc data");const o=s.createCoreModel(r);return t.internalModel=s.createInternalModel(o,i,t.options),e()}throw new TypeError("Missing settings.")})),Oe=class{static registerRuntime(t){Oe.runtimes.push(t),Oe.runtimes.sort(((t,e)=>e.version-t.version))}static findRuntime(t){for(const e of Oe.runtimes)if(e.test(t))return e}static setupLive2DModel(t,e,i){return __async(this,null,(function*(){const s=new Promise((e=>t.once("textureLoaded",e))),r=new Promise((e=>t.once("modelLoaded",e))),o=Promise.all([s,r]).then((()=>t.emit("ready")));yield Te(Oe.live2DModelMiddlewares,{live2dModel:t,source:e,options:i||{}}),yield o,t.emit("load")}))}static loadMotion(t,e,i){var s;const r=s=>t.emit("motionLoadError",e,i,s);try{const o=null==(s=t.definitions[e])?void 0:s[i];if(!o)return Promise.resolve(void 0);t.listeners("destroy").includes(Oe.releaseTasks)||t.once("destroy",Oe.releaseTasks);let a=Oe.motionTasksMap.get(t);a||(a={},Oe.motionTasksMap.set(t,a));let n=a[e];n||(n=[],a[e]=n);const l=t.getMotionFile(o);return null!=n[i]||(n[i]=Ie.load({url:l,settings:t.settings,type:t.motionDataType,target:t}).then((s=>{var r;const a=null==(r=Oe.motionTasksMap.get(t))?void 0:r[e];a&&delete a[i];const n=t.createMotion(s,e,o);return t.emit("motionLoaded",e,i,n),n})).catch((e=>{he.warn(t.tag,`Failed to load motion: ${l}\n`,e),r(e)}))),n[i]}catch(o){he.warn(t.tag,`Failed to load motion at "${e}"[${i}]\n`,o),r(o)}return Promise.resolve(void 0)}static loadExpression(t,e){const i=i=>t.emit("expressionLoadError",e,i);try{const s=t.definitions[e];if(!s)return Promise.resolve(void 0);t.listeners("destroy").includes(Oe.releaseTasks)||t.once("destroy",Oe.releaseTasks);let r=Oe.expressionTasksMap.get(t);r||(r=[],Oe.expressionTasksMap.set(t,r));const o=t.getExpressionFile(s);return null!=r[e]||(r[e]=Ie.load({url:o,settings:t.settings,type:"json",target:t}).then((i=>{const r=Oe.expressionTasksMap.get(t);r&&delete r[e];const o=t.createExpression(i,s);return t.emit("expressionLoaded",e,o),o})).catch((e=>{he.warn(t.tag,`Failed to load expression: ${o}\n`,e),i(e)}))),r[e]}catch(s){he.warn(t.tag,`Failed to load expression at [${e}]\n`,s),i(s)}return Promise.resolve(void 0)}static releaseTasks(){this instanceof Me?Oe.motionTasksMap.delete(this):Oe.expressionTasksMap.delete(this)}};let ke=Oe;ke.runtimes=[],ke.urlToJSON=Le,ke.jsonToSettings=Ae,ke.waitUntilReady=Fe,ke.setupOptionals=De,ke.setupEssentials=Be,ke.createInternalModel=Re,ke.live2DModelMiddlewares=[Le,Ae,Fe,De,Be,Re],ke.motionTasksMap=new WeakMap,ke.expressionTasksMap=new WeakMap,Me.prototype._loadMotion=function(t,e){return ke.loadMotion(this,t,e)},me.prototype._loadExpression=function(t){return ke.loadExpression(this,t)};class Ue{constructor(){this._autoInteract=!1}get autoInteract(){return this._autoInteract}set autoInteract(t){t!==this._autoInteract&&(t?this.on("pointertap",Ve,this):this.off("pointertap",Ve,this),this._autoInteract=t)}registerInteraction(t){t!==this.interactionManager&&(this.unregisterInteraction(),this._autoInteract&&t&&(this.interactionManager=t,t.on("pointermove",Ne,this)))}unregisterInteraction(){var t;this.interactionManager&&(null==(t=this.interactionManager)||t.off("pointermove",Ne,this),this.interactionManager=void 0)}}function Ve(t){this.tap(t.data.global.x,t.data.global.y)}function Ne(t){this.focus(t.data.global.x,t.data.global.y)}class Ge extends i.Transform{}const Xe=new i.Point,ze=new i.Matrix;let je;class We extends r.Container{constructor(t){super(),this.tag="Live2DModel(uninitialized)",this.textures=[],this.transform=new Ge,this.anchor=new i.ObservablePoint(this.onAnchorChange,this,0,0),this.glContextID=-1,this.elapsedTime=performance.now(),this.deltaTime=0,this._autoUpdate=!1,this.once("modelLoaded",(()=>this.init(t)))}static from(t,e){const i=new this(e);return ke.setupLive2DModel(i,t,e).then((()=>i))}static fromSync(t,e){const i=new this(e);return ke.setupLive2DModel(i,t,e).then(null==e?void 0:e.onLoad).catch(null==e?void 0:e.onError),i}static registerTicker(t){je=t}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){var e;je||(je=null==(e=window.PIXI)?void 0:e.Ticker),t?this._destroyed||(je?(je.shared.add(this.onTickerUpdate,this),this._autoUpdate=!0):he.warn(this.tag,"No Ticker registered, please call Live2DModel.registerTicker(Ticker).")):(null==je||je.shared.remove(this.onTickerUpdate,this),this._autoUpdate=!1)}init(t){this.tag=`Live2DModel(${this.internalModel.settings.name})`;const e=Object.assign({autoUpdate:!0,autoInteract:!0},t);e.autoInteract&&(this.interactive=!0),this.autoInteract=e.autoInteract,this.autoUpdate=e.autoUpdate}onAnchorChange(){this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(t,e,{priority:i=2,sound:s,volume:r=1,expression:o,resetExpression:a=!0}={}){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i,{sound:s,volume:r,expression:o,resetExpression:a}):this.internalModel.motionManager.startMotion(t,e,i,{sound:s,volume:r,expression:o,resetExpression:a})}resetMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(t,{volume:e=1,expression:i,resetExpression:s=!0}={}){return this.internalModel.motionManager.speakUp(t,{volume:e,expression:i,resetExpression:s})}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){Xe.x=t,Xe.y=e,this.toModelPosition(Xe,Xe,!0);let s=Xe.x/this.internalModel.originalWidth*2-1,r=Xe.y/this.internalModel.originalHeight*2-1,o=Math.atan2(r,s);this.internalModel.focusController.focus(Math.cos(o),-Math.sin(o),i)}tap(t,e){const i=this.hitTest(t,e);i.length&&(he.log(this.tag,"Hit",i),this.emit("hit",i))}hitTest(t,e){return Xe.x=t,Xe.y=e,this.toModelPosition(Xe,Xe),this.internalModel.hitTest(Xe.x,Xe.y)}toModelPosition(t,e=t.clone(),i){return i||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.transform.worldTransform.applyInverse(t,e),this.internalModel.localTransform.applyInverse(e,e),e}containsPoint(t){return this.getBounds(!0).contains(t.x,t.y)}_calculateBounds(){this._bounds.addFrame(this.transform,0,0,this.internalModel.width,this.internalModel.height)}onTickerUpdate(){this.update(je.shared.deltaMS)}update(t){this.deltaTime+=t,this.elapsedTime+=t}_render(t){this.registerInteraction(t.plugins.interaction),t.batch.reset(),t.geometry.reset(),t.shader.reset(),t.state.reset();let e=!1;this.glContextID!==t.CONTEXT_UID&&(this.glContextID=t.CONTEXT_UID,this.internalModel.updateWebGLContext(t.gl,this.glContextID),e=!0);for(let r=0;re.destroy(t.baseTexture))),this.internalModel.destroy(),super.destroy(t)}}de(We,[Ue]);const He=class{static resolveURL(t,e){var i;const s=null==(i=He.filesMap[t])?void 0:i[e];if(void 0===s)throw new Error("Cannot find this file from uploaded files: "+e);return s}static upload(t,i){return __async(this,null,(function*(){const s={};for(const r of i.getDefinedFiles()){const o=decodeURI(e.url.resolve(i.url,r)),a=t.find((t=>t.webkitRelativePath===o));a&&(s[r]=URL.createObjectURL(a))}He.filesMap[i._objectURL]=s}))}static createSettings(t){return __async(this,null,(function*(){const e=t.find((t=>t.name.endsWith("model.json")||t.name.endsWith("model3.json")));if(!e)throw new TypeError("Settings file not found");const i=yield He.readText(e),s=JSON.parse(i);s.url=e.webkitRelativePath;const r=ke.findRuntime(s);if(!r)throw new Error("Unknown settings JSON");const o=r.createModelSettings(s);return o._objectURL=URL.createObjectURL(e),o}))}static readText(t){return __async(this,null,(function*(){return new Promise(((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")}))}))}};let Ye=He;Ye.filesMap={},Ye.factory=(t,e)=>__async(this,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 He.createSettings(e);i.validateFiles(e.map((t=>encodeURI(t.webkitRelativePath)))),yield He.upload(e,i),i.resolveURL=function(t){return He.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),He.filesMap[t])for(const e of Object.values(He.filesMap[t]))URL.revokeObjectURL(e);delete He.filesMap[t]}))}))}return e()})),ke.live2DModelMiddlewares.unshift(Ye.factory);const qe=class{static unzip(t,i){return __async(this,null,(function*(){const s=yield qe.getFilePaths(t),r=[];for(const t of i.getDefinedFiles()){const o=decodeURI(e.url.resolve(i.url,t));s.includes(o)&&r.push(o)}const o=yield qe.getFiles(t,r);for(let t=0;tt.endsWith("model.json")||t.endsWith("model3.json")));if(!e)throw new Error("Settings file not found");const i=yield qe.readText(t,e);if(!i)throw new Error("Empty settings file: "+e);const s=JSON.parse(i);s.url=e;const r=ke.findRuntime(s);if(!r)throw new Error("Unknown settings JSON");return r.createModelSettings(s)}))}static zipReader(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static getFilePaths(t){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static getFiles(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static readText(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static releaseReader(t){}};let $e=qe;if($e.ZIP_PROTOCOL="zip://",$e.uid=0,$e.factory=(t,e)=>__async(this,null,(function*(){const i=t.source;let s,r,o;if("string"==typeof i&&(i.endsWith(".zip")||i.startsWith(qe.ZIP_PROTOCOL))?(s=i.startsWith(qe.ZIP_PROTOCOL)?i.slice(qe.ZIP_PROTOCOL.length):i,r=yield Ie.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),o=i.settings),r){if(!r.size)throw new Error("Empty zip file");const e=yield qe.zipReader(r,s);o||(o=yield qe.createSettings(e)),o._objectURL=qe.ZIP_PROTOCOL+qe.uid+"/"+o.url;const i=yield qe.unzip(e,o);i.settings=o,t.source=i,s.startsWith("blob:")&&t.live2dModel.once("modelLoaded",(t=>{t.once("destroy",(function(){URL.revokeObjectURL(s)}))})),qe.releaseReader(e)}return e()})),ke.live2DModelMiddlewares.unshift($e.factory),!window.Live2DCubismCore)throw new Error("Could not find Cubism 4 runtime. This plugin requires live2dcubismcore.js to be loaded.");class Je extends me{constructor(t,e){var i;super(t,e),this.queueManager=new nt,this.definitions=null!=(i=t.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 V.create(t)}_setExpression(t){return this.queueManager.startMotion(t,!1,performance.now())}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.doUpdateMotion(t,e)}}class Ze extends _e{constructor(t){if(super(t),!Ze.isValidJSON(t))throw new TypeError("Invalid JSON.");Object.assign(this,new Kt(t))}static isValidJSON(t){var e;return!!(null==t?void 0:t.FileReferences)&&"string"==typeof t.FileReferences.Moc&&(null==(e=t.FileReferences.Textures)?void 0:e.length)>0&&t.FileReferences.Textures.every((t=>"string"==typeof t))}replaceFiles(t){if(super.replaceFiles(t),this.motions)for(const[e,i]of Object.entries(this.motions))for(let s=0;s{this.emit("motion:"+e)}))}isFinished(){return this.queueManager.isFinished()}_startMotion(t,e){return t.setFinishedMotionHandler(e),this.queueManager.stopAllMotions(),this.queueManager.startMotion(t,!1,performance.now())}_stopAllMotions(){this.queueManager.stopAllMotions()}createMotion(e,i,s){const r=ot.create(e),o=new $(e),a=(i===this.groups.idle?t.config.idleMotionFadingDuration:t.config.motionFadingDuration)/1e3;return void 0===o.getMotionFadeInTime()&&r.setFadeInTime(s.FadeInTime>0?s.FadeInTime:a),void 0===o.getMotionFadeOutTime()&&r.setFadeOutTime(s.FadeOutTime>0?s.FadeOutTime:a),r.setEffectIds(this.eyeBlinkIds,this.lipSyncIds),r}getMotionFile(t){return t.File}getMotionName(t){return t.File}getSoundFile(t){return t.Sound}updateParameters(t,e){return this.queueManager.doUpdateMotion(t,e)}destroy(){super.destroy(),this.queueManager.release(),this.queueManager=void 0}}const Ke=new p;class ti extends Pe{constructor(t,e,s){super(),this.lipSync=!0,this.breath=o.create(),this.renderer=new Qt,this.idParamAngleX=te,this.idParamAngleY=ee,this.idParamAngleZ=ie,this.idParamEyeBallX=se,this.idParamEyeBallY=re,this.idParamBodyAngleX=ae,this.idParamBreath=ne,this.idParamMouthForm=oe,this.pixelsPerUnit=1,this.centeringTransform=new i.Matrix,this.coreModel=t,this.settings=e,this.motionManager=new Qe(e,s),this.init()}init(){var t;super.init(),(null==(t=this.settings.getEyeBlinkParameters())?void 0:t.length)>0&&(this.eyeBlink=l.create(this.settings)),this.breath.setParameters([new a(this.idParamAngleX,0,15,6.5345,.5),new a(this.idParamAngleY,0,8,3.5345,.5),new a(this.idParamAngleZ,0,10,5.5345,.5),new a(this.idParamBodyAngleX,0,4,15.5345,.5),new a(this.idParamBreath,0,.5,3.2345,.5)]),this.renderer.initialize(this.coreModel),this.renderer.setIsPremultipliedAlpha(!0)}getSize(){return[this.coreModel.getModel().canvasinfo.CanvasWidth,this.coreModel.getModel().canvasinfo.CanvasHeight]}getLayout(){const t={};if(this.settings.layout)for(const e of Object.keys(this.settings.layout)){t[e.charAt(0).toLowerCase()+e.slice(1)]=this.settings.layout[e]}return t}setupLayout(){super.setupLayout(),this.pixelsPerUnit=this.coreModel.getModel().canvasinfo.PixelsPerUnit,this.centeringTransform.scale(this.pixelsPerUnit,this.pixelsPerUnit).translate(this.originalWidth/2,this.originalHeight/2)}updateWebGLContext(t,e){this.renderer.firstDraw=!0,this.renderer._bufferData={vertex:null,uv:null,index:null},this.renderer.startUp(t),this.renderer._clippingManager._currentFrameNo=e,this.renderer._clippingManager._maskTexture=void 0,zt.getInstance()._shaderSets=[]}bindTexture(t,e){this.renderer.bindTexture(t,e)}getHitAreaDefs(){var t,e;return null!=(e=null==(t=this.settings.hitAreas)?void 0:t.map((t=>({id:t.Id,name:t.Name,index:this.coreModel.getDrawableIndex(t.Id)}))))?e:[]}getDrawableIDs(){return this.coreModel.getDrawableIds()}getDrawableIndex(t){return this.coreModel.getDrawableIndex(t)}getDrawableVertices(t){if("string"==typeof t&&-1===(t=this.coreModel.getDrawableIndex(t)))throw new TypeError("Unable to find drawable ID: "+t);const e=this.coreModel.getDrawableVertices(t).slice();for(let i=0;i0&&(e=.4),t=ue(t*1.2,e,1);for(let i=0;i{!function i(){try{ri(),t()}catch(s){if(ii--,ii<0){const t=new Error("Failed to start up Cubism 4 framework.");return t.cause=s,void e(t)}he.log("Cubism4","Startup failed, retrying 10ms later..."),setTimeout(i,10)}}()}))),ei)}function ri(t){t=Object.assign({logFunction:console.log,loggingLevel:b.LogLevel_Verbose},t),P.startUp(t),P.initialize()}function oi(){var t;null==(t=this.__moc)||t.release()}ke.registerRuntime({version:4,ready:si,test:t=>t instanceof Ze||Ze.isValidJSON(t),isValidMoc(t){if(t.byteLength<4)return!1;const e=new Int8Array(t,0,4);return"MOC3"===String.fromCharCode(...e)},createModelSettings:t=>new Ze(t),createCoreModel(t,e){const i=R.create(t,!!(null==e?void 0:e.checkMocConsistency));try{const t=i.createModel();return t.__moc=i,t}catch(s){try{i.release()}catch(r){}throw s}},createInternalModel(t,e,i){const s=new ti(t,e,i),r=t;return r.__moc&&(s.__moc=r.__moc,delete r.__moc,s.once("destroy",oi)),s},createPhysics:(t,e)=>yt.create(e),createPose:(t,e)=>u.create(e)}),t.ACubismMotion=U,t.BreathParameterData=a,t.CSM_ASSERT=S,t.Constant=v,t.Cubism4ExpressionManager=Je,t.Cubism4InternalModel=ti,t.Cubism4ModelSettings=Ze,t.Cubism4MotionManager=Qe,t.CubismBlendMode=f,t.CubismBreath=o,t.CubismClippingContext=Gt,t.CubismClippingManager_WebGL=Vt,t.CubismDebug=L,t.CubismExpressionMotion=V,t.CubismEyeBlink=l,t.CubismFramework=P,t.CubismLogDebug=w,t.CubismLogError=E,t.CubismLogInfo=T,t.CubismLogVerbose=function(t,...e){L.print(b.LogLevel_Verbose,"[CSM][V]"+t+"\n",e)},t.CubismLogWarning=I,t.CubismMath=m,t.CubismMatrix44=p,t.CubismMoc=R,t.CubismModel=B,t.CubismModelSettingsJson=Kt,t.CubismModelUserData=k,t.CubismModelUserDataJson=O,t.CubismMotion=ot,t.CubismMotionCurve=H,t.CubismMotionCurveTarget=X,t.CubismMotionData=q,t.CubismMotionEvent=Y,t.CubismMotionJson=$,t.CubismMotionManager=class extends nt{constructor(){super(),this._currentPriority=0,this._reservePriority=0}getCurrentPriority(){return this._currentPriority}getReservePriority(){return this._reservePriority}setReservePriority(t){this._reservePriority=t}startMotionPriority(t,e,i){return i==this._reservePriority&&(this._reservePriority=0),this._currentPriority=i,super.startMotion(t,e,this._userTimeSeconds)}updateMotion(t,e){this._userTimeSeconds+=e;const i=super.doUpdateMotion(t,this._userTimeSeconds);return this.isFinished()&&(this._currentPriority=0),i}reserveMotion(t){return!(t<=this._reservePriority||t<=this._currentPriority)&&(this._reservePriority=t,!0)}},t.CubismMotionPoint=j,t.CubismMotionQueueEntry=at,t.CubismMotionQueueManager=nt,t.CubismMotionSegment=W,t.CubismMotionSegmentType=z,t.CubismPhysics=yt,t.CubismPhysicsInput=gt,t.CubismPhysicsJson=_t,t.CubismPhysicsOutput=mt,t.CubismPhysicsParticle=dt,t.CubismPhysicsRig=pt,t.CubismPhysicsSource=ut,t.CubismPhysicsSubRig=ct,t.CubismPhysicsTargetType=ht,t.CubismPose=u,t.CubismRenderTextureResource=Nt,t.CubismRenderer=_,t.CubismRendererProfile_WebGL=Xt,t.CubismRenderer_WebGL=Qt,t.CubismShader_WebGL=zt,t.CubismTextureColor=y,t.CubismVector2=c,t.DrawableColorData=A,t.DrawableCullingData=D,t.EvaluationOptionFlag=J,t.ExpressionBlendType=G,t.ExpressionManager=me,t.EyeState=h,t.FileLoader=Ye,t.FocusController=pe,t.HitAreaBody="Body",t.HitAreaHead="Head",t.HitAreaPrefix="HitArea",t.InteractionMixin=Ue,t.InternalModel=Pe,t.InvalidMotionQueueEntryHandleValue=lt,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DFactory=ke,t.Live2DLoader=Ie,t.Live2DModel=We,t.Live2DTransform=Ge,t.LogLevel=b,t.ModelSettings=_e,t.MotionManager=Me,t.MotionPreloadStrategy=Ce,t.MotionPriority=fe,t.MotionState=ye,t.Options=xt,t.ParamAngleX=te,t.ParamAngleY=ee,t.ParamAngleZ=ie,t.ParamArmLA="ParamArmLA",t.ParamArmLB="ParamArmLB",t.ParamArmRA="ParamArmRA",t.ParamArmRB="ParamArmRB",t.ParamBaseX="ParamBaseX",t.ParamBaseY="ParamBaseY",t.ParamBodyAngleX=ae,t.ParamBodyAngleY="ParamBodyAngleY",t.ParamBodyAngleZ="ParamBodyAngleZ",t.ParamBreath=ne,t.ParamBrowLAngle="ParamBrowLAngle",t.ParamBrowLForm="ParamBrowLForm",t.ParamBrowLX="ParamBrowLX",t.ParamBrowLY="ParamBrowLY",t.ParamBrowRAngle="ParamBrowRAngle",t.ParamBrowRForm="ParamBrowRForm",t.ParamBrowRX="ParamBrowRX",t.ParamBrowRY="ParamBrowRY",t.ParamBustX="ParamBustX",t.ParamBustY="ParamBustY",t.ParamCheek="ParamCheek",t.ParamEyeBallForm="ParamEyeBallForm",t.ParamEyeBallX=se,t.ParamEyeBallY=re,t.ParamEyeLOpen="ParamEyeLOpen",t.ParamEyeLSmile="ParamEyeLSmile",t.ParamEyeROpen="ParamEyeROpen",t.ParamEyeRSmile="ParamEyeRSmile",t.ParamHairBack="ParamHairBack",t.ParamHairFluffy="ParamHairFluffy",t.ParamHairFront="ParamHairFront",t.ParamHairSide="ParamHairSide",t.ParamHandL="ParamHandL",t.ParamHandR="ParamHandR",t.ParamMouthForm=oe,t.ParamMouthOpenY="ParamMouthOpenY",t.ParamNONE="NONE:",t.ParamShoulderY="ParamShoulderY",t.PartColorData=F,t.PartData=d,t.PartsArmLPrefix="Parts01ArmL_",t.PartsArmPrefix="Parts01Arm_",t.PartsArmRPrefix="Parts01ArmR_",t.PartsIdCore="Parts01Core",t.PhysicsJsonEffectiveForces=class{constructor(){this.gravity=new c(0,0),this.wind=new c(0,0)}},t.PhysicsOutput=Ct,t.ShaderNames=jt,t.SoundManager=xe,t.VERSION="0.4.0",t.XHRLoader=we,t.ZipLoader=$e,t.applyMixins=de,t.clamp=ue,t.copyArray=function(t,e,i,s,r){const o=e[s];Array.isArray(o)&&(i[r]=o.filter((e=>null!==e&&typeof e===t)))},t.copyProperty=function(t,e,i,s,r){const o=e[s];null!==o&&typeof o===t&&(i[r]=o)},t.csmRect=Rt,t.cubism4Ready=si,t.folderName=ce,t.fragmentShaderSrcMaskInvertedPremultipliedAlpha=Zt,t.fragmentShaderSrcMaskPremultipliedAlpha=Jt,t.fragmentShaderSrcPremultipliedAlpha=$t,t.fragmentShaderSrcsetupMask=Ht,t.logger=he,t.rand=function(t,e){return Math.random()*(e-t)+t},t.remove=ge,t.startUpCubism4=ri,t.vertexShaderSrc=Yt,t.vertexShaderSrcMasked=qt,t.vertexShaderSrcSetupMask=Wt,Object.defineProperties(t,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})); diff --git a/dist/index.es.js b/dist/index.es.js index 277f0196..ca8efa37 100644 --- a/dist/index.es.js +++ b/dist/index.es.js @@ -582,8 +582,8 @@ class MotionManager extends EventEmitter { _loadMotion(group, index) { throw new Error("Not implemented."); } - speakUp(sound, volume, expression) { - return __async(this, null, function* () { + speakUp(_0) { + return __async(this, arguments, function* (sound, { volume = 1, expression, resetExpression = true } = {}) { if (!config.sound) { return false; } @@ -614,10 +614,10 @@ class MotionManager extends EventEmitter { if (file) { try { audio = SoundManager.add(file, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }); this.currentAudio = audio; @@ -651,7 +651,7 @@ class MotionManager extends EventEmitter { }); } startMotion(_0, _1) { - return __async(this, arguments, function* (group, index, priority = MotionPriority.NORMAL, sound, volume, expression) { + return __async(this, arguments, function* (group, index, priority = MotionPriority.NORMAL, { sound = void 0, volume = 1, expression = void 0, resetExpression = true } = {}) { var _a; if (this.currentAudio) { if (!this.currentAudio.ended) { @@ -691,10 +691,10 @@ class MotionManager extends EventEmitter { if (file) { try { audio = SoundManager.add(file, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }); this.currentAudio = audio; @@ -740,8 +740,8 @@ class MotionManager extends EventEmitter { return true; }); } - startRandomMotion(group, priority, sound, volume) { - return __async(this, null, function* () { + startRandomMotion(_0, _1) { + return __async(this, arguments, function* (group, priority, { sound = void 0, volume = 1, expression = void 0, resetExpression = true } = {}) { const groupDefs = this.definitions[group]; if (groupDefs == null ? void 0 : groupDefs.length) { const availableIndices = []; @@ -752,7 +752,12 @@ class MotionManager extends EventEmitter { } if (availableIndices.length) { const index = availableIndices[Math.floor(Math.random() * availableIndices.length)]; - return this.startMotion(group, index, priority, sound, volume); + return this.startMotion(group, index, priority, { + sound, + volume, + expression, + resetExpression + }); } } return false; @@ -1398,14 +1403,28 @@ class Live2DModel extends Container { onAnchorChange() { this.pivot.set(this.anchor.x * this.internalModel.width, this.anchor.y * this.internalModel.height); } - motion(group, index, priority, sound, volume, expression) { - return index === void 0 ? this.internalModel.motionManager.startRandomMotion(group, priority) : this.internalModel.motionManager.startMotion(group, index, priority, sound, volume, expression); + motion(group, index, { priority = 2, sound, volume = 1, expression, resetExpression = true } = {}) { + return index === void 0 ? this.internalModel.motionManager.startRandomMotion(group, priority, { + sound, + volume, + expression, + resetExpression + }) : this.internalModel.motionManager.startMotion(group, index, priority, { + sound, + volume, + expression, + resetExpression + }); } resetMotions() { return this.internalModel.motionManager.stopAllMotions(); } - speak(sound, volume, expression) { - return this.internalModel.motionManager.speakUp(sound, volume, expression); + speak(sound, { volume = 1, expression, resetExpression = true } = {}) { + return this.internalModel.motionManager.speakUp(sound, { + volume, + expression, + resetExpression + }); } stopSpeaking() { return this.internalModel.motionManager.stopSpeaking(); @@ -1790,6 +1809,7 @@ class Cubism2MotionManager extends MotionManager { this.queueManager = new MotionQueueManager(); this.definitions = this.settings.motions; this.init(options); + this.lipSyncIds = ["PARAM_MOUTH_OPEN_Y"]; } init(options) { super.init(options); @@ -1903,6 +1923,7 @@ class Cubism2InternalModel extends InternalModel { constructor(coreModel, settings, options) { super(); this.textureFlipY = true; + this.lipSync = true; this.drawDataCount = 0; this.disableCulling = false; this.coreModel = coreModel; @@ -1916,6 +1937,7 @@ class Cubism2InternalModel extends InternalModel { this.angleZParamIndex = coreModel.getParamIndex("PARAM_ANGLE_Z"); this.bodyAngleXParamIndex = coreModel.getParamIndex("PARAM_BODY_ANGLE_X"); this.breathParamIndex = coreModel.getParamIndex("PARAM_BREATH"); + this.mouthFormIndex = coreModel.getParamIndex("PARAM_MOUTH_FORM"); this.init(); } init() { @@ -2024,6 +2046,19 @@ class Cubism2InternalModel extends InternalModel { } this.updateFocus(); this.updateNaturalMovements(dt, now); + if (this.lipSync && this.motionManager.currentAudio) { + let value = this.motionManager.mouthSync(); + let min_ = 0; + let max_ = 1; + let weight = 1.2; + if (value > 0) { + min_ = 0.4; + } + value = clamp(value * weight, min_, max_); + for (let i = 0; i < this.motionManager.lipSyncIds.length; ++i) { + this.coreModel.setParamFloat(this.coreModel.getParamIndex(this.motionManager.lipSyncIds[i]), value); + } + } (_c = this.physics) == null ? void 0 : _c.update(now); (_d = this.pose) == null ? void 0 : _d.update(dt); this.emit("beforeModelUpdate"); @@ -4007,6 +4042,7 @@ const ParamAngleY = "ParamAngleY"; const ParamAngleZ = "ParamAngleZ"; const ParamEyeBallX = "ParamEyeBallX"; const ParamEyeBallY = "ParamEyeBallY"; +const ParamMouthForm = "ParamMouthForm"; const ParamBodyAngleX = "ParamBodyAngleX"; const ParamBreath = "ParamBreath"; class CubismBreath { @@ -5268,6 +5304,7 @@ class Cubism4InternalModel extends InternalModel { this.idParamEyeBallY = ParamEyeBallY; this.idParamBodyAngleX = ParamBodyAngleX; this.idParamBreath = ParamBreath; + this.idParamMouthForm = ParamMouthForm; this.pixelsPerUnit = 1; this.centeringTransform = new Matrix(); this.coreModel = coreModel; @@ -5370,6 +5407,19 @@ class Cubism4InternalModel extends InternalModel { } this.updateFocus(); this.updateNaturalMovements(dt * 1e3, now * 1e3); + if (this.lipSync && this.motionManager.currentAudio) { + let value = this.motionManager.mouthSync(); + let min_ = 0; + let max_ = 1; + let weight = 1.2; + if (value > 0) { + min_ = 0.4; + } + value = clamp(value * weight, min_, max_); + for (let i = 0; i < this.motionManager.lipSyncIds.length; ++i) { + model.addParameterValueById(this.motionManager.lipSyncIds[i], value, 0.8); + } + } (_c = this.physics) == null ? void 0 : _c.evaluate(model, dt); (_d = this.pose) == null ? void 0 : _d.updateParameters(model, dt); this.emit("beforeModelUpdate"); @@ -5384,6 +5434,9 @@ class Cubism4InternalModel extends InternalModel { this.coreModel.addParameterValueById(this.idParamAngleZ, this.focusController.x * this.focusController.y * -30); this.coreModel.addParameterValueById(this.idParamBodyAngleX, this.focusController.x * 10); } + updateFacialEmotion(mouthForm) { + this.coreModel.addParameterValueById(this.idParamMouthForm, mouthForm); + } updateNaturalMovements(dt, now) { var _a; (_a = this.breath) == null ? void 0 : _a.updateParameters(this.coreModel, dt / 1e3); diff --git a/dist/index.js b/dist/index.js index 94507684..3171f60a 100644 --- a/dist/index.js +++ b/dist/index.js @@ -582,8 +582,8 @@ var __async = (__this, __arguments, generator) => { _loadMotion(group, index) { throw new Error("Not implemented."); } - speakUp(sound, volume, expression) { - return __async(this, null, function* () { + speakUp(_0) { + return __async(this, arguments, function* (sound, { volume = 1, expression, resetExpression = true } = {}) { if (!exports2.config.sound) { return false; } @@ -614,10 +614,10 @@ var __async = (__this, __arguments, generator) => { if (file) { try { audio = SoundManager.add(file, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }); this.currentAudio = audio; @@ -651,7 +651,7 @@ var __async = (__this, __arguments, generator) => { }); } startMotion(_0, _1) { - return __async(this, arguments, function* (group, index, priority = MotionPriority.NORMAL, sound, volume, expression) { + return __async(this, arguments, function* (group, index, priority = MotionPriority.NORMAL, { sound = void 0, volume = 1, expression = void 0, resetExpression = true } = {}) { var _a; if (this.currentAudio) { if (!this.currentAudio.ended) { @@ -691,10 +691,10 @@ var __async = (__this, __arguments, generator) => { if (file) { try { audio = SoundManager.add(file, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }, () => { - expression && that.expressionManager && that.expressionManager.resetExpression(); + resetExpression && expression && that.expressionManager && that.expressionManager.resetExpression(); that.currentAudio = void 0; }); this.currentAudio = audio; @@ -740,8 +740,8 @@ var __async = (__this, __arguments, generator) => { return true; }); } - startRandomMotion(group, priority, sound, volume) { - return __async(this, null, function* () { + startRandomMotion(_0, _1) { + return __async(this, arguments, function* (group, priority, { sound = void 0, volume = 1, expression = void 0, resetExpression = true } = {}) { const groupDefs = this.definitions[group]; if (groupDefs == null ? void 0 : groupDefs.length) { const availableIndices = []; @@ -752,7 +752,12 @@ var __async = (__this, __arguments, generator) => { } if (availableIndices.length) { const index = availableIndices[Math.floor(Math.random() * availableIndices.length)]; - return this.startMotion(group, index, priority, sound, volume); + return this.startMotion(group, index, priority, { + sound, + volume, + expression, + resetExpression + }); } } return false; @@ -1398,14 +1403,28 @@ var __async = (__this, __arguments, generator) => { onAnchorChange() { this.pivot.set(this.anchor.x * this.internalModel.width, this.anchor.y * this.internalModel.height); } - motion(group, index, priority, sound, volume, expression) { - return index === void 0 ? this.internalModel.motionManager.startRandomMotion(group, priority) : this.internalModel.motionManager.startMotion(group, index, priority, sound, volume, expression); + motion(group, index, { priority = 2, sound, volume = 1, expression, resetExpression = true } = {}) { + return index === void 0 ? this.internalModel.motionManager.startRandomMotion(group, priority, { + sound, + volume, + expression, + resetExpression + }) : this.internalModel.motionManager.startMotion(group, index, priority, { + sound, + volume, + expression, + resetExpression + }); } resetMotions() { return this.internalModel.motionManager.stopAllMotions(); } - speak(sound, volume, expression) { - return this.internalModel.motionManager.speakUp(sound, volume, expression); + speak(sound, { volume = 1, expression, resetExpression = true } = {}) { + return this.internalModel.motionManager.speakUp(sound, { + volume, + expression, + resetExpression + }); } stopSpeaking() { return this.internalModel.motionManager.stopSpeaking(); @@ -1790,6 +1809,7 @@ var __async = (__this, __arguments, generator) => { this.queueManager = new MotionQueueManager(); this.definitions = this.settings.motions; this.init(options); + this.lipSyncIds = ["PARAM_MOUTH_OPEN_Y"]; } init(options) { super.init(options); @@ -1903,6 +1923,7 @@ var __async = (__this, __arguments, generator) => { constructor(coreModel, settings, options) { super(); this.textureFlipY = true; + this.lipSync = true; this.drawDataCount = 0; this.disableCulling = false; this.coreModel = coreModel; @@ -1916,6 +1937,7 @@ var __async = (__this, __arguments, generator) => { this.angleZParamIndex = coreModel.getParamIndex("PARAM_ANGLE_Z"); this.bodyAngleXParamIndex = coreModel.getParamIndex("PARAM_BODY_ANGLE_X"); this.breathParamIndex = coreModel.getParamIndex("PARAM_BREATH"); + this.mouthFormIndex = coreModel.getParamIndex("PARAM_MOUTH_FORM"); this.init(); } init() { @@ -2024,6 +2046,19 @@ var __async = (__this, __arguments, generator) => { } this.updateFocus(); this.updateNaturalMovements(dt, now); + if (this.lipSync && this.motionManager.currentAudio) { + let value = this.motionManager.mouthSync(); + let min_ = 0; + let max_ = 1; + let weight = 1.2; + if (value > 0) { + min_ = 0.4; + } + value = clamp(value * weight, min_, max_); + for (let i = 0; i < this.motionManager.lipSyncIds.length; ++i) { + this.coreModel.setParamFloat(this.coreModel.getParamIndex(this.motionManager.lipSyncIds[i]), value); + } + } (_c = this.physics) == null ? void 0 : _c.update(now); (_d = this.pose) == null ? void 0 : _d.update(dt); this.emit("beforeModelUpdate"); @@ -4007,6 +4042,7 @@ var __async = (__this, __arguments, generator) => { const ParamAngleZ = "ParamAngleZ"; const ParamEyeBallX = "ParamEyeBallX"; const ParamEyeBallY = "ParamEyeBallY"; + const ParamMouthForm = "ParamMouthForm"; const ParamBodyAngleX = "ParamBodyAngleX"; const ParamBreath = "ParamBreath"; class CubismBreath { @@ -5268,6 +5304,7 @@ var __async = (__this, __arguments, generator) => { this.idParamEyeBallY = ParamEyeBallY; this.idParamBodyAngleX = ParamBodyAngleX; this.idParamBreath = ParamBreath; + this.idParamMouthForm = ParamMouthForm; this.pixelsPerUnit = 1; this.centeringTransform = new math.Matrix(); this.coreModel = coreModel; @@ -5370,6 +5407,19 @@ var __async = (__this, __arguments, generator) => { } this.updateFocus(); this.updateNaturalMovements(dt * 1e3, now * 1e3); + if (this.lipSync && this.motionManager.currentAudio) { + let value = this.motionManager.mouthSync(); + let min_ = 0; + let max_ = 1; + let weight = 1.2; + if (value > 0) { + min_ = 0.4; + } + value = clamp(value * weight, min_, max_); + for (let i = 0; i < this.motionManager.lipSyncIds.length; ++i) { + model.addParameterValueById(this.motionManager.lipSyncIds[i], value, 0.8); + } + } (_c = this.physics) == null ? void 0 : _c.evaluate(model, dt); (_d = this.pose) == null ? void 0 : _d.updateParameters(model, dt); this.emit("beforeModelUpdate"); @@ -5384,6 +5434,9 @@ var __async = (__this, __arguments, generator) => { this.coreModel.addParameterValueById(this.idParamAngleZ, this.focusController.x * this.focusController.y * -30); this.coreModel.addParameterValueById(this.idParamBodyAngleX, this.focusController.x * 10); } + updateFacialEmotion(mouthForm) { + this.coreModel.addParameterValueById(this.idParamMouthForm, mouthForm); + } updateNaturalMovements(dt, now) { var _a; (_a = this.breath) == null ? void 0 : _a.updateParameters(this.coreModel, dt / 1e3); diff --git a/dist/index.min.js b/dist/index.min.js index 72b430f8..c78a4a02 100644 --- a/dist/index.min.js +++ b/dist/index.min.js @@ -1 +1 @@ -var __pow=Math.pow,__async=(t,e,i)=>new Promise(((s,r)=>{var o=t=>{try{n(i.next(t))}catch(e){r(e)}},a=t=>{try{n(i.throw(t))}catch(e){r(e)}},n=t=>t.done?s(t.value):Promise.resolve(t.value).then(o,a);n((i=i.apply(t,e)).next())}));!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("@pixi/utils"),require("@pixi/math"),require("@pixi/core"),require("@pixi/display")):"function"==typeof define&&define.amd?define(["exports","@pixi/utils","@pixi/math","@pixi/core","@pixi/display"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).PIXI=t.PIXI||{},t.PIXI.live2d=t.PIXI.live2d||{}),t.PIXI.utils,t.PIXI,t.PIXI,t.PIXI)}(this,(function(t,e,i,s,r){"use strict";var o,a,n;(a=o||(o={})).supportMoreMaskDivisions=!0,a.setOpacityFromMotion=!1,t.config=void 0,(n=t.config||(t.config={})).LOG_LEVEL_VERBOSE=0,n.LOG_LEVEL_WARNING=1,n.LOG_LEVEL_ERROR=2,n.LOG_LEVEL_NONE=999,n.logLevel=n.LOG_LEVEL_WARNING,n.sound=!0,n.motionSync=!0,n.motionFadingDuration=500,n.idleMotionFadingDuration=2e3,n.expressionFadingDuration=500,n.preserveExpressionOnMotion=!0,n.cubism4=o;const l={log(e,...i){t.config.logLevel<=t.config.LOG_LEVEL_VERBOSE&&console.log(`[${e}]`,...i)},warn(e,...i){t.config.logLevel<=t.config.LOG_LEVEL_WARNING&&console.warn(`[${e}]`,...i)},error(e,...i){t.config.logLevel<=t.config.LOG_LEVEL_ERROR&&console.error(`[${e}]`,...i)}};function h(t,e,i){return ti?i:t}function u(t,e){return Math.random()*(e-t)+t}function d(t,e,i,s,r){const o=e[s];null!==o&&typeof o===t&&(i[r]=o)}function c(t,e,i,s,r){const o=e[s];Array.isArray(o)&&(i[r]=o.filter((e=>null!==e&&typeof e===t)))}function g(t,e){e.forEach((e=>{Object.getOwnPropertyNames(e.prototype).forEach((i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i))}))}))}function m(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 p(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}class _ extends e.EventEmitter{constructor(t,e){super(),this.expressions=[],this.reserveExpressionIndex=-1,this.destroyed=!1,this.settings=t,this.tag=`ExpressionManager(${t.name})`}init(){this.defaultExpression=this.createExpression({},void 0),this.currentExpression=this.defaultExpression,this.stopAllExpressions()}loadExpression(t){return __async(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 __async(this,null,(function*(){if(this.definitions.length){const t=[];for(let e=0;e-1&&tl&&(o*=l/n,a*=l/n),this.vx+=o,this.vy+=a;const h=Math.sqrt(__pow(this.vx,2)+__pow(this.vy,2)),u=.5*(Math.sqrt(__pow(l,2)+8*l*s)-l);h>u&&(this.vx*=u/h,this.vy*=u/h),this.x+=this.vx,this.y+=this.vy}}class x{constructor(t){this.json=t;let e=t.url;if("string"!=typeof e)throw new TypeError("The `url` field in settings JSON must be defined as a string.");this.url=e,this.name=m(this.url)}resolveURL(t){return e.url.resolve(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(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 y=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(y||{});class M{constructor(){this.debug=!1,this.currentPriority=0,this.reservePriority=0}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!t.config.preserveExpressionOnMotion&&this.currentPriority>1}dump(t,e){if(this.debug){return`\n group = "${t}", index = ${e}\n`+["currentPriority","reservePriority","currentGroup","currentIndex","reservedGroup","reservedIndex","reservedIdleGroup","reservedIdleIndex"].map((t=>"["+t+"] "+this[t])).join("\n")}return""}}class C{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,i){const s=new Audio(t);return s.volume=this._volume,s.preload="auto",s.autoplay=!0,s.crossOrigin="anonymous",s.addEventListener("ended",(()=>{this.dispose(s),null==e||e()})),s.addEventListener("error",(e=>{this.dispose(s),l.warn("SoundManager",`Error occurred on "${t}"`,e.error),null==i||i(e.error)})),this.audios.push(s),s}static play(t){return new Promise(((e,i)=>{var s;null==(s=t.play())||s.catch((e=>{t.dispatchEvent(new ErrorEvent("error",{error:e})),i(e)})),t.readyState===t.HAVE_ENOUGH_DATA?e():t.addEventListener("canplaythrough",e)}))}static addContext(t){const e=new AudioContext;return this.contexts.push(e),e}static addAnalyzer(t,e){const i=e.createMediaElementSource(t),s=e.createAnalyser();return s.fftSize=256,s.minDecibels=-90,s.maxDecibels=-10,s.smoothingTimeConstant=.85,i.connect(s),s.connect(e.destination),this.analysers.push(s),s}static analyze(t){if(null!=t){let e=new Float32Array(t.fftSize),i=0;t.getFloatTimeDomainData(e);for(const t of e)i+=t*t;return parseFloat(Math.sqrt(i/e.length*20).toFixed(1))}return parseFloat(Math.random().toFixed(1))}static dispose(t){t.pause(),t.removeAttribute("src"),p(this.audios,t)}static destroy(){for(let t=this.contexts.length-1;t>=0;t--)this.contexts[t].close();for(let t=this.audios.length-1;t>=0;t--)this.dispose(this.audios[t])}}C.audios=[],C.analysers=[],C.contexts=[],C._volume=.9;var v=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(v||{});class P extends e.EventEmitter{constructor(t,e){super(),this.motionGroups={},this.state=new M,this.playing=!1,this.destroyed=!1,this.settings=t,this.tag=`MotionManager(${t.name})`,this.state.tag=this.tag}init(t){(null==t?void 0:t.idleMotionGroup)&&(this.groups.idle=t.idleMotionGroup),this.setupMotions(t),this.stopAllMotions()}setupMotions(t){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)if(this.definitions[i])for(let t=0;t{s&&c.expressionManager&&c.expressionManager.resetExpression(),c.currentAudio=void 0}),(()=>{s&&c.expressionManager&&c.expressionManager.resetExpression(),c.currentAudio=void 0})),this.currentAudio=r;let t=1;void 0!==i&&(t=i),C.volume=t,a=C.addContext(this.currentAudio),this.currentContext=a,o=C.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=o}catch(g){l.warn(this.tag,"Failed to create audio",n,g)}if(r){const e=C.play(r).catch((t=>l.warn(this.tag,"Failed to play audio",r.src,t)));t.config.motionSync&&(yield e)}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),s&&this.expressionManager&&this.expressionManager.setExpression(s),this.playing=!0,!0}))}startMotion(e,i){return __async(this,arguments,(function*(e,i,s=y.NORMAL,r,o,a){var n;if(this.currentAudio&&!this.currentAudio.ended)return!1;if(!this.state.reserve(e,i,s))return!1;const h=null==(n=this.definitions[e])?void 0:n[i];if(!h)return!1;let u,d,c;if(this.currentAudio&&C.dispose(this.currentAudio),t.config.sound){const t=r&&r.startsWith("data:audio/wav;base64");if(r&&!t){var g=document.createElement("a");g.href=r,r=g.href}const e=r&&(r.startsWith("http")||r.startsWith("blob")),i=this.getSoundFile(h);let s=i;i&&(s=this.settings.resolveURL(i)+"?cache-buster="+(new Date).getTime()),(e||t)&&(s=r);const n=this;if(s)try{u=C.add(s,(()=>{a&&n.expressionManager&&n.expressionManager.resetExpression(),n.currentAudio=void 0}),(()=>{a&&n.expressionManager&&n.expressionManager.resetExpression(),n.currentAudio=void 0})),this.currentAudio=u;let t=1;void 0!==o&&(t=o),C.volume=t,c=C.addContext(this.currentAudio),this.currentContext=c,d=C.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=d}catch(p){l.warn(this.tag,"Failed to create audio",i,p)}}const m=yield this.loadMotion(e,i);if(u){s=3;const e=C.play(u).catch((t=>l.warn(this.tag,"Failed to play audio",u.src,t)));t.config.motionSync&&(yield e)}return this.state.start(m,e,i,s)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),l.log(this.tag,"Start motion:",this.getMotionName(h)),this.emit("motionStart",e,i,u),a&&this.expressionManager&&this.expressionManager.setExpression(a),this.playing=!0,this._startMotion(m),!0):(u&&(C.dispose(u),this.currentAudio=void 0),!1)}))}startRandomMotion(t,e,i,s){return __async(this,null,(function*(){const r=this.definitions[t];if(null==r?void 0:r.length){const o=[];for(let e=0;et.index>=0));for(const e of t)this.hitAreas[e.name]=e}hitTest(t,e){return Object.keys(this.hitAreas).filter((i=>this.isHit(i,t,e)))}isHit(t,e,i){if(!this.hitAreas[t])return!1;const s=this.hitAreas[t].index,r=this.getDrawableBounds(s,b);return r.x<=e&&e<=r.x+r.width&&r.y<=i&&i<=r.y+r.height}getDrawableBounds(t,e){const i=this.getDrawableVertices(t);let s=i[0],r=i[0],o=i[1],a=i[1];for(let n=0;n{200!==o.status&&0!==o.status||!o.response?o.onerror():s(o.response)},o.onerror=()=>{l.warn("XHRLoader",`Failed to load resource as ${o.responseType} (Status ${o.status}): ${e}`),r(new w("Network error.",e,o.status))},o.onabort=()=>r(new w("Aborted.",e,o.status,!0)),o.onloadend=()=>{var e;I.allXhrSet.delete(o),t&&(null==(e=I.xhrMap.get(t))||e.delete(o))},o}static cancelXHRs(){var t;null==(t=I.xhrMap.get(this))||t.forEach((t=>{t.abort(),I.allXhrSet.delete(t)})),I.xhrMap.delete(this)}static release(){I.allXhrSet.forEach((t=>t.abort())),I.allXhrSet.clear(),I.xhrMap=new WeakMap}};let T=I;function E(t,e){let i=-1;return function s(r,o){if(o)return Promise.reject(o);if(r<=i)return Promise.reject(new Error("next() called multiple times"));i=r;const a=t[r];if(!a)return Promise.resolve();try{return Promise.resolve(a(e,s.bind(null,r+1)))}catch(n){return Promise.reject(n)}}(0)}T.xhrMap=new WeakMap,T.allXhrSet=new Set,T.loader=(t,e)=>new Promise(((e,i)=>{I.createXHR(t.target,t.settings?t.settings.resolveURL(t.url):t.url,t.type,(i=>{t.result=i,e()}),i).send()}));class L{static load(t){return E(this.middlewares,t).then((()=>t.result))}}L.middlewares=[T.loader];const F="Live2DFactory",A=(t,e)=>__async(this,null,(function*(){if("string"==typeof t.source){const e=yield L.load({url:t.source,type:"json",target:t.live2dModel});e.url=t.source,t.source=e,t.live2dModel.emit("settingsJSONLoaded",e)}return e()})),D=(t,e)=>__async(this,null,(function*(){if(t.source instanceof x)return t.settings=t.source,e();if("object"==typeof t.source){const i=V.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.")})),R=(t,e)=>{if(t.settings){const i=V.findRuntime(t.settings);if(i)return i.ready().then(e)}return e()},B=(t,e)=>__async(this,null,(function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=V.findRuntime(e);if(s){const r=[];e.pose&&r.push(L.load({settings:e,url:e.pose,type:"json",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(F,"Failed to load pose.",e)}))),e.physics&&r.push(L.load({settings:e,url:e.physics,type:"json",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(F,"Failed to load physics.",e)}))),r.length&&(yield Promise.all(r))}}})),O=(t,e)=>__async(this,null,(function*(){if(!t.settings)throw new TypeError("Missing settings.");{const i=t.live2dModel,r=t.settings.textures.map((e=>function(t,e={}){const i={resourceOptions:{crossorigin:e.crossOrigin}};if(s.Texture.fromURL)return s.Texture.fromURL(t,i).catch((t=>{if(t instanceof Error)throw t;const e=new Error("Texture loading error");throw e.event=t,e}));i.resourceOptions.autoLoad=!1;const r=s.Texture.from(t,i);if(r.baseTexture.valid)return Promise.resolve(r);const o=r.baseTexture.resource;return null!=o._live2d_load||(o._live2d_load=new Promise(((t,e)=>{const i=t=>{o.source.removeEventListener("error",i);const s=new Error("Texture loading error");s.event=t,e(s)};o.source.addEventListener("error",i),o.load().then((()=>t(r))).catch(i)}))),o._live2d_load}(t.settings.resolveURL(e),{crossOrigin:t.options.crossOrigin})));if(yield e(),!t.internalModel)throw new TypeError("Missing internal model.");i.internalModel=t.internalModel,i.emit("modelLoaded",t.internalModel),i.textures=yield Promise.all(r),i.emit("textureLoaded",i.textures)}})),k=(t,e)=>__async(this,null,(function*(){const i=t.settings;if(i instanceof x){const s=V.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield L.load({settings:i,url:i.moc,type:"arraybuffer",target:t.live2dModel});if(!s.isValidMoc(r))throw new Error("Invalid moc data");const o=s.createCoreModel(r);return t.internalModel=s.createInternalModel(o,i,t.options),e()}throw new TypeError("Missing settings.")})),U=class{static registerRuntime(t){U.runtimes.push(t),U.runtimes.sort(((t,e)=>e.version-t.version))}static findRuntime(t){for(const e of U.runtimes)if(e.test(t))return e}static setupLive2DModel(t,e,i){return __async(this,null,(function*(){const s=new Promise((e=>t.once("textureLoaded",e))),r=new Promise((e=>t.once("modelLoaded",e))),o=Promise.all([s,r]).then((()=>t.emit("ready")));yield E(U.live2DModelMiddlewares,{live2dModel:t,source:e,options:i||{}}),yield o,t.emit("load")}))}static loadMotion(t,e,i){var s;const r=s=>t.emit("motionLoadError",e,i,s);try{const o=null==(s=t.definitions[e])?void 0:s[i];if(!o)return Promise.resolve(void 0);t.listeners("destroy").includes(U.releaseTasks)||t.once("destroy",U.releaseTasks);let a=U.motionTasksMap.get(t);a||(a={},U.motionTasksMap.set(t,a));let n=a[e];n||(n=[],a[e]=n);const h=t.getMotionFile(o);return null!=n[i]||(n[i]=L.load({url:h,settings:t.settings,type:t.motionDataType,target:t}).then((s=>{var r;const a=null==(r=U.motionTasksMap.get(t))?void 0:r[e];a&&delete a[i];const n=t.createMotion(s,e,o);return t.emit("motionLoaded",e,i,n),n})).catch((e=>{l.warn(t.tag,`Failed to load motion: ${h}\n`,e),r(e)}))),n[i]}catch(o){l.warn(t.tag,`Failed to load motion at "${e}"[${i}]\n`,o),r(o)}return Promise.resolve(void 0)}static loadExpression(t,e){const i=i=>t.emit("expressionLoadError",e,i);try{const s=t.definitions[e];if(!s)return Promise.resolve(void 0);t.listeners("destroy").includes(U.releaseTasks)||t.once("destroy",U.releaseTasks);let r=U.expressionTasksMap.get(t);r||(r=[],U.expressionTasksMap.set(t,r));const o=t.getExpressionFile(s);return null!=r[e]||(r[e]=L.load({url:o,settings:t.settings,type:"json",target:t}).then((i=>{const r=U.expressionTasksMap.get(t);r&&delete r[e];const o=t.createExpression(i,s);return t.emit("expressionLoaded",e,o),o})).catch((e=>{l.warn(t.tag,`Failed to load expression: ${o}\n`,e),i(e)}))),r[e]}catch(s){l.warn(t.tag,`Failed to load expression at [${e}]\n`,s),i(s)}return Promise.resolve(void 0)}static releaseTasks(){this instanceof P?U.motionTasksMap.delete(this):U.expressionTasksMap.delete(this)}};let V=U;V.runtimes=[],V.urlToJSON=A,V.jsonToSettings=D,V.waitUntilReady=R,V.setupOptionals=B,V.setupEssentials=O,V.createInternalModel=k,V.live2DModelMiddlewares=[A,D,R,B,O,k],V.motionTasksMap=new WeakMap,V.expressionTasksMap=new WeakMap,P.prototype._loadMotion=function(t,e){return V.loadMotion(this,t,e)},_.prototype._loadExpression=function(t){return V.loadExpression(this,t)};class N{constructor(){this._autoInteract=!1}get autoInteract(){return this._autoInteract}set autoInteract(t){t!==this._autoInteract&&(t?this.on("pointertap",G,this):this.off("pointertap",G,this),this._autoInteract=t)}registerInteraction(t){t!==this.interactionManager&&(this.unregisterInteraction(),this._autoInteract&&t&&(this.interactionManager=t,t.on("pointermove",X,this)))}unregisterInteraction(){var t;this.interactionManager&&(null==(t=this.interactionManager)||t.off("pointermove",X,this),this.interactionManager=void 0)}}function G(t){this.tap(t.data.global.x,t.data.global.y)}function X(t){this.focus(t.data.global.x,t.data.global.y)}class z extends i.Transform{}const j=new i.Point,W=new i.Matrix;let H;class Y extends r.Container{constructor(t){super(),this.tag="Live2DModel(uninitialized)",this.textures=[],this.transform=new z,this.anchor=new i.ObservablePoint(this.onAnchorChange,this,0,0),this.glContextID=-1,this.elapsedTime=performance.now(),this.deltaTime=0,this._autoUpdate=!1,this.once("modelLoaded",(()=>this.init(t)))}static from(t,e){const i=new this(e);return V.setupLive2DModel(i,t,e).then((()=>i))}static fromSync(t,e){const i=new this(e);return V.setupLive2DModel(i,t,e).then(null==e?void 0:e.onLoad).catch(null==e?void 0:e.onError),i}static registerTicker(t){H=t}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){var e;H||(H=null==(e=window.PIXI)?void 0:e.Ticker),t?this._destroyed||(H?(H.shared.add(this.onTickerUpdate,this),this._autoUpdate=!0):l.warn(this.tag,"No Ticker registered, please call Live2DModel.registerTicker(Ticker).")):(null==H||H.shared.remove(this.onTickerUpdate,this),this._autoUpdate=!1)}init(t){this.tag=`Live2DModel(${this.internalModel.settings.name})`;const e=Object.assign({autoUpdate:!0,autoInteract:!0},t);e.autoInteract&&(this.interactive=!0),this.autoInteract=e.autoInteract,this.autoUpdate=e.autoUpdate}onAnchorChange(){this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(t,e,i,s,r,o){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i):this.internalModel.motionManager.startMotion(t,e,i,s,r,o)}resetMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(t,e,i){return this.internalModel.motionManager.speakUp(t,e,i)}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){j.x=t,j.y=e,this.toModelPosition(j,j,!0);let s=j.x/this.internalModel.originalWidth*2-1,r=j.y/this.internalModel.originalHeight*2-1,o=Math.atan2(r,s);this.internalModel.focusController.focus(Math.cos(o),-Math.sin(o),i)}tap(t,e){const i=this.hitTest(t,e);i.length&&(l.log(this.tag,"Hit",i),this.emit("hit",i))}hitTest(t,e){return j.x=t,j.y=e,this.toModelPosition(j,j),this.internalModel.hitTest(j.x,j.y)}toModelPosition(t,e=t.clone(),i){return i||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.transform.worldTransform.applyInverse(t,e),this.internalModel.localTransform.applyInverse(e,e),e}containsPoint(t){return this.getBounds(!0).contains(t.x,t.y)}_calculateBounds(){this._bounds.addFrame(this.transform,0,0,this.internalModel.width,this.internalModel.height)}onTickerUpdate(){this.update(H.shared.deltaMS)}update(t){this.deltaTime+=t,this.elapsedTime+=t}_render(t){this.registerInteraction(t.plugins.interaction),t.batch.reset(),t.geometry.reset(),t.shader.reset(),t.state.reset();let e=!1;this.glContextID!==t.CONTEXT_UID&&(this.glContextID=t.CONTEXT_UID,this.internalModel.updateWebGLContext(t.gl,this.glContextID),e=!0);for(let r=0;re.destroy(t.baseTexture))),this.internalModel.destroy(),super.destroy(t)}}g(Y,[N]);const q=class{static resolveURL(t,e){var i;const s=null==(i=q.filesMap[t])?void 0:i[e];if(void 0===s)throw new Error("Cannot find this file from uploaded files: "+e);return s}static upload(t,i){return __async(this,null,(function*(){const s={};for(const r of i.getDefinedFiles()){const o=decodeURI(e.url.resolve(i.url,r)),a=t.find((t=>t.webkitRelativePath===o));a&&(s[r]=URL.createObjectURL(a))}q.filesMap[i._objectURL]=s}))}static createSettings(t){return __async(this,null,(function*(){const e=t.find((t=>t.name.endsWith("model.json")||t.name.endsWith("model3.json")));if(!e)throw new TypeError("Settings file not found");const i=yield q.readText(e),s=JSON.parse(i);s.url=e.webkitRelativePath;const r=V.findRuntime(s);if(!r)throw new Error("Unknown settings JSON");const o=r.createModelSettings(s);return o._objectURL=URL.createObjectURL(e),o}))}static readText(t){return __async(this,null,(function*(){return new Promise(((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")}))}))}};let $=q;$.filesMap={},$.factory=(t,e)=>__async(this,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 q.createSettings(e);i.validateFiles(e.map((t=>encodeURI(t.webkitRelativePath)))),yield q.upload(e,i),i.resolveURL=function(t){return q.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),q.filesMap[t])for(const e of Object.values(q.filesMap[t]))URL.revokeObjectURL(e);delete q.filesMap[t]}))}))}return e()})),V.live2DModelMiddlewares.unshift($.factory);const J=class{static unzip(t,i){return __async(this,null,(function*(){const s=yield J.getFilePaths(t),r=[];for(const t of i.getDefinedFiles()){const o=decodeURI(e.url.resolve(i.url,t));s.includes(o)&&r.push(o)}const o=yield J.getFiles(t,r);for(let t=0;tt.endsWith("model.json")||t.endsWith("model3.json")));if(!e)throw new Error("Settings file not found");const i=yield J.readText(t,e);if(!i)throw new Error("Empty settings file: "+e);const s=JSON.parse(i);s.url=e;const r=V.findRuntime(s);if(!r)throw new Error("Unknown settings JSON");return r.createModelSettings(s)}))}static zipReader(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static getFilePaths(t){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static getFiles(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static readText(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static releaseReader(t){}};let Z=J;if(Z.ZIP_PROTOCOL="zip://",Z.uid=0,Z.factory=(t,e)=>__async(this,null,(function*(){const i=t.source;let s,r,o;if("string"==typeof i&&(i.endsWith(".zip")||i.startsWith(J.ZIP_PROTOCOL))?(s=i.startsWith(J.ZIP_PROTOCOL)?i.slice(J.ZIP_PROTOCOL.length):i,r=yield L.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),o=i.settings),r){if(!r.size)throw new Error("Empty zip file");const e=yield J.zipReader(r,s);o||(o=yield J.createSettings(e)),o._objectURL=J.ZIP_PROTOCOL+J.uid+"/"+o.url;const i=yield J.unzip(e,o);i.settings=o,t.source=i,s.startsWith("blob:")&&t.live2dModel.once("modelLoaded",(t=>{t.once("destroy",(function(){URL.revokeObjectURL(s)}))})),J.releaseReader(e)}return e()})),V.live2DModelMiddlewares.unshift(Z.factory),!window.Live2D)throw new Error("Could not find Cubism 2 runtime. This plugin requires live2d.min.js to be loaded.");const Q=Live2DMotion.prototype.updateParam;Live2DMotion.prototype.updateParam=function(t,e){Q.call(this,t,e),e.isFinished()&&this.onFinishHandler&&(this.onFinishHandler(this),delete this.onFinishHandler)};class K extends AMotion{constructor(e){super(),this.params=[],this.setFadeIn(e.fade_in>0?e.fade_in:t.config.expressionFadingDuration),this.setFadeOut(e.fade_out>0?e.fade_out:t.config.expressionFadingDuration),Array.isArray(e.params)&&e.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 tt extends _{constructor(t,e){var i;super(t,e),this.queueManager=new MotionQueueManager,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 K(t)}_setExpression(t){return this.queueManager.startMotion(t)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}}class et extends P{constructor(t,e){super(t,e),this.groups={idle:"idle"},this.motionDataType="arraybuffer",this.queueManager=new MotionQueueManager,this.definitions=this.settings.motions,this.init(e)}init(t){super.init(t),this.settings.expressions&&(this.expressionManager=new tt(this.settings,t))}isFinished(){return this.queueManager.isFinished()}createMotion(e,i,s){const r=Live2DMotion.loadMotion(e),o=i===this.groups.idle?t.config.idleMotionFadingDuration:t.config.motionFadingDuration;return r.setFadeIn(s.fade_in>0?s.fade_in:o),r.setFadeOut(s.fade_out>0?s.fade_out:o),r}getMotionFile(t){return t.file}getMotionName(t){return t.file}getSoundFile(t){return t.sound}_startMotion(t,e){return t.onFinishHandler=e,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}}class it{constructor(t){this.coreModel=t,this.blinkInterval=4e3,this.closingDuration=100,this.closedDuration=50,this.openingDuration=150,this.eyeState=0,this.eyeParamValue=1,this.closedTimer=0,this.nextBlinkTimeLeft=this.blinkInterval,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+u(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 st=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class rt extends S{constructor(t,e,i){super(),this.textureFlipY=!0,this.drawDataCount=0,this.disableCulling=!1,this.coreModel=t,this.settings=e,this.motionManager=new et(e,i),this.eyeBlink=new it(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;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 of Object.keys(this.settings.layout)){let i=e;"center_x"===e?i="centerX":"center_y"===e&&(i="centerY"),t[i]=this.settings.layout[e]}return t}updateWebGLContext(t,e){const i=this.coreModel.drawParamWebGL;i.firstDraw=!0,i.setGL(t),i.glno=e;for(const o in i)i.hasOwnProperty(o)&&i[o]instanceof WebGLBuffer&&(i[o]=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;return(null==(t=this.settings.hitAreas)?void 0:t.map((t=>({id:t.id,name:t.name,index:this.coreModel.getDrawDataIndex(t.id)}))))||[]}getDrawableIDs(){const t=this.coreModel.getModelContext(),e=[];for(let i=0;i0&&t.textures.every((t=>"string"==typeof t))}copy(t){d("string",t,this,"name","name"),d("string",t,this,"pose","pose"),d("string",t,this,"physics","physics"),d("object",t,this,"layout","layout"),d("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")}replaceFiles(t){super.replaceFiles(t);for(const[e,i]of Object.entries(this.motions))for(let s=0;s{const e=new PhysicsHair;return e.setup(t.setup.length,t.setup.regist,t.setup.mass),t.src.forEach((({id:t,ptype:i,scale:s,weight:r})=>{const o=at[i];o&&e.addSrcParam(o,t,s,r)})),t.targets.forEach((({id:t,ptype:i,scale:s,weight:r})=>{const o=nt[i];o&&e.addTargetParam(o,t,s,r)})),e})))}update(t){this.physicsHairs.forEach((e=>e.update(this.coreModel,t)))}}class ht{constructor(t){this.id=t,this.paramIndex=-1,this.partsIndex=-1,this.link=[]}initIndex(t){this.paramIndex=t.getParamIndex("VISIBLE:"+this.id),this.partsIndex=t.getPartsDataIndex(PartsDataID.getID(this.id)),t.setParamFloat(this.paramIndex,1)}}class ut{constructor(t,e){this.coreModel=t,this.opacityAnimDuration=500,this.partsGroups=[],e.parts_visible&&(this.partsGroups=e.parts_visible.map((({group:t})=>t.map((({id:t,link:e})=>{const i=new ht(t);return e&&(i.link=e.map((t=>new ht(t)))),i})))),this.init())}init(){this.partsGroups.forEach((t=>{t.forEach((t=>{if(t.initIndex(this.coreModel),t.paramIndex>=0){const e=0!==this.coreModel.getParamFloat(t.paramIndex);this.coreModel.setPartsOpacity(t.partsIndex,e?1:0),this.coreModel.setParamFloat(t.paramIndex,e?1:0),t.link.length>0&&t.link.forEach((t=>t.initIndex(this.coreModel)))}}))}))}normalizePartsOpacityGroup(t,e){const i=this.coreModel,s=.5;let r=1,o=t.findIndex((({paramIndex:t,partsIndex:e})=>e>=0&&0!==i.getParamFloat(t)));if(o>=0){const s=i.getPartsOpacity(t[o].partsIndex);r=h(s+e/this.opacityAnimDuration,0,1)}else o=0,r=1;t.forEach((({partsIndex:t},e)=>{if(t>=0)if(o==e)i.setPartsOpacity(t,r);else{let e,o=i.getPartsOpacity(t);e=r.15&&(e=1-.15/(1-r)),o>e&&(o=e),i.setPartsOpacity(t,o)}}))}copyOpacity(t){const e=this.coreModel;t.forEach((({partsIndex:t,link:i})=>{if(t>=0&&i){const s=e.getPartsOpacity(t);i.forEach((({partsIndex:t})=>{t>=0&&e.setPartsOpacity(t,s)}))}}))}update(t){this.partsGroups.forEach((e=>{this.normalizePartsOpacityGroup(e,t),this.copyOpacity(e)}))}}if(V.registerRuntime({version:2,test:t=>t instanceof ot||ot.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 ot(t),createCoreModel(t){const e=Live2DModelWebGL.loadModel(t),i=Live2D.getError();if(i)throw i;return e},createInternalModel:(t,e,i)=>new rt(t,e,i),createPose:(t,e)=>new ut(t,e),createPhysics:(t,e)=>new lt(t,e)}),!window.Live2DCubismCore)throw new Error("Could not find Cubism 4 runtime. This plugin requires live2dcubismcore.js to be loaded.");class dt{constructor(t,e){this.x=t||0,this.y=e||0}add(t){const e=new dt(0,0);return e.x=this.x+t.x,e.y=this.y+t.y,e}substract(t){const e=new dt(0,0);return e.x=this.x-t.x,e.y=this.y-t.y,e}multiply(t){const e=new dt(0,0);return e.x=this.x*t.x,e.y=this.y*t.y,e}multiplyByScaler(t){return this.multiply(new dt(t,t))}division(t){const e=new dt(0,0);return e.x=this.x/t.x,e.y=this.y/t.y,e}divisionByScalar(t){return this.division(new dt(t,t))}getLength(){return Math.sqrt(this.x*this.x+this.y*this.y)}getDistanceWith(t){return Math.sqrt((this.x-t.x)*(this.x-t.x)+(this.y-t.y)*(this.y-t.y))}dot(t){return this.x*t.x+this.y*t.y}normalize(){const t=Math.pow(this.x*this.x+this.y*this.y,.5);this.x=this.x/t,this.y=this.y/t}isEqual(t){return this.x==t.x&&this.y==t.y}isNotEqual(t){return!this.isEqual(t)}}const ct=class{static range(t,e,i){return ti&&(t=i),t}static sin(t){return Math.sin(t)}static cos(t){return Math.cos(t)}static abs(t){return Math.abs(t)}static sqrt(t){return Math.sqrt(t)}static cbrt(t){if(0===t)return t;let e=t;const i=e<0;let s;return i&&(e=-e),e===1/0?s=1/0:(s=Math.exp(Math.log(e)/3),s=(e/(s*s)+2*s)/3),i?-s:s}static getEasingSine(t){return t<0?0:t>1?1:.5-.5*this.cos(t*Math.PI)}static max(t,e){return t>e?t:e}static min(t,e){return t>e?e:t}static degreesToRadian(t){return t/180*Math.PI}static radianToDegrees(t){return 180*t/Math.PI}static directionToRadian(t,e){let i=Math.atan2(e.y,e.x)-Math.atan2(t.y,t.x);for(;i<-Math.PI;)i+=2*Math.PI;for(;i>Math.PI;)i-=2*Math.PI;return i}static directionToDegrees(t,e){const i=this.directionToRadian(t,e);let s=this.radianToDegrees(i);return e.x-t.x>0&&(s=-s),s}static radianToDirection(t){const e=new dt;return e.x=this.sin(t),e.y=this.cos(t),e}static quadraticEquation(t,e,i){return this.abs(t)1&&(t=1),e<0?e=0:e>1&&(e=1),i<0?i=0:i>1&&(i=1),s<0?s=0:s>1&&(s=1),this._modelColor.R=t,this._modelColor.G=e,this._modelColor.B=i,this._modelColor.A=s}getModelColor(){return Object.assign({},this._modelColor)}setIsPremultipliedAlpha(t){this._isPremultipliedAlpha=t}isPremultipliedAlpha(){return this._isPremultipliedAlpha}setIsCulling(t){this._isCulling=t}isCulling(){return this._isCulling}setAnisotropy(t){this._anisotropy=t}getAnisotropy(){return this._anisotropy}getModel(){return this._model}useHighPrecisionMask(t){this._useHighPrecisionMask=t}isUsingHighPrecisionMask(){return this._useHighPrecisionMask}constructor(){this._isCulling=!1,this._isPremultipliedAlpha=!1,this._anisotropy=0,this._modelColor=new ft,this._useHighPrecisionMask=!1,this._mvpMatrix4x4=new mt,this._mvpMatrix4x4.loadIdentity()}}var _t=(t=>(t[t.CubismBlendMode_Normal=0]="CubismBlendMode_Normal",t[t.CubismBlendMode_Additive=1]="CubismBlendMode_Additive",t[t.CubismBlendMode_Multiplicative=2]="CubismBlendMode_Multiplicative",t))(_t||{});class ft{constructor(t=1,e=1,i=1,s=1){this.R=t,this.G=e,this.B=i,this.A=s}}let xt,yt=!1,Mt=!1;const Ct=0,vt=2;class Pt{static startUp(t){if(yt)return wt("CubismFramework.startUp() is already done."),yt;if(Live2DCubismCore._isStarted)return yt=!0,!0;if(Live2DCubismCore._isStarted=!0,xt=t,xt&&Live2DCubismCore.Logging.csmSetLogFunction(xt.logFunction),yt=!0,yt){const t=Live2DCubismCore.Version.csmGetVersion(),e=(16711680&t)>>16,i=65535&t,s=t;wt("Live2D Cubism Core version: {0}.{1}.{2} ({3})",("00"+((4278190080&t)>>24)).slice(-2),("00"+e).slice(-2),("0000"+i).slice(-4),s)}return wt("CubismFramework.startUp() is complete."),yt}static cleanUp(){yt=!1,Mt=!1,xt=void 0}static initialize(t=0){yt?Mt?It("CubismFramework.initialize() skipped, already initialized."):(Live2DCubismCore.Memory.initializeAmountOfMemory(t),Mt=!0,wt("CubismFramework.initialize() is complete.")):It("CubismFramework is not started.")}static dispose(){yt?Mt?(pt.staticRelease(),Mt=!1,wt("CubismFramework.dispose() is complete.")):It("CubismFramework.dispose() skipped, not initialized."):It("CubismFramework is not started.")}static isStarted(){return yt}static isInitialized(){return Mt}static coreLogFunction(t){Live2DCubismCore.Logging.csmGetLogFunction()&&Live2DCubismCore.Logging.csmGetLogFunction()(t)}static getLoggingLevel(){return null!=xt?xt.loggingLevel:bt.LogLevel_Off}constructor(){}}var bt=(t=>(t[t.LogLevel_Verbose=0]="LogLevel_Verbose",t[t.LogLevel_Debug=1]="LogLevel_Debug",t[t.LogLevel_Info=2]="LogLevel_Info",t[t.LogLevel_Warning=3]="LogLevel_Warning",t[t.LogLevel_Error=4]="LogLevel_Error",t[t.LogLevel_Off=5]="LogLevel_Off",t))(bt||{});function St(t,...e){Et.print(bt.LogLevel_Debug,"[CSM][D]"+t+"\n",e)}function wt(t,...e){Et.print(bt.LogLevel_Info,"[CSM][I]"+t+"\n",e)}function It(t,...e){Et.print(bt.LogLevel_Warning,"[CSM][W]"+t+"\n",e)}function Tt(t,...e){Et.print(bt.LogLevel_Error,"[CSM][E]"+t+"\n",e)}class Et{static print(t,e,i){if(ti[e])))}static dumpBytes(t,e,i){for(let s=0;s0?this.print(t,"\n"):s%8==0&&s>0&&this.print(t," "),this.print(t,"{0} ",[255&e[s]]);this.print(t,"\n")}constructor(){}}class Lt{constructor(){this._fadeInSeconds=-1,this._fadeOutSeconds=-1,this._weight=1,this._offsetSeconds=0,this._firedEventValues=[]}release(){this._weight=0}updateParameters(t,e,i){if(!e.isAvailable()||e.isFinished())return;if(!e.isStarted()){e.setIsStarted(!0),e.setStartTime(i-this._offsetSeconds),e.setFadeInStartTime(i);const t=this.getDuration();e.getEndTime()<0&&e.setEndTime(t<=0?-1:e.getStartTime()+t)}let s=this._weight;s=s*(0==this._fadeInSeconds?1:gt.getEasingSine((i-e.getFadeInStartTime())/this._fadeInSeconds))*(0==this._fadeOutSeconds||e.getEndTime()<0?1:gt.getEasingSine((e.getEndTime()-i)/this._fadeOutSeconds)),e.setState(i,s),this.doUpdateParameters(t,i,s,e),e.getEndTime()>0&&e.getEndTime()(t[t.ExpressionBlendType_Add=0]="ExpressionBlendType_Add",t[t.ExpressionBlendType_Multiply=1]="ExpressionBlendType_Multiply",t[t.ExpressionBlendType_Overwrite=2]="ExpressionBlendType_Overwrite",t))(At||{});class Dt{constructor(){this._autoDelete=!1,this._available=!0,this._finished=!1,this._started=!1,this._startTimeSeconds=-1,this._fadeInStartTimeSeconds=0,this._endTimeSeconds=-1,this._stateTimeSeconds=0,this._stateWeight=0,this._lastEventCheckSeconds=0,this._motionQueueEntryHandle=this,this._fadeOutSeconds=0,this._isTriggeredFadeOut=!1}release(){this._autoDelete&&this._motion&&this._motion.release()}setFadeOut(t){this._fadeOutSeconds=t,this._isTriggeredFadeOut=!0}startFadeOut(t,e){const i=e+t;this._isTriggeredFadeOut=!0,(this._endTimeSeconds<0||inull!=e&&e._motionQueueEntryHandle==t))}setEventCallback(t,e=null){this._eventCallBack=t,this._eventCustomData=e}doUpdateMotion(t,e){let i=!1,s=0;for(;se.Name===t))}getExpressionFile(t){return t.File}createExpression(t,e){return Ft.create(t)}_setExpression(t){return this.queueManager.startMotion(t,!1,performance.now())}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.doUpdateMotion(t,e)}}class kt{constructor(t){this.groups=t.Groups,this.hitAreas=t.HitAreas,this.layout=t.Layout,this.moc=t.FileReferences.Moc,this.expressions=t.FileReferences.Expressions,this.motions=t.FileReferences.Motions,this.textures=t.FileReferences.Textures,this.physics=t.FileReferences.Physics,this.pose=t.FileReferences.Pose}getEyeBlinkParameters(){var t,e;return null==(e=null==(t=this.groups)?void 0:t.find((t=>"EyeBlink"===t.Name)))?void 0:e.Ids}getLipSyncParameters(){var t,e;return null==(e=null==(t=this.groups)?void 0:t.find((t=>"LipSync"===t.Name)))?void 0:e.Ids}}class Ut extends x{constructor(t){if(super(t),!Ut.isValidJSON(t))throw new TypeError("Invalid JSON.");Object.assign(this,new kt(t))}static isValidJSON(t){var e;return!!(null==t?void 0:t.FileReferences)&&"string"==typeof t.FileReferences.Moc&&(null==(e=t.FileReferences.Textures)?void 0:e.length)>0&&t.FileReferences.Textures.every((t=>"string"==typeof t))}replaceFiles(t){if(super.replaceFiles(t),this.motions)for(const[e,i]of Object.entries(this.motions))for(let s=0;s(t[t.CubismMotionCurveTarget_Model=0]="CubismMotionCurveTarget_Model",t[t.CubismMotionCurveTarget_Parameter=1]="CubismMotionCurveTarget_Parameter",t[t.CubismMotionCurveTarget_PartOpacity=2]="CubismMotionCurveTarget_PartOpacity",t))(Vt||{}),Nt=(t=>(t[t.CubismMotionSegmentType_Linear=0]="CubismMotionSegmentType_Linear",t[t.CubismMotionSegmentType_Bezier=1]="CubismMotionSegmentType_Bezier",t[t.CubismMotionSegmentType_Stepped=2]="CubismMotionSegmentType_Stepped",t[t.CubismMotionSegmentType_InverseStepped=3]="CubismMotionSegmentType_InverseStepped",t))(Nt||{});class Gt{constructor(t=0,e=0){this.time=t,this.value=e}}class Xt{constructor(){this.basePointIndex=0,this.segmentType=0}}class zt{constructor(){this.id="",this.type=0,this.segmentCount=0,this.baseSegmentIndex=0,this.fadeInTime=0,this.fadeOutTime=0}}class jt{constructor(){this.fireTime=0,this.value=""}}class Wt{constructor(){this.duration=0,this.loop=!1,this.curveCount=0,this.eventCount=0,this.fps=0,this.curves=[],this.segments=[],this.points=[],this.events=[]}}class Ht{constructor(t){this._json=t}release(){this._json=void 0}getMotionDuration(){return this._json.Meta.Duration}isMotionLoop(){return this._json.Meta.Loop||!1}getEvaluationOptionFlag(t){return Yt.EvaluationOptionFlag_AreBeziersRistricted==t&&!!this._json.Meta.AreBeziersRestricted}getMotionCurveCount(){return this._json.Meta.CurveCount}getMotionFps(){return this._json.Meta.Fps}getMotionTotalSegmentCount(){return this._json.Meta.TotalSegmentCount}getMotionTotalPointCount(){return this._json.Meta.TotalPointCount}getMotionFadeInTime(){return this._json.Meta.FadeInTime}getMotionFadeOutTime(){return this._json.Meta.FadeOutTime}getMotionCurveTarget(t){return this._json.Curves[t].Target}getMotionCurveId(t){return this._json.Curves[t].Id}getMotionCurveFadeInTime(t){return this._json.Curves[t].FadeInTime}getMotionCurveFadeOutTime(t){return this._json.Curves[t].FadeOutTime}getMotionCurveSegmentCount(t){return this._json.Curves[t].Segments.length}getMotionCurveSegment(t,e){return this._json.Curves[t].Segments[e]}getEventCount(){return this._json.Meta.UserDataCount||0}getTotalEventValueSize(){return this._json.Meta.TotalUserDataSize}getEventTime(t){return this._json.UserData[t].Time}getEventValue(t){return this._json.UserData[t].Value}}var Yt=(t=>(t[t.EvaluationOptionFlag_AreBeziersRistricted=0]="EvaluationOptionFlag_AreBeziersRistricted",t))(Yt||{});const qt="Opacity";function $t(t,e,i){const s=new Gt;return s.time=t.time+(e.time-t.time)*i,s.value=t.value+(e.value-t.value)*i,s}function Jt(t,e){let i=(e-t[0].time)/(t[1].time-t[0].time);return i<0&&(i=0),t[0].value+(t[1].value-t[0].value)*i}function Zt(t,e){let i=(e-t[0].time)/(t[3].time-t[0].time);i<0&&(i=0);const s=$t(t[0],t[1],i),r=$t(t[1],t[2],i),o=$t(t[2],t[3],i),a=$t(s,r,i),n=$t(r,o,i);return $t(a,n,i).value}function Qt(t,e){const i=e,s=t[0].time,r=t[3].time,o=t[1].time,a=t[2].time,n=r-3*a+3*o-s,l=3*a-6*o+3*s,h=3*o-3*s,u=s-i,d=gt.cardanoAlgorithmForBezier(n,l,h,u),c=$t(t[0],t[1],d),g=$t(t[1],t[2],d),m=$t(t[2],t[3],d),p=$t(c,g,d),_=$t(g,m,d);return $t(p,_,d).value}function Kt(t,e){return t[0].value}function te(t,e){return t[1].value}function ee(t,e,i){const s=t.curves[e];let r=-1;const o=s.baseSegmentIndex+s.segmentCount;let a=0;for(let l=s.baseSegmentIndex;li){r=l;break}if(-1==r)return t.points[a].value;const n=t.segments[r];return n.evaluate(t.points.slice(n.basePointIndex),i)}class ie extends Lt{constructor(){super(),this._eyeBlinkParameterIds=[],this._lipSyncParameterIds=[],this._sourceFrameRate=30,this._loopDurationSeconds=-1,this._isLoop=!1,this._isLoopFadeIn=!0,this._lastWeight=0,this._modelOpacity=1}static create(t,e){const i=new ie;return i.parse(t),i._sourceFrameRate=i._motionData.fps,i._loopDurationSeconds=i._motionData.duration,i._onFinishedMotion=e,i}doUpdateParameters(t,e,i,s){null==this._modelCurveIdEyeBlink&&(this._modelCurveIdEyeBlink="EyeBlink"),null==this._modelCurveIdLipSync&&(this._modelCurveIdLipSync="LipSync"),null==this._modelCurveIdOpacity&&(this._modelCurveIdOpacity=qt);let r=e-s.getStartTime();r<0&&(r=0);let a=Number.MAX_VALUE,n=Number.MAX_VALUE;const l=64;let h=0,u=0;this._eyeBlinkParameterIds.length>l&&St("too many eye blink targets : {0}",this._eyeBlinkParameterIds.length),this._lipSyncParameterIds.length>l&&St("too many lip sync targets : {0}",this._lipSyncParameterIds.length);const d=this._fadeInSeconds<=0?1:gt.getEasingSine((e-s.getFadeInStartTime())/this._fadeInSeconds),c=this._fadeOutSeconds<=0||s.getEndTime()<0?1:gt.getEasingSine((s.getEndTime()-e)/this._fadeOutSeconds);let g,m,p,_=r;if(this._isLoop)for(;_>this._motionData.duration;)_-=this._motionData.duration;const f=this._motionData.curves;for(m=0;m>o&1)continue;const s=e+(n-e)*i;t.setParameterValueById(this._eyeBlinkParameterIds[o],s)}if(a!=Number.MAX_VALUE)for(let o=0;o>o&1)continue;const s=e+(a-e)*i;t.setParameterValueById(this._lipSyncParameterIds[o],s)}for(;m=this._motionData.duration&&(this._isLoop?(s.setStartTime(e),this._isLoopFadeIn&&s.setFadeInStartTime(e)):(this._onFinishedMotion&&this._onFinishedMotion(this),s.setIsFinished(!0))),this._lastWeight=i}setIsLoop(t){this._isLoop=t}isLoop(){return this._isLoop}setIsLoopFadeIn(t){this._isLoopFadeIn=t}isLoopFadeIn(){return this._isLoopFadeIn}getDuration(){return this._isLoop?-1:this._loopDurationSeconds}getLoopDuration(){return this._loopDurationSeconds}setParameterFadeInTime(t,e){const i=this._motionData.curves;for(let s=0;snew zt)),this._motionData.segments=Array.from({length:e.getMotionTotalSegmentCount()}).map((()=>new Xt)),this._motionData.events=Array.from({length:this._motionData.eventCount}).map((()=>new jt)),this._motionData.points=[];let o=0,a=0;for(let n=0;nt&&this._motionData.events[i].fireTime<=e&&this._firedEventValues.push(this._motionData.events[i].value);return this._firedEventValues}isExistModelOpacity(){for(let t=0;t{this.emit("motion:"+e)}))}isFinished(){return this.queueManager.isFinished()}_startMotion(t,e){return t.setFinishedMotionHandler(e),this.queueManager.stopAllMotions(),this.queueManager.startMotion(t,!1,performance.now())}_stopAllMotions(){this.queueManager.stopAllMotions()}createMotion(e,i,s){const r=ie.create(e),o=new Ht(e),a=(i===this.groups.idle?t.config.idleMotionFadingDuration:t.config.motionFadingDuration)/1e3;return void 0===o.getMotionFadeInTime()&&r.setFadeInTime(s.FadeInTime>0?s.FadeInTime:a),void 0===o.getMotionFadeOutTime()&&r.setFadeOutTime(s.FadeOutTime>0?s.FadeOutTime:a),r.setEffectIds(this.eyeBlinkIds,this.lipSyncIds),r}getMotionFile(t){return t.File}getMotionName(t){return t.File}getSoundFile(t){return t.Sound}updateParameters(t,e){return this.queueManager.doUpdateMotion(t,e)}destroy(){super.destroy(),this.queueManager.release(),this.queueManager=void 0}}class re{constructor(){this._breathParameters=[],this._currentTime=0}static create(){return new re}setParameters(t){this._breathParameters=t}getParameters(){return this._breathParameters}updateParameters(t,e){this._currentTime+=e;const i=2*this._currentTime*3.14159;for(let s=0;s=1&&(s=1,this._blinkingState=le.EyeState_Closed,this._stateStartTimeSeconds=this._userTimeSeconds),i=1-s;break;case le.EyeState_Closed:s=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._closedSeconds,s>=1&&(this._blinkingState=le.EyeState_Opening,this._stateStartTimeSeconds=this._userTimeSeconds),i=0;break;case le.EyeState_Opening:s=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._openingSeconds,s>=1&&(s=1,this._blinkingState=le.EyeState_Interval,this._nextBlinkingTime=this.determinNextBlinkingTiming()),i=s;break;case le.EyeState_Interval:this._nextBlinkingTime(t[t.EyeState_First=0]="EyeState_First",t[t.EyeState_Interval=1]="EyeState_Interval",t[t.EyeState_Closing=2]="EyeState_Closing",t[t.EyeState_Closed=3]="EyeState_Closed",t[t.EyeState_Opening=4]="EyeState_Opening",t))(le||{});class he{constructor(t=0,e=0,i=0,s=0){this.x=t,this.y=e,this.width=i,this.height=s}getCenterX(){return this.x+.5*this.width}getCenterY(){return this.y+.5*this.height}getRight(){return this.x+this.width}getBottom(){return this.y+this.height}setRect(t){this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height}expand(t,e){this.x-=t,this.y-=e,this.width+=2*t,this.height+=2*e}}let ue,de,ce;class ge{getChannelFlagAsColor(t){return this._channelColors[t]}getMaskRenderTexture(){if(this._maskTexture&&null!=this._maskTexture.textures)this._maskTexture.frameNo=this._currentFrameNo;else{this._maskRenderTextures=[],this._maskColorBuffers=[];const t=this._clippingMaskBufferSize;for(let e=0;ec&&(c=e),ig&&(g=i)}if(u!=Number.MAX_VALUE)if(ur&&(r=c),g>o&&(o=g),i==Number.MAX_VALUE)e._allClippedDrawRect.x=0,e._allClippedDrawRect.y=0,e._allClippedDrawRect.width=0,e._allClippedDrawRect.height=0,e._isUsing=!1;else{e._isUsing=!0;const t=r-i,a=o-s;e._allClippedDrawRect.x=i,e._allClippedDrawRect.y=s,e._allClippedDrawRect.width=t,e._allClippedDrawRect.height=a}}}constructor(){this._currentMaskRenderTexture=null,this._currentFrameNo=0,this._renderTextureCount=0,this._clippingMaskBufferSize=256,this._clippingContextListForMask=[],this._clippingContextListForDraw=[],this._channelColors=[],this._tmpBoundsOnModel=new he,this._tmpMatrix=new mt,this._tmpMatrixForMask=new mt,this._tmpMatrixForDraw=new mt;let t=new ft;t.R=1,t.G=0,t.B=0,t.A=0,this._channelColors.push(t),t=new ft,t.R=0,t.G=1,t.B=0,t.A=0,this._channelColors.push(t),t=new ft,t.R=0,t.G=0,t.B=1,t.A=0,this._channelColors.push(t),t=new ft,t.R=0,t.G=0,t.B=0,t.A=1,this._channelColors.push(t)}release(){var t;const e=this;for(let i=0;i0){this.setupLayoutBounds(e.isUsingHighPrecisionMask()?0:i),e.isUsingHighPrecisionMask()||(this.gl.viewport(0,0,this._clippingMaskBufferSize,this._clippingMaskBufferSize),this._currentMaskRenderTexture=this.getMaskRenderTexture()[0],e.preDraw(),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this._currentMaskRenderTexture)),this._clearedFrameBufferflags||(this._clearedFrameBufferflags=[]);for(let t=0;th?(this._tmpBoundsOnModel.expand(r.width*a,0),n=o.width/this._tmpBoundsOnModel.width):n=e/h,this._tmpBoundsOnModel.height*e>u?(this._tmpBoundsOnModel.expand(0,r.height*a),l=o.height/this._tmpBoundsOnModel.height):l=e/u}else this._tmpBoundsOnModel.setRect(r),this._tmpBoundsOnModel.expand(r.width*a,r.height*a),n=o.width/this._tmpBoundsOnModel.width,l=o.height/this._tmpBoundsOnModel.height;if(this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(-1,-1),this._tmpMatrix.scaleRelative(2,2),this._tmpMatrix.translateRelative(o.x,o.y),this._tmpMatrix.scaleRelative(n,l),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForMask.setMatrix(this._tmpMatrix.getArray()),this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(o.x,o.y),this._tmpMatrix.scaleRelative(n,l),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForDraw.setMatrix(this._tmpMatrix.getArray()),s._matrixForMask.setMatrix(this._tmpMatrixForMask.getArray()),s._matrixForDraw.setMatrix(this._tmpMatrixForDraw.getArray()),!e.isUsingHighPrecisionMask()){const i=s._clippingIdCount;for(let r=0;re){t>e&&Tt("not supported mask count : {0}\n[Details] render texture count : {1}, mask count : {2}",t-e,this._renderTextureCount,t);for(let t=0;t=4?0:n+1;if(u(t[t.ShaderNames_SetupMask=0]="ShaderNames_SetupMask",t[t.ShaderNames_NormalPremultipliedAlpha=1]="ShaderNames_NormalPremultipliedAlpha",t[t.ShaderNames_NormalMaskedPremultipliedAlpha=2]="ShaderNames_NormalMaskedPremultipliedAlpha",t[t.ShaderNames_NomralMaskedInvertedPremultipliedAlpha=3]="ShaderNames_NomralMaskedInvertedPremultipliedAlpha",t[t.ShaderNames_AddPremultipliedAlpha=4]="ShaderNames_AddPremultipliedAlpha",t[t.ShaderNames_AddMaskedPremultipliedAlpha=5]="ShaderNames_AddMaskedPremultipliedAlpha",t[t.ShaderNames_AddMaskedPremultipliedAlphaInverted=6]="ShaderNames_AddMaskedPremultipliedAlphaInverted",t[t.ShaderNames_MultPremultipliedAlpha=7]="ShaderNames_MultPremultipliedAlpha",t[t.ShaderNames_MultMaskedPremultipliedAlpha=8]="ShaderNames_MultMaskedPremultipliedAlpha",t[t.ShaderNames_MultMaskedPremultipliedAlphaInverted=9]="ShaderNames_MultMaskedPremultipliedAlphaInverted",t))(xe||{});const ye="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_myPos;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_clipMatrix * a_position; v_myPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",Me="precision mediump float;varying vec2 v_texCoord;varying vec4 v_myPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;void main(){ float isInside = step(u_baseColor.x, v_myPos.x/v_myPos.w) * step(u_baseColor.y, v_myPos.y/v_myPos.w) * step(v_myPos.x/v_myPos.w, u_baseColor.z) * step(v_myPos.y/v_myPos.w, u_baseColor.w); gl_FragColor = u_channelFlag * texture2D(s_texture0, v_texCoord).a * isInside;}",Ce="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;uniform mat4 u_matrix;void main(){ gl_Position = u_matrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",ve="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform mat4 u_matrix;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_matrix * a_position; v_clipPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",Pe="precision mediump float;varying vec2 v_texCoord;uniform vec4 u_baseColor;uniform sampler2D s_texture0;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 color = texColor * u_baseColor; gl_FragColor = vec4(color.rgb, color.a);}",be="precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;uniform sampler2D s_texture1;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 col_formask = texColor * u_baseColor; vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag; float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a; col_formask = col_formask * maskVal; gl_FragColor = col_formask;}",Se="precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform sampler2D s_texture0;uniform sampler2D s_texture1;uniform vec4 u_channelFlag;uniform vec4 u_baseColor;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 col_formask = texColor * u_baseColor; vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag; float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a; col_formask = col_formask * (1.0 - maskVal); gl_FragColor = col_formask;}";class we extends pt{constructor(){super(),this._clippingContextBufferForMask=null,this._clippingContextBufferForDraw=null,this._rendererProfile=new _e,this.firstDraw=!0,this._textures={},this._sortedDrawableIndexList=[],this._bufferData={vertex:null,uv:null,index:null}}initialize(t,e=1){t.isUsingMasking()&&(this._clippingManager=new ge,this._clippingManager.initialize(t,t.getDrawableCount(),t.getDrawableMasks(),t.getDrawableMaskCounts(),e));for(let i=t.getDrawableCount()-1;i>=0;i--)this._sortedDrawableIndexList[i]=0;super.initialize(t)}bindTexture(t,e){this._textures[t]=e}getBindedTextures(){return this._textures}setClippingMaskBufferSize(t){if(!this._model.isUsingMasking())return;const e=this._clippingManager.getRenderTextureCount();this._clippingManager.release(),this._clippingManager=new ge,this._clippingManager.setClippingMaskBufferSize(t),this._clippingManager.initialize(this.getModel(),this.getModel().getDrawableCount(),this.getModel().getDrawableMasks(),this.getModel().getDrawableMaskCounts(),e)}getClippingMaskBufferSize(){return this._model.isUsingMasking()?this._clippingManager.getClippingMaskBufferSize():-1}getRenderTextureCount(){return this._model.isUsingMasking()?this._clippingManager.getRenderTextureCount():-1}release(){var t,e,i;const s=this;this._clippingManager.release(),s._clippingManager=void 0,null==(t=this.gl)||t.deleteBuffer(this._bufferData.vertex),this._bufferData.vertex=null,null==(e=this.gl)||e.deleteBuffer(this._bufferData.uv),this._bufferData.uv=null,null==(i=this.gl)||i.deleteBuffer(this._bufferData.index),this._bufferData.index=null,s._bufferData=void 0,s._textures=void 0}doDrawModel(){if(null==this.gl)return void Tt("'gl' is null. WebGLRenderingContext is required.\nPlease call 'CubimRenderer_WebGL.startUp' function.");null!=this._clippingManager&&(this.preDraw(),this._clippingManager.setupClippingContext(this.getModel(),this)),this.preDraw();const t=this.getModel().getDrawableCount(),e=this.getModel().getDrawableRenderOrders();for(let i=0;i0&&this._extension)for(const t of Object.entries(this._textures))this.gl.bindTexture(this.gl.TEXTURE_2D,t),this.gl.texParameterf(this.gl.TEXTURE_2D,this._extension.TEXTURE_MAX_ANISOTROPY_EXT,this.getAnisotropy())}setClippingContextBufferForMask(t){this._clippingContextBufferForMask=t}getClippingContextBufferForMask(){return this._clippingContextBufferForMask}setClippingContextBufferForDraw(t){this._clippingContextBufferForDraw=t}getClippingContextBufferForDraw(){return this._clippingContextBufferForDraw}startUp(t){this.gl=t,this._clippingManager&&this._clippingManager.setGL(t),fe.getInstance().setGl(t),this._rendererProfile.setGl(t),this._extension=this.gl.getExtension("EXT_texture_filter_anisotropic")||this.gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this.gl.getExtension("MOZ_EXT_texture_filter_anisotropic")}}pt.staticRelease=()=>{we.doStaticRelease()};const Ie=new mt;class Te extends S{constructor(t,e,s){super(),this.lipSync=!0,this.breath=re.create(),this.renderer=new we,this.idParamAngleX="ParamAngleX",this.idParamAngleY="ParamAngleY",this.idParamAngleZ="ParamAngleZ",this.idParamEyeBallX="ParamEyeBallX",this.idParamEyeBallY="ParamEyeBallY",this.idParamBodyAngleX="ParamBodyAngleX",this.idParamBreath="ParamBreath",this.pixelsPerUnit=1,this.centeringTransform=new i.Matrix,this.coreModel=t,this.settings=e,this.motionManager=new se(e,s),this.init()}init(){var t;super.init(),(null==(t=this.settings.getEyeBlinkParameters())?void 0:t.length)>0&&(this.eyeBlink=ne.create(this.settings)),this.breath.setParameters([new oe(this.idParamAngleX,0,15,6.5345,.5),new oe(this.idParamAngleY,0,8,3.5345,.5),new oe(this.idParamAngleZ,0,10,5.5345,.5),new oe(this.idParamBodyAngleX,0,4,15.5345,.5),new oe(this.idParamBreath,0,.5,3.2345,.5)]),this.renderer.initialize(this.coreModel),this.renderer.setIsPremultipliedAlpha(!0)}getSize(){return[this.coreModel.getModel().canvasinfo.CanvasWidth,this.coreModel.getModel().canvasinfo.CanvasHeight]}getLayout(){const t={};if(this.settings.layout)for(const e of Object.keys(this.settings.layout)){t[e.charAt(0).toLowerCase()+e.slice(1)]=this.settings.layout[e]}return t}setupLayout(){super.setupLayout(),this.pixelsPerUnit=this.coreModel.getModel().canvasinfo.PixelsPerUnit,this.centeringTransform.scale(this.pixelsPerUnit,this.pixelsPerUnit).translate(this.originalWidth/2,this.originalHeight/2)}updateWebGLContext(t,e){this.renderer.firstDraw=!0,this.renderer._bufferData={vertex:null,uv:null,index:null},this.renderer.startUp(t),this.renderer._clippingManager._currentFrameNo=e,this.renderer._clippingManager._maskTexture=void 0,fe.getInstance()._shaderSets=[]}bindTexture(t,e){this.renderer.bindTexture(t,e)}getHitAreaDefs(){var t,e;return null!=(e=null==(t=this.settings.hitAreas)?void 0:t.map((t=>({id:t.Id,name:t.Name,index:this.coreModel.getDrawableIndex(t.Id)}))))?e:[]}getDrawableIDs(){return this.coreModel.getDrawableIds()}getDrawableIndex(t){return this.coreModel.getDrawableIndex(t)}getDrawableVertices(t){if("string"==typeof t&&-1===(t=this.coreModel.getDrawableIndex(t)))throw new TypeError("Unable to find drawable ID: "+t);const e=this.coreModel.getDrawableVertices(t).slice();for(let i=0;i{!function i(){try{Ae(),t()}catch(s){if(Le--,Le<0){const t=new Error("Failed to start up Cubism 4 framework.");return t.cause=s,void e(t)}l.log("Cubism4","Startup failed, retrying 10ms later..."),setTimeout(i,10)}}()}))),Ee)}function Ae(t){t=Object.assign({logFunction:console.log,loggingLevel:bt.LogLevel_Verbose},t),Pt.startUp(t),Pt.initialize()}class De{static create(t){const e=new De;"number"==typeof t.FadeInTime&&(e._fadeTimeSeconds=t.FadeInTime,e._fadeTimeSeconds<=0&&(e._fadeTimeSeconds=.5));const i=t.Groups,s=i.length;for(let r=0;r.001){if(r>=0)break;r=n,o=t.getPartOpacityByIndex(i),o+=e/this._fadeTimeSeconds,o>1&&(o=1)}}r<0&&(r=0,o=1);for(let n=i;n.15&&(i=1-.15/(1-o)),s>i&&(s=i),t.setPartOpacityByIndex(e,s)}}}constructor(){this._fadeTimeSeconds=.5,this._lastModel=void 0,this._partGroups=[],this._partGroupCounts=[]}}class Re{constructor(t){this.parameterIndex=0,this.partIndex=0,this.partId="",this.link=[],null!=t&&this.assignment(t)}assignment(t){return this.partId=t.partId,this.link=t.link.map((t=>t.clone())),this}initialize(t){this.parameterIndex=t.getParameterIndex(this.partId),this.partIndex=t.getPartIndex(this.partId),t.setParameterValueByIndex(this.parameterIndex,1)}clone(){const t=new Re;return t.partId=this.partId,t.parameterIndex=this.parameterIndex,t.partIndex=this.partIndex,t.link=this.link.map((t=>t.clone())),t}}class Be{constructor(t=!1,e=new ft){this.isOverwritten=t,this.Color=e}}class Oe{constructor(t=!1,e=new ft){this.isOverwritten=t,this.Color=e}}class ke{constructor(t=!1,e=!1){this.isOverwritten=t,this.isCulling=e}}class Ue{update(){this._model.update(),this._model.drawables.resetDynamicFlags()}getPixelsPerUnit(){return null==this._model?0:this._model.canvasinfo.PixelsPerUnit}getCanvasWidth(){return null==this._model?0:this._model.canvasinfo.CanvasWidth/this._model.canvasinfo.PixelsPerUnit}getCanvasHeight(){return null==this._model?0:this._model.canvasinfo.CanvasHeight/this._model.canvasinfo.PixelsPerUnit}saveParameters(){const t=this._model.parameters.count,e=this._savedParameters.length;for(let i=0;ie&&(e=this._model.parameters.minimumValues[t]),this._parameterValues[t]=1==i?e:this._parameterValues[t]=this._parameterValues[t]*(1-i)+e*i)}setParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.setParameterValueByIndex(s,e,i)}addParameterValueByIndex(t,e,i=1){this.setParameterValueByIndex(t,this.getParameterValueByIndex(t)+e*i)}addParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.addParameterValueByIndex(s,e,i)}multiplyParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.multiplyParameterValueByIndex(s,e,i)}multiplyParameterValueByIndex(t,e,i=1){this.setParameterValueByIndex(t,this.getParameterValueByIndex(t)*(1+(e-1)*i))}getDrawableIds(){return this._drawableIds.slice()}getDrawableIndex(t){const e=this._model.drawables.count;for(let i=0;ie&&(t=e);for(let i=0;i=0&&this._partChildDrawables[n].push(t)}}}constructor(t){this._model=t,this._savedParameters=[],this._parameterIds=[],this._drawableIds=[],this._partIds=[],this._isOverwrittenModelMultiplyColors=!1,this._isOverwrittenModelScreenColors=!1,this._isOverwrittenCullings=!1,this._modelOpacity=1,this._userMultiplyColors=[],this._userScreenColors=[],this._userCullings=[],this._userPartMultiplyColors=[],this._userPartScreenColors=[],this._partChildDrawables=[],this._notExistPartId={},this._notExistParameterId={},this._notExistParameterValues={},this._notExistPartOpacities={},this.initialize()}release(){this._model.release(),this._model=void 0}}class Ve{static create(t,e){if(e){if(!this.hasMocConsistency(t))throw new Error("Inconsistent MOC3.")}const i=Live2DCubismCore.Moc.fromArrayBuffer(t);if(i){const e=new Ve(i);return e._mocVersion=Live2DCubismCore.Version.csmGetMocVersion(i,t),e}throw new Error("Failed to CubismMoc.create().")}createModel(){let t;const e=Live2DCubismCore.Model.fromMoc(this._moc);if(e)return t=new Ue(e),++this._modelCount,t;throw new Error("Unknown error")}deleteModel(t){null!=t&&--this._modelCount}constructor(t){this._moc=t,this._modelCount=0,this._mocVersion=0}release(){this._moc._release(),this._moc=void 0}getLatestMocVersion(){return Live2DCubismCore.Version.csmGetLatestMocVersion()}getMocVersion(){return this._mocVersion}static hasMocConsistency(t){return 1===Live2DCubismCore.Moc.prototype.hasMocConsistency(t)}}var Ne=(t=>(t[t.CubismPhysicsTargetType_Parameter=0]="CubismPhysicsTargetType_Parameter",t))(Ne||{}),Ge=(t=>(t[t.CubismPhysicsSource_X=0]="CubismPhysicsSource_X",t[t.CubismPhysicsSource_Y=1]="CubismPhysicsSource_Y",t[t.CubismPhysicsSource_Angle=2]="CubismPhysicsSource_Angle",t))(Ge||{});class Xe{constructor(){this.initialPosition=new dt(0,0),this.position=new dt(0,0),this.lastPosition=new dt(0,0),this.lastGravity=new dt(0,0),this.force=new dt(0,0),this.velocity=new dt(0,0)}}class ze{constructor(){this.normalizationPosition={},this.normalizationAngle={}}}class je{constructor(){this.source={}}}class We{constructor(){this.destination={},this.translationScale=new dt(0,0)}}class He{constructor(){this.settings=[],this.inputs=[],this.outputs=[],this.particles=[],this.gravity=new dt(0,0),this.wind=new dt(0,0),this.fps=0}}class Ye{constructor(t){this._json=t}release(){this._json=void 0}getGravity(){const t=new dt(0,0);return t.x=this._json.Meta.EffectiveForces.Gravity.X,t.y=this._json.Meta.EffectiveForces.Gravity.Y,t}getWind(){const t=new dt(0,0);return t.x=this._json.Meta.EffectiveForces.Wind.X,t.y=this._json.Meta.EffectiveForces.Wind.Y,t}getFps(){return this._json.Meta.Fps||0}getSubRigCount(){return this._json.Meta.PhysicsSettingCount}getTotalInputCount(){return this._json.Meta.TotalInputCount}getTotalOutputCount(){return this._json.Meta.TotalOutputCount}getVertexCount(){return this._json.Meta.VertexCount}getNormalizationPositionMinimumValue(t){return this._json.PhysicsSettings[t].Normalization.Position.Minimum}getNormalizationPositionMaximumValue(t){return this._json.PhysicsSettings[t].Normalization.Position.Maximum}getNormalizationPositionDefaultValue(t){return this._json.PhysicsSettings[t].Normalization.Position.Default}getNormalizationAngleMinimumValue(t){return this._json.PhysicsSettings[t].Normalization.Angle.Minimum}getNormalizationAngleMaximumValue(t){return this._json.PhysicsSettings[t].Normalization.Angle.Maximum}getNormalizationAngleDefaultValue(t){return this._json.PhysicsSettings[t].Normalization.Angle.Default}getInputCount(t){return this._json.PhysicsSettings[t].Input.length}getInputWeight(t,e){return this._json.PhysicsSettings[t].Input[e].Weight}getInputReflect(t,e){return this._json.PhysicsSettings[t].Input[e].Reflect}getInputType(t,e){return this._json.PhysicsSettings[t].Input[e].Type}getInputSourceId(t,e){return this._json.PhysicsSettings[t].Input[e].Source.Id}getOutputCount(t){return this._json.PhysicsSettings[t].Output.length}getOutputVertexIndex(t,e){return this._json.PhysicsSettings[t].Output[e].VertexIndex}getOutputAngleScale(t,e){return this._json.PhysicsSettings[t].Output[e].Scale}getOutputWeight(t,e){return this._json.PhysicsSettings[t].Output[e].Weight}getOutputDestinationId(t,e){return this._json.PhysicsSettings[t].Output[e].Destination.Id}getOutputType(t,e){return this._json.PhysicsSettings[t].Output[e].Type}getOutputReflect(t,e){return this._json.PhysicsSettings[t].Output[e].Reflect}getParticleCount(t){return this._json.PhysicsSettings[t].Vertices.length}getParticleMobility(t,e){return this._json.PhysicsSettings[t].Vertices[e].Mobility}getParticleDelay(t,e){return this._json.PhysicsSettings[t].Vertices[e].Delay}getParticleAcceleration(t,e){return this._json.PhysicsSettings[t].Vertices[e].Acceleration}getParticleRadius(t,e){return this._json.PhysicsSettings[t].Vertices[e].Radius}getParticlePosition(t,e){const i=new dt(0,0);return i.x=this._json.PhysicsSettings[t].Vertices[e].Position.X,i.y=this._json.PhysicsSettings[t].Vertices[e].Position.Y,i}}const qe="Angle";class $e{static create(t){const e=new $e;return e.parse(t),e._physicsRig.gravity.y=0,e}static delete(t){null!=t&&t.release()}parse(t){this._physicsRig=new He;const e=new Ye(t);this._physicsRig.gravity=e.getGravity(),this._physicsRig.wind=e.getWind(),this._physicsRig.subRigCount=e.getSubRigCount(),this._physicsRig.fps=e.getFps(),this._currentRigOutputs=[],this._previousRigOutputs=[];let i=0,s=0,r=0;for(let o=0;o=u.particleCount)continue;let s=new dt;s=g[i].position.substract(g[i-1].position),l=c[e].getValue(s,g,i,c[e].reflect,this._options.gravity),this._currentRigOutputs[x].outputs[e]=l,this._previousRigOutputs[x].outputs[e]=l;const r=c[e].destinationParameterIndex,o=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(m.subarray(r))):m.slice(r);ui(o,_[r],p[r],l,c[e]);for(let t=r,e=0;t=e)return;if(this._currentRemainTime+=e,this._currentRemainTime>5&&(this._currentRemainTime=0),p=t.getModel().parameters.values,_=t.getModel().parameters.maximumValues,f=t.getModel().parameters.minimumValues,x=t.getModel().parameters.defaultValues,(null!=(s=null==(i=this._parameterCaches)?void 0:i.length)?s:0)0?1/this._physicsRig.fps:e;this._currentRemainTime>=y;){for(let t=0;t=d.particleCount)continue;const r=new dt;r.x=m[s].position.x-m[s-1].position.x,r.y=m[s].position.y-m[s-1].position.y,h=g[e].getValue(r,m,s,g[e].reflect,this._options.gravity),this._currentRigOutputs[i].outputs[e]=h;const o=g[e].destinationParameterIndex,a=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(this._parameterCaches.subarray(o))):this._parameterCaches.slice(o);ui(a,f[o],_[o],h,g[e]);for(let t=o,e=0;t=2?e[i-1].position.substract(e[i-2].position):r.multiplyByScaler(-1),o=gt.directionToRadian(r,t),s&&(o*=-1),o}function ri(t,e){return Math.min(t,e)+function(t,e){return Math.abs(Math.max(t,e)-Math.min(t,e))}(t,e)/2}function oi(t,e){return t.x}function ai(t,e){return t.y}function ni(t,e){return e}function li(t,e,i,s,r,o,a,n){let l,h,u,d,c=new dt(0,0),g=new dt(0,0),m=new dt(0,0),p=new dt(0,0);t[0].position=new dt(i.x,i.y),l=gt.degreesToRadian(s),d=gt.radianToDirection(l),d.normalize();for(let _=1;_i&&(a>r.valueExceededMaximum&&(r.valueExceededMaximum=a),a=i),n=r.weight/100,n>=1||(a=t[0]*(1-n)+a*n),t[0]=a}function di(t,e,i,s,r,o,a,n){let l=0;const h=gt.max(i,e);ht&&(t=u);const d=gt.min(r,o),c=gt.max(r,o),g=a,m=ri(u,h),p=t-m;switch(Math.sign(p)){case 1:{const t=c-g,e=h-m;0!=e&&(l=p*(t/e),l+=g);break}case-1:{const t=d-g,e=u-m;0!=e&&(l=p*(t/e),l+=g);break}case 0:l=g}return n?l:-1*l}function ci(){var t;null==(t=this.__moc)||t.release()}V.registerRuntime({version:4,ready:Fe,test:t=>t instanceof Ut||Ut.isValidJSON(t),isValidMoc(t){if(t.byteLength<4)return!1;const e=new Int8Array(t,0,4);return"MOC3"===String.fromCharCode(...e)},createModelSettings:t=>new Ut(t),createCoreModel(t,e){const i=Ve.create(t,!!(null==e?void 0:e.checkMocConsistency));try{const t=i.createModel();return t.__moc=i,t}catch(s){try{i.release()}catch(r){}throw s}},createInternalModel(t,e,i){const s=new Te(t,e,i),r=t;return r.__moc&&(s.__moc=r.__moc,delete r.__moc,s.once("destroy",ci)),s},createPhysics:(t,e)=>$e.create(e),createPose:(t,e)=>De.create(e)}),t.Cubism2ExpressionManager=tt,t.Cubism2InternalModel=rt,t.Cubism2ModelSettings=ot,t.Cubism2MotionManager=et,t.Cubism4ExpressionManager=Ot,t.Cubism4InternalModel=Te,t.Cubism4ModelSettings=Ut,t.Cubism4MotionManager=se,t.ExpressionManager=_,t.FileLoader=$,t.FocusController=f,t.InteractionMixin=N,t.InternalModel=S,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DExpression=K,t.Live2DEyeBlink=it,t.Live2DFactory=V,t.Live2DLoader=L,t.Live2DModel=Y,t.Live2DPhysics=lt,t.Live2DPose=ut,t.Live2DTransform=z,t.ModelSettings=x,t.MotionManager=P,t.MotionPreloadStrategy=v,t.MotionPriority=y,t.MotionState=M,t.SoundManager=C,t.VERSION="0.4.0",t.XHRLoader=T,t.ZipLoader=Z,t.applyMixins=g,t.clamp=h,t.copyArray=c,t.copyProperty=d,t.cubism4Ready=Fe,t.folderName=m,t.logger=l,t.rand=u,t.remove=p,t.startUpCubism4=Ae,Object.defineProperties(t,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})); +var __pow=Math.pow,__async=(t,e,i)=>new Promise(((s,r)=>{var o=t=>{try{n(i.next(t))}catch(e){r(e)}},a=t=>{try{n(i.throw(t))}catch(e){r(e)}},n=t=>t.done?s(t.value):Promise.resolve(t.value).then(o,a);n((i=i.apply(t,e)).next())}));!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("@pixi/utils"),require("@pixi/math"),require("@pixi/core"),require("@pixi/display")):"function"==typeof define&&define.amd?define(["exports","@pixi/utils","@pixi/math","@pixi/core","@pixi/display"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).PIXI=t.PIXI||{},t.PIXI.live2d=t.PIXI.live2d||{}),t.PIXI.utils,t.PIXI,t.PIXI,t.PIXI)}(this,(function(t,e,i,s,r){"use strict";var o,a,n;(a=o||(o={})).supportMoreMaskDivisions=!0,a.setOpacityFromMotion=!1,t.config=void 0,(n=t.config||(t.config={})).LOG_LEVEL_VERBOSE=0,n.LOG_LEVEL_WARNING=1,n.LOG_LEVEL_ERROR=2,n.LOG_LEVEL_NONE=999,n.logLevel=n.LOG_LEVEL_WARNING,n.sound=!0,n.motionSync=!0,n.motionFadingDuration=500,n.idleMotionFadingDuration=2e3,n.expressionFadingDuration=500,n.preserveExpressionOnMotion=!0,n.cubism4=o;const l={log(e,...i){t.config.logLevel<=t.config.LOG_LEVEL_VERBOSE&&console.log(`[${e}]`,...i)},warn(e,...i){t.config.logLevel<=t.config.LOG_LEVEL_WARNING&&console.warn(`[${e}]`,...i)},error(e,...i){t.config.logLevel<=t.config.LOG_LEVEL_ERROR&&console.error(`[${e}]`,...i)}};function h(t,e,i){return ti?i:t}function u(t,e){return Math.random()*(e-t)+t}function d(t,e,i,s,r){const o=e[s];null!==o&&typeof o===t&&(i[r]=o)}function c(t,e,i,s,r){const o=e[s];Array.isArray(o)&&(i[r]=o.filter((e=>null!==e&&typeof e===t)))}function g(t,e){e.forEach((e=>{Object.getOwnPropertyNames(e.prototype).forEach((i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i))}))}))}function m(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 p(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}class _ extends e.EventEmitter{constructor(t,e){super(),this.expressions=[],this.reserveExpressionIndex=-1,this.destroyed=!1,this.settings=t,this.tag=`ExpressionManager(${t.name})`}init(){this.defaultExpression=this.createExpression({},void 0),this.currentExpression=this.defaultExpression,this.stopAllExpressions()}loadExpression(t){return __async(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 __async(this,null,(function*(){if(this.definitions.length){const t=[];for(let e=0;e-1&&tl&&(o*=l/n,a*=l/n),this.vx+=o,this.vy+=a;const h=Math.sqrt(__pow(this.vx,2)+__pow(this.vy,2)),u=.5*(Math.sqrt(__pow(l,2)+8*l*s)-l);h>u&&(this.vx*=u/h,this.vy*=u/h),this.x+=this.vx,this.y+=this.vy}}class x{constructor(t){this.json=t;let e=t.url;if("string"!=typeof e)throw new TypeError("The `url` field in settings JSON must be defined as a string.");this.url=e,this.name=m(this.url)}resolveURL(t){return e.url.resolve(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(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 y=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(y||{});class M{constructor(){this.debug=!1,this.currentPriority=0,this.reservePriority=0}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!t.config.preserveExpressionOnMotion&&this.currentPriority>1}dump(t,e){if(this.debug){return`\n group = "${t}", index = ${e}\n`+["currentPriority","reservePriority","currentGroup","currentIndex","reservedGroup","reservedIndex","reservedIdleGroup","reservedIdleIndex"].map((t=>"["+t+"] "+this[t])).join("\n")}return""}}class C{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,i){const s=new Audio(t);return s.volume=this._volume,s.preload="auto",s.autoplay=!0,s.crossOrigin="anonymous",s.addEventListener("ended",(()=>{this.dispose(s),null==e||e()})),s.addEventListener("error",(e=>{this.dispose(s),l.warn("SoundManager",`Error occurred on "${t}"`,e.error),null==i||i(e.error)})),this.audios.push(s),s}static play(t){return new Promise(((e,i)=>{var s;null==(s=t.play())||s.catch((e=>{t.dispatchEvent(new ErrorEvent("error",{error:e})),i(e)})),t.readyState===t.HAVE_ENOUGH_DATA?e():t.addEventListener("canplaythrough",e)}))}static addContext(t){const e=new AudioContext;return this.contexts.push(e),e}static addAnalyzer(t,e){const i=e.createMediaElementSource(t),s=e.createAnalyser();return s.fftSize=256,s.minDecibels=-90,s.maxDecibels=-10,s.smoothingTimeConstant=.85,i.connect(s),s.connect(e.destination),this.analysers.push(s),s}static analyze(t){if(null!=t){let e=new Float32Array(t.fftSize),i=0;t.getFloatTimeDomainData(e);for(const t of e)i+=t*t;return parseFloat(Math.sqrt(i/e.length*20).toFixed(1))}return parseFloat(Math.random().toFixed(1))}static dispose(t){t.pause(),t.removeAttribute("src"),p(this.audios,t)}static destroy(){for(let t=this.contexts.length-1;t>=0;t--)this.contexts[t].close();for(let t=this.audios.length-1;t>=0;t--)this.dispose(this.audios[t])}}C.audios=[],C.analysers=[],C.contexts=[],C._volume=.9;var v=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(v||{});class P extends e.EventEmitter{constructor(t,e){super(),this.motionGroups={},this.state=new M,this.playing=!1,this.destroyed=!1,this.settings=t,this.tag=`MotionManager(${t.name})`,this.state.tag=this.tag}init(t){(null==t?void 0:t.idleMotionGroup)&&(this.groups.idle=t.idleMotionGroup),this.setupMotions(t),this.stopAllMotions()}setupMotions(t){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)if(this.definitions[i])for(let t=0;t{r&&s&&g.expressionManager&&g.expressionManager.resetExpression(),g.currentAudio=void 0}),(()=>{r&&s&&g.expressionManager&&g.expressionManager.resetExpression(),g.currentAudio=void 0})),this.currentAudio=o;let t=1;void 0!==i&&(t=i),C.volume=t,n=C.addContext(this.currentAudio),this.currentContext=n,a=C.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=a}catch(m){l.warn(this.tag,"Failed to create audio",h,m)}if(o){const e=C.play(o).catch((t=>l.warn(this.tag,"Failed to play audio",o.src,t)));t.config.motionSync&&(yield e)}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),s&&this.expressionManager&&this.expressionManager.setExpression(s),this.playing=!0,!0}))}startMotion(e,i){return __async(this,arguments,(function*(e,i,s=y.NORMAL,{sound:r,volume:o=1,expression:a,resetExpression:n=!0}={}){var h;if(this.currentAudio&&!this.currentAudio.ended)return!1;if(!this.state.reserve(e,i,s))return!1;const u=null==(h=this.definitions[e])?void 0:h[i];if(!u)return!1;let d,c,g;if(this.currentAudio&&C.dispose(this.currentAudio),t.config.sound){const t=r&&r.startsWith("data:audio/wav;base64");if(r&&!t){var m=document.createElement("a");m.href=r,r=m.href}const e=r&&(r.startsWith("http")||r.startsWith("blob")),i=this.getSoundFile(u);let s=i;i&&(s=this.settings.resolveURL(i)+"?cache-buster="+(new Date).getTime()),(e||t)&&(s=r);const h=this;if(s)try{d=C.add(s,(()=>{n&&a&&h.expressionManager&&h.expressionManager.resetExpression(),h.currentAudio=void 0}),(()=>{n&&a&&h.expressionManager&&h.expressionManager.resetExpression(),h.currentAudio=void 0})),this.currentAudio=d;let t=1;void 0!==o&&(t=o),C.volume=t,g=C.addContext(this.currentAudio),this.currentContext=g,c=C.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=c}catch(_){l.warn(this.tag,"Failed to create audio",i,_)}}const p=yield this.loadMotion(e,i);if(d){s=3;const e=C.play(d).catch((t=>l.warn(this.tag,"Failed to play audio",d.src,t)));t.config.motionSync&&(yield e)}return this.state.start(p,e,i,s)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),l.log(this.tag,"Start motion:",this.getMotionName(u)),this.emit("motionStart",e,i,d),a&&this.expressionManager&&this.expressionManager.setExpression(a),this.playing=!0,this._startMotion(p),!0):(d&&(C.dispose(d),this.currentAudio=void 0),!1)}))}startRandomMotion(t,e){return __async(this,arguments,(function*(t,e,{sound:i,volume:s=1,expression:r,resetExpression:o=!0}={}){const a=this.definitions[t];if(null==a?void 0:a.length){const n=[];for(let e=0;et.index>=0));for(const e of t)this.hitAreas[e.name]=e}hitTest(t,e){return Object.keys(this.hitAreas).filter((i=>this.isHit(i,t,e)))}isHit(t,e,i){if(!this.hitAreas[t])return!1;const s=this.hitAreas[t].index,r=this.getDrawableBounds(s,b);return r.x<=e&&e<=r.x+r.width&&r.y<=i&&i<=r.y+r.height}getDrawableBounds(t,e){const i=this.getDrawableVertices(t);let s=i[0],r=i[0],o=i[1],a=i[1];for(let n=0;n{200!==o.status&&0!==o.status||!o.response?o.onerror():s(o.response)},o.onerror=()=>{l.warn("XHRLoader",`Failed to load resource as ${o.responseType} (Status ${o.status}): ${e}`),r(new w("Network error.",e,o.status))},o.onabort=()=>r(new w("Aborted.",e,o.status,!0)),o.onloadend=()=>{var e;I.allXhrSet.delete(o),t&&(null==(e=I.xhrMap.get(t))||e.delete(o))},o}static cancelXHRs(){var t;null==(t=I.xhrMap.get(this))||t.forEach((t=>{t.abort(),I.allXhrSet.delete(t)})),I.xhrMap.delete(this)}static release(){I.allXhrSet.forEach((t=>t.abort())),I.allXhrSet.clear(),I.xhrMap=new WeakMap}};let T=I;function E(t,e){let i=-1;return function s(r,o){if(o)return Promise.reject(o);if(r<=i)return Promise.reject(new Error("next() called multiple times"));i=r;const a=t[r];if(!a)return Promise.resolve();try{return Promise.resolve(a(e,s.bind(null,r+1)))}catch(n){return Promise.reject(n)}}(0)}T.xhrMap=new WeakMap,T.allXhrSet=new Set,T.loader=(t,e)=>new Promise(((e,i)=>{I.createXHR(t.target,t.settings?t.settings.resolveURL(t.url):t.url,t.type,(i=>{t.result=i,e()}),i).send()}));class L{static load(t){return E(this.middlewares,t).then((()=>t.result))}}L.middlewares=[T.loader];const F="Live2DFactory",A=(t,e)=>__async(this,null,(function*(){if("string"==typeof t.source){const e=yield L.load({url:t.source,type:"json",target:t.live2dModel});e.url=t.source,t.source=e,t.live2dModel.emit("settingsJSONLoaded",e)}return e()})),D=(t,e)=>__async(this,null,(function*(){if(t.source instanceof x)return t.settings=t.source,e();if("object"==typeof t.source){const i=V.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.")})),R=(t,e)=>{if(t.settings){const i=V.findRuntime(t.settings);if(i)return i.ready().then(e)}return e()},B=(t,e)=>__async(this,null,(function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=V.findRuntime(e);if(s){const r=[];e.pose&&r.push(L.load({settings:e,url:e.pose,type:"json",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(F,"Failed to load pose.",e)}))),e.physics&&r.push(L.load({settings:e,url:e.physics,type:"json",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(F,"Failed to load physics.",e)}))),r.length&&(yield Promise.all(r))}}})),O=(t,e)=>__async(this,null,(function*(){if(!t.settings)throw new TypeError("Missing settings.");{const i=t.live2dModel,r=t.settings.textures.map((e=>function(t,e={}){const i={resourceOptions:{crossorigin:e.crossOrigin}};if(s.Texture.fromURL)return s.Texture.fromURL(t,i).catch((t=>{if(t instanceof Error)throw t;const e=new Error("Texture loading error");throw e.event=t,e}));i.resourceOptions.autoLoad=!1;const r=s.Texture.from(t,i);if(r.baseTexture.valid)return Promise.resolve(r);const o=r.baseTexture.resource;return null!=o._live2d_load||(o._live2d_load=new Promise(((t,e)=>{const i=t=>{o.source.removeEventListener("error",i);const s=new Error("Texture loading error");s.event=t,e(s)};o.source.addEventListener("error",i),o.load().then((()=>t(r))).catch(i)}))),o._live2d_load}(t.settings.resolveURL(e),{crossOrigin:t.options.crossOrigin})));if(yield e(),!t.internalModel)throw new TypeError("Missing internal model.");i.internalModel=t.internalModel,i.emit("modelLoaded",t.internalModel),i.textures=yield Promise.all(r),i.emit("textureLoaded",i.textures)}})),k=(t,e)=>__async(this,null,(function*(){const i=t.settings;if(i instanceof x){const s=V.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield L.load({settings:i,url:i.moc,type:"arraybuffer",target:t.live2dModel});if(!s.isValidMoc(r))throw new Error("Invalid moc data");const o=s.createCoreModel(r);return t.internalModel=s.createInternalModel(o,i,t.options),e()}throw new TypeError("Missing settings.")})),U=class{static registerRuntime(t){U.runtimes.push(t),U.runtimes.sort(((t,e)=>e.version-t.version))}static findRuntime(t){for(const e of U.runtimes)if(e.test(t))return e}static setupLive2DModel(t,e,i){return __async(this,null,(function*(){const s=new Promise((e=>t.once("textureLoaded",e))),r=new Promise((e=>t.once("modelLoaded",e))),o=Promise.all([s,r]).then((()=>t.emit("ready")));yield E(U.live2DModelMiddlewares,{live2dModel:t,source:e,options:i||{}}),yield o,t.emit("load")}))}static loadMotion(t,e,i){var s;const r=s=>t.emit("motionLoadError",e,i,s);try{const o=null==(s=t.definitions[e])?void 0:s[i];if(!o)return Promise.resolve(void 0);t.listeners("destroy").includes(U.releaseTasks)||t.once("destroy",U.releaseTasks);let a=U.motionTasksMap.get(t);a||(a={},U.motionTasksMap.set(t,a));let n=a[e];n||(n=[],a[e]=n);const h=t.getMotionFile(o);return null!=n[i]||(n[i]=L.load({url:h,settings:t.settings,type:t.motionDataType,target:t}).then((s=>{var r;const a=null==(r=U.motionTasksMap.get(t))?void 0:r[e];a&&delete a[i];const n=t.createMotion(s,e,o);return t.emit("motionLoaded",e,i,n),n})).catch((e=>{l.warn(t.tag,`Failed to load motion: ${h}\n`,e),r(e)}))),n[i]}catch(o){l.warn(t.tag,`Failed to load motion at "${e}"[${i}]\n`,o),r(o)}return Promise.resolve(void 0)}static loadExpression(t,e){const i=i=>t.emit("expressionLoadError",e,i);try{const s=t.definitions[e];if(!s)return Promise.resolve(void 0);t.listeners("destroy").includes(U.releaseTasks)||t.once("destroy",U.releaseTasks);let r=U.expressionTasksMap.get(t);r||(r=[],U.expressionTasksMap.set(t,r));const o=t.getExpressionFile(s);return null!=r[e]||(r[e]=L.load({url:o,settings:t.settings,type:"json",target:t}).then((i=>{const r=U.expressionTasksMap.get(t);r&&delete r[e];const o=t.createExpression(i,s);return t.emit("expressionLoaded",e,o),o})).catch((e=>{l.warn(t.tag,`Failed to load expression: ${o}\n`,e),i(e)}))),r[e]}catch(s){l.warn(t.tag,`Failed to load expression at [${e}]\n`,s),i(s)}return Promise.resolve(void 0)}static releaseTasks(){this instanceof P?U.motionTasksMap.delete(this):U.expressionTasksMap.delete(this)}};let V=U;V.runtimes=[],V.urlToJSON=A,V.jsonToSettings=D,V.waitUntilReady=R,V.setupOptionals=B,V.setupEssentials=O,V.createInternalModel=k,V.live2DModelMiddlewares=[A,D,R,B,O,k],V.motionTasksMap=new WeakMap,V.expressionTasksMap=new WeakMap,P.prototype._loadMotion=function(t,e){return V.loadMotion(this,t,e)},_.prototype._loadExpression=function(t){return V.loadExpression(this,t)};class N{constructor(){this._autoInteract=!1}get autoInteract(){return this._autoInteract}set autoInteract(t){t!==this._autoInteract&&(t?this.on("pointertap",G,this):this.off("pointertap",G,this),this._autoInteract=t)}registerInteraction(t){t!==this.interactionManager&&(this.unregisterInteraction(),this._autoInteract&&t&&(this.interactionManager=t,t.on("pointermove",X,this)))}unregisterInteraction(){var t;this.interactionManager&&(null==(t=this.interactionManager)||t.off("pointermove",X,this),this.interactionManager=void 0)}}function G(t){this.tap(t.data.global.x,t.data.global.y)}function X(t){this.focus(t.data.global.x,t.data.global.y)}class z extends i.Transform{}const j=new i.Point,W=new i.Matrix;let H;class Y extends r.Container{constructor(t){super(),this.tag="Live2DModel(uninitialized)",this.textures=[],this.transform=new z,this.anchor=new i.ObservablePoint(this.onAnchorChange,this,0,0),this.glContextID=-1,this.elapsedTime=performance.now(),this.deltaTime=0,this._autoUpdate=!1,this.once("modelLoaded",(()=>this.init(t)))}static from(t,e){const i=new this(e);return V.setupLive2DModel(i,t,e).then((()=>i))}static fromSync(t,e){const i=new this(e);return V.setupLive2DModel(i,t,e).then(null==e?void 0:e.onLoad).catch(null==e?void 0:e.onError),i}static registerTicker(t){H=t}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){var e;H||(H=null==(e=window.PIXI)?void 0:e.Ticker),t?this._destroyed||(H?(H.shared.add(this.onTickerUpdate,this),this._autoUpdate=!0):l.warn(this.tag,"No Ticker registered, please call Live2DModel.registerTicker(Ticker).")):(null==H||H.shared.remove(this.onTickerUpdate,this),this._autoUpdate=!1)}init(t){this.tag=`Live2DModel(${this.internalModel.settings.name})`;const e=Object.assign({autoUpdate:!0,autoInteract:!0},t);e.autoInteract&&(this.interactive=!0),this.autoInteract=e.autoInteract,this.autoUpdate=e.autoUpdate}onAnchorChange(){this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(t,e,{priority:i=2,sound:s,volume:r=1,expression:o,resetExpression:a=!0}={}){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i,{sound:s,volume:r,expression:o,resetExpression:a}):this.internalModel.motionManager.startMotion(t,e,i,{sound:s,volume:r,expression:o,resetExpression:a})}resetMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(t,{volume:e=1,expression:i,resetExpression:s=!0}={}){return this.internalModel.motionManager.speakUp(t,{volume:e,expression:i,resetExpression:s})}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){j.x=t,j.y=e,this.toModelPosition(j,j,!0);let s=j.x/this.internalModel.originalWidth*2-1,r=j.y/this.internalModel.originalHeight*2-1,o=Math.atan2(r,s);this.internalModel.focusController.focus(Math.cos(o),-Math.sin(o),i)}tap(t,e){const i=this.hitTest(t,e);i.length&&(l.log(this.tag,"Hit",i),this.emit("hit",i))}hitTest(t,e){return j.x=t,j.y=e,this.toModelPosition(j,j),this.internalModel.hitTest(j.x,j.y)}toModelPosition(t,e=t.clone(),i){return i||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.transform.worldTransform.applyInverse(t,e),this.internalModel.localTransform.applyInverse(e,e),e}containsPoint(t){return this.getBounds(!0).contains(t.x,t.y)}_calculateBounds(){this._bounds.addFrame(this.transform,0,0,this.internalModel.width,this.internalModel.height)}onTickerUpdate(){this.update(H.shared.deltaMS)}update(t){this.deltaTime+=t,this.elapsedTime+=t}_render(t){this.registerInteraction(t.plugins.interaction),t.batch.reset(),t.geometry.reset(),t.shader.reset(),t.state.reset();let e=!1;this.glContextID!==t.CONTEXT_UID&&(this.glContextID=t.CONTEXT_UID,this.internalModel.updateWebGLContext(t.gl,this.glContextID),e=!0);for(let r=0;re.destroy(t.baseTexture))),this.internalModel.destroy(),super.destroy(t)}}g(Y,[N]);const q=class{static resolveURL(t,e){var i;const s=null==(i=q.filesMap[t])?void 0:i[e];if(void 0===s)throw new Error("Cannot find this file from uploaded files: "+e);return s}static upload(t,i){return __async(this,null,(function*(){const s={};for(const r of i.getDefinedFiles()){const o=decodeURI(e.url.resolve(i.url,r)),a=t.find((t=>t.webkitRelativePath===o));a&&(s[r]=URL.createObjectURL(a))}q.filesMap[i._objectURL]=s}))}static createSettings(t){return __async(this,null,(function*(){const e=t.find((t=>t.name.endsWith("model.json")||t.name.endsWith("model3.json")));if(!e)throw new TypeError("Settings file not found");const i=yield q.readText(e),s=JSON.parse(i);s.url=e.webkitRelativePath;const r=V.findRuntime(s);if(!r)throw new Error("Unknown settings JSON");const o=r.createModelSettings(s);return o._objectURL=URL.createObjectURL(e),o}))}static readText(t){return __async(this,null,(function*(){return new Promise(((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")}))}))}};let $=q;$.filesMap={},$.factory=(t,e)=>__async(this,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 q.createSettings(e);i.validateFiles(e.map((t=>encodeURI(t.webkitRelativePath)))),yield q.upload(e,i),i.resolveURL=function(t){return q.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),q.filesMap[t])for(const e of Object.values(q.filesMap[t]))URL.revokeObjectURL(e);delete q.filesMap[t]}))}))}return e()})),V.live2DModelMiddlewares.unshift($.factory);const J=class{static unzip(t,i){return __async(this,null,(function*(){const s=yield J.getFilePaths(t),r=[];for(const t of i.getDefinedFiles()){const o=decodeURI(e.url.resolve(i.url,t));s.includes(o)&&r.push(o)}const o=yield J.getFiles(t,r);for(let t=0;tt.endsWith("model.json")||t.endsWith("model3.json")));if(!e)throw new Error("Settings file not found");const i=yield J.readText(t,e);if(!i)throw new Error("Empty settings file: "+e);const s=JSON.parse(i);s.url=e;const r=V.findRuntime(s);if(!r)throw new Error("Unknown settings JSON");return r.createModelSettings(s)}))}static zipReader(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static getFilePaths(t){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static getFiles(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static readText(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static releaseReader(t){}};let Z=J;if(Z.ZIP_PROTOCOL="zip://",Z.uid=0,Z.factory=(t,e)=>__async(this,null,(function*(){const i=t.source;let s,r,o;if("string"==typeof i&&(i.endsWith(".zip")||i.startsWith(J.ZIP_PROTOCOL))?(s=i.startsWith(J.ZIP_PROTOCOL)?i.slice(J.ZIP_PROTOCOL.length):i,r=yield L.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),o=i.settings),r){if(!r.size)throw new Error("Empty zip file");const e=yield J.zipReader(r,s);o||(o=yield J.createSettings(e)),o._objectURL=J.ZIP_PROTOCOL+J.uid+"/"+o.url;const i=yield J.unzip(e,o);i.settings=o,t.source=i,s.startsWith("blob:")&&t.live2dModel.once("modelLoaded",(t=>{t.once("destroy",(function(){URL.revokeObjectURL(s)}))})),J.releaseReader(e)}return e()})),V.live2DModelMiddlewares.unshift(Z.factory),!window.Live2D)throw new Error("Could not find Cubism 2 runtime. This plugin requires live2d.min.js to be loaded.");const Q=Live2DMotion.prototype.updateParam;Live2DMotion.prototype.updateParam=function(t,e){Q.call(this,t,e),e.isFinished()&&this.onFinishHandler&&(this.onFinishHandler(this),delete this.onFinishHandler)};class K extends AMotion{constructor(e){super(),this.params=[],this.setFadeIn(e.fade_in>0?e.fade_in:t.config.expressionFadingDuration),this.setFadeOut(e.fade_out>0?e.fade_out:t.config.expressionFadingDuration),Array.isArray(e.params)&&e.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 tt extends _{constructor(t,e){var i;super(t,e),this.queueManager=new MotionQueueManager,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 K(t)}_setExpression(t){return this.queueManager.startMotion(t)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}}class et extends P{constructor(t,e){super(t,e),this.groups={idle:"idle"},this.motionDataType="arraybuffer",this.queueManager=new MotionQueueManager,this.definitions=this.settings.motions,this.init(e),this.lipSyncIds=["PARAM_MOUTH_OPEN_Y"]}init(t){super.init(t),this.settings.expressions&&(this.expressionManager=new tt(this.settings,t))}isFinished(){return this.queueManager.isFinished()}createMotion(e,i,s){const r=Live2DMotion.loadMotion(e),o=i===this.groups.idle?t.config.idleMotionFadingDuration:t.config.motionFadingDuration;return r.setFadeIn(s.fade_in>0?s.fade_in:o),r.setFadeOut(s.fade_out>0?s.fade_out:o),r}getMotionFile(t){return t.file}getMotionName(t){return t.file}getSoundFile(t){return t.sound}_startMotion(t,e){return t.onFinishHandler=e,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}}class it{constructor(t){this.coreModel=t,this.blinkInterval=4e3,this.closingDuration=100,this.closedDuration=50,this.openingDuration=150,this.eyeState=0,this.eyeParamValue=1,this.closedTimer=0,this.nextBlinkTimeLeft=this.blinkInterval,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+u(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 st=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class rt extends S{constructor(t,e,i){super(),this.textureFlipY=!0,this.lipSync=!0,this.drawDataCount=0,this.disableCulling=!1,this.coreModel=t,this.settings=e,this.motionManager=new et(e,i),this.eyeBlink=new it(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.mouthFormIndex=t.getParamIndex("PARAM_MOUTH_FORM"),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;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 of Object.keys(this.settings.layout)){let i=e;"center_x"===e?i="centerX":"center_y"===e&&(i="centerY"),t[i]=this.settings.layout[e]}return t}updateWebGLContext(t,e){const i=this.coreModel.drawParamWebGL;i.firstDraw=!0,i.setGL(t),i.glno=e;for(const o in i)i.hasOwnProperty(o)&&i[o]instanceof WebGLBuffer&&(i[o]=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;return(null==(t=this.settings.hitAreas)?void 0:t.map((t=>({id:t.id,name:t.name,index:this.coreModel.getDrawDataIndex(t.id)}))))||[]}getDrawableIDs(){const t=this.coreModel.getModelContext(),e=[];for(let i=0;i0&&(e=.4),t=h(t*1.2,e,1);for(let i=0;i0&&t.textures.every((t=>"string"==typeof t))}copy(t){d("string",t,this,"name","name"),d("string",t,this,"pose","pose"),d("string",t,this,"physics","physics"),d("object",t,this,"layout","layout"),d("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")}replaceFiles(t){super.replaceFiles(t);for(const[e,i]of Object.entries(this.motions))for(let s=0;s{const e=new PhysicsHair;return e.setup(t.setup.length,t.setup.regist,t.setup.mass),t.src.forEach((({id:t,ptype:i,scale:s,weight:r})=>{const o=at[i];o&&e.addSrcParam(o,t,s,r)})),t.targets.forEach((({id:t,ptype:i,scale:s,weight:r})=>{const o=nt[i];o&&e.addTargetParam(o,t,s,r)})),e})))}update(t){this.physicsHairs.forEach((e=>e.update(this.coreModel,t)))}}class ht{constructor(t){this.id=t,this.paramIndex=-1,this.partsIndex=-1,this.link=[]}initIndex(t){this.paramIndex=t.getParamIndex("VISIBLE:"+this.id),this.partsIndex=t.getPartsDataIndex(PartsDataID.getID(this.id)),t.setParamFloat(this.paramIndex,1)}}class ut{constructor(t,e){this.coreModel=t,this.opacityAnimDuration=500,this.partsGroups=[],e.parts_visible&&(this.partsGroups=e.parts_visible.map((({group:t})=>t.map((({id:t,link:e})=>{const i=new ht(t);return e&&(i.link=e.map((t=>new ht(t)))),i})))),this.init())}init(){this.partsGroups.forEach((t=>{t.forEach((t=>{if(t.initIndex(this.coreModel),t.paramIndex>=0){const e=0!==this.coreModel.getParamFloat(t.paramIndex);this.coreModel.setPartsOpacity(t.partsIndex,e?1:0),this.coreModel.setParamFloat(t.paramIndex,e?1:0),t.link.length>0&&t.link.forEach((t=>t.initIndex(this.coreModel)))}}))}))}normalizePartsOpacityGroup(t,e){const i=this.coreModel,s=.5;let r=1,o=t.findIndex((({paramIndex:t,partsIndex:e})=>e>=0&&0!==i.getParamFloat(t)));if(o>=0){const s=i.getPartsOpacity(t[o].partsIndex);r=h(s+e/this.opacityAnimDuration,0,1)}else o=0,r=1;t.forEach((({partsIndex:t},e)=>{if(t>=0)if(o==e)i.setPartsOpacity(t,r);else{let e,o=i.getPartsOpacity(t);e=r.15&&(e=1-.15/(1-r)),o>e&&(o=e),i.setPartsOpacity(t,o)}}))}copyOpacity(t){const e=this.coreModel;t.forEach((({partsIndex:t,link:i})=>{if(t>=0&&i){const s=e.getPartsOpacity(t);i.forEach((({partsIndex:t})=>{t>=0&&e.setPartsOpacity(t,s)}))}}))}update(t){this.partsGroups.forEach((e=>{this.normalizePartsOpacityGroup(e,t),this.copyOpacity(e)}))}}if(V.registerRuntime({version:2,test:t=>t instanceof ot||ot.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 ot(t),createCoreModel(t){const e=Live2DModelWebGL.loadModel(t),i=Live2D.getError();if(i)throw i;return e},createInternalModel:(t,e,i)=>new rt(t,e,i),createPose:(t,e)=>new ut(t,e),createPhysics:(t,e)=>new lt(t,e)}),!window.Live2DCubismCore)throw new Error("Could not find Cubism 4 runtime. This plugin requires live2dcubismcore.js to be loaded.");class dt{constructor(t,e){this.x=t||0,this.y=e||0}add(t){const e=new dt(0,0);return e.x=this.x+t.x,e.y=this.y+t.y,e}substract(t){const e=new dt(0,0);return e.x=this.x-t.x,e.y=this.y-t.y,e}multiply(t){const e=new dt(0,0);return e.x=this.x*t.x,e.y=this.y*t.y,e}multiplyByScaler(t){return this.multiply(new dt(t,t))}division(t){const e=new dt(0,0);return e.x=this.x/t.x,e.y=this.y/t.y,e}divisionByScalar(t){return this.division(new dt(t,t))}getLength(){return Math.sqrt(this.x*this.x+this.y*this.y)}getDistanceWith(t){return Math.sqrt((this.x-t.x)*(this.x-t.x)+(this.y-t.y)*(this.y-t.y))}dot(t){return this.x*t.x+this.y*t.y}normalize(){const t=Math.pow(this.x*this.x+this.y*this.y,.5);this.x=this.x/t,this.y=this.y/t}isEqual(t){return this.x==t.x&&this.y==t.y}isNotEqual(t){return!this.isEqual(t)}}const ct=class{static range(t,e,i){return ti&&(t=i),t}static sin(t){return Math.sin(t)}static cos(t){return Math.cos(t)}static abs(t){return Math.abs(t)}static sqrt(t){return Math.sqrt(t)}static cbrt(t){if(0===t)return t;let e=t;const i=e<0;let s;return i&&(e=-e),e===1/0?s=1/0:(s=Math.exp(Math.log(e)/3),s=(e/(s*s)+2*s)/3),i?-s:s}static getEasingSine(t){return t<0?0:t>1?1:.5-.5*this.cos(t*Math.PI)}static max(t,e){return t>e?t:e}static min(t,e){return t>e?e:t}static degreesToRadian(t){return t/180*Math.PI}static radianToDegrees(t){return 180*t/Math.PI}static directionToRadian(t,e){let i=Math.atan2(e.y,e.x)-Math.atan2(t.y,t.x);for(;i<-Math.PI;)i+=2*Math.PI;for(;i>Math.PI;)i-=2*Math.PI;return i}static directionToDegrees(t,e){const i=this.directionToRadian(t,e);let s=this.radianToDegrees(i);return e.x-t.x>0&&(s=-s),s}static radianToDirection(t){const e=new dt;return e.x=this.sin(t),e.y=this.cos(t),e}static quadraticEquation(t,e,i){return this.abs(t)1&&(t=1),e<0?e=0:e>1&&(e=1),i<0?i=0:i>1&&(i=1),s<0?s=0:s>1&&(s=1),this._modelColor.R=t,this._modelColor.G=e,this._modelColor.B=i,this._modelColor.A=s}getModelColor(){return Object.assign({},this._modelColor)}setIsPremultipliedAlpha(t){this._isPremultipliedAlpha=t}isPremultipliedAlpha(){return this._isPremultipliedAlpha}setIsCulling(t){this._isCulling=t}isCulling(){return this._isCulling}setAnisotropy(t){this._anisotropy=t}getAnisotropy(){return this._anisotropy}getModel(){return this._model}useHighPrecisionMask(t){this._useHighPrecisionMask=t}isUsingHighPrecisionMask(){return this._useHighPrecisionMask}constructor(){this._isCulling=!1,this._isPremultipliedAlpha=!1,this._anisotropy=0,this._modelColor=new ft,this._useHighPrecisionMask=!1,this._mvpMatrix4x4=new mt,this._mvpMatrix4x4.loadIdentity()}}var _t=(t=>(t[t.CubismBlendMode_Normal=0]="CubismBlendMode_Normal",t[t.CubismBlendMode_Additive=1]="CubismBlendMode_Additive",t[t.CubismBlendMode_Multiplicative=2]="CubismBlendMode_Multiplicative",t))(_t||{});class ft{constructor(t=1,e=1,i=1,s=1){this.R=t,this.G=e,this.B=i,this.A=s}}let xt,yt=!1,Mt=!1;const Ct=0,vt=2;class Pt{static startUp(t){if(yt)return wt("CubismFramework.startUp() is already done."),yt;if(Live2DCubismCore._isStarted)return yt=!0,!0;if(Live2DCubismCore._isStarted=!0,xt=t,xt&&Live2DCubismCore.Logging.csmSetLogFunction(xt.logFunction),yt=!0,yt){const t=Live2DCubismCore.Version.csmGetVersion(),e=(16711680&t)>>16,i=65535&t,s=t;wt("Live2D Cubism Core version: {0}.{1}.{2} ({3})",("00"+((4278190080&t)>>24)).slice(-2),("00"+e).slice(-2),("0000"+i).slice(-4),s)}return wt("CubismFramework.startUp() is complete."),yt}static cleanUp(){yt=!1,Mt=!1,xt=void 0}static initialize(t=0){yt?Mt?It("CubismFramework.initialize() skipped, already initialized."):(Live2DCubismCore.Memory.initializeAmountOfMemory(t),Mt=!0,wt("CubismFramework.initialize() is complete.")):It("CubismFramework is not started.")}static dispose(){yt?Mt?(pt.staticRelease(),Mt=!1,wt("CubismFramework.dispose() is complete.")):It("CubismFramework.dispose() skipped, not initialized."):It("CubismFramework is not started.")}static isStarted(){return yt}static isInitialized(){return Mt}static coreLogFunction(t){Live2DCubismCore.Logging.csmGetLogFunction()&&Live2DCubismCore.Logging.csmGetLogFunction()(t)}static getLoggingLevel(){return null!=xt?xt.loggingLevel:bt.LogLevel_Off}constructor(){}}var bt=(t=>(t[t.LogLevel_Verbose=0]="LogLevel_Verbose",t[t.LogLevel_Debug=1]="LogLevel_Debug",t[t.LogLevel_Info=2]="LogLevel_Info",t[t.LogLevel_Warning=3]="LogLevel_Warning",t[t.LogLevel_Error=4]="LogLevel_Error",t[t.LogLevel_Off=5]="LogLevel_Off",t))(bt||{});function St(t,...e){Et.print(bt.LogLevel_Debug,"[CSM][D]"+t+"\n",e)}function wt(t,...e){Et.print(bt.LogLevel_Info,"[CSM][I]"+t+"\n",e)}function It(t,...e){Et.print(bt.LogLevel_Warning,"[CSM][W]"+t+"\n",e)}function Tt(t,...e){Et.print(bt.LogLevel_Error,"[CSM][E]"+t+"\n",e)}class Et{static print(t,e,i){if(ti[e])))}static dumpBytes(t,e,i){for(let s=0;s0?this.print(t,"\n"):s%8==0&&s>0&&this.print(t," "),this.print(t,"{0} ",[255&e[s]]);this.print(t,"\n")}constructor(){}}class Lt{constructor(){this._fadeInSeconds=-1,this._fadeOutSeconds=-1,this._weight=1,this._offsetSeconds=0,this._firedEventValues=[]}release(){this._weight=0}updateParameters(t,e,i){if(!e.isAvailable()||e.isFinished())return;if(!e.isStarted()){e.setIsStarted(!0),e.setStartTime(i-this._offsetSeconds),e.setFadeInStartTime(i);const t=this.getDuration();e.getEndTime()<0&&e.setEndTime(t<=0?-1:e.getStartTime()+t)}let s=this._weight;s=s*(0==this._fadeInSeconds?1:gt.getEasingSine((i-e.getFadeInStartTime())/this._fadeInSeconds))*(0==this._fadeOutSeconds||e.getEndTime()<0?1:gt.getEasingSine((e.getEndTime()-i)/this._fadeOutSeconds)),e.setState(i,s),this.doUpdateParameters(t,i,s,e),e.getEndTime()>0&&e.getEndTime()(t[t.ExpressionBlendType_Add=0]="ExpressionBlendType_Add",t[t.ExpressionBlendType_Multiply=1]="ExpressionBlendType_Multiply",t[t.ExpressionBlendType_Overwrite=2]="ExpressionBlendType_Overwrite",t))(At||{});class Dt{constructor(){this._autoDelete=!1,this._available=!0,this._finished=!1,this._started=!1,this._startTimeSeconds=-1,this._fadeInStartTimeSeconds=0,this._endTimeSeconds=-1,this._stateTimeSeconds=0,this._stateWeight=0,this._lastEventCheckSeconds=0,this._motionQueueEntryHandle=this,this._fadeOutSeconds=0,this._isTriggeredFadeOut=!1}release(){this._autoDelete&&this._motion&&this._motion.release()}setFadeOut(t){this._fadeOutSeconds=t,this._isTriggeredFadeOut=!0}startFadeOut(t,e){const i=e+t;this._isTriggeredFadeOut=!0,(this._endTimeSeconds<0||inull!=e&&e._motionQueueEntryHandle==t))}setEventCallback(t,e=null){this._eventCallBack=t,this._eventCustomData=e}doUpdateMotion(t,e){let i=!1,s=0;for(;se.Name===t))}getExpressionFile(t){return t.File}createExpression(t,e){return Ft.create(t)}_setExpression(t){return this.queueManager.startMotion(t,!1,performance.now())}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.doUpdateMotion(t,e)}}class kt{constructor(t){this.groups=t.Groups,this.hitAreas=t.HitAreas,this.layout=t.Layout,this.moc=t.FileReferences.Moc,this.expressions=t.FileReferences.Expressions,this.motions=t.FileReferences.Motions,this.textures=t.FileReferences.Textures,this.physics=t.FileReferences.Physics,this.pose=t.FileReferences.Pose}getEyeBlinkParameters(){var t,e;return null==(e=null==(t=this.groups)?void 0:t.find((t=>"EyeBlink"===t.Name)))?void 0:e.Ids}getLipSyncParameters(){var t,e;return null==(e=null==(t=this.groups)?void 0:t.find((t=>"LipSync"===t.Name)))?void 0:e.Ids}}class Ut extends x{constructor(t){if(super(t),!Ut.isValidJSON(t))throw new TypeError("Invalid JSON.");Object.assign(this,new kt(t))}static isValidJSON(t){var e;return!!(null==t?void 0:t.FileReferences)&&"string"==typeof t.FileReferences.Moc&&(null==(e=t.FileReferences.Textures)?void 0:e.length)>0&&t.FileReferences.Textures.every((t=>"string"==typeof t))}replaceFiles(t){if(super.replaceFiles(t),this.motions)for(const[e,i]of Object.entries(this.motions))for(let s=0;s(t[t.CubismMotionCurveTarget_Model=0]="CubismMotionCurveTarget_Model",t[t.CubismMotionCurveTarget_Parameter=1]="CubismMotionCurveTarget_Parameter",t[t.CubismMotionCurveTarget_PartOpacity=2]="CubismMotionCurveTarget_PartOpacity",t))(Vt||{}),Nt=(t=>(t[t.CubismMotionSegmentType_Linear=0]="CubismMotionSegmentType_Linear",t[t.CubismMotionSegmentType_Bezier=1]="CubismMotionSegmentType_Bezier",t[t.CubismMotionSegmentType_Stepped=2]="CubismMotionSegmentType_Stepped",t[t.CubismMotionSegmentType_InverseStepped=3]="CubismMotionSegmentType_InverseStepped",t))(Nt||{});class Gt{constructor(t=0,e=0){this.time=t,this.value=e}}class Xt{constructor(){this.basePointIndex=0,this.segmentType=0}}class zt{constructor(){this.id="",this.type=0,this.segmentCount=0,this.baseSegmentIndex=0,this.fadeInTime=0,this.fadeOutTime=0}}class jt{constructor(){this.fireTime=0,this.value=""}}class Wt{constructor(){this.duration=0,this.loop=!1,this.curveCount=0,this.eventCount=0,this.fps=0,this.curves=[],this.segments=[],this.points=[],this.events=[]}}class Ht{constructor(t){this._json=t}release(){this._json=void 0}getMotionDuration(){return this._json.Meta.Duration}isMotionLoop(){return this._json.Meta.Loop||!1}getEvaluationOptionFlag(t){return Yt.EvaluationOptionFlag_AreBeziersRistricted==t&&!!this._json.Meta.AreBeziersRestricted}getMotionCurveCount(){return this._json.Meta.CurveCount}getMotionFps(){return this._json.Meta.Fps}getMotionTotalSegmentCount(){return this._json.Meta.TotalSegmentCount}getMotionTotalPointCount(){return this._json.Meta.TotalPointCount}getMotionFadeInTime(){return this._json.Meta.FadeInTime}getMotionFadeOutTime(){return this._json.Meta.FadeOutTime}getMotionCurveTarget(t){return this._json.Curves[t].Target}getMotionCurveId(t){return this._json.Curves[t].Id}getMotionCurveFadeInTime(t){return this._json.Curves[t].FadeInTime}getMotionCurveFadeOutTime(t){return this._json.Curves[t].FadeOutTime}getMotionCurveSegmentCount(t){return this._json.Curves[t].Segments.length}getMotionCurveSegment(t,e){return this._json.Curves[t].Segments[e]}getEventCount(){return this._json.Meta.UserDataCount||0}getTotalEventValueSize(){return this._json.Meta.TotalUserDataSize}getEventTime(t){return this._json.UserData[t].Time}getEventValue(t){return this._json.UserData[t].Value}}var Yt=(t=>(t[t.EvaluationOptionFlag_AreBeziersRistricted=0]="EvaluationOptionFlag_AreBeziersRistricted",t))(Yt||{});const qt="Opacity";function $t(t,e,i){const s=new Gt;return s.time=t.time+(e.time-t.time)*i,s.value=t.value+(e.value-t.value)*i,s}function Jt(t,e){let i=(e-t[0].time)/(t[1].time-t[0].time);return i<0&&(i=0),t[0].value+(t[1].value-t[0].value)*i}function Zt(t,e){let i=(e-t[0].time)/(t[3].time-t[0].time);i<0&&(i=0);const s=$t(t[0],t[1],i),r=$t(t[1],t[2],i),o=$t(t[2],t[3],i),a=$t(s,r,i),n=$t(r,o,i);return $t(a,n,i).value}function Qt(t,e){const i=e,s=t[0].time,r=t[3].time,o=t[1].time,a=t[2].time,n=r-3*a+3*o-s,l=3*a-6*o+3*s,h=3*o-3*s,u=s-i,d=gt.cardanoAlgorithmForBezier(n,l,h,u),c=$t(t[0],t[1],d),g=$t(t[1],t[2],d),m=$t(t[2],t[3],d),p=$t(c,g,d),_=$t(g,m,d);return $t(p,_,d).value}function Kt(t,e){return t[0].value}function te(t,e){return t[1].value}function ee(t,e,i){const s=t.curves[e];let r=-1;const o=s.baseSegmentIndex+s.segmentCount;let a=0;for(let l=s.baseSegmentIndex;li){r=l;break}if(-1==r)return t.points[a].value;const n=t.segments[r];return n.evaluate(t.points.slice(n.basePointIndex),i)}class ie extends Lt{constructor(){super(),this._eyeBlinkParameterIds=[],this._lipSyncParameterIds=[],this._sourceFrameRate=30,this._loopDurationSeconds=-1,this._isLoop=!1,this._isLoopFadeIn=!0,this._lastWeight=0,this._modelOpacity=1}static create(t,e){const i=new ie;return i.parse(t),i._sourceFrameRate=i._motionData.fps,i._loopDurationSeconds=i._motionData.duration,i._onFinishedMotion=e,i}doUpdateParameters(t,e,i,s){null==this._modelCurveIdEyeBlink&&(this._modelCurveIdEyeBlink="EyeBlink"),null==this._modelCurveIdLipSync&&(this._modelCurveIdLipSync="LipSync"),null==this._modelCurveIdOpacity&&(this._modelCurveIdOpacity=qt);let r=e-s.getStartTime();r<0&&(r=0);let a=Number.MAX_VALUE,n=Number.MAX_VALUE;const l=64;let h=0,u=0;this._eyeBlinkParameterIds.length>l&&St("too many eye blink targets : {0}",this._eyeBlinkParameterIds.length),this._lipSyncParameterIds.length>l&&St("too many lip sync targets : {0}",this._lipSyncParameterIds.length);const d=this._fadeInSeconds<=0?1:gt.getEasingSine((e-s.getFadeInStartTime())/this._fadeInSeconds),c=this._fadeOutSeconds<=0||s.getEndTime()<0?1:gt.getEasingSine((s.getEndTime()-e)/this._fadeOutSeconds);let g,m,p,_=r;if(this._isLoop)for(;_>this._motionData.duration;)_-=this._motionData.duration;const f=this._motionData.curves;for(m=0;m>o&1)continue;const s=e+(n-e)*i;t.setParameterValueById(this._eyeBlinkParameterIds[o],s)}if(a!=Number.MAX_VALUE)for(let o=0;o>o&1)continue;const s=e+(a-e)*i;t.setParameterValueById(this._lipSyncParameterIds[o],s)}for(;m=this._motionData.duration&&(this._isLoop?(s.setStartTime(e),this._isLoopFadeIn&&s.setFadeInStartTime(e)):(this._onFinishedMotion&&this._onFinishedMotion(this),s.setIsFinished(!0))),this._lastWeight=i}setIsLoop(t){this._isLoop=t}isLoop(){return this._isLoop}setIsLoopFadeIn(t){this._isLoopFadeIn=t}isLoopFadeIn(){return this._isLoopFadeIn}getDuration(){return this._isLoop?-1:this._loopDurationSeconds}getLoopDuration(){return this._loopDurationSeconds}setParameterFadeInTime(t,e){const i=this._motionData.curves;for(let s=0;snew zt)),this._motionData.segments=Array.from({length:e.getMotionTotalSegmentCount()}).map((()=>new Xt)),this._motionData.events=Array.from({length:this._motionData.eventCount}).map((()=>new jt)),this._motionData.points=[];let o=0,a=0;for(let n=0;nt&&this._motionData.events[i].fireTime<=e&&this._firedEventValues.push(this._motionData.events[i].value);return this._firedEventValues}isExistModelOpacity(){for(let t=0;t{this.emit("motion:"+e)}))}isFinished(){return this.queueManager.isFinished()}_startMotion(t,e){return t.setFinishedMotionHandler(e),this.queueManager.stopAllMotions(),this.queueManager.startMotion(t,!1,performance.now())}_stopAllMotions(){this.queueManager.stopAllMotions()}createMotion(e,i,s){const r=ie.create(e),o=new Ht(e),a=(i===this.groups.idle?t.config.idleMotionFadingDuration:t.config.motionFadingDuration)/1e3;return void 0===o.getMotionFadeInTime()&&r.setFadeInTime(s.FadeInTime>0?s.FadeInTime:a),void 0===o.getMotionFadeOutTime()&&r.setFadeOutTime(s.FadeOutTime>0?s.FadeOutTime:a),r.setEffectIds(this.eyeBlinkIds,this.lipSyncIds),r}getMotionFile(t){return t.File}getMotionName(t){return t.File}getSoundFile(t){return t.Sound}updateParameters(t,e){return this.queueManager.doUpdateMotion(t,e)}destroy(){super.destroy(),this.queueManager.release(),this.queueManager=void 0}}class re{constructor(){this._breathParameters=[],this._currentTime=0}static create(){return new re}setParameters(t){this._breathParameters=t}getParameters(){return this._breathParameters}updateParameters(t,e){this._currentTime+=e;const i=2*this._currentTime*3.14159;for(let s=0;s=1&&(s=1,this._blinkingState=le.EyeState_Closed,this._stateStartTimeSeconds=this._userTimeSeconds),i=1-s;break;case le.EyeState_Closed:s=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._closedSeconds,s>=1&&(this._blinkingState=le.EyeState_Opening,this._stateStartTimeSeconds=this._userTimeSeconds),i=0;break;case le.EyeState_Opening:s=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._openingSeconds,s>=1&&(s=1,this._blinkingState=le.EyeState_Interval,this._nextBlinkingTime=this.determinNextBlinkingTiming()),i=s;break;case le.EyeState_Interval:this._nextBlinkingTime(t[t.EyeState_First=0]="EyeState_First",t[t.EyeState_Interval=1]="EyeState_Interval",t[t.EyeState_Closing=2]="EyeState_Closing",t[t.EyeState_Closed=3]="EyeState_Closed",t[t.EyeState_Opening=4]="EyeState_Opening",t))(le||{});class he{constructor(t=0,e=0,i=0,s=0){this.x=t,this.y=e,this.width=i,this.height=s}getCenterX(){return this.x+.5*this.width}getCenterY(){return this.y+.5*this.height}getRight(){return this.x+this.width}getBottom(){return this.y+this.height}setRect(t){this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height}expand(t,e){this.x-=t,this.y-=e,this.width+=2*t,this.height+=2*e}}let ue,de,ce;class ge{getChannelFlagAsColor(t){return this._channelColors[t]}getMaskRenderTexture(){if(this._maskTexture&&null!=this._maskTexture.textures)this._maskTexture.frameNo=this._currentFrameNo;else{this._maskRenderTextures=[],this._maskColorBuffers=[];const t=this._clippingMaskBufferSize;for(let e=0;ec&&(c=e),ig&&(g=i)}if(u!=Number.MAX_VALUE)if(ur&&(r=c),g>o&&(o=g),i==Number.MAX_VALUE)e._allClippedDrawRect.x=0,e._allClippedDrawRect.y=0,e._allClippedDrawRect.width=0,e._allClippedDrawRect.height=0,e._isUsing=!1;else{e._isUsing=!0;const t=r-i,a=o-s;e._allClippedDrawRect.x=i,e._allClippedDrawRect.y=s,e._allClippedDrawRect.width=t,e._allClippedDrawRect.height=a}}}constructor(){this._currentMaskRenderTexture=null,this._currentFrameNo=0,this._renderTextureCount=0,this._clippingMaskBufferSize=256,this._clippingContextListForMask=[],this._clippingContextListForDraw=[],this._channelColors=[],this._tmpBoundsOnModel=new he,this._tmpMatrix=new mt,this._tmpMatrixForMask=new mt,this._tmpMatrixForDraw=new mt;let t=new ft;t.R=1,t.G=0,t.B=0,t.A=0,this._channelColors.push(t),t=new ft,t.R=0,t.G=1,t.B=0,t.A=0,this._channelColors.push(t),t=new ft,t.R=0,t.G=0,t.B=1,t.A=0,this._channelColors.push(t),t=new ft,t.R=0,t.G=0,t.B=0,t.A=1,this._channelColors.push(t)}release(){var t;const e=this;for(let i=0;i0){this.setupLayoutBounds(e.isUsingHighPrecisionMask()?0:i),e.isUsingHighPrecisionMask()||(this.gl.viewport(0,0,this._clippingMaskBufferSize,this._clippingMaskBufferSize),this._currentMaskRenderTexture=this.getMaskRenderTexture()[0],e.preDraw(),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this._currentMaskRenderTexture)),this._clearedFrameBufferflags||(this._clearedFrameBufferflags=[]);for(let t=0;th?(this._tmpBoundsOnModel.expand(r.width*a,0),n=o.width/this._tmpBoundsOnModel.width):n=e/h,this._tmpBoundsOnModel.height*e>u?(this._tmpBoundsOnModel.expand(0,r.height*a),l=o.height/this._tmpBoundsOnModel.height):l=e/u}else this._tmpBoundsOnModel.setRect(r),this._tmpBoundsOnModel.expand(r.width*a,r.height*a),n=o.width/this._tmpBoundsOnModel.width,l=o.height/this._tmpBoundsOnModel.height;if(this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(-1,-1),this._tmpMatrix.scaleRelative(2,2),this._tmpMatrix.translateRelative(o.x,o.y),this._tmpMatrix.scaleRelative(n,l),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForMask.setMatrix(this._tmpMatrix.getArray()),this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(o.x,o.y),this._tmpMatrix.scaleRelative(n,l),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForDraw.setMatrix(this._tmpMatrix.getArray()),s._matrixForMask.setMatrix(this._tmpMatrixForMask.getArray()),s._matrixForDraw.setMatrix(this._tmpMatrixForDraw.getArray()),!e.isUsingHighPrecisionMask()){const i=s._clippingIdCount;for(let r=0;re){t>e&&Tt("not supported mask count : {0}\n[Details] render texture count : {1}, mask count : {2}",t-e,this._renderTextureCount,t);for(let t=0;t=4?0:n+1;if(u(t[t.ShaderNames_SetupMask=0]="ShaderNames_SetupMask",t[t.ShaderNames_NormalPremultipliedAlpha=1]="ShaderNames_NormalPremultipliedAlpha",t[t.ShaderNames_NormalMaskedPremultipliedAlpha=2]="ShaderNames_NormalMaskedPremultipliedAlpha",t[t.ShaderNames_NomralMaskedInvertedPremultipliedAlpha=3]="ShaderNames_NomralMaskedInvertedPremultipliedAlpha",t[t.ShaderNames_AddPremultipliedAlpha=4]="ShaderNames_AddPremultipliedAlpha",t[t.ShaderNames_AddMaskedPremultipliedAlpha=5]="ShaderNames_AddMaskedPremultipliedAlpha",t[t.ShaderNames_AddMaskedPremultipliedAlphaInverted=6]="ShaderNames_AddMaskedPremultipliedAlphaInverted",t[t.ShaderNames_MultPremultipliedAlpha=7]="ShaderNames_MultPremultipliedAlpha",t[t.ShaderNames_MultMaskedPremultipliedAlpha=8]="ShaderNames_MultMaskedPremultipliedAlpha",t[t.ShaderNames_MultMaskedPremultipliedAlphaInverted=9]="ShaderNames_MultMaskedPremultipliedAlphaInverted",t))(xe||{});const ye="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_myPos;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_clipMatrix * a_position; v_myPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",Me="precision mediump float;varying vec2 v_texCoord;varying vec4 v_myPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;void main(){ float isInside = step(u_baseColor.x, v_myPos.x/v_myPos.w) * step(u_baseColor.y, v_myPos.y/v_myPos.w) * step(v_myPos.x/v_myPos.w, u_baseColor.z) * step(v_myPos.y/v_myPos.w, u_baseColor.w); gl_FragColor = u_channelFlag * texture2D(s_texture0, v_texCoord).a * isInside;}",Ce="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;uniform mat4 u_matrix;void main(){ gl_Position = u_matrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",ve="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform mat4 u_matrix;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_matrix * a_position; v_clipPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",Pe="precision mediump float;varying vec2 v_texCoord;uniform vec4 u_baseColor;uniform sampler2D s_texture0;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 color = texColor * u_baseColor; gl_FragColor = vec4(color.rgb, color.a);}",be="precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;uniform sampler2D s_texture1;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 col_formask = texColor * u_baseColor; vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag; float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a; col_formask = col_formask * maskVal; gl_FragColor = col_formask;}",Se="precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform sampler2D s_texture0;uniform sampler2D s_texture1;uniform vec4 u_channelFlag;uniform vec4 u_baseColor;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 col_formask = texColor * u_baseColor; vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag; float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a; col_formask = col_formask * (1.0 - maskVal); gl_FragColor = col_formask;}";class we extends pt{constructor(){super(),this._clippingContextBufferForMask=null,this._clippingContextBufferForDraw=null,this._rendererProfile=new _e,this.firstDraw=!0,this._textures={},this._sortedDrawableIndexList=[],this._bufferData={vertex:null,uv:null,index:null}}initialize(t,e=1){t.isUsingMasking()&&(this._clippingManager=new ge,this._clippingManager.initialize(t,t.getDrawableCount(),t.getDrawableMasks(),t.getDrawableMaskCounts(),e));for(let i=t.getDrawableCount()-1;i>=0;i--)this._sortedDrawableIndexList[i]=0;super.initialize(t)}bindTexture(t,e){this._textures[t]=e}getBindedTextures(){return this._textures}setClippingMaskBufferSize(t){if(!this._model.isUsingMasking())return;const e=this._clippingManager.getRenderTextureCount();this._clippingManager.release(),this._clippingManager=new ge,this._clippingManager.setClippingMaskBufferSize(t),this._clippingManager.initialize(this.getModel(),this.getModel().getDrawableCount(),this.getModel().getDrawableMasks(),this.getModel().getDrawableMaskCounts(),e)}getClippingMaskBufferSize(){return this._model.isUsingMasking()?this._clippingManager.getClippingMaskBufferSize():-1}getRenderTextureCount(){return this._model.isUsingMasking()?this._clippingManager.getRenderTextureCount():-1}release(){var t,e,i;const s=this;this._clippingManager.release(),s._clippingManager=void 0,null==(t=this.gl)||t.deleteBuffer(this._bufferData.vertex),this._bufferData.vertex=null,null==(e=this.gl)||e.deleteBuffer(this._bufferData.uv),this._bufferData.uv=null,null==(i=this.gl)||i.deleteBuffer(this._bufferData.index),this._bufferData.index=null,s._bufferData=void 0,s._textures=void 0}doDrawModel(){if(null==this.gl)return void Tt("'gl' is null. WebGLRenderingContext is required.\nPlease call 'CubimRenderer_WebGL.startUp' function.");null!=this._clippingManager&&(this.preDraw(),this._clippingManager.setupClippingContext(this.getModel(),this)),this.preDraw();const t=this.getModel().getDrawableCount(),e=this.getModel().getDrawableRenderOrders();for(let i=0;i0&&this._extension)for(const t of Object.entries(this._textures))this.gl.bindTexture(this.gl.TEXTURE_2D,t),this.gl.texParameterf(this.gl.TEXTURE_2D,this._extension.TEXTURE_MAX_ANISOTROPY_EXT,this.getAnisotropy())}setClippingContextBufferForMask(t){this._clippingContextBufferForMask=t}getClippingContextBufferForMask(){return this._clippingContextBufferForMask}setClippingContextBufferForDraw(t){this._clippingContextBufferForDraw=t}getClippingContextBufferForDraw(){return this._clippingContextBufferForDraw}startUp(t){this.gl=t,this._clippingManager&&this._clippingManager.setGL(t),fe.getInstance().setGl(t),this._rendererProfile.setGl(t),this._extension=this.gl.getExtension("EXT_texture_filter_anisotropic")||this.gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this.gl.getExtension("MOZ_EXT_texture_filter_anisotropic")}}pt.staticRelease=()=>{we.doStaticRelease()};const Ie=new mt;class Te extends S{constructor(t,e,s){super(),this.lipSync=!0,this.breath=re.create(),this.renderer=new we,this.idParamAngleX="ParamAngleX",this.idParamAngleY="ParamAngleY",this.idParamAngleZ="ParamAngleZ",this.idParamEyeBallX="ParamEyeBallX",this.idParamEyeBallY="ParamEyeBallY",this.idParamBodyAngleX="ParamBodyAngleX",this.idParamBreath="ParamBreath",this.idParamMouthForm="ParamMouthForm",this.pixelsPerUnit=1,this.centeringTransform=new i.Matrix,this.coreModel=t,this.settings=e,this.motionManager=new se(e,s),this.init()}init(){var t;super.init(),(null==(t=this.settings.getEyeBlinkParameters())?void 0:t.length)>0&&(this.eyeBlink=ne.create(this.settings)),this.breath.setParameters([new oe(this.idParamAngleX,0,15,6.5345,.5),new oe(this.idParamAngleY,0,8,3.5345,.5),new oe(this.idParamAngleZ,0,10,5.5345,.5),new oe(this.idParamBodyAngleX,0,4,15.5345,.5),new oe(this.idParamBreath,0,.5,3.2345,.5)]),this.renderer.initialize(this.coreModel),this.renderer.setIsPremultipliedAlpha(!0)}getSize(){return[this.coreModel.getModel().canvasinfo.CanvasWidth,this.coreModel.getModel().canvasinfo.CanvasHeight]}getLayout(){const t={};if(this.settings.layout)for(const e of Object.keys(this.settings.layout)){t[e.charAt(0).toLowerCase()+e.slice(1)]=this.settings.layout[e]}return t}setupLayout(){super.setupLayout(),this.pixelsPerUnit=this.coreModel.getModel().canvasinfo.PixelsPerUnit,this.centeringTransform.scale(this.pixelsPerUnit,this.pixelsPerUnit).translate(this.originalWidth/2,this.originalHeight/2)}updateWebGLContext(t,e){this.renderer.firstDraw=!0,this.renderer._bufferData={vertex:null,uv:null,index:null},this.renderer.startUp(t),this.renderer._clippingManager._currentFrameNo=e,this.renderer._clippingManager._maskTexture=void 0,fe.getInstance()._shaderSets=[]}bindTexture(t,e){this.renderer.bindTexture(t,e)}getHitAreaDefs(){var t,e;return null!=(e=null==(t=this.settings.hitAreas)?void 0:t.map((t=>({id:t.Id,name:t.Name,index:this.coreModel.getDrawableIndex(t.Id)}))))?e:[]}getDrawableIDs(){return this.coreModel.getDrawableIds()}getDrawableIndex(t){return this.coreModel.getDrawableIndex(t)}getDrawableVertices(t){if("string"==typeof t&&-1===(t=this.coreModel.getDrawableIndex(t)))throw new TypeError("Unable to find drawable ID: "+t);const e=this.coreModel.getDrawableVertices(t).slice();for(let i=0;i0&&(e=.4),t=h(t*1.2,e,1);for(let i=0;i{!function i(){try{Ae(),t()}catch(s){if(Le--,Le<0){const t=new Error("Failed to start up Cubism 4 framework.");return t.cause=s,void e(t)}l.log("Cubism4","Startup failed, retrying 10ms later..."),setTimeout(i,10)}}()}))),Ee)}function Ae(t){t=Object.assign({logFunction:console.log,loggingLevel:bt.LogLevel_Verbose},t),Pt.startUp(t),Pt.initialize()}class De{static create(t){const e=new De;"number"==typeof t.FadeInTime&&(e._fadeTimeSeconds=t.FadeInTime,e._fadeTimeSeconds<=0&&(e._fadeTimeSeconds=.5));const i=t.Groups,s=i.length;for(let r=0;r.001){if(r>=0)break;r=n,o=t.getPartOpacityByIndex(i),o+=e/this._fadeTimeSeconds,o>1&&(o=1)}}r<0&&(r=0,o=1);for(let n=i;n.15&&(i=1-.15/(1-o)),s>i&&(s=i),t.setPartOpacityByIndex(e,s)}}}constructor(){this._fadeTimeSeconds=.5,this._lastModel=void 0,this._partGroups=[],this._partGroupCounts=[]}}class Re{constructor(t){this.parameterIndex=0,this.partIndex=0,this.partId="",this.link=[],null!=t&&this.assignment(t)}assignment(t){return this.partId=t.partId,this.link=t.link.map((t=>t.clone())),this}initialize(t){this.parameterIndex=t.getParameterIndex(this.partId),this.partIndex=t.getPartIndex(this.partId),t.setParameterValueByIndex(this.parameterIndex,1)}clone(){const t=new Re;return t.partId=this.partId,t.parameterIndex=this.parameterIndex,t.partIndex=this.partIndex,t.link=this.link.map((t=>t.clone())),t}}class Be{constructor(t=!1,e=new ft){this.isOverwritten=t,this.Color=e}}class Oe{constructor(t=!1,e=new ft){this.isOverwritten=t,this.Color=e}}class ke{constructor(t=!1,e=!1){this.isOverwritten=t,this.isCulling=e}}class Ue{update(){this._model.update(),this._model.drawables.resetDynamicFlags()}getPixelsPerUnit(){return null==this._model?0:this._model.canvasinfo.PixelsPerUnit}getCanvasWidth(){return null==this._model?0:this._model.canvasinfo.CanvasWidth/this._model.canvasinfo.PixelsPerUnit}getCanvasHeight(){return null==this._model?0:this._model.canvasinfo.CanvasHeight/this._model.canvasinfo.PixelsPerUnit}saveParameters(){const t=this._model.parameters.count,e=this._savedParameters.length;for(let i=0;ie&&(e=this._model.parameters.minimumValues[t]),this._parameterValues[t]=1==i?e:this._parameterValues[t]=this._parameterValues[t]*(1-i)+e*i)}setParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.setParameterValueByIndex(s,e,i)}addParameterValueByIndex(t,e,i=1){this.setParameterValueByIndex(t,this.getParameterValueByIndex(t)+e*i)}addParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.addParameterValueByIndex(s,e,i)}multiplyParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.multiplyParameterValueByIndex(s,e,i)}multiplyParameterValueByIndex(t,e,i=1){this.setParameterValueByIndex(t,this.getParameterValueByIndex(t)*(1+(e-1)*i))}getDrawableIds(){return this._drawableIds.slice()}getDrawableIndex(t){const e=this._model.drawables.count;for(let i=0;ie&&(t=e);for(let i=0;i=0&&this._partChildDrawables[n].push(t)}}}constructor(t){this._model=t,this._savedParameters=[],this._parameterIds=[],this._drawableIds=[],this._partIds=[],this._isOverwrittenModelMultiplyColors=!1,this._isOverwrittenModelScreenColors=!1,this._isOverwrittenCullings=!1,this._modelOpacity=1,this._userMultiplyColors=[],this._userScreenColors=[],this._userCullings=[],this._userPartMultiplyColors=[],this._userPartScreenColors=[],this._partChildDrawables=[],this._notExistPartId={},this._notExistParameterId={},this._notExistParameterValues={},this._notExistPartOpacities={},this.initialize()}release(){this._model.release(),this._model=void 0}}class Ve{static create(t,e){if(e){if(!this.hasMocConsistency(t))throw new Error("Inconsistent MOC3.")}const i=Live2DCubismCore.Moc.fromArrayBuffer(t);if(i){const e=new Ve(i);return e._mocVersion=Live2DCubismCore.Version.csmGetMocVersion(i,t),e}throw new Error("Failed to CubismMoc.create().")}createModel(){let t;const e=Live2DCubismCore.Model.fromMoc(this._moc);if(e)return t=new Ue(e),++this._modelCount,t;throw new Error("Unknown error")}deleteModel(t){null!=t&&--this._modelCount}constructor(t){this._moc=t,this._modelCount=0,this._mocVersion=0}release(){this._moc._release(),this._moc=void 0}getLatestMocVersion(){return Live2DCubismCore.Version.csmGetLatestMocVersion()}getMocVersion(){return this._mocVersion}static hasMocConsistency(t){return 1===Live2DCubismCore.Moc.prototype.hasMocConsistency(t)}}var Ne=(t=>(t[t.CubismPhysicsTargetType_Parameter=0]="CubismPhysicsTargetType_Parameter",t))(Ne||{}),Ge=(t=>(t[t.CubismPhysicsSource_X=0]="CubismPhysicsSource_X",t[t.CubismPhysicsSource_Y=1]="CubismPhysicsSource_Y",t[t.CubismPhysicsSource_Angle=2]="CubismPhysicsSource_Angle",t))(Ge||{});class Xe{constructor(){this.initialPosition=new dt(0,0),this.position=new dt(0,0),this.lastPosition=new dt(0,0),this.lastGravity=new dt(0,0),this.force=new dt(0,0),this.velocity=new dt(0,0)}}class ze{constructor(){this.normalizationPosition={},this.normalizationAngle={}}}class je{constructor(){this.source={}}}class We{constructor(){this.destination={},this.translationScale=new dt(0,0)}}class He{constructor(){this.settings=[],this.inputs=[],this.outputs=[],this.particles=[],this.gravity=new dt(0,0),this.wind=new dt(0,0),this.fps=0}}class Ye{constructor(t){this._json=t}release(){this._json=void 0}getGravity(){const t=new dt(0,0);return t.x=this._json.Meta.EffectiveForces.Gravity.X,t.y=this._json.Meta.EffectiveForces.Gravity.Y,t}getWind(){const t=new dt(0,0);return t.x=this._json.Meta.EffectiveForces.Wind.X,t.y=this._json.Meta.EffectiveForces.Wind.Y,t}getFps(){return this._json.Meta.Fps||0}getSubRigCount(){return this._json.Meta.PhysicsSettingCount}getTotalInputCount(){return this._json.Meta.TotalInputCount}getTotalOutputCount(){return this._json.Meta.TotalOutputCount}getVertexCount(){return this._json.Meta.VertexCount}getNormalizationPositionMinimumValue(t){return this._json.PhysicsSettings[t].Normalization.Position.Minimum}getNormalizationPositionMaximumValue(t){return this._json.PhysicsSettings[t].Normalization.Position.Maximum}getNormalizationPositionDefaultValue(t){return this._json.PhysicsSettings[t].Normalization.Position.Default}getNormalizationAngleMinimumValue(t){return this._json.PhysicsSettings[t].Normalization.Angle.Minimum}getNormalizationAngleMaximumValue(t){return this._json.PhysicsSettings[t].Normalization.Angle.Maximum}getNormalizationAngleDefaultValue(t){return this._json.PhysicsSettings[t].Normalization.Angle.Default}getInputCount(t){return this._json.PhysicsSettings[t].Input.length}getInputWeight(t,e){return this._json.PhysicsSettings[t].Input[e].Weight}getInputReflect(t,e){return this._json.PhysicsSettings[t].Input[e].Reflect}getInputType(t,e){return this._json.PhysicsSettings[t].Input[e].Type}getInputSourceId(t,e){return this._json.PhysicsSettings[t].Input[e].Source.Id}getOutputCount(t){return this._json.PhysicsSettings[t].Output.length}getOutputVertexIndex(t,e){return this._json.PhysicsSettings[t].Output[e].VertexIndex}getOutputAngleScale(t,e){return this._json.PhysicsSettings[t].Output[e].Scale}getOutputWeight(t,e){return this._json.PhysicsSettings[t].Output[e].Weight}getOutputDestinationId(t,e){return this._json.PhysicsSettings[t].Output[e].Destination.Id}getOutputType(t,e){return this._json.PhysicsSettings[t].Output[e].Type}getOutputReflect(t,e){return this._json.PhysicsSettings[t].Output[e].Reflect}getParticleCount(t){return this._json.PhysicsSettings[t].Vertices.length}getParticleMobility(t,e){return this._json.PhysicsSettings[t].Vertices[e].Mobility}getParticleDelay(t,e){return this._json.PhysicsSettings[t].Vertices[e].Delay}getParticleAcceleration(t,e){return this._json.PhysicsSettings[t].Vertices[e].Acceleration}getParticleRadius(t,e){return this._json.PhysicsSettings[t].Vertices[e].Radius}getParticlePosition(t,e){const i=new dt(0,0);return i.x=this._json.PhysicsSettings[t].Vertices[e].Position.X,i.y=this._json.PhysicsSettings[t].Vertices[e].Position.Y,i}}const qe="Angle";class $e{static create(t){const e=new $e;return e.parse(t),e._physicsRig.gravity.y=0,e}static delete(t){null!=t&&t.release()}parse(t){this._physicsRig=new He;const e=new Ye(t);this._physicsRig.gravity=e.getGravity(),this._physicsRig.wind=e.getWind(),this._physicsRig.subRigCount=e.getSubRigCount(),this._physicsRig.fps=e.getFps(),this._currentRigOutputs=[],this._previousRigOutputs=[];let i=0,s=0,r=0;for(let o=0;o=u.particleCount)continue;let s=new dt;s=g[i].position.substract(g[i-1].position),l=c[e].getValue(s,g,i,c[e].reflect,this._options.gravity),this._currentRigOutputs[x].outputs[e]=l,this._previousRigOutputs[x].outputs[e]=l;const r=c[e].destinationParameterIndex,o=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(m.subarray(r))):m.slice(r);ui(o,_[r],p[r],l,c[e]);for(let t=r,e=0;t=e)return;if(this._currentRemainTime+=e,this._currentRemainTime>5&&(this._currentRemainTime=0),p=t.getModel().parameters.values,_=t.getModel().parameters.maximumValues,f=t.getModel().parameters.minimumValues,x=t.getModel().parameters.defaultValues,(null!=(s=null==(i=this._parameterCaches)?void 0:i.length)?s:0)0?1/this._physicsRig.fps:e;this._currentRemainTime>=y;){for(let t=0;t=d.particleCount)continue;const r=new dt;r.x=m[s].position.x-m[s-1].position.x,r.y=m[s].position.y-m[s-1].position.y,h=g[e].getValue(r,m,s,g[e].reflect,this._options.gravity),this._currentRigOutputs[i].outputs[e]=h;const o=g[e].destinationParameterIndex,a=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(this._parameterCaches.subarray(o))):this._parameterCaches.slice(o);ui(a,f[o],_[o],h,g[e]);for(let t=o,e=0;t=2?e[i-1].position.substract(e[i-2].position):r.multiplyByScaler(-1),o=gt.directionToRadian(r,t),s&&(o*=-1),o}function ri(t,e){return Math.min(t,e)+function(t,e){return Math.abs(Math.max(t,e)-Math.min(t,e))}(t,e)/2}function oi(t,e){return t.x}function ai(t,e){return t.y}function ni(t,e){return e}function li(t,e,i,s,r,o,a,n){let l,h,u,d,c=new dt(0,0),g=new dt(0,0),m=new dt(0,0),p=new dt(0,0);t[0].position=new dt(i.x,i.y),l=gt.degreesToRadian(s),d=gt.radianToDirection(l),d.normalize();for(let _=1;_i&&(a>r.valueExceededMaximum&&(r.valueExceededMaximum=a),a=i),n=r.weight/100,n>=1||(a=t[0]*(1-n)+a*n),t[0]=a}function di(t,e,i,s,r,o,a,n){let l=0;const h=gt.max(i,e);ht&&(t=u);const d=gt.min(r,o),c=gt.max(r,o),g=a,m=ri(u,h),p=t-m;switch(Math.sign(p)){case 1:{const t=c-g,e=h-m;0!=e&&(l=p*(t/e),l+=g);break}case-1:{const t=d-g,e=u-m;0!=e&&(l=p*(t/e),l+=g);break}case 0:l=g}return n?l:-1*l}function ci(){var t;null==(t=this.__moc)||t.release()}V.registerRuntime({version:4,ready:Fe,test:t=>t instanceof Ut||Ut.isValidJSON(t),isValidMoc(t){if(t.byteLength<4)return!1;const e=new Int8Array(t,0,4);return"MOC3"===String.fromCharCode(...e)},createModelSettings:t=>new Ut(t),createCoreModel(t,e){const i=Ve.create(t,!!(null==e?void 0:e.checkMocConsistency));try{const t=i.createModel();return t.__moc=i,t}catch(s){try{i.release()}catch(r){}throw s}},createInternalModel(t,e,i){const s=new Te(t,e,i),r=t;return r.__moc&&(s.__moc=r.__moc,delete r.__moc,s.once("destroy",ci)),s},createPhysics:(t,e)=>$e.create(e),createPose:(t,e)=>De.create(e)}),t.Cubism2ExpressionManager=tt,t.Cubism2InternalModel=rt,t.Cubism2ModelSettings=ot,t.Cubism2MotionManager=et,t.Cubism4ExpressionManager=Ot,t.Cubism4InternalModel=Te,t.Cubism4ModelSettings=Ut,t.Cubism4MotionManager=se,t.ExpressionManager=_,t.FileLoader=$,t.FocusController=f,t.InteractionMixin=N,t.InternalModel=S,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DExpression=K,t.Live2DEyeBlink=it,t.Live2DFactory=V,t.Live2DLoader=L,t.Live2DModel=Y,t.Live2DPhysics=lt,t.Live2DPose=ut,t.Live2DTransform=z,t.ModelSettings=x,t.MotionManager=P,t.MotionPreloadStrategy=v,t.MotionPriority=y,t.MotionState=M,t.SoundManager=C,t.VERSION="0.4.0",t.XHRLoader=T,t.ZipLoader=Z,t.applyMixins=g,t.clamp=h,t.copyArray=c,t.copyProperty=d,t.cubism4Ready=Fe,t.folderName=m,t.logger=l,t.rand=u,t.remove=p,t.startUpCubism4=Ae,Object.defineProperties(t,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));