diff --git a/dist/cubism4.es.js b/dist/cubism4.es.js index 929cc21..597e401 100644 --- a/dist/cubism4.es.js +++ b/dist/cubism4.es.js @@ -1476,7 +1476,7 @@ var LogLevel = /* @__PURE__ */ ((LogLevel2) => { LogLevel2[LogLevel2["LogLevel_Off"] = 5] = "LogLevel_Off"; return LogLevel2; })(LogLevel || {}); -const CSM_ASSERT = process.env.NODE_ENV === "production" ? () => { +const CSM_ASSERT = typeof process !== "undefined" && process.env.NODE_ENV === "production" ? () => { } : (expr) => console.assert(expr); function CubismLogVerbose(fmt, ...args) { CubismDebug.print(LogLevel.LogLevel_Verbose, "[CSM][V]" + fmt + "\n", args); diff --git a/dist/cubism4.js b/dist/cubism4.js index 83005e9..69a5372 100644 --- a/dist/cubism4.js +++ b/dist/cubism4.js @@ -1478,7 +1478,7 @@ var __async = (__this, __arguments, generator) => { LogLevel2[LogLevel2["LogLevel_Off"] = 5] = "LogLevel_Off"; return LogLevel2; })(LogLevel || {}); - const CSM_ASSERT = process.env.NODE_ENV === "production" ? () => { + const CSM_ASSERT = typeof process !== "undefined" && process.env.NODE_ENV === "production" ? () => { } : (expr) => console.assert(expr); function CubismLogVerbose(fmt, ...args) { CubismDebug.print(LogLevel.LogLevel_Verbose, "[CSM][V]" + fmt + "\n", args); diff --git a/dist/cubism4.min.js b/dist/cubism4.min.js index 4592483..5b41247 100644 --- a/dist/cubism4.min.js +++ b/dist/cubism4.min.js @@ -1 +1 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("@pixi/core"),require("@pixi/display")):"function"==typeof define&&define.amd?define(["exports","@pixi/core","@pixi/display"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).PIXI=t.PIXI||{},t.PIXI.live2d=t.PIXI.live2d||{}),t.PIXI,t.PIXI)}(this,(function(t,e,i){"use strict";var s=Object.defineProperty,r=Math.pow,o=(t,e,i)=>(((t,e,i)=>{e in t?s(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i})(t,"symbol"!=typeof e?e+"":e,i),i),a=(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())}));class n{constructor(){this._breathParameters=[],this._currentTime=0}static create(){return new n}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&&(r=1,this._blinkingState=3,this._stateStartTimeSeconds=this._userTimeSeconds),s=1-r;break;case 3:r=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._closedSeconds,r>=1&&(this._blinkingState=4,this._stateStartTimeSeconds=this._userTimeSeconds),s=0;break;case 4:r=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._openingSeconds,r>=1&&(r=1,this._blinkingState=1,this._nextBlinkingTime=this.determinNextBlinkingTiming()),s=r;break;case 1:this._nextBlinkingTime(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))(d||{});class c{static create(t){const e=new c;"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 g{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 g;return t.partId=this.partId,t.parameterIndex=this.parameterIndex,t.partIndex=this.partIndex,t.link=this.link.map((t=>t.clone())),t}}class m{constructor(t,e){this.x=t||0,this.y=e||0}add(t){const e=new m(0,0);return e.x=this.x+t.x,e.y=this.y+t.y,e}substract(t){const e=new m(0,0);return e.x=this.x-t.x,e.y=this.y-t.y,e}multiply(t){const e=new m(0,0);return e.x=this.x*t.x,e.y=this.y*t.y,e}multiplyByScaler(t){return this.multiply(new m(t,t))}division(t){const e=new m(0,0);return e.x=this.x/t.x,e.y=this.y/t.y,e}divisionByScalar(t){return this.division(new m(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 p=class t{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 m;return e.x=this.sin(t),e.y=this.cos(t),e}static quadraticEquation(e,i,s){return this.abs(e)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 f,this._mvpMatrix4x4.loadIdentity()}}var C=(t=>(t[t.CubismBlendMode_Normal=0]="CubismBlendMode_Normal",t[t.CubismBlendMode_Additive=1]="CubismBlendMode_Additive",t[t.CubismBlendMode_Multiplicative=2]="CubismBlendMode_Multiplicative",t))(C||{});class y{constructor(t=1,e=1,i=1,s=1){this.R=t,this.G=e,this.B=i,this.A=s}}let M,v=!1,P=!1;const b={vertexOffset:0,vertexStep:2};class S{static startUp(t){if(v)return E("CubismFramework.startUp() is already done."),v;if(Live2DCubismCore._isStarted)return v=!0,!0;if(Live2DCubismCore._isStarted=!0,M=t,M&&Live2DCubismCore.Logging.csmSetLogFunction(M.logFunction),v=!0,v){const t=Live2DCubismCore.Version.csmGetVersion(),e=(16711680&t)>>16,i=65535&t,s=t;E("Live2D Cubism Core version: {0}.{1}.{2} ({3})",("00"+((4278190080&t)>>24)).slice(-2),("00"+e).slice(-2),("0000"+i).slice(-4),s)}return E("CubismFramework.startUp() is complete."),v}static cleanUp(){v=!1,P=!1,M=void 0}static initialize(t=0){v?P?L("CubismFramework.initialize() skipped, already initialized."):(Live2DCubismCore.Memory.initializeAmountOfMemory(t),P=!0,E("CubismFramework.initialize() is complete.")):L("CubismFramework is not started.")}static dispose(){v?P?(x.staticRelease(),P=!1,E("CubismFramework.dispose() is complete.")):L("CubismFramework.dispose() skipped, not initialized."):L("CubismFramework is not started.")}static isStarted(){return v}static isInitialized(){return P}static coreLogFunction(t){Live2DCubismCore.Logging.csmGetLogFunction()&&Live2DCubismCore.Logging.csmGetLogFunction()(t)}static getLoggingLevel(){return null!=M?M.loggingLevel:5}constructor(){}}var w=(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))(w||{});const T="production"===process.env.NODE_ENV?()=>{}:t=>console.assert(t);function I(t,...e){A.print(w.LogLevel_Debug,"[CSM][D]"+t+"\n",e)}function E(t,...e){A.print(w.LogLevel_Info,"[CSM][I]"+t+"\n",e)}function L(t,...e){A.print(w.LogLevel_Warning,"[CSM][W]"+t+"\n",e)}function F(t,...e){A.print(w.LogLevel_Error,"[CSM][E]"+t+"\n",e)}class A{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 D{constructor(t=!1,e=new y){this.isOverwritten=t,this.Color=e}}class B{constructor(t=!1,e=new y){this.isOverwritten=t,this.Color=e}}class R{constructor(t=!1,e=!1){this.isOverwritten=t,this.isCulling=e}}class O{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 k{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 k(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 O(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 U{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 V{static create(t,e){const i=new V;return i.parseUserData(t,e),i}getArtMeshUserDatas(){return this._artMeshUserDataNode}parseUserData(t,e){const i=new U(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))(z||{});t.CubismConfig=void 0,(X=t.CubismConfig||(t.CubismConfig={})).supportMoreMaskDivisions=!0,X.setOpacityFromMotion=!1;var j=(t=>(t[t.CubismMotionCurveTarget_Model=0]="CubismMotionCurveTarget_Model",t[t.CubismMotionCurveTarget_Parameter=1]="CubismMotionCurveTarget_Parameter",t[t.CubismMotionCurveTarget_PartOpacity=2]="CubismMotionCurveTarget_PartOpacity",t))(j||{}),H=(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))(H||{});class W{constructor(t=0,e=0){this.time=t,this.value=e}}class Y{constructor(){this.basePointIndex=0,this.segmentType=0}}class q{constructor(){this.id="",this.type=0,this.segmentCount=0,this.baseSegmentIndex=0,this.fadeInTime=0,this.fadeOutTime=0}}class ${constructor(){this.fireTime=0,this.value=""}}class J{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 Z{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 0==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 Q=(t=>(t[t.EvaluationOptionFlag_AreBeziersRistricted=0]="EvaluationOptionFlag_AreBeziersRistricted",t))(Q||{});const K="Opacity";function tt(t,e,i){const s=new W;return s.time=t.time+(e.time-t.time)*i,s.value=t.value+(e.value-t.value)*i,s}function et(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 it(t,e){let i=(e-t[0].time)/(t[3].time-t[0].time);i<0&&(i=0);const s=tt(t[0],t[1],i),r=tt(t[1],t[2],i),o=tt(t[2],t[3],i),a=tt(s,r,i),n=tt(r,o,i);return tt(a,n,i).value}function st(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=_.cardanoAlgorithmForBezier(n,l,h,u),c=tt(t[0],t[1],d),g=tt(t[1],t[2],d),m=tt(t[2],t[3],d),p=tt(c,g,d),f=tt(g,m,d);return tt(p,f,d).value}function rt(t,e){return t[0].value}function ot(t,e){return t[1].value}function at(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 nt extends N{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 nt;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=K);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&&I("too many eye blink targets : {0}",this._eyeBlinkParameterIds.length),this._lipSyncParameterIds.length>l&&I("too many lip sync targets : {0}",this._lipSyncParameterIds.length);const d=this._fadeInSeconds<=0?1:_.getEasingSine((i-r.getFadeInStartTime())/this._fadeInSeconds),c=this._fadeOutSeconds<=0||r.getEndTime()<0?1:_.getEasingSine((r.getEndTime()-i)/this._fadeOutSeconds);let g,m,p,f=o;if(this._isLoop)for(;f>this._motionData.duration;)f-=this._motionData.duration;const x=this._motionData.curves;for(m=0;m>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(;m=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 q)),this._motionData.segments=Array.from({length:e.getMotionTotalSegmentCount()}).map((()=>new Y)),this._motionData.events=Array.from({length:this._motionData.eventCount}).map((()=>new $)),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))(dt||{}),ct=(t=>(t[t.CubismPhysicsSource_X=0]="CubismPhysicsSource_X",t[t.CubismPhysicsSource_Y=1]="CubismPhysicsSource_Y",t[t.CubismPhysicsSource_Angle=2]="CubismPhysicsSource_Angle",t))(ct||{});class gt{constructor(){this.initialPosition=new m(0,0),this.position=new m(0,0),this.lastPosition=new m(0,0),this.lastGravity=new m(0,0),this.force=new m(0,0),this.velocity=new m(0,0)}}class mt{constructor(){this.normalizationPosition={},this.normalizationAngle={}}}class pt{constructor(){this.source={}}}class _t{constructor(){this.destination={},this.translationScale=new m(0,0)}}class ft{constructor(){this.settings=[],this.inputs=[],this.outputs=[],this.particles=[],this.gravity=new m(0,0),this.wind=new m(0,0),this.fps=0}}class xt{constructor(t){this._json=t}release(){this._json=void 0}getGravity(){const t=new m(0,0);return t.x=this._json.Meta.EffectiveForces.Gravity.X,t.y=this._json.Meta.EffectiveForces.Gravity.Y,t}getWind(){const t=new m(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 m(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 Ct="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 ft;const e=new xt(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 m;s=g[i].position.substract(g[i-1].position),l=c[e].getValue(s,g,i,c[e].reflect,this._options.gravity),this._currentRigOutputs[y].outputs[e]=l,this._previousRigOutputs[y].outputs[e]=l;const r=c[e].destinationParameterIndex,o=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(p.subarray(r))):p.slice(r);Rt(o,x[r],f[r],l,c[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,x=t.getModel().parameters.maximumValues,C=t.getModel().parameters.minimumValues,y=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 m;r.x=p[s].position.x-p[s-1].position.x,r.y=p[s].position.y-p[s-1].position.y,h=g[e].getValue(r,p,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);Rt(a,C[o],x[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=_.directionToRadian(r,t),s&&(o*=-1),o}function Et(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 Lt(t,e){return t.x}function Ft(t,e){return t.y}function At(t,e){return e}function Dt(t,e,i,s,r,o,a,n){let l,h,u,d,c=new m(0,0),g=new m(0,0),p=new m(0,0),f=new m(0,0);t[0].position=new m(i.x,i.y),l=_.degreesToRadian(s),d=_.radianToDirection(l),d.normalize();for(let x=1;xi&&(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 Ot(t,e,i,s,r,o,a,n){let l=0;const h=_.max(i,e);ht&&(t=u);const d=_.min(r,o),c=_.max(r,o),g=a,m=Et(u,h),p=t-m;switch(Math.sign(p)){case 1:{const t=h-m;0!=t&&(l=p*((c-g)/t),l+=g);break}case-1:{const t=u-m;0!=t&&(l=p*((d-g)/t),l+=g);break}case 0:l=g}return n?l:-1*l}class kt{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 Ut,Vt,Nt;class Gt{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 kt,this._tmpMatrix=new f,this._tmpMatrixForMask=new f,this._tmpMatrixForDraw=new f;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&&F("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)&&(u+=h(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))(Wt||{});const Yt="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;}",qt="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;}",$t="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;}",Jt="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;}",Zt="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);}",Qt="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;}",Kt="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 te extends x{initialize(t,e=1){t.isUsingMasking()&&(this._clippingManager=new Gt,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 Gt,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}constructor(){super(),this._clippingContextBufferForMask=null,this._clippingContextBufferForDraw=null,this._rendererProfile=new jt,this.firstDraw=!0,this._textures={},this._sortedDrawableIndexList=[],this._bufferData={vertex:null,uv:null,index:null}}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 F("'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),Ht.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")}}x.staticRelease=()=>{te.doStaticRelease()};class ee{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 ie="ParamAngleX",se="ParamAngleY",re="ParamAngleZ",oe="ParamEyeBallX",ae="ParamEyeBallY",ne="ParamMouthForm",le="ParamBodyAngleX",he="ParamBreath",ue={LOG_LEVEL_VERBOSE:0,LOG_LEVEL_WARNING:1,LOG_LEVEL_ERROR:2,LOG_LEVEL_NONE:999,logLevel:1,sound:!0,motionSync:!0,motionFadingDuration:500,idleMotionFadingDuration:2e3,expressionFadingDuration:500,preserveExpressionOnMotion:!0,cubism4:t.CubismConfig},de={log(t,...e){ue.logLevel<=ue.LOG_LEVEL_VERBOSE&&console.log(`[${t}]`,...e)},warn(t,...e){ue.logLevel<=ue.LOG_LEVEL_WARNING&&console.warn(`[${t}]`,...e)},error(t,...e){ue.logLevel<=ue.LOG_LEVEL_ERROR&&console.error(`[${t}]`,...e)}};function ce(t,e,i){return ti?i:t}function ge(t,e){e.forEach((e=>{Object.getOwnPropertyNames(e.prototype).forEach((i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i))}))}))}function me(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 pe(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}class _e extends e.utils.EventEmitter{constructor(t,e){super(),o(this,"tag"),o(this,"settings"),o(this,"expressions",[]),o(this,"defaultExpression"),o(this,"currentExpression"),o(this,"reserveExpressionIndex",-1),o(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 a(this,null,(function*(){if(!this.definitions[t])return void de.warn(this.tag,`Undefined expression at [${t}]`);if(null===this.expressions[t])return void de.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 a(this,null,(function*(){if(this.definitions.length){const t=[];for(let e=0;e-1&&th&&(a*=h/l,n*=h/l),this.vx+=a,this.vy+=n;const u=Math.sqrt(r(this.vx,2)+r(this.vy,2)),d=.5*(Math.sqrt(r(h,2)+8*h*s)-h);u>d&&(this.vx*=d/u,this.vy*=d/u),this.x+=this.vx,this.y+=this.vy}}class ye{constructor(t){o(this,"json"),o(this,"name"),o(this,"url"),o(this,"pose"),o(this,"physics"),this.json=t;const 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=me(this.url)}resolveURL(t){return e.utils.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 Me=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(Me||{});class ve{constructor(){o(this,"tag"),o(this,"debug",!1),o(this,"currentPriority",0),o(this,"reservePriority",0),o(this,"currentGroup"),o(this,"currentIndex"),o(this,"reservedGroup"),o(this,"reservedIndex"),o(this,"reservedIdleGroup"),o(this,"reservedIdleIndex")}reserve(t,e,i){if(i<=0)return de.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(t===this.currentGroup&&e===this.currentIndex)return de.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 de.log(this.tag,"Motion is already reserved.",this.dump(t,e)),!1;if(1===i){if(0!==this.currentPriority)return de.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,e)),!1;if(void 0!==this.reservedIdleGroup)return de.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 de.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 de.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 de.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 de.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!ue.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""}}const Pe=.5;class be{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,s){const r=new Audio(t);return r.volume=this._volume,r.preload="auto",r.crossOrigin=s,r.addEventListener("ended",(()=>{this.dispose(r),null==e||e()})),r.addEventListener("error",(e=>{this.dispose(r),de.warn("SoundManager",`Error occurred on "${t}"`,e.error),null==i||i(e.error)})),this.audios.push(r),r}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){const e=new Float32Array(t.fftSize);let 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"),pe(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])}}o(be,"audios",[]),o(be,"analysers",[]),o(be,"contexts",[]),o(be,"_volume",Pe);var Se=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(Se||{});class we extends e.utils.EventEmitter{constructor(t,e){super(),o(this,"tag"),o(this,"settings"),o(this,"motionGroups",{}),o(this,"state",new ve),o(this,"currentAudio"),o(this,"currentAnalyzer"),o(this,"currentContext"),o(this,"playing",!1),o(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{console.log("Audio finished playing"),null==o||o(),s&&i&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0}),((t,e=this)=>{console.log("Error during audio playback:",t),null==a||a(t),s&&i&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),r),this.currentAudio=n,be.volume=e,h=be.addContext(this.currentAudio),this.currentContext=h,l=be.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=l}catch(g){return de.warn(this.tag,"Failed to create audio",u,g),!1}if(n){let t=!0;const e=be.play(n).catch((e=>{de.warn(this.tag,"Failed to play audio",n.src,e),t=!1}));if(ue.motionSync&&(yield e,!t))return!1}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),i&&this.expressionManager&&this.expressionManager.setExpression(i),this.playing=!0,!0}))}startMotion(t,e){return a(this,arguments,(function*(t,e,i=Me.NORMAL,{sound:s,volume:r=.5,expression:o,resetExpression:a=!0,crossOrigin:n,onFinish:l,onError:h}={}){var u;if(!this.state.reserve(t,e,i))return!1;if(this.currentAudio&&!this.currentAudio.ended&&i!=Me.FORCE)return!1;const d=null==(u=this.definitions[t])?void 0:u[e];if(!d)return!1;let c,g,m,p;this.currentAudio&&be.dispose(this.currentAudio);const _=s&&s.startsWith("data:");if(s&&!_){const t=document.createElement("a");t.href=s,p=s=t.href}else p=this.getSoundFile(d),p&&(p=this.settings.resolveURL(p));const f=p;if(f)try{c=be.add(f,((t=this)=>{console.log("Audio finished playing"),null==l||l(),console.log(l),a&&o&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0}),((t,e=this)=>{console.log("Error during audio playback:",t),null==h||h(t),a&&o&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),n),this.currentAudio=c,be.volume=r,m=be.addContext(this.currentAudio),this.currentContext=m,g=be.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=g}catch(C){de.warn(this.tag,"Failed to create audio",p,C)}const x=yield this.loadMotion(t,e);if(c){const t=be.play(c).catch((t=>de.warn(this.tag,"Failed to play audio",c.src,t)));ue.motionSync&&(yield t)}return this.state.start(x,t,e,i)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),de.log(this.tag,"Start motion:",this.getMotionName(d)),this.emit("motionStart",t,e,c),o&&this.expressionManager&&this.state.shouldOverrideExpression()&&this.expressionManager.setExpression(o),this.playing=!0,this._startMotion(x),!0):(c&&(be.dispose(c),this.currentAudio=void 0),!1)}))}startRandomMotion(t,e){return a(this,arguments,(function*(t,e,{sound:i,volume:s=.5,expression:r,resetExpression:o=!0,crossOrigin:a,onFinish:n,onError:l}={}){const h=this.definitions[t];if(null==h?void 0:h.length){const u=[];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,Te);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!==a.status&&0!==a.status||!a.response?a.onerror():r(a.response)},a.onerror=()=>{de.warn("XHRLoader",`Failed to load resource as ${a.responseType} (Status ${a.status}): ${i}`),o(new Ee("Network error.",i,a.status))},a.onabort=()=>o(new Ee("Aborted.",i,a.status,!0)),a.onloadend=()=>{var i;t.allXhrSet.delete(a),e&&(null==(i=t.xhrMap.get(e))||i.delete(a))},a}static cancelXHRs(){var e;null==(e=t.xhrMap.get(this))||e.forEach((e=>{e.abort(),t.allXhrSet.delete(e)})),t.xhrMap.delete(this)}static release(){t.allXhrSet.forEach((t=>t.abort())),t.allXhrSet.clear(),t.xhrMap=new WeakMap}};o(Le,"xhrMap",new WeakMap),o(Le,"allXhrSet",new Set),o(Le,"loader",((t,e)=>new Promise(((e,i)=>{Le.createXHR(t.target,t.settings?t.settings.resolveURL(t.url):t.url,t.type,(i=>{t.result=i,e()}),i).send()}))));let Fe=Le;function Ae(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)}class De{static load(t){return Ae(this.middlewares,t).then((()=>t.result))}}function Be(){}o(De,"middlewares",[Fe.loader]);const Re="Live2DFactory",Oe=(t,e)=>a(this,null,(function*(){if("string"==typeof t.source){const e=yield De.load({url:t.source,type:"json",target:t.live2dModel});e.url=t.source,t.source=e,t.live2dModel.emit("settingsJSONLoaded",e)}return e()})),ke=(t,e)=>a(this,null,(function*(){if(t.source instanceof ye)return t.settings=t.source,e();if("object"==typeof t.source){const i=Ye.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.")})),Ue=(t,e)=>{if(t.settings){const i=Ye.findRuntime(t.settings);if(i)return i.ready().then(e)}return e()},Ve=(t,e)=>a(this,null,(function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=Ye.findRuntime(e);if(s){const r=[];e.pose&&r.push(De.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),de.warn(Re,"Failed to load pose.",e)}))),e.physics&&r.push(De.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),de.warn(Re,"Failed to load physics.",e)}))),r.length&&(yield Promise.all(r))}}})),Ne=(t,i)=>a(this,null,(function*(){if(!t.settings)throw new TypeError("Missing settings.");{const s=t.live2dModel,r=Promise.all(t.settings.textures.map((i=>function(t,i={}){const s={resourceOptions:{crossorigin:i.crossOrigin}};if(e.Texture.fromURL)return e.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=e.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 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(i),{crossOrigin:t.options.crossOrigin}))));if(r.catch(Be),yield i(),!t.internalModel)throw new TypeError("Missing internal model.");s.internalModel=t.internalModel,s.emit("modelLoaded",t.internalModel),s.textures=yield r,s.emit("textureLoaded",s.textures)}})),Ge=(t,e)=>a(this,null,(function*(){const i=t.settings;if(i instanceof ye){const s=Ye.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield De.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.")})),Xe=class t{static unzip(i,s){return a(this,null,(function*(){const r=yield t.getFilePaths(i),o=[];for(const t of s.getDefinedFiles()){const i=decodeURI(e.utils.url.resolve(s.url,t));r.includes(i)&&o.push(i)}const a=yield t.getFiles(i,o);for(let t=0;tt.endsWith("model.json")||t.endsWith("model3.json")));if(!i)throw new Error("Settings file not found");const s=yield t.readText(e,i);if(!s)throw new Error("Empty settings file: "+i);const r=JSON.parse(s);r.url=i;const o=t.live2dFactory.findRuntime(r);if(!o)throw new Error("Unknown settings JSON");return o.createModelSettings(r)}))}static zipReader(t,e){return a(this,null,(function*(){throw new Error("Not implemented")}))}static getFilePaths(t){return a(this,null,(function*(){throw new Error("Not implemented")}))}static getFiles(t,e){return a(this,null,(function*(){throw new Error("Not implemented")}))}static readText(t,e){return a(this,null,(function*(){throw new Error("Not implemented")}))}static releaseReader(t){}};o(Xe,"live2dFactory"),o(Xe,"ZIP_PROTOCOL","zip://"),o(Xe,"uid",0),o(Xe,"factory",((t,e)=>a(Xe,null,(function*(){const i=t.source;let s,r,o;if("string"==typeof i&&(i.endsWith(".zip")||i.startsWith(Xe.ZIP_PROTOCOL))?(s=i.startsWith(Xe.ZIP_PROTOCOL)?i.slice(Xe.ZIP_PROTOCOL.length):i,r=yield De.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 Xe.zipReader(r,s);o||(o=yield Xe.createSettings(e)),o._objectURL=Xe.ZIP_PROTOCOL+Xe.uid+"/"+o.url;const i=yield Xe.unzip(e,o);i.settings=o,t.source=i,s.startsWith("blob:")&&t.live2dModel.once("modelLoaded",(t=>{t.once("destroy",(function(){URL.revokeObjectURL(s)}))})),Xe.releaseReader(e)}return e()}))));let ze=Xe;const je=class t{static resolveURL(e,i){var s;const r=null==(s=t.filesMap[e])?void 0:s[i];if(void 0===r)throw new Error("Cannot find this file from uploaded files: "+i);return r}static upload(i,s){return a(this,null,(function*(){const r={};for(const t of s.getDefinedFiles()){const o=decodeURI(e.utils.url.resolve(s.url,t)),a=i.find((t=>t.webkitRelativePath===o));a&&(r[t]=URL.createObjectURL(a))}t.filesMap[s._objectURL]=r}))}static createSettings(e){return a(this,null,(function*(){const i=e.find((t=>t.name.endsWith("model.json")||t.name.endsWith("model3.json")));if(!i)throw new TypeError("Settings file not found");const s=yield t.readText(i),r=JSON.parse(s);r.url=i.webkitRelativePath;const o=Ye.findRuntime(r);if(!o)throw new Error("Unknown settings JSON");const a=o.createModelSettings(r);return a._objectURL=URL.createObjectURL(i),a}))}static readText(t){return a(this,null,(function*(){return new Promise(((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")}))}))}};o(je,"live2dFactory"),o(je,"filesMap",{}),o(je,"factory",((t,e)=>a(je,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 je.createSettings(e);i.validateFiles(e.map((t=>encodeURI(t.webkitRelativePath)))),yield je.upload(e,i),i.resolveURL=function(t){return je.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),je.filesMap[t])for(const e of Object.values(je.filesMap[t]))URL.revokeObjectURL(e);delete je.filesMap[t]}))}))}return e()}))));let He=je;const We=class t{static registerRuntime(e){t.runtimes.push(e),t.runtimes.sort(((t,e)=>e.version-t.version))}static findRuntime(e){for(const i of t.runtimes)if(i.test(e))return i}static setupLive2DModel(e,i,s){return a(this,null,(function*(){const r=new Promise((t=>e.once("textureLoaded",t))),o=new Promise((t=>e.once("modelLoaded",t))),a=Promise.all([r,o]).then((()=>e.emit("ready")));yield Ae(t.live2DModelMiddlewares,{live2dModel:e,source:i,options:s||{}}),yield a,e.emit("load")}))}static loadMotion(e,i,s){var r;const o=t=>e.emit("motionLoadError",i,s,t);try{const a=null==(r=e.definitions[i])?void 0:r[s];if(!a)return Promise.resolve(void 0);e.listeners("destroy").includes(t.releaseTasks)||e.once("destroy",t.releaseTasks);let n=t.motionTasksMap.get(e);n||(n={},t.motionTasksMap.set(e,n));let l=n[i];l||(l=[],n[i]=l);const h=e.getMotionFile(a);return null!=l[s]||(l[s]=De.load({url:h,settings:e.settings,type:e.motionDataType,target:e}).then((r=>{var o;const n=null==(o=t.motionTasksMap.get(e))?void 0:o[i];n&&delete n[s];const l=e.createMotion(r,i,a);return e.emit("motionLoaded",i,s,l),l})).catch((t=>{de.warn(e.tag,`Failed to load motion: ${h}\n`,t),o(t)}))),l[s]}catch(a){de.warn(e.tag,`Failed to load motion at "${i}"[${s}]\n`,a),o(a)}return Promise.resolve(void 0)}static loadExpression(e,i){const s=t=>e.emit("expressionLoadError",i,t);try{const r=e.definitions[i];if(!r)return Promise.resolve(void 0);e.listeners("destroy").includes(t.releaseTasks)||e.once("destroy",t.releaseTasks);let o=t.expressionTasksMap.get(e);o||(o=[],t.expressionTasksMap.set(e,o));const a=e.getExpressionFile(r);return null!=o[i]||(o[i]=De.load({url:a,settings:e.settings,type:"json",target:e}).then((s=>{const o=t.expressionTasksMap.get(e);o&&delete o[i];const a=e.createExpression(s,r);return e.emit("expressionLoaded",i,a),a})).catch((t=>{de.warn(e.tag,`Failed to load expression: ${a}\n`,t),s(t)}))),o[i]}catch(r){de.warn(e.tag,`Failed to load expression at [${i}]\n`,r),s(r)}return Promise.resolve(void 0)}static releaseTasks(){this instanceof we?t.motionTasksMap.delete(this):t.expressionTasksMap.delete(this)}};o(We,"runtimes",[]),o(We,"urlToJSON",Oe),o(We,"jsonToSettings",ke),o(We,"waitUntilReady",Ue),o(We,"setupOptionals",Ve),o(We,"setupEssentials",Ne),o(We,"createInternalModel",Ge),o(We,"live2DModelMiddlewares",[ze.factory,He.factory,Oe,ke,Ue,Ve,Ne,Ge]),o(We,"motionTasksMap",new WeakMap),o(We,"expressionTasksMap",new WeakMap);let Ye=We;we.prototype._loadMotion=function(t,e){return Ye.loadMotion(this,t,e)},_e.prototype._loadExpression=function(t){return Ye.loadExpression(this,t)},He.live2dFactory=Ye,ze.live2dFactory=Ye;const qe=class t{constructor(e,{autoUpdate:i=!0,autoHitTest:s=!0,autoFocus:r=!0,autoInteract:a,ticker:n}={}){o(this,"model"),o(this,"destroyed",!1),o(this,"_ticker"),o(this,"_autoUpdate",!1),o(this,"_autoHitTest",!1),o(this,"_autoFocus",!1),n||(t.defaultTicker?n=t.defaultTicker:"undefined"!=typeof PIXI&&(n=PIXI.Ticker.shared)),void 0!==a&&(s=a,r=a,de.warn(e.tag,"options.autoInteract is deprecated since v0.5.0, use autoHitTest and autoFocus instead.")),this.model=e,this.ticker=n,this.autoUpdate=i,this.autoHitTest=s,this.autoFocus=r,(s||r)&&(this.model.eventMode="static")}get ticker(){return this._ticker}set ticker(t){var e;this._ticker&&this._ticker.remove(Je,this),this._ticker=t,this._autoUpdate&&(null==(e=this._ticker)||e.add(Je,this))}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){var e;this.destroyed||(t?this._ticker?(this._ticker.add(Je,this),this._autoUpdate=!0):de.warn(this.model.tag,"No Ticker to be used for automatic updates. Either set option.ticker when creating Live2DModel, or expose PIXI to global scope (window.PIXI = PIXI)."):(null==(e=this._ticker)||e.remove(Je,this),this._autoUpdate=!1))}get autoHitTest(){return this._autoHitTest}set autoHitTest(t){t!==this.autoHitTest&&(t?this.model.on("pointertap",Ze,this):this.model.off("pointertap",Ze,this),this._autoHitTest=t)}get autoFocus(){return this._autoFocus}set autoFocus(t){t!==this.autoFocus&&(t?this.model.on("globalpointermove",Qe,this):this.model.off("globalpointermove",Qe,this),this._autoFocus=t)}get autoInteract(){return this._autoHitTest&&this._autoFocus}set autoInteract(t){this.autoHitTest=t,this.autoFocus=t}onTickerUpdate(){const t=this.ticker.deltaMS;this.model.update(t)}onTap(t){this.model.tap(t.global.x,t.global.y)}onPointerMove(t){this.model.focus(t.global.x,t.global.y)}destroy(){this.autoFocus=!1,this.autoHitTest=!1,this.autoUpdate=!1,this.ticker=void 0,this.destroyed=!0}};o(qe,"defaultTicker");let $e=qe;function Je(){this.onTickerUpdate()}function Ze(t){this.onTap(t)}function Qe(t){this.onPointerMove(t)}class Ke extends e.Transform{}const ti=new e.Point,ei=new e.Matrix;class ii extends i.Container{constructor(t){super(),o(this,"tag","Live2DModel(uninitialized)"),o(this,"internalModel"),o(this,"textures",[]),o(this,"transform",new Ke),o(this,"anchor",new e.ObservablePoint(this.onAnchorChange,this,0,0)),o(this,"glContextID",-1),o(this,"elapsedTime",0),o(this,"deltaTime",0),o(this,"automator"),this.automator=new $e(this,t),this.once("modelLoaded",(()=>this.init(t)))}static from(t,e){const i=new this(e);return Ye.setupLive2DModel(i,t,e).then((()=>i))}static fromSync(t,e){const i=new this(e);return Ye.setupLive2DModel(i,t,e).then(null==e?void 0:e.onLoad).catch(null==e?void 0:e.onError),i}static registerTicker(t){$e.defaultTicker=t.shared}init(t){this.tag=`Live2DModel(${this.internalModel.settings.name})`}onAnchorChange(){this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(t,e,i,{sound:s,volume:r=.5,expression:o,resetExpression:a=!0,crossOrigin:n,onFinish:l,onError:h}={}){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i,{sound:s,volume:r,expression:o,resetExpression:a,crossOrigin:n,onFinish:l,onError:h}):this.internalModel.motionManager.startMotion(t,e,i,{sound:s,volume:r,expression:o,resetExpression:a,crossOrigin:n,onFinish:l,onError:h})}stopMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(t,{volume:e=.5,expression:i,resetExpression:s=!0,crossOrigin:r,onFinish:o,onError:a}={}){return this.internalModel.motionManager.speak(t,{volume:e,expression:i,resetExpression:s,crossOrigin:r,onFinish:o,onError:a})}stopSpeaking(){return this.internalModel.motionManager.stopSpeaking()}expression(t){return this.internalModel.motionManager.expressionManager?void 0===t?this.internalModel.motionManager.expressionManager.setRandomExpression():this.internalModel.motionManager.expressionManager.setExpression(t):Promise.resolve(!1)}focus(t,e,i=!1){ti.x=t,ti.y=e,this.toModelPosition(ti,ti,!0);const s=ti.x/this.internalModel.originalWidth*2-1,r=ti.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&&(de.log(this.tag,"Hit",i),this.emit("hit",i))}hitTest(t,e){return ti.x=t,ti.y=e,this.toModelPosition(ti,ti),this.internalModel.hitTest(ti.x,ti.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)}update(t){this.deltaTime+=t,this.elapsedTime+=t}_render(t){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.automator.destroy(),this.internalModel.destroy(),super.destroy(t)}}if(!window.Live2DCubismCore)throw new Error("Could not find Cubism 4 runtime. This plugin requires live2dcubismcore.js to be loaded.");class si extends _e{constructor(t,e){var i;super(t,e),o(this,"queueManager",new ht),o(this,"definitions"),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 G.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 ri extends we{constructor(t,e){var i;super(t,e),o(this,"definitions"),o(this,"groups",{idle:"Idle"}),o(this,"motionDataType","json"),o(this,"queueManager",new ht),o(this,"expressionManager"),o(this,"eyeBlinkIds"),o(this,"lipSyncIds",["ParamMouthOpenY"]),this.definitions=null!=(i=t.motions)?i:{},this.eyeBlinkIds=t.getEyeBlinkParameters()||[];const s=t.getLipSyncParameters();(null==s?void 0:s.length)&&(this.lipSyncIds=s),this.init(e)}init(t){super.init(t),this.settings.expressions&&(this.expressionManager=new si(this.settings,t)),this.queueManager.setEventCallback(((t,e,i)=>{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(t,e,i){const s=nt.create(t),r=new Z(t),o=(e===this.groups.idle?ue.idleMotionFadingDuration:ue.motionFadingDuration)/1e3;return void 0===r.getMotionFadeInTime()&&s.setFadeInTime(i.FadeInTime>0?i.FadeInTime:o),void 0===r.getMotionFadeOutTime()&&s.setFadeOutTime(i.FadeOutTime>0?i.FadeOutTime:o),s.setEffectIds(this.eyeBlinkIds,this.lipSyncIds),s}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 oi=new f;class ai extends Ie{constructor(t,i,s){super(),o(this,"settings"),o(this,"coreModel"),o(this,"motionManager"),o(this,"lipSync",!0),o(this,"breath",n.create()),o(this,"eyeBlink"),o(this,"userData"),o(this,"renderer",new te),o(this,"idParamAngleX",ie),o(this,"idParamAngleY",se),o(this,"idParamAngleZ",re),o(this,"idParamEyeBallX",oe),o(this,"idParamEyeBallY",ae),o(this,"idParamBodyAngleX",le),o(this,"idParamBreath",he),o(this,"idParamMouthForm",ne),o(this,"pixelsPerUnit",1),o(this,"centeringTransform",new e.Matrix),this.coreModel=t,this.settings=i,this.motionManager=new ri(i,s),this.init()}init(){var t;super.init(),(null==(t=this.settings.getEyeBlinkParameters())?void 0:t.length)&&(this.eyeBlink=u.create(this.settings)),this.breath.setParameters([new l(this.idParamAngleX,0,15,6.5345,.5),new l(this.idParamAngleY,0,8,3.5345,.5),new l(this.idParamAngleZ,0,10,5.5345,.5),new l(this.idParamBodyAngleX,0,4,15.5345,.5),new l(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,i]of Object.entries(this.settings.layout)){t[e.charAt(0).toLowerCase()+e.slice(1)]=i}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,Ht.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=ce(t*1.2,e,1);for(let i=0;i0&&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{!function i(){try{di(),t()}catch(s){if(hi--,hi<0){const t=new Error("Failed to start up Cubism 4 framework.");return t.cause=s,void e(t)}de.log("Cubism4","Startup failed, retrying 10ms later..."),setTimeout(i,10)}}()}))),li)}function di(t){t=Object.assign({logFunction:console.log,loggingLevel:w.LogLevel_Verbose},t),S.startUp(t),S.initialize()}function ci(){var t;null==(t=this.__moc)||t.release()}Ye.registerRuntime({version:4,ready:ui,test:t=>t instanceof ni||ni.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 ni(t),createCoreModel(t,e){const i=k.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 ai(t,e,i),r=t;return r.__moc&&(s.__moc=r.__moc,delete r.__moc,s.once("destroy",ci)),s},createPhysics:(t,e)=>yt.create(e),createPose:(t,e)=>c.create(e)}),t.ACubismMotion=N,t.BreathParameterData=l,t.CSM_ASSERT=T,t.Constant=b,t.Cubism4ExpressionManager=si,t.Cubism4InternalModel=ai,t.Cubism4ModelSettings=ni,t.Cubism4MotionManager=ri,t.CubismBlendMode=C,t.CubismBreath=n,t.CubismClippingContext=zt,t.CubismClippingManager_WebGL=Gt,t.CubismDebug=A,t.CubismExpressionMotion=G,t.CubismEyeBlink=u,t.CubismFramework=S,t.CubismLogDebug=I,t.CubismLogError=F,t.CubismLogInfo=E,t.CubismLogVerbose=function(t,...e){A.print(w.LogLevel_Verbose,"[CSM][V]"+t+"\n",e)},t.CubismLogWarning=L,t.CubismMath=_,t.CubismMatrix44=f,t.CubismMoc=k,t.CubismModel=O,t.CubismModelSettingsJson=ee,t.CubismModelUserData=V,t.CubismModelUserDataJson=U,t.CubismMotion=nt,t.CubismMotionCurve=q,t.CubismMotionCurveTarget=j,t.CubismMotionData=J,t.CubismMotionEvent=$,t.CubismMotionJson=Z,t.CubismMotionManager=class extends ht{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=W,t.CubismMotionQueueEntry=lt,t.CubismMotionQueueManager=ht,t.CubismMotionSegment=Y,t.CubismMotionSegmentType=H,t.CubismPhysics=yt,t.CubismPhysicsInput=pt,t.CubismPhysicsJson=xt,t.CubismPhysicsOutput=_t,t.CubismPhysicsParticle=gt,t.CubismPhysicsRig=ft,t.CubismPhysicsSource=ct,t.CubismPhysicsSubRig=mt,t.CubismPhysicsTargetType=dt,t.CubismPose=c,t.CubismRenderTextureResource=Xt,t.CubismRenderer=x,t.CubismRendererProfile_WebGL=jt,t.CubismRenderer_WebGL=te,t.CubismShader_WebGL=Ht,t.CubismTextureColor=y,t.CubismVector2=m,t.DrawableColorData=D,t.DrawableCullingData=R,t.EvaluationOptionFlag=Q,t.ExpressionBlendType=z,t.ExpressionManager=_e,t.EyeState=d,t.FileLoader=He,t.FocusController=Ce,t.HitAreaBody="Body",t.HitAreaHead="Head",t.HitAreaPrefix="HitArea",t.InternalModel=Ie,t.InvalidMotionQueueEntryHandleValue=ut,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DFactory=Ye,t.Live2DLoader=De,t.Live2DModel=ii,t.Live2DTransform=Ke,t.LogLevel=w,t.ModelSettings=ye,t.MotionManager=we,t.MotionPreloadStrategy=Se,t.MotionPriority=Me,t.MotionState=ve,t.Options=Mt,t.ParamAngleX=ie,t.ParamAngleY=se,t.ParamAngleZ=re,t.ParamArmLA="ParamArmLA",t.ParamArmLB="ParamArmLB",t.ParamArmRA="ParamArmRA",t.ParamArmRB="ParamArmRB",t.ParamBaseX="ParamBaseX",t.ParamBaseY="ParamBaseY",t.ParamBodyAngleX=le,t.ParamBodyAngleY="ParamBodyAngleY",t.ParamBodyAngleZ="ParamBodyAngleZ",t.ParamBreath=he,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=oe,t.ParamEyeBallY=ae,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=ne,t.ParamMouthOpenY="ParamMouthOpenY",t.ParamNONE="NONE:",t.ParamShoulderY="ParamShoulderY",t.PartColorData=B,t.PartData=g,t.PartsArmLPrefix="Parts01ArmL_",t.PartsArmPrefix="Parts01Arm_",t.PartsArmRPrefix="Parts01ArmR_",t.PartsIdCore="Parts01Core",t.PhysicsJsonEffectiveForces=class{constructor(){this.gravity=new m(0,0),this.wind=new m(0,0)}},t.PhysicsOutput=vt,t.ShaderNames=Wt,t.SoundManager=be,t.VERSION="v0.5.0-beta",t.VOLUME=Pe,t.XHRLoader=Fe,t.ZipLoader=ze,t.applyMixins=ge,t.clamp=ce,t.config=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=kt,t.cubism4Ready=ui,t.folderName=me,t.fragmentShaderSrcMaskInvertedPremultipliedAlpha=Kt,t.fragmentShaderSrcMaskPremultipliedAlpha=Qt,t.fragmentShaderSrcPremultipliedAlpha=Zt,t.fragmentShaderSrcsetupMask=qt,t.logger=de,t.rand=function(t,e){return Math.random()*(e-t)+t},t.remove=pe,t.startUpCubism4=di,t.vertexShaderSrc=$t,t.vertexShaderSrcMasked=Jt,t.vertexShaderSrcSetupMask=Yt,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("@pixi/core"),require("@pixi/display")):"function"==typeof define&&define.amd?define(["exports","@pixi/core","@pixi/display"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).PIXI=t.PIXI||{},t.PIXI.live2d=t.PIXI.live2d||{}),t.PIXI,t.PIXI)}(this,(function(t,e,i){"use strict";var s=Object.defineProperty,r=Math.pow,o=(t,e,i)=>(((t,e,i)=>{e in t?s(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i})(t,"symbol"!=typeof e?e+"":e,i),i),a=(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())}));class n{constructor(){this._breathParameters=[],this._currentTime=0}static create(){return new n}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&&(r=1,this._blinkingState=3,this._stateStartTimeSeconds=this._userTimeSeconds),s=1-r;break;case 3:r=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._closedSeconds,r>=1&&(this._blinkingState=4,this._stateStartTimeSeconds=this._userTimeSeconds),s=0;break;case 4:r=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._openingSeconds,r>=1&&(r=1,this._blinkingState=1,this._nextBlinkingTime=this.determinNextBlinkingTiming()),s=r;break;case 1:this._nextBlinkingTime(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))(d||{});class c{static create(t){const e=new c;"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 g{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 g;return t.partId=this.partId,t.parameterIndex=this.parameterIndex,t.partIndex=this.partIndex,t.link=this.link.map((t=>t.clone())),t}}class m{constructor(t,e){this.x=t||0,this.y=e||0}add(t){const e=new m(0,0);return e.x=this.x+t.x,e.y=this.y+t.y,e}substract(t){const e=new m(0,0);return e.x=this.x-t.x,e.y=this.y-t.y,e}multiply(t){const e=new m(0,0);return e.x=this.x*t.x,e.y=this.y*t.y,e}multiplyByScaler(t){return this.multiply(new m(t,t))}division(t){const e=new m(0,0);return e.x=this.x/t.x,e.y=this.y/t.y,e}divisionByScalar(t){return this.division(new m(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 p=class t{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 m;return e.x=this.sin(t),e.y=this.cos(t),e}static quadraticEquation(e,i,s){return this.abs(e)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 f,this._mvpMatrix4x4.loadIdentity()}}var C=(t=>(t[t.CubismBlendMode_Normal=0]="CubismBlendMode_Normal",t[t.CubismBlendMode_Additive=1]="CubismBlendMode_Additive",t[t.CubismBlendMode_Multiplicative=2]="CubismBlendMode_Multiplicative",t))(C||{});class y{constructor(t=1,e=1,i=1,s=1){this.R=t,this.G=e,this.B=i,this.A=s}}let M,v=!1,P=!1;const b={vertexOffset:0,vertexStep:2};class S{static startUp(t){if(v)return E("CubismFramework.startUp() is already done."),v;if(Live2DCubismCore._isStarted)return v=!0,!0;if(Live2DCubismCore._isStarted=!0,M=t,M&&Live2DCubismCore.Logging.csmSetLogFunction(M.logFunction),v=!0,v){const t=Live2DCubismCore.Version.csmGetVersion(),e=(16711680&t)>>16,i=65535&t,s=t;E("Live2D Cubism Core version: {0}.{1}.{2} ({3})",("00"+((4278190080&t)>>24)).slice(-2),("00"+e).slice(-2),("0000"+i).slice(-4),s)}return E("CubismFramework.startUp() is complete."),v}static cleanUp(){v=!1,P=!1,M=void 0}static initialize(t=0){v?P?L("CubismFramework.initialize() skipped, already initialized."):(Live2DCubismCore.Memory.initializeAmountOfMemory(t),P=!0,E("CubismFramework.initialize() is complete.")):L("CubismFramework is not started.")}static dispose(){v?P?(x.staticRelease(),P=!1,E("CubismFramework.dispose() is complete.")):L("CubismFramework.dispose() skipped, not initialized."):L("CubismFramework is not started.")}static isStarted(){return v}static isInitialized(){return P}static coreLogFunction(t){Live2DCubismCore.Logging.csmGetLogFunction()&&Live2DCubismCore.Logging.csmGetLogFunction()(t)}static getLoggingLevel(){return null!=M?M.loggingLevel:5}constructor(){}}var w=(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))(w||{});const T="undefined"!=typeof process&&"production"===process.env.NODE_ENV?()=>{}:t=>console.assert(t);function I(t,...e){A.print(w.LogLevel_Debug,"[CSM][D]"+t+"\n",e)}function E(t,...e){A.print(w.LogLevel_Info,"[CSM][I]"+t+"\n",e)}function L(t,...e){A.print(w.LogLevel_Warning,"[CSM][W]"+t+"\n",e)}function F(t,...e){A.print(w.LogLevel_Error,"[CSM][E]"+t+"\n",e)}class A{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 D{constructor(t=!1,e=new y){this.isOverwritten=t,this.Color=e}}class B{constructor(t=!1,e=new y){this.isOverwritten=t,this.Color=e}}class R{constructor(t=!1,e=!1){this.isOverwritten=t,this.isCulling=e}}class O{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 k{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 k(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 O(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 U{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 V{static create(t,e){const i=new V;return i.parseUserData(t,e),i}getArtMeshUserDatas(){return this._artMeshUserDataNode}parseUserData(t,e){const i=new U(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))(z||{});t.CubismConfig=void 0,(X=t.CubismConfig||(t.CubismConfig={})).supportMoreMaskDivisions=!0,X.setOpacityFromMotion=!1;var j=(t=>(t[t.CubismMotionCurveTarget_Model=0]="CubismMotionCurveTarget_Model",t[t.CubismMotionCurveTarget_Parameter=1]="CubismMotionCurveTarget_Parameter",t[t.CubismMotionCurveTarget_PartOpacity=2]="CubismMotionCurveTarget_PartOpacity",t))(j||{}),H=(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))(H||{});class W{constructor(t=0,e=0){this.time=t,this.value=e}}class Y{constructor(){this.basePointIndex=0,this.segmentType=0}}class q{constructor(){this.id="",this.type=0,this.segmentCount=0,this.baseSegmentIndex=0,this.fadeInTime=0,this.fadeOutTime=0}}class ${constructor(){this.fireTime=0,this.value=""}}class J{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 Z{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 0==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 Q=(t=>(t[t.EvaluationOptionFlag_AreBeziersRistricted=0]="EvaluationOptionFlag_AreBeziersRistricted",t))(Q||{});const K="Opacity";function tt(t,e,i){const s=new W;return s.time=t.time+(e.time-t.time)*i,s.value=t.value+(e.value-t.value)*i,s}function et(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 it(t,e){let i=(e-t[0].time)/(t[3].time-t[0].time);i<0&&(i=0);const s=tt(t[0],t[1],i),r=tt(t[1],t[2],i),o=tt(t[2],t[3],i),a=tt(s,r,i),n=tt(r,o,i);return tt(a,n,i).value}function st(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=_.cardanoAlgorithmForBezier(n,l,h,u),c=tt(t[0],t[1],d),g=tt(t[1],t[2],d),m=tt(t[2],t[3],d),p=tt(c,g,d),f=tt(g,m,d);return tt(p,f,d).value}function rt(t,e){return t[0].value}function ot(t,e){return t[1].value}function at(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 nt extends N{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 nt;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=K);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&&I("too many eye blink targets : {0}",this._eyeBlinkParameterIds.length),this._lipSyncParameterIds.length>l&&I("too many lip sync targets : {0}",this._lipSyncParameterIds.length);const d=this._fadeInSeconds<=0?1:_.getEasingSine((i-r.getFadeInStartTime())/this._fadeInSeconds),c=this._fadeOutSeconds<=0||r.getEndTime()<0?1:_.getEasingSine((r.getEndTime()-i)/this._fadeOutSeconds);let g,m,p,f=o;if(this._isLoop)for(;f>this._motionData.duration;)f-=this._motionData.duration;const x=this._motionData.curves;for(m=0;m>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(;m=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 q)),this._motionData.segments=Array.from({length:e.getMotionTotalSegmentCount()}).map((()=>new Y)),this._motionData.events=Array.from({length:this._motionData.eventCount}).map((()=>new $)),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))(dt||{}),ct=(t=>(t[t.CubismPhysicsSource_X=0]="CubismPhysicsSource_X",t[t.CubismPhysicsSource_Y=1]="CubismPhysicsSource_Y",t[t.CubismPhysicsSource_Angle=2]="CubismPhysicsSource_Angle",t))(ct||{});class gt{constructor(){this.initialPosition=new m(0,0),this.position=new m(0,0),this.lastPosition=new m(0,0),this.lastGravity=new m(0,0),this.force=new m(0,0),this.velocity=new m(0,0)}}class mt{constructor(){this.normalizationPosition={},this.normalizationAngle={}}}class pt{constructor(){this.source={}}}class _t{constructor(){this.destination={},this.translationScale=new m(0,0)}}class ft{constructor(){this.settings=[],this.inputs=[],this.outputs=[],this.particles=[],this.gravity=new m(0,0),this.wind=new m(0,0),this.fps=0}}class xt{constructor(t){this._json=t}release(){this._json=void 0}getGravity(){const t=new m(0,0);return t.x=this._json.Meta.EffectiveForces.Gravity.X,t.y=this._json.Meta.EffectiveForces.Gravity.Y,t}getWind(){const t=new m(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 m(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 Ct="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 ft;const e=new xt(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 m;s=g[i].position.substract(g[i-1].position),l=c[e].getValue(s,g,i,c[e].reflect,this._options.gravity),this._currentRigOutputs[y].outputs[e]=l,this._previousRigOutputs[y].outputs[e]=l;const r=c[e].destinationParameterIndex,o=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(p.subarray(r))):p.slice(r);Rt(o,x[r],f[r],l,c[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,x=t.getModel().parameters.maximumValues,C=t.getModel().parameters.minimumValues,y=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 m;r.x=p[s].position.x-p[s-1].position.x,r.y=p[s].position.y-p[s-1].position.y,h=g[e].getValue(r,p,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);Rt(a,C[o],x[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=_.directionToRadian(r,t),s&&(o*=-1),o}function Et(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 Lt(t,e){return t.x}function Ft(t,e){return t.y}function At(t,e){return e}function Dt(t,e,i,s,r,o,a,n){let l,h,u,d,c=new m(0,0),g=new m(0,0),p=new m(0,0),f=new m(0,0);t[0].position=new m(i.x,i.y),l=_.degreesToRadian(s),d=_.radianToDirection(l),d.normalize();for(let x=1;xi&&(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 Ot(t,e,i,s,r,o,a,n){let l=0;const h=_.max(i,e);ht&&(t=u);const d=_.min(r,o),c=_.max(r,o),g=a,m=Et(u,h),p=t-m;switch(Math.sign(p)){case 1:{const t=h-m;0!=t&&(l=p*((c-g)/t),l+=g);break}case-1:{const t=u-m;0!=t&&(l=p*((d-g)/t),l+=g);break}case 0:l=g}return n?l:-1*l}class kt{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 Ut,Vt,Nt;class Gt{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 kt,this._tmpMatrix=new f,this._tmpMatrixForMask=new f,this._tmpMatrixForDraw=new f;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&&F("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)&&(u+=h(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))(Wt||{});const Yt="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;}",qt="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;}",$t="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;}",Jt="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;}",Zt="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);}",Qt="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;}",Kt="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 te extends x{initialize(t,e=1){t.isUsingMasking()&&(this._clippingManager=new Gt,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 Gt,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}constructor(){super(),this._clippingContextBufferForMask=null,this._clippingContextBufferForDraw=null,this._rendererProfile=new jt,this.firstDraw=!0,this._textures={},this._sortedDrawableIndexList=[],this._bufferData={vertex:null,uv:null,index:null}}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 F("'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),Ht.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")}}x.staticRelease=()=>{te.doStaticRelease()};class ee{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 ie="ParamAngleX",se="ParamAngleY",re="ParamAngleZ",oe="ParamEyeBallX",ae="ParamEyeBallY",ne="ParamMouthForm",le="ParamBodyAngleX",he="ParamBreath",ue={LOG_LEVEL_VERBOSE:0,LOG_LEVEL_WARNING:1,LOG_LEVEL_ERROR:2,LOG_LEVEL_NONE:999,logLevel:1,sound:!0,motionSync:!0,motionFadingDuration:500,idleMotionFadingDuration:2e3,expressionFadingDuration:500,preserveExpressionOnMotion:!0,cubism4:t.CubismConfig},de={log(t,...e){ue.logLevel<=ue.LOG_LEVEL_VERBOSE&&console.log(`[${t}]`,...e)},warn(t,...e){ue.logLevel<=ue.LOG_LEVEL_WARNING&&console.warn(`[${t}]`,...e)},error(t,...e){ue.logLevel<=ue.LOG_LEVEL_ERROR&&console.error(`[${t}]`,...e)}};function ce(t,e,i){return ti?i:t}function ge(t,e){e.forEach((e=>{Object.getOwnPropertyNames(e.prototype).forEach((i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i))}))}))}function me(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 pe(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}class _e extends e.utils.EventEmitter{constructor(t,e){super(),o(this,"tag"),o(this,"settings"),o(this,"expressions",[]),o(this,"defaultExpression"),o(this,"currentExpression"),o(this,"reserveExpressionIndex",-1),o(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 a(this,null,(function*(){if(!this.definitions[t])return void de.warn(this.tag,`Undefined expression at [${t}]`);if(null===this.expressions[t])return void de.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 a(this,null,(function*(){if(this.definitions.length){const t=[];for(let e=0;e-1&&th&&(a*=h/l,n*=h/l),this.vx+=a,this.vy+=n;const u=Math.sqrt(r(this.vx,2)+r(this.vy,2)),d=.5*(Math.sqrt(r(h,2)+8*h*s)-h);u>d&&(this.vx*=d/u,this.vy*=d/u),this.x+=this.vx,this.y+=this.vy}}class ye{constructor(t){o(this,"json"),o(this,"name"),o(this,"url"),o(this,"pose"),o(this,"physics"),this.json=t;const 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=me(this.url)}resolveURL(t){return e.utils.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 Me=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(Me||{});class ve{constructor(){o(this,"tag"),o(this,"debug",!1),o(this,"currentPriority",0),o(this,"reservePriority",0),o(this,"currentGroup"),o(this,"currentIndex"),o(this,"reservedGroup"),o(this,"reservedIndex"),o(this,"reservedIdleGroup"),o(this,"reservedIdleIndex")}reserve(t,e,i){if(i<=0)return de.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(t===this.currentGroup&&e===this.currentIndex)return de.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 de.log(this.tag,"Motion is already reserved.",this.dump(t,e)),!1;if(1===i){if(0!==this.currentPriority)return de.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,e)),!1;if(void 0!==this.reservedIdleGroup)return de.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 de.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 de.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 de.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 de.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!ue.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""}}const Pe=.5;class be{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,s){const r=new Audio(t);return r.volume=this._volume,r.preload="auto",r.crossOrigin=s,r.addEventListener("ended",(()=>{this.dispose(r),null==e||e()})),r.addEventListener("error",(e=>{this.dispose(r),de.warn("SoundManager",`Error occurred on "${t}"`,e.error),null==i||i(e.error)})),this.audios.push(r),r}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){const e=new Float32Array(t.fftSize);let 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"),pe(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])}}o(be,"audios",[]),o(be,"analysers",[]),o(be,"contexts",[]),o(be,"_volume",Pe);var Se=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(Se||{});class we extends e.utils.EventEmitter{constructor(t,e){super(),o(this,"tag"),o(this,"settings"),o(this,"motionGroups",{}),o(this,"state",new ve),o(this,"currentAudio"),o(this,"currentAnalyzer"),o(this,"currentContext"),o(this,"playing",!1),o(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{console.log("Audio finished playing"),null==o||o(),s&&i&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0}),((t,e=this)=>{console.log("Error during audio playback:",t),null==a||a(t),s&&i&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),r),this.currentAudio=n,be.volume=e,h=be.addContext(this.currentAudio),this.currentContext=h,l=be.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=l}catch(g){return de.warn(this.tag,"Failed to create audio",u,g),!1}if(n){let t=!0;const e=be.play(n).catch((e=>{de.warn(this.tag,"Failed to play audio",n.src,e),t=!1}));if(ue.motionSync&&(yield e,!t))return!1}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),i&&this.expressionManager&&this.expressionManager.setExpression(i),this.playing=!0,!0}))}startMotion(t,e){return a(this,arguments,(function*(t,e,i=Me.NORMAL,{sound:s,volume:r=.5,expression:o,resetExpression:a=!0,crossOrigin:n,onFinish:l,onError:h}={}){var u;if(!this.state.reserve(t,e,i))return!1;if(this.currentAudio&&!this.currentAudio.ended&&i!=Me.FORCE)return!1;const d=null==(u=this.definitions[t])?void 0:u[e];if(!d)return!1;let c,g,m,p;this.currentAudio&&be.dispose(this.currentAudio);const _=s&&s.startsWith("data:");if(s&&!_){const t=document.createElement("a");t.href=s,p=s=t.href}else p=this.getSoundFile(d),p&&(p=this.settings.resolveURL(p));const f=p;if(f)try{c=be.add(f,((t=this)=>{console.log("Audio finished playing"),null==l||l(),console.log(l),a&&o&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0}),((t,e=this)=>{console.log("Error during audio playback:",t),null==h||h(t),a&&o&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),n),this.currentAudio=c,be.volume=r,m=be.addContext(this.currentAudio),this.currentContext=m,g=be.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=g}catch(C){de.warn(this.tag,"Failed to create audio",p,C)}const x=yield this.loadMotion(t,e);if(c){const t=be.play(c).catch((t=>de.warn(this.tag,"Failed to play audio",c.src,t)));ue.motionSync&&(yield t)}return this.state.start(x,t,e,i)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),de.log(this.tag,"Start motion:",this.getMotionName(d)),this.emit("motionStart",t,e,c),o&&this.expressionManager&&this.state.shouldOverrideExpression()&&this.expressionManager.setExpression(o),this.playing=!0,this._startMotion(x),!0):(c&&(be.dispose(c),this.currentAudio=void 0),!1)}))}startRandomMotion(t,e){return a(this,arguments,(function*(t,e,{sound:i,volume:s=.5,expression:r,resetExpression:o=!0,crossOrigin:a,onFinish:n,onError:l}={}){const h=this.definitions[t];if(null==h?void 0:h.length){const u=[];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,Te);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!==a.status&&0!==a.status||!a.response?a.onerror():r(a.response)},a.onerror=()=>{de.warn("XHRLoader",`Failed to load resource as ${a.responseType} (Status ${a.status}): ${i}`),o(new Ee("Network error.",i,a.status))},a.onabort=()=>o(new Ee("Aborted.",i,a.status,!0)),a.onloadend=()=>{var i;t.allXhrSet.delete(a),e&&(null==(i=t.xhrMap.get(e))||i.delete(a))},a}static cancelXHRs(){var e;null==(e=t.xhrMap.get(this))||e.forEach((e=>{e.abort(),t.allXhrSet.delete(e)})),t.xhrMap.delete(this)}static release(){t.allXhrSet.forEach((t=>t.abort())),t.allXhrSet.clear(),t.xhrMap=new WeakMap}};o(Le,"xhrMap",new WeakMap),o(Le,"allXhrSet",new Set),o(Le,"loader",((t,e)=>new Promise(((e,i)=>{Le.createXHR(t.target,t.settings?t.settings.resolveURL(t.url):t.url,t.type,(i=>{t.result=i,e()}),i).send()}))));let Fe=Le;function Ae(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)}class De{static load(t){return Ae(this.middlewares,t).then((()=>t.result))}}function Be(){}o(De,"middlewares",[Fe.loader]);const Re="Live2DFactory",Oe=(t,e)=>a(this,null,(function*(){if("string"==typeof t.source){const e=yield De.load({url:t.source,type:"json",target:t.live2dModel});e.url=t.source,t.source=e,t.live2dModel.emit("settingsJSONLoaded",e)}return e()})),ke=(t,e)=>a(this,null,(function*(){if(t.source instanceof ye)return t.settings=t.source,e();if("object"==typeof t.source){const i=Ye.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.")})),Ue=(t,e)=>{if(t.settings){const i=Ye.findRuntime(t.settings);if(i)return i.ready().then(e)}return e()},Ve=(t,e)=>a(this,null,(function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=Ye.findRuntime(e);if(s){const r=[];e.pose&&r.push(De.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),de.warn(Re,"Failed to load pose.",e)}))),e.physics&&r.push(De.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),de.warn(Re,"Failed to load physics.",e)}))),r.length&&(yield Promise.all(r))}}})),Ne=(t,i)=>a(this,null,(function*(){if(!t.settings)throw new TypeError("Missing settings.");{const s=t.live2dModel,r=Promise.all(t.settings.textures.map((i=>function(t,i={}){const s={resourceOptions:{crossorigin:i.crossOrigin}};if(e.Texture.fromURL)return e.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=e.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 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(i),{crossOrigin:t.options.crossOrigin}))));if(r.catch(Be),yield i(),!t.internalModel)throw new TypeError("Missing internal model.");s.internalModel=t.internalModel,s.emit("modelLoaded",t.internalModel),s.textures=yield r,s.emit("textureLoaded",s.textures)}})),Ge=(t,e)=>a(this,null,(function*(){const i=t.settings;if(i instanceof ye){const s=Ye.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield De.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.")})),Xe=class t{static unzip(i,s){return a(this,null,(function*(){const r=yield t.getFilePaths(i),o=[];for(const t of s.getDefinedFiles()){const i=decodeURI(e.utils.url.resolve(s.url,t));r.includes(i)&&o.push(i)}const a=yield t.getFiles(i,o);for(let t=0;tt.endsWith("model.json")||t.endsWith("model3.json")));if(!i)throw new Error("Settings file not found");const s=yield t.readText(e,i);if(!s)throw new Error("Empty settings file: "+i);const r=JSON.parse(s);r.url=i;const o=t.live2dFactory.findRuntime(r);if(!o)throw new Error("Unknown settings JSON");return o.createModelSettings(r)}))}static zipReader(t,e){return a(this,null,(function*(){throw new Error("Not implemented")}))}static getFilePaths(t){return a(this,null,(function*(){throw new Error("Not implemented")}))}static getFiles(t,e){return a(this,null,(function*(){throw new Error("Not implemented")}))}static readText(t,e){return a(this,null,(function*(){throw new Error("Not implemented")}))}static releaseReader(t){}};o(Xe,"live2dFactory"),o(Xe,"ZIP_PROTOCOL","zip://"),o(Xe,"uid",0),o(Xe,"factory",((t,e)=>a(Xe,null,(function*(){const i=t.source;let s,r,o;if("string"==typeof i&&(i.endsWith(".zip")||i.startsWith(Xe.ZIP_PROTOCOL))?(s=i.startsWith(Xe.ZIP_PROTOCOL)?i.slice(Xe.ZIP_PROTOCOL.length):i,r=yield De.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 Xe.zipReader(r,s);o||(o=yield Xe.createSettings(e)),o._objectURL=Xe.ZIP_PROTOCOL+Xe.uid+"/"+o.url;const i=yield Xe.unzip(e,o);i.settings=o,t.source=i,s.startsWith("blob:")&&t.live2dModel.once("modelLoaded",(t=>{t.once("destroy",(function(){URL.revokeObjectURL(s)}))})),Xe.releaseReader(e)}return e()}))));let ze=Xe;const je=class t{static resolveURL(e,i){var s;const r=null==(s=t.filesMap[e])?void 0:s[i];if(void 0===r)throw new Error("Cannot find this file from uploaded files: "+i);return r}static upload(i,s){return a(this,null,(function*(){const r={};for(const t of s.getDefinedFiles()){const o=decodeURI(e.utils.url.resolve(s.url,t)),a=i.find((t=>t.webkitRelativePath===o));a&&(r[t]=URL.createObjectURL(a))}t.filesMap[s._objectURL]=r}))}static createSettings(e){return a(this,null,(function*(){const i=e.find((t=>t.name.endsWith("model.json")||t.name.endsWith("model3.json")));if(!i)throw new TypeError("Settings file not found");const s=yield t.readText(i),r=JSON.parse(s);r.url=i.webkitRelativePath;const o=Ye.findRuntime(r);if(!o)throw new Error("Unknown settings JSON");const a=o.createModelSettings(r);return a._objectURL=URL.createObjectURL(i),a}))}static readText(t){return a(this,null,(function*(){return new Promise(((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")}))}))}};o(je,"live2dFactory"),o(je,"filesMap",{}),o(je,"factory",((t,e)=>a(je,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 je.createSettings(e);i.validateFiles(e.map((t=>encodeURI(t.webkitRelativePath)))),yield je.upload(e,i),i.resolveURL=function(t){return je.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),je.filesMap[t])for(const e of Object.values(je.filesMap[t]))URL.revokeObjectURL(e);delete je.filesMap[t]}))}))}return e()}))));let He=je;const We=class t{static registerRuntime(e){t.runtimes.push(e),t.runtimes.sort(((t,e)=>e.version-t.version))}static findRuntime(e){for(const i of t.runtimes)if(i.test(e))return i}static setupLive2DModel(e,i,s){return a(this,null,(function*(){const r=new Promise((t=>e.once("textureLoaded",t))),o=new Promise((t=>e.once("modelLoaded",t))),a=Promise.all([r,o]).then((()=>e.emit("ready")));yield Ae(t.live2DModelMiddlewares,{live2dModel:e,source:i,options:s||{}}),yield a,e.emit("load")}))}static loadMotion(e,i,s){var r;const o=t=>e.emit("motionLoadError",i,s,t);try{const a=null==(r=e.definitions[i])?void 0:r[s];if(!a)return Promise.resolve(void 0);e.listeners("destroy").includes(t.releaseTasks)||e.once("destroy",t.releaseTasks);let n=t.motionTasksMap.get(e);n||(n={},t.motionTasksMap.set(e,n));let l=n[i];l||(l=[],n[i]=l);const h=e.getMotionFile(a);return null!=l[s]||(l[s]=De.load({url:h,settings:e.settings,type:e.motionDataType,target:e}).then((r=>{var o;const n=null==(o=t.motionTasksMap.get(e))?void 0:o[i];n&&delete n[s];const l=e.createMotion(r,i,a);return e.emit("motionLoaded",i,s,l),l})).catch((t=>{de.warn(e.tag,`Failed to load motion: ${h}\n`,t),o(t)}))),l[s]}catch(a){de.warn(e.tag,`Failed to load motion at "${i}"[${s}]\n`,a),o(a)}return Promise.resolve(void 0)}static loadExpression(e,i){const s=t=>e.emit("expressionLoadError",i,t);try{const r=e.definitions[i];if(!r)return Promise.resolve(void 0);e.listeners("destroy").includes(t.releaseTasks)||e.once("destroy",t.releaseTasks);let o=t.expressionTasksMap.get(e);o||(o=[],t.expressionTasksMap.set(e,o));const a=e.getExpressionFile(r);return null!=o[i]||(o[i]=De.load({url:a,settings:e.settings,type:"json",target:e}).then((s=>{const o=t.expressionTasksMap.get(e);o&&delete o[i];const a=e.createExpression(s,r);return e.emit("expressionLoaded",i,a),a})).catch((t=>{de.warn(e.tag,`Failed to load expression: ${a}\n`,t),s(t)}))),o[i]}catch(r){de.warn(e.tag,`Failed to load expression at [${i}]\n`,r),s(r)}return Promise.resolve(void 0)}static releaseTasks(){this instanceof we?t.motionTasksMap.delete(this):t.expressionTasksMap.delete(this)}};o(We,"runtimes",[]),o(We,"urlToJSON",Oe),o(We,"jsonToSettings",ke),o(We,"waitUntilReady",Ue),o(We,"setupOptionals",Ve),o(We,"setupEssentials",Ne),o(We,"createInternalModel",Ge),o(We,"live2DModelMiddlewares",[ze.factory,He.factory,Oe,ke,Ue,Ve,Ne,Ge]),o(We,"motionTasksMap",new WeakMap),o(We,"expressionTasksMap",new WeakMap);let Ye=We;we.prototype._loadMotion=function(t,e){return Ye.loadMotion(this,t,e)},_e.prototype._loadExpression=function(t){return Ye.loadExpression(this,t)},He.live2dFactory=Ye,ze.live2dFactory=Ye;const qe=class t{constructor(e,{autoUpdate:i=!0,autoHitTest:s=!0,autoFocus:r=!0,autoInteract:a,ticker:n}={}){o(this,"model"),o(this,"destroyed",!1),o(this,"_ticker"),o(this,"_autoUpdate",!1),o(this,"_autoHitTest",!1),o(this,"_autoFocus",!1),n||(t.defaultTicker?n=t.defaultTicker:"undefined"!=typeof PIXI&&(n=PIXI.Ticker.shared)),void 0!==a&&(s=a,r=a,de.warn(e.tag,"options.autoInteract is deprecated since v0.5.0, use autoHitTest and autoFocus instead.")),this.model=e,this.ticker=n,this.autoUpdate=i,this.autoHitTest=s,this.autoFocus=r,(s||r)&&(this.model.eventMode="static")}get ticker(){return this._ticker}set ticker(t){var e;this._ticker&&this._ticker.remove(Je,this),this._ticker=t,this._autoUpdate&&(null==(e=this._ticker)||e.add(Je,this))}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){var e;this.destroyed||(t?this._ticker?(this._ticker.add(Je,this),this._autoUpdate=!0):de.warn(this.model.tag,"No Ticker to be used for automatic updates. Either set option.ticker when creating Live2DModel, or expose PIXI to global scope (window.PIXI = PIXI)."):(null==(e=this._ticker)||e.remove(Je,this),this._autoUpdate=!1))}get autoHitTest(){return this._autoHitTest}set autoHitTest(t){t!==this.autoHitTest&&(t?this.model.on("pointertap",Ze,this):this.model.off("pointertap",Ze,this),this._autoHitTest=t)}get autoFocus(){return this._autoFocus}set autoFocus(t){t!==this.autoFocus&&(t?this.model.on("globalpointermove",Qe,this):this.model.off("globalpointermove",Qe,this),this._autoFocus=t)}get autoInteract(){return this._autoHitTest&&this._autoFocus}set autoInteract(t){this.autoHitTest=t,this.autoFocus=t}onTickerUpdate(){const t=this.ticker.deltaMS;this.model.update(t)}onTap(t){this.model.tap(t.global.x,t.global.y)}onPointerMove(t){this.model.focus(t.global.x,t.global.y)}destroy(){this.autoFocus=!1,this.autoHitTest=!1,this.autoUpdate=!1,this.ticker=void 0,this.destroyed=!0}};o(qe,"defaultTicker");let $e=qe;function Je(){this.onTickerUpdate()}function Ze(t){this.onTap(t)}function Qe(t){this.onPointerMove(t)}class Ke extends e.Transform{}const ti=new e.Point,ei=new e.Matrix;class ii extends i.Container{constructor(t){super(),o(this,"tag","Live2DModel(uninitialized)"),o(this,"internalModel"),o(this,"textures",[]),o(this,"transform",new Ke),o(this,"anchor",new e.ObservablePoint(this.onAnchorChange,this,0,0)),o(this,"glContextID",-1),o(this,"elapsedTime",0),o(this,"deltaTime",0),o(this,"automator"),this.automator=new $e(this,t),this.once("modelLoaded",(()=>this.init(t)))}static from(t,e){const i=new this(e);return Ye.setupLive2DModel(i,t,e).then((()=>i))}static fromSync(t,e){const i=new this(e);return Ye.setupLive2DModel(i,t,e).then(null==e?void 0:e.onLoad).catch(null==e?void 0:e.onError),i}static registerTicker(t){$e.defaultTicker=t.shared}init(t){this.tag=`Live2DModel(${this.internalModel.settings.name})`}onAnchorChange(){this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(t,e,i,{sound:s,volume:r=.5,expression:o,resetExpression:a=!0,crossOrigin:n,onFinish:l,onError:h}={}){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i,{sound:s,volume:r,expression:o,resetExpression:a,crossOrigin:n,onFinish:l,onError:h}):this.internalModel.motionManager.startMotion(t,e,i,{sound:s,volume:r,expression:o,resetExpression:a,crossOrigin:n,onFinish:l,onError:h})}stopMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(t,{volume:e=.5,expression:i,resetExpression:s=!0,crossOrigin:r,onFinish:o,onError:a}={}){return this.internalModel.motionManager.speak(t,{volume:e,expression:i,resetExpression:s,crossOrigin:r,onFinish:o,onError:a})}stopSpeaking(){return this.internalModel.motionManager.stopSpeaking()}expression(t){return this.internalModel.motionManager.expressionManager?void 0===t?this.internalModel.motionManager.expressionManager.setRandomExpression():this.internalModel.motionManager.expressionManager.setExpression(t):Promise.resolve(!1)}focus(t,e,i=!1){ti.x=t,ti.y=e,this.toModelPosition(ti,ti,!0);const s=ti.x/this.internalModel.originalWidth*2-1,r=ti.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&&(de.log(this.tag,"Hit",i),this.emit("hit",i))}hitTest(t,e){return ti.x=t,ti.y=e,this.toModelPosition(ti,ti),this.internalModel.hitTest(ti.x,ti.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)}update(t){this.deltaTime+=t,this.elapsedTime+=t}_render(t){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.automator.destroy(),this.internalModel.destroy(),super.destroy(t)}}if(!window.Live2DCubismCore)throw new Error("Could not find Cubism 4 runtime. This plugin requires live2dcubismcore.js to be loaded.");class si extends _e{constructor(t,e){var i;super(t,e),o(this,"queueManager",new ht),o(this,"definitions"),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 G.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 ri extends we{constructor(t,e){var i;super(t,e),o(this,"definitions"),o(this,"groups",{idle:"Idle"}),o(this,"motionDataType","json"),o(this,"queueManager",new ht),o(this,"expressionManager"),o(this,"eyeBlinkIds"),o(this,"lipSyncIds",["ParamMouthOpenY"]),this.definitions=null!=(i=t.motions)?i:{},this.eyeBlinkIds=t.getEyeBlinkParameters()||[];const s=t.getLipSyncParameters();(null==s?void 0:s.length)&&(this.lipSyncIds=s),this.init(e)}init(t){super.init(t),this.settings.expressions&&(this.expressionManager=new si(this.settings,t)),this.queueManager.setEventCallback(((t,e,i)=>{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(t,e,i){const s=nt.create(t),r=new Z(t),o=(e===this.groups.idle?ue.idleMotionFadingDuration:ue.motionFadingDuration)/1e3;return void 0===r.getMotionFadeInTime()&&s.setFadeInTime(i.FadeInTime>0?i.FadeInTime:o),void 0===r.getMotionFadeOutTime()&&s.setFadeOutTime(i.FadeOutTime>0?i.FadeOutTime:o),s.setEffectIds(this.eyeBlinkIds,this.lipSyncIds),s}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 oi=new f;class ai extends Ie{constructor(t,i,s){super(),o(this,"settings"),o(this,"coreModel"),o(this,"motionManager"),o(this,"lipSync",!0),o(this,"breath",n.create()),o(this,"eyeBlink"),o(this,"userData"),o(this,"renderer",new te),o(this,"idParamAngleX",ie),o(this,"idParamAngleY",se),o(this,"idParamAngleZ",re),o(this,"idParamEyeBallX",oe),o(this,"idParamEyeBallY",ae),o(this,"idParamBodyAngleX",le),o(this,"idParamBreath",he),o(this,"idParamMouthForm",ne),o(this,"pixelsPerUnit",1),o(this,"centeringTransform",new e.Matrix),this.coreModel=t,this.settings=i,this.motionManager=new ri(i,s),this.init()}init(){var t;super.init(),(null==(t=this.settings.getEyeBlinkParameters())?void 0:t.length)&&(this.eyeBlink=u.create(this.settings)),this.breath.setParameters([new l(this.idParamAngleX,0,15,6.5345,.5),new l(this.idParamAngleY,0,8,3.5345,.5),new l(this.idParamAngleZ,0,10,5.5345,.5),new l(this.idParamBodyAngleX,0,4,15.5345,.5),new l(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,i]of Object.entries(this.settings.layout)){t[e.charAt(0).toLowerCase()+e.slice(1)]=i}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,Ht.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=ce(t*1.2,e,1);for(let i=0;i0&&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{!function i(){try{di(),t()}catch(s){if(hi--,hi<0){const t=new Error("Failed to start up Cubism 4 framework.");return t.cause=s,void e(t)}de.log("Cubism4","Startup failed, retrying 10ms later..."),setTimeout(i,10)}}()}))),li)}function di(t){t=Object.assign({logFunction:console.log,loggingLevel:w.LogLevel_Verbose},t),S.startUp(t),S.initialize()}function ci(){var t;null==(t=this.__moc)||t.release()}Ye.registerRuntime({version:4,ready:ui,test:t=>t instanceof ni||ni.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 ni(t),createCoreModel(t,e){const i=k.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 ai(t,e,i),r=t;return r.__moc&&(s.__moc=r.__moc,delete r.__moc,s.once("destroy",ci)),s},createPhysics:(t,e)=>yt.create(e),createPose:(t,e)=>c.create(e)}),t.ACubismMotion=N,t.BreathParameterData=l,t.CSM_ASSERT=T,t.Constant=b,t.Cubism4ExpressionManager=si,t.Cubism4InternalModel=ai,t.Cubism4ModelSettings=ni,t.Cubism4MotionManager=ri,t.CubismBlendMode=C,t.CubismBreath=n,t.CubismClippingContext=zt,t.CubismClippingManager_WebGL=Gt,t.CubismDebug=A,t.CubismExpressionMotion=G,t.CubismEyeBlink=u,t.CubismFramework=S,t.CubismLogDebug=I,t.CubismLogError=F,t.CubismLogInfo=E,t.CubismLogVerbose=function(t,...e){A.print(w.LogLevel_Verbose,"[CSM][V]"+t+"\n",e)},t.CubismLogWarning=L,t.CubismMath=_,t.CubismMatrix44=f,t.CubismMoc=k,t.CubismModel=O,t.CubismModelSettingsJson=ee,t.CubismModelUserData=V,t.CubismModelUserDataJson=U,t.CubismMotion=nt,t.CubismMotionCurve=q,t.CubismMotionCurveTarget=j,t.CubismMotionData=J,t.CubismMotionEvent=$,t.CubismMotionJson=Z,t.CubismMotionManager=class extends ht{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=W,t.CubismMotionQueueEntry=lt,t.CubismMotionQueueManager=ht,t.CubismMotionSegment=Y,t.CubismMotionSegmentType=H,t.CubismPhysics=yt,t.CubismPhysicsInput=pt,t.CubismPhysicsJson=xt,t.CubismPhysicsOutput=_t,t.CubismPhysicsParticle=gt,t.CubismPhysicsRig=ft,t.CubismPhysicsSource=ct,t.CubismPhysicsSubRig=mt,t.CubismPhysicsTargetType=dt,t.CubismPose=c,t.CubismRenderTextureResource=Xt,t.CubismRenderer=x,t.CubismRendererProfile_WebGL=jt,t.CubismRenderer_WebGL=te,t.CubismShader_WebGL=Ht,t.CubismTextureColor=y,t.CubismVector2=m,t.DrawableColorData=D,t.DrawableCullingData=R,t.EvaluationOptionFlag=Q,t.ExpressionBlendType=z,t.ExpressionManager=_e,t.EyeState=d,t.FileLoader=He,t.FocusController=Ce,t.HitAreaBody="Body",t.HitAreaHead="Head",t.HitAreaPrefix="HitArea",t.InternalModel=Ie,t.InvalidMotionQueueEntryHandleValue=ut,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DFactory=Ye,t.Live2DLoader=De,t.Live2DModel=ii,t.Live2DTransform=Ke,t.LogLevel=w,t.ModelSettings=ye,t.MotionManager=we,t.MotionPreloadStrategy=Se,t.MotionPriority=Me,t.MotionState=ve,t.Options=Mt,t.ParamAngleX=ie,t.ParamAngleY=se,t.ParamAngleZ=re,t.ParamArmLA="ParamArmLA",t.ParamArmLB="ParamArmLB",t.ParamArmRA="ParamArmRA",t.ParamArmRB="ParamArmRB",t.ParamBaseX="ParamBaseX",t.ParamBaseY="ParamBaseY",t.ParamBodyAngleX=le,t.ParamBodyAngleY="ParamBodyAngleY",t.ParamBodyAngleZ="ParamBodyAngleZ",t.ParamBreath=he,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=oe,t.ParamEyeBallY=ae,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=ne,t.ParamMouthOpenY="ParamMouthOpenY",t.ParamNONE="NONE:",t.ParamShoulderY="ParamShoulderY",t.PartColorData=B,t.PartData=g,t.PartsArmLPrefix="Parts01ArmL_",t.PartsArmPrefix="Parts01Arm_",t.PartsArmRPrefix="Parts01ArmR_",t.PartsIdCore="Parts01Core",t.PhysicsJsonEffectiveForces=class{constructor(){this.gravity=new m(0,0),this.wind=new m(0,0)}},t.PhysicsOutput=vt,t.ShaderNames=Wt,t.SoundManager=be,t.VERSION="v0.5.0-beta",t.VOLUME=Pe,t.XHRLoader=Fe,t.ZipLoader=ze,t.applyMixins=ge,t.clamp=ce,t.config=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=kt,t.cubism4Ready=ui,t.folderName=me,t.fragmentShaderSrcMaskInvertedPremultipliedAlpha=Kt,t.fragmentShaderSrcMaskPremultipliedAlpha=Qt,t.fragmentShaderSrcPremultipliedAlpha=Zt,t.fragmentShaderSrcsetupMask=qt,t.logger=de,t.rand=function(t,e){return Math.random()*(e-t)+t},t.remove=pe,t.startUpCubism4=di,t.vertexShaderSrc=$t,t.vertexShaderSrcMasked=Jt,t.vertexShaderSrcSetupMask=Yt,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})})); diff --git a/dist/index.es.js b/dist/index.es.js index 1d5fb1f..8026d90 100644 --- a/dist/index.es.js +++ b/dist/index.es.js @@ -4384,7 +4384,7 @@ var LogLevel = /* @__PURE__ */ ((LogLevel2) => { LogLevel2[LogLevel2["LogLevel_Off"] = 5] = "LogLevel_Off"; return LogLevel2; })(LogLevel || {}); -const CSM_ASSERT = process.env.NODE_ENV === "production" ? () => { +const CSM_ASSERT = typeof process !== "undefined" && process.env.NODE_ENV === "production" ? () => { } : (expr) => console.assert(expr); function CubismLogDebug(fmt, ...args) { CubismDebug.print(LogLevel.LogLevel_Debug, "[CSM][D]" + fmt + "\n", args); diff --git a/dist/index.js b/dist/index.js index c7a8071..2e2717f 100644 --- a/dist/index.js +++ b/dist/index.js @@ -4386,7 +4386,7 @@ var __async = (__this, __arguments, generator) => { LogLevel2[LogLevel2["LogLevel_Off"] = 5] = "LogLevel_Off"; return LogLevel2; })(LogLevel || {}); - const CSM_ASSERT = process.env.NODE_ENV === "production" ? () => { + const CSM_ASSERT = typeof process !== "undefined" && process.env.NODE_ENV === "production" ? () => { } : (expr) => console.assert(expr); function CubismLogDebug(fmt, ...args) { CubismDebug.print(LogLevel.LogLevel_Debug, "[CSM][D]" + fmt + "\n", args); diff --git a/dist/index.min.js b/dist/index.min.js index 550f629..1631ead 100644 --- a/dist/index.min.js +++ b/dist/index.min.js @@ -1 +1 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("@pixi/core"),require("@pixi/display")):"function"==typeof define&&define.amd?define(["exports","@pixi/core","@pixi/display"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).PIXI=t.PIXI||{},t.PIXI.live2d=t.PIXI.live2d||{}),t.PIXI,t.PIXI)}(this,(function(t,e,i){"use strict";var s=Object.defineProperty,r=Math.pow,o=(t,e,i)=>(((t,e,i)=>{e in t?s(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i})(t,"symbol"!=typeof e?e+"":e,i),i),n=(t,e,i)=>new Promise(((s,r)=>{var o=t=>{try{a(i.next(t))}catch(e){r(e)}},n=t=>{try{a(i.throw(t))}catch(e){r(e)}},a=t=>t.done?s(t.value):Promise.resolve(t.value).then(o,n);a((i=i.apply(t,e)).next())}));var a,l;(l=a||(a={})).supportMoreMaskDivisions=!0,l.setOpacityFromMotion=!1;const h={LOG_LEVEL_VERBOSE:0,LOG_LEVEL_WARNING:1,LOG_LEVEL_ERROR:2,LOG_LEVEL_NONE:999,logLevel:1,sound:!0,motionSync:!0,motionFadingDuration:500,idleMotionFadingDuration:2e3,expressionFadingDuration:500,preserveExpressionOnMotion:!0,cubism4:a},u={log(t,...e){h.logLevel<=h.LOG_LEVEL_VERBOSE&&console.log(`[${t}]`,...e)},warn(t,...e){h.logLevel<=h.LOG_LEVEL_WARNING&&console.warn(`[${t}]`,...e)},error(t,...e){h.logLevel<=h.LOG_LEVEL_ERROR&&console.error(`[${t}]`,...e)}};function d(t,e,i){return ti?i:t}function c(t,e){return Math.random()*(e-t)+t}function g(t,e,i,s,r){const o=e[s];null!==o&&typeof o===t&&(i[r]=o)}function m(t,e,i,s,r){const o=e[s];Array.isArray(o)&&(i[r]=o.filter((e=>null!==e&&typeof e===t)))}function p(t,e){e.forEach((e=>{Object.getOwnPropertyNames(e.prototype).forEach((i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i))}))}))}function _(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 f(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}class x extends e.utils.EventEmitter{constructor(t,e){super(),o(this,"tag"),o(this,"settings"),o(this,"expressions",[]),o(this,"defaultExpression"),o(this,"currentExpression"),o(this,"reserveExpressionIndex",-1),o(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 n(this,null,(function*(){if(!this.definitions[t])return void u.warn(this.tag,`Undefined expression at [${t}]`);if(null===this.expressions[t])return void u.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 n(this,null,(function*(){if(this.definitions.length){const t=[];for(let e=0;e-1&&th&&(n*=h/l,a*=h/l),this.vx+=n,this.vy+=a;const u=Math.sqrt(r(this.vx,2)+r(this.vy,2)),d=.5*(Math.sqrt(r(h,2)+8*h*s)-h);u>d&&(this.vx*=d/u,this.vy*=d/u),this.x+=this.vx,this.y+=this.vy}}class v{constructor(t){o(this,"json"),o(this,"name"),o(this,"url"),o(this,"pose"),o(this,"physics"),this.json=t;const 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=_(this.url)}resolveURL(t){return e.utils.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 P=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(P||{});class b{constructor(){o(this,"tag"),o(this,"debug",!1),o(this,"currentPriority",0),o(this,"reservePriority",0),o(this,"currentGroup"),o(this,"currentIndex"),o(this,"reservedGroup"),o(this,"reservedIndex"),o(this,"reservedIdleGroup"),o(this,"reservedIdleIndex")}reserve(t,e,i){if(i<=0)return u.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(t===this.currentGroup&&e===this.currentIndex)return u.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 u.log(this.tag,"Motion is already reserved.",this.dump(t,e)),!1;if(1===i){if(0!==this.currentPriority)return u.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,e)),!1;if(void 0!==this.reservedIdleGroup)return u.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 u.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 u.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 u.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 u.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!h.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""}}const S=.5;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,i,s){const r=new Audio(t);return r.volume=this._volume,r.preload="auto",r.crossOrigin=s,r.addEventListener("ended",(()=>{this.dispose(r),null==e||e()})),r.addEventListener("error",(e=>{this.dispose(r),u.warn("SoundManager",`Error occurred on "${t}"`,e.error),null==i||i(e.error)})),this.audios.push(r),r}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){const e=new Float32Array(t.fftSize);let 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"),f(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])}}o(w,"audios",[]),o(w,"analysers",[]),o(w,"contexts",[]),o(w,"_volume",S);var I=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(I||{});class T extends e.utils.EventEmitter{constructor(t,e){super(),o(this,"tag"),o(this,"settings"),o(this,"motionGroups",{}),o(this,"state",new b),o(this,"currentAudio"),o(this,"currentAnalyzer"),o(this,"currentContext"),o(this,"playing",!1),o(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{console.log("Audio finished playing"),null==o||o(),s&&i&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0}),((t,e=this)=>{console.log("Error during audio playback:",t),null==n||n(t),s&&i&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),r),this.currentAudio=a,w.volume=e,d=w.addContext(this.currentAudio),this.currentContext=d,l=w.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=l}catch(p){return u.warn(this.tag,"Failed to create audio",c,p),!1}if(a){let t=!0;const e=w.play(a).catch((e=>{u.warn(this.tag,"Failed to play audio",a.src,e),t=!1}));if(h.motionSync&&(yield e,!t))return!1}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),i&&this.expressionManager&&this.expressionManager.setExpression(i),this.playing=!0,!0}))}startMotion(t,e){return n(this,arguments,(function*(t,e,i=P.NORMAL,{sound:s,volume:r=.5,expression:o,resetExpression:n=!0,crossOrigin:a,onFinish:l,onError:d}={}){var c;if(!this.state.reserve(t,e,i))return!1;if(this.currentAudio&&!this.currentAudio.ended&&i!=P.FORCE)return!1;const g=null==(c=this.definitions[t])?void 0:c[e];if(!g)return!1;let m,p,_,f;this.currentAudio&&w.dispose(this.currentAudio);const x=s&&s.startsWith("data:");if(s&&!x){const t=document.createElement("a");t.href=s,f=s=t.href}else f=this.getSoundFile(g),f&&(f=this.settings.resolveURL(f));const y=f;if(y)try{m=w.add(y,((t=this)=>{console.log("Audio finished playing"),null==l||l(),console.log(l),n&&o&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0}),((t,e=this)=>{console.log("Error during audio playback:",t),null==d||d(t),n&&o&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),a),this.currentAudio=m,w.volume=r,_=w.addContext(this.currentAudio),this.currentContext=_,p=w.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=p}catch(C){u.warn(this.tag,"Failed to create audio",f,C)}const M=yield this.loadMotion(t,e);if(m){const t=w.play(m).catch((t=>u.warn(this.tag,"Failed to play audio",m.src,t)));h.motionSync&&(yield t)}return this.state.start(M,t,e,i)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),u.log(this.tag,"Start motion:",this.getMotionName(g)),this.emit("motionStart",t,e,m),o&&this.expressionManager&&this.state.shouldOverrideExpression()&&this.expressionManager.setExpression(o),this.playing=!0,this._startMotion(M),!0):(m&&(w.dispose(m),this.currentAudio=void 0),!1)}))}startRandomMotion(t,e){return n(this,arguments,(function*(t,e,{sound:i,volume:s=.5,expression:r,resetExpression:o=!0,crossOrigin:n,onFinish:a,onError:l}={}){const h=this.definitions[t];if(null==h?void 0:h.length){const u=[];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,E);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],n=i[1];for(let a=0;a{200!==n.status&&0!==n.status||!n.response?n.onerror():r(n.response)},n.onerror=()=>{u.warn("XHRLoader",`Failed to load resource as ${n.responseType} (Status ${n.status}): ${i}`),o(new F("Network error.",i,n.status))},n.onabort=()=>o(new F("Aborted.",i,n.status,!0)),n.onloadend=()=>{var i;t.allXhrSet.delete(n),e&&(null==(i=t.xhrMap.get(e))||i.delete(n))},n}static cancelXHRs(){var e;null==(e=t.xhrMap.get(this))||e.forEach((e=>{e.abort(),t.allXhrSet.delete(e)})),t.xhrMap.delete(this)}static release(){t.allXhrSet.forEach((t=>t.abort())),t.allXhrSet.clear(),t.xhrMap=new WeakMap}};o(D,"xhrMap",new WeakMap),o(D,"allXhrSet",new Set),o(D,"loader",((t,e)=>new Promise(((e,i)=>{D.createXHR(t.target,t.settings?t.settings.resolveURL(t.url):t.url,t.type,(i=>{t.result=i,e()}),i).send()}))));let A=D;function R(t,e){let i=-1;return function s(r,o){if(o)return Promise.reject(o);if(r<=i)return Promise.reject(new Error("next() called multiple times"));i=r;const n=t[r];if(!n)return Promise.resolve();try{return Promise.resolve(n(e,s.bind(null,r+1)))}catch(a){return Promise.reject(a)}}(0)}class B{static load(t){return R(this.middlewares,t).then((()=>t.result))}}function O(){}o(B,"middlewares",[A.loader]);const k="Live2DFactory",U=(t,e)=>n(this,null,(function*(){if("string"==typeof t.source){const e=yield B.load({url:t.source,type:"json",target:t.live2dModel});e.url=t.source,t.source=e,t.live2dModel.emit("settingsJSONLoaded",e)}return e()})),V=(t,e)=>n(this,null,(function*(){if(t.source instanceof v)return t.settings=t.source,e();if("object"==typeof t.source){const i=$.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.")})),N=(t,e)=>{if(t.settings){const i=$.findRuntime(t.settings);if(i)return i.ready().then(e)}return e()},G=(t,e)=>n(this,null,(function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=$.findRuntime(e);if(s){const r=[];e.pose&&r.push(B.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),u.warn(k,"Failed to load pose.",e)}))),e.physics&&r.push(B.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),u.warn(k,"Failed to load physics.",e)}))),r.length&&(yield Promise.all(r))}}})),X=(t,i)=>n(this,null,(function*(){if(!t.settings)throw new TypeError("Missing settings.");{const s=t.live2dModel,r=Promise.all(t.settings.textures.map((i=>function(t,i={}){const s={resourceOptions:{crossorigin:i.crossOrigin}};if(e.Texture.fromURL)return e.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=e.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 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(i),{crossOrigin:t.options.crossOrigin}))));if(r.catch(O),yield i(),!t.internalModel)throw new TypeError("Missing internal model.");s.internalModel=t.internalModel,s.emit("modelLoaded",t.internalModel),s.textures=yield r,s.emit("textureLoaded",s.textures)}})),j=(t,e)=>n(this,null,(function*(){const i=t.settings;if(i instanceof v){const s=$.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield B.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.")})),z=class t{static unzip(i,s){return n(this,null,(function*(){const r=yield t.getFilePaths(i),o=[];for(const t of s.getDefinedFiles()){const i=decodeURI(e.utils.url.resolve(s.url,t));r.includes(i)&&o.push(i)}const n=yield t.getFiles(i,o);for(let t=0;tt.endsWith("model.json")||t.endsWith("model3.json")));if(!i)throw new Error("Settings file not found");const s=yield t.readText(e,i);if(!s)throw new Error("Empty settings file: "+i);const r=JSON.parse(s);r.url=i;const o=t.live2dFactory.findRuntime(r);if(!o)throw new Error("Unknown settings JSON");return o.createModelSettings(r)}))}static zipReader(t,e){return n(this,null,(function*(){throw new Error("Not implemented")}))}static getFilePaths(t){return n(this,null,(function*(){throw new Error("Not implemented")}))}static getFiles(t,e){return n(this,null,(function*(){throw new Error("Not implemented")}))}static readText(t,e){return n(this,null,(function*(){throw new Error("Not implemented")}))}static releaseReader(t){}};o(z,"live2dFactory"),o(z,"ZIP_PROTOCOL","zip://"),o(z,"uid",0),o(z,"factory",((t,e)=>n(z,null,(function*(){const i=t.source;let s,r,o;if("string"==typeof i&&(i.endsWith(".zip")||i.startsWith(z.ZIP_PROTOCOL))?(s=i.startsWith(z.ZIP_PROTOCOL)?i.slice(z.ZIP_PROTOCOL.length):i,r=yield B.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 z.zipReader(r,s);o||(o=yield z.createSettings(e)),o._objectURL=z.ZIP_PROTOCOL+z.uid+"/"+o.url;const i=yield z.unzip(e,o);i.settings=o,t.source=i,s.startsWith("blob:")&&t.live2dModel.once("modelLoaded",(t=>{t.once("destroy",(function(){URL.revokeObjectURL(s)}))})),z.releaseReader(e)}return e()}))));let H=z;const W=class t{static resolveURL(e,i){var s;const r=null==(s=t.filesMap[e])?void 0:s[i];if(void 0===r)throw new Error("Cannot find this file from uploaded files: "+i);return r}static upload(i,s){return n(this,null,(function*(){const r={};for(const t of s.getDefinedFiles()){const o=decodeURI(e.utils.url.resolve(s.url,t)),n=i.find((t=>t.webkitRelativePath===o));n&&(r[t]=URL.createObjectURL(n))}t.filesMap[s._objectURL]=r}))}static createSettings(e){return n(this,null,(function*(){const i=e.find((t=>t.name.endsWith("model.json")||t.name.endsWith("model3.json")));if(!i)throw new TypeError("Settings file not found");const s=yield t.readText(i),r=JSON.parse(s);r.url=i.webkitRelativePath;const o=$.findRuntime(r);if(!o)throw new Error("Unknown settings JSON");const n=o.createModelSettings(r);return n._objectURL=URL.createObjectURL(i),n}))}static readText(t){return n(this,null,(function*(){return new Promise(((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")}))}))}};o(W,"live2dFactory"),o(W,"filesMap",{}),o(W,"factory",((t,e)=>n(W,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 W.createSettings(e);i.validateFiles(e.map((t=>encodeURI(t.webkitRelativePath)))),yield W.upload(e,i),i.resolveURL=function(t){return W.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),W.filesMap[t])for(const e of Object.values(W.filesMap[t]))URL.revokeObjectURL(e);delete W.filesMap[t]}))}))}return e()}))));let Y=W;const q=class t{static registerRuntime(e){t.runtimes.push(e),t.runtimes.sort(((t,e)=>e.version-t.version))}static findRuntime(e){for(const i of t.runtimes)if(i.test(e))return i}static setupLive2DModel(e,i,s){return n(this,null,(function*(){const r=new Promise((t=>e.once("textureLoaded",t))),o=new Promise((t=>e.once("modelLoaded",t))),n=Promise.all([r,o]).then((()=>e.emit("ready")));yield R(t.live2DModelMiddlewares,{live2dModel:e,source:i,options:s||{}}),yield n,e.emit("load")}))}static loadMotion(e,i,s){var r;const o=t=>e.emit("motionLoadError",i,s,t);try{const n=null==(r=e.definitions[i])?void 0:r[s];if(!n)return Promise.resolve(void 0);e.listeners("destroy").includes(t.releaseTasks)||e.once("destroy",t.releaseTasks);let a=t.motionTasksMap.get(e);a||(a={},t.motionTasksMap.set(e,a));let l=a[i];l||(l=[],a[i]=l);const h=e.getMotionFile(n);return null!=l[s]||(l[s]=B.load({url:h,settings:e.settings,type:e.motionDataType,target:e}).then((r=>{var o;const a=null==(o=t.motionTasksMap.get(e))?void 0:o[i];a&&delete a[s];const l=e.createMotion(r,i,n);return e.emit("motionLoaded",i,s,l),l})).catch((t=>{u.warn(e.tag,`Failed to load motion: ${h}\n`,t),o(t)}))),l[s]}catch(n){u.warn(e.tag,`Failed to load motion at "${i}"[${s}]\n`,n),o(n)}return Promise.resolve(void 0)}static loadExpression(e,i){const s=t=>e.emit("expressionLoadError",i,t);try{const r=e.definitions[i];if(!r)return Promise.resolve(void 0);e.listeners("destroy").includes(t.releaseTasks)||e.once("destroy",t.releaseTasks);let o=t.expressionTasksMap.get(e);o||(o=[],t.expressionTasksMap.set(e,o));const n=e.getExpressionFile(r);return null!=o[i]||(o[i]=B.load({url:n,settings:e.settings,type:"json",target:e}).then((s=>{const o=t.expressionTasksMap.get(e);o&&delete o[i];const n=e.createExpression(s,r);return e.emit("expressionLoaded",i,n),n})).catch((t=>{u.warn(e.tag,`Failed to load expression: ${n}\n`,t),s(t)}))),o[i]}catch(r){u.warn(e.tag,`Failed to load expression at [${i}]\n`,r),s(r)}return Promise.resolve(void 0)}static releaseTasks(){this instanceof T?t.motionTasksMap.delete(this):t.expressionTasksMap.delete(this)}};o(q,"runtimes",[]),o(q,"urlToJSON",U),o(q,"jsonToSettings",V),o(q,"waitUntilReady",N),o(q,"setupOptionals",G),o(q,"setupEssentials",X),o(q,"createInternalModel",j),o(q,"live2DModelMiddlewares",[H.factory,Y.factory,U,V,N,G,X,j]),o(q,"motionTasksMap",new WeakMap),o(q,"expressionTasksMap",new WeakMap);let $=q;T.prototype._loadMotion=function(t,e){return $.loadMotion(this,t,e)},x.prototype._loadExpression=function(t){return $.loadExpression(this,t)},Y.live2dFactory=$,H.live2dFactory=$;const Z=class t{constructor(e,{autoUpdate:i=!0,autoHitTest:s=!0,autoFocus:r=!0,autoInteract:n,ticker:a}={}){o(this,"model"),o(this,"destroyed",!1),o(this,"_ticker"),o(this,"_autoUpdate",!1),o(this,"_autoHitTest",!1),o(this,"_autoFocus",!1),a||(t.defaultTicker?a=t.defaultTicker:"undefined"!=typeof PIXI&&(a=PIXI.Ticker.shared)),void 0!==n&&(s=n,r=n,u.warn(e.tag,"options.autoInteract is deprecated since v0.5.0, use autoHitTest and autoFocus instead.")),this.model=e,this.ticker=a,this.autoUpdate=i,this.autoHitTest=s,this.autoFocus=r,(s||r)&&(this.model.eventMode="static")}get ticker(){return this._ticker}set ticker(t){var e;this._ticker&&this._ticker.remove(Q,this),this._ticker=t,this._autoUpdate&&(null==(e=this._ticker)||e.add(Q,this))}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){var e;this.destroyed||(t?this._ticker?(this._ticker.add(Q,this),this._autoUpdate=!0):u.warn(this.model.tag,"No Ticker to be used for automatic updates. Either set option.ticker when creating Live2DModel, or expose PIXI to global scope (window.PIXI = PIXI)."):(null==(e=this._ticker)||e.remove(Q,this),this._autoUpdate=!1))}get autoHitTest(){return this._autoHitTest}set autoHitTest(t){t!==this.autoHitTest&&(t?this.model.on("pointertap",K,this):this.model.off("pointertap",K,this),this._autoHitTest=t)}get autoFocus(){return this._autoFocus}set autoFocus(t){t!==this.autoFocus&&(t?this.model.on("globalpointermove",tt,this):this.model.off("globalpointermove",tt,this),this._autoFocus=t)}get autoInteract(){return this._autoHitTest&&this._autoFocus}set autoInteract(t){this.autoHitTest=t,this.autoFocus=t}onTickerUpdate(){const t=this.ticker.deltaMS;this.model.update(t)}onTap(t){this.model.tap(t.global.x,t.global.y)}onPointerMove(t){this.model.focus(t.global.x,t.global.y)}destroy(){this.autoFocus=!1,this.autoHitTest=!1,this.autoUpdate=!1,this.ticker=void 0,this.destroyed=!0}};o(Z,"defaultTicker");let J=Z;function Q(){this.onTickerUpdate()}function K(t){this.onTap(t)}function tt(t){this.onPointerMove(t)}class et extends e.Transform{}const it=new e.Point,st=new e.Matrix;class rt extends i.Container{constructor(t){super(),o(this,"tag","Live2DModel(uninitialized)"),o(this,"internalModel"),o(this,"textures",[]),o(this,"transform",new et),o(this,"anchor",new e.ObservablePoint(this.onAnchorChange,this,0,0)),o(this,"glContextID",-1),o(this,"elapsedTime",0),o(this,"deltaTime",0),o(this,"automator"),this.automator=new J(this,t),this.once("modelLoaded",(()=>this.init(t)))}static from(t,e){const i=new this(e);return $.setupLive2DModel(i,t,e).then((()=>i))}static fromSync(t,e){const i=new this(e);return $.setupLive2DModel(i,t,e).then(null==e?void 0:e.onLoad).catch(null==e?void 0:e.onError),i}static registerTicker(t){J.defaultTicker=t.shared}init(t){this.tag=`Live2DModel(${this.internalModel.settings.name})`}onAnchorChange(){this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(t,e,i,{sound:s,volume:r=.5,expression:o,resetExpression:n=!0,crossOrigin:a,onFinish:l,onError:h}={}){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i,{sound:s,volume:r,expression:o,resetExpression:n,crossOrigin:a,onFinish:l,onError:h}):this.internalModel.motionManager.startMotion(t,e,i,{sound:s,volume:r,expression:o,resetExpression:n,crossOrigin:a,onFinish:l,onError:h})}stopMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(t,{volume:e=.5,expression:i,resetExpression:s=!0,crossOrigin:r,onFinish:o,onError:n}={}){return this.internalModel.motionManager.speak(t,{volume:e,expression:i,resetExpression:s,crossOrigin:r,onFinish:o,onError:n})}stopSpeaking(){return this.internalModel.motionManager.stopSpeaking()}expression(t){return this.internalModel.motionManager.expressionManager?void 0===t?this.internalModel.motionManager.expressionManager.setRandomExpression():this.internalModel.motionManager.expressionManager.setExpression(t):Promise.resolve(!1)}focus(t,e,i=!1){it.x=t,it.y=e,this.toModelPosition(it,it,!0);const s=it.x/this.internalModel.originalWidth*2-1,r=it.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&&(u.log(this.tag,"Hit",i),this.emit("hit",i))}hitTest(t,e){return it.x=t,it.y=e,this.toModelPosition(it,it),this.internalModel.hitTest(it.x,it.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)}update(t){this.deltaTime+=t,this.elapsedTime+=t}_render(t){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.automator.destroy(),this.internalModel.destroy(),super.destroy(t)}}if(!window.Live2D)throw new Error("Could not find Cubism 2 runtime. This plugin requires live2d.min.js to be loaded.");const ot=Live2DMotion.prototype.updateParam;Live2DMotion.prototype.updateParam=function(t,e){ot.call(this,t,e),e.isFinished()&&this.onFinishHandler&&(this.onFinishHandler(this),delete this.onFinishHandler)};class nt extends AMotion{constructor(t){super(),o(this,"params",[]),this.setFadeIn(t.fade_in>0?t.fade_in:h.expressionFadingDuration),this.setFadeOut(t.fade_out>0?t.fade_out:h.expressionFadingDuration),Array.isArray(t.params)&&t.params.forEach((t=>{const e=t.calc||"add";if("add"===e){const e=t.def||0;t.val-=e}else if("mult"===e){const e=t.def||1;t.val/=e}this.params.push({calc:e,val:t.val,id:t.id})}))}updateParamExe(t,e,i,s){this.params.forEach((e=>{t.setParamFloat(e.id,e.val*i)}))}}class at extends x{constructor(t,e){var i;super(t,e),o(this,"queueManager",new MotionQueueManager),o(this,"definitions"),this.definitions=null!=(i=this.settings.expressions)?i:[],this.init()}isFinished(){return this.queueManager.isFinished()}getExpressionIndex(t){return this.definitions.findIndex((e=>e.name===t))}getExpressionFile(t){return t.file}createExpression(t,e){return new nt(t)}_setExpression(t){return this.queueManager.startMotion(t)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}}class lt extends T{constructor(t,e){super(t,e),o(this,"definitions"),o(this,"groups",{idle:"idle"}),o(this,"motionDataType","arraybuffer"),o(this,"queueManager",new MotionQueueManager),o(this,"lipSyncIds"),o(this,"expressionManager"),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 at(this.settings,t))}isFinished(){return this.queueManager.isFinished()}createMotion(t,e,i){const s=Live2DMotion.loadMotion(t),r=e===this.groups.idle?h.idleMotionFadingDuration:h.motionFadingDuration;return s.setFadeIn(i.fade_in>0?i.fade_in:r),s.setFadeOut(i.fade_out>0?i.fade_out:r),s}getMotionFile(t){return t.file}getMotionName(t){return t.file}getSoundFile(t){return t.sound}_startMotion(t,e){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 ht{constructor(t){o(this,"leftParam"),o(this,"rightParam"),o(this,"blinkInterval",4e3),o(this,"closingDuration",100),o(this,"closedDuration",50),o(this,"openingDuration",150),o(this,"eyeState",0),o(this,"eyeParamValue",1),o(this,"closedTimer",0),o(this,"nextBlinkTimeLeft",this.blinkInterval),this.coreModel=t,this.leftParam=t.getParamIndex("PARAM_EYE_L_OPEN"),this.rightParam=t.getParamIndex("PARAM_EYE_R_OPEN")}setEyeParams(t){this.eyeParamValue=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+c(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 ut=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class dt extends L{constructor(t,e,i){super(),o(this,"settings"),o(this,"coreModel"),o(this,"motionManager"),o(this,"eyeBlink"),o(this,"eyeballXParamIndex"),o(this,"eyeballYParamIndex"),o(this,"angleXParamIndex"),o(this,"angleYParamIndex"),o(this,"angleZParamIndex"),o(this,"bodyAngleXParamIndex"),o(this,"breathParamIndex"),o(this,"textureFlipY",!0),o(this,"lipSync",!0),o(this,"drawDataCount",0),o(this,"disableCulling",!1),o(this,"hasDrawn",!1),this.coreModel=t,this.settings=e,this.motionManager=new lt(e,i),this.eyeBlink=new ht(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,i]of Object.entries(this.settings.layout)){let s=e;"center_x"===e?s="centerX":"center_y"===e&&(s="centerY"),t[s]=i}return t}updateWebGLContext(t,e){const i=this.coreModel.drawParamWebGL;i.firstDraw=!0,i.setGL(t),i.glno=e;for(const[o,n]of Object.entries(i))n 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=Math.pow(t,r),t=d(t*s,e,i);for(let o=0;o0&&t.textures.every((t=>"string"==typeof t))}copy(t){g("string",t,this,"name","name"),g("string",t,this,"pose","pose"),g("string",t,this,"physics","physics"),g("object",t,this,"layout","layout"),g("object",t,this,"motions","motions"),m("object",t,this,"hit_areas","hitAreas"),m("object",t,this,"expressions","expressions"),m("object",t,this,"init_params","initParams"),m("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=gt[i];o&&e.addSrcParam(o,t,s,r)})),t.targets.forEach((({id:t,ptype:i,scale:s,weight:r})=>{const o=mt[i];o&&e.addTargetParam(o,t,s,r)})),e})))}update(t){this.physicsHairs.forEach((e=>e.update(this.coreModel,t)))}}class _t{constructor(t){o(this,"paramIndex",-1),o(this,"partsIndex",-1),o(this,"link",[]),this.id=t}initIndex(t){this.paramIndex=t.getParamIndex("VISIBLE:"+this.id),this.partsIndex=t.getPartsDataIndex(PartsDataID.getID(this.id)),t.setParamFloat(this.paramIndex,1)}}class ft{constructor(t,e){o(this,"opacityAnimDuration",500),o(this,"partsGroups",[]),this.coreModel=t,e.parts_visible&&(this.partsGroups=e.parts_visible.map((({group:t})=>t.map((({id:t,link:e})=>{const i=new _t(t);return e&&(i.link=e.map((t=>new _t(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=d(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($.registerRuntime({version:2,test:t=>t instanceof ct||ct.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 ct(t),createCoreModel(t){const e=Live2DModelWebGL.loadModel(t),i=Live2D.getError();if(i)throw i;return e},createInternalModel:(t,e,i)=>new dt(t,e,i),createPose:(t,e)=>new ft(t,e),createPhysics:(t,e)=>new pt(t,e)}),!window.Live2DCubismCore)throw new Error("Could not find Cubism 4 runtime. This plugin requires live2dcubismcore.js to be loaded.");class xt{constructor(t,e){this.x=t||0,this.y=e||0}add(t){const e=new xt(0,0);return e.x=this.x+t.x,e.y=this.y+t.y,e}substract(t){const e=new xt(0,0);return e.x=this.x-t.x,e.y=this.y-t.y,e}multiply(t){const e=new xt(0,0);return e.x=this.x*t.x,e.y=this.y*t.y,e}multiplyByScaler(t){return this.multiply(new xt(t,t))}division(t){const e=new xt(0,0);return e.x=this.x/t.x,e.y=this.y/t.y,e}divisionByScalar(t){return this.division(new xt(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 yt=class t{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 xt;return e.x=this.sin(t),e.y=this.cos(t),e}static quadraticEquation(e,i,s){return this.abs(e)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 bt,this._useHighPrecisionMask=!1,this._mvpMatrix4x4=new Ct,this._mvpMatrix4x4.loadIdentity()}}var Pt=(t=>(t[t.CubismBlendMode_Normal=0]="CubismBlendMode_Normal",t[t.CubismBlendMode_Additive=1]="CubismBlendMode_Additive",t[t.CubismBlendMode_Multiplicative=2]="CubismBlendMode_Multiplicative",t))(Pt||{});class bt{constructor(t=1,e=1,i=1,s=1){this.R=t,this.G=e,this.B=i,this.A=s}}let St,wt=!1,It=!1;const Tt=0,Et=2;class Lt{static startUp(t){if(wt)return Rt("CubismFramework.startUp() is already done."),wt;if(Live2DCubismCore._isStarted)return wt=!0,!0;if(Live2DCubismCore._isStarted=!0,St=t,St&&Live2DCubismCore.Logging.csmSetLogFunction(St.logFunction),wt=!0,wt){const t=Live2DCubismCore.Version.csmGetVersion(),e=(16711680&t)>>16,i=65535&t,s=t;Rt("Live2D Cubism Core version: {0}.{1}.{2} ({3})",("00"+((4278190080&t)>>24)).slice(-2),("00"+e).slice(-2),("0000"+i).slice(-4),s)}return Rt("CubismFramework.startUp() is complete."),wt}static cleanUp(){wt=!1,It=!1,St=void 0}static initialize(t=0){wt?It?Bt("CubismFramework.initialize() skipped, already initialized."):(Live2DCubismCore.Memory.initializeAmountOfMemory(t),It=!0,Rt("CubismFramework.initialize() is complete.")):Bt("CubismFramework is not started.")}static dispose(){wt?It?(vt.staticRelease(),It=!1,Rt("CubismFramework.dispose() is complete.")):Bt("CubismFramework.dispose() skipped, not initialized."):Bt("CubismFramework is not started.")}static isStarted(){return wt}static isInitialized(){return It}static coreLogFunction(t){Live2DCubismCore.Logging.csmGetLogFunction()&&Live2DCubismCore.Logging.csmGetLogFunction()(t)}static getLoggingLevel(){return null!=St?St.loggingLevel:5}constructor(){}}var Ft=(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))(Ft||{});const Dt="production"===process.env.NODE_ENV?()=>{}:t=>console.assert(t);function At(t,...e){kt.print(Ft.LogLevel_Debug,"[CSM][D]"+t+"\n",e)}function Rt(t,...e){kt.print(Ft.LogLevel_Info,"[CSM][I]"+t+"\n",e)}function Bt(t,...e){kt.print(Ft.LogLevel_Warning,"[CSM][W]"+t+"\n",e)}function Ot(t,...e){kt.print(Ft.LogLevel_Error,"[CSM][E]"+t+"\n",e)}class kt{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 Ut{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:Mt.getEasingSine((i-e.getFadeInStartTime())/this._fadeInSeconds))*(0==this._fadeOutSeconds||e.getEndTime()<0?1:Mt.getEasingSine((e.getEndTime()-i)/this._fadeOutSeconds)),e.setState(i,s),Dt(0<=s&&s<=1),this.doUpdateParameters(t,i,s,e),e.getEndTime()>0&&e.getEndTime()null!=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 Vt.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)}}var zt=(t=>(t[t.CubismMotionCurveTarget_Model=0]="CubismMotionCurveTarget_Model",t[t.CubismMotionCurveTarget_Parameter=1]="CubismMotionCurveTarget_Parameter",t[t.CubismMotionCurveTarget_PartOpacity=2]="CubismMotionCurveTarget_PartOpacity",t))(zt||{}),Ht=(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))(Ht||{});class Wt{constructor(t=0,e=0){this.time=t,this.value=e}}class Yt{constructor(){this.basePointIndex=0,this.segmentType=0}}class qt{constructor(){this.id="",this.type=0,this.segmentCount=0,this.baseSegmentIndex=0,this.fadeInTime=0,this.fadeOutTime=0}}class $t{constructor(){this.fireTime=0,this.value=""}}class Zt{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 Jt{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 0==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 Qt=(t=>(t[t.EvaluationOptionFlag_AreBeziersRistricted=0]="EvaluationOptionFlag_AreBeziersRistricted",t))(Qt||{});const Kt="Opacity";function te(t,e,i){const s=new Wt;return s.time=t.time+(e.time-t.time)*i,s.value=t.value+(e.value-t.value)*i,s}function ee(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 ie(t,e){let i=(e-t[0].time)/(t[3].time-t[0].time);i<0&&(i=0);const s=te(t[0],t[1],i),r=te(t[1],t[2],i),o=te(t[2],t[3],i),n=te(s,r,i),a=te(r,o,i);return te(n,a,i).value}function se(t,e){const i=e,s=t[0].time,r=t[3].time,o=t[1].time,n=t[2].time,a=r-3*n+3*o-s,l=3*n-6*o+3*s,h=3*o-3*s,u=s-i,d=Mt.cardanoAlgorithmForBezier(a,l,h,u),c=te(t[0],t[1],d),g=te(t[1],t[2],d),m=te(t[2],t[3],d),p=te(c,g,d),_=te(g,m,d);return te(p,_,d).value}function re(t,e){return t[0].value}function oe(t,e){return t[1].value}function ne(t,e,i){const s=t.curves[e];let r=-1;const o=s.baseSegmentIndex+s.segmentCount;let n=0;for(let l=s.baseSegmentIndex;li){r=l;break}if(-1==r)return t.points[n].value;const a=t.segments[r];return a.evaluate(t.points.slice(a.basePointIndex),i)}class ae extends Ut{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 ae;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=Kt);let r=e-s.getStartTime();r<0&&(r=0);let o=Number.MAX_VALUE,n=Number.MAX_VALUE;const l=64;let h=0,u=0;this._eyeBlinkParameterIds.length>l&&At("too many eye blink targets : {0}",this._eyeBlinkParameterIds.length),this._lipSyncParameterIds.length>l&&At("too many lip sync targets : {0}",this._lipSyncParameterIds.length);const d=this._fadeInSeconds<=0?1:Mt.getEasingSine((e-s.getFadeInStartTime())/this._fadeInSeconds),c=this._fadeOutSeconds<=0||s.getEndTime()<0?1:Mt.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>a&1)continue;const s=e+(n-e)*i;t.setParameterValueById(this._eyeBlinkParameterIds[a],s)}if(o!=Number.MAX_VALUE)for(let a=0;a>a&1)continue;const s=e+(o-e)*i;t.setParameterValueById(this._lipSyncParameterIds[a],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 qt)),this._motionData.segments=Array.from({length:e.getMotionTotalSegmentCount()}).map((()=>new Yt)),this._motionData.events=Array.from({length:this._motionData.eventCount}).map((()=>new $t)),this._motionData.points=[];let o=0,n=0;for(let a=0;at&&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(t,e,i){const s=ae.create(t),r=new Jt(t),o=(e===this.groups.idle?h.idleMotionFadingDuration:h.motionFadingDuration)/1e3;return void 0===r.getMotionFadeInTime()&&s.setFadeInTime(i.FadeInTime>0?i.FadeInTime:o),void 0===r.getMotionFadeOutTime()&&s.setFadeOutTime(i.FadeOutTime>0?i.FadeOutTime:o),s.setEffectIds(this.eyeBlinkIds,this.lipSyncIds),s}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 he{constructor(){this._breathParameters=[],this._currentTime=0}static create(){return new he}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&&(r=1,this._blinkingState=3,this._stateStartTimeSeconds=this._userTimeSeconds),s=1-r;break;case 3:r=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._closedSeconds,r>=1&&(this._blinkingState=4,this._stateStartTimeSeconds=this._userTimeSeconds),s=0;break;case 4:r=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._openingSeconds,r>=1&&(r=1,this._blinkingState=1,this._nextBlinkingTime=this.determinNextBlinkingTiming()),s=r;break;case 1:this._nextBlinkingTimec&&(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,n=o-s;e._allClippedDrawRect.x=i,e._allClippedDrawRect.y=s,e._allClippedDrawRect.width=t,e._allClippedDrawRect.height=n}}}constructor(){this._currentMaskRenderTexture=null,this._currentFrameNo=0,this._renderTextureCount=0,this._clippingMaskBufferSize=256,this._clippingContextListForMask=[],this._clippingContextListForDraw=[],this._channelColors=[],this._tmpBoundsOnModel=new ge,this._tmpMatrix=new Ct,this._tmpMatrixForMask=new Ct,this._tmpMatrixForDraw=new Ct;let t=new bt;t.R=1,t.G=0,t.B=0,t.A=0,this._channelColors.push(t),t=new bt,t.R=0,t.G=1,t.B=0,t.A=0,this._channelColors.push(t),t=new bt,t.R=0,t.G=0,t.B=1,t.A=0,this._channelColors.push(t),t=new bt,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*n,0),a=o.width/this._tmpBoundsOnModel.width):a=e/h,this._tmpBoundsOnModel.height*e>u?(this._tmpBoundsOnModel.expand(0,r.height*n),l=o.height/this._tmpBoundsOnModel.height):l=e/u}else this._tmpBoundsOnModel.setRect(r),this._tmpBoundsOnModel.expand(r.width*n,r.height*n),a=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(a,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(a,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&&Ot("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)&&(u+=h=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 fe,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}constructor(){super(),this._clippingContextBufferForMask=null,this._clippingContextBufferForDraw=null,this._rendererProfile=new Me,this.firstDraw=!0,this._textures={},this._sortedDrawableIndexList=[],this._bufferData={vertex:null,uv:null,index:null}}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 Ot("'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),Ce.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")}}vt.staticRelease=()=>{Ee.doStaticRelease()};const Le=new Ct;class Fe extends L{constructor(t,i,s){super(),o(this,"settings"),o(this,"coreModel"),o(this,"motionManager"),o(this,"lipSync",!0),o(this,"breath",he.create()),o(this,"eyeBlink"),o(this,"userData"),o(this,"renderer",new Ee),o(this,"idParamAngleX","ParamAngleX"),o(this,"idParamAngleY","ParamAngleY"),o(this,"idParamAngleZ","ParamAngleZ"),o(this,"idParamEyeBallX","ParamEyeBallX"),o(this,"idParamEyeBallY","ParamEyeBallY"),o(this,"idParamBodyAngleX","ParamBodyAngleX"),o(this,"idParamBreath","ParamBreath"),o(this,"idParamMouthForm","ParamMouthForm"),o(this,"pixelsPerUnit",1),o(this,"centeringTransform",new e.Matrix),this.coreModel=t,this.settings=i,this.motionManager=new le(i,s),this.init()}init(){var t;super.init(),(null==(t=this.settings.getEyeBlinkParameters())?void 0:t.length)&&(this.eyeBlink=ce.create(this.settings)),this.breath.setParameters([new ue(this.idParamAngleX,0,15,6.5345,.5),new ue(this.idParamAngleY,0,8,3.5345,.5),new ue(this.idParamAngleZ,0,10,5.5345,.5),new ue(this.idParamBodyAngleX,0,4,15.5345,.5),new ue(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,i]of Object.entries(this.settings.layout)){t[e.charAt(0).toLowerCase()+e.slice(1)]=i}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,Ce.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=d(t*1.2,e,1);for(let i=0;i"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 Ae extends v{constructor(t){if(super(t),o(this,"moc"),o(this,"textures"),!Ae.isValidJSON(t))throw new TypeError("Invalid JSON.");Object.assign(this,new De(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{!function i(){try{ke(),t()}catch(s){if(Be--,Be<0){const t=new Error("Failed to start up Cubism 4 framework.");return t.cause=s,void e(t)}u.log("Cubism4","Startup failed, retrying 10ms later..."),setTimeout(i,10)}}()}))),Re)}function ke(t){t=Object.assign({logFunction:console.log,loggingLevel:Ft.LogLevel_Verbose},t),Lt.startUp(t),Lt.initialize()}class Ue{static create(t){const e=new Ue;"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=a,o=t.getPartOpacityByIndex(i),o+=e/this._fadeTimeSeconds,o>1&&(o=1)}}r<0&&(r=0,o=1);for(let a=i;a.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 Ve{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 Ve;return t.partId=this.partId,t.parameterIndex=this.parameterIndex,t.partIndex=this.partIndex,t.link=this.link.map((t=>t.clone())),t}}class Ne{constructor(t=!1,e=new bt){this.isOverwritten=t,this.Color=e}}class Ge{constructor(t=!1,e=new bt){this.isOverwritten=t,this.Color=e}}class Xe{constructor(t=!1,e=!1){this.isOverwritten=t,this.isCulling=e}}class je{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[a].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 ze{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 ze(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 je(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 He=(t=>(t[t.CubismPhysicsTargetType_Parameter=0]="CubismPhysicsTargetType_Parameter",t))(He||{}),We=(t=>(t[t.CubismPhysicsSource_X=0]="CubismPhysicsSource_X",t[t.CubismPhysicsSource_Y=1]="CubismPhysicsSource_Y",t[t.CubismPhysicsSource_Angle=2]="CubismPhysicsSource_Angle",t))(We||{});class Ye{constructor(){this.initialPosition=new xt(0,0),this.position=new xt(0,0),this.lastPosition=new xt(0,0),this.lastGravity=new xt(0,0),this.force=new xt(0,0),this.velocity=new xt(0,0)}}class qe{constructor(){this.normalizationPosition={},this.normalizationAngle={}}}class $e{constructor(){this.source={}}}class Ze{constructor(){this.destination={},this.translationScale=new xt(0,0)}}class Je{constructor(){this.settings=[],this.inputs=[],this.outputs=[],this.particles=[],this.gravity=new xt(0,0),this.wind=new xt(0,0),this.fps=0}}class Qe{constructor(t){this._json=t}release(){this._json=void 0}getGravity(){const t=new xt(0,0);return t.x=this._json.Meta.EffectiveForces.Gravity.X,t.y=this._json.Meta.EffectiveForces.Gravity.Y,t}getWind(){const t=new xt(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 xt(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 Ke="Angle";class ti{static create(t){const e=new ti;return e.parse(t),e._physicsRig.gravity.y=0,e}static delete(t){null!=t&&t.release()}parse(t){this._physicsRig=new Je;const e=new Qe(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 xt;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);pi(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 xt;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,n=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(this._parameterCaches.subarray(o))):this._parameterCaches.slice(o);pi(n,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=Mt.directionToRadian(r,t),s&&(o*=-1),o}function hi(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 ui(t,e){return t.x}function di(t,e){return t.y}function ci(t,e){return e}function gi(t,e,i,s,r,o,n,a){let l,h,u,d,c=new xt(0,0),g=new xt(0,0),m=new xt(0,0),p=new xt(0,0);t[0].position=new xt(i.x,i.y),l=Mt.degreesToRadian(s),d=Mt.radianToDirection(l),d.normalize();for(let _=1;_i&&(n>r.valueExceededMaximum&&(r.valueExceededMaximum=n),n=i),a=r.weight/100,a>=1||(n=t[0]*(1-a)+n*a),t[0]=n}function _i(t,e,i,s,r,o,n,a){let l=0;const h=Mt.max(i,e);ht&&(t=u);const d=Mt.min(r,o),c=Mt.max(r,o),g=n,m=hi(u,h),p=t-m;switch(Math.sign(p)){case 1:{const t=h-m;0!=t&&(l=p*((c-g)/t),l+=g);break}case-1:{const t=u-m;0!=t&&(l=p*((d-g)/t),l+=g);break}case 0:l=g}return a?l:-1*l}function fi(){var t;null==(t=this.__moc)||t.release()}$.registerRuntime({version:4,ready:Oe,test:t=>t instanceof Ae||Ae.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 Ae(t),createCoreModel(t,e){const i=ze.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 Fe(t,e,i),r=t;return r.__moc&&(s.__moc=r.__moc,delete r.__moc,s.once("destroy",fi)),s},createPhysics:(t,e)=>ti.create(e),createPose:(t,e)=>Ue.create(e)}),t.Cubism2ExpressionManager=at,t.Cubism2InternalModel=dt,t.Cubism2ModelSettings=ct,t.Cubism2MotionManager=lt,t.Cubism4ExpressionManager=jt,t.Cubism4InternalModel=Fe,t.Cubism4ModelSettings=Ae,t.Cubism4MotionManager=le,t.ExpressionManager=x,t.FileLoader=Y,t.FocusController=C,t.InternalModel=L,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DExpression=nt,t.Live2DEyeBlink=ht,t.Live2DFactory=$,t.Live2DLoader=B,t.Live2DModel=rt,t.Live2DPhysics=pt,t.Live2DPose=ft,t.Live2DTransform=et,t.ModelSettings=v,t.MotionManager=T,t.MotionPreloadStrategy=I,t.MotionPriority=P,t.MotionState=b,t.SoundManager=w,t.VERSION="v0.5.0-beta",t.VOLUME=S,t.XHRLoader=A,t.ZipLoader=H,t.applyMixins=p,t.clamp=d,t.config=h,t.copyArray=m,t.copyProperty=g,t.cubism4Ready=Oe,t.folderName=_,t.logger=u,t.rand=c,t.remove=f,t.startUpCubism4=ke,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("@pixi/core"),require("@pixi/display")):"function"==typeof define&&define.amd?define(["exports","@pixi/core","@pixi/display"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).PIXI=t.PIXI||{},t.PIXI.live2d=t.PIXI.live2d||{}),t.PIXI,t.PIXI)}(this,(function(t,e,i){"use strict";var s=Object.defineProperty,r=Math.pow,o=(t,e,i)=>(((t,e,i)=>{e in t?s(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i})(t,"symbol"!=typeof e?e+"":e,i),i),n=(t,e,i)=>new Promise(((s,r)=>{var o=t=>{try{a(i.next(t))}catch(e){r(e)}},n=t=>{try{a(i.throw(t))}catch(e){r(e)}},a=t=>t.done?s(t.value):Promise.resolve(t.value).then(o,n);a((i=i.apply(t,e)).next())}));var a,l;(l=a||(a={})).supportMoreMaskDivisions=!0,l.setOpacityFromMotion=!1;const h={LOG_LEVEL_VERBOSE:0,LOG_LEVEL_WARNING:1,LOG_LEVEL_ERROR:2,LOG_LEVEL_NONE:999,logLevel:1,sound:!0,motionSync:!0,motionFadingDuration:500,idleMotionFadingDuration:2e3,expressionFadingDuration:500,preserveExpressionOnMotion:!0,cubism4:a},u={log(t,...e){h.logLevel<=h.LOG_LEVEL_VERBOSE&&console.log(`[${t}]`,...e)},warn(t,...e){h.logLevel<=h.LOG_LEVEL_WARNING&&console.warn(`[${t}]`,...e)},error(t,...e){h.logLevel<=h.LOG_LEVEL_ERROR&&console.error(`[${t}]`,...e)}};function d(t,e,i){return ti?i:t}function c(t,e){return Math.random()*(e-t)+t}function g(t,e,i,s,r){const o=e[s];null!==o&&typeof o===t&&(i[r]=o)}function m(t,e,i,s,r){const o=e[s];Array.isArray(o)&&(i[r]=o.filter((e=>null!==e&&typeof e===t)))}function p(t,e){e.forEach((e=>{Object.getOwnPropertyNames(e.prototype).forEach((i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i))}))}))}function _(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 f(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}class x extends e.utils.EventEmitter{constructor(t,e){super(),o(this,"tag"),o(this,"settings"),o(this,"expressions",[]),o(this,"defaultExpression"),o(this,"currentExpression"),o(this,"reserveExpressionIndex",-1),o(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 n(this,null,(function*(){if(!this.definitions[t])return void u.warn(this.tag,`Undefined expression at [${t}]`);if(null===this.expressions[t])return void u.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 n(this,null,(function*(){if(this.definitions.length){const t=[];for(let e=0;e-1&&th&&(n*=h/l,a*=h/l),this.vx+=n,this.vy+=a;const u=Math.sqrt(r(this.vx,2)+r(this.vy,2)),d=.5*(Math.sqrt(r(h,2)+8*h*s)-h);u>d&&(this.vx*=d/u,this.vy*=d/u),this.x+=this.vx,this.y+=this.vy}}class v{constructor(t){o(this,"json"),o(this,"name"),o(this,"url"),o(this,"pose"),o(this,"physics"),this.json=t;const 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=_(this.url)}resolveURL(t){return e.utils.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 P=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(P||{});class b{constructor(){o(this,"tag"),o(this,"debug",!1),o(this,"currentPriority",0),o(this,"reservePriority",0),o(this,"currentGroup"),o(this,"currentIndex"),o(this,"reservedGroup"),o(this,"reservedIndex"),o(this,"reservedIdleGroup"),o(this,"reservedIdleIndex")}reserve(t,e,i){if(i<=0)return u.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(t===this.currentGroup&&e===this.currentIndex)return u.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 u.log(this.tag,"Motion is already reserved.",this.dump(t,e)),!1;if(1===i){if(0!==this.currentPriority)return u.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,e)),!1;if(void 0!==this.reservedIdleGroup)return u.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 u.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 u.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 u.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 u.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!h.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""}}const S=.5;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,i,s){const r=new Audio(t);return r.volume=this._volume,r.preload="auto",r.crossOrigin=s,r.addEventListener("ended",(()=>{this.dispose(r),null==e||e()})),r.addEventListener("error",(e=>{this.dispose(r),u.warn("SoundManager",`Error occurred on "${t}"`,e.error),null==i||i(e.error)})),this.audios.push(r),r}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){const e=new Float32Array(t.fftSize);let 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"),f(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])}}o(w,"audios",[]),o(w,"analysers",[]),o(w,"contexts",[]),o(w,"_volume",S);var I=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(I||{});class T extends e.utils.EventEmitter{constructor(t,e){super(),o(this,"tag"),o(this,"settings"),o(this,"motionGroups",{}),o(this,"state",new b),o(this,"currentAudio"),o(this,"currentAnalyzer"),o(this,"currentContext"),o(this,"playing",!1),o(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{console.log("Audio finished playing"),null==o||o(),s&&i&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0}),((t,e=this)=>{console.log("Error during audio playback:",t),null==n||n(t),s&&i&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),r),this.currentAudio=a,w.volume=e,d=w.addContext(this.currentAudio),this.currentContext=d,l=w.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=l}catch(p){return u.warn(this.tag,"Failed to create audio",c,p),!1}if(a){let t=!0;const e=w.play(a).catch((e=>{u.warn(this.tag,"Failed to play audio",a.src,e),t=!1}));if(h.motionSync&&(yield e,!t))return!1}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),i&&this.expressionManager&&this.expressionManager.setExpression(i),this.playing=!0,!0}))}startMotion(t,e){return n(this,arguments,(function*(t,e,i=P.NORMAL,{sound:s,volume:r=.5,expression:o,resetExpression:n=!0,crossOrigin:a,onFinish:l,onError:d}={}){var c;if(!this.state.reserve(t,e,i))return!1;if(this.currentAudio&&!this.currentAudio.ended&&i!=P.FORCE)return!1;const g=null==(c=this.definitions[t])?void 0:c[e];if(!g)return!1;let m,p,_,f;this.currentAudio&&w.dispose(this.currentAudio);const x=s&&s.startsWith("data:");if(s&&!x){const t=document.createElement("a");t.href=s,f=s=t.href}else f=this.getSoundFile(g),f&&(f=this.settings.resolveURL(f));const y=f;if(y)try{m=w.add(y,((t=this)=>{console.log("Audio finished playing"),null==l||l(),console.log(l),n&&o&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0}),((t,e=this)=>{console.log("Error during audio playback:",t),null==d||d(t),n&&o&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),a),this.currentAudio=m,w.volume=r,_=w.addContext(this.currentAudio),this.currentContext=_,p=w.addAnalyzer(this.currentAudio,this.currentContext),this.currentAnalyzer=p}catch(C){u.warn(this.tag,"Failed to create audio",f,C)}const M=yield this.loadMotion(t,e);if(m){const t=w.play(m).catch((t=>u.warn(this.tag,"Failed to play audio",m.src,t)));h.motionSync&&(yield t)}return this.state.start(M,t,e,i)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),u.log(this.tag,"Start motion:",this.getMotionName(g)),this.emit("motionStart",t,e,m),o&&this.expressionManager&&this.state.shouldOverrideExpression()&&this.expressionManager.setExpression(o),this.playing=!0,this._startMotion(M),!0):(m&&(w.dispose(m),this.currentAudio=void 0),!1)}))}startRandomMotion(t,e){return n(this,arguments,(function*(t,e,{sound:i,volume:s=.5,expression:r,resetExpression:o=!0,crossOrigin:n,onFinish:a,onError:l}={}){const h=this.definitions[t];if(null==h?void 0:h.length){const u=[];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,E);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],n=i[1];for(let a=0;a{200!==n.status&&0!==n.status||!n.response?n.onerror():r(n.response)},n.onerror=()=>{u.warn("XHRLoader",`Failed to load resource as ${n.responseType} (Status ${n.status}): ${i}`),o(new F("Network error.",i,n.status))},n.onabort=()=>o(new F("Aborted.",i,n.status,!0)),n.onloadend=()=>{var i;t.allXhrSet.delete(n),e&&(null==(i=t.xhrMap.get(e))||i.delete(n))},n}static cancelXHRs(){var e;null==(e=t.xhrMap.get(this))||e.forEach((e=>{e.abort(),t.allXhrSet.delete(e)})),t.xhrMap.delete(this)}static release(){t.allXhrSet.forEach((t=>t.abort())),t.allXhrSet.clear(),t.xhrMap=new WeakMap}};o(D,"xhrMap",new WeakMap),o(D,"allXhrSet",new Set),o(D,"loader",((t,e)=>new Promise(((e,i)=>{D.createXHR(t.target,t.settings?t.settings.resolveURL(t.url):t.url,t.type,(i=>{t.result=i,e()}),i).send()}))));let A=D;function R(t,e){let i=-1;return function s(r,o){if(o)return Promise.reject(o);if(r<=i)return Promise.reject(new Error("next() called multiple times"));i=r;const n=t[r];if(!n)return Promise.resolve();try{return Promise.resolve(n(e,s.bind(null,r+1)))}catch(a){return Promise.reject(a)}}(0)}class B{static load(t){return R(this.middlewares,t).then((()=>t.result))}}function O(){}o(B,"middlewares",[A.loader]);const k="Live2DFactory",U=(t,e)=>n(this,null,(function*(){if("string"==typeof t.source){const e=yield B.load({url:t.source,type:"json",target:t.live2dModel});e.url=t.source,t.source=e,t.live2dModel.emit("settingsJSONLoaded",e)}return e()})),V=(t,e)=>n(this,null,(function*(){if(t.source instanceof v)return t.settings=t.source,e();if("object"==typeof t.source){const i=$.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.")})),N=(t,e)=>{if(t.settings){const i=$.findRuntime(t.settings);if(i)return i.ready().then(e)}return e()},G=(t,e)=>n(this,null,(function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=$.findRuntime(e);if(s){const r=[];e.pose&&r.push(B.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),u.warn(k,"Failed to load pose.",e)}))),e.physics&&r.push(B.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),u.warn(k,"Failed to load physics.",e)}))),r.length&&(yield Promise.all(r))}}})),X=(t,i)=>n(this,null,(function*(){if(!t.settings)throw new TypeError("Missing settings.");{const s=t.live2dModel,r=Promise.all(t.settings.textures.map((i=>function(t,i={}){const s={resourceOptions:{crossorigin:i.crossOrigin}};if(e.Texture.fromURL)return e.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=e.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 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(i),{crossOrigin:t.options.crossOrigin}))));if(r.catch(O),yield i(),!t.internalModel)throw new TypeError("Missing internal model.");s.internalModel=t.internalModel,s.emit("modelLoaded",t.internalModel),s.textures=yield r,s.emit("textureLoaded",s.textures)}})),j=(t,e)=>n(this,null,(function*(){const i=t.settings;if(i instanceof v){const s=$.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield B.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.")})),z=class t{static unzip(i,s){return n(this,null,(function*(){const r=yield t.getFilePaths(i),o=[];for(const t of s.getDefinedFiles()){const i=decodeURI(e.utils.url.resolve(s.url,t));r.includes(i)&&o.push(i)}const n=yield t.getFiles(i,o);for(let t=0;tt.endsWith("model.json")||t.endsWith("model3.json")));if(!i)throw new Error("Settings file not found");const s=yield t.readText(e,i);if(!s)throw new Error("Empty settings file: "+i);const r=JSON.parse(s);r.url=i;const o=t.live2dFactory.findRuntime(r);if(!o)throw new Error("Unknown settings JSON");return o.createModelSettings(r)}))}static zipReader(t,e){return n(this,null,(function*(){throw new Error("Not implemented")}))}static getFilePaths(t){return n(this,null,(function*(){throw new Error("Not implemented")}))}static getFiles(t,e){return n(this,null,(function*(){throw new Error("Not implemented")}))}static readText(t,e){return n(this,null,(function*(){throw new Error("Not implemented")}))}static releaseReader(t){}};o(z,"live2dFactory"),o(z,"ZIP_PROTOCOL","zip://"),o(z,"uid",0),o(z,"factory",((t,e)=>n(z,null,(function*(){const i=t.source;let s,r,o;if("string"==typeof i&&(i.endsWith(".zip")||i.startsWith(z.ZIP_PROTOCOL))?(s=i.startsWith(z.ZIP_PROTOCOL)?i.slice(z.ZIP_PROTOCOL.length):i,r=yield B.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 z.zipReader(r,s);o||(o=yield z.createSettings(e)),o._objectURL=z.ZIP_PROTOCOL+z.uid+"/"+o.url;const i=yield z.unzip(e,o);i.settings=o,t.source=i,s.startsWith("blob:")&&t.live2dModel.once("modelLoaded",(t=>{t.once("destroy",(function(){URL.revokeObjectURL(s)}))})),z.releaseReader(e)}return e()}))));let H=z;const W=class t{static resolveURL(e,i){var s;const r=null==(s=t.filesMap[e])?void 0:s[i];if(void 0===r)throw new Error("Cannot find this file from uploaded files: "+i);return r}static upload(i,s){return n(this,null,(function*(){const r={};for(const t of s.getDefinedFiles()){const o=decodeURI(e.utils.url.resolve(s.url,t)),n=i.find((t=>t.webkitRelativePath===o));n&&(r[t]=URL.createObjectURL(n))}t.filesMap[s._objectURL]=r}))}static createSettings(e){return n(this,null,(function*(){const i=e.find((t=>t.name.endsWith("model.json")||t.name.endsWith("model3.json")));if(!i)throw new TypeError("Settings file not found");const s=yield t.readText(i),r=JSON.parse(s);r.url=i.webkitRelativePath;const o=$.findRuntime(r);if(!o)throw new Error("Unknown settings JSON");const n=o.createModelSettings(r);return n._objectURL=URL.createObjectURL(i),n}))}static readText(t){return n(this,null,(function*(){return new Promise(((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")}))}))}};o(W,"live2dFactory"),o(W,"filesMap",{}),o(W,"factory",((t,e)=>n(W,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 W.createSettings(e);i.validateFiles(e.map((t=>encodeURI(t.webkitRelativePath)))),yield W.upload(e,i),i.resolveURL=function(t){return W.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),W.filesMap[t])for(const e of Object.values(W.filesMap[t]))URL.revokeObjectURL(e);delete W.filesMap[t]}))}))}return e()}))));let Y=W;const q=class t{static registerRuntime(e){t.runtimes.push(e),t.runtimes.sort(((t,e)=>e.version-t.version))}static findRuntime(e){for(const i of t.runtimes)if(i.test(e))return i}static setupLive2DModel(e,i,s){return n(this,null,(function*(){const r=new Promise((t=>e.once("textureLoaded",t))),o=new Promise((t=>e.once("modelLoaded",t))),n=Promise.all([r,o]).then((()=>e.emit("ready")));yield R(t.live2DModelMiddlewares,{live2dModel:e,source:i,options:s||{}}),yield n,e.emit("load")}))}static loadMotion(e,i,s){var r;const o=t=>e.emit("motionLoadError",i,s,t);try{const n=null==(r=e.definitions[i])?void 0:r[s];if(!n)return Promise.resolve(void 0);e.listeners("destroy").includes(t.releaseTasks)||e.once("destroy",t.releaseTasks);let a=t.motionTasksMap.get(e);a||(a={},t.motionTasksMap.set(e,a));let l=a[i];l||(l=[],a[i]=l);const h=e.getMotionFile(n);return null!=l[s]||(l[s]=B.load({url:h,settings:e.settings,type:e.motionDataType,target:e}).then((r=>{var o;const a=null==(o=t.motionTasksMap.get(e))?void 0:o[i];a&&delete a[s];const l=e.createMotion(r,i,n);return e.emit("motionLoaded",i,s,l),l})).catch((t=>{u.warn(e.tag,`Failed to load motion: ${h}\n`,t),o(t)}))),l[s]}catch(n){u.warn(e.tag,`Failed to load motion at "${i}"[${s}]\n`,n),o(n)}return Promise.resolve(void 0)}static loadExpression(e,i){const s=t=>e.emit("expressionLoadError",i,t);try{const r=e.definitions[i];if(!r)return Promise.resolve(void 0);e.listeners("destroy").includes(t.releaseTasks)||e.once("destroy",t.releaseTasks);let o=t.expressionTasksMap.get(e);o||(o=[],t.expressionTasksMap.set(e,o));const n=e.getExpressionFile(r);return null!=o[i]||(o[i]=B.load({url:n,settings:e.settings,type:"json",target:e}).then((s=>{const o=t.expressionTasksMap.get(e);o&&delete o[i];const n=e.createExpression(s,r);return e.emit("expressionLoaded",i,n),n})).catch((t=>{u.warn(e.tag,`Failed to load expression: ${n}\n`,t),s(t)}))),o[i]}catch(r){u.warn(e.tag,`Failed to load expression at [${i}]\n`,r),s(r)}return Promise.resolve(void 0)}static releaseTasks(){this instanceof T?t.motionTasksMap.delete(this):t.expressionTasksMap.delete(this)}};o(q,"runtimes",[]),o(q,"urlToJSON",U),o(q,"jsonToSettings",V),o(q,"waitUntilReady",N),o(q,"setupOptionals",G),o(q,"setupEssentials",X),o(q,"createInternalModel",j),o(q,"live2DModelMiddlewares",[H.factory,Y.factory,U,V,N,G,X,j]),o(q,"motionTasksMap",new WeakMap),o(q,"expressionTasksMap",new WeakMap);let $=q;T.prototype._loadMotion=function(t,e){return $.loadMotion(this,t,e)},x.prototype._loadExpression=function(t){return $.loadExpression(this,t)},Y.live2dFactory=$,H.live2dFactory=$;const Z=class t{constructor(e,{autoUpdate:i=!0,autoHitTest:s=!0,autoFocus:r=!0,autoInteract:n,ticker:a}={}){o(this,"model"),o(this,"destroyed",!1),o(this,"_ticker"),o(this,"_autoUpdate",!1),o(this,"_autoHitTest",!1),o(this,"_autoFocus",!1),a||(t.defaultTicker?a=t.defaultTicker:"undefined"!=typeof PIXI&&(a=PIXI.Ticker.shared)),void 0!==n&&(s=n,r=n,u.warn(e.tag,"options.autoInteract is deprecated since v0.5.0, use autoHitTest and autoFocus instead.")),this.model=e,this.ticker=a,this.autoUpdate=i,this.autoHitTest=s,this.autoFocus=r,(s||r)&&(this.model.eventMode="static")}get ticker(){return this._ticker}set ticker(t){var e;this._ticker&&this._ticker.remove(Q,this),this._ticker=t,this._autoUpdate&&(null==(e=this._ticker)||e.add(Q,this))}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){var e;this.destroyed||(t?this._ticker?(this._ticker.add(Q,this),this._autoUpdate=!0):u.warn(this.model.tag,"No Ticker to be used for automatic updates. Either set option.ticker when creating Live2DModel, or expose PIXI to global scope (window.PIXI = PIXI)."):(null==(e=this._ticker)||e.remove(Q,this),this._autoUpdate=!1))}get autoHitTest(){return this._autoHitTest}set autoHitTest(t){t!==this.autoHitTest&&(t?this.model.on("pointertap",K,this):this.model.off("pointertap",K,this),this._autoHitTest=t)}get autoFocus(){return this._autoFocus}set autoFocus(t){t!==this.autoFocus&&(t?this.model.on("globalpointermove",tt,this):this.model.off("globalpointermove",tt,this),this._autoFocus=t)}get autoInteract(){return this._autoHitTest&&this._autoFocus}set autoInteract(t){this.autoHitTest=t,this.autoFocus=t}onTickerUpdate(){const t=this.ticker.deltaMS;this.model.update(t)}onTap(t){this.model.tap(t.global.x,t.global.y)}onPointerMove(t){this.model.focus(t.global.x,t.global.y)}destroy(){this.autoFocus=!1,this.autoHitTest=!1,this.autoUpdate=!1,this.ticker=void 0,this.destroyed=!0}};o(Z,"defaultTicker");let J=Z;function Q(){this.onTickerUpdate()}function K(t){this.onTap(t)}function tt(t){this.onPointerMove(t)}class et extends e.Transform{}const it=new e.Point,st=new e.Matrix;class rt extends i.Container{constructor(t){super(),o(this,"tag","Live2DModel(uninitialized)"),o(this,"internalModel"),o(this,"textures",[]),o(this,"transform",new et),o(this,"anchor",new e.ObservablePoint(this.onAnchorChange,this,0,0)),o(this,"glContextID",-1),o(this,"elapsedTime",0),o(this,"deltaTime",0),o(this,"automator"),this.automator=new J(this,t),this.once("modelLoaded",(()=>this.init(t)))}static from(t,e){const i=new this(e);return $.setupLive2DModel(i,t,e).then((()=>i))}static fromSync(t,e){const i=new this(e);return $.setupLive2DModel(i,t,e).then(null==e?void 0:e.onLoad).catch(null==e?void 0:e.onError),i}static registerTicker(t){J.defaultTicker=t.shared}init(t){this.tag=`Live2DModel(${this.internalModel.settings.name})`}onAnchorChange(){this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(t,e,i,{sound:s,volume:r=.5,expression:o,resetExpression:n=!0,crossOrigin:a,onFinish:l,onError:h}={}){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i,{sound:s,volume:r,expression:o,resetExpression:n,crossOrigin:a,onFinish:l,onError:h}):this.internalModel.motionManager.startMotion(t,e,i,{sound:s,volume:r,expression:o,resetExpression:n,crossOrigin:a,onFinish:l,onError:h})}stopMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(t,{volume:e=.5,expression:i,resetExpression:s=!0,crossOrigin:r,onFinish:o,onError:n}={}){return this.internalModel.motionManager.speak(t,{volume:e,expression:i,resetExpression:s,crossOrigin:r,onFinish:o,onError:n})}stopSpeaking(){return this.internalModel.motionManager.stopSpeaking()}expression(t){return this.internalModel.motionManager.expressionManager?void 0===t?this.internalModel.motionManager.expressionManager.setRandomExpression():this.internalModel.motionManager.expressionManager.setExpression(t):Promise.resolve(!1)}focus(t,e,i=!1){it.x=t,it.y=e,this.toModelPosition(it,it,!0);const s=it.x/this.internalModel.originalWidth*2-1,r=it.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&&(u.log(this.tag,"Hit",i),this.emit("hit",i))}hitTest(t,e){return it.x=t,it.y=e,this.toModelPosition(it,it),this.internalModel.hitTest(it.x,it.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)}update(t){this.deltaTime+=t,this.elapsedTime+=t}_render(t){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.automator.destroy(),this.internalModel.destroy(),super.destroy(t)}}if(!window.Live2D)throw new Error("Could not find Cubism 2 runtime. This plugin requires live2d.min.js to be loaded.");const ot=Live2DMotion.prototype.updateParam;Live2DMotion.prototype.updateParam=function(t,e){ot.call(this,t,e),e.isFinished()&&this.onFinishHandler&&(this.onFinishHandler(this),delete this.onFinishHandler)};class nt extends AMotion{constructor(t){super(),o(this,"params",[]),this.setFadeIn(t.fade_in>0?t.fade_in:h.expressionFadingDuration),this.setFadeOut(t.fade_out>0?t.fade_out:h.expressionFadingDuration),Array.isArray(t.params)&&t.params.forEach((t=>{const e=t.calc||"add";if("add"===e){const e=t.def||0;t.val-=e}else if("mult"===e){const e=t.def||1;t.val/=e}this.params.push({calc:e,val:t.val,id:t.id})}))}updateParamExe(t,e,i,s){this.params.forEach((e=>{t.setParamFloat(e.id,e.val*i)}))}}class at extends x{constructor(t,e){var i;super(t,e),o(this,"queueManager",new MotionQueueManager),o(this,"definitions"),this.definitions=null!=(i=this.settings.expressions)?i:[],this.init()}isFinished(){return this.queueManager.isFinished()}getExpressionIndex(t){return this.definitions.findIndex((e=>e.name===t))}getExpressionFile(t){return t.file}createExpression(t,e){return new nt(t)}_setExpression(t){return this.queueManager.startMotion(t)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}}class lt extends T{constructor(t,e){super(t,e),o(this,"definitions"),o(this,"groups",{idle:"idle"}),o(this,"motionDataType","arraybuffer"),o(this,"queueManager",new MotionQueueManager),o(this,"lipSyncIds"),o(this,"expressionManager"),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 at(this.settings,t))}isFinished(){return this.queueManager.isFinished()}createMotion(t,e,i){const s=Live2DMotion.loadMotion(t),r=e===this.groups.idle?h.idleMotionFadingDuration:h.motionFadingDuration;return s.setFadeIn(i.fade_in>0?i.fade_in:r),s.setFadeOut(i.fade_out>0?i.fade_out:r),s}getMotionFile(t){return t.file}getMotionName(t){return t.file}getSoundFile(t){return t.sound}_startMotion(t,e){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 ht{constructor(t){o(this,"leftParam"),o(this,"rightParam"),o(this,"blinkInterval",4e3),o(this,"closingDuration",100),o(this,"closedDuration",50),o(this,"openingDuration",150),o(this,"eyeState",0),o(this,"eyeParamValue",1),o(this,"closedTimer",0),o(this,"nextBlinkTimeLeft",this.blinkInterval),this.coreModel=t,this.leftParam=t.getParamIndex("PARAM_EYE_L_OPEN"),this.rightParam=t.getParamIndex("PARAM_EYE_R_OPEN")}setEyeParams(t){this.eyeParamValue=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+c(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 ut=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class dt extends L{constructor(t,e,i){super(),o(this,"settings"),o(this,"coreModel"),o(this,"motionManager"),o(this,"eyeBlink"),o(this,"eyeballXParamIndex"),o(this,"eyeballYParamIndex"),o(this,"angleXParamIndex"),o(this,"angleYParamIndex"),o(this,"angleZParamIndex"),o(this,"bodyAngleXParamIndex"),o(this,"breathParamIndex"),o(this,"textureFlipY",!0),o(this,"lipSync",!0),o(this,"drawDataCount",0),o(this,"disableCulling",!1),o(this,"hasDrawn",!1),this.coreModel=t,this.settings=e,this.motionManager=new lt(e,i),this.eyeBlink=new ht(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,i]of Object.entries(this.settings.layout)){let s=e;"center_x"===e?s="centerX":"center_y"===e&&(s="centerY"),t[s]=i}return t}updateWebGLContext(t,e){const i=this.coreModel.drawParamWebGL;i.firstDraw=!0,i.setGL(t),i.glno=e;for(const[o,n]of Object.entries(i))n 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=Math.pow(t,r),t=d(t*s,e,i);for(let o=0;o0&&t.textures.every((t=>"string"==typeof t))}copy(t){g("string",t,this,"name","name"),g("string",t,this,"pose","pose"),g("string",t,this,"physics","physics"),g("object",t,this,"layout","layout"),g("object",t,this,"motions","motions"),m("object",t,this,"hit_areas","hitAreas"),m("object",t,this,"expressions","expressions"),m("object",t,this,"init_params","initParams"),m("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=gt[i];o&&e.addSrcParam(o,t,s,r)})),t.targets.forEach((({id:t,ptype:i,scale:s,weight:r})=>{const o=mt[i];o&&e.addTargetParam(o,t,s,r)})),e})))}update(t){this.physicsHairs.forEach((e=>e.update(this.coreModel,t)))}}class _t{constructor(t){o(this,"paramIndex",-1),o(this,"partsIndex",-1),o(this,"link",[]),this.id=t}initIndex(t){this.paramIndex=t.getParamIndex("VISIBLE:"+this.id),this.partsIndex=t.getPartsDataIndex(PartsDataID.getID(this.id)),t.setParamFloat(this.paramIndex,1)}}class ft{constructor(t,e){o(this,"opacityAnimDuration",500),o(this,"partsGroups",[]),this.coreModel=t,e.parts_visible&&(this.partsGroups=e.parts_visible.map((({group:t})=>t.map((({id:t,link:e})=>{const i=new _t(t);return e&&(i.link=e.map((t=>new _t(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=d(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($.registerRuntime({version:2,test:t=>t instanceof ct||ct.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 ct(t),createCoreModel(t){const e=Live2DModelWebGL.loadModel(t),i=Live2D.getError();if(i)throw i;return e},createInternalModel:(t,e,i)=>new dt(t,e,i),createPose:(t,e)=>new ft(t,e),createPhysics:(t,e)=>new pt(t,e)}),!window.Live2DCubismCore)throw new Error("Could not find Cubism 4 runtime. This plugin requires live2dcubismcore.js to be loaded.");class xt{constructor(t,e){this.x=t||0,this.y=e||0}add(t){const e=new xt(0,0);return e.x=this.x+t.x,e.y=this.y+t.y,e}substract(t){const e=new xt(0,0);return e.x=this.x-t.x,e.y=this.y-t.y,e}multiply(t){const e=new xt(0,0);return e.x=this.x*t.x,e.y=this.y*t.y,e}multiplyByScaler(t){return this.multiply(new xt(t,t))}division(t){const e=new xt(0,0);return e.x=this.x/t.x,e.y=this.y/t.y,e}divisionByScalar(t){return this.division(new xt(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 yt=class t{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 xt;return e.x=this.sin(t),e.y=this.cos(t),e}static quadraticEquation(e,i,s){return this.abs(e)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 bt,this._useHighPrecisionMask=!1,this._mvpMatrix4x4=new Ct,this._mvpMatrix4x4.loadIdentity()}}var Pt=(t=>(t[t.CubismBlendMode_Normal=0]="CubismBlendMode_Normal",t[t.CubismBlendMode_Additive=1]="CubismBlendMode_Additive",t[t.CubismBlendMode_Multiplicative=2]="CubismBlendMode_Multiplicative",t))(Pt||{});class bt{constructor(t=1,e=1,i=1,s=1){this.R=t,this.G=e,this.B=i,this.A=s}}let St,wt=!1,It=!1;const Tt=0,Et=2;class Lt{static startUp(t){if(wt)return Rt("CubismFramework.startUp() is already done."),wt;if(Live2DCubismCore._isStarted)return wt=!0,!0;if(Live2DCubismCore._isStarted=!0,St=t,St&&Live2DCubismCore.Logging.csmSetLogFunction(St.logFunction),wt=!0,wt){const t=Live2DCubismCore.Version.csmGetVersion(),e=(16711680&t)>>16,i=65535&t,s=t;Rt("Live2D Cubism Core version: {0}.{1}.{2} ({3})",("00"+((4278190080&t)>>24)).slice(-2),("00"+e).slice(-2),("0000"+i).slice(-4),s)}return Rt("CubismFramework.startUp() is complete."),wt}static cleanUp(){wt=!1,It=!1,St=void 0}static initialize(t=0){wt?It?Bt("CubismFramework.initialize() skipped, already initialized."):(Live2DCubismCore.Memory.initializeAmountOfMemory(t),It=!0,Rt("CubismFramework.initialize() is complete.")):Bt("CubismFramework is not started.")}static dispose(){wt?It?(vt.staticRelease(),It=!1,Rt("CubismFramework.dispose() is complete.")):Bt("CubismFramework.dispose() skipped, not initialized."):Bt("CubismFramework is not started.")}static isStarted(){return wt}static isInitialized(){return It}static coreLogFunction(t){Live2DCubismCore.Logging.csmGetLogFunction()&&Live2DCubismCore.Logging.csmGetLogFunction()(t)}static getLoggingLevel(){return null!=St?St.loggingLevel:5}constructor(){}}var Ft=(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))(Ft||{});const Dt="undefined"!=typeof process&&"production"===process.env.NODE_ENV?()=>{}:t=>console.assert(t);function At(t,...e){kt.print(Ft.LogLevel_Debug,"[CSM][D]"+t+"\n",e)}function Rt(t,...e){kt.print(Ft.LogLevel_Info,"[CSM][I]"+t+"\n",e)}function Bt(t,...e){kt.print(Ft.LogLevel_Warning,"[CSM][W]"+t+"\n",e)}function Ot(t,...e){kt.print(Ft.LogLevel_Error,"[CSM][E]"+t+"\n",e)}class kt{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 Ut{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:Mt.getEasingSine((i-e.getFadeInStartTime())/this._fadeInSeconds))*(0==this._fadeOutSeconds||e.getEndTime()<0?1:Mt.getEasingSine((e.getEndTime()-i)/this._fadeOutSeconds)),e.setState(i,s),Dt(0<=s&&s<=1),this.doUpdateParameters(t,i,s,e),e.getEndTime()>0&&e.getEndTime()null!=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 Vt.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)}}var zt=(t=>(t[t.CubismMotionCurveTarget_Model=0]="CubismMotionCurveTarget_Model",t[t.CubismMotionCurveTarget_Parameter=1]="CubismMotionCurveTarget_Parameter",t[t.CubismMotionCurveTarget_PartOpacity=2]="CubismMotionCurveTarget_PartOpacity",t))(zt||{}),Ht=(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))(Ht||{});class Wt{constructor(t=0,e=0){this.time=t,this.value=e}}class Yt{constructor(){this.basePointIndex=0,this.segmentType=0}}class qt{constructor(){this.id="",this.type=0,this.segmentCount=0,this.baseSegmentIndex=0,this.fadeInTime=0,this.fadeOutTime=0}}class $t{constructor(){this.fireTime=0,this.value=""}}class Zt{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 Jt{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 0==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 Qt=(t=>(t[t.EvaluationOptionFlag_AreBeziersRistricted=0]="EvaluationOptionFlag_AreBeziersRistricted",t))(Qt||{});const Kt="Opacity";function te(t,e,i){const s=new Wt;return s.time=t.time+(e.time-t.time)*i,s.value=t.value+(e.value-t.value)*i,s}function ee(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 ie(t,e){let i=(e-t[0].time)/(t[3].time-t[0].time);i<0&&(i=0);const s=te(t[0],t[1],i),r=te(t[1],t[2],i),o=te(t[2],t[3],i),n=te(s,r,i),a=te(r,o,i);return te(n,a,i).value}function se(t,e){const i=e,s=t[0].time,r=t[3].time,o=t[1].time,n=t[2].time,a=r-3*n+3*o-s,l=3*n-6*o+3*s,h=3*o-3*s,u=s-i,d=Mt.cardanoAlgorithmForBezier(a,l,h,u),c=te(t[0],t[1],d),g=te(t[1],t[2],d),m=te(t[2],t[3],d),p=te(c,g,d),_=te(g,m,d);return te(p,_,d).value}function re(t,e){return t[0].value}function oe(t,e){return t[1].value}function ne(t,e,i){const s=t.curves[e];let r=-1;const o=s.baseSegmentIndex+s.segmentCount;let n=0;for(let l=s.baseSegmentIndex;li){r=l;break}if(-1==r)return t.points[n].value;const a=t.segments[r];return a.evaluate(t.points.slice(a.basePointIndex),i)}class ae extends Ut{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 ae;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=Kt);let r=e-s.getStartTime();r<0&&(r=0);let o=Number.MAX_VALUE,n=Number.MAX_VALUE;const l=64;let h=0,u=0;this._eyeBlinkParameterIds.length>l&&At("too many eye blink targets : {0}",this._eyeBlinkParameterIds.length),this._lipSyncParameterIds.length>l&&At("too many lip sync targets : {0}",this._lipSyncParameterIds.length);const d=this._fadeInSeconds<=0?1:Mt.getEasingSine((e-s.getFadeInStartTime())/this._fadeInSeconds),c=this._fadeOutSeconds<=0||s.getEndTime()<0?1:Mt.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>a&1)continue;const s=e+(n-e)*i;t.setParameterValueById(this._eyeBlinkParameterIds[a],s)}if(o!=Number.MAX_VALUE)for(let a=0;a>a&1)continue;const s=e+(o-e)*i;t.setParameterValueById(this._lipSyncParameterIds[a],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 qt)),this._motionData.segments=Array.from({length:e.getMotionTotalSegmentCount()}).map((()=>new Yt)),this._motionData.events=Array.from({length:this._motionData.eventCount}).map((()=>new $t)),this._motionData.points=[];let o=0,n=0;for(let a=0;at&&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(t,e,i){const s=ae.create(t),r=new Jt(t),o=(e===this.groups.idle?h.idleMotionFadingDuration:h.motionFadingDuration)/1e3;return void 0===r.getMotionFadeInTime()&&s.setFadeInTime(i.FadeInTime>0?i.FadeInTime:o),void 0===r.getMotionFadeOutTime()&&s.setFadeOutTime(i.FadeOutTime>0?i.FadeOutTime:o),s.setEffectIds(this.eyeBlinkIds,this.lipSyncIds),s}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 he{constructor(){this._breathParameters=[],this._currentTime=0}static create(){return new he}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&&(r=1,this._blinkingState=3,this._stateStartTimeSeconds=this._userTimeSeconds),s=1-r;break;case 3:r=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._closedSeconds,r>=1&&(this._blinkingState=4,this._stateStartTimeSeconds=this._userTimeSeconds),s=0;break;case 4:r=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._openingSeconds,r>=1&&(r=1,this._blinkingState=1,this._nextBlinkingTime=this.determinNextBlinkingTiming()),s=r;break;case 1:this._nextBlinkingTimec&&(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,n=o-s;e._allClippedDrawRect.x=i,e._allClippedDrawRect.y=s,e._allClippedDrawRect.width=t,e._allClippedDrawRect.height=n}}}constructor(){this._currentMaskRenderTexture=null,this._currentFrameNo=0,this._renderTextureCount=0,this._clippingMaskBufferSize=256,this._clippingContextListForMask=[],this._clippingContextListForDraw=[],this._channelColors=[],this._tmpBoundsOnModel=new ge,this._tmpMatrix=new Ct,this._tmpMatrixForMask=new Ct,this._tmpMatrixForDraw=new Ct;let t=new bt;t.R=1,t.G=0,t.B=0,t.A=0,this._channelColors.push(t),t=new bt,t.R=0,t.G=1,t.B=0,t.A=0,this._channelColors.push(t),t=new bt,t.R=0,t.G=0,t.B=1,t.A=0,this._channelColors.push(t),t=new bt,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*n,0),a=o.width/this._tmpBoundsOnModel.width):a=e/h,this._tmpBoundsOnModel.height*e>u?(this._tmpBoundsOnModel.expand(0,r.height*n),l=o.height/this._tmpBoundsOnModel.height):l=e/u}else this._tmpBoundsOnModel.setRect(r),this._tmpBoundsOnModel.expand(r.width*n,r.height*n),a=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(a,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(a,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&&Ot("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)&&(u+=h=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 fe,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}constructor(){super(),this._clippingContextBufferForMask=null,this._clippingContextBufferForDraw=null,this._rendererProfile=new Me,this.firstDraw=!0,this._textures={},this._sortedDrawableIndexList=[],this._bufferData={vertex:null,uv:null,index:null}}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 Ot("'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),Ce.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")}}vt.staticRelease=()=>{Ee.doStaticRelease()};const Le=new Ct;class Fe extends L{constructor(t,i,s){super(),o(this,"settings"),o(this,"coreModel"),o(this,"motionManager"),o(this,"lipSync",!0),o(this,"breath",he.create()),o(this,"eyeBlink"),o(this,"userData"),o(this,"renderer",new Ee),o(this,"idParamAngleX","ParamAngleX"),o(this,"idParamAngleY","ParamAngleY"),o(this,"idParamAngleZ","ParamAngleZ"),o(this,"idParamEyeBallX","ParamEyeBallX"),o(this,"idParamEyeBallY","ParamEyeBallY"),o(this,"idParamBodyAngleX","ParamBodyAngleX"),o(this,"idParamBreath","ParamBreath"),o(this,"idParamMouthForm","ParamMouthForm"),o(this,"pixelsPerUnit",1),o(this,"centeringTransform",new e.Matrix),this.coreModel=t,this.settings=i,this.motionManager=new le(i,s),this.init()}init(){var t;super.init(),(null==(t=this.settings.getEyeBlinkParameters())?void 0:t.length)&&(this.eyeBlink=ce.create(this.settings)),this.breath.setParameters([new ue(this.idParamAngleX,0,15,6.5345,.5),new ue(this.idParamAngleY,0,8,3.5345,.5),new ue(this.idParamAngleZ,0,10,5.5345,.5),new ue(this.idParamBodyAngleX,0,4,15.5345,.5),new ue(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,i]of Object.entries(this.settings.layout)){t[e.charAt(0).toLowerCase()+e.slice(1)]=i}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,Ce.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=d(t*1.2,e,1);for(let i=0;i"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 Ae extends v{constructor(t){if(super(t),o(this,"moc"),o(this,"textures"),!Ae.isValidJSON(t))throw new TypeError("Invalid JSON.");Object.assign(this,new De(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{!function i(){try{ke(),t()}catch(s){if(Be--,Be<0){const t=new Error("Failed to start up Cubism 4 framework.");return t.cause=s,void e(t)}u.log("Cubism4","Startup failed, retrying 10ms later..."),setTimeout(i,10)}}()}))),Re)}function ke(t){t=Object.assign({logFunction:console.log,loggingLevel:Ft.LogLevel_Verbose},t),Lt.startUp(t),Lt.initialize()}class Ue{static create(t){const e=new Ue;"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=a,o=t.getPartOpacityByIndex(i),o+=e/this._fadeTimeSeconds,o>1&&(o=1)}}r<0&&(r=0,o=1);for(let a=i;a.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 Ve{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 Ve;return t.partId=this.partId,t.parameterIndex=this.parameterIndex,t.partIndex=this.partIndex,t.link=this.link.map((t=>t.clone())),t}}class Ne{constructor(t=!1,e=new bt){this.isOverwritten=t,this.Color=e}}class Ge{constructor(t=!1,e=new bt){this.isOverwritten=t,this.Color=e}}class Xe{constructor(t=!1,e=!1){this.isOverwritten=t,this.isCulling=e}}class je{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[a].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 ze{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 ze(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 je(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 He=(t=>(t[t.CubismPhysicsTargetType_Parameter=0]="CubismPhysicsTargetType_Parameter",t))(He||{}),We=(t=>(t[t.CubismPhysicsSource_X=0]="CubismPhysicsSource_X",t[t.CubismPhysicsSource_Y=1]="CubismPhysicsSource_Y",t[t.CubismPhysicsSource_Angle=2]="CubismPhysicsSource_Angle",t))(We||{});class Ye{constructor(){this.initialPosition=new xt(0,0),this.position=new xt(0,0),this.lastPosition=new xt(0,0),this.lastGravity=new xt(0,0),this.force=new xt(0,0),this.velocity=new xt(0,0)}}class qe{constructor(){this.normalizationPosition={},this.normalizationAngle={}}}class $e{constructor(){this.source={}}}class Ze{constructor(){this.destination={},this.translationScale=new xt(0,0)}}class Je{constructor(){this.settings=[],this.inputs=[],this.outputs=[],this.particles=[],this.gravity=new xt(0,0),this.wind=new xt(0,0),this.fps=0}}class Qe{constructor(t){this._json=t}release(){this._json=void 0}getGravity(){const t=new xt(0,0);return t.x=this._json.Meta.EffectiveForces.Gravity.X,t.y=this._json.Meta.EffectiveForces.Gravity.Y,t}getWind(){const t=new xt(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 xt(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 Ke="Angle";class ti{static create(t){const e=new ti;return e.parse(t),e._physicsRig.gravity.y=0,e}static delete(t){null!=t&&t.release()}parse(t){this._physicsRig=new Je;const e=new Qe(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 xt;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);pi(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 xt;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,n=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(this._parameterCaches.subarray(o))):this._parameterCaches.slice(o);pi(n,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=Mt.directionToRadian(r,t),s&&(o*=-1),o}function hi(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 ui(t,e){return t.x}function di(t,e){return t.y}function ci(t,e){return e}function gi(t,e,i,s,r,o,n,a){let l,h,u,d,c=new xt(0,0),g=new xt(0,0),m=new xt(0,0),p=new xt(0,0);t[0].position=new xt(i.x,i.y),l=Mt.degreesToRadian(s),d=Mt.radianToDirection(l),d.normalize();for(let _=1;_i&&(n>r.valueExceededMaximum&&(r.valueExceededMaximum=n),n=i),a=r.weight/100,a>=1||(n=t[0]*(1-a)+n*a),t[0]=n}function _i(t,e,i,s,r,o,n,a){let l=0;const h=Mt.max(i,e);ht&&(t=u);const d=Mt.min(r,o),c=Mt.max(r,o),g=n,m=hi(u,h),p=t-m;switch(Math.sign(p)){case 1:{const t=h-m;0!=t&&(l=p*((c-g)/t),l+=g);break}case-1:{const t=u-m;0!=t&&(l=p*((d-g)/t),l+=g);break}case 0:l=g}return a?l:-1*l}function fi(){var t;null==(t=this.__moc)||t.release()}$.registerRuntime({version:4,ready:Oe,test:t=>t instanceof Ae||Ae.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 Ae(t),createCoreModel(t,e){const i=ze.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 Fe(t,e,i),r=t;return r.__moc&&(s.__moc=r.__moc,delete r.__moc,s.once("destroy",fi)),s},createPhysics:(t,e)=>ti.create(e),createPose:(t,e)=>Ue.create(e)}),t.Cubism2ExpressionManager=at,t.Cubism2InternalModel=dt,t.Cubism2ModelSettings=ct,t.Cubism2MotionManager=lt,t.Cubism4ExpressionManager=jt,t.Cubism4InternalModel=Fe,t.Cubism4ModelSettings=Ae,t.Cubism4MotionManager=le,t.ExpressionManager=x,t.FileLoader=Y,t.FocusController=C,t.InternalModel=L,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DExpression=nt,t.Live2DEyeBlink=ht,t.Live2DFactory=$,t.Live2DLoader=B,t.Live2DModel=rt,t.Live2DPhysics=pt,t.Live2DPose=ft,t.Live2DTransform=et,t.ModelSettings=v,t.MotionManager=T,t.MotionPreloadStrategy=I,t.MotionPriority=P,t.MotionState=b,t.SoundManager=w,t.VERSION="v0.5.0-beta",t.VOLUME=S,t.XHRLoader=A,t.ZipLoader=H,t.applyMixins=p,t.clamp=d,t.config=h,t.copyArray=m,t.copyProperty=g,t.cubism4Ready=Oe,t.folderName=_,t.logger=u,t.rand=c,t.remove=f,t.startUpCubism4=ke,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})}));