@pixiv/three-vrm 0.6.4 → 0.6.8
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/README.md +2 -2
- package/lib/three-vrm.js +3664 -3472
- package/lib/three-vrm.min.js +2 -2
- package/lib/three-vrm.module.js +3644 -3483
- package/lib/three-vrm.module.min.js +2 -2
- package/package.json +6 -9
- package/ts3.4/types/VRMUtils/index.d.ts +2 -0
- package/ts3.4/types/VRMUtils/removeUnnecessaryVertices.d.ts +12 -0
- package/ts3.4/types/material/getTexelDecodingFunction.d.ts +6 -0
- package/types/VRM.d.ts +110 -110
- package/types/VRMImporter.d.ts +42 -42
- package/types/VRMUtils/extractThumbnailBlob.d.ts +10 -10
- package/types/VRMUtils/index.d.ts +9 -7
- package/types/VRMUtils/removeUnnecessaryJoints.d.ts +9 -9
- package/types/VRMUtils/removeUnnecessaryVertices.d.ts +12 -0
- package/types/blendshape/VRMBlendShapeGroup.d.ts +50 -50
- package/types/blendshape/VRMBlendShapeImporter.d.ts +13 -13
- package/types/blendshape/VRMBlendShapeProxy.d.ts +91 -91
- package/types/blendshape/index.d.ts +3 -3
- package/types/debug/VRMDebug.d.ts +28 -28
- package/types/debug/VRMDebugOptions.d.ts +10 -10
- package/types/debug/VRMImporterDebug.d.ts +11 -11
- package/types/debug/VRMLookAtHeadDebug.d.ts +8 -8
- package/types/debug/VRMLookAtImporterDebug.d.ts +9 -9
- package/types/debug/VRMSpringBoneDebug.d.ts +14 -14
- package/types/debug/VRMSpringBoneImporterDebug.d.ts +10 -10
- package/types/debug/VRMSpringBoneManagerDebug.d.ts +11 -11
- package/types/debug/index.d.ts +4 -4
- package/types/firstperson/VRMFirstPerson.d.ts +116 -116
- package/types/firstperson/VRMFirstPersonImporter.d.ts +15 -15
- package/types/firstperson/index.d.ts +2 -2
- package/types/humanoid/VRMHumanBone.d.ts +22 -22
- package/types/humanoid/VRMHumanBoneArray.d.ts +9 -9
- package/types/humanoid/VRMHumanBones.d.ts +8 -8
- package/types/humanoid/VRMHumanDescription.d.ts +14 -14
- package/types/humanoid/VRMHumanLimit.d.ts +12 -12
- package/types/humanoid/VRMHumanoid.d.ts +87 -87
- package/types/humanoid/VRMHumanoidImporter.d.ts +13 -13
- package/types/humanoid/index.d.ts +6 -6
- package/types/index.d.ts +12 -12
- package/types/lookat/VRMCurveMapper.d.ts +36 -36
- package/types/lookat/VRMLookAtApplyer.d.ts +18 -18
- package/types/lookat/VRMLookAtBlendShapeApplyer.d.ts +26 -26
- package/types/lookat/VRMLookAtBoneApplyer.d.ts +28 -28
- package/types/lookat/VRMLookAtHead.d.ts +57 -57
- package/types/lookat/VRMLookAtImporter.d.ts +23 -23
- package/types/lookat/index.d.ts +6 -6
- package/types/material/MToonMaterial.d.ts +206 -206
- package/types/material/VRMMaterialImporter.d.ts +50 -50
- package/types/material/VRMUnlitMaterial.d.ts +46 -46
- package/types/material/getTexelDecodingFunction.d.ts +9 -3
- package/types/material/index.d.ts +3 -3
- package/types/meta/VRMMeta.d.ts +59 -59
- package/types/meta/VRMMetaImporter.d.ts +14 -14
- package/types/meta/VRMMetaImporterOptions.d.ts +9 -9
- package/types/meta/index.d.ts +3 -3
- package/types/springbone/VRMSpringBone.d.ts +130 -130
- package/types/springbone/VRMSpringBoneColliderGroup.d.ts +15 -15
- package/types/springbone/VRMSpringBoneImporter.d.ts +34 -34
- package/types/springbone/VRMSpringBoneManager.d.ts +35 -35
- package/types/springbone/VRMSpringBoneParameters.d.ts +9 -9
- package/types/springbone/index.d.ts +5 -5
- package/types/types/GLTFSchema.d.ts +887 -887
- package/types/types/VRMSchema.d.ts +440 -440
- package/types/types/index.d.ts +3 -3
- package/types/types/types.d.ts +64 -64
- package/types/utils/Matrix4InverseCache.d.ts +28 -28
- package/types/utils/disposer.d.ts +2 -2
- package/types/utils/gltfExtractPrimitivesFromNode.d.ts +22 -22
- package/types/utils/mat4InvertCompat.d.ts +8 -8
- package/types/utils/math.d.ts +40 -40
- package/types/utils/quatInvertCompat.d.ts +8 -8
- package/types/utils/renameMaterialProperty.d.ts +1 -1
package/lib/three-vrm.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*! (c) 2019-2021 pixiv Inc. - https://github.com/pixiv/three-vrm/blob/release/LICENSE */
|
|
2
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three")):"function"==typeof define&&define.amd?define(["exports","three"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).THREE_VRM={},e.THREE)}(this,(function(e,t){"use strict";
|
|
2
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three")):"function"==typeof define&&define.amd?define(["exports","three"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).THREE_VRM={},e.THREE)}(this,(function(e,t){"use strict";function n(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var i,r=n(t);
|
|
3
3
|
/*! *****************************************************************************
|
|
4
4
|
Copyright (c) Microsoft Corporation.
|
|
5
5
|
|
|
@@ -13,4 +13,4 @@
|
|
|
13
13
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
14
14
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
15
15
|
PERFORMANCE OF THIS SOFTWARE.
|
|
16
|
-
***************************************************************************** */function n(e,t,n,i){return new(n||(n=Promise))((function(r,o){function a(e){try{l(i.next(e))}catch(e){o(e)}}function s(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}l((i=i.apply(e,t||[])).next())}))}function i(e){Object.keys(e).forEach((t=>{const n=e[t];if(null==n?void 0:n.isTexture){n.dispose()}})),e.dispose()}function r(e){const t=e.geometry;t&&t.dispose();const n=e.material;n&&(Array.isArray(n)?n.forEach((e=>i(e))):n&&i(n))}var o;!function(e){e[e.NUMBER=0]="NUMBER",e[e.VECTOR2=1]="VECTOR2",e[e.VECTOR3=2]="VECTOR3",e[e.VECTOR4=3]="VECTOR4",e[e.COLOR=4]="COLOR"}(o||(o={}));const a=new t.Vector2,s=new t.Vector3,l=new t.Vector4,d=new t.Color;class h extends t.Object3D{constructor(e){super(),this.weight=0,this.isBinary=!1,this._binds=[],this._materialValues=[],this.name=`BlendShapeController_${e}`,this.type="BlendShapeController",this.visible=!1}addBind(e){const t=e.weight/100;this._binds.push({meshes:e.meshes,morphTargetIndex:e.morphTargetIndex,weight:t})}addMaterialValue(e){const n=e.material,i=e.propertyName;let r,a,s,l,d=n[i];d&&(d=e.defaultValue||d,d.isVector2?(r=o.VECTOR2,a=d.clone(),s=(new t.Vector2).fromArray(e.targetValue),l=s.clone().sub(a)):d.isVector3?(r=o.VECTOR3,a=d.clone(),s=(new t.Vector3).fromArray(e.targetValue),l=s.clone().sub(a)):d.isVector4?(r=o.VECTOR4,a=d.clone(),s=(new t.Vector4).fromArray([e.targetValue[2],e.targetValue[3],e.targetValue[0],e.targetValue[1]]),l=s.clone().sub(a)):d.isColor?(r=o.COLOR,a=d.clone(),s=(new t.Color).fromArray(e.targetValue),l=s.clone().sub(a)):(r=o.NUMBER,a=d,s=e.targetValue[0],l=s-a),this._materialValues.push({material:n,propertyName:i,defaultValue:a,targetValue:s,deltaValue:l,type:r}))}applyWeight(){const e=this.isBinary?this.weight<.5?0:1:this.weight;this._binds.forEach((t=>{t.meshes.forEach((n=>{n.morphTargetInfluences&&(n.morphTargetInfluences[t.morphTargetIndex]+=e*t.weight)}))})),this._materialValues.forEach((t=>{if(void 0!==t.material[t.propertyName]){if(t.type===o.NUMBER){const n=t.deltaValue;t.material[t.propertyName]+=n*e}else if(t.type===o.VECTOR2){const n=t.deltaValue;t.material[t.propertyName].add(a.copy(n).multiplyScalar(e))}else if(t.type===o.VECTOR3){const n=t.deltaValue;t.material[t.propertyName].add(s.copy(n).multiplyScalar(e))}else if(t.type===o.VECTOR4){const n=t.deltaValue;t.material[t.propertyName].add(l.copy(n).multiplyScalar(e))}else if(t.type===o.COLOR){const n=t.deltaValue;t.material[t.propertyName].add(d.copy(n).multiplyScalar(e))}"boolean"==typeof t.material.shouldApplyUniforms&&(t.material.shouldApplyUniforms=!0)}}))}clearAppliedWeight(){this._binds.forEach((e=>{e.meshes.forEach((t=>{t.morphTargetInfluences&&(t.morphTargetInfluences[e.morphTargetIndex]=0)}))})),this._materialValues.forEach((e=>{if(void 0!==e.material[e.propertyName]){if(e.type===o.NUMBER){const t=e.defaultValue;e.material[e.propertyName]=t}else if(e.type===o.VECTOR2){const t=e.defaultValue;e.material[e.propertyName].copy(t)}else if(e.type===o.VECTOR3){const t=e.defaultValue;e.material[e.propertyName].copy(t)}else if(e.type===o.VECTOR4){const t=e.defaultValue;e.material[e.propertyName].copy(t)}else if(e.type===o.COLOR){const t=e.defaultValue;e.material[e.propertyName].copy(t)}"boolean"==typeof e.material.shouldApplyUniforms&&(e.material.shouldApplyUniforms=!0)}}))}}var u,c,p,m,f,g,_;function v(e,t,n){const i=e.parser.json.nodes[t].mesh;if(null==i)return null;const r=e.parser.json.meshes[i].primitives.length,o=[];return n.traverse((e=>{o.length<r&&e.isMesh&&o.push(e)})),o}function M(e){return n(this,void 0,void 0,(function*(){const t=yield e.parser.getDependencies("node"),n=new Map;return t.forEach(((t,i)=>{const r=v(e,i,t);null!=r&&n.set(i,r)})),n}))}function T(e){return"_"!==e[0]?(console.warn(`renameMaterialProperty: Given property name "${e}" might be invalid`),e):(e=e.substring(1),/[A-Z]/.test(e[0])?e[0].toLowerCase()+e.substring(1):(console.warn(`renameMaterialProperty: Given property name "${e}" might be invalid`),e))}u=e.VRMSchema||(e.VRMSchema={}),(c=u.BlendShapePresetName||(u.BlendShapePresetName={})).A="a",c.Angry="angry",c.Blink="blink",c.BlinkL="blink_l",c.BlinkR="blink_r",c.E="e",c.Fun="fun",c.I="i",c.Joy="joy",c.Lookdown="lookdown",c.Lookleft="lookleft",c.Lookright="lookright",c.Lookup="lookup",c.Neutral="neutral",c.O="o",c.Sorrow="sorrow",c.U="u",c.Unknown="unknown",(p=u.FirstPersonLookAtTypeName||(u.FirstPersonLookAtTypeName={})).BlendShape="BlendShape",p.Bone="Bone",(m=u.HumanoidBoneName||(u.HumanoidBoneName={})).Chest="chest",m.Head="head",m.Hips="hips",m.Jaw="jaw",m.LeftEye="leftEye",m.LeftFoot="leftFoot",m.LeftHand="leftHand",m.LeftIndexDistal="leftIndexDistal",m.LeftIndexIntermediate="leftIndexIntermediate",m.LeftIndexProximal="leftIndexProximal",m.LeftLittleDistal="leftLittleDistal",m.LeftLittleIntermediate="leftLittleIntermediate",m.LeftLittleProximal="leftLittleProximal",m.LeftLowerArm="leftLowerArm",m.LeftLowerLeg="leftLowerLeg",m.LeftMiddleDistal="leftMiddleDistal",m.LeftMiddleIntermediate="leftMiddleIntermediate",m.LeftMiddleProximal="leftMiddleProximal",m.LeftRingDistal="leftRingDistal",m.LeftRingIntermediate="leftRingIntermediate",m.LeftRingProximal="leftRingProximal",m.LeftShoulder="leftShoulder",m.LeftThumbDistal="leftThumbDistal",m.LeftThumbIntermediate="leftThumbIntermediate",m.LeftThumbProximal="leftThumbProximal",m.LeftToes="leftToes",m.LeftUpperArm="leftUpperArm",m.LeftUpperLeg="leftUpperLeg",m.Neck="neck",m.RightEye="rightEye",m.RightFoot="rightFoot",m.RightHand="rightHand",m.RightIndexDistal="rightIndexDistal",m.RightIndexIntermediate="rightIndexIntermediate",m.RightIndexProximal="rightIndexProximal",m.RightLittleDistal="rightLittleDistal",m.RightLittleIntermediate="rightLittleIntermediate",m.RightLittleProximal="rightLittleProximal",m.RightLowerArm="rightLowerArm",m.RightLowerLeg="rightLowerLeg",m.RightMiddleDistal="rightMiddleDistal",m.RightMiddleIntermediate="rightMiddleIntermediate",m.RightMiddleProximal="rightMiddleProximal",m.RightRingDistal="rightRingDistal",m.RightRingIntermediate="rightRingIntermediate",m.RightRingProximal="rightRingProximal",m.RightShoulder="rightShoulder",m.RightThumbDistal="rightThumbDistal",m.RightThumbIntermediate="rightThumbIntermediate",m.RightThumbProximal="rightThumbProximal",m.RightToes="rightToes",m.RightUpperArm="rightUpperArm",m.RightUpperLeg="rightUpperLeg",m.Spine="spine",m.UpperChest="upperChest",(f=u.MetaAllowedUserName||(u.MetaAllowedUserName={})).Everyone="Everyone",f.ExplicitlyLicensedPerson="ExplicitlyLicensedPerson",f.OnlyAuthor="OnlyAuthor",(g=u.MetaUssageName||(u.MetaUssageName={})).Allow="Allow",g.Disallow="Disallow",(_=u.MetaLicenseName||(u.MetaLicenseName={})).Cc0="CC0",_.CcBy="CC_BY",_.CcByNc="CC_BY_NC",_.CcByNcNd="CC_BY_NC_ND",_.CcByNcSa="CC_BY_NC_SA",_.CcByNd="CC_BY_ND",_.CcBySa="CC_BY_SA",_.Other="Other",_.RedistributionProhibited="Redistribution_Prohibited";const y=new t.Vector3,x=new t.Vector3;function S(e,t){return e.matrixWorld.decompose(y,t,x),t}new t.Quaternion;class R{constructor(){this._blendShapeGroups={},this._blendShapePresetMap={},this._unknownGroupNames=[]}get expressions(){return Object.keys(this._blendShapeGroups)}get blendShapePresetMap(){return this._blendShapePresetMap}get unknownGroupNames(){return this._unknownGroupNames}getBlendShapeGroup(e){const t=this._blendShapePresetMap[e],n=t?this._blendShapeGroups[t]:this._blendShapeGroups[e];if(n)return n;console.warn(`no blend shape found by ${e}`)}registerBlendShapeGroup(e,t,n){this._blendShapeGroups[e]=n,t?this._blendShapePresetMap[t]=e:this._unknownGroupNames.push(e)}getValue(e){var t;const n=this.getBlendShapeGroup(e);return null!==(t=null==n?void 0:n.weight)&&void 0!==t?t:null}setValue(e,t){const n=this.getBlendShapeGroup(e);var i;n&&(n.weight=(i=t,Math.max(Math.min(i,1),0)))}getBlendShapeTrackName(e){const t=this.getBlendShapeGroup(e);return t?`${t.name}.weight`:null}update(){Object.keys(this._blendShapeGroups).forEach((e=>{this._blendShapeGroups[e].clearAppliedWeight()})),Object.keys(this._blendShapeGroups).forEach((e=>{this._blendShapeGroups[e].applyWeight()}))}}class L{import(t){var i;return n(this,void 0,void 0,(function*(){const r=null===(i=t.parser.json.extensions)||void 0===i?void 0:i.VRM;if(!r)return null;const o=r.blendShapeMaster;if(!o)return null;const a=new R,s=o.blendShapeGroups;if(!s)return a;const l={};return yield Promise.all(s.map((i=>n(this,void 0,void 0,(function*(){const r=i.name;if(void 0===r)return void console.warn("VRMBlendShapeImporter: One of blendShapeGroups has no name");let o;i.presetName&&i.presetName!==e.VRMSchema.BlendShapePresetName.Unknown&&!l[i.presetName]&&(o=i.presetName,l[i.presetName]=r);const s=new h(r);t.scene.add(s),s.isBinary=i.isBinary||!1,i.binds&&i.binds.forEach((e=>n(this,void 0,void 0,(function*(){if(void 0===e.mesh||void 0===e.index)return;const r=[];t.parser.json.nodes.forEach(((t,n)=>{t.mesh===e.mesh&&r.push(n)}));const o=e.index;yield Promise.all(r.map((r=>n(this,void 0,void 0,(function*(){var a;const l=yield function(e,t){return n(this,void 0,void 0,(function*(){const n=yield e.parser.getDependency("node",t);return v(e,t,n)}))}(t,r);l.every((e=>Array.isArray(e.morphTargetInfluences)&&o<e.morphTargetInfluences.length))?s.addBind({meshes:l,morphTargetIndex:o,weight:null!==(a=e.weight)&&void 0!==a?a:100}):console.warn(`VRMBlendShapeImporter: ${i.name} attempts to index ${o}th morph but not found.`)})))))}))));const d=i.materialValues;d&&d.forEach((e=>{if(void 0===e.materialName||void 0===e.propertyName||void 0===e.targetValue)return;const n=[];t.scene.traverse((t=>{if(t.material){const i=t.material;Array.isArray(i)?n.push(...i.filter((t=>t.name===e.materialName&&-1===n.indexOf(t)))):i.name===e.materialName&&-1===n.indexOf(i)&&n.push(i)}})),n.forEach((t=>{s.addMaterialValue({material:t,propertyName:T(e.propertyName),targetValue:e.targetValue})}))})),a.registerBlendShapeGroup(r,o,s)}))))),a}))}}const E=Object.freeze(new t.Vector3(0,0,-1)),w=new t.Quaternion;var P;!function(e){e[e.Auto=0]="Auto",e[e.Both=1]="Both",e[e.ThirdPersonOnly=2]="ThirdPersonOnly",e[e.FirstPersonOnly=3]="FirstPersonOnly"}(P||(P={}));class A{constructor(e,t){this.firstPersonFlag=A._parseFirstPersonFlag(e),this.primitives=t}static _parseFirstPersonFlag(e){switch(e){case"Both":return P.Both;case"ThirdPersonOnly":return P.ThirdPersonOnly;case"FirstPersonOnly":return P.FirstPersonOnly;default:return P.Auto}}}class C{constructor(e,t,n){this._meshAnnotations=[],this._firstPersonOnlyLayer=C._DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=C._DEFAULT_THIRDPERSON_ONLY_LAYER,this._initialized=!1,this._firstPersonBone=e,this._firstPersonBoneOffset=t,this._meshAnnotations=n}get firstPersonBone(){return this._firstPersonBone}get meshAnnotations(){return this._meshAnnotations}getFirstPersonWorldDirection(e){return e.copy(E).applyQuaternion(S(this._firstPersonBone,w))}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}getFirstPersonBoneOffset(e){return e.copy(this._firstPersonBoneOffset)}getFirstPersonWorldPosition(e){const n=this._firstPersonBoneOffset,i=new t.Vector4(n.x,n.y,n.z,1);return i.applyMatrix4(this._firstPersonBone.matrixWorld),e.set(i.x,i.y,i.z)}setup({firstPersonOnlyLayer:e=C._DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:t=C._DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initialized||(this._initialized=!0,this._firstPersonOnlyLayer=e,this._thirdPersonOnlyLayer=t,this._meshAnnotations.forEach((e=>{e.firstPersonFlag===P.FirstPersonOnly?e.primitives.forEach((e=>{e.layers.set(this._firstPersonOnlyLayer)})):e.firstPersonFlag===P.ThirdPersonOnly?e.primitives.forEach((e=>{e.layers.set(this._thirdPersonOnlyLayer)})):e.firstPersonFlag===P.Auto&&this._createHeadlessModel(e.primitives)})))}_excludeTriangles(e,t,n,i){let r=0;if(null!=t&&t.length>0)for(let o=0;o<e.length;o+=3){const a=e[o],s=e[o+1],l=e[o+2],d=t[a],h=n[a];if(d[0]>0&&i.includes(h[0]))continue;if(d[1]>0&&i.includes(h[1]))continue;if(d[2]>0&&i.includes(h[2]))continue;if(d[3]>0&&i.includes(h[3]))continue;const u=t[s],c=n[s];if(u[0]>0&&i.includes(c[0]))continue;if(u[1]>0&&i.includes(c[1]))continue;if(u[2]>0&&i.includes(c[2]))continue;if(u[3]>0&&i.includes(c[3]))continue;const p=t[l],m=n[l];p[0]>0&&i.includes(m[0])||(p[1]>0&&i.includes(m[1])||p[2]>0&&i.includes(m[2])||p[3]>0&&i.includes(m[3])||(e[r++]=a,e[r++]=s,e[r++]=l))}return r}_createErasedMesh(e,n){const i=new t.SkinnedMesh(e.geometry.clone(),e.material);i.name=`${e.name}(erase)`,i.frustumCulled=e.frustumCulled,i.layers.set(this._firstPersonOnlyLayer);const r=i.geometry,o=r.getAttribute("skinIndex").array,a=[];for(let e=0;e<o.length;e+=4)a.push([o[e],o[e+1],o[e+2],o[e+3]]);const s=r.getAttribute("skinWeight").array,l=[];for(let e=0;e<s.length;e+=4)l.push([s[e],s[e+1],s[e+2],s[e+3]]);const d=r.getIndex();if(!d)throw new Error("The geometry doesn't have an index buffer");const h=Array.from(d.array),u=this._excludeTriangles(h,l,a,n),c=[];for(let e=0;e<u;e++)c[e]=h[e];return r.setIndex(c),e.onBeforeRender&&(i.onBeforeRender=e.onBeforeRender),i.bind(new t.Skeleton(e.skeleton.bones,e.skeleton.boneInverses),new t.Matrix4),i}_createHeadlessModelForSkinnedMesh(e,t){const n=[];if(t.skeleton.bones.forEach(((e,t)=>{this._isEraseTarget(e)&&n.push(t)})),!n.length)return t.layers.enable(this._thirdPersonOnlyLayer),void t.layers.enable(this._firstPersonOnlyLayer);t.layers.set(this._thirdPersonOnlyLayer);const i=this._createErasedMesh(t,n);e.add(i)}_createHeadlessModel(e){e.forEach((e=>{if("SkinnedMesh"===e.type){const t=e;this._createHeadlessModelForSkinnedMesh(t.parent,t)}else this._isEraseTarget(e)&&e.layers.set(this._thirdPersonOnlyLayer)}))}_isEraseTarget(e){return e===this._firstPersonBone||!!e.parent&&this._isEraseTarget(e.parent)}}C._DEFAULT_FIRSTPERSON_ONLY_LAYER=9,C._DEFAULT_THIRDPERSON_ONLY_LAYER=10;class O{import(i,r){var o;return n(this,void 0,void 0,(function*(){const n=null===(o=i.parser.json.extensions)||void 0===o?void 0:o.VRM;if(!n)return null;const a=n.firstPerson;if(!a)return null;const s=a.firstPersonBone;let l;if(l=void 0===s||-1===s?r.getBoneNode(e.VRMSchema.HumanoidBoneName.Head):yield i.parser.getDependency("node",s),!l)return console.warn("VRMFirstPersonImporter: Could not find firstPersonBone of the VRM"),null;const d=a.firstPersonBoneOffset?new t.Vector3(a.firstPersonBoneOffset.x,a.firstPersonBoneOffset.y,-a.firstPersonBoneOffset.z):new t.Vector3(0,.06,0),h=[],u=yield M(i);return Array.from(u.entries()).forEach((([e,t])=>{const n=i.parser.json.nodes[e],r=a.meshAnnotations?a.meshAnnotations.find((e=>e.mesh===n.mesh)):void 0;h.push(new A(null==r?void 0:r.firstPersonFlag,t))})),new C(l,d,h)}))}}class b{constructor(e,t){this.node=e,this.humanLimit=t}}function D(e){return e.invert?e.invert():e.inverse(),e}const N=new t.Vector3,V=new t.Quaternion;class U{constructor(e,t){this.restPose={},this.humanBones=this._createHumanBones(e),this.humanDescription=t,this.restPose=this.getPose()}getPose(){const e={};return Object.keys(this.humanBones).forEach((t=>{const n=this.getBoneNode(t);if(!n)return;if(e[t])return;N.set(0,0,0),V.identity();const i=this.restPose[t];(null==i?void 0:i.position)&&N.fromArray(i.position).negate(),(null==i?void 0:i.rotation)&&D(V.fromArray(i.rotation)),N.add(n.position),V.premultiply(n.quaternion),e[t]={position:N.toArray(),rotation:V.toArray()}}),{}),e}setPose(e){Object.keys(e).forEach((t=>{const n=e[t],i=this.getBoneNode(t);if(!i)return;const r=this.restPose[t];r&&(n.position&&(i.position.fromArray(n.position),r.position&&i.position.add(N.fromArray(r.position))),n.rotation&&(i.quaternion.fromArray(n.rotation),r.rotation&&i.quaternion.multiply(V.fromArray(r.rotation))))}))}resetPose(){Object.entries(this.restPose).forEach((([e,t])=>{const n=this.getBoneNode(e);n&&((null==t?void 0:t.position)&&n.position.fromArray(t.position),(null==t?void 0:t.rotation)&&n.quaternion.fromArray(t.rotation))}))}getBone(e){var t;return null!==(t=this.humanBones[e][0])&&void 0!==t?t:void 0}getBones(e){var t;return null!==(t=this.humanBones[e])&&void 0!==t?t:[]}getBoneNode(e){var t,n;return null!==(n=null===(t=this.humanBones[e][0])||void 0===t?void 0:t.node)&&void 0!==n?n:null}getBoneNodes(e){var t,n;return null!==(n=null===(t=this.humanBones[e])||void 0===t?void 0:t.map((e=>e.node)))&&void 0!==n?n:[]}_createHumanBones(t){const n=Object.values(e.VRMSchema.HumanoidBoneName).reduce(((e,t)=>(e[t]=[],e)),{});return t.forEach((e=>{n[e.name].push(e.bone)})),n}}class I{import(e){var i;return n(this,void 0,void 0,(function*(){const r=null===(i=e.parser.json.extensions)||void 0===i?void 0:i.VRM;if(!r)return null;const o=r.humanoid;if(!o)return null;const a=[];o.humanBones&&(yield Promise.all(o.humanBones.map((i=>n(this,void 0,void 0,(function*(){if(!i.bone||null==i.node)return;const n=yield e.parser.getDependency("node",i.node);a.push({name:i.bone,bone:new b(n,{axisLength:i.axisLength,center:i.center&&new t.Vector3(i.center.x,i.center.y,i.center.z),max:i.max&&new t.Vector3(i.max.x,i.max.y,i.max.z),min:i.min&&new t.Vector3(i.min.x,i.min.y,i.min.z),useDefaultValues:i.useDefaultValues})})}))))));const s={armStretch:o.armStretch,legStretch:o.legStretch,upperArmTwist:o.upperArmTwist,lowerArmTwist:o.lowerArmTwist,upperLegTwist:o.upperLegTwist,lowerLegTwist:o.lowerLegTwist,feetSpacing:o.feetSpacing,hasTranslationDoF:o.hasTranslationDoF};return new U(a,s)}))}}class B{constructor(e,t,n){this.curve=[0,0,0,1,1,1,1,0],this.curveXRangeDegree=90,this.curveYRangeDegree=10,void 0!==e&&(this.curveXRangeDegree=e),void 0!==t&&(this.curveYRangeDegree=t),void 0!==n&&(this.curve=n)}map(e){const t=Math.min(Math.max(e,0),this.curveXRangeDegree)/this.curveXRangeDegree;return this.curveYRangeDegree*((e,t)=>{if(e.length<8)throw new Error("evaluateCurve: Invalid curve detected! (Array length must be 8 at least)");if(e.length%4!=0)throw new Error("evaluateCurve: Invalid curve detected! (Array length must be multiples of 4");let n;for(n=0;;n++){if(e.length<=4*n)return e[4*n-3];if(t<=e[4*n])break}const i=n-1;if(i<0)return e[4*i+5];const r=e[4*i],o=(t-r)/(e[4*n]-r);return((e,t,n,i,r)=>{const o=r*r*r,a=r*r;return e+(t-e)*(-2*o+3*a)+n*(o-2*a+r)+i*(o-a)})(e[4*i+1],e[4*n+1],e[4*i+3],e[4*n+2],o)})(this.curve,t)}}class G{}class F extends G{constructor(t,n,i,r){super(),this.type=e.VRMSchema.FirstPersonLookAtTypeName.BlendShape,this._curveHorizontal=n,this._curveVerticalDown=i,this._curveVerticalUp=r,this._blendShapeProxy=t}name(){return e.VRMSchema.FirstPersonLookAtTypeName.BlendShape}lookAt(t){const n=t.x,i=t.y;n<0?(this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookup,0),this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookdown,this._curveVerticalDown.map(-n))):(this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookdown,0),this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookup,this._curveVerticalUp.map(n))),i<0?(this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookleft,0),this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookright,this._curveHorizontal.map(-i))):(this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookright,0),this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookleft,this._curveHorizontal.map(i)))}}const k=Object.freeze(new t.Vector3(0,0,-1)),W=new t.Vector3,H=new t.Vector3,z=new t.Vector3,j=new t.Quaternion;class Y{constructor(e,n){this.autoUpdate=!0,this._euler=new t.Euler(0,0,0,Y.EULER_ORDER),this.firstPerson=e,this.applyer=n}getLookAtWorldDirection(e){const t=S(this.firstPerson.firstPersonBone,j);return e.copy(k).applyEuler(this._euler).applyQuaternion(t)}lookAt(e){this._calcEuler(this._euler,e),this.applyer&&this.applyer.lookAt(this._euler)}update(e){this.target&&this.autoUpdate&&(this.lookAt(this.target.getWorldPosition(W)),this.applyer&&this.applyer.lookAt(this._euler))}_calcEuler(e,t){const n=this.firstPerson.getFirstPersonWorldPosition(H),i=z.copy(t).sub(n).normalize();return i.applyQuaternion(D(S(this.firstPerson.firstPersonBone,j))),e.x=Math.atan2(i.y,Math.sqrt(i.x*i.x+i.z*i.z)),e.y=Math.atan2(-i.x,-i.z),e}}Y.EULER_ORDER="YXZ";const X=new t.Euler(0,0,0,Y.EULER_ORDER);class q extends G{constructor(t,n,i,r,o){super(),this.type=e.VRMSchema.FirstPersonLookAtTypeName.Bone,this._curveHorizontalInner=n,this._curveHorizontalOuter=i,this._curveVerticalDown=r,this._curveVerticalUp=o,this._leftEye=t.getBoneNode(e.VRMSchema.HumanoidBoneName.LeftEye),this._rightEye=t.getBoneNode(e.VRMSchema.HumanoidBoneName.RightEye)}lookAt(e){const t=e.x,n=e.y;this._leftEye&&(X.x=t<0?-this._curveVerticalDown.map(-t):this._curveVerticalUp.map(t),X.y=n<0?-this._curveHorizontalInner.map(-n):this._curveHorizontalOuter.map(n),this._leftEye.quaternion.setFromEuler(X)),this._rightEye&&(X.x=t<0?-this._curveVerticalDown.map(-t):this._curveVerticalUp.map(t),X.y=n<0?-this._curveHorizontalOuter.map(-n):this._curveHorizontalInner.map(n),this._rightEye.quaternion.setFromEuler(X))}}const Q=Math.PI/180;class Z{import(e,t,n,i){var r;const o=null===(r=e.parser.json.extensions)||void 0===r?void 0:r.VRM;if(!o)return null;const a=o.firstPerson;if(!a)return null;const s=this._importApplyer(a,n,i);return new Y(t,s||void 0)}_importApplyer(t,n,i){const r=t.lookAtHorizontalInner,o=t.lookAtHorizontalOuter,a=t.lookAtVerticalDown,s=t.lookAtVerticalUp;switch(t.lookAtTypeName){case e.VRMSchema.FirstPersonLookAtTypeName.Bone:return void 0===r||void 0===o||void 0===a||void 0===s?null:new q(i,this._importCurveMapperBone(r),this._importCurveMapperBone(o),this._importCurveMapperBone(a),this._importCurveMapperBone(s));case e.VRMSchema.FirstPersonLookAtTypeName.BlendShape:return void 0===o||void 0===a||void 0===s?null:new F(n,this._importCurveMapperBlendShape(o),this._importCurveMapperBlendShape(a),this._importCurveMapperBlendShape(s));default:return null}}_importCurveMapperBone(e){return new B("number"==typeof e.xRange?Q*e.xRange:void 0,"number"==typeof e.yRange?Q*e.yRange:void 0,e.curve)}_importCurveMapperBlendShape(e){return new B("number"==typeof e.xRange?Q*e.xRange:void 0,e.yRange,e.curve)}}const $=(e,n)=>{const i=(e=>{switch(e){case t.LinearEncoding:return["Linear","( value )"];case t.sRGBEncoding:return["sRGB","( value )"];case t.RGBEEncoding:return["RGBE","( value )"];case t.RGBM7Encoding:return["RGBM","( value, 7.0 )"];case t.RGBM16Encoding:return["RGBM","( value, 16.0 )"];case t.RGBDEncoding:return["RGBD","( value, 256.0 )"];case t.GammaEncoding:return["Gamma","( value, float( GAMMA_FACTOR ) )"];default:throw new Error("unsupported encoding: "+e)}})(n);return"vec4 "+e+"( vec4 value ) { return "+i[0]+"ToLinear"+i[1]+"; }"};const J=2*Math.PI;var K,ee,te,ne,ie;(K=e.MToonMaterialCullMode||(e.MToonMaterialCullMode={}))[K.Off=0]="Off",K[K.Front=1]="Front",K[K.Back=2]="Back",(ee=e.MToonMaterialDebugMode||(e.MToonMaterialDebugMode={}))[ee.None=0]="None",ee[ee.Normal=1]="Normal",ee[ee.LitShadeRate=2]="LitShadeRate",ee[ee.UV=3]="UV",(te=e.MToonMaterialOutlineColorMode||(e.MToonMaterialOutlineColorMode={}))[te.FixedColor=0]="FixedColor",te[te.MixedLighting=1]="MixedLighting",(ne=e.MToonMaterialOutlineWidthMode||(e.MToonMaterialOutlineWidthMode={}))[ne.None=0]="None",ne[ne.WorldCoordinates=1]="WorldCoordinates",ne[ne.ScreenCoordinates=2]="ScreenCoordinates",(ie=e.MToonMaterialRenderMode||(e.MToonMaterialRenderMode={}))[ie.Opaque=0]="Opaque",ie[ie.Cutout=1]="Cutout",ie[ie.Transparent=2]="Transparent",ie[ie.TransparentWithZWrite=3]="TransparentWithZWrite";class re extends t.ShaderMaterial{constructor(n={}){super(),this.isMToonMaterial=!0,this.cutoff=.5,this.color=new t.Vector4(1,1,1,1),this.shadeColor=new t.Vector4(.97,.81,.86,1),this.map=null,this.mainTex_ST=new t.Vector4(0,0,1,1),this.shadeTexture=null,this.normalMap=null,this.normalMapType=t.TangentSpaceNormalMap,this.normalScale=new t.Vector2(1,1),this.receiveShadowRate=1,this.receiveShadowTexture=null,this.shadingGradeRate=1,this.shadingGradeTexture=null,this.shadeShift=0,this.shadeToony=.9,this.lightColorAttenuation=0,this.indirectLightIntensity=.1,this.rimTexture=null,this.rimColor=new t.Vector4(0,0,0,1),this.rimLightingMix=0,this.rimFresnelPower=1,this.rimLift=0,this.sphereAdd=null,this.emissionColor=new t.Vector4(0,0,0,1),this.emissiveMap=null,this.outlineWidthTexture=null,this.outlineWidth=.5,this.outlineScaledMaxDistance=1,this.outlineColor=new t.Vector4(0,0,0,1),this.outlineLightingMix=1,this.uvAnimMaskTexture=null,this.uvAnimScrollX=0,this.uvAnimScrollY=0,this.uvAnimRotation=0,this.shouldApplyUniforms=!0,this._debugMode=e.MToonMaterialDebugMode.None,this._blendMode=e.MToonMaterialRenderMode.Opaque,this._outlineWidthMode=e.MToonMaterialOutlineWidthMode.None,this._outlineColorMode=e.MToonMaterialOutlineColorMode.FixedColor,this._cullMode=e.MToonMaterialCullMode.Back,this._outlineCullMode=e.MToonMaterialCullMode.Front,this._isOutline=!1,this._uvAnimOffsetX=0,this._uvAnimOffsetY=0,this._uvAnimPhase=0,this.encoding=n.encoding||t.LinearEncoding,this.encoding!==t.LinearEncoding&&this.encoding!==t.sRGBEncoding&&console.warn("The specified color encoding does not work properly with MToonMaterial. You might want to use THREE.sRGBEncoding instead."),["mToonVersion","shadeTexture_ST","bumpMap_ST","receiveShadowTexture_ST","shadingGradeTexture_ST","rimTexture_ST","sphereAdd_ST","emissionMap_ST","outlineWidthTexture_ST","uvAnimMaskTexture_ST","srcBlend","dstBlend"].forEach((e=>{void 0!==n[e]&&delete n[e]})),n.fog=!0,n.lights=!0,n.clipping=!0,n.skinning=n.skinning||!1,n.morphTargets=n.morphTargets||!1,n.morphNormals=n.morphNormals||!1,n.uniforms=t.UniformsUtils.merge([t.UniformsLib.common,t.UniformsLib.normalmap,t.UniformsLib.emissivemap,t.UniformsLib.fog,t.UniformsLib.lights,{cutoff:{value:.5},color:{value:new t.Color(1,1,1)},colorAlpha:{value:1},shadeColor:{value:new t.Color(.97,.81,.86)},mainTex_ST:{value:new t.Vector4(0,0,1,1)},shadeTexture:{value:null},receiveShadowRate:{value:1},receiveShadowTexture:{value:null},shadingGradeRate:{value:1},shadingGradeTexture:{value:null},shadeShift:{value:0},shadeToony:{value:.9},lightColorAttenuation:{value:0},indirectLightIntensity:{value:.1},rimTexture:{value:null},rimColor:{value:new t.Color(0,0,0)},rimLightingMix:{value:0},rimFresnelPower:{value:1},rimLift:{value:0},sphereAdd:{value:null},emissionColor:{value:new t.Color(0,0,0)},outlineWidthTexture:{value:null},outlineWidth:{value:.5},outlineScaledMaxDistance:{value:1},outlineColor:{value:new t.Color(0,0,0)},outlineLightingMix:{value:1},uvAnimMaskTexture:{value:null},uvAnimOffsetX:{value:0},uvAnimOffsetY:{value:0},uvAnimTheta:{value:0}}]),this.setValues(n),this._updateShaderCode(),this._applyUniforms()}get mainTex(){return this.map}set mainTex(e){this.map=e}get bumpMap(){return this.normalMap}set bumpMap(e){this.normalMap=e}get bumpScale(){return this.normalScale.x}set bumpScale(e){this.normalScale.set(e,e)}get emissionMap(){return this.emissiveMap}set emissionMap(e){this.emissiveMap=e}get blendMode(){return this._blendMode}set blendMode(t){this._blendMode=t,this.depthWrite=this._blendMode!==e.MToonMaterialRenderMode.Transparent,this.transparent=this._blendMode===e.MToonMaterialRenderMode.Transparent||this._blendMode===e.MToonMaterialRenderMode.TransparentWithZWrite,this._updateShaderCode()}get debugMode(){return this._debugMode}set debugMode(e){this._debugMode=e,this._updateShaderCode()}get outlineWidthMode(){return this._outlineWidthMode}set outlineWidthMode(e){this._outlineWidthMode=e,this._updateShaderCode()}get outlineColorMode(){return this._outlineColorMode}set outlineColorMode(e){this._outlineColorMode=e,this._updateShaderCode()}get cullMode(){return this._cullMode}set cullMode(e){this._cullMode=e,this._updateCullFace()}get outlineCullMode(){return this._outlineCullMode}set outlineCullMode(e){this._outlineCullMode=e,this._updateCullFace()}get zWrite(){return this.depthWrite?1:0}set zWrite(e){this.depthWrite=.5<=e}get isOutline(){return this._isOutline}set isOutline(e){this._isOutline=e,this._updateShaderCode(),this._updateCullFace()}updateVRMMaterials(e){this._uvAnimOffsetX=this._uvAnimOffsetX+e*this.uvAnimScrollX,this._uvAnimOffsetY=this._uvAnimOffsetY-e*this.uvAnimScrollY,this._uvAnimPhase=this._uvAnimPhase+e*this.uvAnimRotation,this._applyUniforms()}copy(e){return super.copy(e),this.cutoff=e.cutoff,this.color.copy(e.color),this.shadeColor.copy(e.shadeColor),this.map=e.map,this.mainTex_ST.copy(e.mainTex_ST),this.shadeTexture=e.shadeTexture,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(this.normalScale),this.receiveShadowRate=e.receiveShadowRate,this.receiveShadowTexture=e.receiveShadowTexture,this.shadingGradeRate=e.shadingGradeRate,this.shadingGradeTexture=e.shadingGradeTexture,this.shadeShift=e.shadeShift,this.shadeToony=e.shadeToony,this.lightColorAttenuation=e.lightColorAttenuation,this.indirectLightIntensity=e.indirectLightIntensity,this.rimTexture=e.rimTexture,this.rimColor.copy(e.rimColor),this.rimLightingMix=e.rimLightingMix,this.rimFresnelPower=e.rimFresnelPower,this.rimLift=e.rimLift,this.sphereAdd=e.sphereAdd,this.emissionColor.copy(e.emissionColor),this.emissiveMap=e.emissiveMap,this.outlineWidthTexture=e.outlineWidthTexture,this.outlineWidth=e.outlineWidth,this.outlineScaledMaxDistance=e.outlineScaledMaxDistance,this.outlineColor.copy(e.outlineColor),this.outlineLightingMix=e.outlineLightingMix,this.uvAnimMaskTexture=e.uvAnimMaskTexture,this.uvAnimScrollX=e.uvAnimScrollX,this.uvAnimScrollY=e.uvAnimScrollY,this.uvAnimRotation=e.uvAnimRotation,this.debugMode=e.debugMode,this.blendMode=e.blendMode,this.outlineWidthMode=e.outlineWidthMode,this.outlineColorMode=e.outlineColorMode,this.cullMode=e.cullMode,this.outlineCullMode=e.outlineCullMode,this.isOutline=e.isOutline,this}_applyUniforms(){this.uniforms.uvAnimOffsetX.value=this._uvAnimOffsetX,this.uniforms.uvAnimOffsetY.value=this._uvAnimOffsetY,this.uniforms.uvAnimTheta.value=J*this._uvAnimPhase,this.shouldApplyUniforms&&(this.shouldApplyUniforms=!1,this.uniforms.cutoff.value=this.cutoff,this.uniforms.color.value.setRGB(this.color.x,this.color.y,this.color.z),this.uniforms.colorAlpha.value=this.color.w,this.uniforms.shadeColor.value.setRGB(this.shadeColor.x,this.shadeColor.y,this.shadeColor.z),this.uniforms.map.value=this.map,this.uniforms.mainTex_ST.value.copy(this.mainTex_ST),this.uniforms.shadeTexture.value=this.shadeTexture,this.uniforms.normalMap.value=this.normalMap,this.uniforms.normalScale.value.copy(this.normalScale),this.uniforms.receiveShadowRate.value=this.receiveShadowRate,this.uniforms.receiveShadowTexture.value=this.receiveShadowTexture,this.uniforms.shadingGradeRate.value=this.shadingGradeRate,this.uniforms.shadingGradeTexture.value=this.shadingGradeTexture,this.uniforms.shadeShift.value=this.shadeShift,this.uniforms.shadeToony.value=this.shadeToony,this.uniforms.lightColorAttenuation.value=this.lightColorAttenuation,this.uniforms.indirectLightIntensity.value=this.indirectLightIntensity,this.uniforms.rimTexture.value=this.rimTexture,this.uniforms.rimColor.value.setRGB(this.rimColor.x,this.rimColor.y,this.rimColor.z),this.uniforms.rimLightingMix.value=this.rimLightingMix,this.uniforms.rimFresnelPower.value=this.rimFresnelPower,this.uniforms.rimLift.value=this.rimLift,this.uniforms.sphereAdd.value=this.sphereAdd,this.uniforms.emissionColor.value.setRGB(this.emissionColor.x,this.emissionColor.y,this.emissionColor.z),this.uniforms.emissiveMap.value=this.emissiveMap,this.uniforms.outlineWidthTexture.value=this.outlineWidthTexture,this.uniforms.outlineWidth.value=this.outlineWidth,this.uniforms.outlineScaledMaxDistance.value=this.outlineScaledMaxDistance,this.uniforms.outlineColor.value.setRGB(this.outlineColor.x,this.outlineColor.y,this.outlineColor.z),this.uniforms.outlineLightingMix.value=this.outlineLightingMix,this.uniforms.uvAnimMaskTexture.value=this.uvAnimMaskTexture,this.encoding===t.sRGBEncoding&&(this.uniforms.color.value.convertSRGBToLinear(),this.uniforms.shadeColor.value.convertSRGBToLinear(),this.uniforms.rimColor.value.convertSRGBToLinear(),this.uniforms.emissionColor.value.convertSRGBToLinear(),this.uniforms.outlineColor.value.convertSRGBToLinear()),this._updateCullFace())}_updateShaderCode(){const n=null!==this.outlineWidthTexture,i=null!==this.map||null!==this.shadeTexture||null!==this.receiveShadowTexture||null!==this.shadingGradeTexture||null!==this.rimTexture||null!==this.uvAnimMaskTexture;this.defines={THREE_VRM_THREE_REVISION_126:parseInt(t.REVISION)>=126,OUTLINE:this._isOutline,BLENDMODE_OPAQUE:this._blendMode===e.MToonMaterialRenderMode.Opaque,BLENDMODE_CUTOUT:this._blendMode===e.MToonMaterialRenderMode.Cutout,BLENDMODE_TRANSPARENT:this._blendMode===e.MToonMaterialRenderMode.Transparent||this._blendMode===e.MToonMaterialRenderMode.TransparentWithZWrite,MTOON_USE_UV:n||i,MTOON_UVS_VERTEX_ONLY:n&&!i,USE_SHADETEXTURE:null!==this.shadeTexture,USE_RECEIVESHADOWTEXTURE:null!==this.receiveShadowTexture,USE_SHADINGGRADETEXTURE:null!==this.shadingGradeTexture,USE_RIMTEXTURE:null!==this.rimTexture,USE_SPHEREADD:null!==this.sphereAdd,USE_OUTLINEWIDTHTEXTURE:null!==this.outlineWidthTexture,USE_UVANIMMASKTEXTURE:null!==this.uvAnimMaskTexture,DEBUG_NORMAL:this._debugMode===e.MToonMaterialDebugMode.Normal,DEBUG_LITSHADERATE:this._debugMode===e.MToonMaterialDebugMode.LitShadeRate,DEBUG_UV:this._debugMode===e.MToonMaterialDebugMode.UV,OUTLINE_WIDTH_WORLD:this._outlineWidthMode===e.MToonMaterialOutlineWidthMode.WorldCoordinates,OUTLINE_WIDTH_SCREEN:this._outlineWidthMode===e.MToonMaterialOutlineWidthMode.ScreenCoordinates,OUTLINE_COLOR_FIXED:this._outlineColorMode===e.MToonMaterialOutlineColorMode.FixedColor,OUTLINE_COLOR_MIXED:this._outlineColorMode===e.MToonMaterialOutlineColorMode.MixedLighting};const r=(null!==this.shadeTexture?$("shadeTextureTexelToLinear",this.shadeTexture.encoding)+"\n":"")+(null!==this.sphereAdd?$("sphereAddTexelToLinear",this.sphereAdd.encoding)+"\n":"")+(null!==this.rimTexture?$("rimTextureTexelToLinear",this.rimTexture.encoding)+"\n":"");this.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 #ifdef MTOON_UVS_VERTEX_ONLY\n vec2 vUv;\n #else\n varying vec2 vUv;\n #endif\n\n uniform vec4 mainTex_ST;\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_OUTLINEWIDTHTEXTURE\n uniform sampler2D outlineWidthTexture;\n#endif\n\nuniform float outlineWidth;\nuniform float outlineScaledMaxDistance;\n\nvoid main() {\n\n // #include <uv_vertex>\n #ifdef MTOON_USE_UV\n vUv = uv;\n vUv.y = 1.0 - vUv.y; // uv.y is opposite from UniVRM's\n vUv = mainTex_ST.st + mainTex_ST.pq * vUv;\n vUv.y = 1.0 - vUv.y; // reverting the previous flip\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_OUTLINEWIDTHTEXTURE\n outlineTex = texture2D( outlineWidthTexture, vUv ).r;\n #endif\n\n #ifdef OUTLINE_WIDTH_WORLD\n float worldNormalLength = length( transformedNormal );\n vec3 outlineOffset = 0.01 * outlineWidth * 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 *= min( gl_Position.w, outlineScaledMaxDistance );\n projectedNormal.x *= projectionMatrix[ 0 ].x / projectionMatrix[ 1 ].y;\n gl_Position.xy += 0.01 * outlineWidth * 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}",this.fragmentShader=r+'// #define PHONG\n\n#ifdef BLENDMODE_CUTOUT\n uniform float cutoff;\n#endif\n\nuniform vec3 color;\nuniform float colorAlpha;\nuniform vec3 shadeColor;\n#ifdef USE_SHADETEXTURE\n uniform sampler2D shadeTexture;\n#endif\n\nuniform float receiveShadowRate;\n#ifdef USE_RECEIVESHADOWTEXTURE\n uniform sampler2D receiveShadowTexture;\n#endif\n\nuniform float shadingGradeRate;\n#ifdef USE_SHADINGGRADETEXTURE\n uniform sampler2D shadingGradeTexture;\n#endif\n\nuniform float shadeShift;\nuniform float shadeToony;\nuniform float lightColorAttenuation;\nuniform float indirectLightIntensity;\n\n#ifdef USE_RIMTEXTURE\n uniform sampler2D rimTexture;\n#endif\nuniform vec3 rimColor;\nuniform float rimLightingMix;\nuniform float rimFresnelPower;\nuniform float rimLift;\n\n#ifdef USE_SPHEREADD\n uniform sampler2D sphereAdd;\n#endif\n\nuniform vec3 emissionColor;\n\nuniform vec3 outlineColor;\nuniform float outlineLightingMix;\n\n#ifdef USE_UVANIMMASKTEXTURE\n uniform sampler2D uvAnimMaskTexture;\n#endif\n\nuniform float uvAnimOffsetX;\nuniform float uvAnimOffsetY;\nuniform float uvAnimTheta;\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// #include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n// #include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n// #include <envmap_common_pars_fragment>\n// #include <envmap_pars_fragment>\n// #include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n\n// #include <lights_phong_pars_fragment>\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n\nstruct MToonMaterial {\n vec3 diffuseColor;\n vec3 shadeColor;\n float shadingGrade;\n float receiveShadow;\n};\n\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 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 #ifdef 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// == lighting stuff ===========================================================\nfloat getLightIntensity(\n const in IncidentLight directLight,\n const in GeometricContext geometry,\n const in float shadow,\n const in float shadingGrade\n) {\n float lightIntensity = dot( geometry.normal, directLight.direction );\n lightIntensity = 0.5 + 0.5 * lightIntensity;\n lightIntensity = lightIntensity * shadow;\n lightIntensity = lightIntensity * shadingGrade;\n lightIntensity = lightIntensity * 2.0 - 1.0;\n return shadeToony == 1.0\n ? step( shadeShift, lightIntensity )\n : smoothstep( shadeShift, shadeShift + ( 1.0 - shadeToony ), lightIntensity );\n}\n\nvec3 getLighting( const in vec3 lightColor ) {\n vec3 lighting = lightColor;\n lighting = mix(\n lighting,\n vec3( max( 0.001, max( lighting.x, max( lighting.y, lighting.z ) ) ) ),\n lightColorAttenuation\n );\n\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n lighting *= PI;\n #endif\n\n return lighting;\n}\n\nvec3 getDiffuse(\n const in MToonMaterial material,\n const in float lightIntensity,\n const in vec3 lighting\n) {\n #ifdef DEBUG_LITSHADERATE\n return vec3( BRDF_Diffuse_Lambert( lightIntensity * lighting ) );\n #endif\n\n return lighting * BRDF_Diffuse_Lambert( mix( material.shadeColor, material.diffuseColor, lightIntensity ) );\n}\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_UVANIMMASKTEXTURE\n uvAnimMask = texture2D( uvAnimMaskTexture, uv ).x;\n #endif\n\n uv = uv + vec2( uvAnimOffsetX, uvAnimOffsetY ) * uvAnimMask;\n float uvRotCos = cos( uvAnimTheta * uvAnimMask );\n float uvRotSin = sin( uvAnimTheta * 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( color, colorAlpha );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissionColor;\n\n #include <logdepthbuf_fragment>\n\n // #include <map_fragment>\n #ifdef USE_MAP\n diffuseColor *= mapTexelToLinear( texture2D( map, uv ) );\n #endif\n\n #include <color_fragment>\n // #include <alphamap_fragment>\n\n // -- MToon: alpha -----------------------------------------------------------\n // #include <alphatest_fragment>\n #ifdef BLENDMODE_CUTOUT\n if ( diffuseColor.a <= cutoff ) { discard; }\n diffuseColor.a = 1.0;\n #endif\n\n #ifdef BLENDMODE_OPAQUE\n diffuseColor.a = 1.0;\n #endif\n\n #if defined( OUTLINE ) && defined( OUTLINE_COLOR_FIXED ) // omitting DebugMode\n gl_FragColor = vec4( outlineColor, diffuseColor.a );\n postCorrection();\n return;\n #endif\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 normal = texture2D( normalMap, uv ).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 #ifdef 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 vec3 mapN = texture2D( normalMap, uv ).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 #ifdef 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 totalEmissiveRadiance *= emissiveMapTexelToLinear( texture2D( emissiveMap, uv ) ).rgb;\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 = shadeColor;\n #ifdef USE_SHADETEXTURE\n material.shadeColor *= shadeTextureTexelToLinear( texture2D( shadeTexture, uv ) ).rgb;\n #endif\n\n material.shadingGrade = 1.0;\n #ifdef USE_SHADINGGRADETEXTURE\n material.shadingGrade = 1.0 - shadingGradeRate * ( 1.0 - texture2D( shadingGradeTexture, uv ).r );\n #endif\n\n material.receiveShadow = receiveShadowRate;\n #ifdef USE_RECEIVESHADOWTEXTURE\n material.receiveShadow *= texture2D( receiveShadowTexture, uv ).a;\n #endif\n\n // #include <lights_fragment_begin>\n GeometricContext geometry;\n\n geometry.position = - vViewPosition;\n geometry.normal = normal;\n geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n\n IncidentLight directLight;\n vec3 lightingSum = vec3( 0.0 );\n\n #if ( NUM_POINT_LIGHTS > 0 )\n PointLight pointLight;\n\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 pointLight = pointLights[ i ];\n getPointDirectLightIrradiance( pointLight, geometry, directLight );\n\n float atten = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n pointLightShadow = pointLightShadows[ i ];\n atten = 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 float shadow = 1.0 - material.receiveShadow * ( 1.0 - ( 0.5 + 0.5 * atten ) );\n float lightIntensity = getLightIntensity( directLight, geometry, shadow, material.shadingGrade );\n vec3 lighting = getLighting( directLight.color );\n reflectedLight.directDiffuse += getDiffuse( material, lightIntensity, lighting );\n lightingSum += lighting;\n }\n #pragma unroll_loop_end\n #endif\n\n #if ( NUM_SPOT_LIGHTS > 0 )\n SpotLight spotLight;\n\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 spotLight = spotLights[ i ];\n getSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\n float atten = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n spotLightShadow = spotLightShadows[ i ];\n atten = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n #endif\n\n float shadow = 1.0 - material.receiveShadow * ( 1.0 - ( 0.5 + 0.5 * atten ) );\n float lightIntensity = getLightIntensity( directLight, geometry, shadow, material.shadingGrade );\n vec3 lighting = getLighting( directLight.color );\n reflectedLight.directDiffuse += getDiffuse( material, lightIntensity, lighting );\n lightingSum += lighting;\n }\n #pragma unroll_loop_end\n #endif\n\n #if ( NUM_DIR_LIGHTS > 0 )\n DirectionalLight directionalLight;\n\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 directionalLight = directionalLights[ i ];\n getDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\n float atten = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n directionalLightShadow = directionalLightShadows[ i ];\n atten = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n #endif\n\n float shadow = 1.0 - material.receiveShadow * ( 1.0 - ( 0.5 + 0.5 * atten ) );\n float lightIntensity = getLightIntensity( directLight, geometry, shadow, material.shadingGrade );\n vec3 lighting = getLighting( directLight.color );\n reflectedLight.directDiffuse += getDiffuse( material, lightIntensity, lighting );\n lightingSum += lighting;\n }\n #pragma unroll_loop_end\n #endif\n\n // #if defined( RE_IndirectDiffuse )\n vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n irradiance += getLightProbeIrradiance( lightProbe, geometry );\n #if ( NUM_HEMI_LIGHTS > 0 )\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n }\n #pragma unroll_loop_end\n #endif\n // #endif\n\n // #include <lights_fragment_maps>\n #ifdef USE_LIGHTMAP\n vec4 lightMapTexel = texture2D( lightMap, vUv2 );\n vec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n lightMapIrradiance *= PI;\n #endif\n irradiance += lightMapIrradiance;\n #endif\n\n // #include <lights_fragment_end>\n // RE_IndirectDiffuse here\n reflectedLight.indirectDiffuse += indirectLightIntensity * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n // modulation\n #include <aomap_fragment>\n\n vec3 col = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\n // The "comment out if you want to PBR absolutely" line\n #ifndef DEBUG_LITSHADERATE\n col = min(col, material.diffuseColor);\n #endif\n\n #if defined( OUTLINE ) && defined( OUTLINE_COLOR_MIXED )\n gl_FragColor = vec4(\n outlineColor.rgb * mix( vec3( 1.0 ), col, outlineLightingMix ),\n diffuseColor.a\n );\n postCorrection();\n return;\n #endif\n\n #ifdef DEBUG_LITSHADERATE\n gl_FragColor = vec4( col, diffuseColor.a );\n postCorrection();\n return;\n #endif\n\n // -- MToon: parametric rim lighting -----------------------------------------\n vec3 viewDir = normalize( vViewPosition );\n vec3 rimMix = mix( vec3( 1.0 ), lightingSum + indirectLightIntensity * irradiance, rimLightingMix );\n vec3 rim = rimColor * pow( saturate( 1.0 - dot( viewDir, normal ) + rimLift ), rimFresnelPower );\n #ifdef USE_RIMTEXTURE\n rim *= rimTextureTexelToLinear( texture2D( rimTexture, uv ) ).rgb;\n #endif\n col += rim;\n\n // -- MToon: additive matcap -------------------------------------------------\n #ifdef USE_SPHEREADD\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 vec3 matcap = sphereAddTexelToLinear( texture2D( sphereAdd, sphereUv ) ).xyz;\n col += matcap;\n }\n #endif\n\n // -- MToon: Emission --------------------------------------------------------\n col += totalEmissiveRadiance;\n\n // #include <envmap_fragment>\n\n // -- Almost done! -----------------------------------------------------------\n gl_FragColor = vec4( col, diffuseColor.a );\n postCorrection();\n}',this.needsUpdate=!0}_updateCullFace(){this.isOutline?this.outlineCullMode===e.MToonMaterialCullMode.Off?this.side=t.DoubleSide:this.outlineCullMode===e.MToonMaterialCullMode.Front?this.side=t.BackSide:this.outlineCullMode===e.MToonMaterialCullMode.Back&&(this.side=t.FrontSide):this.cullMode===e.MToonMaterialCullMode.Off?this.side=t.DoubleSide:this.cullMode===e.MToonMaterialCullMode.Front?this.side=t.BackSide:this.cullMode===e.MToonMaterialCullMode.Back&&(this.side=t.FrontSide)}}var oe;(oe=e.VRMUnlitMaterialRenderType||(e.VRMUnlitMaterialRenderType={}))[oe.Opaque=0]="Opaque",oe[oe.Cutout=1]="Cutout",oe[oe.Transparent=2]="Transparent",oe[oe.TransparentWithZWrite=3]="TransparentWithZWrite";class ae extends t.ShaderMaterial{constructor(n){super(),this.isVRMUnlitMaterial=!0,this.cutoff=.5,this.map=null,this.mainTex_ST=new t.Vector4(0,0,1,1),this._renderType=e.VRMUnlitMaterialRenderType.Opaque,this.shouldApplyUniforms=!0,void 0===n&&(n={}),n.fog=!0,n.clipping=!0,n.skinning=n.skinning||!1,n.morphTargets=n.morphTargets||!1,n.morphNormals=n.morphNormals||!1,n.uniforms=t.UniformsUtils.merge([t.UniformsLib.common,t.UniformsLib.fog,{cutoff:{value:.5},mainTex_ST:{value:new t.Vector4(0,0,1,1)}}]),this.setValues(n),this._updateShaderCode(),this._applyUniforms()}get mainTex(){return this.map}set mainTex(e){this.map=e}get renderType(){return this._renderType}set renderType(t){this._renderType=t,this.depthWrite=this._renderType!==e.VRMUnlitMaterialRenderType.Transparent,this.transparent=this._renderType===e.VRMUnlitMaterialRenderType.Transparent||this._renderType===e.VRMUnlitMaterialRenderType.TransparentWithZWrite,this._updateShaderCode()}updateVRMMaterials(e){this._applyUniforms()}copy(e){return super.copy(e),this.cutoff=e.cutoff,this.map=e.map,this.mainTex_ST.copy(e.mainTex_ST),this.renderType=e.renderType,this}_applyUniforms(){this.shouldApplyUniforms&&(this.shouldApplyUniforms=!1,this.uniforms.cutoff.value=this.cutoff,this.uniforms.map.value=this.map,this.uniforms.mainTex_ST.value.copy(this.mainTex_ST))}_updateShaderCode(){this.defines={RENDERTYPE_OPAQUE:this._renderType===e.VRMUnlitMaterialRenderType.Opaque,RENDERTYPE_CUTOUT:this._renderType===e.VRMUnlitMaterialRenderType.Cutout,RENDERTYPE_TRANSPARENT:this._renderType===e.VRMUnlitMaterialRenderType.Transparent||this._renderType===e.VRMUnlitMaterialRenderType.TransparentWithZWrite},this.vertexShader="#include <common>\n\n// #include <uv_pars_vertex>\n#ifdef USE_MAP\n varying vec2 vUv;\n uniform vec4 mainTex_ST;\n#endif\n\n#include <uv2_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 <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n // #include <uv_vertex>\n #ifdef USE_MAP\n vUv = vec2( mainTex_ST.p * uv.x + mainTex_ST.s, mainTex_ST.q * uv.y + mainTex_ST.t );\n #endif\n\n #include <uv2_vertex>\n #include <color_vertex>\n #include <skinbase_vertex>\n\n #ifdef USE_ENVMAP\n\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinnormal_vertex>\n #include <defaultnormal_vertex>\n\n #endif\n\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n\n #include <worldpos_vertex>\n #include <clipping_planes_vertex>\n #include <envmap_vertex>\n #include <fog_vertex>\n\n}",this.fragmentShader="#ifdef RENDERTYPE_CUTOUT\n uniform float cutoff;\n#endif\n\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n// #include <alphamap_pars_fragment>\n// #include <aomap_pars_fragment>\n// #include <lightmap_pars_fragment>\n// #include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n// #include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\n// == main procedure ===========================================================\nvoid main() {\n #include <clipping_planes_fragment>\n\n vec4 diffuseColor = vec4( 1.0 );\n\n #include <logdepthbuf_fragment>\n\n // #include <map_fragment>\n #ifdef USE_MAP\n diffuseColor *= mapTexelToLinear( texture2D( map, vUv ) );\n #endif\n\n #include <color_fragment>\n // #include <alphamap_fragment>\n\n // MToon: alpha\n // #include <alphatest_fragment>\n #ifdef RENDERTYPE_CUTOUT\n if ( diffuseColor.a <= cutoff ) { discard; }\n diffuseColor.a = 1.0;\n #endif\n\n #ifdef RENDERTYPE_OPAQUE\n diffuseColor.a = 1.0;\n #endif\n\n // #include <specularmap_fragment>\n\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\n // accumulation (baked indirect lighting only)\n #ifdef USE_LIGHTMAP\n reflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n #else\n reflectedLight.indirectDiffuse += vec3( 1.0 );\n #endif\n\n // modulation\n // #include <aomap_fragment>\n\n reflectedLight.indirectDiffuse *= diffuseColor.rgb;\n vec3 outgoingLight = reflectedLight.indirectDiffuse;\n\n // #include <envmap_fragment>\n\n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n #include <premultiplied_alpha_fragment>\n #include <tonemapping_fragment>\n #include <encodings_fragment>\n #include <fog_fragment>\n}",this.needsUpdate=!0}}class se{constructor(e={}){this._encoding=e.encoding||t.LinearEncoding,this._encoding!==t.LinearEncoding&&this._encoding!==t.sRGBEncoding&&console.warn("The specified color encoding might not work properly with VRMMaterialImporter. You might want to use THREE.sRGBEncoding instead."),this._requestEnvMap=e.requestEnvMap}convertGLTFMaterials(e){var t;return n(this,void 0,void 0,(function*(){const i=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!i)return null;const r=i.materialProperties;if(!r)return null;const o=yield M(e),a={},s=[];return yield Promise.all(Array.from(o.entries()).map((([t,i])=>n(this,void 0,void 0,(function*(){const o=e.parser.json.nodes[t],l=e.parser.json.meshes[o.mesh];yield Promise.all(i.map(((t,i)=>n(this,void 0,void 0,(function*(){const n=l.primitives[i];if(!n)return;const o=t.geometry,d=o.index?o.index.count:o.attributes.position.count/3;Array.isArray(t.material)||(t.material=[t.material],o.addGroup(0,d,0));const h=n.material;let u,c=r[h];c||(console.warn(`VRMMaterialImporter: There are no material definition for material #${h} on VRM extension.`),c={shader:"VRM_USE_GLTFSHADER"}),a[h]?u=a[h]:(u=yield this.createVRMMaterials(t.material[0],c,e),a[h]=u,s.push(u.surface),u.outline&&s.push(u.outline)),t.material[0]=u.surface,this._requestEnvMap&&u.surface.isMeshStandardMaterial&&this._requestEnvMap().then((e=>{u.surface.envMap=e,u.surface.needsUpdate=!0})),t.renderOrder=c.renderQueue||2e3,u.outline&&(t.material[1]=u.outline,o.addGroup(0,d,1))})))))}))))),s}))}createVRMMaterials(t,i,r){return n(this,void 0,void 0,(function*(){let n,o;if("VRM/MToon"===i.shader){const a=yield this._extractMaterialProperties(t,i,r);["srcBlend","dstBlend","isFirstSetup"].forEach((e=>{void 0!==a[e]&&delete a[e]})),["mainTex","shadeTexture","emissionMap","sphereAdd","rimTexture"].forEach((e=>{void 0!==a[e]&&(a[e].encoding=this._encoding)})),a.encoding=this._encoding,n=new re(a),a.outlineWidthMode!==e.MToonMaterialOutlineWidthMode.None&&(a.isOutline=!0,o=new re(a))}else if("VRM/UnlitTexture"===i.shader){const o=yield this._extractMaterialProperties(t,i,r);o.renderType=e.VRMUnlitMaterialRenderType.Opaque,n=new ae(o)}else if("VRM/UnlitCutout"===i.shader){const o=yield this._extractMaterialProperties(t,i,r);o.renderType=e.VRMUnlitMaterialRenderType.Cutout,n=new ae(o)}else if("VRM/UnlitTransparent"===i.shader){const o=yield this._extractMaterialProperties(t,i,r);o.renderType=e.VRMUnlitMaterialRenderType.Transparent,n=new ae(o)}else if("VRM/UnlitTransparentZWrite"===i.shader){const o=yield this._extractMaterialProperties(t,i,r);o.renderType=e.VRMUnlitMaterialRenderType.TransparentWithZWrite,n=new ae(o)}else"VRM_USE_GLTFSHADER"!==i.shader&&console.warn(`Unknown shader detected: "${i.shader}"`),n=this._convertGLTFMaterial(t.clone());return n.name=t.name,n.userData=JSON.parse(JSON.stringify(t.userData)),n.userData.vrmMaterialProperties=i,o&&(o.name=t.name+" (Outline)",o.userData=JSON.parse(JSON.stringify(t.userData)),o.userData.vrmMaterialProperties=i),{surface:n,outline:o}}))}_renameMaterialProperty(e){return"_"!==e[0]?(console.warn(`VRMMaterials: Given property name "${e}" might be invalid`),e):(e=e.substring(1),/[A-Z]/.test(e[0])?e[0].toLowerCase()+e.substring(1):(console.warn(`VRMMaterials: Given property name "${e}" might be invalid`),e))}_convertGLTFMaterial(e){if(e.isMeshStandardMaterial){const n=e;n.map&&(n.map.encoding=this._encoding),n.emissiveMap&&(n.emissiveMap.encoding=this._encoding),this._encoding===t.LinearEncoding&&(n.color.convertLinearToSRGB(),n.emissive.convertLinearToSRGB())}if(e.isMeshBasicMaterial){const n=e;n.map&&(n.map.encoding=this._encoding),this._encoding===t.LinearEncoding&&n.color.convertLinearToSRGB()}return e}_extractMaterialProperties(e,n,i){const r=[],o={};if(n.textureProperties)for(const e of Object.keys(n.textureProperties)){const t=this._renameMaterialProperty(e),a=n.textureProperties[e];r.push(i.parser.getDependency("texture",a).then((e=>{o[t]=e})))}if(n.floatProperties)for(const e of Object.keys(n.floatProperties)){const t=this._renameMaterialProperty(e);o[t]=n.floatProperties[e]}if(n.vectorProperties)for(const e of Object.keys(n.vectorProperties)){let i=this._renameMaterialProperty(e);["_MainTex","_ShadeTexture","_BumpMap","_ReceiveShadowTexture","_ShadingGradeTexture","_RimTexture","_SphereAdd","_EmissionMap","_OutlineWidthTexture","_UvAnimMaskTexture"].some((t=>e===t))&&(i+="_ST"),o[i]=new t.Vector4(...n.vectorProperties[e])}return o.skinning=e.skinning||!1,o.morphTargets=e.morphTargets||!1,o.morphNormals=e.morphNormals||!1,Promise.all(r).then((()=>o))}}class le{constructor(e){var t;this.ignoreTexture=null!==(t=null==e?void 0:e.ignoreTexture)&&void 0!==t&&t}import(e){var t;return n(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.meta;if(!i)return null;let r;return this.ignoreTexture||null==i.texture||-1===i.texture||(r=yield e.parser.getDependency("texture",i.texture)),{allowedUserName:i.allowedUserName,author:i.author,commercialUssageName:i.commercialUssageName,contactInformation:i.contactInformation,licenseName:i.licenseName,otherLicenseUrl:i.otherLicenseUrl,otherPermissionUrl:i.otherPermissionUrl,reference:i.reference,sexualUssageName:i.sexualUssageName,texture:null!=r?r:void 0,title:i.title,version:i.version,violentUssageName:i.violentUssageName}}))}}const de=new t.Matrix4;function he(e){return e.invert?e.invert():e.getInverse(de.copy(e)),e}class ue{constructor(e){this._inverseCache=new t.Matrix4,this._shouldUpdateInverse=!0,this.matrix=e;const n={set:(e,t,n)=>(this._shouldUpdateInverse=!0,e[t]=n,!0)};this._originalElements=e.elements,e.elements=new Proxy(e.elements,n)}get inverse(){return this._shouldUpdateInverse&&(he(this._inverseCache.copy(this.matrix)),this._shouldUpdateInverse=!1),this._inverseCache}revert(){this.matrix.elements=this._originalElements}}const ce=Object.freeze(new t.Matrix4),pe=Object.freeze(new t.Quaternion),me=new t.Vector3,fe=new t.Vector3,ge=new t.Vector3,_e=new t.Quaternion,ve=new t.Matrix4,Me=new t.Matrix4;class Te{constructor(e,n={}){var i,r,o,a,s,l;if(this._currentTail=new t.Vector3,this._prevTail=new t.Vector3,this._nextTail=new t.Vector3,this._boneAxis=new t.Vector3,this._centerSpacePosition=new t.Vector3,this._center=null,this._parentWorldRotation=new t.Quaternion,this._initialLocalMatrix=new t.Matrix4,this._initialLocalRotation=new t.Quaternion,this._initialLocalChildPosition=new t.Vector3,this.bone=e,this.bone.matrixAutoUpdate=!1,this.radius=null!==(i=n.radius)&&void 0!==i?i:.02,this.stiffnessForce=null!==(r=n.stiffnessForce)&&void 0!==r?r:1,this.gravityDir=n.gravityDir?(new t.Vector3).copy(n.gravityDir):(new t.Vector3).set(0,-1,0),this.gravityPower=null!==(o=n.gravityPower)&&void 0!==o?o:0,this.dragForce=null!==(a=n.dragForce)&&void 0!==a?a:.4,this.colliders=null!==(s=n.colliders)&&void 0!==s?s:[],this._centerSpacePosition.setFromMatrixPosition(this.bone.matrixWorld),this._initialLocalMatrix.copy(this.bone.matrix),this._initialLocalRotation.copy(this.bone.quaternion),0===this.bone.children.length)this._initialLocalChildPosition.copy(this.bone.position).normalize().multiplyScalar(.07);else{const e=this.bone.children[0];this._initialLocalChildPosition.copy(e.position)}this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)),this._prevTail.copy(this._currentTail),this._nextTail.copy(this._currentTail),this._boneAxis.copy(this._initialLocalChildPosition).normalize(),this._centerSpaceBoneLength=me.copy(this._initialLocalChildPosition).applyMatrix4(this.bone.matrixWorld).sub(this._centerSpacePosition).length(),this.center=null!==(l=n.center)&&void 0!==l?l:null}get center(){return this._center}set center(e){var t;this._getMatrixCenterToWorld(ve),this._currentTail.applyMatrix4(ve),this._prevTail.applyMatrix4(ve),this._nextTail.applyMatrix4(ve),(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 ue(this._center.matrixWorld))),this._getMatrixWorldToCenter(ve),this._currentTail.applyMatrix4(ve),this._prevTail.applyMatrix4(ve),this._nextTail.applyMatrix4(ve),ve.multiply(this.bone.matrixWorld),this._centerSpacePosition.setFromMatrixPosition(ve),this._centerSpaceBoneLength=me.copy(this._initialLocalChildPosition).applyMatrix4(ve).sub(this._centerSpacePosition).length()}reset(){this.bone.quaternion.copy(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._getParentMatrixWorld(),this.bone.matrix),this._centerSpacePosition.setFromMatrixPosition(this.bone.matrixWorld),this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)),this._prevTail.copy(this._currentTail),this._nextTail.copy(this._currentTail)}update(e){if(e<=0)return;this.bone.matrixWorld.multiplyMatrices(this._getParentMatrixWorld(),this.bone.matrix),this.bone.parent?S(this.bone.parent,this._parentWorldRotation):this._parentWorldRotation.copy(pe),this._getMatrixWorldToCenter(ve),ve.multiply(this.bone.matrixWorld),this._centerSpacePosition.setFromMatrixPosition(ve),this._getMatrixWorldToCenter(Me),Me.multiply(this._getParentMatrixWorld());const t=this.stiffnessForce*e,n=fe.copy(this.gravityDir).multiplyScalar(this.gravityPower*e);this._nextTail.copy(this._currentTail).add(me.copy(this._currentTail).sub(this._prevTail).multiplyScalar(1-this.dragForce)).add(me.copy(this._boneAxis).applyMatrix4(this._initialLocalMatrix).applyMatrix4(Me).sub(this._centerSpacePosition).normalize().multiplyScalar(t)).add(n),this._nextTail.sub(this._centerSpacePosition).normalize().multiplyScalar(this._centerSpaceBoneLength).add(this._centerSpacePosition),this._collision(this._nextTail),this._prevTail.copy(this._currentTail),this._currentTail.copy(this._nextTail);const i=he(ve.copy(Me.multiply(this._initialLocalMatrix))),r=_e.setFromUnitVectors(this._boneAxis,me.copy(this._nextTail).applyMatrix4(i).normalize());this.bone.quaternion.copy(this._initialLocalRotation).multiply(r),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._getParentMatrixWorld(),this.bone.matrix)}_collision(e){this.colliders.forEach((t=>{this._getMatrixWorldToCenter(ve),ve.multiply(t.matrixWorld);const n=me.setFromMatrixPosition(ve),i=t.geometry.boundingSphere.radius,r=this.radius+i;if(e.distanceToSquared(n)<=r*r){const t=fe.subVectors(e,n).normalize(),i=ge.addVectors(n,t.multiplyScalar(r));e.copy(i.sub(this._centerSpacePosition).normalize().multiplyScalar(this._centerSpaceBoneLength).add(this._centerSpacePosition))}}))}_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}_getParentMatrixWorld(){return this.bone.parent?this.bone.parent.matrixWorld:ce}}class ye{constructor(e,t){this.colliderGroups=[],this.springBoneGroupList=[],this.colliderGroups=e,this.springBoneGroupList=t}setCenter(e){this.springBoneGroupList.forEach((t=>{t.forEach((t=>{t.center=e}))}))}lateUpdate(e){this.springBoneGroupList.forEach((t=>{t.forEach((t=>{t.update(e)}))}))}reset(){this.springBoneGroupList.forEach((e=>{e.forEach((e=>{e.reset()}))}))}}const xe=new t.Vector3,Se=new t.MeshBasicMaterial({visible:!1});class Re{import(e){var t;return n(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.secondaryAnimation;if(!i)return null;const r=yield this._importColliderMeshGroups(e,i),o=yield this._importSpringBoneGroupList(e,i,r);return new ye(r,o)}))}_createSpringBone(e,t={}){return new Te(e,t)}_importSpringBoneGroupList(e,i,r){return n(this,void 0,void 0,(function*(){const o=i.boneGroups||[],a=[];return yield Promise.all(o.map((i=>n(this,void 0,void 0,(function*(){if(void 0===i.stiffiness||void 0===i.gravityDir||void 0===i.gravityDir.x||void 0===i.gravityDir.y||void 0===i.gravityDir.z||void 0===i.gravityPower||void 0===i.dragForce||void 0===i.hitRadius||void 0===i.colliderGroups||void 0===i.bones||void 0===i.center)return;const o=i.stiffiness,s=new t.Vector3(i.gravityDir.x,i.gravityDir.y,-i.gravityDir.z),l=i.gravityPower,d=i.dragForce,h=i.hitRadius,u=[];i.colliderGroups.forEach((e=>{u.push(...r[e].colliders)}));const c=[];yield Promise.all(i.bones.map((t=>n(this,void 0,void 0,(function*(){const n=yield e.parser.getDependency("node",t),r=-1!==i.center?yield e.parser.getDependency("node",i.center):null;n&&n.traverse((e=>{const t=this._createSpringBone(e,{radius:h,stiffnessForce:o,gravityDir:s,gravityPower:l,dragForce:d,colliders:u,center:r});c.push(t)}))}))))),a.push(c)}))))),a}))}_importColliderMeshGroups(e,t){return n(this,void 0,void 0,(function*(){const i=t.colliderGroups;if(void 0===i)return[];const r=[];return i.forEach((t=>n(this,void 0,void 0,(function*(){if(void 0===t.node||void 0===t.colliders)return;const n=yield e.parser.getDependency("node",t.node),i=[];t.colliders.forEach((e=>{if(void 0===e.offset||void 0===e.offset.x||void 0===e.offset.y||void 0===e.offset.z||void 0===e.radius)return;const t=xe.set(e.offset.x,e.offset.y,-e.offset.z),r=this._createColliderMesh(e.radius,t);n.add(r),i.push(r)}));const o={node:t.node,colliders:i};r.push(o)})))),r}))}_createColliderMesh(e,n){const i=new t.Mesh(new t.SphereBufferGeometry(e,8,4),Se);return i.position.copy(n),i.name="vrmColliderSphere",i.geometry.computeBoundingSphere(),i}}class Le{constructor(e={}){this._metaImporter=e.metaImporter||new le,this._blendShapeImporter=e.blendShapeImporter||new L,this._lookAtImporter=e.lookAtImporter||new Z,this._humanoidImporter=e.humanoidImporter||new I,this._firstPersonImporter=e.firstPersonImporter||new O,this._materialImporter=e.materialImporter||new se,this._springBoneImporter=e.springBoneImporter||new Re}import(e){return n(this,void 0,void 0,(function*(){if(void 0===e.parser.json.extensions||void 0===e.parser.json.extensions.VRM)throw new Error("Could not find VRM extension on the GLTF");const t=e.scene;t.updateMatrixWorld(!1),t.traverse((e=>{e.isMesh&&(e.frustumCulled=!1)}));const n=(yield this._metaImporter.import(e))||void 0,i=(yield this._materialImporter.convertGLTFMaterials(e))||void 0,r=(yield this._humanoidImporter.import(e))||void 0,o=r&&(yield this._firstPersonImporter.import(e,r))||void 0,a=(yield this._blendShapeImporter.import(e))||void 0,s=o&&a&&r&&(yield this._lookAtImporter.import(e,o,a,r))||void 0,l=(yield this._springBoneImporter.import(e))||void 0;return new Ee({scene:e.scene,meta:n,materials:i,humanoid:r,firstPerson:o,blendShapeProxy:a,lookAt:s,springBoneManager:l})}))}}class Ee{constructor(e){this.scene=e.scene,this.humanoid=e.humanoid,this.blendShapeProxy=e.blendShapeProxy,this.firstPerson=e.firstPerson,this.lookAt=e.lookAt,this.materials=e.materials,this.springBoneManager=e.springBoneManager,this.meta=e.meta}static from(e,t={}){return n(this,void 0,void 0,(function*(){const n=new Le(t);return yield n.import(e)}))}update(e){this.lookAt&&this.lookAt.update(e),this.blendShapeProxy&&this.blendShapeProxy.update(),this.springBoneManager&&this.springBoneManager.lateUpdate(e),this.materials&&this.materials.forEach((t=>{t.updateVRMMaterials&&t.updateVRMMaterials(e)}))}dispose(){var e,t;const n=this.scene;n&&n.traverse(r),null===(t=null===(e=this.meta)||void 0===e?void 0:e.texture)||void 0===t||t.dispose()}}const we=new t.Vector2,Pe=new t.OrthographicCamera(-1,1,-1,1,-1,1),Ae=new t.MeshBasicMaterial({color:16777215,side:t.DoubleSide}),Ce=new t.Mesh(new t.PlaneBufferGeometry(2,2),Ae),Oe=new t.Scene;Oe.add(Ce);class be{constructor(){}}be.extractThumbnailBlob=function(e,t,n=512){var i;const r=null===(i=t.meta)||void 0===i?void 0:i.texture;if(!r)throw new Error("extractThumbnailBlob: This VRM does not have a thumbnail");const o=e.getContext().canvas;e.getSize(we);const a=we.x,s=we.y;return e.setSize(n,n,!1),Ae.map=r,e.render(Oe,Pe),Ae.map=null,o instanceof OffscreenCanvas?o.convertToBlob().finally((()=>{e.setSize(a,s,!1)})):new Promise(((t,n)=>{o.toBlob((i=>{e.setSize(a,s,!1),null==i?n("extractThumbnailBlob: Failed to create a blob"):t(i)}))}))},be.removeUnnecessaryJoints=function(e){const n=new Map;e.traverse((e=>{if("SkinnedMesh"!==e.type)return;const i=e,r=i.geometry.getAttribute("skinIndex");let o=n.get(r);if(!o){const e=[],a=[],s={},l=r.array;for(let t=0;t<l.length;t++){const n=l[t];void 0===s[n]&&(s[n]=e.length,e.push(i.skeleton.bones[n]),a.push(i.skeleton.boneInverses[n])),l[t]=s[n]}r.copyArray(l),r.needsUpdate=!0,o=new t.Skeleton(e,a),n.set(r,o)}i.bind(o,new t.Matrix4)}))};const De=new t.Vector3;class Ne extends Y{setupHelper(e,n){n.disableFaceDirectionHelper||(this._faceDirectionHelper=new t.ArrowHelper(new t.Vector3(0,0,-1),new t.Vector3(0,0,0),.5,16711935),e.add(this._faceDirectionHelper))}update(e){super.update(e),this._faceDirectionHelper&&(this.firstPerson.getFirstPersonWorldPosition(this._faceDirectionHelper.position),this._faceDirectionHelper.setDirection(this.getLookAtWorldDirection(De)))}}class Ve extends Z{import(e,t,n,i){var r;const o=null===(r=e.parser.json.extensions)||void 0===r?void 0:r.VRM;if(!o)return null;const a=o.firstPerson;if(!a)return null;const s=this._importApplyer(a,n,i);return new Ne(t,s||void 0)}}const Ue=new t.MeshBasicMaterial({color:16711935,wireframe:!0,transparent:!0,depthTest:!1});class Ie extends ye{setupHelper(e,t){t.disableSpringBoneHelper||(this.springBoneGroupList.forEach((t=>{t.forEach((t=>{if(t.getGizmo){const n=t.getGizmo();e.add(n)}}))})),this.colliderGroups.forEach((e=>{e.colliders.forEach((e=>{e.material=Ue,e.renderOrder=We}))})))}}const Be=new t.Vector3;class Ge extends Te{constructor(e,t){super(e,t)}getGizmo(){if(this._gizmo)return this._gizmo;const e=Be.copy(this._nextTail).sub(this._centerSpacePosition),n=e.length();return this._gizmo=new t.ArrowHelper(e.normalize(),this._centerSpacePosition,n,16776960,this.radius,this.radius),this._gizmo.line.renderOrder=We,this._gizmo.cone.renderOrder=We,this._gizmo.line.material.depthTest=!1,this._gizmo.line.material.transparent=!0,this._gizmo.cone.material.depthTest=!1,this._gizmo.cone.material.transparent=!0,this._gizmo}update(e){super.update(e),this._updateGizmo()}_updateGizmo(){if(!this._gizmo)return;const e=Be.copy(this._currentTail).sub(this._centerSpacePosition),t=e.length();this._gizmo.setDirection(e.normalize()),this._gizmo.setLength(t,this.radius,this.radius),this._gizmo.position.copy(this._centerSpacePosition)}}class Fe extends Re{import(e){var t;return n(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.secondaryAnimation;if(!i)return null;const r=yield this._importColliderMeshGroups(e,i),o=yield this._importSpringBoneGroupList(e,i,r);return new Ie(r,o)}))}_createSpringBone(e,t){return new Ge(e,t)}}class ke extends Le{constructor(e={}){e.lookAtImporter=e.lookAtImporter||new Ve,e.springBoneImporter=e.springBoneImporter||new Fe,super(e)}import(e,t={}){return n(this,void 0,void 0,(function*(){if(void 0===e.parser.json.extensions||void 0===e.parser.json.extensions.VRM)throw new Error("Could not find VRM extension on the GLTF");const n=e.scene;n.updateMatrixWorld(!1),n.traverse((e=>{e.isMesh&&(e.frustumCulled=!1)}));const i=(yield this._metaImporter.import(e))||void 0,r=(yield this._materialImporter.convertGLTFMaterials(e))||void 0,o=(yield this._humanoidImporter.import(e))||void 0,a=o&&(yield this._firstPersonImporter.import(e,o))||void 0,s=(yield this._blendShapeImporter.import(e))||void 0,l=a&&s&&o&&(yield this._lookAtImporter.import(e,a,s,o))||void 0;l.setupHelper&&l.setupHelper(n,t);const d=(yield this._springBoneImporter.import(e))||void 0;return d.setupHelper&&d.setupHelper(n,t),new He({scene:e.scene,meta:i,materials:r,humanoid:o,firstPerson:a,blendShapeProxy:s,lookAt:l,springBoneManager:d},t)}))}}const We=1e4;class He extends Ee{static from(e,t={},i={}){return n(this,void 0,void 0,(function*(){const n=new ke(t);return yield n.import(e,i)}))}constructor(e,n={}){super(e),n.disableBoxHelper||this.scene.add(new t.BoxHelper(this.scene)),n.disableSkeletonHelper||this.scene.add(new t.SkeletonHelper(this.scene))}update(e){super.update(e)}}e.MToonMaterial=re,e.VRM=Ee,e.VRMBlendShapeGroup=h,e.VRMBlendShapeImporter=L,e.VRMBlendShapeProxy=R,e.VRMCurveMapper=B,e.VRMDebug=He,e.VRMFirstPerson=C,e.VRMFirstPersonImporter=O,e.VRMHumanBone=b,e.VRMHumanoid=U,e.VRMHumanoidImporter=I,e.VRMImporter=Le,e.VRMLookAtApplyer=G,e.VRMLookAtBlendShapeApplyer=F,e.VRMLookAtBoneApplyer=q,e.VRMLookAtHead=Y,e.VRMLookAtImporter=Z,e.VRMMaterialImporter=se,e.VRMMetaImporter=le,e.VRMRendererFirstPersonFlags=A,e.VRMSpringBone=Te,e.VRMSpringBoneDebug=Ge,e.VRMSpringBoneImporter=Re,e.VRMSpringBoneImporterDebug=Fe,e.VRMSpringBoneManager=ye,e.VRMUnlitMaterial=ae,e.VRMUtils=be,e.VRM_GIZMO_RENDER_ORDER=We,Object.defineProperty(e,"__esModule",{value:!0}),Object.assign(t,e)}));
|
|
16
|
+
***************************************************************************** */function o(e,t,n,i){return new(n||(n=Promise))((function(r,o){function a(e){try{l(i.next(e))}catch(e){o(e)}}function s(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}l((i=i.apply(e,t||[])).next())}))}function a(e){Object.keys(e).forEach((t=>{const n=e[t];if(null==n?void 0:n.isTexture){n.dispose()}})),e.dispose()}function s(e){const t=e.geometry;t&&t.dispose();const n=e.material;n&&(Array.isArray(n)?n.forEach((e=>a(e))):n&&a(n))}!function(e){e[e.NUMBER=0]="NUMBER",e[e.VECTOR2=1]="VECTOR2",e[e.VECTOR3=2]="VECTOR3",e[e.VECTOR4=3]="VECTOR4",e[e.COLOR=4]="COLOR"}(i||(i={}));const l=new r.Vector2,d=new r.Vector3,h=new r.Vector4,u=new r.Color;class c extends r.Object3D{constructor(e){super(),this.weight=0,this.isBinary=!1,this._binds=[],this._materialValues=[],this.name=`BlendShapeController_${e}`,this.type="BlendShapeController",this.visible=!1}addBind(e){const t=e.weight/100;this._binds.push({meshes:e.meshes,morphTargetIndex:e.morphTargetIndex,weight:t})}addMaterialValue(e){const t=e.material,n=e.propertyName;let o,a,s,l,d=t[n];d&&(d=e.defaultValue||d,d.isVector2?(o=i.VECTOR2,a=d.clone(),s=(new r.Vector2).fromArray(e.targetValue),l=s.clone().sub(a)):d.isVector3?(o=i.VECTOR3,a=d.clone(),s=(new r.Vector3).fromArray(e.targetValue),l=s.clone().sub(a)):d.isVector4?(o=i.VECTOR4,a=d.clone(),s=(new r.Vector4).fromArray([e.targetValue[2],e.targetValue[3],e.targetValue[0],e.targetValue[1]]),l=s.clone().sub(a)):d.isColor?(o=i.COLOR,a=d.clone(),s=(new r.Color).fromArray(e.targetValue),l=s.clone().sub(a)):(o=i.NUMBER,a=d,s=e.targetValue[0],l=s-a),this._materialValues.push({material:t,propertyName:n,defaultValue:a,targetValue:s,deltaValue:l,type:o}))}applyWeight(){const e=this.isBinary?this.weight<.5?0:1:this.weight;this._binds.forEach((t=>{t.meshes.forEach((n=>{n.morphTargetInfluences&&(n.morphTargetInfluences[t.morphTargetIndex]+=e*t.weight)}))})),this._materialValues.forEach((t=>{if(void 0!==t.material[t.propertyName]){if(t.type===i.NUMBER){const n=t.deltaValue;t.material[t.propertyName]+=n*e}else if(t.type===i.VECTOR2){const n=t.deltaValue;t.material[t.propertyName].add(l.copy(n).multiplyScalar(e))}else if(t.type===i.VECTOR3){const n=t.deltaValue;t.material[t.propertyName].add(d.copy(n).multiplyScalar(e))}else if(t.type===i.VECTOR4){const n=t.deltaValue;t.material[t.propertyName].add(h.copy(n).multiplyScalar(e))}else if(t.type===i.COLOR){const n=t.deltaValue;t.material[t.propertyName].add(u.copy(n).multiplyScalar(e))}"boolean"==typeof t.material.shouldApplyUniforms&&(t.material.shouldApplyUniforms=!0)}}))}clearAppliedWeight(){this._binds.forEach((e=>{e.meshes.forEach((t=>{t.morphTargetInfluences&&(t.morphTargetInfluences[e.morphTargetIndex]=0)}))})),this._materialValues.forEach((e=>{if(void 0!==e.material[e.propertyName]){if(e.type===i.NUMBER){const t=e.defaultValue;e.material[e.propertyName]=t}else if(e.type===i.VECTOR2){const t=e.defaultValue;e.material[e.propertyName].copy(t)}else if(e.type===i.VECTOR3){const t=e.defaultValue;e.material[e.propertyName].copy(t)}else if(e.type===i.VECTOR4){const t=e.defaultValue;e.material[e.propertyName].copy(t)}else if(e.type===i.COLOR){const t=e.defaultValue;e.material[e.propertyName].copy(t)}"boolean"==typeof e.material.shouldApplyUniforms&&(e.material.shouldApplyUniforms=!0)}}))}}var p,m,f,g,_,v,M;function T(e,t,n){const i=e.parser.json.nodes[t].mesh;if(null==i)return null;const r=e.parser.json.meshes[i].primitives.length,o=[];return n.traverse((e=>{o.length<r&&e.isMesh&&o.push(e)})),o}function y(e){return o(this,void 0,void 0,(function*(){const t=yield e.parser.getDependencies("node"),n=new Map;return t.forEach(((t,i)=>{const r=T(e,i,t);null!=r&&n.set(i,r)})),n}))}function x(e){return"_"!==e[0]?(console.warn(`renameMaterialProperty: Given property name "${e}" might be invalid`),e):(e=e.substring(1),/[A-Z]/.test(e[0])?e[0].toLowerCase()+e.substring(1):(console.warn(`renameMaterialProperty: Given property name "${e}" might be invalid`),e))}e.VRMSchema=void 0,p=e.VRMSchema||(e.VRMSchema={}),(m=p.BlendShapePresetName||(p.BlendShapePresetName={})).A="a",m.Angry="angry",m.Blink="blink",m.BlinkL="blink_l",m.BlinkR="blink_r",m.E="e",m.Fun="fun",m.I="i",m.Joy="joy",m.Lookdown="lookdown",m.Lookleft="lookleft",m.Lookright="lookright",m.Lookup="lookup",m.Neutral="neutral",m.O="o",m.Sorrow="sorrow",m.U="u",m.Unknown="unknown",(f=p.FirstPersonLookAtTypeName||(p.FirstPersonLookAtTypeName={})).BlendShape="BlendShape",f.Bone="Bone",(g=p.HumanoidBoneName||(p.HumanoidBoneName={})).Chest="chest",g.Head="head",g.Hips="hips",g.Jaw="jaw",g.LeftEye="leftEye",g.LeftFoot="leftFoot",g.LeftHand="leftHand",g.LeftIndexDistal="leftIndexDistal",g.LeftIndexIntermediate="leftIndexIntermediate",g.LeftIndexProximal="leftIndexProximal",g.LeftLittleDistal="leftLittleDistal",g.LeftLittleIntermediate="leftLittleIntermediate",g.LeftLittleProximal="leftLittleProximal",g.LeftLowerArm="leftLowerArm",g.LeftLowerLeg="leftLowerLeg",g.LeftMiddleDistal="leftMiddleDistal",g.LeftMiddleIntermediate="leftMiddleIntermediate",g.LeftMiddleProximal="leftMiddleProximal",g.LeftRingDistal="leftRingDistal",g.LeftRingIntermediate="leftRingIntermediate",g.LeftRingProximal="leftRingProximal",g.LeftShoulder="leftShoulder",g.LeftThumbDistal="leftThumbDistal",g.LeftThumbIntermediate="leftThumbIntermediate",g.LeftThumbProximal="leftThumbProximal",g.LeftToes="leftToes",g.LeftUpperArm="leftUpperArm",g.LeftUpperLeg="leftUpperLeg",g.Neck="neck",g.RightEye="rightEye",g.RightFoot="rightFoot",g.RightHand="rightHand",g.RightIndexDistal="rightIndexDistal",g.RightIndexIntermediate="rightIndexIntermediate",g.RightIndexProximal="rightIndexProximal",g.RightLittleDistal="rightLittleDistal",g.RightLittleIntermediate="rightLittleIntermediate",g.RightLittleProximal="rightLittleProximal",g.RightLowerArm="rightLowerArm",g.RightLowerLeg="rightLowerLeg",g.RightMiddleDistal="rightMiddleDistal",g.RightMiddleIntermediate="rightMiddleIntermediate",g.RightMiddleProximal="rightMiddleProximal",g.RightRingDistal="rightRingDistal",g.RightRingIntermediate="rightRingIntermediate",g.RightRingProximal="rightRingProximal",g.RightShoulder="rightShoulder",g.RightThumbDistal="rightThumbDistal",g.RightThumbIntermediate="rightThumbIntermediate",g.RightThumbProximal="rightThumbProximal",g.RightToes="rightToes",g.RightUpperArm="rightUpperArm",g.RightUpperLeg="rightUpperLeg",g.Spine="spine",g.UpperChest="upperChest",(_=p.MetaAllowedUserName||(p.MetaAllowedUserName={})).Everyone="Everyone",_.ExplicitlyLicensedPerson="ExplicitlyLicensedPerson",_.OnlyAuthor="OnlyAuthor",(v=p.MetaUssageName||(p.MetaUssageName={})).Allow="Allow",v.Disallow="Disallow",(M=p.MetaLicenseName||(p.MetaLicenseName={})).Cc0="CC0",M.CcBy="CC_BY",M.CcByNc="CC_BY_NC",M.CcByNcNd="CC_BY_NC_ND",M.CcByNcSa="CC_BY_NC_SA",M.CcByNd="CC_BY_ND",M.CcBySa="CC_BY_SA",M.Other="Other",M.RedistributionProhibited="Redistribution_Prohibited";const S=new r.Vector3,R=new r.Vector3;function E(e,t){return e.matrixWorld.decompose(S,t,R),t}new r.Quaternion;class L{constructor(){this._blendShapeGroups={},this._blendShapePresetMap={},this._unknownGroupNames=[]}get expressions(){return Object.keys(this._blendShapeGroups)}get blendShapePresetMap(){return this._blendShapePresetMap}get unknownGroupNames(){return this._unknownGroupNames}getBlendShapeGroup(e){const t=this._blendShapePresetMap[e],n=t?this._blendShapeGroups[t]:this._blendShapeGroups[e];if(n)return n;console.warn(`no blend shape found by ${e}`)}registerBlendShapeGroup(e,t,n){this._blendShapeGroups[e]=n,t?this._blendShapePresetMap[t]=e:this._unknownGroupNames.push(e)}getValue(e){var t;const n=this.getBlendShapeGroup(e);return null!==(t=null==n?void 0:n.weight)&&void 0!==t?t:null}setValue(e,t){const n=this.getBlendShapeGroup(e);var i;n&&(n.weight=(i=t,Math.max(Math.min(i,1),0)))}getBlendShapeTrackName(e){const t=this.getBlendShapeGroup(e);return t?`${t.name}.weight`:null}update(){Object.keys(this._blendShapeGroups).forEach((e=>{this._blendShapeGroups[e].clearAppliedWeight()})),Object.keys(this._blendShapeGroups).forEach((e=>{this._blendShapeGroups[e].applyWeight()}))}}class w{import(t){var n;return o(this,void 0,void 0,(function*(){const i=null===(n=t.parser.json.extensions)||void 0===n?void 0:n.VRM;if(!i)return null;const r=i.blendShapeMaster;if(!r)return null;const a=new L,s=r.blendShapeGroups;if(!s)return a;const l={};return yield Promise.all(s.map((n=>o(this,void 0,void 0,(function*(){const i=n.name;if(void 0===i)return void console.warn("VRMBlendShapeImporter: One of blendShapeGroups has no name");let r;n.presetName&&n.presetName!==e.VRMSchema.BlendShapePresetName.Unknown&&!l[n.presetName]&&(r=n.presetName,l[n.presetName]=i);const s=new c(i);t.scene.add(s),s.isBinary=n.isBinary||!1,n.binds&&n.binds.forEach((e=>o(this,void 0,void 0,(function*(){if(void 0===e.mesh||void 0===e.index)return;const i=[];t.parser.json.nodes.forEach(((t,n)=>{t.mesh===e.mesh&&i.push(n)}));const r=e.index;yield Promise.all(i.map((i=>o(this,void 0,void 0,(function*(){var a;const l=yield function(e,t){return o(this,void 0,void 0,(function*(){const n=yield e.parser.getDependency("node",t);return T(e,t,n)}))}(t,i);l.every((e=>Array.isArray(e.morphTargetInfluences)&&r<e.morphTargetInfluences.length))?s.addBind({meshes:l,morphTargetIndex:r,weight:null!==(a=e.weight)&&void 0!==a?a:100}):console.warn(`VRMBlendShapeImporter: ${n.name} attempts to index ${r}th morph but not found.`)})))))}))));const d=n.materialValues;d&&d.forEach((e=>{if(void 0===e.materialName||void 0===e.propertyName||void 0===e.targetValue)return;const n=[];t.scene.traverse((t=>{if(t.material){const i=t.material;Array.isArray(i)?n.push(...i.filter((t=>t.name===e.materialName&&-1===n.indexOf(t)))):i.name===e.materialName&&-1===n.indexOf(i)&&n.push(i)}})),n.forEach((t=>{s.addMaterialValue({material:t,propertyName:x(e.propertyName),targetValue:e.targetValue})}))})),a.registerBlendShapeGroup(i,r,s)}))))),a}))}}const P=Object.freeze(new r.Vector3(0,0,-1)),A=new r.Quaternion;var b;!function(e){e[e.Auto=0]="Auto",e[e.Both=1]="Both",e[e.ThirdPersonOnly=2]="ThirdPersonOnly",e[e.FirstPersonOnly=3]="FirstPersonOnly"}(b||(b={}));class O{constructor(e,t){this.firstPersonFlag=O._parseFirstPersonFlag(e),this.primitives=t}static _parseFirstPersonFlag(e){switch(e){case"Both":return b.Both;case"ThirdPersonOnly":return b.ThirdPersonOnly;case"FirstPersonOnly":return b.FirstPersonOnly;default:return b.Auto}}}class C{constructor(e,t,n){this._meshAnnotations=[],this._firstPersonOnlyLayer=C._DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=C._DEFAULT_THIRDPERSON_ONLY_LAYER,this._initialized=!1,this._firstPersonBone=e,this._firstPersonBoneOffset=t,this._meshAnnotations=n}get firstPersonBone(){return this._firstPersonBone}get meshAnnotations(){return this._meshAnnotations}getFirstPersonWorldDirection(e){return e.copy(P).applyQuaternion(E(this._firstPersonBone,A))}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}getFirstPersonBoneOffset(e){return e.copy(this._firstPersonBoneOffset)}getFirstPersonWorldPosition(e){const t=this._firstPersonBoneOffset,n=new r.Vector4(t.x,t.y,t.z,1);return n.applyMatrix4(this._firstPersonBone.matrixWorld),e.set(n.x,n.y,n.z)}setup({firstPersonOnlyLayer:e=C._DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:t=C._DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initialized||(this._initialized=!0,this._firstPersonOnlyLayer=e,this._thirdPersonOnlyLayer=t,this._meshAnnotations.forEach((e=>{e.firstPersonFlag===b.FirstPersonOnly?e.primitives.forEach((e=>{e.layers.set(this._firstPersonOnlyLayer)})):e.firstPersonFlag===b.ThirdPersonOnly?e.primitives.forEach((e=>{e.layers.set(this._thirdPersonOnlyLayer)})):e.firstPersonFlag===b.Auto&&this._createHeadlessModel(e.primitives)})))}_excludeTriangles(e,t,n,i){let r=0;if(null!=t&&t.length>0)for(let o=0;o<e.length;o+=3){const a=e[o],s=e[o+1],l=e[o+2],d=t[a],h=n[a];if(d[0]>0&&i.includes(h[0]))continue;if(d[1]>0&&i.includes(h[1]))continue;if(d[2]>0&&i.includes(h[2]))continue;if(d[3]>0&&i.includes(h[3]))continue;const u=t[s],c=n[s];if(u[0]>0&&i.includes(c[0]))continue;if(u[1]>0&&i.includes(c[1]))continue;if(u[2]>0&&i.includes(c[2]))continue;if(u[3]>0&&i.includes(c[3]))continue;const p=t[l],m=n[l];p[0]>0&&i.includes(m[0])||(p[1]>0&&i.includes(m[1])||p[2]>0&&i.includes(m[2])||p[3]>0&&i.includes(m[3])||(e[r++]=a,e[r++]=s,e[r++]=l))}return r}_createErasedMesh(e,t){const n=new r.SkinnedMesh(e.geometry.clone(),e.material);n.name=`${e.name}(erase)`,n.frustumCulled=e.frustumCulled,n.layers.set(this._firstPersonOnlyLayer);const i=n.geometry,o=i.getAttribute("skinIndex").array,a=[];for(let e=0;e<o.length;e+=4)a.push([o[e],o[e+1],o[e+2],o[e+3]]);const s=i.getAttribute("skinWeight").array,l=[];for(let e=0;e<s.length;e+=4)l.push([s[e],s[e+1],s[e+2],s[e+3]]);const d=i.getIndex();if(!d)throw new Error("The geometry doesn't have an index buffer");const h=Array.from(d.array),u=this._excludeTriangles(h,l,a,t),c=[];for(let e=0;e<u;e++)c[e]=h[e];return i.setIndex(c),e.onBeforeRender&&(n.onBeforeRender=e.onBeforeRender),n.bind(new r.Skeleton(e.skeleton.bones,e.skeleton.boneInverses),new r.Matrix4),n}_createHeadlessModelForSkinnedMesh(e,t){const n=[];if(t.skeleton.bones.forEach(((e,t)=>{this._isEraseTarget(e)&&n.push(t)})),!n.length)return t.layers.enable(this._thirdPersonOnlyLayer),void t.layers.enable(this._firstPersonOnlyLayer);t.layers.set(this._thirdPersonOnlyLayer);const i=this._createErasedMesh(t,n);e.add(i)}_createHeadlessModel(e){e.forEach((e=>{if("SkinnedMesh"===e.type){const t=e;this._createHeadlessModelForSkinnedMesh(t.parent,t)}else this._isEraseTarget(e)&&e.layers.set(this._thirdPersonOnlyLayer)}))}_isEraseTarget(e){return e===this._firstPersonBone||!!e.parent&&this._isEraseTarget(e.parent)}}C._DEFAULT_FIRSTPERSON_ONLY_LAYER=9,C._DEFAULT_THIRDPERSON_ONLY_LAYER=10;class I{import(t,n){var i;return o(this,void 0,void 0,(function*(){const o=null===(i=t.parser.json.extensions)||void 0===i?void 0:i.VRM;if(!o)return null;const a=o.firstPerson;if(!a)return null;const s=a.firstPersonBone;let l;if(l=void 0===s||-1===s?n.getBoneNode(e.VRMSchema.HumanoidBoneName.Head):yield t.parser.getDependency("node",s),!l)return console.warn("VRMFirstPersonImporter: Could not find firstPersonBone of the VRM"),null;const d=a.firstPersonBoneOffset?new r.Vector3(a.firstPersonBoneOffset.x,a.firstPersonBoneOffset.y,-a.firstPersonBoneOffset.z):new r.Vector3(0,.06,0),h=[],u=yield y(t);return Array.from(u.entries()).forEach((([e,n])=>{const i=t.parser.json.nodes[e],r=a.meshAnnotations?a.meshAnnotations.find((e=>e.mesh===i.mesh)):void 0;h.push(new O(null==r?void 0:r.firstPersonFlag,n))})),new C(l,d,h)}))}}class V{constructor(e,t){this.node=e,this.humanLimit=t}}function D(e){return e.invert?e.invert():e.inverse(),e}const N=new r.Vector3,U=new r.Quaternion;class B{constructor(e,t){this.restPose={},this.humanBones=this._createHumanBones(e),this.humanDescription=t,this.restPose=this.getPose()}getPose(){const e={};return Object.keys(this.humanBones).forEach((t=>{const n=this.getBoneNode(t);if(!n)return;if(e[t])return;N.set(0,0,0),U.identity();const i=this.restPose[t];(null==i?void 0:i.position)&&N.fromArray(i.position).negate(),(null==i?void 0:i.rotation)&&D(U.fromArray(i.rotation)),N.add(n.position),U.premultiply(n.quaternion),e[t]={position:N.toArray(),rotation:U.toArray()}}),{}),e}setPose(e){Object.keys(e).forEach((t=>{const n=e[t],i=this.getBoneNode(t);if(!i)return;const r=this.restPose[t];r&&(n.position&&(i.position.fromArray(n.position),r.position&&i.position.add(N.fromArray(r.position))),n.rotation&&(i.quaternion.fromArray(n.rotation),r.rotation&&i.quaternion.multiply(U.fromArray(r.rotation))))}))}resetPose(){Object.entries(this.restPose).forEach((([e,t])=>{const n=this.getBoneNode(e);n&&((null==t?void 0:t.position)&&n.position.fromArray(t.position),(null==t?void 0:t.rotation)&&n.quaternion.fromArray(t.rotation))}))}getBone(e){var t;return null!==(t=this.humanBones[e][0])&&void 0!==t?t:void 0}getBones(e){var t;return null!==(t=this.humanBones[e])&&void 0!==t?t:[]}getBoneNode(e){var t,n;return null!==(n=null===(t=this.humanBones[e][0])||void 0===t?void 0:t.node)&&void 0!==n?n:null}getBoneNodes(e){var t,n;return null!==(n=null===(t=this.humanBones[e])||void 0===t?void 0:t.map((e=>e.node)))&&void 0!==n?n:[]}_createHumanBones(t){const n=Object.values(e.VRMSchema.HumanoidBoneName).reduce(((e,t)=>(e[t]=[],e)),{});return t.forEach((e=>{n[e.name].push(e.bone)})),n}}class G{import(e){var t;return o(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.humanoid;if(!i)return null;const a=[];i.humanBones&&(yield Promise.all(i.humanBones.map((t=>o(this,void 0,void 0,(function*(){if(!t.bone||null==t.node)return;const n=yield e.parser.getDependency("node",t.node);a.push({name:t.bone,bone:new V(n,{axisLength:t.axisLength,center:t.center&&new r.Vector3(t.center.x,t.center.y,t.center.z),max:t.max&&new r.Vector3(t.max.x,t.max.y,t.max.z),min:t.min&&new r.Vector3(t.min.x,t.min.y,t.min.z),useDefaultValues:t.useDefaultValues})})}))))));const s={armStretch:i.armStretch,legStretch:i.legStretch,upperArmTwist:i.upperArmTwist,lowerArmTwist:i.lowerArmTwist,upperLegTwist:i.upperLegTwist,lowerLegTwist:i.lowerLegTwist,feetSpacing:i.feetSpacing,hasTranslationDoF:i.hasTranslationDoF};return new B(a,s)}))}}class k{constructor(e,t,n){this.curve=[0,0,0,1,1,1,1,0],this.curveXRangeDegree=90,this.curveYRangeDegree=10,void 0!==e&&(this.curveXRangeDegree=e),void 0!==t&&(this.curveYRangeDegree=t),void 0!==n&&(this.curve=n)}map(e){const t=Math.min(Math.max(e,0),this.curveXRangeDegree)/this.curveXRangeDegree;return this.curveYRangeDegree*((e,t)=>{if(e.length<8)throw new Error("evaluateCurve: Invalid curve detected! (Array length must be 8 at least)");if(e.length%4!=0)throw new Error("evaluateCurve: Invalid curve detected! (Array length must be multiples of 4");let n;for(n=0;;n++){if(e.length<=4*n)return e[4*n-3];if(t<=e[4*n])break}const i=n-1;if(i<0)return e[4*i+5];const r=e[4*i],o=(t-r)/(e[4*n]-r);return((e,t,n,i,r)=>{const o=r*r*r,a=r*r;return e+(t-e)*(-2*o+3*a)+n*(o-2*a+r)+i*(o-a)})(e[4*i+1],e[4*n+1],e[4*i+3],e[4*n+2],o)})(this.curve,t)}}class F{}class H extends F{constructor(t,n,i,r){super(),this.type=e.VRMSchema.FirstPersonLookAtTypeName.BlendShape,this._curveHorizontal=n,this._curveVerticalDown=i,this._curveVerticalUp=r,this._blendShapeProxy=t}name(){return e.VRMSchema.FirstPersonLookAtTypeName.BlendShape}lookAt(t){const n=t.x,i=t.y;n<0?(this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookup,0),this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookdown,this._curveVerticalDown.map(-n))):(this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookdown,0),this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookup,this._curveVerticalUp.map(n))),i<0?(this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookleft,0),this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookright,this._curveHorizontal.map(-i))):(this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookright,0),this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookleft,this._curveHorizontal.map(i)))}}const W=Object.freeze(new r.Vector3(0,0,-1)),z=new r.Vector3,j=new r.Vector3,Y=new r.Vector3,X=new r.Quaternion;class q{constructor(e,t){this.autoUpdate=!0,this._euler=new r.Euler(0,0,0,q.EULER_ORDER),this.firstPerson=e,this.applyer=t}getLookAtWorldDirection(e){const t=E(this.firstPerson.firstPersonBone,X);return e.copy(W).applyEuler(this._euler).applyQuaternion(t)}lookAt(e){this._calcEuler(this._euler,e),this.applyer&&this.applyer.lookAt(this._euler)}update(e){this.target&&this.autoUpdate&&(this.lookAt(this.target.getWorldPosition(z)),this.applyer&&this.applyer.lookAt(this._euler))}_calcEuler(e,t){const n=this.firstPerson.getFirstPersonWorldPosition(j),i=Y.copy(t).sub(n).normalize();return i.applyQuaternion(D(E(this.firstPerson.firstPersonBone,X))),e.x=Math.atan2(i.y,Math.sqrt(i.x*i.x+i.z*i.z)),e.y=Math.atan2(-i.x,-i.z),e}}q.EULER_ORDER="YXZ";const Q=new r.Euler(0,0,0,q.EULER_ORDER);class Z extends F{constructor(t,n,i,r,o){super(),this.type=e.VRMSchema.FirstPersonLookAtTypeName.Bone,this._curveHorizontalInner=n,this._curveHorizontalOuter=i,this._curveVerticalDown=r,this._curveVerticalUp=o,this._leftEye=t.getBoneNode(e.VRMSchema.HumanoidBoneName.LeftEye),this._rightEye=t.getBoneNode(e.VRMSchema.HumanoidBoneName.RightEye)}lookAt(e){const t=e.x,n=e.y;this._leftEye&&(Q.x=t<0?-this._curveVerticalDown.map(-t):this._curveVerticalUp.map(t),Q.y=n<0?-this._curveHorizontalInner.map(-n):this._curveHorizontalOuter.map(n),this._leftEye.quaternion.setFromEuler(Q)),this._rightEye&&(Q.x=t<0?-this._curveVerticalDown.map(-t):this._curveVerticalUp.map(t),Q.y=n<0?-this._curveHorizontalOuter.map(-n):this._curveHorizontalInner.map(n),this._rightEye.quaternion.setFromEuler(Q))}}const $=Math.PI/180;class J{import(e,t,n,i){var r;const o=null===(r=e.parser.json.extensions)||void 0===r?void 0:r.VRM;if(!o)return null;const a=o.firstPerson;if(!a)return null;const s=this._importApplyer(a,n,i);return new q(t,s||void 0)}_importApplyer(t,n,i){const r=t.lookAtHorizontalInner,o=t.lookAtHorizontalOuter,a=t.lookAtVerticalDown,s=t.lookAtVerticalUp;switch(t.lookAtTypeName){case e.VRMSchema.FirstPersonLookAtTypeName.Bone:return void 0===r||void 0===o||void 0===a||void 0===s?null:new Z(i,this._importCurveMapperBone(r),this._importCurveMapperBone(o),this._importCurveMapperBone(a),this._importCurveMapperBone(s));case e.VRMSchema.FirstPersonLookAtTypeName.BlendShape:return void 0===o||void 0===a||void 0===s?null:new H(n,this._importCurveMapperBlendShape(o),this._importCurveMapperBlendShape(a),this._importCurveMapperBlendShape(s));default:return null}}_importCurveMapperBone(e){return new k("number"==typeof e.xRange?$*e.xRange:void 0,"number"==typeof e.yRange?$*e.yRange:void 0,e.curve)}_importCurveMapperBlendShape(e){return new k("number"==typeof e.xRange?$*e.xRange:void 0,e.yRange,e.curve)}}const K=(e,t)=>{const n=(e=>{if(parseInt(r.REVISION,10)>=136)switch(e){case r.LinearEncoding:return["Linear","( value )"];case r.sRGBEncoding:return["sRGB","( value )"];default:return console.warn("THREE.WebGLProgram: Unsupported encoding:",e),["Linear","( value )"]}else switch(e){case r.LinearEncoding:return["Linear","( value )"];case r.sRGBEncoding:return["sRGB","( value )"];case r.RGBEEncoding:return["RGBE","( value )"];case r.RGBM7Encoding:return["RGBM","( value, 7.0 )"];case r.RGBM16Encoding:return["RGBM","( value, 16.0 )"];case r.RGBDEncoding:return["RGBD","( value, 256.0 )"];case r.GammaEncoding:return["Gamma","( value, float( GAMMA_FACTOR ) )"];default:throw new Error("unsupported encoding: "+e)}})(t);return"vec4 "+e+"( vec4 value ) { return "+n[0]+"ToLinear"+n[1]+"; }"};const ee=2*Math.PI;var te,ne,ie,re,oe;e.MToonMaterialCullMode=void 0,(te=e.MToonMaterialCullMode||(e.MToonMaterialCullMode={}))[te.Off=0]="Off",te[te.Front=1]="Front",te[te.Back=2]="Back",e.MToonMaterialDebugMode=void 0,(ne=e.MToonMaterialDebugMode||(e.MToonMaterialDebugMode={}))[ne.None=0]="None",ne[ne.Normal=1]="Normal",ne[ne.LitShadeRate=2]="LitShadeRate",ne[ne.UV=3]="UV",e.MToonMaterialOutlineColorMode=void 0,(ie=e.MToonMaterialOutlineColorMode||(e.MToonMaterialOutlineColorMode={}))[ie.FixedColor=0]="FixedColor",ie[ie.MixedLighting=1]="MixedLighting",e.MToonMaterialOutlineWidthMode=void 0,(re=e.MToonMaterialOutlineWidthMode||(e.MToonMaterialOutlineWidthMode={}))[re.None=0]="None",re[re.WorldCoordinates=1]="WorldCoordinates",re[re.ScreenCoordinates=2]="ScreenCoordinates",e.MToonMaterialRenderMode=void 0,(oe=e.MToonMaterialRenderMode||(e.MToonMaterialRenderMode={}))[oe.Opaque=0]="Opaque",oe[oe.Cutout=1]="Cutout",oe[oe.Transparent=2]="Transparent",oe[oe.TransparentWithZWrite=3]="TransparentWithZWrite";class ae extends r.ShaderMaterial{constructor(t={}){super(),this.isMToonMaterial=!0,this.cutoff=.5,this.color=new r.Vector4(1,1,1,1),this.shadeColor=new r.Vector4(.97,.81,.86,1),this.map=null,this.mainTex_ST=new r.Vector4(0,0,1,1),this.shadeTexture=null,this.normalMap=null,this.normalMapType=r.TangentSpaceNormalMap,this.normalScale=new r.Vector2(1,1),this.receiveShadowRate=1,this.receiveShadowTexture=null,this.shadingGradeRate=1,this.shadingGradeTexture=null,this.shadeShift=0,this.shadeToony=.9,this.lightColorAttenuation=0,this.indirectLightIntensity=.1,this.rimTexture=null,this.rimColor=new r.Vector4(0,0,0,1),this.rimLightingMix=0,this.rimFresnelPower=1,this.rimLift=0,this.sphereAdd=null,this.emissionColor=new r.Vector4(0,0,0,1),this.emissiveMap=null,this.outlineWidthTexture=null,this.outlineWidth=.5,this.outlineScaledMaxDistance=1,this.outlineColor=new r.Vector4(0,0,0,1),this.outlineLightingMix=1,this.uvAnimMaskTexture=null,this.uvAnimScrollX=0,this.uvAnimScrollY=0,this.uvAnimRotation=0,this.shouldApplyUniforms=!0,this._debugMode=e.MToonMaterialDebugMode.None,this._blendMode=e.MToonMaterialRenderMode.Opaque,this._outlineWidthMode=e.MToonMaterialOutlineWidthMode.None,this._outlineColorMode=e.MToonMaterialOutlineColorMode.FixedColor,this._cullMode=e.MToonMaterialCullMode.Back,this._outlineCullMode=e.MToonMaterialCullMode.Front,this._isOutline=!1,this._uvAnimOffsetX=0,this._uvAnimOffsetY=0,this._uvAnimPhase=0,this.encoding=t.encoding||r.LinearEncoding,this.encoding!==r.LinearEncoding&&this.encoding!==r.sRGBEncoding&&console.warn("The specified color encoding does not work properly with MToonMaterial. You might want to use THREE.sRGBEncoding instead."),["mToonVersion","shadeTexture_ST","bumpMap_ST","receiveShadowTexture_ST","shadingGradeTexture_ST","rimTexture_ST","sphereAdd_ST","emissionMap_ST","outlineWidthTexture_ST","uvAnimMaskTexture_ST","srcBlend","dstBlend"].forEach((e=>{void 0!==t[e]&&delete t[e]})),t.fog=!0,t.lights=!0,t.clipping=!0,parseInt(r.REVISION,10)<129&&(t.skinning=t.skinning||!1),parseInt(r.REVISION,10)<131&&(t.morphTargets=t.morphTargets||!1,t.morphNormals=t.morphNormals||!1),t.uniforms=r.UniformsUtils.merge([r.UniformsLib.common,r.UniformsLib.normalmap,r.UniformsLib.emissivemap,r.UniformsLib.fog,r.UniformsLib.lights,{cutoff:{value:.5},color:{value:new r.Color(1,1,1)},colorAlpha:{value:1},shadeColor:{value:new r.Color(.97,.81,.86)},mainTex_ST:{value:new r.Vector4(0,0,1,1)},shadeTexture:{value:null},receiveShadowRate:{value:1},receiveShadowTexture:{value:null},shadingGradeRate:{value:1},shadingGradeTexture:{value:null},shadeShift:{value:0},shadeToony:{value:.9},lightColorAttenuation:{value:0},indirectLightIntensity:{value:.1},rimTexture:{value:null},rimColor:{value:new r.Color(0,0,0)},rimLightingMix:{value:0},rimFresnelPower:{value:1},rimLift:{value:0},sphereAdd:{value:null},emissionColor:{value:new r.Color(0,0,0)},outlineWidthTexture:{value:null},outlineWidth:{value:.5},outlineScaledMaxDistance:{value:1},outlineColor:{value:new r.Color(0,0,0)},outlineLightingMix:{value:1},uvAnimMaskTexture:{value:null},uvAnimOffsetX:{value:0},uvAnimOffsetY:{value:0},uvAnimTheta:{value:0}}]),this.setValues(t),this._updateShaderCode(),this._applyUniforms()}get mainTex(){return this.map}set mainTex(e){this.map=e}get bumpMap(){return this.normalMap}set bumpMap(e){this.normalMap=e}get bumpScale(){return this.normalScale.x}set bumpScale(e){this.normalScale.set(e,e)}get emissionMap(){return this.emissiveMap}set emissionMap(e){this.emissiveMap=e}get blendMode(){return this._blendMode}set blendMode(t){this._blendMode=t,this.depthWrite=this._blendMode!==e.MToonMaterialRenderMode.Transparent,this.transparent=this._blendMode===e.MToonMaterialRenderMode.Transparent||this._blendMode===e.MToonMaterialRenderMode.TransparentWithZWrite,this._updateShaderCode()}get debugMode(){return this._debugMode}set debugMode(e){this._debugMode=e,this._updateShaderCode()}get outlineWidthMode(){return this._outlineWidthMode}set outlineWidthMode(e){this._outlineWidthMode=e,this._updateShaderCode()}get outlineColorMode(){return this._outlineColorMode}set outlineColorMode(e){this._outlineColorMode=e,this._updateShaderCode()}get cullMode(){return this._cullMode}set cullMode(e){this._cullMode=e,this._updateCullFace()}get outlineCullMode(){return this._outlineCullMode}set outlineCullMode(e){this._outlineCullMode=e,this._updateCullFace()}get zWrite(){return this.depthWrite?1:0}set zWrite(e){this.depthWrite=.5<=e}get isOutline(){return this._isOutline}set isOutline(e){this._isOutline=e,this._updateShaderCode(),this._updateCullFace()}updateVRMMaterials(e){this._uvAnimOffsetX=this._uvAnimOffsetX+e*this.uvAnimScrollX,this._uvAnimOffsetY=this._uvAnimOffsetY-e*this.uvAnimScrollY,this._uvAnimPhase=this._uvAnimPhase+e*this.uvAnimRotation,this._applyUniforms()}copy(e){return super.copy(e),this.cutoff=e.cutoff,this.color.copy(e.color),this.shadeColor.copy(e.shadeColor),this.map=e.map,this.mainTex_ST.copy(e.mainTex_ST),this.shadeTexture=e.shadeTexture,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(this.normalScale),this.receiveShadowRate=e.receiveShadowRate,this.receiveShadowTexture=e.receiveShadowTexture,this.shadingGradeRate=e.shadingGradeRate,this.shadingGradeTexture=e.shadingGradeTexture,this.shadeShift=e.shadeShift,this.shadeToony=e.shadeToony,this.lightColorAttenuation=e.lightColorAttenuation,this.indirectLightIntensity=e.indirectLightIntensity,this.rimTexture=e.rimTexture,this.rimColor.copy(e.rimColor),this.rimLightingMix=e.rimLightingMix,this.rimFresnelPower=e.rimFresnelPower,this.rimLift=e.rimLift,this.sphereAdd=e.sphereAdd,this.emissionColor.copy(e.emissionColor),this.emissiveMap=e.emissiveMap,this.outlineWidthTexture=e.outlineWidthTexture,this.outlineWidth=e.outlineWidth,this.outlineScaledMaxDistance=e.outlineScaledMaxDistance,this.outlineColor.copy(e.outlineColor),this.outlineLightingMix=e.outlineLightingMix,this.uvAnimMaskTexture=e.uvAnimMaskTexture,this.uvAnimScrollX=e.uvAnimScrollX,this.uvAnimScrollY=e.uvAnimScrollY,this.uvAnimRotation=e.uvAnimRotation,this.debugMode=e.debugMode,this.blendMode=e.blendMode,this.outlineWidthMode=e.outlineWidthMode,this.outlineColorMode=e.outlineColorMode,this.cullMode=e.cullMode,this.outlineCullMode=e.outlineCullMode,this.isOutline=e.isOutline,this}_applyUniforms(){this.uniforms.uvAnimOffsetX.value=this._uvAnimOffsetX,this.uniforms.uvAnimOffsetY.value=this._uvAnimOffsetY,this.uniforms.uvAnimTheta.value=ee*this._uvAnimPhase,this.shouldApplyUniforms&&(this.shouldApplyUniforms=!1,this.uniforms.cutoff.value=this.cutoff,this.uniforms.color.value.setRGB(this.color.x,this.color.y,this.color.z),this.uniforms.colorAlpha.value=this.color.w,this.uniforms.shadeColor.value.setRGB(this.shadeColor.x,this.shadeColor.y,this.shadeColor.z),this.uniforms.map.value=this.map,this.uniforms.mainTex_ST.value.copy(this.mainTex_ST),this.uniforms.shadeTexture.value=this.shadeTexture,this.uniforms.normalMap.value=this.normalMap,this.uniforms.normalScale.value.copy(this.normalScale),this.uniforms.receiveShadowRate.value=this.receiveShadowRate,this.uniforms.receiveShadowTexture.value=this.receiveShadowTexture,this.uniforms.shadingGradeRate.value=this.shadingGradeRate,this.uniforms.shadingGradeTexture.value=this.shadingGradeTexture,this.uniforms.shadeShift.value=this.shadeShift,this.uniforms.shadeToony.value=this.shadeToony,this.uniforms.lightColorAttenuation.value=this.lightColorAttenuation,this.uniforms.indirectLightIntensity.value=this.indirectLightIntensity,this.uniforms.rimTexture.value=this.rimTexture,this.uniforms.rimColor.value.setRGB(this.rimColor.x,this.rimColor.y,this.rimColor.z),this.uniforms.rimLightingMix.value=this.rimLightingMix,this.uniforms.rimFresnelPower.value=this.rimFresnelPower,this.uniforms.rimLift.value=this.rimLift,this.uniforms.sphereAdd.value=this.sphereAdd,this.uniforms.emissionColor.value.setRGB(this.emissionColor.x,this.emissionColor.y,this.emissionColor.z),this.uniforms.emissiveMap.value=this.emissiveMap,this.uniforms.outlineWidthTexture.value=this.outlineWidthTexture,this.uniforms.outlineWidth.value=this.outlineWidth,this.uniforms.outlineScaledMaxDistance.value=this.outlineScaledMaxDistance,this.uniforms.outlineColor.value.setRGB(this.outlineColor.x,this.outlineColor.y,this.outlineColor.z),this.uniforms.outlineLightingMix.value=this.outlineLightingMix,this.uniforms.uvAnimMaskTexture.value=this.uvAnimMaskTexture,this.encoding===r.sRGBEncoding&&(this.uniforms.color.value.convertSRGBToLinear(),this.uniforms.shadeColor.value.convertSRGBToLinear(),this.uniforms.rimColor.value.convertSRGBToLinear(),this.uniforms.emissionColor.value.convertSRGBToLinear(),this.uniforms.outlineColor.value.convertSRGBToLinear()),this._updateCullFace())}_updateShaderCode(){const t=null!==this.outlineWidthTexture,n=null!==this.map||null!==this.shadeTexture||null!==this.receiveShadowTexture||null!==this.shadingGradeTexture||null!==this.rimTexture||null!==this.uvAnimMaskTexture;this.defines={THREE_VRM_THREE_REVISION:parseInt(r.REVISION,10),OUTLINE:this._isOutline,BLENDMODE_OPAQUE:this._blendMode===e.MToonMaterialRenderMode.Opaque,BLENDMODE_CUTOUT:this._blendMode===e.MToonMaterialRenderMode.Cutout,BLENDMODE_TRANSPARENT:this._blendMode===e.MToonMaterialRenderMode.Transparent||this._blendMode===e.MToonMaterialRenderMode.TransparentWithZWrite,MTOON_USE_UV:t||n,MTOON_UVS_VERTEX_ONLY:t&&!n,USE_SHADETEXTURE:null!==this.shadeTexture,USE_RECEIVESHADOWTEXTURE:null!==this.receiveShadowTexture,USE_SHADINGGRADETEXTURE:null!==this.shadingGradeTexture,USE_RIMTEXTURE:null!==this.rimTexture,USE_SPHEREADD:null!==this.sphereAdd,USE_OUTLINEWIDTHTEXTURE:null!==this.outlineWidthTexture,USE_UVANIMMASKTEXTURE:null!==this.uvAnimMaskTexture,DEBUG_NORMAL:this._debugMode===e.MToonMaterialDebugMode.Normal,DEBUG_LITSHADERATE:this._debugMode===e.MToonMaterialDebugMode.LitShadeRate,DEBUG_UV:this._debugMode===e.MToonMaterialDebugMode.UV,OUTLINE_WIDTH_WORLD:this._outlineWidthMode===e.MToonMaterialOutlineWidthMode.WorldCoordinates,OUTLINE_WIDTH_SCREEN:this._outlineWidthMode===e.MToonMaterialOutlineWidthMode.ScreenCoordinates,OUTLINE_COLOR_FIXED:this._outlineColorMode===e.MToonMaterialOutlineColorMode.FixedColor,OUTLINE_COLOR_MIXED:this._outlineColorMode===e.MToonMaterialOutlineColorMode.MixedLighting};const i=(null!==this.shadeTexture?K("shadeTextureTexelToLinear",this.shadeTexture.encoding)+"\n":"")+(null!==this.sphereAdd?K("sphereAddTexelToLinear",this.sphereAdd.encoding)+"\n":"")+(null!==this.rimTexture?K("rimTextureTexelToLinear",this.rimTexture.encoding)+"\n":"");this.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 #ifdef MTOON_UVS_VERTEX_ONLY\n vec2 vUv;\n #else\n varying vec2 vUv;\n #endif\n\n uniform vec4 mainTex_ST;\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_OUTLINEWIDTHTEXTURE\n uniform sampler2D outlineWidthTexture;\n#endif\n\nuniform float outlineWidth;\nuniform float outlineScaledMaxDistance;\n\nvoid main() {\n\n // #include <uv_vertex>\n #ifdef MTOON_USE_UV\n vUv = uv;\n vUv.y = 1.0 - vUv.y; // uv.y is opposite from UniVRM's\n vUv = mainTex_ST.st + mainTex_ST.pq * vUv;\n vUv.y = 1.0 - vUv.y; // reverting the previous flip\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_OUTLINEWIDTHTEXTURE\n outlineTex = texture2D( outlineWidthTexture, vUv ).r;\n #endif\n\n #ifdef OUTLINE_WIDTH_WORLD\n float worldNormalLength = length( transformedNormal );\n vec3 outlineOffset = 0.01 * outlineWidth * 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 *= min( gl_Position.w, outlineScaledMaxDistance );\n projectedNormal.x *= projectionMatrix[ 0 ].x / projectionMatrix[ 1 ].y;\n gl_Position.xy += 0.01 * outlineWidth * 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}",this.fragmentShader=i+'// #define PHONG\n\n#ifdef BLENDMODE_CUTOUT\n uniform float cutoff;\n#endif\n\nuniform vec3 color;\nuniform float colorAlpha;\nuniform vec3 shadeColor;\n#ifdef USE_SHADETEXTURE\n uniform sampler2D shadeTexture;\n#endif\n\nuniform float receiveShadowRate;\n#ifdef USE_RECEIVESHADOWTEXTURE\n uniform sampler2D receiveShadowTexture;\n#endif\n\nuniform float shadingGradeRate;\n#ifdef USE_SHADINGGRADETEXTURE\n uniform sampler2D shadingGradeTexture;\n#endif\n\nuniform float shadeShift;\nuniform float shadeToony;\nuniform float lightColorAttenuation;\nuniform float indirectLightIntensity;\n\n#ifdef USE_RIMTEXTURE\n uniform sampler2D rimTexture;\n#endif\nuniform vec3 rimColor;\nuniform float rimLightingMix;\nuniform float rimFresnelPower;\nuniform float rimLift;\n\n#ifdef USE_SPHEREADD\n uniform sampler2D sphereAdd;\n#endif\n\nuniform vec3 emissionColor;\n\nuniform vec3 outlineColor;\nuniform float outlineLightingMix;\n\n#ifdef USE_UVANIMMASKTEXTURE\n uniform sampler2D uvAnimMaskTexture;\n#endif\n\nuniform float uvAnimOffsetX;\nuniform float uvAnimOffsetY;\nuniform float uvAnimTheta;\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// #include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n// #include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\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// #include <lights_phong_pars_fragment>\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n\nstruct MToonMaterial {\n vec3 diffuseColor;\n vec3 shadeColor;\n float shadingGrade;\n float receiveShadow;\n};\n\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 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// == lighting stuff ===========================================================\nfloat getLightIntensity(\n const in IncidentLight directLight,\n const in GeometricContext geometry,\n const in float shadow,\n const in float shadingGrade\n) {\n float lightIntensity = dot( geometry.normal, directLight.direction );\n lightIntensity = 0.5 + 0.5 * lightIntensity;\n lightIntensity = lightIntensity * shadow;\n lightIntensity = lightIntensity * shadingGrade;\n lightIntensity = lightIntensity * 2.0 - 1.0;\n return shadeToony == 1.0\n ? step( shadeShift, lightIntensity )\n : smoothstep( shadeShift, shadeShift + ( 1.0 - shadeToony ), lightIntensity );\n}\n\nvec3 getLighting( const in vec3 lightColor ) {\n vec3 lighting = lightColor;\n lighting = mix(\n lighting,\n vec3( max( 0.001, max( lighting.x, max( lighting.y, lighting.z ) ) ) ),\n lightColorAttenuation\n );\n\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n lighting *= PI;\n #endif\n\n return lighting;\n}\n\nvec3 getDiffuse(\n const in MToonMaterial material,\n const in float lightIntensity,\n const in vec3 lighting\n) {\n #ifdef DEBUG_LITSHADERATE\n return vec3( BRDF_Lambert( lightIntensity * lighting ) );\n #endif\n\n return lighting * BRDF_Lambert( mix( material.shadeColor, material.diffuseColor, lightIntensity ) );\n}\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_UVANIMMASKTEXTURE\n uvAnimMask = texture2D( uvAnimMaskTexture, uv ).x;\n #endif\n\n uv = uv + vec2( uvAnimOffsetX, uvAnimOffsetY ) * uvAnimMask;\n float uvRotCos = cos( uvAnimTheta * uvAnimMask );\n float uvRotSin = sin( uvAnimTheta * 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( color, colorAlpha );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissionColor;\n\n #include <logdepthbuf_fragment>\n\n // #include <map_fragment>\n #ifdef USE_MAP\n diffuseColor *= mapTexelToLinear( texture2D( map, uv ) );\n #endif\n\n #include <color_fragment>\n // #include <alphamap_fragment>\n\n // -- MToon: alpha -----------------------------------------------------------\n // #include <alphatest_fragment>\n #ifdef BLENDMODE_CUTOUT\n if ( diffuseColor.a <= cutoff ) { discard; }\n diffuseColor.a = 1.0;\n #endif\n\n #ifdef BLENDMODE_OPAQUE\n diffuseColor.a = 1.0;\n #endif\n\n #if defined( OUTLINE ) && defined( OUTLINE_COLOR_FIXED ) // omitting DebugMode\n gl_FragColor = vec4( outlineColor, diffuseColor.a );\n postCorrection();\n return;\n #endif\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 normal = texture2D( normalMap, uv ).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 vec3 mapN = texture2D( normalMap, uv ).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 totalEmissiveRadiance *= emissiveMapTexelToLinear( texture2D( emissiveMap, uv ) ).rgb;\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 = shadeColor;\n #ifdef USE_SHADETEXTURE\n material.shadeColor *= shadeTextureTexelToLinear( texture2D( shadeTexture, uv ) ).rgb;\n #endif\n\n material.shadingGrade = 1.0;\n #ifdef USE_SHADINGGRADETEXTURE\n material.shadingGrade = 1.0 - shadingGradeRate * ( 1.0 - texture2D( shadingGradeTexture, uv ).r );\n #endif\n\n material.receiveShadow = receiveShadowRate;\n #ifdef USE_RECEIVESHADOWTEXTURE\n material.receiveShadow *= texture2D( receiveShadowTexture, uv ).a;\n #endif\n\n // #include <lights_fragment_begin>\n GeometricContext geometry;\n\n geometry.position = - vViewPosition;\n geometry.normal = normal;\n geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n\n IncidentLight directLight;\n vec3 lightingSum = vec3( 0.0 );\n\n // since these variables will be used in unrolled loop, we have to define in prior\n float atten, shadow, lightIntensity;\n vec3 lighting;\n\n #if ( NUM_POINT_LIGHTS > 0 )\n PointLight pointLight;\n\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 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 atten = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n pointLightShadow = pointLightShadows[ i ];\n atten = 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 shadow = 1.0 - material.receiveShadow * ( 1.0 - ( 0.5 + 0.5 * atten ) );\n lightIntensity = getLightIntensity( directLight, geometry, shadow, material.shadingGrade );\n lighting = getLighting( directLight.color );\n reflectedLight.directDiffuse += getDiffuse( material, lightIntensity, lighting );\n lightingSum += lighting;\n }\n #pragma unroll_loop_end\n #endif\n\n #if ( NUM_SPOT_LIGHTS > 0 )\n SpotLight spotLight;\n\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 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 atten = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n spotLightShadow = spotLightShadows[ i ];\n atten = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n #endif\n\n shadow = 1.0 - material.receiveShadow * ( 1.0 - ( 0.5 + 0.5 * atten ) );\n lightIntensity = getLightIntensity( directLight, geometry, shadow, material.shadingGrade );\n lighting = getLighting( directLight.color );\n reflectedLight.directDiffuse += getDiffuse( material, lightIntensity, lighting );\n lightingSum += lighting;\n }\n #pragma unroll_loop_end\n #endif\n\n #if ( NUM_DIR_LIGHTS > 0 )\n DirectionalLight directionalLight;\n\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 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 atten = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n directionalLightShadow = directionalLightShadows[ i ];\n atten = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n #endif\n\n shadow = 1.0 - material.receiveShadow * ( 1.0 - ( 0.5 + 0.5 * atten ) );\n lightIntensity = getLightIntensity( directLight, geometry, shadow, material.shadingGrade );\n lighting = getLighting( directLight.color );\n reflectedLight.directDiffuse += getDiffuse( material, lightIntensity, lighting );\n lightingSum += lighting;\n }\n #pragma unroll_loop_end\n #endif\n\n // #if defined( RE_IndirectDiffuse )\n vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n #if THREE_VRM_THREE_REVISION >= 133\n irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n #else\n irradiance += getLightProbeIrradiance( lightProbe, geometry );\n #endif\n #if ( NUM_HEMI_LIGHTS > 0 )\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n }\n #pragma unroll_loop_end\n #endif\n // #endif\n\n // #include <lights_fragment_maps>\n #ifdef USE_LIGHTMAP\n vec4 lightMapTexel = texture2D( lightMap, vUv2 );\n vec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n lightMapIrradiance *= PI;\n #endif\n irradiance += lightMapIrradiance;\n #endif\n\n // #include <lights_fragment_end>\n // RE_IndirectDiffuse here\n reflectedLight.indirectDiffuse += indirectLightIntensity * irradiance * BRDF_Lambert( material.diffuseColor );\n\n // modulation\n #include <aomap_fragment>\n\n vec3 col = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\n // The "comment out if you want to PBR absolutely" line\n #ifndef DEBUG_LITSHADERATE\n col = min(col, material.diffuseColor);\n #endif\n\n #if defined( OUTLINE ) && defined( OUTLINE_COLOR_MIXED )\n gl_FragColor = vec4(\n outlineColor.rgb * mix( vec3( 1.0 ), col, outlineLightingMix ),\n diffuseColor.a\n );\n postCorrection();\n return;\n #endif\n\n #ifdef DEBUG_LITSHADERATE\n gl_FragColor = vec4( col, diffuseColor.a );\n postCorrection();\n return;\n #endif\n\n // -- MToon: parametric rim lighting -----------------------------------------\n vec3 viewDir = normalize( vViewPosition );\n vec3 rimMix = mix( vec3( 1.0 ), lightingSum + indirectLightIntensity * irradiance, rimLightingMix );\n vec3 rim = rimColor * pow( saturate( 1.0 - dot( viewDir, normal ) + rimLift ), rimFresnelPower );\n #ifdef USE_RIMTEXTURE\n rim *= rimTextureTexelToLinear( texture2D( rimTexture, uv ) ).rgb;\n #endif\n col += rim;\n\n // -- MToon: additive matcap -------------------------------------------------\n #ifdef USE_SPHEREADD\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 vec3 matcap = sphereAddTexelToLinear( texture2D( sphereAdd, sphereUv ) ).xyz;\n col += matcap;\n }\n #endif\n\n // -- MToon: Emission --------------------------------------------------------\n col += totalEmissiveRadiance;\n\n // #include <envmap_fragment>\n\n // -- Almost done! -----------------------------------------------------------\n gl_FragColor = vec4( col, diffuseColor.a );\n postCorrection();\n}',this.needsUpdate=!0}_updateCullFace(){this.isOutline?this.outlineCullMode===e.MToonMaterialCullMode.Off?this.side=r.DoubleSide:this.outlineCullMode===e.MToonMaterialCullMode.Front?this.side=r.BackSide:this.outlineCullMode===e.MToonMaterialCullMode.Back&&(this.side=r.FrontSide):this.cullMode===e.MToonMaterialCullMode.Off?this.side=r.DoubleSide:this.cullMode===e.MToonMaterialCullMode.Front?this.side=r.BackSide:this.cullMode===e.MToonMaterialCullMode.Back&&(this.side=r.FrontSide)}}var se;e.VRMUnlitMaterialRenderType=void 0,(se=e.VRMUnlitMaterialRenderType||(e.VRMUnlitMaterialRenderType={}))[se.Opaque=0]="Opaque",se[se.Cutout=1]="Cutout",se[se.Transparent=2]="Transparent",se[se.TransparentWithZWrite=3]="TransparentWithZWrite";class le extends r.ShaderMaterial{constructor(t){super(),this.isVRMUnlitMaterial=!0,this.cutoff=.5,this.map=null,this.mainTex_ST=new r.Vector4(0,0,1,1),this._renderType=e.VRMUnlitMaterialRenderType.Opaque,this.shouldApplyUniforms=!0,void 0===t&&(t={}),t.fog=!0,t.clipping=!0,parseInt(r.REVISION,10)<129&&(t.skinning=t.skinning||!1),parseInt(r.REVISION,10)<131&&(t.morphTargets=t.morphTargets||!1,t.morphNormals=t.morphNormals||!1),t.uniforms=r.UniformsUtils.merge([r.UniformsLib.common,r.UniformsLib.fog,{cutoff:{value:.5},mainTex_ST:{value:new r.Vector4(0,0,1,1)}}]),this.setValues(t),this._updateShaderCode(),this._applyUniforms()}get mainTex(){return this.map}set mainTex(e){this.map=e}get renderType(){return this._renderType}set renderType(t){this._renderType=t,this.depthWrite=this._renderType!==e.VRMUnlitMaterialRenderType.Transparent,this.transparent=this._renderType===e.VRMUnlitMaterialRenderType.Transparent||this._renderType===e.VRMUnlitMaterialRenderType.TransparentWithZWrite,this._updateShaderCode()}updateVRMMaterials(e){this._applyUniforms()}copy(e){return super.copy(e),this.cutoff=e.cutoff,this.map=e.map,this.mainTex_ST.copy(e.mainTex_ST),this.renderType=e.renderType,this}_applyUniforms(){this.shouldApplyUniforms&&(this.shouldApplyUniforms=!1,this.uniforms.cutoff.value=this.cutoff,this.uniforms.map.value=this.map,this.uniforms.mainTex_ST.value.copy(this.mainTex_ST))}_updateShaderCode(){this.defines={RENDERTYPE_OPAQUE:this._renderType===e.VRMUnlitMaterialRenderType.Opaque,RENDERTYPE_CUTOUT:this._renderType===e.VRMUnlitMaterialRenderType.Cutout,RENDERTYPE_TRANSPARENT:this._renderType===e.VRMUnlitMaterialRenderType.Transparent||this._renderType===e.VRMUnlitMaterialRenderType.TransparentWithZWrite},this.vertexShader="#include <common>\n\n// #include <uv_pars_vertex>\n#ifdef USE_MAP\n varying vec2 vUv;\n uniform vec4 mainTex_ST;\n#endif\n\n#include <uv2_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 <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n // #include <uv_vertex>\n #ifdef USE_MAP\n vUv = vec2( mainTex_ST.p * uv.x + mainTex_ST.s, mainTex_ST.q * uv.y + mainTex_ST.t );\n #endif\n\n #include <uv2_vertex>\n #include <color_vertex>\n #include <skinbase_vertex>\n\n #ifdef USE_ENVMAP\n\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinnormal_vertex>\n #include <defaultnormal_vertex>\n\n #endif\n\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n\n #include <worldpos_vertex>\n #include <clipping_planes_vertex>\n #include <envmap_vertex>\n #include <fog_vertex>\n\n}",this.fragmentShader="#ifdef RENDERTYPE_CUTOUT\n uniform float cutoff;\n#endif\n\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n// #include <alphamap_pars_fragment>\n// #include <aomap_pars_fragment>\n// #include <lightmap_pars_fragment>\n// #include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n// #include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\n// == main procedure ===========================================================\nvoid main() {\n #include <clipping_planes_fragment>\n\n vec4 diffuseColor = vec4( 1.0 );\n\n #include <logdepthbuf_fragment>\n\n // #include <map_fragment>\n #ifdef USE_MAP\n diffuseColor *= mapTexelToLinear( texture2D( map, vUv ) );\n #endif\n\n #include <color_fragment>\n // #include <alphamap_fragment>\n\n // MToon: alpha\n // #include <alphatest_fragment>\n #ifdef RENDERTYPE_CUTOUT\n if ( diffuseColor.a <= cutoff ) { discard; }\n diffuseColor.a = 1.0;\n #endif\n\n #ifdef RENDERTYPE_OPAQUE\n diffuseColor.a = 1.0;\n #endif\n\n // #include <specularmap_fragment>\n\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\n // accumulation (baked indirect lighting only)\n #ifdef USE_LIGHTMAP\n reflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n #else\n reflectedLight.indirectDiffuse += vec3( 1.0 );\n #endif\n\n // modulation\n // #include <aomap_fragment>\n\n reflectedLight.indirectDiffuse *= diffuseColor.rgb;\n vec3 outgoingLight = reflectedLight.indirectDiffuse;\n\n // #include <envmap_fragment>\n\n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n #include <premultiplied_alpha_fragment>\n #include <tonemapping_fragment>\n #include <encodings_fragment>\n #include <fog_fragment>\n}",this.needsUpdate=!0}}class de{constructor(e={}){this._encoding=e.encoding||r.LinearEncoding,this._encoding!==r.LinearEncoding&&this._encoding!==r.sRGBEncoding&&console.warn("The specified color encoding might not work properly with VRMMaterialImporter. You might want to use THREE.sRGBEncoding instead."),this._requestEnvMap=e.requestEnvMap}convertGLTFMaterials(e){var t;return o(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.materialProperties;if(!i)return null;const r=yield y(e),a={},s=[];return yield Promise.all(Array.from(r.entries()).map((([t,n])=>o(this,void 0,void 0,(function*(){const r=e.parser.json.nodes[t],l=e.parser.json.meshes[r.mesh];yield Promise.all(n.map(((t,n)=>o(this,void 0,void 0,(function*(){const r=l.primitives[n];if(!r)return;const o=t.geometry,d=o.index?o.index.count:o.attributes.position.count/3;Array.isArray(t.material)||(t.material=[t.material],o.addGroup(0,d,0));const h=r.material;let u,c=i[h];c||(console.warn(`VRMMaterialImporter: There are no material definition for material #${h} on VRM extension.`),c={shader:"VRM_USE_GLTFSHADER"}),a[h]?u=a[h]:(u=yield this.createVRMMaterials(t.material[0],c,e),a[h]=u,s.push(u.surface),u.outline&&s.push(u.outline)),t.material[0]=u.surface,this._requestEnvMap&&u.surface.isMeshStandardMaterial&&this._requestEnvMap().then((e=>{u.surface.envMap=e,u.surface.needsUpdate=!0})),t.renderOrder=c.renderQueue||2e3,u.outline&&(t.material[1]=u.outline,o.addGroup(0,d,1))})))))}))))),s}))}createVRMMaterials(t,n,i){return o(this,void 0,void 0,(function*(){let r,o;if("VRM/MToon"===n.shader){const a=yield this._extractMaterialProperties(t,n,i);["srcBlend","dstBlend","isFirstSetup"].forEach((e=>{void 0!==a[e]&&delete a[e]})),["mainTex","shadeTexture","emissionMap","sphereAdd","rimTexture"].forEach((e=>{void 0!==a[e]&&(a[e].encoding=this._encoding)})),a.encoding=this._encoding,r=new ae(a),a.outlineWidthMode!==e.MToonMaterialOutlineWidthMode.None&&(a.isOutline=!0,o=new ae(a))}else if("VRM/UnlitTexture"===n.shader){const o=yield this._extractMaterialProperties(t,n,i);o.renderType=e.VRMUnlitMaterialRenderType.Opaque,r=new le(o)}else if("VRM/UnlitCutout"===n.shader){const o=yield this._extractMaterialProperties(t,n,i);o.renderType=e.VRMUnlitMaterialRenderType.Cutout,r=new le(o)}else if("VRM/UnlitTransparent"===n.shader){const o=yield this._extractMaterialProperties(t,n,i);o.renderType=e.VRMUnlitMaterialRenderType.Transparent,r=new le(o)}else if("VRM/UnlitTransparentZWrite"===n.shader){const o=yield this._extractMaterialProperties(t,n,i);o.renderType=e.VRMUnlitMaterialRenderType.TransparentWithZWrite,r=new le(o)}else"VRM_USE_GLTFSHADER"!==n.shader&&console.warn(`Unknown shader detected: "${n.shader}"`),r=this._convertGLTFMaterial(t.clone());return r.name=t.name,r.userData=JSON.parse(JSON.stringify(t.userData)),r.userData.vrmMaterialProperties=n,o&&(o.name=t.name+" (Outline)",o.userData=JSON.parse(JSON.stringify(t.userData)),o.userData.vrmMaterialProperties=n),{surface:r,outline:o}}))}_renameMaterialProperty(e){return"_"!==e[0]?(console.warn(`VRMMaterials: Given property name "${e}" might be invalid`),e):(e=e.substring(1),/[A-Z]/.test(e[0])?e[0].toLowerCase()+e.substring(1):(console.warn(`VRMMaterials: Given property name "${e}" might be invalid`),e))}_convertGLTFMaterial(e){if(e.isMeshStandardMaterial){const t=e;t.map&&(t.map.encoding=this._encoding),t.emissiveMap&&(t.emissiveMap.encoding=this._encoding),this._encoding===r.LinearEncoding&&(t.color.convertLinearToSRGB(),t.emissive.convertLinearToSRGB())}if(e.isMeshBasicMaterial){const t=e;t.map&&(t.map.encoding=this._encoding),this._encoding===r.LinearEncoding&&t.color.convertLinearToSRGB()}return e}_extractMaterialProperties(e,t,n){const i=[],o={};if(t.textureProperties)for(const e of Object.keys(t.textureProperties)){const r=this._renameMaterialProperty(e),a=t.textureProperties[e];i.push(n.parser.getDependency("texture",a).then((e=>{o[r]=e})))}if(t.floatProperties)for(const e of Object.keys(t.floatProperties)){const n=this._renameMaterialProperty(e);o[n]=t.floatProperties[e]}if(t.vectorProperties)for(const e of Object.keys(t.vectorProperties)){let n=this._renameMaterialProperty(e);["_MainTex","_ShadeTexture","_BumpMap","_ReceiveShadowTexture","_ShadingGradeTexture","_RimTexture","_SphereAdd","_EmissionMap","_OutlineWidthTexture","_UvAnimMaskTexture"].some((t=>e===t))&&(n+="_ST"),o[n]=new r.Vector4(...t.vectorProperties[e])}return parseInt(r.REVISION,10)<129&&(o.skinning=e.skinning||!1),parseInt(r.REVISION,10)<131&&(o.morphTargets=e.morphTargets||!1,o.morphNormals=e.morphNormals||!1),Promise.all(i).then((()=>o))}}class he{constructor(e){var t;this.ignoreTexture=null!==(t=null==e?void 0:e.ignoreTexture)&&void 0!==t&&t}import(e){var t;return o(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.meta;if(!i)return null;let r;return this.ignoreTexture||null==i.texture||-1===i.texture||(r=yield e.parser.getDependency("texture",i.texture)),{allowedUserName:i.allowedUserName,author:i.author,commercialUssageName:i.commercialUssageName,contactInformation:i.contactInformation,licenseName:i.licenseName,otherLicenseUrl:i.otherLicenseUrl,otherPermissionUrl:i.otherPermissionUrl,reference:i.reference,sexualUssageName:i.sexualUssageName,texture:null!=r?r:void 0,title:i.title,version:i.version,violentUssageName:i.violentUssageName}}))}}const ue=new r.Matrix4;function ce(e){return e.invert?e.invert():e.getInverse(ue.copy(e)),e}class pe{constructor(e){this._inverseCache=new r.Matrix4,this._shouldUpdateInverse=!0,this.matrix=e;const t={set:(e,t,n)=>(this._shouldUpdateInverse=!0,e[t]=n,!0)};this._originalElements=e.elements,e.elements=new Proxy(e.elements,t)}get inverse(){return this._shouldUpdateInverse&&(ce(this._inverseCache.copy(this.matrix)),this._shouldUpdateInverse=!1),this._inverseCache}revert(){this.matrix.elements=this._originalElements}}const me=Object.freeze(new r.Matrix4),fe=Object.freeze(new r.Quaternion),ge=new r.Vector3,_e=new r.Vector3,ve=new r.Vector3,Me=new r.Quaternion,Te=new r.Matrix4,ye=new r.Matrix4;class xe{constructor(e,t={}){var n,i,o,a,s,l;if(this._currentTail=new r.Vector3,this._prevTail=new r.Vector3,this._nextTail=new r.Vector3,this._boneAxis=new r.Vector3,this._centerSpacePosition=new r.Vector3,this._center=null,this._parentWorldRotation=new r.Quaternion,this._initialLocalMatrix=new r.Matrix4,this._initialLocalRotation=new r.Quaternion,this._initialLocalChildPosition=new r.Vector3,this.bone=e,this.bone.matrixAutoUpdate=!1,this.radius=null!==(n=t.radius)&&void 0!==n?n:.02,this.stiffnessForce=null!==(i=t.stiffnessForce)&&void 0!==i?i:1,this.gravityDir=t.gravityDir?(new r.Vector3).copy(t.gravityDir):(new r.Vector3).set(0,-1,0),this.gravityPower=null!==(o=t.gravityPower)&&void 0!==o?o:0,this.dragForce=null!==(a=t.dragForce)&&void 0!==a?a:.4,this.colliders=null!==(s=t.colliders)&&void 0!==s?s:[],this._centerSpacePosition.setFromMatrixPosition(this.bone.matrixWorld),this._initialLocalMatrix.copy(this.bone.matrix),this._initialLocalRotation.copy(this.bone.quaternion),0===this.bone.children.length)this._initialLocalChildPosition.copy(this.bone.position).normalize().multiplyScalar(.07);else{const e=this.bone.children[0];this._initialLocalChildPosition.copy(e.position)}this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)),this._prevTail.copy(this._currentTail),this._nextTail.copy(this._currentTail),this._boneAxis.copy(this._initialLocalChildPosition).normalize(),this._centerSpaceBoneLength=ge.copy(this._initialLocalChildPosition).applyMatrix4(this.bone.matrixWorld).sub(this._centerSpacePosition).length(),this.center=null!==(l=t.center)&&void 0!==l?l:null}get center(){return this._center}set center(e){var t;this._getMatrixCenterToWorld(Te),this._currentTail.applyMatrix4(Te),this._prevTail.applyMatrix4(Te),this._nextTail.applyMatrix4(Te),(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 pe(this._center.matrixWorld))),this._getMatrixWorldToCenter(Te),this._currentTail.applyMatrix4(Te),this._prevTail.applyMatrix4(Te),this._nextTail.applyMatrix4(Te),Te.multiply(this.bone.matrixWorld),this._centerSpacePosition.setFromMatrixPosition(Te),this._centerSpaceBoneLength=ge.copy(this._initialLocalChildPosition).applyMatrix4(Te).sub(this._centerSpacePosition).length()}reset(){this.bone.quaternion.copy(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._getParentMatrixWorld(),this.bone.matrix),this._centerSpacePosition.setFromMatrixPosition(this.bone.matrixWorld),this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)),this._prevTail.copy(this._currentTail),this._nextTail.copy(this._currentTail)}update(e){if(e<=0)return;this.bone.matrixWorld.multiplyMatrices(this._getParentMatrixWorld(),this.bone.matrix),this.bone.parent?E(this.bone.parent,this._parentWorldRotation):this._parentWorldRotation.copy(fe),this._getMatrixWorldToCenter(Te),Te.multiply(this.bone.matrixWorld),this._centerSpacePosition.setFromMatrixPosition(Te),this._getMatrixWorldToCenter(ye),ye.multiply(this._getParentMatrixWorld());const t=this.stiffnessForce*e,n=_e.copy(this.gravityDir).multiplyScalar(this.gravityPower*e);this._nextTail.copy(this._currentTail).add(ge.copy(this._currentTail).sub(this._prevTail).multiplyScalar(1-this.dragForce)).add(ge.copy(this._boneAxis).applyMatrix4(this._initialLocalMatrix).applyMatrix4(ye).sub(this._centerSpacePosition).normalize().multiplyScalar(t)).add(n),this._nextTail.sub(this._centerSpacePosition).normalize().multiplyScalar(this._centerSpaceBoneLength).add(this._centerSpacePosition),this._collision(this._nextTail),this._prevTail.copy(this._currentTail),this._currentTail.copy(this._nextTail);const i=ce(Te.copy(ye.multiply(this._initialLocalMatrix))),r=Me.setFromUnitVectors(this._boneAxis,ge.copy(this._nextTail).applyMatrix4(i).normalize());this.bone.quaternion.copy(this._initialLocalRotation).multiply(r),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._getParentMatrixWorld(),this.bone.matrix)}_collision(e){this.colliders.forEach((t=>{this._getMatrixWorldToCenter(Te),Te.multiply(t.matrixWorld);const n=ge.setFromMatrixPosition(Te),i=t.geometry.boundingSphere.radius,r=this.radius+i;if(e.distanceToSquared(n)<=r*r){const t=_e.subVectors(e,n).normalize(),i=ve.addVectors(n,t.multiplyScalar(r));e.copy(i.sub(this._centerSpacePosition).normalize().multiplyScalar(this._centerSpaceBoneLength).add(this._centerSpacePosition))}}))}_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}_getParentMatrixWorld(){return this.bone.parent?this.bone.parent.matrixWorld:me}}class Se{constructor(e,t){this.colliderGroups=[],this.springBoneGroupList=[],this.colliderGroups=e,this.springBoneGroupList=t}setCenter(e){this.springBoneGroupList.forEach((t=>{t.forEach((t=>{t.center=e}))}))}lateUpdate(e){this.springBoneGroupList.forEach((t=>{t.forEach((t=>{t.update(e)}))}))}reset(){this.springBoneGroupList.forEach((e=>{e.forEach((e=>{e.reset()}))}))}}const Re=new r.Vector3,Ee=new r.MeshBasicMaterial({visible:!1});class Le{import(e){var t;return o(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.secondaryAnimation;if(!i)return null;const r=yield this._importColliderMeshGroups(e,i),o=yield this._importSpringBoneGroupList(e,i,r);return new Se(r,o)}))}_createSpringBone(e,t={}){return new xe(e,t)}_importSpringBoneGroupList(e,t,n){return o(this,void 0,void 0,(function*(){const i=t.boneGroups||[],a=[];return yield Promise.all(i.map((t=>o(this,void 0,void 0,(function*(){if(void 0===t.stiffiness||void 0===t.gravityDir||void 0===t.gravityDir.x||void 0===t.gravityDir.y||void 0===t.gravityDir.z||void 0===t.gravityPower||void 0===t.dragForce||void 0===t.hitRadius||void 0===t.colliderGroups||void 0===t.bones||void 0===t.center)return;const i=t.stiffiness,s=new r.Vector3(t.gravityDir.x,t.gravityDir.y,-t.gravityDir.z),l=t.gravityPower,d=t.dragForce,h=t.hitRadius,u=[];t.colliderGroups.forEach((e=>{u.push(...n[e].colliders)}));const c=[];yield Promise.all(t.bones.map((n=>o(this,void 0,void 0,(function*(){const r=yield e.parser.getDependency("node",n),o=-1!==t.center?yield e.parser.getDependency("node",t.center):null;r&&r.traverse((e=>{const t=this._createSpringBone(e,{radius:h,stiffnessForce:i,gravityDir:s,gravityPower:l,dragForce:d,colliders:u,center:o});c.push(t)}))}))))),a.push(c)}))))),a}))}_importColliderMeshGroups(e,t){return o(this,void 0,void 0,(function*(){const n=t.colliderGroups;if(void 0===n)return[];const i=[];return n.forEach((t=>o(this,void 0,void 0,(function*(){if(void 0===t.node||void 0===t.colliders)return;const n=yield e.parser.getDependency("node",t.node),r=[];t.colliders.forEach((e=>{if(void 0===e.offset||void 0===e.offset.x||void 0===e.offset.y||void 0===e.offset.z||void 0===e.radius)return;const t=Re.set(e.offset.x,e.offset.y,-e.offset.z),i=this._createColliderMesh(e.radius,t);n.add(i),r.push(i)}));const o={node:t.node,colliders:r};i.push(o)})))),i}))}_createColliderMesh(e,t){const n=new r.Mesh(new r.SphereBufferGeometry(e,8,4),Ee);return n.position.copy(t),n.name="vrmColliderSphere",n.geometry.computeBoundingSphere(),n}}class we{constructor(e={}){this._metaImporter=e.metaImporter||new he,this._blendShapeImporter=e.blendShapeImporter||new w,this._lookAtImporter=e.lookAtImporter||new J,this._humanoidImporter=e.humanoidImporter||new G,this._firstPersonImporter=e.firstPersonImporter||new I,this._materialImporter=e.materialImporter||new de,this._springBoneImporter=e.springBoneImporter||new Le}import(e){return o(this,void 0,void 0,(function*(){if(void 0===e.parser.json.extensions||void 0===e.parser.json.extensions.VRM)throw new Error("Could not find VRM extension on the GLTF");const t=e.scene;t.updateMatrixWorld(!1),t.traverse((e=>{e.isMesh&&(e.frustumCulled=!1)}));const n=(yield this._metaImporter.import(e))||void 0,i=(yield this._materialImporter.convertGLTFMaterials(e))||void 0,r=(yield this._humanoidImporter.import(e))||void 0,o=r&&(yield this._firstPersonImporter.import(e,r))||void 0,a=(yield this._blendShapeImporter.import(e))||void 0,s=o&&a&&r&&(yield this._lookAtImporter.import(e,o,a,r))||void 0,l=(yield this._springBoneImporter.import(e))||void 0;return new Pe({scene:e.scene,meta:n,materials:i,humanoid:r,firstPerson:o,blendShapeProxy:a,lookAt:s,springBoneManager:l})}))}}class Pe{constructor(e){this.scene=e.scene,this.humanoid=e.humanoid,this.blendShapeProxy=e.blendShapeProxy,this.firstPerson=e.firstPerson,this.lookAt=e.lookAt,this.materials=e.materials,this.springBoneManager=e.springBoneManager,this.meta=e.meta}static from(e,t={}){return o(this,void 0,void 0,(function*(){const n=new we(t);return yield n.import(e)}))}update(e){this.lookAt&&this.lookAt.update(e),this.blendShapeProxy&&this.blendShapeProxy.update(),this.springBoneManager&&this.springBoneManager.lateUpdate(e),this.materials&&this.materials.forEach((t=>{t.updateVRMMaterials&&t.updateVRMMaterials(e)}))}dispose(){var e,t;const n=this.scene;n&&n.traverse(s),null===(t=null===(e=this.meta)||void 0===e?void 0:e.texture)||void 0===t||t.dispose()}}const Ae=new r.Vector2,be=new r.OrthographicCamera(-1,1,-1,1,-1,1),Oe=new r.MeshBasicMaterial({color:16777215,side:r.DoubleSide}),Ce=new r.Mesh(new r.PlaneBufferGeometry(2,2),Oe),Ie=new r.Scene;Ie.add(Ce);class Ve{constructor(){}}Ve.extractThumbnailBlob=function(e,t,n=512){var i;const r=null===(i=t.meta)||void 0===i?void 0:i.texture;if(!r)throw new Error("extractThumbnailBlob: This VRM does not have a thumbnail");const o=e.getContext().canvas;e.getSize(Ae);const a=Ae.x,s=Ae.y;return e.setSize(n,n,!1),Oe.map=r,e.render(Ie,be),Oe.map=null,o instanceof OffscreenCanvas?o.convertToBlob().finally((()=>{e.setSize(a,s,!1)})):new Promise(((t,n)=>{o.toBlob((i=>{e.setSize(a,s,!1),null==i?n("extractThumbnailBlob: Failed to create a blob"):t(i)}))}))},Ve.removeUnnecessaryJoints=function(e){const t=new Map;e.traverse((e=>{if("SkinnedMesh"!==e.type)return;const n=e,i=n.geometry.getAttribute("skinIndex");let o=t.get(i);if(!o){const e=[],a=[],s={},l=i.array;for(let t=0;t<l.length;t++){const i=l[t];void 0===s[i]&&(s[i]=e.length,e.push(n.skeleton.bones[i]),a.push(n.skeleton.boneInverses[i])),l[t]=s[i]}i.copyArray(l),i.needsUpdate=!0,o=new r.Skeleton(e,a),t.set(i,o)}n.bind(o,new r.Matrix4)}))},Ve.removeUnnecessaryVertices=function(e){const n=new Map;e.traverse((e=>{var i,o,a,s;if(!e.isMesh)return;const l=e,d=l.geometry,h=d.index;if(null==h)return;const u=n.get(d);if(null!=u)return void(l.geometry=u);const c=new r.BufferGeometry;c.name=d.name,c.morphTargetsRelative=d.morphTargetsRelative,d.groups.forEach((e=>{c.addGroup(e.start,e.count,e.materialIndex)})),c.boundingBox=null!==(o=null===(i=d.boundingBox)||void 0===i?void 0:i.clone())&&void 0!==o?o:null,c.boundingSphere=null!==(s=null===(a=d.boundingSphere)||void 0===a?void 0:a.clone())&&void 0!==s?s:null,c.setDrawRange(d.drawRange.start,d.drawRange.count),c.userData=d.userData,n.set(d,c);const p=[],m=[];{const e=h.array,n=new e.constructor(e.length);let i=0;for(let t=0;t<e.length;t++){const r=e[t];let o=p[r];null==o&&(p[r]=i,m[i]=r,o=i,i++),n[t]=o}c.setIndex(new t.BufferAttribute(n,1,!1))}Object.keys(d.attributes).forEach((e=>{const n=d.attributes[e];if(n.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");const i=n.array,{itemSize:r,normalized:o}=n,a=new i.constructor(m.length*r);m.forEach(((e,t)=>{for(let n=0;n<r;n++)a[t*r+n]=i[e*r+n]})),c.setAttribute(e,new t.BufferAttribute(a,r,o))}));let f=!0;Object.keys(d.morphAttributes).forEach((e=>{c.morphAttributes[e]=[];const n=d.morphAttributes[e];for(let i=0;i<n.length;i++){const r=n[i];if(r.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");const o=r.array,{itemSize:a,normalized:s}=r,l=new o.constructor(m.length*a);m.forEach(((e,t)=>{for(let n=0;n<a;n++)l[t*a+n]=o[e*a+n]})),f=f&&l.every((e=>0===e)),c.morphAttributes[e][i]=new t.BufferAttribute(l,a,s)}})),f&&(c.morphAttributes={}),l.geometry=c})),Array.from(n.keys()).forEach((e=>{e.dispose()}))};const De=new r.Vector3;class Ne extends q{setupHelper(e,t){t.disableFaceDirectionHelper||(this._faceDirectionHelper=new r.ArrowHelper(new r.Vector3(0,0,-1),new r.Vector3(0,0,0),.5,16711935),e.add(this._faceDirectionHelper))}update(e){super.update(e),this._faceDirectionHelper&&(this.firstPerson.getFirstPersonWorldPosition(this._faceDirectionHelper.position),this._faceDirectionHelper.setDirection(this.getLookAtWorldDirection(De)))}}class Ue extends J{import(e,t,n,i){var r;const o=null===(r=e.parser.json.extensions)||void 0===r?void 0:r.VRM;if(!o)return null;const a=o.firstPerson;if(!a)return null;const s=this._importApplyer(a,n,i);return new Ne(t,s||void 0)}}const Be=new r.MeshBasicMaterial({color:16711935,wireframe:!0,transparent:!0,depthTest:!1});class Ge extends Se{setupHelper(e,t){t.disableSpringBoneHelper||(this.springBoneGroupList.forEach((t=>{t.forEach((t=>{if(t.getGizmo){const n=t.getGizmo();e.add(n)}}))})),this.colliderGroups.forEach((e=>{e.colliders.forEach((e=>{e.material=Be,e.renderOrder=ze}))})))}}const ke=new r.Vector3;class Fe extends xe{constructor(e,t){super(e,t)}getGizmo(){if(this._gizmo)return this._gizmo;const e=ke.copy(this._nextTail).sub(this._centerSpacePosition),t=e.length();return this._gizmo=new r.ArrowHelper(e.normalize(),this._centerSpacePosition,t,16776960,this.radius,this.radius),this._gizmo.line.renderOrder=ze,this._gizmo.cone.renderOrder=ze,this._gizmo.line.material.depthTest=!1,this._gizmo.line.material.transparent=!0,this._gizmo.cone.material.depthTest=!1,this._gizmo.cone.material.transparent=!0,this._gizmo}update(e){super.update(e),this._updateGizmo()}_updateGizmo(){if(!this._gizmo)return;const e=ke.copy(this._currentTail).sub(this._centerSpacePosition),t=e.length();this._gizmo.setDirection(e.normalize()),this._gizmo.setLength(t,this.radius,this.radius),this._gizmo.position.copy(this._centerSpacePosition)}}class He extends Le{import(e){var t;return o(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.secondaryAnimation;if(!i)return null;const r=yield this._importColliderMeshGroups(e,i),o=yield this._importSpringBoneGroupList(e,i,r);return new Ge(r,o)}))}_createSpringBone(e,t){return new Fe(e,t)}}class We extends we{constructor(e={}){e.lookAtImporter=e.lookAtImporter||new Ue,e.springBoneImporter=e.springBoneImporter||new He,super(e)}import(e,t={}){return o(this,void 0,void 0,(function*(){if(void 0===e.parser.json.extensions||void 0===e.parser.json.extensions.VRM)throw new Error("Could not find VRM extension on the GLTF");const n=e.scene;n.updateMatrixWorld(!1),n.traverse((e=>{e.isMesh&&(e.frustumCulled=!1)}));const i=(yield this._metaImporter.import(e))||void 0,r=(yield this._materialImporter.convertGLTFMaterials(e))||void 0,o=(yield this._humanoidImporter.import(e))||void 0,a=o&&(yield this._firstPersonImporter.import(e,o))||void 0,s=(yield this._blendShapeImporter.import(e))||void 0,l=a&&s&&o&&(yield this._lookAtImporter.import(e,a,s,o))||void 0;l.setupHelper&&l.setupHelper(n,t);const d=(yield this._springBoneImporter.import(e))||void 0;return d.setupHelper&&d.setupHelper(n,t),new je({scene:e.scene,meta:i,materials:r,humanoid:o,firstPerson:a,blendShapeProxy:s,lookAt:l,springBoneManager:d},t)}))}}const ze=1e4;class je extends Pe{static from(e,t={},n={}){return o(this,void 0,void 0,(function*(){const i=new We(t);return yield i.import(e,n)}))}constructor(e,t={}){super(e),t.disableBoxHelper||this.scene.add(new r.BoxHelper(this.scene)),t.disableSkeletonHelper||this.scene.add(new r.SkeletonHelper(this.scene))}update(e){super.update(e)}}e.MToonMaterial=ae,e.VRM=Pe,e.VRMBlendShapeGroup=c,e.VRMBlendShapeImporter=w,e.VRMBlendShapeProxy=L,e.VRMCurveMapper=k,e.VRMDebug=je,e.VRMFirstPerson=C,e.VRMFirstPersonImporter=I,e.VRMHumanBone=V,e.VRMHumanoid=B,e.VRMHumanoidImporter=G,e.VRMImporter=we,e.VRMLookAtApplyer=F,e.VRMLookAtBlendShapeApplyer=H,e.VRMLookAtBoneApplyer=Z,e.VRMLookAtHead=q,e.VRMLookAtImporter=J,e.VRMMaterialImporter=de,e.VRMMetaImporter=he,e.VRMRendererFirstPersonFlags=O,e.VRMSpringBone=xe,e.VRMSpringBoneDebug=Fe,e.VRMSpringBoneImporter=Le,e.VRMSpringBoneImporterDebug=He,e.VRMSpringBoneManager=Se,e.VRMUnlitMaterial=le,e.VRMUtils=Ve,e.VRM_GIZMO_RENDER_ORDER=ze,Object.defineProperty(e,"__esModule",{value:!0}),Object.assign(t,e)}));
|