UNPKG

@pixiv/three-vrm

Version:

VRM file loader for three.js.

10 lines 148 kB
/*! (c) 2019-2024 pixiv Inc. - https://github.com/pixiv/three-vrm/blob/release/LICENSE */ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three")):"function"==typeof define&&define.amd?define(["exports","three"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).THREE_VRM={},e.THREE)}(this,(function(e,t){"use strict";function i(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var n=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var n=i(t); /*! * @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 r extends n.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 o(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 s(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 a(e,t){return o(this,void 0,void 0,(function*(){const i=yield e.parser.getDependency("node",t);return s(e,t,i)}))}function l(e){return o(this,void 0,void 0,(function*(){const t=yield e.parser.getDependencies("node"),i=new Map;return t.forEach(((t,n)=>{const r=s(e,n,t);null!=r&&i.set(n,r)})),i}))}function u(e,t){var i,r;let o=null;if(parseInt(n.REVISION,10)>=133)o=null!==(r=null===(i=e.associations.get(t))||void 0===i?void 0:i.materials)&&void 0!==r?r:null;else{const i=e.associations.get(t);"materials"===(null==i?void 0:i.type)&&(o=i.index)}return o}"function"==typeof SuppressedError&&SuppressedError;const d={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 h(e){return Math.max(Math.min(e,1),0)}class c{get expressions(){return this._expressions.concat()}get expressionMap(){return Object.assign({},this._expressionMap)}get presetExpressionMap(){const e={},t=new Set(Object.values(d));return Object.entries(this._expressionMap).forEach((([i,n])=>{t.has(i)&&(e[i]=n)})),e}get customExpressionMap(){const e={},t=new Set(Object.values(d));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 c).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=h(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 p={Color:"color",EmissionColor:"emissionColor",ShadeColor:"shadeColor",MatcapColor:"matcapColor",RimColor:"rimColor",OutlineColor:"outlineColor"},m={_Color:p.Color,_EmissionColor:p.EmissionColor,_ShadeColor:p.ShadeColor,_RimColor:p.RimColor,_OutlineColor:p.OutlineColor},f=new n.Color;class g{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(f.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 e,t,i;const{material:r,type:o,targetValue:s}=this,a=this._getPropertyNameMap(),l=null!==(t=null===(e=null==a?void 0:a[o])||void 0===e?void 0:e[0])&&void 0!==t?t:null;if(null==l)return console.warn(`Tried to add a material color bind to the material ${null!==(i=r.name)&&void 0!==i?i:"(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 n.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(g._propertyNameMapMap).find((([e])=>!0===this.material[e])))||void 0===e?void 0:e[1])&&void 0!==t?t:null}}g._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 v{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 _=new n.Vector2;class M{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(M._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(_.copy(t.deltaOffset).multiplyScalar(e)),i.repeat.add(_.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))}))}}M._propertyNamesMap={isMeshStandardMaterial:["map","emissiveMap","bumpMap","normalMap","displacementMap","roughnessMap","metalnessMap","alphaMap"],isMeshBasicMaterial:["map","specularMap","alphaMap"],isMToonMaterial:["map","normalMap","emissiveMap","shadeMultiplyTexture","rimMultiplyTexture","outlineWidthMultiplyTexture","uvAnimationMaskTexture"]};const x=new Set(["1.0","1.0-beta"]);class y{get name(){return"VRMExpressionLoaderPlugin"}constructor(e){this.parser=e}afterRoot(e){return o(this,void 0,void 0,(function*(){e.userData.vrmExpressionManager=yield this._import(e)}))}_import(e){return o(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 o(this,void 0,void 0,(function*(){const s=this.parser.json;if(!(-1!==(null===(t=s.extensionsUsed)||void 0===t?void 0:t.indexOf("VRMC_vrm"))))return null;const l=null===(i=s.extensions)||void 0===i?void 0:i.VRMC_vrm;if(!l)return null;const h=l.specVersion;if(!x.has(h))return console.warn(`VRMExpressionLoaderPlugin: Unknown VRMC_vrm specVersion "${h}"`),null;const p=l.expressions;if(!p)return null;const m=new Set(Object.values(d)),f=new Map;null!=p.preset&&Object.entries(p.preset).forEach((([e,t])=>{null!=t&&(m.has(e)?f.set(e,t):console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${e}" detected. Ignoring the expression`))})),null!=p.custom&&Object.entries(p.custom).forEach((([e,t])=>{m.has(e)?console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${e}". Ignoring the expression`):f.set(e,t)}));const _=new c;return yield Promise.all(Array.from(f.entries()).map((([t,i])=>o(this,void 0,void 0,(function*(){var s,l,d,h,c,p,m;const f=new r(t);if(e.scene.add(f),f.isBinary=null!==(s=i.isBinary)&&void 0!==s&&s,f.overrideBlink=null!==(l=i.overrideBlink)&&void 0!==l?l:"none",f.overrideLookAt=null!==(d=i.overrideLookAt)&&void 0!==d?d:"none",f.overrideMouth=null!==(h=i.overrideMouth)&&void 0!==h?h:"none",null===(c=i.morphTargetBinds)||void 0===c||c.forEach((t=>o(this,void 0,void 0,(function*(){var n;if(void 0===t.node||void 0===t.index)return;const r=yield a(e,t.node),o=t.index;r.every((e=>Array.isArray(e.morphTargetInfluences)&&o<e.morphTargetInfluences.length))?f.addBind(new v({primitives:r,index:o,weight:null!==(n=t.weight)&&void 0!==n?n:1})):console.warn(`VRMExpressionLoaderPlugin: ${i.name} attempts to index morph #${o} but not found.`)})))),i.materialColorBinds||i.textureTransformBinds){const t=[];e.scene.traverse((e=>{const i=e.material;i&&t.push(i)})),null===(p=i.materialColorBinds)||void 0===p||p.forEach((e=>o(this,void 0,void 0,(function*(){t.filter((t=>{const i=u(this.parser,t);return e.material===i})).forEach((t=>{f.addBind(new g({material:t,type:e.type,targetValue:(new n.Color).fromArray(e.targetValue),targetAlpha:e.targetValue[3]}))}))})))),null===(m=i.textureTransformBinds)||void 0===m||m.forEach((e=>o(this,void 0,void 0,(function*(){t.filter((t=>{const i=u(this.parser,t);return e.material===i})).forEach((t=>{var i,r;f.addBind(new M({material:t,offset:(new n.Vector2).fromArray(null!==(i=e.offset)&&void 0!==i?i:[0,0]),scale:(new n.Vector2).fromArray(null!==(r=e.scale)&&void 0!==r?r:[1,1])}))}))}))))}_.registerExpression(f)}))))),_}))}_v0Import(e){var t;return o(this,void 0,void 0,(function*(){const i=this.parser.json,s=null===(t=i.extensions)||void 0===t?void 0:t.VRM;if(!s)return null;const l=s.blendShapeMaster;if(!l)return null;const u=new c,d=l.blendShapeGroups;if(!d)return u;const h=new Set;return yield Promise.all(d.map((t=>o(this,void 0,void 0,(function*(){var s;const l=t.presetName,d=null!=l&&y.v0v1PresetNameMap[l]||null,c=null!=d?d:t.name;if(null==c)return void console.warn("VRMExpressionLoaderPlugin: One of custom expressions has no name. Ignoring the expression");if(h.has(c))return void console.warn(`VRMExpressionLoaderPlugin: An expression preset ${l} has duplicated entries. Ignoring the expression`);h.add(c);const p=new r(c);e.scene.add(p),p.isBinary=null!==(s=t.isBinary)&&void 0!==s&&s,t.binds&&t.binds.forEach((n=>o(this,void 0,void 0,(function*(){var r;if(void 0===n.mesh||void 0===n.index)return;const s=[];null===(r=i.nodes)||void 0===r||r.forEach(((e,t)=>{e.mesh===n.mesh&&s.push(t)}));const l=n.index;yield Promise.all(s.map((i=>o(this,void 0,void 0,(function*(){var r;const o=yield a(e,i);o.every((e=>Array.isArray(e.morphTargetInfluences)&&l<e.morphTargetInfluences.length))?p.addBind(new v({primitives:o,index:l,weight:.01*(null!==(r=n.weight)&&void 0!==r?r:100)})):console.warn(`VRMExpressionLoaderPlugin: ${t.name} attempts to index ${l}th morph but not found.`)})))))}))));const f=t.materialValues;f&&0!==f.length&&f.forEach((t=>{if(void 0===t.materialName||void 0===t.propertyName||void 0===t.targetValue)return;const i=[];e.scene.traverse((e=>{if(e.material){const n=e.material;Array.isArray(n)?i.push(...n.filter((e=>(e.name===t.materialName||e.name===t.materialName+" (Outline)")&&-1===i.indexOf(e)))):n.name===t.materialName&&-1===i.indexOf(n)&&i.push(n)}}));const r=t.propertyName;i.forEach((e=>{if("_MainTex_ST"===r){const i=new n.Vector2(t.targetValue[0],t.targetValue[1]),r=new n.Vector2(t.targetValue[2],t.targetValue[3]);return r.y=1-r.y-i.y,void p.addBind(new M({material:e,scale:i,offset:r}))}const i=m[r];i?p.addBind(new g({material:e,type:i,targetValue:(new n.Color).fromArray(t.targetValue),targetAlpha:t.targetValue[3]})):console.warn(r+" is not supported")}))})),u.registerExpression(p)}))))),u}))}}y.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"};class R{constructor(e,t){this._firstPersonOnlyLayer=R.DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=R.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 R(this.humanoid,this.meshAnnotations).copy(this)}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}setup({firstPersonOnlyLayer:e=R.DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:t=R.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(e,t){const i=new n.SkinnedMesh(e.geometry.clone(),e.material);i.name=`${e.name}(erase)`,i.frustumCulled=e.frustumCulled,i.layers.set(this._firstPersonOnlyLayer);const r=i.geometry,o=r.getAttribute("skinIndex"),s=o instanceof n.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 n.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,t),m=[];for(let e=0;e<p;e++)m[e]=c[e];return r.setIndex(m),e.onBeforeRender&&(i.onBeforeRender=e.onBeforeRender),i.bind(new n.Skeleton(e.skeleton.bones,e.skeleton.boneInverses),new n.Matrix4),i}_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(e){if("Group"===e.type)if(e.layers.set(this._thirdPersonOnlyLayer),this._isEraseTarget(e))e.traverse((e=>e.layers.set(this._thirdPersonOnlyLayer)));else{const t=new n.Group;t.name=`_headless_${e.name}`,t.layers.set(this._firstPersonOnlyLayer),e.parent.add(t),e.children.filter((e=>"SkinnedMesh"===e.type)).forEach((e=>{const i=e;this._createHeadlessModelForSkinnedMesh(t,i)}))}else if("SkinnedMesh"===e.type){const t=e;this._createHeadlessModelForSkinnedMesh(e.parent,t)}else this._isEraseTarget(e)&&(e.layers.set(this._thirdPersonOnlyLayer),e.traverse((e=>e.layers.set(this._thirdPersonOnlyLayer))))}_isEraseTarget(e){return e===this.humanoid.getRawBoneNode("head")||!!e.parent&&this._isEraseTarget(e.parent)}}R.DEFAULT_FIRSTPERSON_ONLY_LAYER=9,R.DEFAULT_THIRDPERSON_ONLY_LAYER=10;const T=new Set(["1.0","1.0-beta"]);class E{get name(){return"VRMFirstPersonLoaderPlugin"}constructor(e){this.parser=e}afterRoot(e){return o(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 o(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,n;return o(this,void 0,void 0,(function*(){const r=this.parser.json;if(!(-1!==(null===(i=r.extensionsUsed)||void 0===i?void 0:i.indexOf("VRMC_vrm"))))return null;const o=null===(n=r.extensions)||void 0===n?void 0:n.VRMC_vrm;if(!o)return null;const s=o.specVersion;if(!T.has(s))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${s}"`),null;const a=o.firstPerson;if(!a)return null;const u=[],d=yield l(e);return Array.from(d.entries()).forEach((([e,t])=>{var i;const n=a.meshAnnotations?a.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 R(t,u)}))}_v0Import(e,t){var i;return o(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 s=[],a=yield l(e);return Array.from(a.entries()).forEach((([e,t])=>{const i=n.nodes[e],r=o.meshAnnotations?o.meshAnnotations.find((e=>e.mesh===i.mesh)):void 0;s.push({meshes:t,type:this._convertV0FlagToV1Type(null==r?void 0:r.firstPersonFlag)})})),new R(t,s)}))}_convertV0FlagToV1Type(e){return"FirstPersonOnly"===e?"firstPersonOnly":"ThirdPersonOnly"===e?"thirdPersonOnly":"Auto"===e?"auto":"both"}}const w=new n.Vector3,P=new n.Vector3,S=new n.Quaternion;class L extends n.Group{constructor(e){super(),this.vrmHumanoid=e,this._boneAxesMap=new Map,Object.values(e.humanBones).forEach((e=>{const t=new n.AxesHelper(1);t.matrixAutoUpdate=!1,t.material.depthTest=!1,t.material.depthWrite=!1,this.add(t),this._boneAxesMap.set(e,t)}))}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 A=["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: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 b(e){return e.invert?e.invert():e.inverse(),e}const V=new n.Vector3,U=new n.Quaternion;class O{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&&(V.copy(n.position),U.copy(n.quaternion),e[i]={position:V.toArray(),rotation:U.toArray()})})),e}getPose(){const e={};return Object.keys(this.humanBones).forEach((t=>{const i=t,n=this.getBoneNode(i);if(!n)return;V.set(0,0,0),U.identity();const r=this.restPose[i];(null==r?void 0:r.position)&&V.fromArray(r.position).negate(),(null==r?void 0:r.rotation)&&b(U.fromArray(r.rotation)),V.add(n.position),U.premultiply(n.quaternion),e[i]={position:V.toArray(),rotation:U.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(V.fromArray(r.position))),(null==t?void 0:t.rotation)&&(n.quaternion.fromArray(t.rotation),r.rotation&&n.quaternion.multiply(U.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 N=new n.Vector3,C=new n.Quaternion,D=new n.Vector3;class F extends O{static _setupTransforms(e){const t=new n.Object3D;t.name="VRMHumanoidRig";const i={},r={},o={};A.forEach((t=>{var s;const a=e.getBoneNode(t);if(a){const e=new n.Vector3,l=new n.Quaternion;a.updateWorldMatrix(!0,!1),a.matrixWorld.decompose(e,l,N),i[t]=e,r[t]=a.quaternion.clone();const u=new n.Quaternion;null===(s=a.parent)||void 0===s||s.matrixWorld.decompose(N,u,N),o[t]=u}}));const s={};return A.forEach((r=>{var o;const a=e.getBoneNode(r);if(a){const e=i[r];let l,u=r;for(;null==l&&(u=I[u],null!=u);)l=i[u];const d=new n.Object3D;d.name="Normalized_"+a.name;(u?null===(o=s[u])||void 0===o?void 0:o.node:t).add(d),d.position.copy(e),l&&d.position.sub(l),s[r]={node:d}}})),{rigBones:s,root:t,parentWorldRotations:o,boneRotations:r}}constructor(e){const{rigBones:t,root:i,parentWorldRotations:n,boneRotations:r}=F._setupTransforms(e);super(t),this.original=e,this.root=i,this._parentWorldRotations=n,this._boneRotations=r}update(){A.forEach((e=>{const t=this.original.getBoneNode(e);if(null!=t){const i=this.getBoneNode(e),n=this._parentWorldRotations[e],r=C.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(D);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 O(e),this._normalizedHumanBones=new F(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new O(e.humanBones),this._normalizedHumanBones=new F(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 H={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"},k=new Set(["1.0","1.0-beta"]),W={leftThumbProximal:"leftThumbMetacarpal",leftThumbIntermediate:"leftThumbProximal",rightThumbProximal:"rightThumbMetacarpal",rightThumbIntermediate:"rightThumbProximal"};class z{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 o(this,void 0,void 0,(function*(){e.userData.vrmHumanoid=yield this._import(e)}))}_import(e){return o(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 o(this,void 0,void 0,(function*(){const n=this.parser.json;if(!(-1!==(null===(t=n.extensionsUsed)||void 0===t?void 0:t.indexOf("VRMC_vrm"))))return null;const r=null===(i=n.extensions)||void 0===i?void 0:i.VRMC_vrm;if(!r)return null;const s=r.specVersion;if(!k.has(s))return console.warn(`VRMHumanoidLoaderPlugin: Unknown VRMC_vrm specVersion "${s}"`),null;const a=r.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])=>o(this,void 0,void 0,(function*(){let i=e;const n=t.node;if(l){const e=W[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 L(d);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return d}))}_v0Import(e){var t;return o(this,void 0,void 0,(function*(){const i=this.parser.json,n=null===(t=i.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const r=n.humanoid;if(!r)return null;const s={};null!=r.humanBones&&(yield Promise.all(r.humanBones.map((e=>o(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=W[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 L(a);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return a}))}_ensureRequiredBonesExist(e){const t=Object.values(H).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 G extends n.BufferGeometry{constructor(){super(),this._currentTheta=0,this._currentRadius=0,this.theta=0,this.radius=0,this._currentTheta=0,this._currentRadius=0,this._attrPos=new n.BufferAttribute(new Float32Array(195),3),this.setAttribute("position",this._attrPos),this._attrIndex=new n.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 n.BufferGeometry{constructor(){super(),this.radius=0,this._currentRadius=0,this.tail=new n.Vector3,this._currentTail=new n.Vector3,this._attrPos=new n.BufferAttribute(new Float32Array(294),3),this.setAttribute("position",this._attrPos),this._attrIndex=new n.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 Q=new n.Quaternion,X=new n.Quaternion,Y=new n.Vector3,q=new n.Vector3,$=Math.sqrt(2)/2,Z=new n.Quaternion(0,0,-$,$),J=new n.Vector3(0,1,0);class K extends n.Group{constructor(e){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=e;{const e=new G;e.radius=.5;const t=new n.MeshBasicMaterial({color:65280,transparent:!0,opacity:.5,side:n.DoubleSide,depthTest:!1,depthWrite:!1});this._meshPitch=new n.Mesh(e,t),this.add(this._meshPitch)}{const e=new G;e.radius=.5;const t=new n.MeshBasicMaterial({color:16711680,transparent:!0,opacity:.5,side:n.DoubleSide,depthTest:!1,depthWrite:!1});this._meshYaw=new n.Mesh(e,t),this.add(this._meshYaw)}{const e=new j;e.radius=.1;const t=new n.LineBasicMaterial({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new n.LineSegments(e,t),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(e){const t=n.MathUtils.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=t,this._meshYaw.geometry.update();const i=n.MathUtils.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=i,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition(Y),this.vrmLookAt.getLookAtWorldQuaternion(Q),Q.multiply(this.vrmLookAt.getFaceFrontQuaternion(X)),this._meshYaw.position.copy(Y),this._meshYaw.quaternion.copy(Q),this._meshPitch.position.copy(Y),this._meshPitch.quaternion.copy(Q),this._meshPitch.quaternion.multiply(X.setFromAxisAngle(J,t)),this._meshPitch.quaternion.multiply(Z);const{target:r,autoUpdate:o}=this.vrmLookAt;null!=r&&o&&(r.getWorldPosition(q).sub(Y),this._lineTarget.geometry.tail.copy(q),this._lineTarget.geometry.update(),this._lineTarget.position.copy(Y)),super.updateMatrixWorld(e)}}const ee=new n.Vector3,te=new n.Vector3;function ie(e,t){return e.matrixWorld.decompose(ee,t,te),t}function ne(e){return[Math.atan2(-e.z,e.x),Math.atan2(e.y,Math.sqrt(e.x*e.x+e.z*e.z))]}function re(e){const t=Math.round(e/2/Math.PI);return e-2*Math.PI*t}const oe=new n.Vector3(0,0,1),se=new n.Vector3,ae=new n.Vector3,le=new n.Vector3,ue=new n.Quaternion,de=new n.Quaternion,he=new n.Quaternion,ce=new n.Quaternion,pe=new n.Euler;class me{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 n.Euler)}constructor(e,t){this.offsetFromHeadBone=new n.Vector3,this.autoUpdate=!0,this.faceFront=new n.Vector3(0,0,1),this.humanoid=e,this.applier=t,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new n.Quaternion)}getEuler(e){return e.set(n.MathUtils.DEG2RAD*this._pitch,n.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 me(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 ie(this.humanoid.getRawBoneNode("head"),e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(oe)<.01)return e.copy(this._restHeadWorldQuaternion).invert();const[t,i]=ne(this.faceFront);return pe.set(0,.5*Math.PI+t,i,"YZX"),e.setFromEuler(pe).premultiply(ce.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(de),this.getFaceFrontQuaternion(he),e.copy(oe).applyQuaternion(de).applyQuaternion(he).applyEuler(this.getEuler(pe))}lookAt(e){const t=ue.copy(this._restHeadWorldQuaternion).multiply(b(this.getLookAtWorldQuaternion(de))),i=this.getLookAtWorldPosition(ae),r=le.copy(e).sub(i).applyQuaternion(t).normalize(),[o,s]=ne(this.faceFront),[a,l]=ne(r),u=re(a-o),d=re(s-l);this._yaw=n.MathUtils.RAD2DEG*u,this._pitch=n.MathUtils.RAD2DEG*d,this._needsUpdate=!0}update(e){null!=this.target&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(se)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}}me.EULER_ORDER="YXZ";const fe=new n.Vector3(0,0,1),ge=new n.Quaternion,ve=new n.Quaternion,_e=new n.Euler(0,0,0,"YXZ");class Me{constructor(e,t,i,r,o){this.humanoid=e,this.rangeMapHorizontalInner=t,this.rangeMapHorizontalOuter=i,this.rangeMapVerticalDown=r,this.rangeMapVerticalUp=o,this.faceFront=new n.Vector3(0,0,1),this._restQuatLeftEye=new n.Quaternion,this._restQuatRightEye=new n.Quaternion,this._restLeftEyeParentWorldQuat=new n.Quaternion,this._restRightEyeParentWorldQuat=new n.Quaternion;const s=this.humanoid.getRawBoneNode("leftEye"),a=this.humanoid.getRawBoneNode("rightEye");s&&(this._restQuatLeftEye.copy(s.quaternion),ie(s.parent,this._restLeftEyeParentWorldQuat)),a&&(this._restQuatRightEye.copy(a.quaternion),ie(a.parent,this._restRightEyeParentWorldQuat))}applyYawPitch(e,t){const i=this.humanoid.getRawBoneNode("leftEye"),r=this.humanoid.getRawBoneNode("rightEye"),o=this.humanoid.getNormalizedBoneNode("leftEye"),s=this.humanoid.getNormalizedBoneNode("rightEye");i&&(_e.x=t<0?-n.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-t):n.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(t),_e.y=e<0?-n.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(-e):n.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(e),ge.setFromEuler(_e),this._getWorldFaceFrontQuat(ve),o.quaternion.copy(ve).multiply(ge).multiply(ve.invert()),ge.copy(this._restLeftEyeParentWorldQuat),i.quaternion.copy(o.quaternion).multiply(ge).premultiply(ge.invert()).multiply(this._restQuatLeftEye)),r&&(_e.x=t<0?-n.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-t):n.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(t),_e.y=e<0?-n.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(-e):n.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(e),ge.setFromEuler(_e),this._getWorldFaceFrontQuat(ve),s.quaternion.copy(ve).multiply(ge).multiply(ve.invert()),ge.copy(this._restRightEyeParentWorldQuat),r.quaternion.copy(s.quaternion).multiply(ge).premultiply(ge.invert()).multiply(this._restQuatRightEye))}lookAt(e){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");const t=n.MathUtils.RAD2DEG*e.y,i=n.MathUtils.RAD2DEG*e.x;this.applyYawPitch(t,i)}_getWorldFaceFrontQuat(e){if(this.faceFront.distanceToSquared(fe)<.01)return e.identity();const[t,i]=ne(this.faceFront);return _e.set(0,.5*Math.PI+t,i,"YZX"),e.setFromEuler(_e)}}Me.type="bone";class xe{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(e){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");const t=n.MathUtils.RAD2DEG*e.y,i=n.MathUtils.RAD2DEG*e.x;this.applyYawPitch(t,i)}}xe.type="expression";class ye{constructor(e,t){this.inputMaxValue=e,this.outputScale=t}map(e){return this.outputScale*h(e/this.inputMaxValue)}}const Re=new Set(["1.0","1.0-beta"]),Te=.01;class Ee{get name(){return"VRMLookAtLoaderPlugin"}constructor(e,t){this.parser=e,this.helperRoot=null==t?void 0:t.helperRoot}afterRoot(e){return o(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 o(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 n,r,s;return o(this,void 0,void 0,(function*(){const e=this.parser.json;if(!(-1!==(null===(n=e.extensionsUsed)||void 0===n?void 0:n.indexOf("VRMC_vrm"))))return null;const o=null===(r=e.extensions)||void 0===r?void 0:r.VRMC_vrm;if(!o)return null;const a=o.specVersion;if(!Re.has(a))return console.warn(`VRMLookAtLoaderPlugin: Unknown VRMC_vrm specVersion "${a}"`),null;const l=o.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 xe(i,d,h,c,p):new Me(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<Te&&(console.warn("VRMLookAtLoaderPlugin: inputMaxValue of a range map is too small. Consider reviewing the range map!"),r=Te),new ye(r,o)}_v0Import(e,t,i){var n,r,s,a;return o(this,void 0,void 0,(function*(){const e=this.parser.json,o=null===(n=e.extensions)||void 0===n?void 0:n.VRM;if(!o)return null;const l=o.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 xe(i,d,h,c,p):new Me(t,d,h,c,p);const f=this._importLookAt(t,m);return l.firstPersonBoneOffset?f.offsetFromHeadBone.set(null!==(r=l.firstPersonBoneOffset.x)&&void 0!==r?r: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 Me&&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<Te&&(console.warn("VRMLookAtLoaderPlugin: xRange of a degree map is too small. Consider reviewing the degree map!"),o=Te),new ye(o,s)}_importLookAt(e,t){const i=new me(e,t);if(this.helperRoot){const e=new K(i);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return i}}const we=new Set(["1.0","1.0-beta"]);class Pe{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 o(this,void 0,void 0,(function*(){e.userData.vrmMeta=yield this._import(e)}))}_import(e){return o(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,n;return o(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 r=null===(i=e.extensions)||void 0===i?void 0:i.VRMC_vrm;if(null==r)return null;const o=r.specVersion;if(!we.has(o))return console.warn(`VRMMetaLoaderPlugin: Unknown VRMC_vrm specVersion "${o}"`),null;const s=r.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;return this.needThumbnailImage&&null!=s.thumbnailImage&&(l=null!==(n=yield this._extractGLTFImage(s.thumbnailImage))&&void 0!==n?n:void 0),{metaVersion:"1",name:s.name,version:s.version,authors:s.authors,copyrightInformation:s.copyrightInformation,contactInformation:s.contactInformation,references:s.references,thirdPartyLicenses:s.thirdPartyLicenses,thumbnailImage:l,licenseUrl:s.licenseUrl,avatarPermission:s.avatarPermission,allowExcessivelyViolentUsage:s.allowExcessivelyViolentUsage,allowExcessivelySexualUsage:s.allowExcessivelySexualUsage,commercialUsage:s.commercialUsage,allowPoliticalOrReligiousUsage:s.allowPoliticalOrReligiousUsage,allowAntisocialOrHateUsage:s.allowAntisocialOrHateUsage,creditNotation:s.creditNotation,allowRedistribution:s.allowRedistribution,modification:s.modification,otherLicenseUrl:s.otherLicenseUrl}}))}_v0Import(e){var t;return o(this,void 0,void 0,(function*(){const e=this.parser.json,i=null===(t=e.extensions)||void 0===t?void 0:t.VRM;if(!i)return null;const n=i.meta;if(!n)return null;if(!this.acceptV0Meta)throw new Error("VRMMetaLoaderPlugin: Attempted to load VRM0.0 meta but acceptV0Meta is false");let r;return this.needThumbnailImage&&null!=n.texture&&-1!==n.texture&&(r=yield this.parser.getDependency("texture",n.texture)),{metaVersion:"0",allowedUserName:n.allowedUserName,author:n.author,commercialUssageName:n.commercialUssageName,contactInformation:n.contactInformation,lice