@pixiv/three-vrm 1.0.2 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/lib/three-vrm.js +29 -29
- package/lib/three-vrm.min.js +19 -117
- package/lib/three-vrm.module.js +25 -23
- package/lib/three-vrm.module.min.js +19 -117
- package/package.json +13 -13
|
@@ -1,152 +1,54 @@
|
|
|
1
|
-
/*! (c) 2019-
|
|
1
|
+
/*! (c) 2019-2022 pixiv Inc. - https://github.com/pixiv/three-vrm/blob/release/LICENSE */
|
|
2
2
|
import*as e from"three";import{BufferAttribute as t}from"three";
|
|
3
3
|
/*!
|
|
4
|
-
* @pixiv/three-vrm-core v1.0.
|
|
4
|
+
* @pixiv/three-vrm-core v1.0.3
|
|
5
5
|
* The implementation of core features of VRM, for @pixiv/three-vrm
|
|
6
6
|
*
|
|
7
|
-
* Copyright (c) 2020-
|
|
7
|
+
* Copyright (c) 2020-2022 pixiv Inc.
|
|
8
8
|
* @pixiv/three-vrm-core is distributed under MIT License
|
|
9
9
|
* https://github.com/pixiv/three-vrm/blob/release/LICENSE
|
|
10
10
|
*/
|
|
11
|
-
class i extends e.Object3D{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}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}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()))}}
|
|
12
|
-
/*! *****************************************************************************
|
|
13
|
-
Copyright (c) Microsoft Corporation.
|
|
14
|
-
|
|
15
|
-
Permission to use, copy, modify, and/or distribute this software for any
|
|
16
|
-
purpose with or without fee is hereby granted.
|
|
17
|
-
|
|
18
|
-
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
19
|
-
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
20
|
-
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
21
|
-
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
22
|
-
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
23
|
-
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
24
|
-
PERFORMANCE OF THIS SOFTWARE.
|
|
25
|
-
***************************************************************************** */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}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{constructor(){this.blinkExpressionNames=["blink","blinkLeft","blinkRight"],this.lookAtExpressionNames=["lookLeft","lookRight","lookUp","lookDown"],this.mouthExpressionNames=["aa","ee","ih","oh","ou"],this._expressions=[],this._expressionMap={}}get expressions(){return this._expressions.concat()}get expressionMap(){return Object.assign({},this._expressionMap)}get presetExpressionMap(){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}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:t,type:i,targetValue:n}){var r,o,s;this.material=t,this.type=i,this.targetValue=n;const a=null===(r=Object.entries(m._propertyNameMapMap).find((([e])=>!0===t[e])))||void 0===r?void 0:r[1],l=null!==(o=null==a?void 0:a[i])&&void 0!==o?o:null;if(null==l)console.warn(`Tried to add a material color bind to the material ${null!==(s=t.name)&&void 0!==s?s:"(no name)"}, the type ${i} but the material or the type is not supported.`),this._state=null;else{const i=t[l].clone(),r=new e.Color(n.r-i.r,n.g-i.g,n.b-i.b);this._state={propertyName:l,initialValue:i,deltaValue:r}}}applyWeight(e){if(null==this._state)return;const{propertyName:t,deltaValue:i}=this._state,n=this.material[t];void 0!==n&&(n.add(p.copy(i).multiplyScalar(e)),"boolean"==typeof this.material.shouldApplyUniforms&&(this.material.shouldApplyUniforms=!0))}clearAppliedWeight(){if(null==this._state)return;const{propertyName:e,initialValue:t}=this._state,i=this.material[e];void 0!==i&&(i.copy(t),"boolean"==typeof this.material.shouldApplyUniforms&&(this.material.shouldApplyUniforms=!0))}}m._propertyNameMapMap={isMeshStandardMaterial:{color:"color",emissionColor:"emissive"},isMeshBasicMaterial:{color:"color"},isMToonMaterial:{color:"color",emissionColor:"emissive",outlineColor:"outlineColorFactor",matcapColor:"matcapFactor",rimColor:"parametricRimColorFactor",shadeColor:"shadeColorFactor"}};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 v=new e.Vector2;class g{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(g._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(v.copy(t.deltaOffset).multiplyScalar(e)),i.repeat.add(v.copy(t.deltaScale).multiplyScalar(e)),i.needsUpdate=!0)}))}clearAppliedWeight(){this._properties.forEach((e=>{const t=this.material[e.name];void 0!==t&&(t.offset.copy(e.initialOffset),t.repeat.copy(e.initialScale),t.needsUpdate=!0)}))}}g._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 x{constructor(e){this.parser=e}get name(){return"VRMExpressionLoaderPlugin"}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 v=new Set(Object.values(l)),x=new Map;null!=p.preset&&Object.entries(p.preset).forEach((([e,t])=>{null!=t&&(v.has(e)?x.set(e,t):console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${e}" detected. Ignoring the expression`))})),null!=p.custom&&Object.entries(p.custom).forEach((([e,t])=>{v.has(e)?console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${e}". Ignoring the expression`):x.set(e,t)}));const M=new d;return yield Promise.all(Array.from(x.entries()).map((([r,s])=>n(this,void 0,void 0,(function*(){var l,u,d,h,c,p,v;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)}))}))})))),null===(v=s.textureTransformBinds)||void 0===v||v.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 g({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])}))}))}))))}M.registerExpression(_)}))))),M}))}_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&&x.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 v=new i(h);t.scene.add(v),v.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))?v.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 void v.addBind(new g({material:t,scale:n,offset:r}))}const n=c[r];n?v.addBind(new m({material:t,type:n,targetValue:new e.Color(...i.targetValue.slice(0,3))})):console.warn(r+" is not supported")}))})),u.registerExpression(v)}))))),u}))}}x.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 M={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").array,s=[];for(let e=0;e<o.length;e+=4)s.push([o[e],o[e+1],o[e+2],o[e+3]]);const a=r.getAttribute("skinWeight").array,l=[];for(let e=0;e<a.length;e+=4)l.push([a[e],a[e+1],a[e+2],a[e+3]]);const u=r.getIndex();if(!u)throw new Error("The geometry doesn't have an index buffer");const d=Array.from(u.array),h=this._excludeTriangles(d,l,s,i),c=[];for(let e=0;e<h;e++)c[e]=d[e];return r.setIndex(c),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{constructor(e){this.parser=e}get name(){return"VRMFirstPersonLoaderPlugin"}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 w={Auto:"auto",Both:"both",ThirdPersonOnly:"thirdPersonOnly",FirstPersonOnly:"firstPersonOnly"},E=new e.Vector3,P=new e.Vector3,L=new e.Quaternion;class S 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(E,L,P);const i=E.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"],b={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"},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 U(e){return e.invert?e.invert():e.inverse(),e}const O=new e.Vector3,V=new e.Quaternion;class C{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),V.copy(n.quaternion),e[i]={position:O.toArray(),rotation:V.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),V.identity();const r=this.restPose[i];(null==r?void 0:r.position)&&O.fromArray(r.position).negate(),(null==r?void 0:r.rotation)&&U(V.fromArray(r.rotation)),O.add(n.position),V.premultiply(n.quaternion),e[i]={position:O.toArray(),rotation:V.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(V.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 e.Vector3,D=new e.Quaternion;class F extends C{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}static _setupTransforms(t){const i=new e.Object3D;i.name="VRMHumanoidRig";const n={},r={},o={};A.forEach((i=>{const s=t.getBoneNode(i);if(s){const t=new e.Vector3,a=new e.Quaternion;s.updateWorldMatrix(!0,!1),s.matrixWorld.decompose(t,a,N),n[i]=t,r[i]=a,o[i]=s.quaternion.clone()}}));const s={},a={};return A.forEach((o=>{var l;const u=t.getBoneNode(o);if(u){const t=n[o];let d,h,c=o;for(;null==d&&(c=I[c],null!=c);)d=n[c],h=r[c];const p=new e.Object3D;p.name="Normalized_"+u.name;(c?null===(l=a[c])||void 0===l?void 0:l.node:i).add(p),p.position.copy(t),d&&p.position.sub(d),a[o]={node:p},s[o]=null!=h?h:new e.Quaternion}})),{rigBones:a,root:i,parentWorldRotations:s,boneRotations:o}}update(){A.forEach((t=>{const i=this.original.getBoneNode(t);if(null!=i){const n=this.getBoneNode(t),r=this._parentWorldRotations[t],o=D.copy(r).invert(),s=this._boneRotations[t];if(i.quaternion.copy(n.quaternion).multiply(r).premultiply(o).multiply(s),"hips"===t){const t=n.getWorldPosition(new e.Vector3),r=i.parent.matrixWorld,o=t.applyMatrix4(r.invert());i.position.copy(o)}}}))}}class B{constructor(e,t){var i;this.autoUpdateHumanBones=null===(i=null==t?void 0:t.autoUpdateHumanBones)||void 0===i||i,this._rawHumanBones=new C(e),this._normalizedHumanBones=new F(this._rawHumanBones)}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}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new C(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._rawHumanBones.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{constructor(e,t){this.parser=e,this.helperRoot=null==t?void 0:t.helperRoot,this.autoUpdateHumanBones=null==t?void 0:t.autoUpdateHumanBones}get name(){return"VRMHumanoidLoaderPlugin"}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(!k.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=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 S(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=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 S(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 j 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 Q 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,G=new e.Quaternion,Y=new e.Vector3,q=new e.Vector3,$=Math.sqrt(2)/2,Z=new e.Quaternion(0,0,-$,$),J=new e.Vector3(0,1,0);class K extends e.Group{constructor(t){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=t;{const t=new j;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 j;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 Q;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(Y),this.vrmLookAt.getLookAtWorldQuaternion(X),X.multiply(this.vrmLookAt.getFaceFrontQuaternion(G)),this._meshYaw.position.copy(Y),this._meshYaw.quaternion.copy(X),this._meshPitch.position.copy(Y),this._meshPitch.quaternion.copy(X),this._meshPitch.quaternion.multiply(G.setFromAxisAngle(J,i)),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(t)}}const ee=new e.Vector3,te=new e.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 e.Vector3(0,0,1),se=new e.Vector3,ae=new e.Vector3,le=new e.Vector3,ue=new e.Quaternion,de=new e.Quaternion,he=new e.Quaternion,ce=new e.Quaternion,pe=new e.Euler;class me{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)}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)}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 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(t){const i=ue.copy(this._restHeadWorldQuaternion).multiply(U(this.getLookAtWorldQuaternion(de))),n=this.getLookAtWorldPosition(ae),r=le.copy(t).sub(n).applyQuaternion(i).normalize(),[o,s]=ne(this.faceFront),[a,l]=ne(r),u=re(a-o),d=re(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(se)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}}me.EULER_ORDER="YXZ";const fe=new e.Vector3(0,0,1),ve=new e.Quaternion,ge=new e.Quaternion,_e=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("leftEye");s&&(this._restQuatLeftEye.copy(s.quaternion),ie(s.parent,this._restLeftEyeParentWorldQuat)),a&&(this._restQuatRightEye.copy(a.quaternion),ie(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&&(_e.x=i<0?-e.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-i):e.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(i),_e.y=t<0?-e.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(-t):e.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(t),ve.setFromEuler(_e),this._getWorldFaceFrontQuat(ge),o.quaternion.copy(ge).multiply(ve).multiply(ge.invert()),ve.copy(this._restLeftEyeParentWorldQuat),n.quaternion.copy(o.quaternion).multiply(ve).premultiply(ve.invert()).multiply(this._restQuatLeftEye)),r&&(_e.x=i<0?-e.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-i):e.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(i),_e.y=t<0?-e.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(-t):e.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(t),ve.setFromEuler(_e),this._getWorldFaceFrontQuat(ge),s.quaternion.copy(ge).multiply(ve).multiply(ge.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(fe)<.01)return e.identity();const[t,i]=ne(this.faceFront);return _e.set(0,.5*Math.PI+t,i,"YZX"),e.setFromEuler(_e)}}xe.type="bone";class Me{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)}}Me.type="expression";class ye{constructor(e,t){this.inputMaxValue=e,this.outputScale=t}map(e){return this.outputScale*u(e/this.inputMaxValue)}}const Te=new Set(["1.0","1.0-beta"]);class Re{constructor(e,t){this.parser=e,this.helperRoot=null==t?void 0:t.helperRoot}get name(){return"VRMLookAtLoaderPlugin"}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(!Te.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 Me(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;return new ye(null!==(i=null==e?void 0:e.inputMaxValue)&&void 0!==i?i:90,null!==(n=null==e?void 0:e.outputScale)&&void 0!==n?n:t)}_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 Me(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;return"[0,0,0,1,1,1,1,0]"!==JSON.stringify(r)&&console.warn("Curves of LookAtDegreeMap defined in VRM 0.0 are not supported"),new ye(null!==(i=null==e?void 0:e.xRange)&&void 0!==i?i:90,null!==(n=null==e?void 0:e.yRange)&&void 0!==n?n:t)}_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={Bone:"bone",Expression:"expression"};const Ee=new Set(["1.0","1.0-beta"]);class Pe{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}get name(){return"VRMMetaLoaderPlugin"}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(!Ee.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;return this.needThumbnailImage&&null!=s.thumbnailImage&&(l=null!==(r=yield this._extractGLTFImage(s.thumbnailImage))&&void 0!==r?r: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 n(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,licenseName:n.licenseName,otherLicenseUrl:n.otherLicenseUrl,otherPermissionUrl:n.otherPermissionUrl,reference:n.reference,sexualUssageName:n.sexualUssageName,texture:null!=r?r:void 0,title:n.title,version:n.version,violentUssageName:n.violentUssageName}}))}_extractGLTFImage(t){var i;return n(this,void 0,void 0,(function*(){const n=this.parser.json,r=null===(i=n.images)||void 0===i?void 0:i[t];if(null==r)return console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${t}] of glTF as a thumbnail but the image doesn't exist`),null;let o=r.uri;if(null!=r.bufferView){const e=yield this.parser.getDependency("bufferView",r.bufferView),t=new Blob([e],{type:r.mimeType});o=URL.createObjectURL(t)}if(null==o)return console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${t}] of glTF as a thumbnail but the image couldn't load properly`),null;const s=new e.ImageLoader;return yield s.loadAsync((a=o,l=this.parser.options.path,"string"!=typeof a||""===a?"":(/^https?:\/\//i.test(l)&&/^\//.test(a)&&(l=l.replace(/(^https?:\/\/[^/]+).*/i,"$1")),/^(https?:)?\/\//i.test(a)||/^data:.*,.*$/i.test(a)||/^blob:.*$/i.test(a)?a:l+a))).catch((e=>(console.error(e),console.warn("VRMMetaLoaderPlugin: Failed to load a thumbnail image"),null)));var a,l}))}}class Le{constructor(e){this.scene=e.scene,this.meta=e.meta,this.humanoid=e.humanoid,this.expressionManager=e.expressionManager,this.firstPerson=e.firstPerson,this.lookAt=e.lookAt}update(e){this.humanoid.update(),this.lookAt&&this.lookAt.update(e),this.expressionManager&&this.expressionManager.update()}}class Se{constructor(e,t){var i,n,r,o,s;this.parser=e;const a=null==t?void 0:t.helperRoot,l=null==t?void 0:t.autoUpdateHumanBones;this.expressionPlugin=null!==(i=null==t?void 0:t.expressionPlugin)&&void 0!==i?i:new x(e),this.firstPersonPlugin=null!==(n=null==t?void 0:t.firstPersonPlugin)&&void 0!==n?n:new R(e),this.humanoidPlugin=null!==(r=null==t?void 0:t.humanoidPlugin)&&void 0!==r?r:new z(e,{helperRoot:a,autoUpdateHumanBones:l}),this.lookAtPlugin=null!==(o=null==t?void 0:t.lookAtPlugin)&&void 0!==o?o:new Re(e,{helperRoot:a}),this.metaPlugin=null!==(s=null==t?void 0:t.metaPlugin)&&void 0!==s?s:new Pe(e)}get name(){return"VRMC_vrm"}afterRoot(e){return n(this,void 0,void 0,(function*(){yield this.metaPlugin.afterRoot(e),yield this.humanoidPlugin.afterRoot(e),yield this.expressionPlugin.afterRoot(e),yield this.lookAtPlugin.afterRoot(e),yield this.firstPersonPlugin.afterRoot(e);const t=e.userData.vrmMeta,i=e.userData.vrmHumanoid;if(t&&i){const n=new Le({scene:e.scene,expressionManager:e.userData.vrmExpressionManager,firstPerson:e.userData.vrmFirstPerson,humanoid:i,lookAt:e.userData.vrmLookAt,meta:t});e.userData.vrmCore=n}}))}}class Ae extends Le{constructor(e){super(e),this.materials=e.materials,this.springBoneManager=e.springBoneManager,this.nodeConstraintManager=e.nodeConstraintManager}update(e){super.update(e),this.nodeConstraintManager&&this.nodeConstraintManager.update(),this.springBoneManager&&this.springBoneManager.update(e),this.materials&&this.materials.forEach((t=>{t.update&&t.update(e)}))}}
|
|
26
|
-
/*! *****************************************************************************
|
|
27
|
-
Copyright (c) Microsoft Corporation.
|
|
28
|
-
|
|
29
|
-
Permission to use, copy, modify, and/or distribute this software for any
|
|
30
|
-
purpose with or without fee is hereby granted.
|
|
31
|
-
|
|
32
|
-
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
33
|
-
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
34
|
-
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
35
|
-
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
36
|
-
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
37
|
-
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
38
|
-
PERFORMANCE OF THIS SOFTWARE.
|
|
39
|
-
***************************************************************************** */function be(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())}))}
|
|
11
|
+
class i extends e.Object3D{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}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}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}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{constructor(){this.blinkExpressionNames=["blink","blinkLeft","blinkRight"],this.lookAtExpressionNames=["lookLeft","lookRight","lookUp","lookDown"],this.mouthExpressionNames=["aa","ee","ih","oh","ou"],this._expressions=[],this._expressionMap={}}get expressions(){return this._expressions.concat()}get expressionMap(){return Object.assign({},this._expressionMap)}get presetExpressionMap(){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}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:t,type:i,targetValue:n}){var r,o,s;this.material=t,this.type=i,this.targetValue=n;const a=null===(r=Object.entries(m._propertyNameMapMap).find((([e])=>!0===t[e])))||void 0===r?void 0:r[1],l=null!==(o=null==a?void 0:a[i])&&void 0!==o?o:null;if(null==l)console.warn(`Tried to add a material color bind to the material ${null!==(s=t.name)&&void 0!==s?s:"(no name)"}, the type ${i} but the material or the type is not supported.`),this._state=null;else{const i=t[l].clone(),r=new e.Color(n.r-i.r,n.g-i.g,n.b-i.b);this._state={propertyName:l,initialValue:i,deltaValue:r}}}applyWeight(e){if(null==this._state)return;const{propertyName:t,deltaValue:i}=this._state,n=this.material[t];void 0!==n&&(n.add(p.copy(i).multiplyScalar(e)),"boolean"==typeof this.material.shouldApplyUniforms&&(this.material.shouldApplyUniforms=!0))}clearAppliedWeight(){if(null==this._state)return;const{propertyName:e,initialValue:t}=this._state,i=this.material[e];void 0!==i&&(i.copy(t),"boolean"==typeof this.material.shouldApplyUniforms&&(this.material.shouldApplyUniforms=!0))}}m._propertyNameMapMap={isMeshStandardMaterial:{color:"color",emissionColor:"emissive"},isMeshBasicMaterial:{color:"color"},isMToonMaterial:{color:"color",emissionColor:"emissive",outlineColor:"outlineColorFactor",matcapColor:"matcapFactor",rimColor:"parametricRimColorFactor",shadeColor:"shadeColorFactor"}};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 v=new e.Vector2;class g{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(g._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(v.copy(t.deltaOffset).multiplyScalar(e)),i.repeat.add(v.copy(t.deltaScale).multiplyScalar(e)),i.needsUpdate=!0)}))}clearAppliedWeight(){this._properties.forEach((e=>{const t=this.material[e.name];void 0!==t&&(t.offset.copy(e.initialOffset),t.repeat.copy(e.initialScale),t.needsUpdate=!0)}))}}g._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 x{constructor(e){this.parser=e}get name(){return"VRMExpressionLoaderPlugin"}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 v=new Set(Object.values(l)),x=new Map;null!=p.preset&&Object.entries(p.preset).forEach((([e,t])=>{null!=t&&(v.has(e)?x.set(e,t):console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${e}" detected. Ignoring the expression`))})),null!=p.custom&&Object.entries(p.custom).forEach((([e,t])=>{v.has(e)?console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${e}". Ignoring the expression`):x.set(e,t)}));const M=new d;return yield Promise.all(Array.from(x.entries()).map((([r,s])=>n(this,void 0,void 0,(function*(){var l,u,d,h,c,p,v;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)}))}))})))),null===(v=s.textureTransformBinds)||void 0===v||v.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 g({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])}))}))}))))}M.registerExpression(_)}))))),M}))}_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&&x.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 v=new i(h);t.scene.add(v),v.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))?v.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 void v.addBind(new g({material:t,scale:n,offset:r}))}const n=c[r];n?v.addBind(new m({material:t,type:n,targetValue:new e.Color(...i.targetValue.slice(0,3))})):console.warn(r+" is not supported")}))})),u.registerExpression(v)}))))),u}))}}x.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 M={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").array,s=[];for(let e=0;e<o.length;e+=4)s.push([o[e],o[e+1],o[e+2],o[e+3]]);const a=r.getAttribute("skinWeight").array,l=[];for(let e=0;e<a.length;e+=4)l.push([a[e],a[e+1],a[e+2],a[e+3]]);const u=r.getIndex();if(!u)throw new Error("The geometry doesn't have an index buffer");const d=Array.from(u.array),h=this._excludeTriangles(d,l,s,i),c=[];for(let e=0;e<h;e++)c[e]=d[e];return r.setIndex(c),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{constructor(e){this.parser=e}get name(){return"VRMFirstPersonLoaderPlugin"}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 w={Auto:"auto",Both:"both",ThirdPersonOnly:"thirdPersonOnly",FirstPersonOnly:"firstPersonOnly"},E=new e.Vector3,P=new e.Vector3,L=new e.Quaternion;class S 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(E,L,P);const i=E.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"],b={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"},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 U(e){return e.invert?e.invert():e.inverse(),e}const O=new e.Vector3,V=new e.Quaternion;class C{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),V.copy(n.quaternion),e[i]={position:O.toArray(),rotation:V.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),V.identity();const r=this.restPose[i];(null==r?void 0:r.position)&&O.fromArray(r.position).negate(),(null==r?void 0:r.rotation)&&U(V.fromArray(r.rotation)),O.add(n.position),V.premultiply(n.quaternion),e[i]={position:O.toArray(),rotation:V.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(V.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 e.Vector3,D=new e.Quaternion,F=new e.Vector3;class B extends C{constructor(e){const{rigBones:t,root:i,parentWorldRotations:n,boneRotations:r}=B._setupTransforms(e);super(t),this.original=e,this.root=i,this._parentWorldRotations=n,this._boneRotations=r}static _setupTransforms(t){const i=new e.Object3D;i.name="VRMHumanoidRig";const n={},r={},o={};A.forEach((i=>{const s=t.getBoneNode(i);if(s){const t=new e.Vector3,a=new e.Quaternion;s.updateWorldMatrix(!0,!1),s.matrixWorld.decompose(t,a,N),n[i]=t,r[i]=a,o[i]=s.quaternion.clone()}}));const s={},a={};return A.forEach((o=>{var l;const u=t.getBoneNode(o);if(u){const t=n[o];let d,h,c=o;for(;null==d&&(c=I[c],null!=c);)d=n[c],h=r[c];const p=new e.Object3D;p.name="Normalized_"+u.name;(c?null===(l=a[c])||void 0===l?void 0:l.node:i).add(p),p.position.copy(t),d&&p.position.sub(d),a[o]={node:p},s[o]=null!=h?h:new e.Quaternion}})),{rigBones:a,root:i,parentWorldRotations:s,boneRotations:o}}update(){A.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 H{constructor(e,t){var i;this.autoUpdateHumanBones=null===(i=null==t?void 0:t.autoUpdateHumanBones)||void 0===i||i,this._rawHumanBones=new C(e),this._normalizedHumanBones=new B(this._rawHumanBones)}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}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new C(e.humanBones),this._normalizedHumanBones=new B(this._rawHumanBones),this}clone(){return new H(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._rawHumanBones.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 j{constructor(e,t){this.parser=e,this.helperRoot=null==t?void 0:t.helperRoot,this.autoUpdateHumanBones=null==t?void 0:t.autoUpdateHumanBones}get name(){return"VRMHumanoidLoaderPlugin"}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 H(this._ensureRequiredBonesExist(u),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(d.normalizedHumanBonesRoot),this.helperRoot){const e=new S(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 H(this._ensureRequiredBonesExist(s),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(a.normalizedHumanBonesRoot),this.helperRoot){const e=new S(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 X 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 G=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 X;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(G),G.multiply(this.vrmLookAt.getFaceFrontQuaternion(Y)),this._meshYaw.position.copy(q),this._meshYaw.quaternion.copy(G),this._meshPitch.position.copy(q),this._meshPitch.quaternion.copy(G),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{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)}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)}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 ve=new e.Vector3(0,0,1),ge=new e.Quaternion,_e=new e.Quaternion,xe=new e.Euler(0,0,0,"YXZ");class Me{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("leftEye");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&&(xe.x=i<0?-e.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-i):e.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(i),xe.y=t<0?-e.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(-t):e.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(t),ge.setFromEuler(xe),this._getWorldFaceFrontQuat(_e),o.quaternion.copy(_e).multiply(ge).multiply(_e.invert()),ge.copy(this._restLeftEyeParentWorldQuat),n.quaternion.copy(o.quaternion).multiply(ge).premultiply(ge.invert()).multiply(this._restQuatLeftEye)),r&&(xe.x=i<0?-e.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-i):e.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(i),xe.y=t<0?-e.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(-t):e.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(t),ge.setFromEuler(xe),this._getWorldFaceFrontQuat(_e),s.quaternion.copy(_e).multiply(ge).multiply(_e.invert()),ge.copy(this._restRightEyeParentWorldQuat),r.quaternion.copy(s.quaternion).multiply(ge).premultiply(ge.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(ve)<.01)return e.identity();const[t,i]=re(this.faceFront);return xe.set(0,.5*Math.PI+t,i,"YZX"),e.setFromEuler(xe)}}Me.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 we{constructor(e,t){this.parser=e,this.helperRoot=null==t?void 0:t.helperRoot}get name(){return"VRMLookAtLoaderPlugin"}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 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;return new Te(null!==(i=null==e?void 0:e.inputMaxValue)&&void 0!==i?i:90,null!==(n=null==e?void 0:e.outputScale)&&void 0!==n?n:t)}_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 Me(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 Me&&m.faceFront.set(0,0,-1),f}))}_v0ImportDegreeMap(e,t){var i,n;const r=null==e?void 0:e.curve;return"[0,0,0,1,1,1,1,0]"!==JSON.stringify(r)&&console.warn("Curves of LookAtDegreeMap defined in VRM 0.0 are not supported"),new Te(null!==(i=null==e?void 0:e.xRange)&&void 0!==i?i:90,null!==(n=null==e?void 0:e.yRange)&&void 0!==n?n:t)}_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 Ee={Bone:"bone",Expression:"expression"};const Pe=new Set(["1.0","1.0-beta"]);class Le{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}get name(){return"VRMMetaLoaderPlugin"}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;return this.needThumbnailImage&&null!=s.thumbnailImage&&(l=null!==(r=yield this._extractGLTFImage(s.thumbnailImage))&&void 0!==r?r: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 n(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,licenseName:n.licenseName,otherLicenseUrl:n.otherLicenseUrl,otherPermissionUrl:n.otherPermissionUrl,reference:n.reference,sexualUssageName:n.sexualUssageName,texture:null!=r?r:void 0,title:n.title,version:n.version,violentUssageName:n.violentUssageName}}))}_extractGLTFImage(t){var i;return n(this,void 0,void 0,(function*(){const n=this.parser.json,r=null===(i=n.images)||void 0===i?void 0:i[t];if(null==r)return console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${t}] of glTF as a thumbnail but the image doesn't exist`),null;let o=r.uri;if(null!=r.bufferView){const e=yield this.parser.getDependency("bufferView",r.bufferView),t=new Blob([e],{type:r.mimeType});o=URL.createObjectURL(t)}if(null==o)return console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${t}] of glTF as a thumbnail but the image couldn't load properly`),null;const s=new e.ImageLoader;return yield s.loadAsync((a=o,l=this.parser.options.path,"string"!=typeof a||""===a?"":(/^https?:\/\//i.test(l)&&/^\//.test(a)&&(l=l.replace(/(^https?:\/\/[^/]+).*/i,"$1")),/^(https?:)?\/\//i.test(a)||/^data:.*,.*$/i.test(a)||/^blob:.*$/i.test(a)?a:l+a))).catch((e=>(console.error(e),console.warn("VRMMetaLoaderPlugin: Failed to load a thumbnail image"),null)));var a,l}))}}class Se{constructor(e){this.scene=e.scene,this.meta=e.meta,this.humanoid=e.humanoid,this.expressionManager=e.expressionManager,this.firstPerson=e.firstPerson,this.lookAt=e.lookAt}update(e){this.humanoid.update(),this.lookAt&&this.lookAt.update(e),this.expressionManager&&this.expressionManager.update()}}class Ae{constructor(e,t){var i,n,r,o,s;this.parser=e;const a=null==t?void 0:t.helperRoot,l=null==t?void 0:t.autoUpdateHumanBones;this.expressionPlugin=null!==(i=null==t?void 0:t.expressionPlugin)&&void 0!==i?i:new x(e),this.firstPersonPlugin=null!==(n=null==t?void 0:t.firstPersonPlugin)&&void 0!==n?n:new R(e),this.humanoidPlugin=null!==(r=null==t?void 0:t.humanoidPlugin)&&void 0!==r?r:new j(e,{helperRoot:a,autoUpdateHumanBones:l}),this.lookAtPlugin=null!==(o=null==t?void 0:t.lookAtPlugin)&&void 0!==o?o:new we(e,{helperRoot:a}),this.metaPlugin=null!==(s=null==t?void 0:t.metaPlugin)&&void 0!==s?s:new Le(e)}get name(){return"VRMC_vrm"}afterRoot(e){return n(this,void 0,void 0,(function*(){yield this.metaPlugin.afterRoot(e),yield this.humanoidPlugin.afterRoot(e),yield this.expressionPlugin.afterRoot(e),yield this.lookAtPlugin.afterRoot(e),yield this.firstPersonPlugin.afterRoot(e);const t=e.userData.vrmMeta,i=e.userData.vrmHumanoid;if(t&&i){const n=new Se({scene:e.scene,expressionManager:e.userData.vrmExpressionManager,firstPerson:e.userData.vrmFirstPerson,humanoid:i,lookAt:e.userData.vrmLookAt,meta:t});e.userData.vrmCore=n}}))}}class be extends Se{constructor(e){super(e),this.materials=e.materials,this.springBoneManager=e.springBoneManager,this.nodeConstraintManager=e.nodeConstraintManager}update(e){super.update(e),this.nodeConstraintManager&&this.nodeConstraintManager.update(),this.springBoneManager&&this.springBoneManager.update(e),this.materials&&this.materials.forEach((t=>{t.update&&t.update(e)}))}}function Ie(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())}))}
|
|
40
12
|
/*!
|
|
41
|
-
* @pixiv/three-vrm-materials-mtoon v1.0.
|
|
13
|
+
* @pixiv/three-vrm-materials-mtoon v1.0.3
|
|
42
14
|
* MToon (toon material) module for @pixiv/three-vrm
|
|
43
15
|
*
|
|
44
|
-
* Copyright (c) 2020-
|
|
16
|
+
* Copyright (c) 2020-2022 pixiv Inc.
|
|
45
17
|
* @pixiv/three-vrm-materials-mtoon is distributed under MIT License
|
|
46
18
|
* https://github.com/pixiv/three-vrm/blob/release/LICENSE
|
|
47
|
-
*/
|
|
48
|
-
/*! *****************************************************************************
|
|
49
|
-
Copyright (c) Microsoft Corporation.
|
|
50
|
-
|
|
51
|
-
Permission to use, copy, modify, and/or distribute this software for any
|
|
52
|
-
purpose with or without fee is hereby granted.
|
|
53
|
-
|
|
54
|
-
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
55
|
-
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
56
|
-
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
57
|
-
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
58
|
-
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
59
|
-
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
60
|
-
PERFORMANCE OF THIS SOFTWARE.
|
|
61
|
-
***************************************************************************** */function Ie(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())}))}const Ue={None:"none",Normal:"normal",LitShadeRate:"litShadeRate",UV:"uv"},Oe={None:"none",WorldCoordinates:"worldCoordinates",ScreenCoordinates:"screenCoordinates"},Ve=(t,i)=>{const n=(t=>{if(parseInt(e.REVISION,10)>=136)switch(t){case e.LinearEncoding:return["Linear","( value )"];case e.sRGBEncoding:return["sRGB","( value )"];default:return console.warn("THREE.WebGLProgram: Unsupported encoding:",t),["Linear","( value )"]}else switch(t){case e.LinearEncoding:return["Linear","( value )"];case e.sRGBEncoding:return["sRGB","( value )"];case 3002:return["RGBE","( value )"];case 3004:return["RGBM","( value, 7.0 )"];case 3005:return["RGBM","( value, 16.0 )"];case 3006:return["RGBD","( value, 256.0 )"];case 3007:return["Gamma","( value, float( GAMMA_FACTOR ) )"];default:throw new Error("unsupported encoding: "+t)}})(i);return"vec4 "+t+"( vec4 value ) { return "+n[0]+"ToLinear"+n[1]+"; }"};function Ce(t,i){let n;return n=t&&t.isTexture?t.encoding:e.LinearEncoding,parseInt(e.REVISION,10)>=133&&i&&t&&t.isTexture&&t.format===e.RGBAFormat&&t.type===e.UnsignedByteType&&t.encoding===e.sRGBEncoding&&(n=e.LinearEncoding),n}class Ne extends e.ShaderMaterial{constructor(t={}){super({vertexShader:"// #define PHONG\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n\n#include <common>\n\n// #include <uv_pars_vertex>\n#ifdef MTOON_USE_UV\n varying vec2 vUv;\n uniform mat3 uvTransform;\n#endif\n\n#include <uv2_pars_vertex>\n// #include <displacementmap_pars_vertex>\n// #include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\n#ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE\n uniform sampler2D outlineWidthMultiplyTexture;\n uniform mat3 outlineWidthMultiplyTextureUvTransform;\n#endif\n\nuniform float outlineWidthFactor;\n\nvoid main() {\n\n // #include <uv_vertex>\n #ifdef MTOON_USE_UV\n vUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n #endif\n\n #include <uv2_vertex>\n #include <color_vertex>\n\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n\n // we need this to compute the outline properly\n objectNormal = normalize( objectNormal );\n\n #include <defaultnormal_vertex>\n\n #ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n vNormal = normalize( transformedNormal );\n #endif\n\n #include <begin_vertex>\n\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n // #include <displacementmap_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n\n vViewPosition = - mvPosition.xyz;\n\n float outlineTex = 1.0;\n\n #ifdef OUTLINE\n #ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE\n vec2 outlineWidthMultiplyTextureUv = ( outlineWidthMultiplyTextureUvTransform * vec3( vUv, 1 ) ).xy;\n outlineTex = texture2D( outlineWidthMultiplyTexture, outlineWidthMultiplyTextureUv ).g;\n #endif\n\n #ifdef OUTLINE_WIDTH_WORLD\n float worldNormalLength = length( transformedNormal );\n vec3 outlineOffset = outlineWidthFactor * outlineTex * worldNormalLength * objectNormal;\n gl_Position = projectionMatrix * modelViewMatrix * vec4( outlineOffset + transformed, 1.0 );\n #endif\n\n #ifdef OUTLINE_WIDTH_SCREEN\n vec3 clipNormal = ( projectionMatrix * modelViewMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n vec2 projectedNormal = normalize( clipNormal.xy );\n projectedNormal.x *= projectionMatrix[ 0 ].x / projectionMatrix[ 1 ].y;\n gl_Position.xy += 2.0 * outlineWidthFactor * outlineTex * projectedNormal.xy;\n #endif\n\n gl_Position.z += 1E-6 * gl_Position.w; // anti-artifact magic\n #endif\n\n #include <worldpos_vertex>\n // #include <envmap_vertex>\n #include <shadowmap_vertex>\n #include <fog_vertex>\n\n}",fragmentShader:'// #define PHONG\n\nuniform vec3 litFactor;\n\nuniform float opacity;\n\nuniform vec3 shadeColorFactor;\n#ifdef USE_SHADEMULTIPLYTEXTURE\n uniform sampler2D shadeMultiplyTexture;\n uniform mat3 shadeMultiplyTextureUvTransform;\n#endif\n\nuniform float shadingShiftFactor;\nuniform float shadingToonyFactor;\n\n#ifdef USE_SHADINGSHIFTTEXTURE\n uniform sampler2D shadingShiftTexture;\n uniform mat3 shadingShiftTextureUvTransform;\n uniform float shadingShiftTextureScale;\n#endif\n\nuniform float giEqualizationFactor;\n\nuniform vec3 parametricRimColorFactor;\n#ifdef USE_RIMMULTIPLYTEXTURE\n uniform sampler2D rimMultiplyTexture;\n uniform mat3 rimMultiplyTextureUvTransform;\n#endif\nuniform float rimLightingMixFactor;\nuniform float parametricRimFresnelPowerFactor;\nuniform float parametricRimLiftFactor;\n\n#ifdef USE_MATCAPTEXTURE\n uniform vec3 matcapFactor;\n uniform sampler2D matcapTexture;\n uniform mat3 matcapTextureUvTransform;\n#endif\n\nuniform vec3 emissive;\nuniform float emissiveIntensity;\n\nuniform vec3 outlineColorFactor;\nuniform float outlineLightingMixFactor;\n\n#ifdef USE_UVANIMATIONMASKTEXTURE\n uniform sampler2D uvAnimationMaskTexture;\n uniform mat3 uvAnimationMaskTextureUvTransform;\n#endif\n\nuniform float uvAnimationScrollXOffset;\nuniform float uvAnimationScrollYOffset;\nuniform float uvAnimationRotationPhase;\n\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n\n// #include <uv_pars_fragment>\n#if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n varying vec2 vUv;\n#endif\n\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n\n#ifdef USE_MAP\n uniform mat3 mapUvTransform;\n#endif\n\n// #include <alphamap_pars_fragment>\n\n#if THREE_VRM_THREE_REVISION >= 132\n #include <alphatest_pars_fragment>\n#endif\n\n#include <aomap_pars_fragment>\n// #include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n\n#ifdef USE_EMISSIVEMAP\n uniform mat3 emissiveMapUvTransform;\n#endif\n\n// #include <envmap_common_pars_fragment>\n// #include <envmap_pars_fragment>\n// #include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n\n// #include <bsdfs>\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n return RECIPROCAL_PI * diffuseColor;\n}\n\n#include <lights_pars_begin>\n\n#if THREE_VRM_THREE_REVISION >= 132\n #include <normal_pars_fragment>\n#endif\n\n// #include <lights_phong_pars_fragment>\nvarying vec3 vViewPosition;\n\n#if THREE_VRM_THREE_REVISION < 132\n #ifndef FLAT_SHADED\n varying vec3 vNormal;\n #endif\n#endif\n\nstruct MToonMaterial {\n vec3 diffuseColor;\n vec3 shadeColor;\n float shadingShift;\n};\n\nfloat linearstep( float a, float b, float t ) {\n return clamp( ( t - a ) / ( b - a ), 0.0, 1.0 );\n}\n\n/**\n * Convert NdotL into toon shading factor using shadingShift and shadingToony\n */\nfloat getShading(\n const in float dotNL,\n const in float shadow,\n const in float shadingShift\n) {\n float shading = dotNL;\n shading = shading + shadingShift;\n shading = linearstep( -1.0 + shadingToonyFactor, 1.0 - shadingToonyFactor, shading );\n shading *= shadow;\n return shading;\n}\n\n/**\n * Mix diffuseColor and shadeColor using shading factor and light color\n */\nvec3 getDiffuse(\n const in MToonMaterial material,\n const in float shading,\n in vec3 lightColor\n) {\n #ifdef DEBUG_LITSHADERATE\n return vec3( BRDF_Lambert( shading * lightColor ) );\n #endif\n\n #if THREE_VRM_THREE_REVISION < 132\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n lightColor *= PI;\n #endif\n #endif\n\n vec3 col = lightColor * BRDF_Lambert( mix( material.shadeColor, material.diffuseColor, shading ) );\n\n // The "comment out if you want to PBR absolutely" line\n #ifdef V0_COMPAT_SHADE\n col = min( col, material.diffuseColor );\n #endif\n\n return col;\n}\n\nvoid RE_Direct_MToon( const in IncidentLight directLight, const in GeometricContext geometry, const in MToonMaterial material, const in float shadow, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n vec3 irradiance = directLight.color;\n\n #if THREE_VRM_THREE_REVISION < 132\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n irradiance *= PI;\n #endif\n #endif\n\n // directSpecular will be used for rim lighting, not an actual specular\n reflectedLight.directSpecular += irradiance;\n\n irradiance *= dotNL;\n\n float shading = getShading( dotNL, shadow, material.shadingShift );\n\n // toon shaded diffuse\n reflectedLight.directDiffuse += getDiffuse( material, shading, directLight.color );\n}\n\nvoid RE_IndirectDiffuse_MToon( const in vec3 irradiance, const in GeometricContext geometry, const in MToonMaterial material, inout ReflectedLight reflectedLight ) {\n // indirect diffuse will use diffuseColor, no shadeColor involved\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\n // directSpecular will be used for rim lighting, not an actual specular\n reflectedLight.directSpecular += irradiance;\n}\n\n#define RE_Direct RE_Direct_MToon\n#define RE_IndirectDiffuse RE_IndirectDiffuse_MToon\n#define Material_LightProbeLOD( material ) (0)\n\n#include <shadowmap_pars_fragment>\n// #include <bumpmap_pars_fragment>\n\n// #include <normalmap_pars_fragment>\n#ifdef USE_NORMALMAP\n\n uniform sampler2D normalMap;\n uniform mat3 normalMapUvTransform;\n uniform vec2 normalScale;\n\n#endif\n\n#ifdef OBJECTSPACE_NORMALMAP\n\n uniform mat3 normalMatrix;\n\n#endif\n\n#if ! defined ( USE_TANGENT ) && defined ( TANGENTSPACE_NORMALMAP )\n\n // Per-Pixel Tangent Space Normal Mapping\n // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n // three-vrm specific change: it requires `uv` as an input in order to support uv scrolls\n\n // Temporary compat against shader change @ Three.js r126\n // See: #21205, #21307, #21299\n #if THREE_VRM_THREE_REVISION >= 126\n\n vec3 perturbNormal2Arb( vec2 uv, vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\n vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n vec2 st0 = dFdx( uv.st );\n vec2 st1 = dFdy( uv.st );\n\n vec3 N = normalize( surf_norm );\n\n vec3 q1perp = cross( q1, N );\n vec3 q0perp = cross( N, q0 );\n\n vec3 T = q1perp * st0.x + q0perp * st1.x;\n vec3 B = q1perp * st0.y + q0perp * st1.y;\n\n // three-vrm specific change: Workaround for the issue that happens when delta of uv = 0.0\n // TODO: Is this still required? Or shall I make a PR about it?\n if ( length( T ) == 0.0 || length( B ) == 0.0 ) {\n return surf_norm;\n }\n\n float det = max( dot( T, T ), dot( B, B ) );\n float scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\n return normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\n }\n\n #else\n\n vec3 perturbNormal2Arb( vec2 uv, vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\n // Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988\n\n vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n vec2 st0 = dFdx( uv.st );\n vec2 st1 = dFdy( uv.st );\n\n float scale = sign( st1.t * st0.s - st0.t * st1.s ); // we do not care about the magnitude\n\n vec3 S = ( q0 * st1.t - q1 * st0.t ) * scale;\n vec3 T = ( - q0 * st1.s + q1 * st0.s ) * scale;\n\n // three-vrm specific change: Workaround for the issue that happens when delta of uv = 0.0\n // TODO: Is this still required? Or shall I make a PR about it?\n\n if ( length( S ) == 0.0 || length( T ) == 0.0 ) {\n return surf_norm;\n }\n\n S = normalize( S );\n T = normalize( T );\n vec3 N = normalize( surf_norm );\n\n #ifdef DOUBLE_SIDED\n\n // Workaround for Adreno GPUs gl_FrontFacing bug. See #15850 and #10331\n\n bool frontFacing = dot( cross( S, T ), N ) > 0.0;\n\n mapN.xy *= ( float( frontFacing ) * 2.0 - 1.0 );\n\n #else\n\n mapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n #endif\n\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n\n }\n\n #endif\n\n#endif\n\n// #include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\n// == post correction ==========================================================\nvoid postCorrection() {\n #include <tonemapping_fragment>\n #include <encodings_fragment>\n #include <fog_fragment>\n #include <premultiplied_alpha_fragment>\n #include <dithering_fragment>\n}\n\n// == main procedure ===========================================================\nvoid main() {\n #include <clipping_planes_fragment>\n\n vec2 uv = vec2(0.5, 0.5);\n\n #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n uv = vUv;\n\n float uvAnimMask = 1.0;\n #ifdef USE_UVANIMATIONMASKTEXTURE\n vec2 uvAnimationMaskTextureUv = ( uvAnimationMaskTextureUvTransform * vec3( uv, 1 ) ).xy;\n uvAnimMask = texture2D( uvAnimationMaskTexture, uvAnimationMaskTextureUv ).b;\n #endif\n\n uv = uv + vec2( uvAnimationScrollXOffset, uvAnimationScrollYOffset ) * uvAnimMask;\n float uvRotCos = cos( uvAnimationRotationPhase * uvAnimMask );\n float uvRotSin = sin( uvAnimationRotationPhase * uvAnimMask );\n uv = mat2( uvRotCos, uvRotSin, -uvRotSin, uvRotCos ) * ( uv - 0.5 ) + 0.5;\n #endif\n\n #ifdef DEBUG_UV\n gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n gl_FragColor = vec4( uv, 0.0, 1.0 );\n #endif\n return;\n #endif\n\n vec4 diffuseColor = vec4( litFactor, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive * emissiveIntensity;\n\n #include <logdepthbuf_fragment>\n\n // #include <map_fragment>\n #ifdef USE_MAP\n vec2 mapUv = ( mapUvTransform * vec3( uv, 1 ) ).xy;\n #if THREE_VRM_THREE_REVISION >= 137\n vec4 sampledDiffuseColor = texture2D( map, mapUv );\n #ifdef DECODE_VIDEO_TEXTURE\n sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n #endif\n diffuseColor *= sampledDiffuseColor;\n #else\n // COMPAT: pre-r137\n vec4 texelColor = texture2D( map, mapUv );\n texelColor = mapTexelToLinear( texelColor );\n diffuseColor *= texelColor;\n #endif\n #endif\n\n // #include <color_fragment>\n #if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) )\n diffuseColor.rgb *= vColor;\n #endif\n\n // #include <alphamap_fragment>\n\n #include <alphatest_fragment>\n\n // #include <specularmap_fragment>\n #include <normal_fragment_begin>\n\n #ifdef OUTLINE\n normal *= -1.0;\n #endif\n\n // #include <normal_fragment_maps>\n\n #ifdef OBJECTSPACE_NORMALMAP\n\n vec2 normalMapUv = ( normalMapUvTransform * vec3( uv, 1 ) ).xy;\n normal = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0; // overrides both flatShading and attribute normals\n\n #ifdef FLIP_SIDED\n\n normal = - normal;\n\n #endif\n\n #ifdef DOUBLE_SIDED\n\n // Temporary compat against shader change @ Three.js r126\n // See: #21205, #21307, #21299\n #if THREE_VRM_THREE_REVISION >= 126\n\n normal = normal * faceDirection;\n\n #else\n\n normal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n #endif\n\n #endif\n\n normal = normalize( normalMatrix * normal );\n\n #elif defined( TANGENTSPACE_NORMALMAP )\n\n vec2 normalMapUv = ( normalMapUvTransform * vec3( uv, 1 ) ).xy;\n vec3 mapN = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0;\n mapN.xy *= normalScale;\n\n #ifdef USE_TANGENT\n\n normal = normalize( vTBN * mapN );\n\n #else\n\n // Temporary compat against shader change @ Three.js r126\n // See: #21205, #21307, #21299\n #if THREE_VRM_THREE_REVISION >= 126\n\n normal = perturbNormal2Arb( uv, -vViewPosition, normal, mapN, faceDirection );\n\n #else\n\n normal = perturbNormal2Arb( uv, -vViewPosition, normal, mapN );\n\n #endif\n\n #endif\n\n #endif\n\n // #include <emissivemap_fragment>\n #ifdef USE_EMISSIVEMAP\n vec2 emissiveMapUv = ( emissiveMapUvTransform * vec3( uv, 1 ) ).xy;\n #if THREE_VRM_THREE_REVISION >= 137\n totalEmissiveRadiance *= texture2D( emissiveMap, emissiveMapUv ).rgb;\n #else\n // COMPAT: pre-r137\n totalEmissiveRadiance *= emissiveMapTexelToLinear( texture2D( emissiveMap, emissiveMapUv ) ).rgb;\n #endif\n #endif\n\n #ifdef DEBUG_NORMAL\n gl_FragColor = vec4( 0.5 + 0.5 * normal, 1.0 );\n return;\n #endif\n\n // -- MToon: lighting --------------------------------------------------------\n // accumulation\n // #include <lights_phong_fragment>\n MToonMaterial material;\n\n material.diffuseColor = diffuseColor.rgb;\n\n material.shadeColor = shadeColorFactor;\n #ifdef USE_SHADEMULTIPLYTEXTURE\n vec2 shadeMultiplyTextureUv = ( shadeMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy;\n #if THREE_VRM_THREE_REVISION >= 137\n material.shadeColor *= texture2D( shadeMultiplyTexture, shadeMultiplyTextureUv ).rgb;\n #else\n // COMPAT: pre-r137\n material.shadeColor *= shadeMultiplyTextureTexelToLinear( texture2D( shadeMultiplyTexture, shadeMultiplyTextureUv) ).rgb;\n #endif\n #endif\n\n #if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) )\n material.shadeColor.rgb *= vColor;\n #endif\n\n material.shadingShift = shadingShiftFactor;\n #ifdef USE_SHADINGSHIFTTEXTURE\n vec2 shadingShiftTextureUv = ( shadingShiftTextureUvTransform * vec3( uv, 1 ) ).xy;\n material.shadingShift += texture2D( shadingShiftTexture, shadingShiftTextureUv ).r * shadingShiftTextureScale;\n #endif\n\n // #include <lights_fragment_begin>\n\n // MToon Specific changes:\n // Since we want to take shadows into account of shading instead of irradiance,\n // we had to modify the codes that multiplies the results of shadowmap into color of direct lights.\n\n GeometricContext geometry;\n\n geometry.position = - vViewPosition;\n geometry.normal = normal;\n geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n\n #ifdef CLEARCOAT\n\n geometry.clearcoatNormal = clearcoatNormal;\n\n #endif\n\n IncidentLight directLight;\n\n // since these variables will be used in unrolled loop, we have to define in prior\n float shadow;\n\n #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\n PointLight pointLight;\n #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n PointLightShadow pointLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n pointLight = pointLights[ i ];\n\n #if THREE_VRM_THREE_REVISION >= 132\n getPointLightInfo( pointLight, geometry, directLight );\n #else\n getPointDirectLightIrradiance( pointLight, geometry, directLight );\n #endif\n\n shadow = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n pointLightShadow = pointLightShadows[ i ];\n shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n #endif\n\n RE_Direct( directLight, geometry, material, shadow, reflectedLight );\n\n }\n #pragma unroll_loop_end\n\n #endif\n\n #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\n SpotLight spotLight;\n #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n SpotLightShadow spotLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n spotLight = spotLights[ i ];\n\n #if THREE_VRM_THREE_REVISION >= 132\n getSpotLightInfo( spotLight, geometry, directLight );\n #else\n getSpotDirectLightIrradiance( spotLight, geometry, directLight );\n #endif\n\n shadow = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n spotLightShadow = spotLightShadows[ i ];\n shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n #endif\n\n RE_Direct( directLight, geometry, material, shadow, reflectedLight );\n\n }\n #pragma unroll_loop_end\n\n #endif\n\n #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\n DirectionalLight directionalLight;\n #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n DirectionalLightShadow directionalLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n directionalLight = directionalLights[ i ];\n\n #if THREE_VRM_THREE_REVISION >= 132\n getDirectionalLightInfo( directionalLight, geometry, directLight );\n #else\n getDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n #endif\n\n shadow = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n directionalLightShadow = directionalLightShadows[ i ];\n shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n #endif\n\n RE_Direct( directLight, geometry, material, shadow, reflectedLight );\n\n }\n #pragma unroll_loop_end\n\n #endif\n\n // #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\n // RectAreaLight rectAreaLight;\n\n // #pragma unroll_loop_start\n // for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\n // rectAreaLight = rectAreaLights[ i ];\n // RE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\n // }\n // #pragma unroll_loop_end\n\n // #endif\n\n #if defined( RE_IndirectDiffuse )\n\n vec3 iblIrradiance = vec3( 0.0 );\n\n vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\n #if THREE_VRM_THREE_REVISION >= 133\n irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n #else\n irradiance += getLightProbeIrradiance( lightProbe, geometry );\n #endif\n\n #if ( NUM_HEMI_LIGHTS > 0 )\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n #if THREE_VRM_THREE_REVISION >= 133\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n #else\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n #endif\n\n }\n #pragma unroll_loop_end\n\n #endif\n\n #endif\n\n // #if defined( RE_IndirectSpecular )\n\n // vec3 radiance = vec3( 0.0 );\n // vec3 clearcoatRadiance = vec3( 0.0 );\n\n // #endif\n\n #include <lights_fragment_maps>\n #include <lights_fragment_end>\n\n // modulation\n #include <aomap_fragment>\n\n vec3 col = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\n #ifdef DEBUG_LITSHADERATE\n gl_FragColor = vec4( col, diffuseColor.a );\n postCorrection();\n return;\n #endif\n\n // -- MToon: rim lighting -----------------------------------------\n vec3 viewDir = normalize( vViewPosition );\n\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n reflectedLight.directSpecular /= PI;\n #endif\n vec3 rimMix = mix( vec3( 1.0 ), reflectedLight.directSpecular, 1.0 );\n\n vec3 rim = parametricRimColorFactor * pow( saturate( 1.0 - dot( viewDir, normal ) + parametricRimLiftFactor ), parametricRimFresnelPowerFactor );\n\n #ifdef USE_MATCAPTEXTURE\n {\n vec3 x = normalize( vec3( viewDir.z, 0.0, -viewDir.x ) );\n vec3 y = cross( viewDir, x ); // guaranteed to be normalized\n vec2 sphereUv = 0.5 + 0.5 * vec2( dot( x, normal ), -dot( y, normal ) );\n sphereUv = ( matcapTextureUvTransform * vec3( sphereUv, 1 ) ).xy;\n #if THREE_VRM_THREE_REVISION >= 137\n vec3 matcap = texture2D( matcapTexture, sphereUv ).rgb;\n #else\n // COMPAT: pre-r137\n vec3 matcap = matcapTextureTexelToLinear( texture2D( matcapTexture, sphereUv ) ).rgb;\n #endif\n rim += matcapFactor * matcap;\n }\n #endif\n\n #ifdef USE_RIMMULTIPLYTEXTURE\n vec2 rimMultiplyTextureUv = ( rimMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy;\n #if THREE_VRM_THREE_REVISION >= 137\n rim *= texture2D( rimMultiplyTexture, rimMultiplyTextureUv ).rgb;\n #else\n // COMPAT: pre-r137\n rim *= rimMultiplyTextureTexelToLinear( texture2D( rimMultiplyTexture, rimMultiplyTextureUv ) ).rgb;\n #endif\n #endif\n\n col += rimMix * rim;\n\n // -- MToon: Emission --------------------------------------------------------\n col += totalEmissiveRadiance;\n\n // #include <envmap_fragment>\n\n // -- Almost done! -----------------------------------------------------------\n #if defined( OUTLINE )\n col = outlineColorFactor.rgb * mix( vec3( 1.0 ), col, outlineLightingMixFactor );\n #endif\n\n gl_FragColor = vec4( col, diffuseColor.a );\n postCorrection();\n}\n'}),this.uvAnimationScrollXSpeedFactor=0,this.uvAnimationScrollYSpeedFactor=0,this.uvAnimationRotationSpeedFactor=0,this.fog=!0,this.normalMapType=e.TangentSpaceNormalMap,this._ignoreVertexColor=!0,this._v0CompatShade=!1,this._debugMode=Ue.None,this._outlineWidthMode=Oe.None,this._isOutline=!1,t.transparentWithZWrite&&(t.depthWrite=!0),delete t.transparentWithZWrite,t.fog=!0,t.lights=!0,t.clipping=!0,parseInt(e.REVISION,10)<129&&(t.skinning=t.skinning||!1),parseInt(e.REVISION,10)<131&&(t.morphTargets=t.morphTargets||!1,t.morphNormals=t.morphNormals||!1),this.uniforms=e.UniformsUtils.merge([e.UniformsLib.common,e.UniformsLib.normalmap,e.UniformsLib.emissivemap,e.UniformsLib.fog,e.UniformsLib.lights,{litFactor:{value:new e.Color(1,1,1)},mapUvTransform:{value:new e.Matrix3},colorAlpha:{value:1},normalMapUvTransform:{value:new e.Matrix3},shadeColorFactor:{value:new e.Color(.97,.81,.86)},shadeMultiplyTexture:{value:null},shadeMultiplyTextureUvTransform:{value:new e.Matrix3},shadingShiftFactor:{value:0},shadingShiftTexture:{value:null},shadingShiftTextureUvTransform:{value:new e.Matrix3},shadingShiftTextureScale:{value:null},shadingToonyFactor:{value:.9},giEqualizationFactor:{value:.9},matcapFactor:{value:new e.Color(0,0,0)},matcapTexture:{value:null},matcapTextureUvTransform:{value:new e.Matrix3},parametricRimColorFactor:{value:new e.Color(0,0,0)},rimMultiplyTexture:{value:null},rimMultiplyTextureUvTransform:{value:new e.Matrix3},rimLightingMixFactor:{value:0},parametricRimFresnelPowerFactor:{value:1},parametricRimLiftFactor:{value:0},emissive:{value:new e.Color(0,0,0)},emissiveIntensity:{value:1},emissiveMapUvTransform:{value:new e.Matrix3},outlineWidthMultiplyTexture:{value:null},outlineWidthMultiplyTextureUvTransform:{value:new e.Matrix3},outlineWidthFactor:{value:.5},outlineColorFactor:{value:new e.Color(0,0,0)},outlineLightingMixFactor:{value:1},uvAnimationMaskTexture:{value:null},uvAnimationMaskTextureUvTransform:{value:new e.Matrix3},uvAnimationScrollXOffset:{value:0},uvAnimationScrollYOffset:{value:0},uvAnimationRotationPhase:{value:0}},t.uniforms]),this.setValues(t),this._uploadUniformsWorkaround(),this.customProgramCacheKey=()=>[this._ignoreVertexColor?"ignoreVertexColor":"",this._v0CompatShade?"v0CompatShade":"","none"!==this._debugMode?`debugMode:${this._debugMode}`:"","none"!==this._outlineWidthMode?`outlineWidthMode:${this._outlineWidthMode}`:"",this._isOutline?"isOutline":"",...Object.entries(this._generateDefines()).map((([e,t])=>`${e}:${t}`)),this.matcapTexture?`matcapTextureEncoding:${this.matcapTexture.encoding}`:"",this.shadeMultiplyTexture?`shadeMultiplyTextureEncoding:${this.shadeMultiplyTexture.encoding}`:"",this.rimMultiplyTexture?`rimMultiplyTextureEncoding:${this.rimMultiplyTexture.encoding}`:""].join(","),this.onBeforeCompile=(t,i)=>{const n=i.capabilities.isWebGL2,r=parseInt(e.REVISION,10),o=Object.entries(Object.assign(Object.assign({},this._generateDefines()),this.defines)).filter((([e,t])=>!!t)).map((([e,t])=>`#define ${e} ${t}`)).join("\n")+"\n";let s="";parseInt(e.REVISION,10)<137&&(s=(null!==this.matcapTexture?Ve("matcapTextureTexelToLinear",Ce(this.matcapTexture,n))+"\n":"")+(null!==this.shadeMultiplyTexture?Ve("shadeMultiplyTextureTexelToLinear",Ce(this.shadeMultiplyTexture,n))+"\n":"")+(null!==this.rimMultiplyTexture?Ve("rimMultiplyTextureTexelToLinear",Ce(this.rimMultiplyTexture,n))+"\n":"")),t.vertexShader=o+t.vertexShader,t.fragmentShader=o+s+t.fragmentShader,r<132&&(t.fragmentShader=t.fragmentShader.replace("#include <normal_pars_fragment>",""),t.fragmentShader=t.fragmentShader.replace("#include <alphatest_pars_fragment>",""))}}get color(){return this.uniforms.litFactor.value}set color(e){this.uniforms.litFactor.value=e}get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}get normalMap(){return this.uniforms.normalMap.value}set normalMap(e){this.uniforms.normalMap.value=e}get normalScale(){return this.uniforms.normalScale.value}set normalScale(e){this.uniforms.normalScale.value=e}get emissive(){return this.uniforms.emissive.value}set emissive(e){this.uniforms.emissive.value=e}get emissiveIntensity(){return this.uniforms.emissiveIntensity.value}set emissiveIntensity(e){this.uniforms.emissiveIntensity.value=e}get emissiveMap(){return this.uniforms.emissiveMap.value}set emissiveMap(e){this.uniforms.emissiveMap.value=e}get shadeColorFactor(){return this.uniforms.shadeColorFactor.value}set shadeColorFactor(e){this.uniforms.shadeColorFactor.value=e}get shadeMultiplyTexture(){return this.uniforms.shadeMultiplyTexture.value}set shadeMultiplyTexture(e){this.uniforms.shadeMultiplyTexture.value=e}get shadingShiftFactor(){return this.uniforms.shadingShiftFactor.value}set shadingShiftFactor(e){this.uniforms.shadingShiftFactor.value=e}get shadingShiftTexture(){return this.uniforms.shadingShiftTexture.value}set shadingShiftTexture(e){this.uniforms.shadingShiftTexture.value=e}get shadingShiftTextureScale(){return this.uniforms.shadingShiftTextureScale.value}set shadingShiftTextureScale(e){this.uniforms.shadingShiftTextureScale.value=e}get shadingToonyFactor(){return this.uniforms.shadingToonyFactor.value}set shadingToonyFactor(e){this.uniforms.shadingToonyFactor.value=e}get giEqualizationFactor(){return this.uniforms.giEqualizationFactor.value}set giEqualizationFactor(e){this.uniforms.giEqualizationFactor.value=e}get matcapFactor(){return this.uniforms.matcapFactor.value}set matcapFactor(e){this.uniforms.matcapFactor.value=e}get matcapTexture(){return this.uniforms.matcapTexture.value}set matcapTexture(e){this.uniforms.matcapTexture.value=e}get parametricRimColorFactor(){return this.uniforms.parametricRimColorFactor.value}set parametricRimColorFactor(e){this.uniforms.parametricRimColorFactor.value=e}get rimMultiplyTexture(){return this.uniforms.rimMultiplyTexture.value}set rimMultiplyTexture(e){this.uniforms.rimMultiplyTexture.value=e}get rimLightingMixFactor(){return this.uniforms.rimLightingMixFactor.value}set rimLightingMixFactor(e){this.uniforms.rimLightingMixFactor.value=e}get parametricRimFresnelPowerFactor(){return this.uniforms.parametricRimFresnelPowerFactor.value}set parametricRimFresnelPowerFactor(e){this.uniforms.parametricRimFresnelPowerFactor.value=e}get parametricRimLiftFactor(){return this.uniforms.parametricRimLiftFactor.value}set parametricRimLiftFactor(e){this.uniforms.parametricRimLiftFactor.value=e}get outlineWidthMultiplyTexture(){return this.uniforms.outlineWidthMultiplyTexture.value}set outlineWidthMultiplyTexture(e){this.uniforms.outlineWidthMultiplyTexture.value=e}get outlineWidthFactor(){return this.uniforms.outlineWidthFactor.value}set outlineWidthFactor(e){this.uniforms.outlineWidthFactor.value=e}get outlineColorFactor(){return this.uniforms.outlineColorFactor.value}set outlineColorFactor(e){this.uniforms.outlineColorFactor.value=e}get outlineLightingMixFactor(){return this.uniforms.outlineLightingMixFactor.value}set outlineLightingMixFactor(e){this.uniforms.outlineLightingMixFactor.value=e}get uvAnimationMaskTexture(){return this.uniforms.uvAnimationMaskTexture.value}set uvAnimationMaskTexture(e){this.uniforms.uvAnimationMaskTexture.value=e}get uvAnimationScrollXOffset(){return this.uniforms.uvAnimationScrollXOffset.value}set uvAnimationScrollXOffset(e){this.uniforms.uvAnimationScrollXOffset.value=e}get uvAnimationScrollYOffset(){return this.uniforms.uvAnimationScrollYOffset.value}set uvAnimationScrollYOffset(e){this.uniforms.uvAnimationScrollYOffset.value=e}get uvAnimationRotationPhase(){return this.uniforms.uvAnimationRotationPhase.value}set uvAnimationRotationPhase(e){this.uniforms.uvAnimationRotationPhase.value=e}get ignoreVertexColor(){return this._ignoreVertexColor}set ignoreVertexColor(e){this._ignoreVertexColor=e,this.needsUpdate=!0}get v0CompatShade(){return this._v0CompatShade}set v0CompatShade(e){this._v0CompatShade=e,this.needsUpdate=!0}get debugMode(){return this._debugMode}set debugMode(e){this._debugMode=e,this.needsUpdate=!0}get outlineWidthMode(){return this._outlineWidthMode}set outlineWidthMode(e){this._outlineWidthMode=e,this.needsUpdate=!0}get isOutline(){return this._isOutline}set isOutline(e){this._isOutline=e,this.needsUpdate=!0}get isMToonMaterial(){return!0}update(e){this._uploadUniformsWorkaround(),this._updateUVAnimation(e)}copy(e){return super.copy(e),this.map=e.map,this.normalMap=e.normalMap,this.emissiveMap=e.emissiveMap,this.shadeMultiplyTexture=e.shadeMultiplyTexture,this.shadingShiftTexture=e.shadingShiftTexture,this.matcapTexture=e.matcapTexture,this.rimMultiplyTexture=e.rimMultiplyTexture,this.outlineWidthMultiplyTexture=e.outlineWidthMultiplyTexture,this.uvAnimationMaskTexture=e.uvAnimationMaskTexture,this.normalMapType=e.normalMapType,this.uvAnimationScrollXSpeedFactor=e.uvAnimationScrollXSpeedFactor,this.uvAnimationScrollYSpeedFactor=e.uvAnimationScrollYSpeedFactor,this.uvAnimationRotationSpeedFactor=e.uvAnimationRotationSpeedFactor,this.ignoreVertexColor=e.ignoreVertexColor,this.v0CompatShade=e.v0CompatShade,this.debugMode=e.debugMode,this.outlineWidthMode=e.outlineWidthMode,this.isOutline=e.isOutline,this.needsUpdate=!0,this}_updateUVAnimation(e){this.uniforms.uvAnimationScrollXOffset.value+=e*this.uvAnimationScrollXSpeedFactor,this.uniforms.uvAnimationScrollYOffset.value+=e*this.uvAnimationScrollYSpeedFactor,this.uniforms.uvAnimationRotationPhase.value+=e*this.uvAnimationRotationSpeedFactor,this.uniformsNeedUpdate=!0}_uploadUniformsWorkaround(){this.uniforms.opacity.value=this.opacity,this._updateTextureMatrix(this.uniforms.map,this.uniforms.mapUvTransform),this._updateTextureMatrix(this.uniforms.normalMap,this.uniforms.normalMapUvTransform),this._updateTextureMatrix(this.uniforms.emissiveMap,this.uniforms.emissiveMapUvTransform),this._updateTextureMatrix(this.uniforms.shadeMultiplyTexture,this.uniforms.shadeMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.shadingShiftTexture,this.uniforms.shadingShiftTextureUvTransform),this._updateTextureMatrix(this.uniforms.matcapTexture,this.uniforms.matcapTextureUvTransform),this._updateTextureMatrix(this.uniforms.rimMultiplyTexture,this.uniforms.rimMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.outlineWidthMultiplyTexture,this.uniforms.outlineWidthMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.uvAnimationMaskTexture,this.uniforms.uvAnimationMaskTextureUvTransform);parseInt(e.REVISION,10)>=132&&(this.uniforms.alphaTest.value=this.alphaTest),this.uniformsNeedUpdate=!0}_generateDefines(){const t=parseInt(e.REVISION,10),i=null!==this.outlineWidthMultiplyTexture,n=null!==this.map||null!==this.emissiveMap||null!==this.shadeMultiplyTexture||null!==this.shadingShiftTexture||null!==this.rimMultiplyTexture||null!==this.uvAnimationMaskTexture;return{THREE_VRM_THREE_REVISION:t,OUTLINE:this._isOutline,MTOON_USE_UV:i||n,MTOON_UVS_VERTEX_ONLY:i&&!n,V0_COMPAT_SHADE:this._v0CompatShade,USE_SHADEMULTIPLYTEXTURE:null!==this.shadeMultiplyTexture,USE_SHADINGSHIFTTEXTURE:null!==this.shadingShiftTexture,USE_MATCAPTEXTURE:null!==this.matcapTexture,USE_RIMMULTIPLYTEXTURE:null!==this.rimMultiplyTexture,USE_OUTLINEWIDTHMULTIPLYTEXTURE:null!==this.outlineWidthMultiplyTexture,USE_UVANIMATIONMASKTEXTURE:null!==this.uvAnimationMaskTexture,IGNORE_VERTEX_COLOR:!0===this._ignoreVertexColor,DEBUG_NORMAL:"normal"===this._debugMode,DEBUG_LITSHADERATE:"litShadeRate"===this._debugMode,DEBUG_UV:"uv"===this._debugMode,OUTLINE_WIDTH_WORLD:this._outlineWidthMode===Oe.WorldCoordinates,OUTLINE_WIDTH_SCREEN:this._outlineWidthMode===Oe.ScreenCoordinates}}_updateTextureMatrix(e,t){e.value&&(e.value.matrixAutoUpdate&&e.value.updateMatrix(),t.value.copy(e.value.matrix))}}class De{constructor(e,t){this._parser=e,this._materialParams=t,this._pendings=[]}get pending(){return Promise.all(this._pendings)}assignPrimitive(e,t){null!=t&&(this._materialParams[e]=t)}assignColor(t,i,n){null!=i&&(this._materialParams[t]=(new e.Color).fromArray(i),n&&this._materialParams[t].convertSRGBToLinear())}assignTexture(t,i,n){return Ie(this,void 0,void 0,(function*(){const r=(()=>Ie(this,void 0,void 0,(function*(){null!=i&&(yield this._parser.assignTexture(this._materialParams,t,i),n&&(this._materialParams[t].encoding=e.sRGBEncoding))})))();return this._pendings.push(r),r}))}assignTextureByIndex(e,t,i){return Ie(this,void 0,void 0,(function*(){return this.assignTexture(e,null!=t?{index:t}:void 0,i)}))}}const Fe=new Set(["1.0","1.0-beta"]);class Be{constructor(e,t={}){var i,n,r;this.parser=e,this.renderOrderOffset=null!==(i=t.renderOrderOffset)&&void 0!==i?i:0,this.v0CompatShade=null!==(n=t.v0CompatShade)&&void 0!==n&&n,this.debugMode=null!==(r=t.debugMode)&&void 0!==r?r:"none",this._mToonMaterialSet=new Set}get name(){return Be.EXTENSION_NAME}beforeRoot(){return Ie(this,void 0,void 0,(function*(){this._removeUnlitExtensionIfMToonExists()}))}afterRoot(e){return Ie(this,void 0,void 0,(function*(){e.userData.vrmMToonMaterials=Array.from(this._mToonMaterialSet)}))}getMaterialType(e){return this._getMToonExtension(e)?Ne:null}extendMaterialParams(e,t){const i=this._getMToonExtension(e);return i?this._extendMaterialParams(i,t):null}loadMesh(e){var t;return Ie(this,void 0,void 0,(function*(){const i=this.parser,n=i.json,r=null===(t=n.meshes)||void 0===t?void 0:t[e];if(null==r)throw new Error(`MToonMaterialLoaderPlugin: Attempt to use meshes[${e}] of glTF but the mesh doesn't exist`);const o=r.primitives,s=yield i.loadMesh(e);if(1===o.length){const e=s,t=o[0].material;null!=t&&this._setupPrimitive(e,t)}else{const e=s;for(let t=0;t<o.length;t++){const i=e.children[t],n=o[t].material;null!=n&&this._setupPrimitive(i,n)}}return s}))}_removeUnlitExtensionIfMToonExists(){const e=this.parser.json.materials;null==e||e.map(((e,t)=>{var i;this._getMToonExtension(t)&&(null===(i=e.extensions)||void 0===i?void 0:i.KHR_materials_unlit)&&delete e.extensions.KHR_materials_unlit}))}_getMToonExtension(e){var t,i;const n=null===(t=this.parser.json.materials)||void 0===t?void 0:t[e];if(null==n)return void console.warn(`MToonMaterialLoaderPlugin: Attempt to use materials[${e}] of glTF but the material doesn't exist`);const r=null===(i=n.extensions)||void 0===i?void 0:i[Be.EXTENSION_NAME];if(null==r)return;const o=r.specVersion;if(Fe.has(o))return r;console.warn(`MToonMaterialLoaderPlugin: Unknown ${Be.EXTENSION_NAME} specVersion "${o}"`)}_extendMaterialParams(e,t){var i;return Ie(this,void 0,void 0,(function*(){delete t.metalness,delete t.roughness;const n=new De(this.parser,t);n.assignPrimitive("transparentWithZWrite",e.transparentWithZWrite),n.assignColor("shadeColorFactor",e.shadeColorFactor),n.assignTexture("shadeMultiplyTexture",e.shadeMultiplyTexture,!0),n.assignPrimitive("shadingShiftFactor",e.shadingShiftFactor),n.assignTexture("shadingShiftTexture",e.shadingShiftTexture,!0),n.assignPrimitive("shadingShiftTextureScale",null===(i=e.shadingShiftTexture)||void 0===i?void 0:i.scale),n.assignPrimitive("shadingToonyFactor",e.shadingToonyFactor),n.assignPrimitive("giEqualizationFactor",e.giEqualizationFactor),n.assignColor("matcapFactor",e.matcapFactor),n.assignTexture("matcapTexture",e.matcapTexture,!0),n.assignColor("parametricRimColorFactor",e.parametricRimColorFactor),n.assignTexture("rimMultiplyTexture",e.rimMultiplyTexture,!0),n.assignPrimitive("rimLightingMixFactor",e.rimLightingMixFactor),n.assignPrimitive("parametricRimFresnelPowerFactor",e.parametricRimFresnelPowerFactor),n.assignPrimitive("parametricRimLiftFactor",e.parametricRimLiftFactor),n.assignPrimitive("outlineWidthMode",e.outlineWidthMode),n.assignPrimitive("outlineWidthFactor",e.outlineWidthFactor),n.assignTexture("outlineWidthMultiplyTexture",e.outlineWidthMultiplyTexture,!1),n.assignColor("outlineColorFactor",e.outlineColorFactor),n.assignPrimitive("outlineLightingMixFactor",e.outlineLightingMixFactor),n.assignTexture("uvAnimationMaskTexture",e.uvAnimationMaskTexture,!1),n.assignPrimitive("uvAnimationScrollXSpeedFactor",e.uvAnimationScrollXSpeedFactor),n.assignPrimitive("uvAnimationScrollYSpeedFactor",e.uvAnimationScrollYSpeedFactor),n.assignPrimitive("uvAnimationRotationSpeedFactor",e.uvAnimationRotationSpeedFactor),n.assignPrimitive("v0CompatShade",this.v0CompatShade),n.assignPrimitive("debugMode",this.debugMode),yield n.pending}))}_setupPrimitive(e,t){const i=this._getMToonExtension(t);if(i){const t=this._parseRenderOrder(i);return e.renderOrder=t+this.renderOrderOffset,this._generateOutline(e),void this._addToMaterialSet(e)}}_generateOutline(t){const i=t.material;if(!(i instanceof Ne))return;if("none"===i.outlineWidthMode||i.outlineWidthFactor<=0)return;t.material=[i];const n=i.clone();n.name+=" (Outline)",n.isOutline=!0,n.side=e.BackSide,t.material.push(n);const r=t.geometry,o=r.index?r.index.count:r.attributes.position.count/3;r.addGroup(0,o,0),r.addGroup(0,o,1)}_addToMaterialSet(e){const t=e.material,i=new Set;Array.isArray(t)?t.forEach((e=>i.add(e))):i.add(t);for(const e of i)e instanceof Ne&&this._mToonMaterialSet.add(e)}_parseRenderOrder(e){var t;return(e.transparentWithZWrite?0:19)+(null!==(t=e.renderQueueOffsetNumber)&&void 0!==t?t:0)}}
|
|
19
|
+
*/function Ue(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())}))}const Oe={None:"none",Normal:"normal",LitShadeRate:"litShadeRate",UV:"uv"},Ve={None:"none",WorldCoordinates:"worldCoordinates",ScreenCoordinates:"screenCoordinates"},Ce=(t,i)=>{const n=(t=>{if(parseInt(e.REVISION,10)>=136)switch(t){case e.LinearEncoding:return["Linear","( value )"];case e.sRGBEncoding:return["sRGB","( value )"];default:return console.warn("THREE.WebGLProgram: Unsupported encoding:",t),["Linear","( value )"]}else switch(t){case e.LinearEncoding:return["Linear","( value )"];case e.sRGBEncoding:return["sRGB","( value )"];case 3002:return["RGBE","( value )"];case 3004:return["RGBM","( value, 7.0 )"];case 3005:return["RGBM","( value, 16.0 )"];case 3006:return["RGBD","( value, 256.0 )"];case 3007:return["Gamma","( value, float( GAMMA_FACTOR ) )"];default:throw new Error("unsupported encoding: "+t)}})(i);return"vec4 "+t+"( vec4 value ) { return "+n[0]+"ToLinear"+n[1]+"; }"};function Ne(t,i){let n;return n=t&&t.isTexture?t.encoding:e.LinearEncoding,parseInt(e.REVISION,10)>=133&&i&&t&&t.isTexture&&t.format===e.RGBAFormat&&t.type===e.UnsignedByteType&&t.encoding===e.sRGBEncoding&&(n=e.LinearEncoding),n}class De extends e.ShaderMaterial{constructor(t={}){super({vertexShader:"// #define PHONG\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n\n#include <common>\n\n// #include <uv_pars_vertex>\n#ifdef MTOON_USE_UV\n varying vec2 vUv;\n uniform mat3 uvTransform;\n#endif\n\n#include <uv2_pars_vertex>\n// #include <displacementmap_pars_vertex>\n// #include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\n#ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE\n uniform sampler2D outlineWidthMultiplyTexture;\n uniform mat3 outlineWidthMultiplyTextureUvTransform;\n#endif\n\nuniform float outlineWidthFactor;\n\nvoid main() {\n\n // #include <uv_vertex>\n #ifdef MTOON_USE_UV\n vUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n #endif\n\n #include <uv2_vertex>\n #include <color_vertex>\n\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n\n // we need this to compute the outline properly\n objectNormal = normalize( objectNormal );\n\n #include <defaultnormal_vertex>\n\n #ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n vNormal = normalize( transformedNormal );\n #endif\n\n #include <begin_vertex>\n\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n // #include <displacementmap_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n\n vViewPosition = - mvPosition.xyz;\n\n float outlineTex = 1.0;\n\n #ifdef OUTLINE\n #ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE\n vec2 outlineWidthMultiplyTextureUv = ( outlineWidthMultiplyTextureUvTransform * vec3( vUv, 1 ) ).xy;\n outlineTex = texture2D( outlineWidthMultiplyTexture, outlineWidthMultiplyTextureUv ).g;\n #endif\n\n #ifdef OUTLINE_WIDTH_WORLD\n float worldNormalLength = length( transformedNormal );\n vec3 outlineOffset = outlineWidthFactor * outlineTex * worldNormalLength * objectNormal;\n gl_Position = projectionMatrix * modelViewMatrix * vec4( outlineOffset + transformed, 1.0 );\n #endif\n\n #ifdef OUTLINE_WIDTH_SCREEN\n vec3 clipNormal = ( projectionMatrix * modelViewMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n vec2 projectedNormal = normalize( clipNormal.xy );\n projectedNormal.x *= projectionMatrix[ 0 ].x / projectionMatrix[ 1 ].y;\n gl_Position.xy += 2.0 * outlineWidthFactor * outlineTex * projectedNormal.xy;\n #endif\n\n gl_Position.z += 1E-6 * gl_Position.w; // anti-artifact magic\n #endif\n\n #include <worldpos_vertex>\n // #include <envmap_vertex>\n #include <shadowmap_vertex>\n #include <fog_vertex>\n\n}",fragmentShader:'// #define PHONG\n\nuniform vec3 litFactor;\n\nuniform float opacity;\n\nuniform vec3 shadeColorFactor;\n#ifdef USE_SHADEMULTIPLYTEXTURE\n uniform sampler2D shadeMultiplyTexture;\n uniform mat3 shadeMultiplyTextureUvTransform;\n#endif\n\nuniform float shadingShiftFactor;\nuniform float shadingToonyFactor;\n\n#ifdef USE_SHADINGSHIFTTEXTURE\n uniform sampler2D shadingShiftTexture;\n uniform mat3 shadingShiftTextureUvTransform;\n uniform float shadingShiftTextureScale;\n#endif\n\nuniform float giEqualizationFactor;\n\nuniform vec3 parametricRimColorFactor;\n#ifdef USE_RIMMULTIPLYTEXTURE\n uniform sampler2D rimMultiplyTexture;\n uniform mat3 rimMultiplyTextureUvTransform;\n#endif\nuniform float rimLightingMixFactor;\nuniform float parametricRimFresnelPowerFactor;\nuniform float parametricRimLiftFactor;\n\n#ifdef USE_MATCAPTEXTURE\n uniform vec3 matcapFactor;\n uniform sampler2D matcapTexture;\n uniform mat3 matcapTextureUvTransform;\n#endif\n\nuniform vec3 emissive;\nuniform float emissiveIntensity;\n\nuniform vec3 outlineColorFactor;\nuniform float outlineLightingMixFactor;\n\n#ifdef USE_UVANIMATIONMASKTEXTURE\n uniform sampler2D uvAnimationMaskTexture;\n uniform mat3 uvAnimationMaskTextureUvTransform;\n#endif\n\nuniform float uvAnimationScrollXOffset;\nuniform float uvAnimationScrollYOffset;\nuniform float uvAnimationRotationPhase;\n\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n\n// #include <uv_pars_fragment>\n#if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n varying vec2 vUv;\n#endif\n\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n\n#ifdef USE_MAP\n uniform mat3 mapUvTransform;\n#endif\n\n// #include <alphamap_pars_fragment>\n\n#if THREE_VRM_THREE_REVISION >= 132\n #include <alphatest_pars_fragment>\n#endif\n\n#include <aomap_pars_fragment>\n// #include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n\n#ifdef USE_EMISSIVEMAP\n uniform mat3 emissiveMapUvTransform;\n#endif\n\n// #include <envmap_common_pars_fragment>\n// #include <envmap_pars_fragment>\n// #include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n\n// #include <bsdfs>\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n return RECIPROCAL_PI * diffuseColor;\n}\n\n#include <lights_pars_begin>\n\n#if THREE_VRM_THREE_REVISION >= 132\n #include <normal_pars_fragment>\n#endif\n\n// #include <lights_phong_pars_fragment>\nvarying vec3 vViewPosition;\n\n#if THREE_VRM_THREE_REVISION < 132\n #ifndef FLAT_SHADED\n varying vec3 vNormal;\n #endif\n#endif\n\nstruct MToonMaterial {\n vec3 diffuseColor;\n vec3 shadeColor;\n float shadingShift;\n};\n\nfloat linearstep( float a, float b, float t ) {\n return clamp( ( t - a ) / ( b - a ), 0.0, 1.0 );\n}\n\n/**\n * Convert NdotL into toon shading factor using shadingShift and shadingToony\n */\nfloat getShading(\n const in float dotNL,\n const in float shadow,\n const in float shadingShift\n) {\n float shading = dotNL;\n shading = shading + shadingShift;\n shading = linearstep( -1.0 + shadingToonyFactor, 1.0 - shadingToonyFactor, shading );\n shading *= shadow;\n return shading;\n}\n\n/**\n * Mix diffuseColor and shadeColor using shading factor and light color\n */\nvec3 getDiffuse(\n const in MToonMaterial material,\n const in float shading,\n in vec3 lightColor\n) {\n #ifdef DEBUG_LITSHADERATE\n return vec3( BRDF_Lambert( shading * lightColor ) );\n #endif\n\n #if THREE_VRM_THREE_REVISION < 132\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n lightColor *= PI;\n #endif\n #endif\n\n vec3 col = lightColor * BRDF_Lambert( mix( material.shadeColor, material.diffuseColor, shading ) );\n\n // The "comment out if you want to PBR absolutely" line\n #ifdef V0_COMPAT_SHADE\n col = min( col, material.diffuseColor );\n #endif\n\n return col;\n}\n\nvoid RE_Direct_MToon( const in IncidentLight directLight, const in GeometricContext geometry, const in MToonMaterial material, const in float shadow, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n vec3 irradiance = directLight.color;\n\n #if THREE_VRM_THREE_REVISION < 132\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n irradiance *= PI;\n #endif\n #endif\n\n // directSpecular will be used for rim lighting, not an actual specular\n reflectedLight.directSpecular += irradiance;\n\n irradiance *= dotNL;\n\n float shading = getShading( dotNL, shadow, material.shadingShift );\n\n // toon shaded diffuse\n reflectedLight.directDiffuse += getDiffuse( material, shading, directLight.color );\n}\n\nvoid RE_IndirectDiffuse_MToon( const in vec3 irradiance, const in GeometricContext geometry, const in MToonMaterial material, inout ReflectedLight reflectedLight ) {\n // indirect diffuse will use diffuseColor, no shadeColor involved\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\n // directSpecular will be used for rim lighting, not an actual specular\n reflectedLight.directSpecular += irradiance;\n}\n\n#define RE_Direct RE_Direct_MToon\n#define RE_IndirectDiffuse RE_IndirectDiffuse_MToon\n#define Material_LightProbeLOD( material ) (0)\n\n#include <shadowmap_pars_fragment>\n// #include <bumpmap_pars_fragment>\n\n// #include <normalmap_pars_fragment>\n#ifdef USE_NORMALMAP\n\n uniform sampler2D normalMap;\n uniform mat3 normalMapUvTransform;\n uniform vec2 normalScale;\n\n#endif\n\n#ifdef OBJECTSPACE_NORMALMAP\n\n uniform mat3 normalMatrix;\n\n#endif\n\n#if ! defined ( USE_TANGENT ) && defined ( TANGENTSPACE_NORMALMAP )\n\n // Per-Pixel Tangent Space Normal Mapping\n // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n // three-vrm specific change: it requires `uv` as an input in order to support uv scrolls\n\n // Temporary compat against shader change @ Three.js r126\n // See: #21205, #21307, #21299\n #if THREE_VRM_THREE_REVISION >= 126\n\n vec3 perturbNormal2Arb( vec2 uv, vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\n vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n vec2 st0 = dFdx( uv.st );\n vec2 st1 = dFdy( uv.st );\n\n vec3 N = normalize( surf_norm );\n\n vec3 q1perp = cross( q1, N );\n vec3 q0perp = cross( N, q0 );\n\n vec3 T = q1perp * st0.x + q0perp * st1.x;\n vec3 B = q1perp * st0.y + q0perp * st1.y;\n\n // three-vrm specific change: Workaround for the issue that happens when delta of uv = 0.0\n // TODO: Is this still required? Or shall I make a PR about it?\n if ( length( T ) == 0.0 || length( B ) == 0.0 ) {\n return surf_norm;\n }\n\n float det = max( dot( T, T ), dot( B, B ) );\n float scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\n return normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\n }\n\n #else\n\n vec3 perturbNormal2Arb( vec2 uv, vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\n // Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988\n\n vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n vec2 st0 = dFdx( uv.st );\n vec2 st1 = dFdy( uv.st );\n\n float scale = sign( st1.t * st0.s - st0.t * st1.s ); // we do not care about the magnitude\n\n vec3 S = ( q0 * st1.t - q1 * st0.t ) * scale;\n vec3 T = ( - q0 * st1.s + q1 * st0.s ) * scale;\n\n // three-vrm specific change: Workaround for the issue that happens when delta of uv = 0.0\n // TODO: Is this still required? Or shall I make a PR about it?\n\n if ( length( S ) == 0.0 || length( T ) == 0.0 ) {\n return surf_norm;\n }\n\n S = normalize( S );\n T = normalize( T );\n vec3 N = normalize( surf_norm );\n\n #ifdef DOUBLE_SIDED\n\n // Workaround for Adreno GPUs gl_FrontFacing bug. See #15850 and #10331\n\n bool frontFacing = dot( cross( S, T ), N ) > 0.0;\n\n mapN.xy *= ( float( frontFacing ) * 2.0 - 1.0 );\n\n #else\n\n mapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n #endif\n\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n\n }\n\n #endif\n\n#endif\n\n// #include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\n// == post correction ==========================================================\nvoid postCorrection() {\n #include <tonemapping_fragment>\n #include <encodings_fragment>\n #include <fog_fragment>\n #include <premultiplied_alpha_fragment>\n #include <dithering_fragment>\n}\n\n// == main procedure ===========================================================\nvoid main() {\n #include <clipping_planes_fragment>\n\n vec2 uv = vec2(0.5, 0.5);\n\n #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n uv = vUv;\n\n float uvAnimMask = 1.0;\n #ifdef USE_UVANIMATIONMASKTEXTURE\n vec2 uvAnimationMaskTextureUv = ( uvAnimationMaskTextureUvTransform * vec3( uv, 1 ) ).xy;\n uvAnimMask = texture2D( uvAnimationMaskTexture, uvAnimationMaskTextureUv ).b;\n #endif\n\n uv = uv + vec2( uvAnimationScrollXOffset, uvAnimationScrollYOffset ) * uvAnimMask;\n float uvRotCos = cos( uvAnimationRotationPhase * uvAnimMask );\n float uvRotSin = sin( uvAnimationRotationPhase * uvAnimMask );\n uv = mat2( uvRotCos, uvRotSin, -uvRotSin, uvRotCos ) * ( uv - 0.5 ) + 0.5;\n #endif\n\n #ifdef DEBUG_UV\n gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n gl_FragColor = vec4( uv, 0.0, 1.0 );\n #endif\n return;\n #endif\n\n vec4 diffuseColor = vec4( litFactor, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive * emissiveIntensity;\n\n #include <logdepthbuf_fragment>\n\n // #include <map_fragment>\n #ifdef USE_MAP\n vec2 mapUv = ( mapUvTransform * vec3( uv, 1 ) ).xy;\n #if THREE_VRM_THREE_REVISION >= 137\n vec4 sampledDiffuseColor = texture2D( map, mapUv );\n #ifdef DECODE_VIDEO_TEXTURE\n sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n #endif\n diffuseColor *= sampledDiffuseColor;\n #else\n // COMPAT: pre-r137\n vec4 texelColor = texture2D( map, mapUv );\n texelColor = mapTexelToLinear( texelColor );\n diffuseColor *= texelColor;\n #endif\n #endif\n\n // #include <color_fragment>\n #if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) )\n diffuseColor.rgb *= vColor;\n #endif\n\n // #include <alphamap_fragment>\n\n #include <alphatest_fragment>\n\n // #include <specularmap_fragment>\n #include <normal_fragment_begin>\n\n #ifdef OUTLINE\n normal *= -1.0;\n #endif\n\n // #include <normal_fragment_maps>\n\n #ifdef OBJECTSPACE_NORMALMAP\n\n vec2 normalMapUv = ( normalMapUvTransform * vec3( uv, 1 ) ).xy;\n normal = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0; // overrides both flatShading and attribute normals\n\n #ifdef FLIP_SIDED\n\n normal = - normal;\n\n #endif\n\n #ifdef DOUBLE_SIDED\n\n // Temporary compat against shader change @ Three.js r126\n // See: #21205, #21307, #21299\n #if THREE_VRM_THREE_REVISION >= 126\n\n normal = normal * faceDirection;\n\n #else\n\n normal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n #endif\n\n #endif\n\n normal = normalize( normalMatrix * normal );\n\n #elif defined( TANGENTSPACE_NORMALMAP )\n\n vec2 normalMapUv = ( normalMapUvTransform * vec3( uv, 1 ) ).xy;\n vec3 mapN = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0;\n mapN.xy *= normalScale;\n\n #ifdef USE_TANGENT\n\n normal = normalize( vTBN * mapN );\n\n #else\n\n // Temporary compat against shader change @ Three.js r126\n // See: #21205, #21307, #21299\n #if THREE_VRM_THREE_REVISION >= 126\n\n normal = perturbNormal2Arb( uv, -vViewPosition, normal, mapN, faceDirection );\n\n #else\n\n normal = perturbNormal2Arb( uv, -vViewPosition, normal, mapN );\n\n #endif\n\n #endif\n\n #endif\n\n // #include <emissivemap_fragment>\n #ifdef USE_EMISSIVEMAP\n vec2 emissiveMapUv = ( emissiveMapUvTransform * vec3( uv, 1 ) ).xy;\n #if THREE_VRM_THREE_REVISION >= 137\n totalEmissiveRadiance *= texture2D( emissiveMap, emissiveMapUv ).rgb;\n #else\n // COMPAT: pre-r137\n totalEmissiveRadiance *= emissiveMapTexelToLinear( texture2D( emissiveMap, emissiveMapUv ) ).rgb;\n #endif\n #endif\n\n #ifdef DEBUG_NORMAL\n gl_FragColor = vec4( 0.5 + 0.5 * normal, 1.0 );\n return;\n #endif\n\n // -- MToon: lighting --------------------------------------------------------\n // accumulation\n // #include <lights_phong_fragment>\n MToonMaterial material;\n\n material.diffuseColor = diffuseColor.rgb;\n\n material.shadeColor = shadeColorFactor;\n #ifdef USE_SHADEMULTIPLYTEXTURE\n vec2 shadeMultiplyTextureUv = ( shadeMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy;\n #if THREE_VRM_THREE_REVISION >= 137\n material.shadeColor *= texture2D( shadeMultiplyTexture, shadeMultiplyTextureUv ).rgb;\n #else\n // COMPAT: pre-r137\n material.shadeColor *= shadeMultiplyTextureTexelToLinear( texture2D( shadeMultiplyTexture, shadeMultiplyTextureUv) ).rgb;\n #endif\n #endif\n\n #if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) )\n material.shadeColor.rgb *= vColor;\n #endif\n\n material.shadingShift = shadingShiftFactor;\n #ifdef USE_SHADINGSHIFTTEXTURE\n vec2 shadingShiftTextureUv = ( shadingShiftTextureUvTransform * vec3( uv, 1 ) ).xy;\n material.shadingShift += texture2D( shadingShiftTexture, shadingShiftTextureUv ).r * shadingShiftTextureScale;\n #endif\n\n // #include <lights_fragment_begin>\n\n // MToon Specific changes:\n // Since we want to take shadows into account of shading instead of irradiance,\n // we had to modify the codes that multiplies the results of shadowmap into color of direct lights.\n\n GeometricContext geometry;\n\n geometry.position = - vViewPosition;\n geometry.normal = normal;\n geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n\n #ifdef CLEARCOAT\n\n geometry.clearcoatNormal = clearcoatNormal;\n\n #endif\n\n IncidentLight directLight;\n\n // since these variables will be used in unrolled loop, we have to define in prior\n float shadow;\n\n #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\n PointLight pointLight;\n #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n PointLightShadow pointLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n pointLight = pointLights[ i ];\n\n #if THREE_VRM_THREE_REVISION >= 132\n getPointLightInfo( pointLight, geometry, directLight );\n #else\n getPointDirectLightIrradiance( pointLight, geometry, directLight );\n #endif\n\n shadow = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n pointLightShadow = pointLightShadows[ i ];\n shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n #endif\n\n RE_Direct( directLight, geometry, material, shadow, reflectedLight );\n\n }\n #pragma unroll_loop_end\n\n #endif\n\n #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\n SpotLight spotLight;\n #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n SpotLightShadow spotLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n spotLight = spotLights[ i ];\n\n #if THREE_VRM_THREE_REVISION >= 132\n getSpotLightInfo( spotLight, geometry, directLight );\n #else\n getSpotDirectLightIrradiance( spotLight, geometry, directLight );\n #endif\n\n shadow = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n spotLightShadow = spotLightShadows[ i ];\n shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n #endif\n\n RE_Direct( directLight, geometry, material, shadow, reflectedLight );\n\n }\n #pragma unroll_loop_end\n\n #endif\n\n #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\n DirectionalLight directionalLight;\n #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n DirectionalLightShadow directionalLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n directionalLight = directionalLights[ i ];\n\n #if THREE_VRM_THREE_REVISION >= 132\n getDirectionalLightInfo( directionalLight, geometry, directLight );\n #else\n getDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n #endif\n\n shadow = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n directionalLightShadow = directionalLightShadows[ i ];\n shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n #endif\n\n RE_Direct( directLight, geometry, material, shadow, reflectedLight );\n\n }\n #pragma unroll_loop_end\n\n #endif\n\n // #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\n // RectAreaLight rectAreaLight;\n\n // #pragma unroll_loop_start\n // for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\n // rectAreaLight = rectAreaLights[ i ];\n // RE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\n // }\n // #pragma unroll_loop_end\n\n // #endif\n\n #if defined( RE_IndirectDiffuse )\n\n vec3 iblIrradiance = vec3( 0.0 );\n\n vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\n #if THREE_VRM_THREE_REVISION >= 133\n irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n #else\n irradiance += getLightProbeIrradiance( lightProbe, geometry );\n #endif\n\n #if ( NUM_HEMI_LIGHTS > 0 )\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n #if THREE_VRM_THREE_REVISION >= 133\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n #else\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n #endif\n\n }\n #pragma unroll_loop_end\n\n #endif\n\n #endif\n\n // #if defined( RE_IndirectSpecular )\n\n // vec3 radiance = vec3( 0.0 );\n // vec3 clearcoatRadiance = vec3( 0.0 );\n\n // #endif\n\n #include <lights_fragment_maps>\n #include <lights_fragment_end>\n\n // modulation\n #include <aomap_fragment>\n\n vec3 col = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\n #ifdef DEBUG_LITSHADERATE\n gl_FragColor = vec4( col, diffuseColor.a );\n postCorrection();\n return;\n #endif\n\n // -- MToon: rim lighting -----------------------------------------\n vec3 viewDir = normalize( vViewPosition );\n\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n reflectedLight.directSpecular /= PI;\n #endif\n vec3 rimMix = mix( vec3( 1.0 ), reflectedLight.directSpecular, 1.0 );\n\n vec3 rim = parametricRimColorFactor * pow( saturate( 1.0 - dot( viewDir, normal ) + parametricRimLiftFactor ), parametricRimFresnelPowerFactor );\n\n #ifdef USE_MATCAPTEXTURE\n {\n vec3 x = normalize( vec3( viewDir.z, 0.0, -viewDir.x ) );\n vec3 y = cross( viewDir, x ); // guaranteed to be normalized\n vec2 sphereUv = 0.5 + 0.5 * vec2( dot( x, normal ), -dot( y, normal ) );\n sphereUv = ( matcapTextureUvTransform * vec3( sphereUv, 1 ) ).xy;\n #if THREE_VRM_THREE_REVISION >= 137\n vec3 matcap = texture2D( matcapTexture, sphereUv ).rgb;\n #else\n // COMPAT: pre-r137\n vec3 matcap = matcapTextureTexelToLinear( texture2D( matcapTexture, sphereUv ) ).rgb;\n #endif\n rim += matcapFactor * matcap;\n }\n #endif\n\n #ifdef USE_RIMMULTIPLYTEXTURE\n vec2 rimMultiplyTextureUv = ( rimMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy;\n #if THREE_VRM_THREE_REVISION >= 137\n rim *= texture2D( rimMultiplyTexture, rimMultiplyTextureUv ).rgb;\n #else\n // COMPAT: pre-r137\n rim *= rimMultiplyTextureTexelToLinear( texture2D( rimMultiplyTexture, rimMultiplyTextureUv ) ).rgb;\n #endif\n #endif\n\n col += rimMix * rim;\n\n // -- MToon: Emission --------------------------------------------------------\n col += totalEmissiveRadiance;\n\n // #include <envmap_fragment>\n\n // -- Almost done! -----------------------------------------------------------\n #if defined( OUTLINE )\n col = outlineColorFactor.rgb * mix( vec3( 1.0 ), col, outlineLightingMixFactor );\n #endif\n\n gl_FragColor = vec4( col, diffuseColor.a );\n postCorrection();\n}\n'}),this.uvAnimationScrollXSpeedFactor=0,this.uvAnimationScrollYSpeedFactor=0,this.uvAnimationRotationSpeedFactor=0,this.fog=!0,this.normalMapType=e.TangentSpaceNormalMap,this._ignoreVertexColor=!0,this._v0CompatShade=!1,this._debugMode=Oe.None,this._outlineWidthMode=Ve.None,this._isOutline=!1,t.transparentWithZWrite&&(t.depthWrite=!0),delete t.transparentWithZWrite,t.fog=!0,t.lights=!0,t.clipping=!0,parseInt(e.REVISION,10)<129&&(t.skinning=t.skinning||!1),parseInt(e.REVISION,10)<131&&(t.morphTargets=t.morphTargets||!1,t.morphNormals=t.morphNormals||!1),this.uniforms=e.UniformsUtils.merge([e.UniformsLib.common,e.UniformsLib.normalmap,e.UniformsLib.emissivemap,e.UniformsLib.fog,e.UniformsLib.lights,{litFactor:{value:new e.Color(1,1,1)},mapUvTransform:{value:new e.Matrix3},colorAlpha:{value:1},normalMapUvTransform:{value:new e.Matrix3},shadeColorFactor:{value:new e.Color(.97,.81,.86)},shadeMultiplyTexture:{value:null},shadeMultiplyTextureUvTransform:{value:new e.Matrix3},shadingShiftFactor:{value:0},shadingShiftTexture:{value:null},shadingShiftTextureUvTransform:{value:new e.Matrix3},shadingShiftTextureScale:{value:null},shadingToonyFactor:{value:.9},giEqualizationFactor:{value:.9},matcapFactor:{value:new e.Color(0,0,0)},matcapTexture:{value:null},matcapTextureUvTransform:{value:new e.Matrix3},parametricRimColorFactor:{value:new e.Color(0,0,0)},rimMultiplyTexture:{value:null},rimMultiplyTextureUvTransform:{value:new e.Matrix3},rimLightingMixFactor:{value:0},parametricRimFresnelPowerFactor:{value:1},parametricRimLiftFactor:{value:0},emissive:{value:new e.Color(0,0,0)},emissiveIntensity:{value:1},emissiveMapUvTransform:{value:new e.Matrix3},outlineWidthMultiplyTexture:{value:null},outlineWidthMultiplyTextureUvTransform:{value:new e.Matrix3},outlineWidthFactor:{value:.5},outlineColorFactor:{value:new e.Color(0,0,0)},outlineLightingMixFactor:{value:1},uvAnimationMaskTexture:{value:null},uvAnimationMaskTextureUvTransform:{value:new e.Matrix3},uvAnimationScrollXOffset:{value:0},uvAnimationScrollYOffset:{value:0},uvAnimationRotationPhase:{value:0}},t.uniforms]),this.setValues(t),this._uploadUniformsWorkaround(),this.customProgramCacheKey=()=>[this._ignoreVertexColor?"ignoreVertexColor":"",this._v0CompatShade?"v0CompatShade":"","none"!==this._debugMode?`debugMode:${this._debugMode}`:"","none"!==this._outlineWidthMode?`outlineWidthMode:${this._outlineWidthMode}`:"",this._isOutline?"isOutline":"",...Object.entries(this._generateDefines()).map((([e,t])=>`${e}:${t}`)),this.matcapTexture?`matcapTextureEncoding:${this.matcapTexture.encoding}`:"",this.shadeMultiplyTexture?`shadeMultiplyTextureEncoding:${this.shadeMultiplyTexture.encoding}`:"",this.rimMultiplyTexture?`rimMultiplyTextureEncoding:${this.rimMultiplyTexture.encoding}`:""].join(","),this.onBeforeCompile=(t,i)=>{const n=i.capabilities.isWebGL2,r=parseInt(e.REVISION,10),o=Object.entries(Object.assign(Object.assign({},this._generateDefines()),this.defines)).filter((([e,t])=>!!t)).map((([e,t])=>`#define ${e} ${t}`)).join("\n")+"\n";let s="";parseInt(e.REVISION,10)<137&&(s=(null!==this.matcapTexture?Ce("matcapTextureTexelToLinear",Ne(this.matcapTexture,n))+"\n":"")+(null!==this.shadeMultiplyTexture?Ce("shadeMultiplyTextureTexelToLinear",Ne(this.shadeMultiplyTexture,n))+"\n":"")+(null!==this.rimMultiplyTexture?Ce("rimMultiplyTextureTexelToLinear",Ne(this.rimMultiplyTexture,n))+"\n":"")),t.vertexShader=o+t.vertexShader,t.fragmentShader=o+s+t.fragmentShader,r<132&&(t.fragmentShader=t.fragmentShader.replace("#include <normal_pars_fragment>",""),t.fragmentShader=t.fragmentShader.replace("#include <alphatest_pars_fragment>",""))}}get color(){return this.uniforms.litFactor.value}set color(e){this.uniforms.litFactor.value=e}get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}get normalMap(){return this.uniforms.normalMap.value}set normalMap(e){this.uniforms.normalMap.value=e}get normalScale(){return this.uniforms.normalScale.value}set normalScale(e){this.uniforms.normalScale.value=e}get emissive(){return this.uniforms.emissive.value}set emissive(e){this.uniforms.emissive.value=e}get emissiveIntensity(){return this.uniforms.emissiveIntensity.value}set emissiveIntensity(e){this.uniforms.emissiveIntensity.value=e}get emissiveMap(){return this.uniforms.emissiveMap.value}set emissiveMap(e){this.uniforms.emissiveMap.value=e}get shadeColorFactor(){return this.uniforms.shadeColorFactor.value}set shadeColorFactor(e){this.uniforms.shadeColorFactor.value=e}get shadeMultiplyTexture(){return this.uniforms.shadeMultiplyTexture.value}set shadeMultiplyTexture(e){this.uniforms.shadeMultiplyTexture.value=e}get shadingShiftFactor(){return this.uniforms.shadingShiftFactor.value}set shadingShiftFactor(e){this.uniforms.shadingShiftFactor.value=e}get shadingShiftTexture(){return this.uniforms.shadingShiftTexture.value}set shadingShiftTexture(e){this.uniforms.shadingShiftTexture.value=e}get shadingShiftTextureScale(){return this.uniforms.shadingShiftTextureScale.value}set shadingShiftTextureScale(e){this.uniforms.shadingShiftTextureScale.value=e}get shadingToonyFactor(){return this.uniforms.shadingToonyFactor.value}set shadingToonyFactor(e){this.uniforms.shadingToonyFactor.value=e}get giEqualizationFactor(){return this.uniforms.giEqualizationFactor.value}set giEqualizationFactor(e){this.uniforms.giEqualizationFactor.value=e}get matcapFactor(){return this.uniforms.matcapFactor.value}set matcapFactor(e){this.uniforms.matcapFactor.value=e}get matcapTexture(){return this.uniforms.matcapTexture.value}set matcapTexture(e){this.uniforms.matcapTexture.value=e}get parametricRimColorFactor(){return this.uniforms.parametricRimColorFactor.value}set parametricRimColorFactor(e){this.uniforms.parametricRimColorFactor.value=e}get rimMultiplyTexture(){return this.uniforms.rimMultiplyTexture.value}set rimMultiplyTexture(e){this.uniforms.rimMultiplyTexture.value=e}get rimLightingMixFactor(){return this.uniforms.rimLightingMixFactor.value}set rimLightingMixFactor(e){this.uniforms.rimLightingMixFactor.value=e}get parametricRimFresnelPowerFactor(){return this.uniforms.parametricRimFresnelPowerFactor.value}set parametricRimFresnelPowerFactor(e){this.uniforms.parametricRimFresnelPowerFactor.value=e}get parametricRimLiftFactor(){return this.uniforms.parametricRimLiftFactor.value}set parametricRimLiftFactor(e){this.uniforms.parametricRimLiftFactor.value=e}get outlineWidthMultiplyTexture(){return this.uniforms.outlineWidthMultiplyTexture.value}set outlineWidthMultiplyTexture(e){this.uniforms.outlineWidthMultiplyTexture.value=e}get outlineWidthFactor(){return this.uniforms.outlineWidthFactor.value}set outlineWidthFactor(e){this.uniforms.outlineWidthFactor.value=e}get outlineColorFactor(){return this.uniforms.outlineColorFactor.value}set outlineColorFactor(e){this.uniforms.outlineColorFactor.value=e}get outlineLightingMixFactor(){return this.uniforms.outlineLightingMixFactor.value}set outlineLightingMixFactor(e){this.uniforms.outlineLightingMixFactor.value=e}get uvAnimationMaskTexture(){return this.uniforms.uvAnimationMaskTexture.value}set uvAnimationMaskTexture(e){this.uniforms.uvAnimationMaskTexture.value=e}get uvAnimationScrollXOffset(){return this.uniforms.uvAnimationScrollXOffset.value}set uvAnimationScrollXOffset(e){this.uniforms.uvAnimationScrollXOffset.value=e}get uvAnimationScrollYOffset(){return this.uniforms.uvAnimationScrollYOffset.value}set uvAnimationScrollYOffset(e){this.uniforms.uvAnimationScrollYOffset.value=e}get uvAnimationRotationPhase(){return this.uniforms.uvAnimationRotationPhase.value}set uvAnimationRotationPhase(e){this.uniforms.uvAnimationRotationPhase.value=e}get ignoreVertexColor(){return this._ignoreVertexColor}set ignoreVertexColor(e){this._ignoreVertexColor=e,this.needsUpdate=!0}get v0CompatShade(){return this._v0CompatShade}set v0CompatShade(e){this._v0CompatShade=e,this.needsUpdate=!0}get debugMode(){return this._debugMode}set debugMode(e){this._debugMode=e,this.needsUpdate=!0}get outlineWidthMode(){return this._outlineWidthMode}set outlineWidthMode(e){this._outlineWidthMode=e,this.needsUpdate=!0}get isOutline(){return this._isOutline}set isOutline(e){this._isOutline=e,this.needsUpdate=!0}get isMToonMaterial(){return!0}update(e){this._uploadUniformsWorkaround(),this._updateUVAnimation(e)}copy(e){return super.copy(e),this.map=e.map,this.normalMap=e.normalMap,this.emissiveMap=e.emissiveMap,this.shadeMultiplyTexture=e.shadeMultiplyTexture,this.shadingShiftTexture=e.shadingShiftTexture,this.matcapTexture=e.matcapTexture,this.rimMultiplyTexture=e.rimMultiplyTexture,this.outlineWidthMultiplyTexture=e.outlineWidthMultiplyTexture,this.uvAnimationMaskTexture=e.uvAnimationMaskTexture,this.normalMapType=e.normalMapType,this.uvAnimationScrollXSpeedFactor=e.uvAnimationScrollXSpeedFactor,this.uvAnimationScrollYSpeedFactor=e.uvAnimationScrollYSpeedFactor,this.uvAnimationRotationSpeedFactor=e.uvAnimationRotationSpeedFactor,this.ignoreVertexColor=e.ignoreVertexColor,this.v0CompatShade=e.v0CompatShade,this.debugMode=e.debugMode,this.outlineWidthMode=e.outlineWidthMode,this.isOutline=e.isOutline,this.needsUpdate=!0,this}_updateUVAnimation(e){this.uniforms.uvAnimationScrollXOffset.value+=e*this.uvAnimationScrollXSpeedFactor,this.uniforms.uvAnimationScrollYOffset.value+=e*this.uvAnimationScrollYSpeedFactor,this.uniforms.uvAnimationRotationPhase.value+=e*this.uvAnimationRotationSpeedFactor,this.uniformsNeedUpdate=!0}_uploadUniformsWorkaround(){this.uniforms.opacity.value=this.opacity,this._updateTextureMatrix(this.uniforms.map,this.uniforms.mapUvTransform),this._updateTextureMatrix(this.uniforms.normalMap,this.uniforms.normalMapUvTransform),this._updateTextureMatrix(this.uniforms.emissiveMap,this.uniforms.emissiveMapUvTransform),this._updateTextureMatrix(this.uniforms.shadeMultiplyTexture,this.uniforms.shadeMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.shadingShiftTexture,this.uniforms.shadingShiftTextureUvTransform),this._updateTextureMatrix(this.uniforms.matcapTexture,this.uniforms.matcapTextureUvTransform),this._updateTextureMatrix(this.uniforms.rimMultiplyTexture,this.uniforms.rimMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.outlineWidthMultiplyTexture,this.uniforms.outlineWidthMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.uvAnimationMaskTexture,this.uniforms.uvAnimationMaskTextureUvTransform);parseInt(e.REVISION,10)>=132&&(this.uniforms.alphaTest.value=this.alphaTest),this.uniformsNeedUpdate=!0}_generateDefines(){const t=parseInt(e.REVISION,10),i=null!==this.outlineWidthMultiplyTexture,n=null!==this.map||null!==this.emissiveMap||null!==this.shadeMultiplyTexture||null!==this.shadingShiftTexture||null!==this.rimMultiplyTexture||null!==this.uvAnimationMaskTexture;return{THREE_VRM_THREE_REVISION:t,OUTLINE:this._isOutline,MTOON_USE_UV:i||n,MTOON_UVS_VERTEX_ONLY:i&&!n,V0_COMPAT_SHADE:this._v0CompatShade,USE_SHADEMULTIPLYTEXTURE:null!==this.shadeMultiplyTexture,USE_SHADINGSHIFTTEXTURE:null!==this.shadingShiftTexture,USE_MATCAPTEXTURE:null!==this.matcapTexture,USE_RIMMULTIPLYTEXTURE:null!==this.rimMultiplyTexture,USE_OUTLINEWIDTHMULTIPLYTEXTURE:null!==this.outlineWidthMultiplyTexture,USE_UVANIMATIONMASKTEXTURE:null!==this.uvAnimationMaskTexture,IGNORE_VERTEX_COLOR:!0===this._ignoreVertexColor,DEBUG_NORMAL:"normal"===this._debugMode,DEBUG_LITSHADERATE:"litShadeRate"===this._debugMode,DEBUG_UV:"uv"===this._debugMode,OUTLINE_WIDTH_WORLD:this._outlineWidthMode===Ve.WorldCoordinates,OUTLINE_WIDTH_SCREEN:this._outlineWidthMode===Ve.ScreenCoordinates}}_updateTextureMatrix(e,t){e.value&&(e.value.matrixAutoUpdate&&e.value.updateMatrix(),t.value.copy(e.value.matrix))}}class Fe{constructor(e,t){this._parser=e,this._materialParams=t,this._pendings=[]}get pending(){return Promise.all(this._pendings)}assignPrimitive(e,t){null!=t&&(this._materialParams[e]=t)}assignColor(t,i,n){null!=i&&(this._materialParams[t]=(new e.Color).fromArray(i),n&&this._materialParams[t].convertSRGBToLinear())}assignTexture(t,i,n){return Ue(this,void 0,void 0,(function*(){const r=(()=>Ue(this,void 0,void 0,(function*(){null!=i&&(yield this._parser.assignTexture(this._materialParams,t,i),n&&(this._materialParams[t].encoding=e.sRGBEncoding))})))();return this._pendings.push(r),r}))}assignTextureByIndex(e,t,i){return Ue(this,void 0,void 0,(function*(){return this.assignTexture(e,null!=t?{index:t}:void 0,i)}))}}const Be=new Set(["1.0","1.0-beta"]);class He{constructor(e,t={}){var i,n,r;this.parser=e,this.renderOrderOffset=null!==(i=t.renderOrderOffset)&&void 0!==i?i:0,this.v0CompatShade=null!==(n=t.v0CompatShade)&&void 0!==n&&n,this.debugMode=null!==(r=t.debugMode)&&void 0!==r?r:"none",this._mToonMaterialSet=new Set}get name(){return He.EXTENSION_NAME}beforeRoot(){return Ue(this,void 0,void 0,(function*(){this._removeUnlitExtensionIfMToonExists()}))}afterRoot(e){return Ue(this,void 0,void 0,(function*(){e.userData.vrmMToonMaterials=Array.from(this._mToonMaterialSet)}))}getMaterialType(e){return this._getMToonExtension(e)?De:null}extendMaterialParams(e,t){const i=this._getMToonExtension(e);return i?this._extendMaterialParams(i,t):null}loadMesh(e){var t;return Ue(this,void 0,void 0,(function*(){const i=this.parser,n=i.json,r=null===(t=n.meshes)||void 0===t?void 0:t[e];if(null==r)throw new Error(`MToonMaterialLoaderPlugin: Attempt to use meshes[${e}] of glTF but the mesh doesn't exist`);const o=r.primitives,s=yield i.loadMesh(e);if(1===o.length){const e=s,t=o[0].material;null!=t&&this._setupPrimitive(e,t)}else{const e=s;for(let t=0;t<o.length;t++){const i=e.children[t],n=o[t].material;null!=n&&this._setupPrimitive(i,n)}}return s}))}_removeUnlitExtensionIfMToonExists(){const e=this.parser.json.materials;null==e||e.map(((e,t)=>{var i;this._getMToonExtension(t)&&(null===(i=e.extensions)||void 0===i?void 0:i.KHR_materials_unlit)&&delete e.extensions.KHR_materials_unlit}))}_getMToonExtension(e){var t,i;const n=null===(t=this.parser.json.materials)||void 0===t?void 0:t[e];if(null==n)return void console.warn(`MToonMaterialLoaderPlugin: Attempt to use materials[${e}] of glTF but the material doesn't exist`);const r=null===(i=n.extensions)||void 0===i?void 0:i[He.EXTENSION_NAME];if(null==r)return;const o=r.specVersion;if(Be.has(o))return r;console.warn(`MToonMaterialLoaderPlugin: Unknown ${He.EXTENSION_NAME} specVersion "${o}"`)}_extendMaterialParams(e,t){var i;return Ue(this,void 0,void 0,(function*(){delete t.metalness,delete t.roughness;const n=new Fe(this.parser,t);n.assignPrimitive("transparentWithZWrite",e.transparentWithZWrite),n.assignColor("shadeColorFactor",e.shadeColorFactor),n.assignTexture("shadeMultiplyTexture",e.shadeMultiplyTexture,!0),n.assignPrimitive("shadingShiftFactor",e.shadingShiftFactor),n.assignTexture("shadingShiftTexture",e.shadingShiftTexture,!0),n.assignPrimitive("shadingShiftTextureScale",null===(i=e.shadingShiftTexture)||void 0===i?void 0:i.scale),n.assignPrimitive("shadingToonyFactor",e.shadingToonyFactor),n.assignPrimitive("giEqualizationFactor",e.giEqualizationFactor),n.assignColor("matcapFactor",e.matcapFactor),n.assignTexture("matcapTexture",e.matcapTexture,!0),n.assignColor("parametricRimColorFactor",e.parametricRimColorFactor),n.assignTexture("rimMultiplyTexture",e.rimMultiplyTexture,!0),n.assignPrimitive("rimLightingMixFactor",e.rimLightingMixFactor),n.assignPrimitive("parametricRimFresnelPowerFactor",e.parametricRimFresnelPowerFactor),n.assignPrimitive("parametricRimLiftFactor",e.parametricRimLiftFactor),n.assignPrimitive("outlineWidthMode",e.outlineWidthMode),n.assignPrimitive("outlineWidthFactor",e.outlineWidthFactor),n.assignTexture("outlineWidthMultiplyTexture",e.outlineWidthMultiplyTexture,!1),n.assignColor("outlineColorFactor",e.outlineColorFactor),n.assignPrimitive("outlineLightingMixFactor",e.outlineLightingMixFactor),n.assignTexture("uvAnimationMaskTexture",e.uvAnimationMaskTexture,!1),n.assignPrimitive("uvAnimationScrollXSpeedFactor",e.uvAnimationScrollXSpeedFactor),n.assignPrimitive("uvAnimationScrollYSpeedFactor",e.uvAnimationScrollYSpeedFactor),n.assignPrimitive("uvAnimationRotationSpeedFactor",e.uvAnimationRotationSpeedFactor),n.assignPrimitive("v0CompatShade",this.v0CompatShade),n.assignPrimitive("debugMode",this.debugMode),yield n.pending}))}_setupPrimitive(e,t){const i=this._getMToonExtension(t);if(i){const t=this._parseRenderOrder(i);return e.renderOrder=t+this.renderOrderOffset,this._generateOutline(e),void this._addToMaterialSet(e)}}_generateOutline(t){const i=t.material;if(!(i instanceof De))return;if("none"===i.outlineWidthMode||i.outlineWidthFactor<=0)return;t.material=[i];const n=i.clone();n.name+=" (Outline)",n.isOutline=!0,n.side=e.BackSide,t.material.push(n);const r=t.geometry,o=r.index?r.index.count:r.attributes.position.count/3;r.addGroup(0,o,0),r.addGroup(0,o,1)}_addToMaterialSet(e){const t=e.material,i=new Set;Array.isArray(t)?t.forEach((e=>i.add(e))):i.add(t);for(const e of i)e instanceof De&&this._mToonMaterialSet.add(e)}_parseRenderOrder(e){var t;return(e.transparentWithZWrite?0:19)+(null!==(t=e.renderQueueOffsetNumber)&&void 0!==t?t:0)}}
|
|
62
20
|
/*!
|
|
63
|
-
* @pixiv/three-vrm-materials-hdr-emissive-multiplier v1.0.
|
|
21
|
+
* @pixiv/three-vrm-materials-hdr-emissive-multiplier v1.0.3
|
|
64
22
|
* Support VRMC_hdr_emissiveMultiplier for @pixiv/three-vrm
|
|
65
23
|
*
|
|
66
|
-
* Copyright (c) 2020-
|
|
24
|
+
* Copyright (c) 2020-2022 pixiv Inc.
|
|
67
25
|
* @pixiv/three-vrm-materials-hdr-emissive-multiplier is distributed under MIT License
|
|
68
26
|
* https://github.com/pixiv/three-vrm/blob/release/LICENSE
|
|
69
27
|
*/
|
|
70
|
-
|
|
71
|
-
Copyright (c) Microsoft Corporation.
|
|
72
|
-
|
|
73
|
-
Permission to use, copy, modify, and/or distribute this software for any
|
|
74
|
-
purpose with or without fee is hereby granted.
|
|
75
|
-
|
|
76
|
-
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
77
|
-
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
78
|
-
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
79
|
-
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
80
|
-
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
81
|
-
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
82
|
-
PERFORMANCE OF THIS SOFTWARE.
|
|
83
|
-
***************************************************************************** */
|
|
84
|
-
function He(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())}))}Be.EXTENSION_NAME="VRMC_materials_mtoon";class ke{constructor(e){this.parser=e}get name(){return ke.EXTENSION_NAME}extendMaterialParams(e,t){return He(this,void 0,void 0,(function*(){const i=this._getHDREmissiveMultiplierExtension(e);if(null==i)return;console.warn("VRMMaterialsHDREmissiveMultiplierLoaderPlugin: `VRMC_materials_hdr_emissiveMultiplier` is archived. Use `KHR_materials_emissive_strength` instead.");const n=i.emissiveMultiplier;t.emissiveIntensity=n}))}_getHDREmissiveMultiplierExtension(e){var t,i;const n=null===(t=this.parser.json.materials)||void 0===t?void 0:t[e];if(null==n)return void console.warn(`VRMMaterialsHDREmissiveMultiplierLoaderPlugin: Attempt to use materials[${e}] of glTF but the material doesn't exist`);const r=null===(i=n.extensions)||void 0===i?void 0:i[ke.EXTENSION_NAME];return null!=r?r:void 0}}
|
|
28
|
+
function ke(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())}))}He.EXTENSION_NAME="VRMC_materials_mtoon";class We{constructor(e){this.parser=e}get name(){return We.EXTENSION_NAME}extendMaterialParams(e,t){return ke(this,void 0,void 0,(function*(){const i=this._getHDREmissiveMultiplierExtension(e);if(null==i)return;console.warn("VRMMaterialsHDREmissiveMultiplierLoaderPlugin: `VRMC_materials_hdr_emissiveMultiplier` is archived. Use `KHR_materials_emissive_strength` instead.");const n=i.emissiveMultiplier;t.emissiveIntensity=n}))}_getHDREmissiveMultiplierExtension(e){var t,i;const n=null===(t=this.parser.json.materials)||void 0===t?void 0:t[e];if(null==n)return void console.warn(`VRMMaterialsHDREmissiveMultiplierLoaderPlugin: Attempt to use materials[${e}] of glTF but the material doesn't exist`);const r=null===(i=n.extensions)||void 0===i?void 0:i[We.EXTENSION_NAME];return null!=r?r:void 0}}
|
|
85
29
|
/*!
|
|
86
|
-
* @pixiv/three-vrm-materials-v0compat v1.0.
|
|
30
|
+
* @pixiv/three-vrm-materials-v0compat v1.0.3
|
|
87
31
|
* VRM0.0 materials compatibility layer plugin for @pixiv/three-vrm
|
|
88
32
|
*
|
|
89
|
-
* Copyright (c) 2020-
|
|
33
|
+
* Copyright (c) 2020-2022 pixiv Inc.
|
|
90
34
|
* @pixiv/three-vrm-materials-v0compat is distributed under MIT License
|
|
91
35
|
* https://github.com/pixiv/three-vrm/blob/release/LICENSE
|
|
92
36
|
*/
|
|
93
|
-
|
|
94
|
-
Copyright (c) Microsoft Corporation.
|
|
95
|
-
|
|
96
|
-
Permission to use, copy, modify, and/or distribute this software for any
|
|
97
|
-
purpose with or without fee is hereby granted.
|
|
98
|
-
|
|
99
|
-
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
100
|
-
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
101
|
-
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
102
|
-
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
103
|
-
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
104
|
-
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
105
|
-
PERFORMANCE OF THIS SOFTWARE.
|
|
106
|
-
***************************************************************************** */
|
|
107
|
-
function We(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 ze(e){return Math.pow(e,2.2)}ke.EXTENSION_NAME="VRMC_materials_hdr_emissiveMultiplier";class je{constructor(e){var t;this.parser=e,this._renderQueueMapTransparent=new Map,this._renderQueueMapTransparentZWrite=new Map;const i=this.parser.json;i.extensionsUsed=null!==(t=i.extensionsUsed)&&void 0!==t?t:[],-1===i.extensionsUsed.indexOf("KHR_texture_transform")&&i.extensionsUsed.push("KHR_texture_transform")}get name(){return"VRMMaterialsV0CompatPlugin"}beforeRoot(){var e;return We(this,void 0,void 0,(function*(){const t=this.parser.json,i=null===(e=t.extensions)||void 0===e?void 0:e.VRM,n=null==i?void 0:i.materialProperties;n&&(this._populateRenderQueueMap(n),n.forEach(((e,i)=>{var n,r;const o=null===(n=t.materials)||void 0===n?void 0:n[i];if(null!=o)if("VRM/MToon"===e.shader){const n=this._parseV0MToonProperties(e,o);t.materials[i]=n}else if(null===(r=e.shader)||void 0===r?void 0:r.startsWith("VRM/Unlit")){const n=this._parseV0UnlitProperties(e,o);t.materials[i]=n}else"VRM_USE_GLTFSHADER"===e.shader||console.warn(`VRMMaterialsV0CompatPlugin: Unknown shader: ${e.shader}`);else console.warn(`VRMMaterialsV0CompatPlugin: Attempt to use materials[${i}] of glTF but the material doesn't exist`)})))}))}_parseV0MToonProperties(t,i){var n,r,o,s,a,l,u,d,h,c,p,m,f,v,g,_,x,M,y,T,R,w,E,P,L,S,A,b,I,U,O,V,C,N,D,F,B,H,k,W,z,j,Q,X;const G=null!==(r=null===(n=t.keywordMap)||void 0===n?void 0:n._ALPHABLEND_ON)&&void 0!==r&&r,Y=1===(null===(o=t.floatProperties)||void 0===o?void 0:o._ZWrite)&&G,q=this._v0ParseRenderQueue(t),$=null!==(a=null===(s=t.keywordMap)||void 0===s?void 0:s._ALPHATEST_ON)&&void 0!==a&&a,Z=G?"BLEND":$?"MASK":"OPAQUE",J=$?null===(l=t.floatProperties)||void 0===l?void 0:l._Cutoff:void 0,K=0===(null!==(d=null===(u=t.floatProperties)||void 0===u?void 0:u._CullMode)&&void 0!==d?d:2),ee=this._portTextureTransform(t),te=null===(c=null===(h=t.vectorProperties)||void 0===h?void 0:h._Color)||void 0===c?void 0:c.map(((e,t)=>3===t?e:ze(e))),ie=null===(p=t.textureProperties)||void 0===p?void 0:p._MainTex,ne=null!=ie?{index:ie,extensions:Object.assign({},ee)}:void 0,re=null===(m=t.floatProperties)||void 0===m?void 0:m._BumpScale,oe=null===(f=t.textureProperties)||void 0===f?void 0:f._BumpMap,se=null!=oe?{index:oe,scale:re,extensions:Object.assign({},ee)}:void 0,ae=null===(g=null===(v=t.vectorProperties)||void 0===v?void 0:v._EmissionColor)||void 0===g?void 0:g.map(ze),le=null===(_=t.textureProperties)||void 0===_?void 0:_._EmissionMap,ue=null!=le?{index:le,extensions:Object.assign({},ee)}:void 0,de=null===(M=null===(x=t.vectorProperties)||void 0===x?void 0:x._ShadeColor)||void 0===M?void 0:M.map(ze),he=null===(y=t.textureProperties)||void 0===y?void 0:y._ShadeTexture,ce=null!=he?{index:he,extensions:Object.assign({},ee)}:void 0;let pe=null!==(R=null===(T=t.floatProperties)||void 0===T?void 0:T._ShadeShift)&&void 0!==R?R:0,me=null!==(E=null===(w=t.floatProperties)||void 0===w?void 0:w._ShadeToony)&&void 0!==E?E:.9;me=e.MathUtils.lerp(me,1,.5+.5*pe),pe=-pe-(1-me);const fe=null===(P=t.floatProperties)||void 0===P?void 0:P._IndirectLightIntensity,ve=fe?1-fe:void 0,ge=null===(L=t.textureProperties)||void 0===L?void 0:L._SphereAdd,_e=null!=ge?[1,1,1]:void 0,xe=null!=ge?{index:ge}:void 0,Me=null===(S=t.floatProperties)||void 0===S?void 0:S._RimLightingMix,ye=null===(A=t.textureProperties)||void 0===A?void 0:A._RimTexture,Te=null!=ye?{index:ye,extensions:Object.assign({},ee)}:void 0,Re=null===(I=null===(b=t.vectorProperties)||void 0===b?void 0:b._RimColor)||void 0===I?void 0:I.map(ze),we=null===(U=t.floatProperties)||void 0===U?void 0:U._RimFresnelPower,Ee=null===(O=t.floatProperties)||void 0===O?void 0:O._RimLift,Pe=["none","worldCoordinates","screenCoordinates"][null!==(C=null===(V=t.floatProperties)||void 0===V?void 0:V._OutlineWidthMode)&&void 0!==C?C:0];let Le=null!==(D=null===(N=t.floatProperties)||void 0===N?void 0:N._OutlineWidth)&&void 0!==D?D:0;Le*=.01;const Se=null===(F=t.textureProperties)||void 0===F?void 0:F._OutlineWidthTexture,Ae=null!=Se?{index:Se,extensions:Object.assign({},ee)}:void 0,be=null===(H=null===(B=t.vectorProperties)||void 0===B?void 0:B._OutlineColor)||void 0===H?void 0:H.map(ze),Ie=1===(null===(k=t.floatProperties)||void 0===k?void 0:k._OutlineColorMode)?null===(W=t.floatProperties)||void 0===W?void 0:W._OutlineLightingMix:0,Ue=null===(z=t.textureProperties)||void 0===z?void 0:z._UvAnimMaskTexture,Oe=null!=Ue?{index:Ue,extensions:Object.assign({},ee)}:void 0,Ve=null===(j=t.floatProperties)||void 0===j?void 0:j._UvAnimScrollX;let Ce=null===(Q=t.floatProperties)||void 0===Q?void 0:Q._UvAnimScrollY;null!=Ce&&(Ce=-Ce);const Ne={specVersion:"1.0",transparentWithZWrite:Y,renderQueueOffsetNumber:q,shadeColorFactor:de,shadeMultiplyTexture:ce,shadingShiftFactor:pe,shadingToonyFactor:me,giEqualizationFactor:ve,matcapFactor:_e,matcapTexture:xe,rimLightingMixFactor:Me,rimMultiplyTexture:Te,parametricRimColorFactor:Re,parametricRimFresnelPowerFactor:we,parametricRimLiftFactor:Ee,outlineWidthMode:Pe,outlineWidthFactor:Le,outlineWidthMultiplyTexture:Ae,outlineColorFactor:be,outlineLightingMixFactor:Ie,uvAnimationMaskTexture:Oe,uvAnimationScrollXSpeedFactor:Ve,uvAnimationScrollYSpeedFactor:Ce,uvAnimationRotationSpeedFactor:null===(X=t.floatProperties)||void 0===X?void 0:X._UvAnimRotation};return Object.assign(Object.assign({},i),{pbrMetallicRoughness:{baseColorFactor:te,baseColorTexture:ne},normalTexture:se,emissiveTexture:ue,emissiveFactor:ae,alphaMode:Z,alphaCutoff:J,doubleSided:K,extensions:{VRMC_materials_mtoon:Ne}})}_parseV0UnlitProperties(e,t){var i,n,r,o;const s="VRM/UnlitTransparentZWrite"===e.shader,a="VRM/UnlitTransparent"===e.shader||s,l=this._v0ParseRenderQueue(e),u="VRM/UnlitCutout"===e.shader,d=a?"BLEND":u?"MASK":"OPAQUE",h=u?null===(i=e.floatProperties)||void 0===i?void 0:i._Cutoff:void 0,c=this._portTextureTransform(e),p=null===(r=null===(n=e.vectorProperties)||void 0===n?void 0:n._Color)||void 0===r?void 0:r.map(ze),m=null===(o=e.textureProperties)||void 0===o?void 0:o._MainTex,f=null!=m?{index:m,extensions:Object.assign({},c)}:void 0,v={specVersion:"1.0",transparentWithZWrite:s,renderQueueOffsetNumber:l,shadeColorFactor:p,shadeMultiplyTexture:f};return Object.assign(Object.assign({},t),{pbrMetallicRoughness:{baseColorFactor:p,baseColorTexture:f},alphaMode:d,alphaCutoff:h,extensions:{VRMC_materials_mtoon:v}})}_portTextureTransform(e){var t,i,n,r,o;const s=null===(t=e.vectorProperties)||void 0===t?void 0:t._MainTex;if(null==s)return{};const a=[null!==(i=null==s?void 0:s[0])&&void 0!==i?i:0,null!==(n=null==s?void 0:s[1])&&void 0!==n?n:0],l=[null!==(r=null==s?void 0:s[2])&&void 0!==r?r:1,null!==(o=null==s?void 0:s[3])&&void 0!==o?o:1];return a[1]=l[1]*(1-a[1])%1,{KHR_texture_transform:{offset:a,scale:l}}}_v0ParseRenderQueue(e){var t,i,n;const r=null!==(i=null===(t=e.keywordMap)||void 0===t?void 0:t._ALPHABLEND_ON)&&void 0!==i&&i,o=1===(null===(n=e.floatProperties)||void 0===n?void 0:n._ZWrite);let s=0;if(r){const t=e.renderQueue;null!=t&&(s=o?this._renderQueueMapTransparentZWrite.get(t):this._renderQueueMapTransparent.get(t))}return s}_populateRenderQueueMap(e){const t=new Set,i=new Set;e.forEach((e=>{var n,r,o;const s=null!==(r=null===(n=e.keywordMap)||void 0===n?void 0:n._ALPHABLEND_ON)&&void 0!==r&&r,a=1===(null===(o=e.floatProperties)||void 0===o?void 0:o._ZWrite);if(s){const n=e.renderQueue;null!=n&&(a?i.add(n):t.add(n))}})),t.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${t.size} render queues for Transparent materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),i.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${i.size} render queues for TransparentZWrite materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),Array.from(t).sort().forEach(((e,i)=>{const n=Math.min(Math.max(i-t.size+1,-9),0);this._renderQueueMapTransparent.set(e,n)})),Array.from(i).sort().forEach(((e,t)=>{const i=Math.min(Math.max(t,0),9);this._renderQueueMapTransparentZWrite.set(e,i)}))}}
|
|
37
|
+
function ze(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 je(e){return Math.pow(e,2.2)}We.EXTENSION_NAME="VRMC_materials_hdr_emissiveMultiplier";class Qe{constructor(e){var t;this.parser=e,this._renderQueueMapTransparent=new Map,this._renderQueueMapTransparentZWrite=new Map;const i=this.parser.json;i.extensionsUsed=null!==(t=i.extensionsUsed)&&void 0!==t?t:[],-1===i.extensionsUsed.indexOf("KHR_texture_transform")&&i.extensionsUsed.push("KHR_texture_transform")}get name(){return"VRMMaterialsV0CompatPlugin"}beforeRoot(){var e;return ze(this,void 0,void 0,(function*(){const t=this.parser.json,i=null===(e=t.extensions)||void 0===e?void 0:e.VRM,n=null==i?void 0:i.materialProperties;n&&(this._populateRenderQueueMap(n),n.forEach(((e,i)=>{var n,r;const o=null===(n=t.materials)||void 0===n?void 0:n[i];if(null!=o)if("VRM/MToon"===e.shader){const n=this._parseV0MToonProperties(e,o);t.materials[i]=n}else if(null===(r=e.shader)||void 0===r?void 0:r.startsWith("VRM/Unlit")){const n=this._parseV0UnlitProperties(e,o);t.materials[i]=n}else"VRM_USE_GLTFSHADER"===e.shader||console.warn(`VRMMaterialsV0CompatPlugin: Unknown shader: ${e.shader}`);else console.warn(`VRMMaterialsV0CompatPlugin: Attempt to use materials[${i}] of glTF but the material doesn't exist`)})))}))}_parseV0MToonProperties(t,i){var n,r,o,s,a,l,u,d,h,c,p,m,f,v,g,_,x,M,y,T,R,w,E,P,L,S,A,b,I,U,O,V,C,N,D,F,B,H,k,W,z,j,Q,X;const G=null!==(r=null===(n=t.keywordMap)||void 0===n?void 0:n._ALPHABLEND_ON)&&void 0!==r&&r,Y=1===(null===(o=t.floatProperties)||void 0===o?void 0:o._ZWrite)&&G,q=this._v0ParseRenderQueue(t),$=null!==(a=null===(s=t.keywordMap)||void 0===s?void 0:s._ALPHATEST_ON)&&void 0!==a&&a,Z=G?"BLEND":$?"MASK":"OPAQUE",J=$?null===(l=t.floatProperties)||void 0===l?void 0:l._Cutoff:void 0,K=0===(null!==(d=null===(u=t.floatProperties)||void 0===u?void 0:u._CullMode)&&void 0!==d?d:2),ee=this._portTextureTransform(t),te=null===(c=null===(h=t.vectorProperties)||void 0===h?void 0:h._Color)||void 0===c?void 0:c.map(((e,t)=>3===t?e:je(e))),ie=null===(p=t.textureProperties)||void 0===p?void 0:p._MainTex,ne=null!=ie?{index:ie,extensions:Object.assign({},ee)}:void 0,re=null===(m=t.floatProperties)||void 0===m?void 0:m._BumpScale,oe=null===(f=t.textureProperties)||void 0===f?void 0:f._BumpMap,se=null!=oe?{index:oe,scale:re,extensions:Object.assign({},ee)}:void 0,ae=null===(g=null===(v=t.vectorProperties)||void 0===v?void 0:v._EmissionColor)||void 0===g?void 0:g.map(je),le=null===(_=t.textureProperties)||void 0===_?void 0:_._EmissionMap,ue=null!=le?{index:le,extensions:Object.assign({},ee)}:void 0,de=null===(M=null===(x=t.vectorProperties)||void 0===x?void 0:x._ShadeColor)||void 0===M?void 0:M.map(je),he=null===(y=t.textureProperties)||void 0===y?void 0:y._ShadeTexture,ce=null!=he?{index:he,extensions:Object.assign({},ee)}:void 0;let pe=null!==(R=null===(T=t.floatProperties)||void 0===T?void 0:T._ShadeShift)&&void 0!==R?R:0,me=null!==(E=null===(w=t.floatProperties)||void 0===w?void 0:w._ShadeToony)&&void 0!==E?E:.9;me=e.MathUtils.lerp(me,1,.5+.5*pe),pe=-pe-(1-me);const fe=null===(P=t.floatProperties)||void 0===P?void 0:P._IndirectLightIntensity,ve=fe?1-fe:void 0,ge=null===(L=t.textureProperties)||void 0===L?void 0:L._SphereAdd,_e=null!=ge?[1,1,1]:void 0,xe=null!=ge?{index:ge}:void 0,Me=null===(S=t.floatProperties)||void 0===S?void 0:S._RimLightingMix,ye=null===(A=t.textureProperties)||void 0===A?void 0:A._RimTexture,Te=null!=ye?{index:ye,extensions:Object.assign({},ee)}:void 0,Re=null===(I=null===(b=t.vectorProperties)||void 0===b?void 0:b._RimColor)||void 0===I?void 0:I.map(je),we=null===(U=t.floatProperties)||void 0===U?void 0:U._RimFresnelPower,Ee=null===(O=t.floatProperties)||void 0===O?void 0:O._RimLift,Pe=["none","worldCoordinates","screenCoordinates"][null!==(C=null===(V=t.floatProperties)||void 0===V?void 0:V._OutlineWidthMode)&&void 0!==C?C:0];let Le=null!==(D=null===(N=t.floatProperties)||void 0===N?void 0:N._OutlineWidth)&&void 0!==D?D:0;Le*=.01;const Se=null===(F=t.textureProperties)||void 0===F?void 0:F._OutlineWidthTexture,Ae=null!=Se?{index:Se,extensions:Object.assign({},ee)}:void 0,be=null===(H=null===(B=t.vectorProperties)||void 0===B?void 0:B._OutlineColor)||void 0===H?void 0:H.map(je),Ie=1===(null===(k=t.floatProperties)||void 0===k?void 0:k._OutlineColorMode)?null===(W=t.floatProperties)||void 0===W?void 0:W._OutlineLightingMix:0,Ue=null===(z=t.textureProperties)||void 0===z?void 0:z._UvAnimMaskTexture,Oe=null!=Ue?{index:Ue,extensions:Object.assign({},ee)}:void 0,Ve=null===(j=t.floatProperties)||void 0===j?void 0:j._UvAnimScrollX;let Ce=null===(Q=t.floatProperties)||void 0===Q?void 0:Q._UvAnimScrollY;null!=Ce&&(Ce=-Ce);const Ne={specVersion:"1.0",transparentWithZWrite:Y,renderQueueOffsetNumber:q,shadeColorFactor:de,shadeMultiplyTexture:ce,shadingShiftFactor:pe,shadingToonyFactor:me,giEqualizationFactor:ve,matcapFactor:_e,matcapTexture:xe,rimLightingMixFactor:Me,rimMultiplyTexture:Te,parametricRimColorFactor:Re,parametricRimFresnelPowerFactor:we,parametricRimLiftFactor:Ee,outlineWidthMode:Pe,outlineWidthFactor:Le,outlineWidthMultiplyTexture:Ae,outlineColorFactor:be,outlineLightingMixFactor:Ie,uvAnimationMaskTexture:Oe,uvAnimationScrollXSpeedFactor:Ve,uvAnimationScrollYSpeedFactor:Ce,uvAnimationRotationSpeedFactor:null===(X=t.floatProperties)||void 0===X?void 0:X._UvAnimRotation};return Object.assign(Object.assign({},i),{pbrMetallicRoughness:{baseColorFactor:te,baseColorTexture:ne},normalTexture:se,emissiveTexture:ue,emissiveFactor:ae,alphaMode:Z,alphaCutoff:J,doubleSided:K,extensions:{VRMC_materials_mtoon:Ne}})}_parseV0UnlitProperties(e,t){var i,n,r,o;const s="VRM/UnlitTransparentZWrite"===e.shader,a="VRM/UnlitTransparent"===e.shader||s,l=this._v0ParseRenderQueue(e),u="VRM/UnlitCutout"===e.shader,d=a?"BLEND":u?"MASK":"OPAQUE",h=u?null===(i=e.floatProperties)||void 0===i?void 0:i._Cutoff:void 0,c=this._portTextureTransform(e),p=null===(r=null===(n=e.vectorProperties)||void 0===n?void 0:n._Color)||void 0===r?void 0:r.map(je),m=null===(o=e.textureProperties)||void 0===o?void 0:o._MainTex,f=null!=m?{index:m,extensions:Object.assign({},c)}:void 0,v={specVersion:"1.0",transparentWithZWrite:s,renderQueueOffsetNumber:l,shadeColorFactor:p,shadeMultiplyTexture:f};return Object.assign(Object.assign({},t),{pbrMetallicRoughness:{baseColorFactor:p,baseColorTexture:f},alphaMode:d,alphaCutoff:h,extensions:{VRMC_materials_mtoon:v}})}_portTextureTransform(e){var t,i,n,r,o;const s=null===(t=e.vectorProperties)||void 0===t?void 0:t._MainTex;if(null==s)return{};const a=[null!==(i=null==s?void 0:s[0])&&void 0!==i?i:0,null!==(n=null==s?void 0:s[1])&&void 0!==n?n:0],l=[null!==(r=null==s?void 0:s[2])&&void 0!==r?r:1,null!==(o=null==s?void 0:s[3])&&void 0!==o?o:1];return a[1]=l[1]*(1-a[1])%1,{KHR_texture_transform:{offset:a,scale:l}}}_v0ParseRenderQueue(e){var t,i,n;const r=null!==(i=null===(t=e.keywordMap)||void 0===t?void 0:t._ALPHABLEND_ON)&&void 0!==i&&i,o=1===(null===(n=e.floatProperties)||void 0===n?void 0:n._ZWrite);let s=0;if(r){const t=e.renderQueue;null!=t&&(s=o?this._renderQueueMapTransparentZWrite.get(t):this._renderQueueMapTransparent.get(t))}return s}_populateRenderQueueMap(e){const t=new Set,i=new Set;e.forEach((e=>{var n,r,o;const s=null!==(r=null===(n=e.keywordMap)||void 0===n?void 0:n._ALPHABLEND_ON)&&void 0!==r&&r,a=1===(null===(o=e.floatProperties)||void 0===o?void 0:o._ZWrite);if(s){const n=e.renderQueue;null!=n&&(a?i.add(n):t.add(n))}})),t.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${t.size} render queues for Transparent materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),i.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${i.size} render queues for TransparentZWrite materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),Array.from(t).sort().forEach(((e,i)=>{const n=Math.min(Math.max(i-t.size+1,-9),0);this._renderQueueMapTransparent.set(e,n)})),Array.from(i).sort().forEach(((e,t)=>{const i=Math.min(Math.max(t,0),9);this._renderQueueMapTransparentZWrite.set(e,i)}))}}
|
|
108
38
|
/*!
|
|
109
|
-
* @pixiv/three-vrm-node-constraint v1.0.
|
|
39
|
+
* @pixiv/three-vrm-node-constraint v1.0.3
|
|
110
40
|
* Node constraint module for @pixiv/three-vrm
|
|
111
41
|
*
|
|
112
|
-
* Copyright (c) 2020-
|
|
42
|
+
* Copyright (c) 2020-2022 pixiv Inc.
|
|
113
43
|
* @pixiv/three-vrm-node-constraint is distributed under MIT License
|
|
114
44
|
* https://github.com/pixiv/three-vrm/blob/release/LICENSE
|
|
115
|
-
*/const
|
|
116
|
-
/*! *****************************************************************************
|
|
117
|
-
Copyright (c) Microsoft Corporation.
|
|
118
|
-
|
|
119
|
-
Permission to use, copy, modify, and/or distribute this software for any
|
|
120
|
-
purpose with or without fee is hereby granted.
|
|
121
|
-
|
|
122
|
-
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
123
|
-
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
124
|
-
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
125
|
-
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
126
|
-
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
127
|
-
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
128
|
-
PERFORMANCE OF THIS SOFTWARE.
|
|
129
|
-
***************************************************************************** */function ot(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 st(e,t){const i=[e];let n=e.parent;for(;null!==n;)i.unshift(n),n=n.parent;i.forEach((e=>{t(e)}))}class at{constructor(){this._constraints=new Set,this._objectConstraintsMap=new Map}get constraints(){return this._constraints}addConstraint(e){this._constraints.add(e);let t=this._objectConstraintsMap.get(e.destination);null==t&&(t=new Set,this._objectConstraintsMap.set(e.destination,t)),t.add(e)}deleteConstraint(e){this._constraints.delete(e);this._objectConstraintsMap.get(e.destination).delete(e)}setInitState(){const e=new Set,t=new Set;for(const i of this._constraints)this._processConstraint(i,e,t,(e=>e.setInitState()))}update(){const e=new Set,t=new Set;for(const i of this._constraints)this._processConstraint(i,e,t,(e=>e.update()))}_processConstraint(e,t,i,n){if(i.has(e))return;if(t.has(e))throw new Error("VRMNodeConstraintManager: Circular dependency detected while updating constraints");t.add(e);const r=e.dependencies;for(const e of r)st(e,(e=>{const r=this._objectConstraintsMap.get(e);if(r)for(const e of r)this._processConstraint(e,t,i,n)}));n(e),i.add(e)}}const lt=new e.Quaternion,ut=new e.Quaternion;class dt extends Ze{constructor(t,i){super(t,i),this._dstRestQuat=new e.Quaternion,this._invSrcRestQuat=new e.Quaternion}get dependencies(){return new Set([this.source])}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),$e(this._invSrcRestQuat.copy(this.source.quaternion))}update(){const e=lt.copy(this._invSrcRestQuat).multiply(this.source.quaternion),t=ut.copy(this._dstRestQuat).multiply(e);this.destination.quaternion.copy(this._dstRestQuat).slerp(t,this.weight)}}const ht=new e.Vector3,ct=new e.Quaternion,pt=new e.Quaternion;class mt extends Ze{constructor(t,i){super(t,i),this._rollAxis="X",this._v3RollAxis=new e.Vector3(1,0,0),this._dstRestQuat=new e.Quaternion,this._invDstRestQuat=new e.Quaternion,this._invSrcRestQuatMulDstRestQuat=new e.Quaternion}get rollAxis(){return this._rollAxis}set rollAxis(e){this._rollAxis=e,this._v3RollAxis.set("X"===e?1:0,"Y"===e?1:0,"Z"===e?1:0)}get dependencies(){return new Set([this.source])}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),$e(this._invDstRestQuat.copy(this._dstRestQuat)),$e(this._invSrcRestQuatMulDstRestQuat.copy(this.source.quaternion)).multiply(this._dstRestQuat)}update(){const e=ct.copy(this._invDstRestQuat).multiply(this.source.quaternion).multiply(this._invSrcRestQuatMulDstRestQuat),t=ht.copy(this._v3RollAxis).applyQuaternion(e),i=pt.setFromUnitVectors(t,this._v3RollAxis).premultiply(this._dstRestQuat).multiply(e);this.destination.quaternion.copy(this._dstRestQuat).slerp(i,this.weight)}}const ft=new Set(["1.0","1.0-beta"]);class vt{constructor(e,t){this.parser=e,this.helperRoot=null==t?void 0:t.helperRoot}get name(){return vt.EXTENSION_NAME}afterRoot(e){return ot(this,void 0,void 0,(function*(){e.userData.vrmNodeConstraintManager=yield this._import(e)}))}_import(e){var t;return ot(this,void 0,void 0,(function*(){const i=this.parser.json;if(!(-1!==(null===(t=i.extensionsUsed)||void 0===t?void 0:t.indexOf(vt.EXTENSION_NAME))))return null;const n=new at,r=yield this.parser.getDependencies("node");return r.forEach(((e,t)=>{var o;const s=i.nodes[t],a=null===(o=null==s?void 0:s.extensions)||void 0===o?void 0:o[vt.EXTENSION_NAME];if(null==a)return;const l=a.specVersion;if(!ft.has(l))return void console.warn(`VRMNodeConstraintLoaderPlugin: Unknown ${vt.EXTENSION_NAME} specVersion "${l}"`);const u=a.constraint;if(null!=u.roll){const t=this._importRollConstraint(e,r,u.roll);n.addConstraint(t)}else if(null!=u.aim){const t=this._importAimConstraint(e,r,u.aim);n.addConstraint(t)}else if(null!=u.rotation){const t=this._importRotationConstraint(e,r,u.rotation);n.addConstraint(t)}})),e.scene.updateMatrixWorld(),n.setInitState(),n}))}_importRollConstraint(e,t,i){const{source:n,rollAxis:r,weight:o}=i,s=t[n],a=new mt(e,s);if(null!=r&&(a.rollAxis=r),null!=o&&(a.weight=o),this.helperRoot){const e=new Xe(a);this.helperRoot.add(e)}return a}_importAimConstraint(e,t,i){const{source:n,aimAxis:r,weight:o}=i,s=t[n],a=new rt(e,s);if(null!=r&&(a.aimAxis=r),null!=o&&(a.weight=o),this.helperRoot){const e=new Xe(a);this.helperRoot.add(e)}return a}_importRotationConstraint(e,t,i){const{source:n,weight:r}=i,o=t[n],s=new dt(e,o);if(null!=r&&(s.weight=r),this.helperRoot){const e=new Xe(s);this.helperRoot.add(e)}return s}}vt.EXTENSION_NAME="VRMC_node_constraint";
|
|
45
|
+
*/const Xe=new e.Vector3;class Ge extends e.Group{constructor(t){super(),this._attrPosition=new e.BufferAttribute(new Float32Array([0,0,0,0,0,0]),3),this._attrPosition.setUsage(e.DynamicDrawUsage);const i=new e.BufferGeometry;i.setAttribute("position",this._attrPosition);const n=new e.LineBasicMaterial({color:16711935,depthTest:!1,depthWrite:!1});this._line=new e.Line(i,n),this.add(this._line),this.constraint=t}updateMatrixWorld(e){Xe.setFromMatrixPosition(this.constraint.destination.matrixWorld),this._attrPosition.setXYZ(0,Xe.x,Xe.y,Xe.z),this.constraint.source&&Xe.setFromMatrixPosition(this.constraint.source.matrixWorld),this._attrPosition.setXYZ(1,Xe.x,Xe.y,Xe.z),this._attrPosition.needsUpdate=!0,super.updateMatrixWorld(e)}}function Ye(e,t){return t.set(e.elements[12],e.elements[13],e.elements[14])}const qe=new e.Vector3,$e=new e.Vector3;function Ze(e){return e.invert?e.invert():e.inverse(),e}class Je{constructor(e,t){this.destination=e,this.source=t,this.weight=1}}const Ke=new e.Vector3,et=new e.Vector3,tt=new e.Vector3,it=new e.Quaternion,nt=new e.Quaternion,rt=new e.Quaternion;class ot extends Je{constructor(t,i){super(t,i),this._aimAxis="PositiveX",this._v3AimAxis=new e.Vector3(1,0,0),this._dstRestQuat=new e.Quaternion}get aimAxis(){return this._aimAxis}set aimAxis(e){this._aimAxis=e,this._v3AimAxis.set("PositiveX"===e?1:"NegativeX"===e?-1:0,"PositiveY"===e?1:"NegativeY"===e?-1:0,"PositiveZ"===e?1:"NegativeZ"===e?-1:0)}get dependencies(){const e=new Set([this.source]);return this.destination.parent&&e.add(this.destination.parent),e}setInitState(){this._dstRestQuat.copy(this.destination.quaternion)}update(){this.destination.updateWorldMatrix(!0,!1),this.source.updateWorldMatrix(!0,!1);const e=it.identity(),t=nt.identity();var i,n;this.destination.parent&&(i=this.destination.parent.matrixWorld,n=e,i.decompose(qe,n,$e),Ze(t.copy(e)));const r=Ke.copy(this._v3AimAxis).applyQuaternion(this._dstRestQuat).applyQuaternion(e),o=Ye(this.source.matrixWorld,et).sub(Ye(this.destination.matrixWorld,tt)).normalize(),s=rt.setFromUnitVectors(r,o).premultiply(t).multiply(e).multiply(this._dstRestQuat);this.destination.quaternion.copy(this._dstRestQuat).slerp(s,this.weight)}}function st(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 at(e,t){const i=[e];let n=e.parent;for(;null!==n;)i.unshift(n),n=n.parent;i.forEach((e=>{t(e)}))}class lt{constructor(){this._constraints=new Set,this._objectConstraintsMap=new Map}get constraints(){return this._constraints}addConstraint(e){this._constraints.add(e);let t=this._objectConstraintsMap.get(e.destination);null==t&&(t=new Set,this._objectConstraintsMap.set(e.destination,t)),t.add(e)}deleteConstraint(e){this._constraints.delete(e);this._objectConstraintsMap.get(e.destination).delete(e)}setInitState(){const e=new Set,t=new Set;for(const i of this._constraints)this._processConstraint(i,e,t,(e=>e.setInitState()))}update(){const e=new Set,t=new Set;for(const i of this._constraints)this._processConstraint(i,e,t,(e=>e.update()))}_processConstraint(e,t,i,n){if(i.has(e))return;if(t.has(e))throw new Error("VRMNodeConstraintManager: Circular dependency detected while updating constraints");t.add(e);const r=e.dependencies;for(const e of r)at(e,(e=>{const r=this._objectConstraintsMap.get(e);if(r)for(const e of r)this._processConstraint(e,t,i,n)}));n(e),i.add(e)}}const ut=new e.Quaternion,dt=new e.Quaternion;class ht extends Je{constructor(t,i){super(t,i),this._dstRestQuat=new e.Quaternion,this._invSrcRestQuat=new e.Quaternion}get dependencies(){return new Set([this.source])}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),Ze(this._invSrcRestQuat.copy(this.source.quaternion))}update(){const e=ut.copy(this._invSrcRestQuat).multiply(this.source.quaternion),t=dt.copy(this._dstRestQuat).multiply(e);this.destination.quaternion.copy(this._dstRestQuat).slerp(t,this.weight)}}const ct=new e.Vector3,pt=new e.Quaternion,mt=new e.Quaternion;class ft extends Je{constructor(t,i){super(t,i),this._rollAxis="X",this._v3RollAxis=new e.Vector3(1,0,0),this._dstRestQuat=new e.Quaternion,this._invDstRestQuat=new e.Quaternion,this._invSrcRestQuatMulDstRestQuat=new e.Quaternion}get rollAxis(){return this._rollAxis}set rollAxis(e){this._rollAxis=e,this._v3RollAxis.set("X"===e?1:0,"Y"===e?1:0,"Z"===e?1:0)}get dependencies(){return new Set([this.source])}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),Ze(this._invDstRestQuat.copy(this._dstRestQuat)),Ze(this._invSrcRestQuatMulDstRestQuat.copy(this.source.quaternion)).multiply(this._dstRestQuat)}update(){const e=pt.copy(this._invDstRestQuat).multiply(this.source.quaternion).multiply(this._invSrcRestQuatMulDstRestQuat),t=ct.copy(this._v3RollAxis).applyQuaternion(e),i=mt.setFromUnitVectors(t,this._v3RollAxis).premultiply(this._dstRestQuat).multiply(e);this.destination.quaternion.copy(this._dstRestQuat).slerp(i,this.weight)}}const vt=new Set(["1.0","1.0-beta"]);class gt{constructor(e,t){this.parser=e,this.helperRoot=null==t?void 0:t.helperRoot}get name(){return gt.EXTENSION_NAME}afterRoot(e){return st(this,void 0,void 0,(function*(){e.userData.vrmNodeConstraintManager=yield this._import(e)}))}_import(e){var t;return st(this,void 0,void 0,(function*(){const i=this.parser.json;if(!(-1!==(null===(t=i.extensionsUsed)||void 0===t?void 0:t.indexOf(gt.EXTENSION_NAME))))return null;const n=new lt,r=yield this.parser.getDependencies("node");return r.forEach(((e,t)=>{var o;const s=i.nodes[t],a=null===(o=null==s?void 0:s.extensions)||void 0===o?void 0:o[gt.EXTENSION_NAME];if(null==a)return;const l=a.specVersion;if(!vt.has(l))return void console.warn(`VRMNodeConstraintLoaderPlugin: Unknown ${gt.EXTENSION_NAME} specVersion "${l}"`);const u=a.constraint;if(null!=u.roll){const t=this._importRollConstraint(e,r,u.roll);n.addConstraint(t)}else if(null!=u.aim){const t=this._importAimConstraint(e,r,u.aim);n.addConstraint(t)}else if(null!=u.rotation){const t=this._importRotationConstraint(e,r,u.rotation);n.addConstraint(t)}})),e.scene.updateMatrixWorld(),n.setInitState(),n}))}_importRollConstraint(e,t,i){const{source:n,rollAxis:r,weight:o}=i,s=t[n],a=new ft(e,s);if(null!=r&&(a.rollAxis=r),null!=o&&(a.weight=o),this.helperRoot){const e=new Ge(a);this.helperRoot.add(e)}return a}_importAimConstraint(e,t,i){const{source:n,aimAxis:r,weight:o}=i,s=t[n],a=new ot(e,s);if(null!=r&&(a.aimAxis=r),null!=o&&(a.weight=o),this.helperRoot){const e=new Ge(a);this.helperRoot.add(e)}return a}_importRotationConstraint(e,t,i){const{source:n,weight:r}=i,o=t[n],s=new ht(e,o);if(null!=r&&(s.weight=r),this.helperRoot){const e=new Ge(s);this.helperRoot.add(e)}return s}}gt.EXTENSION_NAME="VRMC_node_constraint";
|
|
130
46
|
/*!
|
|
131
|
-
* @pixiv/three-vrm-springbone v1.0.
|
|
47
|
+
* @pixiv/three-vrm-springbone v1.0.3
|
|
132
48
|
* Spring bone module for @pixiv/three-vrm
|
|
133
49
|
*
|
|
134
|
-
* Copyright (c) 2020-
|
|
50
|
+
* Copyright (c) 2020-2022 pixiv Inc.
|
|
135
51
|
* @pixiv/three-vrm-springbone is distributed under MIT License
|
|
136
52
|
* https://github.com/pixiv/three-vrm/blob/release/LICENSE
|
|
137
53
|
*/
|
|
138
|
-
class gt{}const _t=new e.Vector3,xt=new e.Vector3;class Mt extends gt{constructor(t){var i,n,r;super(),this.offset=null!==(i=null==t?void 0:t.offset)&&void 0!==i?i:new e.Vector3(0,0,0),this.tail=null!==(n=null==t?void 0:t.tail)&&void 0!==n?n:new e.Vector3(0,0,0),this.radius=null!==(r=null==t?void 0:t.radius)&&void 0!==r?r:0}get type(){return"capsule"}calculateCollision(e,t,i,n){_t.copy(this.offset).applyMatrix4(e),xt.copy(this.tail).applyMatrix4(e),xt.sub(_t);const r=xt.lengthSq();n.copy(t).sub(_t);const o=xt.dot(n);o<=0||(r<=o||xt.multiplyScalar(o/r),n.sub(xt));const s=i+this.radius,a=n.length()-s;return n.normalize(),a}}class yt extends gt{constructor(t){var i,n;super(),this.offset=null!==(i=null==t?void 0:t.offset)&&void 0!==i?i:new e.Vector3(0,0,0),this.radius=null!==(n=null==t?void 0:t.radius)&&void 0!==n?n:0}get type(){return"sphere"}calculateCollision(e,t,i,n){n.copy(this.offset).applyMatrix4(e),n.negate().add(t);const r=i+this.radius,o=n.length()-r;return n.normalize(),o}}const Tt=new e.Vector3;class Rt extends e.BufferGeometry{constructor(t){super(),this._currentRadius=0,this._currentOffset=new e.Vector3,this._currentTail=new e.Vector3,this._shape=t,this._attrPos=new e.BufferAttribute(new Float32Array(396),3),this.setAttribute("position",this._attrPos),this._attrIndex=new e.BufferAttribute(new Uint16Array(264),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentRadius!==this._shape.radius&&(this._currentRadius=this._shape.radius,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0),this._currentTail.equals(this._shape.tail)||(this._currentTail.copy(this._shape.tail),e=!0),e&&this._buildPosition()}_buildPosition(){Tt.copy(this._currentTail).sub(this._currentOffset);const e=Tt.length()/this._currentRadius;for(let t=0;t<=16;t++){const i=t/16*Math.PI;this._attrPos.setXYZ(t,-Math.sin(i),-Math.cos(i),0),this._attrPos.setXYZ(17+t,e+Math.sin(i),Math.cos(i),0),this._attrPos.setXYZ(34+t,-Math.sin(i),0,-Math.cos(i)),this._attrPos.setXYZ(51+t,e+Math.sin(i),0,Math.cos(i))}for(let t=0;t<32;t++){const i=t/16*Math.PI;this._attrPos.setXYZ(68+t,0,Math.sin(i),Math.cos(i)),this._attrPos.setXYZ(100+t,e,Math.sin(i),Math.cos(i))}const t=Math.atan2(Tt.y,Math.sqrt(Tt.x*Tt.x+Tt.z*Tt.z)),i=-Math.atan2(Tt.z,Tt.x);this.rotateZ(t),this.rotateY(i),this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<34;e++){const t=(e+1)%34;this._attrIndex.setXY(2*e,e,t),this._attrIndex.setXY(68+2*e,34+e,34+t)}for(let e=0;e<32;e++){const t=(e+1)%32;this._attrIndex.setXY(136+2*e,68+e,68+t),this._attrIndex.setXY(200+2*e,100+e,100+t)}this._attrIndex.needsUpdate=!0}}class wt extends e.BufferGeometry{constructor(t){super(),this._currentRadius=0,this._currentOffset=new e.Vector3,this._shape=t,this._attrPos=new e.BufferAttribute(new Float32Array(288),3),this.setAttribute("position",this._attrPos),this._attrIndex=new e.BufferAttribute(new Uint16Array(192),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentRadius!==this._shape.radius&&(this._currentRadius=this._shape.radius,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),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._currentOffset.x,this._currentOffset.y,this._currentOffset.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.needsUpdate=!0}}class Et extends e.Group{constructor(t){if(super(),this.matrixAutoUpdate=!1,this.collider=t,this.collider.shape instanceof yt)this._geometry=new wt(this.collider.shape);else{if(!(this.collider.shape instanceof Mt))throw new Error("VRMSpringBoneColliderHelper: Unknown collider shape type detected");this._geometry=new Rt(this.collider.shape)}const i=new e.LineBasicMaterial({color:16711935,depthTest:!1,depthWrite:!1});this._line=new e.LineSegments(this._geometry,i),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.collider.updateWorldMatrix(!0,!1),this.matrix.copy(this.collider.matrixWorld),this._geometry.update(),super.updateMatrixWorld(e)}}class Pt extends e.BufferGeometry{constructor(t){super(),this._currentRadius=0,this._currentTail=new e.Vector3,this._springBone=t,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._springBone.settings.hitRadius&&(this._currentRadius=this._springBone.settings.hitRadius,e=!0),this._currentTail.equals(this._springBone.initialLocalChildPosition)||(this._currentTail.copy(this._springBone.initialLocalChildPosition),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}}class Lt extends e.Group{constructor(t){super(),this.matrixAutoUpdate=!1,this.springBone=t,this._geometry=new Pt(this.springBone);const i=new e.LineBasicMaterial({color:16776960,depthTest:!1,depthWrite:!1});this._line=new e.LineSegments(this._geometry,i),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.springBone.bone.updateWorldMatrix(!0,!1),this.matrix.copy(this.springBone.bone.matrixWorld),this._geometry.update(),super.updateMatrixWorld(e)}}class St extends e.Object3D{constructor(e){super(),this.shape=e}}const At=new e.Matrix4;function bt(e){return e.invert?e.invert():e.getInverse(At.copy(e)),e}class It{constructor(t){this._inverseCache=new e.Matrix4,this._shouldUpdateInverse=!0,this.matrix=t;const i={set:(e,t,i)=>(this._shouldUpdateInverse=!0,e[t]=i,!0)};this._originalElements=t.elements,t.elements=new Proxy(t.elements,i)}get inverse(){return this._shouldUpdateInverse&&(this._inverseCache.copy(this.matrix),bt(this._inverseCache),this._shouldUpdateInverse=!1),this._inverseCache}revert(){this.matrix.elements=this._originalElements}}const Ut=new e.Matrix4,Ot=new e.Vector3,Vt=new e.Vector3,Ct=new e.Vector3,Nt=new e.Vector3,Dt=new e.Vector3,Ft=new e.Vector3,Bt=new e.Quaternion,Ht=new e.Matrix4,kt=new e.Matrix4;class Wt{constructor(t,i,n={},r=[]){var o,s,a,l,u,d;this._currentTail=new e.Vector3,this._prevTail=new e.Vector3,this._boneAxis=new e.Vector3,this._worldSpaceBoneLength=0,this._center=null,this._initialLocalMatrix=new e.Matrix4,this._initialLocalRotation=new e.Quaternion,this._initialLocalChildPosition=new e.Vector3,this.bone=t,this.bone.matrixAutoUpdate=!1,this.child=i,this.settings={hitRadius:null!==(o=n.hitRadius)&&void 0!==o?o:0,stiffness:null!==(s=n.stiffness)&&void 0!==s?s:1,gravityPower:null!==(a=n.gravityPower)&&void 0!==a?a:0,gravityDir:null!==(u=null===(l=n.gravityDir)||void 0===l?void 0:l.clone())&&void 0!==u?u:new e.Vector3(0,-1,0),dragForce:null!==(d=n.dragForce)&&void 0!==d?d:.4},this.colliderGroups=r}get center(){return this._center}set center(e){var t;(null===(t=this._center)||void 0===t?void 0:t.userData.inverseCacheProxy)&&(this._center.userData.inverseCacheProxy.revert(),delete this._center.userData.inverseCacheProxy),this._center=e,this._center&&(this._center.userData.inverseCacheProxy||(this._center.userData.inverseCacheProxy=new It(this._center.matrixWorld)))}get initialLocalChildPosition(){return this._initialLocalChildPosition}get _parentMatrixWorld(){return this.bone.parent?this.bone.parent.matrixWorld:Ut}setInitState(){this._initialLocalMatrix.copy(this.bone.matrix),this._initialLocalRotation.copy(this.bone.quaternion),this.child?this._initialLocalChildPosition.copy(this.child.position):this._initialLocalChildPosition.copy(this.bone.position).normalize().multiplyScalar(.07),this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)),this._prevTail.copy(this._currentTail),this._boneAxis.copy(this._initialLocalChildPosition).normalize(),this._worldSpaceBoneLength=Ot.copy(this._initialLocalChildPosition).applyMatrix4(this.bone.matrixWorld).sub(Vt.setFromMatrixPosition(this.bone.matrixWorld)).length()}reset(){this.bone.quaternion.copy(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix);const e=this._getMatrixWorldToCenter(Ht);this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(e),this._prevTail.copy(this._currentTail)}update(e){if(e<=0)return;Nt.setFromMatrixPosition(this.bone.matrixWorld);let t=this._getMatrixWorldToCenter(Ht);Dt.copy(Nt).applyMatrix4(t);const i=Bt.setFromRotationMatrix(t),n=kt.copy(t).multiply(this._parentMatrixWorld),r=Vt.copy(this._boneAxis).applyMatrix4(this._initialLocalMatrix).applyMatrix4(n).sub(Dt).normalize(),o=Ct.copy(this.settings.gravityDir).applyQuaternion(i).normalize(),s=this._getMatrixCenterToWorld(Ht);Ft.copy(this._currentTail).add(Ot.copy(this._currentTail).sub(this._prevTail).multiplyScalar(1-this.settings.dragForce)).add(Ot.copy(r).multiplyScalar(this.settings.stiffness*e)).add(Ot.copy(o).multiplyScalar(this.settings.gravityPower*e)).applyMatrix4(s),Ft.sub(Nt).normalize().multiplyScalar(this._worldSpaceBoneLength).add(Nt),this._collision(Ft),t=this._getMatrixWorldToCenter(Ht),this._prevTail.copy(this._currentTail),this._currentTail.copy(Ot.copy(Ft).applyMatrix4(t));const a=bt(Ht.copy(this._parentMatrixWorld).multiply(this._initialLocalMatrix)),l=Bt.setFromUnitVectors(this._boneAxis,Ot.copy(Ft).applyMatrix4(a).normalize());this.bone.quaternion.copy(this._initialLocalRotation).multiply(l),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix)}_collision(e){this.colliderGroups.forEach((t=>{t.colliders.forEach((t=>{const i=t.shape.calculateCollision(t.matrixWorld,e,this.settings.hitRadius,Ot);i<0&&(e.add(Ot.multiplyScalar(-i)),e.sub(Nt).normalize().multiplyScalar(this._worldSpaceBoneLength).add(Nt))}))}))}_getMatrixCenterToWorld(e){return this._center?e.copy(this._center.matrixWorld):e.identity(),e}_getMatrixWorldToCenter(e){return this._center?e.copy(this._center.userData.inverseCacheProxy.inverse):e.identity(),e}}
|
|
139
|
-
/*! *****************************************************************************
|
|
140
|
-
Copyright (c) Microsoft Corporation.
|
|
141
|
-
|
|
142
|
-
Permission to use, copy, modify, and/or distribute this software for any
|
|
143
|
-
purpose with or without fee is hereby granted.
|
|
144
|
-
|
|
145
|
-
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
146
|
-
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
147
|
-
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
148
|
-
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
149
|
-
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
150
|
-
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
151
|
-
PERFORMANCE OF THIS SOFTWARE.
|
|
152
|
-
***************************************************************************** */function zt(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 jt(e,t){const i=[];let n=e;for(;null!==n;)i.unshift(n),n=n.parent;i.forEach((e=>{t(e)}))}function Qt(e,t){e.children.forEach((e=>{t(e)||Qt(e,t)}))}class Xt{constructor(){this._joints=new Set,this._objectSpringBonesMap=new Map}get joints(){return this._joints}get springBones(){return console.warn("VRMSpringBoneManager: springBones is deprecated. use joints instead."),this._joints}get colliderGroups(){const e=new Set;return this._joints.forEach((t=>{t.colliderGroups.forEach((t=>{e.add(t)}))})),Array.from(e)}get colliders(){const e=new Set;return this.colliderGroups.forEach((t=>{t.colliders.forEach((t=>{e.add(t)}))})),Array.from(e)}addJoint(e){this._joints.add(e);let t=this._objectSpringBonesMap.get(e.bone);null==t&&(t=new Set,this._objectSpringBonesMap.set(e.bone,t)),t.add(e)}addSpringBone(e){console.warn("VRMSpringBoneManager: addSpringBone() is deprecated. use addJoint() instead."),this.addJoint(e)}deleteJoint(e){this._joints.delete(e);this._objectSpringBonesMap.get(e.bone).delete(e)}deleteSpringBone(e){console.warn("VRMSpringBoneManager: deleteSpringBone() is deprecated. use deleteJoint() instead."),this.deleteJoint(e)}setInitState(){const e=new Set,t=new Set,i=new Set;for(const n of this._joints)this._processSpringBone(n,e,t,i,(e=>e.setInitState()))}reset(){const e=new Set,t=new Set,i=new Set;for(const n of this._joints)this._processSpringBone(n,e,t,i,(e=>e.reset()))}update(e){const t=new Set,i=new Set,n=new Set;for(const r of this._joints)this._processSpringBone(r,t,i,n,(t=>t.update(e))),Qt(r.bone,(e=>{var t,i;return(null!==(i=null===(t=this._objectSpringBonesMap.get(e))||void 0===t?void 0:t.size)&&void 0!==i?i:0)>0||(e.updateWorldMatrix(!1,!1),!1)}))}_processSpringBone(e,t,i,n,r){if(i.has(e))return;if(t.has(e))throw new Error("VRMSpringBoneManager: Circular dependency detected while updating springbones");t.add(e);const o=this._getDependencies(e);for(const e of o)jt(e,(e=>{const o=this._objectSpringBonesMap.get(e);if(o)for(const e of o)this._processSpringBone(e,t,i,n,r);else n.has(e)||(e.updateWorldMatrix(!1,!1),n.add(e))}));e.bone.updateMatrix(),e.bone.updateWorldMatrix(!1,!1),r(e),n.add(e.bone),i.add(e)}_getDependencies(e){const t=new Set,i=e.bone.parent;return i&&t.add(i),e.colliderGroups.forEach((e=>{e.colliders.forEach((e=>{t.add(e)}))})),t}}const Gt=new Set(["1.0","1.0-beta"]);class Yt{constructor(e,t){this.parser=e,this.jointHelperRoot=null==t?void 0:t.jointHelperRoot,this.colliderHelperRoot=null==t?void 0:t.colliderHelperRoot}get name(){return Yt.EXTENSION_NAME}afterRoot(e){return zt(this,void 0,void 0,(function*(){e.userData.vrmSpringBoneManager=yield this._import(e)}))}_import(e){return zt(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(t){var i,n,r,o,s;return zt(this,void 0,void 0,(function*(){const a=t.parser.json;if(!(-1!==(null===(i=a.extensionsUsed)||void 0===i?void 0:i.indexOf(Yt.EXTENSION_NAME))))return null;const l=new Xt,u=yield t.parser.getDependencies("node"),d=null===(n=a.extensions)||void 0===n?void 0:n[Yt.EXTENSION_NAME];if(!d)return null;const h=d.specVersion;if(!Gt.has(h))return console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${Yt.EXTENSION_NAME} specVersion "${h}"`),null;const c=null===(r=d.colliders)||void 0===r?void 0:r.map(((t,i)=>{var n,r,o,s,a;const l=u[t.node],d=t.shape;if(d.sphere)return this._importSphereCollider(l,{offset:(new e.Vector3).fromArray(null!==(n=d.sphere.offset)&&void 0!==n?n:[0,0,0]),radius:null!==(r=d.sphere.radius)&&void 0!==r?r:0});if(d.capsule)return this._importCapsuleCollider(l,{offset:(new e.Vector3).fromArray(null!==(o=d.capsule.offset)&&void 0!==o?o:[0,0,0]),radius:null!==(s=d.capsule.radius)&&void 0!==s?s:0,tail:(new e.Vector3).fromArray(null!==(a=d.capsule.tail)&&void 0!==a?a:[0,0,0])});throw new Error(`VRMSpringBoneLoaderPlugin: The collider #${i} has no valid shape`)})),p=null===(o=d.colliderGroups)||void 0===o?void 0:o.map(((e,t)=>{var i;return{colliders:(null!==(i=e.colliders)&&void 0!==i?i:[]).map((e=>{const i=null==c?void 0:c[e];if(null==i)throw new Error(`VRMSpringBoneLoaderPlugin: The colliderGroup #${t} attempted to use a collider #${e} but not found`);return i})),name:e.name}}));return null===(s=d.springs)||void 0===s||s.forEach(((t,i)=>{var n;const r=t.joints,o=null===(n=t.colliderGroups)||void 0===n?void 0:n.map((e=>{const t=null==p?void 0:p[e];if(null==t)throw new Error(`VRMSpringBoneLoaderPlugin: The spring #${i} attempted to use a colliderGroup ${e} but not found`);return t})),s=null!=t.center?u[t.center]:void 0;let a;r.forEach((t=>{if(a){const i=a.node,n=u[i],r=t.node,d=u[r],h={hitRadius:a.hitRadius,dragForce:a.dragForce,gravityPower:a.gravityPower,stiffness:a.stiffness,gravityDir:null!=a.gravityDir?(new e.Vector3).fromArray(a.gravityDir):void 0},c=this._importJoint(n,d,h,o);s&&(c.center=s),l.addJoint(c)}a=t}))})),l.setInitState(),l}))}_v0Import(t){var i,n,r;return zt(this,void 0,void 0,(function*(){const o=t.parser.json;if(!(-1!==(null===(i=o.extensionsUsed)||void 0===i?void 0:i.indexOf("VRM"))))return null;const s=null===(n=o.extensions)||void 0===n?void 0:n.VRM,a=null==s?void 0:s.secondaryAnimation;if(!a)return null;const l=null==a?void 0:a.boneGroups;if(!l)return null;const u=new Xt,d=yield t.parser.getDependencies("node"),h=null===(r=a.colliderGroups)||void 0===r?void 0:r.map((t=>{var i;const n=d[t.node];return{colliders:(null!==(i=t.colliders)&&void 0!==i?i:[]).map(((t,i)=>{var r,o,s;const a=new e.Vector3(0,0,0);return t.offset&&a.set(null!==(r=t.offset.x)&&void 0!==r?r:0,null!==(o=t.offset.y)&&void 0!==o?o:0,t.offset.z?-t.offset.z:0),this._importSphereCollider(n,{offset:a,radius:null!==(s=t.radius)&&void 0!==s?s:0})}))}}));return null==l||l.forEach(((t,i)=>{const n=t.bones;n&&n.forEach((n=>{var r,o,s,a;const l=d[n],c=new e.Vector3;t.gravityDir?c.set(null!==(r=t.gravityDir.x)&&void 0!==r?r:0,null!==(o=t.gravityDir.y)&&void 0!==o?o:0,null!==(s=t.gravityDir.z)&&void 0!==s?s:0):c.set(0,-1,0);const p=null!=t.center?d[t.center]:void 0,m={hitRadius:t.hitRadius,dragForce:t.dragForce,gravityPower:t.gravityPower,stiffness:t.stiffiness,gravityDir:c},f=null===(a=t.colliderGroups)||void 0===a?void 0:a.map((e=>{const t=null==h?void 0:h[e];if(null==t)throw new Error(`VRMSpringBoneLoaderPlugin: The spring #${i} attempted to use a colliderGroup ${e} but not found`);return t}));l.traverse((e=>{var t;const i=null!==(t=e.children[0])&&void 0!==t?t:null,n=this._importJoint(e,i,m,f);p&&(n.center=p),u.addJoint(n)}))}))})),t.scene.updateMatrixWorld(),u.setInitState(),u}))}_importJoint(e,t,i,n){const r=new Wt(e,t,i,n);if(this.jointHelperRoot){const e=new Lt(r);this.jointHelperRoot.add(e),e.renderOrder=this.jointHelperRoot.renderOrder}return r}_importSphereCollider(e,t){const{offset:i,radius:n}=t,r=new yt({offset:i,radius:n}),o=new St(r);if(e.add(o),this.colliderHelperRoot){const e=new Et(o);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return o}_importCapsuleCollider(e,t){const{offset:i,radius:n,tail:r}=t,o=new Mt({offset:i,radius:n,tail:r}),s=new St(o);if(e.add(s),this.colliderHelperRoot){const e=new Et(s);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return s}}Yt.EXTENSION_NAME="VRMC_springBone";class qt{constructor(e,t){var i,n,r,o,s,a,l,u,d,h;this.parser=e;const c=null==t?void 0:t.helperRoot,p=null==t?void 0:t.autoUpdateHumanBones;this.expressionPlugin=null!==(i=null==t?void 0:t.expressionPlugin)&&void 0!==i?i:new x(e),this.firstPersonPlugin=null!==(n=null==t?void 0:t.firstPersonPlugin)&&void 0!==n?n:new R(e),this.humanoidPlugin=null!==(r=null==t?void 0:t.humanoidPlugin)&&void 0!==r?r:new z(e,{helperRoot:c,autoUpdateHumanBones:p}),this.lookAtPlugin=null!==(o=null==t?void 0:t.lookAtPlugin)&&void 0!==o?o:new Re(e,{helperRoot:c}),this.metaPlugin=null!==(s=null==t?void 0:t.metaPlugin)&&void 0!==s?s:new Pe(e),this.mtoonMaterialPlugin=null!==(a=null==t?void 0:t.mtoonMaterialPlugin)&&void 0!==a?a:new Be(e),this.materialsHDREmissiveMultiplierPlugin=null!==(l=null==t?void 0:t.materialsHDREmissiveMultiplierPlugin)&&void 0!==l?l:new ke(e),this.materialsV0CompatPlugin=null!==(u=null==t?void 0:t.materialsV0CompatPlugin)&&void 0!==u?u:new je(e),this.springBonePlugin=null!==(d=null==t?void 0:t.springBonePlugin)&&void 0!==d?d:new Yt(e,{colliderHelperRoot:c,jointHelperRoot:c}),this.nodeConstraintPlugin=null!==(h=null==t?void 0:t.nodeConstraintPlugin)&&void 0!==h?h:new vt(e,{helperRoot:c})}get name(){return"VRMLoaderPlugin"}beforeRoot(){return be(this,void 0,void 0,(function*(){yield this.materialsV0CompatPlugin.beforeRoot(),yield this.mtoonMaterialPlugin.beforeRoot()}))}loadMesh(e){return be(this,void 0,void 0,(function*(){return yield this.mtoonMaterialPlugin.loadMesh(e)}))}getMaterialType(e){const t=this.mtoonMaterialPlugin.getMaterialType(e);return null!=t?t:null}extendMaterialParams(e,t){return be(this,void 0,void 0,(function*(){yield this.materialsHDREmissiveMultiplierPlugin.extendMaterialParams(e,t),yield this.mtoonMaterialPlugin.extendMaterialParams(e,t)}))}afterRoot(e){return be(this,void 0,void 0,(function*(){yield this.metaPlugin.afterRoot(e),yield this.humanoidPlugin.afterRoot(e),yield this.expressionPlugin.afterRoot(e),yield this.lookAtPlugin.afterRoot(e),yield this.firstPersonPlugin.afterRoot(e),yield this.springBonePlugin.afterRoot(e),yield this.nodeConstraintPlugin.afterRoot(e),yield this.mtoonMaterialPlugin.afterRoot(e);const t=e.userData.vrmMeta,i=e.userData.vrmHumanoid;if(t&&i){const n=new Ae({scene:e.scene,expressionManager:e.userData.vrmExpressionManager,firstPerson:e.userData.vrmFirstPerson,humanoid:i,lookAt:e.userData.vrmLookAt,meta:t,materials:e.userData.vrmMToonMaterials,springBoneManager:e.userData.vrmSpringBoneManager,nodeConstraintManager:e.userData.vrmNodeConstraintManager});e.userData.vrm=n}}))}}function $t(e){if(Object.values(e).forEach((e=>{if(null==e?void 0:e.isTexture){e.dispose()}})),e.isShaderMaterial){const t=e.uniforms;t&&Object.values(t).forEach((e=>{const t=e.value;if(null==t?void 0:t.isTexture){t.dispose()}}))}e.dispose()}function Zt(e){const t=e.geometry;t&&t.dispose();const i=e.skeleton;i&&i.dispose();const n=e.material;n&&(Array.isArray(n)?n.forEach((e=>$t(e))):n&&$t(n))}class Jt{constructor(){}}Jt.deepDispose=function(e){e.traverse(Zt)},Jt.removeUnnecessaryJoints=function(t){const i=new Map;t.traverse((t=>{if("SkinnedMesh"!==t.type)return;const n=t,r=n.geometry.getAttribute("skinIndex");let o=i.get(r);if(!o){const t=[],s=[],a={},l=r.array;for(let e=0;e<l.length;e++){const i=l[e];void 0===a[i]&&(a[i]=t.length,t.push(n.skeleton.bones[i]),s.push(n.skeleton.boneInverses[i])),l[e]=a[i]}r.copyArray(l),r.needsUpdate=!0,o=new e.Skeleton(t,s),i.set(r,o)}n.bind(o,new e.Matrix4)}))},Jt.removeUnnecessaryVertices=function(i){const n=new Map;i.traverse((i=>{var r,o,s,a;if(!i.isMesh)return;const l=i,u=l.geometry,d=u.index;if(null==d)return;const h=n.get(u);if(null!=h)return void(l.geometry=h);const c=new e.BufferGeometry;c.name=u.name,c.morphTargetsRelative=u.morphTargetsRelative,u.groups.forEach((e=>{c.addGroup(e.start,e.count,e.materialIndex)})),c.boundingBox=null!==(o=null===(r=u.boundingBox)||void 0===r?void 0:r.clone())&&void 0!==o?o:null,c.boundingSphere=null!==(a=null===(s=u.boundingSphere)||void 0===s?void 0:s.clone())&&void 0!==a?a:null,c.setDrawRange(u.drawRange.start,u.drawRange.count),c.userData=u.userData,n.set(u,c);const p=[],m=[];{const e=d.array,i=new e.constructor(e.length);let n=0;for(let t=0;t<e.length;t++){const r=e[t];let o=p[r];null==o&&(p[r]=n,m[n]=r,o=n,n++),i[t]=o}c.setIndex(new t(i,1,!1))}Object.keys(u.attributes).forEach((e=>{const i=u.attributes[e];if(i.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");const n=i.array,{itemSize:r,normalized:o}=i,s=new n.constructor(m.length*r);m.forEach(((e,t)=>{for(let i=0;i<r;i++)s[t*r+i]=n[e*r+i]})),c.setAttribute(e,new t(s,r,o))}));let f=!0;Object.keys(u.morphAttributes).forEach((e=>{c.morphAttributes[e]=[];const i=u.morphAttributes[e];for(let n=0;n<i.length;n++){const r=i[n];if(r.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");const o=r.array,{itemSize:s,normalized:a}=r,l=new o.constructor(m.length*s);m.forEach(((e,t)=>{for(let i=0;i<s;i++)l[t*s+i]=o[e*s+i]})),f=f&&l.every((e=>0===e)),c.morphAttributes[e][n]=new t(l,s,a)}})),f&&(c.morphAttributes={}),l.geometry=c})),Array.from(n.keys()).forEach((e=>{e.dispose()}))},Jt.rotateVRM0=function(e){var t;"0"===(null===(t=e.meta)||void 0===t?void 0:t.metaVersion)&&(e.scene.rotation.y=Math.PI)};export{Ne as MToonMaterial,Ue as MToonMaterialDebugMode,Be as MToonMaterialLoaderPlugin,Oe as MToonMaterialOutlineWidthMode,Ae as VRM,rt as VRMAimConstraint,Le as VRMCore,Se as VRMCoreLoaderPlugin,i as VRMExpression,x as VRMExpressionLoaderPlugin,d as VRMExpressionManager,h as VRMExpressionMaterialColorType,M as VRMExpressionOverrideType,l as VRMExpressionPresetName,y as VRMFirstPerson,R as VRMFirstPersonLoaderPlugin,w as VRMFirstPersonMeshAnnotationType,A as VRMHumanBoneList,b as VRMHumanBoneName,I as VRMHumanBoneParentMap,B as VRMHumanoid,S as VRMHumanoidHelper,z as VRMHumanoidLoaderPlugin,qt as VRMLoaderPlugin,me as VRMLookAt,xe as VRMLookAtBoneApplier,Me as VRMLookAtExpressionApplier,K as VRMLookAtHelper,Re as VRMLookAtLoaderPlugin,ye as VRMLookAtRangeMap,we as VRMLookAtTypeName,Pe as VRMMetaLoaderPlugin,Ze as VRMNodeConstraint,Xe as VRMNodeConstraintHelper,vt as VRMNodeConstraintLoaderPlugin,at as VRMNodeConstraintManager,H as VRMRequiredHumanBoneName,mt as VRMRollConstraint,dt as VRMRotationConstraint,St as VRMSpringBoneCollider,Et as VRMSpringBoneColliderHelper,gt as VRMSpringBoneColliderShape,Mt as VRMSpringBoneColliderShapeCapsule,yt as VRMSpringBoneColliderShapeSphere,Wt as VRMSpringBoneJoint,Lt as VRMSpringBoneJointHelper,Yt as VRMSpringBoneLoaderPlugin,Xt as VRMSpringBoneManager,Jt as VRMUtils};
|
|
54
|
+
class _t{}const xt=new e.Vector3,Mt=new e.Vector3;class yt extends _t{constructor(t){var i,n,r;super(),this.offset=null!==(i=null==t?void 0:t.offset)&&void 0!==i?i:new e.Vector3(0,0,0),this.tail=null!==(n=null==t?void 0:t.tail)&&void 0!==n?n:new e.Vector3(0,0,0),this.radius=null!==(r=null==t?void 0:t.radius)&&void 0!==r?r:0}get type(){return"capsule"}calculateCollision(e,t,i,n){xt.copy(this.offset).applyMatrix4(e),Mt.copy(this.tail).applyMatrix4(e),Mt.sub(xt);const r=Mt.lengthSq();n.copy(t).sub(xt);const o=Mt.dot(n);o<=0||(r<=o||Mt.multiplyScalar(o/r),n.sub(Mt));const s=i+this.radius,a=n.length()-s;return n.normalize(),a}}class Tt extends _t{constructor(t){var i,n;super(),this.offset=null!==(i=null==t?void 0:t.offset)&&void 0!==i?i:new e.Vector3(0,0,0),this.radius=null!==(n=null==t?void 0:t.radius)&&void 0!==n?n:0}get type(){return"sphere"}calculateCollision(e,t,i,n){n.copy(this.offset).applyMatrix4(e),n.negate().add(t);const r=i+this.radius,o=n.length()-r;return n.normalize(),o}}const Rt=new e.Vector3;class wt extends e.BufferGeometry{constructor(t){super(),this._currentRadius=0,this._currentOffset=new e.Vector3,this._currentTail=new e.Vector3,this._shape=t,this._attrPos=new e.BufferAttribute(new Float32Array(396),3),this.setAttribute("position",this._attrPos),this._attrIndex=new e.BufferAttribute(new Uint16Array(264),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentRadius!==this._shape.radius&&(this._currentRadius=this._shape.radius,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0),this._currentTail.equals(this._shape.tail)||(this._currentTail.copy(this._shape.tail),e=!0),e&&this._buildPosition()}_buildPosition(){Rt.copy(this._currentTail).sub(this._currentOffset);const e=Rt.length()/this._currentRadius;for(let t=0;t<=16;t++){const i=t/16*Math.PI;this._attrPos.setXYZ(t,-Math.sin(i),-Math.cos(i),0),this._attrPos.setXYZ(17+t,e+Math.sin(i),Math.cos(i),0),this._attrPos.setXYZ(34+t,-Math.sin(i),0,-Math.cos(i)),this._attrPos.setXYZ(51+t,e+Math.sin(i),0,Math.cos(i))}for(let t=0;t<32;t++){const i=t/16*Math.PI;this._attrPos.setXYZ(68+t,0,Math.sin(i),Math.cos(i)),this._attrPos.setXYZ(100+t,e,Math.sin(i),Math.cos(i))}const t=Math.atan2(Rt.y,Math.sqrt(Rt.x*Rt.x+Rt.z*Rt.z)),i=-Math.atan2(Rt.z,Rt.x);this.rotateZ(t),this.rotateY(i),this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<34;e++){const t=(e+1)%34;this._attrIndex.setXY(2*e,e,t),this._attrIndex.setXY(68+2*e,34+e,34+t)}for(let e=0;e<32;e++){const t=(e+1)%32;this._attrIndex.setXY(136+2*e,68+e,68+t),this._attrIndex.setXY(200+2*e,100+e,100+t)}this._attrIndex.needsUpdate=!0}}class Et extends e.BufferGeometry{constructor(t){super(),this._currentRadius=0,this._currentOffset=new e.Vector3,this._shape=t,this._attrPos=new e.BufferAttribute(new Float32Array(288),3),this.setAttribute("position",this._attrPos),this._attrIndex=new e.BufferAttribute(new Uint16Array(192),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentRadius!==this._shape.radius&&(this._currentRadius=this._shape.radius,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),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._currentOffset.x,this._currentOffset.y,this._currentOffset.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.needsUpdate=!0}}class Pt extends e.Group{constructor(t){if(super(),this.matrixAutoUpdate=!1,this.collider=t,this.collider.shape instanceof Tt)this._geometry=new Et(this.collider.shape);else{if(!(this.collider.shape instanceof yt))throw new Error("VRMSpringBoneColliderHelper: Unknown collider shape type detected");this._geometry=new wt(this.collider.shape)}const i=new e.LineBasicMaterial({color:16711935,depthTest:!1,depthWrite:!1});this._line=new e.LineSegments(this._geometry,i),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.collider.updateWorldMatrix(!0,!1),this.matrix.copy(this.collider.matrixWorld),this._geometry.update(),super.updateMatrixWorld(e)}}class Lt extends e.BufferGeometry{constructor(t){super(),this._currentRadius=0,this._currentTail=new e.Vector3,this._springBone=t,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._springBone.settings.hitRadius&&(this._currentRadius=this._springBone.settings.hitRadius,e=!0),this._currentTail.equals(this._springBone.initialLocalChildPosition)||(this._currentTail.copy(this._springBone.initialLocalChildPosition),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}}class St extends e.Group{constructor(t){super(),this.matrixAutoUpdate=!1,this.springBone=t,this._geometry=new Lt(this.springBone);const i=new e.LineBasicMaterial({color:16776960,depthTest:!1,depthWrite:!1});this._line=new e.LineSegments(this._geometry,i),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.springBone.bone.updateWorldMatrix(!0,!1),this.matrix.copy(this.springBone.bone.matrixWorld),this._geometry.update(),super.updateMatrixWorld(e)}}class At extends e.Object3D{constructor(e){super(),this.shape=e}}const bt=new e.Matrix4;function It(e){return e.invert?e.invert():e.getInverse(bt.copy(e)),e}class Ut{constructor(t){this._inverseCache=new e.Matrix4,this._shouldUpdateInverse=!0,this.matrix=t;const i={set:(e,t,i)=>(this._shouldUpdateInverse=!0,e[t]=i,!0)};this._originalElements=t.elements,t.elements=new Proxy(t.elements,i)}get inverse(){return this._shouldUpdateInverse&&(this._inverseCache.copy(this.matrix),It(this._inverseCache),this._shouldUpdateInverse=!1),this._inverseCache}revert(){this.matrix.elements=this._originalElements}}const Ot=new e.Matrix4,Vt=new e.Vector3,Ct=new e.Vector3,Nt=new e.Vector3,Dt=new e.Vector3,Ft=new e.Vector3,Bt=new e.Vector3,Ht=new e.Quaternion,kt=new e.Matrix4,Wt=new e.Matrix4;class zt{constructor(t,i,n={},r=[]){var o,s,a,l,u,d;this._currentTail=new e.Vector3,this._prevTail=new e.Vector3,this._boneAxis=new e.Vector3,this._worldSpaceBoneLength=0,this._center=null,this._initialLocalMatrix=new e.Matrix4,this._initialLocalRotation=new e.Quaternion,this._initialLocalChildPosition=new e.Vector3,this.bone=t,this.bone.matrixAutoUpdate=!1,this.child=i,this.settings={hitRadius:null!==(o=n.hitRadius)&&void 0!==o?o:0,stiffness:null!==(s=n.stiffness)&&void 0!==s?s:1,gravityPower:null!==(a=n.gravityPower)&&void 0!==a?a:0,gravityDir:null!==(u=null===(l=n.gravityDir)||void 0===l?void 0:l.clone())&&void 0!==u?u:new e.Vector3(0,-1,0),dragForce:null!==(d=n.dragForce)&&void 0!==d?d:.4},this.colliderGroups=r}get center(){return this._center}set center(e){var t;(null===(t=this._center)||void 0===t?void 0:t.userData.inverseCacheProxy)&&(this._center.userData.inverseCacheProxy.revert(),delete this._center.userData.inverseCacheProxy),this._center=e,this._center&&(this._center.userData.inverseCacheProxy||(this._center.userData.inverseCacheProxy=new Ut(this._center.matrixWorld)))}get initialLocalChildPosition(){return this._initialLocalChildPosition}get _parentMatrixWorld(){return this.bone.parent?this.bone.parent.matrixWorld:Ot}setInitState(){this._initialLocalMatrix.copy(this.bone.matrix),this._initialLocalRotation.copy(this.bone.quaternion),this.child?this._initialLocalChildPosition.copy(this.child.position):this._initialLocalChildPosition.copy(this.bone.position).normalize().multiplyScalar(.07),this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)),this._prevTail.copy(this._currentTail),this._boneAxis.copy(this._initialLocalChildPosition).normalize(),this._worldSpaceBoneLength=Vt.copy(this._initialLocalChildPosition).applyMatrix4(this.bone.matrixWorld).sub(Ct.setFromMatrixPosition(this.bone.matrixWorld)).length()}reset(){this.bone.quaternion.copy(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix);const e=this._getMatrixWorldToCenter(kt);this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(e),this._prevTail.copy(this._currentTail)}update(e){if(e<=0)return;Dt.setFromMatrixPosition(this.bone.matrixWorld);let t=this._getMatrixWorldToCenter(kt);Ft.copy(Dt).applyMatrix4(t);const i=Ht.setFromRotationMatrix(t),n=Wt.copy(t).multiply(this._parentMatrixWorld),r=Ct.copy(this._boneAxis).applyMatrix4(this._initialLocalMatrix).applyMatrix4(n).sub(Ft).normalize(),o=Nt.copy(this.settings.gravityDir).applyQuaternion(i).normalize(),s=this._getMatrixCenterToWorld(kt);Bt.copy(this._currentTail).add(Vt.copy(this._currentTail).sub(this._prevTail).multiplyScalar(1-this.settings.dragForce)).add(Vt.copy(r).multiplyScalar(this.settings.stiffness*e)).add(Vt.copy(o).multiplyScalar(this.settings.gravityPower*e)).applyMatrix4(s),Bt.sub(Dt).normalize().multiplyScalar(this._worldSpaceBoneLength).add(Dt),this._collision(Bt),t=this._getMatrixWorldToCenter(kt),this._prevTail.copy(this._currentTail),this._currentTail.copy(Vt.copy(Bt).applyMatrix4(t));const a=It(kt.copy(this._parentMatrixWorld).multiply(this._initialLocalMatrix)),l=Ht.setFromUnitVectors(this._boneAxis,Vt.copy(Bt).applyMatrix4(a).normalize());this.bone.quaternion.copy(this._initialLocalRotation).multiply(l),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix)}_collision(e){this.colliderGroups.forEach((t=>{t.colliders.forEach((t=>{const i=t.shape.calculateCollision(t.matrixWorld,e,this.settings.hitRadius,Vt);i<0&&(e.add(Vt.multiplyScalar(-i)),e.sub(Dt).normalize().multiplyScalar(this._worldSpaceBoneLength).add(Dt))}))}))}_getMatrixCenterToWorld(e){return this._center?e.copy(this._center.matrixWorld):e.identity(),e}_getMatrixWorldToCenter(e){return this._center?e.copy(this._center.userData.inverseCacheProxy.inverse):e.identity(),e}}function jt(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 Qt(e,t){const i=[];let n=e;for(;null!==n;)i.unshift(n),n=n.parent;i.forEach((e=>{t(e)}))}function Xt(e,t){e.children.forEach((e=>{t(e)||Xt(e,t)}))}class Gt{constructor(){this._joints=new Set,this._objectSpringBonesMap=new Map}get joints(){return this._joints}get springBones(){return console.warn("VRMSpringBoneManager: springBones is deprecated. use joints instead."),this._joints}get colliderGroups(){const e=new Set;return this._joints.forEach((t=>{t.colliderGroups.forEach((t=>{e.add(t)}))})),Array.from(e)}get colliders(){const e=new Set;return this.colliderGroups.forEach((t=>{t.colliders.forEach((t=>{e.add(t)}))})),Array.from(e)}addJoint(e){this._joints.add(e);let t=this._objectSpringBonesMap.get(e.bone);null==t&&(t=new Set,this._objectSpringBonesMap.set(e.bone,t)),t.add(e)}addSpringBone(e){console.warn("VRMSpringBoneManager: addSpringBone() is deprecated. use addJoint() instead."),this.addJoint(e)}deleteJoint(e){this._joints.delete(e);this._objectSpringBonesMap.get(e.bone).delete(e)}deleteSpringBone(e){console.warn("VRMSpringBoneManager: deleteSpringBone() is deprecated. use deleteJoint() instead."),this.deleteJoint(e)}setInitState(){const e=new Set,t=new Set,i=new Set;for(const n of this._joints)this._processSpringBone(n,e,t,i,(e=>e.setInitState()))}reset(){const e=new Set,t=new Set,i=new Set;for(const n of this._joints)this._processSpringBone(n,e,t,i,(e=>e.reset()))}update(e){const t=new Set,i=new Set,n=new Set;for(const r of this._joints)this._processSpringBone(r,t,i,n,(t=>t.update(e))),Xt(r.bone,(e=>{var t,i;return(null!==(i=null===(t=this._objectSpringBonesMap.get(e))||void 0===t?void 0:t.size)&&void 0!==i?i:0)>0||(e.updateWorldMatrix(!1,!1),!1)}))}_processSpringBone(e,t,i,n,r){if(i.has(e))return;if(t.has(e))throw new Error("VRMSpringBoneManager: Circular dependency detected while updating springbones");t.add(e);const o=this._getDependencies(e);for(const e of o)Qt(e,(e=>{const o=this._objectSpringBonesMap.get(e);if(o)for(const e of o)this._processSpringBone(e,t,i,n,r);else n.has(e)||(e.updateWorldMatrix(!1,!1),n.add(e))}));e.bone.updateMatrix(),e.bone.updateWorldMatrix(!1,!1),r(e),n.add(e.bone),i.add(e)}_getDependencies(e){const t=new Set,i=e.bone.parent;return i&&t.add(i),e.colliderGroups.forEach((e=>{e.colliders.forEach((e=>{t.add(e)}))})),t}}const Yt=new Set(["1.0","1.0-beta"]);class qt{constructor(e,t){this.parser=e,this.jointHelperRoot=null==t?void 0:t.jointHelperRoot,this.colliderHelperRoot=null==t?void 0:t.colliderHelperRoot}get name(){return qt.EXTENSION_NAME}afterRoot(e){return jt(this,void 0,void 0,(function*(){e.userData.vrmSpringBoneManager=yield this._import(e)}))}_import(e){return jt(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(t){var i,n,r,o,s;return jt(this,void 0,void 0,(function*(){const a=t.parser.json;if(!(-1!==(null===(i=a.extensionsUsed)||void 0===i?void 0:i.indexOf(qt.EXTENSION_NAME))))return null;const l=new Gt,u=yield t.parser.getDependencies("node"),d=null===(n=a.extensions)||void 0===n?void 0:n[qt.EXTENSION_NAME];if(!d)return null;const h=d.specVersion;if(!Yt.has(h))return console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${qt.EXTENSION_NAME} specVersion "${h}"`),null;const c=null===(r=d.colliders)||void 0===r?void 0:r.map(((t,i)=>{var n,r,o,s,a;const l=u[t.node],d=t.shape;if(d.sphere)return this._importSphereCollider(l,{offset:(new e.Vector3).fromArray(null!==(n=d.sphere.offset)&&void 0!==n?n:[0,0,0]),radius:null!==(r=d.sphere.radius)&&void 0!==r?r:0});if(d.capsule)return this._importCapsuleCollider(l,{offset:(new e.Vector3).fromArray(null!==(o=d.capsule.offset)&&void 0!==o?o:[0,0,0]),radius:null!==(s=d.capsule.radius)&&void 0!==s?s:0,tail:(new e.Vector3).fromArray(null!==(a=d.capsule.tail)&&void 0!==a?a:[0,0,0])});throw new Error(`VRMSpringBoneLoaderPlugin: The collider #${i} has no valid shape`)})),p=null===(o=d.colliderGroups)||void 0===o?void 0:o.map(((e,t)=>{var i;return{colliders:(null!==(i=e.colliders)&&void 0!==i?i:[]).map((e=>{const i=null==c?void 0:c[e];if(null==i)throw new Error(`VRMSpringBoneLoaderPlugin: The colliderGroup #${t} attempted to use a collider #${e} but not found`);return i})),name:e.name}}));return null===(s=d.springs)||void 0===s||s.forEach(((t,i)=>{var n;const r=t.joints,o=null===(n=t.colliderGroups)||void 0===n?void 0:n.map((e=>{const t=null==p?void 0:p[e];if(null==t)throw new Error(`VRMSpringBoneLoaderPlugin: The spring #${i} attempted to use a colliderGroup ${e} but not found`);return t})),s=null!=t.center?u[t.center]:void 0;let a;r.forEach((t=>{if(a){const i=a.node,n=u[i],r=t.node,d=u[r],h={hitRadius:a.hitRadius,dragForce:a.dragForce,gravityPower:a.gravityPower,stiffness:a.stiffness,gravityDir:null!=a.gravityDir?(new e.Vector3).fromArray(a.gravityDir):void 0},c=this._importJoint(n,d,h,o);s&&(c.center=s),l.addJoint(c)}a=t}))})),l.setInitState(),l}))}_v0Import(t){var i,n,r;return jt(this,void 0,void 0,(function*(){const o=t.parser.json;if(!(-1!==(null===(i=o.extensionsUsed)||void 0===i?void 0:i.indexOf("VRM"))))return null;const s=null===(n=o.extensions)||void 0===n?void 0:n.VRM,a=null==s?void 0:s.secondaryAnimation;if(!a)return null;const l=null==a?void 0:a.boneGroups;if(!l)return null;const u=new Gt,d=yield t.parser.getDependencies("node"),h=null===(r=a.colliderGroups)||void 0===r?void 0:r.map((t=>{var i;const n=d[t.node],r=(null!==(i=t.colliders)&&void 0!==i?i:[]).map(((t,i)=>{var r,o,s;const a=new e.Vector3(0,0,0);return t.offset&&a.set(null!==(r=t.offset.x)&&void 0!==r?r:0,null!==(o=t.offset.y)&&void 0!==o?o:0,t.offset.z?-t.offset.z:0),this._importSphereCollider(n,{offset:a,radius:null!==(s=t.radius)&&void 0!==s?s:0})}));return{colliders:r}}));return null==l||l.forEach(((t,i)=>{const n=t.bones;n&&n.forEach((n=>{var r,o,s,a;const l=d[n],c=new e.Vector3;t.gravityDir?c.set(null!==(r=t.gravityDir.x)&&void 0!==r?r:0,null!==(o=t.gravityDir.y)&&void 0!==o?o:0,null!==(s=t.gravityDir.z)&&void 0!==s?s:0):c.set(0,-1,0);const p=null!=t.center?d[t.center]:void 0,m={hitRadius:t.hitRadius,dragForce:t.dragForce,gravityPower:t.gravityPower,stiffness:t.stiffiness,gravityDir:c},f=null===(a=t.colliderGroups)||void 0===a?void 0:a.map((e=>{const t=null==h?void 0:h[e];if(null==t)throw new Error(`VRMSpringBoneLoaderPlugin: The spring #${i} attempted to use a colliderGroup ${e} but not found`);return t}));l.traverse((e=>{var t;const i=null!==(t=e.children[0])&&void 0!==t?t:null,n=this._importJoint(e,i,m,f);p&&(n.center=p),u.addJoint(n)}))}))})),t.scene.updateMatrixWorld(),u.setInitState(),u}))}_importJoint(e,t,i,n){const r=new zt(e,t,i,n);if(this.jointHelperRoot){const e=new St(r);this.jointHelperRoot.add(e),e.renderOrder=this.jointHelperRoot.renderOrder}return r}_importSphereCollider(e,t){const{offset:i,radius:n}=t,r=new Tt({offset:i,radius:n}),o=new At(r);if(e.add(o),this.colliderHelperRoot){const e=new Pt(o);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return o}_importCapsuleCollider(e,t){const{offset:i,radius:n,tail:r}=t,o=new yt({offset:i,radius:n,tail:r}),s=new At(o);if(e.add(s),this.colliderHelperRoot){const e=new Pt(s);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return s}}qt.EXTENSION_NAME="VRMC_springBone";class $t{constructor(e,t){var i,n,r,o,s,a,l,u,d,h;this.parser=e;const c=null==t?void 0:t.helperRoot,p=null==t?void 0:t.autoUpdateHumanBones;this.expressionPlugin=null!==(i=null==t?void 0:t.expressionPlugin)&&void 0!==i?i:new x(e),this.firstPersonPlugin=null!==(n=null==t?void 0:t.firstPersonPlugin)&&void 0!==n?n:new R(e),this.humanoidPlugin=null!==(r=null==t?void 0:t.humanoidPlugin)&&void 0!==r?r:new j(e,{helperRoot:c,autoUpdateHumanBones:p}),this.lookAtPlugin=null!==(o=null==t?void 0:t.lookAtPlugin)&&void 0!==o?o:new we(e,{helperRoot:c}),this.metaPlugin=null!==(s=null==t?void 0:t.metaPlugin)&&void 0!==s?s:new Le(e),this.mtoonMaterialPlugin=null!==(a=null==t?void 0:t.mtoonMaterialPlugin)&&void 0!==a?a:new He(e),this.materialsHDREmissiveMultiplierPlugin=null!==(l=null==t?void 0:t.materialsHDREmissiveMultiplierPlugin)&&void 0!==l?l:new We(e),this.materialsV0CompatPlugin=null!==(u=null==t?void 0:t.materialsV0CompatPlugin)&&void 0!==u?u:new Qe(e),this.springBonePlugin=null!==(d=null==t?void 0:t.springBonePlugin)&&void 0!==d?d:new qt(e,{colliderHelperRoot:c,jointHelperRoot:c}),this.nodeConstraintPlugin=null!==(h=null==t?void 0:t.nodeConstraintPlugin)&&void 0!==h?h:new gt(e,{helperRoot:c})}get name(){return"VRMLoaderPlugin"}beforeRoot(){return Ie(this,void 0,void 0,(function*(){yield this.materialsV0CompatPlugin.beforeRoot(),yield this.mtoonMaterialPlugin.beforeRoot()}))}loadMesh(e){return Ie(this,void 0,void 0,(function*(){return yield this.mtoonMaterialPlugin.loadMesh(e)}))}getMaterialType(e){const t=this.mtoonMaterialPlugin.getMaterialType(e);return null!=t?t:null}extendMaterialParams(e,t){return Ie(this,void 0,void 0,(function*(){yield this.materialsHDREmissiveMultiplierPlugin.extendMaterialParams(e,t),yield this.mtoonMaterialPlugin.extendMaterialParams(e,t)}))}afterRoot(e){return Ie(this,void 0,void 0,(function*(){yield this.metaPlugin.afterRoot(e),yield this.humanoidPlugin.afterRoot(e),yield this.expressionPlugin.afterRoot(e),yield this.lookAtPlugin.afterRoot(e),yield this.firstPersonPlugin.afterRoot(e),yield this.springBonePlugin.afterRoot(e),yield this.nodeConstraintPlugin.afterRoot(e),yield this.mtoonMaterialPlugin.afterRoot(e);const t=e.userData.vrmMeta,i=e.userData.vrmHumanoid;if(t&&i){const n=new be({scene:e.scene,expressionManager:e.userData.vrmExpressionManager,firstPerson:e.userData.vrmFirstPerson,humanoid:i,lookAt:e.userData.vrmLookAt,meta:t,materials:e.userData.vrmMToonMaterials,springBoneManager:e.userData.vrmSpringBoneManager,nodeConstraintManager:e.userData.vrmNodeConstraintManager});e.userData.vrm=n}}))}}function Zt(e){if(Object.values(e).forEach((e=>{if(null==e?void 0:e.isTexture){e.dispose()}})),e.isShaderMaterial){const t=e.uniforms;t&&Object.values(t).forEach((e=>{const t=e.value;if(null==t?void 0:t.isTexture){t.dispose()}}))}e.dispose()}function Jt(e){const t=e.geometry;t&&t.dispose();const i=e.skeleton;i&&i.dispose();const n=e.material;n&&(Array.isArray(n)?n.forEach((e=>Zt(e))):n&&Zt(n))}class Kt{constructor(){}}Kt.deepDispose=function(e){e.traverse(Jt)},Kt.removeUnnecessaryJoints=function(t){const i=new Map;t.traverse((t=>{if("SkinnedMesh"!==t.type)return;const n=t,r=n.geometry.getAttribute("skinIndex");let o=i.get(r);if(!o){const t=[],s=[],a={},l=r.array;for(let e=0;e<l.length;e++){const i=l[e];void 0===a[i]&&(a[i]=t.length,t.push(n.skeleton.bones[i]),s.push(n.skeleton.boneInverses[i])),l[e]=a[i]}r.copyArray(l),r.needsUpdate=!0,o=new e.Skeleton(t,s),i.set(r,o)}n.bind(o,new e.Matrix4)}))},Kt.removeUnnecessaryVertices=function(i){const n=new Map;i.traverse((i=>{var r,o,s,a;if(!i.isMesh)return;const l=i,u=l.geometry,d=u.index;if(null==d)return;const h=n.get(u);if(null!=h)return void(l.geometry=h);const c=new e.BufferGeometry;c.name=u.name,c.morphTargetsRelative=u.morphTargetsRelative,u.groups.forEach((e=>{c.addGroup(e.start,e.count,e.materialIndex)})),c.boundingBox=null!==(o=null===(r=u.boundingBox)||void 0===r?void 0:r.clone())&&void 0!==o?o:null,c.boundingSphere=null!==(a=null===(s=u.boundingSphere)||void 0===s?void 0:s.clone())&&void 0!==a?a:null,c.setDrawRange(u.drawRange.start,u.drawRange.count),c.userData=u.userData,n.set(u,c);const p=[],m=[];{const e=d.array,i=new e.constructor(e.length);let n=0;for(let t=0;t<e.length;t++){const r=e[t];let o=p[r];null==o&&(p[r]=n,m[n]=r,o=n,n++),i[t]=o}c.setIndex(new t(i,1,!1))}Object.keys(u.attributes).forEach((e=>{const i=u.attributes[e];if(i.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");const n=i.array,{itemSize:r,normalized:o}=i,s=new n.constructor(m.length*r);m.forEach(((e,t)=>{for(let i=0;i<r;i++)s[t*r+i]=n[e*r+i]})),c.setAttribute(e,new t(s,r,o))}));let f=!0;Object.keys(u.morphAttributes).forEach((e=>{c.morphAttributes[e]=[];const i=u.morphAttributes[e];for(let n=0;n<i.length;n++){const r=i[n];if(r.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");const o=r.array,{itemSize:s,normalized:a}=r,l=new o.constructor(m.length*s);m.forEach(((e,t)=>{for(let i=0;i<s;i++)l[t*s+i]=o[e*s+i]})),f=f&&l.every((e=>0===e)),c.morphAttributes[e][n]=new t(l,s,a)}})),f&&(c.morphAttributes={}),l.geometry=c})),Array.from(n.keys()).forEach((e=>{e.dispose()}))},Kt.rotateVRM0=function(e){var t;"0"===(null===(t=e.meta)||void 0===t?void 0:t.metaVersion)&&(e.scene.rotation.y=Math.PI)};export{De as MToonMaterial,Oe as MToonMaterialDebugMode,He as MToonMaterialLoaderPlugin,Ve as MToonMaterialOutlineWidthMode,be as VRM,ot as VRMAimConstraint,Se as VRMCore,Ae as VRMCoreLoaderPlugin,i as VRMExpression,x as VRMExpressionLoaderPlugin,d as VRMExpressionManager,h as VRMExpressionMaterialColorType,M as VRMExpressionOverrideType,l as VRMExpressionPresetName,y as VRMFirstPerson,R as VRMFirstPersonLoaderPlugin,w as VRMFirstPersonMeshAnnotationType,A as VRMHumanBoneList,b as VRMHumanBoneName,I as VRMHumanBoneParentMap,H as VRMHumanoid,S as VRMHumanoidHelper,j as VRMHumanoidLoaderPlugin,$t as VRMLoaderPlugin,fe as VRMLookAt,Me as VRMLookAtBoneApplier,ye as VRMLookAtExpressionApplier,ee as VRMLookAtHelper,we as VRMLookAtLoaderPlugin,Te as VRMLookAtRangeMap,Ee as VRMLookAtTypeName,Le as VRMMetaLoaderPlugin,Je as VRMNodeConstraint,Ge as VRMNodeConstraintHelper,gt as VRMNodeConstraintLoaderPlugin,lt as VRMNodeConstraintManager,k as VRMRequiredHumanBoneName,ft as VRMRollConstraint,ht as VRMRotationConstraint,At as VRMSpringBoneCollider,Pt as VRMSpringBoneColliderHelper,_t as VRMSpringBoneColliderShape,yt as VRMSpringBoneColliderShapeCapsule,Tt as VRMSpringBoneColliderShapeSphere,zt as VRMSpringBoneJoint,St as VRMSpringBoneJointHelper,qt as VRMSpringBoneLoaderPlugin,Gt as VRMSpringBoneManager,Kt as VRMUtils};
|