@pixiv/three-vrm
Version:
VRM file loader for three.js.
2 lines • 152 kB
JavaScript
/*! (c) 2019-2025 pixiv Inc. - https://github.com/pixiv/three-vrm/blob/release/LICENSE */
"use strict";var yr=Object.create;var Fe=Object.defineProperty;var wr=Object.getOwnPropertyDescriptor;var Sr=Object.getOwnPropertyNames;var Pr=Object.getPrototypeOf,Ar=Object.prototype.hasOwnProperty;var Lr=(t,e)=>{for(var n in e)Fe(t,n,{get:e[n],enumerable:!0})},Sn=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Sr(e))!Ar.call(t,r)&&r!==n&&Fe(t,r,{get:()=>e[r],enumerable:!(i=wr(e,r))||i.enumerable});return t};var R=(t,e,n)=>(n=t!=null?yr(Pr(t)):{},Sn(e||!t||!t.__esModule?Fe(n,"default",{value:t,enumerable:!0}):n,t)),br=t=>Sn(Fe({},"__esModule",{value:!0}),t);var Se=(t,e,n)=>new Promise((i,r)=>{var o=s=>{try{l(n.next(s))}catch(u){r(u)}},a=s=>{try{l(n.throw(s))}catch(u){r(u)}},l=s=>s.done?i(s.value):Promise.resolve(s.value).then(o,a);l((n=n.apply(t,e)).next())});var us={};Lr(us,{MToonMaterial:()=>fi,MToonMaterialDebugMode:()=>pi,MToonMaterialLoaderPlugin:()=>Ct,MToonMaterialOutlineWidthMode:()=>Vt,VRM:()=>ve,VRMAimConstraint:()=>Si,VRMCore:()=>Ke,VRMCoreLoaderPlugin:()=>io,VRMExpression:()=>vt,VRMExpressionLoaderPlugin:()=>Qe,VRMExpressionManager:()=>Et,VRMExpressionMaterialColorBind:()=>Mt,VRMExpressionMaterialColorType:()=>fe,VRMExpressionMorphTargetBind:()=>_e,VRMExpressionOverrideType:()=>Cr,VRMExpressionPresetName:()=>je,VRMExpressionTextureTransformBind:()=>Rt,VRMFirstPerson:()=>Tt,VRMFirstPersonLoaderPlugin:()=>Ye,VRMFirstPersonMeshAnnotationType:()=>Or,VRMHumanBoneList:()=>ze,VRMHumanBoneName:()=>Br,VRMHumanBoneParentMap:()=>Jn,VRMHumanoid:()=>wt,VRMHumanoidHelper:()=>xt,VRMHumanoidLoaderPlugin:()=>$e,VRMLoaderPlugin:()=>dt,VRMLookAt:()=>si,VRMLookAtBoneApplier:()=>Ae,VRMLookAtExpressionApplier:()=>Xe,VRMLookAtHelper:()=>ii,VRMLookAtLoaderPlugin:()=>Ze,VRMLookAtRangeMap:()=>At,VRMLookAtTypeName:()=>eo,VRMMetaLoaderPlugin:()=>Je,VRMNodeConstraint:()=>rt,VRMNodeConstraintHelper:()=>nt,VRMNodeConstraintLoaderPlugin:()=>Nt,VRMNodeConstraintManager:()=>Pi,VRMRequiredHumanBoneName:()=>ni,VRMRollConstraint:()=>Li,VRMRotationConstraint:()=>Ai,VRMSpringBoneCollider:()=>at,VRMSpringBoneColliderHelper:()=>st,VRMSpringBoneColliderShape:()=>lt,VRMSpringBoneColliderShapeCapsule:()=>zt,VRMSpringBoneColliderShapePlane:()=>Gt,VRMSpringBoneColliderShapeSphere:()=>Xt,VRMSpringBoneJoint:()=>Oi,VRMSpringBoneJointHelper:()=>Vi,VRMSpringBoneLoaderPlugin:()=>Qt,VRMSpringBoneManager:()=>Wt,VRMUtils:()=>K});module.exports=br(us);var kn=R(require("three"),1),ee=R(require("three"),1),Lt=R(require("three"),1),Qn=R(require("three"),1),F=R(require("three"),1),$=R(require("three"),1),qe=R(require("three"),1),k=R(require("three"),1),I=R(require("three"),1),Le=R(require("three"),1),te=R(require("three"),1),C=R(require("three"),1),Ht=R(require("three"),1),V=R(require("three"),1),Pt=R(require("three"),1),ai=R(require("three"),1);var w=(t,e,n)=>new Promise((i,r)=>{var o=s=>{try{l(n.next(s))}catch(u){r(u)}},a=s=>{try{l(n.throw(s))}catch(u){r(u)}},l=s=>s.done?i(s.value):Promise.resolve(s.value).then(o,a);l((n=n.apply(t,e)).next())}),vt=class extends kn.Object3D{constructor(t){super(),this.weight=0,this.isBinary=!1,this.overrideBlink="none",this.overrideLookAt="none",this.overrideMouth="none",this._binds=[],this.name=`VRMExpression_${t}`,this.expressionName=t,this.type="VRMExpression",this.visible=!1}get binds(){return this._binds}get overrideBlinkAmount(){return this.overrideBlink==="block"?0<this.outputWeight?1:0:this.overrideBlink==="blend"?this.outputWeight:0}get overrideLookAtAmount(){return this.overrideLookAt==="block"?0<this.outputWeight?1:0:this.overrideLookAt==="blend"?this.outputWeight:0}get overrideMouthAmount(){return this.overrideMouth==="block"?0<this.outputWeight?1:0:this.overrideMouth==="blend"?this.outputWeight:0}get outputWeight(){return this.isBinary?this.weight>.5?1:0:this.weight}addBind(t){this._binds.push(t)}deleteBind(t){let e=this._binds.indexOf(t);e>=0&&this._binds.splice(e,1)}applyWeight(t){var e;let n=this.outputWeight;n*=(e=t==null?void 0:t.multiplier)!=null?e:1,this.isBinary&&n<1&&(n=0),this._binds.forEach(i=>i.applyWeight(n))}clearAppliedWeight(){this._binds.forEach(t=>t.clearAppliedWeight())}};function Wn(t,e,n){var i,r;let o=t.parser.json,a=(i=o.nodes)==null?void 0:i[e];if(a==null)return console.warn(`extractPrimitivesInternal: Attempt to use nodes[${e}] of glTF but the node doesn't exist`),null;let l=a.mesh;if(l==null)return null;let s=(r=o.meshes)==null?void 0:r[l];if(s==null)return console.warn(`extractPrimitivesInternal: Attempt to use meshes[${l}] of glTF but the mesh doesn't exist`),null;let u=s.primitives.length,d=[];return n.traverse(h=>{d.length<u&&h.isMesh&&d.push(h)}),d}function Pn(t,e){return w(this,null,function*(){let n=yield t.parser.getDependency("node",e);return Wn(t,e,n)})}function An(t){return w(this,null,function*(){let e=yield t.parser.getDependencies("node"),n=new Map;return e.forEach((i,r)=>{let o=Wn(t,r,i);o!=null&&n.set(r,o)}),n})}var je={Aa:"aa",Ih:"ih",Ou:"ou",Ee:"ee",Oh:"oh",Blink:"blink",Happy:"happy",Angry:"angry",Sad:"sad",Relaxed:"relaxed",LookUp:"lookUp",Surprised:"surprised",LookDown:"lookDown",LookLeft:"lookLeft",LookRight:"lookRight",BlinkLeft:"blinkLeft",BlinkRight:"blinkRight",Neutral:"neutral"};function zn(t){return Math.max(Math.min(t,1),0)}var Et=class Gn{constructor(){this.blinkExpressionNames=["blink","blinkLeft","blinkRight"],this.lookAtExpressionNames=["lookLeft","lookRight","lookUp","lookDown"],this.mouthExpressionNames=["aa","ee","ih","oh","ou"],this._expressions=[],this._expressionMap={}}get expressions(){return this._expressions.concat()}get expressionMap(){return Object.assign({},this._expressionMap)}get presetExpressionMap(){let e={},n=new Set(Object.values(je));return Object.entries(this._expressionMap).forEach(([i,r])=>{n.has(i)&&(e[i]=r)}),e}get customExpressionMap(){let e={},n=new Set(Object.values(je));return Object.entries(this._expressionMap).forEach(([i,r])=>{n.has(i)||(e[i]=r)}),e}copy(e){return this._expressions.concat().forEach(i=>{this.unregisterExpression(i)}),e._expressions.forEach(i=>{this.registerExpression(i)}),this.blinkExpressionNames=e.blinkExpressionNames.concat(),this.lookAtExpressionNames=e.lookAtExpressionNames.concat(),this.mouthExpressionNames=e.mouthExpressionNames.concat(),this}clone(){return new Gn().copy(this)}getExpression(e){var n;return(n=this._expressionMap[e])!=null?n:null}registerExpression(e){this._expressions.push(e),this._expressionMap[e.expressionName]=e}unregisterExpression(e){let n=this._expressions.indexOf(e);n===-1&&console.warn("VRMExpressionManager: The specified expressions is not registered"),this._expressions.splice(n,1),delete this._expressionMap[e.expressionName]}getValue(e){var n;let i=this.getExpression(e);return(n=i==null?void 0:i.weight)!=null?n:null}setValue(e,n){let i=this.getExpression(e);i&&(i.weight=zn(n))}resetValues(){this._expressions.forEach(e=>{e.weight=0})}getExpressionTrackName(e){let n=this.getExpression(e);return n?`${n.name}.weight`:null}update(){let e=this._calculateWeightMultipliers();this._expressions.forEach(n=>{n.clearAppliedWeight()}),this._expressions.forEach(n=>{let i=1,r=n.expressionName;this.blinkExpressionNames.indexOf(r)!==-1&&(i*=e.blink),this.lookAtExpressionNames.indexOf(r)!==-1&&(i*=e.lookAt),this.mouthExpressionNames.indexOf(r)!==-1&&(i*=e.mouth),n.applyWeight({multiplier:i})})}_calculateWeightMultipliers(){let e=1,n=1,i=1;return this._expressions.forEach(r=>{e-=r.overrideBlinkAmount,n-=r.overrideLookAtAmount,i-=r.overrideMouthAmount}),e=Math.max(0,e),n=Math.max(0,n),i=Math.max(0,i),{blink:e,lookAt:n,mouth:i}}},fe={Color:"color",EmissionColor:"emissionColor",ShadeColor:"shadeColor",MatcapColor:"matcapColor",RimColor:"rimColor",OutlineColor:"outlineColor"},Hr={_Color:fe.Color,_EmissionColor:fe.EmissionColor,_ShadeColor:fe.ShadeColor,_RimColor:fe.RimColor,_OutlineColor:fe.OutlineColor},Ir=new Lt.Color,jn=class Xn{constructor({material:e,type:n,targetValue:i,targetAlpha:r}){this.material=e,this.type=n,this.targetValue=i,this.targetAlpha=r!=null?r:1;let o=this._initColorBindState(),a=this._initAlphaBindState();this._state={color:o,alpha:a}}applyWeight(e){let{color:n,alpha:i}=this._state;if(n!=null){let{propertyName:r,deltaValue:o}=n,a=this.material[r];a!=null&&a.add(Ir.copy(o).multiplyScalar(e))}if(i!=null){let{propertyName:r,deltaValue:o}=i;this.material[r]!=null&&(this.material[r]+=o*e)}}clearAppliedWeight(){let{color:e,alpha:n}=this._state;if(e!=null){let{propertyName:i,initialValue:r}=e,o=this.material[i];o!=null&&o.copy(r)}if(n!=null){let{propertyName:i,initialValue:r}=n;this.material[i]!=null&&(this.material[i]=r)}}_initColorBindState(){var e,n,i;let{material:r,type:o,targetValue:a}=this,l=this._getPropertyNameMap(),s=(n=(e=l==null?void 0:l[o])==null?void 0:e[0])!=null?n:null;if(s==null)return console.warn(`Tried to add a material color bind to the material ${(i=r.name)!=null?i:"(no name)"}, the type ${o} but the material or the type is not supported.`),null;let d=r[s].clone(),h=new Lt.Color(a.r-d.r,a.g-d.g,a.b-d.b);return{propertyName:s,initialValue:d,deltaValue:h}}_initAlphaBindState(){var e,n,i;let{material:r,type:o,targetAlpha:a}=this,l=this._getPropertyNameMap(),s=(n=(e=l==null?void 0:l[o])==null?void 0:e[1])!=null?n:null;if(s==null&&a!==1)return console.warn(`Tried to add a material alpha bind to the material ${(i=r.name)!=null?i:"(no name)"}, the type ${o} but the material or the type does not support alpha.`),null;if(s==null)return null;let u=r[s],d=a-u;return{propertyName:s,initialValue:u,deltaValue:d}}_getPropertyNameMap(){var e,n;return(n=(e=Object.entries(Xn._propertyNameMapMap).find(([i])=>this.material[i]===!0))==null?void 0:e[1])!=null?n:null}};jn._propertyNameMapMap={isMeshStandardMaterial:{color:["color","opacity"],emissionColor:["emissive",null]},isMeshBasicMaterial:{color:["color","opacity"]},isMToonMaterial:{color:["color","opacity"],emissionColor:["emissive",null],outlineColor:["outlineColorFactor",null],matcapColor:["matcapFactor",null],rimColor:["parametricRimColorFactor",null],shadeColor:["shadeColorFactor",null]}};var Mt=jn,_e=class{constructor({primitives:t,index:e,weight:n}){this.primitives=t,this.index=e,this.weight=n}applyWeight(t){this.primitives.forEach(e=>{var n;((n=e.morphTargetInfluences)==null?void 0:n[this.index])!=null&&(e.morphTargetInfluences[this.index]+=this.weight*t)})}clearAppliedWeight(){this.primitives.forEach(t=>{var e;((e=t.morphTargetInfluences)==null?void 0:e[this.index])!=null&&(t.morphTargetInfluences[this.index]=0)})}},Ln=new Qn.Vector2,Yn=class qn{constructor({material:e,scale:n,offset:i}){var r,o;this.material=e,this.scale=n,this.offset=i;let a=(r=Object.entries(qn._propertyNamesMap).find(([l])=>e[l]===!0))==null?void 0:r[1];a==null?(console.warn(`Tried to add a texture transform bind to the material ${(o=e.name)!=null?o:"(no name)"} but the material is not supported.`),this._properties=[]):(this._properties=[],a.forEach(l=>{var s;let u=(s=e[l])==null?void 0:s.clone();if(!u)return null;e[l]=u;let d=u.offset.clone(),h=u.repeat.clone(),p=i.clone().sub(d),m=n.clone().sub(h);this._properties.push({name:l,initialOffset:d,deltaOffset:p,initialScale:h,deltaScale:m})}))}applyWeight(e){this._properties.forEach(n=>{let i=this.material[n.name];i!==void 0&&(i.offset.add(Ln.copy(n.deltaOffset).multiplyScalar(e)),i.repeat.add(Ln.copy(n.deltaScale).multiplyScalar(e)))})}clearAppliedWeight(){this._properties.forEach(e=>{let n=this.material[e.name];n!==void 0&&(n.offset.copy(e.initialOffset),n.repeat.copy(e.initialScale))})}};Yn._propertyNamesMap={isMeshStandardMaterial:["map","emissiveMap","bumpMap","normalMap","displacementMap","roughnessMap","metalnessMap","alphaMap"],isMeshBasicMaterial:["map","specularMap","alphaMap"],isMToonMaterial:["map","normalMap","emissiveMap","shadeMultiplyTexture","rimMultiplyTexture","outlineWidthMultiplyTexture","uvAnimationMaskTexture"]};var Rt=Yn,Vr=new Set(["1.0","1.0-beta"]),$n=class Zn{get name(){return"VRMExpressionLoaderPlugin"}constructor(e){this.parser=e}afterRoot(e){return w(this,null,function*(){e.userData.vrmExpressionManager=yield this._import(e)})}_import(e){return w(this,null,function*(){let n=yield this._v1Import(e);if(n)return n;let i=yield this._v0Import(e);return i||null})}_v1Import(e){return w(this,null,function*(){var n,i;let r=this.parser.json;if(!(((n=r.extensionsUsed)==null?void 0:n.indexOf("VRMC_vrm"))!==-1))return null;let a=(i=r.extensions)==null?void 0:i.VRMC_vrm;if(!a)return null;let l=a.specVersion;if(!Vr.has(l))return console.warn(`VRMExpressionLoaderPlugin: Unknown VRMC_vrm specVersion "${l}"`),null;let s=a.expressions;if(!s)return null;let u=new Set(Object.values(je)),d=new Map;s.preset!=null&&Object.entries(s.preset).forEach(([p,m])=>{if(m!=null){if(!u.has(p)){console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${p}" detected. Ignoring the expression`);return}d.set(p,m)}}),s.custom!=null&&Object.entries(s.custom).forEach(([p,m])=>{if(u.has(p)){console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${p}". Ignoring the expression`);return}d.set(p,m)});let h=new Et;return yield Promise.all(Array.from(d.entries()).map(p=>w(this,[p],function*([m,c]){var f,g,v,P,y,_,E;let M=new vt(m);if(e.scene.add(M),M.isBinary=(f=c.isBinary)!=null?f:!1,M.overrideBlink=(g=c.overrideBlink)!=null?g:"none",M.overrideLookAt=(v=c.overrideLookAt)!=null?v:"none",M.overrideMouth=(P=c.overrideMouth)!=null?P:"none",(y=c.morphTargetBinds)==null||y.forEach(T=>w(this,null,function*(){var x;if(T.node===void 0||T.index===void 0)return;let L=yield Pn(e,T.node),b=T.index;if(!L.every(A=>Array.isArray(A.morphTargetInfluences)&&b<A.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${c.name} attempts to index morph #${b} but not found.`);return}M.addBind(new _e({primitives:L,index:b,weight:(x=T.weight)!=null?x:1}))})),c.materialColorBinds||c.textureTransformBinds){let T=[];e.scene.traverse(x=>{let L=x.material;L&&(Array.isArray(L)?T.push(...L):T.push(L))}),(_=c.materialColorBinds)==null||_.forEach(x=>w(this,null,function*(){T.filter(b=>{var A;let H=(A=this.parser.associations.get(b))==null?void 0:A.materials;return x.material===H}).forEach(b=>{M.addBind(new Mt({material:b,type:x.type,targetValue:new ee.Color().fromArray(x.targetValue),targetAlpha:x.targetValue[3]}))})})),(E=c.textureTransformBinds)==null||E.forEach(x=>w(this,null,function*(){T.filter(b=>{var A;let H=(A=this.parser.associations.get(b))==null?void 0:A.materials;return x.material===H}).forEach(b=>{var A,H;M.addBind(new Rt({material:b,offset:new ee.Vector2().fromArray((A=x.offset)!=null?A:[0,0]),scale:new ee.Vector2().fromArray((H=x.scale)!=null?H:[1,1])}))})}))}h.registerExpression(M)}))),h})}_v0Import(e){return w(this,null,function*(){var n;let i=this.parser.json,r=(n=i.extensions)==null?void 0:n.VRM;if(!r)return null;let o=r.blendShapeMaster;if(!o)return null;let a=new Et,l=o.blendShapeGroups;if(!l)return a;let s=new Set;return yield Promise.all(l.map(u=>w(this,null,function*(){var d;let h=u.presetName,p=h!=null&&Zn.v0v1PresetNameMap[h]||null,m=p!=null?p:u.name;if(m==null){console.warn("VRMExpressionLoaderPlugin: One of custom expressions has no name. Ignoring the expression");return}if(s.has(m)){console.warn(`VRMExpressionLoaderPlugin: An expression preset ${h} has duplicated entries. Ignoring the expression`);return}s.add(m);let c=new vt(m);e.scene.add(c),c.isBinary=(d=u.isBinary)!=null?d:!1,u.binds&&u.binds.forEach(g=>w(this,null,function*(){var v;if(g.mesh===void 0||g.index===void 0)return;let P=[];(v=i.nodes)==null||v.forEach((_,E)=>{_.mesh===g.mesh&&P.push(E)});let y=g.index;yield Promise.all(P.map(_=>w(this,null,function*(){var E;let M=yield Pn(e,_);if(!M.every(T=>Array.isArray(T.morphTargetInfluences)&&y<T.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${u.name} attempts to index ${y}th morph but not found.`);return}c.addBind(new _e({primitives:M,index:y,weight:.01*((E=g.weight)!=null?E:100)}))})))}));let f=u.materialValues;f&&f.length!==0&&f.forEach(g=>{if(g.materialName===void 0||g.propertyName===void 0||g.targetValue===void 0)return;let v=[];e.scene.traverse(y=>{if(y.material){let _=y.material;Array.isArray(_)?v.push(..._.filter(E=>(E.name===g.materialName||E.name===g.materialName+" (Outline)")&&v.indexOf(E)===-1)):_.name===g.materialName&&v.indexOf(_)===-1&&v.push(_)}});let P=g.propertyName;v.forEach(y=>{if(P==="_MainTex_ST"){let E=new ee.Vector2(g.targetValue[0],g.targetValue[1]),M=new ee.Vector2(g.targetValue[2],g.targetValue[3]);M.y=1-M.y-E.y,c.addBind(new Rt({material:y,scale:E,offset:M}));return}let _=Hr[P];if(_){c.addBind(new Mt({material:y,type:_,targetValue:new ee.Color().fromArray(g.targetValue),targetAlpha:g.targetValue[3]}));return}console.warn(P+" is not supported")})}),a.registerExpression(c)}))),a})}};$n.v0v1PresetNameMap={a:"aa",e:"ee",i:"ih",o:"oh",u:"ou",blink:"blink",joy:"happy",angry:"angry",sorrow:"sad",fun:"relaxed",lookup:"lookUp",lookdown:"lookDown",lookleft:"lookLeft",lookright:"lookRight",blink_l:"blinkLeft",blink_r:"blinkRight",neutral:"neutral"};var Qe=$n,Cr={None:"none",Block:"block",Blend:"blend"},bt=class ge{constructor(e,n){this._firstPersonOnlyLayer=ge.DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=ge.DEFAULT_THIRDPERSON_ONLY_LAYER,this._initializedLayers=!1,this.humanoid=e,this.meshAnnotations=n}copy(e){if(this.humanoid!==e.humanoid)throw new Error("VRMFirstPerson: humanoid must be same in order to copy");return this.meshAnnotations=e.meshAnnotations.map(n=>({meshes:n.meshes.concat(),type:n.type})),this}clone(){return new ge(this.humanoid,this.meshAnnotations).copy(this)}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}setup({firstPersonOnlyLayer:e=ge.DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:n=ge.DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initializedLayers||(this._firstPersonOnlyLayer=e,this._thirdPersonOnlyLayer=n,this.meshAnnotations.forEach(i=>{i.meshes.forEach(r=>{i.type==="firstPersonOnly"?(r.layers.set(this._firstPersonOnlyLayer),r.traverse(o=>o.layers.set(this._firstPersonOnlyLayer))):i.type==="thirdPersonOnly"?(r.layers.set(this._thirdPersonOnlyLayer),r.traverse(o=>o.layers.set(this._thirdPersonOnlyLayer))):i.type==="auto"&&this._createHeadlessModel(r)})}),this._initializedLayers=!0)}_excludeTriangles(e,n,i,r){let o=0;if(n!=null&&n.length>0)for(let a=0;a<e.length;a+=3){let l=e[a],s=e[a+1],u=e[a+2],d=n[l],h=i[l];if(d[0]>0&&r.includes(h[0])||d[1]>0&&r.includes(h[1])||d[2]>0&&r.includes(h[2])||d[3]>0&&r.includes(h[3]))continue;let p=n[s],m=i[s];if(p[0]>0&&r.includes(m[0])||p[1]>0&&r.includes(m[1])||p[2]>0&&r.includes(m[2])||p[3]>0&&r.includes(m[3]))continue;let c=n[u],f=i[u];c[0]>0&&r.includes(f[0])||c[1]>0&&r.includes(f[1])||c[2]>0&&r.includes(f[2])||c[3]>0&&r.includes(f[3])||(e[o++]=l,e[o++]=s,e[o++]=u)}return o}_createErasedMesh(e,n){let i=new F.SkinnedMesh(e.geometry.clone(),e.material);i.name=`${e.name}(erase)`,i.frustumCulled=e.frustumCulled,i.layers.set(this._firstPersonOnlyLayer);let r=i.geometry,o=r.getAttribute("skinIndex"),a=o instanceof F.GLBufferAttribute?[]:o.array,l=[];for(let f=0;f<a.length;f+=4)l.push([a[f],a[f+1],a[f+2],a[f+3]]);let s=r.getAttribute("skinWeight"),u=s instanceof F.GLBufferAttribute?[]:s.array,d=[];for(let f=0;f<u.length;f+=4)d.push([u[f],u[f+1],u[f+2],u[f+3]]);let h=r.getIndex();if(!h)throw new Error("The geometry doesn't have an index buffer");let p=Array.from(h.array),m=this._excludeTriangles(p,d,l,n),c=[];for(let f=0;f<m;f++)c[f]=p[f];return r.setIndex(c),e.onBeforeRender&&(i.onBeforeRender=e.onBeforeRender),i.bind(new F.Skeleton(e.skeleton.bones,e.skeleton.boneInverses),new F.Matrix4),i}_createHeadlessModelForSkinnedMesh(e,n){let i=[];if(n.skeleton.bones.forEach((o,a)=>{this._isEraseTarget(o)&&i.push(a)}),!i.length){n.layers.enable(this._thirdPersonOnlyLayer),n.layers.enable(this._firstPersonOnlyLayer);return}n.layers.set(this._thirdPersonOnlyLayer);let r=this._createErasedMesh(n,i);e.add(r)}_createHeadlessModel(e){if(e.type==="Group")if(e.layers.set(this._thirdPersonOnlyLayer),this._isEraseTarget(e))e.traverse(n=>n.layers.set(this._thirdPersonOnlyLayer));else{let n=new F.Group;n.name=`_headless_${e.name}`,n.layers.set(this._firstPersonOnlyLayer),e.parent.add(n),e.children.filter(i=>i.type==="SkinnedMesh").forEach(i=>{let r=i;this._createHeadlessModelForSkinnedMesh(n,r)})}else if(e.type==="SkinnedMesh"){let n=e;this._createHeadlessModelForSkinnedMesh(e.parent,n)}else this._isEraseTarget(e)&&(e.layers.set(this._thirdPersonOnlyLayer),e.traverse(n=>n.layers.set(this._thirdPersonOnlyLayer)))}_isEraseTarget(e){return e===this.humanoid.getRawBoneNode("head")?!0:e.parent?this._isEraseTarget(e.parent):!1}};bt.DEFAULT_FIRSTPERSON_ONLY_LAYER=9;bt.DEFAULT_THIRDPERSON_ONLY_LAYER=10;var Tt=bt,Ur=new Set(["1.0","1.0-beta"]),Ye=class{get name(){return"VRMFirstPersonLoaderPlugin"}constructor(t){this.parser=t}afterRoot(t){return w(this,null,function*(){let e=t.userData.vrmHumanoid;if(e!==null){if(e===void 0)throw new Error("VRMFirstPersonLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first");t.userData.vrmFirstPerson=yield this._import(t,e)}})}_import(t,e){return w(this,null,function*(){if(e==null)return null;let n=yield this._v1Import(t,e);if(n)return n;let i=yield this._v0Import(t,e);return i||null})}_v1Import(t,e){return w(this,null,function*(){var n,i;let r=this.parser.json;if(!(((n=r.extensionsUsed)==null?void 0:n.indexOf("VRMC_vrm"))!==-1))return null;let a=(i=r.extensions)==null?void 0:i.VRMC_vrm;if(!a)return null;let l=a.specVersion;if(!Ur.has(l))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${l}"`),null;let s=a.firstPerson,u=[],d=yield An(t);return Array.from(d.entries()).forEach(([h,p])=>{var m,c;let f=(m=s==null?void 0:s.meshAnnotations)==null?void 0:m.find(g=>g.node===h);u.push({meshes:p,type:(c=f==null?void 0:f.type)!=null?c:"auto"})}),new Tt(e,u)})}_v0Import(t,e){return w(this,null,function*(){var n;let i=this.parser.json,r=(n=i.extensions)==null?void 0:n.VRM;if(!r)return null;let o=r.firstPerson;if(!o)return null;let a=[],l=yield An(t);return Array.from(l.entries()).forEach(([s,u])=>{let d=i.nodes[s],h=o.meshAnnotations?o.meshAnnotations.find(p=>p.mesh===d.mesh):void 0;a.push({meshes:u,type:this._convertV0FlagToV1Type(h==null?void 0:h.firstPersonFlag)})}),new Tt(e,a)})}_convertV0FlagToV1Type(t){return t==="FirstPersonOnly"?"firstPersonOnly":t==="ThirdPersonOnly"?"thirdPersonOnly":t==="Both"?"both":"auto"}},Or={Auto:"auto",Both:"both",ThirdPersonOnly:"thirdPersonOnly",FirstPersonOnly:"firstPersonOnly"},bn=new $.Vector3,Hn=new $.Vector3,Nr=new $.Quaternion,xt=class extends $.Group{constructor(t){super(),this.vrmHumanoid=t,this._boneAxesMap=new Map,Object.values(t.humanBones).forEach(e=>{let n=new $.AxesHelper(1);n.matrixAutoUpdate=!1,n.material.depthTest=!1,n.material.depthWrite=!1,this.add(n),this._boneAxesMap.set(e,n)})}dispose(){Array.from(this._boneAxesMap.values()).forEach(t=>{t.geometry.dispose(),t.material.dispose()})}updateMatrixWorld(t){Array.from(this._boneAxesMap.entries()).forEach(([e,n])=>{e.node.updateWorldMatrix(!0,!1),e.node.matrixWorld.decompose(bn,Nr,Hn);let i=bn.set(.1,.1,.1).divide(Hn);n.matrix.copy(e.node.matrixWorld).scale(i)}),super.updateMatrixWorld(t)}},ze=["hips","spine","chest","upperChest","neck","head","leftEye","rightEye","jaw","leftUpperLeg","leftLowerLeg","leftFoot","leftToes","rightUpperLeg","rightLowerLeg","rightFoot","rightToes","leftShoulder","leftUpperArm","leftLowerArm","leftHand","rightShoulder","rightUpperArm","rightLowerArm","rightHand","leftThumbMetacarpal","leftThumbProximal","leftThumbDistal","leftIndexProximal","leftIndexIntermediate","leftIndexDistal","leftMiddleProximal","leftMiddleIntermediate","leftMiddleDistal","leftRingProximal","leftRingIntermediate","leftRingDistal","leftLittleProximal","leftLittleIntermediate","leftLittleDistal","rightThumbMetacarpal","rightThumbProximal","rightThumbDistal","rightIndexProximal","rightIndexIntermediate","rightIndexDistal","rightMiddleProximal","rightMiddleIntermediate","rightMiddleDistal","rightRingProximal","rightRingIntermediate","rightRingDistal","rightLittleProximal","rightLittleIntermediate","rightLittleDistal"],Br={Hips:"hips",Spine:"spine",Chest:"chest",UpperChest:"upperChest",Neck:"neck",Head:"head",LeftEye:"leftEye",RightEye:"rightEye",Jaw:"jaw",LeftUpperLeg:"leftUpperLeg",LeftLowerLeg:"leftLowerLeg",LeftFoot:"leftFoot",LeftToes:"leftToes",RightUpperLeg:"rightUpperLeg",RightLowerLeg:"rightLowerLeg",RightFoot:"rightFoot",RightToes:"rightToes",LeftShoulder:"leftShoulder",LeftUpperArm:"leftUpperArm",LeftLowerArm:"leftLowerArm",LeftHand:"leftHand",RightShoulder:"rightShoulder",RightUpperArm:"rightUpperArm",RightLowerArm:"rightLowerArm",RightHand:"rightHand",LeftThumbMetacarpal:"leftThumbMetacarpal",LeftThumbProximal:"leftThumbProximal",LeftThumbDistal:"leftThumbDistal",LeftIndexProximal:"leftIndexProximal",LeftIndexIntermediate:"leftIndexIntermediate",LeftIndexDistal:"leftIndexDistal",LeftMiddleProximal:"leftMiddleProximal",LeftMiddleIntermediate:"leftMiddleIntermediate",LeftMiddleDistal:"leftMiddleDistal",LeftRingProximal:"leftRingProximal",LeftRingIntermediate:"leftRingIntermediate",LeftRingDistal:"leftRingDistal",LeftLittleProximal:"leftLittleProximal",LeftLittleIntermediate:"leftLittleIntermediate",LeftLittleDistal:"leftLittleDistal",RightThumbMetacarpal:"rightThumbMetacarpal",RightThumbProximal:"rightThumbProximal",RightThumbDistal:"rightThumbDistal",RightIndexProximal:"rightIndexProximal",RightIndexIntermediate:"rightIndexIntermediate",RightIndexDistal:"rightIndexDistal",RightMiddleProximal:"rightMiddleProximal",RightMiddleIntermediate:"rightMiddleIntermediate",RightMiddleDistal:"rightMiddleDistal",RightRingProximal:"rightRingProximal",RightRingIntermediate:"rightRingIntermediate",RightRingDistal:"rightRingDistal",RightLittleProximal:"rightLittleProximal",RightLittleIntermediate:"rightLittleIntermediate",RightLittleDistal:"rightLittleDistal"},Jn={hips:null,spine:"hips",chest:"spine",upperChest:"chest",neck:"upperChest",head:"neck",leftEye:"head",rightEye:"head",jaw:"head",leftUpperLeg:"hips",leftLowerLeg:"leftUpperLeg",leftFoot:"leftLowerLeg",leftToes:"leftFoot",rightUpperLeg:"hips",rightLowerLeg:"rightUpperLeg",rightFoot:"rightLowerLeg",rightToes:"rightFoot",leftShoulder:"upperChest",leftUpperArm:"leftShoulder",leftLowerArm:"leftUpperArm",leftHand:"leftLowerArm",rightShoulder:"upperChest",rightUpperArm:"rightShoulder",rightLowerArm:"rightUpperArm",rightHand:"rightLowerArm",leftThumbMetacarpal:"leftHand",leftThumbProximal:"leftThumbMetacarpal",leftThumbDistal:"leftThumbProximal",leftIndexProximal:"leftHand",leftIndexIntermediate:"leftIndexProximal",leftIndexDistal:"leftIndexIntermediate",leftMiddleProximal:"leftHand",leftMiddleIntermediate:"leftMiddleProximal",leftMiddleDistal:"leftMiddleIntermediate",leftRingProximal:"leftHand",leftRingIntermediate:"leftRingProximal",leftRingDistal:"leftRingIntermediate",leftLittleProximal:"leftHand",leftLittleIntermediate:"leftLittleProximal",leftLittleDistal:"leftLittleIntermediate",rightThumbMetacarpal:"rightHand",rightThumbProximal:"rightThumbMetacarpal",rightThumbDistal:"rightThumbProximal",rightIndexProximal:"rightHand",rightIndexIntermediate:"rightIndexProximal",rightIndexDistal:"rightIndexIntermediate",rightMiddleProximal:"rightHand",rightMiddleIntermediate:"rightMiddleProximal",rightMiddleDistal:"rightMiddleIntermediate",rightRingProximal:"rightHand",rightRingIntermediate:"rightRingProximal",rightRingDistal:"rightRingIntermediate",rightLittleProximal:"rightHand",rightLittleIntermediate:"rightLittleProximal",rightLittleDistal:"rightLittleIntermediate"};function Kn(t){return t.invert?t.invert():t.inverse(),t}var ae=new qe.Vector3,le=new qe.Quaternion,yt=class{constructor(t){this.humanBones=t,this.restPose=this.getAbsolutePose()}getAbsolutePose(){let t={};return Object.keys(this.humanBones).forEach(e=>{let n=e,i=this.getBoneNode(n);i&&(ae.copy(i.position),le.copy(i.quaternion),t[n]={position:ae.toArray(),rotation:le.toArray()})}),t}getPose(){let t={};return Object.keys(this.humanBones).forEach(e=>{let n=e,i=this.getBoneNode(n);if(!i)return;ae.set(0,0,0),le.identity();let r=this.restPose[n];r!=null&&r.position&&ae.fromArray(r.position).negate(),r!=null&&r.rotation&&Kn(le.fromArray(r.rotation)),ae.add(i.position),le.premultiply(i.quaternion),t[n]={position:ae.toArray(),rotation:le.toArray()}}),t}setPose(t){Object.entries(t).forEach(([e,n])=>{let i=e,r=this.getBoneNode(i);if(!r)return;let o=this.restPose[i];o&&(n!=null&&n.position&&(r.position.fromArray(n.position),o.position&&r.position.add(ae.fromArray(o.position))),n!=null&&n.rotation&&(r.quaternion.fromArray(n.rotation),o.rotation&&r.quaternion.multiply(le.fromArray(o.rotation))))})}resetPose(){Object.entries(this.restPose).forEach(([t,e])=>{let n=this.getBoneNode(t);n&&(e!=null&&e.position&&n.position.fromArray(e.position),e!=null&&e.rotation&&n.quaternion.fromArray(e.rotation))})}getBone(t){var e;return(e=this.humanBones[t])!=null?e:void 0}getBoneNode(t){var e,n;return(n=(e=this.humanBones[t])==null?void 0:e.node)!=null?n:null}},ft=new k.Vector3,Dr=new k.Quaternion,Fr=new k.Vector3,In=class ei extends yt{static _setupTransforms(e){let n=new k.Object3D;n.name="VRMHumanoidRig";let i={},r={},o={},a={};ze.forEach(s=>{var u;let d=e.getBoneNode(s);if(d){let h=new k.Vector3,p=new k.Quaternion;d.updateWorldMatrix(!0,!1),d.matrixWorld.decompose(h,p,ft),i[s]=h,r[s]=p,o[s]=d.quaternion.clone();let m=new k.Quaternion;(u=d.parent)==null||u.matrixWorld.decompose(ft,m,ft),a[s]=m}});let l={};return ze.forEach(s=>{var u;let d=e.getBoneNode(s);if(d){let h=i[s],p=s,m;for(;m==null&&(p=Jn[p],p!=null);)m=i[p];let c=new k.Object3D;c.name="Normalized_"+d.name,(p?(u=l[p])==null?void 0:u.node:n).add(c),c.position.copy(h),m&&c.position.sub(m),l[s]={node:c}}}),{rigBones:l,root:n,parentWorldRotations:a,boneRotations:o}}constructor(e){let{rigBones:n,root:i,parentWorldRotations:r,boneRotations:o}=ei._setupTransforms(e);super(n),this.original=e,this.root=i,this._parentWorldRotations=r,this._boneRotations=o}update(){ze.forEach(e=>{let n=this.original.getBoneNode(e);if(n!=null){let i=this.getBoneNode(e),r=this._parentWorldRotations[e],o=Dr.copy(r).invert(),a=this._boneRotations[e];if(n.quaternion.copy(i.quaternion).multiply(r).premultiply(o).multiply(a),e==="hips"){let l=i.getWorldPosition(Fr);n.parent.updateWorldMatrix(!0,!1);let s=n.parent.matrixWorld,u=l.applyMatrix4(s.invert());n.position.copy(u)}}})}},wt=class ti{get restPose(){return console.warn("VRMHumanoid: restPose is deprecated. Use either rawRestPose or normalizedRestPose instead."),this.rawRestPose}get rawRestPose(){return this._rawHumanBones.restPose}get normalizedRestPose(){return this._normalizedHumanBones.restPose}get humanBones(){return this._rawHumanBones.humanBones}get rawHumanBones(){return this._rawHumanBones.humanBones}get normalizedHumanBones(){return this._normalizedHumanBones.humanBones}get normalizedHumanBonesRoot(){return this._normalizedHumanBones.root}constructor(e,n){var i;this.autoUpdateHumanBones=(i=n==null?void 0:n.autoUpdateHumanBones)!=null?i:!0,this._rawHumanBones=new yt(e),this._normalizedHumanBones=new In(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new yt(e.humanBones),this._normalizedHumanBones=new In(this._rawHumanBones),this}clone(){return new ti(this.humanBones,{autoUpdateHumanBones:this.autoUpdateHumanBones}).copy(this)}getAbsolutePose(){return console.warn("VRMHumanoid: getAbsolutePose() is deprecated. Use either getRawAbsolutePose() or getNormalizedAbsolutePose() instead."),this.getRawAbsolutePose()}getRawAbsolutePose(){return this._rawHumanBones.getAbsolutePose()}getNormalizedAbsolutePose(){return this._normalizedHumanBones.getAbsolutePose()}getPose(){return console.warn("VRMHumanoid: getPose() is deprecated. Use either getRawPose() or getNormalizedPose() instead."),this.getRawPose()}getRawPose(){return this._rawHumanBones.getPose()}getNormalizedPose(){return this._normalizedHumanBones.getPose()}setPose(e){return console.warn("VRMHumanoid: setPose() is deprecated. Use either setRawPose() or setNormalizedPose() instead."),this.setRawPose(e)}setRawPose(e){return this._rawHumanBones.setPose(e)}setNormalizedPose(e){return this._normalizedHumanBones.setPose(e)}resetPose(){return console.warn("VRMHumanoid: resetPose() is deprecated. Use either resetRawPose() or resetNormalizedPose() instead."),this.resetRawPose()}resetRawPose(){return this._rawHumanBones.resetPose()}resetNormalizedPose(){return this._normalizedHumanBones.resetPose()}getBone(e){return console.warn("VRMHumanoid: getBone() is deprecated. Use either getRawBone() or getNormalizedBone() instead."),this.getRawBone(e)}getRawBone(e){return this._rawHumanBones.getBone(e)}getNormalizedBone(e){return this._normalizedHumanBones.getBone(e)}getBoneNode(e){return console.warn("VRMHumanoid: getBoneNode() is deprecated. Use either getRawBoneNode() or getNormalizedBoneNode() instead."),this.getRawBoneNode(e)}getRawBoneNode(e){return this._rawHumanBones.getBoneNode(e)}getNormalizedBoneNode(e){return this._normalizedHumanBones.getBoneNode(e)}update(){this.autoUpdateHumanBones&&this._normalizedHumanBones.update()}},ni={Hips:"hips",Spine:"spine",Head:"head",LeftUpperLeg:"leftUpperLeg",LeftLowerLeg:"leftLowerLeg",LeftFoot:"leftFoot",RightUpperLeg:"rightUpperLeg",RightLowerLeg:"rightLowerLeg",RightFoot:"rightFoot",LeftUpperArm:"leftUpperArm",LeftLowerArm:"leftLowerArm",LeftHand:"leftHand",RightUpperArm:"rightUpperArm",RightLowerArm:"rightLowerArm",RightHand:"rightHand"},kr=new Set(["1.0","1.0-beta"]),Vn={leftThumbProximal:"leftThumbMetacarpal",leftThumbIntermediate:"leftThumbProximal",rightThumbProximal:"rightThumbMetacarpal",rightThumbIntermediate:"rightThumbProximal"},$e=class{get name(){return"VRMHumanoidLoaderPlugin"}constructor(t,e){this.parser=t,this.helperRoot=e==null?void 0:e.helperRoot,this.autoUpdateHumanBones=e==null?void 0:e.autoUpdateHumanBones}afterRoot(t){return w(this,null,function*(){t.userData.vrmHumanoid=yield this._import(t)})}_import(t){return w(this,null,function*(){let e=yield this._v1Import(t);if(e)return e;let n=yield this._v0Import(t);return n||null})}_v1Import(t){return w(this,null,function*(){var e,n;let i=this.parser.json;if(!(((e=i.extensionsUsed)==null?void 0:e.indexOf("VRMC_vrm"))!==-1))return null;let o=(n=i.extensions)==null?void 0:n.VRMC_vrm;if(!o)return null;let a=o.specVersion;if(!kr.has(a))return console.warn(`VRMHumanoidLoaderPlugin: Unknown VRMC_vrm specVersion "${a}"`),null;let l=o.humanoid;if(!l)return null;let s=l.humanBones.leftThumbIntermediate!=null||l.humanBones.rightThumbIntermediate!=null,u={};l.humanBones!=null&&(yield Promise.all(Object.entries(l.humanBones).map(h=>w(this,[h],function*([p,m]){let c=p,f=m.node;if(s){let v=Vn[c];v!=null&&(c=v)}let g=yield this.parser.getDependency("node",f);if(g==null){console.warn(`A glTF node bound to the humanoid bone ${c} (index = ${f}) does not exist`);return}u[c]={node:g}}))));let d=new wt(this._ensureRequiredBonesExist(u),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(t.scene.add(d.normalizedHumanBonesRoot),this.helperRoot){let h=new xt(d);this.helperRoot.add(h),h.renderOrder=this.helperRoot.renderOrder}return d})}_v0Import(t){return w(this,null,function*(){var e;let i=(e=this.parser.json.extensions)==null?void 0:e.VRM;if(!i)return null;let r=i.humanoid;if(!r)return null;let o={};r.humanBones!=null&&(yield Promise.all(r.humanBones.map(l=>w(this,null,function*(){let s=l.bone,u=l.node;if(s==null||u==null)return;let d=yield this.parser.getDependency("node",u);if(d==null){console.warn(`A glTF node bound to the humanoid bone ${s} (index = ${u}) does not exist`);return}let h=Vn[s],p=h!=null?h:s;if(o[p]!=null){console.warn(`Multiple bone entries for ${p} detected (index = ${u}), ignoring duplicated entries.`);return}o[p]={node:d}}))));let a=new wt(this._ensureRequiredBonesExist(o),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(t.scene.add(a.normalizedHumanBonesRoot),this.helperRoot){let l=new xt(a);this.helperRoot.add(l),l.renderOrder=this.helperRoot.renderOrder}return a})}_ensureRequiredBonesExist(t){let e=Object.values(ni).filter(n=>t[n]==null);if(e.length>0)throw new Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${e.join(", ")}`);return t}},Cn=class extends Le.BufferGeometry{constructor(){super(),this._currentTheta=0,this._currentRadius=0,this.theta=0,this.radius=0,this._currentTheta=0,this._currentRadius=0,this._attrPos=new Le.BufferAttribute(new Float32Array(65*3),3),this.setAttribute("position",this._attrPos),this._attrIndex=new Le.BufferAttribute(new Uint16Array(3*63),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let t=!1;this._currentTheta!==this.theta&&(this._currentTheta=this.theta,t=!0),this._currentRadius!==this.radius&&(this._currentRadius=this.radius,t=!0),t&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,0,0,0);for(let t=0;t<64;t++){let e=t/63*this._currentTheta;this._attrPos.setXYZ(t+1,this._currentRadius*Math.sin(e),0,this._currentRadius*Math.cos(e))}this._attrPos.needsUpdate=!0}_buildIndex(){for(let t=0;t<63;t++)this._attrIndex.setXYZ(t*3,0,t+1,t+2);this._attrIndex.needsUpdate=!0}},Wr=class extends te.BufferGeometry{constructor(){super(),this.radius=0,this._currentRadius=0,this.tail=new te.Vector3,this._currentTail=new te.Vector3,this._attrPos=new te.BufferAttribute(new Float32Array(294),3),this.setAttribute("position",this._attrPos),this._attrIndex=new te.BufferAttribute(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let t=!1;this._currentRadius!==this.radius&&(this._currentRadius=this.radius,t=!0),this._currentTail.equals(this.tail)||(this._currentTail.copy(this.tail),t=!0),t&&this._buildPosition()}_buildPosition(){for(let t=0;t<32;t++){let e=t/16*Math.PI;this._attrPos.setXYZ(t,Math.cos(e),Math.sin(e),0),this._attrPos.setXYZ(32+t,0,Math.cos(e),Math.sin(e)),this._attrPos.setXYZ(64+t,Math.sin(e),0,Math.cos(e))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let t=0;t<32;t++){let e=(t+1)%32;this._attrIndex.setXY(t*2,t,e),this._attrIndex.setXY(64+t*2,32+t,32+e),this._attrIndex.setXY(128+t*2,64+t,64+e)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},ke=new I.Quaternion,Un=new I.Quaternion,Pe=new I.Vector3,On=new I.Vector3,Nn=Math.sqrt(2)/2,zr=new I.Quaternion(0,0,-Nn,Nn),Gr=new I.Vector3(0,1,0),ii=class extends I.Group{constructor(t){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=t;{let e=new Cn;e.radius=.5;let n=new I.MeshBasicMaterial({color:65280,transparent:!0,opacity:.5,side:I.DoubleSide,depthTest:!1,depthWrite:!1});this._meshPitch=new I.Mesh(e,n),this.add(this._meshPitch)}{let e=new Cn;e.radius=.5;let n=new I.MeshBasicMaterial({color:16711680,transparent:!0,opacity:.5,side:I.DoubleSide,depthTest:!1,depthWrite:!1});this._meshYaw=new I.Mesh(e,n),this.add(this._meshYaw)}{let e=new Wr;e.radius=.1;let n=new I.LineBasicMaterial({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new I.LineSegments(e,n),this._lineTarget.frustumCulled=!1,this.add(this._lineTarget)}}dispose(){this._meshYaw.geometry.dispose(),this._meshYaw.material.dispose(),this._meshPitch.geometry.dispose(),this._meshPitch.material.dispose(),this._lineTarget.geometry.dispose(),this._lineTarget.material.dispose()}updateMatrixWorld(t){let e=I.MathUtils.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=e,this._meshYaw.geometry.update();let n=I.MathUtils.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=n,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition(Pe),this.vrmLookAt.getLookAtWorldQuaternion(ke),ke.multiply(this.vrmLookAt.getFaceFrontQuaternion(Un)),this._meshYaw.position.copy(Pe),this._meshYaw.quaternion.copy(ke),this._meshPitch.position.copy(Pe),this._meshPitch.quaternion.copy(ke),this._meshPitch.quaternion.multiply(Un.setFromAxisAngle(Gr,e)),this._meshPitch.quaternion.multiply(zr);let{target:i,autoUpdate:r}=this.vrmLookAt;i!=null&&r&&(i.getWorldPosition(On).sub(Pe),this._lineTarget.geometry.tail.copy(On),this._lineTarget.geometry.update(),this._lineTarget.position.copy(Pe)),super.updateMatrixWorld(t)}},jr=new Ht.Vector3,Xr=new Ht.Vector3;function St(t,e){return t.matrixWorld.decompose(jr,e,Xr),e}function Ge(t){return[Math.atan2(-t.z,t.x),Math.atan2(t.y,Math.sqrt(t.x*t.x+t.z*t.z))]}function Bn(t){let e=Math.round(t/2/Math.PI);return t-2*Math.PI*e}var Dn=new C.Vector3(0,0,1),Qr=new C.Vector3,Yr=new C.Vector3,qr=new C.Vector3,$r=new C.Quaternion,gt=new C.Quaternion,Fn=new C.Quaternion,Zr=new C.Quaternion,_t=new C.Euler,ri=class oi{constructor(e,n){this.offsetFromHeadBone=new C.Vector3,this.autoUpdate=!0,this.faceFront=new C.Vector3(0,0,1),this.humanoid=e,this.applier=n,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new C.Quaternion)}get yaw(){return this._yaw}set yaw(e){this._yaw=e,this._needsUpdate=!0}get pitch(){return this._pitch}set pitch(e){this._pitch=e,this._needsUpdate=!0}get euler(){return console.warn("VRMLookAt: euler is deprecated. use getEuler() instead."),this.getEuler(new C.Euler)}getEuler(e){return e.set(C.MathUtils.DEG2RAD*this._pitch,C.MathUtils.DEG2RAD*this._yaw,0,"YXZ")}copy(e){if(this.humanoid!==e.humanoid)throw new Error("VRMLookAt: humanoid must be same in order to copy");return this.offsetFromHeadBone.copy(e.offsetFromHeadBone),this.applier=e.applier,this.autoUpdate=e.autoUpdate,this.target=e.target,this.faceFront.copy(e.faceFront),this}clone(){return new oi(this.humanoid,this.applier).copy(this)}reset(){this._yaw=0,this._pitch=0,this._needsUpdate=!0}getLookAtWorldPosition(e){let n=this.humanoid.getRawBoneNode("head");return e.copy(this.offsetFromHeadBone).applyMatrix4(n.matrixWorld)}getLookAtWorldQuaternion(e){let n=this.humanoid.getRawBoneNode("head");return St(n,e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(Dn)<.01)return e.copy(this._restHeadWorldQuaternion).invert();let[n,i]=Ge(this.faceFront);return _t.set(0,.5*Math.PI+n,i,"YZX"),e.setFromEuler(_t).premultiply(Zr.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(gt),this.getFaceFrontQuaternion(Fn),e.copy(Dn).applyQuaternion(gt).applyQuaternion(Fn).applyEuler(this.getEuler(_t))}lookAt(e){let n=$r.copy(this._restHeadWorldQuaternion).multiply(Kn(this.getLookAtWorldQuaternion(gt))),i=this.getLookAtWorldPosition(Yr),r=qr.copy(e).sub(i).applyQuaternion(n).normalize(),[o,a]=Ge(this.faceFront),[l,s]=Ge(r),u=Bn(l-o),d=Bn(a-s);this._yaw=C.MathUtils.RAD2DEG*u,this._pitch=C.MathUtils.RAD2DEG*d,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(Qr)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};ri.EULER_ORDER="YXZ";var si=ri,Jr=new V.Vector3(0,0,1),j=new V.Quaternion,me=new V.Quaternion,B=new V.Euler(0,0,0,"YXZ"),Ae=class{constructor(t,e,n,i,r){this.humanoid=t,this.rangeMapHorizontalInner=e,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=i,this.rangeMapVerticalUp=r,this.faceFront=new V.Vector3(0,0,1),this._restQuatLeftEye=new V.Quaternion,this._restQuatRightEye=new V.Quaternion,this._restLeftEyeParentWorldQuat=new V.Quaternion,this._restRightEyeParentWorldQuat=new V.Quaternion;let o=this.humanoid.getRawBoneNode("leftEye"),a=this.humanoid.getRawBoneNode("rightEye");o&&(this._restQuatLeftEye.copy(o.quaternion),St(o.parent,this._restLeftEyeParentWorldQuat)),a&&(this._restQuatRightEye.copy(a.quaternion),St(a.parent,this._restRightEyeParentWorldQuat))}applyYawPitch(t,e){let n=this.humanoid.getRawBoneNode("leftEye"),i=this.humanoid.getRawBoneNode("rightEye"),r=this.humanoid.getNormalizedBoneNode("leftEye"),o=this.humanoid.getNormalizedBoneNode("rightEye");n&&(e<0?B.x=-V.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-e):B.x=V.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(e),t<0?B.y=-V.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(-t):B.y=V.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(t),j.setFromEuler(B),this._getWorldFaceFrontQuat(me),r.quaternion.copy(me).multiply(j).multiply(me.invert()),j.copy(this._restLeftEyeParentWorldQuat),n.quaternion.copy(r.quaternion).multiply(j).premultiply(j.invert()).multiply(this._restQuatLeftEye)),i&&(e<0?B.x=-V.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-e):B.x=V.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(e),t<0?B.y=-V.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(-t):B.y=V.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(t),j.setFromEuler(B),this._getWorldFaceFrontQuat(me),o.quaternion.copy(me).multiply(j).multiply(me.invert()),j.copy(this._restRightEyeParentWorldQuat),i.quaternion.copy(o.quaternion).multiply(j).premultiply(j.invert()).multiply(this._restQuatRightEye))}lookAt(t){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");let e=V.MathUtils.RAD2DEG*t.y,n=V.MathUtils.RAD2DEG*t.x;this.applyYawPitch(e,n)}_getWorldFaceFrontQuat(t){if(this.faceFront.distanceToSquared(Jr)<.01)return t.identity();let[e,n]=Ge(this.faceFront);return B.set(0,.5*Math.PI+e,n,"YZX"),t.setFromEuler(B)}};Ae.type="bone";var Xe=class{constructor(t,e,n,i,r){this.expressions=t,this.rangeMapHorizontalInner=e,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=i,this.rangeMapVerticalUp=r}applyYawPitch(t,e){e<0?(this.expressions.setValue("lookDown",0),this.expressions.setValue("lookUp",this.rangeMapVerticalUp.map(-e))):(this.expressions.setValue("lookUp",0),this.expressions.setValue("lookDown",this.rangeMapVerticalDown.map(e))),t<0?(this.expressions.setValue("lookLeft",0),this.expressions.setValue("lookRight",this.rangeMapHorizontalOuter.map(-t))):(this.expressions.setValue("lookRight",0),this.expressions.setValue("lookLeft",this.rangeMapHorizontalOuter.map(t)))}lookAt(t){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");let e=Pt.MathUtils.RAD2DEG*t.y,n=Pt.MathUtils.RAD2DEG*t.x;this.applyYawPitch(e,n)}};Xe.type="expression";var At=class{constructor(t,e){this.inputMaxValue=t,this.outputScale=e}map(t){return this.outputScale*zn(t/this.inputMaxValue)}},Kr=new Set(["1.0","1.0-beta"]),We=.01,Ze=class{get name(){return"VRMLookAtLoaderPlugin"}constructor(t,e){this.parser=t,this.helperRoot=e==null?void 0:e.helperRoot}afterRoot(t){return w(this,null,function*(){let e=t.userData.vrmHumanoid;if(e===null)return;if(e===void 0)throw new Error("VRMLookAtLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first");let n=t.userData.vrmExpressionManager;if(n!==null){if(n===void 0)throw new Error("VRMLookAtLoaderPlugin: vrmExpressionManager is undefined. VRMExpressionLoaderPlugin have to be used first");t.userData.vrmLookAt=yield this._import(t,e,n)}})}_import(t,e,n){return w(this,null,function*(){if(e==null||n==null)return null;let i=yield this._v1Import(t,e,n);if(i)return i;let r=yield this._v0Import(t,e,n);return r||null})}_v1Import(t,e,n){return w(this,null,function*(){var i,r,o;let a=this.parser.json;if(!(((i=a.extensionsUsed)==null?void 0:i.indexOf("VRMC_vrm"))!==-1))return null;let s=(r=a.extensions)==null?void 0:r.VRMC_vrm;if(!s)return null;let u=s.specVersion;if(!Kr.has(u))return console.warn(`VRMLookAtLoaderPlugin: Unknown VRMC_vrm specVersion "${u}"`),null;let d=s.lookAt;if(!d)return null;let h=d.type==="expression"?1:10,p=this._v1ImportRangeMap(d.rangeMapHorizontalInner,h),m=this._v1ImportRangeMap(d.rangeMapHorizontalOuter,h),c=this._v1ImportRangeMap(d.rangeMapVerticalDown,h),f=this._v1ImportRangeMap(d.rangeMapVerticalUp,h),g;d.type==="expression"?g=new Xe(n,p,m,c,f):g=new Ae(e,p,m,c,f);let v=this._importLookAt(e,g);return v.offsetFromHeadBone.fromArray((o=d.offsetFromHeadBone)!=null?o:[0,.06,0]),v})}_v1ImportRangeMap(t,e){var n,i;let r=(n=t==null?void 0:t.inputMaxValue)!=null?n:90,o=(i=t==null?void 0:t.outputScale)!=null?i:e;return r<We&&(console.warn("VRMLookAtLoaderPlugin: inputMaxValue of a range map is too small. Consider reviewing the range map!"),r=We),new At(r,o)}_v0Import(t,e,n){return w(this,null,function*(){var i,r,o,a;let s=(i=this.parser.json.extensions)==null?void 0:i.VRM;if(!s)return null;let u=s.firstPerson;if(!u)return null;let d=u.lookAtTypeName==="BlendShape"?1:10,h=this._v0ImportDegreeMap(u.lookAtHorizontalInner,d),p=this._v0ImportDegreeMap(u.lookAtHorizontalOuter,d),m=this._v0ImportDegreeMap(u.lookAtVerticalDown,d),c=this._v0ImportDegreeMap(u.lookAtVerticalUp,d),f;u.lookAtTypeName==="BlendShape"?f=new Xe(n,h,p,m,c):f=new Ae(e,h,p,m,c);let g=this._importLookAt(e,f);return u.firstPersonBoneOffset?g.offsetFromHeadBone.set((r=u.firstPersonBoneOffset.x)!=null?r:0,(o=u.firstPersonBoneOffset.y)!=null?o:.06,-((a=u.firstPersonBoneOffset.z)!=null?a:0)):g.offsetFromHeadBone.set(0,.06,0),g.faceFront.set(0,0,-1),f instanceof Ae&&f.faceFront.set(0,0,-1),g})}_v0ImportDegreeMap(t,e){var n,i;let r=t==null?void 0:t.curve;JSON.stringify(r)!=="[0,0,0,1,1,1,1,0]"&&console.warn("Curves of LookAtDegreeMap defined in VRM 0.0 are not supported");let o=(n=t==null?void 0:t.xRange)!=null?n:90,a=(i=t==null?void 0:t.yRange)!=null?i:e;return o<We&&(console.warn("VRMLookAtLoaderPlugin: xRange of a degree map is too small. Consider reviewing the degree map!"),o=We),new At(o,a)}_importLookAt(t,e){let n=new si(t,e);if(this.helperRoot){let i=new ii(n);this.helperRoot.add(i),i.renderOrder=this.helperRoot.renderOrder}return n}},eo={Bone:"bone",Expression:"expression"};function to(t,e){return typeof t!="string"||t===""?"":(/^https?:\/\//i.test(e)&&/^\//.test(t)&&(e=e.replace(/(^https?:\/\/[^/]+).*/i,"$1")),/^(https?:)?\/\//i.test(t)||/^data:.*,.*