UNPKG

@pixiv/three-vrm

Version:

VRM file loader for three.js.

11 lines 147 kB
/*! (c) 2019-2024 pixiv Inc. - https://github.com/pixiv/three-vrm/blob/release/LICENSE */ import*as e from"three";import{BufferAttribute as t}from"three"; /*! * @pixiv/three-vrm-core v2.1.0 * The implementation of core features of VRM, for @pixiv/three-vrm * * Copyright (c) 2020-2024 pixiv Inc. * @pixiv/three-vrm-core is distributed under MIT License * https://github.com/pixiv/three-vrm/blob/release/LICENSE */ class i extends e.Object3D{get overrideBlinkAmount(){return"block"===this.overrideBlink?0<this.weight?1:0:"blend"===this.overrideBlink?this.weight:0}get overrideLookAtAmount(){return"block"===this.overrideLookAt?0<this.weight?1:0:"blend"===this.overrideLookAt?this.weight:0}get overrideMouthAmount(){return"block"===this.overrideMouth?0<this.weight?1:0:"blend"===this.overrideMouth?this.weight:0}constructor(e){super(),this.weight=0,this.isBinary=!1,this.overrideBlink="none",this.overrideLookAt="none",this.overrideMouth="none",this._binds=[],this.name=`VRMExpression_${e}`,this.expressionName=e,this.type="VRMExpression",this.visible=!1}addBind(e){this._binds.push(e)}applyWeight(e){var t;let i=this.isBinary?this.weight<=.5?0:1:this.weight;i*=null!==(t=null==e?void 0:e.multiplier)&&void 0!==t?t:1,this._binds.forEach((e=>e.applyWeight(i)))}clearAppliedWeight(){this._binds.forEach((e=>e.clearAppliedWeight()))}}function n(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))}function r(e,t,i){var n,r;const o=e.parser.json,s=null===(n=o.nodes)||void 0===n?void 0:n[t];if(null==s)return console.warn(`extractPrimitivesInternal: Attempt to use nodes[${t}] of glTF but the node doesn't exist`),null;const a=s.mesh;if(null==a)return null;const l=null===(r=o.meshes)||void 0===r?void 0:r[a];if(null==l)return console.warn(`extractPrimitivesInternal: Attempt to use meshes[${a}] of glTF but the mesh doesn't exist`),null;const u=l.primitives.length,d=[];return i.traverse((e=>{d.length<u&&e.isMesh&&d.push(e)})),d}function o(e,t){return n(this,void 0,void 0,(function*(){const i=yield e.parser.getDependency("node",t);return r(e,t,i)}))}function s(e){return n(this,void 0,void 0,(function*(){const t=yield e.parser.getDependencies("node"),i=new Map;return t.forEach(((t,n)=>{const o=r(e,n,t);null!=o&&i.set(n,o)})),i}))}function a(t,i){var n,r;let o=null;if(parseInt(e.REVISION,10)>=133)o=null!==(r=null===(n=t.associations.get(i))||void 0===n?void 0:n.materials)&&void 0!==r?r:null;else{const e=t.associations.get(i);"materials"===(null==e?void 0:e.type)&&(o=e.index)}return o}"function"==typeof SuppressedError&&SuppressedError;const l={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 u(e){return Math.max(Math.min(e,1),0)}class d{get expressions(){return this._expressions.concat()}get expressionMap(){return Object.assign({},this._expressionMap)}get presetExpressionMap(){const e={},t=new Set(Object.values(l));return Object.entries(this._expressionMap).forEach((([i,n])=>{t.has(i)&&(e[i]=n)})),e}get customExpressionMap(){const e={},t=new Set(Object.values(l));return Object.entries(this._expressionMap).forEach((([i,n])=>{t.has(i)||(e[i]=n)})),e}constructor(){this.blinkExpressionNames=["blink","blinkLeft","blinkRight"],this.lookAtExpressionNames=["lookLeft","lookRight","lookUp","lookDown"],this.mouthExpressionNames=["aa","ee","ih","oh","ou"],this._expressions=[],this._expressionMap={}}copy(e){return this._expressions.concat().forEach((e=>{this.unregisterExpression(e)})),e._expressions.forEach((e=>{this.registerExpression(e)})),this.blinkExpressionNames=e.blinkExpressionNames.concat(),this.lookAtExpressionNames=e.lookAtExpressionNames.concat(),this.mouthExpressionNames=e.mouthExpressionNames.concat(),this}clone(){return(new d).copy(this)}getExpression(e){var t;return null!==(t=this._expressionMap[e])&&void 0!==t?t:null}registerExpression(e){this._expressions.push(e),this._expressionMap[e.expressionName]=e}unregisterExpression(e){const t=this._expressions.indexOf(e);-1===t&&console.warn("VRMExpressionManager: The specified expressions is not registered"),this._expressions.splice(t,1),delete this._expressionMap[e.expressionName]}getValue(e){var t;const i=this.getExpression(e);return null!==(t=null==i?void 0:i.weight)&&void 0!==t?t:null}setValue(e,t){const i=this.getExpression(e);i&&(i.weight=u(t))}getExpressionTrackName(e){const t=this.getExpression(e);return t?`${t.name}.weight`:null}update(){const e=this._calculateWeightMultipliers();this._expressions.forEach((e=>{e.clearAppliedWeight()})),this._expressions.forEach((t=>{let i=1;const n=t.expressionName;-1!==this.blinkExpressionNames.indexOf(n)&&(i*=e.blink),-1!==this.lookAtExpressionNames.indexOf(n)&&(i*=e.lookAt),-1!==this.mouthExpressionNames.indexOf(n)&&(i*=e.mouth),t.applyWeight({multiplier:i})}))}_calculateWeightMultipliers(){let e=1,t=1,i=1;return this._expressions.forEach((n=>{e-=n.overrideBlinkAmount,t-=n.overrideLookAtAmount,i-=n.overrideMouthAmount})),e=Math.max(0,e),t=Math.max(0,t),i=Math.max(0,i),{blink:e,lookAt:t,mouth:i}}}const h={Color:"color",EmissionColor:"emissionColor",ShadeColor:"shadeColor",MatcapColor:"matcapColor",RimColor:"rimColor",OutlineColor:"outlineColor"},c={_Color:h.Color,_EmissionColor:h.EmissionColor,_ShadeColor:h.ShadeColor,_RimColor:h.RimColor,_OutlineColor:h.OutlineColor},p=new e.Color;class m{constructor({material:e,type:t,targetValue:i,targetAlpha:n}){this.material=e,this.type=t,this.targetValue=i,this.targetAlpha=null!=n?n:1;const r=this._initColorBindState(),o=this._initAlphaBindState();this._state={color:r,alpha:o}}applyWeight(e){const{color:t,alpha:i}=this._state;if(null!=t){const{propertyName:i,deltaValue:n}=t,r=this.material[i];null!=r&&r.add(p.copy(n).multiplyScalar(e))}if(null!=i){const{propertyName:t,deltaValue:n}=i;null!=this.material[t]&&(this.material[t]+=n*e)}}clearAppliedWeight(){const{color:e,alpha:t}=this._state;if(null!=e){const{propertyName:t,initialValue:i}=e,n=this.material[t];null!=n&&n.copy(i)}if(null!=t){const{propertyName:e,initialValue:i}=t;null!=this.material[e]&&(this.material[e]=i)}}_initColorBindState(){var t,i,n;const{material:r,type:o,targetValue:s}=this,a=this._getPropertyNameMap(),l=null!==(i=null===(t=null==a?void 0:a[o])||void 0===t?void 0:t[0])&&void 0!==i?i:null;if(null==l)return console.warn(`Tried to add a material color bind to the material ${null!==(n=r.name)&&void 0!==n?n:"(no name)"}, the type ${o} but the material or the type is not supported.`),null;const u=r[l].clone();return{propertyName:l,initialValue:u,deltaValue:new e.Color(s.r-u.r,s.g-u.g,s.b-u.b)}}_initAlphaBindState(){var e,t,i;const{material:n,type:r,targetAlpha:o}=this,s=this._getPropertyNameMap(),a=null!==(t=null===(e=null==s?void 0:s[r])||void 0===e?void 0:e[1])&&void 0!==t?t:null;if(null==a&&1!==o)return console.warn(`Tried to add a material alpha bind to the material ${null!==(i=n.name)&&void 0!==i?i:"(no name)"}, the type ${r} but the material or the type does not support alpha.`),null;if(null==a)return null;const l=n[a];return{propertyName:a,initialValue:l,deltaValue:o-l}}_getPropertyNameMap(){var e,t;return null!==(t=null===(e=Object.entries(m._propertyNameMapMap).find((([e])=>!0===this.material[e])))||void 0===e?void 0:e[1])&&void 0!==t?t:null}}m._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]}};class f{constructor({primitives:e,index:t,weight:i}){this.primitives=e,this.index=t,this.weight=i}applyWeight(e){this.primitives.forEach((t=>{var i;null!=(null===(i=t.morphTargetInfluences)||void 0===i?void 0:i[this.index])&&(t.morphTargetInfluences[this.index]+=this.weight*e)}))}clearAppliedWeight(){this.primitives.forEach((e=>{var t;null!=(null===(t=e.morphTargetInfluences)||void 0===t?void 0:t[this.index])&&(e.morphTargetInfluences[this.index]=0)}))}}const g=new e.Vector2;class v{constructor({material:e,scale:t,offset:i}){var n,r;this.material=e,this.scale=t,this.offset=i;const o=null===(n=Object.entries(v._propertyNamesMap).find((([t])=>!0===e[t])))||void 0===n?void 0:n[1];null==o?(console.warn(`Tried to add a texture transform bind to the material ${null!==(r=e.name)&&void 0!==r?r:"(no name)"} but the material is not supported.`),this._properties=[]):(this._properties=[],o.forEach((n=>{var r;const o=null===(r=e[n])||void 0===r?void 0:r.clone();if(!o)return null;e[n]=o;const s=o.offset.clone(),a=o.repeat.clone(),l=i.clone().sub(s),u=t.clone().sub(a);this._properties.push({name:n,initialOffset:s,deltaOffset:l,initialScale:a,deltaScale:u})})))}applyWeight(e){this._properties.forEach((t=>{const i=this.material[t.name];void 0!==i&&(i.offset.add(g.copy(t.deltaOffset).multiplyScalar(e)),i.repeat.add(g.copy(t.deltaScale).multiplyScalar(e)))}))}clearAppliedWeight(){this._properties.forEach((e=>{const t=this.material[e.name];void 0!==t&&(t.offset.copy(e.initialOffset),t.repeat.copy(e.initialScale))}))}}v._propertyNamesMap={isMeshStandardMaterial:["map","emissiveMap","bumpMap","normalMap","displacementMap","roughnessMap","metalnessMap","alphaMap"],isMeshBasicMaterial:["map","specularMap","alphaMap"],isMToonMaterial:["map","normalMap","emissiveMap","shadeMultiplyTexture","rimMultiplyTexture","outlineWidthMultiplyTexture","uvAnimationMaskTexture"]};const _=new Set(["1.0","1.0-beta"]);class M{get name(){return"VRMExpressionLoaderPlugin"}constructor(e){this.parser=e}afterRoot(e){return n(this,void 0,void 0,(function*(){e.userData.vrmExpressionManager=yield this._import(e)}))}_import(e){return n(this,void 0,void 0,(function*(){const t=yield this._v1Import(e);if(t)return t;const i=yield this._v0Import(e);return i||null}))}_v1Import(t){var r,s;return n(this,void 0,void 0,(function*(){const u=this.parser.json;if(!(-1!==(null===(r=u.extensionsUsed)||void 0===r?void 0:r.indexOf("VRMC_vrm"))))return null;const h=null===(s=u.extensions)||void 0===s?void 0:s.VRMC_vrm;if(!h)return null;const c=h.specVersion;if(!_.has(c))return console.warn(`VRMExpressionLoaderPlugin: Unknown VRMC_vrm specVersion "${c}"`),null;const p=h.expressions;if(!p)return null;const g=new Set(Object.values(l)),M=new Map;null!=p.preset&&Object.entries(p.preset).forEach((([e,t])=>{null!=t&&(g.has(e)?M.set(e,t):console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${e}" detected. Ignoring the expression`))})),null!=p.custom&&Object.entries(p.custom).forEach((([e,t])=>{g.has(e)?console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${e}". Ignoring the expression`):M.set(e,t)}));const x=new d;return yield Promise.all(Array.from(M.entries()).map((([r,s])=>n(this,void 0,void 0,(function*(){var l,u,d,h,c,p,g;const _=new i(r);if(t.scene.add(_),_.isBinary=null!==(l=s.isBinary)&&void 0!==l&&l,_.overrideBlink=null!==(u=s.overrideBlink)&&void 0!==u?u:"none",_.overrideLookAt=null!==(d=s.overrideLookAt)&&void 0!==d?d:"none",_.overrideMouth=null!==(h=s.overrideMouth)&&void 0!==h?h:"none",null===(c=s.morphTargetBinds)||void 0===c||c.forEach((e=>n(this,void 0,void 0,(function*(){var i;if(void 0===e.node||void 0===e.index)return;const n=yield o(t,e.node),r=e.index;n.every((e=>Array.isArray(e.morphTargetInfluences)&&r<e.morphTargetInfluences.length))?_.addBind(new f({primitives:n,index:r,weight:null!==(i=e.weight)&&void 0!==i?i:1})):console.warn(`VRMExpressionLoaderPlugin: ${s.name} attempts to index morph #${r} but not found.`)})))),s.materialColorBinds||s.textureTransformBinds){const i=[];t.scene.traverse((e=>{const t=e.material;t&&i.push(t)})),null===(p=s.materialColorBinds)||void 0===p||p.forEach((t=>n(this,void 0,void 0,(function*(){i.filter((e=>{const i=a(this.parser,e);return t.material===i})).forEach((i=>{_.addBind(new m({material:i,type:t.type,targetValue:(new e.Color).fromArray(t.targetValue),targetAlpha:t.targetValue[3]}))}))})))),null===(g=s.textureTransformBinds)||void 0===g||g.forEach((t=>n(this,void 0,void 0,(function*(){i.filter((e=>{const i=a(this.parser,e);return t.material===i})).forEach((i=>{var n,r;_.addBind(new v({material:i,offset:(new e.Vector2).fromArray(null!==(n=t.offset)&&void 0!==n?n:[0,0]),scale:(new e.Vector2).fromArray(null!==(r=t.scale)&&void 0!==r?r:[1,1])}))}))}))))}x.registerExpression(_)}))))),x}))}_v0Import(t){var r;return n(this,void 0,void 0,(function*(){const s=this.parser.json,a=null===(r=s.extensions)||void 0===r?void 0:r.VRM;if(!a)return null;const l=a.blendShapeMaster;if(!l)return null;const u=new d,h=l.blendShapeGroups;if(!h)return u;const p=new Set;return yield Promise.all(h.map((r=>n(this,void 0,void 0,(function*(){var a;const l=r.presetName,d=null!=l&&M.v0v1PresetNameMap[l]||null,h=null!=d?d:r.name;if(null==h)return void console.warn("VRMExpressionLoaderPlugin: One of custom expressions has no name. Ignoring the expression");if(p.has(h))return void console.warn(`VRMExpressionLoaderPlugin: An expression preset ${l} has duplicated entries. Ignoring the expression`);p.add(h);const g=new i(h);t.scene.add(g),g.isBinary=null!==(a=r.isBinary)&&void 0!==a&&a,r.binds&&r.binds.forEach((e=>n(this,void 0,void 0,(function*(){var i;if(void 0===e.mesh||void 0===e.index)return;const a=[];null===(i=s.nodes)||void 0===i||i.forEach(((t,i)=>{t.mesh===e.mesh&&a.push(i)}));const l=e.index;yield Promise.all(a.map((i=>n(this,void 0,void 0,(function*(){var n;const s=yield o(t,i);s.every((e=>Array.isArray(e.morphTargetInfluences)&&l<e.morphTargetInfluences.length))?g.addBind(new f({primitives:s,index:l,weight:.01*(null!==(n=e.weight)&&void 0!==n?n:100)})):console.warn(`VRMExpressionLoaderPlugin: ${r.name} attempts to index ${l}th morph but not found.`)})))))}))));const _=r.materialValues;_&&0!==_.length&&_.forEach((i=>{if(void 0===i.materialName||void 0===i.propertyName||void 0===i.targetValue)return;const n=[];t.scene.traverse((e=>{if(e.material){const t=e.material;Array.isArray(t)?n.push(...t.filter((e=>(e.name===i.materialName||e.name===i.materialName+" (Outline)")&&-1===n.indexOf(e)))):t.name===i.materialName&&-1===n.indexOf(t)&&n.push(t)}}));const r=i.propertyName;n.forEach((t=>{if("_MainTex_ST"===r){const n=new e.Vector2(i.targetValue[0],i.targetValue[1]),r=new e.Vector2(i.targetValue[2],i.targetValue[3]);return r.y=1-r.y-n.y,void g.addBind(new v({material:t,scale:n,offset:r}))}const n=c[r];n?g.addBind(new m({material:t,type:n,targetValue:(new e.Color).fromArray(i.targetValue),targetAlpha:i.targetValue[3]})):console.warn(r+" is not supported")}))})),u.registerExpression(g)}))))),u}))}}M.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"};const x={None:"none",Block:"block",Blend:"blend"};class y{constructor(e,t){this._firstPersonOnlyLayer=y.DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=y.DEFAULT_THIRDPERSON_ONLY_LAYER,this._initializedLayers=!1,this.humanoid=e,this.meshAnnotations=t}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((e=>({meshes:e.meshes.concat(),type:e.type}))),this}clone(){return new y(this.humanoid,this.meshAnnotations).copy(this)}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}setup({firstPersonOnlyLayer:e=y.DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:t=y.DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initializedLayers||(this._firstPersonOnlyLayer=e,this._thirdPersonOnlyLayer=t,this.meshAnnotations.forEach((e=>{e.meshes.forEach((t=>{"firstPersonOnly"===e.type?(t.layers.set(this._firstPersonOnlyLayer),t.traverse((e=>e.layers.set(this._firstPersonOnlyLayer)))):"thirdPersonOnly"===e.type?(t.layers.set(this._thirdPersonOnlyLayer),t.traverse((e=>e.layers.set(this._thirdPersonOnlyLayer)))):"auto"===e.type&&this._createHeadlessModel(t)}))})),this._initializedLayers=!0)}_excludeTriangles(e,t,i,n){let r=0;if(null!=t&&t.length>0)for(let o=0;o<e.length;o+=3){const s=e[o],a=e[o+1],l=e[o+2],u=t[s],d=i[s];if(u[0]>0&&n.includes(d[0]))continue;if(u[1]>0&&n.includes(d[1]))continue;if(u[2]>0&&n.includes(d[2]))continue;if(u[3]>0&&n.includes(d[3]))continue;const h=t[a],c=i[a];if(h[0]>0&&n.includes(c[0]))continue;if(h[1]>0&&n.includes(c[1]))continue;if(h[2]>0&&n.includes(c[2]))continue;if(h[3]>0&&n.includes(c[3]))continue;const p=t[l],m=i[l];p[0]>0&&n.includes(m[0])||(p[1]>0&&n.includes(m[1])||p[2]>0&&n.includes(m[2])||p[3]>0&&n.includes(m[3])||(e[r++]=s,e[r++]=a,e[r++]=l))}return r}_createErasedMesh(t,i){const n=new e.SkinnedMesh(t.geometry.clone(),t.material);n.name=`${t.name}(erase)`,n.frustumCulled=t.frustumCulled,n.layers.set(this._firstPersonOnlyLayer);const r=n.geometry,o=r.getAttribute("skinIndex"),s=o instanceof e.GLBufferAttribute?[]:o.array,a=[];for(let e=0;e<s.length;e+=4)a.push([s[e],s[e+1],s[e+2],s[e+3]]);const l=r.getAttribute("skinWeight"),u=l instanceof e.GLBufferAttribute?[]:l.array,d=[];for(let e=0;e<u.length;e+=4)d.push([u[e],u[e+1],u[e+2],u[e+3]]);const h=r.getIndex();if(!h)throw new Error("The geometry doesn't have an index buffer");const c=Array.from(h.array),p=this._excludeTriangles(c,d,a,i),m=[];for(let e=0;e<p;e++)m[e]=c[e];return r.setIndex(m),t.onBeforeRender&&(n.onBeforeRender=t.onBeforeRender),n.bind(new e.Skeleton(t.skeleton.bones,t.skeleton.boneInverses),new e.Matrix4),n}_createHeadlessModelForSkinnedMesh(e,t){const i=[];if(t.skeleton.bones.forEach(((e,t)=>{this._isEraseTarget(e)&&i.push(t)})),!i.length)return t.layers.enable(this._thirdPersonOnlyLayer),void t.layers.enable(this._firstPersonOnlyLayer);t.layers.set(this._thirdPersonOnlyLayer);const n=this._createErasedMesh(t,i);e.add(n)}_createHeadlessModel(t){if("Group"===t.type)if(t.layers.set(this._thirdPersonOnlyLayer),this._isEraseTarget(t))t.traverse((e=>e.layers.set(this._thirdPersonOnlyLayer)));else{const i=new e.Group;i.name=`_headless_${t.name}`,i.layers.set(this._firstPersonOnlyLayer),t.parent.add(i),t.children.filter((e=>"SkinnedMesh"===e.type)).forEach((e=>{const t=e;this._createHeadlessModelForSkinnedMesh(i,t)}))}else if("SkinnedMesh"===t.type){const e=t;this._createHeadlessModelForSkinnedMesh(t.parent,e)}else this._isEraseTarget(t)&&(t.layers.set(this._thirdPersonOnlyLayer),t.traverse((e=>e.layers.set(this._thirdPersonOnlyLayer))))}_isEraseTarget(e){return e===this.humanoid.getRawBoneNode("head")||!!e.parent&&this._isEraseTarget(e.parent)}}y.DEFAULT_FIRSTPERSON_ONLY_LAYER=9,y.DEFAULT_THIRDPERSON_ONLY_LAYER=10;const T=new Set(["1.0","1.0-beta"]);class R{get name(){return"VRMFirstPersonLoaderPlugin"}constructor(e){this.parser=e}afterRoot(e){return n(this,void 0,void 0,(function*(){const t=e.userData.vrmHumanoid;if(null!==t){if(void 0===t)throw new Error("VRMFirstPersonLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first");e.userData.vrmFirstPerson=yield this._import(e,t)}}))}_import(e,t){return n(this,void 0,void 0,(function*(){if(null==t)return null;const i=yield this._v1Import(e,t);if(i)return i;const n=yield this._v0Import(e,t);return n||null}))}_v1Import(e,t){var i,r;return n(this,void 0,void 0,(function*(){const n=this.parser.json;if(!(-1!==(null===(i=n.extensionsUsed)||void 0===i?void 0:i.indexOf("VRMC_vrm"))))return null;const o=null===(r=n.extensions)||void 0===r?void 0:r.VRMC_vrm;if(!o)return null;const a=o.specVersion;if(!T.has(a))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${a}"`),null;const l=o.firstPerson;if(!l)return null;const u=[],d=yield s(e);return Array.from(d.entries()).forEach((([e,t])=>{var i;const n=l.meshAnnotations?l.meshAnnotations.find((t=>t.node===e)):void 0;u.push({meshes:t,type:null!==(i=null==n?void 0:n.type)&&void 0!==i?i:"both"})})),new y(t,u)}))}_v0Import(e,t){var i;return n(this,void 0,void 0,(function*(){const n=this.parser.json,r=null===(i=n.extensions)||void 0===i?void 0:i.VRM;if(!r)return null;const o=r.firstPerson;if(!o)return null;const a=[],l=yield s(e);return Array.from(l.entries()).forEach((([e,t])=>{const i=n.nodes[e],r=o.meshAnnotations?o.meshAnnotations.find((e=>e.mesh===i.mesh)):void 0;a.push({meshes:t,type:this._convertV0FlagToV1Type(null==r?void 0:r.firstPersonFlag)})})),new y(t,a)}))}_convertV0FlagToV1Type(e){return"FirstPersonOnly"===e?"firstPersonOnly":"ThirdPersonOnly"===e?"thirdPersonOnly":"Auto"===e?"auto":"both"}}const E={Auto:"auto",Both:"both",ThirdPersonOnly:"thirdPersonOnly",FirstPersonOnly:"firstPersonOnly"},w=new e.Vector3,P=new e.Vector3,S=new e.Quaternion;class A extends e.Group{constructor(t){super(),this.vrmHumanoid=t,this._boneAxesMap=new Map,Object.values(t.humanBones).forEach((t=>{const i=new e.AxesHelper(1);i.matrixAutoUpdate=!1,i.material.depthTest=!1,i.material.depthWrite=!1,this.add(i),this._boneAxesMap.set(t,i)}))}dispose(){Array.from(this._boneAxesMap.values()).forEach((e=>{e.geometry.dispose(),e.material.dispose()}))}updateMatrixWorld(e){Array.from(this._boneAxesMap.entries()).forEach((([e,t])=>{e.node.updateWorldMatrix(!0,!1),e.node.matrixWorld.decompose(w,S,P);const i=w.set(.1,.1,.1).divide(P);t.matrix.copy(e.node.matrixWorld).scale(i)})),super.updateMatrixWorld(e)}}const L=["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"],I={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"},b={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 U(e){return e.invert?e.invert():e.inverse(),e}const O=new e.Vector3,N=new e.Quaternion;class V{constructor(e){this.humanBones=e,this.restPose=this.getAbsolutePose()}getAbsolutePose(){const e={};return Object.keys(this.humanBones).forEach((t=>{const i=t,n=this.getBoneNode(i);n&&(O.copy(n.position),N.copy(n.quaternion),e[i]={position:O.toArray(),rotation:N.toArray()})})),e}getPose(){const e={};return Object.keys(this.humanBones).forEach((t=>{const i=t,n=this.getBoneNode(i);if(!n)return;O.set(0,0,0),N.identity();const r=this.restPose[i];(null==r?void 0:r.position)&&O.fromArray(r.position).negate(),(null==r?void 0:r.rotation)&&U(N.fromArray(r.rotation)),O.add(n.position),N.premultiply(n.quaternion),e[i]={position:O.toArray(),rotation:N.toArray()}})),e}setPose(e){Object.entries(e).forEach((([e,t])=>{const i=e,n=this.getBoneNode(i);if(!n)return;const r=this.restPose[i];r&&((null==t?void 0:t.position)&&(n.position.fromArray(t.position),r.position&&n.position.add(O.fromArray(r.position))),(null==t?void 0:t.rotation)&&(n.quaternion.fromArray(t.rotation),r.rotation&&n.quaternion.multiply(N.fromArray(r.rotation))))}))}resetPose(){Object.entries(this.restPose).forEach((([e,t])=>{const i=this.getBoneNode(e);i&&((null==t?void 0:t.position)&&i.position.fromArray(t.position),(null==t?void 0:t.rotation)&&i.quaternion.fromArray(t.rotation))}))}getBone(e){var t;return null!==(t=this.humanBones[e])&&void 0!==t?t:void 0}getBoneNode(e){var t,i;return null!==(i=null===(t=this.humanBones[e])||void 0===t?void 0:t.node)&&void 0!==i?i:null}}const C=new e.Vector3,D=new e.Quaternion,F=new e.Vector3;class H extends V{static _setupTransforms(t){const i=new e.Object3D;i.name="VRMHumanoidRig";const n={},r={},o={};L.forEach((i=>{var s;const a=t.getBoneNode(i);if(a){const t=new e.Vector3,l=new e.Quaternion;a.updateWorldMatrix(!0,!1),a.matrixWorld.decompose(t,l,C),n[i]=t,r[i]=a.quaternion.clone();const u=new e.Quaternion;null===(s=a.parent)||void 0===s||s.matrixWorld.decompose(C,u,C),o[i]=u}}));const s={};return L.forEach((r=>{var o;const a=t.getBoneNode(r);if(a){const t=n[r];let l,u=r;for(;null==l&&(u=b[u],null!=u);)l=n[u];const d=new e.Object3D;d.name="Normalized_"+a.name;(u?null===(o=s[u])||void 0===o?void 0:o.node:i).add(d),d.position.copy(t),l&&d.position.sub(l),s[r]={node:d}}})),{rigBones:s,root:i,parentWorldRotations:o,boneRotations:r}}constructor(e){const{rigBones:t,root:i,parentWorldRotations:n,boneRotations:r}=H._setupTransforms(e);super(t),this.original=e,this.root=i,this._parentWorldRotations=n,this._boneRotations=r}update(){L.forEach((e=>{const t=this.original.getBoneNode(e);if(null!=t){const i=this.getBoneNode(e),n=this._parentWorldRotations[e],r=D.copy(n).invert(),o=this._boneRotations[e];if(t.quaternion.copy(i.quaternion).multiply(n).premultiply(r).multiply(o),"hips"===e){const e=i.getWorldPosition(F);t.parent.updateWorldMatrix(!0,!1);const n=t.parent.matrixWorld,r=e.applyMatrix4(n.invert());t.position.copy(r)}}}))}}class B{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,t){var i;this.autoUpdateHumanBones=null===(i=null==t?void 0:t.autoUpdateHumanBones)||void 0===i||i,this._rawHumanBones=new V(e),this._normalizedHumanBones=new H(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new V(e.humanBones),this._normalizedHumanBones=new H(this._rawHumanBones),this}clone(){return new B(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()}}const k={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"},W=new Set(["1.0","1.0-beta"]),z={leftThumbProximal:"leftThumbMetacarpal",leftThumbIntermediate:"leftThumbProximal",rightThumbProximal:"rightThumbMetacarpal",rightThumbIntermediate:"rightThumbProximal"};class G{get name(){return"VRMHumanoidLoaderPlugin"}constructor(e,t){this.parser=e,this.helperRoot=null==t?void 0:t.helperRoot,this.autoUpdateHumanBones=null==t?void 0:t.autoUpdateHumanBones}afterRoot(e){return n(this,void 0,void 0,(function*(){e.userData.vrmHumanoid=yield this._import(e)}))}_import(e){return n(this,void 0,void 0,(function*(){const t=yield this._v1Import(e);if(t)return t;const i=yield this._v0Import(e);return i||null}))}_v1Import(e){var t,i;return n(this,void 0,void 0,(function*(){const r=this.parser.json;if(!(-1!==(null===(t=r.extensionsUsed)||void 0===t?void 0:t.indexOf("VRMC_vrm"))))return null;const o=null===(i=r.extensions)||void 0===i?void 0:i.VRMC_vrm;if(!o)return null;const s=o.specVersion;if(!W.has(s))return console.warn(`VRMHumanoidLoaderPlugin: Unknown VRMC_vrm specVersion "${s}"`),null;const a=o.humanoid;if(!a)return null;const l=null!=a.humanBones.leftThumbIntermediate||null!=a.humanBones.rightThumbIntermediate,u={};null!=a.humanBones&&(yield Promise.all(Object.entries(a.humanBones).map((([e,t])=>n(this,void 0,void 0,(function*(){let i=e;const n=t.node;if(l){const e=z[i];null!=e&&(i=e)}const r=yield this.parser.getDependency("node",n);null!=r?u[i]={node:r}:console.warn(`A glTF node bound to the humanoid bone ${i} (index = ${n}) does not exist`)}))))));const d=new B(this._ensureRequiredBonesExist(u),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(d.normalizedHumanBonesRoot),this.helperRoot){const e=new A(d);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return d}))}_v0Import(e){var t;return n(this,void 0,void 0,(function*(){const i=this.parser.json,r=null===(t=i.extensions)||void 0===t?void 0:t.VRM;if(!r)return null;const o=r.humanoid;if(!o)return null;const s={};null!=o.humanBones&&(yield Promise.all(o.humanBones.map((e=>n(this,void 0,void 0,(function*(){const t=e.bone,i=e.node;if(null==t||null==i)return;const n=yield this.parser.getDependency("node",i);if(null==n)return void console.warn(`A glTF node bound to the humanoid bone ${t} (index = ${i}) does not exist`);const r=z[t],o=null!=r?r:t;null==s[o]?s[o]={node:n}:console.warn(`Multiple bone entries for ${o} detected (index = ${i}), ignoring duplicated entries.`)}))))));const a=new B(this._ensureRequiredBonesExist(s),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(a.normalizedHumanBonesRoot),this.helperRoot){const e=new A(a);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return a}))}_ensureRequiredBonesExist(e){const t=Object.values(k).filter((t=>null==e[t]));if(t.length>0)throw new Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${t.join(", ")}`);return e}}class Q extends e.BufferGeometry{constructor(){super(),this._currentTheta=0,this._currentRadius=0,this.theta=0,this.radius=0,this._currentTheta=0,this._currentRadius=0,this._attrPos=new e.BufferAttribute(new Float32Array(195),3),this.setAttribute("position",this._attrPos),this._attrIndex=new e.BufferAttribute(new Uint16Array(189),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentTheta!==this.theta&&(this._currentTheta=this.theta,e=!0),this._currentRadius!==this.radius&&(this._currentRadius=this.radius,e=!0),e&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,0,0,0);for(let e=0;e<64;e++){const t=e/63*this._currentTheta;this._attrPos.setXYZ(e+1,this._currentRadius*Math.sin(t),0,this._currentRadius*Math.cos(t))}this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<63;e++)this._attrIndex.setXYZ(3*e,0,e+1,e+2);this._attrIndex.needsUpdate=!0}}class j extends e.BufferGeometry{constructor(){super(),this.radius=0,this._currentRadius=0,this.tail=new e.Vector3,this._currentTail=new e.Vector3,this._attrPos=new e.BufferAttribute(new Float32Array(294),3),this.setAttribute("position",this._attrPos),this._attrIndex=new e.BufferAttribute(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentRadius!==this.radius&&(this._currentRadius=this.radius,e=!0),this._currentTail.equals(this.tail)||(this._currentTail.copy(this.tail),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){const t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}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 e=0;e<32;e++){const t=(e+1)%32;this._attrIndex.setXY(2*e,e,t),this._attrIndex.setXY(64+2*e,32+e,32+t),this._attrIndex.setXY(128+2*e,64+e,64+t)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}}const X=new e.Quaternion,Y=new e.Quaternion,q=new e.Vector3,$=new e.Vector3,Z=Math.sqrt(2)/2,J=new e.Quaternion(0,0,-Z,Z),K=new e.Vector3(0,1,0);class ee extends e.Group{constructor(t){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=t;{const t=new Q;t.radius=.5;const i=new e.MeshBasicMaterial({color:65280,transparent:!0,opacity:.5,side:e.DoubleSide,depthTest:!1,depthWrite:!1});this._meshPitch=new e.Mesh(t,i),this.add(this._meshPitch)}{const t=new Q;t.radius=.5;const i=new e.MeshBasicMaterial({color:16711680,transparent:!0,opacity:.5,side:e.DoubleSide,depthTest:!1,depthWrite:!1});this._meshYaw=new e.Mesh(t,i),this.add(this._meshYaw)}{const t=new j;t.radius=.1;const i=new e.LineBasicMaterial({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new e.LineSegments(t,i),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){const i=e.MathUtils.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=i,this._meshYaw.geometry.update();const n=e.MathUtils.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=n,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition(q),this.vrmLookAt.getLookAtWorldQuaternion(X),X.multiply(this.vrmLookAt.getFaceFrontQuaternion(Y)),this._meshYaw.position.copy(q),this._meshYaw.quaternion.copy(X),this._meshPitch.position.copy(q),this._meshPitch.quaternion.copy(X),this._meshPitch.quaternion.multiply(Y.setFromAxisAngle(K,i)),this._meshPitch.quaternion.multiply(J);const{target:r,autoUpdate:o}=this.vrmLookAt;null!=r&&o&&(r.getWorldPosition($).sub(q),this._lineTarget.geometry.tail.copy($),this._lineTarget.geometry.update(),this._lineTarget.position.copy(q)),super.updateMatrixWorld(t)}}const te=new e.Vector3,ie=new e.Vector3;function ne(e,t){return e.matrixWorld.decompose(te,t,ie),t}function re(e){return[Math.atan2(-e.z,e.x),Math.atan2(e.y,Math.sqrt(e.x*e.x+e.z*e.z))]}function oe(e){const t=Math.round(e/2/Math.PI);return e-2*Math.PI*t}const se=new e.Vector3(0,0,1),ae=new e.Vector3,le=new e.Vector3,ue=new e.Vector3,de=new e.Quaternion,he=new e.Quaternion,ce=new e.Quaternion,pe=new e.Quaternion,me=new e.Euler;class fe{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 e.Euler)}constructor(t,i){this.offsetFromHeadBone=new e.Vector3,this.autoUpdate=!0,this.faceFront=new e.Vector3(0,0,1),this.humanoid=t,this.applier=i,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new e.Quaternion)}getEuler(t){return t.set(e.MathUtils.DEG2RAD*this._pitch,e.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 fe(this.humanoid,this.applier).copy(this)}reset(){this._yaw=0,this._pitch=0,this._needsUpdate=!0}getLookAtWorldPosition(e){const t=this.humanoid.getRawBoneNode("head");return e.copy(this.offsetFromHeadBone).applyMatrix4(t.matrixWorld)}getLookAtWorldQuaternion(e){return ne(this.humanoid.getRawBoneNode("head"),e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(se)<.01)return e.copy(this._restHeadWorldQuaternion).invert();const[t,i]=re(this.faceFront);return me.set(0,.5*Math.PI+t,i,"YZX"),e.setFromEuler(me).premultiply(pe.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(he),this.getFaceFrontQuaternion(ce),e.copy(se).applyQuaternion(he).applyQuaternion(ce).applyEuler(this.getEuler(me))}lookAt(t){const i=de.copy(this._restHeadWorldQuaternion).multiply(U(this.getLookAtWorldQuaternion(he))),n=this.getLookAtWorldPosition(le),r=ue.copy(t).sub(n).applyQuaternion(i).normalize(),[o,s]=re(this.faceFront),[a,l]=re(r),u=oe(a-o),d=oe(s-l);this._yaw=e.MathUtils.RAD2DEG*u,this._pitch=e.MathUtils.RAD2DEG*d,this._needsUpdate=!0}update(e){null!=this.target&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(ae)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}}fe.EULER_ORDER="YXZ";const ge=new e.Vector3(0,0,1),ve=new e.Quaternion,_e=new e.Quaternion,Me=new e.Euler(0,0,0,"YXZ");class xe{constructor(t,i,n,r,o){this.humanoid=t,this.rangeMapHorizontalInner=i,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=r,this.rangeMapVerticalUp=o,this.faceFront=new e.Vector3(0,0,1),this._restQuatLeftEye=new e.Quaternion,this._restQuatRightEye=new e.Quaternion,this._restLeftEyeParentWorldQuat=new e.Quaternion,this._restRightEyeParentWorldQuat=new e.Quaternion;const s=this.humanoid.getRawBoneNode("leftEye"),a=this.humanoid.getRawBoneNode("rightEye");s&&(this._restQuatLeftEye.copy(s.quaternion),ne(s.parent,this._restLeftEyeParentWorldQuat)),a&&(this._restQuatRightEye.copy(a.quaternion),ne(a.parent,this._restRightEyeParentWorldQuat))}applyYawPitch(t,i){const n=this.humanoid.getRawBoneNode("leftEye"),r=this.humanoid.getRawBoneNode("rightEye"),o=this.humanoid.getNormalizedBoneNode("leftEye"),s=this.humanoid.getNormalizedBoneNode("rightEye");n&&(Me.x=i<0?-e.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-i):e.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(i),Me.y=t<0?-e.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(-t):e.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(t),ve.setFromEuler(Me),this._getWorldFaceFrontQuat(_e),o.quaternion.copy(_e).multiply(ve).multiply(_e.invert()),ve.copy(this._restLeftEyeParentWorldQuat),n.quaternion.copy(o.quaternion).multiply(ve).premultiply(ve.invert()).multiply(this._restQuatLeftEye)),r&&(Me.x=i<0?-e.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-i):e.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(i),Me.y=t<0?-e.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(-t):e.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(t),ve.setFromEuler(Me),this._getWorldFaceFrontQuat(_e),s.quaternion.copy(_e).multiply(ve).multiply(_e.invert()),ve.copy(this._restRightEyeParentWorldQuat),r.quaternion.copy(s.quaternion).multiply(ve).premultiply(ve.invert()).multiply(this._restQuatRightEye))}lookAt(t){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");const i=e.MathUtils.RAD2DEG*t.y,n=e.MathUtils.RAD2DEG*t.x;this.applyYawPitch(i,n)}_getWorldFaceFrontQuat(e){if(this.faceFront.distanceToSquared(ge)<.01)return e.identity();const[t,i]=re(this.faceFront);return Me.set(0,.5*Math.PI+t,i,"YZX"),e.setFromEuler(Me)}}xe.type="bone";class ye{constructor(e,t,i,n,r){this.expressions=e,this.rangeMapHorizontalInner=t,this.rangeMapHorizontalOuter=i,this.rangeMapVerticalDown=n,this.rangeMapVerticalUp=r}applyYawPitch(e,t){t<0?(this.expressions.setValue("lookDown",0),this.expressions.setValue("lookUp",this.rangeMapVerticalUp.map(-t))):(this.expressions.setValue("lookUp",0),this.expressions.setValue("lookDown",this.rangeMapVerticalDown.map(t))),e<0?(this.expressions.setValue("lookLeft",0),this.expressions.setValue("lookRight",this.rangeMapHorizontalOuter.map(-e))):(this.expressions.setValue("lookRight",0),this.expressions.setValue("lookLeft",this.rangeMapHorizontalOuter.map(e)))}lookAt(t){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");const i=e.MathUtils.RAD2DEG*t.y,n=e.MathUtils.RAD2DEG*t.x;this.applyYawPitch(i,n)}}ye.type="expression";class Te{constructor(e,t){this.inputMaxValue=e,this.outputScale=t}map(e){return this.outputScale*u(e/this.inputMaxValue)}}const Re=new Set(["1.0","1.0-beta"]);class Ee{get name(){return"VRMLookAtLoaderPlugin"}constructor(e,t){this.parser=e,this.helperRoot=null==t?void 0:t.helperRoot}afterRoot(e){return n(this,void 0,void 0,(function*(){const t=e.userData.vrmHumanoid;if(null===t)return;if(void 0===t)throw new Error("VRMLookAtLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first");const i=e.userData.vrmExpressionManager;if(null!==i){if(void 0===i)throw new Error("VRMLookAtLoaderPlugin: vrmExpressionManager is undefined. VRMExpressionLoaderPlugin have to be used first");e.userData.vrmLookAt=yield this._import(e,t,i)}}))}_import(e,t,i){return n(this,void 0,void 0,(function*(){if(null==t||null==i)return null;const n=yield this._v1Import(e,t,i);if(n)return n;const r=yield this._v0Import(e,t,i);return r||null}))}_v1Import(e,t,i){var r,o,s;return n(this,void 0,void 0,(function*(){const e=this.parser.json;if(!(-1!==(null===(r=e.extensionsUsed)||void 0===r?void 0:r.indexOf("VRMC_vrm"))))return null;const n=null===(o=e.extensions)||void 0===o?void 0:o.VRMC_vrm;if(!n)return null;const a=n.specVersion;if(!Re.has(a))return console.warn(`VRMLookAtLoaderPlugin: Unknown VRMC_vrm specVersion "${a}"`),null;const l=n.lookAt;if(!l)return null;const u="expression"===l.type?1:10,d=this._v1ImportRangeMap(l.rangeMapHorizontalInner,u),h=this._v1ImportRangeMap(l.rangeMapHorizontalOuter,u),c=this._v1ImportRangeMap(l.rangeMapVerticalDown,u),p=this._v1ImportRangeMap(l.rangeMapVerticalUp,u);let m;m="expression"===l.type?new ye(i,d,h,c,p):new xe(t,d,h,c,p);const f=this._importLookAt(t,m);return f.offsetFromHeadBone.fromArray(null!==(s=l.offsetFromHeadBone)&&void 0!==s?s:[0,.06,0]),f}))}_v1ImportRangeMap(e,t){var i,n;let r=null!==(i=null==e?void 0:e.inputMaxValue)&&void 0!==i?i:90;const o=null!==(n=null==e?void 0:e.outputScale)&&void 0!==n?n:t;return r<.01&&(console.warn("VRMLookAtLoaderPlugin: inputMaxValue of a range map is too small. Consider reviewing the range map!"),r=.01),new Te(r,o)}_v0Import(e,t,i){var r,o,s,a;return n(this,void 0,void 0,(function*(){const e=this.parser.json,n=null===(r=e.extensions)||void 0===r?void 0:r.VRM;if(!n)return null;const l=n.firstPerson;if(!l)return null;const u="BlendShape"===l.lookAtTypeName?1:10,d=this._v0ImportDegreeMap(l.lookAtHorizontalInner,u),h=this._v0ImportDegreeMap(l.lookAtHorizontalOuter,u),c=this._v0ImportDegreeMap(l.lookAtVerticalDown,u),p=this._v0ImportDegreeMap(l.lookAtVerticalUp,u);let m;m="BlendShape"===l.lookAtTypeName?new ye(i,d,h,c,p):new xe(t,d,h,c,p);const f=this._importLookAt(t,m);return l.firstPersonBoneOffset?f.offsetFromHeadBone.set(null!==(o=l.firstPersonBoneOffset.x)&&void 0!==o?o:0,null!==(s=l.firstPersonBoneOffset.y)&&void 0!==s?s:.06,-(null!==(a=l.firstPersonBoneOffset.z)&&void 0!==a?a:0)):f.offsetFromHeadBone.set(0,.06,0),f.faceFront.set(0,0,-1),m instanceof xe&&m.faceFront.set(0,0,-1),f}))}_v0ImportDegreeMap(e,t){var i,n;const r=null==e?void 0:e.curve;"[0,0,0,1,1,1,1,0]"!==JSON.stringify(r)&&console.warn("Curves of LookAtDegreeMap defined in VRM 0.0 are not supported");let o=null!==(i=null==e?void 0:e.xRange)&&void 0!==i?i:90;const s=null!==(n=null==e?void 0:e.yRange)&&void 0!==n?n:t;return o<.01&&(console.warn("VRMLookAtLoaderPlugin: xRange of a degree map is too small. Consider reviewing the degree map!"),o=.01),new Te(o,s)}_importLookAt(e,t){const i=new fe(e,t);if(this.helperRoot){const e=new ee(i);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return i}}const we={Bone:"bone",Expression:"expression"};const Pe=new Set(["1.0","1.0-beta"]);class Se{get name(){return"VRMMetaLoaderPlugin"}constructor(e,t){var i,n,r;this.parser=e,this.needThumbnailImage=null===(i=null==t?void 0:t.needThumbnailImage)||void 0===i||i,this.acceptLicenseUrls=null!==(n=null==t?void 0:t.acceptLicenseUrls)&&void 0!==n?n:["https://vrm.dev/licenses/1.0/"],this.acceptV0Meta=null===(r=null==t?void 0:t.acceptV0Meta)||void 0===r||r}afterRoot(e){return n(this,void 0,void 0,(function*(){e.userData.vrmMeta=yield this._import(e)}))}_import(e){return n(this,void 0,void 0,(function*(){const t=yield this._v1Import(e);if(null!=t)return t;const i=yield this._v0Import(e);return null!=i?i:null}))}_v1Import(e){var t,i,r;return n(this,void 0,void 0,(function*(){const e=this.parser.json;if(!(-1!==(null===(t=e.extensionsUsed)||void 0===t?void 0:t.indexOf("VRMC_vrm"))))return null;const n=null===(i=e.extensions)||void 0===i?void 0:i.VRMC_vrm;if(null==n)return null;const o=n.specVersion;if(!Pe.has(o))return console.warn(`VRMMetaLoaderPlugin: Unknown VRMC_vrm specVersion "${o}"`),null;const s=n.meta;if(!s)return null;const a=s.licenseUrl;if(!new Set(this.acceptLicenseUrls).has(a))throw new Error(`VRMMetaLoaderPlugin: The license url "${a}" is not accepted`);let l;retu