incanto 0.63.0 → 0.64.0
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/bin/incanto-playtest.mjs +14 -5
- package/bin/incanto-verify.mjs +9 -4
- package/dist/2d.js +3 -3
- package/dist/3d.js +4 -4
- package/dist/{create-game-lLeITaZ5.js → create-game-B1KM6dA6.js} +3 -3
- package/dist/{create-game-viBqXUoZ.js → create-game-B746rYbr.js} +3 -3
- package/dist/{environment-presets-QR7_75KJ.js → environment-presets-D2vzw583.js} +1 -1
- package/dist/{gameplay-CuqoHHUB.js → gameplay-CLgFdkh5.js} +32 -1
- package/dist/gameplay.d.ts +23 -0
- package/dist/gameplay.js +1 -1
- package/dist/index.js +2 -2
- package/dist/{physics-2d-CllJXlic.js → physics-2d-BPJcJRRP.js} +4 -4
- package/dist/{physics-3d-BL_pFJ19.js → physics-3d-BOO58xzw.js} +2 -2
- package/dist/react.js +1 -1
- package/dist/{register-1cKM8DEj.js → register-dGsbnJ87.js} +1 -1
- package/dist/{replay-Bhdntkvq.js → replay-DKRmiVjk.js} +40 -0
- package/dist/{src-BlV9Sv4m.js → src-DEWy2qpb.js} +1 -1
- package/dist/{test-Ct1_zf5S.js → test-Ccob3X5i.js} +8 -8
- package/dist/test.js +2 -2
- package/dist/vite.js +2 -2
- package/editor/assets/{agent8-CLZXBRoM.js → agent8-Di-UEn5O.js} +1 -1
- package/editor/assets/{debug-eaSKFAKW.js → debug-DWztJ5_y.js} +1 -1
- package/editor/assets/{index-D66AuRwG.js → index-fct4H89G.js} +50 -50
- package/editor/index.html +1 -1
- package/package.json +1 -1
- package/skills/incanto-gameplay-behaviors.md +27 -5
- package/skills/incanto-node-reference.md +1 -1
- package/skills/incanto-physics-and-input.md +40 -8
- package/skills/incanto-your-first-game.md +18 -5
- package/templates-app/beacon-isle-3d/package.json +1 -1
- package/templates-app/platformer-2d/package.json +1 -1
- package/templates-app/star-survivor/package.json +1 -1
- package/templates-app/tps-3d/PROJECT/Requirements.md +3 -1
- package/templates-app/tps-3d/index.html +3 -1
- package/templates-app/tps-3d/package.json +1 -1
- package/templates-app/tps-3d/src/behaviors.ts +4 -2
- package/templates-app/village-quest-3d/package.json +1 -1
- package/templates-app/village-quest-3d/src/grove.scene.json +6 -2
- package/templates-app/village-quest-3d/src/village.scene.json +12 -4
|
@@ -4,7 +4,7 @@ import{t as e}from"./GameServer-C56iOUgF.js";(function(){let e=document.createEl
|
|
|
4
4
|
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
5
5
|
}`,Ed=`void main() {
|
|
6
6
|
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
|
|
7
|
-
}`,Dd=class extends Ll{constructor(e){super(),this.isShaderMaterial=!0,this.type=`ShaderMaterial`,this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=Td,this.fragmentShader=Ed,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=yd(e.uniforms),this.uniformsGroups=Sd(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let n in this.uniforms){let r=this.uniforms[n].value;r&&r.isTexture?t.uniforms[n]={type:`t`,value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[n]={type:`c`,value:r.getHex()}:r&&r.isVector2?t.uniforms[n]={type:`v2`,value:r.toArray()}:r&&r.isVector3?t.uniforms[n]={type:`v3`,value:r.toArray()}:r&&r.isVector4?t.uniforms[n]={type:`v4`,value:r.toArray()}:r&&r.isMatrix3?t.uniforms[n]={type:`m3`,value:r.toArray()}:r&&r.isMatrix4?t.uniforms[n]={type:`m4`,value:r.toArray()}:t.uniforms[n]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let e in this.extensions)this.extensions[e]===!0&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}},Od=class extends Dd{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type=`RawShaderMaterial`}},kd=class extends Ll{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type=`MeshStandardMaterial`,this.defines={STANDARD:``},this.color=new q(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new q(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new H(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new cc,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:``},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Ad=class extends kd{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:``,PHYSICAL:``},this.type=`MeshPhysicalMaterial`,this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new H(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return ls(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new q(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new q(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new q(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:``,PHYSICAL:``},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}},jd=class extends Ll{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type=`MeshDepthMaterial`,this.depthPacking=Io,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},Md=class extends Ll{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type=`MeshDistanceMaterial`,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}};function Nd(e,t){return!e||e.constructor===t?e:typeof t.BYTES_PER_ELEMENT==`number`?new t(e):Array.prototype.slice.call(e)}function Pd(e){function t(t,n){return e[t]-e[n]}let n=e.length,r=Array(n);for(let e=0;e!==n;++e)r[e]=e;return r.sort(t),r}function Fd(e,t,n){let r=e.length,i=new e.constructor(r);for(let a=0,o=0;o!==r;++a){let r=n[a]*t;for(let n=0;n!==t;++n)i[o++]=e[r+n]}return i}function Id(e,t,n,r){let i=1,a=e[0];for(;a!==void 0&&a[r]===void 0;)a=e[i++];if(a===void 0)return;let o=a[r];if(o!==void 0)if(Array.isArray(o))do o=a[r],o!==void 0&&(t.push(a.time),n.push(...o)),a=e[i++];while(a!==void 0);else if(o.toArray!==void 0)do o=a[r],o!==void 0&&(t.push(a.time),o.toArray(n,n.length)),a=e[i++];while(a!==void 0);else do o=a[r],o!==void 0&&(t.push(a.time),n.push(o)),a=e[i++];while(a!==void 0)}var Ld=class{constructor(e,t,n,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r===void 0?new t.constructor(n):r,this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,r=t[n],i=t[n-1];validate_interval:{seek:{let a;linear_scan:{forward_scan:if(!(e<r)){for(let a=n+2;;){if(r===void 0){if(e<i)break forward_scan;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(i=r,r=t[++n],e<r)break seek}a=t.length;break linear_scan}if(!(e>=i)){let o=t[1];e<o&&(n=2,i=o);for(let a=n-2;;){if(i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===a)break;if(r=i,i=t[--n-1],e>=i)break seek}a=n,n=0;break linear_scan}break validate_interval}for(;n<a;){let r=n+a>>>1;e<t[r]?a=r:n=r+1}if(r=t[n],i=t[n-1],i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(r===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,i,r)}return this.interpolate_(n,i,e,r)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r;for(let e=0;e!==r;++e)t[e]=n[i+e];return t}interpolate_(){throw Error(`call to abstract method`)}intervalChanged_(){}},Rd=class extends Ld{constructor(e,t,n,r){super(e,t,n,r),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:jo,endingEnd:jo}}intervalChanged_(e,t,n){let r=this.parameterPositions,i=e-2,a=e+1,o=r[i],s=r[a];if(o===void 0)switch(this.getSettings_().endingStart){case Mo:i=e,o=2*t-n;break;case No:i=r.length-2,o=t+r[i]-r[i+1];break;default:i=e,o=n}if(s===void 0)switch(this.getSettings_().endingEnd){case Mo:a=e,s=2*n-t;break;case No:a=1,s=n+r[1]-r[0];break;default:a=e-1,s=t}let c=(n-t)*.5,l=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(s-n),this._offsetPrev=i*l,this._offsetNext=a*l}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,p=(n-t)/(r-t),m=p*p,h=m*p,g=-d*h+2*d*m-d*p,_=(1+d)*h+(-1.5-2*d)*m+(-.5+d)*p+1,v=(-1-f)*h+(1.5+f)*m+.5*p,y=f*h-f*m;for(let e=0;e!==o;++e)i[e]=g*a[l+e]+_*a[c+e]+v*a[s+e]+y*a[u+e];return i}},zd=class extends Ld{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=(n-t)/(r-t),u=1-l;for(let e=0;e!==o;++e)i[e]=a[c+e]*u+a[s+e]*l;return i}},Bd=class extends Ld{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e){return this.copySampleValue_(e-1)}},Vd=class extends Ld{interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this.settings||this.DefaultSettings_,u=l.inTangents,d=l.outTangents;if(!u||!d){let e=(n-t)/(r-t),l=1-e;for(let t=0;t!==o;++t)i[t]=a[c+t]*l+a[s+t]*e;return i}let f=o*2,p=e-1;for(let l=0;l!==o;++l){let o=a[c+l],m=a[s+l],h=p*f+l*2,g=d[h],_=d[h+1],v=e*f+l*2,y=u[v],b=u[v+1],x=(n-t)/(r-t),S,C,w,T,E;for(let e=0;e<8;e++){S=x*x,C=S*x,w=1-x,T=w*w,E=T*w;let e=E*t+3*T*x*g+3*w*S*y+C*r-n;if(Math.abs(e)<1e-10)break;let i=3*T*(g-t)+6*w*x*(y-g)+3*S*(r-y);if(Math.abs(i)<1e-10)break;x-=e/i,x=Math.max(0,Math.min(1,x))}i[l]=E*o+3*T*x*_+3*w*S*b+C*m}return i}},Hd=class{constructor(e,t,n,r){if(e===void 0)throw Error(`THREE.KeyframeTrack: track name is undefined`);if(t===void 0||t.length===0)throw Error(`THREE.KeyframeTrack: no keyframes in track named `+e);this.name=e,this.times=Nd(t,this.TimeBufferType),this.values=Nd(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:Nd(e.times,Array),values:Nd(e.values,Array)};let t=e.getInterpolation();t!==e.DefaultInterpolation&&(n.interpolation=t)}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new Bd(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new zd(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Rd(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodBezier(e){let t=new Vd(this.times,this.values,this.getValueSize(),e);return this.settings&&(t.settings=this.settings),t}setInterpolation(e){let t;switch(e){case Do:t=this.InterpolantFactoryMethodDiscrete;break;case Oo:t=this.InterpolantFactoryMethodLinear;break;case ko:t=this.InterpolantFactoryMethodSmooth;break;case Ao:t=this.InterpolantFactoryMethodBezier;break}if(t===void 0){let t=`unsupported interpolation for `+this.ValueTypeName+` keyframe track named `+this.name;if(this.createInterpolant===void 0)if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(t);return B(`KeyframeTrack:`,t),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return Do;case this.InterpolantFactoryMethodLinear:return Oo;case this.InterpolantFactoryMethodSmooth:return ko;case this.InterpolantFactoryMethodBezier:return Ao}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]*=e}return this}trim(e,t){let n=this.times,r=n.length,i=0,a=r-1;for(;i!==r&&n[i]<e;)++i;for(;a!==-1&&n[a]>t;)--a;if(++a,i!==0||a!==r){i>=a&&(a=Math.max(a,1),i=a-1);let e=this.getValueSize();this.times=n.slice(i,a),this.values=this.values.slice(i*e,a*e)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(V(`KeyframeTrack: Invalid value size in track.`,this),e=!1);let n=this.times,r=this.values,i=n.length;i===0&&(V(`KeyframeTrack: Track is empty.`,this),e=!1);let a=null;for(let t=0;t!==i;t++){let r=n[t];if(typeof r==`number`&&isNaN(r)){V(`KeyframeTrack: Time is not a valid number.`,this,t,r),e=!1;break}if(a!==null&&a>r){V(`KeyframeTrack: Out of order keys.`,this,t,r,a),e=!1;break}a=r}if(r!==void 0&&qo(r))for(let t=0,n=r.length;t!==n;++t){let n=r[t];if(isNaN(n)){V(`KeyframeTrack: Value is not a valid number.`,this,t,n),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),r=this.getInterpolation()===ko,i=e.length-1,a=1;for(let o=1;o<i;++o){let i=!1,s=e[o];if(s!==e[o+1]&&(o!==1||s!==e[0]))if(r)i=!0;else{let e=o*n,r=e-n,a=e+n;for(let o=0;o!==n;++o){let n=t[e+o];if(n!==t[r+o]||n!==t[a+o]){i=!0;break}}}if(i){if(o!==a){e[a]=e[o];let r=o*n,i=a*n;for(let e=0;e!==n;++e)t[i+e]=t[r+e]}++a}}if(i>0){e[a]=e[i];for(let e=i*n,r=a*n,o=0;o!==n;++o)t[r+o]=t[e+o];++a}return a===e.length?(this.times=e,this.values=t):(this.times=e.slice(0,a),this.values=t.slice(0,a*n)),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,r}};Hd.prototype.ValueTypeName=``,Hd.prototype.TimeBufferType=Float32Array,Hd.prototype.ValueBufferType=Float32Array,Hd.prototype.DefaultInterpolation=Oo;var Ud=class extends Hd{constructor(e,t,n){super(e,t,n)}};Ud.prototype.ValueTypeName=`bool`,Ud.prototype.ValueBufferType=Array,Ud.prototype.DefaultInterpolation=Do,Ud.prototype.InterpolantFactoryMethodLinear=void 0,Ud.prototype.InterpolantFactoryMethodSmooth=void 0;var Wd=class extends Hd{constructor(e,t,n,r){super(e,t,n,r)}};Wd.prototype.ValueTypeName=`color`;var Gd=class extends Hd{constructor(e,t,n,r){super(e,t,n,r)}};Gd.prototype.ValueTypeName=`number`;var Kd=class extends Ld{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=(n-t)/(r-t),c=e*o;for(let e=c+o;c!==e;c+=4)U.slerpFlat(i,0,a,c-o,a,c,s);return i}},qd=class extends Hd{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new Kd(this.times,this.values,this.getValueSize(),e)}};qd.prototype.ValueTypeName=`quaternion`,qd.prototype.InterpolantFactoryMethodSmooth=void 0;var Jd=class extends Hd{constructor(e,t,n){super(e,t,n)}};Jd.prototype.ValueTypeName=`string`,Jd.prototype.ValueBufferType=Array,Jd.prototype.DefaultInterpolation=Do,Jd.prototype.InterpolantFactoryMethodLinear=void 0,Jd.prototype.InterpolantFactoryMethodSmooth=void 0;var Yd=class extends Hd{constructor(e,t,n,r){super(e,t,n,r)}};Yd.prototype.ValueTypeName=`vector`;var Xd=class{constructor(e=``,t=-1,n=[],r=Po){this.name=e,this.tracks=n,this.duration=t,this.blendMode=r,this.uuid=cs(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){let t=[],n=e.tracks,r=1/(e.fps||1);for(let e=0,i=n.length;e!==i;++e)t.push(Qd(n[e]).scale(r));let i=new this(e.name,e.duration,t,e.blendMode);return i.uuid=e.uuid,i.userData=JSON.parse(e.userData||`{}`),i}static toJSON(e){let t=[],n=e.tracks,r={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let e=0,r=n.length;e!==r;++e)t.push(Hd.toJSON(n[e]));return r}static CreateFromMorphTargetSequence(e,t,n,r){let i=t.length,a=[];for(let e=0;e<i;e++){let o=[],s=[];o.push((e+i-1)%i,e,(e+1)%i),s.push(0,1,0);let c=Pd(o);o=Fd(o,1,c),s=Fd(s,1,c),!r&&o[0]===0&&(o.push(i),s.push(s[0])),a.push(new Gd(`.morphTargetInfluences[`+t[e].name+`]`,o,s).scale(1/n))}return new this(e,-1,a)}static findByName(e,t){let n=e;if(!Array.isArray(e)){let t=e;n=t.geometry&&t.geometry.animations||t.animations}for(let e=0;e<n.length;e++)if(n[e].name===t)return n[e];return null}static CreateClipsFromMorphTargetSequences(e,t,n){let r={},i=/^([\w-]*?)([\d]+)$/;for(let t=0,n=e.length;t<n;t++){let n=e[t],a=n.name.match(i);if(a&&a.length>1){let e=a[1],t=r[e];t||(r[e]=t=[]),t.push(n)}}let a=[];for(let e in r)a.push(this.CreateFromMorphTargetSequence(e,r[e],t,n));return a}static parseAnimation(e,t){if(B(`AnimationClip: parseAnimation() is deprecated and will be removed with r185`),!e)return V(`AnimationClip: No animation in JSONLoader data.`),null;let n=function(e,t,n,r,i){if(n.length!==0){let a=[],o=[];Id(n,a,o,r),a.length!==0&&i.push(new e(t,a,o))}},r=[],i=e.name||`default`,a=e.fps||30,o=e.blendMode,s=e.length||-1,c=e.hierarchy||[];for(let e=0;e<c.length;e++){let i=c[e].keys;if(!(!i||i.length===0))if(i[0].morphTargets){let e={},t;for(t=0;t<i.length;t++)if(i[t].morphTargets)for(let n=0;n<i[t].morphTargets.length;n++)e[i[t].morphTargets[n]]=-1;for(let n in e){let e=[],a=[];for(let r=0;r!==i[t].morphTargets.length;++r){let r=i[t];e.push(r.time),a.push(+(r.morphTarget===n))}r.push(new Gd(`.morphTargetInfluence[`+n+`]`,e,a))}s=e.length*a}else{let a=`.bones[`+t[e].name+`]`;n(Yd,a+`.position`,i,`pos`,r),n(qd,a+`.quaternion`,i,`rot`,r),n(Yd,a+`.scale`,i,`scl`,r)}}return r.length===0?null:new this(i,s,r,o)}resetDuration(){let e=this.tracks,t=0;for(let n=0,r=e.length;n!==r;++n){let e=this.tracks[n];t=Math.max(t,e.times[e.times.length-1])}return this.duration=t,this}trim(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].trim(0,this.duration);return this}validate(){let e=!0;for(let t=0;t<this.tracks.length;t++)e&&=this.tracks[t].validate();return e}optimize(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].optimize();return this}clone(){let e=[];for(let t=0;t<this.tracks.length;t++)e.push(this.tracks[t].clone());let t=new this.constructor(this.name,this.duration,e,this.blendMode);return t.userData=JSON.parse(JSON.stringify(this.userData)),t}toJSON(){return this.constructor.toJSON(this)}};function Zd(e){switch(e.toLowerCase()){case`scalar`:case`double`:case`float`:case`number`:case`integer`:return Gd;case`vector`:case`vector2`:case`vector3`:case`vector4`:return Yd;case`color`:return Wd;case`quaternion`:return qd;case`bool`:case`boolean`:return Ud;case`string`:return Jd}throw Error(`THREE.KeyframeTrack: Unsupported typeName: `+e)}function Qd(e){if(e.type===void 0)throw Error(`THREE.KeyframeTrack: track type undefined, can not parse`);let t=Zd(e.type);if(e.times===void 0){let t=[],n=[];Id(e.keys,t,n,`value`),e.times=t,e.values=n}return t.parse===void 0?new t(e.name,e.times,e.values,e.interpolation):t.parse(e)}var $d={enabled:!1,files:{},add:function(e,t){this.enabled!==!1&&(ef(e)||(this.files[e]=t))},get:function(e){if(this.enabled!==!1&&!ef(e))return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};function ef(e){try{let t=e.slice(e.indexOf(`:`)+1);return new URL(t).protocol===`blob:`}catch{return!1}}var tf=new class{constructor(e,t,n){let r=this,i=!1,a=0,o=0,s,c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this._abortController=null,this.itemStart=function(e){o++,i===!1&&r.onStart!==void 0&&r.onStart(e,a,o),i=!0},this.itemEnd=function(e){a++,r.onProgress!==void 0&&r.onProgress(e,a,o),a===o&&(i=!1,r.onLoad!==void 0&&r.onLoad())},this.itemError=function(e){r.onError!==void 0&&r.onError(e)},this.resolveURL=function(e){return s?s(e):e},this.setURLModifier=function(e){return s=e,this},this.addHandler=function(e,t){return c.push(e,t),this},this.removeHandler=function(e){let t=c.indexOf(e);return t!==-1&&c.splice(t,2),this},this.getHandler=function(e){for(let t=0,n=c.length;t<n;t+=2){let n=c[t],r=c[t+1];if(n.global&&(n.lastIndex=0),n.test(e))return r}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){return this._abortController||=new AbortController,this._abortController}},nf=class{constructor(e){this.manager=e===void 0?tf:e,this.crossOrigin=`anonymous`,this.withCredentials=!1,this.path=``,this.resourcePath=``,this.requestHeader={},typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}load(){}loadAsync(e,t){let n=this;return new Promise(function(r,i){n.load(e,r,t,i)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}abort(){return this}};nf.DEFAULT_MATERIAL_NAME=`__DEFAULT`;var rf={},af=class extends Error{constructor(e,t){super(e),this.response=t}},of=class extends nf{constructor(e){super(e),this.mimeType=``,this.responseType=``,this._abortController=new AbortController}load(e,t,n,r){e===void 0&&(e=``),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=$d.get(`file:${e}`);if(i!==void 0){this.manager.itemStart(e),setTimeout(()=>{t&&t(i),this.manager.itemEnd(e)},0);return}if(rf[e]!==void 0){rf[e].push({onLoad:t,onProgress:n,onError:r});return}rf[e]=[],rf[e].push({onLoad:t,onProgress:n,onError:r});let a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?`include`:`same-origin`,signal:typeof AbortSignal.any==`function`?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,s=this.responseType;fetch(a).then(t=>{if(t.status===200||t.status===0){if(t.status===0&&B(`FileLoader: HTTP Status 0 received.`),typeof ReadableStream>`u`||t.body===void 0||t.body.getReader===void 0)return t;let n=rf[e],r=t.body.getReader(),i=t.headers.get(`X-File-Size`)||t.headers.get(`Content-Length`),a=i?parseInt(i):0,o=a!==0,s=0,c=new ReadableStream({start(e){t();function t(){r.read().then(({done:r,value:i})=>{if(r)e.close();else{s+=i.byteLength;let r=new ProgressEvent(`progress`,{lengthComputable:o,loaded:s,total:a});for(let e=0,t=n.length;e<t;e++){let t=n[e];t.onProgress&&t.onProgress(r)}e.enqueue(i),t()}},t=>{e.error(t)})}}});return new Response(c)}else throw new af(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`,t)}).then(e=>{switch(s){case`arraybuffer`:return e.arrayBuffer();case`blob`:return e.blob();case`document`:return e.text().then(e=>new DOMParser().parseFromString(e,o));case`json`:return e.json();default:if(o===``)return e.text();{let t=/charset="?([^;"\s]*)"?/i.exec(o),n=t&&t[1]?t[1].toLowerCase():void 0,r=new TextDecoder(n);return e.arrayBuffer().then(e=>r.decode(e))}}}).then(t=>{$d.add(`file:${e}`,t);let n=rf[e];delete rf[e];for(let e=0,r=n.length;e<r;e++){let r=n[e];r.onLoad&&r.onLoad(t)}}).catch(t=>{let n=rf[e];if(n===void 0)throw this.manager.itemError(e),t;delete rf[e];for(let e=0,r=n.length;e<r;e++){let r=n[e];r.onError&&r.onError(t)}this.manager.itemError(e)}).finally(()=>{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},sf=new WeakMap,cf=class extends nf{constructor(e){super(e)}load(e,t,n,r){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=this,a=$d.get(`image:${e}`);if(a!==void 0){if(a.complete===!0)i.manager.itemStart(e),setTimeout(function(){t&&t(a),i.manager.itemEnd(e)},0);else{let e=sf.get(a);e===void 0&&(e=[],sf.set(a,e)),e.push({onLoad:t,onError:r})}return a}let o=Jo(`img`);function s(){l(),t&&t(this);let n=sf.get(this)||[];for(let e=0;e<n.length;e++){let t=n[e];t.onLoad&&t.onLoad(this)}sf.delete(this),i.manager.itemEnd(e)}function c(t){l(),r&&r(t),$d.remove(`image:${e}`);let n=sf.get(this)||[];for(let e=0;e<n.length;e++){let r=n[e];r.onError&&r.onError(t)}sf.delete(this),i.manager.itemError(e),i.manager.itemEnd(e)}function l(){o.removeEventListener(`load`,s,!1),o.removeEventListener(`error`,c,!1)}return o.addEventListener(`load`,s,!1),o.addEventListener(`error`,c,!1),e.slice(0,5)!==`data:`&&this.crossOrigin!==void 0&&(o.crossOrigin=this.crossOrigin),$d.add(`image:${e}`,o),i.manager.itemStart(e),o.src=e,o}},lf=class extends nf{constructor(e){super(e)}load(e,t,n,r){let i=this,a=new vu,o=new of(this.manager);return o.setResponseType(`arraybuffer`),o.setRequestHeader(this.requestHeader),o.setPath(this.path),o.setWithCredentials(i.withCredentials),o.load(e,function(e){let n;try{n=i.parse(e)}catch(e){r===void 0?V(e):r(e);return}n.image===void 0?n.data!==void 0&&(a.image.width=n.width,a.image.height=n.height,a.image.data=n.data):a.image=n.image,a.wrapS=n.wrapS===void 0?ua:n.wrapS,a.wrapT=n.wrapT===void 0?ua:n.wrapT,a.magFilter=n.magFilter===void 0?ha:n.magFilter,a.minFilter=n.minFilter===void 0?ha:n.minFilter,a.anisotropy=n.anisotropy===void 0?1:n.anisotropy,n.colorSpace!==void 0&&(a.colorSpace=n.colorSpace),n.flipY!==void 0&&(a.flipY=n.flipY),n.format!==void 0&&(a.format=n.format),n.type!==void 0&&(a.type=n.type),n.mipmaps!==void 0&&(a.mipmaps=n.mipmaps,a.minFilter=_a),n.mipmapCount===1&&(a.minFilter=ha),n.generateMipmaps!==void 0&&(a.generateMipmaps=n.generateMipmaps),a.needsUpdate=!0,t&&t(a,n)},n,r),a}},uf=class extends nf{constructor(e){super(e)}load(e,t,n,r){let i=new qs,a=new cf(this.manager);return a.setCrossOrigin(this.crossOrigin),a.setPath(this.path),a.load(e,function(e){i.image=e,i.needsUpdate=!0,t!==void 0&&t(i)},n,r),i}},df=class extends Tc{constructor(e,t=1){super(),this.isLight=!0,this.type=`Light`,this.color=new q(e),this.intensity=t}dispose(){this.dispatchEvent({type:`dispose`})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){let t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}},ff=new K,pf=new W,mf=new W,hf=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new H(512,512),this.mapType=va,this.map=null,this.mapPass=null,this.matrix=new K,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Ru,this._frameExtents=new H(1,1),this._viewportCount=1,this._viewports=[new Js(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,n=this.matrix;pf.setFromMatrixPosition(e.matrixWorld),t.position.copy(pf),mf.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(mf),t.updateMatrixWorld(),ff.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(ff,t.coordinateSystem,t.reversedDepth),t.coordinateSystem===2001||t.reversedDepth?n.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(ff)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this.biasNode=e.biasNode,this}clone(){return new this.constructor().copy(this)}toJSON(){let e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}},gf=new W,_f=new U,vf=new W,yf=class extends Tc{constructor(){super(),this.isCamera=!0,this.type=`Camera`,this.matrixWorldInverse=new K,this.projectionMatrix=new K,this.projectionMatrixInverse=new K,this.coordinateSystem=Go,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorld.decompose(gf,_f,vf),vf.x===1&&vf.y===1&&vf.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(gf,_f,vf.set(1,1,1)).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorld.decompose(gf,_f,vf),vf.x===1&&vf.y===1&&vf.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(gf,_f,vf.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}},bf=new W,xf=new H,Sf=new H,Cf=class extends yf{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type=`PerspectiveCamera`,this.fov=e,this.zoom=1,this.near=n,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=ss*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(os*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return ss*2*Math.atan(Math.tan(os*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){bf.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(bf.x,bf.y).multiplyScalar(-e/bf.z),bf.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(bf.x,bf.y).multiplyScalar(-e/bf.z)}getViewSize(e,t){return this.getViewBounds(e,xf,Sf),t.subVectors(Sf,xf)}setViewOffset(e,t,n,r,i,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(os*.5*this.fov)/this.zoom,n=2*t,r=this.aspect*n,i=-.5*r,a=this.view;if(this.view!==null&&this.view.enabled){let e=a.fullWidth,o=a.fullHeight;i+=a.offsetX*r/e,t-=a.offsetY*n/o,r*=a.width/e,n*=a.height/o}let o=this.filmOffset;o!==0&&(i+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+r,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},wf=class extends hf{constructor(){super(new Cf(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){let t=this.camera,n=ss*2*e.angle*this.focus,r=this.mapSize.width/this.mapSize.height*this.aspect,i=e.distance||t.far;(n!==t.fov||r!==t.aspect||i!==t.far)&&(t.fov=n,t.aspect=r,t.far=i,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}},Tf=class extends df{constructor(e,t,n=0,r=Math.PI/3,i=0,a=2){super(e,t),this.isSpotLight=!0,this.type=`SpotLight`,this.position.copy(Tc.DEFAULT_UP),this.updateMatrix(),this.target=new Tc,this.distance=n,this.angle=r,this.penumbra=i,this.decay=a,this.map=null,this.shadow=new wf}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.map=e.map,this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.distance=this.distance,t.object.angle=this.angle,t.object.decay=this.decay,t.object.penumbra=this.penumbra,t.object.target=this.target.uuid,this.map&&this.map.isTexture&&(t.object.map=this.map.toJSON(e).uuid),t.object.shadow=this.shadow.toJSON(),t}},Ef=class extends hf{constructor(){super(new Cf(90,1,.5,500)),this.isPointLightShadow=!0}},Df=class extends df{constructor(e,t,n=0,r=2){super(e,t),this.isPointLight=!0,this.type=`PointLight`,this.distance=n,this.decay=r,this.shadow=new Ef}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}},Of=class extends yf{constructor(e=-1,t=1,n=1,r=-1,i=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type=`OrthographicCamera`,this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=r,this.near=i,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,r,i,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,r=(this.top+this.bottom)/2,i=n-e,a=n+e,o=r+t,s=r-t;if(this.view!==null&&this.view.enabled){let e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;i+=e*this.view.offsetX,a=i+e*this.view.width,o-=t*this.view.offsetY,s=o-t*this.view.height}this.projectionMatrix.makeOrthographic(i,a,o,s,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},kf=class extends hf{constructor(){super(new Of(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},Af=class extends df{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type=`DirectionalLight`,this.position.copy(Tc.DEFAULT_UP),this.updateMatrix(),this.target=new Tc,this.shadow=new kf}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}},jf=class extends df{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type=`AmbientLight`}},Mf=class{static extractUrlBase(e){let t=e.lastIndexOf(`/`);return t===-1?`./`:e.slice(0,t+1)}static resolveURL(e,t){return typeof e!=`string`||e===``?``:(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,`$1`)),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}},Nf=new WeakMap,Pf=class extends nf{constructor(e){super(e),this.isImageBitmapLoader=!0,typeof createImageBitmap>`u`&&B(`ImageBitmapLoader: createImageBitmap() not supported.`),typeof fetch>`u`&&B(`ImageBitmapLoader: fetch() not supported.`),this.options={premultiplyAlpha:`none`},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,n,r){e===void 0&&(e=``),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=this,a=$d.get(`image-bitmap:${e}`);if(a!==void 0){if(i.manager.itemStart(e),a.then){a.then(n=>{Nf.has(a)===!0?(r&&r(Nf.get(a)),i.manager.itemError(e),i.manager.itemEnd(e)):(t&&t(n),i.manager.itemEnd(e))});return}setTimeout(function(){t&&t(a),i.manager.itemEnd(e)},0);return}let o={};o.credentials=this.crossOrigin===`anonymous`?`same-origin`:`include`,o.headers=this.requestHeader,o.signal=typeof AbortSignal.any==`function`?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;let s=fetch(e,o).then(function(e){return e.blob()}).then(function(e){return createImageBitmap(e,Object.assign(i.options,{colorSpaceConversion:`none`}))}).then(function(n){$d.add(`image-bitmap:${e}`,n),t&&t(n),i.manager.itemEnd(e)}).catch(function(t){r&&r(t),Nf.set(s,t),$d.remove(`image-bitmap:${e}`),i.manager.itemError(e),i.manager.itemEnd(e)});$d.add(`image-bitmap:${e}`,s),i.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},Ff=-90,If=1,Lf=class extends Tc{constructor(e,t,n){super(),this.type=`CubeCamera`,this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new Cf(Ff,If,e,t);r.layers=this.layers,this.add(r);let i=new Cf(Ff,If,e,t);i.layers=this.layers,this.add(i);let a=new Cf(Ff,If,e,t);a.layers=this.layers,this.add(a);let o=new Cf(Ff,If,e,t);o.layers=this.layers,this.add(o);let s=new Cf(Ff,If,e,t);s.layers=this.layers,this.add(s);let c=new Cf(Ff,If,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,r,i,a,o,s]=t;for(let e of t)this.remove(e);if(e===2e3)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),i.up.set(0,0,-1),i.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),s.up.set(0,1,0),s.lookAt(0,0,-1);else if(e===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),i.up.set(0,0,1),i.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),s.up.set(0,-1,0),s.lookAt(0,0,-1);else throw Error(`THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: `+e);for(let e of t)this.add(e),e.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[i,a,o,s,c,l]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;let m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let h=!1;h=e.isWebGLRenderer===!0?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(n,0,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,i),e.setRenderTarget(n,1,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,2,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,3,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,4,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(u,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}},Rf=class extends Cf{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},zf=class{constructor(e,t,n){this.binding=e,this.valueSize=n;let r,i,a;switch(t){case`quaternion`:r=this._slerp,i=this._slerpAdditive,a=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(n*6),this._workIndex=5;break;case`string`:case`bool`:r=this._select,i=this._select,a=this._setAdditiveIdentityOther,this.buffer=Array(n*5);break;default:r=this._lerp,i=this._lerpAdditive,a=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(n*5)}this._mixBufferRegion=r,this._mixBufferRegionAdditive=i,this._setIdentity=a,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){let n=this.buffer,r=this.valueSize,i=e*r+r,a=this.cumulativeWeight;if(a===0){for(let e=0;e!==r;++e)n[i+e]=n[e];a=t}else{a+=t;let e=t/a;this._mixBufferRegion(n,i,0,e,r)}this.cumulativeWeight=a}accumulateAdditive(e){let t=this.buffer,n=this.valueSize,r=n*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,r,0,e,n),this.cumulativeWeightAdditive+=e}apply(e){let t=this.valueSize,n=this.buffer,r=e*t+t,i=this.cumulativeWeight,a=this.cumulativeWeightAdditive,o=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,i<1){let e=t*this._origIndex;this._mixBufferRegion(n,r,e,1-i,t)}a>0&&this._mixBufferRegionAdditive(n,r,this._addIndex*t,1,t);for(let e=t,i=t+t;e!==i;++e)if(n[e]!==n[e+t]){o.setValue(n,r);break}}saveOriginalState(){let e=this.binding,t=this.buffer,n=this.valueSize,r=n*this._origIndex;e.getValue(t,r);for(let e=n,i=r;e!==i;++e)t[e]=t[r+e%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){let e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n<t;n++)this.buffer[n]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){let e=this._origIndex*this.valueSize,t=this._addIndex*this.valueSize;for(let n=0;n<this.valueSize;n++)this.buffer[t+n]=this.buffer[e+n]}_select(e,t,n,r,i){if(r>=.5)for(let r=0;r!==i;++r)e[t+r]=e[n+r]}_slerp(e,t,n,r){U.slerpFlat(e,t,e,t,e,n,r)}_slerpAdditive(e,t,n,r,i){let a=this._workIndex*i;U.multiplyQuaternionsFlat(e,a,e,t,e,n),U.slerpFlat(e,t,e,t,e,a,r)}_lerp(e,t,n,r,i){let a=1-r;for(let o=0;o!==i;++o){let i=t+o;e[i]=e[i]*a+e[n+o]*r}}_lerpAdditive(e,t,n,r,i){for(let a=0;a!==i;++a){let i=t+a;e[i]=e[i]+e[n+a]*r}}},Bf=`\\[\\]\\.:\\/`,Vf=RegExp(`[\\[\\]\\.:\\/]`,`g`),Hf=`[^\\[\\]\\.:\\/]`,Uf=`[^`+Bf.replace(`\\.`,``)+`]`,Wf=`((?:WC+[\\/:])*)`.replace(`WC`,Hf),Gf=`(WCOD+)?`.replace(`WCOD`,Uf),Kf=`(?:\\.(WC+)(?:\\[(.+)\\])?)?`.replace(`WC`,Hf),qf=`\\.(WC+)(?:\\[(.+)\\])?`.replace(`WC`,Hf),Jf=RegExp(`^`+Wf+Gf+Kf+qf+`$`),Yf=[`material`,`materials`,`bones`,`map`],Xf=class{constructor(e,t,n){let r=n||Zf.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,i=n.length;r!==i;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},Zf=class e{constructor(t,n,r){this.path=n,this.parsedPath=r||e.parseTrackName(n),this.node=e.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,n,r){return t&&t.isAnimationObjectGroup?new e.Composite(t,n,r):new e(t,n,r)}static sanitizeNodeName(e){return e.replace(/\s/g,`_`).replace(Vf,``)}static parseTrackName(e){let t=Jf.exec(e);if(t===null)throw Error(`PropertyBinding: Cannot parse trackName: `+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(`.`);if(r!==void 0&&r!==-1){let e=n.nodeName.substring(r+1);Yf.indexOf(e)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=e)}if(n.propertyName===null||n.propertyName.length===0)throw Error(`PropertyBinding: can not parse propertyName from trackName: `+e);return n}static findNode(e,t){if(t===void 0||t===``||t===`.`||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(e){for(let r=0;r<e.length;r++){let i=e[r];if(i.name===t||i.uuid===t)return i;let a=n(i.children);if(a)return a}return null},r=n(e.children);if(r)return r}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)e[t++]=n[r]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let t=this.node,n=this.parsedPath,r=n.objectName,i=n.propertyName,a=n.propertyIndex;if(t||(t=e.findNode(this.rootNode,n.nodeName),this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t){B(`PropertyBinding: No target node found for track: `+this.path+`.`);return}if(r){let e=n.objectIndex;switch(r){case`materials`:if(!t.material){V(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.materials){V(`PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.`,this);return}t=t.material.materials;break;case`bones`:if(!t.skeleton){V(`PropertyBinding: Can not bind to bones as node does not have a skeleton.`,this);return}t=t.skeleton.bones;for(let n=0;n<t.length;n++)if(t[n].name===e){e=n;break}break;case`map`:if(`map`in t){t=t.map;break}if(!t.material){V(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.map){V(`PropertyBinding: Can not bind to material.map as node.material does not have a map.`,this);return}t=t.material.map;break;default:if(t[r]===void 0){V(`PropertyBinding: Can not bind to objectName of node undefined.`,this);return}t=t[r]}if(e!==void 0){if(t[e]===void 0){V(`PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.`,this,t);return}t=t[e]}}let o=t[i];if(o===void 0){let e=n.nodeName;V(`PropertyBinding: Trying to update property for track: `+e+`.`+i+` but it wasn't found.`,t);return}let s=this.Versioning.None;this.targetObject=t,t.isMaterial===!0?s=this.Versioning.NeedsUpdate:t.isObject3D===!0&&(s=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(a!==void 0){if(i===`morphTargetInfluences`){if(!t.geometry){V(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.`,this);return}if(!t.geometry.morphAttributes){V(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.`,this);return}t.morphTargetDictionary[a]!==void 0&&(a=t.morphTargetDictionary[a])}c=this.BindingType.ArrayElement,this.resolvedProperty=o,this.propertyIndex=a}else o.fromArray!==void 0&&o.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=o):Array.isArray(o)?(c=this.BindingType.EntireArray,this.resolvedProperty=o):this.propertyName=i;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][s]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};Zf.Composite=Xf,Zf.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Zf.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},Zf.prototype.GetterByBindingType=[Zf.prototype._getValue_direct,Zf.prototype._getValue_array,Zf.prototype._getValue_arrayElement,Zf.prototype._getValue_toArray],Zf.prototype.SetterByBindingTypeAndVersioning=[[Zf.prototype._setValue_direct,Zf.prototype._setValue_direct_setNeedsUpdate,Zf.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[Zf.prototype._setValue_array,Zf.prototype._setValue_array_setNeedsUpdate,Zf.prototype._setValue_array_setMatrixWorldNeedsUpdate],[Zf.prototype._setValue_arrayElement,Zf.prototype._setValue_arrayElement_setNeedsUpdate,Zf.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[Zf.prototype._setValue_fromArray,Zf.prototype._setValue_fromArray_setNeedsUpdate,Zf.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];var Qf=class{constructor(e,t,n=null,r=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=r;let i=t.tracks,a=i.length,o=Array(a),s={endingStart:jo,endingEnd:jo};for(let e=0;e!==a;++e){let t=i[e].createInterpolant(null);o[e]=t,t.settings&&Object.assign(s,t.settings),t.settings=s}this._interpolantSettings=s,this._interpolants=o,this._propertyBindings=Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=To,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,n=!1){if(e.fadeOut(t),this.fadeIn(t),n===!0){let n=this._clip.duration,r=e._clip.duration,i=r/n,a=n/r;e.warp(1,i,t),this.warp(a,1,t)}return this}crossFadeTo(e,t,n=!1){return e.crossFadeFrom(this,t,n)}stopFading(){let e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,n){let r=this._mixer,i=r.time,a=this.timeScale,o=this._timeScaleInterpolant;o===null&&(o=r._lendControlInterpolant(),this._timeScaleInterpolant=o);let s=o.parameterPositions,c=o.sampleValues;return s[0]=i,s[1]=i+n,c[0]=e/a,c[1]=t/a,this}stopWarping(){let e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,n,r){if(!this.enabled){this._updateWeight(e);return}let i=this._startTime;if(i!==null){let r=(e-i)*n;r<0||n===0?t=0:(this._startTime=null,t=n*r)}t*=this._updateTimeScale(e);let a=this._updateTime(t),o=this._updateWeight(e);if(o>0){let e=this._interpolants,t=this._propertyBindings;switch(this.blendMode){case Fo:for(let n=0,r=e.length;n!==r;++n)e[n].evaluate(a),t[n].accumulateAdditive(o);break;case Po:default:for(let n=0,i=e.length;n!==i;++n)e[n].evaluate(a),t[n].accumulate(r,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let n=this._weightInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(this.stopFading(),r===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;let n=this._timeScaleInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,n=this.loop,r=this.time+e,i=this._loopCount,a=n===Eo;if(e===0)return i===-1?r:a&&(i&1)==1?t-r:r;if(n===2200){i===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));handle_stop:{if(r>=t)r=t;else if(r<0)r=0;else{this.time=r;break handle_stop}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=r,this._mixer.dispatchEvent({type:`finished`,action:this,direction:e<0?-1:1})}}else{if(i===-1&&(e>=0?(i=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),r>=t||r<0){let n=Math.floor(r/t);r-=t*n,i+=Math.abs(n);let o=this.repetitions-i;if(o<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,r=e>0?t:0,this.time=r,this._mixer.dispatchEvent({type:`finished`,action:this,direction:e>0?1:-1});else{if(o===1){let t=e<0;this._setEndings(t,!t,a)}else this._setEndings(!1,!1,a);this._loopCount=i,this.time=r,this._mixer.dispatchEvent({type:`loop`,action:this,loopDelta:n})}}else this._loopCount=i,this.time=r;if(a&&(i&1)==1)return t-r}return r}_setEndings(e,t,n){let r=this._interpolantSettings;n?(r.endingStart=Mo,r.endingEnd=Mo):(e?r.endingStart=this.zeroSlopeAtStart?Mo:jo:r.endingStart=No,t?r.endingEnd=this.zeroSlopeAtEnd?Mo:jo:r.endingEnd=No)}_scheduleFading(e,t,n){let r=this._mixer,i=r.time,a=this._weightInterpolant;a===null&&(a=r._lendControlInterpolant(),this._weightInterpolant=a);let o=a.parameterPositions,s=a.sampleValues;return o[0]=i,s[0]=t,o[1]=i+e,s[1]=n,this}},$f=new Float32Array(1),ep=class extends rs{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}_bindAction(e,t){let n=e._localRoot||this._root,r=e._clip.tracks,i=r.length,a=e._propertyBindings,o=e._interpolants,s=n.uuid,c=this._bindingsByRootAndName,l=c[s];l===void 0&&(l={},c[s]=l);for(let e=0;e!==i;++e){let i=r[e],c=i.name,u=l[c];if(u!==void 0)++u.referenceCount,a[e]=u;else{if(u=a[e],u!==void 0){u._cacheIndex===null&&(++u.referenceCount,this._addInactiveBinding(u,s,c));continue}let r=t&&t._propertyBindings[e].binding.parsedPath;u=new zf(Zf.create(n,c,r),i.ValueTypeName,i.getValueSize()),++u.referenceCount,this._addInactiveBinding(u,s,c),a[e]=u}o[e].resultBuffer=u.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let t=(e._localRoot||this._root).uuid,n=e._clip.uuid,r=this._actionsByClip[n];this._bindAction(e,r&&r.knownActions[0]),this._addInactiveAction(e,n,t)}let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];n.useCount++===0&&(this._lendBinding(n),n.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];--n.useCount===0&&(n.restoreOriginalState(),this._takeBackBinding(n))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){let t=e._cacheIndex;return t!==null&&t<this._nActiveActions}_addInactiveAction(e,t,n){let r=this._actions,i=this._actionsByClip,a=i[t];if(a===void 0)a={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,i[t]=a;else{let t=a.knownActions;e._byClipCacheIndex=t.length,t.push(e)}e._cacheIndex=r.length,r.push(e),a.actionByRoot[n]=e}_removeInactiveAction(e){let t=this._actions,n=t[t.length-1],r=e._cacheIndex;n._cacheIndex=r,t[r]=n,t.pop(),e._cacheIndex=null;let i=e._clip.uuid,a=this._actionsByClip,o=a[i],s=o.knownActions,c=s[s.length-1],l=e._byClipCacheIndex;c._byClipCacheIndex=l,s[l]=c,s.pop(),e._byClipCacheIndex=null;let u=o.actionByRoot,d=(e._localRoot||this._root).uuid;delete u[d],s.length===0&&delete a[i],this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];--n.referenceCount===0&&this._removeInactiveBinding(n)}}_lendAction(e){let t=this._actions,n=e._cacheIndex,r=this._nActiveActions++,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_takeBackAction(e){let t=this._actions,n=e._cacheIndex,r=--this._nActiveActions,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_addInactiveBinding(e,t,n){let r=this._bindingsByRootAndName,i=this._bindings,a=r[t];a===void 0&&(a={},r[t]=a),a[n]=e,e._cacheIndex=i.length,i.push(e)}_removeInactiveBinding(e){let t=this._bindings,n=e.binding,r=n.rootNode.uuid,i=n.path,a=this._bindingsByRootAndName,o=a[r],s=t[t.length-1],c=e._cacheIndex;s._cacheIndex=c,t[c]=s,t.pop(),delete o[i],Object.keys(o).length===0&&delete a[r]}_lendBinding(e){let t=this._bindings,n=e._cacheIndex,r=this._nActiveBindings++,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_takeBackBinding(e){let t=this._bindings,n=e._cacheIndex,r=--this._nActiveBindings,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_lendControlInterpolant(){let e=this._controlInterpolants,t=this._nActiveControlInterpolants++,n=e[t];return n===void 0&&(n=new zd(new Float32Array(2),new Float32Array(2),1,$f),n.__cacheIndex=t,e[t]=n),n}_takeBackControlInterpolant(e){let t=this._controlInterpolants,n=e.__cacheIndex,r=--this._nActiveControlInterpolants,i=t[r];e.__cacheIndex=r,t[r]=e,i.__cacheIndex=n,t[n]=i}clipAction(e,t,n){let r=t||this._root,i=r.uuid,a=typeof e==`string`?Xd.findByName(r,e):e,o=a===null?e:a.uuid,s=this._actionsByClip[o],c=null;if(n===void 0&&(n=a===null?Po:a.blendMode),s!==void 0){let e=s.actionByRoot[i];if(e!==void 0&&e.blendMode===n)return e;c=s.knownActions[0],a===null&&(a=c._clip)}if(a===null)return null;let l=new Qf(this,a,t,n);return this._bindAction(l,c),this._addInactiveAction(l,o,i),l}existingAction(e,t){let n=t||this._root,r=n.uuid,i=typeof e==`string`?Xd.findByName(n,e):e,a=i?i.uuid:e,o=this._actionsByClip[a];return o===void 0?null:o.actionByRoot[r]||null}stopAllAction(){let e=this._actions,t=this._nActiveActions;for(let n=t-1;n>=0;--n)e[n].stop();return this}update(e){e*=this.timeScale;let t=this._actions,n=this._nActiveActions,r=this.time+=e,i=Math.sign(e),a=this._accuIndex^=1;for(let o=0;o!==n;++o)t[o]._update(r,e,i,a);let o=this._bindings,s=this._nActiveBindings;for(let e=0;e!==s;++e)o[e].apply(a);return this}setTime(e){this.time=0;for(let e=0;e<this._actions.length;e++)this._actions[e].time=0;return this.update(e)}getRoot(){return this._root}uncacheClip(e){let t=this._actions,n=e.uuid,r=this._actionsByClip,i=r[n];if(i!==void 0){let e=i.knownActions;for(let n=0,r=e.length;n!==r;++n){let r=e[n];this._deactivateAction(r);let i=r._cacheIndex,a=t[t.length-1];r._cacheIndex=null,r._byClipCacheIndex=null,a._cacheIndex=i,t[i]=a,t.pop(),this._removeInactiveBindingsForAction(r)}delete r[n]}}uncacheRoot(e){let t=e.uuid,n=this._actionsByClip;for(let e in n){let r=n[e].actionByRoot[t];r!==void 0&&(this._deactivateAction(r),this._removeInactiveAction(r))}let r=this._bindingsByRootAndName[t];if(r!==void 0)for(let e in r){let t=r[e];t.restoreOriginalState(),this._removeInactiveBinding(t)}}uncacheAction(e,t){let n=this.existingAction(e,t);n!==null&&(this._deactivateAction(n),this._removeInactiveAction(n))}},tp=class{constructor(e,t,n,r,i,a=!1){this.isGLBufferAttribute=!0,this.name=``,this.buffer=e,this.type=t,this.itemSize=n,this.elementSize=r,this.count=i,this.normalized=a,this.version=0}set needsUpdate(e){e===!0&&this.version++}setBuffer(e){return this.buffer=e,this}setType(e,t){return this.type=e,this.elementSize=t,this}setItemSize(e){return this.itemSize=e,this}setCount(e){return this.count=e,this}},np=new K,rp=class{constructor(e,t,n=0,r=1/0){this.ray=new Gl(e,t),this.near=n,this.far=r,this.camera=null,this.layers=new lc,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(e,t){this.ray.set(e,t)}setFromCamera(e,t){t.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t):t.isOrthographicCamera?(this.ray.origin.set(e.x,e.y,(t.near+t.far)/(t.near-t.far)).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):V(`Raycaster: Unsupported camera type: `+t.type)}setFromXRController(e){return np.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(np),this}intersectObject(e,t=!0,n=[]){return ap(e,this,n,t),n.sort(ip),n}intersectObjects(e,t=!0,n=[]){for(let r=0,i=e.length;r<i;r++)ap(e[r],this,n,t);return n.sort(ip),n}};function ip(e,t){return e.distance-t.distance}function ap(e,t,n,r){let i=!0;if(e.layers.test(t.layers)&&e.raycast(t,n)===!1&&(i=!1),i===!0&&r===!0){let r=e.children;for(let e=0,i=r.length;e<i;e++)ap(r[e],t,n,!0)}}(class e{static{e.prototype.isMatrix2=!0}constructor(e,t,n,r){this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,n,r)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let n=0;n<4;n++)this.elements[n]=e[n+t];return this}set(e,t,n,r){let i=this.elements;return i[0]=e,i[2]=t,i[1]=n,i[3]=r,this}});var op=class extends Zu{constructor(e=1){let t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],n=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],r=new Y;r.setAttribute(`position`,new xl(t,3)),r.setAttribute(`color`,new xl(n,3));let i=new zu({vertexColors:!0,toneMapped:!1});super(r,i),this.type=`AxesHelper`}setColors(e,t,n){let r=new q,i=this.geometry.attributes.color.array;return r.set(e),r.toArray(i,0),r.toArray(i,3),r.set(t),r.toArray(i,6),r.toArray(i,9),r.set(n),r.toArray(i,12),r.toArray(i,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}};function sp(e,t,n,r){let i=cp(r);switch(n){case ja:return e*t;case Ia:return e*t/i.components*i.byteLength;case La:return e*t/i.components*i.byteLength;case Ra:return e*t*2/i.components*i.byteLength;case za:return e*t*2/i.components*i.byteLength;case Ma:return e*t*3/i.components*i.byteLength;case Na:return e*t*4/i.components*i.byteLength;case Ba:return e*t*4/i.components*i.byteLength;case Va:case Ha:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Ua:case Wa:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ka:case Ja:return Math.max(e,16)*Math.max(t,8)/4;case Ga:case qa:return Math.max(e,8)*Math.max(t,8)/2;case Ya:case Xa:case Qa:case $a:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Za:case eo:case to:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case no:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case ro:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case io:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case ao:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case oo:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case so:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case co:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case lo:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case uo:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case fo:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case po:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case mo:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case ho:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case go:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case _o:case vo:case yo:return Math.ceil(e/4)*Math.ceil(t/4)*16;case bo:case xo:return Math.ceil(e/4)*Math.ceil(t/4)*8;case So:case Co:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw Error(`Unable to determine texture byte length for ${n} format.`)}function cp(e){switch(e){case va:case ya:return{byteLength:1,components:1};case xa:case ba:case Ta:return{byteLength:2,components:1};case Ea:case Da:return{byteLength:2,components:4};case Ca:case Sa:case wa:return{byteLength:4,components:1};case ka:case Aa:return{byteLength:4,components:3}}throw Error(`Unknown texture type ${e}.`)}typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`register`,{detail:{revision:`184`}})),typeof window<`u`&&(window.__THREE__?B(`WARNING: Multiple instances of Three.js being imported.`):window.__THREE__=`184`);function lp(){let e=null,t=!1,n=null,r=null;function i(t,a){n(t,a),r=e.requestAnimationFrame(i)}return{start:function(){t!==!0&&n!==null&&e!==null&&(r=e.requestAnimationFrame(i),t=!0)},stop:function(){e!==null&&e.cancelAnimationFrame(r),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function up(e){let t=new WeakMap;function n(t,n){let r=t.array,i=t.usage,a=r.byteLength,o=e.createBuffer();e.bindBuffer(n,o),e.bufferData(n,r,i),t.onUploadCallback();let s;if(r instanceof Float32Array)s=e.FLOAT;else if(typeof Float16Array<`u`&&r instanceof Float16Array)s=e.HALF_FLOAT;else if(r instanceof Uint16Array)s=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(r instanceof Int16Array)s=e.SHORT;else if(r instanceof Uint32Array)s=e.UNSIGNED_INT;else if(r instanceof Int32Array)s=e.INT;else if(r instanceof Int8Array)s=e.BYTE;else if(r instanceof Uint8Array)s=e.UNSIGNED_BYTE;else if(r instanceof Uint8ClampedArray)s=e.UNSIGNED_BYTE;else throw Error(`THREE.WebGLAttributes: Unsupported buffer data format: `+r);return{buffer:o,type:s,bytesPerElement:r.BYTES_PER_ELEMENT,version:t.version,size:a}}function r(t,n,r){let i=n.array,a=n.updateRanges;if(e.bindBuffer(r,t),a.length===0)e.bufferSubData(r,0,i);else{a.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e<a.length;e++){let n=a[t],r=a[e];r.start<=n.start+n.count+1?n.count=Math.max(n.count,r.start+r.count-n.start):(++t,a[t]=r)}a.length=t+1;for(let t=0,n=a.length;t<n;t++){let n=a[t];e.bufferSubData(r,n.start*i.BYTES_PER_ELEMENT,i,n.start,n.count)}n.clearUpdateRanges()}n.onUploadCallback()}function i(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)}function a(n){n.isInterleavedBufferAttribute&&(n=n.data);let r=t.get(n);r&&(e.deleteBuffer(r.buffer),t.delete(n))}function o(e,i){if(e.isInterleavedBufferAttribute&&(e=e.data),e.isGLBufferAttribute){let n=t.get(e);(!n||n.version<e.version)&&t.set(e,{buffer:e.buffer,type:e.type,bytesPerElement:e.elementSize,version:e.version});return}let a=t.get(e);if(a===void 0)t.set(e,n(e,i));else if(a.version<e.version){if(a.size!==e.array.byteLength)throw Error(`THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.`);r(a.buffer,e,i),a.version=e.version}}return{get:i,remove:a,update:o}}var X={alphahash_fragment:`#ifdef USE_ALPHAHASH
|
|
7
|
+
}`,Dd=class extends Ll{constructor(e){super(),this.isShaderMaterial=!0,this.type=`ShaderMaterial`,this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=Td,this.fragmentShader=Ed,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=yd(e.uniforms),this.uniformsGroups=Sd(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let n in this.uniforms){let r=this.uniforms[n].value;r&&r.isTexture?t.uniforms[n]={type:`t`,value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[n]={type:`c`,value:r.getHex()}:r&&r.isVector2?t.uniforms[n]={type:`v2`,value:r.toArray()}:r&&r.isVector3?t.uniforms[n]={type:`v3`,value:r.toArray()}:r&&r.isVector4?t.uniforms[n]={type:`v4`,value:r.toArray()}:r&&r.isMatrix3?t.uniforms[n]={type:`m3`,value:r.toArray()}:r&&r.isMatrix4?t.uniforms[n]={type:`m4`,value:r.toArray()}:t.uniforms[n]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let e in this.extensions)this.extensions[e]===!0&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}},Od=class extends Dd{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type=`RawShaderMaterial`}},kd=class extends Ll{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type=`MeshStandardMaterial`,this.defines={STANDARD:``},this.color=new q(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new q(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new H(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new cc,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:``},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Ad=class extends kd{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:``,PHYSICAL:``},this.type=`MeshPhysicalMaterial`,this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new H(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return ls(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new q(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new q(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new q(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:``,PHYSICAL:``},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}},jd=class extends Ll{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type=`MeshDepthMaterial`,this.depthPacking=Io,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},Md=class extends Ll{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type=`MeshDistanceMaterial`,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}};function Nd(e,t){return!e||e.constructor===t?e:typeof t.BYTES_PER_ELEMENT==`number`?new t(e):Array.prototype.slice.call(e)}function Pd(e){function t(t,n){return e[t]-e[n]}let n=e.length,r=Array(n);for(let e=0;e!==n;++e)r[e]=e;return r.sort(t),r}function Fd(e,t,n){let r=e.length,i=new e.constructor(r);for(let a=0,o=0;o!==r;++a){let r=n[a]*t;for(let n=0;n!==t;++n)i[o++]=e[r+n]}return i}function Id(e,t,n,r){let i=1,a=e[0];for(;a!==void 0&&a[r]===void 0;)a=e[i++];if(a===void 0)return;let o=a[r];if(o!==void 0)if(Array.isArray(o))do o=a[r],o!==void 0&&(t.push(a.time),n.push(...o)),a=e[i++];while(a!==void 0);else if(o.toArray!==void 0)do o=a[r],o!==void 0&&(t.push(a.time),o.toArray(n,n.length)),a=e[i++];while(a!==void 0);else do o=a[r],o!==void 0&&(t.push(a.time),n.push(o)),a=e[i++];while(a!==void 0)}var Ld=class{constructor(e,t,n,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r===void 0?new t.constructor(n):r,this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,r=t[n],i=t[n-1];validate_interval:{seek:{let a;linear_scan:{forward_scan:if(!(e<r)){for(let a=n+2;;){if(r===void 0){if(e<i)break forward_scan;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(i=r,r=t[++n],e<r)break seek}a=t.length;break linear_scan}if(!(e>=i)){let o=t[1];e<o&&(n=2,i=o);for(let a=n-2;;){if(i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===a)break;if(r=i,i=t[--n-1],e>=i)break seek}a=n,n=0;break linear_scan}break validate_interval}for(;n<a;){let r=n+a>>>1;e<t[r]?a=r:n=r+1}if(r=t[n],i=t[n-1],i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(r===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,i,r)}return this.interpolate_(n,i,e,r)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r;for(let e=0;e!==r;++e)t[e]=n[i+e];return t}interpolate_(){throw Error(`call to abstract method`)}intervalChanged_(){}},Rd=class extends Ld{constructor(e,t,n,r){super(e,t,n,r),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:jo,endingEnd:jo}}intervalChanged_(e,t,n){let r=this.parameterPositions,i=e-2,a=e+1,o=r[i],s=r[a];if(o===void 0)switch(this.getSettings_().endingStart){case Mo:i=e,o=2*t-n;break;case No:i=r.length-2,o=t+r[i]-r[i+1];break;default:i=e,o=n}if(s===void 0)switch(this.getSettings_().endingEnd){case Mo:a=e,s=2*n-t;break;case No:a=1,s=n+r[1]-r[0];break;default:a=e-1,s=t}let c=(n-t)*.5,l=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(s-n),this._offsetPrev=i*l,this._offsetNext=a*l}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,p=(n-t)/(r-t),m=p*p,h=m*p,g=-d*h+2*d*m-d*p,_=(1+d)*h+(-1.5-2*d)*m+(-.5+d)*p+1,v=(-1-f)*h+(1.5+f)*m+.5*p,y=f*h-f*m;for(let e=0;e!==o;++e)i[e]=g*a[l+e]+_*a[c+e]+v*a[s+e]+y*a[u+e];return i}},zd=class extends Ld{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=(n-t)/(r-t),u=1-l;for(let e=0;e!==o;++e)i[e]=a[c+e]*u+a[s+e]*l;return i}},Bd=class extends Ld{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e){return this.copySampleValue_(e-1)}},Vd=class extends Ld{interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this.settings||this.DefaultSettings_,u=l.inTangents,d=l.outTangents;if(!u||!d){let e=(n-t)/(r-t),l=1-e;for(let t=0;t!==o;++t)i[t]=a[c+t]*l+a[s+t]*e;return i}let f=o*2,p=e-1;for(let l=0;l!==o;++l){let o=a[c+l],m=a[s+l],h=p*f+l*2,g=d[h],_=d[h+1],v=e*f+l*2,y=u[v],b=u[v+1],x=(n-t)/(r-t),S,C,w,T,E;for(let e=0;e<8;e++){S=x*x,C=S*x,w=1-x,T=w*w,E=T*w;let e=E*t+3*T*x*g+3*w*S*y+C*r-n;if(Math.abs(e)<1e-10)break;let i=3*T*(g-t)+6*w*x*(y-g)+3*S*(r-y);if(Math.abs(i)<1e-10)break;x-=e/i,x=Math.max(0,Math.min(1,x))}i[l]=E*o+3*T*x*_+3*w*S*b+C*m}return i}},Hd=class{constructor(e,t,n,r){if(e===void 0)throw Error(`THREE.KeyframeTrack: track name is undefined`);if(t===void 0||t.length===0)throw Error(`THREE.KeyframeTrack: no keyframes in track named `+e);this.name=e,this.times=Nd(t,this.TimeBufferType),this.values=Nd(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:Nd(e.times,Array),values:Nd(e.values,Array)};let t=e.getInterpolation();t!==e.DefaultInterpolation&&(n.interpolation=t)}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new Bd(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new zd(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Rd(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodBezier(e){let t=new Vd(this.times,this.values,this.getValueSize(),e);return this.settings&&(t.settings=this.settings),t}setInterpolation(e){let t;switch(e){case Do:t=this.InterpolantFactoryMethodDiscrete;break;case Oo:t=this.InterpolantFactoryMethodLinear;break;case ko:t=this.InterpolantFactoryMethodSmooth;break;case Ao:t=this.InterpolantFactoryMethodBezier;break}if(t===void 0){let t=`unsupported interpolation for `+this.ValueTypeName+` keyframe track named `+this.name;if(this.createInterpolant===void 0)if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(t);return B(`KeyframeTrack:`,t),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return Do;case this.InterpolantFactoryMethodLinear:return Oo;case this.InterpolantFactoryMethodSmooth:return ko;case this.InterpolantFactoryMethodBezier:return Ao}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]*=e}return this}trim(e,t){let n=this.times,r=n.length,i=0,a=r-1;for(;i!==r&&n[i]<e;)++i;for(;a!==-1&&n[a]>t;)--a;if(++a,i!==0||a!==r){i>=a&&(a=Math.max(a,1),i=a-1);let e=this.getValueSize();this.times=n.slice(i,a),this.values=this.values.slice(i*e,a*e)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(V(`KeyframeTrack: Invalid value size in track.`,this),e=!1);let n=this.times,r=this.values,i=n.length;i===0&&(V(`KeyframeTrack: Track is empty.`,this),e=!1);let a=null;for(let t=0;t!==i;t++){let r=n[t];if(typeof r==`number`&&isNaN(r)){V(`KeyframeTrack: Time is not a valid number.`,this,t,r),e=!1;break}if(a!==null&&a>r){V(`KeyframeTrack: Out of order keys.`,this,t,r,a),e=!1;break}a=r}if(r!==void 0&&qo(r))for(let t=0,n=r.length;t!==n;++t){let n=r[t];if(isNaN(n)){V(`KeyframeTrack: Value is not a valid number.`,this,t,n),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),r=this.getInterpolation()===ko,i=e.length-1,a=1;for(let o=1;o<i;++o){let i=!1,s=e[o];if(s!==e[o+1]&&(o!==1||s!==e[0]))if(r)i=!0;else{let e=o*n,r=e-n,a=e+n;for(let o=0;o!==n;++o){let n=t[e+o];if(n!==t[r+o]||n!==t[a+o]){i=!0;break}}}if(i){if(o!==a){e[a]=e[o];let r=o*n,i=a*n;for(let e=0;e!==n;++e)t[i+e]=t[r+e]}++a}}if(i>0){e[a]=e[i];for(let e=i*n,r=a*n,o=0;o!==n;++o)t[r+o]=t[e+o];++a}return a===e.length?(this.times=e,this.values=t):(this.times=e.slice(0,a),this.values=t.slice(0,a*n)),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,r}};Hd.prototype.ValueTypeName=``,Hd.prototype.TimeBufferType=Float32Array,Hd.prototype.ValueBufferType=Float32Array,Hd.prototype.DefaultInterpolation=Oo;var Ud=class extends Hd{constructor(e,t,n){super(e,t,n)}};Ud.prototype.ValueTypeName=`bool`,Ud.prototype.ValueBufferType=Array,Ud.prototype.DefaultInterpolation=Do,Ud.prototype.InterpolantFactoryMethodLinear=void 0,Ud.prototype.InterpolantFactoryMethodSmooth=void 0;var Wd=class extends Hd{constructor(e,t,n,r){super(e,t,n,r)}};Wd.prototype.ValueTypeName=`color`;var Gd=class extends Hd{constructor(e,t,n,r){super(e,t,n,r)}};Gd.prototype.ValueTypeName=`number`;var Kd=class extends Ld{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=(n-t)/(r-t),c=e*o;for(let e=c+o;c!==e;c+=4)U.slerpFlat(i,0,a,c-o,a,c,s);return i}},qd=class extends Hd{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new Kd(this.times,this.values,this.getValueSize(),e)}};qd.prototype.ValueTypeName=`quaternion`,qd.prototype.InterpolantFactoryMethodSmooth=void 0;var Jd=class extends Hd{constructor(e,t,n){super(e,t,n)}};Jd.prototype.ValueTypeName=`string`,Jd.prototype.ValueBufferType=Array,Jd.prototype.DefaultInterpolation=Do,Jd.prototype.InterpolantFactoryMethodLinear=void 0,Jd.prototype.InterpolantFactoryMethodSmooth=void 0;var Yd=class extends Hd{constructor(e,t,n,r){super(e,t,n,r)}};Yd.prototype.ValueTypeName=`vector`;var Xd=class{constructor(e=``,t=-1,n=[],r=Po){this.name=e,this.tracks=n,this.duration=t,this.blendMode=r,this.uuid=cs(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){let t=[],n=e.tracks,r=1/(e.fps||1);for(let e=0,i=n.length;e!==i;++e)t.push(Qd(n[e]).scale(r));let i=new this(e.name,e.duration,t,e.blendMode);return i.uuid=e.uuid,i.userData=JSON.parse(e.userData||`{}`),i}static toJSON(e){let t=[],n=e.tracks,r={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let e=0,r=n.length;e!==r;++e)t.push(Hd.toJSON(n[e]));return r}static CreateFromMorphTargetSequence(e,t,n,r){let i=t.length,a=[];for(let e=0;e<i;e++){let o=[],s=[];o.push((e+i-1)%i,e,(e+1)%i),s.push(0,1,0);let c=Pd(o);o=Fd(o,1,c),s=Fd(s,1,c),!r&&o[0]===0&&(o.push(i),s.push(s[0])),a.push(new Gd(`.morphTargetInfluences[`+t[e].name+`]`,o,s).scale(1/n))}return new this(e,-1,a)}static findByName(e,t){let n=e;if(!Array.isArray(e)){let t=e;n=t.geometry&&t.geometry.animations||t.animations}for(let e=0;e<n.length;e++)if(n[e].name===t)return n[e];return null}static CreateClipsFromMorphTargetSequences(e,t,n){let r={},i=/^([\w-]*?)([\d]+)$/;for(let t=0,n=e.length;t<n;t++){let n=e[t],a=n.name.match(i);if(a&&a.length>1){let e=a[1],t=r[e];t||(r[e]=t=[]),t.push(n)}}let a=[];for(let e in r)a.push(this.CreateFromMorphTargetSequence(e,r[e],t,n));return a}static parseAnimation(e,t){if(B(`AnimationClip: parseAnimation() is deprecated and will be removed with r185`),!e)return V(`AnimationClip: No animation in JSONLoader data.`),null;let n=function(e,t,n,r,i){if(n.length!==0){let a=[],o=[];Id(n,a,o,r),a.length!==0&&i.push(new e(t,a,o))}},r=[],i=e.name||`default`,a=e.fps||30,o=e.blendMode,s=e.length||-1,c=e.hierarchy||[];for(let e=0;e<c.length;e++){let i=c[e].keys;if(!(!i||i.length===0))if(i[0].morphTargets){let e={},t;for(t=0;t<i.length;t++)if(i[t].morphTargets)for(let n=0;n<i[t].morphTargets.length;n++)e[i[t].morphTargets[n]]=-1;for(let n in e){let e=[],a=[];for(let r=0;r!==i[t].morphTargets.length;++r){let r=i[t];e.push(r.time),a.push(+(r.morphTarget===n))}r.push(new Gd(`.morphTargetInfluence[`+n+`]`,e,a))}s=e.length*a}else{let a=`.bones[`+t[e].name+`]`;n(Yd,a+`.position`,i,`pos`,r),n(qd,a+`.quaternion`,i,`rot`,r),n(Yd,a+`.scale`,i,`scl`,r)}}return r.length===0?null:new this(i,s,r,o)}resetDuration(){let e=this.tracks,t=0;for(let n=0,r=e.length;n!==r;++n){let e=this.tracks[n];t=Math.max(t,e.times[e.times.length-1])}return this.duration=t,this}trim(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].trim(0,this.duration);return this}validate(){let e=!0;for(let t=0;t<this.tracks.length;t++)e&&=this.tracks[t].validate();return e}optimize(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].optimize();return this}clone(){let e=[];for(let t=0;t<this.tracks.length;t++)e.push(this.tracks[t].clone());let t=new this.constructor(this.name,this.duration,e,this.blendMode);return t.userData=JSON.parse(JSON.stringify(this.userData)),t}toJSON(){return this.constructor.toJSON(this)}};function Zd(e){switch(e.toLowerCase()){case`scalar`:case`double`:case`float`:case`number`:case`integer`:return Gd;case`vector`:case`vector2`:case`vector3`:case`vector4`:return Yd;case`color`:return Wd;case`quaternion`:return qd;case`bool`:case`boolean`:return Ud;case`string`:return Jd}throw Error(`THREE.KeyframeTrack: Unsupported typeName: `+e)}function Qd(e){if(e.type===void 0)throw Error(`THREE.KeyframeTrack: track type undefined, can not parse`);let t=Zd(e.type);if(e.times===void 0){let t=[],n=[];Id(e.keys,t,n,`value`),e.times=t,e.values=n}return t.parse===void 0?new t(e.name,e.times,e.values,e.interpolation):t.parse(e)}var $d={enabled:!1,files:{},add:function(e,t){this.enabled!==!1&&(ef(e)||(this.files[e]=t))},get:function(e){if(this.enabled!==!1&&!ef(e))return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};function ef(e){try{let t=e.slice(e.indexOf(`:`)+1);return new URL(t).protocol===`blob:`}catch{return!1}}var tf=new class{constructor(e,t,n){let r=this,i=!1,a=0,o=0,s,c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this._abortController=null,this.itemStart=function(e){o++,i===!1&&r.onStart!==void 0&&r.onStart(e,a,o),i=!0},this.itemEnd=function(e){a++,r.onProgress!==void 0&&r.onProgress(e,a,o),a===o&&(i=!1,r.onLoad!==void 0&&r.onLoad())},this.itemError=function(e){r.onError!==void 0&&r.onError(e)},this.resolveURL=function(e){return s?s(e):e},this.setURLModifier=function(e){return s=e,this},this.addHandler=function(e,t){return c.push(e,t),this},this.removeHandler=function(e){let t=c.indexOf(e);return t!==-1&&c.splice(t,2),this},this.getHandler=function(e){for(let t=0,n=c.length;t<n;t+=2){let n=c[t],r=c[t+1];if(n.global&&(n.lastIndex=0),n.test(e))return r}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){return this._abortController||=new AbortController,this._abortController}},nf=class{constructor(e){this.manager=e===void 0?tf:e,this.crossOrigin=`anonymous`,this.withCredentials=!1,this.path=``,this.resourcePath=``,this.requestHeader={},typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}load(){}loadAsync(e,t){let n=this;return new Promise(function(r,i){n.load(e,r,t,i)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}abort(){return this}};nf.DEFAULT_MATERIAL_NAME=`__DEFAULT`;var rf={},af=class extends Error{constructor(e,t){super(e),this.response=t}},of=class extends nf{constructor(e){super(e),this.mimeType=``,this.responseType=``,this._abortController=new AbortController}load(e,t,n,r){e===void 0&&(e=``),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=$d.get(`file:${e}`);if(i!==void 0){this.manager.itemStart(e),setTimeout(()=>{t&&t(i),this.manager.itemEnd(e)},0);return}if(rf[e]!==void 0){rf[e].push({onLoad:t,onProgress:n,onError:r});return}rf[e]=[],rf[e].push({onLoad:t,onProgress:n,onError:r});let a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?`include`:`same-origin`,signal:typeof AbortSignal.any==`function`?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,s=this.responseType;fetch(a).then(t=>{if(t.status===200||t.status===0){if(t.status===0&&B(`FileLoader: HTTP Status 0 received.`),typeof ReadableStream>`u`||t.body===void 0||t.body.getReader===void 0)return t;let n=rf[e],r=t.body.getReader(),i=t.headers.get(`X-File-Size`)||t.headers.get(`Content-Length`),a=i?parseInt(i):0,o=a!==0,s=0,c=new ReadableStream({start(e){t();function t(){r.read().then(({done:r,value:i})=>{if(r)e.close();else{s+=i.byteLength;let r=new ProgressEvent(`progress`,{lengthComputable:o,loaded:s,total:a});for(let e=0,t=n.length;e<t;e++){let t=n[e];t.onProgress&&t.onProgress(r)}e.enqueue(i),t()}},t=>{e.error(t)})}}});return new Response(c)}else throw new af(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`,t)}).then(e=>{switch(s){case`arraybuffer`:return e.arrayBuffer();case`blob`:return e.blob();case`document`:return e.text().then(e=>new DOMParser().parseFromString(e,o));case`json`:return e.json();default:if(o===``)return e.text();{let t=/charset="?([^;"\s]*)"?/i.exec(o),n=t&&t[1]?t[1].toLowerCase():void 0,r=new TextDecoder(n);return e.arrayBuffer().then(e=>r.decode(e))}}}).then(t=>{$d.add(`file:${e}`,t);let n=rf[e];delete rf[e];for(let e=0,r=n.length;e<r;e++){let r=n[e];r.onLoad&&r.onLoad(t)}}).catch(t=>{let n=rf[e];if(n===void 0)throw this.manager.itemError(e),t;delete rf[e];for(let e=0,r=n.length;e<r;e++){let r=n[e];r.onError&&r.onError(t)}this.manager.itemError(e)}).finally(()=>{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},sf=new WeakMap,cf=class extends nf{constructor(e){super(e)}load(e,t,n,r){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=this,a=$d.get(`image:${e}`);if(a!==void 0){if(a.complete===!0)i.manager.itemStart(e),setTimeout(function(){t&&t(a),i.manager.itemEnd(e)},0);else{let e=sf.get(a);e===void 0&&(e=[],sf.set(a,e)),e.push({onLoad:t,onError:r})}return a}let o=Jo(`img`);function s(){l(),t&&t(this);let n=sf.get(this)||[];for(let e=0;e<n.length;e++){let t=n[e];t.onLoad&&t.onLoad(this)}sf.delete(this),i.manager.itemEnd(e)}function c(t){l(),r&&r(t),$d.remove(`image:${e}`);let n=sf.get(this)||[];for(let e=0;e<n.length;e++){let r=n[e];r.onError&&r.onError(t)}sf.delete(this),i.manager.itemError(e),i.manager.itemEnd(e)}function l(){o.removeEventListener(`load`,s,!1),o.removeEventListener(`error`,c,!1)}return o.addEventListener(`load`,s,!1),o.addEventListener(`error`,c,!1),e.slice(0,5)!==`data:`&&this.crossOrigin!==void 0&&(o.crossOrigin=this.crossOrigin),$d.add(`image:${e}`,o),i.manager.itemStart(e),o.src=e,o}},lf=class extends nf{constructor(e){super(e)}load(e,t,n,r){let i=this,a=new vu,o=new of(this.manager);return o.setResponseType(`arraybuffer`),o.setRequestHeader(this.requestHeader),o.setPath(this.path),o.setWithCredentials(i.withCredentials),o.load(e,function(e){let n;try{n=i.parse(e)}catch(e){r===void 0?V(e):r(e);return}n.image===void 0?n.data!==void 0&&(a.image.width=n.width,a.image.height=n.height,a.image.data=n.data):a.image=n.image,a.wrapS=n.wrapS===void 0?ua:n.wrapS,a.wrapT=n.wrapT===void 0?ua:n.wrapT,a.magFilter=n.magFilter===void 0?ha:n.magFilter,a.minFilter=n.minFilter===void 0?ha:n.minFilter,a.anisotropy=n.anisotropy===void 0?1:n.anisotropy,n.colorSpace!==void 0&&(a.colorSpace=n.colorSpace),n.flipY!==void 0&&(a.flipY=n.flipY),n.format!==void 0&&(a.format=n.format),n.type!==void 0&&(a.type=n.type),n.mipmaps!==void 0&&(a.mipmaps=n.mipmaps,a.minFilter=_a),n.mipmapCount===1&&(a.minFilter=ha),n.generateMipmaps!==void 0&&(a.generateMipmaps=n.generateMipmaps),a.needsUpdate=!0,t&&t(a,n)},n,r),a}},uf=class extends nf{constructor(e){super(e)}load(e,t,n,r){let i=new qs,a=new cf(this.manager);return a.setCrossOrigin(this.crossOrigin),a.setPath(this.path),a.load(e,function(e){i.image=e,i.needsUpdate=!0,t!==void 0&&t(i)},n,r),i}},df=class extends Tc{constructor(e,t=1){super(),this.isLight=!0,this.type=`Light`,this.color=new q(e),this.intensity=t}dispose(){this.dispatchEvent({type:`dispose`})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){let t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}},ff=new K,pf=new W,mf=new W,hf=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new H(512,512),this.mapType=va,this.map=null,this.mapPass=null,this.matrix=new K,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Ru,this._frameExtents=new H(1,1),this._viewportCount=1,this._viewports=[new Js(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,n=this.matrix;pf.setFromMatrixPosition(e.matrixWorld),t.position.copy(pf),mf.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(mf),t.updateMatrixWorld(),ff.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(ff,t.coordinateSystem,t.reversedDepth),t.coordinateSystem===2001||t.reversedDepth?n.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(ff)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this.biasNode=e.biasNode,this}clone(){return new this.constructor().copy(this)}toJSON(){let e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}},gf=new W,_f=new U,vf=new W,yf=class extends Tc{constructor(){super(),this.isCamera=!0,this.type=`Camera`,this.matrixWorldInverse=new K,this.projectionMatrix=new K,this.projectionMatrixInverse=new K,this.coordinateSystem=Go,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorld.decompose(gf,_f,vf),vf.x===1&&vf.y===1&&vf.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(gf,_f,vf.set(1,1,1)).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorld.decompose(gf,_f,vf),vf.x===1&&vf.y===1&&vf.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(gf,_f,vf.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}},bf=new W,xf=new H,Sf=new H,Cf=class extends yf{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type=`PerspectiveCamera`,this.fov=e,this.zoom=1,this.near=n,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=ss*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(os*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return ss*2*Math.atan(Math.tan(os*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){bf.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(bf.x,bf.y).multiplyScalar(-e/bf.z),bf.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(bf.x,bf.y).multiplyScalar(-e/bf.z)}getViewSize(e,t){return this.getViewBounds(e,xf,Sf),t.subVectors(Sf,xf)}setViewOffset(e,t,n,r,i,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(os*.5*this.fov)/this.zoom,n=2*t,r=this.aspect*n,i=-.5*r,a=this.view;if(this.view!==null&&this.view.enabled){let e=a.fullWidth,o=a.fullHeight;i+=a.offsetX*r/e,t-=a.offsetY*n/o,r*=a.width/e,n*=a.height/o}let o=this.filmOffset;o!==0&&(i+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+r,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},wf=class extends hf{constructor(){super(new Cf(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){let t=this.camera,n=ss*2*e.angle*this.focus,r=this.mapSize.width/this.mapSize.height*this.aspect,i=e.distance||t.far;(n!==t.fov||r!==t.aspect||i!==t.far)&&(t.fov=n,t.aspect=r,t.far=i,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}},Tf=class extends df{constructor(e,t,n=0,r=Math.PI/3,i=0,a=2){super(e,t),this.isSpotLight=!0,this.type=`SpotLight`,this.position.copy(Tc.DEFAULT_UP),this.updateMatrix(),this.target=new Tc,this.distance=n,this.angle=r,this.penumbra=i,this.decay=a,this.map=null,this.shadow=new wf}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.map=e.map,this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.distance=this.distance,t.object.angle=this.angle,t.object.decay=this.decay,t.object.penumbra=this.penumbra,t.object.target=this.target.uuid,this.map&&this.map.isTexture&&(t.object.map=this.map.toJSON(e).uuid),t.object.shadow=this.shadow.toJSON(),t}},Ef=class extends hf{constructor(){super(new Cf(90,1,.5,500)),this.isPointLightShadow=!0}},Df=class extends df{constructor(e,t,n=0,r=2){super(e,t),this.isPointLight=!0,this.type=`PointLight`,this.distance=n,this.decay=r,this.shadow=new Ef}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}},Of=class extends yf{constructor(e=-1,t=1,n=1,r=-1,i=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type=`OrthographicCamera`,this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=r,this.near=i,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,r,i,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,r=(this.top+this.bottom)/2,i=n-e,a=n+e,o=r+t,s=r-t;if(this.view!==null&&this.view.enabled){let e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;i+=e*this.view.offsetX,a=i+e*this.view.width,o-=t*this.view.offsetY,s=o-t*this.view.height}this.projectionMatrix.makeOrthographic(i,a,o,s,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},kf=class extends hf{constructor(){super(new Of(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},Af=class extends df{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type=`DirectionalLight`,this.position.copy(Tc.DEFAULT_UP),this.updateMatrix(),this.target=new Tc,this.shadow=new kf}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}},jf=class extends df{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type=`AmbientLight`}},Mf=class{static extractUrlBase(e){let t=e.lastIndexOf(`/`);return t===-1?`./`:e.slice(0,t+1)}static resolveURL(e,t){return typeof e!=`string`||e===``?``:(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,`$1`)),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}},Nf=new WeakMap,Pf=class extends nf{constructor(e){super(e),this.isImageBitmapLoader=!0,typeof createImageBitmap>`u`&&B(`ImageBitmapLoader: createImageBitmap() not supported.`),typeof fetch>`u`&&B(`ImageBitmapLoader: fetch() not supported.`),this.options={premultiplyAlpha:`none`},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,n,r){e===void 0&&(e=``),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=this,a=$d.get(`image-bitmap:${e}`);if(a!==void 0){if(i.manager.itemStart(e),a.then){a.then(n=>{Nf.has(a)===!0?(r&&r(Nf.get(a)),i.manager.itemError(e),i.manager.itemEnd(e)):(t&&t(n),i.manager.itemEnd(e))});return}setTimeout(function(){t&&t(a),i.manager.itemEnd(e)},0);return}let o={};o.credentials=this.crossOrigin===`anonymous`?`same-origin`:`include`,o.headers=this.requestHeader,o.signal=typeof AbortSignal.any==`function`?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;let s=fetch(e,o).then(function(e){return e.blob()}).then(function(e){return createImageBitmap(e,Object.assign(i.options,{colorSpaceConversion:`none`}))}).then(function(n){$d.add(`image-bitmap:${e}`,n),t&&t(n),i.manager.itemEnd(e)}).catch(function(t){r&&r(t),Nf.set(s,t),$d.remove(`image-bitmap:${e}`),i.manager.itemError(e),i.manager.itemEnd(e)});$d.add(`image-bitmap:${e}`,s),i.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},Ff=-90,If=1,Lf=class extends Tc{constructor(e,t,n){super(),this.type=`CubeCamera`,this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new Cf(Ff,If,e,t);r.layers=this.layers,this.add(r);let i=new Cf(Ff,If,e,t);i.layers=this.layers,this.add(i);let a=new Cf(Ff,If,e,t);a.layers=this.layers,this.add(a);let o=new Cf(Ff,If,e,t);o.layers=this.layers,this.add(o);let s=new Cf(Ff,If,e,t);s.layers=this.layers,this.add(s);let c=new Cf(Ff,If,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,r,i,a,o,s]=t;for(let e of t)this.remove(e);if(e===2e3)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),i.up.set(0,0,-1),i.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),s.up.set(0,1,0),s.lookAt(0,0,-1);else if(e===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),i.up.set(0,0,1),i.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),s.up.set(0,-1,0),s.lookAt(0,0,-1);else throw Error(`THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: `+e);for(let e of t)this.add(e),e.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[i,a,o,s,c,l]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;let m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let h=!1;h=e.isWebGLRenderer===!0?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(n,0,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,i),e.setRenderTarget(n,1,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,2,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,3,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,4,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(u,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}},Rf=class extends Cf{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},zf=class{constructor(e,t,n){this.binding=e,this.valueSize=n;let r,i,a;switch(t){case`quaternion`:r=this._slerp,i=this._slerpAdditive,a=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(n*6),this._workIndex=5;break;case`string`:case`bool`:r=this._select,i=this._select,a=this._setAdditiveIdentityOther,this.buffer=Array(n*5);break;default:r=this._lerp,i=this._lerpAdditive,a=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(n*5)}this._mixBufferRegion=r,this._mixBufferRegionAdditive=i,this._setIdentity=a,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){let n=this.buffer,r=this.valueSize,i=e*r+r,a=this.cumulativeWeight;if(a===0){for(let e=0;e!==r;++e)n[i+e]=n[e];a=t}else{a+=t;let e=t/a;this._mixBufferRegion(n,i,0,e,r)}this.cumulativeWeight=a}accumulateAdditive(e){let t=this.buffer,n=this.valueSize,r=n*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,r,0,e,n),this.cumulativeWeightAdditive+=e}apply(e){let t=this.valueSize,n=this.buffer,r=e*t+t,i=this.cumulativeWeight,a=this.cumulativeWeightAdditive,o=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,i<1){let e=t*this._origIndex;this._mixBufferRegion(n,r,e,1-i,t)}a>0&&this._mixBufferRegionAdditive(n,r,this._addIndex*t,1,t);for(let e=t,i=t+t;e!==i;++e)if(n[e]!==n[e+t]){o.setValue(n,r);break}}saveOriginalState(){let e=this.binding,t=this.buffer,n=this.valueSize,r=n*this._origIndex;e.getValue(t,r);for(let e=n,i=r;e!==i;++e)t[e]=t[r+e%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){let e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n<t;n++)this.buffer[n]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){let e=this._origIndex*this.valueSize,t=this._addIndex*this.valueSize;for(let n=0;n<this.valueSize;n++)this.buffer[t+n]=this.buffer[e+n]}_select(e,t,n,r,i){if(r>=.5)for(let r=0;r!==i;++r)e[t+r]=e[n+r]}_slerp(e,t,n,r){U.slerpFlat(e,t,e,t,e,n,r)}_slerpAdditive(e,t,n,r,i){let a=this._workIndex*i;U.multiplyQuaternionsFlat(e,a,e,t,e,n),U.slerpFlat(e,t,e,t,e,a,r)}_lerp(e,t,n,r,i){let a=1-r;for(let o=0;o!==i;++o){let i=t+o;e[i]=e[i]*a+e[n+o]*r}}_lerpAdditive(e,t,n,r,i){for(let a=0;a!==i;++a){let i=t+a;e[i]=e[i]+e[n+a]*r}}},Bf=`\\[\\]\\.:\\/`,Vf=RegExp(`[\\[\\]\\.:\\/]`,`g`),Hf=`[^\\[\\]\\.:\\/]`,Uf=`[^`+Bf.replace(`\\.`,``)+`]`,Wf=`((?:WC+[\\/:])*)`.replace(`WC`,Hf),Gf=`(WCOD+)?`.replace(`WCOD`,Uf),Kf=`(?:\\.(WC+)(?:\\[(.+)\\])?)?`.replace(`WC`,Hf),qf=`\\.(WC+)(?:\\[(.+)\\])?`.replace(`WC`,Hf),Jf=RegExp(`^`+Wf+Gf+Kf+qf+`$`),Yf=[`material`,`materials`,`bones`,`map`],Xf=class{constructor(e,t,n){let r=n||Zf.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,i=n.length;r!==i;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},Zf=class e{constructor(t,n,r){this.path=n,this.parsedPath=r||e.parseTrackName(n),this.node=e.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,n,r){return t&&t.isAnimationObjectGroup?new e.Composite(t,n,r):new e(t,n,r)}static sanitizeNodeName(e){return e.replace(/\s/g,`_`).replace(Vf,``)}static parseTrackName(e){let t=Jf.exec(e);if(t===null)throw Error(`PropertyBinding: Cannot parse trackName: `+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(`.`);if(r!==void 0&&r!==-1){let e=n.nodeName.substring(r+1);Yf.indexOf(e)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=e)}if(n.propertyName===null||n.propertyName.length===0)throw Error(`PropertyBinding: can not parse propertyName from trackName: `+e);return n}static findNode(e,t){if(t===void 0||t===``||t===`.`||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(e){for(let r=0;r<e.length;r++){let i=e[r];if(i.name===t||i.uuid===t)return i;let a=n(i.children);if(a)return a}return null},r=n(e.children);if(r)return r}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)e[t++]=n[r]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let t=this.node,n=this.parsedPath,r=n.objectName,i=n.propertyName,a=n.propertyIndex;if(t||(t=e.findNode(this.rootNode,n.nodeName),this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t){B(`PropertyBinding: No target node found for track: `+this.path+`.`);return}if(r){let e=n.objectIndex;switch(r){case`materials`:if(!t.material){V(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.materials){V(`PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.`,this);return}t=t.material.materials;break;case`bones`:if(!t.skeleton){V(`PropertyBinding: Can not bind to bones as node does not have a skeleton.`,this);return}t=t.skeleton.bones;for(let n=0;n<t.length;n++)if(t[n].name===e){e=n;break}break;case`map`:if(`map`in t){t=t.map;break}if(!t.material){V(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.map){V(`PropertyBinding: Can not bind to material.map as node.material does not have a map.`,this);return}t=t.material.map;break;default:if(t[r]===void 0){V(`PropertyBinding: Can not bind to objectName of node undefined.`,this);return}t=t[r]}if(e!==void 0){if(t[e]===void 0){V(`PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.`,this,t);return}t=t[e]}}let o=t[i];if(o===void 0){let e=n.nodeName;V(`PropertyBinding: Trying to update property for track: `+e+`.`+i+` but it wasn't found.`,t);return}let s=this.Versioning.None;this.targetObject=t,t.isMaterial===!0?s=this.Versioning.NeedsUpdate:t.isObject3D===!0&&(s=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(a!==void 0){if(i===`morphTargetInfluences`){if(!t.geometry){V(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.`,this);return}if(!t.geometry.morphAttributes){V(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.`,this);return}t.morphTargetDictionary[a]!==void 0&&(a=t.morphTargetDictionary[a])}c=this.BindingType.ArrayElement,this.resolvedProperty=o,this.propertyIndex=a}else o.fromArray!==void 0&&o.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=o):Array.isArray(o)?(c=this.BindingType.EntireArray,this.resolvedProperty=o):this.propertyName=i;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][s]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};Zf.Composite=Xf,Zf.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Zf.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},Zf.prototype.GetterByBindingType=[Zf.prototype._getValue_direct,Zf.prototype._getValue_array,Zf.prototype._getValue_arrayElement,Zf.prototype._getValue_toArray],Zf.prototype.SetterByBindingTypeAndVersioning=[[Zf.prototype._setValue_direct,Zf.prototype._setValue_direct_setNeedsUpdate,Zf.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[Zf.prototype._setValue_array,Zf.prototype._setValue_array_setNeedsUpdate,Zf.prototype._setValue_array_setMatrixWorldNeedsUpdate],[Zf.prototype._setValue_arrayElement,Zf.prototype._setValue_arrayElement_setNeedsUpdate,Zf.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[Zf.prototype._setValue_fromArray,Zf.prototype._setValue_fromArray_setNeedsUpdate,Zf.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];var Qf=class{constructor(e,t,n=null,r=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=r;let i=t.tracks,a=i.length,o=Array(a),s={endingStart:jo,endingEnd:jo};for(let e=0;e!==a;++e){let t=i[e].createInterpolant(null);o[e]=t,t.settings&&Object.assign(s,t.settings),t.settings=s}this._interpolantSettings=s,this._interpolants=o,this._propertyBindings=Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=To,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,n=!1){if(e.fadeOut(t),this.fadeIn(t),n===!0){let n=this._clip.duration,r=e._clip.duration,i=r/n,a=n/r;e.warp(1,i,t),this.warp(a,1,t)}return this}crossFadeTo(e,t,n=!1){return e.crossFadeFrom(this,t,n)}stopFading(){let e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,n){let r=this._mixer,i=r.time,a=this.timeScale,o=this._timeScaleInterpolant;o===null&&(o=r._lendControlInterpolant(),this._timeScaleInterpolant=o);let s=o.parameterPositions,c=o.sampleValues;return s[0]=i,s[1]=i+n,c[0]=e/a,c[1]=t/a,this}stopWarping(){let e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,n,r){if(!this.enabled){this._updateWeight(e);return}let i=this._startTime;if(i!==null){let r=(e-i)*n;r<0||n===0?t=0:(this._startTime=null,t=n*r)}t*=this._updateTimeScale(e);let a=this._updateTime(t),o=this._updateWeight(e);if(o>0){let e=this._interpolants,t=this._propertyBindings;switch(this.blendMode){case Fo:for(let n=0,r=e.length;n!==r;++n)e[n].evaluate(a),t[n].accumulateAdditive(o);break;case Po:default:for(let n=0,i=e.length;n!==i;++n)e[n].evaluate(a),t[n].accumulate(r,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let n=this._weightInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(this.stopFading(),r===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;let n=this._timeScaleInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,n=this.loop,r=this.time+e,i=this._loopCount,a=n===Eo;if(e===0)return i===-1?r:a&&(i&1)==1?t-r:r;if(n===2200){i===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));handle_stop:{if(r>=t)r=t;else if(r<0)r=0;else{this.time=r;break handle_stop}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=r,this._mixer.dispatchEvent({type:`finished`,action:this,direction:e<0?-1:1})}}else{if(i===-1&&(e>=0?(i=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),r>=t||r<0){let n=Math.floor(r/t);r-=t*n,i+=Math.abs(n);let o=this.repetitions-i;if(o<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,r=e>0?t:0,this.time=r,this._mixer.dispatchEvent({type:`finished`,action:this,direction:e>0?1:-1});else{if(o===1){let t=e<0;this._setEndings(t,!t,a)}else this._setEndings(!1,!1,a);this._loopCount=i,this.time=r,this._mixer.dispatchEvent({type:`loop`,action:this,loopDelta:n})}}else this._loopCount=i,this.time=r;if(a&&(i&1)==1)return t-r}return r}_setEndings(e,t,n){let r=this._interpolantSettings;n?(r.endingStart=Mo,r.endingEnd=Mo):(e?r.endingStart=this.zeroSlopeAtStart?Mo:jo:r.endingStart=No,t?r.endingEnd=this.zeroSlopeAtEnd?Mo:jo:r.endingEnd=No)}_scheduleFading(e,t,n){let r=this._mixer,i=r.time,a=this._weightInterpolant;a===null&&(a=r._lendControlInterpolant(),this._weightInterpolant=a);let o=a.parameterPositions,s=a.sampleValues;return o[0]=i,s[0]=t,o[1]=i+e,s[1]=n,this}},$f=new Float32Array(1),ep=class extends rs{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}_bindAction(e,t){let n=e._localRoot||this._root,r=e._clip.tracks,i=r.length,a=e._propertyBindings,o=e._interpolants,s=n.uuid,c=this._bindingsByRootAndName,l=c[s];l===void 0&&(l={},c[s]=l);for(let e=0;e!==i;++e){let i=r[e],c=i.name,u=l[c];if(u!==void 0)++u.referenceCount,a[e]=u;else{if(u=a[e],u!==void 0){u._cacheIndex===null&&(++u.referenceCount,this._addInactiveBinding(u,s,c));continue}let r=t&&t._propertyBindings[e].binding.parsedPath;u=new zf(Zf.create(n,c,r),i.ValueTypeName,i.getValueSize()),++u.referenceCount,this._addInactiveBinding(u,s,c),a[e]=u}o[e].resultBuffer=u.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let t=(e._localRoot||this._root).uuid,n=e._clip.uuid,r=this._actionsByClip[n];this._bindAction(e,r&&r.knownActions[0]),this._addInactiveAction(e,n,t)}let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];n.useCount++===0&&(this._lendBinding(n),n.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];--n.useCount===0&&(n.restoreOriginalState(),this._takeBackBinding(n))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){let t=e._cacheIndex;return t!==null&&t<this._nActiveActions}_addInactiveAction(e,t,n){let r=this._actions,i=this._actionsByClip,a=i[t];if(a===void 0)a={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,i[t]=a;else{let t=a.knownActions;e._byClipCacheIndex=t.length,t.push(e)}e._cacheIndex=r.length,r.push(e),a.actionByRoot[n]=e}_removeInactiveAction(e){let t=this._actions,n=t[t.length-1],r=e._cacheIndex;n._cacheIndex=r,t[r]=n,t.pop(),e._cacheIndex=null;let i=e._clip.uuid,a=this._actionsByClip,o=a[i],s=o.knownActions,c=s[s.length-1],l=e._byClipCacheIndex;c._byClipCacheIndex=l,s[l]=c,s.pop(),e._byClipCacheIndex=null;let u=o.actionByRoot,d=(e._localRoot||this._root).uuid;delete u[d],s.length===0&&delete a[i],this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];--n.referenceCount===0&&this._removeInactiveBinding(n)}}_lendAction(e){let t=this._actions,n=e._cacheIndex,r=this._nActiveActions++,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_takeBackAction(e){let t=this._actions,n=e._cacheIndex,r=--this._nActiveActions,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_addInactiveBinding(e,t,n){let r=this._bindingsByRootAndName,i=this._bindings,a=r[t];a===void 0&&(a={},r[t]=a),a[n]=e,e._cacheIndex=i.length,i.push(e)}_removeInactiveBinding(e){let t=this._bindings,n=e.binding,r=n.rootNode.uuid,i=n.path,a=this._bindingsByRootAndName,o=a[r],s=t[t.length-1],c=e._cacheIndex;s._cacheIndex=c,t[c]=s,t.pop(),delete o[i],Object.keys(o).length===0&&delete a[r]}_lendBinding(e){let t=this._bindings,n=e._cacheIndex,r=this._nActiveBindings++,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_takeBackBinding(e){let t=this._bindings,n=e._cacheIndex,r=--this._nActiveBindings,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_lendControlInterpolant(){let e=this._controlInterpolants,t=this._nActiveControlInterpolants++,n=e[t];return n===void 0&&(n=new zd(new Float32Array(2),new Float32Array(2),1,$f),n.__cacheIndex=t,e[t]=n),n}_takeBackControlInterpolant(e){let t=this._controlInterpolants,n=e.__cacheIndex,r=--this._nActiveControlInterpolants,i=t[r];e.__cacheIndex=r,t[r]=e,i.__cacheIndex=n,t[n]=i}clipAction(e,t,n){let r=t||this._root,i=r.uuid,a=typeof e==`string`?Xd.findByName(r,e):e,o=a===null?e:a.uuid,s=this._actionsByClip[o],c=null;if(n===void 0&&(n=a===null?Po:a.blendMode),s!==void 0){let e=s.actionByRoot[i];if(e!==void 0&&e.blendMode===n)return e;c=s.knownActions[0],a===null&&(a=c._clip)}if(a===null)return null;let l=new Qf(this,a,t,n);return this._bindAction(l,c),this._addInactiveAction(l,o,i),l}existingAction(e,t){let n=t||this._root,r=n.uuid,i=typeof e==`string`?Xd.findByName(n,e):e,a=i?i.uuid:e,o=this._actionsByClip[a];return o===void 0?null:o.actionByRoot[r]||null}stopAllAction(){let e=this._actions,t=this._nActiveActions;for(let n=t-1;n>=0;--n)e[n].stop();return this}update(e){e*=this.timeScale;let t=this._actions,n=this._nActiveActions,r=this.time+=e,i=Math.sign(e),a=this._accuIndex^=1;for(let o=0;o!==n;++o)t[o]._update(r,e,i,a);let o=this._bindings,s=this._nActiveBindings;for(let e=0;e!==s;++e)o[e].apply(a);return this}setTime(e){this.time=0;for(let e=0;e<this._actions.length;e++)this._actions[e].time=0;return this.update(e)}getRoot(){return this._root}uncacheClip(e){let t=this._actions,n=e.uuid,r=this._actionsByClip,i=r[n];if(i!==void 0){let e=i.knownActions;for(let n=0,r=e.length;n!==r;++n){let r=e[n];this._deactivateAction(r);let i=r._cacheIndex,a=t[t.length-1];r._cacheIndex=null,r._byClipCacheIndex=null,a._cacheIndex=i,t[i]=a,t.pop(),this._removeInactiveBindingsForAction(r)}delete r[n]}}uncacheRoot(e){let t=e.uuid,n=this._actionsByClip;for(let e in n){let r=n[e].actionByRoot[t];r!==void 0&&(this._deactivateAction(r),this._removeInactiveAction(r))}let r=this._bindingsByRootAndName[t];if(r!==void 0)for(let e in r){let t=r[e];t.restoreOriginalState(),this._removeInactiveBinding(t)}}uncacheAction(e,t){let n=this.existingAction(e,t);n!==null&&(this._deactivateAction(n),this._removeInactiveAction(n))}},tp=class{constructor(e,t,n,r,i,a=!1){this.isGLBufferAttribute=!0,this.name=``,this.buffer=e,this.type=t,this.itemSize=n,this.elementSize=r,this.count=i,this.normalized=a,this.version=0}set needsUpdate(e){e===!0&&this.version++}setBuffer(e){return this.buffer=e,this}setType(e,t){return this.type=e,this.elementSize=t,this}setItemSize(e){return this.itemSize=e,this}setCount(e){return this.count=e,this}},np=new K,rp=class{constructor(e,t,n=0,r=1/0){this.ray=new Gl(e,t),this.near=n,this.far=r,this.camera=null,this.layers=new lc,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(e,t){this.ray.set(e,t)}setFromCamera(e,t){t.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t):t.isOrthographicCamera?(this.ray.origin.set(e.x,e.y,(t.near+t.far)/(t.near-t.far)).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):V(`Raycaster: Unsupported camera type: `+t.type)}setFromXRController(e){return np.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(np),this}intersectObject(e,t=!0,n=[]){return ap(e,this,n,t),n.sort(ip),n}intersectObjects(e,t=!0,n=[]){for(let r=0,i=e.length;r<i;r++)ap(e[r],this,n,t);return n.sort(ip),n}};function ip(e,t){return e.distance-t.distance}function ap(e,t,n,r){let i=!0;if(e.layers.test(t.layers)&&e.raycast(t,n)===!1&&(i=!1),i===!0&&r===!0){let r=e.children;for(let e=0,i=r.length;e<i;e++)ap(r[e],t,n,!0)}}(class e{static{e.prototype.isMatrix2=!0}constructor(e,t,n,r){this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,n,r)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let n=0;n<4;n++)this.elements[n]=e[n+t];return this}set(e,t,n,r){let i=this.elements;return i[0]=e,i[2]=t,i[1]=n,i[3]=r,this}});var op=class extends Zu{constructor(e=1){let t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],n=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],r=new Y;r.setAttribute(`position`,new xl(t,3)),r.setAttribute(`color`,new xl(n,3));let i=new zu({vertexColors:!0,toneMapped:!1});super(r,i),this.type=`AxesHelper`}setColors(e,t,n){let r=new q,i=this.geometry.attributes.color.array;return r.set(e),r.toArray(i,0),r.toArray(i,3),r.set(t),r.toArray(i,6),r.toArray(i,9),r.set(n),r.toArray(i,12),r.toArray(i,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}};function sp(e,t,n,r){let i=cp(r);switch(n){case ja:return e*t;case Ia:return e*t/i.components*i.byteLength;case La:return e*t/i.components*i.byteLength;case Ra:return e*t*2/i.components*i.byteLength;case za:return e*t*2/i.components*i.byteLength;case Ma:return e*t*3/i.components*i.byteLength;case Na:return e*t*4/i.components*i.byteLength;case Ba:return e*t*4/i.components*i.byteLength;case Va:case Ha:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Ua:case Wa:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ka:case Ja:return Math.max(e,16)*Math.max(t,8)/4;case Ga:case qa:return Math.max(e,8)*Math.max(t,8)/2;case Ya:case Xa:case Qa:case $a:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Za:case eo:case to:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case no:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case ro:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case io:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case ao:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case oo:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case so:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case co:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case lo:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case uo:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case fo:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case po:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case mo:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case ho:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case go:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case _o:case vo:case yo:return Math.ceil(e/4)*Math.ceil(t/4)*16;case bo:case xo:return Math.ceil(e/4)*Math.ceil(t/4)*8;case So:case Co:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw Error(`Unable to determine texture byte length for ${n} format.`)}function cp(e){switch(e){case va:case ya:return{byteLength:1,components:1};case xa:case ba:case Ta:return{byteLength:2,components:1};case Ea:case Da:return{byteLength:2,components:4};case Ca:case Sa:case wa:return{byteLength:4,components:1};case ka:case Aa:return{byteLength:4,components:3}}throw Error(`Unknown texture type ${e}.`)}typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`register`,{detail:{revision:`184`}})),typeof window<`u`&&(window.__THREE__?B(`WARNING: Multiple instances of Three.js being imported.`):window.__THREE__=`184`);function lp(){let e=null,t=!1,n=null,r=null;function i(t,a){n(t,a),r=e.requestAnimationFrame(i)}return{start:function(){t!==!0&&n!==null&&e!==null&&(r=e.requestAnimationFrame(i),t=!0)},stop:function(){e!==null&&e.cancelAnimationFrame(r),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function up(e){let t=new WeakMap;function n(t,n){let r=t.array,i=t.usage,a=r.byteLength,o=e.createBuffer();e.bindBuffer(n,o),e.bufferData(n,r,i),t.onUploadCallback();let s;if(r instanceof Float32Array)s=e.FLOAT;else if(typeof Float16Array<`u`&&r instanceof Float16Array)s=e.HALF_FLOAT;else if(r instanceof Uint16Array)s=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(r instanceof Int16Array)s=e.SHORT;else if(r instanceof Uint32Array)s=e.UNSIGNED_INT;else if(r instanceof Int32Array)s=e.INT;else if(r instanceof Int8Array)s=e.BYTE;else if(r instanceof Uint8Array)s=e.UNSIGNED_BYTE;else if(r instanceof Uint8ClampedArray)s=e.UNSIGNED_BYTE;else throw Error(`THREE.WebGLAttributes: Unsupported buffer data format: `+r);return{buffer:o,type:s,bytesPerElement:r.BYTES_PER_ELEMENT,version:t.version,size:a}}function r(t,n,r){let i=n.array,a=n.updateRanges;if(e.bindBuffer(r,t),a.length===0)e.bufferSubData(r,0,i);else{a.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e<a.length;e++){let n=a[t],r=a[e];r.start<=n.start+n.count+1?n.count=Math.max(n.count,r.start+r.count-n.start):(++t,a[t]=r)}a.length=t+1;for(let t=0,n=a.length;t<n;t++){let n=a[t];e.bufferSubData(r,n.start*i.BYTES_PER_ELEMENT,i,n.start,n.count)}n.clearUpdateRanges()}n.onUploadCallback()}function i(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)}function a(n){n.isInterleavedBufferAttribute&&(n=n.data);let r=t.get(n);r&&(e.deleteBuffer(r.buffer),t.delete(n))}function o(e,i){if(e.isInterleavedBufferAttribute&&(e=e.data),e.isGLBufferAttribute){let n=t.get(e);(!n||n.version<e.version)&&t.set(e,{buffer:e.buffer,type:e.type,bytesPerElement:e.elementSize,version:e.version});return}let a=t.get(e);if(a===void 0)t.set(e,n(e,i));else if(a.version<e.version){if(a.size!==e.array.byteLength)throw Error(`THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.`);r(a.buffer,e,i),a.version=e.version}}return{get:i,remove:a,update:o}}var dp={alphahash_fragment:`#ifdef USE_ALPHAHASH
|
|
8
8
|
if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
|
|
9
9
|
#endif`,alphahash_pars_fragment:`#ifdef USE_ALPHAHASH
|
|
10
10
|
const float ALPHA_HASH_SCALE = 0.05;
|
|
@@ -3666,7 +3666,7 @@ void main() {
|
|
|
3666
3666
|
#include <tonemapping_fragment>
|
|
3667
3667
|
#include <colorspace_fragment>
|
|
3668
3668
|
#include <fog_fragment>
|
|
3669
|
-
}`},Z={common:{diffuse:{value:new q(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new G},alphaMap:{value:null},alphaMapTransform:{value:new G},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new G}},envmap:{envMap:{value:null},envMapRotation:{value:new G},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new G}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new G}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new G},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new G},normalScale:{value:new H(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new G},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new G}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new G}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new G}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new q(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new W},probesMax:{value:new W},probesResolution:{value:new W}},points:{diffuse:{value:new q(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new G},alphaTest:{value:0},uvTransform:{value:new G}},sprite:{diffuse:{value:new q(16777215)},opacity:{value:1},center:{value:new H(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new G},alphaMap:{value:null},alphaMapTransform:{value:new G},alphaTest:{value:0}}},dp={basic:{uniforms:bd([Z.common,Z.specularmap,Z.envmap,Z.aomap,Z.lightmap,Z.fog]),vertexShader:X.meshbasic_vert,fragmentShader:X.meshbasic_frag},lambert:{uniforms:bd([Z.common,Z.specularmap,Z.envmap,Z.aomap,Z.lightmap,Z.emissivemap,Z.bumpmap,Z.normalmap,Z.displacementmap,Z.fog,Z.lights,{emissive:{value:new q(0)},envMapIntensity:{value:1}}]),vertexShader:X.meshlambert_vert,fragmentShader:X.meshlambert_frag},phong:{uniforms:bd([Z.common,Z.specularmap,Z.envmap,Z.aomap,Z.lightmap,Z.emissivemap,Z.bumpmap,Z.normalmap,Z.displacementmap,Z.fog,Z.lights,{emissive:{value:new q(0)},specular:{value:new q(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:X.meshphong_vert,fragmentShader:X.meshphong_frag},standard:{uniforms:bd([Z.common,Z.envmap,Z.aomap,Z.lightmap,Z.emissivemap,Z.bumpmap,Z.normalmap,Z.displacementmap,Z.roughnessmap,Z.metalnessmap,Z.fog,Z.lights,{emissive:{value:new q(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:X.meshphysical_vert,fragmentShader:X.meshphysical_frag},toon:{uniforms:bd([Z.common,Z.aomap,Z.lightmap,Z.emissivemap,Z.bumpmap,Z.normalmap,Z.displacementmap,Z.gradientmap,Z.fog,Z.lights,{emissive:{value:new q(0)}}]),vertexShader:X.meshtoon_vert,fragmentShader:X.meshtoon_frag},matcap:{uniforms:bd([Z.common,Z.bumpmap,Z.normalmap,Z.displacementmap,Z.fog,{matcap:{value:null}}]),vertexShader:X.meshmatcap_vert,fragmentShader:X.meshmatcap_frag},points:{uniforms:bd([Z.points,Z.fog]),vertexShader:X.points_vert,fragmentShader:X.points_frag},dashed:{uniforms:bd([Z.common,Z.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:X.linedashed_vert,fragmentShader:X.linedashed_frag},depth:{uniforms:bd([Z.common,Z.displacementmap]),vertexShader:X.depth_vert,fragmentShader:X.depth_frag},normal:{uniforms:bd([Z.common,Z.bumpmap,Z.normalmap,Z.displacementmap,{opacity:{value:1}}]),vertexShader:X.meshnormal_vert,fragmentShader:X.meshnormal_frag},sprite:{uniforms:bd([Z.sprite,Z.fog]),vertexShader:X.sprite_vert,fragmentShader:X.sprite_frag},background:{uniforms:{uvTransform:{value:new G},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:X.background_vert,fragmentShader:X.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new G}},vertexShader:X.backgroundCube_vert,fragmentShader:X.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:X.cube_vert,fragmentShader:X.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:X.equirect_vert,fragmentShader:X.equirect_frag},distance:{uniforms:bd([Z.common,Z.displacementmap,{referencePosition:{value:new W},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:X.distance_vert,fragmentShader:X.distance_frag},shadow:{uniforms:bd([Z.lights,Z.fog,{color:{value:new q(0)},opacity:{value:1}}]),vertexShader:X.shadow_vert,fragmentShader:X.shadow_frag}};dp.physical={uniforms:bd([dp.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new G},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new G},clearcoatNormalScale:{value:new H(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new G},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new G},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new G},sheen:{value:0},sheenColor:{value:new q(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new G},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new G},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new G},transmissionSamplerSize:{value:new H},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new G},attenuationDistance:{value:0},attenuationColor:{value:new q(0)},specularColor:{value:new q(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new G},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new G},anisotropyVector:{value:new H},anisotropyMap:{value:null},anisotropyMapTransform:{value:new G}}]),vertexShader:X.meshphysical_vert,fragmentShader:X.meshphysical_frag};var fp={r:0,b:0,g:0},pp=new K,mp=new G;mp.set(-1,0,0,0,1,0,0,0,1);function hp(e,t,n,r,i,a){let o=new q(0),s=i===!0?0:1,c,l,u=null,d=0,f=null;function p(e){let n=e.isScene===!0?e.background:null;if(n&&n.isTexture){let r=e.backgroundBlurriness>0;n=t.get(n,r)}return n}function m(t){let r=!1,i=p(t);i===null?g(o,s):i&&i.isColor&&(g(i,1),r=!0);let c=e.xr.getEnvironmentBlendMode();c===`additive`?n.buffers.color.setClear(0,0,0,1,a):c===`alpha-blend`&&n.buffers.color.setClear(0,0,0,0,a),(e.autoClear||r)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))}function h(t,n){let i=p(n);i&&(i.isCubeTexture||i.mapping===306)?(l===void 0&&(l=new iu(new dd(1,1,1),new Dd({name:`BackgroundCubeMaterial`,uniforms:yd(dp.backgroundCube.uniforms),vertexShader:dp.backgroundCube.vertexShader,fragmentShader:dp.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute(`normal`),l.geometry.deleteAttribute(`uv`),l.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(l)),l.material.uniforms.envMap.value=i,l.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(pp.makeRotationFromEuler(n.backgroundRotation)).transpose(),i.isCubeTexture&&i.isRenderTargetTexture===!1&&l.material.uniforms.backgroundRotation.value.premultiply(mp),l.material.toneMapped=Ls.getTransfer(i.colorSpace)!==Vo,(u!==i||d!==i.version||f!==e.toneMapping)&&(l.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null)):i&&i.isTexture&&(c===void 0&&(c=new iu(new _d(2,2),new Dd({name:`BackgroundMaterial`,uniforms:yd(dp.background.uniforms),vertexShader:dp.background.vertexShader,fragmentShader:dp.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute(`normal`),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(c)),c.material.uniforms.t2D.value=i,c.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,c.material.toneMapped=Ls.getTransfer(i.colorSpace)!==Vo,i.matrixAutoUpdate===!0&&i.updateMatrix(),c.material.uniforms.uvTransform.value.copy(i.matrix),(u!==i||d!==i.version||f!==e.toneMapping)&&(c.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),c.layers.enableAll(),t.unshift(c,c.geometry,c.material,0,0,null))}function g(t,r){t.getRGB(fp,Cd(e)),n.buffers.color.setClear(fp.r,fp.g,fp.b,r,a)}function _(){l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(e,t=1){o.set(e),s=t,g(o,s)},getClearAlpha:function(){return s},setClearAlpha:function(e){s=e,g(o,s)},render:m,addToRenderList:h,dispose:_}}function gp(e,t){let n=e.getParameter(e.MAX_VERTEX_ATTRIBS),r={},i=f(null),a=i,o=!1;function s(n,r,i,s,c){let u=!1,f=d(n,s,i,r);a!==f&&(a=f,l(a.object)),u=p(n,s,i,c),u&&m(n,s,i,c),c!==null&&t.update(c,e.ELEMENT_ARRAY_BUFFER),(u||o)&&(o=!1,b(n,r,i,s),c!==null&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(c).buffer))}function c(){return e.createVertexArray()}function l(t){return e.bindVertexArray(t)}function u(t){return e.deleteVertexArray(t)}function d(e,t,n,i){let a=i.wireframe===!0,o=r[t.id];o===void 0&&(o={},r[t.id]=o);let s=e.isInstancedMesh===!0?e.id:0,l=o[s];l===void 0&&(l={},o[s]=l);let u=l[n.id];u===void 0&&(u={},l[n.id]=u);let d=u[a];return d===void 0&&(d=f(c()),u[a]=d),d}function f(e){let t=[],r=[],i=[];for(let e=0;e<n;e++)t[e]=0,r[e]=0,i[e]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:r,attributeDivisors:i,object:e,attributes:{},index:null}}function p(e,t,n,r){let i=a.attributes,o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=i[t],r=o[t];if(r===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(r=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(r=e.instanceColor)),n===void 0||n.attribute!==r||r&&n.data!==r.data)return!0;s++}return a.attributesNum!==s||a.index!==r}function m(e,t,n,r){let i={},o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=o[t];n===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(n=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(n=e.instanceColor));let r={};r.attribute=n,n&&n.data&&(r.data=n.data),i[t]=r,s++}a.attributes=i,a.attributesNum=s,a.index=r}function h(){let e=a.newAttributes;for(let t=0,n=e.length;t<n;t++)e[t]=0}function g(e){_(e,0)}function _(t,n){let r=a.newAttributes,i=a.enabledAttributes,o=a.attributeDivisors;r[t]=1,i[t]===0&&(e.enableVertexAttribArray(t),i[t]=1),o[t]!==n&&(e.vertexAttribDivisor(t,n),o[t]=n)}function v(){let t=a.newAttributes,n=a.enabledAttributes;for(let r=0,i=n.length;r<i;r++)n[r]!==t[r]&&(e.disableVertexAttribArray(r),n[r]=0)}function y(t,n,r,i,a,o,s){s===!0?e.vertexAttribIPointer(t,n,r,a,o):e.vertexAttribPointer(t,n,r,i,a,o)}function b(n,r,i,a){h();let o=a.attributes,s=i.getAttributes(),c=r.defaultAttributeValues;for(let r in s){let i=s[r];if(i.location>=0){let s=o[r];if(s===void 0&&(r===`instanceMatrix`&&n.instanceMatrix&&(s=n.instanceMatrix),r===`instanceColor`&&n.instanceColor&&(s=n.instanceColor)),s!==void 0){let r=s.normalized,o=s.itemSize,c=t.get(s);if(c===void 0)continue;let l=c.buffer,u=c.type,d=c.bytesPerElement,f=u===e.INT||u===e.UNSIGNED_INT||s.gpuType===1013;if(s.isInterleavedBufferAttribute){let t=s.data,c=t.stride,p=s.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e<i.locationSize;e++)_(i.location+e,t.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=t.meshPerAttribute*t.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,c*d,(p+o/i.locationSize*e)*d,f)}else{if(s.isInstancedBufferAttribute){for(let e=0;e<i.locationSize;e++)_(i.location+e,s.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=s.meshPerAttribute*s.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,o*d,o/i.locationSize*e*d,f)}}else if(c!==void 0){let t=c[r];if(t!==void 0)switch(t.length){case 2:e.vertexAttrib2fv(i.location,t);break;case 3:e.vertexAttrib3fv(i.location,t);break;case 4:e.vertexAttrib4fv(i.location,t);break;default:e.vertexAttrib1fv(i.location,t)}}}}v()}function x(){T();for(let e in r){let t=r[e];for(let e in t){let n=t[e];for(let e in n){let t=n[e];for(let e in t)u(t[e].object),delete t[e];delete n[e]}}delete r[e]}}function S(e){if(r[e.id]===void 0)return;let t=r[e.id];for(let e in t){let n=t[e];for(let e in n){let t=n[e];for(let e in t)u(t[e].object),delete t[e];delete n[e]}}delete r[e.id]}function C(e){for(let t in r){let n=r[t];for(let t in n){let r=n[t];if(r[e.id]===void 0)continue;let i=r[e.id];for(let e in i)u(i[e].object),delete i[e];delete r[e.id]}}}function w(e){for(let t in r){let n=r[t],i=e.isInstancedMesh===!0?e.id:0,a=n[i];if(a!==void 0){for(let e in a){let t=a[e];for(let e in t)u(t[e].object),delete t[e];delete a[e]}delete n[i],Object.keys(n).length===0&&delete r[t]}}}function T(){E(),o=!0,a!==i&&(a=i,l(a.object))}function E(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:s,reset:T,resetDefaultState:E,dispose:x,releaseStatesOfGeometry:S,releaseStatesOfObject:w,releaseStatesOfProgram:C,initAttributes:h,enableAttribute:g,disableUnusedAttributes:v}}function _p(e,t,n){let r;function i(e){r=e}function a(t,i){e.drawArrays(r,t,i),n.update(i,r,1)}function o(t,i,a){a!==0&&(e.drawArraysInstanced(r,t,i,a),n.update(i,r,a))}function s(e,i,a){if(a===0)return;t.get(`WEBGL_multi_draw`).multiDrawArraysWEBGL(r,e,0,i,0,a);let o=0;for(let e=0;e<a;e++)o+=i[e];n.update(o,r,1)}this.setMode=i,this.render=a,this.renderInstances=o,this.renderMultiDraw=s}function vp(e,t,n,r){let i;function a(){if(i!==void 0)return i;if(t.has(`EXT_texture_filter_anisotropic`)===!0){let n=t.get(`EXT_texture_filter_anisotropic`);i=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function o(t){return!(t!==1023&&r.convert(t)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT))}function s(n){let i=n===1016&&(t.has(`EXT_color_buffer_half_float`)||t.has(`EXT_color_buffer_float`));return!(n!==1009&&r.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==1015&&!i)}function c(t){if(t===`highp`){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return`highp`;t=`mediump`}return t===`mediump`&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?`mediump`:`lowp`}let l=n.precision===void 0?`highp`:n.precision,u=c(l);u!==l&&(B(`WebGLRenderer:`,l,`not supported, using`,u,`instead.`),l=u);let d=n.logarithmicDepthBuffer===!0,f=n.reversedDepthBuffer===!0&&t.has(`EXT_clip_control`);n.reversedDepthBuffer===!0&&f===!1&&B(`WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.`);let p=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),m=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_TEXTURE_SIZE),g=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),_=e.getParameter(e.MAX_VERTEX_ATTRIBS),v=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),y=e.getParameter(e.MAX_VARYING_VECTORS),b=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),x=e.getParameter(e.MAX_SAMPLES),S=e.getParameter(e.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:s,precision:l,logarithmicDepthBuffer:d,reversedDepthBuffer:f,maxTextures:p,maxVertexTextures:m,maxTextureSize:h,maxCubemapSize:g,maxAttributes:_,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,maxSamples:x,samples:S}}function yp(e){let t=this,n=null,r=0,i=!1,a=!1,o=new Pu,s=new G,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){let n=e.length!==0||t||r!==0||i;return i=t,r=e.length,n},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(e,t){n=u(e,t,0)},this.setState=function(t,o,s){let d=t.clippingPlanes,f=t.clipIntersection,p=t.clipShadows,m=e.get(t);if(!i||d===null||d.length===0||a&&!p)a?u(null):l();else{let e=a?0:r,t=e*4,i=m.clippingState||null;c.value=i,i=u(d,o,t,s);for(let e=0;e!==t;++e)i[e]=n[e];m.clippingState=i,this.numIntersection=f?this.numPlanes:0,this.numPlanes+=e}};function l(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),t.numPlanes=r,t.numIntersection=0}function u(e,n,r,i){let a=e===null?0:e.length,l=null;if(a!==0){if(l=c.value,i!==!0||l===null){let t=r+a*4,i=n.matrixWorldInverse;s.getNormalMatrix(i),(l===null||l.length<t)&&(l=new Float32Array(t));for(let t=0,n=r;t!==a;++t,n+=4)o.copy(e[t]).applyMatrix4(i,s),o.normal.toArray(l,n),l[n+3]=o.constant}c.value=l,c.needsUpdate=!0}return t.numPlanes=a,t.numIntersection=0,l}}var bp=4,xp=[.125,.215,.35,.446,.526,.582],Sp=20,Cp=256,wp=new Of,Tp=new q,Ep=null,Dp=0,Op=0,kp=!1,Ap=new W,jp=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,r=100,i={}){let{size:a=256,position:o=Ap}=i;Ep=this._renderer.getRenderTarget(),Dp=this._renderer.getActiveCubeFace(),Op=this._renderer.getActiveMipmapLevel(),kp=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);let s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,n,r,s,o),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Rp(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Lp(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=2**this._lodMax}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(Ep,Dp,Op),this._renderer.xr.enabled=kp,e.scissorTest=!1,Pp(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===301||e.mapping===302?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),Ep=this._renderer.getRenderTarget(),Dp=this._renderer.getActiveCubeFace(),Op=this._renderer.getActiveMipmapLevel(),kp=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){let e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:ha,minFilter:ha,generateMipmaps:!1,type:Ta,format:Na,colorSpace:zo,depthBuffer:!1},r=Np(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Np(e,t,n);let{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=Mp(r)),this._blurMaterial=Ip(r,e,t),this._ggxMaterial=Fp(r,e,t)}return r}_compileMaterial(e){let t=new iu(new Y,e);this._renderer.compile(t,wp)}_sceneToCubeUV(e,t,n,r,i){let a=new Cf(90,1,t,n),o=[1,-1,1,1,1,1],s=[1,1,1,-1,-1,-1],c=this._renderer,l=c.autoClear,u=c.toneMapping;c.getClearColor(Tp),c.toneMapping=0,c.autoClear=!1,c.state.buffers.depth.getReversed()&&(c.setRenderTarget(r),c.clearDepth(),c.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new iu(new dd,new Kl({name:`PMREM.Background`,side:1,depthWrite:!1,depthTest:!1})));let d=this._backgroundBox,f=d.material,p=!1,m=e.background;m?m.isColor&&(f.color.copy(m),e.background=null,p=!0):(f.color.copy(Tp),p=!0);for(let t=0;t<6;t++){let n=t%3;n===0?(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x+s[t],i.y,i.z)):n===1?(a.up.set(0,0,o[t]),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y+s[t],i.z)):(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y,i.z+s[t]));let l=this._cubeSize;Pp(r,n*l,t>2?l:0,l,l),c.setRenderTarget(r),p&&c.render(d,a),c.render(e,a)}c.toneMapping=u,c.autoClear=l,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,r=e.mapping===301||e.mapping===302;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=Rp()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Lp());let i=r?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=i;let o=i.uniforms;o.envMap.value=e;let s=this._cubeSize;Pp(t,0,0,3*s,2*s),n.setRenderTarget(t),n.render(a,wp)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let r=this._lodMeshes.length;for(let t=1;t<r;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=n}_applyGGXFilter(e,t,n){let r=this._renderer,i=this._pingPongRenderTarget,a=this._ggxMaterial,o=this._lodMeshes[n];o.material=a;let s=a.uniforms,c=n/(this._lodMeshes.length-1),l=t/(this._lodMeshes.length-1),u=Math.sqrt(c*c-l*l)*(0+c*1.25),{_lodMax:d}=this,f=this._sizeLods[n],p=3*f*(n>d-bp?n-d+bp:0),m=4*(this._cubeSize-f);s.envMap.value=e.texture,s.roughness.value=u,s.mipInt.value=d-t,Pp(i,p,m,3*f,2*f),r.setRenderTarget(i),r.render(o,wp),s.envMap.value=i.texture,s.roughness.value=0,s.mipInt.value=d-n,Pp(e,p,m,3*f,2*f),r.setRenderTarget(e),r.render(o,wp)}_blur(e,t,n,r,i){let a=this._pingPongRenderTarget;this._halfBlur(e,a,t,n,r,`latitudinal`,i),this._halfBlur(a,e,n,n,r,`longitudinal`,i)}_halfBlur(e,t,n,r,i,a,o){let s=this._renderer,c=this._blurMaterial;a!==`latitudinal`&&a!==`longitudinal`&&V(`blur direction must be either latitudinal or longitudinal!`);let l=this._lodMeshes[r];l.material=c;let u=c.uniforms,d=this._sizeLods[n]-1,f=isFinite(i)?Math.PI/(2*d):2*Math.PI/(2*Sp-1),p=i/f,m=isFinite(i)?1+Math.floor(3*p):Sp;m>Sp&&B(`sigmaRadians, ${i}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${Sp}`);let h=[],g=0;for(let e=0;e<Sp;++e){let t=e/p,n=Math.exp(-t*t/2);h.push(n),e===0?g+=n:e<m&&(g+=2*n)}for(let e=0;e<h.length;e++)h[e]=h[e]/g;u.envMap.value=e.texture,u.samples.value=m,u.weights.value=h,u.latitudinal.value=a===`latitudinal`,o&&(u.poleAxis.value=o);let{_lodMax:_}=this;u.dTheta.value=f,u.mipInt.value=_-n;let v=this._sizeLods[r];Pp(t,3*v*(r>_-bp?r-_+bp:0),4*(this._cubeSize-v),3*v,2*v),s.setRenderTarget(t),s.render(l,wp)}};function Mp(e){let t=[],n=[],r=[],i=e,a=e-bp+1+xp.length;for(let o=0;o<a;o++){let a=2**i;t.push(a);let s=1/a;o>e-bp?s=xp[o-e+bp-1]:o===0&&(s=0),n.push(s);let c=1/(a-2),l=-c,u=1+c,d=[l,l,u,l,u,u,l,l,u,u,l,u],f=new Float32Array(108),p=new Float32Array(72),m=new Float32Array(36);for(let e=0;e<6;e++){let t=e%3*2/3-1,n=e>2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];f.set(r,18*e),p.set(d,12*e);let i=[e,e,e,e,e,e];m.set(i,6*e)}let h=new Y;h.setAttribute(`position`,new J(f,3)),h.setAttribute(`uv`,new J(p,2)),h.setAttribute(`faceIndex`,new J(m,1)),r.push(new iu(h,null)),i>bp&&i--}return{lodMeshes:r,sizeLods:t,sigmas:n}}function Np(e,t,n){let r=new Xs(e,t,n);return r.texture.mapping=306,r.texture.name=`PMREM.cubeUv`,r.scissorTest=!0,r}function Pp(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function Fp(e,t,n){return new Dd({name:`PMREMGGXConvolution`,defines:{GGX_SAMPLES:Cp,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:zp(),fragmentShader:`
|
|
3669
|
+
}`},X={common:{diffuse:{value:new q(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new G},alphaMap:{value:null},alphaMapTransform:{value:new G},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new G}},envmap:{envMap:{value:null},envMapRotation:{value:new G},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new G}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new G}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new G},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new G},normalScale:{value:new H(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new G},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new G}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new G}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new G}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new q(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new W},probesMax:{value:new W},probesResolution:{value:new W}},points:{diffuse:{value:new q(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new G},alphaTest:{value:0},uvTransform:{value:new G}},sprite:{diffuse:{value:new q(16777215)},opacity:{value:1},center:{value:new H(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new G},alphaMap:{value:null},alphaMapTransform:{value:new G},alphaTest:{value:0}}},fp={basic:{uniforms:bd([X.common,X.specularmap,X.envmap,X.aomap,X.lightmap,X.fog]),vertexShader:dp.meshbasic_vert,fragmentShader:dp.meshbasic_frag},lambert:{uniforms:bd([X.common,X.specularmap,X.envmap,X.aomap,X.lightmap,X.emissivemap,X.bumpmap,X.normalmap,X.displacementmap,X.fog,X.lights,{emissive:{value:new q(0)},envMapIntensity:{value:1}}]),vertexShader:dp.meshlambert_vert,fragmentShader:dp.meshlambert_frag},phong:{uniforms:bd([X.common,X.specularmap,X.envmap,X.aomap,X.lightmap,X.emissivemap,X.bumpmap,X.normalmap,X.displacementmap,X.fog,X.lights,{emissive:{value:new q(0)},specular:{value:new q(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:dp.meshphong_vert,fragmentShader:dp.meshphong_frag},standard:{uniforms:bd([X.common,X.envmap,X.aomap,X.lightmap,X.emissivemap,X.bumpmap,X.normalmap,X.displacementmap,X.roughnessmap,X.metalnessmap,X.fog,X.lights,{emissive:{value:new q(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:dp.meshphysical_vert,fragmentShader:dp.meshphysical_frag},toon:{uniforms:bd([X.common,X.aomap,X.lightmap,X.emissivemap,X.bumpmap,X.normalmap,X.displacementmap,X.gradientmap,X.fog,X.lights,{emissive:{value:new q(0)}}]),vertexShader:dp.meshtoon_vert,fragmentShader:dp.meshtoon_frag},matcap:{uniforms:bd([X.common,X.bumpmap,X.normalmap,X.displacementmap,X.fog,{matcap:{value:null}}]),vertexShader:dp.meshmatcap_vert,fragmentShader:dp.meshmatcap_frag},points:{uniforms:bd([X.points,X.fog]),vertexShader:dp.points_vert,fragmentShader:dp.points_frag},dashed:{uniforms:bd([X.common,X.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:dp.linedashed_vert,fragmentShader:dp.linedashed_frag},depth:{uniforms:bd([X.common,X.displacementmap]),vertexShader:dp.depth_vert,fragmentShader:dp.depth_frag},normal:{uniforms:bd([X.common,X.bumpmap,X.normalmap,X.displacementmap,{opacity:{value:1}}]),vertexShader:dp.meshnormal_vert,fragmentShader:dp.meshnormal_frag},sprite:{uniforms:bd([X.sprite,X.fog]),vertexShader:dp.sprite_vert,fragmentShader:dp.sprite_frag},background:{uniforms:{uvTransform:{value:new G},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:dp.background_vert,fragmentShader:dp.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new G}},vertexShader:dp.backgroundCube_vert,fragmentShader:dp.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:dp.cube_vert,fragmentShader:dp.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:dp.equirect_vert,fragmentShader:dp.equirect_frag},distance:{uniforms:bd([X.common,X.displacementmap,{referencePosition:{value:new W},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:dp.distance_vert,fragmentShader:dp.distance_frag},shadow:{uniforms:bd([X.lights,X.fog,{color:{value:new q(0)},opacity:{value:1}}]),vertexShader:dp.shadow_vert,fragmentShader:dp.shadow_frag}};fp.physical={uniforms:bd([fp.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new G},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new G},clearcoatNormalScale:{value:new H(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new G},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new G},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new G},sheen:{value:0},sheenColor:{value:new q(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new G},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new G},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new G},transmissionSamplerSize:{value:new H},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new G},attenuationDistance:{value:0},attenuationColor:{value:new q(0)},specularColor:{value:new q(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new G},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new G},anisotropyVector:{value:new H},anisotropyMap:{value:null},anisotropyMapTransform:{value:new G}}]),vertexShader:dp.meshphysical_vert,fragmentShader:dp.meshphysical_frag};var pp={r:0,b:0,g:0},mp=new K,hp=new G;hp.set(-1,0,0,0,1,0,0,0,1);function gp(e,t,n,r,i,a){let o=new q(0),s=i===!0?0:1,c,l,u=null,d=0,f=null;function p(e){let n=e.isScene===!0?e.background:null;if(n&&n.isTexture){let r=e.backgroundBlurriness>0;n=t.get(n,r)}return n}function m(t){let r=!1,i=p(t);i===null?g(o,s):i&&i.isColor&&(g(i,1),r=!0);let c=e.xr.getEnvironmentBlendMode();c===`additive`?n.buffers.color.setClear(0,0,0,1,a):c===`alpha-blend`&&n.buffers.color.setClear(0,0,0,0,a),(e.autoClear||r)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))}function h(t,n){let i=p(n);i&&(i.isCubeTexture||i.mapping===306)?(l===void 0&&(l=new iu(new dd(1,1,1),new Dd({name:`BackgroundCubeMaterial`,uniforms:yd(fp.backgroundCube.uniforms),vertexShader:fp.backgroundCube.vertexShader,fragmentShader:fp.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute(`normal`),l.geometry.deleteAttribute(`uv`),l.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(l)),l.material.uniforms.envMap.value=i,l.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(mp.makeRotationFromEuler(n.backgroundRotation)).transpose(),i.isCubeTexture&&i.isRenderTargetTexture===!1&&l.material.uniforms.backgroundRotation.value.premultiply(hp),l.material.toneMapped=Ls.getTransfer(i.colorSpace)!==Vo,(u!==i||d!==i.version||f!==e.toneMapping)&&(l.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null)):i&&i.isTexture&&(c===void 0&&(c=new iu(new _d(2,2),new Dd({name:`BackgroundMaterial`,uniforms:yd(fp.background.uniforms),vertexShader:fp.background.vertexShader,fragmentShader:fp.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute(`normal`),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(c)),c.material.uniforms.t2D.value=i,c.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,c.material.toneMapped=Ls.getTransfer(i.colorSpace)!==Vo,i.matrixAutoUpdate===!0&&i.updateMatrix(),c.material.uniforms.uvTransform.value.copy(i.matrix),(u!==i||d!==i.version||f!==e.toneMapping)&&(c.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),c.layers.enableAll(),t.unshift(c,c.geometry,c.material,0,0,null))}function g(t,r){t.getRGB(pp,Cd(e)),n.buffers.color.setClear(pp.r,pp.g,pp.b,r,a)}function _(){l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(e,t=1){o.set(e),s=t,g(o,s)},getClearAlpha:function(){return s},setClearAlpha:function(e){s=e,g(o,s)},render:m,addToRenderList:h,dispose:_}}function _p(e,t){let n=e.getParameter(e.MAX_VERTEX_ATTRIBS),r={},i=f(null),a=i,o=!1;function s(n,r,i,s,c){let u=!1,f=d(n,s,i,r);a!==f&&(a=f,l(a.object)),u=p(n,s,i,c),u&&m(n,s,i,c),c!==null&&t.update(c,e.ELEMENT_ARRAY_BUFFER),(u||o)&&(o=!1,b(n,r,i,s),c!==null&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(c).buffer))}function c(){return e.createVertexArray()}function l(t){return e.bindVertexArray(t)}function u(t){return e.deleteVertexArray(t)}function d(e,t,n,i){let a=i.wireframe===!0,o=r[t.id];o===void 0&&(o={},r[t.id]=o);let s=e.isInstancedMesh===!0?e.id:0,l=o[s];l===void 0&&(l={},o[s]=l);let u=l[n.id];u===void 0&&(u={},l[n.id]=u);let d=u[a];return d===void 0&&(d=f(c()),u[a]=d),d}function f(e){let t=[],r=[],i=[];for(let e=0;e<n;e++)t[e]=0,r[e]=0,i[e]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:r,attributeDivisors:i,object:e,attributes:{},index:null}}function p(e,t,n,r){let i=a.attributes,o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=i[t],r=o[t];if(r===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(r=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(r=e.instanceColor)),n===void 0||n.attribute!==r||r&&n.data!==r.data)return!0;s++}return a.attributesNum!==s||a.index!==r}function m(e,t,n,r){let i={},o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=o[t];n===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(n=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(n=e.instanceColor));let r={};r.attribute=n,n&&n.data&&(r.data=n.data),i[t]=r,s++}a.attributes=i,a.attributesNum=s,a.index=r}function h(){let e=a.newAttributes;for(let t=0,n=e.length;t<n;t++)e[t]=0}function g(e){_(e,0)}function _(t,n){let r=a.newAttributes,i=a.enabledAttributes,o=a.attributeDivisors;r[t]=1,i[t]===0&&(e.enableVertexAttribArray(t),i[t]=1),o[t]!==n&&(e.vertexAttribDivisor(t,n),o[t]=n)}function v(){let t=a.newAttributes,n=a.enabledAttributes;for(let r=0,i=n.length;r<i;r++)n[r]!==t[r]&&(e.disableVertexAttribArray(r),n[r]=0)}function y(t,n,r,i,a,o,s){s===!0?e.vertexAttribIPointer(t,n,r,a,o):e.vertexAttribPointer(t,n,r,i,a,o)}function b(n,r,i,a){h();let o=a.attributes,s=i.getAttributes(),c=r.defaultAttributeValues;for(let r in s){let i=s[r];if(i.location>=0){let s=o[r];if(s===void 0&&(r===`instanceMatrix`&&n.instanceMatrix&&(s=n.instanceMatrix),r===`instanceColor`&&n.instanceColor&&(s=n.instanceColor)),s!==void 0){let r=s.normalized,o=s.itemSize,c=t.get(s);if(c===void 0)continue;let l=c.buffer,u=c.type,d=c.bytesPerElement,f=u===e.INT||u===e.UNSIGNED_INT||s.gpuType===1013;if(s.isInterleavedBufferAttribute){let t=s.data,c=t.stride,p=s.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e<i.locationSize;e++)_(i.location+e,t.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=t.meshPerAttribute*t.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,c*d,(p+o/i.locationSize*e)*d,f)}else{if(s.isInstancedBufferAttribute){for(let e=0;e<i.locationSize;e++)_(i.location+e,s.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=s.meshPerAttribute*s.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,o*d,o/i.locationSize*e*d,f)}}else if(c!==void 0){let t=c[r];if(t!==void 0)switch(t.length){case 2:e.vertexAttrib2fv(i.location,t);break;case 3:e.vertexAttrib3fv(i.location,t);break;case 4:e.vertexAttrib4fv(i.location,t);break;default:e.vertexAttrib1fv(i.location,t)}}}}v()}function x(){T();for(let e in r){let t=r[e];for(let e in t){let n=t[e];for(let e in n){let t=n[e];for(let e in t)u(t[e].object),delete t[e];delete n[e]}}delete r[e]}}function S(e){if(r[e.id]===void 0)return;let t=r[e.id];for(let e in t){let n=t[e];for(let e in n){let t=n[e];for(let e in t)u(t[e].object),delete t[e];delete n[e]}}delete r[e.id]}function C(e){for(let t in r){let n=r[t];for(let t in n){let r=n[t];if(r[e.id]===void 0)continue;let i=r[e.id];for(let e in i)u(i[e].object),delete i[e];delete r[e.id]}}}function w(e){for(let t in r){let n=r[t],i=e.isInstancedMesh===!0?e.id:0,a=n[i];if(a!==void 0){for(let e in a){let t=a[e];for(let e in t)u(t[e].object),delete t[e];delete a[e]}delete n[i],Object.keys(n).length===0&&delete r[t]}}}function T(){E(),o=!0,a!==i&&(a=i,l(a.object))}function E(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:s,reset:T,resetDefaultState:E,dispose:x,releaseStatesOfGeometry:S,releaseStatesOfObject:w,releaseStatesOfProgram:C,initAttributes:h,enableAttribute:g,disableUnusedAttributes:v}}function vp(e,t,n){let r;function i(e){r=e}function a(t,i){e.drawArrays(r,t,i),n.update(i,r,1)}function o(t,i,a){a!==0&&(e.drawArraysInstanced(r,t,i,a),n.update(i,r,a))}function s(e,i,a){if(a===0)return;t.get(`WEBGL_multi_draw`).multiDrawArraysWEBGL(r,e,0,i,0,a);let o=0;for(let e=0;e<a;e++)o+=i[e];n.update(o,r,1)}this.setMode=i,this.render=a,this.renderInstances=o,this.renderMultiDraw=s}function yp(e,t,n,r){let i;function a(){if(i!==void 0)return i;if(t.has(`EXT_texture_filter_anisotropic`)===!0){let n=t.get(`EXT_texture_filter_anisotropic`);i=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function o(t){return!(t!==1023&&r.convert(t)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT))}function s(n){let i=n===1016&&(t.has(`EXT_color_buffer_half_float`)||t.has(`EXT_color_buffer_float`));return!(n!==1009&&r.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==1015&&!i)}function c(t){if(t===`highp`){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return`highp`;t=`mediump`}return t===`mediump`&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?`mediump`:`lowp`}let l=n.precision===void 0?`highp`:n.precision,u=c(l);u!==l&&(B(`WebGLRenderer:`,l,`not supported, using`,u,`instead.`),l=u);let d=n.logarithmicDepthBuffer===!0,f=n.reversedDepthBuffer===!0&&t.has(`EXT_clip_control`);n.reversedDepthBuffer===!0&&f===!1&&B(`WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.`);let p=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),m=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_TEXTURE_SIZE),g=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),_=e.getParameter(e.MAX_VERTEX_ATTRIBS),v=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),y=e.getParameter(e.MAX_VARYING_VECTORS),b=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),x=e.getParameter(e.MAX_SAMPLES),S=e.getParameter(e.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:s,precision:l,logarithmicDepthBuffer:d,reversedDepthBuffer:f,maxTextures:p,maxVertexTextures:m,maxTextureSize:h,maxCubemapSize:g,maxAttributes:_,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,maxSamples:x,samples:S}}function bp(e){let t=this,n=null,r=0,i=!1,a=!1,o=new Pu,s=new G,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){let n=e.length!==0||t||r!==0||i;return i=t,r=e.length,n},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(e,t){n=u(e,t,0)},this.setState=function(t,o,s){let d=t.clippingPlanes,f=t.clipIntersection,p=t.clipShadows,m=e.get(t);if(!i||d===null||d.length===0||a&&!p)a?u(null):l();else{let e=a?0:r,t=e*4,i=m.clippingState||null;c.value=i,i=u(d,o,t,s);for(let e=0;e!==t;++e)i[e]=n[e];m.clippingState=i,this.numIntersection=f?this.numPlanes:0,this.numPlanes+=e}};function l(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),t.numPlanes=r,t.numIntersection=0}function u(e,n,r,i){let a=e===null?0:e.length,l=null;if(a!==0){if(l=c.value,i!==!0||l===null){let t=r+a*4,i=n.matrixWorldInverse;s.getNormalMatrix(i),(l===null||l.length<t)&&(l=new Float32Array(t));for(let t=0,n=r;t!==a;++t,n+=4)o.copy(e[t]).applyMatrix4(i,s),o.normal.toArray(l,n),l[n+3]=o.constant}c.value=l,c.needsUpdate=!0}return t.numPlanes=a,t.numIntersection=0,l}}var xp=4,Sp=[.125,.215,.35,.446,.526,.582],Cp=20,wp=256,Tp=new Of,Ep=new q,Dp=null,Op=0,kp=0,Ap=!1,jp=new W,Mp=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,r=100,i={}){let{size:a=256,position:o=jp}=i;Dp=this._renderer.getRenderTarget(),Op=this._renderer.getActiveCubeFace(),kp=this._renderer.getActiveMipmapLevel(),Ap=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);let s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,n,r,s,o),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=zp(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Rp(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=2**this._lodMax}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(Dp,Op,kp),this._renderer.xr.enabled=Ap,e.scissorTest=!1,Fp(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===301||e.mapping===302?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),Dp=this._renderer.getRenderTarget(),Op=this._renderer.getActiveCubeFace(),kp=this._renderer.getActiveMipmapLevel(),Ap=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){let e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:ha,minFilter:ha,generateMipmaps:!1,type:Ta,format:Na,colorSpace:zo,depthBuffer:!1},r=Pp(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Pp(e,t,n);let{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=Np(r)),this._blurMaterial=Lp(r,e,t),this._ggxMaterial=Ip(r,e,t)}return r}_compileMaterial(e){let t=new iu(new Y,e);this._renderer.compile(t,Tp)}_sceneToCubeUV(e,t,n,r,i){let a=new Cf(90,1,t,n),o=[1,-1,1,1,1,1],s=[1,1,1,-1,-1,-1],c=this._renderer,l=c.autoClear,u=c.toneMapping;c.getClearColor(Ep),c.toneMapping=0,c.autoClear=!1,c.state.buffers.depth.getReversed()&&(c.setRenderTarget(r),c.clearDepth(),c.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new iu(new dd,new Kl({name:`PMREM.Background`,side:1,depthWrite:!1,depthTest:!1})));let d=this._backgroundBox,f=d.material,p=!1,m=e.background;m?m.isColor&&(f.color.copy(m),e.background=null,p=!0):(f.color.copy(Ep),p=!0);for(let t=0;t<6;t++){let n=t%3;n===0?(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x+s[t],i.y,i.z)):n===1?(a.up.set(0,0,o[t]),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y+s[t],i.z)):(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y,i.z+s[t]));let l=this._cubeSize;Fp(r,n*l,t>2?l:0,l,l),c.setRenderTarget(r),p&&c.render(d,a),c.render(e,a)}c.toneMapping=u,c.autoClear=l,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,r=e.mapping===301||e.mapping===302;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=zp()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Rp());let i=r?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=i;let o=i.uniforms;o.envMap.value=e;let s=this._cubeSize;Fp(t,0,0,3*s,2*s),n.setRenderTarget(t),n.render(a,Tp)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let r=this._lodMeshes.length;for(let t=1;t<r;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=n}_applyGGXFilter(e,t,n){let r=this._renderer,i=this._pingPongRenderTarget,a=this._ggxMaterial,o=this._lodMeshes[n];o.material=a;let s=a.uniforms,c=n/(this._lodMeshes.length-1),l=t/(this._lodMeshes.length-1),u=Math.sqrt(c*c-l*l)*(0+c*1.25),{_lodMax:d}=this,f=this._sizeLods[n],p=3*f*(n>d-xp?n-d+xp:0),m=4*(this._cubeSize-f);s.envMap.value=e.texture,s.roughness.value=u,s.mipInt.value=d-t,Fp(i,p,m,3*f,2*f),r.setRenderTarget(i),r.render(o,Tp),s.envMap.value=i.texture,s.roughness.value=0,s.mipInt.value=d-n,Fp(e,p,m,3*f,2*f),r.setRenderTarget(e),r.render(o,Tp)}_blur(e,t,n,r,i){let a=this._pingPongRenderTarget;this._halfBlur(e,a,t,n,r,`latitudinal`,i),this._halfBlur(a,e,n,n,r,`longitudinal`,i)}_halfBlur(e,t,n,r,i,a,o){let s=this._renderer,c=this._blurMaterial;a!==`latitudinal`&&a!==`longitudinal`&&V(`blur direction must be either latitudinal or longitudinal!`);let l=this._lodMeshes[r];l.material=c;let u=c.uniforms,d=this._sizeLods[n]-1,f=isFinite(i)?Math.PI/(2*d):2*Math.PI/(2*Cp-1),p=i/f,m=isFinite(i)?1+Math.floor(3*p):Cp;m>Cp&&B(`sigmaRadians, ${i}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${Cp}`);let h=[],g=0;for(let e=0;e<Cp;++e){let t=e/p,n=Math.exp(-t*t/2);h.push(n),e===0?g+=n:e<m&&(g+=2*n)}for(let e=0;e<h.length;e++)h[e]=h[e]/g;u.envMap.value=e.texture,u.samples.value=m,u.weights.value=h,u.latitudinal.value=a===`latitudinal`,o&&(u.poleAxis.value=o);let{_lodMax:_}=this;u.dTheta.value=f,u.mipInt.value=_-n;let v=this._sizeLods[r];Fp(t,3*v*(r>_-xp?r-_+xp:0),4*(this._cubeSize-v),3*v,2*v),s.setRenderTarget(t),s.render(l,Tp)}};function Np(e){let t=[],n=[],r=[],i=e,a=e-xp+1+Sp.length;for(let o=0;o<a;o++){let a=2**i;t.push(a);let s=1/a;o>e-xp?s=Sp[o-e+xp-1]:o===0&&(s=0),n.push(s);let c=1/(a-2),l=-c,u=1+c,d=[l,l,u,l,u,u,l,l,u,u,l,u],f=new Float32Array(108),p=new Float32Array(72),m=new Float32Array(36);for(let e=0;e<6;e++){let t=e%3*2/3-1,n=e>2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];f.set(r,18*e),p.set(d,12*e);let i=[e,e,e,e,e,e];m.set(i,6*e)}let h=new Y;h.setAttribute(`position`,new J(f,3)),h.setAttribute(`uv`,new J(p,2)),h.setAttribute(`faceIndex`,new J(m,1)),r.push(new iu(h,null)),i>xp&&i--}return{lodMeshes:r,sizeLods:t,sigmas:n}}function Pp(e,t,n){let r=new Xs(e,t,n);return r.texture.mapping=306,r.texture.name=`PMREM.cubeUv`,r.scissorTest=!0,r}function Fp(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function Ip(e,t,n){return new Dd({name:`PMREMGGXConvolution`,defines:{GGX_SAMPLES:wp,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Bp(),fragmentShader:`
|
|
3670
3670
|
|
|
3671
3671
|
precision highp float;
|
|
3672
3672
|
precision highp int;
|
|
@@ -3770,7 +3770,7 @@ void main() {
|
|
|
3770
3770
|
|
|
3771
3771
|
gl_FragColor = vec4(prefilteredColor, 1.0);
|
|
3772
3772
|
}
|
|
3773
|
-
`,blending:0,depthTest:!1,depthWrite:!1})}function
|
|
3773
|
+
`,blending:0,depthTest:!1,depthWrite:!1})}function Lp(e,t,n){let r=new Float32Array(Cp),i=new W(0,1,0);return new Dd({name:`SphericalGaussianBlur`,defines:{n:Cp,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:Bp(),fragmentShader:`
|
|
3774
3774
|
|
|
3775
3775
|
precision mediump float;
|
|
3776
3776
|
precision mediump int;
|
|
@@ -3830,7 +3830,7 @@ void main() {
|
|
|
3830
3830
|
}
|
|
3831
3831
|
|
|
3832
3832
|
}
|
|
3833
|
-
`,blending:0,depthTest:!1,depthWrite:!1})}function
|
|
3833
|
+
`,blending:0,depthTest:!1,depthWrite:!1})}function Rp(){return new Dd({name:`EquirectangularToCubeUV`,uniforms:{envMap:{value:null}},vertexShader:Bp(),fragmentShader:`
|
|
3834
3834
|
|
|
3835
3835
|
precision mediump float;
|
|
3836
3836
|
precision mediump int;
|
|
@@ -3849,7 +3849,7 @@ void main() {
|
|
|
3849
3849
|
gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
|
|
3850
3850
|
|
|
3851
3851
|
}
|
|
3852
|
-
`,blending:0,depthTest:!1,depthWrite:!1})}function
|
|
3852
|
+
`,blending:0,depthTest:!1,depthWrite:!1})}function zp(){return new Dd({name:`CubemapToCubeUV`,uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Bp(),fragmentShader:`
|
|
3853
3853
|
|
|
3854
3854
|
precision mediump float;
|
|
3855
3855
|
precision mediump int;
|
|
@@ -3865,7 +3865,7 @@ void main() {
|
|
|
3865
3865
|
gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
|
|
3866
3866
|
|
|
3867
3867
|
}
|
|
3868
|
-
`,blending:0,depthTest:!1,depthWrite:!1})}function
|
|
3868
|
+
`,blending:0,depthTest:!1,depthWrite:!1})}function Bp(){return`
|
|
3869
3869
|
|
|
3870
3870
|
precision mediump float;
|
|
3871
3871
|
precision mediump int;
|
|
@@ -3920,7 +3920,7 @@ void main() {
|
|
|
3920
3920
|
gl_Position = vec4( position, 1.0 );
|
|
3921
3921
|
|
|
3922
3922
|
}
|
|
3923
|
-
`}var
|
|
3923
|
+
`}var Vp=class extends Xs{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1},r=[n,n,n,n,n,n];this.texture=new od(r),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;let n={uniforms:{tEquirect:{value:null}},vertexShader:`
|
|
3924
3924
|
|
|
3925
3925
|
varying vec3 vWorldDirection;
|
|
3926
3926
|
|
|
@@ -3955,7 +3955,7 @@ void main() {
|
|
|
3955
3955
|
gl_FragColor = texture2D( tEquirect, sampleUV );
|
|
3956
3956
|
|
|
3957
3957
|
}
|
|
3958
|
-
`},r=new dd(5,5,5),i=new Dd({name:`CubemapFromEquirect`,uniforms:yd(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});i.uniforms.tEquirect.value=t;let a=new iu(r,i),o=t.minFilter;return t.minFilter===1008&&(t.minFilter=ha),new Lf(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,r=!0){let i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,n,r);e.setRenderTarget(i)}};function
|
|
3958
|
+
`},r=new dd(5,5,5),i=new Dd({name:`CubemapFromEquirect`,uniforms:yd(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});i.uniforms.tEquirect.value=t;let a=new iu(r,i),o=t.minFilter;return t.minFilter===1008&&(t.minFilter=ha),new Lf(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,r=!0){let i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,n,r);e.setRenderTarget(i)}};function Hp(e){let t=new WeakMap,n=new WeakMap,r=null;function i(e,t=!1){return e==null?null:t?o(e):a(e)}function a(n){if(n&&n.isTexture){let r=n.mapping;if(r===303||r===304)if(t.has(n)){let e=t.get(n).texture;return s(e,n.mapping)}else{let r=n.image;if(r&&r.height>0){let i=new Vp(r.height);return i.fromEquirectangularTexture(e,n),t.set(n,i),n.addEventListener(`dispose`,l),s(i.texture,n.mapping)}else return null}}return n}function o(t){if(t&&t.isTexture){let i=t.mapping,a=i===303||i===304,o=i===301||i===302;if(a||o){let i=n.get(t),s=i===void 0?0:i.texture.pmremVersion;if(t.isRenderTargetTexture&&t.pmremVersion!==s)return r===null&&(r=new Mp(e)),i=a?r.fromEquirectangular(t,i):r.fromCubemap(t,i),i.texture.pmremVersion=t.pmremVersion,n.set(t,i),i.texture;if(i!==void 0)return i.texture;{let s=t.image;return a&&s&&s.height>0||o&&s&&c(s)?(r===null&&(r=new Mp(e)),i=a?r.fromEquirectangular(t):r.fromCubemap(t),i.texture.pmremVersion=t.pmremVersion,n.set(t,i),t.addEventListener(`dispose`,u),i.texture):null}}}return t}function s(e,t){return t===303?e.mapping=301:t===304&&(e.mapping=302),e}function c(e){let t=0;for(let n=0;n<6;n++)e[n]!==void 0&&t++;return t===6}function l(e){let n=e.target;n.removeEventListener(`dispose`,l);let r=t.get(n);r!==void 0&&(t.delete(n),r.dispose())}function u(e){let t=e.target;t.removeEventListener(`dispose`,u);let r=n.get(t);r!==void 0&&(n.delete(t),r.dispose())}function d(){t=new WeakMap,n=new WeakMap,r!==null&&(r.dispose(),r=null)}return{get:i,dispose:d}}function Up(e){let t={};function n(n){if(t[n]!==void 0)return t[n];let r=e.getExtension(n);return t[n]=r,r}return{has:function(e){return n(e)!==null},init:function(){n(`EXT_color_buffer_float`),n(`WEBGL_clip_cull_distance`),n(`OES_texture_float_linear`),n(`EXT_color_buffer_half_float`),n(`WEBGL_multisampled_render_to_texture`),n(`WEBGL_render_shared_exponent`)},get:function(e){let t=n(e);return t===null&&es(`WebGLRenderer: `+e+` extension not supported.`),t}}}function Wp(e,t,n,r){let i={},a=new WeakMap;function o(e){let s=e.target;s.index!==null&&t.remove(s.index);for(let e in s.attributes)t.remove(s.attributes[e]);s.removeEventListener(`dispose`,o),delete i[s.id];let c=a.get(s);c&&(t.remove(c),a.delete(s)),r.releaseStatesOfGeometry(s),s.isInstancedBufferGeometry===!0&&delete s._maxInstanceCount,n.memory.geometries--}function s(e,t){return i[t.id]===!0?t:(t.addEventListener(`dispose`,o),i[t.id]=!0,n.memory.geometries++,t)}function c(n){let r=n.attributes;for(let n in r)t.update(r[n],e.ARRAY_BUFFER)}function l(e){let n=[],r=e.index,i=e.attributes.position,o=0;if(i===void 0)return;if(r!==null){let e=r.array;o=r.version;for(let t=0,r=e.length;t<r;t+=3){let r=e[t+0],i=e[t+1],a=e[t+2];n.push(r,i,i,a,a,r)}}else{let e=i.array;o=i.version;for(let t=0,r=e.length/3-1;t<r;t+=3){let e=t+0,r=t+1,i=t+2;n.push(e,r,r,i,i,e)}}let s=new(i.count>=65535?bl:yl)(n,1);s.version=o;let c=a.get(e);c&&t.remove(c),a.set(e,s)}function u(e){let t=a.get(e);if(t){let n=e.index;n!==null&&t.version<n.version&&l(e)}else l(e);return a.get(e)}return{get:s,update:c,getWireframeAttribute:u}}function Gp(e,t,n){let r;function i(e){r=e}let a,o;function s(e){a=e.type,o=e.bytesPerElement}function c(t,i){e.drawElements(r,i,a,t*o),n.update(i,r,1)}function l(t,i,s){s!==0&&(e.drawElementsInstanced(r,i,a,t*o,s),n.update(i,r,s))}function u(e,i,o){if(o===0)return;t.get(`WEBGL_multi_draw`).multiDrawElementsWEBGL(r,i,0,a,e,0,o);let s=0;for(let e=0;e<o;e++)s+=i[e];n.update(s,r,1)}this.setMode=i,this.setIndex=s,this.render=c,this.renderInstances=l,this.renderMultiDraw=u}function Kp(e){let t={geometries:0,textures:0},n={frame:0,calls:0,triangles:0,points:0,lines:0};function r(t,r,i){switch(n.calls++,r){case e.TRIANGLES:n.triangles+=t/3*i;break;case e.LINES:n.lines+=t/2*i;break;case e.LINE_STRIP:n.lines+=i*(t-1);break;case e.LINE_LOOP:n.lines+=i*t;break;case e.POINTS:n.points+=i*t;break;default:V(`WebGLInfo: Unknown draw mode:`,r);break}}function i(){n.calls=0,n.triangles=0,n.points=0,n.lines=0}return{memory:t,render:n,programs:null,autoReset:!0,reset:i,update:r}}function qp(e,t,n){let r=new WeakMap,i=new Js;function a(a,o,s){let c=a.morphTargetInfluences,l=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,u=l===void 0?0:l.length,d=r.get(o);if(d===void 0||d.count!==u){d!==void 0&&d.texture.dispose();let e=o.morphAttributes.position!==void 0,n=o.morphAttributes.normal!==void 0,a=o.morphAttributes.color!==void 0,s=o.morphAttributes.position||[],c=o.morphAttributes.normal||[],l=o.morphAttributes.color||[],f=0;e===!0&&(f=1),n===!0&&(f=2),a===!0&&(f=3);let p=o.attributes.position.count*f,m=1;p>t.maxTextureSize&&(m=Math.ceil(p/t.maxTextureSize),p=t.maxTextureSize);let h=new Float32Array(p*m*4*u),g=new Zs(h,p,m,u);g.type=wa,g.needsUpdate=!0;let _=f*4;for(let t=0;t<u;t++){let r=s[t],o=c[t],u=l[t],d=p*m*4*t;for(let t=0;t<r.count;t++){let s=t*_;e===!0&&(i.fromBufferAttribute(r,t),h[d+s+0]=i.x,h[d+s+1]=i.y,h[d+s+2]=i.z,h[d+s+3]=0),n===!0&&(i.fromBufferAttribute(o,t),h[d+s+4]=i.x,h[d+s+5]=i.y,h[d+s+6]=i.z,h[d+s+7]=0),a===!0&&(i.fromBufferAttribute(u,t),h[d+s+8]=i.x,h[d+s+9]=i.y,h[d+s+10]=i.z,h[d+s+11]=u.itemSize===4?i.w:1)}}d={count:u,texture:g,size:new H(p,m)},r.set(o,d);function v(){g.dispose(),r.delete(o),o.removeEventListener(`dispose`,v)}o.addEventListener(`dispose`,v)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)s.getUniforms().setValue(e,`morphTexture`,a.morphTexture,n);else{let t=0;for(let e=0;e<c.length;e++)t+=c[e];let n=o.morphTargetsRelative?1:1-t;s.getUniforms().setValue(e,`morphTargetBaseInfluence`,n),s.getUniforms().setValue(e,`morphTargetInfluences`,c)}s.getUniforms().setValue(e,`morphTargetsTexture`,d.texture,n),s.getUniforms().setValue(e,`morphTargetsTextureSize`,d.size)}return{update:a}}function Jp(e,t,n,r,i){let a=new WeakMap;function o(r){let o=i.render.frame,s=r.geometry,l=t.get(r,s);if(a.get(l)!==o&&(t.update(l),a.set(l,o)),r.isInstancedMesh&&(r.hasEventListener(`dispose`,c)===!1&&r.addEventListener(`dispose`,c),a.get(r)!==o&&(n.update(r.instanceMatrix,e.ARRAY_BUFFER),r.instanceColor!==null&&n.update(r.instanceColor,e.ARRAY_BUFFER),a.set(r,o))),r.isSkinnedMesh){let e=r.skeleton;a.get(e)!==o&&(e.update(),a.set(e,o))}return l}function s(){a=new WeakMap}function c(e){let t=e.target;t.removeEventListener(`dispose`,c),r.releaseStatesOfObject(t),n.remove(t.instanceMatrix),t.instanceColor!==null&&n.remove(t.instanceColor)}return{update:o,dispose:s}}var Yp={1:`LINEAR_TONE_MAPPING`,2:`REINHARD_TONE_MAPPING`,3:`CINEON_TONE_MAPPING`,4:`ACES_FILMIC_TONE_MAPPING`,6:`AGX_TONE_MAPPING`,7:`NEUTRAL_TONE_MAPPING`,5:`CUSTOM_TONE_MAPPING`};function Xp(e,t,n,r,i){let a=new Xs(t,n,{type:e,depthBuffer:r,stencilBuffer:i,depthTexture:r?new cd(t,n):void 0}),o=new Xs(t,n,{type:Ta,depthBuffer:!1,stencilBuffer:!1}),s=new Y;s.setAttribute(`position`,new xl([-1,3,0,-1,-1,0,3,-1,0],3)),s.setAttribute(`uv`,new xl([0,2,0,0,2,0],2));let c=new Od({uniforms:{tDiffuse:{value:null}},vertexShader:`
|
|
3959
3959
|
precision highp float;
|
|
3960
3960
|
|
|
3961
3961
|
uniform mat4 modelViewMatrix;
|
|
@@ -4001,17 +4001,17 @@ void main() {
|
|
|
4001
4001
|
#ifdef SRGB_TRANSFER
|
|
4002
4002
|
gl_FragColor = sRGBTransferOETF( gl_FragColor );
|
|
4003
4003
|
#endif
|
|
4004
|
-
}`,depthTest:!1,depthWrite:!1}),l=new iu(s,c),u=new Of(-1,1,1,-1,0,1),d=null,f=null,p=!1,m,h=null,g=[],_=!1;this.setSize=function(e,t){a.setSize(e,t),o.setSize(e,t);for(let n=0;n<g.length;n++){let r=g[n];r.setSize&&r.setSize(e,t)}},this.setEffects=function(e){g=e,_=g.length>0&&g[0].isRenderPass===!0;let t=a.width,n=a.height;for(let e=0;e<g.length;e++){let r=g[e];r.setSize&&r.setSize(t,n)}},this.begin=function(e,t){if(p||e.toneMapping===0&&g.length===0)return!1;if(h=t,t!==null){let e=t.width,n=t.height;(a.width!==e||a.height!==n)&&this.setSize(e,n)}return _===!1&&e.setRenderTarget(a),m=e.toneMapping,e.toneMapping=0,!0},this.hasRenderPass=function(){return _},this.end=function(e,t){e.toneMapping=m,p=!0;let n=a,r=o;for(let i=0;i<g.length;i++){let a=g[i];if(a.enabled!==!1&&(a.render(e,r,n,t),a.needsSwap!==!1)){let e=n;n=r,r=e}}if(d!==e.outputColorSpace||f!==e.toneMapping){d=e.outputColorSpace,f=e.toneMapping,c.defines={},Ls.getTransfer(d)===`srgb`&&(c.defines.SRGB_TRANSFER=``);let t=
|
|
4004
|
+
}`,depthTest:!1,depthWrite:!1}),l=new iu(s,c),u=new Of(-1,1,1,-1,0,1),d=null,f=null,p=!1,m,h=null,g=[],_=!1;this.setSize=function(e,t){a.setSize(e,t),o.setSize(e,t);for(let n=0;n<g.length;n++){let r=g[n];r.setSize&&r.setSize(e,t)}},this.setEffects=function(e){g=e,_=g.length>0&&g[0].isRenderPass===!0;let t=a.width,n=a.height;for(let e=0;e<g.length;e++){let r=g[e];r.setSize&&r.setSize(t,n)}},this.begin=function(e,t){if(p||e.toneMapping===0&&g.length===0)return!1;if(h=t,t!==null){let e=t.width,n=t.height;(a.width!==e||a.height!==n)&&this.setSize(e,n)}return _===!1&&e.setRenderTarget(a),m=e.toneMapping,e.toneMapping=0,!0},this.hasRenderPass=function(){return _},this.end=function(e,t){e.toneMapping=m,p=!0;let n=a,r=o;for(let i=0;i<g.length;i++){let a=g[i];if(a.enabled!==!1&&(a.render(e,r,n,t),a.needsSwap!==!1)){let e=n;n=r,r=e}}if(d!==e.outputColorSpace||f!==e.toneMapping){d=e.outputColorSpace,f=e.toneMapping,c.defines={},Ls.getTransfer(d)===`srgb`&&(c.defines.SRGB_TRANSFER=``);let t=Yp[f];t&&(c.defines[t]=``),c.needsUpdate=!0}c.uniforms.tDiffuse.value=n.texture,e.setRenderTarget(h),e.render(l,u),h=null,p=!1},this.isCompositing=function(){return p},this.dispose=function(){a.depthTexture&&a.depthTexture.dispose(),a.dispose(),o.dispose(),s.dispose(),c.dispose()}}var Zp=new qs,Qp=new cd(1,1),$p=new Zs,em=new Qs,tm=new od,nm=[],rm=[],im=new Float32Array(16),am=new Float32Array(9),om=new Float32Array(4);function sm(e,t,n){let r=e[0];if(r<=0||r>0)return e;let i=t*n,a=nm[i];if(a===void 0&&(a=new Float32Array(i),nm[i]=a),t!==0){r.toArray(a,0);for(let r=1,i=0;r!==t;++r)i+=n,e[r].toArray(a,i)}return a}function cm(e,t){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n<r;n++)if(e[n]!==t[n])return!1;return!0}function lm(e,t){for(let n=0,r=t.length;n<r;n++)e[n]=t[n]}function um(e,t){let n=rm[t];n===void 0&&(n=new Int32Array(t),rm[t]=n);for(let r=0;r!==t;++r)n[r]=e.allocateTextureUnit();return n}function dm(e,t){let n=this.cache;n[0]!==t&&(e.uniform1f(this.addr,t),n[0]=t)}function fm(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2f(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(cm(n,t))return;e.uniform2fv(this.addr,t),lm(n,t)}}function pm(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3f(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else if(t.r!==void 0)(n[0]!==t.r||n[1]!==t.g||n[2]!==t.b)&&(e.uniform3f(this.addr,t.r,t.g,t.b),n[0]=t.r,n[1]=t.g,n[2]=t.b);else{if(cm(n,t))return;e.uniform3fv(this.addr,t),lm(n,t)}}function mm(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4f(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(cm(n,t))return;e.uniform4fv(this.addr,t),lm(n,t)}}function hm(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(cm(n,t))return;e.uniformMatrix2fv(this.addr,!1,t),lm(n,t)}else{if(cm(n,r))return;om.set(r),e.uniformMatrix2fv(this.addr,!1,om),lm(n,r)}}function gm(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(cm(n,t))return;e.uniformMatrix3fv(this.addr,!1,t),lm(n,t)}else{if(cm(n,r))return;am.set(r),e.uniformMatrix3fv(this.addr,!1,am),lm(n,r)}}function _m(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(cm(n,t))return;e.uniformMatrix4fv(this.addr,!1,t),lm(n,t)}else{if(cm(n,r))return;im.set(r),e.uniformMatrix4fv(this.addr,!1,im),lm(n,r)}}function vm(e,t){let n=this.cache;n[0]!==t&&(e.uniform1i(this.addr,t),n[0]=t)}function ym(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2i(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(cm(n,t))return;e.uniform2iv(this.addr,t),lm(n,t)}}function bm(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3i(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(cm(n,t))return;e.uniform3iv(this.addr,t),lm(n,t)}}function xm(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4i(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(cm(n,t))return;e.uniform4iv(this.addr,t),lm(n,t)}}function Sm(e,t){let n=this.cache;n[0]!==t&&(e.uniform1ui(this.addr,t),n[0]=t)}function Cm(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2ui(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(cm(n,t))return;e.uniform2uiv(this.addr,t),lm(n,t)}}function wm(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3ui(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(cm(n,t))return;e.uniform3uiv(this.addr,t),lm(n,t)}}function Tm(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4ui(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(cm(n,t))return;e.uniform4uiv(this.addr,t),lm(n,t)}}function Em(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i);let a;this.type===e.SAMPLER_2D_SHADOW?(Qp.compareFunction=n.isReversedDepthBuffer()?518:515,a=Qp):a=Zp,n.setTexture2D(t||a,i)}function Dm(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTexture3D(t||em,i)}function Om(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTextureCube(t||tm,i)}function km(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTexture2DArray(t||$p,i)}function Am(e){switch(e){case 5126:return dm;case 35664:return fm;case 35665:return pm;case 35666:return mm;case 35674:return hm;case 35675:return gm;case 35676:return _m;case 5124:case 35670:return vm;case 35667:case 35671:return ym;case 35668:case 35672:return bm;case 35669:case 35673:return xm;case 5125:return Sm;case 36294:return Cm;case 36295:return wm;case 36296:return Tm;case 35678:case 36198:case 36298:case 36306:case 35682:return Em;case 35679:case 36299:case 36307:return Dm;case 35680:case 36300:case 36308:case 36293:return Om;case 36289:case 36303:case 36311:case 36292:return km}}function jm(e,t){e.uniform1fv(this.addr,t)}function Mm(e,t){let n=sm(t,this.size,2);e.uniform2fv(this.addr,n)}function Nm(e,t){let n=sm(t,this.size,3);e.uniform3fv(this.addr,n)}function Pm(e,t){let n=sm(t,this.size,4);e.uniform4fv(this.addr,n)}function Fm(e,t){let n=sm(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,n)}function Im(e,t){let n=sm(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,n)}function Lm(e,t){let n=sm(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,n)}function Rm(e,t){e.uniform1iv(this.addr,t)}function zm(e,t){e.uniform2iv(this.addr,t)}function Bm(e,t){e.uniform3iv(this.addr,t)}function Vm(e,t){e.uniform4iv(this.addr,t)}function Hm(e,t){e.uniform1uiv(this.addr,t)}function Um(e,t){e.uniform2uiv(this.addr,t)}function Wm(e,t){e.uniform3uiv(this.addr,t)}function Gm(e,t){e.uniform4uiv(this.addr,t)}function Km(e,t,n){let r=this.cache,i=t.length,a=um(n,i);cm(r,a)||(e.uniform1iv(this.addr,a),lm(r,a));let o;o=this.type===e.SAMPLER_2D_SHADOW?Qp:Zp;for(let e=0;e!==i;++e)n.setTexture2D(t[e]||o,a[e])}function qm(e,t,n){let r=this.cache,i=t.length,a=um(n,i);cm(r,a)||(e.uniform1iv(this.addr,a),lm(r,a));for(let e=0;e!==i;++e)n.setTexture3D(t[e]||em,a[e])}function Jm(e,t,n){let r=this.cache,i=t.length,a=um(n,i);cm(r,a)||(e.uniform1iv(this.addr,a),lm(r,a));for(let e=0;e!==i;++e)n.setTextureCube(t[e]||tm,a[e])}function Ym(e,t,n){let r=this.cache,i=t.length,a=um(n,i);cm(r,a)||(e.uniform1iv(this.addr,a),lm(r,a));for(let e=0;e!==i;++e)n.setTexture2DArray(t[e]||$p,a[e])}function Xm(e){switch(e){case 5126:return jm;case 35664:return Mm;case 35665:return Nm;case 35666:return Pm;case 35674:return Fm;case 35675:return Im;case 35676:return Lm;case 5124:case 35670:return Rm;case 35667:case 35671:return zm;case 35668:case 35672:return Bm;case 35669:case 35673:return Vm;case 5125:return Hm;case 36294:return Um;case 36295:return Wm;case 36296:return Gm;case 35678:case 36198:case 36298:case 36306:case 35682:return Km;case 35679:case 36299:case 36307:return qm;case 35680:case 36300:case 36308:case 36293:return Jm;case 36289:case 36303:case 36311:case 36292:return Ym}}var Zm=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=Am(t.type)}},Qm=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=Xm(t.type)}},$m=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){let r=this.seq;for(let i=0,a=r.length;i!==a;++i){let a=r[i];a.setValue(e,t[a.id],n)}}},eh=/(\w+)(\])?(\[|\.)?/g;function th(e,t){e.seq.push(t),e.map[t.id]=t}function nh(e,t,n){let r=e.name,i=r.length;for(eh.lastIndex=0;;){let a=eh.exec(r),o=eh.lastIndex,s=a[1],c=a[2]===`]`,l=a[3];if(c&&(s|=0),l===void 0||l===`[`&&o+2===i){th(n,l===void 0?new Zm(s,e,t):new Qm(s,e,t));break}else{let e=n.map[s];e===void 0&&(e=new $m(s),th(n,e)),n=e}}}var rh=class{constructor(e,t){this.seq=[],this.map={};let n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let r=0;r<n;++r){let n=e.getActiveUniform(t,r);nh(n,e.getUniformLocation(t,n.name),this)}let r=[],i=[];for(let t of this.seq)t.type===e.SAMPLER_2D_SHADOW||t.type===e.SAMPLER_CUBE_SHADOW||t.type===e.SAMPLER_2D_ARRAY_SHADOW?r.push(t):i.push(t);r.length>0&&(this.seq=r.concat(i))}setValue(e,t,n,r){let i=this.map[t];i!==void 0&&i.setValue(e,n,r)}setOptional(e,t,n){let r=t[n];r!==void 0&&this.setValue(e,n,r)}static upload(e,t,n,r){for(let i=0,a=t.length;i!==a;++i){let a=t[i],o=n[a.id];o.needsUpdate!==!1&&a.setValue(e,o.value,r)}}static seqWithValue(e,t){let n=[];for(let r=0,i=e.length;r!==i;++r){let i=e[r];i.id in t&&n.push(i)}return n}};function ih(e,t,n){let r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),r}var ah=37297,oh=0;function sh(e,t){let n=e.split(`
|
|
4005
4005
|
`),r=[],i=Math.max(t-6,0),a=Math.min(t+6,n.length);for(let e=i;e<a;e++){let i=e+1;r.push(`${i===t?`>`:` `} ${i}: ${n[e]}`)}return r.join(`
|
|
4006
|
-
`)}var
|
|
4006
|
+
`)}var ch=new G;function lh(e){Ls._getMatrix(ch,Ls.workingColorSpace,e);let t=`mat3( ${ch.elements.map(e=>e.toFixed(4))} )`;switch(Ls.getTransfer(e)){case Bo:return[t,`LinearTransferOETF`];case Vo:return[t,`sRGBTransferOETF`];default:return B(`WebGLProgram: Unsupported color space: `,e),[t,`LinearTransferOETF`]}}function uh(e,t,n){let r=e.getShaderParameter(t,e.COMPILE_STATUS),i=(e.getShaderInfoLog(t)||``).trim();if(r&&i===``)return``;let a=/ERROR: 0:(\d+)/.exec(i);if(a){let r=parseInt(a[1]);return n.toUpperCase()+`
|
|
4007
4007
|
|
|
4008
4008
|
`+i+`
|
|
4009
4009
|
|
|
4010
|
-
`+
|
|
4011
|
-
`)}var
|
|
4012
|
-
`)}function
|
|
4013
|
-
`)}function
|
|
4014
|
-
`)}function
|
|
4010
|
+
`+sh(e.getShaderSource(t),r)}else return i}function dh(e,t){let n=lh(t);return[`vec4 ${e}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,`}`].join(`
|
|
4011
|
+
`)}var fh={1:`Linear`,2:`Reinhard`,3:`Cineon`,4:`ACESFilmic`,6:`AgX`,7:`Neutral`,5:`Custom`};function ph(e,t){let n=fh[t];return n===void 0?(B(`WebGLProgram: Unsupported toneMapping:`,t),`vec3 `+e+`( vec3 color ) { return LinearToneMapping( color ); }`):`vec3 `+e+`( vec3 color ) { return `+n+`ToneMapping( color ); }`}var mh=new W;function hh(){return Ls.getLuminanceCoefficients(mh),[`float luminance( const in vec3 rgb ) {`,` const vec3 weights = vec3( ${mh.x.toFixed(4)}, ${mh.y.toFixed(4)}, ${mh.z.toFixed(4)} );`,` return dot( weights, rgb );`,`}`].join(`
|
|
4012
|
+
`)}function gh(e){return[e.extensionClipCullDistance?`#extension GL_ANGLE_clip_cull_distance : require`:``,e.extensionMultiDraw?`#extension GL_ANGLE_multi_draw : require`:``].filter(yh).join(`
|
|
4013
|
+
`)}function _h(e){let t=[];for(let n in e){let r=e[n];r!==!1&&t.push(`#define `+n+` `+r)}return t.join(`
|
|
4014
|
+
`)}function vh(e,t){let n={},r=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let i=0;i<r;i++){let r=e.getActiveAttrib(t,i),a=r.name,o=1;r.type===e.FLOAT_MAT2&&(o=2),r.type===e.FLOAT_MAT3&&(o=3),r.type===e.FLOAT_MAT4&&(o=4),n[a]={type:r.type,location:e.getAttribLocation(t,a),locationSize:o}}return n}function yh(e){return e!==``}function bh(e,t){let n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function xh(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}var Sh=/^[ \t]*#include +<([\w\d./]+)>/gm;function Ch(e){return e.replace(Sh,Th)}var wh=new Map;function Th(e,t){let n=dp[t];if(n===void 0){let e=wh.get(t);if(e!==void 0)n=dp[e],B(`WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.`,t,e);else throw Error(`Can not resolve #include <`+t+`>`)}return Ch(n)}var Eh=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Dh(e){return e.replace(Eh,Oh)}function Oh(e,t,n,r){let i=``;for(let e=parseInt(t);e<parseInt(n);e++)i+=r.replace(/\[\s*i\s*\]/g,`[ `+e+` ]`).replace(/UNROLLED_LOOP_INDEX/g,e);return i}function kh(e){let t=`precision ${e.precision} float;
|
|
4015
4015
|
precision ${e.precision} int;
|
|
4016
4016
|
precision ${e.precision} sampler2D;
|
|
4017
4017
|
precision ${e.precision} samplerCube;
|
|
@@ -4031,30 +4031,30 @@ void main() {
|
|
|
4031
4031
|
`;return e.precision===`highp`?t+=`
|
|
4032
4032
|
#define HIGH_PRECISION`:e.precision===`mediump`?t+=`
|
|
4033
4033
|
#define MEDIUM_PRECISION`:e.precision===`lowp`&&(t+=`
|
|
4034
|
-
#define LOW_PRECISION`),t}var
|
|
4035
|
-
`:``;n.isRawShaderMaterial?(g=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(
|
|
4034
|
+
#define LOW_PRECISION`),t}var Ah={1:`SHADOWMAP_TYPE_PCF`,3:`SHADOWMAP_TYPE_VSM`};function jh(e){return Ah[e.shadowMapType]||`SHADOWMAP_TYPE_BASIC`}var Mh={301:`ENVMAP_TYPE_CUBE`,302:`ENVMAP_TYPE_CUBE`,306:`ENVMAP_TYPE_CUBE_UV`};function Nh(e){return e.envMap===!1?`ENVMAP_TYPE_CUBE`:Mh[e.envMapMode]||`ENVMAP_TYPE_CUBE`}var Ph={302:`ENVMAP_MODE_REFRACTION`};function Fh(e){return e.envMap===!1?`ENVMAP_MODE_REFLECTION`:Ph[e.envMapMode]||`ENVMAP_MODE_REFLECTION`}var Ih={0:`ENVMAP_BLENDING_MULTIPLY`,1:`ENVMAP_BLENDING_MIX`,2:`ENVMAP_BLENDING_ADD`};function Lh(e){return e.envMap===!1?`ENVMAP_BLENDING_NONE`:Ih[e.combine]||`ENVMAP_BLENDING_NONE`}function Rh(e){let t=e.envMapCubeUVHeight;if(t===null)return null;let n=Math.log2(t)-2,r=1/t;return{texelWidth:1/(3*Math.max(2**n,112)),texelHeight:r,maxMip:n}}function zh(e,t,n,r){let i=e.getContext(),a=n.defines,o=n.vertexShader,s=n.fragmentShader,c=jh(n),l=Nh(n),u=Fh(n),d=Lh(n),f=Rh(n),p=gh(n),m=_h(a),h=i.createProgram(),g,_,v=n.glslVersion?`#version `+n.glslVersion+`
|
|
4035
|
+
`:``;n.isRawShaderMaterial?(g=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(yh).join(`
|
|
4036
4036
|
`),g.length>0&&(g+=`
|
|
4037
|
-
`),_=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(
|
|
4037
|
+
`),_=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(yh).join(`
|
|
4038
4038
|
`),_.length>0&&(_+=`
|
|
4039
|
-
`)):(g=[
|
|
4040
|
-
`].filter(
|
|
4041
|
-
`),_=[
|
|
4042
|
-
`].filter(
|
|
4043
|
-
`)),o=
|
|
4039
|
+
`)):(g=[kh(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.extensionClipCullDistance?`#define USE_CLIP_DISTANCE`:``,n.batching?`#define USE_BATCHING`:``,n.batchingColor?`#define USE_BATCHING_COLOR`:``,n.instancing?`#define USE_INSTANCING`:``,n.instancingColor?`#define USE_INSTANCING_COLOR`:``,n.instancingMorph?`#define USE_INSTANCING_MORPH`:``,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.map?`#define USE_MAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+u:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.displacementMap?`#define USE_DISPLACEMENTMAP`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.mapUv?`#define MAP_UV `+n.mapUv:``,n.alphaMapUv?`#define ALPHAMAP_UV `+n.alphaMapUv:``,n.lightMapUv?`#define LIGHTMAP_UV `+n.lightMapUv:``,n.aoMapUv?`#define AOMAP_UV `+n.aoMapUv:``,n.emissiveMapUv?`#define EMISSIVEMAP_UV `+n.emissiveMapUv:``,n.bumpMapUv?`#define BUMPMAP_UV `+n.bumpMapUv:``,n.normalMapUv?`#define NORMALMAP_UV `+n.normalMapUv:``,n.displacementMapUv?`#define DISPLACEMENTMAP_UV `+n.displacementMapUv:``,n.metalnessMapUv?`#define METALNESSMAP_UV `+n.metalnessMapUv:``,n.roughnessMapUv?`#define ROUGHNESSMAP_UV `+n.roughnessMapUv:``,n.anisotropyMapUv?`#define ANISOTROPYMAP_UV `+n.anisotropyMapUv:``,n.clearcoatMapUv?`#define CLEARCOATMAP_UV `+n.clearcoatMapUv:``,n.clearcoatNormalMapUv?`#define CLEARCOAT_NORMALMAP_UV `+n.clearcoatNormalMapUv:``,n.clearcoatRoughnessMapUv?`#define CLEARCOAT_ROUGHNESSMAP_UV `+n.clearcoatRoughnessMapUv:``,n.iridescenceMapUv?`#define IRIDESCENCEMAP_UV `+n.iridescenceMapUv:``,n.iridescenceThicknessMapUv?`#define IRIDESCENCE_THICKNESSMAP_UV `+n.iridescenceThicknessMapUv:``,n.sheenColorMapUv?`#define SHEEN_COLORMAP_UV `+n.sheenColorMapUv:``,n.sheenRoughnessMapUv?`#define SHEEN_ROUGHNESSMAP_UV `+n.sheenRoughnessMapUv:``,n.specularMapUv?`#define SPECULARMAP_UV `+n.specularMapUv:``,n.specularColorMapUv?`#define SPECULAR_COLORMAP_UV `+n.specularColorMapUv:``,n.specularIntensityMapUv?`#define SPECULAR_INTENSITYMAP_UV `+n.specularIntensityMapUv:``,n.transmissionMapUv?`#define TRANSMISSIONMAP_UV `+n.transmissionMapUv:``,n.thicknessMapUv?`#define THICKNESSMAP_UV `+n.thicknessMapUv:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexNormals?`#define HAS_NORMAL`:``,n.vertexColors?`#define USE_COLOR`:``,n.vertexAlphas?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.flatShading?`#define FLAT_SHADED`:``,n.skinning?`#define USE_SKINNING`:``,n.morphTargets?`#define USE_MORPHTARGETS`:``,n.morphNormals&&n.flatShading===!1?`#define USE_MORPHNORMALS`:``,n.morphColors?`#define USE_MORPHCOLORS`:``,n.morphTargetsCount>0?`#define MORPHTARGETS_TEXTURE_STRIDE `+n.morphTextureStride:``,n.morphTargetsCount>0?`#define MORPHTARGETS_COUNT `+n.morphTargetsCount:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.sizeAttenuation?`#define USE_SIZEATTENUATION`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`uniform mat4 modelMatrix;`,`uniform mat4 modelViewMatrix;`,`uniform mat4 projectionMatrix;`,`uniform mat4 viewMatrix;`,`uniform mat3 normalMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,`#ifdef USE_INSTANCING`,` attribute mat4 instanceMatrix;`,`#endif`,`#ifdef USE_INSTANCING_COLOR`,` attribute vec3 instanceColor;`,`#endif`,`#ifdef USE_INSTANCING_MORPH`,` uniform sampler2D morphTexture;`,`#endif`,`attribute vec3 position;`,`attribute vec3 normal;`,`attribute vec2 uv;`,`#ifdef USE_UV1`,` attribute vec2 uv1;`,`#endif`,`#ifdef USE_UV2`,` attribute vec2 uv2;`,`#endif`,`#ifdef USE_UV3`,` attribute vec2 uv3;`,`#endif`,`#ifdef USE_TANGENT`,` attribute vec4 tangent;`,`#endif`,`#if defined( USE_COLOR_ALPHA )`,` attribute vec4 color;`,`#elif defined( USE_COLOR )`,` attribute vec3 color;`,`#endif`,`#ifdef USE_SKINNING`,` attribute vec4 skinIndex;`,` attribute vec4 skinWeight;`,`#endif`,`
|
|
4040
|
+
`].filter(yh).join(`
|
|
4041
|
+
`),_=[kh(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.alphaToCoverage?`#define ALPHA_TO_COVERAGE`:``,n.map?`#define USE_MAP`:``,n.matcap?`#define USE_MATCAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+l:``,n.envMap?`#define `+u:``,n.envMap?`#define `+d:``,f?`#define CUBEUV_TEXEL_WIDTH `+f.texelWidth:``,f?`#define CUBEUV_TEXEL_HEIGHT `+f.texelHeight:``,f?`#define CUBEUV_MAX_MIP `+f.maxMip+`.0`:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.packedNormalMap?`#define USE_PACKED_NORMALMAP`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoat?`#define USE_CLEARCOAT`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.dispersion?`#define USE_DISPERSION`:``,n.iridescence?`#define USE_IRIDESCENCE`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaTest?`#define USE_ALPHATEST`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.sheen?`#define USE_SHEEN`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexColors||n.instancingColor?`#define USE_COLOR`:``,n.vertexAlphas||n.batchingColor?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.gradientMap?`#define USE_GRADIENTMAP`:``,n.flatShading?`#define FLAT_SHADED`:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.premultipliedAlpha?`#define PREMULTIPLIED_ALPHA`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.numLightProbeGrids>0?`#define USE_LIGHT_PROBES_GRID`:``,n.decodeVideoTexture?`#define DECODE_VIDEO_TEXTURE`:``,n.decodeVideoTextureEmissive?`#define DECODE_VIDEO_TEXTURE_EMISSIVE`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`uniform mat4 viewMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,n.toneMapping===0?``:`#define TONE_MAPPING`,n.toneMapping===0?``:dp.tonemapping_pars_fragment,n.toneMapping===0?``:ph(`toneMapping`,n.toneMapping),n.dithering?`#define DITHERING`:``,n.opaque?`#define OPAQUE`:``,dp.colorspace_pars_fragment,dh(`linearToOutputTexel`,n.outputColorSpace),hh(),n.useDepthPacking?`#define DEPTH_PACKING `+n.depthPacking:``,`
|
|
4042
|
+
`].filter(yh).join(`
|
|
4043
|
+
`)),o=Ch(o),o=bh(o,n),o=xh(o,n),s=Ch(s),s=bh(s,n),s=xh(s,n),o=Dh(o),s=Dh(s),n.isRawShaderMaterial!==!0&&(v=`#version 300 es
|
|
4044
4044
|
`,g=[p,`#define attribute in`,`#define varying out`,`#define texture2D texture`].join(`
|
|
4045
4045
|
`)+`
|
|
4046
4046
|
`+g,_=[`#define varying in`,n.glslVersion===`300 es`?``:`layout(location = 0) out highp vec4 pc_fragColor;`,n.glslVersion===`300 es`?``:`#define gl_FragColor pc_fragColor`,`#define gl_FragDepthEXT gl_FragDepth`,`#define texture2D texture`,`#define textureCube texture`,`#define texture2DProj textureProj`,`#define texture2DLodEXT textureLod`,`#define texture2DProjLodEXT textureProjLod`,`#define textureCubeLodEXT textureLod`,`#define texture2DGradEXT textureGrad`,`#define texture2DProjGradEXT textureProjGrad`,`#define textureCubeGradEXT textureGrad`].join(`
|
|
4047
4047
|
`)+`
|
|
4048
|
-
`+_);let y=v+g+o,b=v+_+s,x=
|
|
4048
|
+
`+_);let y=v+g+o,b=v+_+s,x=ih(i,i.VERTEX_SHADER,y),S=ih(i,i.FRAGMENT_SHADER,b);i.attachShader(h,x),i.attachShader(h,S),n.index0AttributeName===void 0?n.morphTargets===!0&&i.bindAttribLocation(h,0,`position`):i.bindAttribLocation(h,0,n.index0AttributeName),i.linkProgram(h);function C(t){if(e.debug.checkShaderErrors){let n=i.getProgramInfoLog(h)||``,r=i.getShaderInfoLog(x)||``,a=i.getShaderInfoLog(S)||``,o=n.trim(),s=r.trim(),c=a.trim(),l=!0,u=!0;if(i.getProgramParameter(h,i.LINK_STATUS)===!1)if(l=!1,typeof e.debug.onShaderError==`function`)e.debug.onShaderError(i,h,x,S);else{let e=uh(i,x,`vertex`),n=uh(i,S,`fragment`);V(`THREE.WebGLProgram: Shader Error `+i.getError()+` - VALIDATE_STATUS `+i.getProgramParameter(h,i.VALIDATE_STATUS)+`
|
|
4049
4049
|
|
|
4050
4050
|
Material Name: `+t.name+`
|
|
4051
4051
|
Material Type: `+t.type+`
|
|
4052
4052
|
|
|
4053
4053
|
Program Info Log: `+o+`
|
|
4054
4054
|
`+e+`
|
|
4055
|
-
`+n)}else o===``?(s===``||c===``)&&(u=!1):B(`WebGLProgram: Program Info Log:`,o);u&&(t.diagnostics={runnable:l,programLog:o,vertexShader:{log:s,prefix:g},fragmentShader:{log:c,prefix:_}})}i.deleteShader(x),i.deleteShader(S),w=new nh(i,h),T=_h(i,h)}let w;this.getUniforms=function(){return w===void 0&&C(this),w};let T;this.getAttributes=function(){return T===void 0&&C(this),T};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=i.getProgramParameter(h,ih)),E},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(h),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=ah++,this.cacheKey=t,this.usedTimes=1,this.program=h,this.vertexShader=x,this.fragmentShader=S,this}var zh=0,Bh=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){let t=e.vertexShader,n=e.fragmentShader,r=this._getShaderStage(t),i=this._getShaderStage(n),a=this._getShaderCacheForMaterial(e);return a.has(r)===!1&&(a.add(r),r.usedTimes++),a.has(i)===!1&&(a.add(i),i.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let e of t)e.usedTimes--,e.usedTimes===0&&this.shaderCache.delete(e.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new Vh(e),t.set(e,n)),n}},Vh=class{constructor(e){this.id=zh++,this.code=e,this.usedTimes=0}};function Hh(e){return e===1030||e===37490||e===36285}function Uh(e,t,n,r,i,a){let o=new lc,s=new Bh,c=new Set,l=[],u=new Map,d=r.logarithmicDepthBuffer,f=r.precision,p={MeshDepthMaterial:`depth`,MeshDistanceMaterial:`distance`,MeshNormalMaterial:`normal`,MeshBasicMaterial:`basic`,MeshLambertMaterial:`lambert`,MeshPhongMaterial:`phong`,MeshToonMaterial:`toon`,MeshStandardMaterial:`physical`,MeshPhysicalMaterial:`physical`,MeshMatcapMaterial:`matcap`,LineBasicMaterial:`basic`,LineDashedMaterial:`dashed`,PointsMaterial:`points`,ShadowMaterial:`shadow`,SpriteMaterial:`sprite`};function m(e){return c.add(e),e===0?`uv`:`uv${e}`}function h(i,o,l,u,h,g){let _=u.fog,v=h.geometry,y=i.isMeshStandardMaterial||i.isMeshLambertMaterial||i.isMeshPhongMaterial?u.environment:null,b=i.isMeshStandardMaterial||i.isMeshLambertMaterial&&!i.envMap||i.isMeshPhongMaterial&&!i.envMap,x=t.get(i.envMap||y,b),S=x&&x.mapping===306?x.image.height:null,C=p[i.type];i.precision!==null&&(f=r.getMaxPrecision(i.precision),f!==i.precision&&B(`WebGLProgram.getParameters:`,i.precision,`not supported, using`,f,`instead.`));let w=v.morphAttributes.position||v.morphAttributes.normal||v.morphAttributes.color,T=w===void 0?0:w.length,E=0;v.morphAttributes.position!==void 0&&(E=1),v.morphAttributes.normal!==void 0&&(E=2),v.morphAttributes.color!==void 0&&(E=3);let D,O,k,A;if(C){let e=dp[C];D=e.vertexShader,O=e.fragmentShader}else D=i.vertexShader,O=i.fragmentShader,s.update(i),k=s.getVertexShaderID(i),A=s.getFragmentShaderID(i);let ee=e.getRenderTarget(),te=e.state.buffers.depth.getReversed(),ne=h.isInstancedMesh===!0,re=h.isBatchedMesh===!0,ie=!!i.map,ae=!!i.matcap,j=!!x,oe=!!i.aoMap,se=!!i.lightMap,ce=!!i.bumpMap,le=!!i.normalMap,ue=!!i.displacementMap,M=!!i.emissiveMap,de=!!i.metalnessMap,fe=!!i.roughnessMap,pe=i.anisotropy>0,me=i.clearcoat>0,he=i.dispersion>0,ge=i.iridescence>0,_e=i.sheen>0,ve=i.transmission>0,ye=pe&&!!i.anisotropyMap,be=me&&!!i.clearcoatMap,xe=me&&!!i.clearcoatNormalMap,N=me&&!!i.clearcoatRoughnessMap,Se=ge&&!!i.iridescenceMap,Ce=ge&&!!i.iridescenceThicknessMap,we=_e&&!!i.sheenColorMap,P=_e&&!!i.sheenRoughnessMap,Te=!!i.specularMap,F=!!i.specularColorMap,I=!!i.specularIntensityMap,L=ve&&!!i.transmissionMap,Ee=ve&&!!i.thicknessMap,De=!!i.gradientMap,Oe=!!i.alphaMap,ke=i.alphaTest>0,Ae=!!i.alphaHash,je=!!i.extensions,Me=0;i.toneMapped&&(ee===null||ee.isXRRenderTarget===!0)&&(Me=e.toneMapping);let Ne={shaderID:C,shaderType:i.type,shaderName:i.name,vertexShader:D,fragmentShader:O,defines:i.defines,customVertexShaderID:k,customFragmentShaderID:A,isRawShaderMaterial:i.isRawShaderMaterial===!0,glslVersion:i.glslVersion,precision:f,batching:re,batchingColor:re&&h._colorsTexture!==null,instancing:ne,instancingColor:ne&&h.instanceColor!==null,instancingMorph:ne&&h.morphTexture!==null,outputColorSpace:ee===null?e.outputColorSpace:ee.isXRRenderTarget===!0?ee.texture.colorSpace:Ls.workingColorSpace,alphaToCoverage:!!i.alphaToCoverage,map:ie,matcap:ae,envMap:j,envMapMode:j&&x.mapping,envMapCubeUVHeight:S,aoMap:oe,lightMap:se,bumpMap:ce,normalMap:le,displacementMap:ue,emissiveMap:M,normalMapObjectSpace:le&&i.normalMapType===1,normalMapTangentSpace:le&&i.normalMapType===0,packedNormalMap:le&&i.normalMapType===0&&Hh(i.normalMap.format),metalnessMap:de,roughnessMap:fe,anisotropy:pe,anisotropyMap:ye,clearcoat:me,clearcoatMap:be,clearcoatNormalMap:xe,clearcoatRoughnessMap:N,dispersion:he,iridescence:ge,iridescenceMap:Se,iridescenceThicknessMap:Ce,sheen:_e,sheenColorMap:we,sheenRoughnessMap:P,specularMap:Te,specularColorMap:F,specularIntensityMap:I,transmission:ve,transmissionMap:L,thicknessMap:Ee,gradientMap:De,opaque:i.transparent===!1&&i.blending===1&&i.alphaToCoverage===!1,alphaMap:Oe,alphaTest:ke,alphaHash:Ae,combine:i.combine,mapUv:ie&&m(i.map.channel),aoMapUv:oe&&m(i.aoMap.channel),lightMapUv:se&&m(i.lightMap.channel),bumpMapUv:ce&&m(i.bumpMap.channel),normalMapUv:le&&m(i.normalMap.channel),displacementMapUv:ue&&m(i.displacementMap.channel),emissiveMapUv:M&&m(i.emissiveMap.channel),metalnessMapUv:de&&m(i.metalnessMap.channel),roughnessMapUv:fe&&m(i.roughnessMap.channel),anisotropyMapUv:ye&&m(i.anisotropyMap.channel),clearcoatMapUv:be&&m(i.clearcoatMap.channel),clearcoatNormalMapUv:xe&&m(i.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:N&&m(i.clearcoatRoughnessMap.channel),iridescenceMapUv:Se&&m(i.iridescenceMap.channel),iridescenceThicknessMapUv:Ce&&m(i.iridescenceThicknessMap.channel),sheenColorMapUv:we&&m(i.sheenColorMap.channel),sheenRoughnessMapUv:P&&m(i.sheenRoughnessMap.channel),specularMapUv:Te&&m(i.specularMap.channel),specularColorMapUv:F&&m(i.specularColorMap.channel),specularIntensityMapUv:I&&m(i.specularIntensityMap.channel),transmissionMapUv:L&&m(i.transmissionMap.channel),thicknessMapUv:Ee&&m(i.thicknessMap.channel),alphaMapUv:Oe&&m(i.alphaMap.channel),vertexTangents:!!v.attributes.tangent&&(le||pe),vertexNormals:!!v.attributes.normal,vertexColors:i.vertexColors,vertexAlphas:i.vertexColors===!0&&!!v.attributes.color&&v.attributes.color.itemSize===4,pointsUvs:h.isPoints===!0&&!!v.attributes.uv&&(ie||Oe),fog:!!_,useFog:i.fog===!0,fogExp2:!!_&&_.isFogExp2,flatShading:i.wireframe===!1&&(i.flatShading===!0||v.attributes.normal===void 0&&le===!1&&(i.isMeshLambertMaterial||i.isMeshPhongMaterial||i.isMeshStandardMaterial||i.isMeshPhysicalMaterial)),sizeAttenuation:i.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:te,skinning:h.isSkinnedMesh===!0,morphTargets:v.morphAttributes.position!==void 0,morphNormals:v.morphAttributes.normal!==void 0,morphColors:v.morphAttributes.color!==void 0,morphTargetsCount:T,morphTextureStride:E,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numLightProbeGrids:g.length,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:i.dithering,shadowMapEnabled:e.shadowMap.enabled&&l.length>0,shadowMapType:e.shadowMap.type,toneMapping:Me,decodeVideoTexture:ie&&i.map.isVideoTexture===!0&&Ls.getTransfer(i.map.colorSpace)===`srgb`,decodeVideoTextureEmissive:M&&i.emissiveMap.isVideoTexture===!0&&Ls.getTransfer(i.emissiveMap.colorSpace)===`srgb`,premultipliedAlpha:i.premultipliedAlpha,doubleSided:i.side===2,flipSided:i.side===1,useDepthPacking:i.depthPacking>=0,depthPacking:i.depthPacking||0,index0AttributeName:i.index0AttributeName,extensionClipCullDistance:je&&i.extensions.clipCullDistance===!0&&n.has(`WEBGL_clip_cull_distance`),extensionMultiDraw:(je&&i.extensions.multiDraw===!0||re)&&n.has(`WEBGL_multi_draw`),rendererExtensionParallelShaderCompile:n.has(`KHR_parallel_shader_compile`),customProgramCacheKey:i.customProgramCacheKey()};return Ne.vertexUv1s=c.has(1),Ne.vertexUv2s=c.has(2),Ne.vertexUv3s=c.has(3),c.clear(),Ne}function g(t){let n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),t.defines!==void 0)for(let e in t.defines)n.push(e),n.push(t.defines[e]);return t.isRawShaderMaterial===!1&&(_(n,t),v(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()}function _(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}function v(e,t){o.disableAll(),t.instancing&&o.enable(0),t.instancingColor&&o.enable(1),t.instancingMorph&&o.enable(2),t.matcap&&o.enable(3),t.envMap&&o.enable(4),t.normalMapObjectSpace&&o.enable(5),t.normalMapTangentSpace&&o.enable(6),t.clearcoat&&o.enable(7),t.iridescence&&o.enable(8),t.alphaTest&&o.enable(9),t.vertexColors&&o.enable(10),t.vertexAlphas&&o.enable(11),t.vertexUv1s&&o.enable(12),t.vertexUv2s&&o.enable(13),t.vertexUv3s&&o.enable(14),t.vertexTangents&&o.enable(15),t.anisotropy&&o.enable(16),t.alphaHash&&o.enable(17),t.batching&&o.enable(18),t.dispersion&&o.enable(19),t.batchingColor&&o.enable(20),t.gradientMap&&o.enable(21),t.packedNormalMap&&o.enable(22),t.vertexNormals&&o.enable(23),e.push(o.mask),o.disableAll(),t.fog&&o.enable(0),t.useFog&&o.enable(1),t.flatShading&&o.enable(2),t.logarithmicDepthBuffer&&o.enable(3),t.reversedDepthBuffer&&o.enable(4),t.skinning&&o.enable(5),t.morphTargets&&o.enable(6),t.morphNormals&&o.enable(7),t.morphColors&&o.enable(8),t.premultipliedAlpha&&o.enable(9),t.shadowMapEnabled&&o.enable(10),t.doubleSided&&o.enable(11),t.flipSided&&o.enable(12),t.useDepthPacking&&o.enable(13),t.dithering&&o.enable(14),t.transmission&&o.enable(15),t.sheen&&o.enable(16),t.opaque&&o.enable(17),t.pointsUvs&&o.enable(18),t.decodeVideoTexture&&o.enable(19),t.decodeVideoTextureEmissive&&o.enable(20),t.alphaToCoverage&&o.enable(21),t.numLightProbeGrids>0&&o.enable(22),e.push(o.mask)}function y(e){let t=p[e.type],n;if(t){let e=dp[t];n=wd.clone(e.uniforms)}else n=e.uniforms;return n}function b(t,n){let r=u.get(n);return r===void 0?(r=new Rh(e,n,t,i),l.push(r),u.set(n,r)):++r.usedTimes,r}function x(e){if(--e.usedTimes===0){let t=l.indexOf(e);l[t]=l[l.length-1],l.pop(),u.delete(e.cacheKey),e.destroy()}}function S(e){s.remove(e)}function C(){s.dispose()}return{getParameters:h,getProgramCacheKey:g,getUniforms:y,acquireProgram:b,releaseProgram:x,releaseShaderCache:S,programs:l,dispose:C}}function Wh(){let e=new WeakMap;function t(t){return e.has(t)}function n(t){let n=e.get(t);return n===void 0&&(n={},e.set(t,n)),n}function r(t){e.delete(t)}function i(t,n,r){e.get(t)[n]=r}function a(){e=new WeakMap}return{has:t,get:n,remove:r,update:i,dispose:a}}function Gh(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.material.id===t.material.id?e.materialVariant===t.materialVariant?e.z===t.z?e.id-t.id:e.z-t.z:e.materialVariant-t.materialVariant:e.material.id-t.material.id:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function Kh(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.z===t.z?e.id-t.id:t.z-e.z:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function qh(){let e=[],t=0,n=[],r=[],i=[];function a(){t=0,n.length=0,r.length=0,i.length=0}function o(e){let t=0;return e.isInstancedMesh&&(t+=2),e.isSkinnedMesh&&(t+=1),t}function s(n,r,i,a,s,c){let l=e[t];return l===void 0?(l={id:n.id,object:n,geometry:r,material:i,materialVariant:o(n),groupOrder:a,renderOrder:n.renderOrder,z:s,group:c},e[t]=l):(l.id=n.id,l.object=n,l.geometry=r,l.material=i,l.materialVariant=o(n),l.groupOrder=a,l.renderOrder=n.renderOrder,l.z=s,l.group=c),t++,l}function c(e,t,a,o,c,l){let u=s(e,t,a,o,c,l);a.transmission>0?r.push(u):a.transparent===!0?i.push(u):n.push(u)}function l(e,t,a,o,c,l){let u=s(e,t,a,o,c,l);a.transmission>0?r.unshift(u):a.transparent===!0?i.unshift(u):n.unshift(u)}function u(e,t){n.length>1&&n.sort(e||Gh),r.length>1&&r.sort(t||Kh),i.length>1&&i.sort(t||Kh)}function d(){for(let n=t,r=e.length;n<r;n++){let t=e[n];if(t.id===null)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}}return{opaque:n,transmissive:r,transparent:i,init:a,push:c,unshift:l,finish:d,sort:u}}function Jh(){let e=new WeakMap;function t(t,n){let r=e.get(t),i;return r===void 0?(i=new qh,e.set(t,[i])):n>=r.length?(i=new qh,r.push(i)):i=r[n],i}function n(){e=new WeakMap}return{get:t,dispose:n}}function Yh(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={direction:new W,color:new q};break;case`SpotLight`:n={position:new W,direction:new W,color:new q,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case`PointLight`:n={position:new W,color:new q,distance:0,decay:0};break;case`HemisphereLight`:n={direction:new W,skyColor:new q,groundColor:new q};break;case`RectAreaLight`:n={color:new q,position:new W,halfWidth:new W,halfHeight:new W};break}return e[t.id]=n,n}}}function Xh(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new H};break;case`SpotLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new H};break;case`PointLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new H,shadowCameraNear:1,shadowCameraFar:1e3};break}return e[t.id]=n,n}}}var Zh=0;function Qh(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+ +!!t.map-!!e.map}function $h(e){let t=new Yh,n=Xh(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)r.probe.push(new W);let i=new W,a=new K,o=new K;function s(i){let a=0,o=0,s=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0;i.sort(Qh);for(let e=0,y=i.length;e<y;e++){let y=i[e],b=y.color,x=y.intensity,S=y.distance,C=null;if(y.shadow&&y.shadow.map&&(C=y.shadow.map.texture.format===1030?y.shadow.map.texture:y.shadow.map.depthTexture||y.shadow.map.texture),y.isAmbientLight)a+=b.r*x,o+=b.g*x,s+=b.b*x;else if(y.isLightProbe){for(let e=0;e<9;e++)r.probe[e].addScaledVector(y.sh.coefficients[e],x);v++}else if(y.isDirectionalLight){let e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),y.castShadow){let e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,r.directionalShadow[c]=t,r.directionalShadowMap[c]=C,r.directionalShadowMatrix[c]=y.shadow.matrix,p++}r.directional[c]=e,c++}else if(y.isSpotLight){let e=t.get(y);e.position.setFromMatrixPosition(y.matrixWorld),e.color.copy(b).multiplyScalar(x),e.distance=S,e.coneCos=Math.cos(y.angle),e.penumbraCos=Math.cos(y.angle*(1-y.penumbra)),e.decay=y.decay,r.spot[u]=e;let i=y.shadow;if(y.map&&(r.spotLightMap[g]=y.map,g++,i.updateMatrices(y),y.castShadow&&_++),r.spotLightMatrix[u]=i.matrix,y.castShadow){let e=n.get(y);e.shadowIntensity=i.intensity,e.shadowBias=i.bias,e.shadowNormalBias=i.normalBias,e.shadowRadius=i.radius,e.shadowMapSize=i.mapSize,r.spotShadow[u]=e,r.spotShadowMap[u]=C,h++}u++}else if(y.isRectAreaLight){let e=t.get(y);e.color.copy(b).multiplyScalar(x),e.halfWidth.set(y.width*.5,0,0),e.halfHeight.set(0,y.height*.5,0),r.rectArea[d]=e,d++}else if(y.isPointLight){let e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),e.distance=y.distance,e.decay=y.decay,y.castShadow){let e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,r.pointShadow[l]=t,r.pointShadowMap[l]=C,r.pointShadowMatrix[l]=y.shadow.matrix,m++}r.point[l]=e,l++}else if(y.isHemisphereLight){let e=t.get(y);e.skyColor.copy(y.color).multiplyScalar(x),e.groundColor.copy(y.groundColor).multiplyScalar(x),r.hemi[f]=e,f++}}d>0&&(e.has(`OES_texture_float_linear`)===!0?(r.rectAreaLTC1=Z.LTC_FLOAT_1,r.rectAreaLTC2=Z.LTC_FLOAT_2):(r.rectAreaLTC1=Z.LTC_HALF_1,r.rectAreaLTC2=Z.LTC_HALF_2)),r.ambient[0]=a,r.ambient[1]=o,r.ambient[2]=s;let y=r.hash;(y.directionalLength!==c||y.pointLength!==l||y.spotLength!==u||y.rectAreaLength!==d||y.hemiLength!==f||y.numDirectionalShadows!==p||y.numPointShadows!==m||y.numSpotShadows!==h||y.numSpotMaps!==g||y.numLightProbes!==v)&&(r.directional.length=c,r.spot.length=u,r.rectArea.length=d,r.point.length=l,r.hemi.length=f,r.directionalShadow.length=p,r.directionalShadowMap.length=p,r.pointShadow.length=m,r.pointShadowMap.length=m,r.spotShadow.length=h,r.spotShadowMap.length=h,r.directionalShadowMatrix.length=p,r.pointShadowMatrix.length=m,r.spotLightMatrix.length=h+g-_,r.spotLightMap.length=g,r.numSpotLightShadowsWithMaps=_,r.numLightProbes=v,y.directionalLength=c,y.pointLength=l,y.spotLength=u,y.rectAreaLength=d,y.hemiLength=f,y.numDirectionalShadows=p,y.numPointShadows=m,y.numSpotShadows=h,y.numSpotMaps=g,y.numLightProbes=v,r.version=Zh++)}function c(e,t){let n=0,s=0,c=0,l=0,u=0,d=t.matrixWorldInverse;for(let t=0,f=e.length;t<f;t++){let f=e[t];if(f.isDirectionalLight){let e=r.directional[n];e.direction.setFromMatrixPosition(f.matrixWorld),i.setFromMatrixPosition(f.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(d),n++}else if(f.isSpotLight){let e=r.spot[c];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),e.direction.setFromMatrixPosition(f.matrixWorld),i.setFromMatrixPosition(f.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(d),c++}else if(f.isRectAreaLight){let e=r.rectArea[l];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),o.identity(),a.copy(f.matrixWorld),a.premultiply(d),o.extractRotation(a),e.halfWidth.set(f.width*.5,0,0),e.halfHeight.set(0,f.height*.5,0),e.halfWidth.applyMatrix4(o),e.halfHeight.applyMatrix4(o),l++}else if(f.isPointLight){let e=r.point[s];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),s++}else if(f.isHemisphereLight){let e=r.hemi[u];e.direction.setFromMatrixPosition(f.matrixWorld),e.direction.transformDirection(d),u++}}}return{setup:s,setupView:c,state:r}}function eg(e){let t=new $h(e),n=[],r=[],i=[];function a(e){d.camera=e,n.length=0,r.length=0,i.length=0}function o(e){n.push(e)}function s(e){r.push(e)}function c(e){i.push(e)}function l(){t.setup(n)}function u(e){t.setupView(n,e)}let d={lightsArray:n,shadowsArray:r,lightProbeGridArray:i,camera:null,lights:t,transmissionRenderTarget:{},textureUnits:0};return{init:a,state:d,setupLights:l,setupLightsView:u,pushLight:o,pushShadow:s,pushLightProbeGrid:c}}function tg(e){let t=new WeakMap;function n(n,r=0){let i=t.get(n),a;return i===void 0?(a=new eg(e),t.set(n,[a])):r>=i.length?(a=new eg(e),i.push(a)):a=i[r],a}function r(){t=new WeakMap}return{get:n,dispose:r}}var ng=`void main() {
|
|
4055
|
+
`+n)}else o===``?(s===``||c===``)&&(u=!1):B(`WebGLProgram: Program Info Log:`,o);u&&(t.diagnostics={runnable:l,programLog:o,vertexShader:{log:s,prefix:g},fragmentShader:{log:c,prefix:_}})}i.deleteShader(x),i.deleteShader(S),w=new rh(i,h),T=vh(i,h)}let w;this.getUniforms=function(){return w===void 0&&C(this),w};let T;this.getAttributes=function(){return T===void 0&&C(this),T};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=i.getProgramParameter(h,ah)),E},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(h),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=oh++,this.cacheKey=t,this.usedTimes=1,this.program=h,this.vertexShader=x,this.fragmentShader=S,this}var Bh=0,Vh=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){let t=e.vertexShader,n=e.fragmentShader,r=this._getShaderStage(t),i=this._getShaderStage(n),a=this._getShaderCacheForMaterial(e);return a.has(r)===!1&&(a.add(r),r.usedTimes++),a.has(i)===!1&&(a.add(i),i.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let e of t)e.usedTimes--,e.usedTimes===0&&this.shaderCache.delete(e.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new Hh(e),t.set(e,n)),n}},Hh=class{constructor(e){this.id=Bh++,this.code=e,this.usedTimes=0}};function Uh(e){return e===1030||e===37490||e===36285}function Wh(e,t,n,r,i,a){let o=new lc,s=new Vh,c=new Set,l=[],u=new Map,d=r.logarithmicDepthBuffer,f=r.precision,p={MeshDepthMaterial:`depth`,MeshDistanceMaterial:`distance`,MeshNormalMaterial:`normal`,MeshBasicMaterial:`basic`,MeshLambertMaterial:`lambert`,MeshPhongMaterial:`phong`,MeshToonMaterial:`toon`,MeshStandardMaterial:`physical`,MeshPhysicalMaterial:`physical`,MeshMatcapMaterial:`matcap`,LineBasicMaterial:`basic`,LineDashedMaterial:`dashed`,PointsMaterial:`points`,ShadowMaterial:`shadow`,SpriteMaterial:`sprite`};function m(e){return c.add(e),e===0?`uv`:`uv${e}`}function h(i,o,l,u,h,g){let _=u.fog,v=h.geometry,y=i.isMeshStandardMaterial||i.isMeshLambertMaterial||i.isMeshPhongMaterial?u.environment:null,b=i.isMeshStandardMaterial||i.isMeshLambertMaterial&&!i.envMap||i.isMeshPhongMaterial&&!i.envMap,x=t.get(i.envMap||y,b),S=x&&x.mapping===306?x.image.height:null,C=p[i.type];i.precision!==null&&(f=r.getMaxPrecision(i.precision),f!==i.precision&&B(`WebGLProgram.getParameters:`,i.precision,`not supported, using`,f,`instead.`));let w=v.morphAttributes.position||v.morphAttributes.normal||v.morphAttributes.color,T=w===void 0?0:w.length,E=0;v.morphAttributes.position!==void 0&&(E=1),v.morphAttributes.normal!==void 0&&(E=2),v.morphAttributes.color!==void 0&&(E=3);let D,O,k,A;if(C){let e=fp[C];D=e.vertexShader,O=e.fragmentShader}else D=i.vertexShader,O=i.fragmentShader,s.update(i),k=s.getVertexShaderID(i),A=s.getFragmentShaderID(i);let ee=e.getRenderTarget(),te=e.state.buffers.depth.getReversed(),ne=h.isInstancedMesh===!0,re=h.isBatchedMesh===!0,ie=!!i.map,ae=!!i.matcap,j=!!x,oe=!!i.aoMap,se=!!i.lightMap,ce=!!i.bumpMap,le=!!i.normalMap,ue=!!i.displacementMap,M=!!i.emissiveMap,de=!!i.metalnessMap,fe=!!i.roughnessMap,pe=i.anisotropy>0,me=i.clearcoat>0,he=i.dispersion>0,ge=i.iridescence>0,_e=i.sheen>0,ve=i.transmission>0,ye=pe&&!!i.anisotropyMap,be=me&&!!i.clearcoatMap,xe=me&&!!i.clearcoatNormalMap,N=me&&!!i.clearcoatRoughnessMap,Se=ge&&!!i.iridescenceMap,Ce=ge&&!!i.iridescenceThicknessMap,we=_e&&!!i.sheenColorMap,P=_e&&!!i.sheenRoughnessMap,Te=!!i.specularMap,F=!!i.specularColorMap,I=!!i.specularIntensityMap,L=ve&&!!i.transmissionMap,Ee=ve&&!!i.thicknessMap,De=!!i.gradientMap,Oe=!!i.alphaMap,ke=i.alphaTest>0,Ae=!!i.alphaHash,je=!!i.extensions,Me=0;i.toneMapped&&(ee===null||ee.isXRRenderTarget===!0)&&(Me=e.toneMapping);let Ne={shaderID:C,shaderType:i.type,shaderName:i.name,vertexShader:D,fragmentShader:O,defines:i.defines,customVertexShaderID:k,customFragmentShaderID:A,isRawShaderMaterial:i.isRawShaderMaterial===!0,glslVersion:i.glslVersion,precision:f,batching:re,batchingColor:re&&h._colorsTexture!==null,instancing:ne,instancingColor:ne&&h.instanceColor!==null,instancingMorph:ne&&h.morphTexture!==null,outputColorSpace:ee===null?e.outputColorSpace:ee.isXRRenderTarget===!0?ee.texture.colorSpace:Ls.workingColorSpace,alphaToCoverage:!!i.alphaToCoverage,map:ie,matcap:ae,envMap:j,envMapMode:j&&x.mapping,envMapCubeUVHeight:S,aoMap:oe,lightMap:se,bumpMap:ce,normalMap:le,displacementMap:ue,emissiveMap:M,normalMapObjectSpace:le&&i.normalMapType===1,normalMapTangentSpace:le&&i.normalMapType===0,packedNormalMap:le&&i.normalMapType===0&&Uh(i.normalMap.format),metalnessMap:de,roughnessMap:fe,anisotropy:pe,anisotropyMap:ye,clearcoat:me,clearcoatMap:be,clearcoatNormalMap:xe,clearcoatRoughnessMap:N,dispersion:he,iridescence:ge,iridescenceMap:Se,iridescenceThicknessMap:Ce,sheen:_e,sheenColorMap:we,sheenRoughnessMap:P,specularMap:Te,specularColorMap:F,specularIntensityMap:I,transmission:ve,transmissionMap:L,thicknessMap:Ee,gradientMap:De,opaque:i.transparent===!1&&i.blending===1&&i.alphaToCoverage===!1,alphaMap:Oe,alphaTest:ke,alphaHash:Ae,combine:i.combine,mapUv:ie&&m(i.map.channel),aoMapUv:oe&&m(i.aoMap.channel),lightMapUv:se&&m(i.lightMap.channel),bumpMapUv:ce&&m(i.bumpMap.channel),normalMapUv:le&&m(i.normalMap.channel),displacementMapUv:ue&&m(i.displacementMap.channel),emissiveMapUv:M&&m(i.emissiveMap.channel),metalnessMapUv:de&&m(i.metalnessMap.channel),roughnessMapUv:fe&&m(i.roughnessMap.channel),anisotropyMapUv:ye&&m(i.anisotropyMap.channel),clearcoatMapUv:be&&m(i.clearcoatMap.channel),clearcoatNormalMapUv:xe&&m(i.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:N&&m(i.clearcoatRoughnessMap.channel),iridescenceMapUv:Se&&m(i.iridescenceMap.channel),iridescenceThicknessMapUv:Ce&&m(i.iridescenceThicknessMap.channel),sheenColorMapUv:we&&m(i.sheenColorMap.channel),sheenRoughnessMapUv:P&&m(i.sheenRoughnessMap.channel),specularMapUv:Te&&m(i.specularMap.channel),specularColorMapUv:F&&m(i.specularColorMap.channel),specularIntensityMapUv:I&&m(i.specularIntensityMap.channel),transmissionMapUv:L&&m(i.transmissionMap.channel),thicknessMapUv:Ee&&m(i.thicknessMap.channel),alphaMapUv:Oe&&m(i.alphaMap.channel),vertexTangents:!!v.attributes.tangent&&(le||pe),vertexNormals:!!v.attributes.normal,vertexColors:i.vertexColors,vertexAlphas:i.vertexColors===!0&&!!v.attributes.color&&v.attributes.color.itemSize===4,pointsUvs:h.isPoints===!0&&!!v.attributes.uv&&(ie||Oe),fog:!!_,useFog:i.fog===!0,fogExp2:!!_&&_.isFogExp2,flatShading:i.wireframe===!1&&(i.flatShading===!0||v.attributes.normal===void 0&&le===!1&&(i.isMeshLambertMaterial||i.isMeshPhongMaterial||i.isMeshStandardMaterial||i.isMeshPhysicalMaterial)),sizeAttenuation:i.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:te,skinning:h.isSkinnedMesh===!0,morphTargets:v.morphAttributes.position!==void 0,morphNormals:v.morphAttributes.normal!==void 0,morphColors:v.morphAttributes.color!==void 0,morphTargetsCount:T,morphTextureStride:E,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numLightProbeGrids:g.length,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:i.dithering,shadowMapEnabled:e.shadowMap.enabled&&l.length>0,shadowMapType:e.shadowMap.type,toneMapping:Me,decodeVideoTexture:ie&&i.map.isVideoTexture===!0&&Ls.getTransfer(i.map.colorSpace)===`srgb`,decodeVideoTextureEmissive:M&&i.emissiveMap.isVideoTexture===!0&&Ls.getTransfer(i.emissiveMap.colorSpace)===`srgb`,premultipliedAlpha:i.premultipliedAlpha,doubleSided:i.side===2,flipSided:i.side===1,useDepthPacking:i.depthPacking>=0,depthPacking:i.depthPacking||0,index0AttributeName:i.index0AttributeName,extensionClipCullDistance:je&&i.extensions.clipCullDistance===!0&&n.has(`WEBGL_clip_cull_distance`),extensionMultiDraw:(je&&i.extensions.multiDraw===!0||re)&&n.has(`WEBGL_multi_draw`),rendererExtensionParallelShaderCompile:n.has(`KHR_parallel_shader_compile`),customProgramCacheKey:i.customProgramCacheKey()};return Ne.vertexUv1s=c.has(1),Ne.vertexUv2s=c.has(2),Ne.vertexUv3s=c.has(3),c.clear(),Ne}function g(t){let n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),t.defines!==void 0)for(let e in t.defines)n.push(e),n.push(t.defines[e]);return t.isRawShaderMaterial===!1&&(_(n,t),v(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()}function _(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}function v(e,t){o.disableAll(),t.instancing&&o.enable(0),t.instancingColor&&o.enable(1),t.instancingMorph&&o.enable(2),t.matcap&&o.enable(3),t.envMap&&o.enable(4),t.normalMapObjectSpace&&o.enable(5),t.normalMapTangentSpace&&o.enable(6),t.clearcoat&&o.enable(7),t.iridescence&&o.enable(8),t.alphaTest&&o.enable(9),t.vertexColors&&o.enable(10),t.vertexAlphas&&o.enable(11),t.vertexUv1s&&o.enable(12),t.vertexUv2s&&o.enable(13),t.vertexUv3s&&o.enable(14),t.vertexTangents&&o.enable(15),t.anisotropy&&o.enable(16),t.alphaHash&&o.enable(17),t.batching&&o.enable(18),t.dispersion&&o.enable(19),t.batchingColor&&o.enable(20),t.gradientMap&&o.enable(21),t.packedNormalMap&&o.enable(22),t.vertexNormals&&o.enable(23),e.push(o.mask),o.disableAll(),t.fog&&o.enable(0),t.useFog&&o.enable(1),t.flatShading&&o.enable(2),t.logarithmicDepthBuffer&&o.enable(3),t.reversedDepthBuffer&&o.enable(4),t.skinning&&o.enable(5),t.morphTargets&&o.enable(6),t.morphNormals&&o.enable(7),t.morphColors&&o.enable(8),t.premultipliedAlpha&&o.enable(9),t.shadowMapEnabled&&o.enable(10),t.doubleSided&&o.enable(11),t.flipSided&&o.enable(12),t.useDepthPacking&&o.enable(13),t.dithering&&o.enable(14),t.transmission&&o.enable(15),t.sheen&&o.enable(16),t.opaque&&o.enable(17),t.pointsUvs&&o.enable(18),t.decodeVideoTexture&&o.enable(19),t.decodeVideoTextureEmissive&&o.enable(20),t.alphaToCoverage&&o.enable(21),t.numLightProbeGrids>0&&o.enable(22),e.push(o.mask)}function y(e){let t=p[e.type],n;if(t){let e=fp[t];n=wd.clone(e.uniforms)}else n=e.uniforms;return n}function b(t,n){let r=u.get(n);return r===void 0?(r=new zh(e,n,t,i),l.push(r),u.set(n,r)):++r.usedTimes,r}function x(e){if(--e.usedTimes===0){let t=l.indexOf(e);l[t]=l[l.length-1],l.pop(),u.delete(e.cacheKey),e.destroy()}}function S(e){s.remove(e)}function C(){s.dispose()}return{getParameters:h,getProgramCacheKey:g,getUniforms:y,acquireProgram:b,releaseProgram:x,releaseShaderCache:S,programs:l,dispose:C}}function Gh(){let e=new WeakMap;function t(t){return e.has(t)}function n(t){let n=e.get(t);return n===void 0&&(n={},e.set(t,n)),n}function r(t){e.delete(t)}function i(t,n,r){e.get(t)[n]=r}function a(){e=new WeakMap}return{has:t,get:n,remove:r,update:i,dispose:a}}function Kh(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.material.id===t.material.id?e.materialVariant===t.materialVariant?e.z===t.z?e.id-t.id:e.z-t.z:e.materialVariant-t.materialVariant:e.material.id-t.material.id:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function qh(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.z===t.z?e.id-t.id:t.z-e.z:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function Jh(){let e=[],t=0,n=[],r=[],i=[];function a(){t=0,n.length=0,r.length=0,i.length=0}function o(e){let t=0;return e.isInstancedMesh&&(t+=2),e.isSkinnedMesh&&(t+=1),t}function s(n,r,i,a,s,c){let l=e[t];return l===void 0?(l={id:n.id,object:n,geometry:r,material:i,materialVariant:o(n),groupOrder:a,renderOrder:n.renderOrder,z:s,group:c},e[t]=l):(l.id=n.id,l.object=n,l.geometry=r,l.material=i,l.materialVariant=o(n),l.groupOrder=a,l.renderOrder=n.renderOrder,l.z=s,l.group=c),t++,l}function c(e,t,a,o,c,l){let u=s(e,t,a,o,c,l);a.transmission>0?r.push(u):a.transparent===!0?i.push(u):n.push(u)}function l(e,t,a,o,c,l){let u=s(e,t,a,o,c,l);a.transmission>0?r.unshift(u):a.transparent===!0?i.unshift(u):n.unshift(u)}function u(e,t){n.length>1&&n.sort(e||Kh),r.length>1&&r.sort(t||qh),i.length>1&&i.sort(t||qh)}function d(){for(let n=t,r=e.length;n<r;n++){let t=e[n];if(t.id===null)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}}return{opaque:n,transmissive:r,transparent:i,init:a,push:c,unshift:l,finish:d,sort:u}}function Yh(){let e=new WeakMap;function t(t,n){let r=e.get(t),i;return r===void 0?(i=new Jh,e.set(t,[i])):n>=r.length?(i=new Jh,r.push(i)):i=r[n],i}function n(){e=new WeakMap}return{get:t,dispose:n}}function Xh(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={direction:new W,color:new q};break;case`SpotLight`:n={position:new W,direction:new W,color:new q,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case`PointLight`:n={position:new W,color:new q,distance:0,decay:0};break;case`HemisphereLight`:n={direction:new W,skyColor:new q,groundColor:new q};break;case`RectAreaLight`:n={color:new q,position:new W,halfWidth:new W,halfHeight:new W};break}return e[t.id]=n,n}}}function Zh(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new H};break;case`SpotLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new H};break;case`PointLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new H,shadowCameraNear:1,shadowCameraFar:1e3};break}return e[t.id]=n,n}}}var Qh=0;function $h(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+ +!!t.map-!!e.map}function eg(e){let t=new Xh,n=Zh(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)r.probe.push(new W);let i=new W,a=new K,o=new K;function s(i){let a=0,o=0,s=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0;i.sort($h);for(let e=0,y=i.length;e<y;e++){let y=i[e],b=y.color,x=y.intensity,S=y.distance,C=null;if(y.shadow&&y.shadow.map&&(C=y.shadow.map.texture.format===1030?y.shadow.map.texture:y.shadow.map.depthTexture||y.shadow.map.texture),y.isAmbientLight)a+=b.r*x,o+=b.g*x,s+=b.b*x;else if(y.isLightProbe){for(let e=0;e<9;e++)r.probe[e].addScaledVector(y.sh.coefficients[e],x);v++}else if(y.isDirectionalLight){let e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),y.castShadow){let e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,r.directionalShadow[c]=t,r.directionalShadowMap[c]=C,r.directionalShadowMatrix[c]=y.shadow.matrix,p++}r.directional[c]=e,c++}else if(y.isSpotLight){let e=t.get(y);e.position.setFromMatrixPosition(y.matrixWorld),e.color.copy(b).multiplyScalar(x),e.distance=S,e.coneCos=Math.cos(y.angle),e.penumbraCos=Math.cos(y.angle*(1-y.penumbra)),e.decay=y.decay,r.spot[u]=e;let i=y.shadow;if(y.map&&(r.spotLightMap[g]=y.map,g++,i.updateMatrices(y),y.castShadow&&_++),r.spotLightMatrix[u]=i.matrix,y.castShadow){let e=n.get(y);e.shadowIntensity=i.intensity,e.shadowBias=i.bias,e.shadowNormalBias=i.normalBias,e.shadowRadius=i.radius,e.shadowMapSize=i.mapSize,r.spotShadow[u]=e,r.spotShadowMap[u]=C,h++}u++}else if(y.isRectAreaLight){let e=t.get(y);e.color.copy(b).multiplyScalar(x),e.halfWidth.set(y.width*.5,0,0),e.halfHeight.set(0,y.height*.5,0),r.rectArea[d]=e,d++}else if(y.isPointLight){let e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),e.distance=y.distance,e.decay=y.decay,y.castShadow){let e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,r.pointShadow[l]=t,r.pointShadowMap[l]=C,r.pointShadowMatrix[l]=y.shadow.matrix,m++}r.point[l]=e,l++}else if(y.isHemisphereLight){let e=t.get(y);e.skyColor.copy(y.color).multiplyScalar(x),e.groundColor.copy(y.groundColor).multiplyScalar(x),r.hemi[f]=e,f++}}d>0&&(e.has(`OES_texture_float_linear`)===!0?(r.rectAreaLTC1=X.LTC_FLOAT_1,r.rectAreaLTC2=X.LTC_FLOAT_2):(r.rectAreaLTC1=X.LTC_HALF_1,r.rectAreaLTC2=X.LTC_HALF_2)),r.ambient[0]=a,r.ambient[1]=o,r.ambient[2]=s;let y=r.hash;(y.directionalLength!==c||y.pointLength!==l||y.spotLength!==u||y.rectAreaLength!==d||y.hemiLength!==f||y.numDirectionalShadows!==p||y.numPointShadows!==m||y.numSpotShadows!==h||y.numSpotMaps!==g||y.numLightProbes!==v)&&(r.directional.length=c,r.spot.length=u,r.rectArea.length=d,r.point.length=l,r.hemi.length=f,r.directionalShadow.length=p,r.directionalShadowMap.length=p,r.pointShadow.length=m,r.pointShadowMap.length=m,r.spotShadow.length=h,r.spotShadowMap.length=h,r.directionalShadowMatrix.length=p,r.pointShadowMatrix.length=m,r.spotLightMatrix.length=h+g-_,r.spotLightMap.length=g,r.numSpotLightShadowsWithMaps=_,r.numLightProbes=v,y.directionalLength=c,y.pointLength=l,y.spotLength=u,y.rectAreaLength=d,y.hemiLength=f,y.numDirectionalShadows=p,y.numPointShadows=m,y.numSpotShadows=h,y.numSpotMaps=g,y.numLightProbes=v,r.version=Qh++)}function c(e,t){let n=0,s=0,c=0,l=0,u=0,d=t.matrixWorldInverse;for(let t=0,f=e.length;t<f;t++){let f=e[t];if(f.isDirectionalLight){let e=r.directional[n];e.direction.setFromMatrixPosition(f.matrixWorld),i.setFromMatrixPosition(f.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(d),n++}else if(f.isSpotLight){let e=r.spot[c];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),e.direction.setFromMatrixPosition(f.matrixWorld),i.setFromMatrixPosition(f.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(d),c++}else if(f.isRectAreaLight){let e=r.rectArea[l];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),o.identity(),a.copy(f.matrixWorld),a.premultiply(d),o.extractRotation(a),e.halfWidth.set(f.width*.5,0,0),e.halfHeight.set(0,f.height*.5,0),e.halfWidth.applyMatrix4(o),e.halfHeight.applyMatrix4(o),l++}else if(f.isPointLight){let e=r.point[s];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),s++}else if(f.isHemisphereLight){let e=r.hemi[u];e.direction.setFromMatrixPosition(f.matrixWorld),e.direction.transformDirection(d),u++}}}return{setup:s,setupView:c,state:r}}function tg(e){let t=new eg(e),n=[],r=[],i=[];function a(e){d.camera=e,n.length=0,r.length=0,i.length=0}function o(e){n.push(e)}function s(e){r.push(e)}function c(e){i.push(e)}function l(){t.setup(n)}function u(e){t.setupView(n,e)}let d={lightsArray:n,shadowsArray:r,lightProbeGridArray:i,camera:null,lights:t,transmissionRenderTarget:{},textureUnits:0};return{init:a,state:d,setupLights:l,setupLightsView:u,pushLight:o,pushShadow:s,pushLightProbeGrid:c}}function ng(e){let t=new WeakMap;function n(n,r=0){let i=t.get(n),a;return i===void 0?(a=new tg(e),t.set(n,[a])):r>=i.length?(a=new tg(e),i.push(a)):a=i[r],a}function r(){t=new WeakMap}return{get:n,dispose:r}}var rg=`void main() {
|
|
4056
4056
|
gl_Position = vec4( position, 1.0 );
|
|
4057
|
-
}`,
|
|
4057
|
+
}`,ig=`uniform sampler2D shadow_pass;
|
|
4058
4058
|
uniform vec2 resolution;
|
|
4059
4059
|
uniform float radius;
|
|
4060
4060
|
void main() {
|
|
@@ -4079,12 +4079,12 @@ void main() {
|
|
|
4079
4079
|
squared_mean = squared_mean / samples;
|
|
4080
4080
|
float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );
|
|
4081
4081
|
gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );
|
|
4082
|
-
}`,ig=[new W(1,0,0),new W(-1,0,0),new W(0,1,0),new W(0,-1,0),new W(0,0,1),new W(0,0,-1)],ag=[new W(0,-1,0),new W(0,-1,0),new W(0,0,1),new W(0,0,-1),new W(0,-1,0),new W(0,-1,0)],og=new K,sg=new W,cg=new W;function lg(e,t,n){let r=new Ru,i=new H,a=new H,o=new Js,s=new jd,c=new Md,l={},u=n.maxTextureSize,d={0:1,1:0,2:2},f=new Dd({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new H},radius:{value:4}},vertexShader:ng,fragmentShader:rg}),p=f.clone();p.defines.HORIZONTAL_PASS=1;let m=new Y;m.setAttribute(`position`,new J(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let h=new iu(m,f),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let _=this.type;this.render=function(t,n,s){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||t.length===0)return;this.type===2&&(B(`WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead.`),this.type=1);let c=e.getRenderTarget(),l=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),f=e.state;f.setBlending(0),f.buffers.depth.getReversed()===!0?f.buffers.color.setClear(0,0,0,0):f.buffers.color.setClear(1,1,1,1),f.buffers.depth.setTest(!0),f.setScissorTest(!1);let p=_!==this.type;p&&n.traverse(function(e){e.material&&(Array.isArray(e.material)?e.material.forEach(e=>e.needsUpdate=!0):e.material.needsUpdate=!0)});for(let c=0,l=t.length;c<l;c++){let l=t[c],d=l.shadow;if(d===void 0){B(`WebGLShadowMap:`,l,`has no shadow.`);continue}if(d.autoUpdate===!1&&d.needsUpdate===!1)continue;i.copy(d.mapSize);let m=d.getFrameExtents();i.multiply(m),a.copy(d.mapSize),(i.x>u||i.y>u)&&(i.x>u&&(a.x=Math.floor(u/m.x),i.x=a.x*m.x,d.mapSize.x=a.x),i.y>u&&(a.y=Math.floor(u/m.y),i.y=a.y*m.y,d.mapSize.y=a.y));let h=e.state.buffers.depth.getReversed();if(d.camera._reversedDepth=h,d.map===null||p===!0){if(d.map!==null&&(d.map.depthTexture!==null&&(d.map.depthTexture.dispose(),d.map.depthTexture=null),d.map.dispose()),this.type===3){if(l.isPointLight){B(`WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.`);continue}d.map=new Xs(i.x,i.y,{format:Ra,type:Ta,minFilter:ha,magFilter:ha,generateMipmaps:!1}),d.map.texture.name=l.name+`.shadowMap`,d.map.depthTexture=new cd(i.x,i.y,wa),d.map.depthTexture.name=l.name+`.shadowMapDepth`,d.map.depthTexture.format=Pa,d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=fa,d.map.depthTexture.magFilter=fa}else l.isPointLight?(d.map=new Bp(i.x),d.map.depthTexture=new ld(i.x,Ca)):(d.map=new Xs(i.x,i.y),d.map.depthTexture=new cd(i.x,i.y,Ca)),d.map.depthTexture.name=l.name+`.shadowMap`,d.map.depthTexture.format=Pa,this.type===1?(d.map.depthTexture.compareFunction=h?518:515,d.map.depthTexture.minFilter=ha,d.map.depthTexture.magFilter=ha):(d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=fa,d.map.depthTexture.magFilter=fa);d.camera.updateProjectionMatrix()}let g=d.map.isWebGLCubeRenderTarget?6:1;for(let t=0;t<g;t++){if(d.map.isWebGLCubeRenderTarget)e.setRenderTarget(d.map,t),e.clear();else{t===0&&(e.setRenderTarget(d.map),e.clear());let n=d.getViewport(t);o.set(a.x*n.x,a.y*n.y,a.x*n.z,a.y*n.w),f.viewport(o)}if(l.isPointLight){let e=d.camera,n=d.matrix,r=l.distance||e.far;r!==e.far&&(e.far=r,e.updateProjectionMatrix()),sg.setFromMatrixPosition(l.matrixWorld),e.position.copy(sg),cg.copy(e.position),cg.add(ig[t]),e.up.copy(ag[t]),e.lookAt(cg),e.updateMatrixWorld(),n.makeTranslation(-sg.x,-sg.y,-sg.z),og.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),d._frustum.setFromProjectionMatrix(og,e.coordinateSystem,e.reversedDepth)}else d.updateMatrices(l);r=d.getFrustum(),b(n,s,d.camera,l,this.type)}d.isPointLightShadow!==!0&&this.type===3&&v(d,s),d.needsUpdate=!1}_=this.type,g.needsUpdate=!1,e.setRenderTarget(c,l,d)};function v(n,r){let a=t.update(h);f.defines.VSM_SAMPLES!==n.blurSamples&&(f.defines.VSM_SAMPLES=n.blurSamples,p.defines.VSM_SAMPLES=n.blurSamples,f.needsUpdate=!0,p.needsUpdate=!0),n.mapPass===null&&(n.mapPass=new Xs(i.x,i.y,{format:Ra,type:Ta})),f.uniforms.shadow_pass.value=n.map.depthTexture,f.uniforms.resolution.value=n.mapSize,f.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(r,null,a,f,h,null),p.uniforms.shadow_pass.value=n.mapPass.texture,p.uniforms.resolution.value=n.mapSize,p.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(r,null,a,p,h,null)}function y(t,n,r,i){let a=null,o=r.isPointLight===!0?t.customDistanceMaterial:t.customDepthMaterial;if(o!==void 0)a=o;else if(a=r.isPointLight===!0?c:s,e.localClippingEnabled&&n.clipShadows===!0&&Array.isArray(n.clippingPlanes)&&n.clippingPlanes.length!==0||n.displacementMap&&n.displacementScale!==0||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||n.alphaToCoverage===!0){let e=a.uuid,t=n.uuid,r=l[e];r===void 0&&(r={},l[e]=r);let i=r[t];i===void 0&&(i=a.clone(),r[t]=i,n.addEventListener(`dispose`,x)),a=i}if(a.visible=n.visible,a.wireframe=n.wireframe,i===3?a.side=n.shadowSide===null?n.side:n.shadowSide:a.side=n.shadowSide===null?d[n.side]:n.shadowSide,a.alphaMap=n.alphaMap,a.alphaTest=n.alphaToCoverage===!0?.5:n.alphaTest,a.map=n.map,a.clipShadows=n.clipShadows,a.clippingPlanes=n.clippingPlanes,a.clipIntersection=n.clipIntersection,a.displacementMap=n.displacementMap,a.displacementScale=n.displacementScale,a.displacementBias=n.displacementBias,a.wireframeLinewidth=n.wireframeLinewidth,a.linewidth=n.linewidth,r.isPointLight===!0&&a.isMeshDistanceMaterial===!0){let t=e.properties.get(a);t.light=r}return a}function b(n,i,a,o,s){if(n.visible===!1)return;if(n.layers.test(i.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&s===3)&&(!n.frustumCulled||r.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,n.matrixWorld);let r=t.update(n),c=n.material;if(Array.isArray(c)){let t=r.groups;for(let l=0,u=t.length;l<u;l++){let u=t[l],d=c[u.materialIndex];if(d&&d.visible){let t=y(n,d,o,s);n.onBeforeShadow(e,n,i,a,r,t,u),e.renderBufferDirect(a,null,r,t,n,u),n.onAfterShadow(e,n,i,a,r,t,u)}}}else if(c.visible){let t=y(n,c,o,s);n.onBeforeShadow(e,n,i,a,r,t,null),e.renderBufferDirect(a,null,r,t,n,null),n.onAfterShadow(e,n,i,a,r,t,null)}}let c=n.children;for(let e=0,t=c.length;e<t;e++)b(c[e],i,a,o,s)}function x(e){e.target.removeEventListener(`dispose`,x);for(let t in l){let n=l[t],r=e.target.uuid;r in n&&(n[r].dispose(),delete n[r])}}}function ug(e,t){function n(){let t=!1,n=new Js,r=null,i=new Js(0,0,0,0);return{setMask:function(n){r!==n&&!t&&(e.colorMask(n,n,n,n),r=n)},setLocked:function(e){t=e},setClear:function(t,r,a,o,s){s===!0&&(t*=o,r*=o,a*=o),n.set(t,r,a,o),i.equals(n)===!1&&(e.clearColor(t,r,a,o),i.copy(n))},reset:function(){t=!1,r=null,i.set(-1,0,0,0)}}}function r(){let n=!1,r=!1,i=null,a=null,o=null;return{setReversed:function(e){if(r!==e){let n=t.get(`EXT_clip_control`);e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),r=e;let i=o;o=null,this.setClear(i)}},getReversed:function(){return r},setTest:function(t){t?de(e.DEPTH_TEST):fe(e.DEPTH_TEST)},setMask:function(t){i!==t&&!n&&(e.depthMask(t),i=t)},setFunc:function(t){if(r&&(t=ns[t]),a!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}a=t}},setLocked:function(e){n=e},setClear:function(t){o!==t&&(o=t,r&&(t=1-t),e.clearDepth(t))},reset:function(){n=!1,i=null,a=null,o=null,r=!1}}}function i(){let t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null;return{setTest:function(n){t||(n?de(e.STENCIL_TEST):fe(e.STENCIL_TEST))},setMask:function(r){n!==r&&!t&&(e.stencilMask(r),n=r)},setFunc:function(t,n,o){(r!==t||i!==n||a!==o)&&(e.stencilFunc(t,n,o),r=t,i=n,a=o)},setOp:function(t,n,r){(o!==t||s!==n||c!==r)&&(e.stencilOp(t,n,r),o=t,s=n,c=r)},setLocked:function(e){t=e},setClear:function(t){l!==t&&(e.clearStencil(t),l=t)},reset:function(){t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null}}}let a=new n,o=new r,s=new i,c=new WeakMap,l=new WeakMap,u={},d={},f={},p=new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new q(0,0,0),T=0,E=!1,D=null,O=null,k=null,A=null,ee=null,te=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),ne=!1,re=0,ie=e.getParameter(e.VERSION);ie.indexOf(`WebGL`)===-1?ie.indexOf(`OpenGL ES`)!==-1&&(re=parseFloat(/^OpenGL ES (\d)/.exec(ie)[1]),ne=re>=2):(re=parseFloat(/^WebGL (\d)/.exec(ie)[1]),ne=re>=1);let ae=null,j={},oe=e.getParameter(e.SCISSOR_BOX),se=e.getParameter(e.VIEWPORT),ce=new Js().fromArray(oe),le=new Js().fromArray(se);function ue(t,n,r,i){let a=new Uint8Array(4),o=e.createTexture();e.bindTexture(t,o),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;o<r;o++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(n,0,e.RGBA,1,1,i,0,e.RGBA,e.UNSIGNED_BYTE,a):e.texImage2D(n+o,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,a);return o}let M={};M[e.TEXTURE_2D]=ue(e.TEXTURE_2D,e.TEXTURE_2D,1),M[e.TEXTURE_CUBE_MAP]=ue(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),M[e.TEXTURE_2D_ARRAY]=ue(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),M[e.TEXTURE_3D]=ue(e.TEXTURE_3D,e.TEXTURE_3D,1,1),a.setClear(0,0,0,1),o.setClear(1),s.setClear(0),de(e.DEPTH_TEST),o.setFunc(3),be(!1),xe(1),de(e.CULL_FACE),ve(0);function de(t){u[t]!==!0&&(e.enable(t),u[t]=!0)}function fe(t){u[t]!==!1&&(e.disable(t),u[t]=!1)}function pe(t,n){return f[t]===n?!1:(e.bindFramebuffer(t,n),f[t]=n,t===e.DRAW_FRAMEBUFFER&&(f[e.FRAMEBUFFER]=n),t===e.FRAMEBUFFER&&(f[e.DRAW_FRAMEBUFFER]=n),!0)}function me(t,n){let r=m,i=!1;if(t){r=p.get(n),r===void 0&&(r=[],p.set(n,r));let a=t.textures;if(r.length!==a.length||r[0]!==e.COLOR_ATTACHMENT0){for(let t=0,n=a.length;t<n;t++)r[t]=e.COLOR_ATTACHMENT0+t;r.length=a.length,i=!0}}else r[0]!==e.BACK&&(r[0]=e.BACK,i=!0);i&&e.drawBuffers(r)}function he(t){return h===t?!1:(e.useProgram(t),h=t,!0)}let ge={100:e.FUNC_ADD,101:e.FUNC_SUBTRACT,102:e.FUNC_REVERSE_SUBTRACT};ge[103]=e.MIN,ge[104]=e.MAX;let _e={200:e.ZERO,201:e.ONE,202:e.SRC_COLOR,204:e.SRC_ALPHA,210:e.SRC_ALPHA_SATURATE,208:e.DST_COLOR,206:e.DST_ALPHA,203:e.ONE_MINUS_SRC_COLOR,205:e.ONE_MINUS_SRC_ALPHA,209:e.ONE_MINUS_DST_COLOR,207:e.ONE_MINUS_DST_ALPHA,211:e.CONSTANT_COLOR,212:e.ONE_MINUS_CONSTANT_COLOR,213:e.CONSTANT_ALPHA,214:e.ONE_MINUS_CONSTANT_ALPHA};function ve(t,n,r,i,a,o,s,c,l,u){if(t===0){g===!0&&(fe(e.BLEND),g=!1);return}if(g===!1&&(de(e.BLEND),g=!0),t!==5){if(t!==_||u!==E){if((v!==100||x!==100)&&(e.blendEquation(e.FUNC_ADD),v=100,x=100),u)switch(t){case 1:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFunc(e.ONE,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:V(`WebGLState: Invalid blending: `,t);break}else switch(t){case 1:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case 3:V(`WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true`);break;case 4:V(`WebGLState: MultiplyBlending requires material.premultipliedAlpha = true`);break;default:V(`WebGLState: Invalid blending: `,t);break}y=null,b=null,S=null,C=null,w.set(0,0,0),T=0,_=t,E=u}return}a||=n,o||=r,s||=i,(n!==v||a!==x)&&(e.blendEquationSeparate(ge[n],ge[a]),v=n,x=a),(r!==y||i!==b||o!==S||s!==C)&&(e.blendFuncSeparate(_e[r],_e[i],_e[o],_e[s]),y=r,b=i,S=o,C=s),(c.equals(w)===!1||l!==T)&&(e.blendColor(c.r,c.g,c.b,l),w.copy(c),T=l),_=t,E=!1}function ye(t,n){t.side===2?fe(e.CULL_FACE):de(e.CULL_FACE);let r=t.side===1;n&&(r=!r),be(r),t.blending===1&&t.transparent===!1?ve(0):ve(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),o.setFunc(t.depthFunc),o.setTest(t.depthTest),o.setMask(t.depthWrite),a.setMask(t.colorWrite);let i=t.stencilWrite;s.setTest(i),i&&(s.setMask(t.stencilWriteMask),s.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),s.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),Se(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),t.alphaToCoverage===!0?de(e.SAMPLE_ALPHA_TO_COVERAGE):fe(e.SAMPLE_ALPHA_TO_COVERAGE)}function be(t){D!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),D=t)}function xe(t){t===0?fe(e.CULL_FACE):(de(e.CULL_FACE),t!==O&&(t===1?e.cullFace(e.BACK):t===2?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))),O=t}function N(t){t!==k&&(ne&&e.lineWidth(t),k=t)}function Se(t,n,r){t?(de(e.POLYGON_OFFSET_FILL),(A!==n||ee!==r)&&(A=n,ee=r,o.getReversed()&&(n=-n),e.polygonOffset(n,r))):fe(e.POLYGON_OFFSET_FILL)}function Ce(t){t?de(e.SCISSOR_TEST):fe(e.SCISSOR_TEST)}function we(t){t===void 0&&(t=e.TEXTURE0+te-1),ae!==t&&(e.activeTexture(t),ae=t)}function P(t,n,r){r===void 0&&(r=ae===null?e.TEXTURE0+te-1:ae);let i=j[r];i===void 0&&(i={type:void 0,texture:void 0},j[r]=i),(i.type!==t||i.texture!==n)&&(ae!==r&&(e.activeTexture(r),ae=r),e.bindTexture(t,n||M[t]),i.type=t,i.texture=n)}function Te(){let t=j[ae];t!==void 0&&t.type!==void 0&&(e.bindTexture(t.type,null),t.type=void 0,t.texture=void 0)}function F(){try{e.compressedTexImage2D(...arguments)}catch(e){V(`WebGLState:`,e)}}function I(){try{e.compressedTexImage3D(...arguments)}catch(e){V(`WebGLState:`,e)}}function L(){try{e.texSubImage2D(...arguments)}catch(e){V(`WebGLState:`,e)}}function Ee(){try{e.texSubImage3D(...arguments)}catch(e){V(`WebGLState:`,e)}}function De(){try{e.compressedTexSubImage2D(...arguments)}catch(e){V(`WebGLState:`,e)}}function Oe(){try{e.compressedTexSubImage3D(...arguments)}catch(e){V(`WebGLState:`,e)}}function ke(){try{e.texStorage2D(...arguments)}catch(e){V(`WebGLState:`,e)}}function Ae(){try{e.texStorage3D(...arguments)}catch(e){V(`WebGLState:`,e)}}function je(){try{e.texImage2D(...arguments)}catch(e){V(`WebGLState:`,e)}}function Me(){try{e.texImage3D(...arguments)}catch(e){V(`WebGLState:`,e)}}function Ne(t){return d[t]===void 0?e.getParameter(t):d[t]}function Pe(t,n){d[t]!==n&&(e.pixelStorei(t,n),d[t]=n)}function Fe(t){ce.equals(t)===!1&&(e.scissor(t.x,t.y,t.z,t.w),ce.copy(t))}function Ie(t){le.equals(t)===!1&&(e.viewport(t.x,t.y,t.z,t.w),le.copy(t))}function Le(t,n){let r=l.get(n);r===void 0&&(r=new WeakMap,l.set(n,r));let i=r.get(t);i===void 0&&(i=e.getUniformBlockIndex(n,t.name),r.set(t,i))}function Re(t,n){let r=l.get(n).get(t);c.get(n)!==r&&(e.uniformBlockBinding(n,r,t.__bindingPointIndex),c.set(n,r))}function ze(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),o.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),u={},d={},ae=null,j={},f={},p=new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new q(0,0,0),T=0,E=!1,D=null,O=null,k=null,A=null,ee=null,ce.set(0,0,e.canvas.width,e.canvas.height),le.set(0,0,e.canvas.width,e.canvas.height),a.reset(),o.reset(),s.reset()}return{buffers:{color:a,depth:o,stencil:s},enable:de,disable:fe,bindFramebuffer:pe,drawBuffers:me,useProgram:he,setBlending:ve,setMaterial:ye,setFlipSided:be,setCullFace:xe,setLineWidth:N,setPolygonOffset:Se,setScissorTest:Ce,activeTexture:we,bindTexture:P,unbindTexture:Te,compressedTexImage2D:F,compressedTexImage3D:I,texImage2D:je,texImage3D:Me,pixelStorei:Pe,getParameter:Ne,updateUBOMapping:Le,uniformBlockBinding:Re,texStorage2D:ke,texStorage3D:Ae,texSubImage2D:L,texSubImage3D:Ee,compressedTexSubImage2D:De,compressedTexSubImage3D:Oe,scissor:Fe,viewport:Ie,reset:ze}}function dg(e,t,n,r,i,a,o){let s=t.has(`WEBGL_multisampled_render_to_texture`)?t.get(`WEBGL_multisampled_render_to_texture`):null,c=typeof navigator>`u`?!1:/OculusBrowser/g.test(navigator.userAgent),l=new H,u=new WeakMap,d=new Set,f,p=new WeakMap,m=!1;try{m=typeof OffscreenCanvas<`u`&&new OffscreenCanvas(1,1).getContext(`2d`)!==null}catch{}function h(e,t){return m?new OffscreenCanvas(e,t):Jo(`canvas`)}function g(e,t,n){let r=1,i=F(e);if((i.width>n||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1)if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof VideoFrame<`u`&&e instanceof VideoFrame){let n=Math.floor(r*i.width),a=Math.floor(r*i.height);f===void 0&&(f=h(n,a));let o=t?h(n,a):f;return o.width=n,o.height=a,o.getContext(`2d`).drawImage(e,0,0,n,a),B(`WebGLRenderer: Texture has been resized from (`+i.width+`x`+i.height+`) to (`+n+`x`+a+`).`),o}else return`data`in e&&B(`WebGLRenderer: Image in DataTexture is too big (`+i.width+`x`+i.height+`).`),e;return e}function _(e){return e.generateMipmaps}function v(t){e.generateMipmap(t)}function y(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function b(n,r,i,a,o,s=!1){if(n!==null){if(e[n]!==void 0)return e[n];B(`WebGLRenderer: Attempt to use non-existing WebGL internal format '`+n+`'`)}let c;a&&(c=t.get(`EXT_texture_norm16`),c||B(`WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension`));let l=r;if(r===e.RED&&(i===e.FLOAT&&(l=e.R32F),i===e.HALF_FLOAT&&(l=e.R16F),i===e.UNSIGNED_BYTE&&(l=e.R8),i===e.UNSIGNED_SHORT&&c&&(l=c.R16_EXT),i===e.SHORT&&c&&(l=c.R16_SNORM_EXT)),r===e.RED_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.R8UI),i===e.UNSIGNED_SHORT&&(l=e.R16UI),i===e.UNSIGNED_INT&&(l=e.R32UI),i===e.BYTE&&(l=e.R8I),i===e.SHORT&&(l=e.R16I),i===e.INT&&(l=e.R32I)),r===e.RG&&(i===e.FLOAT&&(l=e.RG32F),i===e.HALF_FLOAT&&(l=e.RG16F),i===e.UNSIGNED_BYTE&&(l=e.RG8),i===e.UNSIGNED_SHORT&&c&&(l=c.RG16_EXT),i===e.SHORT&&c&&(l=c.RG16_SNORM_EXT)),r===e.RG_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RG8UI),i===e.UNSIGNED_SHORT&&(l=e.RG16UI),i===e.UNSIGNED_INT&&(l=e.RG32UI),i===e.BYTE&&(l=e.RG8I),i===e.SHORT&&(l=e.RG16I),i===e.INT&&(l=e.RG32I)),r===e.RGB_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGB8UI),i===e.UNSIGNED_SHORT&&(l=e.RGB16UI),i===e.UNSIGNED_INT&&(l=e.RGB32UI),i===e.BYTE&&(l=e.RGB8I),i===e.SHORT&&(l=e.RGB16I),i===e.INT&&(l=e.RGB32I)),r===e.RGBA_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGBA8UI),i===e.UNSIGNED_SHORT&&(l=e.RGBA16UI),i===e.UNSIGNED_INT&&(l=e.RGBA32UI),i===e.BYTE&&(l=e.RGBA8I),i===e.SHORT&&(l=e.RGBA16I),i===e.INT&&(l=e.RGBA32I)),r===e.RGB&&(i===e.UNSIGNED_SHORT&&c&&(l=c.RGB16_EXT),i===e.SHORT&&c&&(l=c.RGB16_SNORM_EXT),i===e.UNSIGNED_INT_5_9_9_9_REV&&(l=e.RGB9_E5),i===e.UNSIGNED_INT_10F_11F_11F_REV&&(l=e.R11F_G11F_B10F)),r===e.RGBA){let t=s?Bo:Ls.getTransfer(o);i===e.FLOAT&&(l=e.RGBA32F),i===e.HALF_FLOAT&&(l=e.RGBA16F),i===e.UNSIGNED_BYTE&&(l=t===`srgb`?e.SRGB8_ALPHA8:e.RGBA8),i===e.UNSIGNED_SHORT&&c&&(l=c.RGBA16_EXT),i===e.SHORT&&c&&(l=c.RGBA16_SNORM_EXT),i===e.UNSIGNED_SHORT_4_4_4_4&&(l=e.RGBA4),i===e.UNSIGNED_SHORT_5_5_5_1&&(l=e.RGB5_A1)}return(l===e.R16F||l===e.R32F||l===e.RG16F||l===e.RG32F||l===e.RGBA16F||l===e.RGBA32F)&&t.get(`EXT_color_buffer_float`),l}function x(t,n){let r;return t?n===null||n===1014||n===1020?r=e.DEPTH24_STENCIL8:n===1015?r=e.DEPTH32F_STENCIL8:n===1012&&(r=e.DEPTH24_STENCIL8,B(`DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.`)):n===null||n===1014||n===1020?r=e.DEPTH_COMPONENT24:n===1015?r=e.DEPTH_COMPONENT32F:n===1012&&(r=e.DEPTH_COMPONENT16),r}function S(e,t){return _(e)===!0||e.isFramebufferTexture&&e.minFilter!==1003&&e.minFilter!==1006?Math.log2(Math.max(t.width,t.height))+1:e.mipmaps!==void 0&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function C(e){let t=e.target;t.removeEventListener(`dispose`,C),T(t),t.isVideoTexture&&u.delete(t),t.isHTMLTexture&&d.delete(t)}function w(e){let t=e.target;t.removeEventListener(`dispose`,w),D(t)}function T(e){let t=r.get(e);if(t.__webglInit===void 0)return;let n=e.source,i=p.get(n);if(i){let r=i[t.__cacheKey];r.usedTimes--,r.usedTimes===0&&E(e),Object.keys(i).length===0&&p.delete(n)}r.remove(e)}function E(t){let n=r.get(t);e.deleteTexture(n.__webglTexture);let i=t.source,a=p.get(i);delete a[n.__cacheKey],o.memory.textures--}function D(t){let n=r.get(t);if(t.depthTexture&&(t.depthTexture.dispose(),r.remove(t.depthTexture)),t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let r=0;r<n.__webglFramebuffer[t].length;r++)e.deleteFramebuffer(n.__webglFramebuffer[t][r]);else e.deleteFramebuffer(n.__webglFramebuffer[t]);n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer[t])}else{if(Array.isArray(n.__webglFramebuffer))for(let t=0;t<n.__webglFramebuffer.length;t++)e.deleteFramebuffer(n.__webglFramebuffer[t]);else e.deleteFramebuffer(n.__webglFramebuffer);if(n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&e.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let t=0;t<n.__webglColorRenderbuffer.length;t++)n.__webglColorRenderbuffer[t]&&e.deleteRenderbuffer(n.__webglColorRenderbuffer[t]);n.__webglDepthRenderbuffer&&e.deleteRenderbuffer(n.__webglDepthRenderbuffer)}let i=t.textures;for(let t=0,n=i.length;t<n;t++){let n=r.get(i[t]);n.__webglTexture&&(e.deleteTexture(n.__webglTexture),o.memory.textures--),r.remove(i[t])}r.remove(t)}let O=0;function k(){O=0}function A(){return O}function ee(e){O=e}function te(){let e=O;return e>=i.maxTextures&&B(`WebGLTextures: Trying to use `+e+` texture units while this GPU supports only `+i.maxTextures),O+=1,e}function ne(e){let t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}function re(t,i){let a=r.get(t);if(t.isVideoTexture&&P(t),t.isRenderTargetTexture===!1&&t.isExternalTexture!==!0&&t.version>0&&a.__version!==t.version){let e=t.image;if(e===null)B(`WebGLRenderer: Texture marked for update but no image data found.`);else if(e.complete===!1)B(`WebGLRenderer: Texture marked for update but image is incomplete`);else{fe(a,t,i);return}}else t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D,a.__webglTexture,e.TEXTURE0+i)}function ie(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){fe(a,t,i);return}else t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D_ARRAY,a.__webglTexture,e.TEXTURE0+i)}function ae(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){fe(a,t,i);return}n.bindTexture(e.TEXTURE_3D,a.__webglTexture,e.TEXTURE0+i)}function j(t,i){let a=r.get(t);if(t.isCubeDepthTexture!==!0&&t.version>0&&a.__version!==t.version){pe(a,t,i);return}n.bindTexture(e.TEXTURE_CUBE_MAP,a.__webglTexture,e.TEXTURE0+i)}let oe={[la]:e.REPEAT,[ua]:e.CLAMP_TO_EDGE,[da]:e.MIRRORED_REPEAT},se={[fa]:e.NEAREST,[pa]:e.NEAREST_MIPMAP_NEAREST,[ma]:e.NEAREST_MIPMAP_LINEAR,[ha]:e.LINEAR,[ga]:e.LINEAR_MIPMAP_NEAREST,[_a]:e.LINEAR_MIPMAP_LINEAR},ce={512:e.NEVER,519:e.ALWAYS,513:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL};function le(n,a){if(a.type===1015&&t.has(`OES_texture_float_linear`)===!1&&(a.magFilter===1006||a.magFilter===1007||a.magFilter===1005||a.magFilter===1008||a.minFilter===1006||a.minFilter===1007||a.minFilter===1005||a.minFilter===1008)&&B(`WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.`),e.texParameteri(n,e.TEXTURE_WRAP_S,oe[a.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,oe[a.wrapT]),(n===e.TEXTURE_3D||n===e.TEXTURE_2D_ARRAY)&&e.texParameteri(n,e.TEXTURE_WRAP_R,oe[a.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,se[a.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,se[a.minFilter]),a.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,ce[a.compareFunction])),t.has(`EXT_texture_filter_anisotropic`)===!0){if(a.magFilter===1003||a.minFilter!==1005&&a.minFilter!==1008||a.type===1015&&t.has(`OES_texture_float_linear`)===!1)return;if(a.anisotropy>1||r.get(a).__currentAnisotropy){let o=t.get(`EXT_texture_filter_anisotropic`);e.texParameterf(n,o.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(a.anisotropy,i.getMaxAnisotropy())),r.get(a).__currentAnisotropy=a.anisotropy}}}function ue(t,n){let r=!1;t.__webglInit===void 0&&(t.__webglInit=!0,n.addEventListener(`dispose`,C));let i=n.source,a=p.get(i);a===void 0&&(a={},p.set(i,a));let s=ne(n);if(s!==t.__cacheKey){a[s]===void 0&&(a[s]={texture:e.createTexture(),usedTimes:0},o.memory.textures++,r=!0),a[s].usedTimes++;let i=a[t.__cacheKey];i!==void 0&&(a[t.__cacheKey].usedTimes--,i.usedTimes===0&&E(n)),t.__cacheKey=s,t.__webglTexture=a[s].texture}return r}function M(e,t,n){return Math.floor(Math.floor(e/n)/t)}function de(t,r,i,a){let o=t.updateRanges;if(o.length===0)n.texSubImage2D(e.TEXTURE_2D,0,0,0,r.width,r.height,i,a,r.data);else{o.sort((e,t)=>e.start-t.start);let s=0;for(let e=1;e<o.length;e++){let t=o[s],n=o[e],i=t.start+t.count,a=M(n.start,r.width,4),c=M(t.start,r.width,4);n.start<=i+1&&a===c&&M(n.start+n.count-1,r.width,4)===a?t.count=Math.max(t.count,n.start+n.count-t.start):(++s,o[s]=n)}o.length=s+1;let c=n.getParameter(e.UNPACK_ROW_LENGTH),l=n.getParameter(e.UNPACK_SKIP_PIXELS),u=n.getParameter(e.UNPACK_SKIP_ROWS);n.pixelStorei(e.UNPACK_ROW_LENGTH,r.width);for(let t=0,s=o.length;t<s;t++){let s=o[t],c=Math.floor(s.start/4),l=Math.ceil(s.count/4),u=c%r.width,d=Math.floor(c/r.width),f=l;n.pixelStorei(e.UNPACK_SKIP_PIXELS,u),n.pixelStorei(e.UNPACK_SKIP_ROWS,d),n.texSubImage2D(e.TEXTURE_2D,0,u,d,f,1,i,a,r.data)}t.clearUpdateRanges(),n.pixelStorei(e.UNPACK_ROW_LENGTH,c),n.pixelStorei(e.UNPACK_SKIP_PIXELS,l),n.pixelStorei(e.UNPACK_SKIP_ROWS,u)}}function fe(t,o,s){let c=e.TEXTURE_2D;(o.isDataArrayTexture||o.isCompressedArrayTexture)&&(c=e.TEXTURE_2D_ARRAY),o.isData3DTexture&&(c=e.TEXTURE_3D);let l=ue(t,o),u=o.source;n.bindTexture(c,t.__webglTexture,e.TEXTURE0+s);let f=r.get(u);if(u.version!==f.__version||l===!0){if(n.activeTexture(e.TEXTURE0+s),!(typeof ImageBitmap<`u`&&o.image instanceof ImageBitmap)){let t=Ls.getPrimaries(Ls.workingColorSpace),r=o.colorSpace===``?null:Ls.getPrimaries(o.colorSpace),i=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,i)}n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment);let t=g(o.image,!1,i.maxTextureSize);t=Te(o,t);let r=a.convert(o.format,o.colorSpace),p=a.convert(o.type),m=b(o.internalFormat,r,p,o.normalized,o.colorSpace,o.isVideoTexture);le(c,o);let h,y=o.mipmaps,C=o.isVideoTexture!==!0,w=f.__version===void 0||l===!0,T=u.dataReady,E=S(o,t);if(o.isDepthTexture)m=x(o.format===Fa,o.type),w&&(C?n.texStorage2D(e.TEXTURE_2D,1,m,t.width,t.height):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,null));else if(o.isDataTexture)if(y.length>0){C&&w&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data);o.generateMipmaps=!1}else C?(w&&n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height),T&&de(o,t,r,p)):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,t.data);else if(o.isCompressedTexture)if(o.isCompressedArrayTexture){C&&w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,y[0].width,y[0].height,t.depth);for(let i=0,a=y.length;i<a;i++)if(h=y[i],o.format!==1023)if(r!==null)if(C){if(T)if(o.layerUpdates.size>0){let t=sp(h.width,h.height,o.format,o.type);for(let a of o.layerUpdates){let o=h.data.subarray(a*t/h.data.BYTES_PER_ELEMENT,(a+1)*t/h.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,a,h.width,h.height,1,r,o)}o.clearLayerUpdates()}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,h.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,h.data,0,0);else B(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`);else C?T&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,p,h.data):n.texImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,r,p,h.data)}else{C&&w&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],o.format===1023?C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data):r===null?B(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`):C?T&&n.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,h.data):n.compressedTexImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,h.data)}else if(o.isDataArrayTexture)if(C){if(w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,t.width,t.height,t.depth),T)if(o.layerUpdates.size>0){let i=sp(t.width,t.height,o.format,o.type);for(let a of o.layerUpdates){let o=t.data.subarray(a*i/t.data.BYTES_PER_ELEMENT,(a+1)*i/t.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,a,t.width,t.height,1,r,p,o)}o.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,m,t.width,t.height,t.depth,0,r,p,t.data);else if(o.isData3DTexture)C?(w&&n.texStorage3D(e.TEXTURE_3D,E,m,t.width,t.height,t.depth),T&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)):n.texImage3D(e.TEXTURE_3D,0,m,t.width,t.height,t.depth,0,r,p,t.data);else if(o.isFramebufferTexture){if(w)if(C)n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height);else{let i=t.width,a=t.height;for(let t=0;t<E;t++)n.texImage2D(e.TEXTURE_2D,t,m,i,a,0,r,p,null),i>>=1,a>>=1}}else if(o.isHTMLTexture){if(`texElementImage2D`in e){let n=e.canvas;if(n.hasAttribute(`layoutsubtree`)||n.setAttribute(`layoutsubtree`,`true`),t.parentNode!==n){n.appendChild(t),d.add(o),n.onpaint=e=>{let t=e.changedElements;for(let e of d)t.includes(e.image)&&(e.needsUpdate=!0)},n.requestPaint();return}let r=e.RGBA,i=e.RGBA,a=e.UNSIGNED_BYTE;e.texElementImage2D(e.TEXTURE_2D,0,r,i,a,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}}else if(y.length>0){if(C&&w){let t=F(y[0]);n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height)}for(let t=0,i=y.length;t<i;t++)h=y[t],C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,r,p,h):n.texImage2D(e.TEXTURE_2D,t,m,r,p,h);o.generateMipmaps=!1}else if(C){if(w){let r=F(t);n.texStorage2D(e.TEXTURE_2D,E,m,r.width,r.height)}T&&n.texSubImage2D(e.TEXTURE_2D,0,0,0,r,p,t)}else n.texImage2D(e.TEXTURE_2D,0,m,r,p,t);_(o)&&v(c),f.__version=u.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function pe(t,o,s){if(o.image.length!==6)return;let c=ue(t,o),l=o.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+s);let u=r.get(l);if(l.version!==u.__version||c===!0){n.activeTexture(e.TEXTURE0+s);let t=Ls.getPrimaries(Ls.workingColorSpace),r=o.colorSpace===``?null:Ls.getPrimaries(o.colorSpace),d=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let f=o.isCompressedTexture||o.image[0].isCompressedTexture,p=o.image[0]&&o.image[0].isDataTexture,m=[];for(let e=0;e<6;e++)!f&&!p?m[e]=g(o.image[e],!0,i.maxCubemapSize):m[e]=p?o.image[e].image:o.image[e],m[e]=Te(o,m[e]);let h=m[0],y=a.convert(o.format,o.colorSpace),x=a.convert(o.type),C=b(o.internalFormat,y,x,o.normalized,o.colorSpace),w=o.isVideoTexture!==!0,T=u.__version===void 0||c===!0,E=l.dataReady,D=S(o,h);le(e.TEXTURE_CUBE_MAP,o);let O;if(f){w&&T&&n.texStorage2D(e.TEXTURE_CUBE_MAP,D,C,h.width,h.height);for(let t=0;t<6;t++){O=m[t].mipmaps;for(let r=0;r<O.length;r++){let i=O[r];o.format===1023?w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,C,i.width,i.height,0,y,x,i.data):y===null?B(`WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()`):w?E&&n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,i.data):n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,C,i.width,i.height,0,i.data)}}}else{if(O=o.mipmaps,w&&T){O.length>0&&D++;let t=F(m[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,D,C,t.width,t.height)}for(let t=0;t<6;t++)if(p){w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,m[t].width,m[t].height,y,x,m[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,m[t].width,m[t].height,0,y,x,m[t].data);for(let r=0;r<O.length;r++){let i=O[r].image[t].image;w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,C,i.width,i.height,0,y,x,i.data)}}else{w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,y,x,m[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,y,x,m[t]);for(let r=0;r<O.length;r++){let i=O[r];w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,y,x,i.image[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,C,y,x,i.image[t])}}}_(o)&&v(e.TEXTURE_CUBE_MAP),u.__version=l.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function me(t,i,o,c,l,u){let d=a.convert(o.format,o.colorSpace),f=a.convert(o.type),p=b(o.internalFormat,d,f,o.normalized,o.colorSpace),m=r.get(i),h=r.get(o);if(h.__renderTarget=i,!m.__hasExternalTextures){let t=Math.max(1,i.width>>u),r=Math.max(1,i.height>>u);l===e.TEXTURE_3D||l===e.TEXTURE_2D_ARRAY?n.texImage3D(l,u,p,t,r,i.depth,0,d,f,null):n.texImage2D(l,u,p,t,r,0,d,f,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),we(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,c,l,h.__webglTexture,0,Ce(i)):(l===e.TEXTURE_2D||l>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&l<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,c,l,h.__webglTexture,u),n.bindFramebuffer(e.FRAMEBUFFER,null)}function he(t,n,r){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){let i=n.depthTexture,a=i&&i.isDepthTexture?i.type:null,o=x(n.stencilBuffer,a),c=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;we(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Ce(n),o,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,Ce(n),o,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,o,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,c,e.RENDERBUFFER,t)}else{let t=n.textures;for(let i=0;i<t.length;i++){let o=t[i],c=a.convert(o.format,o.colorSpace),l=a.convert(o.type),u=b(o.internalFormat,c,l,o.normalized,o.colorSpace);we(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Ce(n),u,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,Ce(n),u,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,u,n.width,n.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function ge(t,i,o){let c=i.isWebGLCubeRenderTarget===!0;if(n.bindFramebuffer(e.FRAMEBUFFER,t),!(i.depthTexture&&i.depthTexture.isDepthTexture))throw Error(`renderTarget.depthTexture must be an instance of THREE.DepthTexture`);let l=r.get(i.depthTexture);if(l.__renderTarget=i,(!l.__webglTexture||i.depthTexture.image.width!==i.width||i.depthTexture.image.height!==i.height)&&(i.depthTexture.image.width=i.width,i.depthTexture.image.height=i.height,i.depthTexture.needsUpdate=!0),c){if(l.__webglInit===void 0&&(l.__webglInit=!0,i.depthTexture.addEventListener(`dispose`,C)),l.__webglTexture===void 0){l.__webglTexture=e.createTexture(),n.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),le(e.TEXTURE_CUBE_MAP,i.depthTexture);let t=a.convert(i.depthTexture.format),r=a.convert(i.depthTexture.type),o;i.depthTexture.format===1026?o=e.DEPTH_COMPONENT24:i.depthTexture.format===1027&&(o=e.DEPTH24_STENCIL8);for(let n=0;n<6;n++)e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,o,i.width,i.height,0,t,r,null)}}else re(i.depthTexture,0);let u=l.__webglTexture,d=Ce(i),f=c?e.TEXTURE_CUBE_MAP_POSITIVE_X+o:e.TEXTURE_2D,p=i.depthTexture.format===1027?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(i.depthTexture.format===1026)we(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else if(i.depthTexture.format===1027)we(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else throw Error(`Unknown depthTexture format`)}function _e(t){let i=r.get(t),a=t.isWebGLCubeRenderTarget===!0;if(i.__boundDepthTexture!==t.depthTexture){let e=t.depthTexture;if(i.__depthDisposeCallback&&i.__depthDisposeCallback(),e){let t=()=>{delete i.__boundDepthTexture,delete i.__depthDisposeCallback,e.removeEventListener(`dispose`,t)};e.addEventListener(`dispose`,t),i.__depthDisposeCallback=t}i.__boundDepthTexture=e}if(t.depthTexture&&!i.__autoAllocateDepthBuffer)if(a)for(let e=0;e<6;e++)ge(i.__webglFramebuffer[e],t,e);else{let e=t.texture.mipmaps;e&&e.length>0?ge(i.__webglFramebuffer[0],t,0):ge(i.__webglFramebuffer,t,0)}else if(a){i.__webglDepthbuffer=[];for(let r=0;r<6;r++)if(n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[r]),i.__webglDepthbuffer[r]===void 0)i.__webglDepthbuffer[r]=e.createRenderbuffer(),he(i.__webglDepthbuffer[r],t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,a=i.__webglDepthbuffer[r];e.bindRenderbuffer(e.RENDERBUFFER,a),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,a)}}else{let r=t.texture.mipmaps;if(r&&r.length>0?n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[0]):n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer),i.__webglDepthbuffer===void 0)i.__webglDepthbuffer=e.createRenderbuffer(),he(i.__webglDepthbuffer,t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,r=i.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,r)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}function ve(t,n,i){let a=r.get(t);n!==void 0&&me(a.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),i!==void 0&&_e(t)}function ye(t){let i=t.texture,s=r.get(t),c=r.get(i);t.addEventListener(`dispose`,w);let l=t.textures,u=t.isWebGLCubeRenderTarget===!0,d=l.length>1;if(d||(c.__webglTexture===void 0&&(c.__webglTexture=e.createTexture()),c.__version=i.version,o.memory.textures++),u){s.__webglFramebuffer=[];for(let t=0;t<6;t++)if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer[t]=[];for(let n=0;n<i.mipmaps.length;n++)s.__webglFramebuffer[t][n]=e.createFramebuffer()}else s.__webglFramebuffer[t]=e.createFramebuffer()}else{if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer=[];for(let t=0;t<i.mipmaps.length;t++)s.__webglFramebuffer[t]=e.createFramebuffer()}else s.__webglFramebuffer=e.createFramebuffer();if(d)for(let t=0,n=l.length;t<n;t++){let n=r.get(l[t]);n.__webglTexture===void 0&&(n.__webglTexture=e.createTexture(),o.memory.textures++)}if(t.samples>0&&we(t)===!1){s.__webglMultisampledFramebuffer=e.createFramebuffer(),s.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,s.__webglMultisampledFramebuffer);for(let n=0;n<l.length;n++){let r=l[n];s.__webglColorRenderbuffer[n]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,s.__webglColorRenderbuffer[n]);let i=a.convert(r.format,r.colorSpace),o=a.convert(r.type),c=b(r.internalFormat,i,o,r.normalized,r.colorSpace,t.isXRRenderTarget===!0),u=Ce(t);e.renderbufferStorageMultisample(e.RENDERBUFFER,u,c,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+n,e.RENDERBUFFER,s.__webglColorRenderbuffer[n])}e.bindRenderbuffer(e.RENDERBUFFER,null),t.depthBuffer&&(s.__webglDepthRenderbuffer=e.createRenderbuffer(),he(s.__webglDepthRenderbuffer,t,!0)),n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(u){n.bindTexture(e.TEXTURE_CUBE_MAP,c.__webglTexture),le(e.TEXTURE_CUBE_MAP,i);for(let n=0;n<6;n++)if(i.mipmaps&&i.mipmaps.length>0)for(let r=0;r<i.mipmaps.length;r++)me(s.__webglFramebuffer[n][r],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,r);else me(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0);_(i)&&v(e.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(d){for(let i=0,a=l.length;i<a;i++){let a=l[i],o=r.get(a),c=e.TEXTURE_2D;(t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(c=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(c,o.__webglTexture),le(c,a),me(s.__webglFramebuffer,t,a,e.COLOR_ATTACHMENT0+i,c,0),_(a)&&v(c)}n.unbindTexture()}else{let r=e.TEXTURE_2D;if((t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(r=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(r,c.__webglTexture),le(r,i),i.mipmaps&&i.mipmaps.length>0)for(let n=0;n<i.mipmaps.length;n++)me(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,r,n);else me(s.__webglFramebuffer,t,i,e.COLOR_ATTACHMENT0,r,0);_(i)&&v(r),n.unbindTexture()}t.depthBuffer&&_e(t)}function be(e){let t=e.textures;for(let i=0,a=t.length;i<a;i++){let a=t[i];if(_(a)){let t=y(e),i=r.get(a).__webglTexture;n.bindTexture(t,i),v(t),n.unbindTexture()}}}let xe=[],N=[];function Se(t){if(t.samples>0){if(we(t)===!1){let i=t.textures,a=t.width,o=t.height,s=e.COLOR_BUFFER_BIT,l=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,u=r.get(t),d=i.length>1;if(d)for(let t=0;t<i.length;t++)n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,u.__webglMultisampledFramebuffer);let f=t.texture.mipmaps;f&&f.length>0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer);for(let n=0;n<i.length;n++){if(t.resolveDepthBuffer&&(t.depthBuffer&&(s|=e.DEPTH_BUFFER_BIT),t.stencilBuffer&&t.resolveStencilBuffer&&(s|=e.STENCIL_BUFFER_BIT)),d){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,u.__webglColorRenderbuffer[n]);let t=r.get(i[n]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,a,o,0,0,a,o,s,e.NEAREST),c===!0&&(xe.length=0,N.length=0,xe.push(e.COLOR_ATTACHMENT0+n),t.depthBuffer&&t.resolveDepthBuffer===!1&&(xe.push(l),N.push(l),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,N)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,xe))}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),d)for(let t=0;t<i.length;t++){n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,u.__webglColorRenderbuffer[t]);let a=r.get(i[t]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,a,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglMultisampledFramebuffer)}else if(t.depthBuffer&&t.resolveDepthBuffer===!1&&c){let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[n])}}}function Ce(e){return Math.min(i.maxSamples,e.samples)}function we(e){let n=r.get(e);return e.samples>0&&t.has(`WEBGL_multisampled_render_to_texture`)===!0&&n.__useRenderToTexture!==!1}function P(e){let t=o.render.frame;u.get(e)!==t&&(u.set(e,t),e.update())}function Te(e,t){let n=e.colorSpace,r=e.format,i=e.type;return e.isCompressedTexture===!0||e.isVideoTexture===!0||n!==`srgb-linear`&&n!==``&&(Ls.getTransfer(n)===`srgb`?(r!==1023||i!==1009)&&B(`WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.`):V(`WebGLTextures: Unsupported texture color space:`,n)),t}function F(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement?(l.width=e.naturalWidth||e.width,l.height=e.naturalHeight||e.height):typeof VideoFrame<`u`&&e instanceof VideoFrame?(l.width=e.displayWidth,l.height=e.displayHeight):(l.width=e.width,l.height=e.height),l}this.allocateTextureUnit=te,this.resetTextureUnits=k,this.getTextureUnits=A,this.setTextureUnits=ee,this.setTexture2D=re,this.setTexture2DArray=ie,this.setTexture3D=ae,this.setTextureCube=j,this.rebindTextures=ve,this.setupRenderTarget=ye,this.updateRenderTargetMipmap=be,this.updateMultisampleRenderTarget=Se,this.setupDepthRenderbuffer=_e,this.setupFrameBufferTexture=me,this.useMultisampledRTT=we,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function fg(e,t){function n(n,r=``){let i,a=Ls.getTransfer(r);if(n===1009)return e.UNSIGNED_BYTE;if(n===1017)return e.UNSIGNED_SHORT_4_4_4_4;if(n===1018)return e.UNSIGNED_SHORT_5_5_5_1;if(n===35902)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===35899)return e.UNSIGNED_INT_10F_11F_11F_REV;if(n===1010)return e.BYTE;if(n===1011)return e.SHORT;if(n===1012)return e.UNSIGNED_SHORT;if(n===1013)return e.INT;if(n===1014)return e.UNSIGNED_INT;if(n===1015)return e.FLOAT;if(n===1016)return e.HALF_FLOAT;if(n===1021)return e.ALPHA;if(n===1022)return e.RGB;if(n===1023)return e.RGBA;if(n===1026)return e.DEPTH_COMPONENT;if(n===1027)return e.DEPTH_STENCIL;if(n===1028)return e.RED;if(n===1029)return e.RED_INTEGER;if(n===1030)return e.RG;if(n===1031)return e.RG_INTEGER;if(n===1033)return e.RGBA_INTEGER;if(n===33776||n===33777||n===33778||n===33779)if(a===`srgb`)if(i=t.get(`WEBGL_compressed_texture_s3tc_srgb`),i!==null){if(n===33776)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(i=t.get(`WEBGL_compressed_texture_s3tc`),i!==null){if(n===33776)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===35840||n===35841||n===35842||n===35843)if(i=t.get(`WEBGL_compressed_texture_pvrtc`),i!==null){if(n===35840)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===35841)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===35842)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===35843)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===36196||n===37492||n===37496||n===37488||n===37489||n===37490||n===37491)if(i=t.get(`WEBGL_compressed_texture_etc`),i!==null){if(n===36196||n===37492)return a===`srgb`?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(n===37496)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC;if(n===37488)return i.COMPRESSED_R11_EAC;if(n===37489)return i.COMPRESSED_SIGNED_R11_EAC;if(n===37490)return i.COMPRESSED_RG11_EAC;if(n===37491)return i.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===37808||n===37809||n===37810||n===37811||n===37812||n===37813||n===37814||n===37815||n===37816||n===37817||n===37818||n===37819||n===37820||n===37821)if(i=t.get(`WEBGL_compressed_texture_astc`),i!==null){if(n===37808)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===37809)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===37810)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===37811)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===37812)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===37813)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===37814)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===37815)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===37816)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===37817)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===37818)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===37819)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===37820)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===37821)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===36492||n===36494||n===36495)if(i=t.get(`EXT_texture_compression_bptc`),i!==null){if(n===36492)return a===`srgb`?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===36494)return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===36495)return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===36283||n===36284||n===36285||n===36286)if(i=t.get(`EXT_texture_compression_rgtc`),i!==null){if(n===36283)return i.COMPRESSED_RED_RGTC1_EXT;if(n===36284)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===36285)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===36286)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===1020?e.UNSIGNED_INT_24_8:e[n]===void 0?null:e[n]}return{convert:n}}var pg=`
|
|
4082
|
+
}`,ag=[new W(1,0,0),new W(-1,0,0),new W(0,1,0),new W(0,-1,0),new W(0,0,1),new W(0,0,-1)],og=[new W(0,-1,0),new W(0,-1,0),new W(0,0,1),new W(0,0,-1),new W(0,-1,0),new W(0,-1,0)],sg=new K,cg=new W,lg=new W;function ug(e,t,n){let r=new Ru,i=new H,a=new H,o=new Js,s=new jd,c=new Md,l={},u=n.maxTextureSize,d={0:1,1:0,2:2},f=new Dd({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new H},radius:{value:4}},vertexShader:rg,fragmentShader:ig}),p=f.clone();p.defines.HORIZONTAL_PASS=1;let m=new Y;m.setAttribute(`position`,new J(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let h=new iu(m,f),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let _=this.type;this.render=function(t,n,s){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||t.length===0)return;this.type===2&&(B(`WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead.`),this.type=1);let c=e.getRenderTarget(),l=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),f=e.state;f.setBlending(0),f.buffers.depth.getReversed()===!0?f.buffers.color.setClear(0,0,0,0):f.buffers.color.setClear(1,1,1,1),f.buffers.depth.setTest(!0),f.setScissorTest(!1);let p=_!==this.type;p&&n.traverse(function(e){e.material&&(Array.isArray(e.material)?e.material.forEach(e=>e.needsUpdate=!0):e.material.needsUpdate=!0)});for(let c=0,l=t.length;c<l;c++){let l=t[c],d=l.shadow;if(d===void 0){B(`WebGLShadowMap:`,l,`has no shadow.`);continue}if(d.autoUpdate===!1&&d.needsUpdate===!1)continue;i.copy(d.mapSize);let m=d.getFrameExtents();i.multiply(m),a.copy(d.mapSize),(i.x>u||i.y>u)&&(i.x>u&&(a.x=Math.floor(u/m.x),i.x=a.x*m.x,d.mapSize.x=a.x),i.y>u&&(a.y=Math.floor(u/m.y),i.y=a.y*m.y,d.mapSize.y=a.y));let h=e.state.buffers.depth.getReversed();if(d.camera._reversedDepth=h,d.map===null||p===!0){if(d.map!==null&&(d.map.depthTexture!==null&&(d.map.depthTexture.dispose(),d.map.depthTexture=null),d.map.dispose()),this.type===3){if(l.isPointLight){B(`WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.`);continue}d.map=new Xs(i.x,i.y,{format:Ra,type:Ta,minFilter:ha,magFilter:ha,generateMipmaps:!1}),d.map.texture.name=l.name+`.shadowMap`,d.map.depthTexture=new cd(i.x,i.y,wa),d.map.depthTexture.name=l.name+`.shadowMapDepth`,d.map.depthTexture.format=Pa,d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=fa,d.map.depthTexture.magFilter=fa}else l.isPointLight?(d.map=new Vp(i.x),d.map.depthTexture=new ld(i.x,Ca)):(d.map=new Xs(i.x,i.y),d.map.depthTexture=new cd(i.x,i.y,Ca)),d.map.depthTexture.name=l.name+`.shadowMap`,d.map.depthTexture.format=Pa,this.type===1?(d.map.depthTexture.compareFunction=h?518:515,d.map.depthTexture.minFilter=ha,d.map.depthTexture.magFilter=ha):(d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=fa,d.map.depthTexture.magFilter=fa);d.camera.updateProjectionMatrix()}let g=d.map.isWebGLCubeRenderTarget?6:1;for(let t=0;t<g;t++){if(d.map.isWebGLCubeRenderTarget)e.setRenderTarget(d.map,t),e.clear();else{t===0&&(e.setRenderTarget(d.map),e.clear());let n=d.getViewport(t);o.set(a.x*n.x,a.y*n.y,a.x*n.z,a.y*n.w),f.viewport(o)}if(l.isPointLight){let e=d.camera,n=d.matrix,r=l.distance||e.far;r!==e.far&&(e.far=r,e.updateProjectionMatrix()),cg.setFromMatrixPosition(l.matrixWorld),e.position.copy(cg),lg.copy(e.position),lg.add(ag[t]),e.up.copy(og[t]),e.lookAt(lg),e.updateMatrixWorld(),n.makeTranslation(-cg.x,-cg.y,-cg.z),sg.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),d._frustum.setFromProjectionMatrix(sg,e.coordinateSystem,e.reversedDepth)}else d.updateMatrices(l);r=d.getFrustum(),b(n,s,d.camera,l,this.type)}d.isPointLightShadow!==!0&&this.type===3&&v(d,s),d.needsUpdate=!1}_=this.type,g.needsUpdate=!1,e.setRenderTarget(c,l,d)};function v(n,r){let a=t.update(h);f.defines.VSM_SAMPLES!==n.blurSamples&&(f.defines.VSM_SAMPLES=n.blurSamples,p.defines.VSM_SAMPLES=n.blurSamples,f.needsUpdate=!0,p.needsUpdate=!0),n.mapPass===null&&(n.mapPass=new Xs(i.x,i.y,{format:Ra,type:Ta})),f.uniforms.shadow_pass.value=n.map.depthTexture,f.uniforms.resolution.value=n.mapSize,f.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(r,null,a,f,h,null),p.uniforms.shadow_pass.value=n.mapPass.texture,p.uniforms.resolution.value=n.mapSize,p.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(r,null,a,p,h,null)}function y(t,n,r,i){let a=null,o=r.isPointLight===!0?t.customDistanceMaterial:t.customDepthMaterial;if(o!==void 0)a=o;else if(a=r.isPointLight===!0?c:s,e.localClippingEnabled&&n.clipShadows===!0&&Array.isArray(n.clippingPlanes)&&n.clippingPlanes.length!==0||n.displacementMap&&n.displacementScale!==0||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||n.alphaToCoverage===!0){let e=a.uuid,t=n.uuid,r=l[e];r===void 0&&(r={},l[e]=r);let i=r[t];i===void 0&&(i=a.clone(),r[t]=i,n.addEventListener(`dispose`,x)),a=i}if(a.visible=n.visible,a.wireframe=n.wireframe,i===3?a.side=n.shadowSide===null?n.side:n.shadowSide:a.side=n.shadowSide===null?d[n.side]:n.shadowSide,a.alphaMap=n.alphaMap,a.alphaTest=n.alphaToCoverage===!0?.5:n.alphaTest,a.map=n.map,a.clipShadows=n.clipShadows,a.clippingPlanes=n.clippingPlanes,a.clipIntersection=n.clipIntersection,a.displacementMap=n.displacementMap,a.displacementScale=n.displacementScale,a.displacementBias=n.displacementBias,a.wireframeLinewidth=n.wireframeLinewidth,a.linewidth=n.linewidth,r.isPointLight===!0&&a.isMeshDistanceMaterial===!0){let t=e.properties.get(a);t.light=r}return a}function b(n,i,a,o,s){if(n.visible===!1)return;if(n.layers.test(i.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&s===3)&&(!n.frustumCulled||r.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,n.matrixWorld);let r=t.update(n),c=n.material;if(Array.isArray(c)){let t=r.groups;for(let l=0,u=t.length;l<u;l++){let u=t[l],d=c[u.materialIndex];if(d&&d.visible){let t=y(n,d,o,s);n.onBeforeShadow(e,n,i,a,r,t,u),e.renderBufferDirect(a,null,r,t,n,u),n.onAfterShadow(e,n,i,a,r,t,u)}}}else if(c.visible){let t=y(n,c,o,s);n.onBeforeShadow(e,n,i,a,r,t,null),e.renderBufferDirect(a,null,r,t,n,null),n.onAfterShadow(e,n,i,a,r,t,null)}}let c=n.children;for(let e=0,t=c.length;e<t;e++)b(c[e],i,a,o,s)}function x(e){e.target.removeEventListener(`dispose`,x);for(let t in l){let n=l[t],r=e.target.uuid;r in n&&(n[r].dispose(),delete n[r])}}}function dg(e,t){function n(){let t=!1,n=new Js,r=null,i=new Js(0,0,0,0);return{setMask:function(n){r!==n&&!t&&(e.colorMask(n,n,n,n),r=n)},setLocked:function(e){t=e},setClear:function(t,r,a,o,s){s===!0&&(t*=o,r*=o,a*=o),n.set(t,r,a,o),i.equals(n)===!1&&(e.clearColor(t,r,a,o),i.copy(n))},reset:function(){t=!1,r=null,i.set(-1,0,0,0)}}}function r(){let n=!1,r=!1,i=null,a=null,o=null;return{setReversed:function(e){if(r!==e){let n=t.get(`EXT_clip_control`);e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),r=e;let i=o;o=null,this.setClear(i)}},getReversed:function(){return r},setTest:function(t){t?de(e.DEPTH_TEST):fe(e.DEPTH_TEST)},setMask:function(t){i!==t&&!n&&(e.depthMask(t),i=t)},setFunc:function(t){if(r&&(t=ns[t]),a!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}a=t}},setLocked:function(e){n=e},setClear:function(t){o!==t&&(o=t,r&&(t=1-t),e.clearDepth(t))},reset:function(){n=!1,i=null,a=null,o=null,r=!1}}}function i(){let t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null;return{setTest:function(n){t||(n?de(e.STENCIL_TEST):fe(e.STENCIL_TEST))},setMask:function(r){n!==r&&!t&&(e.stencilMask(r),n=r)},setFunc:function(t,n,o){(r!==t||i!==n||a!==o)&&(e.stencilFunc(t,n,o),r=t,i=n,a=o)},setOp:function(t,n,r){(o!==t||s!==n||c!==r)&&(e.stencilOp(t,n,r),o=t,s=n,c=r)},setLocked:function(e){t=e},setClear:function(t){l!==t&&(e.clearStencil(t),l=t)},reset:function(){t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null}}}let a=new n,o=new r,s=new i,c=new WeakMap,l=new WeakMap,u={},d={},f={},p=new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new q(0,0,0),T=0,E=!1,D=null,O=null,k=null,A=null,ee=null,te=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),ne=!1,re=0,ie=e.getParameter(e.VERSION);ie.indexOf(`WebGL`)===-1?ie.indexOf(`OpenGL ES`)!==-1&&(re=parseFloat(/^OpenGL ES (\d)/.exec(ie)[1]),ne=re>=2):(re=parseFloat(/^WebGL (\d)/.exec(ie)[1]),ne=re>=1);let ae=null,j={},oe=e.getParameter(e.SCISSOR_BOX),se=e.getParameter(e.VIEWPORT),ce=new Js().fromArray(oe),le=new Js().fromArray(se);function ue(t,n,r,i){let a=new Uint8Array(4),o=e.createTexture();e.bindTexture(t,o),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;o<r;o++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(n,0,e.RGBA,1,1,i,0,e.RGBA,e.UNSIGNED_BYTE,a):e.texImage2D(n+o,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,a);return o}let M={};M[e.TEXTURE_2D]=ue(e.TEXTURE_2D,e.TEXTURE_2D,1),M[e.TEXTURE_CUBE_MAP]=ue(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),M[e.TEXTURE_2D_ARRAY]=ue(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),M[e.TEXTURE_3D]=ue(e.TEXTURE_3D,e.TEXTURE_3D,1,1),a.setClear(0,0,0,1),o.setClear(1),s.setClear(0),de(e.DEPTH_TEST),o.setFunc(3),be(!1),xe(1),de(e.CULL_FACE),ve(0);function de(t){u[t]!==!0&&(e.enable(t),u[t]=!0)}function fe(t){u[t]!==!1&&(e.disable(t),u[t]=!1)}function pe(t,n){return f[t]===n?!1:(e.bindFramebuffer(t,n),f[t]=n,t===e.DRAW_FRAMEBUFFER&&(f[e.FRAMEBUFFER]=n),t===e.FRAMEBUFFER&&(f[e.DRAW_FRAMEBUFFER]=n),!0)}function me(t,n){let r=m,i=!1;if(t){r=p.get(n),r===void 0&&(r=[],p.set(n,r));let a=t.textures;if(r.length!==a.length||r[0]!==e.COLOR_ATTACHMENT0){for(let t=0,n=a.length;t<n;t++)r[t]=e.COLOR_ATTACHMENT0+t;r.length=a.length,i=!0}}else r[0]!==e.BACK&&(r[0]=e.BACK,i=!0);i&&e.drawBuffers(r)}function he(t){return h===t?!1:(e.useProgram(t),h=t,!0)}let ge={100:e.FUNC_ADD,101:e.FUNC_SUBTRACT,102:e.FUNC_REVERSE_SUBTRACT};ge[103]=e.MIN,ge[104]=e.MAX;let _e={200:e.ZERO,201:e.ONE,202:e.SRC_COLOR,204:e.SRC_ALPHA,210:e.SRC_ALPHA_SATURATE,208:e.DST_COLOR,206:e.DST_ALPHA,203:e.ONE_MINUS_SRC_COLOR,205:e.ONE_MINUS_SRC_ALPHA,209:e.ONE_MINUS_DST_COLOR,207:e.ONE_MINUS_DST_ALPHA,211:e.CONSTANT_COLOR,212:e.ONE_MINUS_CONSTANT_COLOR,213:e.CONSTANT_ALPHA,214:e.ONE_MINUS_CONSTANT_ALPHA};function ve(t,n,r,i,a,o,s,c,l,u){if(t===0){g===!0&&(fe(e.BLEND),g=!1);return}if(g===!1&&(de(e.BLEND),g=!0),t!==5){if(t!==_||u!==E){if((v!==100||x!==100)&&(e.blendEquation(e.FUNC_ADD),v=100,x=100),u)switch(t){case 1:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFunc(e.ONE,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:V(`WebGLState: Invalid blending: `,t);break}else switch(t){case 1:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case 3:V(`WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true`);break;case 4:V(`WebGLState: MultiplyBlending requires material.premultipliedAlpha = true`);break;default:V(`WebGLState: Invalid blending: `,t);break}y=null,b=null,S=null,C=null,w.set(0,0,0),T=0,_=t,E=u}return}a||=n,o||=r,s||=i,(n!==v||a!==x)&&(e.blendEquationSeparate(ge[n],ge[a]),v=n,x=a),(r!==y||i!==b||o!==S||s!==C)&&(e.blendFuncSeparate(_e[r],_e[i],_e[o],_e[s]),y=r,b=i,S=o,C=s),(c.equals(w)===!1||l!==T)&&(e.blendColor(c.r,c.g,c.b,l),w.copy(c),T=l),_=t,E=!1}function ye(t,n){t.side===2?fe(e.CULL_FACE):de(e.CULL_FACE);let r=t.side===1;n&&(r=!r),be(r),t.blending===1&&t.transparent===!1?ve(0):ve(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),o.setFunc(t.depthFunc),o.setTest(t.depthTest),o.setMask(t.depthWrite),a.setMask(t.colorWrite);let i=t.stencilWrite;s.setTest(i),i&&(s.setMask(t.stencilWriteMask),s.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),s.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),Se(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),t.alphaToCoverage===!0?de(e.SAMPLE_ALPHA_TO_COVERAGE):fe(e.SAMPLE_ALPHA_TO_COVERAGE)}function be(t){D!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),D=t)}function xe(t){t===0?fe(e.CULL_FACE):(de(e.CULL_FACE),t!==O&&(t===1?e.cullFace(e.BACK):t===2?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))),O=t}function N(t){t!==k&&(ne&&e.lineWidth(t),k=t)}function Se(t,n,r){t?(de(e.POLYGON_OFFSET_FILL),(A!==n||ee!==r)&&(A=n,ee=r,o.getReversed()&&(n=-n),e.polygonOffset(n,r))):fe(e.POLYGON_OFFSET_FILL)}function Ce(t){t?de(e.SCISSOR_TEST):fe(e.SCISSOR_TEST)}function we(t){t===void 0&&(t=e.TEXTURE0+te-1),ae!==t&&(e.activeTexture(t),ae=t)}function P(t,n,r){r===void 0&&(r=ae===null?e.TEXTURE0+te-1:ae);let i=j[r];i===void 0&&(i={type:void 0,texture:void 0},j[r]=i),(i.type!==t||i.texture!==n)&&(ae!==r&&(e.activeTexture(r),ae=r),e.bindTexture(t,n||M[t]),i.type=t,i.texture=n)}function Te(){let t=j[ae];t!==void 0&&t.type!==void 0&&(e.bindTexture(t.type,null),t.type=void 0,t.texture=void 0)}function F(){try{e.compressedTexImage2D(...arguments)}catch(e){V(`WebGLState:`,e)}}function I(){try{e.compressedTexImage3D(...arguments)}catch(e){V(`WebGLState:`,e)}}function L(){try{e.texSubImage2D(...arguments)}catch(e){V(`WebGLState:`,e)}}function Ee(){try{e.texSubImage3D(...arguments)}catch(e){V(`WebGLState:`,e)}}function De(){try{e.compressedTexSubImage2D(...arguments)}catch(e){V(`WebGLState:`,e)}}function Oe(){try{e.compressedTexSubImage3D(...arguments)}catch(e){V(`WebGLState:`,e)}}function ke(){try{e.texStorage2D(...arguments)}catch(e){V(`WebGLState:`,e)}}function Ae(){try{e.texStorage3D(...arguments)}catch(e){V(`WebGLState:`,e)}}function je(){try{e.texImage2D(...arguments)}catch(e){V(`WebGLState:`,e)}}function Me(){try{e.texImage3D(...arguments)}catch(e){V(`WebGLState:`,e)}}function Ne(t){return d[t]===void 0?e.getParameter(t):d[t]}function Pe(t,n){d[t]!==n&&(e.pixelStorei(t,n),d[t]=n)}function Fe(t){ce.equals(t)===!1&&(e.scissor(t.x,t.y,t.z,t.w),ce.copy(t))}function Ie(t){le.equals(t)===!1&&(e.viewport(t.x,t.y,t.z,t.w),le.copy(t))}function Le(t,n){let r=l.get(n);r===void 0&&(r=new WeakMap,l.set(n,r));let i=r.get(t);i===void 0&&(i=e.getUniformBlockIndex(n,t.name),r.set(t,i))}function Re(t,n){let r=l.get(n).get(t);c.get(n)!==r&&(e.uniformBlockBinding(n,r,t.__bindingPointIndex),c.set(n,r))}function ze(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),o.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),u={},d={},ae=null,j={},f={},p=new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new q(0,0,0),T=0,E=!1,D=null,O=null,k=null,A=null,ee=null,ce.set(0,0,e.canvas.width,e.canvas.height),le.set(0,0,e.canvas.width,e.canvas.height),a.reset(),o.reset(),s.reset()}return{buffers:{color:a,depth:o,stencil:s},enable:de,disable:fe,bindFramebuffer:pe,drawBuffers:me,useProgram:he,setBlending:ve,setMaterial:ye,setFlipSided:be,setCullFace:xe,setLineWidth:N,setPolygonOffset:Se,setScissorTest:Ce,activeTexture:we,bindTexture:P,unbindTexture:Te,compressedTexImage2D:F,compressedTexImage3D:I,texImage2D:je,texImage3D:Me,pixelStorei:Pe,getParameter:Ne,updateUBOMapping:Le,uniformBlockBinding:Re,texStorage2D:ke,texStorage3D:Ae,texSubImage2D:L,texSubImage3D:Ee,compressedTexSubImage2D:De,compressedTexSubImage3D:Oe,scissor:Fe,viewport:Ie,reset:ze}}function fg(e,t,n,r,i,a,o){let s=t.has(`WEBGL_multisampled_render_to_texture`)?t.get(`WEBGL_multisampled_render_to_texture`):null,c=typeof navigator>`u`?!1:/OculusBrowser/g.test(navigator.userAgent),l=new H,u=new WeakMap,d=new Set,f,p=new WeakMap,m=!1;try{m=typeof OffscreenCanvas<`u`&&new OffscreenCanvas(1,1).getContext(`2d`)!==null}catch{}function h(e,t){return m?new OffscreenCanvas(e,t):Jo(`canvas`)}function g(e,t,n){let r=1,i=F(e);if((i.width>n||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1)if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof VideoFrame<`u`&&e instanceof VideoFrame){let n=Math.floor(r*i.width),a=Math.floor(r*i.height);f===void 0&&(f=h(n,a));let o=t?h(n,a):f;return o.width=n,o.height=a,o.getContext(`2d`).drawImage(e,0,0,n,a),B(`WebGLRenderer: Texture has been resized from (`+i.width+`x`+i.height+`) to (`+n+`x`+a+`).`),o}else return`data`in e&&B(`WebGLRenderer: Image in DataTexture is too big (`+i.width+`x`+i.height+`).`),e;return e}function _(e){return e.generateMipmaps}function v(t){e.generateMipmap(t)}function y(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function b(n,r,i,a,o,s=!1){if(n!==null){if(e[n]!==void 0)return e[n];B(`WebGLRenderer: Attempt to use non-existing WebGL internal format '`+n+`'`)}let c;a&&(c=t.get(`EXT_texture_norm16`),c||B(`WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension`));let l=r;if(r===e.RED&&(i===e.FLOAT&&(l=e.R32F),i===e.HALF_FLOAT&&(l=e.R16F),i===e.UNSIGNED_BYTE&&(l=e.R8),i===e.UNSIGNED_SHORT&&c&&(l=c.R16_EXT),i===e.SHORT&&c&&(l=c.R16_SNORM_EXT)),r===e.RED_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.R8UI),i===e.UNSIGNED_SHORT&&(l=e.R16UI),i===e.UNSIGNED_INT&&(l=e.R32UI),i===e.BYTE&&(l=e.R8I),i===e.SHORT&&(l=e.R16I),i===e.INT&&(l=e.R32I)),r===e.RG&&(i===e.FLOAT&&(l=e.RG32F),i===e.HALF_FLOAT&&(l=e.RG16F),i===e.UNSIGNED_BYTE&&(l=e.RG8),i===e.UNSIGNED_SHORT&&c&&(l=c.RG16_EXT),i===e.SHORT&&c&&(l=c.RG16_SNORM_EXT)),r===e.RG_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RG8UI),i===e.UNSIGNED_SHORT&&(l=e.RG16UI),i===e.UNSIGNED_INT&&(l=e.RG32UI),i===e.BYTE&&(l=e.RG8I),i===e.SHORT&&(l=e.RG16I),i===e.INT&&(l=e.RG32I)),r===e.RGB_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGB8UI),i===e.UNSIGNED_SHORT&&(l=e.RGB16UI),i===e.UNSIGNED_INT&&(l=e.RGB32UI),i===e.BYTE&&(l=e.RGB8I),i===e.SHORT&&(l=e.RGB16I),i===e.INT&&(l=e.RGB32I)),r===e.RGBA_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGBA8UI),i===e.UNSIGNED_SHORT&&(l=e.RGBA16UI),i===e.UNSIGNED_INT&&(l=e.RGBA32UI),i===e.BYTE&&(l=e.RGBA8I),i===e.SHORT&&(l=e.RGBA16I),i===e.INT&&(l=e.RGBA32I)),r===e.RGB&&(i===e.UNSIGNED_SHORT&&c&&(l=c.RGB16_EXT),i===e.SHORT&&c&&(l=c.RGB16_SNORM_EXT),i===e.UNSIGNED_INT_5_9_9_9_REV&&(l=e.RGB9_E5),i===e.UNSIGNED_INT_10F_11F_11F_REV&&(l=e.R11F_G11F_B10F)),r===e.RGBA){let t=s?Bo:Ls.getTransfer(o);i===e.FLOAT&&(l=e.RGBA32F),i===e.HALF_FLOAT&&(l=e.RGBA16F),i===e.UNSIGNED_BYTE&&(l=t===`srgb`?e.SRGB8_ALPHA8:e.RGBA8),i===e.UNSIGNED_SHORT&&c&&(l=c.RGBA16_EXT),i===e.SHORT&&c&&(l=c.RGBA16_SNORM_EXT),i===e.UNSIGNED_SHORT_4_4_4_4&&(l=e.RGBA4),i===e.UNSIGNED_SHORT_5_5_5_1&&(l=e.RGB5_A1)}return(l===e.R16F||l===e.R32F||l===e.RG16F||l===e.RG32F||l===e.RGBA16F||l===e.RGBA32F)&&t.get(`EXT_color_buffer_float`),l}function x(t,n){let r;return t?n===null||n===1014||n===1020?r=e.DEPTH24_STENCIL8:n===1015?r=e.DEPTH32F_STENCIL8:n===1012&&(r=e.DEPTH24_STENCIL8,B(`DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.`)):n===null||n===1014||n===1020?r=e.DEPTH_COMPONENT24:n===1015?r=e.DEPTH_COMPONENT32F:n===1012&&(r=e.DEPTH_COMPONENT16),r}function S(e,t){return _(e)===!0||e.isFramebufferTexture&&e.minFilter!==1003&&e.minFilter!==1006?Math.log2(Math.max(t.width,t.height))+1:e.mipmaps!==void 0&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function C(e){let t=e.target;t.removeEventListener(`dispose`,C),T(t),t.isVideoTexture&&u.delete(t),t.isHTMLTexture&&d.delete(t)}function w(e){let t=e.target;t.removeEventListener(`dispose`,w),D(t)}function T(e){let t=r.get(e);if(t.__webglInit===void 0)return;let n=e.source,i=p.get(n);if(i){let r=i[t.__cacheKey];r.usedTimes--,r.usedTimes===0&&E(e),Object.keys(i).length===0&&p.delete(n)}r.remove(e)}function E(t){let n=r.get(t);e.deleteTexture(n.__webglTexture);let i=t.source,a=p.get(i);delete a[n.__cacheKey],o.memory.textures--}function D(t){let n=r.get(t);if(t.depthTexture&&(t.depthTexture.dispose(),r.remove(t.depthTexture)),t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let r=0;r<n.__webglFramebuffer[t].length;r++)e.deleteFramebuffer(n.__webglFramebuffer[t][r]);else e.deleteFramebuffer(n.__webglFramebuffer[t]);n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer[t])}else{if(Array.isArray(n.__webglFramebuffer))for(let t=0;t<n.__webglFramebuffer.length;t++)e.deleteFramebuffer(n.__webglFramebuffer[t]);else e.deleteFramebuffer(n.__webglFramebuffer);if(n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&e.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let t=0;t<n.__webglColorRenderbuffer.length;t++)n.__webglColorRenderbuffer[t]&&e.deleteRenderbuffer(n.__webglColorRenderbuffer[t]);n.__webglDepthRenderbuffer&&e.deleteRenderbuffer(n.__webglDepthRenderbuffer)}let i=t.textures;for(let t=0,n=i.length;t<n;t++){let n=r.get(i[t]);n.__webglTexture&&(e.deleteTexture(n.__webglTexture),o.memory.textures--),r.remove(i[t])}r.remove(t)}let O=0;function k(){O=0}function A(){return O}function ee(e){O=e}function te(){let e=O;return e>=i.maxTextures&&B(`WebGLTextures: Trying to use `+e+` texture units while this GPU supports only `+i.maxTextures),O+=1,e}function ne(e){let t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}function re(t,i){let a=r.get(t);if(t.isVideoTexture&&P(t),t.isRenderTargetTexture===!1&&t.isExternalTexture!==!0&&t.version>0&&a.__version!==t.version){let e=t.image;if(e===null)B(`WebGLRenderer: Texture marked for update but no image data found.`);else if(e.complete===!1)B(`WebGLRenderer: Texture marked for update but image is incomplete`);else{fe(a,t,i);return}}else t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D,a.__webglTexture,e.TEXTURE0+i)}function ie(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){fe(a,t,i);return}else t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D_ARRAY,a.__webglTexture,e.TEXTURE0+i)}function ae(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){fe(a,t,i);return}n.bindTexture(e.TEXTURE_3D,a.__webglTexture,e.TEXTURE0+i)}function j(t,i){let a=r.get(t);if(t.isCubeDepthTexture!==!0&&t.version>0&&a.__version!==t.version){pe(a,t,i);return}n.bindTexture(e.TEXTURE_CUBE_MAP,a.__webglTexture,e.TEXTURE0+i)}let oe={[la]:e.REPEAT,[ua]:e.CLAMP_TO_EDGE,[da]:e.MIRRORED_REPEAT},se={[fa]:e.NEAREST,[pa]:e.NEAREST_MIPMAP_NEAREST,[ma]:e.NEAREST_MIPMAP_LINEAR,[ha]:e.LINEAR,[ga]:e.LINEAR_MIPMAP_NEAREST,[_a]:e.LINEAR_MIPMAP_LINEAR},ce={512:e.NEVER,519:e.ALWAYS,513:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL};function le(n,a){if(a.type===1015&&t.has(`OES_texture_float_linear`)===!1&&(a.magFilter===1006||a.magFilter===1007||a.magFilter===1005||a.magFilter===1008||a.minFilter===1006||a.minFilter===1007||a.minFilter===1005||a.minFilter===1008)&&B(`WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.`),e.texParameteri(n,e.TEXTURE_WRAP_S,oe[a.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,oe[a.wrapT]),(n===e.TEXTURE_3D||n===e.TEXTURE_2D_ARRAY)&&e.texParameteri(n,e.TEXTURE_WRAP_R,oe[a.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,se[a.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,se[a.minFilter]),a.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,ce[a.compareFunction])),t.has(`EXT_texture_filter_anisotropic`)===!0){if(a.magFilter===1003||a.minFilter!==1005&&a.minFilter!==1008||a.type===1015&&t.has(`OES_texture_float_linear`)===!1)return;if(a.anisotropy>1||r.get(a).__currentAnisotropy){let o=t.get(`EXT_texture_filter_anisotropic`);e.texParameterf(n,o.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(a.anisotropy,i.getMaxAnisotropy())),r.get(a).__currentAnisotropy=a.anisotropy}}}function ue(t,n){let r=!1;t.__webglInit===void 0&&(t.__webglInit=!0,n.addEventListener(`dispose`,C));let i=n.source,a=p.get(i);a===void 0&&(a={},p.set(i,a));let s=ne(n);if(s!==t.__cacheKey){a[s]===void 0&&(a[s]={texture:e.createTexture(),usedTimes:0},o.memory.textures++,r=!0),a[s].usedTimes++;let i=a[t.__cacheKey];i!==void 0&&(a[t.__cacheKey].usedTimes--,i.usedTimes===0&&E(n)),t.__cacheKey=s,t.__webglTexture=a[s].texture}return r}function M(e,t,n){return Math.floor(Math.floor(e/n)/t)}function de(t,r,i,a){let o=t.updateRanges;if(o.length===0)n.texSubImage2D(e.TEXTURE_2D,0,0,0,r.width,r.height,i,a,r.data);else{o.sort((e,t)=>e.start-t.start);let s=0;for(let e=1;e<o.length;e++){let t=o[s],n=o[e],i=t.start+t.count,a=M(n.start,r.width,4),c=M(t.start,r.width,4);n.start<=i+1&&a===c&&M(n.start+n.count-1,r.width,4)===a?t.count=Math.max(t.count,n.start+n.count-t.start):(++s,o[s]=n)}o.length=s+1;let c=n.getParameter(e.UNPACK_ROW_LENGTH),l=n.getParameter(e.UNPACK_SKIP_PIXELS),u=n.getParameter(e.UNPACK_SKIP_ROWS);n.pixelStorei(e.UNPACK_ROW_LENGTH,r.width);for(let t=0,s=o.length;t<s;t++){let s=o[t],c=Math.floor(s.start/4),l=Math.ceil(s.count/4),u=c%r.width,d=Math.floor(c/r.width),f=l;n.pixelStorei(e.UNPACK_SKIP_PIXELS,u),n.pixelStorei(e.UNPACK_SKIP_ROWS,d),n.texSubImage2D(e.TEXTURE_2D,0,u,d,f,1,i,a,r.data)}t.clearUpdateRanges(),n.pixelStorei(e.UNPACK_ROW_LENGTH,c),n.pixelStorei(e.UNPACK_SKIP_PIXELS,l),n.pixelStorei(e.UNPACK_SKIP_ROWS,u)}}function fe(t,o,s){let c=e.TEXTURE_2D;(o.isDataArrayTexture||o.isCompressedArrayTexture)&&(c=e.TEXTURE_2D_ARRAY),o.isData3DTexture&&(c=e.TEXTURE_3D);let l=ue(t,o),u=o.source;n.bindTexture(c,t.__webglTexture,e.TEXTURE0+s);let f=r.get(u);if(u.version!==f.__version||l===!0){if(n.activeTexture(e.TEXTURE0+s),!(typeof ImageBitmap<`u`&&o.image instanceof ImageBitmap)){let t=Ls.getPrimaries(Ls.workingColorSpace),r=o.colorSpace===``?null:Ls.getPrimaries(o.colorSpace),i=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,i)}n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment);let t=g(o.image,!1,i.maxTextureSize);t=Te(o,t);let r=a.convert(o.format,o.colorSpace),p=a.convert(o.type),m=b(o.internalFormat,r,p,o.normalized,o.colorSpace,o.isVideoTexture);le(c,o);let h,y=o.mipmaps,C=o.isVideoTexture!==!0,w=f.__version===void 0||l===!0,T=u.dataReady,E=S(o,t);if(o.isDepthTexture)m=x(o.format===Fa,o.type),w&&(C?n.texStorage2D(e.TEXTURE_2D,1,m,t.width,t.height):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,null));else if(o.isDataTexture)if(y.length>0){C&&w&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data);o.generateMipmaps=!1}else C?(w&&n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height),T&&de(o,t,r,p)):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,t.data);else if(o.isCompressedTexture)if(o.isCompressedArrayTexture){C&&w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,y[0].width,y[0].height,t.depth);for(let i=0,a=y.length;i<a;i++)if(h=y[i],o.format!==1023)if(r!==null)if(C){if(T)if(o.layerUpdates.size>0){let t=sp(h.width,h.height,o.format,o.type);for(let a of o.layerUpdates){let o=h.data.subarray(a*t/h.data.BYTES_PER_ELEMENT,(a+1)*t/h.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,a,h.width,h.height,1,r,o)}o.clearLayerUpdates()}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,h.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,h.data,0,0);else B(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`);else C?T&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,p,h.data):n.texImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,r,p,h.data)}else{C&&w&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],o.format===1023?C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data):r===null?B(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`):C?T&&n.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,h.data):n.compressedTexImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,h.data)}else if(o.isDataArrayTexture)if(C){if(w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,t.width,t.height,t.depth),T)if(o.layerUpdates.size>0){let i=sp(t.width,t.height,o.format,o.type);for(let a of o.layerUpdates){let o=t.data.subarray(a*i/t.data.BYTES_PER_ELEMENT,(a+1)*i/t.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,a,t.width,t.height,1,r,p,o)}o.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,m,t.width,t.height,t.depth,0,r,p,t.data);else if(o.isData3DTexture)C?(w&&n.texStorage3D(e.TEXTURE_3D,E,m,t.width,t.height,t.depth),T&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)):n.texImage3D(e.TEXTURE_3D,0,m,t.width,t.height,t.depth,0,r,p,t.data);else if(o.isFramebufferTexture){if(w)if(C)n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height);else{let i=t.width,a=t.height;for(let t=0;t<E;t++)n.texImage2D(e.TEXTURE_2D,t,m,i,a,0,r,p,null),i>>=1,a>>=1}}else if(o.isHTMLTexture){if(`texElementImage2D`in e){let n=e.canvas;if(n.hasAttribute(`layoutsubtree`)||n.setAttribute(`layoutsubtree`,`true`),t.parentNode!==n){n.appendChild(t),d.add(o),n.onpaint=e=>{let t=e.changedElements;for(let e of d)t.includes(e.image)&&(e.needsUpdate=!0)},n.requestPaint();return}let r=e.RGBA,i=e.RGBA,a=e.UNSIGNED_BYTE;e.texElementImage2D(e.TEXTURE_2D,0,r,i,a,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}}else if(y.length>0){if(C&&w){let t=F(y[0]);n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height)}for(let t=0,i=y.length;t<i;t++)h=y[t],C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,r,p,h):n.texImage2D(e.TEXTURE_2D,t,m,r,p,h);o.generateMipmaps=!1}else if(C){if(w){let r=F(t);n.texStorage2D(e.TEXTURE_2D,E,m,r.width,r.height)}T&&n.texSubImage2D(e.TEXTURE_2D,0,0,0,r,p,t)}else n.texImage2D(e.TEXTURE_2D,0,m,r,p,t);_(o)&&v(c),f.__version=u.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function pe(t,o,s){if(o.image.length!==6)return;let c=ue(t,o),l=o.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+s);let u=r.get(l);if(l.version!==u.__version||c===!0){n.activeTexture(e.TEXTURE0+s);let t=Ls.getPrimaries(Ls.workingColorSpace),r=o.colorSpace===``?null:Ls.getPrimaries(o.colorSpace),d=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let f=o.isCompressedTexture||o.image[0].isCompressedTexture,p=o.image[0]&&o.image[0].isDataTexture,m=[];for(let e=0;e<6;e++)!f&&!p?m[e]=g(o.image[e],!0,i.maxCubemapSize):m[e]=p?o.image[e].image:o.image[e],m[e]=Te(o,m[e]);let h=m[0],y=a.convert(o.format,o.colorSpace),x=a.convert(o.type),C=b(o.internalFormat,y,x,o.normalized,o.colorSpace),w=o.isVideoTexture!==!0,T=u.__version===void 0||c===!0,E=l.dataReady,D=S(o,h);le(e.TEXTURE_CUBE_MAP,o);let O;if(f){w&&T&&n.texStorage2D(e.TEXTURE_CUBE_MAP,D,C,h.width,h.height);for(let t=0;t<6;t++){O=m[t].mipmaps;for(let r=0;r<O.length;r++){let i=O[r];o.format===1023?w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,C,i.width,i.height,0,y,x,i.data):y===null?B(`WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()`):w?E&&n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,i.data):n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,C,i.width,i.height,0,i.data)}}}else{if(O=o.mipmaps,w&&T){O.length>0&&D++;let t=F(m[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,D,C,t.width,t.height)}for(let t=0;t<6;t++)if(p){w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,m[t].width,m[t].height,y,x,m[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,m[t].width,m[t].height,0,y,x,m[t].data);for(let r=0;r<O.length;r++){let i=O[r].image[t].image;w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,C,i.width,i.height,0,y,x,i.data)}}else{w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,y,x,m[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,y,x,m[t]);for(let r=0;r<O.length;r++){let i=O[r];w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,y,x,i.image[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,C,y,x,i.image[t])}}}_(o)&&v(e.TEXTURE_CUBE_MAP),u.__version=l.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function me(t,i,o,c,l,u){let d=a.convert(o.format,o.colorSpace),f=a.convert(o.type),p=b(o.internalFormat,d,f,o.normalized,o.colorSpace),m=r.get(i),h=r.get(o);if(h.__renderTarget=i,!m.__hasExternalTextures){let t=Math.max(1,i.width>>u),r=Math.max(1,i.height>>u);l===e.TEXTURE_3D||l===e.TEXTURE_2D_ARRAY?n.texImage3D(l,u,p,t,r,i.depth,0,d,f,null):n.texImage2D(l,u,p,t,r,0,d,f,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),we(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,c,l,h.__webglTexture,0,Ce(i)):(l===e.TEXTURE_2D||l>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&l<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,c,l,h.__webglTexture,u),n.bindFramebuffer(e.FRAMEBUFFER,null)}function he(t,n,r){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){let i=n.depthTexture,a=i&&i.isDepthTexture?i.type:null,o=x(n.stencilBuffer,a),c=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;we(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Ce(n),o,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,Ce(n),o,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,o,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,c,e.RENDERBUFFER,t)}else{let t=n.textures;for(let i=0;i<t.length;i++){let o=t[i],c=a.convert(o.format,o.colorSpace),l=a.convert(o.type),u=b(o.internalFormat,c,l,o.normalized,o.colorSpace);we(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Ce(n),u,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,Ce(n),u,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,u,n.width,n.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function ge(t,i,o){let c=i.isWebGLCubeRenderTarget===!0;if(n.bindFramebuffer(e.FRAMEBUFFER,t),!(i.depthTexture&&i.depthTexture.isDepthTexture))throw Error(`renderTarget.depthTexture must be an instance of THREE.DepthTexture`);let l=r.get(i.depthTexture);if(l.__renderTarget=i,(!l.__webglTexture||i.depthTexture.image.width!==i.width||i.depthTexture.image.height!==i.height)&&(i.depthTexture.image.width=i.width,i.depthTexture.image.height=i.height,i.depthTexture.needsUpdate=!0),c){if(l.__webglInit===void 0&&(l.__webglInit=!0,i.depthTexture.addEventListener(`dispose`,C)),l.__webglTexture===void 0){l.__webglTexture=e.createTexture(),n.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),le(e.TEXTURE_CUBE_MAP,i.depthTexture);let t=a.convert(i.depthTexture.format),r=a.convert(i.depthTexture.type),o;i.depthTexture.format===1026?o=e.DEPTH_COMPONENT24:i.depthTexture.format===1027&&(o=e.DEPTH24_STENCIL8);for(let n=0;n<6;n++)e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,o,i.width,i.height,0,t,r,null)}}else re(i.depthTexture,0);let u=l.__webglTexture,d=Ce(i),f=c?e.TEXTURE_CUBE_MAP_POSITIVE_X+o:e.TEXTURE_2D,p=i.depthTexture.format===1027?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(i.depthTexture.format===1026)we(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else if(i.depthTexture.format===1027)we(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else throw Error(`Unknown depthTexture format`)}function _e(t){let i=r.get(t),a=t.isWebGLCubeRenderTarget===!0;if(i.__boundDepthTexture!==t.depthTexture){let e=t.depthTexture;if(i.__depthDisposeCallback&&i.__depthDisposeCallback(),e){let t=()=>{delete i.__boundDepthTexture,delete i.__depthDisposeCallback,e.removeEventListener(`dispose`,t)};e.addEventListener(`dispose`,t),i.__depthDisposeCallback=t}i.__boundDepthTexture=e}if(t.depthTexture&&!i.__autoAllocateDepthBuffer)if(a)for(let e=0;e<6;e++)ge(i.__webglFramebuffer[e],t,e);else{let e=t.texture.mipmaps;e&&e.length>0?ge(i.__webglFramebuffer[0],t,0):ge(i.__webglFramebuffer,t,0)}else if(a){i.__webglDepthbuffer=[];for(let r=0;r<6;r++)if(n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[r]),i.__webglDepthbuffer[r]===void 0)i.__webglDepthbuffer[r]=e.createRenderbuffer(),he(i.__webglDepthbuffer[r],t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,a=i.__webglDepthbuffer[r];e.bindRenderbuffer(e.RENDERBUFFER,a),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,a)}}else{let r=t.texture.mipmaps;if(r&&r.length>0?n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[0]):n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer),i.__webglDepthbuffer===void 0)i.__webglDepthbuffer=e.createRenderbuffer(),he(i.__webglDepthbuffer,t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,r=i.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,r)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}function ve(t,n,i){let a=r.get(t);n!==void 0&&me(a.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),i!==void 0&&_e(t)}function ye(t){let i=t.texture,s=r.get(t),c=r.get(i);t.addEventListener(`dispose`,w);let l=t.textures,u=t.isWebGLCubeRenderTarget===!0,d=l.length>1;if(d||(c.__webglTexture===void 0&&(c.__webglTexture=e.createTexture()),c.__version=i.version,o.memory.textures++),u){s.__webglFramebuffer=[];for(let t=0;t<6;t++)if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer[t]=[];for(let n=0;n<i.mipmaps.length;n++)s.__webglFramebuffer[t][n]=e.createFramebuffer()}else s.__webglFramebuffer[t]=e.createFramebuffer()}else{if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer=[];for(let t=0;t<i.mipmaps.length;t++)s.__webglFramebuffer[t]=e.createFramebuffer()}else s.__webglFramebuffer=e.createFramebuffer();if(d)for(let t=0,n=l.length;t<n;t++){let n=r.get(l[t]);n.__webglTexture===void 0&&(n.__webglTexture=e.createTexture(),o.memory.textures++)}if(t.samples>0&&we(t)===!1){s.__webglMultisampledFramebuffer=e.createFramebuffer(),s.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,s.__webglMultisampledFramebuffer);for(let n=0;n<l.length;n++){let r=l[n];s.__webglColorRenderbuffer[n]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,s.__webglColorRenderbuffer[n]);let i=a.convert(r.format,r.colorSpace),o=a.convert(r.type),c=b(r.internalFormat,i,o,r.normalized,r.colorSpace,t.isXRRenderTarget===!0),u=Ce(t);e.renderbufferStorageMultisample(e.RENDERBUFFER,u,c,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+n,e.RENDERBUFFER,s.__webglColorRenderbuffer[n])}e.bindRenderbuffer(e.RENDERBUFFER,null),t.depthBuffer&&(s.__webglDepthRenderbuffer=e.createRenderbuffer(),he(s.__webglDepthRenderbuffer,t,!0)),n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(u){n.bindTexture(e.TEXTURE_CUBE_MAP,c.__webglTexture),le(e.TEXTURE_CUBE_MAP,i);for(let n=0;n<6;n++)if(i.mipmaps&&i.mipmaps.length>0)for(let r=0;r<i.mipmaps.length;r++)me(s.__webglFramebuffer[n][r],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,r);else me(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0);_(i)&&v(e.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(d){for(let i=0,a=l.length;i<a;i++){let a=l[i],o=r.get(a),c=e.TEXTURE_2D;(t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(c=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(c,o.__webglTexture),le(c,a),me(s.__webglFramebuffer,t,a,e.COLOR_ATTACHMENT0+i,c,0),_(a)&&v(c)}n.unbindTexture()}else{let r=e.TEXTURE_2D;if((t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(r=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(r,c.__webglTexture),le(r,i),i.mipmaps&&i.mipmaps.length>0)for(let n=0;n<i.mipmaps.length;n++)me(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,r,n);else me(s.__webglFramebuffer,t,i,e.COLOR_ATTACHMENT0,r,0);_(i)&&v(r),n.unbindTexture()}t.depthBuffer&&_e(t)}function be(e){let t=e.textures;for(let i=0,a=t.length;i<a;i++){let a=t[i];if(_(a)){let t=y(e),i=r.get(a).__webglTexture;n.bindTexture(t,i),v(t),n.unbindTexture()}}}let xe=[],N=[];function Se(t){if(t.samples>0){if(we(t)===!1){let i=t.textures,a=t.width,o=t.height,s=e.COLOR_BUFFER_BIT,l=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,u=r.get(t),d=i.length>1;if(d)for(let t=0;t<i.length;t++)n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,u.__webglMultisampledFramebuffer);let f=t.texture.mipmaps;f&&f.length>0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer);for(let n=0;n<i.length;n++){if(t.resolveDepthBuffer&&(t.depthBuffer&&(s|=e.DEPTH_BUFFER_BIT),t.stencilBuffer&&t.resolveStencilBuffer&&(s|=e.STENCIL_BUFFER_BIT)),d){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,u.__webglColorRenderbuffer[n]);let t=r.get(i[n]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,a,o,0,0,a,o,s,e.NEAREST),c===!0&&(xe.length=0,N.length=0,xe.push(e.COLOR_ATTACHMENT0+n),t.depthBuffer&&t.resolveDepthBuffer===!1&&(xe.push(l),N.push(l),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,N)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,xe))}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),d)for(let t=0;t<i.length;t++){n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,u.__webglColorRenderbuffer[t]);let a=r.get(i[t]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,a,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglMultisampledFramebuffer)}else if(t.depthBuffer&&t.resolveDepthBuffer===!1&&c){let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[n])}}}function Ce(e){return Math.min(i.maxSamples,e.samples)}function we(e){let n=r.get(e);return e.samples>0&&t.has(`WEBGL_multisampled_render_to_texture`)===!0&&n.__useRenderToTexture!==!1}function P(e){let t=o.render.frame;u.get(e)!==t&&(u.set(e,t),e.update())}function Te(e,t){let n=e.colorSpace,r=e.format,i=e.type;return e.isCompressedTexture===!0||e.isVideoTexture===!0||n!==`srgb-linear`&&n!==``&&(Ls.getTransfer(n)===`srgb`?(r!==1023||i!==1009)&&B(`WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.`):V(`WebGLTextures: Unsupported texture color space:`,n)),t}function F(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement?(l.width=e.naturalWidth||e.width,l.height=e.naturalHeight||e.height):typeof VideoFrame<`u`&&e instanceof VideoFrame?(l.width=e.displayWidth,l.height=e.displayHeight):(l.width=e.width,l.height=e.height),l}this.allocateTextureUnit=te,this.resetTextureUnits=k,this.getTextureUnits=A,this.setTextureUnits=ee,this.setTexture2D=re,this.setTexture2DArray=ie,this.setTexture3D=ae,this.setTextureCube=j,this.rebindTextures=ve,this.setupRenderTarget=ye,this.updateRenderTargetMipmap=be,this.updateMultisampleRenderTarget=Se,this.setupDepthRenderbuffer=_e,this.setupFrameBufferTexture=me,this.useMultisampledRTT=we,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function pg(e,t){function n(n,r=``){let i,a=Ls.getTransfer(r);if(n===1009)return e.UNSIGNED_BYTE;if(n===1017)return e.UNSIGNED_SHORT_4_4_4_4;if(n===1018)return e.UNSIGNED_SHORT_5_5_5_1;if(n===35902)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===35899)return e.UNSIGNED_INT_10F_11F_11F_REV;if(n===1010)return e.BYTE;if(n===1011)return e.SHORT;if(n===1012)return e.UNSIGNED_SHORT;if(n===1013)return e.INT;if(n===1014)return e.UNSIGNED_INT;if(n===1015)return e.FLOAT;if(n===1016)return e.HALF_FLOAT;if(n===1021)return e.ALPHA;if(n===1022)return e.RGB;if(n===1023)return e.RGBA;if(n===1026)return e.DEPTH_COMPONENT;if(n===1027)return e.DEPTH_STENCIL;if(n===1028)return e.RED;if(n===1029)return e.RED_INTEGER;if(n===1030)return e.RG;if(n===1031)return e.RG_INTEGER;if(n===1033)return e.RGBA_INTEGER;if(n===33776||n===33777||n===33778||n===33779)if(a===`srgb`)if(i=t.get(`WEBGL_compressed_texture_s3tc_srgb`),i!==null){if(n===33776)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(i=t.get(`WEBGL_compressed_texture_s3tc`),i!==null){if(n===33776)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===35840||n===35841||n===35842||n===35843)if(i=t.get(`WEBGL_compressed_texture_pvrtc`),i!==null){if(n===35840)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===35841)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===35842)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===35843)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===36196||n===37492||n===37496||n===37488||n===37489||n===37490||n===37491)if(i=t.get(`WEBGL_compressed_texture_etc`),i!==null){if(n===36196||n===37492)return a===`srgb`?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(n===37496)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC;if(n===37488)return i.COMPRESSED_R11_EAC;if(n===37489)return i.COMPRESSED_SIGNED_R11_EAC;if(n===37490)return i.COMPRESSED_RG11_EAC;if(n===37491)return i.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===37808||n===37809||n===37810||n===37811||n===37812||n===37813||n===37814||n===37815||n===37816||n===37817||n===37818||n===37819||n===37820||n===37821)if(i=t.get(`WEBGL_compressed_texture_astc`),i!==null){if(n===37808)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===37809)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===37810)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===37811)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===37812)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===37813)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===37814)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===37815)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===37816)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===37817)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===37818)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===37819)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===37820)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===37821)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===36492||n===36494||n===36495)if(i=t.get(`EXT_texture_compression_bptc`),i!==null){if(n===36492)return a===`srgb`?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===36494)return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===36495)return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===36283||n===36284||n===36285||n===36286)if(i=t.get(`EXT_texture_compression_rgtc`),i!==null){if(n===36283)return i.COMPRESSED_RED_RGTC1_EXT;if(n===36284)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===36285)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===36286)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===1020?e.UNSIGNED_INT_24_8:e[n]===void 0?null:e[n]}return{convert:n}}var mg=`
|
|
4083
4083
|
void main() {
|
|
4084
4084
|
|
|
4085
4085
|
gl_Position = vec4( position, 1.0 );
|
|
4086
4086
|
|
|
4087
|
-
}`,
|
|
4087
|
+
}`,hg=`
|
|
4088
4088
|
uniform sampler2DArray depthColor;
|
|
4089
4089
|
uniform float depthWidth;
|
|
4090
4090
|
uniform float depthHeight;
|
|
@@ -4103,12 +4103,12 @@ void main() {
|
|
|
4103
4103
|
|
|
4104
4104
|
}
|
|
4105
4105
|
|
|
4106
|
-
}`,hg=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new ud(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new Dd({vertexShader:pg,fragmentShader:mg,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new iu(new _d(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},gg=class extends rs{constructor(e,t){super();let n=this,r=null,i=1,a=null,o=`local-floor`,s=1,c=null,l=null,u=null,d=null,f=null,p=null,m=typeof XRWebGLBinding<`u`,h=new hg,g={},_=t.getContextAttributes(),v=null,y=null,b=[],x=[],S=new H,C=null,w=new Cf;w.viewport=new Js;let T=new Cf;T.viewport=new Js;let E=[w,T],D=new Rf,O=null,k=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=b[e];return t===void 0&&(t=new Oc,b[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=b[e];return t===void 0&&(t=new Oc,b[e]=t),t.getGripSpace()},this.getHand=function(e){let t=b[e];return t===void 0&&(t=new Oc,b[e]=t),t.getHandSpace()};function A(e){let t=x.indexOf(e.inputSource);if(t===-1)return;let n=b[t];n!==void 0&&(n.update(e.inputSource,e.frame,c||a),n.dispatchEvent({type:e.type,data:e.inputSource}))}function ee(){r.removeEventListener(`select`,A),r.removeEventListener(`selectstart`,A),r.removeEventListener(`selectend`,A),r.removeEventListener(`squeeze`,A),r.removeEventListener(`squeezestart`,A),r.removeEventListener(`squeezeend`,A),r.removeEventListener(`end`,ee),r.removeEventListener(`inputsourceschange`,te);for(let e=0;e<b.length;e++){let t=x[e];t!==null&&(x[e]=null,b[e].disconnect(t))}O=null,k=null,h.reset();for(let e in g)delete g[e];e.setRenderTarget(v),f=null,d=null,u=null,r=null,y=null,ce.stop(),n.isPresenting=!1,e.setPixelRatio(C),e.setSize(S.width,S.height,!1),n.dispatchEvent({type:`sessionend`})}this.setFramebufferScaleFactor=function(e){i=e,n.isPresenting===!0&&B(`WebXRManager: Cannot change framebuffer scale while presenting.`)},this.setReferenceSpaceType=function(e){o=e,n.isPresenting===!0&&B(`WebXRManager: Cannot change reference space type while presenting.`)},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(e){c=e},this.getBaseLayer=function(){return d===null?f:d},this.getBinding=function(){return u===null&&m&&(u=new XRWebGLBinding(r,t)),u},this.getFrame=function(){return p},this.getSession=function(){return r},this.setSession=async function(l){if(r=l,r!==null){if(v=e.getRenderTarget(),r.addEventListener(`select`,A),r.addEventListener(`selectstart`,A),r.addEventListener(`selectend`,A),r.addEventListener(`squeeze`,A),r.addEventListener(`squeezestart`,A),r.addEventListener(`squeezeend`,A),r.addEventListener(`end`,ee),r.addEventListener(`inputsourceschange`,te),_.xrCompatible!==!0&&await t.makeXRCompatible(),C=e.getPixelRatio(),e.getSize(S),m&&`createProjectionLayer`in XRWebGLBinding.prototype){let n=null,a=null,o=null;_.depth&&(o=_.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=_.stencil?Fa:Pa,a=_.stencil?Oa:Ca);let s={colorFormat:t.RGBA8,depthFormat:o,scaleFactor:i};u=this.getBinding(),d=u.createProjectionLayer(s),r.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),y=new Xs(d.textureWidth,d.textureHeight,{format:Na,type:va,depthTexture:new cd(d.textureWidth,d.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{let n={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:i};f=new XRWebGLLayer(r,t,n),r.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new Xs(f.framebufferWidth,f.framebufferHeight,{format:Na,type:va,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(s),c=null,a=await r.requestReferenceSpace(o),ce.setContext(r),ce.start(),n.isPresenting=!0,n.dispatchEvent({type:`sessionstart`})}},this.getEnvironmentBlendMode=function(){if(r!==null)return r.environmentBlendMode},this.getDepthTexture=function(){return h.getDepthTexture()};function te(e){for(let t=0;t<e.removed.length;t++){let n=e.removed[t],r=x.indexOf(n);r>=0&&(x[r]=null,b[r].disconnect(n))}for(let t=0;t<e.added.length;t++){let n=e.added[t],r=x.indexOf(n);if(r===-1){for(let e=0;e<b.length;e++)if(e>=x.length){x.push(n),r=e;break}else if(x[e]===null){x[e]=n,r=e;break}if(r===-1)break}let i=b[r];i&&i.connect(n)}}let ne=new W,re=new W;function ie(e,t,n){ne.setFromMatrixPosition(t.matrixWorld),re.setFromMatrixPosition(n.matrixWorld);let r=ne.distanceTo(re),i=t.projectionMatrix.elements,a=n.projectionMatrix.elements,o=i[14]/(i[10]-1),s=i[14]/(i[10]+1),c=(i[9]+1)/i[5],l=(i[9]-1)/i[5],u=(i[8]-1)/i[0],d=(a[8]+1)/a[0],f=o*u,p=o*d,m=r/(-u+d),h=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(h),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),i[10]===-1)e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{let t=o+m,n=s+m,i=f-h,a=p+(r-h),u=c*s/n*t,d=l*s/n*t;e.projectionMatrix.makePerspective(i,a,u,d,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}function ae(e,t){t===null?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(r===null)return;let t=e.near,n=e.far;h.texture!==null&&(h.depthNear>0&&(t=h.depthNear),h.depthFar>0&&(n=h.depthFar)),D.near=T.near=w.near=t,D.far=T.far=w.far=n,(O!==D.near||k!==D.far)&&(r.updateRenderState({depthNear:D.near,depthFar:D.far}),O=D.near,k=D.far),D.layers.mask=e.layers.mask|6,w.layers.mask=D.layers.mask&-5,T.layers.mask=D.layers.mask&-3;let i=e.parent,a=D.cameras;ae(D,i);for(let e=0;e<a.length;e++)ae(a[e],i);a.length===2?ie(D,w,T):D.projectionMatrix.copy(w.projectionMatrix),j(e,D,i)};function j(e,t,n){n===null?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld)),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=ss*2*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}this.getCamera=function(){return D},this.getFoveation=function(){if(!(d===null&&f===null))return s},this.setFoveation=function(e){s=e,d!==null&&(d.fixedFoveation=e),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=e)},this.hasDepthSensing=function(){return h.texture!==null},this.getDepthSensingMesh=function(){return h.getMesh(D)},this.getCameraTexture=function(e){return g[e]};let oe=null;function se(t,i){if(l=i.getViewerPose(c||a),p=i,l!==null){let t=l.views;f!==null&&(e.setRenderTargetFramebuffer(y,f.framebuffer),e.setRenderTarget(y));let i=!1;t.length!==D.cameras.length&&(D.cameras.length=0,i=!0);for(let n=0;n<t.length;n++){let r=t[n],a=null;if(f!==null)a=f.getViewport(r);else{let t=u.getViewSubImage(d,r);a=t.viewport,n===0&&(e.setRenderTargetTextures(y,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(y))}let o=E[n];o===void 0&&(o=new Cf,o.layers.enable(n),o.viewport=new Js,E[n]=o),o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale),o.projectionMatrix.fromArray(r.projectionMatrix),o.projectionMatrixInverse.copy(o.projectionMatrix).invert(),o.viewport.set(a.x,a.y,a.width,a.height),n===0&&(D.matrix.copy(o.matrix),D.matrix.decompose(D.position,D.quaternion,D.scale)),i===!0&&D.cameras.push(o)}let a=r.enabledFeatures;if(a&&a.includes(`depth-sensing`)&&r.depthUsage==`gpu-optimized`&&m){u=n.getBinding();let e=u.getDepthInformation(t[0]);e&&e.isValid&&e.texture&&h.init(e,r.renderState)}if(a&&a.includes(`camera-access`)&&m){e.state.unbindTexture(),u=n.getBinding();for(let e=0;e<t.length;e++){let n=t[e].camera;if(n){let e=g[n];e||(e=new ud,g[n]=e);let t=u.getCameraImage(n);e.sourceTexture=t}}}}for(let e=0;e<b.length;e++){let t=x[e],n=b[e];t!==null&&n!==void 0&&n.update(t,i,c||a)}oe&&oe(t,i),i.detectedPlanes&&n.dispatchEvent({type:`planesdetected`,data:i}),p=null}let ce=new lp;ce.setAnimationLoop(se),this.setAnimationLoop=function(e){oe=e},this.dispose=function(){}}},_g=new K,vg=new G;vg.set(-1,0,0,0,1,0,0,0,1);function yg(e,t){function n(e,t){e.matrixAutoUpdate===!0&&e.updateMatrix(),t.value.copy(e.matrix)}function r(t,n){n.color.getRGB(t.fogColor.value,Cd(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)}function i(e,t,n,r,i){t.isNodeMaterial?t.uniformsNeedUpdate=!1:t.isMeshBasicMaterial?a(e,t):t.isMeshLambertMaterial?(a(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshToonMaterial?(a(e,t),d(e,t)):t.isMeshPhongMaterial?(a(e,t),u(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshStandardMaterial?(a(e,t),f(e,t),t.isMeshPhysicalMaterial&&p(e,t,i)):t.isMeshMatcapMaterial?(a(e,t),m(e,t)):t.isMeshDepthMaterial?a(e,t):t.isMeshDistanceMaterial?(a(e,t),h(e,t)):t.isMeshNormalMaterial?a(e,t):t.isLineBasicMaterial?(o(e,t),t.isLineDashedMaterial&&s(e,t)):t.isPointsMaterial?c(e,t,n,r):t.isSpriteMaterial?l(e,t):t.isShadowMaterial?(e.color.value.copy(t.color),e.opacity.value=t.opacity):t.isShaderMaterial&&(t.uniformsNeedUpdate=!1)}function a(e,r){e.opacity.value=r.opacity,r.color&&e.diffuse.value.copy(r.color),r.emissive&&e.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity),r.map&&(e.map.value=r.map,n(r.map,e.mapTransform)),r.alphaMap&&(e.alphaMap.value=r.alphaMap,n(r.alphaMap,e.alphaMapTransform)),r.bumpMap&&(e.bumpMap.value=r.bumpMap,n(r.bumpMap,e.bumpMapTransform),e.bumpScale.value=r.bumpScale,r.side===1&&(e.bumpScale.value*=-1)),r.normalMap&&(e.normalMap.value=r.normalMap,n(r.normalMap,e.normalMapTransform),e.normalScale.value.copy(r.normalScale),r.side===1&&e.normalScale.value.negate()),r.displacementMap&&(e.displacementMap.value=r.displacementMap,n(r.displacementMap,e.displacementMapTransform),e.displacementScale.value=r.displacementScale,e.displacementBias.value=r.displacementBias),r.emissiveMap&&(e.emissiveMap.value=r.emissiveMap,n(r.emissiveMap,e.emissiveMapTransform)),r.specularMap&&(e.specularMap.value=r.specularMap,n(r.specularMap,e.specularMapTransform)),r.alphaTest>0&&(e.alphaTest.value=r.alphaTest);let i=t.get(r),a=i.envMap,o=i.envMapRotation;a&&(e.envMap.value=a,e.envMapRotation.value.setFromMatrix4(_g.makeRotationFromEuler(o)).transpose(),a.isCubeTexture&&a.isRenderTargetTexture===!1&&e.envMapRotation.value.premultiply(vg),e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}function o(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}function s(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}function c(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=i*.5,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function l(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function u(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}function d(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}function f(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform)),e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform)),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}function p(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform))),t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===1&&e.clearcoatNormalScale.value.negate())),t.dispersion>0&&(e.dispersion.value=t.dispersion),t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform))),t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor)),t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform))),e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform)),t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}function m(e,t){t.matcap&&(e.matcap.value=t.matcap)}function h(e,n){let r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function bg(e,t,n,r){let i={},a={},o=[],s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(e,t){let n=t.program;r.uniformBlockBinding(e,n)}function l(e,n){let o=i[e.id];o===void 0&&(m(e),o=u(e),i[e.id]=o,e.addEventListener(`dispose`,g));let s=n.program;r.updateUBOMapping(e,s);let c=t.render.frame;a[e.id]!==c&&(f(e),a[e.id]=c)}function u(t){let n=d();t.__bindingPointIndex=n;let r=e.createBuffer(),i=t.__size,a=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,r),e.bufferData(e.UNIFORM_BUFFER,i,a),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,r),r}function d(){for(let e=0;e<s;e++)if(o.indexOf(e)===-1)return o.push(e),e;return V(`WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.`),0}function f(t){let n=i[t.id],r=t.uniforms,a=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,n);for(let t=0,n=r.length;t<n;t++){let n=Array.isArray(r[t])?r[t]:[r[t]];for(let r=0,i=n.length;r<i;r++){let i=n[r];if(p(i,t,r,a)===!0){let t=i.__offset,n=Array.isArray(i.value)?i.value:[i.value],r=0;for(let a=0;a<n.length;a++){let o=n[a],s=h(o);typeof o==`number`||typeof o==`boolean`?(i.__data[0]=o,e.bufferSubData(e.UNIFORM_BUFFER,t+r,i.__data)):o.isMatrix3?(i.__data[0]=o.elements[0],i.__data[1]=o.elements[1],i.__data[2]=o.elements[2],i.__data[3]=0,i.__data[4]=o.elements[3],i.__data[5]=o.elements[4],i.__data[6]=o.elements[5],i.__data[7]=0,i.__data[8]=o.elements[6],i.__data[9]=o.elements[7],i.__data[10]=o.elements[8],i.__data[11]=0):ArrayBuffer.isView(o)?i.__data.set(new o.constructor(o.buffer,o.byteOffset,i.__data.length)):(o.toArray(i.__data,r),r+=s.storage/Float32Array.BYTES_PER_ELEMENT)}e.bufferSubData(e.UNIFORM_BUFFER,t,i.__data)}}}e.bindBuffer(e.UNIFORM_BUFFER,null)}function p(e,t,n,r){let i=e.value,a=t+`_`+n;if(r[a]===void 0)return typeof i==`number`||typeof i==`boolean`?r[a]=i:ArrayBuffer.isView(i)?r[a]=i.slice():r[a]=i.clone(),!0;{let e=r[a];if(typeof i==`number`||typeof i==`boolean`){if(e!==i)return r[a]=i,!0}else if(ArrayBuffer.isView(i))return!0;else if(e.equals(i)===!1)return e.copy(i),!0}return!1}function m(e){let t=e.uniforms,n=0;for(let e=0,r=t.length;e<r;e++){let r=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0,t=r.length;e<t;e++){let t=r[e],i=Array.isArray(t.value)?t.value:[t.value];for(let e=0,r=i.length;e<r;e++){let r=i[e],a=h(r),o=n%16,s=o%a.boundary,c=o+s;n+=s,c!==0&&16-c<a.storage&&(n+=16-c),t.__data=new Float32Array(a.storage/Float32Array.BYTES_PER_ELEMENT),t.__offset=n,n+=a.storage}}}let r=n%16;return r>0&&(n+=16-r),e.__size=n,e.__cache={},this}function h(e){let t={boundary:0,storage:0};return typeof e==`number`||typeof e==`boolean`?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?B(`WebGLRenderer: Texture samplers can not be part of an uniforms group.`):ArrayBuffer.isView(e)?(t.boundary=16,t.storage=e.byteLength):B(`WebGLRenderer: Unsupported uniform value type.`,e),t}function g(t){let n=t.target;n.removeEventListener(`dispose`,g);let r=o.indexOf(n.__bindingPointIndex);o.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete a[n.id]}function _(){for(let t in i)e.deleteBuffer(i[t]);o=[],i={},a={}}return{bind:c,update:l,dispose:_}}var xg=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]),Sg=null;function Cg(){return Sg===null&&(Sg=new vu(xg,16,16,Ra,Ta),Sg.name=`DFG_LUT`,Sg.minFilter=ha,Sg.magFilter=ha,Sg.wrapS=ua,Sg.wrapT=ua,Sg.generateMipmaps=!1,Sg.needsUpdate=!0),Sg}var wg=class{constructor(e={}){let{canvas:t=Yo(),context:n=null,depth:r=!0,stencil:i=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:s=!0,preserveDrawingBuffer:c=!1,powerPreference:l=`default`,failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=va}=e;this.isWebGLRenderer=!0;let p;if(n!==null){if(typeof WebGLRenderingContext<`u`&&n instanceof WebGLRenderingContext)throw Error(`THREE.WebGLRenderer: WebGL 1 is not supported since r163.`);p=n.getContextAttributes().alpha}else p=a;let m=f,h=new Set([Ba,za,La]),g=new Set([va,Ca,xa,Oa,Ea,Da]),_=new Uint32Array(4),v=new Int32Array(4),y=new W,b=null,x=null,S=[],C=[],w=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let T=this,E=!1,D=null;this._outputColorSpace=Ro;let O=0,k=0,A=null,ee=-1,te=null,ne=new Js,re=new Js,ie=null,ae=new q(0),j=0,oe=t.width,se=t.height,ce=1,le=null,ue=null,M=new Js(0,0,oe,se),de=new Js(0,0,oe,se),fe=!1,pe=new Ru,me=!1,he=!1,ge=new K,_e=new W,ve=new Js,ye={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},be=!1;function xe(){return A===null?ce:1}let N=n;function Se(e,n){return t.getContext(e,n)}try{let e={alpha:!0,depth:r,stencil:i,antialias:o,premultipliedAlpha:s,preserveDrawingBuffer:c,powerPreference:l,failIfMajorPerformanceCaveat:u};if(`setAttribute`in t&&t.setAttribute(`data-engine`,`three.js r184`),t.addEventListener(`webglcontextlost`,We,!1),t.addEventListener(`webglcontextrestored`,Ge,!1),t.addEventListener(`webglcontextcreationerror`,Ke,!1),N===null){let t=`webgl2`;if(N=Se(t,e),N===null)throw Se(t)?Error(`Error creating WebGL context with your selected attributes.`):Error(`Error creating WebGL context.`)}}catch(e){throw V(`WebGLRenderer: `+e.message),e}let Ce,we,P,Te,F,I,L,Ee,De,Oe,ke,Ae,je,Me,Ne,Pe,Fe,Ie,Le,Re,ze,Be,Ve;function He(){Ce=new Hp(N),Ce.init(),ze=new fg(N,Ce),we=new vp(N,Ce,e,ze),P=new ug(N,Ce),we.reversedDepthBuffer&&d&&P.buffers.depth.setReversed(!0),Te=new Gp(N),F=new Wh,I=new dg(N,Ce,P,F,we,ze,Te),L=new Vp(T),Ee=new up(N),Be=new gp(N,Ee),De=new Up(N,Ee,Te,Be),Oe=new qp(N,De,Ee,Be,Te),Ie=new Kp(N,we,I),Ne=new yp(F),ke=new Uh(T,L,Ce,we,Be,Ne),Ae=new yg(T,F),je=new Jh,Me=new tg(Ce),Fe=new hp(T,L,P,Oe,p,s),Pe=new lg(T,Oe,we),Ve=new bg(N,Te,we,P),Le=new _p(N,Ce,Te),Re=new Wp(N,Ce,Te),Te.programs=ke.programs,T.capabilities=we,T.extensions=Ce,T.properties=F,T.renderLists=je,T.shadowMap=Pe,T.state=P,T.info=Te}He(),m!==1009&&(w=new Yp(m,t.width,t.height,r,i));let Ue=new gg(T,N);this.xr=Ue,this.getContext=function(){return N},this.getContextAttributes=function(){return N.getContextAttributes()},this.forceContextLoss=function(){let e=Ce.get(`WEBGL_lose_context`);e&&e.loseContext()},this.forceContextRestore=function(){let e=Ce.get(`WEBGL_lose_context`);e&&e.restoreContext()},this.getPixelRatio=function(){return ce},this.setPixelRatio=function(e){e!==void 0&&(ce=e,this.setSize(oe,se,!1))},this.getSize=function(e){return e.set(oe,se)},this.setSize=function(e,n,r=!0){if(Ue.isPresenting){B(`WebGLRenderer: Can't change size while VR device is presenting.`);return}oe=e,se=n,t.width=Math.floor(e*ce),t.height=Math.floor(n*ce),r===!0&&(t.style.width=e+`px`,t.style.height=n+`px`),w!==null&&w.setSize(t.width,t.height),this.setViewport(0,0,e,n)},this.getDrawingBufferSize=function(e){return e.set(oe*ce,se*ce).floor()},this.setDrawingBufferSize=function(e,n,r){oe=e,se=n,ce=r,t.width=Math.floor(e*r),t.height=Math.floor(n*r),this.setViewport(0,0,e,n)},this.setEffects=function(e){if(m===1009){V(`THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.`);return}if(e){for(let t=0;t<e.length;t++)if(e[t].isOutputPass===!0){B(`THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.`);break}}w.setEffects(e||[])},this.getCurrentViewport=function(e){return e.copy(ne)},this.getViewport=function(e){return e.copy(M)},this.setViewport=function(e,t,n,r){e.isVector4?M.set(e.x,e.y,e.z,e.w):M.set(e,t,n,r),P.viewport(ne.copy(M).multiplyScalar(ce).round())},this.getScissor=function(e){return e.copy(de)},this.setScissor=function(e,t,n,r){e.isVector4?de.set(e.x,e.y,e.z,e.w):de.set(e,t,n,r),P.scissor(re.copy(de).multiplyScalar(ce).round())},this.getScissorTest=function(){return fe},this.setScissorTest=function(e){P.setScissorTest(fe=e)},this.setOpaqueSort=function(e){le=e},this.setTransparentSort=function(e){ue=e},this.getClearColor=function(e){return e.copy(Fe.getClearColor())},this.setClearColor=function(){Fe.setClearColor(...arguments)},this.getClearAlpha=function(){return Fe.getClearAlpha()},this.setClearAlpha=function(){Fe.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,n=!0){let r=0;if(e){let e=!1;if(A!==null){let t=A.texture.format;e=h.has(t)}if(e){let e=A.texture.type,t=g.has(e),n=Fe.getClearColor(),r=Fe.getClearAlpha(),i=n.r,a=n.g,o=n.b;t?(_[0]=i,_[1]=a,_[2]=o,_[3]=r,N.clearBufferuiv(N.COLOR,0,_)):(v[0]=i,v[1]=a,v[2]=o,v[3]=r,N.clearBufferiv(N.COLOR,0,v))}else r|=N.COLOR_BUFFER_BIT}t&&(r|=N.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),n&&(r|=N.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),r!==0&&N.clear(r)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(e){e.setRenderer(this),D=e},this.dispose=function(){t.removeEventListener(`webglcontextlost`,We,!1),t.removeEventListener(`webglcontextrestored`,Ge,!1),t.removeEventListener(`webglcontextcreationerror`,Ke,!1),Fe.dispose(),je.dispose(),Me.dispose(),F.dispose(),L.dispose(),Oe.dispose(),Be.dispose(),Ve.dispose(),ke.dispose(),Ue.dispose(),Ue.removeEventListener(`sessionstart`,$e),Ue.removeEventListener(`sessionend`,et),R.stop()};function We(e){e.preventDefault(),Qo(`WebGLRenderer: Context Lost.`),E=!0}function Ge(){Qo(`WebGLRenderer: Context Restored.`),E=!1;let e=Te.autoReset,t=Pe.enabled,n=Pe.autoUpdate,r=Pe.needsUpdate,i=Pe.type;He(),Te.autoReset=e,Pe.enabled=t,Pe.autoUpdate=n,Pe.needsUpdate=r,Pe.type=i}function Ke(e){V(`WebGLRenderer: A WebGL context could not be created. Reason: `,e.statusMessage)}function qe(e){let t=e.target;t.removeEventListener(`dispose`,qe),Je(t)}function Je(e){Ye(e),F.remove(e)}function Ye(e){let t=F.get(e).programs;t!==void 0&&(t.forEach(function(e){ke.releaseProgram(e)}),e.isShaderMaterial&&ke.releaseShaderCache(e))}this.renderBufferDirect=function(e,t,n,r,i,a){t===null&&(t=ye);let o=i.isMesh&&i.matrixWorld.determinant()<0,s=lt(e,t,n,r,i);P.setMaterial(r,o);let c=n.index,l=1;if(r.wireframe===!0){if(c=De.getWireframeAttribute(n),c===void 0)return;l=2}let u=n.drawRange,d=n.attributes.position,f=u.start*l,p=(u.start+u.count)*l;a!==null&&(f=Math.max(f,a.start*l),p=Math.min(p,(a.start+a.count)*l)),c===null?d!=null&&(f=Math.max(f,0),p=Math.min(p,d.count)):(f=Math.max(f,0),p=Math.min(p,c.count));let m=p-f;if(m<0||m===1/0)return;Be.setup(i,r,s,n,c);let h,g=Le;if(c!==null&&(h=Ee.get(c),g=Re,g.setIndex(h)),i.isMesh)r.wireframe===!0?(P.setLineWidth(r.wireframeLinewidth*xe()),g.setMode(N.LINES)):g.setMode(N.TRIANGLES);else if(i.isLine){let e=r.linewidth;e===void 0&&(e=1),P.setLineWidth(e*xe()),i.isLineSegments?g.setMode(N.LINES):i.isLineLoop?g.setMode(N.LINE_LOOP):g.setMode(N.LINE_STRIP)}else i.isPoints?g.setMode(N.POINTS):i.isSprite&&g.setMode(N.TRIANGLES);if(i.isBatchedMesh)if(Ce.get(`WEBGL_multi_draw`))g.renderMultiDraw(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount);else{let e=i._multiDrawStarts,t=i._multiDrawCounts,n=i._multiDrawCount,a=c?Ee.get(c).bytesPerElement:1,o=F.get(r).currentProgram.getUniforms();for(let r=0;r<n;r++)o.setValue(N,`_gl_DrawID`,r),g.render(e[r]/a,t[r])}else if(i.isInstancedMesh)g.renderInstances(f,m,i.count);else if(n.isInstancedBufferGeometry){let e=n._maxInstanceCount===void 0?1/0:n._maxInstanceCount,t=Math.min(n.instanceCount,e);g.renderInstances(f,m,t)}else g.render(f,m)};function Xe(e,t,n){e.transparent===!0&&e.side===2&&e.forceSinglePass===!1?(e.side=1,e.needsUpdate=!0,at(e,t,n),e.side=0,e.needsUpdate=!0,at(e,t,n),e.side=2):at(e,t,n)}this.compile=function(e,t,n=null){n===null&&(n=e),x=Me.get(n),x.init(t),C.push(x),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),x.setupLights();let r=new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;let t=e.material;if(t)if(Array.isArray(t))for(let i=0;i<t.length;i++){let a=t[i];Xe(a,n,e),r.add(a)}else Xe(t,n,e),r.add(t)}),x=C.pop(),r},this.compileAsync=function(e,t,n=null){let r=this.compile(e,t,n);return new Promise(t=>{function n(){if(r.forEach(function(e){F.get(e).currentProgram.isReady()&&r.delete(e)}),r.size===0){t(e);return}setTimeout(n,10)}Ce.get(`KHR_parallel_shader_compile`)===null?setTimeout(n,10):n()})};let Ze=null;function Qe(e){Ze&&Ze(e)}function $e(){R.stop()}function et(){R.start()}let R=new lp;R.setAnimationLoop(Qe),typeof self<`u`&&R.setContext(self),this.setAnimationLoop=function(e){Ze=e,Ue.setAnimationLoop(e),e===null?R.stop():R.start()},Ue.addEventListener(`sessionstart`,$e),Ue.addEventListener(`sessionend`,et),this.render=function(e,t){if(t!==void 0&&t.isCamera!==!0){V(`WebGLRenderer.render: camera is not an instance of THREE.Camera.`);return}if(E===!0)return;D!==null&&D.renderStart(e,t);let n=Ue.enabled===!0&&Ue.isPresenting===!0,r=w!==null&&(A===null||n)&&w.begin(T,A);if(e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),Ue.enabled===!0&&Ue.isPresenting===!0&&(w===null||w.isCompositing()===!1)&&(Ue.cameraAutoUpdate===!0&&Ue.updateCamera(t),t=Ue.getCamera()),e.isScene===!0&&e.onBeforeRender(T,e,t,A),x=Me.get(e,C.length),x.init(t),x.state.textureUnits=I.getTextureUnits(),C.push(x),ge.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),pe.setFromProjectionMatrix(ge,Go,t.reversedDepth),he=this.localClippingEnabled,me=Ne.init(this.clippingPlanes,he),b=je.get(e,S.length),b.init(),S.push(b),Ue.enabled===!0&&Ue.isPresenting===!0){let e=T.xr.getDepthSensingMesh();e!==null&&tt(e,t,-1/0,T.sortObjects)}tt(e,t,0,T.sortObjects),b.finish(),T.sortObjects===!0&&b.sort(le,ue),be=Ue.enabled===!1||Ue.isPresenting===!1||Ue.hasDepthSensing()===!1,be&&Fe.addToRenderList(b,e),this.info.render.frame++,me===!0&&Ne.beginShadows();let i=x.state.shadowsArray;if(Pe.render(i,e,t),me===!0&&Ne.endShadows(),this.info.autoReset===!0&&this.info.reset(),(r&&w.hasRenderPass())===!1){let n=b.opaque,r=b.transmissive;if(x.setupLights(),t.isArrayCamera){let i=t.cameras;if(r.length>0)for(let t=0,a=i.length;t<a;t++){let a=i[t];rt(n,r,e,a)}be&&Fe.render(e);for(let t=0,n=i.length;t<n;t++){let n=i[t];nt(b,e,n,n.viewport)}}else r.length>0&&rt(n,r,e,t),be&&Fe.render(e),nt(b,e,t)}A!==null&&k===0&&(I.updateMultisampleRenderTarget(A),I.updateRenderTargetMipmap(A)),r&&w.end(T),e.isScene===!0&&e.onAfterRender(T,e,t),Be.resetDefaultState(),ee=-1,te=null,C.pop(),C.length>0?(x=C[C.length-1],I.setTextureUnits(x.state.textureUnits),me===!0&&Ne.setGlobalState(T.clippingPlanes,x.state.camera)):x=null,S.pop(),b=S.length>0?S[S.length-1]:null,D!==null&&D.renderEnd()};function tt(e,t,n,r){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder;else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLightProbeGrid)x.pushLightProbeGrid(e);else if(e.isLight)x.pushLight(e),e.castShadow&&x.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||pe.intersectsSprite(e)){r&&ve.setFromMatrixPosition(e.matrixWorld).applyMatrix4(ge);let t=Oe.update(e),i=e.material;i.visible&&b.push(e,t,i,n,ve.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||pe.intersectsObject(e))){let t=Oe.update(e),i=e.material;if(r&&(e.boundingSphere===void 0?(t.boundingSphere===null&&t.computeBoundingSphere(),ve.copy(t.boundingSphere.center)):(e.boundingSphere===null&&e.computeBoundingSphere(),ve.copy(e.boundingSphere.center)),ve.applyMatrix4(e.matrixWorld).applyMatrix4(ge)),Array.isArray(i)){let r=t.groups;for(let a=0,o=r.length;a<o;a++){let o=r[a],s=i[o.materialIndex];s&&s.visible&&b.push(e,t,s,n,ve.z,o)}}else i.visible&&b.push(e,t,i,n,ve.z,null)}}let i=e.children;for(let e=0,a=i.length;e<a;e++)tt(i[e],t,n,r)}function nt(e,t,n,r){let{opaque:i,transmissive:a,transparent:o}=e;x.setupLightsView(n),me===!0&&Ne.setGlobalState(T.clippingPlanes,n),r&&P.viewport(ne.copy(r)),i.length>0&&it(i,t,n),a.length>0&&it(a,t,n),o.length>0&&it(o,t,n),P.buffers.depth.setTest(!0),P.buffers.depth.setMask(!0),P.buffers.color.setMask(!0),P.setPolygonOffset(!1)}function rt(e,t,n,r){if((n.isScene===!0?n.overrideMaterial:null)!==null)return;if(x.state.transmissionRenderTarget[r.id]===void 0){let e=Ce.has(`EXT_color_buffer_half_float`)||Ce.has(`EXT_color_buffer_float`);x.state.transmissionRenderTarget[r.id]=new Xs(1,1,{generateMipmaps:!0,type:e?Ta:va,minFilter:_a,samples:Math.max(4,we.samples),stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Ls.workingColorSpace})}let a=x.state.transmissionRenderTarget[r.id],o=r.viewport||ne;a.setSize(o.z*T.transmissionResolutionScale,o.w*T.transmissionResolutionScale);let s=T.getRenderTarget(),c=T.getActiveCubeFace(),l=T.getActiveMipmapLevel();T.setRenderTarget(a),T.getClearColor(ae),j=T.getClearAlpha(),j<1&&T.setClearColor(16777215,.5),T.clear(),be&&Fe.render(n);let u=T.toneMapping;T.toneMapping=0;let d=r.viewport;if(r.viewport!==void 0&&(r.viewport=void 0),x.setupLightsView(r),me===!0&&Ne.setGlobalState(T.clippingPlanes,r),it(e,n,r),I.updateMultisampleRenderTarget(a),I.updateRenderTargetMipmap(a),Ce.has(`WEBGL_multisampled_render_to_texture`)===!1){let e=!1;for(let i=0,a=t.length;i<a;i++){let{object:a,geometry:o,material:s,group:c}=t[i];if(s.side===2&&a.layers.test(r.layers)){let t=s.side;s.side=1,s.needsUpdate=!0,z(a,n,r,o,s,c),s.side=t,s.needsUpdate=!0,e=!0}}e===!0&&(I.updateMultisampleRenderTarget(a),I.updateRenderTargetMipmap(a))}T.setRenderTarget(s,c,l),T.setClearColor(ae,j),d!==void 0&&(r.viewport=d),T.toneMapping=u}function it(e,t,n){let r=t.isScene===!0?t.overrideMaterial:null;for(let i=0,a=e.length;i<a;i++){let a=e[i],{object:o,geometry:s,group:c}=a,l=a.material;l.allowOverride===!0&&r!==null&&(l=r),o.layers.test(n.layers)&&z(o,t,n,s,l,c)}}function z(e,t,n,r,i,a){e.onBeforeRender(T,t,n,r,i,a),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),i.onBeforeRender(T,t,n,r,e,a),i.transparent===!0&&i.side===2&&i.forceSinglePass===!1?(i.side=1,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=0,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=2):T.renderBufferDirect(n,t,r,i,e,a),e.onAfterRender(T,t,n,r,i,a)}function at(e,t,n){t.isScene!==!0&&(t=ye);let r=F.get(e),i=x.state.lights,a=x.state.shadowsArray,o=i.state.version,s=ke.getParameters(e,i.state,a,t,n,x.state.lightProbeGridArray),c=ke.getProgramCacheKey(s),l=r.programs;r.environment=e.isMeshStandardMaterial||e.isMeshLambertMaterial||e.isMeshPhongMaterial?t.environment:null,r.fog=t.fog;let u=e.isMeshStandardMaterial||e.isMeshLambertMaterial&&!e.envMap||e.isMeshPhongMaterial&&!e.envMap;r.envMap=L.get(e.envMap||r.environment,u),r.envMapRotation=r.environment!==null&&e.envMap===null?t.environmentRotation:e.envMapRotation,l===void 0&&(e.addEventListener(`dispose`,qe),l=new Map,r.programs=l);let d=l.get(c);if(d!==void 0){if(r.currentProgram===d&&r.lightsStateVersion===o)return st(e,s),d}else s.uniforms=ke.getUniforms(e),D!==null&&e.isNodeMaterial&&D.build(e,n,s),e.onBeforeCompile(s,T),d=ke.acquireProgram(s,c),l.set(c,d),r.uniforms=s.uniforms;let f=r.uniforms;return(!e.isShaderMaterial&&!e.isRawShaderMaterial||e.clipping===!0)&&(f.clippingPlanes=Ne.uniform),st(e,s),r.needsLights=dt(e),r.lightsStateVersion=o,r.needsLights&&(f.ambientLightColor.value=i.state.ambient,f.lightProbe.value=i.state.probe,f.directionalLights.value=i.state.directional,f.directionalLightShadows.value=i.state.directionalShadow,f.spotLights.value=i.state.spot,f.spotLightShadows.value=i.state.spotShadow,f.rectAreaLights.value=i.state.rectArea,f.ltc_1.value=i.state.rectAreaLTC1,f.ltc_2.value=i.state.rectAreaLTC2,f.pointLights.value=i.state.point,f.pointLightShadows.value=i.state.pointShadow,f.hemisphereLights.value=i.state.hemi,f.directionalShadowMatrix.value=i.state.directionalShadowMatrix,f.spotLightMatrix.value=i.state.spotLightMatrix,f.spotLightMap.value=i.state.spotLightMap,f.pointShadowMatrix.value=i.state.pointShadowMatrix),r.lightProbeGrid=x.state.lightProbeGridArray.length>0,r.currentProgram=d,r.uniformsList=null,d}function ot(e){if(e.uniformsList===null){let t=e.currentProgram.getUniforms();e.uniformsList=nh.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function st(e,t){let n=F.get(e);n.outputColorSpace=t.outputColorSpace,n.batching=t.batching,n.batchingColor=t.batchingColor,n.instancing=t.instancing,n.instancingColor=t.instancingColor,n.instancingMorph=t.instancingMorph,n.skinning=t.skinning,n.morphTargets=t.morphTargets,n.morphNormals=t.morphNormals,n.morphColors=t.morphColors,n.morphTargetsCount=t.morphTargetsCount,n.numClippingPlanes=t.numClippingPlanes,n.numIntersection=t.numClipIntersection,n.vertexAlphas=t.vertexAlphas,n.vertexTangents=t.vertexTangents,n.toneMapping=t.toneMapping}function ct(e,t){if(e.length===0)return null;if(e.length===1)return e[0].texture===null?null:e[0];y.setFromMatrixPosition(t.matrixWorld);for(let t=0,n=e.length;t<n;t++){let n=e[t];if(n.texture!==null&&n.boundingBox.containsPoint(y))return n}return null}function lt(e,t,n,r,i){t.isScene!==!0&&(t=ye),I.resetTextureUnits();let a=t.fog,o=r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial?t.environment:null,s=A===null?T.outputColorSpace:A.isXRRenderTarget===!0?A.texture.colorSpace:Ls.workingColorSpace,c=r.isMeshStandardMaterial||r.isMeshLambertMaterial&&!r.envMap||r.isMeshPhongMaterial&&!r.envMap,l=L.get(r.envMap||o,c),u=r.vertexColors===!0&&!!n.attributes.color&&n.attributes.color.itemSize===4,d=!!n.attributes.tangent&&(!!r.normalMap||r.anisotropy>0),f=!!n.morphAttributes.position,p=!!n.morphAttributes.normal,m=!!n.morphAttributes.color,h=0;r.toneMapped&&(A===null||A.isXRRenderTarget===!0)&&(h=T.toneMapping);let g=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,_=g===void 0?0:g.length,v=F.get(r),y=x.state.lights;if(me===!0&&(he===!0||e!==te)){let t=e===te&&r.id===ee;Ne.setState(r,e,t)}let b=!1;r.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version?b=!0:v.outputColorSpace===s?i.isBatchedMesh&&v.batching===!1||!i.isBatchedMesh&&v.batching===!0||i.isBatchedMesh&&v.batchingColor===!0&&i.colorTexture===null||i.isBatchedMesh&&v.batchingColor===!1&&i.colorTexture!==null||i.isInstancedMesh&&v.instancing===!1||!i.isInstancedMesh&&v.instancing===!0||i.isSkinnedMesh&&v.skinning===!1||!i.isSkinnedMesh&&v.skinning===!0||i.isInstancedMesh&&v.instancingColor===!0&&i.instanceColor===null||i.isInstancedMesh&&v.instancingColor===!1&&i.instanceColor!==null||i.isInstancedMesh&&v.instancingMorph===!0&&i.morphTexture===null||i.isInstancedMesh&&v.instancingMorph===!1&&i.morphTexture!==null?b=!0:v.envMap===l?r.fog===!0&&v.fog!==a||v.numClippingPlanes!==void 0&&(v.numClippingPlanes!==Ne.numPlanes||v.numIntersection!==Ne.numIntersection)?b=!0:v.vertexAlphas===u&&v.vertexTangents===d&&v.morphTargets===f&&v.morphNormals===p&&v.morphColors===m&&v.toneMapping===h&&v.morphTargetsCount===_?!!v.lightProbeGrid!=x.state.lightProbeGridArray.length>0&&(b=!0):b=!0:b=!0:b=!0:(b=!0,v.__version=r.version);let S=v.currentProgram;b===!0&&(S=at(r,t,i),D&&r.isNodeMaterial&&D.onUpdateProgram(r,S,v));let C=!1,w=!1,E=!1,O=S.getUniforms(),k=v.uniforms;if(P.useProgram(S.program)&&(C=!0,w=!0,E=!0),r.id!==ee&&(ee=r.id,w=!0),v.needsLights){let e=ct(x.state.lightProbeGridArray,i);v.lightProbeGrid!==e&&(v.lightProbeGrid=e,w=!0)}if(C||te!==e){P.buffers.depth.getReversed()&&e.reversedDepth!==!0&&(e._reversedDepth=!0,e.updateProjectionMatrix()),O.setValue(N,`projectionMatrix`,e.projectionMatrix),O.setValue(N,`viewMatrix`,e.matrixWorldInverse);let t=O.map.cameraPosition;t!==void 0&&t.setValue(N,_e.setFromMatrixPosition(e.matrixWorld)),we.logarithmicDepthBuffer&&O.setValue(N,`logDepthBufFC`,2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&O.setValue(N,`isOrthographic`,e.isOrthographicCamera===!0),te!==e&&(te=e,w=!0,E=!0)}if(v.needsLights&&(y.state.directionalShadowMap.length>0&&O.setValue(N,`directionalShadowMap`,y.state.directionalShadowMap,I),y.state.spotShadowMap.length>0&&O.setValue(N,`spotShadowMap`,y.state.spotShadowMap,I),y.state.pointShadowMap.length>0&&O.setValue(N,`pointShadowMap`,y.state.pointShadowMap,I)),i.isSkinnedMesh){O.setOptional(N,i,`bindMatrix`),O.setOptional(N,i,`bindMatrixInverse`);let e=i.skeleton;e&&(e.boneTexture===null&&e.computeBoneTexture(),O.setValue(N,`boneTexture`,e.boneTexture,I))}i.isBatchedMesh&&(O.setOptional(N,i,`batchingTexture`),O.setValue(N,`batchingTexture`,i._matricesTexture,I),O.setOptional(N,i,`batchingIdTexture`),O.setValue(N,`batchingIdTexture`,i._indirectTexture,I),O.setOptional(N,i,`batchingColorTexture`),i._colorsTexture!==null&&O.setValue(N,`batchingColorTexture`,i._colorsTexture,I));let ne=n.morphAttributes;if((ne.position!==void 0||ne.normal!==void 0||ne.color!==void 0)&&Ie.update(i,n,S),(w||v.receiveShadow!==i.receiveShadow)&&(v.receiveShadow=i.receiveShadow,O.setValue(N,`receiveShadow`,i.receiveShadow)),(r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial)&&r.envMap===null&&t.environment!==null&&(k.envMapIntensity.value=t.environmentIntensity),k.dfgLUT!==void 0&&(k.dfgLUT.value=Cg()),w){if(O.setValue(N,`toneMappingExposure`,T.toneMappingExposure),v.needsLights&&ut(k,E),a&&r.fog===!0&&Ae.refreshFogUniforms(k,a),Ae.refreshMaterialUniforms(k,r,ce,se,x.state.transmissionRenderTarget[e.id]),v.needsLights&&v.lightProbeGrid){let e=v.lightProbeGrid;k.probesSH.value=e.texture,k.probesMin.value.copy(e.boundingBox.min),k.probesMax.value.copy(e.boundingBox.max),k.probesResolution.value.copy(e.resolution)}nh.upload(N,ot(v),k,I)}if(r.isShaderMaterial&&r.uniformsNeedUpdate===!0&&(nh.upload(N,ot(v),k,I),r.uniformsNeedUpdate=!1),r.isSpriteMaterial&&O.setValue(N,`center`,i.center),O.setValue(N,`modelViewMatrix`,i.modelViewMatrix),O.setValue(N,`normalMatrix`,i.normalMatrix),O.setValue(N,`modelMatrix`,i.matrixWorld),r.uniformsGroups!==void 0){let e=r.uniformsGroups;for(let t=0,n=e.length;t<n;t++){let n=e[t];Ve.update(n,S),Ve.bind(n,S)}}return S}function ut(e,t){e.ambientLightColor.needsUpdate=t,e.lightProbe.needsUpdate=t,e.directionalLights.needsUpdate=t,e.directionalLightShadows.needsUpdate=t,e.pointLights.needsUpdate=t,e.pointLightShadows.needsUpdate=t,e.spotLights.needsUpdate=t,e.spotLightShadows.needsUpdate=t,e.rectAreaLights.needsUpdate=t,e.hemisphereLights.needsUpdate=t}function dt(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&e.lights===!0}this.getActiveCubeFace=function(){return O},this.getActiveMipmapLevel=function(){return k},this.getRenderTarget=function(){return A},this.setRenderTargetTextures=function(e,t,n){let r=F.get(e);r.__autoAllocateDepthBuffer=e.resolveDepthBuffer===!1,r.__autoAllocateDepthBuffer===!1&&(r.__useRenderToTexture=!1),F.get(e.texture).__webglTexture=t,F.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){let n=F.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=t===void 0};let ft=N.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){A=e,O=t,k=n;let r=null,i=!1,a=!1;if(e){let o=F.get(e);if(o.__useDefaultFramebuffer!==void 0){P.bindFramebuffer(N.FRAMEBUFFER,o.__webglFramebuffer),ne.copy(e.viewport),re.copy(e.scissor),ie=e.scissorTest,P.viewport(ne),P.scissor(re),P.setScissorTest(ie),ee=-1;return}else if(o.__webglFramebuffer===void 0)I.setupRenderTarget(e);else if(o.__hasExternalTextures)I.rebindTextures(e,F.get(e.texture).__webglTexture,F.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){let t=e.depthTexture;if(o.__boundDepthTexture!==t){if(t!==null&&F.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw Error(`WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.`);I.setupDepthRenderbuffer(e)}}let s=e.texture;(s.isData3DTexture||s.isDataArrayTexture||s.isCompressedArrayTexture)&&(a=!0);let c=F.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=Array.isArray(c[t])?c[t][n]:c[t],i=!0):r=e.samples>0&&I.useMultisampledRTT(e)===!1?F.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,ne.copy(e.viewport),re.copy(e.scissor),ie=e.scissorTest}else ne.copy(M).multiplyScalar(ce).floor(),re.copy(de).multiplyScalar(ce).floor(),ie=fe;if(n!==0&&(r=ft),P.bindFramebuffer(N.FRAMEBUFFER,r)&&P.drawBuffers(e,r),P.viewport(ne),P.scissor(re),P.setScissorTest(ie),i){let r=F.get(e.texture);N.framebufferTexture2D(N.FRAMEBUFFER,N.COLOR_ATTACHMENT0,N.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(a){let r=t;for(let t=0;t<e.textures.length;t++){let i=F.get(e.textures[t]);N.framebufferTextureLayer(N.FRAMEBUFFER,N.COLOR_ATTACHMENT0+t,i.__webglTexture,n,r)}}else if(e!==null&&n!==0){let t=F.get(e.texture);N.framebufferTexture2D(N.FRAMEBUFFER,N.COLOR_ATTACHMENT0,N.TEXTURE_2D,t.__webglTexture,n)}ee=-1},this.readRenderTargetPixels=function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget)){V(`WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);return}let c=F.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c){P.bindFramebuffer(N.FRAMEBUFFER,c);try{let o=e.textures[s],c=o.format,l=o.type;if(e.textures.length>1&&N.readBuffer(N.COLOR_ATTACHMENT0+s),!we.textureFormatReadable(c)){V(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.`);return}if(!we.textureTypeReadable(l)){V(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.`);return}t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&N.readPixels(t,n,r,i,ze.convert(c),ze.convert(l),a)}finally{let e=A===null?null:F.get(A).__webglFramebuffer;P.bindFramebuffer(N.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget))throw Error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);let c=F.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c)if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){P.bindFramebuffer(N.FRAMEBUFFER,c);let o=e.textures[s],l=o.format,u=o.type;if(e.textures.length>1&&N.readBuffer(N.COLOR_ATTACHMENT0+s),!we.textureFormatReadable(l))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.`);if(!we.textureTypeReadable(u))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.`);let d=N.createBuffer();N.bindBuffer(N.PIXEL_PACK_BUFFER,d),N.bufferData(N.PIXEL_PACK_BUFFER,a.byteLength,N.STREAM_READ),N.readPixels(t,n,r,i,ze.convert(l),ze.convert(u),0);let f=A===null?null:F.get(A).__webglFramebuffer;P.bindFramebuffer(N.FRAMEBUFFER,f);let p=N.fenceSync(N.SYNC_GPU_COMMANDS_COMPLETE,0);return N.flush(),await ts(N,p,4),N.bindBuffer(N.PIXEL_PACK_BUFFER,d),N.getBufferSubData(N.PIXEL_PACK_BUFFER,0,a),N.deleteBuffer(d),N.deleteSync(p),a}else throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.`)},this.copyFramebufferToTexture=function(e,t=null,n=0){let r=2**-n,i=Math.floor(e.image.width*r),a=Math.floor(e.image.height*r),o=t===null?0:t.x,s=t===null?0:t.y;I.setTexture2D(e,0),N.copyTexSubImage2D(N.TEXTURE_2D,n,0,0,o,s,i,a),P.unbindTexture()};let pt=N.createFramebuffer(),mt=N.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,a=0){let o,s,c,l,u,d,f,p,m,h=e.isCompressedTexture?e.mipmaps[a]:e.image;if(n!==null)o=n.max.x-n.min.x,s=n.max.y-n.min.y,c=n.isBox3?n.max.z-n.min.z:1,l=n.min.x,u=n.min.y,d=n.isBox3?n.min.z:0;else{let t=2**-i;o=Math.floor(h.width*t),s=Math.floor(h.height*t),c=e.isDataArrayTexture?h.depth:e.isData3DTexture?Math.floor(h.depth*t):1,l=0,u=0,d=0}r===null?(f=0,p=0,m=0):(f=r.x,p=r.y,m=r.z);let g=ze.convert(t.format),_=ze.convert(t.type),v;t.isData3DTexture?(I.setTexture3D(t,0),v=N.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(I.setTexture2DArray(t,0),v=N.TEXTURE_2D_ARRAY):(I.setTexture2D(t,0),v=N.TEXTURE_2D),P.activeTexture(N.TEXTURE0),P.pixelStorei(N.UNPACK_FLIP_Y_WEBGL,t.flipY),P.pixelStorei(N.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),P.pixelStorei(N.UNPACK_ALIGNMENT,t.unpackAlignment);let y=P.getParameter(N.UNPACK_ROW_LENGTH),b=P.getParameter(N.UNPACK_IMAGE_HEIGHT),x=P.getParameter(N.UNPACK_SKIP_PIXELS),S=P.getParameter(N.UNPACK_SKIP_ROWS),C=P.getParameter(N.UNPACK_SKIP_IMAGES);P.pixelStorei(N.UNPACK_ROW_LENGTH,h.width),P.pixelStorei(N.UNPACK_IMAGE_HEIGHT,h.height),P.pixelStorei(N.UNPACK_SKIP_PIXELS,l),P.pixelStorei(N.UNPACK_SKIP_ROWS,u),P.pixelStorei(N.UNPACK_SKIP_IMAGES,d);let w=e.isDataArrayTexture||e.isData3DTexture,T=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){let n=F.get(e),r=F.get(t),h=F.get(n.__renderTarget),g=F.get(r.__renderTarget);P.bindFramebuffer(N.READ_FRAMEBUFFER,h.__webglFramebuffer),P.bindFramebuffer(N.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n<c;n++)w&&(N.framebufferTextureLayer(N.READ_FRAMEBUFFER,N.COLOR_ATTACHMENT0,F.get(e).__webglTexture,i,d+n),N.framebufferTextureLayer(N.DRAW_FRAMEBUFFER,N.COLOR_ATTACHMENT0,F.get(t).__webglTexture,a,m+n)),N.blitFramebuffer(l,u,o,s,f,p,o,s,N.DEPTH_BUFFER_BIT,N.NEAREST);P.bindFramebuffer(N.READ_FRAMEBUFFER,null),P.bindFramebuffer(N.DRAW_FRAMEBUFFER,null)}else if(i!==0||e.isRenderTargetTexture||F.has(e)){let n=F.get(e),r=F.get(t);P.bindFramebuffer(N.READ_FRAMEBUFFER,pt),P.bindFramebuffer(N.DRAW_FRAMEBUFFER,mt);for(let e=0;e<c;e++)w?N.framebufferTextureLayer(N.READ_FRAMEBUFFER,N.COLOR_ATTACHMENT0,n.__webglTexture,i,d+e):N.framebufferTexture2D(N.READ_FRAMEBUFFER,N.COLOR_ATTACHMENT0,N.TEXTURE_2D,n.__webglTexture,i),T?N.framebufferTextureLayer(N.DRAW_FRAMEBUFFER,N.COLOR_ATTACHMENT0,r.__webglTexture,a,m+e):N.framebufferTexture2D(N.DRAW_FRAMEBUFFER,N.COLOR_ATTACHMENT0,N.TEXTURE_2D,r.__webglTexture,a),i===0?T?N.copyTexSubImage3D(v,a,f,p,m+e,l,u,o,s):N.copyTexSubImage2D(v,a,f,p,l,u,o,s):N.blitFramebuffer(l,u,o,s,f,p,o,s,N.COLOR_BUFFER_BIT,N.NEAREST);P.bindFramebuffer(N.READ_FRAMEBUFFER,null),P.bindFramebuffer(N.DRAW_FRAMEBUFFER,null)}else T?e.isDataTexture||e.isData3DTexture?N.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h.data):t.isCompressedArrayTexture?N.compressedTexSubImage3D(v,a,f,p,m,o,s,c,g,h.data):N.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h):e.isDataTexture?N.texSubImage2D(N.TEXTURE_2D,a,f,p,o,s,g,_,h.data):e.isCompressedTexture?N.compressedTexSubImage2D(N.TEXTURE_2D,a,f,p,h.width,h.height,g,h.data):N.texSubImage2D(N.TEXTURE_2D,a,f,p,o,s,g,_,h);P.pixelStorei(N.UNPACK_ROW_LENGTH,y),P.pixelStorei(N.UNPACK_IMAGE_HEIGHT,b),P.pixelStorei(N.UNPACK_SKIP_PIXELS,x),P.pixelStorei(N.UNPACK_SKIP_ROWS,S),P.pixelStorei(N.UNPACK_SKIP_IMAGES,C),a===0&&t.generateMipmaps&&N.generateMipmap(v),P.unbindTexture()},this.initRenderTarget=function(e){F.get(e).__webglFramebuffer===void 0&&I.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?I.setTextureCube(e,0):e.isData3DTexture?I.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?I.setTexture2DArray(e,0):I.setTexture2D(e,0),P.unbindTexture()},this.resetState=function(){O=0,k=0,A=null,P.reset(),Be.reset()},typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}get coordinateSystem(){return Go}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=Ls._getDrawingBufferColorSpace(e),t.unpackColorSpace=Ls._getUnpackColorSpace()}},Tg=class{engine;entries=new Map;loader;constructor(e,t=null){this.engine=t,this.loader=e??((e,t)=>new uf().load(e,()=>t?.onLoad?.(),void 0,e=>t?.onError?.(e)))}load(e){for(let[t,n]of Object.entries(e)){let e=n.type;if(e!==`texture`&&e!==`spritesheet`)throw new L(`BAD_FORMAT`,`Asset '${t}': "type" must be 'texture' or 'spritesheet', got ${JSON.stringify(e)}.`);if(typeof n.url!=`string`||n.url===``)throw new L(`BAD_FORMAT`,`Asset '${t}': "url" must be a non-empty string.`);let r,i;if(e===`spritesheet`){if(typeof n.frameWidth!=`number`||typeof n.frameHeight!=`number`)throw new L(`BAD_FORMAT`,`Asset '${t}': spritesheets need numeric "frameWidth" and "frameHeight".`);r=n.frameWidth,i=n.frameHeight}let a=this.entries.get(t),o={status:`loading`},s=this.loader(n.url,{onLoad:()=>{o.status=`ready`},onError:e=>{o.status=`error`,o.error=e instanceof Error?e.message:`could not load ${n.url}`,Nt(this.engine,`error`,`[incanto] failed to load texture '${t}' (${n.url}):`,e)}});a&&a.texture!==s&&a.texture.dispose(),s.colorSpace=Ro,n.filter===`nearest`?(s.magFilter=fa,s.minFilter=fa,s.generateMipmaps=!1):s.magFilter=ha,s.needsUpdate=!0,this.entries.set(t,{texture:s,type:e,frameWidth:r,frameHeight:i,url:n.url,state:o})}}errors(){let e=[];for(let[t,n]of this.entries)n.state.status===`error`&&e.push({ref:`$${t}`,url:n.url,error:n.state.error??`could not load ${n.url}`});return e}status(e){return this.entries.get(e)?.state.status}getTexture(e){return this.resolve(e).texture}getSheet(e){let t=this.resolve(e);if(t.type!==`spritesheet`)throw new L(`BAD_FORMAT`,`Asset '${e}' is a plain texture; a spritesheet (with frameWidth/frameHeight) is required here.`);return{texture:t.texture,frameWidth:t.frameWidth,frameHeight:t.frameHeight}}resolve(e){if(!e.startsWith(`$`))throw new L(`UNKNOWN_ASSET`,`Asset reference '${e}' must use the '$key' form (e.g. '$${e}').`);let t=this.entries.get(e.slice(1));if(!t)throw new L(`UNKNOWN_ASSET`,`Unknown asset '${e}'. Declared assets: [${[...this.entries.keys()].join(`, `)}].`);return t}};function Eg(e){let t=[],n=e=>{e instanceof Kn&&e.loadError&&t.push({ref:e.getPath(),url:e.src,error:e.loadError});for(let t of e.children)n(t)};return e&&n(e),t}function Dg(e){let t=e?.style;t&&(t.touchAction=`none`,t.userSelect=`none`,t.webkitUserSelect=`none`,t.webkitTouchCallout=`none`,t.webkitTapHighlightColor=`transparent`)}function Og(e,t,n){return(.2126*e+.7152*t+.0722*n)/255}var kg=.012,Ag=.004;function jg(e,t,n,r,i){let a=new Uint8Array(r*i*3);for(let o=0;o<i;o++)for(let s=0;s<r;s++){let c=Math.floor(s*t/r),l=Math.max(c+1,Math.floor((s+1)*t/r)),u=Math.floor(o*n/i),d=Math.max(u+1,Math.floor((o+1)*n/i)),f=0,p=0,m=0,h=0;for(let n=u;n<d;n++)for(let r=c;r<l;r++){let i=(n*t+r)*4;f+=e[i]??0,p+=e[i+1]??0,m+=e[i+2]??0,h+=1}let g=(o*r+s)*3;a[g]=Math.round(f/h),a[g+1]=Math.round(p/h),a[g+2]=Math.round(m/h)}return a}var Mg=24;function Ng(e,t,n){let r=0,i=0,a=0,o=0,s=(n,s)=>{let c=(s*t+n)*4;r+=e[c],i+=e[c+1],a+=e[c+2],o+=1};for(let e=0;e<t;e++)s(e,0),s(e,n-1);for(let e=1;e<n-1;e++)s(0,e),s(t-1,e);return o===0?[0,0,0]:[r/o,i/o,a/o]}function Pg(e,t,n){let r=Ng(e,t,n),i=(n,r)=>{let i=(r*t+n)*4;return[e[i],e[i+1],e[i+2]]},a=(e,t)=>Math.abs(e[0]-t[0])+Math.abs(e[1]-t[1])+Math.abs(e[2]-t[2]),o=t,s=n,c=-1,l=-1,u=0;for(let e=0;e<n;e++){let n=i(0,e),d=i(t-1,e),f=a(n,d)>Mg?a(n,r)<=a(d,r)?n:d:[(n[0]+d[0])/2,(n[1]+d[1])/2,(n[2]+d[2])/2];for(let n=0;n<t;n++)a(i(n,e),f)<Mg||(u+=1,n<o&&(o=n),n>c&&(c=n),e<s&&(s=e),e>l&&(l=e))}return c<0?null:{box:{x:o,y:s,w:c-o+1,h:l-s+1},coverage:u/(t*n),clipped:o===0||s===0||c===t-1||l===n-1}}function Fg(e,t,n,r={}){let[i,a]=r.grid??[16,9],o=jg(e,t,n,i,a),s=[],c=0,l=0,u=1;for(let e=0;e<a;e++){let t=[];for(let n=0;n<i;n++){let r=(e*i+n)*3,a=[o[r],o[r+1],o[r+2]],s=Og(a[0],a[1],a[2]);c+=s,l=Math.max(l,s),u=Math.min(u,s),t.push(a)}s.push(t)}let d=i*a,f=c/d,p=l<=kg;return{width:t,height:n,black:p,uniform:l-u<Ag,meanLuma:Math.round(f*1e3)/1e3,grid:s,subject:p?null:Pg(e,t,n)}}function Ig(e){return[]}var Lg=`modulepreload`,Rg=function(e,t){return new URL(e,t).href},zg={},Bg=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=Rg(t,n),t in zg)return;zg[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:Lg,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Vg=160;function Hg(e=``,t=`#0b0d14`){if(typeof document>`u`)return{lift:()=>{}};let n=document.createElement(`div`);if(n.dataset.incantoSwitch=``,n.style.cssText=`position:fixed;inset:0;z-index:2147483646;background:${t};display:flex;align-items:center;justify-content:center;opacity:0;transition:opacity ${Vg}ms ease;pointer-events:auto;`,e){let t=document.createElement(`div`);t.textContent=e,t.style.cssText=`font:13px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:#5d6680;letter-spacing:0.04em;`,n.appendChild(t)}document.body.appendChild(n),requestAnimationFrame(()=>{n.style.opacity=`1`});let r=!1;return{lift(){r||(r=!0,requestAnimationFrame(()=>{n.style.opacity=`0`,setTimeout(()=>n.remove(),200)}))}}}async function Ug(e=Vg){typeof requestAnimationFrame==`function`&&await new Promise(t=>setTimeout(t,e))}function Wg(e){return async(t,n)=>{let r=n||e,i=new URLSearchParams({tags:t.tags.join(`,`),page:String(t.page??1),limit:String(t.limit??24)});t.keyword?.trim()&&i.set(`keyword`,t.keyword.trim());let a=await fetch(`/api/library?${i}`,{headers:r?{"x-incanto-v8-token":r}:{}});if(a.status===401){let e=await a.json().catch(()=>({})),t=Error(e.error??`the asset library needs a Verse8 access token`);throw t.needsToken=!0,t}if(!a.ok)throw Error(`asset library: HTTP ${a.status}`);return await a.json()}}async function Gg(){try{let e=await fetch(`/api/scenes`);if(!e.ok)return null;let t=await e.json();return Array.isArray(t)?t:null}catch{return null}}function Kg(e,t){let n=typeof t.name==`string`?t.name:null;if(!e||!n)return null;let r=e.filter(e=>e.scene?.name===n);return r.length===1?r[0].rel:null}function qg(e,t){let n=typeof t.name==`string`?t.name:`(unnamed)`;if(!e)return`Save: this dev server does not serve the project's scenes, so there is no file to write. ${Jg}`;let r=e.filter(e=>e.scene?.name===n);return r.length>1?`Save: ${r.length} scenes in this project are named "${n}" (${r.map(e=>e.rel).join(`, `)}), so which file this is cannot be told from the scene alone. Open the one you mean from the scene browser and save there.`:`Save: no file in this project contains a scene named "${n}", so there is nowhere to write it. Open a scene from the scene browser first, or pass editor: { save } to createGame so the game decides where edits go.`}var Jg=`this dev server does not serve the project's scenes yet. Add incantoScenes() to vite.config.ts and restart:
|
|
4106
|
+
}`,gg=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new ud(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new Dd({vertexShader:mg,fragmentShader:hg,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new iu(new _d(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},_g=class extends rs{constructor(e,t){super();let n=this,r=null,i=1,a=null,o=`local-floor`,s=1,c=null,l=null,u=null,d=null,f=null,p=null,m=typeof XRWebGLBinding<`u`,h=new gg,g={},_=t.getContextAttributes(),v=null,y=null,b=[],x=[],S=new H,C=null,w=new Cf;w.viewport=new Js;let T=new Cf;T.viewport=new Js;let E=[w,T],D=new Rf,O=null,k=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=b[e];return t===void 0&&(t=new Oc,b[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=b[e];return t===void 0&&(t=new Oc,b[e]=t),t.getGripSpace()},this.getHand=function(e){let t=b[e];return t===void 0&&(t=new Oc,b[e]=t),t.getHandSpace()};function A(e){let t=x.indexOf(e.inputSource);if(t===-1)return;let n=b[t];n!==void 0&&(n.update(e.inputSource,e.frame,c||a),n.dispatchEvent({type:e.type,data:e.inputSource}))}function ee(){r.removeEventListener(`select`,A),r.removeEventListener(`selectstart`,A),r.removeEventListener(`selectend`,A),r.removeEventListener(`squeeze`,A),r.removeEventListener(`squeezestart`,A),r.removeEventListener(`squeezeend`,A),r.removeEventListener(`end`,ee),r.removeEventListener(`inputsourceschange`,te);for(let e=0;e<b.length;e++){let t=x[e];t!==null&&(x[e]=null,b[e].disconnect(t))}O=null,k=null,h.reset();for(let e in g)delete g[e];e.setRenderTarget(v),f=null,d=null,u=null,r=null,y=null,ce.stop(),n.isPresenting=!1,e.setPixelRatio(C),e.setSize(S.width,S.height,!1),n.dispatchEvent({type:`sessionend`})}this.setFramebufferScaleFactor=function(e){i=e,n.isPresenting===!0&&B(`WebXRManager: Cannot change framebuffer scale while presenting.`)},this.setReferenceSpaceType=function(e){o=e,n.isPresenting===!0&&B(`WebXRManager: Cannot change reference space type while presenting.`)},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(e){c=e},this.getBaseLayer=function(){return d===null?f:d},this.getBinding=function(){return u===null&&m&&(u=new XRWebGLBinding(r,t)),u},this.getFrame=function(){return p},this.getSession=function(){return r},this.setSession=async function(l){if(r=l,r!==null){if(v=e.getRenderTarget(),r.addEventListener(`select`,A),r.addEventListener(`selectstart`,A),r.addEventListener(`selectend`,A),r.addEventListener(`squeeze`,A),r.addEventListener(`squeezestart`,A),r.addEventListener(`squeezeend`,A),r.addEventListener(`end`,ee),r.addEventListener(`inputsourceschange`,te),_.xrCompatible!==!0&&await t.makeXRCompatible(),C=e.getPixelRatio(),e.getSize(S),m&&`createProjectionLayer`in XRWebGLBinding.prototype){let n=null,a=null,o=null;_.depth&&(o=_.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=_.stencil?Fa:Pa,a=_.stencil?Oa:Ca);let s={colorFormat:t.RGBA8,depthFormat:o,scaleFactor:i};u=this.getBinding(),d=u.createProjectionLayer(s),r.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),y=new Xs(d.textureWidth,d.textureHeight,{format:Na,type:va,depthTexture:new cd(d.textureWidth,d.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{let n={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:i};f=new XRWebGLLayer(r,t,n),r.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new Xs(f.framebufferWidth,f.framebufferHeight,{format:Na,type:va,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(s),c=null,a=await r.requestReferenceSpace(o),ce.setContext(r),ce.start(),n.isPresenting=!0,n.dispatchEvent({type:`sessionstart`})}},this.getEnvironmentBlendMode=function(){if(r!==null)return r.environmentBlendMode},this.getDepthTexture=function(){return h.getDepthTexture()};function te(e){for(let t=0;t<e.removed.length;t++){let n=e.removed[t],r=x.indexOf(n);r>=0&&(x[r]=null,b[r].disconnect(n))}for(let t=0;t<e.added.length;t++){let n=e.added[t],r=x.indexOf(n);if(r===-1){for(let e=0;e<b.length;e++)if(e>=x.length){x.push(n),r=e;break}else if(x[e]===null){x[e]=n,r=e;break}if(r===-1)break}let i=b[r];i&&i.connect(n)}}let ne=new W,re=new W;function ie(e,t,n){ne.setFromMatrixPosition(t.matrixWorld),re.setFromMatrixPosition(n.matrixWorld);let r=ne.distanceTo(re),i=t.projectionMatrix.elements,a=n.projectionMatrix.elements,o=i[14]/(i[10]-1),s=i[14]/(i[10]+1),c=(i[9]+1)/i[5],l=(i[9]-1)/i[5],u=(i[8]-1)/i[0],d=(a[8]+1)/a[0],f=o*u,p=o*d,m=r/(-u+d),h=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(h),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),i[10]===-1)e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{let t=o+m,n=s+m,i=f-h,a=p+(r-h),u=c*s/n*t,d=l*s/n*t;e.projectionMatrix.makePerspective(i,a,u,d,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}function ae(e,t){t===null?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(r===null)return;let t=e.near,n=e.far;h.texture!==null&&(h.depthNear>0&&(t=h.depthNear),h.depthFar>0&&(n=h.depthFar)),D.near=T.near=w.near=t,D.far=T.far=w.far=n,(O!==D.near||k!==D.far)&&(r.updateRenderState({depthNear:D.near,depthFar:D.far}),O=D.near,k=D.far),D.layers.mask=e.layers.mask|6,w.layers.mask=D.layers.mask&-5,T.layers.mask=D.layers.mask&-3;let i=e.parent,a=D.cameras;ae(D,i);for(let e=0;e<a.length;e++)ae(a[e],i);a.length===2?ie(D,w,T):D.projectionMatrix.copy(w.projectionMatrix),j(e,D,i)};function j(e,t,n){n===null?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld)),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=ss*2*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}this.getCamera=function(){return D},this.getFoveation=function(){if(!(d===null&&f===null))return s},this.setFoveation=function(e){s=e,d!==null&&(d.fixedFoveation=e),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=e)},this.hasDepthSensing=function(){return h.texture!==null},this.getDepthSensingMesh=function(){return h.getMesh(D)},this.getCameraTexture=function(e){return g[e]};let oe=null;function se(t,i){if(l=i.getViewerPose(c||a),p=i,l!==null){let t=l.views;f!==null&&(e.setRenderTargetFramebuffer(y,f.framebuffer),e.setRenderTarget(y));let i=!1;t.length!==D.cameras.length&&(D.cameras.length=0,i=!0);for(let n=0;n<t.length;n++){let r=t[n],a=null;if(f!==null)a=f.getViewport(r);else{let t=u.getViewSubImage(d,r);a=t.viewport,n===0&&(e.setRenderTargetTextures(y,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(y))}let o=E[n];o===void 0&&(o=new Cf,o.layers.enable(n),o.viewport=new Js,E[n]=o),o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale),o.projectionMatrix.fromArray(r.projectionMatrix),o.projectionMatrixInverse.copy(o.projectionMatrix).invert(),o.viewport.set(a.x,a.y,a.width,a.height),n===0&&(D.matrix.copy(o.matrix),D.matrix.decompose(D.position,D.quaternion,D.scale)),i===!0&&D.cameras.push(o)}let a=r.enabledFeatures;if(a&&a.includes(`depth-sensing`)&&r.depthUsage==`gpu-optimized`&&m){u=n.getBinding();let e=u.getDepthInformation(t[0]);e&&e.isValid&&e.texture&&h.init(e,r.renderState)}if(a&&a.includes(`camera-access`)&&m){e.state.unbindTexture(),u=n.getBinding();for(let e=0;e<t.length;e++){let n=t[e].camera;if(n){let e=g[n];e||(e=new ud,g[n]=e);let t=u.getCameraImage(n);e.sourceTexture=t}}}}for(let e=0;e<b.length;e++){let t=x[e],n=b[e];t!==null&&n!==void 0&&n.update(t,i,c||a)}oe&&oe(t,i),i.detectedPlanes&&n.dispatchEvent({type:`planesdetected`,data:i}),p=null}let ce=new lp;ce.setAnimationLoop(se),this.setAnimationLoop=function(e){oe=e},this.dispose=function(){}}},vg=new K,yg=new G;yg.set(-1,0,0,0,1,0,0,0,1);function bg(e,t){function n(e,t){e.matrixAutoUpdate===!0&&e.updateMatrix(),t.value.copy(e.matrix)}function r(t,n){n.color.getRGB(t.fogColor.value,Cd(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)}function i(e,t,n,r,i){t.isNodeMaterial?t.uniformsNeedUpdate=!1:t.isMeshBasicMaterial?a(e,t):t.isMeshLambertMaterial?(a(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshToonMaterial?(a(e,t),d(e,t)):t.isMeshPhongMaterial?(a(e,t),u(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshStandardMaterial?(a(e,t),f(e,t),t.isMeshPhysicalMaterial&&p(e,t,i)):t.isMeshMatcapMaterial?(a(e,t),m(e,t)):t.isMeshDepthMaterial?a(e,t):t.isMeshDistanceMaterial?(a(e,t),h(e,t)):t.isMeshNormalMaterial?a(e,t):t.isLineBasicMaterial?(o(e,t),t.isLineDashedMaterial&&s(e,t)):t.isPointsMaterial?c(e,t,n,r):t.isSpriteMaterial?l(e,t):t.isShadowMaterial?(e.color.value.copy(t.color),e.opacity.value=t.opacity):t.isShaderMaterial&&(t.uniformsNeedUpdate=!1)}function a(e,r){e.opacity.value=r.opacity,r.color&&e.diffuse.value.copy(r.color),r.emissive&&e.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity),r.map&&(e.map.value=r.map,n(r.map,e.mapTransform)),r.alphaMap&&(e.alphaMap.value=r.alphaMap,n(r.alphaMap,e.alphaMapTransform)),r.bumpMap&&(e.bumpMap.value=r.bumpMap,n(r.bumpMap,e.bumpMapTransform),e.bumpScale.value=r.bumpScale,r.side===1&&(e.bumpScale.value*=-1)),r.normalMap&&(e.normalMap.value=r.normalMap,n(r.normalMap,e.normalMapTransform),e.normalScale.value.copy(r.normalScale),r.side===1&&e.normalScale.value.negate()),r.displacementMap&&(e.displacementMap.value=r.displacementMap,n(r.displacementMap,e.displacementMapTransform),e.displacementScale.value=r.displacementScale,e.displacementBias.value=r.displacementBias),r.emissiveMap&&(e.emissiveMap.value=r.emissiveMap,n(r.emissiveMap,e.emissiveMapTransform)),r.specularMap&&(e.specularMap.value=r.specularMap,n(r.specularMap,e.specularMapTransform)),r.alphaTest>0&&(e.alphaTest.value=r.alphaTest);let i=t.get(r),a=i.envMap,o=i.envMapRotation;a&&(e.envMap.value=a,e.envMapRotation.value.setFromMatrix4(vg.makeRotationFromEuler(o)).transpose(),a.isCubeTexture&&a.isRenderTargetTexture===!1&&e.envMapRotation.value.premultiply(yg),e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}function o(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}function s(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}function c(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=i*.5,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function l(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function u(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}function d(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}function f(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform)),e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform)),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}function p(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform))),t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===1&&e.clearcoatNormalScale.value.negate())),t.dispersion>0&&(e.dispersion.value=t.dispersion),t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform))),t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor)),t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform))),e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform)),t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}function m(e,t){t.matcap&&(e.matcap.value=t.matcap)}function h(e,n){let r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function xg(e,t,n,r){let i={},a={},o=[],s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(e,t){let n=t.program;r.uniformBlockBinding(e,n)}function l(e,n){let o=i[e.id];o===void 0&&(m(e),o=u(e),i[e.id]=o,e.addEventListener(`dispose`,g));let s=n.program;r.updateUBOMapping(e,s);let c=t.render.frame;a[e.id]!==c&&(f(e),a[e.id]=c)}function u(t){let n=d();t.__bindingPointIndex=n;let r=e.createBuffer(),i=t.__size,a=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,r),e.bufferData(e.UNIFORM_BUFFER,i,a),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,r),r}function d(){for(let e=0;e<s;e++)if(o.indexOf(e)===-1)return o.push(e),e;return V(`WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.`),0}function f(t){let n=i[t.id],r=t.uniforms,a=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,n);for(let t=0,n=r.length;t<n;t++){let n=Array.isArray(r[t])?r[t]:[r[t]];for(let r=0,i=n.length;r<i;r++){let i=n[r];if(p(i,t,r,a)===!0){let t=i.__offset,n=Array.isArray(i.value)?i.value:[i.value],r=0;for(let a=0;a<n.length;a++){let o=n[a],s=h(o);typeof o==`number`||typeof o==`boolean`?(i.__data[0]=o,e.bufferSubData(e.UNIFORM_BUFFER,t+r,i.__data)):o.isMatrix3?(i.__data[0]=o.elements[0],i.__data[1]=o.elements[1],i.__data[2]=o.elements[2],i.__data[3]=0,i.__data[4]=o.elements[3],i.__data[5]=o.elements[4],i.__data[6]=o.elements[5],i.__data[7]=0,i.__data[8]=o.elements[6],i.__data[9]=o.elements[7],i.__data[10]=o.elements[8],i.__data[11]=0):ArrayBuffer.isView(o)?i.__data.set(new o.constructor(o.buffer,o.byteOffset,i.__data.length)):(o.toArray(i.__data,r),r+=s.storage/Float32Array.BYTES_PER_ELEMENT)}e.bufferSubData(e.UNIFORM_BUFFER,t,i.__data)}}}e.bindBuffer(e.UNIFORM_BUFFER,null)}function p(e,t,n,r){let i=e.value,a=t+`_`+n;if(r[a]===void 0)return typeof i==`number`||typeof i==`boolean`?r[a]=i:ArrayBuffer.isView(i)?r[a]=i.slice():r[a]=i.clone(),!0;{let e=r[a];if(typeof i==`number`||typeof i==`boolean`){if(e!==i)return r[a]=i,!0}else if(ArrayBuffer.isView(i))return!0;else if(e.equals(i)===!1)return e.copy(i),!0}return!1}function m(e){let t=e.uniforms,n=0;for(let e=0,r=t.length;e<r;e++){let r=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0,t=r.length;e<t;e++){let t=r[e],i=Array.isArray(t.value)?t.value:[t.value];for(let e=0,r=i.length;e<r;e++){let r=i[e],a=h(r),o=n%16,s=o%a.boundary,c=o+s;n+=s,c!==0&&16-c<a.storage&&(n+=16-c),t.__data=new Float32Array(a.storage/Float32Array.BYTES_PER_ELEMENT),t.__offset=n,n+=a.storage}}}let r=n%16;return r>0&&(n+=16-r),e.__size=n,e.__cache={},this}function h(e){let t={boundary:0,storage:0};return typeof e==`number`||typeof e==`boolean`?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?B(`WebGLRenderer: Texture samplers can not be part of an uniforms group.`):ArrayBuffer.isView(e)?(t.boundary=16,t.storage=e.byteLength):B(`WebGLRenderer: Unsupported uniform value type.`,e),t}function g(t){let n=t.target;n.removeEventListener(`dispose`,g);let r=o.indexOf(n.__bindingPointIndex);o.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete a[n.id]}function _(){for(let t in i)e.deleteBuffer(i[t]);o=[],i={},a={}}return{bind:c,update:l,dispose:_}}var Sg=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]),Cg=null;function wg(){return Cg===null&&(Cg=new vu(Sg,16,16,Ra,Ta),Cg.name=`DFG_LUT`,Cg.minFilter=ha,Cg.magFilter=ha,Cg.wrapS=ua,Cg.wrapT=ua,Cg.generateMipmaps=!1,Cg.needsUpdate=!0),Cg}var Tg=class{constructor(e={}){let{canvas:t=Yo(),context:n=null,depth:r=!0,stencil:i=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:s=!0,preserveDrawingBuffer:c=!1,powerPreference:l=`default`,failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=va}=e;this.isWebGLRenderer=!0;let p;if(n!==null){if(typeof WebGLRenderingContext<`u`&&n instanceof WebGLRenderingContext)throw Error(`THREE.WebGLRenderer: WebGL 1 is not supported since r163.`);p=n.getContextAttributes().alpha}else p=a;let m=f,h=new Set([Ba,za,La]),g=new Set([va,Ca,xa,Oa,Ea,Da]),_=new Uint32Array(4),v=new Int32Array(4),y=new W,b=null,x=null,S=[],C=[],w=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let T=this,E=!1,D=null;this._outputColorSpace=Ro;let O=0,k=0,A=null,ee=-1,te=null,ne=new Js,re=new Js,ie=null,ae=new q(0),j=0,oe=t.width,se=t.height,ce=1,le=null,ue=null,M=new Js(0,0,oe,se),de=new Js(0,0,oe,se),fe=!1,pe=new Ru,me=!1,he=!1,ge=new K,_e=new W,ve=new Js,ye={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},be=!1;function xe(){return A===null?ce:1}let N=n;function Se(e,n){return t.getContext(e,n)}try{let e={alpha:!0,depth:r,stencil:i,antialias:o,premultipliedAlpha:s,preserveDrawingBuffer:c,powerPreference:l,failIfMajorPerformanceCaveat:u};if(`setAttribute`in t&&t.setAttribute(`data-engine`,`three.js r184`),t.addEventListener(`webglcontextlost`,We,!1),t.addEventListener(`webglcontextrestored`,Ge,!1),t.addEventListener(`webglcontextcreationerror`,Ke,!1),N===null){let t=`webgl2`;if(N=Se(t,e),N===null)throw Se(t)?Error(`Error creating WebGL context with your selected attributes.`):Error(`Error creating WebGL context.`)}}catch(e){throw V(`WebGLRenderer: `+e.message),e}let Ce,we,P,Te,F,I,L,Ee,De,Oe,ke,Ae,je,Me,Ne,Pe,Fe,Ie,Le,Re,ze,Be,Ve;function He(){Ce=new Up(N),Ce.init(),ze=new pg(N,Ce),we=new yp(N,Ce,e,ze),P=new dg(N,Ce),we.reversedDepthBuffer&&d&&P.buffers.depth.setReversed(!0),Te=new Kp(N),F=new Gh,I=new fg(N,Ce,P,F,we,ze,Te),L=new Hp(T),Ee=new up(N),Be=new _p(N,Ee),De=new Wp(N,Ee,Te,Be),Oe=new Jp(N,De,Ee,Be,Te),Ie=new qp(N,we,I),Ne=new bp(F),ke=new Wh(T,L,Ce,we,Be,Ne),Ae=new bg(T,F),je=new Yh,Me=new ng(Ce),Fe=new gp(T,L,P,Oe,p,s),Pe=new ug(T,Oe,we),Ve=new xg(N,Te,we,P),Le=new vp(N,Ce,Te),Re=new Gp(N,Ce,Te),Te.programs=ke.programs,T.capabilities=we,T.extensions=Ce,T.properties=F,T.renderLists=je,T.shadowMap=Pe,T.state=P,T.info=Te}He(),m!==1009&&(w=new Xp(m,t.width,t.height,r,i));let Ue=new _g(T,N);this.xr=Ue,this.getContext=function(){return N},this.getContextAttributes=function(){return N.getContextAttributes()},this.forceContextLoss=function(){let e=Ce.get(`WEBGL_lose_context`);e&&e.loseContext()},this.forceContextRestore=function(){let e=Ce.get(`WEBGL_lose_context`);e&&e.restoreContext()},this.getPixelRatio=function(){return ce},this.setPixelRatio=function(e){e!==void 0&&(ce=e,this.setSize(oe,se,!1))},this.getSize=function(e){return e.set(oe,se)},this.setSize=function(e,n,r=!0){if(Ue.isPresenting){B(`WebGLRenderer: Can't change size while VR device is presenting.`);return}oe=e,se=n,t.width=Math.floor(e*ce),t.height=Math.floor(n*ce),r===!0&&(t.style.width=e+`px`,t.style.height=n+`px`),w!==null&&w.setSize(t.width,t.height),this.setViewport(0,0,e,n)},this.getDrawingBufferSize=function(e){return e.set(oe*ce,se*ce).floor()},this.setDrawingBufferSize=function(e,n,r){oe=e,se=n,ce=r,t.width=Math.floor(e*r),t.height=Math.floor(n*r),this.setViewport(0,0,e,n)},this.setEffects=function(e){if(m===1009){V(`THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.`);return}if(e){for(let t=0;t<e.length;t++)if(e[t].isOutputPass===!0){B(`THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.`);break}}w.setEffects(e||[])},this.getCurrentViewport=function(e){return e.copy(ne)},this.getViewport=function(e){return e.copy(M)},this.setViewport=function(e,t,n,r){e.isVector4?M.set(e.x,e.y,e.z,e.w):M.set(e,t,n,r),P.viewport(ne.copy(M).multiplyScalar(ce).round())},this.getScissor=function(e){return e.copy(de)},this.setScissor=function(e,t,n,r){e.isVector4?de.set(e.x,e.y,e.z,e.w):de.set(e,t,n,r),P.scissor(re.copy(de).multiplyScalar(ce).round())},this.getScissorTest=function(){return fe},this.setScissorTest=function(e){P.setScissorTest(fe=e)},this.setOpaqueSort=function(e){le=e},this.setTransparentSort=function(e){ue=e},this.getClearColor=function(e){return e.copy(Fe.getClearColor())},this.setClearColor=function(){Fe.setClearColor(...arguments)},this.getClearAlpha=function(){return Fe.getClearAlpha()},this.setClearAlpha=function(){Fe.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,n=!0){let r=0;if(e){let e=!1;if(A!==null){let t=A.texture.format;e=h.has(t)}if(e){let e=A.texture.type,t=g.has(e),n=Fe.getClearColor(),r=Fe.getClearAlpha(),i=n.r,a=n.g,o=n.b;t?(_[0]=i,_[1]=a,_[2]=o,_[3]=r,N.clearBufferuiv(N.COLOR,0,_)):(v[0]=i,v[1]=a,v[2]=o,v[3]=r,N.clearBufferiv(N.COLOR,0,v))}else r|=N.COLOR_BUFFER_BIT}t&&(r|=N.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),n&&(r|=N.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),r!==0&&N.clear(r)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(e){e.setRenderer(this),D=e},this.dispose=function(){t.removeEventListener(`webglcontextlost`,We,!1),t.removeEventListener(`webglcontextrestored`,Ge,!1),t.removeEventListener(`webglcontextcreationerror`,Ke,!1),Fe.dispose(),je.dispose(),Me.dispose(),F.dispose(),L.dispose(),Oe.dispose(),Be.dispose(),Ve.dispose(),ke.dispose(),Ue.dispose(),Ue.removeEventListener(`sessionstart`,$e),Ue.removeEventListener(`sessionend`,et),R.stop()};function We(e){e.preventDefault(),Qo(`WebGLRenderer: Context Lost.`),E=!0}function Ge(){Qo(`WebGLRenderer: Context Restored.`),E=!1;let e=Te.autoReset,t=Pe.enabled,n=Pe.autoUpdate,r=Pe.needsUpdate,i=Pe.type;He(),Te.autoReset=e,Pe.enabled=t,Pe.autoUpdate=n,Pe.needsUpdate=r,Pe.type=i}function Ke(e){V(`WebGLRenderer: A WebGL context could not be created. Reason: `,e.statusMessage)}function qe(e){let t=e.target;t.removeEventListener(`dispose`,qe),Je(t)}function Je(e){Ye(e),F.remove(e)}function Ye(e){let t=F.get(e).programs;t!==void 0&&(t.forEach(function(e){ke.releaseProgram(e)}),e.isShaderMaterial&&ke.releaseShaderCache(e))}this.renderBufferDirect=function(e,t,n,r,i,a){t===null&&(t=ye);let o=i.isMesh&&i.matrixWorld.determinant()<0,s=lt(e,t,n,r,i);P.setMaterial(r,o);let c=n.index,l=1;if(r.wireframe===!0){if(c=De.getWireframeAttribute(n),c===void 0)return;l=2}let u=n.drawRange,d=n.attributes.position,f=u.start*l,p=(u.start+u.count)*l;a!==null&&(f=Math.max(f,a.start*l),p=Math.min(p,(a.start+a.count)*l)),c===null?d!=null&&(f=Math.max(f,0),p=Math.min(p,d.count)):(f=Math.max(f,0),p=Math.min(p,c.count));let m=p-f;if(m<0||m===1/0)return;Be.setup(i,r,s,n,c);let h,g=Le;if(c!==null&&(h=Ee.get(c),g=Re,g.setIndex(h)),i.isMesh)r.wireframe===!0?(P.setLineWidth(r.wireframeLinewidth*xe()),g.setMode(N.LINES)):g.setMode(N.TRIANGLES);else if(i.isLine){let e=r.linewidth;e===void 0&&(e=1),P.setLineWidth(e*xe()),i.isLineSegments?g.setMode(N.LINES):i.isLineLoop?g.setMode(N.LINE_LOOP):g.setMode(N.LINE_STRIP)}else i.isPoints?g.setMode(N.POINTS):i.isSprite&&g.setMode(N.TRIANGLES);if(i.isBatchedMesh)if(Ce.get(`WEBGL_multi_draw`))g.renderMultiDraw(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount);else{let e=i._multiDrawStarts,t=i._multiDrawCounts,n=i._multiDrawCount,a=c?Ee.get(c).bytesPerElement:1,o=F.get(r).currentProgram.getUniforms();for(let r=0;r<n;r++)o.setValue(N,`_gl_DrawID`,r),g.render(e[r]/a,t[r])}else if(i.isInstancedMesh)g.renderInstances(f,m,i.count);else if(n.isInstancedBufferGeometry){let e=n._maxInstanceCount===void 0?1/0:n._maxInstanceCount,t=Math.min(n.instanceCount,e);g.renderInstances(f,m,t)}else g.render(f,m)};function Xe(e,t,n){e.transparent===!0&&e.side===2&&e.forceSinglePass===!1?(e.side=1,e.needsUpdate=!0,at(e,t,n),e.side=0,e.needsUpdate=!0,at(e,t,n),e.side=2):at(e,t,n)}this.compile=function(e,t,n=null){n===null&&(n=e),x=Me.get(n),x.init(t),C.push(x),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),x.setupLights();let r=new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;let t=e.material;if(t)if(Array.isArray(t))for(let i=0;i<t.length;i++){let a=t[i];Xe(a,n,e),r.add(a)}else Xe(t,n,e),r.add(t)}),x=C.pop(),r},this.compileAsync=function(e,t,n=null){let r=this.compile(e,t,n);return new Promise(t=>{function n(){if(r.forEach(function(e){F.get(e).currentProgram.isReady()&&r.delete(e)}),r.size===0){t(e);return}setTimeout(n,10)}Ce.get(`KHR_parallel_shader_compile`)===null?setTimeout(n,10):n()})};let Ze=null;function Qe(e){Ze&&Ze(e)}function $e(){R.stop()}function et(){R.start()}let R=new lp;R.setAnimationLoop(Qe),typeof self<`u`&&R.setContext(self),this.setAnimationLoop=function(e){Ze=e,Ue.setAnimationLoop(e),e===null?R.stop():R.start()},Ue.addEventListener(`sessionstart`,$e),Ue.addEventListener(`sessionend`,et),this.render=function(e,t){if(t!==void 0&&t.isCamera!==!0){V(`WebGLRenderer.render: camera is not an instance of THREE.Camera.`);return}if(E===!0)return;D!==null&&D.renderStart(e,t);let n=Ue.enabled===!0&&Ue.isPresenting===!0,r=w!==null&&(A===null||n)&&w.begin(T,A);if(e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),Ue.enabled===!0&&Ue.isPresenting===!0&&(w===null||w.isCompositing()===!1)&&(Ue.cameraAutoUpdate===!0&&Ue.updateCamera(t),t=Ue.getCamera()),e.isScene===!0&&e.onBeforeRender(T,e,t,A),x=Me.get(e,C.length),x.init(t),x.state.textureUnits=I.getTextureUnits(),C.push(x),ge.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),pe.setFromProjectionMatrix(ge,Go,t.reversedDepth),he=this.localClippingEnabled,me=Ne.init(this.clippingPlanes,he),b=je.get(e,S.length),b.init(),S.push(b),Ue.enabled===!0&&Ue.isPresenting===!0){let e=T.xr.getDepthSensingMesh();e!==null&&tt(e,t,-1/0,T.sortObjects)}tt(e,t,0,T.sortObjects),b.finish(),T.sortObjects===!0&&b.sort(le,ue),be=Ue.enabled===!1||Ue.isPresenting===!1||Ue.hasDepthSensing()===!1,be&&Fe.addToRenderList(b,e),this.info.render.frame++,me===!0&&Ne.beginShadows();let i=x.state.shadowsArray;if(Pe.render(i,e,t),me===!0&&Ne.endShadows(),this.info.autoReset===!0&&this.info.reset(),(r&&w.hasRenderPass())===!1){let n=b.opaque,r=b.transmissive;if(x.setupLights(),t.isArrayCamera){let i=t.cameras;if(r.length>0)for(let t=0,a=i.length;t<a;t++){let a=i[t];rt(n,r,e,a)}be&&Fe.render(e);for(let t=0,n=i.length;t<n;t++){let n=i[t];nt(b,e,n,n.viewport)}}else r.length>0&&rt(n,r,e,t),be&&Fe.render(e),nt(b,e,t)}A!==null&&k===0&&(I.updateMultisampleRenderTarget(A),I.updateRenderTargetMipmap(A)),r&&w.end(T),e.isScene===!0&&e.onAfterRender(T,e,t),Be.resetDefaultState(),ee=-1,te=null,C.pop(),C.length>0?(x=C[C.length-1],I.setTextureUnits(x.state.textureUnits),me===!0&&Ne.setGlobalState(T.clippingPlanes,x.state.camera)):x=null,S.pop(),b=S.length>0?S[S.length-1]:null,D!==null&&D.renderEnd()};function tt(e,t,n,r){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder;else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLightProbeGrid)x.pushLightProbeGrid(e);else if(e.isLight)x.pushLight(e),e.castShadow&&x.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||pe.intersectsSprite(e)){r&&ve.setFromMatrixPosition(e.matrixWorld).applyMatrix4(ge);let t=Oe.update(e),i=e.material;i.visible&&b.push(e,t,i,n,ve.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||pe.intersectsObject(e))){let t=Oe.update(e),i=e.material;if(r&&(e.boundingSphere===void 0?(t.boundingSphere===null&&t.computeBoundingSphere(),ve.copy(t.boundingSphere.center)):(e.boundingSphere===null&&e.computeBoundingSphere(),ve.copy(e.boundingSphere.center)),ve.applyMatrix4(e.matrixWorld).applyMatrix4(ge)),Array.isArray(i)){let r=t.groups;for(let a=0,o=r.length;a<o;a++){let o=r[a],s=i[o.materialIndex];s&&s.visible&&b.push(e,t,s,n,ve.z,o)}}else i.visible&&b.push(e,t,i,n,ve.z,null)}}let i=e.children;for(let e=0,a=i.length;e<a;e++)tt(i[e],t,n,r)}function nt(e,t,n,r){let{opaque:i,transmissive:a,transparent:o}=e;x.setupLightsView(n),me===!0&&Ne.setGlobalState(T.clippingPlanes,n),r&&P.viewport(ne.copy(r)),i.length>0&&it(i,t,n),a.length>0&&it(a,t,n),o.length>0&&it(o,t,n),P.buffers.depth.setTest(!0),P.buffers.depth.setMask(!0),P.buffers.color.setMask(!0),P.setPolygonOffset(!1)}function rt(e,t,n,r){if((n.isScene===!0?n.overrideMaterial:null)!==null)return;if(x.state.transmissionRenderTarget[r.id]===void 0){let e=Ce.has(`EXT_color_buffer_half_float`)||Ce.has(`EXT_color_buffer_float`);x.state.transmissionRenderTarget[r.id]=new Xs(1,1,{generateMipmaps:!0,type:e?Ta:va,minFilter:_a,samples:Math.max(4,we.samples),stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Ls.workingColorSpace})}let a=x.state.transmissionRenderTarget[r.id],o=r.viewport||ne;a.setSize(o.z*T.transmissionResolutionScale,o.w*T.transmissionResolutionScale);let s=T.getRenderTarget(),c=T.getActiveCubeFace(),l=T.getActiveMipmapLevel();T.setRenderTarget(a),T.getClearColor(ae),j=T.getClearAlpha(),j<1&&T.setClearColor(16777215,.5),T.clear(),be&&Fe.render(n);let u=T.toneMapping;T.toneMapping=0;let d=r.viewport;if(r.viewport!==void 0&&(r.viewport=void 0),x.setupLightsView(r),me===!0&&Ne.setGlobalState(T.clippingPlanes,r),it(e,n,r),I.updateMultisampleRenderTarget(a),I.updateRenderTargetMipmap(a),Ce.has(`WEBGL_multisampled_render_to_texture`)===!1){let e=!1;for(let i=0,a=t.length;i<a;i++){let{object:a,geometry:o,material:s,group:c}=t[i];if(s.side===2&&a.layers.test(r.layers)){let t=s.side;s.side=1,s.needsUpdate=!0,z(a,n,r,o,s,c),s.side=t,s.needsUpdate=!0,e=!0}}e===!0&&(I.updateMultisampleRenderTarget(a),I.updateRenderTargetMipmap(a))}T.setRenderTarget(s,c,l),T.setClearColor(ae,j),d!==void 0&&(r.viewport=d),T.toneMapping=u}function it(e,t,n){let r=t.isScene===!0?t.overrideMaterial:null;for(let i=0,a=e.length;i<a;i++){let a=e[i],{object:o,geometry:s,group:c}=a,l=a.material;l.allowOverride===!0&&r!==null&&(l=r),o.layers.test(n.layers)&&z(o,t,n,s,l,c)}}function z(e,t,n,r,i,a){e.onBeforeRender(T,t,n,r,i,a),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),i.onBeforeRender(T,t,n,r,e,a),i.transparent===!0&&i.side===2&&i.forceSinglePass===!1?(i.side=1,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=0,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=2):T.renderBufferDirect(n,t,r,i,e,a),e.onAfterRender(T,t,n,r,i,a)}function at(e,t,n){t.isScene!==!0&&(t=ye);let r=F.get(e),i=x.state.lights,a=x.state.shadowsArray,o=i.state.version,s=ke.getParameters(e,i.state,a,t,n,x.state.lightProbeGridArray),c=ke.getProgramCacheKey(s),l=r.programs;r.environment=e.isMeshStandardMaterial||e.isMeshLambertMaterial||e.isMeshPhongMaterial?t.environment:null,r.fog=t.fog;let u=e.isMeshStandardMaterial||e.isMeshLambertMaterial&&!e.envMap||e.isMeshPhongMaterial&&!e.envMap;r.envMap=L.get(e.envMap||r.environment,u),r.envMapRotation=r.environment!==null&&e.envMap===null?t.environmentRotation:e.envMapRotation,l===void 0&&(e.addEventListener(`dispose`,qe),l=new Map,r.programs=l);let d=l.get(c);if(d!==void 0){if(r.currentProgram===d&&r.lightsStateVersion===o)return st(e,s),d}else s.uniforms=ke.getUniforms(e),D!==null&&e.isNodeMaterial&&D.build(e,n,s),e.onBeforeCompile(s,T),d=ke.acquireProgram(s,c),l.set(c,d),r.uniforms=s.uniforms;let f=r.uniforms;return(!e.isShaderMaterial&&!e.isRawShaderMaterial||e.clipping===!0)&&(f.clippingPlanes=Ne.uniform),st(e,s),r.needsLights=dt(e),r.lightsStateVersion=o,r.needsLights&&(f.ambientLightColor.value=i.state.ambient,f.lightProbe.value=i.state.probe,f.directionalLights.value=i.state.directional,f.directionalLightShadows.value=i.state.directionalShadow,f.spotLights.value=i.state.spot,f.spotLightShadows.value=i.state.spotShadow,f.rectAreaLights.value=i.state.rectArea,f.ltc_1.value=i.state.rectAreaLTC1,f.ltc_2.value=i.state.rectAreaLTC2,f.pointLights.value=i.state.point,f.pointLightShadows.value=i.state.pointShadow,f.hemisphereLights.value=i.state.hemi,f.directionalShadowMatrix.value=i.state.directionalShadowMatrix,f.spotLightMatrix.value=i.state.spotLightMatrix,f.spotLightMap.value=i.state.spotLightMap,f.pointShadowMatrix.value=i.state.pointShadowMatrix),r.lightProbeGrid=x.state.lightProbeGridArray.length>0,r.currentProgram=d,r.uniformsList=null,d}function ot(e){if(e.uniformsList===null){let t=e.currentProgram.getUniforms();e.uniformsList=rh.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function st(e,t){let n=F.get(e);n.outputColorSpace=t.outputColorSpace,n.batching=t.batching,n.batchingColor=t.batchingColor,n.instancing=t.instancing,n.instancingColor=t.instancingColor,n.instancingMorph=t.instancingMorph,n.skinning=t.skinning,n.morphTargets=t.morphTargets,n.morphNormals=t.morphNormals,n.morphColors=t.morphColors,n.morphTargetsCount=t.morphTargetsCount,n.numClippingPlanes=t.numClippingPlanes,n.numIntersection=t.numClipIntersection,n.vertexAlphas=t.vertexAlphas,n.vertexTangents=t.vertexTangents,n.toneMapping=t.toneMapping}function ct(e,t){if(e.length===0)return null;if(e.length===1)return e[0].texture===null?null:e[0];y.setFromMatrixPosition(t.matrixWorld);for(let t=0,n=e.length;t<n;t++){let n=e[t];if(n.texture!==null&&n.boundingBox.containsPoint(y))return n}return null}function lt(e,t,n,r,i){t.isScene!==!0&&(t=ye),I.resetTextureUnits();let a=t.fog,o=r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial?t.environment:null,s=A===null?T.outputColorSpace:A.isXRRenderTarget===!0?A.texture.colorSpace:Ls.workingColorSpace,c=r.isMeshStandardMaterial||r.isMeshLambertMaterial&&!r.envMap||r.isMeshPhongMaterial&&!r.envMap,l=L.get(r.envMap||o,c),u=r.vertexColors===!0&&!!n.attributes.color&&n.attributes.color.itemSize===4,d=!!n.attributes.tangent&&(!!r.normalMap||r.anisotropy>0),f=!!n.morphAttributes.position,p=!!n.morphAttributes.normal,m=!!n.morphAttributes.color,h=0;r.toneMapped&&(A===null||A.isXRRenderTarget===!0)&&(h=T.toneMapping);let g=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,_=g===void 0?0:g.length,v=F.get(r),y=x.state.lights;if(me===!0&&(he===!0||e!==te)){let t=e===te&&r.id===ee;Ne.setState(r,e,t)}let b=!1;r.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version?b=!0:v.outputColorSpace===s?i.isBatchedMesh&&v.batching===!1||!i.isBatchedMesh&&v.batching===!0||i.isBatchedMesh&&v.batchingColor===!0&&i.colorTexture===null||i.isBatchedMesh&&v.batchingColor===!1&&i.colorTexture!==null||i.isInstancedMesh&&v.instancing===!1||!i.isInstancedMesh&&v.instancing===!0||i.isSkinnedMesh&&v.skinning===!1||!i.isSkinnedMesh&&v.skinning===!0||i.isInstancedMesh&&v.instancingColor===!0&&i.instanceColor===null||i.isInstancedMesh&&v.instancingColor===!1&&i.instanceColor!==null||i.isInstancedMesh&&v.instancingMorph===!0&&i.morphTexture===null||i.isInstancedMesh&&v.instancingMorph===!1&&i.morphTexture!==null?b=!0:v.envMap===l?r.fog===!0&&v.fog!==a||v.numClippingPlanes!==void 0&&(v.numClippingPlanes!==Ne.numPlanes||v.numIntersection!==Ne.numIntersection)?b=!0:v.vertexAlphas===u&&v.vertexTangents===d&&v.morphTargets===f&&v.morphNormals===p&&v.morphColors===m&&v.toneMapping===h&&v.morphTargetsCount===_?!!v.lightProbeGrid!=x.state.lightProbeGridArray.length>0&&(b=!0):b=!0:b=!0:b=!0:(b=!0,v.__version=r.version);let S=v.currentProgram;b===!0&&(S=at(r,t,i),D&&r.isNodeMaterial&&D.onUpdateProgram(r,S,v));let C=!1,w=!1,E=!1,O=S.getUniforms(),k=v.uniforms;if(P.useProgram(S.program)&&(C=!0,w=!0,E=!0),r.id!==ee&&(ee=r.id,w=!0),v.needsLights){let e=ct(x.state.lightProbeGridArray,i);v.lightProbeGrid!==e&&(v.lightProbeGrid=e,w=!0)}if(C||te!==e){P.buffers.depth.getReversed()&&e.reversedDepth!==!0&&(e._reversedDepth=!0,e.updateProjectionMatrix()),O.setValue(N,`projectionMatrix`,e.projectionMatrix),O.setValue(N,`viewMatrix`,e.matrixWorldInverse);let t=O.map.cameraPosition;t!==void 0&&t.setValue(N,_e.setFromMatrixPosition(e.matrixWorld)),we.logarithmicDepthBuffer&&O.setValue(N,`logDepthBufFC`,2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&O.setValue(N,`isOrthographic`,e.isOrthographicCamera===!0),te!==e&&(te=e,w=!0,E=!0)}if(v.needsLights&&(y.state.directionalShadowMap.length>0&&O.setValue(N,`directionalShadowMap`,y.state.directionalShadowMap,I),y.state.spotShadowMap.length>0&&O.setValue(N,`spotShadowMap`,y.state.spotShadowMap,I),y.state.pointShadowMap.length>0&&O.setValue(N,`pointShadowMap`,y.state.pointShadowMap,I)),i.isSkinnedMesh){O.setOptional(N,i,`bindMatrix`),O.setOptional(N,i,`bindMatrixInverse`);let e=i.skeleton;e&&(e.boneTexture===null&&e.computeBoneTexture(),O.setValue(N,`boneTexture`,e.boneTexture,I))}i.isBatchedMesh&&(O.setOptional(N,i,`batchingTexture`),O.setValue(N,`batchingTexture`,i._matricesTexture,I),O.setOptional(N,i,`batchingIdTexture`),O.setValue(N,`batchingIdTexture`,i._indirectTexture,I),O.setOptional(N,i,`batchingColorTexture`),i._colorsTexture!==null&&O.setValue(N,`batchingColorTexture`,i._colorsTexture,I));let ne=n.morphAttributes;if((ne.position!==void 0||ne.normal!==void 0||ne.color!==void 0)&&Ie.update(i,n,S),(w||v.receiveShadow!==i.receiveShadow)&&(v.receiveShadow=i.receiveShadow,O.setValue(N,`receiveShadow`,i.receiveShadow)),(r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial)&&r.envMap===null&&t.environment!==null&&(k.envMapIntensity.value=t.environmentIntensity),k.dfgLUT!==void 0&&(k.dfgLUT.value=wg()),w){if(O.setValue(N,`toneMappingExposure`,T.toneMappingExposure),v.needsLights&&ut(k,E),a&&r.fog===!0&&Ae.refreshFogUniforms(k,a),Ae.refreshMaterialUniforms(k,r,ce,se,x.state.transmissionRenderTarget[e.id]),v.needsLights&&v.lightProbeGrid){let e=v.lightProbeGrid;k.probesSH.value=e.texture,k.probesMin.value.copy(e.boundingBox.min),k.probesMax.value.copy(e.boundingBox.max),k.probesResolution.value.copy(e.resolution)}rh.upload(N,ot(v),k,I)}if(r.isShaderMaterial&&r.uniformsNeedUpdate===!0&&(rh.upload(N,ot(v),k,I),r.uniformsNeedUpdate=!1),r.isSpriteMaterial&&O.setValue(N,`center`,i.center),O.setValue(N,`modelViewMatrix`,i.modelViewMatrix),O.setValue(N,`normalMatrix`,i.normalMatrix),O.setValue(N,`modelMatrix`,i.matrixWorld),r.uniformsGroups!==void 0){let e=r.uniformsGroups;for(let t=0,n=e.length;t<n;t++){let n=e[t];Ve.update(n,S),Ve.bind(n,S)}}return S}function ut(e,t){e.ambientLightColor.needsUpdate=t,e.lightProbe.needsUpdate=t,e.directionalLights.needsUpdate=t,e.directionalLightShadows.needsUpdate=t,e.pointLights.needsUpdate=t,e.pointLightShadows.needsUpdate=t,e.spotLights.needsUpdate=t,e.spotLightShadows.needsUpdate=t,e.rectAreaLights.needsUpdate=t,e.hemisphereLights.needsUpdate=t}function dt(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&e.lights===!0}this.getActiveCubeFace=function(){return O},this.getActiveMipmapLevel=function(){return k},this.getRenderTarget=function(){return A},this.setRenderTargetTextures=function(e,t,n){let r=F.get(e);r.__autoAllocateDepthBuffer=e.resolveDepthBuffer===!1,r.__autoAllocateDepthBuffer===!1&&(r.__useRenderToTexture=!1),F.get(e.texture).__webglTexture=t,F.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){let n=F.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=t===void 0};let ft=N.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){A=e,O=t,k=n;let r=null,i=!1,a=!1;if(e){let o=F.get(e);if(o.__useDefaultFramebuffer!==void 0){P.bindFramebuffer(N.FRAMEBUFFER,o.__webglFramebuffer),ne.copy(e.viewport),re.copy(e.scissor),ie=e.scissorTest,P.viewport(ne),P.scissor(re),P.setScissorTest(ie),ee=-1;return}else if(o.__webglFramebuffer===void 0)I.setupRenderTarget(e);else if(o.__hasExternalTextures)I.rebindTextures(e,F.get(e.texture).__webglTexture,F.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){let t=e.depthTexture;if(o.__boundDepthTexture!==t){if(t!==null&&F.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw Error(`WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.`);I.setupDepthRenderbuffer(e)}}let s=e.texture;(s.isData3DTexture||s.isDataArrayTexture||s.isCompressedArrayTexture)&&(a=!0);let c=F.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=Array.isArray(c[t])?c[t][n]:c[t],i=!0):r=e.samples>0&&I.useMultisampledRTT(e)===!1?F.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,ne.copy(e.viewport),re.copy(e.scissor),ie=e.scissorTest}else ne.copy(M).multiplyScalar(ce).floor(),re.copy(de).multiplyScalar(ce).floor(),ie=fe;if(n!==0&&(r=ft),P.bindFramebuffer(N.FRAMEBUFFER,r)&&P.drawBuffers(e,r),P.viewport(ne),P.scissor(re),P.setScissorTest(ie),i){let r=F.get(e.texture);N.framebufferTexture2D(N.FRAMEBUFFER,N.COLOR_ATTACHMENT0,N.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(a){let r=t;for(let t=0;t<e.textures.length;t++){let i=F.get(e.textures[t]);N.framebufferTextureLayer(N.FRAMEBUFFER,N.COLOR_ATTACHMENT0+t,i.__webglTexture,n,r)}}else if(e!==null&&n!==0){let t=F.get(e.texture);N.framebufferTexture2D(N.FRAMEBUFFER,N.COLOR_ATTACHMENT0,N.TEXTURE_2D,t.__webglTexture,n)}ee=-1},this.readRenderTargetPixels=function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget)){V(`WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);return}let c=F.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c){P.bindFramebuffer(N.FRAMEBUFFER,c);try{let o=e.textures[s],c=o.format,l=o.type;if(e.textures.length>1&&N.readBuffer(N.COLOR_ATTACHMENT0+s),!we.textureFormatReadable(c)){V(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.`);return}if(!we.textureTypeReadable(l)){V(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.`);return}t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&N.readPixels(t,n,r,i,ze.convert(c),ze.convert(l),a)}finally{let e=A===null?null:F.get(A).__webglFramebuffer;P.bindFramebuffer(N.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget))throw Error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);let c=F.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c)if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){P.bindFramebuffer(N.FRAMEBUFFER,c);let o=e.textures[s],l=o.format,u=o.type;if(e.textures.length>1&&N.readBuffer(N.COLOR_ATTACHMENT0+s),!we.textureFormatReadable(l))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.`);if(!we.textureTypeReadable(u))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.`);let d=N.createBuffer();N.bindBuffer(N.PIXEL_PACK_BUFFER,d),N.bufferData(N.PIXEL_PACK_BUFFER,a.byteLength,N.STREAM_READ),N.readPixels(t,n,r,i,ze.convert(l),ze.convert(u),0);let f=A===null?null:F.get(A).__webglFramebuffer;P.bindFramebuffer(N.FRAMEBUFFER,f);let p=N.fenceSync(N.SYNC_GPU_COMMANDS_COMPLETE,0);return N.flush(),await ts(N,p,4),N.bindBuffer(N.PIXEL_PACK_BUFFER,d),N.getBufferSubData(N.PIXEL_PACK_BUFFER,0,a),N.deleteBuffer(d),N.deleteSync(p),a}else throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.`)},this.copyFramebufferToTexture=function(e,t=null,n=0){let r=2**-n,i=Math.floor(e.image.width*r),a=Math.floor(e.image.height*r),o=t===null?0:t.x,s=t===null?0:t.y;I.setTexture2D(e,0),N.copyTexSubImage2D(N.TEXTURE_2D,n,0,0,o,s,i,a),P.unbindTexture()};let pt=N.createFramebuffer(),mt=N.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,a=0){let o,s,c,l,u,d,f,p,m,h=e.isCompressedTexture?e.mipmaps[a]:e.image;if(n!==null)o=n.max.x-n.min.x,s=n.max.y-n.min.y,c=n.isBox3?n.max.z-n.min.z:1,l=n.min.x,u=n.min.y,d=n.isBox3?n.min.z:0;else{let t=2**-i;o=Math.floor(h.width*t),s=Math.floor(h.height*t),c=e.isDataArrayTexture?h.depth:e.isData3DTexture?Math.floor(h.depth*t):1,l=0,u=0,d=0}r===null?(f=0,p=0,m=0):(f=r.x,p=r.y,m=r.z);let g=ze.convert(t.format),_=ze.convert(t.type),v;t.isData3DTexture?(I.setTexture3D(t,0),v=N.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(I.setTexture2DArray(t,0),v=N.TEXTURE_2D_ARRAY):(I.setTexture2D(t,0),v=N.TEXTURE_2D),P.activeTexture(N.TEXTURE0),P.pixelStorei(N.UNPACK_FLIP_Y_WEBGL,t.flipY),P.pixelStorei(N.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),P.pixelStorei(N.UNPACK_ALIGNMENT,t.unpackAlignment);let y=P.getParameter(N.UNPACK_ROW_LENGTH),b=P.getParameter(N.UNPACK_IMAGE_HEIGHT),x=P.getParameter(N.UNPACK_SKIP_PIXELS),S=P.getParameter(N.UNPACK_SKIP_ROWS),C=P.getParameter(N.UNPACK_SKIP_IMAGES);P.pixelStorei(N.UNPACK_ROW_LENGTH,h.width),P.pixelStorei(N.UNPACK_IMAGE_HEIGHT,h.height),P.pixelStorei(N.UNPACK_SKIP_PIXELS,l),P.pixelStorei(N.UNPACK_SKIP_ROWS,u),P.pixelStorei(N.UNPACK_SKIP_IMAGES,d);let w=e.isDataArrayTexture||e.isData3DTexture,T=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){let n=F.get(e),r=F.get(t),h=F.get(n.__renderTarget),g=F.get(r.__renderTarget);P.bindFramebuffer(N.READ_FRAMEBUFFER,h.__webglFramebuffer),P.bindFramebuffer(N.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n<c;n++)w&&(N.framebufferTextureLayer(N.READ_FRAMEBUFFER,N.COLOR_ATTACHMENT0,F.get(e).__webglTexture,i,d+n),N.framebufferTextureLayer(N.DRAW_FRAMEBUFFER,N.COLOR_ATTACHMENT0,F.get(t).__webglTexture,a,m+n)),N.blitFramebuffer(l,u,o,s,f,p,o,s,N.DEPTH_BUFFER_BIT,N.NEAREST);P.bindFramebuffer(N.READ_FRAMEBUFFER,null),P.bindFramebuffer(N.DRAW_FRAMEBUFFER,null)}else if(i!==0||e.isRenderTargetTexture||F.has(e)){let n=F.get(e),r=F.get(t);P.bindFramebuffer(N.READ_FRAMEBUFFER,pt),P.bindFramebuffer(N.DRAW_FRAMEBUFFER,mt);for(let e=0;e<c;e++)w?N.framebufferTextureLayer(N.READ_FRAMEBUFFER,N.COLOR_ATTACHMENT0,n.__webglTexture,i,d+e):N.framebufferTexture2D(N.READ_FRAMEBUFFER,N.COLOR_ATTACHMENT0,N.TEXTURE_2D,n.__webglTexture,i),T?N.framebufferTextureLayer(N.DRAW_FRAMEBUFFER,N.COLOR_ATTACHMENT0,r.__webglTexture,a,m+e):N.framebufferTexture2D(N.DRAW_FRAMEBUFFER,N.COLOR_ATTACHMENT0,N.TEXTURE_2D,r.__webglTexture,a),i===0?T?N.copyTexSubImage3D(v,a,f,p,m+e,l,u,o,s):N.copyTexSubImage2D(v,a,f,p,l,u,o,s):N.blitFramebuffer(l,u,o,s,f,p,o,s,N.COLOR_BUFFER_BIT,N.NEAREST);P.bindFramebuffer(N.READ_FRAMEBUFFER,null),P.bindFramebuffer(N.DRAW_FRAMEBUFFER,null)}else T?e.isDataTexture||e.isData3DTexture?N.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h.data):t.isCompressedArrayTexture?N.compressedTexSubImage3D(v,a,f,p,m,o,s,c,g,h.data):N.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h):e.isDataTexture?N.texSubImage2D(N.TEXTURE_2D,a,f,p,o,s,g,_,h.data):e.isCompressedTexture?N.compressedTexSubImage2D(N.TEXTURE_2D,a,f,p,h.width,h.height,g,h.data):N.texSubImage2D(N.TEXTURE_2D,a,f,p,o,s,g,_,h);P.pixelStorei(N.UNPACK_ROW_LENGTH,y),P.pixelStorei(N.UNPACK_IMAGE_HEIGHT,b),P.pixelStorei(N.UNPACK_SKIP_PIXELS,x),P.pixelStorei(N.UNPACK_SKIP_ROWS,S),P.pixelStorei(N.UNPACK_SKIP_IMAGES,C),a===0&&t.generateMipmaps&&N.generateMipmap(v),P.unbindTexture()},this.initRenderTarget=function(e){F.get(e).__webglFramebuffer===void 0&&I.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?I.setTextureCube(e,0):e.isData3DTexture?I.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?I.setTexture2DArray(e,0):I.setTexture2D(e,0),P.unbindTexture()},this.resetState=function(){O=0,k=0,A=null,P.reset(),Be.reset()},typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}get coordinateSystem(){return Go}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=Ls._getDrawingBufferColorSpace(e),t.unpackColorSpace=Ls._getUnpackColorSpace()}},Eg=class{engine;entries=new Map;loader;constructor(e,t=null){this.engine=t,this.loader=e??((e,t)=>new uf().load(e,()=>t?.onLoad?.(),void 0,e=>t?.onError?.(e)))}load(e){for(let[t,n]of Object.entries(e)){let e=n.type;if(e!==`texture`&&e!==`spritesheet`)throw new L(`BAD_FORMAT`,`Asset '${t}': "type" must be 'texture' or 'spritesheet', got ${JSON.stringify(e)}.`);if(typeof n.url!=`string`||n.url===``)throw new L(`BAD_FORMAT`,`Asset '${t}': "url" must be a non-empty string.`);let r,i;if(e===`spritesheet`){if(typeof n.frameWidth!=`number`||typeof n.frameHeight!=`number`)throw new L(`BAD_FORMAT`,`Asset '${t}': spritesheets need numeric "frameWidth" and "frameHeight".`);r=n.frameWidth,i=n.frameHeight}let a=this.entries.get(t),o={status:`loading`},s=this.loader(n.url,{onLoad:()=>{o.status=`ready`},onError:e=>{o.status=`error`,o.error=e instanceof Error?e.message:`could not load ${n.url}`,Nt(this.engine,`error`,`[incanto] failed to load texture '${t}' (${n.url}):`,e)}});a&&a.texture!==s&&a.texture.dispose(),s.colorSpace=Ro,n.filter===`nearest`?(s.magFilter=fa,s.minFilter=fa,s.generateMipmaps=!1):s.magFilter=ha,s.needsUpdate=!0,this.entries.set(t,{texture:s,type:e,frameWidth:r,frameHeight:i,url:n.url,state:o})}}errors(){let e=[];for(let[t,n]of this.entries)n.state.status===`error`&&e.push({ref:`$${t}`,url:n.url,error:n.state.error??`could not load ${n.url}`});return e}status(e){return this.entries.get(e)?.state.status}getTexture(e){return this.resolve(e).texture}getSheet(e){let t=this.resolve(e);if(t.type!==`spritesheet`)throw new L(`BAD_FORMAT`,`Asset '${e}' is a plain texture; a spritesheet (with frameWidth/frameHeight) is required here.`);return{texture:t.texture,frameWidth:t.frameWidth,frameHeight:t.frameHeight}}resolve(e){if(!e.startsWith(`$`))throw new L(`UNKNOWN_ASSET`,`Asset reference '${e}' must use the '$key' form (e.g. '$${e}').`);let t=this.entries.get(e.slice(1));if(!t)throw new L(`UNKNOWN_ASSET`,`Unknown asset '${e}'. Declared assets: [${[...this.entries.keys()].join(`, `)}].`);return t}};function Dg(e){let t=[],n=e=>{e instanceof Kn&&e.loadError&&t.push({ref:e.getPath(),url:e.src,error:e.loadError});for(let t of e.children)n(t)};return e&&n(e),t}function Og(e){let t=e?.style;t&&(t.touchAction=`none`,t.userSelect=`none`,t.webkitUserSelect=`none`,t.webkitTouchCallout=`none`,t.webkitTapHighlightColor=`transparent`)}function kg(e,t,n){return(.2126*e+.7152*t+.0722*n)/255}var Ag=.012,jg=.004;function Mg(e,t,n,r,i){let a=new Uint8Array(r*i*3);for(let o=0;o<i;o++)for(let s=0;s<r;s++){let c=Math.floor(s*t/r),l=Math.max(c+1,Math.floor((s+1)*t/r)),u=Math.floor(o*n/i),d=Math.max(u+1,Math.floor((o+1)*n/i)),f=0,p=0,m=0,h=0;for(let n=u;n<d;n++)for(let r=c;r<l;r++){let i=(n*t+r)*4;f+=e[i]??0,p+=e[i+1]??0,m+=e[i+2]??0,h+=1}let g=(o*r+s)*3;a[g]=Math.round(f/h),a[g+1]=Math.round(p/h),a[g+2]=Math.round(m/h)}return a}var Ng=24;function Pg(e,t,n){let r=0,i=0,a=0,o=0,s=(n,s)=>{let c=(s*t+n)*4;r+=e[c],i+=e[c+1],a+=e[c+2],o+=1};for(let e=0;e<t;e++)s(e,0),s(e,n-1);for(let e=1;e<n-1;e++)s(0,e),s(t-1,e);return o===0?[0,0,0]:[r/o,i/o,a/o]}function Fg(e,t,n){let r=Pg(e,t,n),i=(n,r)=>{let i=(r*t+n)*4;return[e[i],e[i+1],e[i+2]]},a=(e,t)=>Math.abs(e[0]-t[0])+Math.abs(e[1]-t[1])+Math.abs(e[2]-t[2]),o=t,s=n,c=-1,l=-1,u=0;for(let e=0;e<n;e++){let n=i(0,e),d=i(t-1,e),f=a(n,d)>Ng?a(n,r)<=a(d,r)?n:d:[(n[0]+d[0])/2,(n[1]+d[1])/2,(n[2]+d[2])/2];for(let n=0;n<t;n++)a(i(n,e),f)<Ng||(u+=1,n<o&&(o=n),n>c&&(c=n),e<s&&(s=e),e>l&&(l=e))}return c<0?null:{box:{x:o,y:s,w:c-o+1,h:l-s+1},coverage:u/(t*n),clipped:o===0||s===0||c===t-1||l===n-1}}function Ig(e,t,n,r={}){let[i,a]=r.grid??[16,9],o=Mg(e,t,n,i,a),s=[],c=0,l=0,u=1;for(let e=0;e<a;e++){let t=[];for(let n=0;n<i;n++){let r=(e*i+n)*3,a=[o[r],o[r+1],o[r+2]],s=kg(a[0],a[1],a[2]);c+=s,l=Math.max(l,s),u=Math.min(u,s),t.push(a)}s.push(t)}let d=i*a,f=c/d,p=l<=Ag;return{width:t,height:n,black:p,uniform:l-u<jg,meanLuma:Math.round(f*1e3)/1e3,grid:s,subject:p?null:Fg(e,t,n)}}function Lg(e){return[]}var Rg=`modulepreload`,zg=function(e,t){return new URL(e,t).href},Bg={},Vg=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=zg(t,n),t in Bg)return;Bg[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:Rg,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Hg=160;function Ug(e=``,t=`#0b0d14`){if(typeof document>`u`)return{lift:()=>{}};let n=document.createElement(`div`);if(n.dataset.incantoSwitch=``,n.style.cssText=`position:fixed;inset:0;z-index:2147483646;background:${t};display:flex;align-items:center;justify-content:center;opacity:0;transition:opacity ${Hg}ms ease;pointer-events:auto;`,e){let t=document.createElement(`div`);t.textContent=e,t.style.cssText=`font:13px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:#5d6680;letter-spacing:0.04em;`,n.appendChild(t)}document.body.appendChild(n),requestAnimationFrame(()=>{n.style.opacity=`1`});let r=!1;return{lift(){r||(r=!0,requestAnimationFrame(()=>{n.style.opacity=`0`,setTimeout(()=>n.remove(),200)}))}}}async function Wg(e=Hg){typeof requestAnimationFrame==`function`&&await new Promise(t=>setTimeout(t,e))}function Gg(e){return async(t,n)=>{let r=n||e,i=new URLSearchParams({tags:t.tags.join(`,`),page:String(t.page??1),limit:String(t.limit??24)});t.keyword?.trim()&&i.set(`keyword`,t.keyword.trim());let a=await fetch(`/api/library?${i}`,{headers:r?{"x-incanto-v8-token":r}:{}});if(a.status===401){let e=await a.json().catch(()=>({})),t=Error(e.error??`the asset library needs a Verse8 access token`);throw t.needsToken=!0,t}if(!a.ok)throw Error(`asset library: HTTP ${a.status}`);return await a.json()}}async function Kg(){try{let e=await fetch(`/api/scenes`);if(!e.ok)return null;let t=await e.json();return Array.isArray(t)?t:null}catch{return null}}function qg(e,t){let n=typeof t.name==`string`?t.name:null;if(!e||!n)return null;let r=e.filter(e=>e.scene?.name===n);return r.length===1?r[0].rel:null}function Jg(e,t){let n=typeof t.name==`string`?t.name:`(unnamed)`;if(!e)return`Save: this dev server does not serve the project's scenes, so there is no file to write. ${Yg}`;let r=e.filter(e=>e.scene?.name===n);return r.length>1?`Save: ${r.length} scenes in this project are named "${n}" (${r.map(e=>e.rel).join(`, `)}), so which file this is cannot be told from the scene alone. Open the one you mean from the scene browser and save there.`:`Save: no file in this project contains a scene named "${n}", so there is nowhere to write it. Open a scene from the scene browser first, or pass editor: { save } to createGame so the game decides where edits go.`}var Yg=`this dev server does not serve the project's scenes yet. Add incantoScenes() to vite.config.ts and restart:
|
|
4107
4107
|
|
|
4108
4108
|
import { incantoScenes } from 'incanto/vite';
|
|
4109
4109
|
export default defineConfig({ plugins: [incantoScenes()] });
|
|
4110
4110
|
|
|
4111
|
-
It also validates every scene you save, before the page reloads into a broken one.`;async function
|
|
4111
|
+
It also validates every scene you save, before the page reloads into a broken one.`;async function Xg(e){let t=await fetch(`/api/scene?file=${encodeURIComponent(e)}`);if(t.ok)return await t.json();let n=await t.json().catch(()=>null);throw Error(n?.error??`could not open ${e}: HTTP ${t.status}`)}async function Zg(e){let t;try{t=await Vg(()=>Promise.resolve().then(()=>CW),void 0,import.meta.url)}catch(e){throw Error(`createGame3D editor: could not load 'incanto/editor'. If this app aliases incanto to the engine SOURCE (the examples and playground do), add an alias for 'incanto/editor' → packages/editor/src/main.ts — or pass editor: { open } and load it yourself. (${e instanceof Error?e.message:String(e)})`)}let n=null,r=await Kg(),i=t.formatSceneJson??(e=>JSON.stringify(e,null,2)),a=async(e,t)=>{let n=await fetch(`/api/scene?file=${encodeURIComponent(e)}`,{method:`PUT`,body:i(t)});if(!n.ok)throw Error(`could not save ${e}: HTTP ${n.status} ${await n.text()}`)};n=await t.mountEditor({...e.camera?{camera:e.camera}:{},api:{meta:async()=>({version:`live`,mode:`project`,root:``,input:null,output:null,hasScene:!0}),loadScene:async t=>t?await Xg(t):e.scene,...e.save||r?{saveScene:async(t,n)=>{if(n)return a(n,t);if(e.save)return void await e.save(t);let i=qg(r,e.scene);if(i)return a(i,t);throw Error(Jg(r,e.scene))}}:{},scenes:async()=>{let e=await Kg();if(!e)throw Error(Yg);return e},createScene:async e=>{let t=await fetch(`/api/scenes`,{method:`POST`,body:JSON.stringify({path:e})});if(t.status===404)throw Error(Yg);if(!t.ok)throw Error(`could not create ${e}: ${await t.text()}`);return await t.json()},...e.library?{library:e.library}:{}},onPlay:(t,r)=>{if(t!==`debug`)return;let i=n?.camera();return Qg(async()=>{n?.dispose(),n=null,await e.play(r,i)},`starting the game…`)},...e.exit?{onExit:()=>Qg(async()=>{n?.dispose(),n=null,await e.exit?.()},`back to the game…`)}:{}})}async function Qg(e,t=``){let n=Ug(t);await Wg();try{await e()}finally{await Wg(0),n.lift()}}function $g(e,t=8){let n=e.cameraBasis,r=e.lastCameraPosition;if(typeof n!=`function`||typeof r!=`function`)return;let i=r.call(e);if(!i)return;let{forward:a}=n.call(e);return{position:[i.x,i.y,i.z],target:[i.x+a.x*t,i.y+a.y*t,i.z+a.z*t]}}function e_(e,t=typeof document>`u`?null:document){if(!t)return()=>{};let n=null,r=!1,i=()=>{if(t.hidden){n===null&&e.timeScale>0&&(n=e.timeScale,e.timeScale=0),e.audio.muted||(e.audio.muted=!0,r=!0);return}n!==null&&(e.timeScale===0&&(e.timeScale=n),n=null),r&&=(e.audio.muted=!1,!1)};return t.addEventListener(`visibilitychange`,i),()=>t.removeEventListener(`visibilitychange`,i)}function t_(e,t=n_){let n=[];for(let r of e){if(!r)continue;let[e,i]=r;try{i()}catch(r){n.push({what:e,error:r});try{t(e,r)}catch{}}}return{failures:n}}function n_(e,t){console.error(`[incanto] teardown: ${e} failed (continuing)`,t)}var r_=new Ru,i_=new K,a_=new Tl;function o_(e,t,n){return i_.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),r_.setFromProjectionMatrix(i_),a_.center.set(t.x,t.y,t.z),a_.radius=n,r_.intersectsSphere(a_)}function s_(e){if(!e||typeof e!=`object`)return 0;switch(e.shape){case`capsule`:return(e.height??0)/2+(e.radius??0);case`sphere`:return e.radius??0;case`box`:return(e.size?.[1]??0)/2;default:return 0}}function c_(e){return .55+Math.min(Math.max(e,0),12)/12*.45}function l_(e,t,n=0){let r=[],i=[],a=new Set;for(let o of t){let t=e.has(o.id);(t?o.y<=o.waterline+n:o.y<o.waterline)?(a.add(o.id),t||r.push(o)):t&&i.push(o)}return{entered:r,exited:i,inWater:a}}function u_(e,t,n,r,i=0,a=8){if(e.length>=a){let t=0;for(let n=1;n<e.length;n++)e[n].age>e[t].age&&(t=n);e.splice(t,1)}e.push({x:t,z:n,age:0,amp:r,foam:i})}function d_(e,t,n=3){for(let r=e.length-1;r>=0;r--){let i=e[r];i.age+=t,i.age>=n&&e.splice(r,1)}}function f_(e,t,n){let r=e-n.x,i=t-n.z,a=Math.sqrt(r*r+i*i);return n.amp*Math.sin(6*a-8*n.age)*Math.exp(-1.1*n.age)*Math.exp(-.15*a*a)}function p_(e,t,n){let r=0;for(let i of n)r+=f_(e,t,i);return r}function m_(e,t,n,r){let i=[];for(let n of e.keys())t.has(n)||e.delete(n);for(let a of t){let t=(e.get(a)??0)+n;t>=r?(i.push(a),e.set(a,t-r)):e.set(a,t)}return i}var h_=`
|
|
4112
4112
|
precision highp float;
|
|
4113
4113
|
|
|
4114
4114
|
// atmosphere: three's linear fog rides the standard chunks (compiled out
|
|
@@ -4132,7 +4132,7 @@ void main() {
|
|
|
4132
4132
|
// atmosphere: fog depth from the displaced surface position
|
|
4133
4133
|
#include <fog_vertex>
|
|
4134
4134
|
}
|
|
4135
|
-
`,
|
|
4135
|
+
`,g_=`
|
|
4136
4136
|
precision highp float;
|
|
4137
4137
|
|
|
4138
4138
|
// atmosphere: standard fog chunk (compiled out without scene fog)
|
|
@@ -4327,13 +4327,13 @@ void main() {
|
|
|
4327
4327
|
#include <colorspace_fragment>
|
|
4328
4328
|
#include <fog_fragment>
|
|
4329
4329
|
}
|
|
4330
|
-
`,
|
|
4330
|
+
`,__=new Set([`Foliage3D`,`Flowers3D`,`Particles3D`,`Trail3D`]);function v_(e,t){return t.length=0,typeof e?.traverse==`function`&&e.traverse(e=>{if(!e.visible)return;if(e.userData?.incantoWaterPassSkip===!0){e.visible=!1,t.push(e);return}let n=(e.userData?.incantoNode)?.constructor?.typeName;n&&__.has(n)&&(e.visible=!1,t.push(e))}),t}function y_(e){for(let t=0;t<e.length;t++){let n=e[t];n&&(n.visible=!0)}e.length=0}var b_=`
|
|
4331
4331
|
varying vec2 vUv;
|
|
4332
4332
|
void main() {
|
|
4333
4333
|
vUv = uv;
|
|
4334
4334
|
gl_Position = vec4(position.xy, 0.0, 1.0);
|
|
4335
4335
|
}
|
|
4336
|
-
`,
|
|
4336
|
+
`,x_=`
|
|
4337
4337
|
float caustic(vec2 uv, float t) {
|
|
4338
4338
|
vec2 p = mod(uv * 6.28318, 6.28318) - 250.0;
|
|
4339
4339
|
vec2 i = p;
|
|
@@ -4348,7 +4348,7 @@ float caustic(vec2 uv, float t) {
|
|
|
4348
4348
|
c = 1.17 - pow(c, 1.4);
|
|
4349
4349
|
return clamp(pow(abs(c), 8.0), 0.0, 1.0);
|
|
4350
4350
|
}
|
|
4351
|
-
`,
|
|
4351
|
+
`,S_=`
|
|
4352
4352
|
precision highp float;
|
|
4353
4353
|
varying vec2 vUv;
|
|
4354
4354
|
uniform sampler2D tColor;
|
|
@@ -4367,7 +4367,7 @@ uniform float uMaxDist;
|
|
|
4367
4367
|
uniform vec3 uSunDirection;
|
|
4368
4368
|
uniform float uRayStrength;
|
|
4369
4369
|
|
|
4370
|
-
${
|
|
4370
|
+
${x_}
|
|
4371
4371
|
|
|
4372
4372
|
/** Cheap 2-octave value noise — the shaft pattern (the caustic loop is far too
|
|
4373
4373
|
* expensive to run once per ray step). */
|
|
@@ -4453,7 +4453,7 @@ void main() {
|
|
|
4453
4453
|
|
|
4454
4454
|
gl_FragColor = color;
|
|
4455
4455
|
}
|
|
4456
|
-
`;function
|
|
4456
|
+
`;function C_(){let e=new Dd({vertexShader:b_,fragmentShader:S_,depthTest:!1,depthWrite:!1,uniforms:{tColor:{value:null},tDepth:{value:null},uInvViewProj:{value:new K},uCameraPos:{value:new W},uWaterLevel:{value:0},uTime:{value:0},uCausticColor:{value:new q(`#cdeeff`)},uCausticIntensity:{value:.55},uCausticScale:{value:.32},uMaxDist:{value:22},uSunDirection:{value:new W(.4,.85,.35)},uRayStrength:{value:0}}}),t=new iu(new _d(2,2),e);return t.frustumCulled=!1,{mesh:t,uniforms:e.uniforms}}var w_=`
|
|
4457
4457
|
precision highp float;
|
|
4458
4458
|
|
|
4459
4459
|
// incanto atmosphere: three's linear fog rides the standard chunks (compiled
|
|
@@ -4701,7 +4701,7 @@ void main() {
|
|
|
4701
4701
|
vec4 mvPosition = viewMatrix * modelPosition;
|
|
4702
4702
|
#include <fog_vertex>
|
|
4703
4703
|
}
|
|
4704
|
-
`,
|
|
4704
|
+
`,T_=`
|
|
4705
4705
|
precision highp float;
|
|
4706
4706
|
|
|
4707
4707
|
// incanto atmosphere: standard fog chunk (compiled out without scene fog)
|
|
@@ -4805,7 +4805,7 @@ const float SHORE_MAX_COLUMN = 2.2;
|
|
|
4805
4805
|
// different optical world (Snell's window), not the top shaded darker.
|
|
4806
4806
|
uniform float uCameraSubmerged;
|
|
4807
4807
|
|
|
4808
|
-
${
|
|
4808
|
+
${x_}
|
|
4809
4809
|
|
|
4810
4810
|
// 🎨 Contact surface color customization uniforms
|
|
4811
4811
|
uniform vec3 uEdgeColor;
|
|
@@ -5747,7 +5747,7 @@ void main() {
|
|
|
5747
5747
|
#include <colorspace_fragment>
|
|
5748
5748
|
#include <fog_fragment>
|
|
5749
5749
|
}
|
|
5750
|
-
`;function T_(e,t,n,r,i=0){return t>=r.centerY?!1:Math.abs(e-r.centerX)<=r.halfW+i&&Math.abs(n-r.centerZ)<=r.halfD+i}var E_=22,D_={enabled:!0,strength:.6},O_={enabled:!0,color:`#cdeeff`,intensity:.55,scale:.32,speed:1};function k_(e,t){if(e===!1)return{enabled:!1,color:M_(t),visibility:E_,caustics:O_,rays:{...D_,enabled:!1}};let n=e&&typeof e==`object`?e:{};return{enabled:!0,color:n.color??M_(t),visibility:n.visibility??E_,caustics:j_(n.caustics),rays:A_(n.rays)}}function A_(e){return e===!1?{...D_,enabled:!1}:typeof e==`number`?{enabled:e>0,strength:e}:{...D_}}function j_(e){if(e===!1)return{...O_,enabled:!1};let t=e&&typeof e==`object`?e:{};return{enabled:!0,color:typeof t.color==`string`?t.color:O_.color,intensity:typeof t.intensity==`number`?t.intensity:O_.intensity,scale:typeof t.scale==`number`?t.scale:O_.scale,speed:typeof t.speed==`number`?t.speed:O_.speed}}function M_(e){let{r:t,g:n,b:r}=N_(e),i=(e,t,n)=>Math.round(e*(1-n)+t*n);return P_(Math.round(i(t,6,.45)*.7),Math.round(i(n,40,.4)*.78),Math.round(i(r,70,.35)*.82))}function N_(e){let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return{r:Number.parseInt(n.slice(0,2),16)||0,g:Number.parseInt(n.slice(2,4),16)||0,b:Number.parseInt(n.slice(4,6),16)||0}}function P_(e,t,n){let r=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,`0`);return`#${r(e)}${r(t)}${r(n)}`}var F_={frequency:6.7,persistence:.3,lacunarity:2.18,iterations:9,speed:.5},I_=.525,L_=.08,R_={freqX:.7,freqZ:.5,cross:.6};function z_(e,t){return e-Math.floor(e/t)*t}function B_(e){return e-Math.floor(e)}function V_(e){return z_((e*34+1)*e,289)}var H_=.211324865405187,U_=.366025403784439,W_=-.577350269189626,G_=.024390243902439;function K_(e,t){let n=Math.floor(e+(e+t)*U_),r=Math.floor(t+(e+t)*U_),i=e-n+(n+r)*H_,a=t-r+(n+r)*H_,o=+(i>a),s=i>a?0:1,c=i+H_-o,l=a+H_-s,u=i+W_,d=a+W_;n=z_(n,289),r=z_(r,289);let f=V_(V_(r)+n),p=V_(V_(r+s)+n+o),m=V_(V_(r+1)+n+1),h=Math.max(.5-(i*i+a*a),0),g=Math.max(.5-(c*c+l*l),0),_=Math.max(.5-(u*u+d*d),0);h*=h,h*=h,g*=g,g*=g,_*=_,_*=_;let v=2*B_(f*G_)-1,y=2*B_(p*G_)-1,b=2*B_(m*G_)-1,x=Math.abs(v)-.5,S=Math.abs(y)-.5,C=Math.abs(b)-.5,w=v-Math.floor(v+.5),T=y-Math.floor(y+.5),E=b-Math.floor(b+.5);h*=1.79284291400159-.85373472095314*(w*w+x*x),g*=1.79284291400159-.85373472095314*(T*T+S*S),_*=1.79284291400159-.85373472095314*(E*E+C*C);let D=w*i+x*a,O=T*c+S*l,k=E*u+C*d;return 130*(h*D+g*O+_*k)}function q_(e,t,n,r){let i=Math.max(r.scaleNorm,1e-6),a=e/i,o=t/i,s=0,c=1,l=r.frequency,u=n*r.speed;for(let e=0;e<r.iterations;e++)s+=c*K_(a*l+u,o*l+u),c*=r.persistence,l*=r.lacunarity;return s*r.amplitude}function J_(e,t,n,r){return r*(Math.sin(e*R_.freqX+n)+R_.cross*Math.sin(t*R_.freqZ+n*1.3))}function Y_(e,t){let n=e.shape;if(n!==void 0){if(n===`box`){let n=e.size;if(!Array.isArray(n)||n.length!==3||n.some(e=>typeof e!=`number`))throw new L(`BAD_FORMAT`,`Collider on '${t}': box needs "size": [x, y, z].`);return}if(n===`sphere`){if(typeof e.radius!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${t}': sphere needs "radius".`);return}if(n===`capsule`){if(typeof e.radius!=`number`||typeof e.height!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${t}': capsule needs "radius" and "height".`);return}if(n===`trimesh`){let n=e.vertices,r=e.indices;if(!Array.isArray(n)||n.length%3!=0||!Array.isArray(r)||r.length%3!=0)throw new L(`BAD_FORMAT`,`Collider on '${t}': trimesh needs "vertices" (flat xyz floats) and "indices" (triangle triplets).`);return}if(n!==`heightfield`&&n!==`auto`)throw new L(`BAD_FORMAT`,`Collider on '${t}': "shape" must be 'auto', 'box', 'sphere', 'capsule', 'trimesh', or 'heightfield', got ${JSON.stringify(n)}.`)}}function X_(e){let t=e;if(t.constructor?.typeName===`Terrain3D`&&typeof t.heightAt==`function`)return e;for(let t of e.children){let e=X_(t);if(e)return e}return null}var Z_=class e extends Ft{static typeName=`Node3D`;static props={position:{default:[0,0,0]},rotation:{default:[0,0,0]},static:{default:!1},scale:{default:[1,1,1]},visible:{default:!0},renderOrder:{default:0},orderGroup:{default:`default`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},snapToGround:{default:null}};position=[0,0,0];rotation=[0,0,0];static=!1;scale=[1,1,1];visible=!0;renderOrder=0;orderGroup=`default`;snapToGround=null;get effectiveRenderOrder(){return gn(this.orderGroup,this.renderOrder,this.tree?.engine?.orderGroups)}_object3D=null;_interpPrev=null;_interpCurr=null;onReady(){this.applyGroundSnap()}applyGroundSnap(){if(this.snapToGround===null||this.snapToGround===!1)return;let t=this.snapToGround===!0?0:this.snapToGround,n=X_(this.getRoot());if(!n)return;let r=this.position[0]??0,i=0,a=this.position[2]??0;for(let t=this.parent;t;t=t.parent){if(!(t instanceof e))continue;let n=(t.rotation[1]??0)*Math.PI/180;if(n!==0){let e=Math.cos(n),t=Math.sin(n),i=r*e+a*t,o=-r*t+a*e;r=i,a=o}r+=t.position[0]??0,i+=t.position[1]??0,a+=t.position[2]??0}let o=r,s=a;this.position=[this.position[0]??0,n.heightAt(o,s)+t-i,this.position[2]??0]}get _builtObject3D(){return this._object3D}_ensureObject3D(){return this._object3D||(this._object3D=this._createObject3D(),this._object3D.userData.incantoNode=this),this._object3D}_createObject3D(){return new Tc}_syncObject3D(e=1,t=null){let n=this._ensureObject3D(),r=this._interpPrev,i=this._interpCurr;r&&i?n.position.set((r[0]??0)+((i[0]??0)-(r[0]??0))*e,(r[1]??0)+((i[1]??0)-(r[1]??0))*e,(r[2]??0)+((i[2]??0)-(r[2]??0))*e):n.position.set(this.position[0]??0,this.position[1]??0,this.position[2]??0),n.rotation.set(As.degToRad(this.rotation[0]??0),As.degToRad(this.rotation[1]??0),As.degToRad(this.rotation[2]??0)),n.scale.set(this.scale[0]??1,this.scale[1]??1,this.scale[2]??1),n.visible=this.visible,n.renderOrder=this.effectiveRenderOrder}free(){super.free(),this._object3D?.removeFromParent(),this._object3D=null,this._interpPrev=null,this._interpCurr=null}},Q_=class extends Z_{static props={collider:{default:{},variants:{tag:`shape`,byTag:{auto:{shape:`auto`},box:{shape:`box`,size:[1,1,1]},sphere:{shape:`sphere`,radius:.5},capsule:{shape:`capsule`,radius:.35,height:1},trimesh:{shape:`trimesh`,vertices:[],indices:[]},heightfield:{shape:`heightfield`}}}},enabled:{default:!0}};static signals=[`triggerEnter`,`triggerExit`];_collider={};_colliderChanged=!1;_enabled=!0;_enabledChanged=!1;get collider(){return this._collider}set collider(e){this._collider=e,this._colliderChanged=!0}get enabled(){return this._enabled}set enabled(e){e!==this._enabled&&(this._enabled=e,this._enabledChanged=!0)}static validateJson(e){let t=e;if(Y_(t.collider,e.name),t.collider.shape===`heightfield`&&!(t instanceof $_))throw new L(`BAD_FORMAT`,`Collider on '${e.name}': heightfield is static terrain — put it on a StaticBody3D (with a Terrain3D child), not a ${t.constructor.typeName}.`,{prop:`collider`})}_physics=null},$_=class extends Q_{static typeName=`StaticBody3D`},ev=class extends Q_{static typeName=`Area3D`},tv=class extends Q_{static typeName=`RigidBody3D`;static props={mass:{default:1},gravityScale:{default:1},fixedRotation:{default:!1},friction:{default:.5},restitution:{default:0},linearVelocity:{default:[0,0,0]}};mass=1;gravityScale=1;fixedRotation=!1;friction=.5;restitution=0;linearVelocity=[0,0,0];_physics3d=null;applyImpulse(e){this._physics3d?.applyImpulse(this,e)}},nv=class extends Q_{static typeName=`CharacterBody3D`;static props={velocity:{default:[0,0,0]},stickToGround:{default:!0},slopeLimitDeg:{default:45},stepHeight:{default:.35,range:{min:0}}};velocity=[0,0,0];stickToGround=!0;slopeLimitDeg=45;stepHeight=.35;onReady(){if(typeof this.snapToGround==`boolean`)throw new L(`PROP_TYPE_MISMATCH`,`'${this.getPath()}' sets snapToGround to a boolean. On a character body that is ambiguous: 'stickToGround' holds the capsule against the surface while it moves (default true), while 'snapToGround' PLACES the node on the ground at load and takes a lift in metres (e.g. 0.8) — omit it to leave y exactly as authored.`,{prop:`snapToGround`});super.onReady()}_grounded=!1;moveAndSlide(){if(!this._physics)throw new L(`TREE_VIOLATION`,this.collider.shape===void 0?`CharacterBody3D '${this.name}' has no collider — set a collider prop (physics skips collider-less bodies).`:`CharacterBody3D '${this.name}' has no physics world — await enablePhysics3D(engine) first.`);this._physics.moveAndSlide(this)}isOnFloor(){return this._grounded}};function rv(e,t){let n=e.scale;if(!Array.isArray(n)||n.every(e=>Math.abs((e??1)-1)<1e-4))return;let r=e.constructor.typeName??`node`,i=e.size,a=Array.isArray(i)?`size: [${i.map((e,t)=>(e??0)*(n[t===1?2:t]??1)).join(`, `)}]`:`size`;throw new L(`BAD_FORMAT`,`${r} '${e.name}' has scale ${JSON.stringify(n)}. On this node scale resizes only the MESH — ${t} read "size" — so the ground you can see would reach past the ground you can stand on. Resize with "${a}" instead.`,{prop:`scale`})}var iv=class extends Z_{static typeName=`WaterCutout3D`;static props={size:{default:[2,1,1]},enabled:{default:!0}};size=[2,1,1];enabled=!0;static validateJson(e){let t=e;if(!Array.isArray(t.size)||t.size.length!==3||t.size.some(e=>!(e>0)))throw new L(`BAD_FORMAT`,`WaterCutout3D '${e.name}' size must be three positive meters [x, y, z], got ${JSON.stringify(t.size)}.`,{prop:`size`})}onReady(){if(!this.parent?.parent)throw new L(`BAD_FORMAT`,`WaterCutout3D '${this.name}' must be a CHILD of the object that holds the water back (a hull, a diving bell, a dock's well) — it re-draws that object to keep water out of it, so at the scene root it has nothing to stand in for.`,{prop:`parent`})}},av=[`fancy`,`simple`],ov=[`trough`,`surface`,`peak`],sv=[`custom`,`ocean`,`pool`,`lake`,`pond`],cv={ocean:{waveHeight:.045,swell:.34,swellWavelength:52,whitecaps:.15,absorption:.17,opacity:.85,detailStrength:.17,sunIntensity:.85,colors:{trough:`#175360`,surface:`#2f8792`,peak:`#9bd8d2`},color:`#2f8792`,causticsAbove:.3,shoreWaves:.7,reflectionInterval:400,_look:{fresnelScale:1.15,reflectivityMax:.93,foamRangeScale:.35,foamIntensity:.55}},pool:{waveHeight:.006,swell:0,whitecaps:0,absorption:.3,opacity:.5,detailStrength:.16,sunIntensity:1.25,colors:{trough:`#1e8dbe`,surface:`#3fb6dc`,peak:`#bdeef7`},color:`#3fb6dc`,causticsAbove:1,reflectionInterval:600,_look:{fresnelScale:.85,reflectivityMax:.5,edgeFade:!1}},lake:{waveHeight:.028,swell:.14,swellWavelength:24,whitecaps:0,absorption:.5,opacity:.88,detailStrength:.3,colors:{trough:`#12343a`,surface:`#25565c`,peak:`#7fb2ab`},color:`#25565c`,causticsAbove:.15,reflectionInterval:300,_look:{fresnelScale:1.25,reflectivityMax:.78}},pond:{waveHeight:.006,swell:0,whitecaps:0,absorption:.85,opacity:.93,detailStrength:.14,sunIntensity:.7,colors:{trough:`#1c2e1e`,surface:`#39543c`,peak:`#6f8a68`},color:`#39543c`,causticsAbove:0,reflectionInterval:800,_look:{fresnelScale:1.05,reflectivityMax:.78,edgeFade:!1}}},lv={trough:`#135a72`,surface:`#2a86a0`,peak:`#a5ddd6`},uv={peakThreshold:.08,peakTransition:.05,troughThreshold:-.01,troughTransition:.15,fresnelScale:1,fresnelPower:5},dv={color:`#dcebe8`,intensity:.32,rangeMin:.45,rangeMax:1.4,scale:.35,edgeColor:`#ffffff`,edgeIntensity:.6,edgeWidth:.5};function fv(e,t){return Math.min(dv.rangeMax,Math.max(dv.rangeMin,Math.min(e,t)*.012))}var pv=128,mv=I_/L_,hv=256,gv=120,_v=2e3,vv=3,yv=640,bv=.06,xv=1024,Sv=.02,Cv=1.5,wv=24,Tv=160,Ev=32,Dv=.18,Ov=10,kv=.05,Av=.08,jv=.02,Mv=.18,Nv=.04,Pv=1.4,Fv=.04,Iv=.45,Lv=.08,Rv=.4,zv=.22,Bv=.09,Vv=.85,Hv=class e extends Z_{static typeName=`Water3D`;static signals=[`entered`,`exited`];static props={size:{default:[40,40]},color:{default:`#2a6fbe`},opacity:{default:.8},renderOrder:{default:1},waveHeight:{default:.04},waveSpeed:{default:1},quality:{default:`fancy`,options:av},colors:{default:{}},reflection:{default:!0},reflectionInterval:{default:1e3},mirror:{default:!1},mirrorInterval:{default:33},swellSteepness:{default:.35},foam:{default:!0},reflectivity:{default:null},interaction:{default:!0},splash:{default:!0},sunDirection:{default:[.5,.8,.3]},sunColor:{default:`#fff5d6`},sunIntensity:{default:1},detailStrength:{default:.26},absorption:{default:.15},refraction:{default:!0},underwater:{default:!0},swell:{default:0},swellDirectionDeg:{default:0},swellWavelength:{default:30},whitecaps:{default:0},preset:{default:`custom`,options:sv},causticsAbove:{default:0},shoreWaves:{default:0}};size=[40,40];color=`#2a6fbe`;opacity=.8;renderOrder=1;waveHeight=.04;waveSpeed=1;quality=`fancy`;colors={};reflection=!0;mirror=!1;mirrorInterval=33;reflectionInterval=1e3;foam=!0;reflectivity=null;interaction=!0;splash=!0;sunDirection=[.5,.8,.3];sunColor=`#fff5d6`;sunIntensity=1;detailStrength=.26;absorption=.15;refraction=!0;underwater=!0;swell=0;swellDirectionDeg=0;swellWavelength=30;swellSteepness=.35;whitecaps=0;preset=`custom`;causticsAbove=0;shoreWaves=0;rp(t){let n=cv[this.preset],r=this;if(n&&t in n){let i=e.props[t]?.default,a=r[t];if(typeof a==`object`&&a?JSON.stringify(a)===JSON.stringify(i):a===i)return n[t]}return r[t]}presetLook(){let e=cv[this.preset]?._look,t=this.rp(`reflectivity`);return{fresnelScale:e?.fresnelScale??uv.fresnelScale,reflectivityMax:typeof t==`number`?Math.min(Math.max(t,0),1):e?.reflectivityMax??.6,edgeFade:e?.edgeFade??!0,foamRangeScale:e?.foamRangeScale??1,foamIntensity:e?.foamIntensity??dv.intensity}}static validateJson(e){rv(e,`the water surface query, underwater fog, splashes and buoyancy all`);let t=e;if(!((t.size[0]??0)>0)||!((t.size[1]??0)>0))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' size must be positive [width, depth] meters, got ${JSON.stringify(t.size)}.`,{prop:`size`});if(!av.includes(t.quality))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' quality must be one of [${av.join(`, `)}], got '${t.quality}'.`,{prop:`quality`,validOptions:av});for(let[n,r]of Object.entries(t.colors)){if(!ov.includes(n))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' colors has unknown key '${n}'. Valid keys: [${ov.join(`, `)}].`,{prop:`colors`,validOptions:ov});if(typeof r!=`string`)throw new L(`BAD_FORMAT`,`Water3D '${e.name}' colors.${n} must be a hex color string, got ${JSON.stringify(r)}.`,{prop:`colors`})}if(!(t.reflectionInterval>0))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' reflectionInterval must be > 0 ms, got ${t.reflectionInterval}.`,{prop:`reflectionInterval`});let n=t.sunDirection;if(!Array.isArray(n)||n.length!==3||!n.every(e=>Number.isFinite(e))||Math.hypot(n[0]??0,n[1]??0,n[2]??0)===0)throw new L(`BAD_FORMAT`,`Water3D '${e.name}' sunDirection must be a non-zero [x, y, z] vector, got ${JSON.stringify(n)}.`,{prop:`sunDirection`});if(!(t.sunIntensity>=0))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' sunIntensity must be >= 0, got ${t.sunIntensity}.`,{prop:`sunIntensity`});if(!(t.detailStrength>=0))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' detailStrength must be >= 0, got ${t.detailStrength}.`,{prop:`detailStrength`});if(!(t.absorption>=0))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' absorption must be >= 0 (per-meter Beer's-law constant), got ${t.absorption}.`,{prop:`absorption`});if(!(t.swell>=0)||!Number.isFinite(t.swell))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' swell must be >= 0 meters (0 = off), got ${JSON.stringify(t.swell)}.`,{prop:`swell`});if(!(t.swellWavelength>=2))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' swellWavelength must be >= 2 meters, got ${JSON.stringify(t.swellWavelength)}.`,{prop:`swellWavelength`});if(!(t.whitecaps>=0)||!(t.whitecaps<=1))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' whitecaps must be in [0, 1], got ${JSON.stringify(t.whitecaps)}.`,{prop:`whitecaps`});if(!sv.includes(t.preset))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' preset must be one of [${sv.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:sv});if(!(t.shoreWaves>=0)||!(t.shoreWaves<=1))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' shoreWaves must be in [0, 1] (0 = off), got ${JSON.stringify(t.shoreWaves)}.`,{prop:`shoreWaves`});if(!(t.causticsAbove>=0)||!(t.causticsAbove<=3))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' causticsAbove must be in [0, 3] (0 = off), got ${JSON.stringify(t.causticsAbove)}.`,{prop:`causticsAbove`});let r=t.underwater;if(typeof r!=`boolean`){if(typeof r!=`object`||!r||Array.isArray(r))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' underwater must be true, false or an object ({ color?, visibility? }), got ${JSON.stringify(r)}.`,{prop:`underwater`});let t=r;if(t.color!==void 0&&typeof t.color!=`string`)throw new L(`BAD_FORMAT`,`Water3D '${e.name}' underwater.color must be a hex color string, got ${JSON.stringify(t.color)}.`,{prop:`underwater`});if(t.visibility!==void 0&&!(t.visibility>0))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' underwater.visibility must be > 0 meters, got ${JSON.stringify(t.visibility)}.`,{prop:`underwater`})}}time=0;surfaceKey=``;_ripples=[];inWater=new Set;bobTimers=new Map;wadeAnchors=new Map;_scratchA={x:0,y:0,z:0};_scratchB={x:0,y:0,z:0};_bodies=[];_cutouts=[];_maskMeshes=[];_maskSaved=[];_passHidden=[];cubeTarget=null;cubeCamera=null;reflectionNear=0;lastReflectionAt=0;scenePassTarget=null;mirrorTarget=null;mirrorCamera=new Cf;mirrorMatrix=new K;lastMirrorAt=0;lastMirrorEye=new W(1/0,1/0,1/0);lastMirrorQuat=new U;_createObject3D(){return new iu}update(e){this.time+=e*this.waveSpeed,u_(this._ripples,e),this.interaction&&this.stepInteraction(e)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();this.rebuildSurfaceIfNeeded(e),this.effectiveQuality()===`simple`?this.syncSimple(e):this.syncFancy(e)}_onRender3D(e){let t=this._ensureObject3D(),n=t.material;if(e.camera.updateWorldMatrix(!0,!1),e.camera.getWorldPosition(oy),this.underwaterAt(oy.x,oy.y,oy.z)){if(n.isShaderMaterial){let e=n.uniforms;e.uUseSceneDepth&&(e.uUseSceneDepth.value=0),e.uUseRefraction&&(e.uUseRefraction.value=0),e.uUseMirror&&(e.uUseMirror.value=0),e.uCameraSubmerged&&(e.uCameraSubmerged.value=1)}this.noteIdleFrame();return}if(this.effectiveQuality()!==`fancy`||!n.isShaderMaterial)return;let r=Math.hypot((this.size[0]??1)/2,(this.size[1]??1)/2);if(!a_(e.camera,Zv(this),r+1)){this.noteIdleFrame();return}let i=n.uniforms;i.uCameraSubmerged&&(i.uCameraSubmerged.value=0),this.idleFrames=0;let a=Date.now();if(this.reflection){this.cubeTarget||=new Bp(hv,{generateMipmaps:!0,minFilter:_a,type:Ta});let n=Math.max((this.size[0]??1)/2,(this.size[1]??1)/2);(!this.cubeCamera||this.reflectionNear!==n)&&(this.reflectionNear=n,this.cubeCamera=new Lf(n,1e3,this.cubeTarget),this.lastReflectionAt=0);let r=this.effectiveCubeInterval();if(this.lastReflectionAt===0||a-this.lastReflectionAt>=r){this.lastReflectionAt=a;let n=Zv(this),r=this.cubeCamera;r.position.set(n.x,n.y+.1,n.z);let i=t.visible;t.visible=!1,r.update(e.gl,e.scene),t.visible=i}i.uEnvironmentMap&&i.uUseEnvironmentMap&&(i.uEnvironmentMap.value=this.cubeTarget.texture,i.uUseEnvironmentMap.value=1)}if(this.effectiveMirror()&&i.uMirrorMap&&i.uMirrorMatrix&&i.uUseMirror){e.gl.getDrawingBufferSize(ay);let n=Math.max(1,Math.min(Math.round(ay.x/vv),yv)),r=Math.max(1,Math.min(Math.round(ay.y/vv),yv));this.mirrorTarget&&(this.mirrorTarget.width!==n||this.mirrorTarget.height!==r)&&(this.mirrorTarget.dispose(),this.mirrorTarget=null),this.mirrorTarget||=new Xs(n,r,{depthBuffer:!0,stencilBuffer:!1,type:Ta,samples:4});let o=Zv(this).y,s=e.camera;s.getWorldPosition(cy),s.getWorldQuaternion(fy),uy.set(0,0,-1).applyQuaternion(fy).add(cy),dy.set(0,1,0).applyQuaternion(fy),cy.y=2*o-cy.y,uy.y=2*o-uy.y,dy.y=-dy.y;let c=this.mirrorCamera;c.fov=s.fov??50,c.aspect=s.aspect??n/r,c.near=s.near??.1,c.far=s.far??1e3,c.position.copy(cy),c.up.copy(dy),c.lookAt(uy),c.updateMatrixWorld(!0),c.updateProjectionMatrix(),s.getWorldPosition(ly);let l=ly.distanceToSquared(this.lastMirrorEye)>1e-6||Math.abs(fy.dot(this.lastMirrorQuat))<.9999995;if(this.lastMirrorAt===0||l||a-this.lastMirrorAt>=this.rp(`mirrorInterval`)){this.lastMirrorAt=a,this.lastMirrorEye.copy(ly),this.lastMirrorQuat.copy(fy),this.mirrorMatrix.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),this.mirrorMatrix.multiply(c.projectionMatrix),this.mirrorMatrix.multiply(c.matrixWorldInverse);let n=e.gl.getRenderTarget(),r=e.gl.clippingPlanes,i=t.visible;t.visible=!1,py.constant=-(o-Sv),e.gl.clippingPlanes=my,e.gl.setRenderTarget(this.mirrorTarget),e.gl.clear(!0,!0,!1),__(e.scene,this._passHidden),e.gl.render(e.scene,c),v_(this._passHidden),e.gl.setRenderTarget(n),e.gl.clippingPlanes=r,t.visible=i}i.uMirrorMap.value=this.mirrorTarget.texture,i.uMirrorMatrix.value.copy(this.mirrorMatrix),i.uUseMirror.value=1}else i.uUseMirror&&(i.uUseMirror.value=0,this.releasePassTargets(`mirror`));e.gl.getDrawingBufferSize(ay);let o=Math.max(1,Math.min(Math.round(ay.x/2),xv)),s=Math.max(1,Math.min(Math.round(ay.y/2),xv));if(this.scenePassTarget&&(this.scenePassTarget.width!==o||this.scenePassTarget.height!==s)&&(this.scenePassTarget.depthTexture?.dispose(),this.scenePassTarget.dispose(),this.scenePassTarget=null),!this.scenePassTarget){let e=new cd(o,s);e.type=wa,this.scenePassTarget=new Xs(o,s,{depthTexture:e,depthBuffer:!0,stencilBuffer:!1,generateMipmaps:!0,minFilter:_a})}let c=e.gl.getRenderTarget(),l=e.gl.autoClear,u=e.gl.clippingPlanes,d=t.visible;t.visible=!1;let f=Zv(this).y;hy.constant=f+Sv,e.gl.clippingPlanes=gy,e.gl.setRenderTarget(this.scenePassTarget),e.gl.autoClear=!0,e.gl.clear(!0,!0,!1),e.gl.render(e.scene,e.camera),vy.constant=-(f-Sv),e.gl.clippingPlanes=yy;let p=e.scene.overrideMaterial,m=e.scene.background;e.scene.overrideMaterial=by,e.scene.background=null,e.gl.autoClear=!1,__(e.scene,this._passHidden),e.gl.render(e.scene,e.camera),v_(this._passHidden),e.scene.overrideMaterial=p,e.scene.background=m,this.renderCutoutMasks(e),e.gl.setRenderTarget(c),e.gl.autoClear=l,e.gl.clippingPlanes=u,t.visible=d,i.uDepthTexture&&i.uSceneColor&&i.uCameraNear&&i.uCameraFar&&i.uUseSceneDepth&&(i.uDepthTexture.value=this.scenePassTarget.depthTexture,(i.uScenePassTexel?.value)?.set(1/o,1/s),i.uSceneColor.value=this.scenePassTarget.texture,i.uCameraNear.value=e.camera.near,i.uCameraFar.value=e.camera.far,i.uUseSceneDepth.value=1,i.uUseRefraction&&(i.uUseRefraction.value=+!!this.refraction),i.uEnableFoam&&(i.uEnableFoam.value=+!!this.foam))}underwaterAt(e,t,n){if(this.underwater===!1)return null;let r=Zv(this,this._scratchA);if(!T_(e,t,n,{centerX:r.x,centerY:r.y,centerZ:r.z,halfW:(this.size[0]??1)/2,halfD:(this.size[1]??1)/2},sy))return null;let i=k_(this.underwater,this.rp(`color`));return i.enabled?{...i,surfaceY:r.y}:null}releasePassTargets(e){this.mirrorTarget?.dispose(),this.mirrorTarget=null,e!==`mirror`&&(this.cubeTarget?.dispose(),this.cubeTarget=null,this.cubeCamera=null,this.scenePassTarget?.depthTexture?.dispose(),this.scenePassTarget?.dispose(),this.scenePassTarget=null)}idleFrames=0;caps=null;_applyQualityCaps(e){this.caps=e}effectiveQuality(){return this.caps&&!this.caps.fancyWater&&this.canFadeItsOwnRim()?`simple`:this.quality}canFadeItsOwnRim(){return Math.max(this.size[0]??1,this.size[1]??1)/2*Dv<=Ov}effectiveMirror(){return this.mirror&&(this.caps?this.caps.waterMirror:!0)}effectiveCubeInterval(){let e=this.rp(`reflectionInterval`),t=this.effectiveMirror()?Math.max(e,_v):e;return Math.max(t,this.caps?.minReflectionIntervalMs??0)}noteIdleFrame(){this.idleFrames+=1,this.idleFrames===gv&&this.releasePassTargets(`all`)}free(){let e=this._builtObject3D;e?.geometry?.dispose(),(e?.material)?.dispose?.(),this.releasePassTargets(`all`),super.free()}rebuildSurfaceIfNeeded(e){let t=this.effectiveQuality(),n=JSON.stringify([this.size,t]);if(n===this.surfaceKey&&e.geometry.getAttribute(`position`))return;this.surfaceKey=n,e.geometry?.dispose(),e.material?.dispose?.();let r=this.size[0]??1,i=this.size[1]??1;t===`simple`?(this.releasePassTargets(`all`),e.geometry=ey(r,i,Ev),e.material=this.buildLakeMaterial()):(e.geometry=ey(r,i,Math.min(Math.max(Math.round(Math.max(r,i)*Cv),wv),Tv)),e.material=this.buildFancyMaterial())}buildFancyMaterial(){return new Dd({vertexShader:C_,fragmentShader:w_,fog:!0,uniforms:{fogColor:{value:new q(`#ffffff`)},fogNear:{value:1},fogFar:{value:1e3},fogDensity:{value:25e-5},uTime:{value:0},uOpacity:{value:this.rp(`opacity`)},uEnvironmentMap:{value:null},uUseEnvironmentMap:{value:0},uMirrorMap:{value:null},uMirrorMatrix:{value:new K},uUseMirror:{value:0},uMirrorDistort:{value:bv},uWavesAmplitude:{value:this.rp(`waveHeight`)*mv},uWavesSpeed:{value:F_.speed},uWavesFrequency:{value:F_.frequency},uWavesPersistence:{value:F_.persistence},uWavesLacunarity:{value:F_.lacunarity},uWavesIterations:{value:F_.iterations},uTroughColor:{value:new q(lv.trough)},uSurfaceColor:{value:new q(lv.surface)},uPeakColor:{value:new q(lv.peak)},uPeakThreshold:{value:uv.peakThreshold},uPeakTransition:{value:uv.peakTransition},uTroughThreshold:{value:uv.troughThreshold},uTroughTransition:{value:uv.troughTransition},uFresnelScale:{value:uv.fresnelScale},uFresnelPower:{value:uv.fresnelPower},uScale:{value:new W(1,1,1)},uWaterCenter:{value:new W},uRipples:{value:Array.from({length:8},()=>new Js)},uRippleFoam:{value:Array.from({length:8},()=>0)},uSplashFoam:{value:+!!this.splash},uSunDirection:{value:new W(.5,.8,.3)},uSunColor:{value:new q(this.sunColor)},uSunIntensity:{value:this.rp(`sunIntensity`)},uDetailStrength:{value:this.rp(`detailStrength`)},uAbsorption:{value:this.rp(`absorption`)},uUseSceneDepth:{value:0},uUseRefraction:{value:0},uSceneColor:{value:null},uEnableFoam:{value:0},uFoamColor:{value:new q(dv.color)},uFoamIntensity:{value:dv.intensity},uFoamRange:{value:fv(this.size[0]??1,this.size[1]??1)},uFoamScale:{value:dv.scale},uDepthTexture:{value:null},uScenePassTexel:{value:new H(1/512,1/512)},uCameraNear:{value:.1},uCameraFar:{value:1e3},uEdgeColor:{value:new q(dv.edgeColor)},uEdgeIntensity:{value:dv.edgeIntensity},uEdgeWidth:{value:dv.edgeWidth},uSwellAmplitude:{value:this.rp(`swell`)},uSwellDir:{value:new H(0,1)},uSwellWavelength:{value:this.rp(`swellWavelength`)},uSwellSteepness:{value:this.rp(`swellSteepness`)},uWhitecaps:{value:this.rp(`whitecaps`)},uWaveEnvelope:{value:0},uCausticsAbove:{value:this.rp(`causticsAbove`)},uShoreWaves:{value:this.rp(`shoreWaves`)},uReflectivityMax:{value:.6},uCameraSubmerged:{value:0},uEdgeFadeOn:{value:1}},transparent:!0,depthTest:!0,depthWrite:!0,side:2})}buildLakeMaterial(){return new Dd({vertexShader:m_,fragmentShader:h_,fog:!0,uniforms:{fogColor:{value:new q(`#ffffff`)},fogNear:{value:1},fogFar:{value:1e3},fogDensity:{value:25e-5},uTime:{value:0},uOpacity:{value:this.rp(`opacity`)},uColor:{value:new q(this.rp(`color`))},uSurfaceColor:{value:new q(this.rp(`color`))},uSkyColor:{value:new q(this.rp(`color`))},uSunDirection:{value:new W(.5,.8,.3).normalize()},uSunColor:{value:new q(this.sunColor)},uSunIntensity:{value:this.rp(`sunIntensity`)},uDetailStrength:{value:this.rp(`detailStrength`)},uFresnelPower:{value:uv.fresnelPower},uScale:{value:new W(1,1,1)},uWaterCenter:{value:new W},uRipples:{value:Array.from({length:8},()=>new Js)},uRippleFoam:{value:Array.from({length:8},()=>0)},uSplashFoam:{value:+!!this.splash},uFoamColor:{value:new q(dv.color)}},transparent:!0,depthTest:!0,depthWrite:!1,side:2})}renderCutoutMasks(e){let t=this._cutouts;t.length=0;let n=this;for(;n.parent;)n=n.parent;if(Kv(n,t),t.length===0)return;let r=xy.uniforms,i=this._maskSaved,a=this._maskMeshes,o=e.gl.clippingPlanes;e.gl.clippingPlanes=_y;let s=0;for(let n of t){if(s>=4)break;let t=qv(n);if(!t)continue;n._syncObject3D();let o=n._ensureObject3D();if(o.updateWorldMatrix(!0,!1),o.getWorldPosition(Uv),o.getWorldQuaternion(Wv),(r.uCenter?.value)?.copy(Uv),(r.uHalf?.value)?.set((n.size[0]??1)/2,(n.size[1]??1)/2,(n.size[2]??1)/2),Gv.setFromQuaternion(Wv,`YXZ`),(r.uYaw?.value)?.set(Math.cos(Gv.y),Math.sin(Gv.y)),a.length=0,i.length=0,Yv(t,a),a.length!==0){for(let e of a)i.push(e.material),e.material=xy;e.gl.render(t,e.camera);for(let e=0;e<a.length;e++){let t=a[e],n=i[e];t&&n&&(t.material=n)}s++}}a.length=0,i.length=0,e.gl.clippingPlanes=o}syncFancy(e){let t=e.material.uniforms,n=this.size[0]??1,r=this.size[1]??1,i=Zv(this);t.uTime&&(t.uTime.value=this.time),t.uOpacity&&(t.uOpacity.value=this.rp(`opacity`)),t.uWavesAmplitude&&(t.uWavesAmplitude.value=this.rp(`waveHeight`)*mv),(t.uScale?.value)?.set(n/2,r/2,r/2),(t.uWaterCenter?.value)?.set(i.x,i.y,i.z);let a=this.resolvePalette();(t.uTroughColor?.value)?.copy(a.trough),(t.uSurfaceColor?.value)?.copy(a.surface),(t.uPeakColor?.value)?.copy(a.peak),(t.uSunDirection?.value)?.set(this.sunDirection[0]??0,this.sunDirection[1]??1,this.sunDirection[2]??0).normalize(),(t.uSunColor?.value)?.set(this.sunColor),t.uSunIntensity&&(t.uSunIntensity.value=this.rp(`sunIntensity`)),t.uDetailStrength&&(t.uDetailStrength.value=this.rp(`detailStrength`)),t.uAbsorption&&(t.uAbsorption.value=this.rp(`absorption`)),t.uSwellAmplitude&&(t.uSwellAmplitude.value=this.rp(`swell`)),t.uSwellWavelength&&(t.uSwellWavelength.value=this.rp(`swellWavelength`)),t.uSwellSteepness&&(t.uSwellSteepness.value=this.rp(`swellSteepness`)),t.uWhitecaps&&(t.uWhitecaps.value=this.rp(`whitecaps`)),t.uCausticsAbove&&(t.uCausticsAbove.value=this.rp(`causticsAbove`)),t.uShoreWaves&&(t.uShoreWaves.value=this.rp(`shoreWaves`));let o=this.presetLook();t.uFresnelScale&&(t.uFresnelScale.value=o.fresnelScale),t.uReflectivityMax&&(t.uReflectivityMax.value=o.reflectivityMax),t.uEdgeFadeOn&&(t.uEdgeFadeOn.value=+!!o.edgeFade),t.uFoamRange&&(t.uFoamRange.value=fv(n,r)*o.foamRangeScale),t.uFoamIntensity&&(t.uFoamIntensity.value=o.foamIntensity);let s=this.swellDirectionDeg*Math.PI/180;(t.uSwellDir?.value)?.set(Math.sin(s),Math.cos(s)),t.uWaveEnvelope&&(t.uWaveEnvelope.value=this.rp(`waveHeight`)*mv*1.5+this.rp(`swell`)*1.03),!this.reflection&&t.uUseEnvironmentMap&&(t.uUseEnvironmentMap.value=0),!this.foam&&t.uEnableFoam&&(t.uEnableFoam.value=0),!this.refraction&&t.uUseRefraction&&(t.uUseRefraction.value=0),t.uSplashFoam&&(t.uSplashFoam.value=+!!this.splash);let c=t.uRipples?.value,l=t.uRippleFoam?.value;if(c)for(let e=0;e<c.length;e++){let t=this._ripples[e];t?c[e].set(t.x,t.z,t.age,t.amp):c[e].set(0,0,0,0),l&&(l[e]=t?t.foam??0:0)}}_applySunDirection(t){let n=e.props.sunDirection?.default;this.sunDirection.every((e,t)=>e===n[t])&&(this._ensureObject3D().material.uniforms?.uSunDirection?.value)?.set(t[0],t[1],t[2])}resolvePalette(){let t=this.rp(`colors`),n=this.rp(`color`),r=n===e.props.color?.default?null:n,i=t.surface??r??lv.surface;return iy.surface.set(i),t.trough?iy.trough.set(t.trough):r?iy.trough.set(r).lerp(ty,.45):iy.trough.set(lv.trough),t.peak?iy.peak.set(t.peak):r?iy.peak.set(r).lerp(ny,.3):iy.peak.set(lv.peak),iy}syncSimple(e){let t=e.material;t.opacity=this.rp(`opacity`);let n=t.uniforms,r=this.size[0]??1,i=this.size[1]??1,a=Zv(this,this._scratchA);n.uTime&&(n.uTime.value=this.time),n.uOpacity&&(n.uOpacity.value=this.rp(`opacity`)),(n.uSurfaceColor?.value)?.set(this.rp(`color`)).lerp(ny,.12),(n.uColor?.value)?.set(this.rp(`color`)).lerp(ty,.4),(n.uSkyColor?.value)?.set(this.rp(`color`)).lerp(ry,.82),(n.uScale?.value)?.set(r/2,i/2,i/2),(n.uWaterCenter?.value)?.set(a.x,a.y,a.z),(n.uSunDirection?.value)?.set(this.sunDirection[0]??0,this.sunDirection[1]??1,this.sunDirection[2]??0).normalize(),(n.uSunColor?.value)?.set(this.sunColor),n.uSunIntensity&&(n.uSunIntensity.value=this.rp(`sunIntensity`)),n.uDetailStrength&&(n.uDetailStrength.value=this.rp(`detailStrength`)),n.uSplashFoam&&(n.uSplashFoam.value=+!!this.splash);let o=n.uRipples?.value,s=n.uRippleFoam?.value;if(o)for(let e=0;e<o.length;e++){let t=this._ripples[e];t?o[e].set(t.x,t.z,t.age,t.amp):o[e].set(0,0,0,0),s&&(s[e]=t?t.foam??0:0)}let c=e.geometry,l=c.getAttribute(`position`),u=c.getAttribute(`normal`),d=this.time,f=this.rp(`waveHeight`),p=a.x,m=a.z,h=this._ripples,g=.5;for(let e=0;e<l.count;e++){let t=l.getX(e),n=l.getZ(e),r=J_(t,n,d,f)+f_(t+p,n+m,h);l.setY(e,r);let i=J_(t+g,n,d,f)+f_(t+p+g,n+m,h),a=J_(t,n+g,d,f)+f_(t+p,n+m+g,h),o=(r-i)/g,s=(r-a)/g,c=1/Math.hypot(o,1,s);u.setXYZ(e,o*c,c,s*c)}l.needsUpdate=!0,u.needsUpdate=!0}stepInteraction(e){let t=this;for(;t.parent;)t=t.parent;let n=this._bodies;n.length=0,Xv(t,n);let r=Zv(this,this._scratchA),i=(this.size[0]??0)/2,a=(this.size[1]??0)/2,o=[];for(let e of n){let t=Zv(e,this._scratchB);if(Math.abs(t.x-r.x)>i||Math.abs(t.z-r.z)>a)continue;let n=o_(e.collider);o.push({id:e,x:t.x,y:t.y,z:t.z,waterline:r.y+this.waveOffsetAt(t.x,t.z,r)+n})}let{entered:s,exited:c,inWater:l}=c_(this.inWater,o,kv);this.inWater=l;let u=this.splash;for(let e of s){let t=Math.abs(Qv(e.id)?.[1]??0);l_(this._ripples,e.x,e.z,$v(e.id),u?s_(t):0),this.emit(`entered`,e.id)}for(let e of c)l_(this._ripples,e.x,e.z,Nv,u?Rv:0),this.emit(`exited`,e.id);for(let t of p_(this.bobTimers,l,e,Pv)){let e=Zv(t,this._scratchB);l_(this._ripples,e.x,e.z,Fv)}for(let e of l){let t=Zv(e,this._scratchB),n=this.wadeAnchors.get(e);if(!n){this.wadeAnchors.set(e,{x:t.x,z:t.z});continue}let r=t.x-n.x,i=t.z-n.z;if(r*r+i*i>=Iv*Iv){let r=Qv(e),i=Math.hypot(r?.[0]??0,r?.[2]??0),a=u?Math.min(zv+Bv*i,Vv):0;l_(this._ripples,t.x,t.z,Lv,a),n.x=t.x,n.z=t.z}}for(let e of this.wadeAnchors.keys())l.has(e)||this.wadeAnchors.delete(e)}heightAt(e,t){let n=Zv(this,this._scratchA);return n.y+this.waveOffsetAt(e,t,n)}_waterYAt(e,t){let n=Zv(this,this._scratchA),r=(this.size[0]??0)/2,i=(this.size[1]??0)/2;return Math.abs(e-n.x)>r||Math.abs(t-n.z)>i?null:n.y}waveOffsetAt(e,t,n){return this.effectiveQuality()===`simple`?J_(e-n.x,t-n.z,this.time,this.rp(`waveHeight`)):q_(e,t,this.time,{amplitude:this.rp(`waveHeight`)*mv,frequency:F_.frequency,persistence:F_.persistence,lacunarity:F_.lacunarity,iterations:F_.iterations,speed:F_.speed,scaleNorm:pv})}},Uv=new W,Wv=new U,Gv=new cc;function Kv(e,t){e instanceof iv&&e.enabled&&e.visible&&t.push(e);for(let n of e.children)Kv(n,t)}function qv(e){let t=e.parent;if(!(t instanceof Z_)||!t.parent)return null;let n=t._ensureObject3D();return typeof n?.traverse==`function`?n:null}var Jv=new Set([`Terrain3D`,`Water3D`,`River3D`]);function Yv(e,t){return e.traverse(e=>{let n=e;if(!n.isMesh||!n.visible||!n.material)return;let r=(e.userData?.incantoNode)?.constructor?.typeName;r&&Jv.has(r)||t.push(n)}),t}function Xv(e,t){(e instanceof nv||e instanceof tv)&&t.push(e);for(let n of e.children)Xv(n,t)}function Zv(e,t={x:0,y:0,z:0}){let n=0,r=0,i=0,a=e;for(;a;)a instanceof Z_&&(n+=a.position[0]??0,r+=a.position[1]??0,i+=a.position[2]??0),a=a.parent;return t.x=n,t.y=r,t.z=i,t}function Qv(e){return e.velocity??e.linearVelocity}function $v(e){let t=Math.abs(Qv(e)?.[1]??0);return Math.min(Av+jv*t,Mv)}function ey(e,t,n){let r=new _d(e,t,n,n);return r.rotateX(-Math.PI/2),r}var ty=new q(`#000000`),ny=new q(`#ffffff`),ry=new q(`#cfe3f0`),iy={trough:new q,surface:new q,peak:new q},ay=new H,oy=new W,sy=3,cy=new W,ly=new W,uy=new W,dy=new W,fy=new U,py=new Pu(new W(0,1,0),0),my=[py],hy=new Pu(new W(0,-1,0),0),gy=[hy],_y=[],vy=new Pu(new W(0,1,0),0),yy=[vy],by=new jd;by.colorWrite=!1;var xy=new Dd({uniforms:{uCenter:{value:new W},uHalf:{value:new W(1,1,1)},uYaw:{value:new H(1,0)}},vertexShader:`
|
|
5750
|
+
`;function E_(e,t,n,r,i=0){return t>=r.centerY?!1:Math.abs(e-r.centerX)<=r.halfW+i&&Math.abs(n-r.centerZ)<=r.halfD+i}var D_=22,O_={enabled:!0,strength:.6},k_={enabled:!0,color:`#cdeeff`,intensity:.55,scale:.32,speed:1};function A_(e,t){if(e===!1)return{enabled:!1,color:N_(t),visibility:D_,caustics:k_,rays:{...O_,enabled:!1}};let n=e&&typeof e==`object`?e:{};return{enabled:!0,color:n.color??N_(t),visibility:n.visibility??D_,caustics:M_(n.caustics),rays:j_(n.rays)}}function j_(e){return e===!1?{...O_,enabled:!1}:typeof e==`number`?{enabled:e>0,strength:e}:{...O_}}function M_(e){if(e===!1)return{...k_,enabled:!1};let t=e&&typeof e==`object`?e:{};return{enabled:!0,color:typeof t.color==`string`?t.color:k_.color,intensity:typeof t.intensity==`number`?t.intensity:k_.intensity,scale:typeof t.scale==`number`?t.scale:k_.scale,speed:typeof t.speed==`number`?t.speed:k_.speed}}function N_(e){let{r:t,g:n,b:r}=P_(e),i=(e,t,n)=>Math.round(e*(1-n)+t*n);return F_(Math.round(i(t,6,.45)*.7),Math.round(i(n,40,.4)*.78),Math.round(i(r,70,.35)*.82))}function P_(e){let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return{r:Number.parseInt(n.slice(0,2),16)||0,g:Number.parseInt(n.slice(2,4),16)||0,b:Number.parseInt(n.slice(4,6),16)||0}}function F_(e,t,n){let r=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,`0`);return`#${r(e)}${r(t)}${r(n)}`}var I_={frequency:6.7,persistence:.3,lacunarity:2.18,iterations:9,speed:.5},L_=.525,R_=.08,z_={freqX:.7,freqZ:.5,cross:.6};function B_(e,t){return e-Math.floor(e/t)*t}function V_(e){return e-Math.floor(e)}function H_(e){return B_((e*34+1)*e,289)}var U_=.211324865405187,W_=.366025403784439,G_=-.577350269189626,K_=.024390243902439;function q_(e,t){let n=Math.floor(e+(e+t)*W_),r=Math.floor(t+(e+t)*W_),i=e-n+(n+r)*U_,a=t-r+(n+r)*U_,o=+(i>a),s=i>a?0:1,c=i+U_-o,l=a+U_-s,u=i+G_,d=a+G_;n=B_(n,289),r=B_(r,289);let f=H_(H_(r)+n),p=H_(H_(r+s)+n+o),m=H_(H_(r+1)+n+1),h=Math.max(.5-(i*i+a*a),0),g=Math.max(.5-(c*c+l*l),0),_=Math.max(.5-(u*u+d*d),0);h*=h,h*=h,g*=g,g*=g,_*=_,_*=_;let v=2*V_(f*K_)-1,y=2*V_(p*K_)-1,b=2*V_(m*K_)-1,x=Math.abs(v)-.5,S=Math.abs(y)-.5,C=Math.abs(b)-.5,w=v-Math.floor(v+.5),T=y-Math.floor(y+.5),E=b-Math.floor(b+.5);h*=1.79284291400159-.85373472095314*(w*w+x*x),g*=1.79284291400159-.85373472095314*(T*T+S*S),_*=1.79284291400159-.85373472095314*(E*E+C*C);let D=w*i+x*a,O=T*c+S*l,k=E*u+C*d;return 130*(h*D+g*O+_*k)}function J_(e,t,n,r){let i=Math.max(r.scaleNorm,1e-6),a=e/i,o=t/i,s=0,c=1,l=r.frequency,u=n*r.speed;for(let e=0;e<r.iterations;e++)s+=c*q_(a*l+u,o*l+u),c*=r.persistence,l*=r.lacunarity;return s*r.amplitude}function Y_(e,t,n,r){return r*(Math.sin(e*z_.freqX+n)+z_.cross*Math.sin(t*z_.freqZ+n*1.3))}function X_(e,t){let n=e.shape;if(n!==void 0){if(n===`box`){let n=e.size;if(!Array.isArray(n)||n.length!==3||n.some(e=>typeof e!=`number`))throw new L(`BAD_FORMAT`,`Collider on '${t}': box needs "size": [x, y, z].`);return}if(n===`sphere`){if(typeof e.radius!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${t}': sphere needs "radius".`);return}if(n===`capsule`){if(typeof e.radius!=`number`||typeof e.height!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${t}': capsule needs "radius" and "height".`);return}if(n===`trimesh`){let n=e.vertices,r=e.indices;if(!Array.isArray(n)||n.length%3!=0||!Array.isArray(r)||r.length%3!=0)throw new L(`BAD_FORMAT`,`Collider on '${t}': trimesh needs "vertices" (flat xyz floats) and "indices" (triangle triplets).`);return}if(n!==`heightfield`&&n!==`auto`)throw new L(`BAD_FORMAT`,`Collider on '${t}': "shape" must be 'auto', 'box', 'sphere', 'capsule', 'trimesh', or 'heightfield', got ${JSON.stringify(n)}.`)}}function Z_(e){let t=e;if(t.constructor?.typeName===`Terrain3D`&&typeof t.heightAt==`function`)return e;for(let t of e.children){let e=Z_(t);if(e)return e}return null}var Q_=class e extends Ft{static typeName=`Node3D`;static props={position:{default:[0,0,0]},rotation:{default:[0,0,0]},static:{default:!1},scale:{default:[1,1,1]},visible:{default:!0},renderOrder:{default:0},orderGroup:{default:`default`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},snapToGround:{default:null}};position=[0,0,0];rotation=[0,0,0];static=!1;scale=[1,1,1];visible=!0;renderOrder=0;orderGroup=`default`;snapToGround=null;get effectiveRenderOrder(){return gn(this.orderGroup,this.renderOrder,this.tree?.engine?.orderGroups)}_object3D=null;_interpPrev=null;_interpCurr=null;onReady(){this.applyGroundSnap()}applyGroundSnap(){if(this.snapToGround===null||this.snapToGround===!1)return;let t=this.snapToGround===!0?0:this.snapToGround,n=Z_(this.getRoot());if(!n)return;let r=this.position[0]??0,i=0,a=this.position[2]??0;for(let t=this.parent;t;t=t.parent){if(!(t instanceof e))continue;let n=(t.rotation[1]??0)*Math.PI/180;if(n!==0){let e=Math.cos(n),t=Math.sin(n),i=r*e+a*t,o=-r*t+a*e;r=i,a=o}r+=t.position[0]??0,i+=t.position[1]??0,a+=t.position[2]??0}let o=r,s=a;this.position=[this.position[0]??0,n.heightAt(o,s)+t-i,this.position[2]??0]}get _builtObject3D(){return this._object3D}_ensureObject3D(){return this._object3D||(this._object3D=this._createObject3D(),this._object3D.userData.incantoNode=this),this._object3D}_createObject3D(){return new Tc}_syncObject3D(e=1,t=null){let n=this._ensureObject3D(),r=this._interpPrev,i=this._interpCurr;r&&i?n.position.set((r[0]??0)+((i[0]??0)-(r[0]??0))*e,(r[1]??0)+((i[1]??0)-(r[1]??0))*e,(r[2]??0)+((i[2]??0)-(r[2]??0))*e):n.position.set(this.position[0]??0,this.position[1]??0,this.position[2]??0),n.rotation.set(As.degToRad(this.rotation[0]??0),As.degToRad(this.rotation[1]??0),As.degToRad(this.rotation[2]??0)),n.scale.set(this.scale[0]??1,this.scale[1]??1,this.scale[2]??1),n.visible=this.visible,n.renderOrder=this.effectiveRenderOrder}free(){super.free(),this._object3D?.removeFromParent(),this._object3D=null,this._interpPrev=null,this._interpCurr=null}},$_=class extends Q_{static props={collider:{default:{},variants:{tag:`shape`,byTag:{auto:{shape:`auto`},box:{shape:`box`,size:[1,1,1]},sphere:{shape:`sphere`,radius:.5},capsule:{shape:`capsule`,radius:.35,height:1},trimesh:{shape:`trimesh`,vertices:[],indices:[]},heightfield:{shape:`heightfield`}}}},enabled:{default:!0}};static signals=[`triggerEnter`,`triggerExit`];_collider={};_colliderChanged=!1;_enabled=!0;_enabledChanged=!1;get collider(){return this._collider}set collider(e){this._collider=e,this._colliderChanged=!0}get enabled(){return this._enabled}set enabled(e){e!==this._enabled&&(this._enabled=e,this._enabledChanged=!0)}static validateJson(e){let t=e;if(X_(t.collider,e.name),t.collider.shape===`heightfield`&&!(t instanceof ev))throw new L(`BAD_FORMAT`,`Collider on '${e.name}': heightfield is static terrain — put it on a StaticBody3D (with a Terrain3D child), not a ${t.constructor.typeName}.`,{prop:`collider`})}_physics=null},ev=class extends $_{static typeName=`StaticBody3D`},tv=class extends $_{static typeName=`Area3D`},nv=class extends $_{static typeName=`RigidBody3D`;static props={mass:{default:1},gravityScale:{default:1},fixedRotation:{default:!1},friction:{default:.5},restitution:{default:0},linearVelocity:{default:[0,0,0]}};mass=1;gravityScale=1;fixedRotation=!1;friction=.5;restitution=0;linearVelocity=[0,0,0];_physics3d=null;applyImpulse(e){this._physics3d?.applyImpulse(this,e)}},rv=class extends $_{static typeName=`CharacterBody3D`;static props={velocity:{default:[0,0,0]},stickToGround:{default:!0},slopeLimitDeg:{default:45},stepHeight:{default:.35,range:{min:0}}};velocity=[0,0,0];stickToGround=!0;slopeLimitDeg=45;stepHeight=.35;onReady(){if(typeof this.snapToGround==`boolean`)throw new L(`PROP_TYPE_MISMATCH`,`'${this.getPath()}' sets snapToGround to a boolean. On a character body that is ambiguous: 'stickToGround' holds the capsule against the surface while it moves (default true), while 'snapToGround' PLACES the node on the ground at load and takes a lift in metres (e.g. 0.8) — omit it to leave y exactly as authored.`,{prop:`snapToGround`});super.onReady()}_grounded=!1;moveAndSlide(){if(!this._physics)throw new L(`TREE_VIOLATION`,this.collider.shape===void 0?`CharacterBody3D '${this.name}' has no collider — set a collider prop (physics skips collider-less bodies).`:`CharacterBody3D '${this.name}' has no physics world — await enablePhysics3D(engine) first.`);this._physics.moveAndSlide(this)}isOnFloor(){return this._grounded}};function iv(e,t){let n=e.scale;if(!Array.isArray(n)||n.every(e=>Math.abs((e??1)-1)<1e-4))return;let r=e.constructor.typeName??`node`,i=e.size,a=Array.isArray(i)?`size: [${i.map((e,t)=>(e??0)*(n[t===1?2:t]??1)).join(`, `)}]`:`size`;throw new L(`BAD_FORMAT`,`${r} '${e.name}' has scale ${JSON.stringify(n)}. On this node scale resizes only the MESH — ${t} read "size" — so the ground you can see would reach past the ground you can stand on. Resize with "${a}" instead.`,{prop:`scale`})}var av=class extends Q_{static typeName=`WaterCutout3D`;static props={size:{default:[2,1,1]},enabled:{default:!0}};size=[2,1,1];enabled=!0;static validateJson(e){let t=e;if(!Array.isArray(t.size)||t.size.length!==3||t.size.some(e=>!(e>0)))throw new L(`BAD_FORMAT`,`WaterCutout3D '${e.name}' size must be three positive meters [x, y, z], got ${JSON.stringify(t.size)}.`,{prop:`size`})}onReady(){if(!this.parent?.parent)throw new L(`BAD_FORMAT`,`WaterCutout3D '${this.name}' must be a CHILD of the object that holds the water back (a hull, a diving bell, a dock's well) — it re-draws that object to keep water out of it, so at the scene root it has nothing to stand in for.`,{prop:`parent`})}},ov=[`fancy`,`simple`],sv=[`trough`,`surface`,`peak`],cv=[`custom`,`ocean`,`pool`,`lake`,`pond`],lv={ocean:{waveHeight:.045,swell:.34,swellWavelength:52,whitecaps:.15,absorption:.17,opacity:.85,detailStrength:.17,sunIntensity:.85,colors:{trough:`#175360`,surface:`#2f8792`,peak:`#9bd8d2`},color:`#2f8792`,causticsAbove:.3,shoreWaves:.7,reflectionInterval:400,_look:{fresnelScale:1.15,reflectivityMax:.93,foamRangeScale:.35,foamIntensity:.55}},pool:{waveHeight:.006,swell:0,whitecaps:0,absorption:.3,opacity:.5,detailStrength:.16,sunIntensity:1.25,colors:{trough:`#1e8dbe`,surface:`#3fb6dc`,peak:`#bdeef7`},color:`#3fb6dc`,causticsAbove:1,reflectionInterval:600,_look:{fresnelScale:.85,reflectivityMax:.5,edgeFade:!1}},lake:{waveHeight:.028,swell:.14,swellWavelength:24,whitecaps:0,absorption:.5,opacity:.88,detailStrength:.3,colors:{trough:`#12343a`,surface:`#25565c`,peak:`#7fb2ab`},color:`#25565c`,causticsAbove:.15,reflectionInterval:300,_look:{fresnelScale:1.25,reflectivityMax:.78}},pond:{waveHeight:.006,swell:0,whitecaps:0,absorption:.85,opacity:.93,detailStrength:.14,sunIntensity:.7,colors:{trough:`#1c2e1e`,surface:`#39543c`,peak:`#6f8a68`},color:`#39543c`,causticsAbove:0,reflectionInterval:800,_look:{fresnelScale:1.05,reflectivityMax:.78,edgeFade:!1}}},uv={trough:`#135a72`,surface:`#2a86a0`,peak:`#a5ddd6`},dv={peakThreshold:.08,peakTransition:.05,troughThreshold:-.01,troughTransition:.15,fresnelScale:1,fresnelPower:5},fv={color:`#dcebe8`,intensity:.32,rangeMin:.45,rangeMax:1.4,scale:.35,edgeColor:`#ffffff`,edgeIntensity:.6,edgeWidth:.5};function pv(e,t){return Math.min(fv.rangeMax,Math.max(fv.rangeMin,Math.min(e,t)*.012))}var mv=128,hv=L_/R_,gv=256,_v=120,vv=2e3,yv=3,bv=640,xv=.06,Sv=1024,Cv=.02,wv=1.5,Tv=24,Ev=160,Dv=32,Ov=.18,kv=10,Av=.05,jv=.08,Mv=.02,Nv=.18,Pv=.04,Fv=1.4,Iv=.04,Lv=.45,Rv=.08,zv=.4,Bv=.22,Vv=.09,Hv=.85,Uv=class e extends Q_{static typeName=`Water3D`;static signals=[`entered`,`exited`];static props={size:{default:[40,40]},color:{default:`#2a6fbe`},opacity:{default:.8},renderOrder:{default:1},waveHeight:{default:.04},waveSpeed:{default:1},quality:{default:`fancy`,options:ov},colors:{default:{}},reflection:{default:!0},reflectionInterval:{default:1e3},mirror:{default:!1},mirrorInterval:{default:33},swellSteepness:{default:.35},foam:{default:!0},reflectivity:{default:null},interaction:{default:!0},splash:{default:!0},sunDirection:{default:[.5,.8,.3]},sunColor:{default:`#fff5d6`},sunIntensity:{default:1},detailStrength:{default:.26},absorption:{default:.15},refraction:{default:!0},underwater:{default:!0},swell:{default:0},swellDirectionDeg:{default:0},swellWavelength:{default:30},whitecaps:{default:0},preset:{default:`custom`,options:cv},causticsAbove:{default:0},shoreWaves:{default:0}};size=[40,40];color=`#2a6fbe`;opacity=.8;renderOrder=1;waveHeight=.04;waveSpeed=1;quality=`fancy`;colors={};reflection=!0;mirror=!1;mirrorInterval=33;reflectionInterval=1e3;foam=!0;reflectivity=null;interaction=!0;splash=!0;sunDirection=[.5,.8,.3];sunColor=`#fff5d6`;sunIntensity=1;detailStrength=.26;absorption=.15;refraction=!0;underwater=!0;swell=0;swellDirectionDeg=0;swellWavelength=30;swellSteepness=.35;whitecaps=0;preset=`custom`;causticsAbove=0;shoreWaves=0;rp(t){let n=lv[this.preset],r=this;if(n&&t in n){let i=e.props[t]?.default,a=r[t];if(typeof a==`object`&&a?JSON.stringify(a)===JSON.stringify(i):a===i)return n[t]}return r[t]}presetLook(){let e=lv[this.preset]?._look,t=this.rp(`reflectivity`);return{fresnelScale:e?.fresnelScale??dv.fresnelScale,reflectivityMax:typeof t==`number`?Math.min(Math.max(t,0),1):e?.reflectivityMax??.6,edgeFade:e?.edgeFade??!0,foamRangeScale:e?.foamRangeScale??1,foamIntensity:e?.foamIntensity??fv.intensity}}static validateJson(e){iv(e,`the water surface query, underwater fog, splashes and buoyancy all`);let t=e;if(!((t.size[0]??0)>0)||!((t.size[1]??0)>0))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' size must be positive [width, depth] meters, got ${JSON.stringify(t.size)}.`,{prop:`size`});if(!ov.includes(t.quality))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' quality must be one of [${ov.join(`, `)}], got '${t.quality}'.`,{prop:`quality`,validOptions:ov});for(let[n,r]of Object.entries(t.colors)){if(!sv.includes(n))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' colors has unknown key '${n}'. Valid keys: [${sv.join(`, `)}].`,{prop:`colors`,validOptions:sv});if(typeof r!=`string`)throw new L(`BAD_FORMAT`,`Water3D '${e.name}' colors.${n} must be a hex color string, got ${JSON.stringify(r)}.`,{prop:`colors`})}if(!(t.reflectionInterval>0))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' reflectionInterval must be > 0 ms, got ${t.reflectionInterval}.`,{prop:`reflectionInterval`});let n=t.sunDirection;if(!Array.isArray(n)||n.length!==3||!n.every(e=>Number.isFinite(e))||Math.hypot(n[0]??0,n[1]??0,n[2]??0)===0)throw new L(`BAD_FORMAT`,`Water3D '${e.name}' sunDirection must be a non-zero [x, y, z] vector, got ${JSON.stringify(n)}.`,{prop:`sunDirection`});if(!(t.sunIntensity>=0))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' sunIntensity must be >= 0, got ${t.sunIntensity}.`,{prop:`sunIntensity`});if(!(t.detailStrength>=0))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' detailStrength must be >= 0, got ${t.detailStrength}.`,{prop:`detailStrength`});if(!(t.absorption>=0))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' absorption must be >= 0 (per-meter Beer's-law constant), got ${t.absorption}.`,{prop:`absorption`});if(!(t.swell>=0)||!Number.isFinite(t.swell))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' swell must be >= 0 meters (0 = off), got ${JSON.stringify(t.swell)}.`,{prop:`swell`});if(!(t.swellWavelength>=2))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' swellWavelength must be >= 2 meters, got ${JSON.stringify(t.swellWavelength)}.`,{prop:`swellWavelength`});if(!(t.whitecaps>=0)||!(t.whitecaps<=1))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' whitecaps must be in [0, 1], got ${JSON.stringify(t.whitecaps)}.`,{prop:`whitecaps`});if(!cv.includes(t.preset))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' preset must be one of [${cv.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:cv});if(!(t.shoreWaves>=0)||!(t.shoreWaves<=1))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' shoreWaves must be in [0, 1] (0 = off), got ${JSON.stringify(t.shoreWaves)}.`,{prop:`shoreWaves`});if(!(t.causticsAbove>=0)||!(t.causticsAbove<=3))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' causticsAbove must be in [0, 3] (0 = off), got ${JSON.stringify(t.causticsAbove)}.`,{prop:`causticsAbove`});let r=t.underwater;if(typeof r!=`boolean`){if(typeof r!=`object`||!r||Array.isArray(r))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' underwater must be true, false or an object ({ color?, visibility? }), got ${JSON.stringify(r)}.`,{prop:`underwater`});let t=r;if(t.color!==void 0&&typeof t.color!=`string`)throw new L(`BAD_FORMAT`,`Water3D '${e.name}' underwater.color must be a hex color string, got ${JSON.stringify(t.color)}.`,{prop:`underwater`});if(t.visibility!==void 0&&!(t.visibility>0))throw new L(`BAD_FORMAT`,`Water3D '${e.name}' underwater.visibility must be > 0 meters, got ${JSON.stringify(t.visibility)}.`,{prop:`underwater`})}}time=0;surfaceKey=``;_ripples=[];inWater=new Set;bobTimers=new Map;wadeAnchors=new Map;_scratchA={x:0,y:0,z:0};_scratchB={x:0,y:0,z:0};_bodies=[];_cutouts=[];_maskMeshes=[];_maskSaved=[];_passHidden=[];cubeTarget=null;cubeCamera=null;reflectionNear=0;lastReflectionAt=0;scenePassTarget=null;mirrorTarget=null;mirrorCamera=new Cf;mirrorMatrix=new K;lastMirrorAt=0;lastMirrorEye=new W(1/0,1/0,1/0);lastMirrorQuat=new U;_createObject3D(){return new iu}update(e){this.time+=e*this.waveSpeed,d_(this._ripples,e),this.interaction&&this.stepInteraction(e)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();this.rebuildSurfaceIfNeeded(e),this.effectiveQuality()===`simple`?this.syncSimple(e):this.syncFancy(e)}_onRender3D(e){let t=this._ensureObject3D(),n=t.material;if(e.camera.updateWorldMatrix(!0,!1),e.camera.getWorldPosition(sy),this.underwaterAt(sy.x,sy.y,sy.z)){if(n.isShaderMaterial){let e=n.uniforms;e.uUseSceneDepth&&(e.uUseSceneDepth.value=0),e.uUseRefraction&&(e.uUseRefraction.value=0),e.uUseMirror&&(e.uUseMirror.value=0),e.uCameraSubmerged&&(e.uCameraSubmerged.value=1)}this.noteIdleFrame();return}if(this.effectiveQuality()!==`fancy`||!n.isShaderMaterial)return;let r=Math.hypot((this.size[0]??1)/2,(this.size[1]??1)/2);if(!o_(e.camera,Qv(this),r+1)){this.noteIdleFrame();return}let i=n.uniforms;i.uCameraSubmerged&&(i.uCameraSubmerged.value=0),this.idleFrames=0;let a=Date.now();if(this.reflection){this.cubeTarget||=new Vp(gv,{generateMipmaps:!0,minFilter:_a,type:Ta});let n=Math.max((this.size[0]??1)/2,(this.size[1]??1)/2);(!this.cubeCamera||this.reflectionNear!==n)&&(this.reflectionNear=n,this.cubeCamera=new Lf(n,1e3,this.cubeTarget),this.lastReflectionAt=0);let r=this.effectiveCubeInterval();if(this.lastReflectionAt===0||a-this.lastReflectionAt>=r){this.lastReflectionAt=a;let n=Qv(this),r=this.cubeCamera;r.position.set(n.x,n.y+.1,n.z);let i=t.visible;t.visible=!1,r.update(e.gl,e.scene),t.visible=i}i.uEnvironmentMap&&i.uUseEnvironmentMap&&(i.uEnvironmentMap.value=this.cubeTarget.texture,i.uUseEnvironmentMap.value=1)}if(this.effectiveMirror()&&i.uMirrorMap&&i.uMirrorMatrix&&i.uUseMirror){e.gl.getDrawingBufferSize(oy);let n=Math.max(1,Math.min(Math.round(oy.x/yv),bv)),r=Math.max(1,Math.min(Math.round(oy.y/yv),bv));this.mirrorTarget&&(this.mirrorTarget.width!==n||this.mirrorTarget.height!==r)&&(this.mirrorTarget.dispose(),this.mirrorTarget=null),this.mirrorTarget||=new Xs(n,r,{depthBuffer:!0,stencilBuffer:!1,type:Ta,samples:4});let o=Qv(this).y,s=e.camera;s.getWorldPosition(ly),s.getWorldQuaternion(py),dy.set(0,0,-1).applyQuaternion(py).add(ly),fy.set(0,1,0).applyQuaternion(py),ly.y=2*o-ly.y,dy.y=2*o-dy.y,fy.y=-fy.y;let c=this.mirrorCamera;c.fov=s.fov??50,c.aspect=s.aspect??n/r,c.near=s.near??.1,c.far=s.far??1e3,c.position.copy(ly),c.up.copy(fy),c.lookAt(dy),c.updateMatrixWorld(!0),c.updateProjectionMatrix(),s.getWorldPosition(uy);let l=uy.distanceToSquared(this.lastMirrorEye)>1e-6||Math.abs(py.dot(this.lastMirrorQuat))<.9999995;if(this.lastMirrorAt===0||l||a-this.lastMirrorAt>=this.rp(`mirrorInterval`)){this.lastMirrorAt=a,this.lastMirrorEye.copy(uy),this.lastMirrorQuat.copy(py),this.mirrorMatrix.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),this.mirrorMatrix.multiply(c.projectionMatrix),this.mirrorMatrix.multiply(c.matrixWorldInverse);let n=e.gl.getRenderTarget(),r=e.gl.clippingPlanes,i=t.visible;t.visible=!1,my.constant=-(o-Cv),e.gl.clippingPlanes=hy,e.gl.setRenderTarget(this.mirrorTarget),e.gl.clear(!0,!0,!1),v_(e.scene,this._passHidden),e.gl.render(e.scene,c),y_(this._passHidden),e.gl.setRenderTarget(n),e.gl.clippingPlanes=r,t.visible=i}i.uMirrorMap.value=this.mirrorTarget.texture,i.uMirrorMatrix.value.copy(this.mirrorMatrix),i.uUseMirror.value=1}else i.uUseMirror&&(i.uUseMirror.value=0,this.releasePassTargets(`mirror`));e.gl.getDrawingBufferSize(oy);let o=Math.max(1,Math.min(Math.round(oy.x/2),Sv)),s=Math.max(1,Math.min(Math.round(oy.y/2),Sv));if(this.scenePassTarget&&(this.scenePassTarget.width!==o||this.scenePassTarget.height!==s)&&(this.scenePassTarget.depthTexture?.dispose(),this.scenePassTarget.dispose(),this.scenePassTarget=null),!this.scenePassTarget){let e=new cd(o,s);e.type=wa,this.scenePassTarget=new Xs(o,s,{depthTexture:e,depthBuffer:!0,stencilBuffer:!1,generateMipmaps:!0,minFilter:_a})}let c=e.gl.getRenderTarget(),l=e.gl.autoClear,u=e.gl.clippingPlanes,d=t.visible;t.visible=!1;let f=Qv(this).y;gy.constant=f+Cv,e.gl.clippingPlanes=_y,e.gl.setRenderTarget(this.scenePassTarget),e.gl.autoClear=!0,e.gl.clear(!0,!0,!1),e.gl.render(e.scene,e.camera),yy.constant=-(f-Cv),e.gl.clippingPlanes=by;let p=e.scene.overrideMaterial,m=e.scene.background;e.scene.overrideMaterial=xy,e.scene.background=null,e.gl.autoClear=!1,v_(e.scene,this._passHidden),e.gl.render(e.scene,e.camera),y_(this._passHidden),e.scene.overrideMaterial=p,e.scene.background=m,this.renderCutoutMasks(e),e.gl.setRenderTarget(c),e.gl.autoClear=l,e.gl.clippingPlanes=u,t.visible=d,i.uDepthTexture&&i.uSceneColor&&i.uCameraNear&&i.uCameraFar&&i.uUseSceneDepth&&(i.uDepthTexture.value=this.scenePassTarget.depthTexture,(i.uScenePassTexel?.value)?.set(1/o,1/s),i.uSceneColor.value=this.scenePassTarget.texture,i.uCameraNear.value=e.camera.near,i.uCameraFar.value=e.camera.far,i.uUseSceneDepth.value=1,i.uUseRefraction&&(i.uUseRefraction.value=+!!this.refraction),i.uEnableFoam&&(i.uEnableFoam.value=+!!this.foam))}underwaterAt(e,t,n){if(this.underwater===!1)return null;let r=Qv(this,this._scratchA);if(!E_(e,t,n,{centerX:r.x,centerY:r.y,centerZ:r.z,halfW:(this.size[0]??1)/2,halfD:(this.size[1]??1)/2},cy))return null;let i=A_(this.underwater,this.rp(`color`));return i.enabled?{...i,surfaceY:r.y}:null}releasePassTargets(e){this.mirrorTarget?.dispose(),this.mirrorTarget=null,e!==`mirror`&&(this.cubeTarget?.dispose(),this.cubeTarget=null,this.cubeCamera=null,this.scenePassTarget?.depthTexture?.dispose(),this.scenePassTarget?.dispose(),this.scenePassTarget=null)}idleFrames=0;caps=null;_applyQualityCaps(e){this.caps=e}effectiveQuality(){return this.caps&&!this.caps.fancyWater&&this.canFadeItsOwnRim()?`simple`:this.quality}canFadeItsOwnRim(){return Math.max(this.size[0]??1,this.size[1]??1)/2*Ov<=kv}effectiveMirror(){return this.mirror&&(this.caps?this.caps.waterMirror:!0)}effectiveCubeInterval(){let e=this.rp(`reflectionInterval`),t=this.effectiveMirror()?Math.max(e,vv):e;return Math.max(t,this.caps?.minReflectionIntervalMs??0)}noteIdleFrame(){this.idleFrames+=1,this.idleFrames===_v&&this.releasePassTargets(`all`)}free(){let e=this._builtObject3D;e?.geometry?.dispose(),(e?.material)?.dispose?.(),this.releasePassTargets(`all`),super.free()}rebuildSurfaceIfNeeded(e){let t=this.effectiveQuality(),n=JSON.stringify([this.size,t]);if(n===this.surfaceKey&&e.geometry.getAttribute(`position`))return;this.surfaceKey=n,e.geometry?.dispose(),e.material?.dispose?.();let r=this.size[0]??1,i=this.size[1]??1;t===`simple`?(this.releasePassTargets(`all`),e.geometry=ty(r,i,Dv),e.material=this.buildLakeMaterial()):(e.geometry=ty(r,i,Math.min(Math.max(Math.round(Math.max(r,i)*wv),Tv),Ev)),e.material=this.buildFancyMaterial())}buildFancyMaterial(){return new Dd({vertexShader:w_,fragmentShader:T_,fog:!0,uniforms:{fogColor:{value:new q(`#ffffff`)},fogNear:{value:1},fogFar:{value:1e3},fogDensity:{value:25e-5},uTime:{value:0},uOpacity:{value:this.rp(`opacity`)},uEnvironmentMap:{value:null},uUseEnvironmentMap:{value:0},uMirrorMap:{value:null},uMirrorMatrix:{value:new K},uUseMirror:{value:0},uMirrorDistort:{value:xv},uWavesAmplitude:{value:this.rp(`waveHeight`)*hv},uWavesSpeed:{value:I_.speed},uWavesFrequency:{value:I_.frequency},uWavesPersistence:{value:I_.persistence},uWavesLacunarity:{value:I_.lacunarity},uWavesIterations:{value:I_.iterations},uTroughColor:{value:new q(uv.trough)},uSurfaceColor:{value:new q(uv.surface)},uPeakColor:{value:new q(uv.peak)},uPeakThreshold:{value:dv.peakThreshold},uPeakTransition:{value:dv.peakTransition},uTroughThreshold:{value:dv.troughThreshold},uTroughTransition:{value:dv.troughTransition},uFresnelScale:{value:dv.fresnelScale},uFresnelPower:{value:dv.fresnelPower},uScale:{value:new W(1,1,1)},uWaterCenter:{value:new W},uRipples:{value:Array.from({length:8},()=>new Js)},uRippleFoam:{value:Array.from({length:8},()=>0)},uSplashFoam:{value:+!!this.splash},uSunDirection:{value:new W(.5,.8,.3)},uSunColor:{value:new q(this.sunColor)},uSunIntensity:{value:this.rp(`sunIntensity`)},uDetailStrength:{value:this.rp(`detailStrength`)},uAbsorption:{value:this.rp(`absorption`)},uUseSceneDepth:{value:0},uUseRefraction:{value:0},uSceneColor:{value:null},uEnableFoam:{value:0},uFoamColor:{value:new q(fv.color)},uFoamIntensity:{value:fv.intensity},uFoamRange:{value:pv(this.size[0]??1,this.size[1]??1)},uFoamScale:{value:fv.scale},uDepthTexture:{value:null},uScenePassTexel:{value:new H(1/512,1/512)},uCameraNear:{value:.1},uCameraFar:{value:1e3},uEdgeColor:{value:new q(fv.edgeColor)},uEdgeIntensity:{value:fv.edgeIntensity},uEdgeWidth:{value:fv.edgeWidth},uSwellAmplitude:{value:this.rp(`swell`)},uSwellDir:{value:new H(0,1)},uSwellWavelength:{value:this.rp(`swellWavelength`)},uSwellSteepness:{value:this.rp(`swellSteepness`)},uWhitecaps:{value:this.rp(`whitecaps`)},uWaveEnvelope:{value:0},uCausticsAbove:{value:this.rp(`causticsAbove`)},uShoreWaves:{value:this.rp(`shoreWaves`)},uReflectivityMax:{value:.6},uCameraSubmerged:{value:0},uEdgeFadeOn:{value:1}},transparent:!0,depthTest:!0,depthWrite:!0,side:2})}buildLakeMaterial(){return new Dd({vertexShader:h_,fragmentShader:g_,fog:!0,uniforms:{fogColor:{value:new q(`#ffffff`)},fogNear:{value:1},fogFar:{value:1e3},fogDensity:{value:25e-5},uTime:{value:0},uOpacity:{value:this.rp(`opacity`)},uColor:{value:new q(this.rp(`color`))},uSurfaceColor:{value:new q(this.rp(`color`))},uSkyColor:{value:new q(this.rp(`color`))},uSunDirection:{value:new W(.5,.8,.3).normalize()},uSunColor:{value:new q(this.sunColor)},uSunIntensity:{value:this.rp(`sunIntensity`)},uDetailStrength:{value:this.rp(`detailStrength`)},uFresnelPower:{value:dv.fresnelPower},uScale:{value:new W(1,1,1)},uWaterCenter:{value:new W},uRipples:{value:Array.from({length:8},()=>new Js)},uRippleFoam:{value:Array.from({length:8},()=>0)},uSplashFoam:{value:+!!this.splash},uFoamColor:{value:new q(fv.color)}},transparent:!0,depthTest:!0,depthWrite:!1,side:2})}renderCutoutMasks(e){let t=this._cutouts;t.length=0;let n=this;for(;n.parent;)n=n.parent;if(qv(n,t),t.length===0)return;let r=Sy.uniforms,i=this._maskSaved,a=this._maskMeshes,o=e.gl.clippingPlanes;e.gl.clippingPlanes=vy;let s=0;for(let n of t){if(s>=4)break;let t=Jv(n);if(!t)continue;n._syncObject3D();let o=n._ensureObject3D();if(o.updateWorldMatrix(!0,!1),o.getWorldPosition(Wv),o.getWorldQuaternion(Gv),(r.uCenter?.value)?.copy(Wv),(r.uHalf?.value)?.set((n.size[0]??1)/2,(n.size[1]??1)/2,(n.size[2]??1)/2),Kv.setFromQuaternion(Gv,`YXZ`),(r.uYaw?.value)?.set(Math.cos(Kv.y),Math.sin(Kv.y)),a.length=0,i.length=0,Xv(t,a),a.length!==0){for(let e of a)i.push(e.material),e.material=Sy;e.gl.render(t,e.camera);for(let e=0;e<a.length;e++){let t=a[e],n=i[e];t&&n&&(t.material=n)}s++}}a.length=0,i.length=0,e.gl.clippingPlanes=o}syncFancy(e){let t=e.material.uniforms,n=this.size[0]??1,r=this.size[1]??1,i=Qv(this);t.uTime&&(t.uTime.value=this.time),t.uOpacity&&(t.uOpacity.value=this.rp(`opacity`)),t.uWavesAmplitude&&(t.uWavesAmplitude.value=this.rp(`waveHeight`)*hv),(t.uScale?.value)?.set(n/2,r/2,r/2),(t.uWaterCenter?.value)?.set(i.x,i.y,i.z);let a=this.resolvePalette();(t.uTroughColor?.value)?.copy(a.trough),(t.uSurfaceColor?.value)?.copy(a.surface),(t.uPeakColor?.value)?.copy(a.peak),(t.uSunDirection?.value)?.set(this.sunDirection[0]??0,this.sunDirection[1]??1,this.sunDirection[2]??0).normalize(),(t.uSunColor?.value)?.set(this.sunColor),t.uSunIntensity&&(t.uSunIntensity.value=this.rp(`sunIntensity`)),t.uDetailStrength&&(t.uDetailStrength.value=this.rp(`detailStrength`)),t.uAbsorption&&(t.uAbsorption.value=this.rp(`absorption`)),t.uSwellAmplitude&&(t.uSwellAmplitude.value=this.rp(`swell`)),t.uSwellWavelength&&(t.uSwellWavelength.value=this.rp(`swellWavelength`)),t.uSwellSteepness&&(t.uSwellSteepness.value=this.rp(`swellSteepness`)),t.uWhitecaps&&(t.uWhitecaps.value=this.rp(`whitecaps`)),t.uCausticsAbove&&(t.uCausticsAbove.value=this.rp(`causticsAbove`)),t.uShoreWaves&&(t.uShoreWaves.value=this.rp(`shoreWaves`));let o=this.presetLook();t.uFresnelScale&&(t.uFresnelScale.value=o.fresnelScale),t.uReflectivityMax&&(t.uReflectivityMax.value=o.reflectivityMax),t.uEdgeFadeOn&&(t.uEdgeFadeOn.value=+!!o.edgeFade),t.uFoamRange&&(t.uFoamRange.value=pv(n,r)*o.foamRangeScale),t.uFoamIntensity&&(t.uFoamIntensity.value=o.foamIntensity);let s=this.swellDirectionDeg*Math.PI/180;(t.uSwellDir?.value)?.set(Math.sin(s),Math.cos(s)),t.uWaveEnvelope&&(t.uWaveEnvelope.value=this.rp(`waveHeight`)*hv*1.5+this.rp(`swell`)*1.03),!this.reflection&&t.uUseEnvironmentMap&&(t.uUseEnvironmentMap.value=0),!this.foam&&t.uEnableFoam&&(t.uEnableFoam.value=0),!this.refraction&&t.uUseRefraction&&(t.uUseRefraction.value=0),t.uSplashFoam&&(t.uSplashFoam.value=+!!this.splash);let c=t.uRipples?.value,l=t.uRippleFoam?.value;if(c)for(let e=0;e<c.length;e++){let t=this._ripples[e];t?c[e].set(t.x,t.z,t.age,t.amp):c[e].set(0,0,0,0),l&&(l[e]=t?t.foam??0:0)}}_applySunDirection(t){let n=e.props.sunDirection?.default;this.sunDirection.every((e,t)=>e===n[t])&&(this._ensureObject3D().material.uniforms?.uSunDirection?.value)?.set(t[0],t[1],t[2])}resolvePalette(){let t=this.rp(`colors`),n=this.rp(`color`),r=n===e.props.color?.default?null:n,i=t.surface??r??uv.surface;return ay.surface.set(i),t.trough?ay.trough.set(t.trough):r?ay.trough.set(r).lerp(ny,.45):ay.trough.set(uv.trough),t.peak?ay.peak.set(t.peak):r?ay.peak.set(r).lerp(ry,.3):ay.peak.set(uv.peak),ay}syncSimple(e){let t=e.material;t.opacity=this.rp(`opacity`);let n=t.uniforms,r=this.size[0]??1,i=this.size[1]??1,a=Qv(this,this._scratchA);n.uTime&&(n.uTime.value=this.time),n.uOpacity&&(n.uOpacity.value=this.rp(`opacity`)),(n.uSurfaceColor?.value)?.set(this.rp(`color`)).lerp(ry,.12),(n.uColor?.value)?.set(this.rp(`color`)).lerp(ny,.4),(n.uSkyColor?.value)?.set(this.rp(`color`)).lerp(iy,.82),(n.uScale?.value)?.set(r/2,i/2,i/2),(n.uWaterCenter?.value)?.set(a.x,a.y,a.z),(n.uSunDirection?.value)?.set(this.sunDirection[0]??0,this.sunDirection[1]??1,this.sunDirection[2]??0).normalize(),(n.uSunColor?.value)?.set(this.sunColor),n.uSunIntensity&&(n.uSunIntensity.value=this.rp(`sunIntensity`)),n.uDetailStrength&&(n.uDetailStrength.value=this.rp(`detailStrength`)),n.uSplashFoam&&(n.uSplashFoam.value=+!!this.splash);let o=n.uRipples?.value,s=n.uRippleFoam?.value;if(o)for(let e=0;e<o.length;e++){let t=this._ripples[e];t?o[e].set(t.x,t.z,t.age,t.amp):o[e].set(0,0,0,0),s&&(s[e]=t?t.foam??0:0)}let c=e.geometry,l=c.getAttribute(`position`),u=c.getAttribute(`normal`),d=this.time,f=this.rp(`waveHeight`),p=a.x,m=a.z,h=this._ripples,g=.5;for(let e=0;e<l.count;e++){let t=l.getX(e),n=l.getZ(e),r=Y_(t,n,d,f)+p_(t+p,n+m,h);l.setY(e,r);let i=Y_(t+g,n,d,f)+p_(t+p+g,n+m,h),a=Y_(t,n+g,d,f)+p_(t+p,n+m+g,h),o=(r-i)/g,s=(r-a)/g,c=1/Math.hypot(o,1,s);u.setXYZ(e,o*c,c,s*c)}l.needsUpdate=!0,u.needsUpdate=!0}stepInteraction(e){let t=this;for(;t.parent;)t=t.parent;let n=this._bodies;n.length=0,Zv(t,n);let r=Qv(this,this._scratchA),i=(this.size[0]??0)/2,a=(this.size[1]??0)/2,o=[];for(let e of n){let t=Qv(e,this._scratchB);if(Math.abs(t.x-r.x)>i||Math.abs(t.z-r.z)>a)continue;let n=s_(e.collider);o.push({id:e,x:t.x,y:t.y,z:t.z,waterline:r.y+this.waveOffsetAt(t.x,t.z,r)+n})}let{entered:s,exited:c,inWater:l}=l_(this.inWater,o,Av);this.inWater=l;let u=this.splash;for(let e of s){let t=Math.abs($v(e.id)?.[1]??0);u_(this._ripples,e.x,e.z,ey(e.id),u?c_(t):0),this.emit(`entered`,e.id)}for(let e of c)u_(this._ripples,e.x,e.z,Pv,u?zv:0),this.emit(`exited`,e.id);for(let t of m_(this.bobTimers,l,e,Fv)){let e=Qv(t,this._scratchB);u_(this._ripples,e.x,e.z,Iv)}for(let e of l){let t=Qv(e,this._scratchB),n=this.wadeAnchors.get(e);if(!n){this.wadeAnchors.set(e,{x:t.x,z:t.z});continue}let r=t.x-n.x,i=t.z-n.z;if(r*r+i*i>=Lv*Lv){let r=$v(e),i=Math.hypot(r?.[0]??0,r?.[2]??0),a=u?Math.min(Bv+Vv*i,Hv):0;u_(this._ripples,t.x,t.z,Rv,a),n.x=t.x,n.z=t.z}}for(let e of this.wadeAnchors.keys())l.has(e)||this.wadeAnchors.delete(e)}heightAt(e,t){let n=Qv(this,this._scratchA);return n.y+this.waveOffsetAt(e,t,n)}_waterYAt(e,t){let n=Qv(this,this._scratchA),r=(this.size[0]??0)/2,i=(this.size[1]??0)/2;return Math.abs(e-n.x)>r||Math.abs(t-n.z)>i?null:n.y}waveOffsetAt(e,t,n){return this.effectiveQuality()===`simple`?Y_(e-n.x,t-n.z,this.time,this.rp(`waveHeight`)):J_(e,t,this.time,{amplitude:this.rp(`waveHeight`)*hv,frequency:I_.frequency,persistence:I_.persistence,lacunarity:I_.lacunarity,iterations:I_.iterations,speed:I_.speed,scaleNorm:mv})}},Wv=new W,Gv=new U,Kv=new cc;function qv(e,t){e instanceof av&&e.enabled&&e.visible&&t.push(e);for(let n of e.children)qv(n,t)}function Jv(e){let t=e.parent;if(!(t instanceof Q_)||!t.parent)return null;let n=t._ensureObject3D();return typeof n?.traverse==`function`?n:null}var Yv=new Set([`Terrain3D`,`Water3D`,`River3D`]);function Xv(e,t){return e.traverse(e=>{let n=e;if(!n.isMesh||!n.visible||!n.material)return;let r=(e.userData?.incantoNode)?.constructor?.typeName;r&&Yv.has(r)||t.push(n)}),t}function Zv(e,t){(e instanceof rv||e instanceof nv)&&t.push(e);for(let n of e.children)Zv(n,t)}function Qv(e,t={x:0,y:0,z:0}){let n=0,r=0,i=0,a=e;for(;a;)a instanceof Q_&&(n+=a.position[0]??0,r+=a.position[1]??0,i+=a.position[2]??0),a=a.parent;return t.x=n,t.y=r,t.z=i,t}function $v(e){return e.velocity??e.linearVelocity}function ey(e){let t=Math.abs($v(e)?.[1]??0);return Math.min(jv+Mv*t,Nv)}function ty(e,t,n){let r=new _d(e,t,n,n);return r.rotateX(-Math.PI/2),r}var ny=new q(`#000000`),ry=new q(`#ffffff`),iy=new q(`#cfe3f0`),ay={trough:new q,surface:new q,peak:new q},oy=new H,sy=new W,cy=3,ly=new W,uy=new W,dy=new W,fy=new W,py=new U,my=new Pu(new W(0,1,0),0),hy=[my],gy=new Pu(new W(0,-1,0),0),_y=[gy],vy=[],yy=new Pu(new W(0,1,0),0),by=[yy],xy=new jd;xy.colorWrite=!1;var Sy=new Dd({uniforms:{uCenter:{value:new W},uHalf:{value:new W(1,1,1)},uYaw:{value:new H(1,0)}},vertexShader:`
|
|
5751
5751
|
uniform vec3 uCenter;
|
|
5752
5752
|
uniform vec2 uYaw;
|
|
5753
5753
|
varying vec3 vCutLocal;
|
|
@@ -5769,7 +5769,7 @@ void main() {
|
|
|
5769
5769
|
if (any(greaterThan(abs(vCutLocal), uHalf))) discard;
|
|
5770
5770
|
gl_FragColor = vec4(0.0);
|
|
5771
5771
|
}
|
|
5772
|
-
`,colorWrite:!1,depthWrite:!0,depthTest:!1,side:2}),Sy=9.81,Cy=6,wy=.15,Ty=class extends vt{static props={water:{default:``,nodePath:!0},draft:{default:.35},stiffness:{default:3},damping:{default:3.5},drift:{default:.6},drag:{default:.9},samples:{default:4},size:{default:[1,1]}};static signals=[`submerged`,`surfaced`];water=``;draft=.35;stiffness=3;damping=3.5;drift=.6;drag=.9;samples=4;size=[1,1];surface=null;wet=!1;reportedNoImpulse=!1;update(e){if(e<=0)return;let t=this.resolveWater();if(!t)return;let n=this.node;if(!n.applyImpulse){this.reportedNoImpulse||(this.reportedNoImpulse=!0,Nt(this.node.tree?.engine??null,`error`,`[incanto] ${this.node.getPath()}: Buoyancy needs a body it can push — this node has no applyImpulse, so it will never float. Put it on a RigidBody3D.`));return}let[r,i,a]=[n.position[0]??0,n.position[1]??0,n.position[2]??0],o=[(this.size[0]??1)/2,(this.size[1]??1)/2],s=this.samplePoints(r,a,o[0],o[1]),c=n.mass??1,l=n.linearVelocity??[0,0,0],u=0,d=0,f=0,p=0;for(let[e,n]of s){let r=t.heightAt(e,n)-(i-this.draft);if(r<=0)continue;p++,u+=Sy*(1+this.stiffness*(r/Math.max(this.draft,wy)));let a=.6;d+=t.heightAt(e+a,n)-t.heightAt(e-a,n),f+=t.heightAt(e,n+a)-t.heightAt(e,n-a)}let m=p>0;if(m!==this.wet&&(this.wet=m,this.emit(m?`submerged`:`surfaced`,this.node)),!m)return;let h=p/s.length,g=Math.min(u/s.length-this.damping*(l[1]??0),Cy*Sy)*e*c,_=(-d*this.drift*12-(l[0]??0)*this.drag)*h*e*c,v=(-f*this.drift*12-(l[2]??0)*this.drag)*h*e*c;n.applyImpulse([_,g,v])}samplePoints(e,t,n,r){let i=Math.max(1,Math.round(this.samples));if(i===1)return[[e,t]];let a=[];for(let o=0;o<i;o++){let s=o/i*Math.PI*2+Math.PI/4;a.push([e+Math.cos(s)*n,t+Math.sin(s)*r])}return a}resolveWater(){if(this.surface)return this.surface;if(this.water!==``){let e=this.node.getNodeOrNull(this.water);if(!(e instanceof Hv))throw new L(`NODE_NOT_FOUND`,`Buoyancy on '${this.node.getPath()}': water '${this.water}' is not a Water3D in the tree.`,{prop:`water`});return this.surface=e,e}return this.surface=Ey(this.node.getRoot()),this.surface}};function Ey(e){if(e instanceof Hv)return e;for(let t of e.children){let e=Ey(t);if(e)return e}return null}function Dy(e,t,n){let r=e;if(typeof r.moveAndSlide!=`function`||r._physics==null||n<=0){e.position=[...t];return}let i=r.position,a=[];for(let e=0;e<i.length;e++)a.push(((t[e]??i[e]??0)-(i[e]??0))/n);r.velocity=a,r.moveAndSlide()}function Oy(e){return Array.isArray(e.position)}function ky(e){let t=e.node;if(!Oy(t)){let n=e.constructor.name;throw new L(`PROP_TYPE_MISMATCH`,`${n} on '${t.getPath()}' needs a spatial node with a numeric 'position' array (a Node2D/Node3D subtype). '${t.name}' has none.`,{path:t.getPath()})}return t}function Ay(e,t){let n=0,r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let r=(e[i]??0)-(t[i]??0);n+=r*r}return Math.sqrt(n)}function jy(e,t){let n=Math.max(e.length,t.length),r=Array(n);for(let i=0;i<n;i++)r[i]=(e[i]??0)+(t[i]??0);return r}function My(e){let t=0;for(let n of e)t+=n*n;return Math.sqrt(t)}function Ny(e){let t=My(e);return t===0?e.map(()=>0):e.map(e=>e/t)}function Py(e,t,n){let r=Math.max(e.length,t.length),i=0;for(let n=0;n<r;n++){let r=(t[n]??0)-(e[n]??0);i+=r*r}let a=Math.sqrt(i),o=Array(r);if(a<=n||a===0){for(let e=0;e<r;e++)o[e]=t[e]??0;return{position:o,reached:!0}}let s=n/a;for(let n=0;n<r;n++){let r=e[n]??0;o[n]=r+((t[n]??0)-r)*s}return{position:o,reached:!1}}function Fy(e,t){let n=Math.min(Math.max(e,0),.99);return n<=0?1:1-n**(t*60)}function Iy(e){let t=e.position;if(!Array.isArray(t))return[];let n=t.slice();for(let t=e.parent;t;t=t.parent){let e=t.position;if(Array.isArray(e))for(let t=0;t<n.length;t++)n[t]=(n[t]??0)+(e[t]??0)}return n}function Ly(e,t){let n=t.slice();for(let t=e.parent;t;t=t.parent){let e=t.position;if(Array.isArray(e))for(let t=0;t<n.length;t++)n[t]=(n[t]??0)-(e[t]??0)}return n}var Ry=class extends vt{static props={target:{default:``,nodePath:!0,required:!0},speed:{default:60},stopRange:{default:0},loseRange:{default:0},moveParent:{default:!1}};static signals=[`reachedTarget`,`lostTarget`];target=``;speed=60;stopRange=0;loseRange=0;moveParent=!1;inRange=!1;lost=!1;onReady(){if(this.target===``)throw new L(`PROP_TYPE_MISMATCH`,`Chase on '${this.node.getPath()}': "target" (a node path) is required.`,{prop:`target`});if(this.moveParent){let e=this.node.parent;if(!e||!Oy(e))throw new L(`PROP_TYPE_MISMATCH`,`Chase on '${this.node.getPath()}': "moveParent" needs a spatial parent (a Node2D/Node3D) to move. '${this.node.name}' has none.`,{prop:`moveParent`,path:this.node.getPath()})}else ky(this)}update(e){let t=this.moveParent?this.node.parent:this.node;if(!t||!Oy(t))return;let n=this.node.getNodeOrNull(this.target);if(!n||!Oy(n))return;let r=Ay(t.position,n.position);if(this.loseRange>0&&r>this.loseRange){this.lost||(this.lost=!0,this.inRange=!1,this.emit(`lostTarget`));return}if(this.lost=!1,this.stopRange>0&&r<=this.stopRange){this.inRange||(this.inRange=!0,this.emit(`reachedTarget`));return}this.inRange=!1;let i=Math.min(this.speed*e,this.stopRange>0?r-this.stopRange:r),{position:a}=Py(t.position,n.position,Math.max(0,i));Dy(t,a,e)}},zy=class extends vt{static props={button:{default:0},maxDistance:{default:0},enabled:{default:!0}};static signals=[`clicked`,`hovered`,`unhovered`];button=0;maxDistance=0;enabled=!0;hovering=!1;pressedHere=!1;update(){let e=this.node.tree?.engine;if(!e||!this.enabled)return;let t=e.picker,n=e.input.pointerPosition();if(!t||!n){this.hovering&&this.setHover(!1);return}let r=t(n.x,n.y),i=r!==null&&this.isSelfOrDescendant(r)&&this.withinRange(r);i!==this.hovering&&this.setHover(i),e.input.mouseJustPressed(this.button)&&(this.pressedHere=i),e.input.mouseJustReleased(this.button)&&(this.pressedHere&&i&&this.emit(`clicked`,this.node),this.pressedHere=!1)}setHover(e){this.hovering=e,this.emit(e?`hovered`:`unhovered`,this.node)}isSelfOrDescendant(e){for(let t=e;t;t=t.parent)if(t===this.node)return!0;return!1}withinRange(e){if(this.maxDistance<=0||!this.node.tree?.engine?.scene?.root)return!0;let t=this.node.position,n=e.position;if(!Array.isArray(t)||!Array.isArray(n))return!0;let r=0;for(let e=0;e<Math.max(t.length,n.length);e++){let i=(t[e]??0)-(n[e]??0);r+=i*i}return Math.sqrt(r)<=this.maxDistance}},By=class extends vt{static props={group:{default:`player`}};static signals=[`totalChanged`];group=`player`;total=0;onReady(){this.node.addToGroup(this.group)}collect(e){this.total+=e,this.emit(`totalChanged`,this.total)}serialize(){return{total:this.total}}deserialize(e){let t=e;typeof t.total==`number`&&(this.total=t.total)}},Vy=class extends vt{static props={max:{default:100},regenPerSec:{default:0},invulnerableFor:{default:0},freeOnDeath:{default:!1}};static signals=[`damaged`,`healed`,`died`,`healthChanged`];max=100;regenPerSec=0;invulnerableFor=0;freeOnDeath=!1;current=0;invulnTimer=0;dead=!1;get isDead(){return this.dead}get invulnerableRemaining(){return this.invulnTimer}onReady(){if(!(this.max>0))throw new L(`PROP_TYPE_MISMATCH`,`Health on '${this.node.getPath()}': "max" must be > 0, got ${this.max}.`,{prop:`max`});if(this.regenPerSec<0)throw new L(`PROP_TYPE_MISMATCH`,`Health on '${this.node.getPath()}': "regenPerSec" must be >= 0, got ${this.regenPerSec}.`,{prop:`regenPerSec`});if(this.invulnerableFor<0)throw new L(`PROP_TYPE_MISMATCH`,`Health on '${this.node.getPath()}': "invulnerableFor" must be >= 0, got ${this.invulnerableFor}.`,{prop:`invulnerableFor`});this.current=this.max}update(e){this.invulnTimer>0&&(this.invulnTimer=Math.max(0,this.invulnTimer-e)),this.regenPerSec>0&&!this.dead&&this.current<this.max&&this.setCurrent(this.current+this.regenPerSec*e)}damage(e){this.dead||e<=0||this.invulnTimer>0||(this.setCurrent(this.current-e),this.emit(`damaged`,e,this.current),this.invulnerableFor>0&&(this.invulnTimer=this.invulnerableFor),this.current<=0&&this.die())}heal(e){this.dead||e<=0||(this.setCurrent(this.current+e),this.emit(`healed`,e,this.current))}kill(){this.dead||(this.setCurrent(0),this.die())}setCurrent(e){let t=Math.max(0,Math.min(this.max,e));t!==this.current&&(this.current=t,this.emit(`healthChanged`,this.current,this.max))}die(){this.dead||(this.dead=!0,this.setCurrent(0),this.emit(`died`),this.freeOnDeath&&this.node.queueFree())}serialize(){return{current:this.current,dead:this.dead}}deserialize(e){let t=e;typeof t.current==`number`&&(this.current=Math.min(this.max,Math.max(0,t.current))),typeof t.dead==`boolean`&&(this.dead=t.dead)}};function Hy(e,t){let n=e.node;if(!n.declaredSignalNames().includes(`triggerEnter`)){let t=e.constructor.name;throw new L(`UNKNOWN_SIGNAL`,`${t} on '${n.getPath()}' needs a node that emits 'triggerEnter' — attach it to an Area2D/Area3D (or another body that declares the collision signals). '${n.name}' declares: [${n.declaredSignalNames().join(`, `)}].`,{signal:`triggerEnter`,path:n.getPath()})}n.on(`triggerEnter`,e=>t(e))}var Uy=class extends vt{static props={amount:{default:10},targetGroup:{default:``},oncePerTarget:{default:!0},repeatEvery:{default:0},destroySelf:{default:!1}};static signals=[`dealtDamage`];amount=10;targetGroup=``;oncePerTarget=!0;repeatEvery=0;destroySelf=!1;hit=new WeakSet;inside=new Map;onReady(){Hy(this,e=>{this.inside.set(e,this.repeatEvery),this.tryDamage(e)}),this.node.on(`triggerExit`,e=>{this.inside.delete(e)})}update(e){if(!(this.repeatEvery<=0||this.inside.size===0))for(let[t,n]of this.inside){if(!t.tree){this.inside.delete(t);continue}let r=n-e;r>0?this.inside.set(t,r):(this.inside.set(t,this.repeatEvery),this.tryDamage(t,{repeat:!0}))}}tryDamage(e,t){if(!t?.repeat&&this.oncePerTarget&&this.hit.has(e))return;let n=Wy(e);n&&(this.targetGroup!==``&&!n.owner.isInGroup(this.targetGroup)||(this.oncePerTarget&&this.hit.add(e),n.health.damage(this.amount),this.emit(`dealtDamage`,this.amount,n.owner),this.destroySelf&&this.node.queueFree()))}};function Wy(e){let t=[e];for(;t.length>0;){let e=t.shift();if(e.behavior instanceof Vy)return{health:e.behavior,owner:e};t.push(...e.children)}for(let t=e.parent;t;t=t.parent)if(t.behavior instanceof Vy)return{health:t.behavior,owner:t};return null}var Gy=class extends vt{static signals=[`dayPhaseChanged`];static props={daySeconds:{default:240},startHour:{default:10},maxSunElevationDeg:{default:55},nightDarkness:{default:.75},paused:{default:!1}};daySeconds=240;startHour=10;maxSunElevationDeg=55;nightDarkness=.75;paused=!1;hour=0;phase=``;applyClock=0;baseAmbient=.3;baseExposure=1;captured=!1;onReady(){this.hour=this.startHour}update(e){if(this.paused||(this.hour=(this.hour+e/this.daySeconds*24)%24),this.applyClock-=e,this.applyClock>0)return;this.applyClock=.2,this.applyHour();let t=Ky(this.hour);t!==this.phase&&(this.phase=t,this.emit(`dayPhaseChanged`,t))}applyHour(){let e=this.node.tree?.engine,t=e?.scene?.environment;if(!e||!t?.sky)return;this.captured||(this.captured=!0,this.baseAmbient=t.ambient?.intensity??.3,this.baseExposure=t.exposure??1);let n=(this.hour-6)/12*Math.PI,r=Math.sin(n);t.sky.elevationDeg=r*this.maxSunElevationDeg+(r<0?r*10:0),t.sky.azimuthDeg=this.hour/24*360+90;let i=Math.max(0,r),a=this.nightDarkness;t.ambient={...t.ambient??{},intensity:this.baseAmbient*(1-a+a*i)},t.exposure=this.baseExposure*(1-a*.55*(1-i))}};function Ky(e){return e<5||e>=20?`night`:e<7.5?`dawn`:e<17.5?`day`:`dusk`}var qy=class extends vt{static props={rise:{default:1},seconds:{default:.7},hold:{default:.3},drift:{default:0},freeOnEnd:{default:!0}};rise=1;seconds=.7;hold=.3;drift=0;freeOnEnd=!0;elapsed=0;start=[];done=!1;onReady(){let e=this.node;this.start=[...e.position??[]],e.opacity===void 0&&Nt(this.node.tree?.engine,`warn`,`[incanto] FloatAway on '${this.node.getPath()}' will not fade — ${this.node.constructor.name} has no "opacity" prop, so it pops out at full brightness instead. Use a node that has one (Label, Label3D, Sprite2D, Sprite3D).`)}update(e){if(this.done)return;let t=this.node;if(!t.position)return;this.elapsed+=e;let n=Math.max(.001,this.seconds),r=Math.min(1,this.elapsed/n),i=[...this.start],a=1-(1-r)*(1-r);if(i[1]=(this.start[1]??0)+this.rise*a,this.drift!==0&&(i[0]=(this.start[0]??0)+this.drift*a),t.position=i,t.opacity!==void 0){let e=Math.min(.99,Math.max(0,this.hold));t.opacity=r<=e?1:1-(r-e)/(1-e)}r>=1&&(this.done=!0,this.freeOnEnd&&this.node.queueFree())}},Jy=class extends vt{static props={target:{default:``,nodePath:!0,required:!0},offset:{default:[]},smoothing:{default:0,range:{min:0,max:1}},deadzone:{default:0,range:{min:0}}};static signals=[];target=``;offset=[];smoothing=0;deadzone=0;onReady(){if(this.target===``)throw new L(`PROP_TYPE_MISMATCH`,`FollowCamera on '${this.node.getPath()}': "target" (a node path) is required.`,{prop:`target`});if(this.deadzone<0)throw new L(`PROP_TYPE_MISMATCH`,`FollowCamera on '${this.node.getPath()}': "deadzone" must be >= 0, got ${this.deadzone}.`,{prop:`deadzone`});ky(this)}shakeMag=0;shakeT=0;shakeFalloff=.28;shake(e,t=.28){this.shakeMag=Math.max(this.shakeMag,e),this.shakeT=t,this.shakeFalloff=t}update(e){let t=this.node;if(!Oy(t))return;let n=t.getNodeOrNull(this.target);if(!n||!Oy(n))return;let r=Iy(t),i=jy(Iy(n),this.offset);if(!(this.deadzone>0&&Ay(r,i)<=this.deadzone)){let n=Fy(this.smoothing,e);n>=1?t.position=Ly(t,i):t.position=Ly(t,r.map((e,t)=>e+((i[t]??e)-e)*n))}if(this.shakeT>0){this.shakeT-=e;let n=this.shakeMag*Math.max(0,this.shakeT)/this.shakeFalloff;this.shakeT<=0&&(this.shakeMag=0);let r=t.position.slice();for(let e=0;e<r.length;e++){let t=r.length>=3&&e===1?.5:1;r[e]=(r[e]??0)+(this.engine.rng.next()*2-1)*n*t}t.position=r}}};function Yy(e,t,n,r){try{return n()}catch(n){if(e.authored&&!e.reported.has(t)){e.reported.add(t);let r=n instanceof Error?n.message:String(n);Nt(e.engine??null,`error`,`[incanto] ${e.who}: ${r} ${e.consequence}`)}return r}}function Xy(e){let t=e.scene?.source;t&&e.setScene(Ai(R(t)))}function Zy(e,t,n){let r=n?.fadeSeconds??.4,i=()=>{e.setScene(Ai(R(t)))};if(typeof document>`u`||r<=0){i();return}let a=`incanto-scene-fade`,o=document.getElementById(a);o||(o=document.createElement(`div`),o.id=a,o.style.cssText=`position:fixed;inset:0;z-index:10001;background:#000;opacity:0;pointer-events:none;`,document.body.appendChild(o)),o.style.transition=`opacity ${r/2}s`,o.style.opacity=`1`,setTimeout(()=>{i();let e=document.getElementById(a);e&&(e.style.opacity=`0`,setTimeout(()=>e.remove(),r*500+60))},r*500+30)}var Qy=class e extends vt{static signals=[`flowChanged`];static props={restartAction:{default:`restart`},pauseAction:{default:`pause`},freezeOnEnd:{default:!0},bannerPath:{default:`%Banner`,nodePath:!0},pausePanelPath:{default:`%PauseMenu`,nodePath:!0}};restartAction=`restart`;freezeOnEnd=!0;bannerPath=`%Banner`;pauseAction=`pause`;reportedActions=new Set;readAction(t,n){let r=this[t],i=e.props[t];return Yy({engine:this.engine,who:this.node.getPath(),reported:this.reportedActions,consequence:n,authored:r!==(typeof i?.default==`string`?i.default:``)},r,()=>this.engine.input.justPressed(r),!1)}pausePanelPath=`%PauseMenu`;state=`playing`;frozeScale=!1;onReady(){this.syncPausePanel()}syncPausePanel(){if(this.pausePanelPath===``)return;let e=this.node.getNodeOrNull(this.pausePanelPath);e&&`visible`in e&&(e.visible=this.state===`paused`)}gameOver(e=`GAME OVER`,t=`#ef4444`){this.transition(`gameover`,e,t)}win(e=`YOU WIN`,t=`#4ade80`){this.transition(`won`,e,t)}pause(){this.state===`playing`&&(this.state=`paused`,this.freeze(),this.syncPausePanel(),this.node.emit(`flowChanged`,this.state))}resume(){this.state===`paused`&&(this.state=`playing`,this.thaw(),this.syncPausePanel(),this.node.emit(`flowChanged`,this.state))}restart(){this.thaw(),Xy(this.engine)}goToScene(e,t){this.thaw(),Zy(this.engine,e,t)}transition(e,t,n){this.state===`gameover`||this.state===`won`||(this.state=e,this.freezeOnEnd&&this.freeze(),this.bannerPath!==``&&this.node.getNodeOrNull(this.bannerPath)?.show(t,{color:n,seconds:0}),this.node.emit(`flowChanged`,e))}freeze(){this.frozeScale||(this.frozeScale=!0,this.engine.timeScale=0)}thaw(){this.frozeScale&&(this.frozeScale=!1,this.engine.timeScale=1)}update(){if(this.state===`playing`||this.state===`paused`){this.readAction(`pauseAction`,`The pause key will do nothing.`)&&(this.state===`playing`?this.pause():this.resume());return}this.state!==`gameover`&&this.state!==`won`||this.readAction(`restartAction`,`The restart key will do nothing.`)&&this.restart()}};function $y(e){return Array.isArray(e.position)}function eb(e,t){let n=0,r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let r=(e[i]??0)-(t[i]??0);n+=r*r}return Math.sqrt(n)}var tb=class extends vt{static props={action:{default:`interact`},range:{default:2},actorGroup:{default:`player`}};static signals=[`interacted`];action=`interact`;range=2;actorGroup=`player`;update(){let e=this.node.tree?.engine;if(!e?.scene||!e.input.justPressed(this.action)||!$y(this.node))return;let t=this.node.position,n=null,r=1/0,i=this.node.tree?.getNodesInGroup(this.actorGroup)??nb(this.node.getRoot(),this.actorGroup);for(let e of i){if(!$y(e))continue;let i=eb(t,e.position);i<=this.range&&i<r&&(n=e,r=i)}n&&this.emit(`interacted`,n)}};function nb(e,t){let n=[],r=e=>{e.isInGroup(t)&&n.push(e);for(let t of e.children)r(t)};return r(e),n}var rb=.28;function ib(e,t,n,r,i){e?.effects.record({kind:t,name:n,from:r,amount:i,at:e.time})}var ab=class extends vt{static props={falloff:{default:rb}};falloff=rb;magnitude=0;t=0;prev=[];shake(e,t){this.engine?.settings.get(`reduceMotion`)!==!0&&(this.magnitude=Math.max(this.magnitude,e),this.t=t??this.falloff,ib(this.engine,`shake`,``,this.node?.getPath()??`engine`,e))}update(e){let t=ky(this),n=t.position;for(let e=0;e<this.prev.length;e++)n[e]=(n[e]??0)-(this.prev[e]??0);if(this.t<=0){this.prev.length>0&&(t.position=n.slice(),this.prev.length=0);return}this.t-=e;let r=this.magnitude*Math.max(0,this.t)/this.falloff;this.t<=0&&(this.magnitude=0);let i=n.slice();this.prev.length!==i.length&&(this.prev=Array(i.length).fill(0));for(let e=0;e<i.length;e++){let t=i.length>=3&&e===1?.5:1;this.prev[e]=(this.engine.rng.next()*2-1)*r*t,i[e]=(i[e]??0)+this.prev[e]}t.position=i}},ob=class extends vt{static props={seconds:{default:1},startOnSignal:{default:!1}};static signals=[`expired`];seconds=1;startOnSignal=!1;elapsed=0;running=!1;fired=!1;onReady(){if(!(this.seconds>0))throw new L(`PROP_TYPE_MISMATCH`,`Lifetime on '${this.node.getPath()}': "seconds" must be > 0, got ${this.seconds}.`,{prop:`seconds`});this.running=!this.startOnSignal}startTimer(){this.elapsed=0,this.fired=!1,this.running=!0}update(e){!this.running||this.fired||(this.elapsed+=e,this.elapsed>=this.seconds&&(this.fired=!0,this.running=!1,this.emit(`expired`),this.node.queueFree()))}},sb=[`linear`,`easeIn`,`easeOut`,`easeInOut`];function cb(e,t){let n=t<0?0:t>1?1:t;switch(e){case`linear`:return n;case`easeIn`:return n*n;case`easeOut`:return 1-(1-n)*(1-n);case`easeInOut`:return n<.5?2*n*n:1-(-2*n+2)**2/2}}var lb=class extends vt{static props={to:{default:[],required:!0},duration:{default:1},ease:{default:`easeInOut`,options:[...sb]},startOnSignal:{default:!1}};static signals=[`arrived`];to=[];duration=1;ease=`easeInOut`;startOnSignal=!1;from=[];elapsed=0;running=!1;arrivedFired=!1;onReady(){if(!(this.duration>0))throw new L(`PROP_TYPE_MISMATCH`,`MoveTo on '${this.node.getPath()}': "duration" must be > 0, got ${this.duration}.`,{prop:`duration`});if(!sb.includes(this.ease))throw new L(`PROP_TYPE_MISMATCH`,`MoveTo on '${this.node.getPath()}': "ease" must be one of [${sb.join(`, `)}], got '${this.ease}'.`,{prop:`ease`});let e=ky(this);this.from=[...e.position],this.startOnSignal||(this.running=!0)}start(){let e=this.node;this.from=[...e.position],this.elapsed=0,this.arrivedFired=!1,this.running=!0}update(e){if(!this.running)return;let t=this.node;this.elapsed+=e;let n=Math.min(1,this.elapsed/this.duration),r=cb(this.ease,n);t.position=this.from.map((e,t)=>e+((this.to[t]??e)-e)*r),n>=1&&!this.arrivedFired&&(this.arrivedFired=!0,this.running=!1,this.emit(`arrived`))}},ub=[`x`,`y`,`z`],db=[`position`,`rotation`,`scale`],fb={x:0,y:1,z:2},pb=class extends vt{static props={axis:{default:`y`,options:[...ub]},amplitude:{default:1},frequency:{default:1},mode:{default:`position`,options:[...db]}};static signals=[];axis=`y`;amplitude=1;frequency=1;mode=`position`;base=0;time=0;onReady(){if(!ub.includes(this.axis))throw new L(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': "axis" must be one of [${ub.join(`, `)}], got '${this.axis}'.`,{prop:`axis`});if(!db.includes(this.mode))throw new L(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': "mode" must be one of [${db.join(`, `)}], got '${this.mode}'.`,{prop:`mode`});this.base=this.readChannel()}update(e){this.time+=e;let t=this.amplitude*Math.sin(2*Math.PI*this.frequency*this.time);this.writeChannel(this.base+t)}isScalarRotation(){return this.mode===`rotation`&&typeof this.node.rotation==`number`}readChannel(){if(this.isScalarRotation())return this.node.rotation;let e=this.node[this.mode];if(!Array.isArray(e))throw new L(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': node has no '${this.mode}' array to oscillate.`,{prop:`mode`});return e[fb[this.axis]]??0}writeChannel(e){if(this.isScalarRotation()){this.node.rotation=e;return}let t=[...this.node[this.mode]];t[fb[this.axis]]=e,this.node[this.mode]=t}},mb=class extends vt{static signals=[`waypointReached`,`arrived`];static props={speed:{default:120},loop:{default:!1}};speed=120;loop=!1;waypoints=[];index=0;get moving(){return this.index<this.waypoints.length}setPath(e){this.waypoints=e.map(e=>[...e]),this.index=0}stop(){this.waypoints=[],this.index=0}update(e){if(!this.moving)return;let t=ky(this),n=this.speed*e;for(;n>0&&this.index<this.waypoints.length;){let e=this.waypoints[this.index],r=Py(t.position,e,n),i=hb(t.position,r.position);if(t.position=r.position,n-=i,r.reached){if(this.node.emit(`waypointReached`,this.index),this.index+=1,this.index>=this.waypoints.length)if(this.loop&&this.waypoints.length>1)this.index=0;else{this.node.emit(`arrived`);return}}else return}}};function hb(e,t){let n=0,r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let r=(t[i]??0)-(e[i]??0);n+=r*r}return Math.sqrt(n)}var gb=class extends vt{static props={points:{default:[],required:!0},speed:{default:60},loop:{default:!0},mode:{default:`loop`,options:[`loop`,`pingpong`]},pauseAt:{default:0}};static signals=[`reachedPoint`];points=[];speed=60;loop=!0;mode=`loop`;pauseAt=0;index=0;direction=1;pauseTimer=0;onReady(){if(!Array.isArray(this.points)||this.points.length===0)throw new L(`PROP_TYPE_MISMATCH`,`Patrol on '${this.node.getPath()}': "points" must be a non-empty array of position arrays or node paths.`,{prop:`points`});if(this.mode!==`loop`&&this.mode!==`pingpong`)throw new L(`PROP_TYPE_MISMATCH`,`Patrol on '${this.node.getPath()}': "mode" must be 'loop' or 'pingpong', got '${this.mode}'.`,{prop:`mode`});ky(this)}update(e){if(this.pauseTimer>0){this.pauseTimer=Math.max(0,this.pauseTimer-e);return}let t=this.node,n=this.pointAt(this.index);if(!n){this.reportDeadWaypoint(this.index);return}let{position:r,reached:i}=Py(t.position,n,this.speed*e);Dy(t,r,e),i&&(this.emit(`reachedPoint`,this.index),this.advance(),this.pauseAt>0&&(this.pauseTimer=this.pauseAt))}reportedDead=new Set;reportDeadWaypoint(e){if(this.reportedDead.has(e))return;this.reportedDead.add(e);let t=this.points[e];Nt(this.node.tree?.engine??null,`error`,`[incanto] ${this.node.getPath()}: waypoint ${e} (${JSON.stringify(t)}) resolves to nothing — the patrol stops here and never moves again.`)}pointAt(e){let t=this.points[e];if(Array.isArray(t))return t;if(typeof t==`string`){let e=this.node.getNodeOrNull(t);return Array.isArray(e?.position)?e.position:null}return null}advance(){let e=this.points.length-1;if(this.mode===`pingpong`){this.index>=e?this.direction=-1:this.index<=0&&(this.direction=1),this.index=Math.min(e,Math.max(0,this.index+this.direction));return}this.index<e?this.index+=1:this.loop&&(this.index=0)}},_b=class extends vt{static props={value:{default:1},kind:{default:`coin`},collectorGroup:{default:`player`}};static signals=[`collected`];value=1;kind=`coin`;collectorGroup=`player`;collectedAlready=!1;onReady(){Hy(this,e=>this.tryCollect(e))}tryCollect(e){if(this.collectedAlready)return;let t=vb(e,this.collectorGroup);t&&(this.collectedAlready=!0,this.node.queueFree(),this.emit(`collected`,this.value,t))}};function vb(e,t){let n=[e];for(;n.length>0;){let e=n.shift();if(e.isInGroup(t))return e;n.push(...e.children)}for(let n=e.parent;n;n=n.parent)if(n.isInGroup(t))return n;return null}var yb=class extends vt{static props={speed:{default:300},direction:{default:null},gravity:{default:0}};static signals=[];speed=300;direction=null;gravity=0;velocity=[];onReady(){if(this.speed===0&&this.gravity===0)throw new L(`PROP_TYPE_MISMATCH`,`Projectile on '${this.node.getPath()}': a projectile with "speed" 0 and "gravity" 0 never moves — set one of them.`,{prop:`speed`});let e=ky(this),t=this.resolveDirection();for(this.velocity=t.map(e=>e*this.speed);this.velocity.length<e.position.length;)this.velocity.push(0)}update(e){let t=this.node;this.gravity!==0&&(this.velocity[1]=(this.velocity[1]??0)+this.gravity*e);let n=t.position,r=Math.max(n.length,this.velocity.length),i=Array(r);for(let t=0;t<r;t++)i[t]=(n[t]??0)+(this.velocity[t]??0)*e;t.position=i}resolveDirection(){if(Array.isArray(this.direction))return Ny(this.direction);if(this.direction===null||this.direction===`forward`)return this.forwardFromRotation();throw new L(`PROP_TYPE_MISMATCH`,`Projectile on '${this.node.getPath()}': "direction" must be a vector or 'forward', got ${JSON.stringify(this.direction)}.`,{prop:`direction`})}forwardFromRotation(){let e=this.node.rotation;if(typeof e==`number`){let t=e*Math.PI/180;return[Math.cos(t),Math.sin(t)]}if(Array.isArray(e)){let t=(e[1]??0)*Math.PI/180,n=(e[0]??0)*Math.PI/180;return Ny([Math.sin(t),-Math.sin(n)*Math.cos(t),Math.cos(n)*Math.cos(t)])}return[1,0]}},bb=class extends vt{static props={game:{default:`game`},slot:{default:`1`},label:{default:``},scene:{default:``},restoreOnReady:{default:!1},probeOnReady:{default:!1}};static signals=[`saved`,`restored`,`noSave`,`hasSave`];game=`game`;slot=`1`;label=``;scene=``;restoreOnReady=!1;probeOnReady=!1;elapsed=0;slots=null;store(){return this.slots??=new kn(this.game),this.slots}pendingRestore=!1;pendingProbe=!1;onReady(){this.pendingRestore=this.restoreOnReady,this.pendingProbe=this.probeOnReady}update(e){this.pendingProbe&&(this.pendingProbe=!1,this.probe()),this.pendingRestore&&(this.pendingRestore=!1,this.restore()),this.elapsed+=e}probe(){let e=this.store().read(this.slot);if(!e){this.emit(`noSave`);return}this.emit(`hasSave`,e.label||e.scene,e.playtime,e.scene)}get playtime(){return Math.round(this.elapsed)}slotScene(){return this.store().read(this.slot)?.scene??null}save(){let e=this.engine;this.store().write(this.slot,{scene:this.scene||(e.scene?.source.name??``),state:e.captureState(),label:this.label,savedAt:Date.now(),playtime:Math.round(this.elapsed)}),this.emit(`saved`,this.slot)}restore(){let e=this.store().read(this.slot);if(!e){this.emit(`noSave`);return}let t=this.engine.restoreState(e.state);this.emit(`restored`,t.restored)}clear(){this.store().remove(this.slot)}serialize(){return{playtime:Math.round(this.elapsed)}}deserialize(e){let t=e;typeof t.playtime==`number`&&t.playtime>=0&&(this.elapsed=t.playtime)}},xb=class extends vt{static props={score:{default:0},lives:{default:0},scoreToWin:{default:0}};static signals=[`scoreChanged`,`won`,`lost`,`lifeLost`];score=0;lives=0;scoreToWin=0;hasWon=!1;hasLost=!1;onReady(){if(this.lives<0)throw new L(`PROP_TYPE_MISMATCH`,`ScoreKeeper on '${this.node.getPath()}': "lives" must be >= 0, got ${this.lives}.`,{prop:`lives`});if(this.scoreToWin<0)throw new L(`PROP_TYPE_MISMATCH`,`ScoreKeeper on '${this.node.getPath()}': "scoreToWin" must be >= 0, got ${this.scoreToWin}.`,{prop:`scoreToWin`})}addScore(e){this.setScore(this.score+e)}setScore(e){this.score=e,this.emit(`scoreChanged`,this.score),this.scoreToWin>0&&!this.hasWon&&this.score>=this.scoreToWin&&(this.hasWon=!0,this.emit(`won`))}loseLife(){this.lives<=0||this.hasLost||(--this.lives,this.emit(`lifeLost`,this.lives),this.lives<=0&&(this.hasLost=!0,this.emit(`lost`)))}serialize(){return{score:this.score,lives:this.lives,hasWon:this.hasWon,hasLost:this.hasLost}}deserialize(e){let t=e;typeof t.score==`number`&&(this.score=t.score),typeof t.lives==`number`&&(this.lives=t.lives),typeof t.hasWon==`boolean`&&(this.hasWon=t.hasWon),typeof t.hasLost==`boolean`&&(this.hasLost=t.hasLost)}},Sb=class{behavior;detached=new Map;constructor(e){this.behavior=e}resolveTemplate(e){let t=this.detached.get(e);if(t)return t;let n=this.behavior.node,r=e===``?null:n.getNodeOrNull(e);if(!r){let t=this.behavior.constructor.name;throw new L(`NODE_NOT_FOUND`,`${t} on '${n.getPath()}': "prefab" '${e}' does not resolve to a template node. Point it at a (usually hidden) child node to clone.`,{prop:`prefab`,path:n.getPath()})}return r.parent&&r.parent.removeChild(r),this.detached.set(e,r),r}spawn(e,t){let n=Xi(e),r=t?.at;return r&&r.length>0&&Oy(n)&&(n.position=jy((t?.parent??this.behavior.node)===this.behavior.node||!Oy(this.behavior.node)?[]:this.behavior.node.position,r)),typeof n.visible==`boolean`&&(n.visible=!0),(t?.parent??this.behavior.node).addChild(n),n}},Cb={CameraShake:ab,DayNight:Gy,GameFlow:Qy,PathFollow:mb,Health:Vy,Lifetime:ob,ScoreKeeper:xb,Pickup:_b,Collector:By,DamageOnContact:Uy,Interactable:tb,Clickable:zy,SavePoint:bb,FollowCamera:Jy,Patrol:gb,Chase:Ry,Wander:class extends vt{static props={speed:{default:40},radius:{default:50},changeEvery:{default:2}};static signals=[];speed=40;radius=50;changeEvery=2;origin=[];goal=[];timer=0;onReady(){if(!(this.radius>0))throw new L(`PROP_TYPE_MISMATCH`,`Wander on '${this.node.getPath()}': "radius" must be > 0, got ${this.radius}.`,{prop:`radius`});let e=ky(this);this.origin=[...e.position],this.goal=[...e.position],this.pickGoal()}update(e){let t=this.node;this.timer-=e;let{position:n,reached:r}=Py(t.position,this.goal,this.speed*e);t.position=n,(r||this.timer<=0)&&this.pickGoal()}pickGoal(){this.timer=this.changeEvery;let e=this.origin.length,t=Array(e);for(let n=0;n<8;n++){for(let n=0;n<e;n++)t[n]=(this.origin[n]??0)+this.rng.range(-this.radius,this.radius);if(Ay(t,this.origin)<=this.radius){this.goal=t;return}}this.goal=t.map((e,n)=>{let r=this.origin[n]??0,i=Ay(t,this.origin)||1;return r+(e-r)/i*this.radius})}},ZombieAI:class extends vt{static props={aggroTarget:{default:``,nodePath:!0},aggroRange:{default:12},deAggroRange:{default:0},chaseSpeed:{default:4},wanderSpeed:{default:1.4},wanderRadius:{default:8},wanderChangeEvery:{default:3},goalTarget:{default:``,nodePath:!0},stopRange:{default:1.2},moveParent:{default:!1}};static signals=[`enteredAggro`,`exitedAggro`,`movementStateChanged`];aggroTarget=``;aggroRange=12;deAggroRange=0;chaseSpeed=4;wanderSpeed=1.4;wanderRadius=8;wanderChangeEvery=3;goalTarget=``;stopRange=1.2;moveParent=!1;aggro=!1;started=!1;home=[];goal=[];timer=0;lastState=``;mover(){let e=this.moveParent?this.node.parent:this.node;return e&&Oy(e)?e:null}effectiveDeAggro(){return this.deAggroRange>0?this.deAggroRange:this.aggroRange*1.5}onReady(){if(this.moveParent){let e=this.node.parent;if(!e||!Oy(e))throw new L(`PROP_TYPE_MISMATCH`,`ZombieAI on '${this.node.getPath()}': "moveParent" needs a spatial parent (a Node2D/Node3D) to move. '${this.node.name}' has none.`,{prop:`moveParent`,path:this.node.getPath()})}else ky(this)}update(e){let t=this.mover();if(!t)return;this.started||(this.started=!0,this.home=[...t.position],this.pickGoal());let n=this.aggroTarget?this.node.getNodeOrNull(this.aggroTarget):null,r=n&&Oy(n)?n.position:null,i=r?this.groundDistance(t.position,r):1/0;if(!this.aggro&&i<=this.aggroRange?(this.aggro=!0,this.emit(`enteredAggro`)):this.aggro&&i>=this.effectiveDeAggro()&&(this.aggro=!1,this.emit(`exitedAggro`),this.pickGoal()),this.aggro&&r){let n=this.approach(t,r,this.chaseSpeed,e);this.setState(n?`idle`:`run`);return}this.timer-=e;let a=this.approach(t,this.goal,this.wanderSpeed,e);this.setState(a?`idle`:`walk`),(a||this.timer<=0)&&this.pickGoal()}approach(e,t,n,r){let i=e.position;if(this.groundDistance(i,t)<=this.stopRange)return!0;let a=i.length>=3?1:-1,o=[...t];a>=0&&(o[a]=i[a]??0);let s=this.groundDistance(i,o),{position:c}=Py(i,o,Math.min(n*r,Math.max(0,s-this.stopRange)));return e.position=c,!1}groundDistance(e,t){if(e.length>=3){let n=(e[0]??0)-(t[0]??0),r=(e[2]??0)-(t[2]??0);return Math.hypot(n,r)}return Ay(e,t)}setState(e){e!==this.lastState&&(this.lastState=e,this.emit(`movementStateChanged`,e))}pickGoal(){this.timer=this.wanderChangeEvery;let e=this.mover(),t=e?e.position:this.home,n=t.length>=3?1:-1,r=this.home,i=this.goalTarget?this.node.getNodeOrNull(this.goalTarget):null;if(i&&Oy(i)){let e=i.position;r=t.map((t,n)=>t+((e[n]??0)-t)*.4)}let a=[...r];for(let e=0;e<a.length;e++)e!==n&&(a[e]=(r[e]??0)+this.rng.range(-this.wanderRadius,this.wanderRadius));n>=0&&(a[n]=t[n]??0),this.goal=a}},MoveTo:lb,Oscillate:pb,Spawner:class extends vt{static props={prefab:{default:``,nodePath:!0,required:!0},interval:{default:1},max:{default:0},at:{default:[]},autoStart:{default:!0},total:{default:0}};static signals=[`spawned`,`finished`];prefab=``;interval=1;max=0;at=[];autoStart=!0;total=0;source=new Sb(this);template;live=new Set;timer=0;running=!1;spawnedCount=0;done=!1;get liveCount(){return this.prune(),this.live.size}_templateForTest(){return this.template}onReady(){this.template=this.source.resolveTemplate(this.prefab),this.running=this.autoStart,this.timer=this.interval}start(){this.done||(this.running=!0)}stop(){this.running=!1}spawn(){if(this.prune(),this.done||this.max>0&&this.live.size>=this.max)return null;let e=this.source.spawn(this.template,this.at.length>0?{at:this.at}:void 0);return this.live.add(e),this.spawnedCount+=1,this.emit(`spawned`,e),this.total>0&&this.spawnedCount>=this.total&&(this.done=!0,this.running=!1,this.emit(`finished`)),e}update(e){this.running&&(this.timer-=e,!(this.timer>0)&&(this.timer+=this.interval,this.spawn()))}prune(){for(let e of this.live)e.parent===null&&this.live.delete(e)}},WaveSpawner:class extends vt{static props={waves:{default:[],required:!0},autoStart:{default:!0}};static signals=[`waveStarted`,`waveCleared`,`allCleared`];waves=[];autoStart=!0;source=new Sb(this);parsed=[];live=new Set;waveIndex=-1;phase=`idle`;timer=0;spawnedThisWave=0;announced=!1;onReady(){if(!Array.isArray(this.waves)||this.waves.length===0)throw new L(`PROP_TYPE_MISMATCH`,`WaveSpawner on '${this.node.getPath()}': "waves" must be a non-empty array of { prefab, count, interval, delayBefore }.`,{prop:`waves`});this.parsed=this.waves.map((e,t)=>this.parseWave(e,t));for(let e of this.parsed)this.source.resolveTemplate(e.prefab);this.autoStart&&this.beginWave(0)}start(){this.beginWave(0)}update(e){if(this.phase===`idle`||this.phase===`done`)return;let t=this.parsed[this.waveIndex];if(t){if(this.announced||(this.announced=!0,this.emit(`waveStarted`,this.waveIndex)),this.phase===`delay`){this.timer-=e,this.timer<=0&&(this.phase=`spawning`,this.timer=0);return}if(this.phase===`spawning`){for(this.timer-=e;this.timer<=0&&this.spawnedThisWave<t.count;){let e=this.source.spawn(this.source.resolveTemplate(t.prefab));this.live.add(e),this.spawnedThisWave+=1,this.timer+=t.interval}this.spawnedThisWave>=t.count&&(this.phase=`clearing`);return}if(this.phase===`clearing`&&(this.prune(),this.live.size===0)){this.emit(`waveCleared`,this.waveIndex);let e=this.waveIndex+1;e<this.parsed.length?this.beginWave(e):(this.phase=`done`,this.emit(`allCleared`))}}}beginWave(e){this.waveIndex=e,this.spawnedThisWave=0,this.announced=!1,this.live.clear();let t=this.parsed[e];t&&(t.delayBefore>0?(this.phase=`delay`,this.timer=t.delayBefore):(this.phase=`spawning`,this.timer=0))}prune(){for(let e of this.live)e.parent===null&&this.live.delete(e)}parseWave(e,t){let n=e,r=typeof n?.prefab==`string`?n.prefab:``;if(r===``)throw new L(`PROP_TYPE_MISMATCH`,`WaveSpawner on '${this.node.getPath()}': wave ${t} needs a "prefab" template path.`,{prop:`waves`});return{prefab:r,count:typeof n?.count==`number`?n.count:1,interval:typeof n?.interval==`number`?n.interval:.5,delayBefore:typeof n?.delayBefore==`number`?n.delayBefore:0}}},Projectile:yb,Buoyancy:Ty,FloatAway:qy};function wb(e){let t=e?.replace??!0;for(let[e,n]of Object.entries(Cb))St(e,n,{replace:t})}function Tb(e,t){let n=e.shape;if(n!==void 0){if(e.oneWay!==void 0&&typeof e.oneWay!=`boolean`)throw new L(`BAD_FORMAT`,`Collider on '${t}': "oneWay" must be a boolean (platforms you jump up through), got ${JSON.stringify(e.oneWay)}.`);if(n===`rect`){let n=e.size;if(!Array.isArray(n)||n.length!==2||n.some(e=>typeof e!=`number`))throw new L(`BAD_FORMAT`,`Collider on '${t}': rect needs "size": [width, height].`);return}if(n===`circle`){if(typeof e.radius!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${t}': circle needs "radius".`);return}if(n===`capsule`){if(typeof e.radius!=`number`||typeof e.height!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${t}': capsule needs "radius" and "height".`);return}throw new L(`BAD_FORMAT`,`Collider on '${t}': "shape" must be 'rect', 'circle', or 'capsule', got ${JSON.stringify(n)}.`)}}var Eb=class extends Ft{static typeName=`Node2D`;static props={position:{default:[0,0]},rotation:{default:0},static:{default:!1},scale:{default:[1,1]},renderOrder:{default:0},orderGroup:{default:`default`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},visible:{default:!0}};static propAliases={zIndex:`renderOrder`};position=[0,0];rotation=0;static=!1;scale=[1,1];renderOrder=0;orderGroup=`default`;get effectiveRenderOrder(){return gn(this.orderGroup,this.renderOrder,this.tree?.engine?.orderGroups)}visible=!0;_object2D=null;_ensureObject2D(){return this._object2D||(this._object2D=this._createObject2D(),this._object2D.userData.incantoNode=this),this._object2D}_createObject2D(){return new Tc}_staticReady(e){return!0}_syncObject2D(e){let t=this._ensureObject2D();t.position.set(this.position[0]??0,-(this.position[1]??0),0),t.rotation.z=-As.degToRad(this.rotation),t.scale.set(this.scale[0]??1,this.scale[1]??1,1),t.visible=this.visible}free(){super.free(),this._object2D?.removeFromParent(),this._object2D=null}},Db=class extends Eb{static props={collider:{default:{},variants:{tag:`shape`,byTag:{rect:{shape:`rect`,size:[32,32]},circle:{shape:`circle`,radius:16},capsule:{shape:`capsule`,radius:12,height:32}}}},enabled:{default:!0}};static signals=[`triggerEnter`,`triggerExit`];_collider={};_colliderChanged=!1;_enabled=!0;_enabledChanged=!1;get collider(){return this._collider}set collider(e){this._collider=e,this._colliderChanged=!0}get enabled(){return this._enabled}set enabled(e){e!==this._enabled&&(this._enabled=e,this._enabledChanged=!0)}static validateJson(e){Tb(e.collider,e.name)}_physics=null},Ob=class extends Db{static typeName=`StaticBody2D`},kb=class extends Db{static typeName=`Area2D`},Ab=class extends Db{static typeName=`RigidBody2D`;static props={mass:{default:1},gravityScale:{default:1},fixedRotation:{default:!1},friction:{default:.5},restitution:{default:0},linearVelocity:{default:[0,0]}};mass=1;gravityScale=1;fixedRotation=!1;friction=.5;restitution=0;linearVelocity=[0,0]},jb=class extends Db{static typeName=`CharacterBody2D`;static props={velocity:{default:[0,0]},stickToGround:{default:!0},slopeLimitDeg:{default:45}};static propAliases={snapToGround:`stickToGround`};velocity=[0,0];stickToGround=!0;slopeLimitDeg=45;_grounded=!1;moveAndSlide(){if(!this._physics)throw new L(`TREE_VIOLATION`,this.collider.shape===void 0?`CharacterBody2D '${this.name}' has no collider — set a collider prop (physics skips collider-less bodies).`:`CharacterBody2D '${this.name}' has no physics world — await enablePhysics2D(engine) first.`);this._physics.moveAndSlide(this)}_onWall=0;_onCeiling=!1;isOnWall(){return this._onWall!==0}wallSide(){return this._onWall}isOnCeiling(){return this._onCeiling}isOnFloor(){return this._grounded}},Mb=new Set;function Nb(e){return Mb.add(e),()=>Mb.delete(e)}function Pb(e,t){return[...Mb].filter(n=>n.dimension===e&&(t===void 0||n.engine===t))}var Fb=`using deprecated parameters for the initialization function`;async function Ib(e,t=console){let n=t.warn;t.warn=(...e)=>{typeof e[0]==`string`&&e[0].includes(Fb)||n.apply(t,e)};try{await e()}finally{t.warn=n}}var Lb=class extends Eb{static typeName=`Joint2D`;static props={type:{default:`revolute`,options:[`fixed`,`revolute`,`rope`,`spring`]},target:{default:``,nodePath:!0,required:!0},anchor:{default:[0,0]},targetAnchor:{default:[0,0]},length:{default:0},stiffness:{default:50},damping:{default:5}};type=`revolute`;target=``;anchor=[0,0];targetAnchor=[0,0];length=0;stiffness=50;damping=5;onEnterTree(){if(!(this.parent instanceof Db))throw new L(`TREE_VIOLATION`,`Joint2D '${this.name}' must be a child of a physics body (its body A); parent is '${this.parent?.name??`none`}'.`);if(this.target===``)throw new L(`BAD_FORMAT`,`Joint2D '${this.name}' needs a "target" node path to the body it links to.`)}_resolveBodies(){let e=this.parent,t=this.getNodeOrNull(this.target);if(!(t instanceof Db))throw new L(`NODE_NOT_FOUND`,`Joint2D '${this.name}': target '${this.target}' is not a physics body.`);return{a:e,b:t}}},Rb=100,zb=Math.PI/180;async function Bb(e,t){let n=await Bg(()=>import(`./rapier-CEuLKeCu.js`),[],import.meta.url);return await Ib(()=>n.init()),new Vb(n,e,t)}var Vb=class{R;engine;debugDraw=!1;debugScope=null;dimension=`2d`;unregisterDebug;warnedNoCollider=new WeakSet;entries=new Map;byColliderHandle=new Map;world;events;kcc;disconnectScene;disconnect;lastDt=1/60;optsGravity;lastScene=null;constructor(e,t,n){this.R=e,this.engine=t,this.optsGravity=n?.gravity,this.simulate=n?.simulate??!0,this.lastScene=t.scene;let r=t.scene?.physics?.gravity,i=n?.gravity??r??[0,980];this.world=new e.World({x:(i[0]??0)/Rb,y:(i[1]??0)/Rb}),this.kcc=this.world.createCharacterController(.01),this.kcc.setUp({x:0,y:-1}),this.events=new e.EventQueue(!0),this.unregisterDebug=Nb(this),this.disconnect=t.fixedUpdated.connect(e=>this.step(e)),this.disconnectScene=t.sceneChanged.connect(()=>{t.scene&&this.syncBodies()}),this.syncBodies()}simulate;step(e){if(this.lastDt=e,!this.simulate){this.syncBodies(),this.poseFromTree();return}if(this.engine.scene!==this.lastScene&&(this.lastScene=this.engine.scene,!this.optsGravity)){let e=this.engine.scene?.physics?.gravity??[0,980];this.world.gravity={x:(e[0]??0)/Rb,y:(e[1]??0)/Rb}}this.syncBodies(),this.world.timestep=e,this.world.step(this.events);for(let[e,t]of this.entries){let n=t.body.translation();if(!t.body.isFixed()&&!(e instanceof kb)){let[t,r]=Jb(e);e.position=[n.x*Rb-t,n.y*Rb-r]}if(e instanceof Ab){e.fixedRotation||(e.rotation=t.body.rotation()/zb,t.lastRot=e.rotation);let n=t.body.linvel();e.linearVelocity=[n.x*Rb,n.y*Rb],t.lastVX=e.linearVelocity[0]??0,t.lastVY=e.linearVelocity[1]??0}let[r,i]=qb(e);t.lastX=r,t.lastY=i}this.events.drainCollisionEvents((e,t,n)=>{let r=this.byColliderHandle.get(e),i=this.byColliderHandle.get(t);if(!r||!i)return;let a=n?`triggerEnter`:`triggerExit`;try{r.emit(a,i),i.emit(a,r)}catch(e){Nt(this.engine,`error`,`incanto: error in a '${a}' handler (${r.name} ↔ ${i.name}):`,e)}})}moveAndSlide(e){let t=this.ensureEntry(e),n=e.velocity[1]??0;e.stickToGround&&n>=0?this.kcc.enableSnapToGround(.05):this.kcc.disableSnapToGround(),this.kcc.setMaxSlopeClimbAngle(e.slopeLimitDeg*zb);let r=0,i=0;if(t.ground&&t.ground._physics===this){let[e,n]=qb(t.ground);r=e-(t.groundX??e),i=n-(t.groundY??n)}else t.ground=null;let a={x:((e.velocity[0]??0)*this.lastDt+r)/Rb*1,y:(n*this.lastDt+i)/Rb*1},o=t.body.translation().y*Rb+Gb(e);this.kcc.computeColliderMovement(t.collider,a,this.R.QueryFilterFlags.EXCLUDE_SENSORS,void 0,t=>{let r=this.byColliderHandle.get(t.handle);return!(r&&r!==e&&r.collider.oneWay===!0&&(n<0||o>Kb(r)+Wb))});let s=this.kcc.computedMovement(),c=t.body.translation();t.body.setNextKinematicTranslation({x:c.x+s.x,y:c.y+s.y}),e._grounded=this.kcc.computedGrounded(),e._onWall=0,e._onCeiling=!1;let l=this.kcc.numComputedCollisions();for(let t=0;t<l;t++){let n=this.kcc.computedCollision(t)?.normal1;n&&(Math.abs(n.y)>.7?e._grounded||(e._onCeiling=!0):Math.abs(n.x)>.7&&(e._onWall=n.x>0?-1:1))}if(e._grounded){let n=(c.x+s.x)*Rb,r=(c.y+s.y)*Rb+Gb(e)-2,i=this.castRay([n,r],[0,1],8,e);if(i?.node&&!(i.node instanceof jb)){t.ground=i.node;let[e,n]=qb(i.node);t.groundX=e,t.groundY=n}else t.ground=null}else t.ground=null}debugLines(){if(!this.debugDraw)return null;let e=this.debugScope?this.scopedLines(this.debugScope):this.world.debugRender().vertices,t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n]*Rb;return t}scopedLines(e){let t=[],n=[],r=e=>{let t=this.entries.get(e);t&&n.push(t.body);for(let t of e.children)r(t)};r(e);for(let t=e.parent;t&&n.length===0;t=t.parent){let e=this.entries.get(t);e&&n.push(e.body)}for(let e of n)for(let n=0;n<e.numColliders();n++){let r=e.collider(n);if(!r)continue;let i=r.translation(),a=r.rotation(),o=Math.cos(a),s=Math.sin(a),c=(e,n)=>{t.push(i.x+e*o-n*s,i.y+e*s+n*o)},l=(e,t,n,r)=>{c(e,t),c(n,r)},u=r.shape;if(u.halfExtents){let{x:e,y:t}=u.halfExtents;l(-e,-t,e,-t),l(e,-t,e,t),l(e,t,-e,t),l(-e,t,-e,-t)}else if(u.radius!==void 0){let e=u.radius,t=u.halfHeight??0;for(let n=0;n<24;n++){let r=n/24*Math.PI*2,i=(n+1)/24*Math.PI*2,a=e=>e>=0?t:-t;l(Math.cos(r)*e,Math.sin(r)*e+a(Math.sin(r)),Math.cos(i)*e,Math.sin(i)*e+a(Math.sin(i)))}t>0&&(l(-e,-t,-e,t),l(e,-t,e,t))}}return new Float32Array(t)}syncJoints(e){let t=this.R;if(e)for(let[e,t]of this.joints)this.jointSet.has(e)||(this.world.removeImpulseJoint(t,!0),this.joints.delete(e));for(let e of this.jointSet){if(this.joints.has(e))continue;let{a:n,b:r}=e._resolveBodies(),i=this.entries.get(n),a=this.entries.get(r);if(!i||!a)continue;let o={x:(e.anchor[0]??0)/Rb,y:(e.anchor[1]??0)/Rb},s={x:(e.targetAnchor[0]??0)/Rb,y:(e.targetAnchor[1]??0)/Rb},c=e.length/Rb;if(e.length===0&&(e.type===`rope`||e.type===`spring`)){let e=i.body.translation(),t=a.body.translation();c=Math.hypot(t.x-e.x,t.y-e.y)}let l;l=e.type===`fixed`?t.JointData.fixed(o,0,s,0):e.type===`rope`?t.JointData.rope(c,o,s):e.type===`spring`?t.JointData.spring(c,e.stiffness,e.damping,o,s):t.JointData.revolute(o,s),this.joints.set(e,this.world.createImpulseJoint(l,i.body,a.body,!0))}}castRay(e,t,n,r,i){let a=Math.hypot(t[0],t[1])||1,o=new this.R.Ray({x:e[0]/Rb,y:e[1]/Rb},{x:t[0]/a,y:t[1]/a}),s=r?this.entries.get(r)?.collider:void 0,c=i?.staticOnly?this.R.QueryFilterFlags.EXCLUDE_DYNAMIC|this.R.QueryFilterFlags.EXCLUDE_KINEMATIC:void 0,l=this.world.castRayAndGetNormal(o,n/Rb,!0,c,void 0,s,void 0,e=>!e.isSensor());return l?{distance:l.timeOfImpact*Rb,normal:[l.normal.x,l.normal.y],node:this.byColliderHandle.get(l.collider.handle)??null}:null}dispose(){this.disconnect(),this.disconnectScene(),this.unregisterDebug(),this.world.free()}lastStructure=-1;lastRoot=null;jointSet=new Set;joints=new Map;bodySet=new Set;poseFromTree(){for(let[e,t]of this.entries){let[n,r]=qb(e);t.body.setTranslation({x:n/Rb,y:r/Rb},!1),t.body.setRotation(e.rotation*zb,!1)}this.world.propagateModifiedBodyPositionsToColliders()}syncBodies(){let e=this.engine.scene;if(!e)return;let t=e.tree._structureVersion,n=e.root===this.lastRoot,r=t!==this.lastStructure||!n;if(r){let r=n?e.tree._structureSince(this.lastStructure):null;if(this.lastStructure=t,this.lastRoot=e.root,r){let t=!1;for(let{node:e,added:n}of r)e instanceof Db&&(n?this.bodySet.add(e):this.bodySet.delete(e)),e instanceof Lb&&(t=!0);t&&(this.jointSet.clear(),Hb(e.root,this.jointSet))}else this.bodySet.clear(),Ub(e.root,this.bodySet),this.jointSet.clear(),Hb(e.root,this.jointSet)}let i=this.bodySet;for(let e of i){if(e.collider.shape===void 0){let t=this.entries.get(e);t&&(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null),this.warnedNoCollider.has(e)||(this.warnedNoCollider.add(e),Nt(this.engine,`warn`,`[incanto] '${e.name}' has no collider — physics skips it.`));continue}let t=this.entries.get(e);t&&e._colliderChanged&&(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null),this.ensureEntry(e)}if(this.syncJoints(r),r)for(let[e,t]of this.entries)i.has(e)||(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null)}ensureEntry(e){let t=this.entries.get(e),n=this.R;if(!t){let[r,i]=qb(e),a=r/Rb,o=i/Rb,s;s=e instanceof Ab?n.RigidBodyDesc.dynamic():e instanceof jb||e instanceof kb?n.RigidBodyDesc.kinematicPositionBased():n.RigidBodyDesc.fixed(),s.setTranslation(a,o).setRotation(e.rotation*zb),e instanceof Ab&&(s.setGravityScale(e.gravityScale),s.setLinvel((e.linearVelocity[0]??0)/Rb,(e.linearVelocity[1]??0)/Rb),e.fixedRotation&&s.lockRotations());let c=this.world.createRigidBody(s),l=Yb(n,e.collider,e.name);l.setActiveEvents(n.ActiveEvents.COLLISION_EVENTS),l.setActiveCollisionTypes(n.ActiveCollisionTypes.ALL),e instanceof kb&&l.setSensor(!0),e instanceof Ab&&l.setMass(e.mass).setFriction(e.friction).setRestitution(e.restitution);let u=this.world.createCollider(l,c);return t={body:c,collider:u,lastX:r,lastY:i,lastRot:e.rotation,lastVX:0,lastVY:0},this.entries.set(e,t),this.byColliderHandle.set(u.handle,e),e.enabled||(u.setEnabled(!1),c.setEnabled(!1)),e._colliderChanged=!1,e._enabledChanged=!1,e._physics=this,t}e._enabledChanged&&=(t.collider.setEnabled(e.enabled),t.body.setEnabled(e.enabled),!1);let[r,i]=qb(e);if((r!==t.lastX||i!==t.lastY)&&(t.body.setTranslation({x:r/Rb,y:i/Rb},!0),t.lastX=r,t.lastY=i),e.rotation!==t.lastRot&&(t.body.setRotation(e.rotation*zb,!0),t.lastRot=e.rotation),e instanceof Ab){let n=e.linearVelocity[0]??0,r=e.linearVelocity[1]??0;(n!==t.lastVX||r!==t.lastVY)&&(t.body.setLinvel({x:n/Rb,y:r/Rb},!0),t.lastVX=n,t.lastVY=r)}return t}};function Hb(e,t){e instanceof Lb&&t.add(e);for(let n of e.children)Hb(n,t)}function Ub(e,t){e instanceof Db&&t.add(e);for(let n of e.children)Ub(n,t)}var Wb=4;function Gb(e){let t=e.collider;return t.shape===`rect`?(t.size?.[1]??32)/2:t.shape===`capsule`?(t.height??32)/2+(t.radius??8):t.radius??16}function Kb(e){let[,t]=qb(e),n=e.collider;return t-(n.shape===`rect`?(n.size?.[1]??32)/2:n.shape===`capsule`?(n.height??32)/2+(n.radius??8):n.radius??16)}function qb(e){let t=0,n=0;for(let r=e;r;r=r.parent)r instanceof Eb&&(t+=r.position[0]??0,n+=r.position[1]??0);return[t,n]}function Jb(e){let t=0,n=0;for(let r=e.parent;r;r=r.parent)r instanceof Eb&&(t+=r.position[0]??0,n+=r.position[1]??0);return[t,n]}function Yb(e,t,n){Tb(t,n);let r=Xb(e,t,n),i=t.offset;return Array.isArray(i)&&r.setTranslation((i[0]??0)/Rb,(i[1]??0)/Rb),r}function Xb(e,t,n){let r=t.shape;if(r===`rect`){let r=t.size;if(!Array.isArray(r)||r.length!==2||r.some(e=>typeof e!=`number`))throw new L(`BAD_FORMAT`,`Collider on '${n}': rect needs "size": [width, height].`);return e.ColliderDesc.cuboid(r[0]/2/Rb,r[1]/2/Rb)}if(r===`circle`){if(typeof t.radius!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${n}': circle needs "radius".`);return e.ColliderDesc.ball(t.radius/Rb)}if(r===`capsule`){if(typeof t.radius!=`number`||typeof t.height!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${n}': capsule needs "radius" and "height".`);return e.ColliderDesc.capsule(t.height/2/Rb,t.radius/Rb)}throw new L(`BAD_FORMAT`,`Collider on '${n}': "shape" must be 'rect', 'circle', or 'capsule', got ${JSON.stringify(r)}.`)}function Zb(e){let t=[];for(let n=2;n<=32;n++)e%n===0&&t.push(e/n);return t.sort((e,t)=>t-e).slice(0,6)}function Qb(e,t,n,r,i,a){if(!r||!i||!t||!n)return null;if(r%t!==0||i%n!==0){let a=[];if(r%t!==0){let e=Zb(r);a.push(`${r} px wide is not a whole number of ${t} px frames`+(e.length>0?` (${e.join(`, `)} would divide it)`:``))}if(i%n!==0){let e=Zb(i);a.push(`${i} px tall is not a whole number of ${n} px frames`+(e.length>0?` (${e.join(`, `)} would divide it)`:``))}return`[incanto] spritesheet '${e}' does not fit its frame size: ${a.join(`; `)}. Every row after the first is cut off centre.`}if(a!==void 0){let o=r/t*(i/n);if(a>=o)return`[incanto] spritesheet '${e}' has ${o} frames (0–${o-1}), and an animation asks for frame ${a}. Those frames draw whatever is at the wrong end of the sheet.`}return null}var $b=new _d(1,1),ex=class extends Eb{static typeName=`Sprite2D`;static props={texture:{default:``,asset:{kind:`texture`,refOnly:!0}},anchor:{default:[.5,.5]},flipX:{default:!1},flipY:{default:!1},tint:{default:`#ffffff`},opacity:{default:1}};texture=``;anchor=[.5,.5];flipX=!1;flipY=!1;tint=`#ffffff`;opacity=1;quadMesh=null;_quad(){return this.quadMesh||(this.quadMesh=new iu($b,new Kl({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_createObject2D(){return super._createObject2D()}resolveTexture(e){if(!this.texture||!e)return null;let t=e.getTexture(this.texture),n=t.image;return!n?.width||!n.height?null:{texture:t,width:n.width,height:n.height}}_staticReady(e){return this.texture===``||this.resolveTexture(e)!==null}_syncObject2D(e){super._syncObject2D(e);let t=this._quad(),n=t.material,r=this.resolveTexture(e);if(!r){t.visible=!1;return}t.visible=!0,n.map!==r.texture&&(n.map=r.texture,n.needsUpdate=!0);let i=r.width,a=r.height;t.scale.set(this.flipX?-i:i,this.flipY?-a:a,1);let o=this.anchor[0]??.5,s=this.anchor[1]??.5;t.position.set((.5-o)*i,(s-.5)*a,0),t.renderOrder=this.effectiveRenderOrder,n.color.set(this.tint),n.opacity=this.opacity}},tx=class extends ex{static typeName=`AnimatedSprite2D`;static signals=[`animationFinished`];static props={sheet:{default:``,asset:{kind:`spritesheet`,refOnly:!0}},animations:{default:{}},autoplay:{default:``}};sheet=``;animations={};autoplay=``;playing=!1;currentFrame=0;currentAnimation=``;frameList=[];frameIndex=0;frameTime=0;currentDef=null;ownTexture=null;loadedSheetRef=``;play(e){let{name:t,def:n}=Zi(this.animations,e,this.name);this.currentAnimation=t,this.currentDef=n,this.frameList=$i(n.frames,t),this.frameIndex=0,this.currentFrame=this.frameList[0]??0,this.frameTime=0,this.playing=!0}stop(){this.playing=!1}onReady(){Qi(this.animations,this.name),this.autoplay&&this.play(this.autoplay)}update(e){if(!this.playing||this.currentAnimation===``)return;let t=this.currentDef;if(!t||!Number.isFinite(t.fps)||t.fps<=0)return;let n=1/t.fps;for(this.frameTime+=e;this.frameTime>=n;)if(this.frameTime-=n,this.frameIndex+=1,this.frameIndex>=this.frameList.length)if(t.loop)this.frameIndex=0;else{this.frameIndex=this.frameList.length-1,this.playing=!1,this.emit(`animationFinished`,this.currentAnimation);break}this.currentFrame=this.frameList[this.frameIndex]??0}gridChecked=``;checkGrid(e,t,n,r,i){if(this.gridChecked===e)return;this.gridChecked=e;let a=0;for(let[e,t]of Object.entries(this.animations))if(typeof t!=`string`)try{for(let n of $i(t.frames,e))n>a&&(a=n)}catch{return}let o=Qb(e,t,n,r,i,a);o&&Nt(this.tree?.engine??null,`error`,o)}resolveTexture(e){if(!this.sheet||!e)return null;let t=e.getSheet(this.sheet);this.loadedSheetRef!==this.sheet&&(this.ownTexture=t.texture.clone(),this.ownTexture.needsUpdate=!0,this.loadedSheetRef=this.sheet);let n=this.ownTexture,r=t.texture.image;if(!r?.width||!r.height)return null;this.checkGrid(this.sheet,t.frameWidth,t.frameHeight,r.width,r.height);let i=Math.max(1,Math.floor(r.width/t.frameWidth)),a=this.currentFrame%i,o=Math.floor(this.currentFrame/i);return n.repeat.set(t.frameWidth/r.width,t.frameHeight/r.height),n.offset.set(a*t.frameWidth/r.width,1-(o+1)*t.frameHeight/r.height),{texture:n,width:t.frameWidth,height:t.frameHeight}}},nx=class extends Eb{static typeName=`Camera2D`;static props={follow:{default:``,nodePath:!0},smoothing:{default:0},zoom:{default:1},limits:{default:[]},current:{default:!1}};follow=``;smoothing=0;zoom=1;limits=[];current=!1;get effectiveZoom(){return Math.max(.01,this.zoom)}update(e){if(!this.follow)return;let t=this.getNodeOrNull(this.follow);if(!(t instanceof Eb))return;let[n=0,r=0]=Iy(t),[i=0,a=0]=Iy(this),o=Math.min(Math.max(this.smoothing,0),.99),s=o<=0?1:1-o**(e*60),[c=0,l=0]=Ly(this,[i+(n-i)*s,a+(r-a)*s]);this.position=[c,l]}clampedCenter(e,t){let n=Iy(this),r=n[0]??0,i=n[1]??0;if(this.limits.length!==0&&this.limits.length!==4)throw new L(`BAD_FORMAT`,`Camera2D '${this.name}' limits must be [] or [minX,minY,maxX,maxY], got length ${this.limits.length}.`);if(this.limits.length===4){let[n,a,o,s]=this.limits,c=e/(2*this.effectiveZoom),l=t/(2*this.effectiveZoom);r=rx(r,n+c,o-c),i=rx(i,a+l,s-l)}return{x:r,y:i}}};function rx(e,t,n){return t>n?(t+n)/2:Math.min(n,Math.max(t,e))}var ix=class extends Ft{static typeName=`CharacterController2D`;static props={mode:{default:`platformer`,options:[`platformer`,`topDown`]},maxSpeed:{default:220},jumpHeight:{default:64},moveAction:{default:`move`},jumpAction:{default:`jump`},coyoteSeconds:{default:0},jumpBufferSeconds:{default:0},jumpCutMultiplier:{default:1},maxJumps:{default:1},dashSpeed:{default:0},dashSeconds:{default:.15},dashAction:{default:`dash`},wallSlideSpeed:{default:0},wallJumpImpulse:{default:[0,0]}};static signals=[`movementStateChanged`];mode=`platformer`;maxSpeed=220;jumpHeight=64;moveAction=`move`;jumpAction=`jump`;coyoteSeconds=0;jumpBufferSeconds=0;jumpCutMultiplier=1;maxJumps=1;dashSpeed=0;dashSeconds=.15;dashAction=`dash`;wallSlideSpeed=0;wallJumpImpulse=[0,0];state=`idle`;coyoteLeft=0;bufferLeft=0;jumpsUsed=0;dashLeft=0;dashDir=1;rising=!1;onReady(){if(!(this.parent instanceof jb))throw new L(`TREE_VIOLATION`,`CharacterController2D '${this.name}' must be a child of a CharacterBody2D (parent is '${this.parent?.name??`none`}').`);if(this.mode!==`platformer`&&this.mode!==`topDown`)throw new L(`PROP_TYPE_MISMATCH`,`CharacterController2D.mode must be 'platformer' or 'topDown', got '${this.mode}'.`)}fixedUpdate(e){let t=this.tree?.engine;if(!t?.scene)return;let n=this.parent;if(!(n instanceof jb))return;let r=t.input,i=r.getVector(this.moveAction);if(this.mode===`topDown`){n.velocity=[i.x*this.maxSpeed,i.y*this.maxSpeed],n.moveAndSlide();return}let a=t.scene.physics?.gravity?.[1]??980,o=n.isOnFloor(),s=-Math.sqrt(2*a*this.jumpHeight);if(this.dashLeft>0){this.dashLeft-=e,n.velocity[0]=this.dashDir*this.dashSpeed,n.velocity[1]=0,n.moveAndSlide(),this.setState(`dash`);return}if(this.dashSpeed>0&&r.justPressed(this.dashAction)){this.dashLeft=this.dashSeconds,this.dashDir=i.x===0?this.dashDir:Math.sign(i.x),n.velocity[0]=this.dashDir*this.dashSpeed,n.velocity[1]=0,n.moveAndSlide(),this.setState(`dash`);return}n.velocity[0]=i.x*this.maxSpeed,o?(this.coyoteLeft=this.coyoteSeconds,this.jumpsUsed=0):(this.coyoteLeft=Math.max(0,this.coyoteLeft-e),this.coyoteLeft<=0&&this.jumpsUsed===0&&(this.jumpsUsed=1)),r.justPressed(this.jumpAction)?this.bufferLeft=Math.max(this.jumpBufferSeconds,0):this.bufferLeft=Math.max(0,this.bufferLeft-e);let c=this.bufferLeft>0||r.justPressed(this.jumpAction),l=this.wallSlideSpeed>0||this.wallJumpImpulse.some(e=>e!==0)?n.isOnWall():!1;if(c&&l&&!o&&this.wallJumpImpulse.some(e=>e!==0)){let e=-n.wallSide();n.velocity[0]=e*(this.wallJumpImpulse[0]??0),n.velocity[1]=-(this.wallJumpImpulse[1]??0),this.bufferLeft=0,this.rising=!0,this.jumpsUsed=1}else c&&(o||this.coyoteLeft>0||this.jumpsUsed<this.maxJumps)?(n.velocity[1]=s,this.bufferLeft=0,this.coyoteLeft=0,this.rising=!0,this.jumpsUsed=o?1:this.jumpsUsed+1):o?(n.velocity[1]=20,this.rising=!1):(n.velocity[1]=(n.velocity[1]??0)+a*e,this.rising&&this.jumpCutMultiplier<1&&!r.isPressed(this.jumpAction)&&(n.velocity[1]=(n.velocity[1]??0)*this.jumpCutMultiplier,this.rising=!1),(n.velocity[1]??0)>=0&&(this.rising=!1),this.wallSlideSpeed>0&&l&&(n.velocity[1]??0)>this.wallSlideSpeed&&(n.velocity[1]=this.wallSlideSpeed));n.isOnCeiling()&&(n.velocity[1]??0)<0&&(n.velocity[1]=0,this.rising=!1),n.moveAndSlide();let u=n.velocity[1]??0;this.wallSlideSpeed>0&&!n.isOnFloor()&&n.isOnWall()&&u>0?this.setState(`wallSlide`):n.isOnFloor()?this.setState(Math.abs(i.x)>.01?`run`:`idle`):this.setState(u<0?`jump`:`fall`)}setState(e){e!==this.state&&(this.state=e,this.emit(`movementStateChanged`,e))}},ax=new _d(1,1),ox=class extends Eb{static typeName=`ColorRect2D`;static props={size:{default:[100,100]},color:{default:`#ffffff`},opacity:{default:1},anchor:{default:[.5,.5]}};size=[100,100];color=`#ffffff`;opacity=1;anchor=[.5,.5];quadMesh=null;_quad(){return this.quadMesh||(this.quadMesh=new iu(ax,new Kl({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_syncObject2D(e){super._syncObject2D(e);let t=this._quad(),n=this.size[0]??0,r=this.size[1]??0;t.visible=n>0&&r>0&&this.opacity>0,t.scale.set(n,r,1);let i=this.anchor[0]??.5,a=this.anchor[1]??.5;t.position.set((.5-i)*n,(a-.5)*r,0),t.renderOrder=this.effectiveRenderOrder;let o=t.material;o.color.set(this.color),o.opacity=this.opacity}},sx=new _d(1,1),cx=class extends Eb{static typeName=`Label`;static props={text:{default:``},fontSize:{default:16},color:{default:`#ffffff`},font:{default:`monospace`},align:{default:`left`},opacity:{default:1,range:{min:0,max:1}}};text=``;fontSize=16;color=`#ffffff`;font=`monospace`;align=`left`;opacity=1;quadMesh=null;canvas=null;lastKey=``;_quad(){return this.quadMesh||(this.quadMesh=new iu(sx,new Kl({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_syncObject2D(e){super._syncObject2D(e);let t=this._quad(),n=Qe(this,this.text);if(typeof document>`u`||n===``){t.visible=!1;return}let r=`${n}\0${this.fontSize}\0${this.color}\0${this.font}\0${this.align}`;r!==this.lastKey&&(this.lastKey=r,this.rasterize()),t.visible=this.opacity>0,t.material.opacity=this.opacity,t.renderOrder=this.effectiveRenderOrder}rasterize(){let e=Qe(this,this.text),t=Math.min(globalThis.devicePixelRatio??1,2);this.canvas??=document.createElement(`canvas`);let n=this.canvas.getContext(`2d`);if(!n)return;let r=`${this.fontSize*t}px ${this.font}`;n.font=r;let i=n.measureText(e),a=Math.max(1,Math.ceil(i.width)),o=Math.ceil(this.fontSize*t*1.4);this.canvas.width=a,this.canvas.height=o,n.font=r,n.fillStyle=this.color,n.textBaseline=`middle`,n.fillText(e,0,o/2);let s=this._quad(),c=s.material;c.map?.dispose();let l=new sd(this.canvas);l.colorSpace=Ro,c.map=l,c.needsUpdate=!0;let u=a/t,d=o/t;s.scale.set(u,d,1);let f=this.align===`center`?.5:+(this.align===`right`);s.position.set((.5-f)*u,0,0)}free(){let e=this.quadMesh;if(e){let t=e.material;t.map?.dispose(),t.dispose(),e.removeFromParent(),this.quadMesh=null}this.canvas=null,super.free()}},lx=new _d(1,1),ux=class e extends Eb{orderGroup=`effects`;static typeName=`Particles2D`;static signals=[`finished`];static props={orderGroup:{default:`effects`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},preset:{default:`custom`,options:[`custom`,...wr]},emitting:{default:!0},worldSpace:{default:!1},rate:{default:40},burst:{default:0},lifetime:{default:[.6,1.2]},speed:{default:[40,120]},directionDeg:{default:-90},spreadDeg:{default:30},gravity:{default:[0,0]},drag:{default:0},sizeStart:{default:8},sizeEnd:{default:2},colorStart:{default:`#ffffff`},colorEnd:{default:`#ffffff`},paletteColors:{default:[]},alphaStart:{default:1},alphaEnd:{default:0},shimmer:{default:0},blend:{default:`add`,options:[`add`,`normal`]},maxParticles:{default:256}};preset=`custom`;emitting=!0;worldSpace=!1;rate=40;burst=0;lifetime=[.6,1.2];speed=[40,120];directionDeg=-90;spreadDeg=30;gravity=[0,0];drag=0;sizeStart=8;sizeEnd=2;colorStart=`#ffffff`;colorEnd=`#ffffff`;paletteColors=[];alphaStart=1;alphaEnd=0;shimmer=0;blend=`add`;maxParticles=256;static validateJson(e){let t=e;if(t.preset!==`custom`&&!wr.includes(t.preset))throw new L(`BAD_FORMAT`,`Particles2D '${e.name}' preset must be 'custom' or one of [${wr.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:wr});if(t.blend!==`add`&&t.blend!==`normal`)throw new L(`BAD_FORMAT`,`Particles2D '${e.name}' blend must be 'add' or 'normal', got '${t.blend}'.`,{prop:`blend`,validOptions:[`add`,`normal`]})}sim=null;bursted=!1;finishedEmitted=!1;_ensureSim(){if(!this.sim){Tr(this,this.preset,ct(e.typeName));let t=this.tree?.engine?.rng??new Ee(4660);this.sim=new Dr({rate:this.emitting?this.rate:0,lifetime:[this.lifetime[0]??1,this.lifetime[1]??1],speed:[this.speed[0]??0,this.speed[1]??0],directionDeg:this.directionDeg,spreadDeg:this.spreadDeg,gravity:[this.gravity[0]??0,this.gravity[1]??0,0],drag:this.drag,maxParticles:this.maxParticles},t)}return this.sim}get aliveCount(){return this.sim?.count??0}particles(){let e=[];return this.sim?.forEach(t=>{e.push({...t})}),e}lastWorld=null;wasEmitting=!1;update(e){let t=this._ensureSim();this.holdWorldSpace(t),t.setRate(this.emitting?this.rate:0),this.burst>0&&!this.bursted&&(this.emitting||this.armedByReplay)&&(this.bursted=!0,this.armedByReplay=!1,t.burst(this.burst),this.report(`burst`,this.burst));let n=this.emitting&&this.rate>0;n!==this.wasEmitting&&(this.wasEmitting=n,n&&this.report(`emit`,this.rate)),t.update(e),(!this.emitting||this.rate===0)&&this.bursted&&t.done&&!this.finishedEmitted&&(this.finishedEmitted=!0,this.emit(`finished`))}holdWorldSpace(e){if(!this.worldSpace){this.lastWorld=null;return}let t=0,n=0;for(let e=this;e;e=e.parent)e instanceof Eb&&(t+=e.position[0]??0,n+=e.position[1]??0);let r=this.lastWorld;r&&e.translateAll(r[0]-t,r[1]-n,r[2]-0),this.lastWorld=[t,n,0]}meshKey=``;free(){this.mesh&&=(this.mesh.removeFromParent(),dx(this.mesh),null),super.free()}report(e,t){let n=this.tree?.engine;n?.effects.record({kind:e,name:this.preset,from:this.getPath(),amount:t,at:n.time})}replay(){this.bursted=!1,this.finishedEmitted=!1,this.armedByReplay=!0}armedByReplay=!1;mesh=null;paletteCache=[];paletteCacheKey=``;refreshPalette(){let e=this.paletteColors;if(e.length===0)return null;let t=e.join(`|`);if(t!==this.paletteCacheKey){this.paletteCacheKey=t;for(let t=0;t<e.length;t++){let n=this.paletteCache[t];n||(n=new q,this.paletteCache[t]=n),n.set(e[t])}this.paletteCache.length=e.length}return this.paletteCache}_syncObject2D(e){super._syncObject2D(e);let t=this._ensureSim(),n=`${this.maxParticles}|${this.blend}`;if(!this.mesh||this.meshKey!==n){this.mesh&&(this.mesh.removeFromParent(),dx(this.mesh)),this.meshKey=n;let e=new Kl({transparent:!0,depthWrite:!1,blending:this.blend===`add`?2:1});this.mesh=new Au(lx,e,this.maxParticles),this.mesh.instanceMatrix.setUsage(Wo),this.mesh.frustumCulled=!1,this._ensureObject2D().add(this.mesh)}let r=this.mesh,i=this.refreshPalette(),a=i?null:px.set(this.colorStart),o=mx.set(this.colorEnd),s=this.shimmer,c=0;t.forEach(e=>{let t=this.sizeStart+(this.sizeEnd-this.sizeStart)*e.t;fx.makeScale(t,t,1),fx.setPosition(e.x,-e.y,0),r.setMatrixAt(c,fx);let n=i?i[Math.floor(e.seed*i.length)]:a,l=Math.max(0,this.alphaStart+(this.alphaEnd-this.alphaStart)*e.t);s>0&&(l*=.5+.5*Math.sin(2*Math.PI*(e.age*s+e.seed))),hx.copy(n).lerp(o,e.t).multiplyScalar(l),r.setColorAt(c,hx),c+=1}),r.count=c,r.instanceMatrix.needsUpdate=!0,r.instanceColor&&(r.instanceColor.needsUpdate=!0),r.renderOrder=this.effectiveRenderOrder}};function dx(e){e.dispose();let t=e.material;for(let e of Array.isArray(t)?t:[t])e.dispose()}var fx=new K,px=new q,mx=new q,hx=new q;function gx(e,t){let n=[],r=0;for(let i of e){let e=[];if(typeof i==`string`)for(let n of i){let r=t[n];if(r!==void 0)e.push(r);else if(n===`.`||n===` `)e.push(-1);else if(n>=`0`&&n<=`9`)e.push(n.charCodeAt(0)-48);else throw new L(`BAD_FORMAT`,`TileMap2D: unknown tile char '${n}' — add it to "legend" (char → tile index), or use '.'/' ' for empty and digits 0-9.`)}else for(let t of i)e.push(t);r=Math.max(r,e.length),n.push(e)}for(let e of n)for(;e.length<r;)e.push(-1);return n}function _x(e,t){let n=e.length,r=n>0?e[0].length:0,i=e.map(e=>e.map(()=>!1)),a=(n,r)=>t.has(e[r][n]),o=[];for(let e=0;e<n;e++)for(let t=0;t<r;t++){if(!a(t,e)||i[e][t])continue;let s=1;for(;t+s<r&&a(t+s,e)&&!i[e][t+s];)s++;let c=1;grow:for(;e+c<n;){for(let n=0;n<s;n++)if(!a(t+n,e+c)||i[e+c][t+n])break grow;c++}for(let n=0;n<c;n++)for(let r=0;r<s;r++)i[e+n][t+r]=!0;o.push({x:t,y:e,w:s,h:c})}return o}var vx=class extends Eb{static typeName=`TileMap2D`;static props={texture:{default:``,asset:{kind:`texture`,refOnly:!0}},tileSize:{default:32},columns:{default:0},cells:{default:[]},legend:{default:{}},solid:{default:[]},opacity:{default:1}};texture=``;tileSize=32;columns=0;_cells=[];_legend={};_solid=[];geometryDirty=!0;gridChecked=``;collidersDirty=!0;get cells(){return this._cells}set cells(e){this._cells=e,this.geometryDirty=!0,this.collidersDirty=!0}get legend(){return this._legend}set legend(e){this._legend=e,this.geometryDirty=!0,this.collidersDirty=!0}get solid(){return this._solid}set solid(e){this._solid=e,this.collidersDirty=!0}opacity=1;tileMesh=null;builtColumns=0;builtRows=0;static validateJson(e){let t=e;gx(t._cells,t._legend)}grid(){return gx(this._cells,this._legend)}onReady(){this.rebuildColliders()}update(e){this.collidersDirty&&this.rebuildColliders()}rebuildColliders(){this.collidersDirty=!1;for(let e of[...this.children])e.name.startsWith(`__tileSolid`)&&e.free();if(this._solid.length===0)return;let e=this.tileSize;_x(this.grid(),new Set(this._solid)).forEach((t,n)=>{let r=new Ob(`__tileSolid${n}`);r.position=[(t.x+t.w/2)*e,(t.y+t.h/2)*e],r.collider={shape:`rect`,size:[t.w*e,t.h*e]},this.addChild(r)})}_mesh(){return this.tileMesh||(this.tileMesh=new iu(new Y,new Kl({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.tileMesh)),this.tileMesh}_staticReady(e){return this.texture===``||!e?this.texture===``:!!e.getTexture(this.texture).image?.width}_syncObject2D(e){super._syncObject2D(e);let t=this._mesh(),n=t.material;if(!this.texture||!e){t.visible=!1;return}let r=e.getTexture(this.texture),i=r.image;if(!i?.width||!i.height){t.visible=!1;return}if(t.visible=this.opacity>0,t.renderOrder=this.effectiveRenderOrder,n.opacity=this.opacity,n.map!==r&&(r.magFilter=fa,n.map=r,n.needsUpdate=!0,this.geometryDirty=!0),this.gridChecked!==this.texture){this.gridChecked=this.texture;let e=Qb(this.texture,this.tileSize,this.tileSize,i.width,i.height);e&&Nt(this.tree?.engine??null,`error`,e)}let a=this.columns>0?this.columns:Math.max(1,Math.floor(i.width/this.tileSize)),o=Math.max(1,Math.floor(i.height/this.tileSize));(a!==this.builtColumns||o!==this.builtRows)&&(this.geometryDirty=!0),this.geometryDirty&&(this.geometryDirty=!1,this.builtColumns=a,this.builtRows=o,this.buildGeometry(t.geometry,a,o))}buildGeometry(e,t,n){let r=this.grid(),i=this.tileSize,a=[],o=[],s=[];for(let e=0;e<r.length;e++){let c=r[e];for(let r=0;r<c.length;r++){let l=c[r];if(l<0)continue;let u=r*i,d=u+i,f=-(e*i),p=-((e+1)*i),m=a.length/3;a.push(u,f,0,d,f,0,d,p,0,u,p,0);let h=l%t,g=Math.floor(l/t),_=h/t,v=(h+1)/t,y=1-g/n,b=1-(g+1)/n;o.push(_,y,v,y,v,b,_,b),s.push(m,m+2,m+1,m,m+3,m+2)}}e.setAttribute(`position`,new J(new Float32Array(a),3)),e.setAttribute(`uv`,new J(new Float32Array(o),2)),e.setIndex(s),e.computeBoundingSphere()}get renderedTileCount(){let e=this.tileMesh?.geometry.getAttribute(`position`);return e?e.count/4:0}free(){this.tileMesh?.geometry.dispose(),super.free()}},yx=[`top-left`,`top`,`top-right`,`left`,`center`,`right`,`bottom-left`,`bottom`,`bottom-right`],bx=class extends Ft{static typeName=`UILayer`;static props={anchor:{default:`top-left`,options:yx}};anchor=`top-left`;group=null;_ensureGroup(){return this.group||(this.group=new Ec,this.group.userData.incantoNode=this),this.group}static validateJson(e){let t=e.anchor;if(!yx.includes(t))throw new L(`BAD_FORMAT`,`UILayer '${e.name}' anchor must be one of [${yx.join(`, `)}], got '${t}'.`,{prop:`anchor`,validOptions:yx})}_anchorOrigin(e,t){let n=this.anchor;return{x:n.includes(`right`)?e:n===`top`||n===`center`||n===`bottom`?e/2:0,y:n.includes(`bottom`)?t:n===`left`||n===`center`||n===`right`?t/2:0}}};function xx(){Or(),z(Eb),z(ex),z(ox),z(ux),z(tx),z(nx),z(cx),z(bx),z(Ob),z(Ab),z(kb),z(jb),z(ix),z(Lb),z(vx)}function Sx(e,t,n){return{x:(t-e.cx)*e.zoom+e.w/2,y:(n-e.cy)*e.zoom+e.h/2}}function Cx(e,t,n){return{x:(t-e.w/2)/e.zoom+e.cx,y:(n-e.h/2)/e.zoom+e.cy}}function wx(e,t,n){return{x:e.offsetX+t/e.uiW*e.contentW,y:e.offsetY+n/e.uiH*e.contentH}}function Tx(e,t,n){return{x:(t-e.offsetX)/e.contentW*e.uiW,y:(n-e.offsetY)/e.contentH*e.uiH}}var Ex=new Xc,Dx=new W,Ox=12,kx=new Float32Array(16);function Ax(e){if(!(e instanceof Eb))return null;let t=e._ensureObject2D();t.updateWorldMatrix(!0,!0),Ex.setFromObject(t),Ex.getSize(Dx);let n,r,i,a;if(!Number.isFinite(Dx.x)||Dx.x===0&&Dx.y===0){let e=new W().setFromMatrixPosition(t.matrixWorld);n=e.x-Ox,i=e.x+Ox,r=e.y-Ox,a=e.y+Ox}else n=Ex.min.x-2,i=Ex.max.x+2,r=Ex.min.y-2,a=Ex.max.y+2;let o=[n,r,i,r,i,r,i,a,i,a,n,a,n,a,n,r];return kx.set(o),kx}function jx(){return{visited:new Set,cameras:[],emitters:[]}}function Mx(e){return e.spatial===!0&&typeof e._setSpatialPose==`function`}function Nx(e,t,n,r,i,a,o){let s=a??jx();s.visited.clear(),s.cameras.length=0,s.emitters.length=0,Rx(e,t,n,!1,s.visited,s.cameras,s.emitters,r,i,o?.ignoreStatic===!0),zx(t,s.visited),zx(n,s.visited);let c=null;for(let e=0;e<s.cameras.length;e++){let t=s.cameras[e];if(t.current){c=t;break}}return c||=s.cameras[0]??null,Lx(s.emitters,c),{activeCamera:c}}var Px=new W,Fx=new W,Ix=new W;function Lx(e,t){if(e.length===0||!t)return;let n=t._ensureObject2D();n.updateWorldMatrix(!0,!1),n.getWorldPosition(Fx),Ix.set(0,1,0).applyQuaternion(n.quaternion);let r={position:[Fx.x,Fx.y,0],forward:[0,0,-1],up:[Ix.x,Ix.y,Ix.z]};for(let{node:t,parent:n}of e)n.updateWorldMatrix(!0,!1),n.getWorldPosition(Px),t._setSpatialPose({position:[Px.x,Px.y,0],listener:r})}function Rx(e,t,n,r,i,a,o,s,c,l){let u=t,d=r;if(e instanceof Eb&&!(e instanceof bx)){let t=e._ensureObject2D();if(e.static&&!l&&t.userData.incantoStaticSynced===!0){t.userData.incantoStatic=!0,i.add(t);return}}if(e instanceof bx){let t=e._ensureGroup();t.parent!==n&&n.add(t);let r=c?e._anchorOrigin(c.width,c.height):{x:0,y:0};t.position.set(r.x,-r.y,0),i.add(t),d=!0,u=t}else if(e instanceof Eb){let n=e._ensureObject2D();n.parent!==t&&t.add(n),e._syncObject2D(s),i.add(n),e instanceof nx&&!r&&a.push(e),u=n}else Mx(e)&&o.push({node:e,parent:u});for(let t of e.children)Rx(t,u,n,d,i,a,o,s,c,l);if(e instanceof Eb&&!(e instanceof bx)){let t=e._ensureObject2D();e.static&&!l&&e._staticReady(s)?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}function zx(e,t){let n=e.children;for(let r=n.length-1;r>=0;r--){let i=n[r];i.userData.incantoNode&&!t.has(i)?e.remove(i):i.userData.incantoStatic!==!0&&zx(i,t)}}var Bx=120,Vx=class{viewOverride=null;webgl;captureFrame(){return new Promise((e,t)=>{this.pendingCaptures.push({resolve:e,reject:t}),setTimeout(()=>{if(this.pendingCaptures.length>0)try{this.render()}catch(e){let t=e instanceof Error?e:Error(String(e));for(let e of this.pendingCaptures.splice(0))e.reject(t)}},Bx)})}pendingCaptures=[];drainFrameCapture(){if(this.pendingCaptures.length===0)return;let e=this.pendingCaptures;this.pendingCaptures=[];try{let t=this.webgl.getContext(),n=this.webgl.domElement.width,r=this.webgl.domElement.height,i=new Uint8Array(n*r*4);this.webgl.setRenderTarget(null),t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,i);for(let e=0;e<Math.floor(r/2);e++){let t=e*n*4,a=(r-1-e)*n*4;for(let e=0;e<n*4;e++){let n=i[t+e];i[t+e]=i[a+e],i[a+e]=n}}for(let t of e)t.resolve({pixels:i,width:n,height:r})}catch(t){let n=t instanceof Error?t:Error(String(t));for(let t of e)t.reject(n)}}basePixelRatio=1;setRenderScale(e){let t=Number.isFinite(e)&&e>0?Math.min(2,Math.max(.25,e)):1;this.webgl.setPixelRatio(this.basePixelRatio*t)}worldScene=new Fc;syncScratch=jx();ignoreStatic=!1;uiScene=new Fc;worldCam=new Of(-1,1,1,-1,-1e3,1e3);uiCam=new Of(-1,1,1,-1,-1e3,1e3);engine;assets;loadedAssetScenes=new WeakSet;disconnect;canvas;constructor(e){this.canvas=e.canvas,this.engine=e.engine,this.assets=e.assets??new Tg(void 0,this.engine);let t=kr(e.engine.scene?.environment,{antialias:!0,pixelRatio:1,preserveDrawingBuffer:!1},globalThis.devicePixelRatio??1,e);this.webgl=new wg({canvas:e.canvas,antialias:t.antialias,preserveDrawingBuffer:t.preserveDrawingBuffer}),this.webgl.info.autoReset=!1,this.engine.picker=(e,t)=>this.pick(e,t),this.basePixelRatio=t.pixelRatio,this.webgl.setPixelRatio(t.pixelRatio),this.webgl.info.autoReset=!1,this.debugLines=new Zu(new Y,new zu({color:`#00ff6e`,transparent:!0,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.worldScene.add(this.debugLines),this.selectionLines=new Zu(new Y,new zu({color:`#ffb020`,transparent:!0,depthTest:!1})),this.selectionLines.frustumCulled=!1,this.selectionLines.renderOrder=1e4,this.selectionLines.visible=!1,this.worldScene.add(this.selectionLines),this.disconnect=this.engine.updated.connect(()=>{let e=performance.now();this.render(),this.engine.noteRenderMs(performance.now()-e)})}debugLines;selectionLines;syncSelectionOutline(){let e=this.engine.debugSelection;e&&e.tree!==this.engine.scene?.tree&&(this.engine.debugSelection=null);let t=this.engine.debugSelection,n=t?Ax(t):null;if(this.selectionLines.visible=n!==null,!n)return;let r=new Float32Array(n.length/2*3);for(let e=0,t=0;e<n.length;e+=2,t+=3)r[t]=n[e],r[t+1]=n[e+1],r[t+2]=0;this.selectionLines.geometry.setAttribute(`position`,new J(r,3)),this.selectionLines.geometry.getAttribute(`position`).needsUpdate=!0}syncDebugLines(){let e=null;for(let t of Pb(`2d`,this.engine))if(e=t.debugLines(),e)break;if(this.debugLines.visible=e!==null,!e)return;let t=new Float32Array(e.length/2*3);for(let n=0,r=0;n<e.length;n+=2,r+=3)t[r]=e[n],t[r+1]=e[n+1],t[r+2]=0;this.debugLines.geometry.setAttribute(`position`,new J(t,3))}render(){let e=this.engine.scene;if(!e)return;this.webgl.info.reset(),this.syncDebugLines(),this.syncSelectionOutline(),e.assets&&!this.loadedAssetScenes.has(e)&&(this.assets.load(e.assets),this.loadedAssetScenes.add(e));let t=e.environment?.background;this.worldScene.background=typeof t==`string`?new q(t):null;let n=this.canvas.clientWidth||this.canvas.width,r=this.canvas.clientHeight||this.canvas.height,i=this.webgl.getSize(Ux);(i.x!==n||i.y!==r)&&this.webgl.setSize(n,r,!1);let a=this.viewOverride?null:Ir(e.viewport),o=a?Lr(n,r,a):null,s=o?o.viewW:n,c=o?o.viewH:r;this.lastUi={w:s,h:c};let{activeCamera:l}=Nx(e.root,this.worldScene,this.uiScene,this.assets,{width:s,height:c},this.syncScratch,{ignoreStatic:this.ignoreStatic}),u=a?{x:a.design[0]/2,y:a.design[1]/2}:{x:n/2,y:r/2},d=1;this.viewOverride?(u={x:this.viewOverride.cx,y:this.viewOverride.cy},d=this.viewOverride.zoom):l&&(u=l.clampedCenter(s,c),d=l.effectiveZoom);let f=o?.scale??1;this.lastView={cx:u.x,cy:u.y,zoom:d*f,w:n,h:r},this.lastViewport=o,o&&(o.offsetX>.5||o.offsetY>.5)?(this.webgl.setScissorTest(!1),this.webgl.setViewport(0,0,n,r),this.webgl.clear(),this.webgl.setViewport(o.offsetX,o.offsetY,o.contentW,o.contentH),this.webgl.setScissor(o.offsetX,o.offsetY,o.contentW,o.contentH),this.webgl.setScissorTest(!0)):(this.webgl.setScissorTest(!1),this.webgl.setViewport(0,0,n,r)),Hx(this.worldCam,u.x,u.y,s/d,c/d),Hx(this.uiCam,s/2,c/2,s,c),this.webgl.info.reset(),this.webgl.autoClear=!0,this.webgl.render(this.worldScene,this.worldCam),this.webgl.autoClear=!1,this.webgl.render(this.uiScene,this.uiCam),this.webgl.autoClear=!0,this.drainFrameCapture()}lastUi={w:1,h:1};lastViewport=null;lastView={cx:0,cy:0,zoom:1,w:1,h:1};view(){return{...this.lastView}}stats(){let e=this.webgl.info;return{triangles:e.render.triangles,drawCalls:e.render.calls,geometries:e.memory.geometries,textures:e.memory.textures}}worldFromScreen(e,t){return Cx(this.lastView,e,t)}screenFromWorld(e,t){return Sx(this.lastView,e,t)}pick(e,t){let{w:n,h:r}=this.lastView,i=this.lastViewport?.offsetX??0,a=this.lastViewport?.offsetY??0,o=this.lastViewport?.contentW??n,s=this.lastViewport?.contentH??r;return Gx.set((e-i)/o*2-1,-((t-a)/s*2-1)),this.hit(this.uiScene,this.uiCam)||this.hit(this.worldScene,this.worldCam)}hit(e,t){Kx.setFromCamera(Gx,t);let n=Kx.intersectObjects(e.children,!0),r=null;for(let e of n){let t=e.object;for(;t&&!t.userData.incantoNode;)t=t.parent;let n=t?.userData.incantoNode;if(!n)continue;let i=e.object.renderOrder??0;(!r||i>=r.order)&&(r={node:n,order:i})}return r?.node??null}isUiNode(e){let t=e._object2D??e._group??null;for(;t;){if(t===this.uiScene)return!0;t=t.parent}return!1}screenFromUi(e,t){return wx(this.uiView(),e,t)}uiFromScreen(e,t){return Tx(this.uiView(),e,t)}uiView(){return{offsetX:this.lastViewport?.offsetX??0,offsetY:this.lastViewport?.offsetY??0,contentW:this.lastViewport?.contentW??this.lastView.w,contentH:this.lastViewport?.contentH??this.lastView.h,uiW:this.lastUi.w,uiH:this.lastUi.h}}boundsOf(e){let t=e._object2D;if(!t||(qx.makeEmpty(),qx.expandByObject(t),qx.isEmpty())||(qx.getSize(Wx),Wx.x===0&&Wx.y===0))return null;let n=this.isUiNode(e)?(e,t)=>this.screenFromUi(e,t):(e,t)=>this.screenFromWorld(e,t),r=n(qx.min.x,-qx.max.y),i=n(qx.max.x,-qx.min.y);return{x:r.x,y:r.y,w:i.x-r.x,h:i.y-r.y}}dispose(){this.engine.picker&&(this.engine.picker=null),this.disconnect();for(let e of[this.worldScene,this.uiScene])e.traverse(e=>{let t=e;if(!t.isMesh)return;let n=Array.isArray(t.material)?t.material:[t.material];for(let e of n)e?.map?.dispose(),e?.dispose()});this.webgl.dispose()}};function Hx(e,t,n,r,i){e.position.set(t,-n,10),e.left=-r/2,e.right=r/2,e.top=i/2,e.bottom=-i/2,e.updateProjectionMatrix()}var Ux=new H,Wx=new W,Gx=new H,Kx=new rp,qx=new Xc;async function Jx(e){xx(),(e.gameplay??!0)&&wb();for(let[t,n]of Object.entries(e.behaviors??{}))St(t,n,{replace:!0});let t=new Hn({seed:e.seed,fixedHz:e.fixedHz,...e._scheduler?{scheduler:e._scheduler}:{}}),n=Yx(e.scene),r=Ai(Yx(n),{resolveScene:e.resolveScene,engine:t});t.setScene(r);let i=null;(e.physics===!0||(e.physics??`auto`)===`auto`&&Xx(r.root))&&(i=await Bb(t));let a=[],o=e.keyboard??(typeof window<`u`?window:!1);if(o&&t.input.attachKeyboard(o),e.pointer){let n=typeof e.pointer==`object`?e.pointer.lockOnClick??!1:!1;t.input.attachPointer(e.canvas,{lockOnClick:n})}a.push(Zx(t,r.root,e.canvas)),a.push(t.settings.bindAudio(t.audio)),a.push($g(t)),a.push(t.settings.bindLocale(t.locale)),e.pageGestures||Dg(e.canvas);let s=e.touch??`auto`;if(s!==!1){let n=e.touchContainer??e.canvas.parentElement??null;if(n){let r={force:s===!0,...e._touchDoc?{doc:e._touchDoc}:{}},i=na(t,n,r),o=t.sceneChanged.connect(()=>{i?.dispose(),i=na(t,n,r)});a.push(()=>{o(),i?.dispose()})}}let c=e._rendererFactory?e._rendererFactory(t,e.canvas):new Vx({canvas:e.canvas,engine:t,...e.pixelRatio===void 0?{}:{pixelRatio:e.pixelRatio},...e.antialias===void 0?{}:{antialias:e.antialias}});a.push(t.settings.bindFrameCap(e=>{t.maxFps=e})),a.push(t.settings.bindRenderScale(e=>{c.setRenderScale?.(e)})),a.push(...Ig({engine:t,applyDrive:async e=>{let n=0,r=!0,i=()=>{r&&(n+=1,requestAnimationFrame(i))};typeof requestAnimationFrame==`function`&&requestAnimationFrame(i);for(let n of e)switch(n.kind){case`press`:t.input.pressAction(n.action);break;case`release`:t.input.releaseAction(n.action);break;case`vector`:t.input.setActionVector(n.action,n.x,n.y);break;case`key`:t.input.handleKey(n.code,n.down);break;case`pointer`:t.input.handlePointerMove(n.dx,n.dy);break;case`step`:await new Promise(e=>setTimeout(e,n.ms));break}return r=!1,n},captureFramePixels:()=>{let e=c.captureFrame;return e?e.call(c):Promise.reject(new L(`TREE_VIOLATION`,`this renderer cannot capture frames`))},rendererStats:()=>c.stats?.(),assetErrors:()=>[...c.assets?.errors()??[],...Eg(t.scene?.tree.root)]}));let l=e.debug??!1,u=e.editor??l,d=u===!0?{}:u||null,f={label:`✎ edit this scene`,run:async()=>{if(!d)return;let t=d.open??Xg,r=async t=>{await Jx({...e,scene:t})};await Zg(async()=>{p();try{await t({scene:n,play:r,exit:()=>r(n),...d.save?{save:d.save}:{},...d.library?{library:d.library===!0?Wg():d.library}:{}})}catch(e){console.error(`[incanto] could not open the editor:`,e),await r(n)}},`opening the editor…`)}};if(l){let n=e.touchContainer??e.canvas.parentElement??(typeof document<`u`?document.body:null);if(n){let{attachDebugOverlay:r}=await Bg(async()=>{let{attachDebugOverlay:e}=await import(`./debug-eaSKFAKW.js`);return{attachDebugOverlay:e}},[],import.meta.url),i=r(t,{container:n,statsSource:()=>c.stats?.()??{},...d?{actions:[f]}:{},...e._debugDoc?{doc:e._debugDoc}:{}});i&&a.push(()=>i.dispose())}}t.start();function p(){e_([i?[`physics`,()=>i?.dispose()]:null,[`app cleanups`,()=>{for(let e of a)e()}],[`engine`,()=>t.dispose()],[`renderer`,()=>c.dispose()]])}return{engine:t,scene:r,sourceJson:n,renderer:c,physics:i,pick(e,n){return t.picker?.(e,n)??null},async frame(e){let t=c.captureFrame;if(!t)throw new L(`TREE_VIOLATION`,`this renderer cannot capture frames`);let n=await t.call(c);return Fg(n.pixels,n.width,n.height,e)},assetErrors(){return[...c.assets?.errors()??[],...Eg(t.scene?.tree.root)]},stats(){return{triangles:0,drawCalls:0,geometries:0,textures:0,...t.stats(),...c.stats?.()}},openEditor:d?f.run:null,dispose:p}}function Yx(e){try{return structuredClone(e)}catch{throw new L(`BAD_FORMAT`,`createGame "scene" must be plain scene JSON (the imported *.scene.json object) — got something unclonable (a loaded Scene, class instances, or functions).`)}}function Xx(e){if(e instanceof Db)return!0;for(let t of e.children)if(Xx(t))return!0;return!1}function Zx(e,t,n){let r=[],i=n;if(i.addEventListener&&r.push({target:i,type:`pointerdown`}),typeof window<`u`){let e=window;r.push({target:e,type:`keydown`}),r.push({target:e,type:`pointerdown`})}if(r.length===0)return()=>{};function a(){for(let e of r)e.target.removeEventListener?.(e.type,o)}function o(){e.sfx.unlock(),e.music.unlock();let n=!1,r=e=>{e instanceof Kn&&(e.retryPending(),e.pendingGesture&&(n=!0));for(let t of e.children)r(t)};r(t),n||a()}for(let e of r)e.target.addEventListener?.(e.type,o,{passive:!0});return a}var Qx=[[`run`,[`run`,`move`,`walk`]],[`jump`,[`jump`,`idle`]],[`fall`,[`fall`,`jump`,`idle`]],[`wallSlide`,[`wallSlide`,`idle`]],[`dash`,[`dash`,`run`,`move`,`idle`]]];function $x(e){let t=new Set(Object.keys(e));if(t.has(`idle`))for(let[n,r]of Qx){if(t.has(n))continue;let i=r.find(e=>e!==n&&t.has(e));i&&(e[n]=i)}}function eS(e,t){let n=e;if(typeof n?.frame?.width!=`number`||typeof n.frame.height!=`number`||!n.animations||Object.keys(n.animations).length===0)throw new L(`BAD_FORMAT`,`Library sprite metadata needs {frame: {width, height}, animations: {<name>: {start, end, frameRate, repeat}}} — got ${JSON.stringify(e).slice(0,120)}.`);let r={},i=null,a=null;for(let[e,t]of Object.entries(n.animations)){if(typeof t.start!=`number`||typeof t.end!=`number`||typeof t.frameRate!=`number`)throw new L(`BAD_FORMAT`,`Library animation '${e}' needs numeric start/end/frameRate, got ${JSON.stringify(t)}.`);let n=t.repeat===-1;r[e]={frames:[t.start,t.end],fps:t.frameRate,loop:n},i??=e,n&&a===null&&(a=e)}$x(r);let o=t.autoplay??a??i;return{asset:{type:`spritesheet`,url:t.url,frameWidth:n.frame.width,frameHeight:n.frame.height},props:{sheet:`$${t.assetKey}`,autoplay:o,animations:r}}}var tS=e({createGame2D:()=>Jx,enablePhysics2D:()=>Bb}),nS=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),rS=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),iS=class extends Tc{constructor(e){super(),this.weight=0,this.isBinary=!1,this.overrideBlink=`none`,this.overrideLookAt=`none`,this.overrideMouth=`none`,this._binds=[],this.name=`VRMExpression_${e}`,this.expressionName=e,this.type=`VRMExpression`,this.visible=!1}get binds(){return this._binds}get overrideBlinkAmount(){return this.overrideBlink===`block`?+(0<this.outputWeight):this.overrideBlink===`blend`?this.outputWeight:0}get overrideLookAtAmount(){return this.overrideLookAt===`block`?+(0<this.outputWeight):this.overrideLookAt===`blend`?this.outputWeight:0}get overrideMouthAmount(){return this.overrideMouth===`block`?+(0<this.outputWeight):this.overrideMouth===`blend`?this.outputWeight:0}get outputWeight(){return this.isBinary?+(this.weight>.5):this.weight}addBind(e){this._binds.push(e)}deleteBind(e){let t=this._binds.indexOf(e);t>=0&&this._binds.splice(t,1)}applyWeight(e){let t=this.outputWeight;t*=e?.multiplier??1,this.isBinary&&t<1&&(t=0),this._binds.forEach(e=>e.applyWeight(t))}clearAppliedWeight(){this._binds.forEach(e=>e.clearAppliedWeight())}};function aS(e,t,n){let r=e.parser.json,i=r.nodes?.[t];if(i==null)return console.warn(`extractPrimitivesInternal: Attempt to use nodes[${t}] of glTF but the node doesn't exist`),null;let a=i.mesh;if(a==null)return null;let o=r.meshes?.[a];if(o==null)return console.warn(`extractPrimitivesInternal: Attempt to use meshes[${a}] of glTF but the mesh doesn't exist`),null;let s=o.primitives.length,c=[];return n.traverse(e=>{c.length<s&&e.isMesh&&c.push(e)}),c}function oS(e,t){return rS(this,null,function*(){return aS(e,t,yield e.parser.getDependency(`node`,t))})}function sS(e){return rS(this,null,function*(){let t=yield e.parser.getDependencies(`node`),n=new Map;return t.forEach((t,r)=>{let i=aS(e,r,t);i!=null&&n.set(r,i)}),n})}var cS={Aa:`aa`,Ih:`ih`,Ou:`ou`,Ee:`ee`,Oh:`oh`,Blink:`blink`,Happy:`happy`,Angry:`angry`,Sad:`sad`,Relaxed:`relaxed`,LookUp:`lookUp`,Surprised:`surprised`,LookDown:`lookDown`,LookLeft:`lookLeft`,LookRight:`lookRight`,BlinkLeft:`blinkLeft`,BlinkRight:`blinkRight`,Neutral:`neutral`};function lS(e){return Math.max(Math.min(e,1),0)}var uS=class e{constructor(){this.blinkExpressionNames=[`blink`,`blinkLeft`,`blinkRight`],this.lookAtExpressionNames=[`lookLeft`,`lookRight`,`lookUp`,`lookDown`],this.mouthExpressionNames=[`aa`,`ee`,`ih`,`oh`,`ou`],this._expressions=[],this._expressionMap={}}get expressions(){return this._expressions.concat()}get expressionMap(){return Object.assign({},this._expressionMap)}get presetExpressionMap(){let e={},t=new Set(Object.values(cS));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)&&(e[n]=r)}),e}get customExpressionMap(){let e={},t=new Set(Object.values(cS));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)||(e[n]=r)}),e}copy(e){return this._expressions.concat().forEach(e=>{this.unregisterExpression(e)}),e._expressions.forEach(e=>{this.registerExpression(e)}),this.blinkExpressionNames=e.blinkExpressionNames.concat(),this.lookAtExpressionNames=e.lookAtExpressionNames.concat(),this.mouthExpressionNames=e.mouthExpressionNames.concat(),this}clone(){return new e().copy(this)}getExpression(e){return this._expressionMap[e]??null}registerExpression(e){this._expressions.push(e),this._expressionMap[e.expressionName]=e}unregisterExpression(e){let t=this._expressions.indexOf(e);t===-1&&console.warn(`VRMExpressionManager: The specified expressions is not registered`),this._expressions.splice(t,1),delete this._expressionMap[e.expressionName]}getValue(e){return this.getExpression(e)?.weight??null}setValue(e,t){let n=this.getExpression(e);n&&(n.weight=lS(t))}resetValues(){this._expressions.forEach(e=>{e.weight=0})}getExpressionTrackName(e){let t=this.getExpression(e);return t?`${t.name}.weight`:null}update(){let e=this._calculateWeightMultipliers();this._expressions.forEach(e=>{e.clearAppliedWeight()}),this._expressions.forEach(t=>{let n=1,r=t.expressionName;this.blinkExpressionNames.indexOf(r)!==-1&&(n*=e.blink),this.lookAtExpressionNames.indexOf(r)!==-1&&(n*=e.lookAt),this.mouthExpressionNames.indexOf(r)!==-1&&(n*=e.mouth),t.applyWeight({multiplier:n})})}_calculateWeightMultipliers(){let e=1,t=1,n=1;return this._expressions.forEach(r=>{e-=r.overrideBlinkAmount,t-=r.overrideLookAtAmount,n-=r.overrideMouthAmount}),e=Math.max(0,e),t=Math.max(0,t),n=Math.max(0,n),{blink:e,lookAt:t,mouth:n}}},dS={Color:`color`,EmissionColor:`emissionColor`,ShadeColor:`shadeColor`,MatcapColor:`matcapColor`,RimColor:`rimColor`,OutlineColor:`outlineColor`},fS={_Color:dS.Color,_EmissionColor:dS.EmissionColor,_ShadeColor:dS.ShadeColor,_RimColor:dS.RimColor,_OutlineColor:dS.OutlineColor},pS=new q,mS=class e{constructor({material:e,type:t,targetValue:n,targetAlpha:r}){this.material=e,this.type=t,this.targetValue=n,this.targetAlpha=r??1;let i=this._initColorBindState(),a=this._initAlphaBindState();this._state={color:i,alpha:a}}applyWeight(e){let{color:t,alpha:n}=this._state;if(t!=null){let{propertyName:n,deltaValue:r}=t;this.material[n]?.add(pS.copy(r).multiplyScalar(e))}if(n!=null){let{propertyName:t,deltaValue:r}=n;this.material[t]!=null&&(this.material[t]+=r*e)}}clearAppliedWeight(){let{color:e,alpha:t}=this._state;if(e!=null){let{propertyName:t,initialValue:n}=e;this.material[t]?.copy(n)}if(t!=null){let{propertyName:e,initialValue:n}=t;this.material[e]!=null&&(this.material[e]=n)}}_initColorBindState(){let{material:e,type:t,targetValue:n}=this,r=this._getPropertyNameMap()?.[t]?.[0]??null;if(r==null)return console.warn(`Tried to add a material color bind to the material ${e.name??`(no name)`}, the type ${t} but the material or the type is not supported.`),null;let i=e[r].clone();return{propertyName:r,initialValue:i,deltaValue:new q(n.r-i.r,n.g-i.g,n.b-i.b)}}_initAlphaBindState(){let{material:e,type:t,targetAlpha:n}=this,r=this._getPropertyNameMap()?.[t]?.[1]??null;if(r==null&&n!==1)return console.warn(`Tried to add a material alpha bind to the material ${e.name??`(no name)`}, the type ${t} but the material or the type does not support alpha.`),null;if(r==null)return null;let i=e[r];return{propertyName:r,initialValue:i,deltaValue:n-i}}_getPropertyNameMap(){return Object.entries(e._propertyNameMapMap).find(([e])=>this.material[e]===!0)?.[1]??null}};mS._propertyNameMapMap={isMeshStandardMaterial:{color:[`color`,`opacity`],emissionColor:[`emissive`,null]},isMeshBasicMaterial:{color:[`color`,`opacity`]},isMToonMaterial:{color:[`color`,`opacity`],emissionColor:[`emissive`,null],outlineColor:[`outlineColorFactor`,null],matcapColor:[`matcapFactor`,null],rimColor:[`parametricRimColorFactor`,null],shadeColor:[`shadeColorFactor`,null]}};var hS=mS,gS=class{constructor({primitives:e,index:t,weight:n}){this.primitives=e,this.index=t,this.weight=n}applyWeight(e){this.primitives.forEach(t=>{t.morphTargetInfluences?.[this.index]!=null&&(t.morphTargetInfluences[this.index]+=this.weight*e)})}clearAppliedWeight(){this.primitives.forEach(e=>{e.morphTargetInfluences?.[this.index]!=null&&(e.morphTargetInfluences[this.index]=0)})}},_S=new H,vS=class e{constructor({material:t,scale:n,offset:r}){this.material=t,this.scale=n,this.offset=r;let i=Object.entries(e._propertyNamesMap).find(([e])=>t[e]===!0)?.[1];i==null?(console.warn(`Tried to add a texture transform bind to the material ${t.name??`(no name)`} but the material is not supported.`),this._properties=[]):(this._properties=[],i.forEach(e=>{let i=t[e]?.clone();if(!i)return null;t[e]=i;let a=i.offset.clone(),o=i.repeat.clone(),s=r.clone().sub(a),c=n.clone().sub(o);this._properties.push({name:e,initialOffset:a,deltaOffset:s,initialScale:o,deltaScale:c})}))}applyWeight(e){this._properties.forEach(t=>{let n=this.material[t.name];n!==void 0&&(n.offset.add(_S.copy(t.deltaOffset).multiplyScalar(e)),n.repeat.add(_S.copy(t.deltaScale).multiplyScalar(e)))})}clearAppliedWeight(){this._properties.forEach(e=>{let t=this.material[e.name];t!==void 0&&(t.offset.copy(e.initialOffset),t.repeat.copy(e.initialScale))})}};vS._propertyNamesMap={isMeshStandardMaterial:[`map`,`emissiveMap`,`bumpMap`,`normalMap`,`displacementMap`,`roughnessMap`,`metalnessMap`,`alphaMap`],isMeshBasicMaterial:[`map`,`specularMap`,`alphaMap`],isMToonMaterial:[`map`,`normalMap`,`emissiveMap`,`shadeMultiplyTexture`,`rimMultiplyTexture`,`outlineWidthMultiplyTexture`,`uvAnimationMaskTexture`]};var yS=vS,bS=new Set([`1.0`,`1.0-beta`]),xS=class e{get name(){return`VRMExpressionLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return rS(this,null,function*(){e.userData.vrmExpressionManager=yield this._import(e)})}_import(e){return rS(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return rS(this,null,function*(){let t=this.parser.json;if(t.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let n=t.extensions?.VRMC_vrm;if(!n)return null;let r=n.specVersion;if(!bS.has(r))return console.warn(`VRMExpressionLoaderPlugin: Unknown VRMC_vrm specVersion "${r}"`),null;let i=n.expressions;if(!i)return null;let a=new Set(Object.values(cS)),o=new Map;i.preset!=null&&Object.entries(i.preset).forEach(([e,t])=>{if(t!=null){if(!a.has(e)){console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${e}" detected. Ignoring the expression`);return}o.set(e,t)}}),i.custom!=null&&Object.entries(i.custom).forEach(([e,t])=>{if(a.has(e)){console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${e}". Ignoring the expression`);return}o.set(e,t)});let s=new uS;return yield Promise.all(Array.from(o.entries()).map(t=>rS(this,[t],function*([t,n]){var r,i,a;let o=new iS(t);if(e.scene.add(o),o.isBinary=n.isBinary??!1,o.overrideBlink=n.overrideBlink??`none`,o.overrideLookAt=n.overrideLookAt??`none`,o.overrideMouth=n.overrideMouth??`none`,(r=n.morphTargetBinds)==null||r.forEach(t=>rS(this,null,function*(){if(t.node===void 0||t.index===void 0)return;let r=yield oS(e,t.node),i=t.index;if(!r.every(e=>Array.isArray(e.morphTargetInfluences)&&i<e.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${n.name} attempts to index morph #${i} but not found.`);return}o.addBind(new gS({primitives:r,index:i,weight:t.weight??1}))})),n.materialColorBinds||n.textureTransformBinds){let t=[];e.scene.traverse(e=>{let n=e.material;n&&(Array.isArray(n)?t.push(...n):t.push(n))}),(i=n.materialColorBinds)==null||i.forEach(e=>rS(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new hS({material:t,type:e.type,targetValue:new q().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}))})})),(a=n.textureTransformBinds)==null||a.forEach(e=>rS(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new yS({material:t,offset:new H().fromArray(e.offset??[0,0]),scale:new H().fromArray(e.scale??[1,1])}))})}))}s.registerExpression(o)}))),s})}_v0Import(t){return rS(this,null,function*(){let n=this.parser.json,r=n.extensions?.VRM;if(!r)return null;let i=r.blendShapeMaster;if(!i)return null;let a=new uS,o=i.blendShapeGroups;if(!o)return a;let s=new Set;return yield Promise.all(o.map(r=>rS(this,null,function*(){let i=r.presetName,o=(i!=null&&e.v0v1PresetNameMap[i]||null)??r.name;if(o==null){console.warn(`VRMExpressionLoaderPlugin: One of custom expressions has no name. Ignoring the expression`);return}if(s.has(o)){console.warn(`VRMExpressionLoaderPlugin: An expression preset ${i} has duplicated entries. Ignoring the expression`);return}s.add(o);let c=new iS(o);t.scene.add(c),c.isBinary=r.isBinary??!1,r.binds&&r.binds.forEach(e=>rS(this,null,function*(){var i;if(e.mesh===void 0||e.index===void 0)return;let a=[];(i=n.nodes)==null||i.forEach((t,n)=>{t.mesh===e.mesh&&a.push(n)});let o=e.index;yield Promise.all(a.map(n=>rS(this,null,function*(){let i=yield oS(t,n);if(!i.every(e=>Array.isArray(e.morphTargetInfluences)&&o<e.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${r.name} attempts to index ${o}th morph but not found.`);return}c.addBind(new gS({primitives:i,index:o,weight:.01*(e.weight??100)}))})))}));let l=r.materialValues;l&&l.length!==0&&l.forEach(e=>{if(e.materialName===void 0||e.propertyName===void 0||e.targetValue===void 0)return;let n=[];t.scene.traverse(t=>{if(t.material){let r=t.material;Array.isArray(r)?n.push(...r.filter(t=>(t.name===e.materialName||t.name===e.materialName+` (Outline)`)&&n.indexOf(t)===-1)):r.name===e.materialName&&n.indexOf(r)===-1&&n.push(r)}});let r=e.propertyName;n.forEach(t=>{if(r===`_MainTex_ST`){let n=new H(e.targetValue[0],e.targetValue[1]),r=new H(e.targetValue[2],e.targetValue[3]);r.y=1-r.y-n.y,c.addBind(new yS({material:t,scale:n,offset:r}));return}let n=fS[r];if(n){c.addBind(new hS({material:t,type:n,targetValue:new q().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}));return}console.warn(r+` is not supported`)})}),a.registerExpression(c)}))),a})}};xS.v0v1PresetNameMap={a:`aa`,e:`ee`,i:`ih`,o:`oh`,u:`ou`,blink:`blink`,joy:`happy`,angry:`angry`,sorrow:`sad`,fun:`relaxed`,lookup:`lookUp`,lookdown:`lookDown`,lookleft:`lookLeft`,lookright:`lookRight`,blink_l:`blinkLeft`,blink_r:`blinkRight`,neutral:`neutral`};var SS=xS,CS=class e{constructor(t,n){this._firstPersonOnlyLayer=e.DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=e.DEFAULT_THIRDPERSON_ONLY_LAYER,this._initializedLayers=!1,this.humanoid=t,this.meshAnnotations=n}copy(e){if(this.humanoid!==e.humanoid)throw Error(`VRMFirstPerson: humanoid must be same in order to copy`);return this.meshAnnotations=e.meshAnnotations.map(e=>({meshes:e.meshes.concat(),type:e.type})),this}clone(){return new e(this.humanoid,this.meshAnnotations).copy(this)}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}setup({firstPersonOnlyLayer:t=e.DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:n=e.DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initializedLayers||=(this._firstPersonOnlyLayer=t,this._thirdPersonOnlyLayer=n,this.meshAnnotations.forEach(e=>{e.meshes.forEach(t=>{e.type===`firstPersonOnly`?(t.layers.set(this._firstPersonOnlyLayer),t.traverse(e=>e.layers.set(this._firstPersonOnlyLayer))):e.type===`thirdPersonOnly`?(t.layers.set(this._thirdPersonOnlyLayer),t.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer))):e.type===`auto`&&this._createHeadlessModel(t)})}),!0)}_excludeTriangles(e,t,n,r){let i=0;if(t!=null&&t.length>0)for(let a=0;a<e.length;a+=3){let o=e[a],s=e[a+1],c=e[a+2],l=t[o],u=n[o];if(l[0]>0&&r.includes(u[0])||l[1]>0&&r.includes(u[1])||l[2]>0&&r.includes(u[2])||l[3]>0&&r.includes(u[3]))continue;let d=t[s],f=n[s];if(d[0]>0&&r.includes(f[0])||d[1]>0&&r.includes(f[1])||d[2]>0&&r.includes(f[2])||d[3]>0&&r.includes(f[3]))continue;let p=t[c],m=n[c];p[0]>0&&r.includes(m[0])||p[1]>0&&r.includes(m[1])||p[2]>0&&r.includes(m[2])||p[3]>0&&r.includes(m[3])||(e[i++]=o,e[i++]=s,e[i++]=c)}return i}_createErasedMesh(e,t){let n=new gu(e.geometry.clone(),e.material);n.name=`${e.name}(erase)`,n.frustumCulled=e.frustumCulled,n.layers.set(this._firstPersonOnlyLayer);let r=n.geometry,i=r.getAttribute(`skinIndex`),a=i instanceof tp?[]:i.array,o=[];for(let e=0;e<a.length;e+=4)o.push([a[e],a[e+1],a[e+2],a[e+3]]);let s=r.getAttribute(`skinWeight`),c=s instanceof tp?[]:s.array,l=[];for(let e=0;e<c.length;e+=4)l.push([c[e],c[e+1],c[e+2],c[e+3]]);let u=r.getIndex();if(!u)throw Error(`The geometry doesn't have an index buffer`);let d=Array.from(u.array),f=this._excludeTriangles(d,l,o,t),p=[];for(let e=0;e<f;e++)p[e]=d[e];return r.setIndex(p),e.onBeforeRender&&(n.onBeforeRender=e.onBeforeRender),n.bind(new xu(e.skeleton.bones,e.skeleton.boneInverses),new K),n}_createHeadlessModelForSkinnedMesh(e,t){let n=[];if(t.skeleton.bones.forEach((e,t)=>{this._isEraseTarget(e)&&n.push(t)}),!n.length){t.layers.enable(this._thirdPersonOnlyLayer),t.layers.enable(this._firstPersonOnlyLayer);return}t.layers.set(this._thirdPersonOnlyLayer);let r=this._createErasedMesh(t,n);e.add(r)}_createHeadlessModel(e){if(e.type===`Group`)if(e.layers.set(this._thirdPersonOnlyLayer),this._isEraseTarget(e))e.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer));else{let t=new Ec;t.name=`_headless_${e.name}`,t.layers.set(this._firstPersonOnlyLayer),e.parent.add(t),e.children.filter(e=>e.type===`SkinnedMesh`).forEach(e=>{let n=e;this._createHeadlessModelForSkinnedMesh(t,n)})}else if(e.type===`SkinnedMesh`){let t=e;this._createHeadlessModelForSkinnedMesh(e.parent,t)}else this._isEraseTarget(e)&&(e.layers.set(this._thirdPersonOnlyLayer),e.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer)))}_isEraseTarget(e){return e===this.humanoid.getRawBoneNode(`head`)?!0:e.parent?this._isEraseTarget(e.parent):!1}};CS.DEFAULT_FIRSTPERSON_ONLY_LAYER=9,CS.DEFAULT_THIRDPERSON_ONLY_LAYER=10;var wS=CS,TS=new Set([`1.0`,`1.0-beta`]),ES=class{get name(){return`VRMFirstPersonLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return rS(this,null,function*(){let t=e.userData.vrmHumanoid;if(t!==null){if(t===void 0)throw Error(`VRMFirstPersonLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first`);e.userData.vrmFirstPerson=yield this._import(e,t)}})}_import(e,t){return rS(this,null,function*(){return t==null?null:(yield this._v1Import(e,t))||(yield this._v0Import(e,t))||null})}_v1Import(e,t){return rS(this,null,function*(){let n=this.parser.json;if(n.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let r=n.extensions?.VRMC_vrm;if(!r)return null;let i=r.specVersion;if(!TS.has(i))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${i}"`),null;let a=r.firstPerson,o=[],s=yield sS(e);return Array.from(s.entries()).forEach(([e,t])=>{let n=(a?.meshAnnotations)?.find(t=>t.node===e);o.push({meshes:t,type:n?.type??`auto`})}),new wS(t,o)})}_v0Import(e,t){return rS(this,null,function*(){let n=this.parser.json,r=n.extensions?.VRM;if(!r)return null;let i=r.firstPerson;if(!i)return null;let a=[],o=yield sS(e);return Array.from(o.entries()).forEach(([e,t])=>{let r=n.nodes[e],o=i.meshAnnotations?i.meshAnnotations.find(e=>e.mesh===r.mesh):void 0;a.push({meshes:t,type:this._convertV0FlagToV1Type(o?.firstPersonFlag)})}),new wS(t,a)})}_convertV0FlagToV1Type(e){return e===`FirstPersonOnly`?`firstPersonOnly`:e===`ThirdPersonOnly`?`thirdPersonOnly`:e===`Both`?`both`:`auto`}},DS=new W,OS=new W,kS=new U,AS=class extends Ec{constructor(e){super(),this.vrmHumanoid=e,this._boneAxesMap=new Map,Object.values(e.humanBones).forEach(e=>{let t=new op(1);t.matrixAutoUpdate=!1,t.material.depthTest=!1,t.material.depthWrite=!1,this.add(t),this._boneAxesMap.set(e,t)})}dispose(){Array.from(this._boneAxesMap.values()).forEach(e=>{e.geometry.dispose(),e.material.dispose()})}updateMatrixWorld(e){Array.from(this._boneAxesMap.entries()).forEach(([e,t])=>{e.node.updateWorldMatrix(!0,!1),e.node.matrixWorld.decompose(DS,kS,OS);let n=DS.set(.1,.1,.1).divide(OS);t.matrix.copy(e.node.matrixWorld).scale(n)}),super.updateMatrixWorld(e)}},jS=`hips.spine.chest.upperChest.neck.head.leftEye.rightEye.jaw.leftUpperLeg.leftLowerLeg.leftFoot.leftToes.rightUpperLeg.rightLowerLeg.rightFoot.rightToes.leftShoulder.leftUpperArm.leftLowerArm.leftHand.rightShoulder.rightUpperArm.rightLowerArm.rightHand.leftThumbMetacarpal.leftThumbProximal.leftThumbDistal.leftIndexProximal.leftIndexIntermediate.leftIndexDistal.leftMiddleProximal.leftMiddleIntermediate.leftMiddleDistal.leftRingProximal.leftRingIntermediate.leftRingDistal.leftLittleProximal.leftLittleIntermediate.leftLittleDistal.rightThumbMetacarpal.rightThumbProximal.rightThumbDistal.rightIndexProximal.rightIndexIntermediate.rightIndexDistal.rightMiddleProximal.rightMiddleIntermediate.rightMiddleDistal.rightRingProximal.rightRingIntermediate.rightRingDistal.rightLittleProximal.rightLittleIntermediate.rightLittleDistal`.split(`.`),MS={hips:null,spine:`hips`,chest:`spine`,upperChest:`chest`,neck:`upperChest`,head:`neck`,leftEye:`head`,rightEye:`head`,jaw:`head`,leftUpperLeg:`hips`,leftLowerLeg:`leftUpperLeg`,leftFoot:`leftLowerLeg`,leftToes:`leftFoot`,rightUpperLeg:`hips`,rightLowerLeg:`rightUpperLeg`,rightFoot:`rightLowerLeg`,rightToes:`rightFoot`,leftShoulder:`upperChest`,leftUpperArm:`leftShoulder`,leftLowerArm:`leftUpperArm`,leftHand:`leftLowerArm`,rightShoulder:`upperChest`,rightUpperArm:`rightShoulder`,rightLowerArm:`rightUpperArm`,rightHand:`rightLowerArm`,leftThumbMetacarpal:`leftHand`,leftThumbProximal:`leftThumbMetacarpal`,leftThumbDistal:`leftThumbProximal`,leftIndexProximal:`leftHand`,leftIndexIntermediate:`leftIndexProximal`,leftIndexDistal:`leftIndexIntermediate`,leftMiddleProximal:`leftHand`,leftMiddleIntermediate:`leftMiddleProximal`,leftMiddleDistal:`leftMiddleIntermediate`,leftRingProximal:`leftHand`,leftRingIntermediate:`leftRingProximal`,leftRingDistal:`leftRingIntermediate`,leftLittleProximal:`leftHand`,leftLittleIntermediate:`leftLittleProximal`,leftLittleDistal:`leftLittleIntermediate`,rightThumbMetacarpal:`rightHand`,rightThumbProximal:`rightThumbMetacarpal`,rightThumbDistal:`rightThumbProximal`,rightIndexProximal:`rightHand`,rightIndexIntermediate:`rightIndexProximal`,rightIndexDistal:`rightIndexIntermediate`,rightMiddleProximal:`rightHand`,rightMiddleIntermediate:`rightMiddleProximal`,rightMiddleDistal:`rightMiddleIntermediate`,rightRingProximal:`rightHand`,rightRingIntermediate:`rightRingProximal`,rightRingDistal:`rightRingIntermediate`,rightLittleProximal:`rightHand`,rightLittleIntermediate:`rightLittleProximal`,rightLittleDistal:`rightLittleIntermediate`};function NS(e){return e.invert?e.invert():e.inverse(),e}var PS=new W,FS=new U,IS=class{constructor(e){this.humanBones=e,this.restPose=this.getAbsolutePose()}getAbsolutePose(){let e={};return Object.keys(this.humanBones).forEach(t=>{let n=t,r=this.getBoneNode(n);r&&(PS.copy(r.position),FS.copy(r.quaternion),e[n]={position:PS.toArray(),rotation:FS.toArray()})}),e}getPose(){let e={};return Object.keys(this.humanBones).forEach(t=>{let n=t,r=this.getBoneNode(n);if(!r)return;PS.set(0,0,0),FS.identity();let i=this.restPose[n];i?.position&&PS.fromArray(i.position).negate(),i?.rotation&&NS(FS.fromArray(i.rotation)),PS.add(r.position),FS.premultiply(r.quaternion),e[n]={position:PS.toArray(),rotation:FS.toArray()}}),e}setPose(e){Object.entries(e).forEach(([e,t])=>{let n=e,r=this.getBoneNode(n);if(!r)return;let i=this.restPose[n];i&&(t?.position&&(r.position.fromArray(t.position),i.position&&r.position.add(PS.fromArray(i.position))),t?.rotation&&(r.quaternion.fromArray(t.rotation),i.rotation&&r.quaternion.multiply(FS.fromArray(i.rotation))))})}resetPose(){Object.entries(this.restPose).forEach(([e,t])=>{let n=this.getBoneNode(e);n&&(t?.position&&n.position.fromArray(t.position),t?.rotation&&n.quaternion.fromArray(t.rotation))})}getBone(e){return this.humanBones[e]??void 0}getBoneNode(e){return this.humanBones[e]?.node??null}},LS=new W,RS=new U,zS=new W,BS=class e extends IS{static _setupTransforms(e){let t=new Tc;t.name=`VRMHumanoidRig`;let n={},r={},i={},a={};jS.forEach(t=>{var o;let s=e.getBoneNode(t);if(s){let e=new W,c=new U;s.updateWorldMatrix(!0,!1),s.matrixWorld.decompose(e,c,LS),n[t]=e,r[t]=c,i[t]=s.quaternion.clone();let l=new U;(o=s.parent)==null||o.matrixWorld.decompose(LS,l,LS),a[t]=l}});let o={};return jS.forEach(r=>{let i=e.getBoneNode(r);if(i){let e=n[r],a=r,s;for(;s==null&&(a=MS[a],a!=null);)s=n[a];let c=new Tc;c.name=`Normalized_`+i.name,(a?o[a]?.node:t).add(c),c.position.copy(e),s&&c.position.sub(s),o[r]={node:c}}}),{rigBones:o,root:t,parentWorldRotations:a,boneRotations:i}}constructor(t){let{rigBones:n,root:r,parentWorldRotations:i,boneRotations:a}=e._setupTransforms(t);super(n),this.original=t,this.root=r,this._parentWorldRotations=i,this._boneRotations=a}update(){jS.forEach(e=>{let t=this.original.getBoneNode(e);if(t!=null){let n=this.getBoneNode(e),r=this._parentWorldRotations[e],i=RS.copy(r).invert(),a=this._boneRotations[e];if(t.quaternion.copy(n.quaternion).multiply(r).premultiply(i).multiply(a),e===`hips`){let e=n.getWorldPosition(zS);t.parent.updateWorldMatrix(!0,!1);let r=t.parent.matrixWorld,i=e.applyMatrix4(r.invert());t.position.copy(i)}}})}},VS=class e{get restPose(){return console.warn(`VRMHumanoid: restPose is deprecated. Use either rawRestPose or normalizedRestPose instead.`),this.rawRestPose}get rawRestPose(){return this._rawHumanBones.restPose}get normalizedRestPose(){return this._normalizedHumanBones.restPose}get humanBones(){return this._rawHumanBones.humanBones}get rawHumanBones(){return this._rawHumanBones.humanBones}get normalizedHumanBones(){return this._normalizedHumanBones.humanBones}get normalizedHumanBonesRoot(){return this._normalizedHumanBones.root}constructor(e,t){this.autoUpdateHumanBones=t?.autoUpdateHumanBones??!0,this._rawHumanBones=new IS(e),this._normalizedHumanBones=new BS(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new IS(e.humanBones),this._normalizedHumanBones=new BS(this._rawHumanBones),this}clone(){return new e(this.humanBones,{autoUpdateHumanBones:this.autoUpdateHumanBones}).copy(this)}getAbsolutePose(){return console.warn(`VRMHumanoid: getAbsolutePose() is deprecated. Use either getRawAbsolutePose() or getNormalizedAbsolutePose() instead.`),this.getRawAbsolutePose()}getRawAbsolutePose(){return this._rawHumanBones.getAbsolutePose()}getNormalizedAbsolutePose(){return this._normalizedHumanBones.getAbsolutePose()}getPose(){return console.warn(`VRMHumanoid: getPose() is deprecated. Use either getRawPose() or getNormalizedPose() instead.`),this.getRawPose()}getRawPose(){return this._rawHumanBones.getPose()}getNormalizedPose(){return this._normalizedHumanBones.getPose()}setPose(e){return console.warn(`VRMHumanoid: setPose() is deprecated. Use either setRawPose() or setNormalizedPose() instead.`),this.setRawPose(e)}setRawPose(e){return this._rawHumanBones.setPose(e)}setNormalizedPose(e){return this._normalizedHumanBones.setPose(e)}resetPose(){return console.warn(`VRMHumanoid: resetPose() is deprecated. Use either resetRawPose() or resetNormalizedPose() instead.`),this.resetRawPose()}resetRawPose(){return this._rawHumanBones.resetPose()}resetNormalizedPose(){return this._normalizedHumanBones.resetPose()}getBone(e){return console.warn(`VRMHumanoid: getBone() is deprecated. Use either getRawBone() or getNormalizedBone() instead.`),this.getRawBone(e)}getRawBone(e){return this._rawHumanBones.getBone(e)}getNormalizedBone(e){return this._normalizedHumanBones.getBone(e)}getBoneNode(e){return console.warn(`VRMHumanoid: getBoneNode() is deprecated. Use either getRawBoneNode() or getNormalizedBoneNode() instead.`),this.getRawBoneNode(e)}getRawBoneNode(e){return this._rawHumanBones.getBoneNode(e)}getNormalizedBoneNode(e){return this._normalizedHumanBones.getBoneNode(e)}update(){this.autoUpdateHumanBones&&this._normalizedHumanBones.update()}},HS={Hips:`hips`,Spine:`spine`,Head:`head`,LeftUpperLeg:`leftUpperLeg`,LeftLowerLeg:`leftLowerLeg`,LeftFoot:`leftFoot`,RightUpperLeg:`rightUpperLeg`,RightLowerLeg:`rightLowerLeg`,RightFoot:`rightFoot`,LeftUpperArm:`leftUpperArm`,LeftLowerArm:`leftLowerArm`,LeftHand:`leftHand`,RightUpperArm:`rightUpperArm`,RightLowerArm:`rightLowerArm`,RightHand:`rightHand`},US=new Set([`1.0`,`1.0-beta`]),WS={leftThumbProximal:`leftThumbMetacarpal`,leftThumbIntermediate:`leftThumbProximal`,rightThumbProximal:`rightThumbMetacarpal`,rightThumbIntermediate:`rightThumbProximal`},GS=class{get name(){return`VRMHumanoidLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot,this.autoUpdateHumanBones=t?.autoUpdateHumanBones}afterRoot(e){return rS(this,null,function*(){e.userData.vrmHumanoid=yield this._import(e)})}_import(e){return rS(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return rS(this,null,function*(){let t=this.parser.json;if(t.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let n=t.extensions?.VRMC_vrm;if(!n)return null;let r=n.specVersion;if(!US.has(r))return console.warn(`VRMHumanoidLoaderPlugin: Unknown VRMC_vrm specVersion "${r}"`),null;let i=n.humanoid;if(!i)return null;let a=i.humanBones.leftThumbIntermediate!=null||i.humanBones.rightThumbIntermediate!=null,o={};i.humanBones!=null&&(yield Promise.all(Object.entries(i.humanBones).map(e=>rS(this,[e],function*([e,t]){let n=e,r=t.node;if(a){let e=WS[n];e!=null&&(n=e)}let i=yield this.parser.getDependency(`node`,r);if(i==null){console.warn(`A glTF node bound to the humanoid bone ${n} (index = ${r}) does not exist`);return}o[n]={node:i}}))));let s=new VS(this._ensureRequiredBonesExist(o),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(s.normalizedHumanBonesRoot),this.helperRoot){let e=new AS(s);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return s})}_v0Import(e){return rS(this,null,function*(){let t=this.parser.json.extensions?.VRM;if(!t)return null;let n=t.humanoid;if(!n)return null;let r={};n.humanBones!=null&&(yield Promise.all(n.humanBones.map(e=>rS(this,null,function*(){let t=e.bone,n=e.node;if(t==null||n==null)return;let i=yield this.parser.getDependency(`node`,n);if(i==null){console.warn(`A glTF node bound to the humanoid bone ${t} (index = ${n}) does not exist`);return}let a=WS[t]??t;if(r[a]!=null){console.warn(`Multiple bone entries for ${a} detected (index = ${n}), ignoring duplicated entries.`);return}r[a]={node:i}}))));let i=new VS(this._ensureRequiredBonesExist(r),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(i.normalizedHumanBonesRoot),this.helperRoot){let e=new AS(i);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return i})}_ensureRequiredBonesExist(e){let t=Object.values(HS).filter(t=>e[t]==null);if(t.length>0)throw Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${t.join(`, `)}`);return e}},KS=class extends Y{constructor(){super(),this._currentTheta=0,this._currentRadius=0,this.theta=0,this.radius=0,this._currentTheta=0,this._currentRadius=0,this._attrPos=new J(new Float32Array(195),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new J(new Uint16Array(189),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentTheta!==this.theta&&(this._currentTheta=this.theta,e=!0),this._currentRadius!==this.radius&&(this._currentRadius=this.radius,e=!0),e&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,0,0,0);for(let e=0;e<64;e++){let t=e/63*this._currentTheta;this._attrPos.setXYZ(e+1,this._currentRadius*Math.sin(t),0,this._currentRadius*Math.cos(t))}this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<63;e++)this._attrIndex.setXYZ(e*3,0,e+1,e+2);this._attrIndex.needsUpdate=!0}},qS=class extends Y{constructor(){super(),this.radius=0,this._currentRadius=0,this.tail=new W,this._currentTail=new W,this._attrPos=new J(new Float32Array(294),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new J(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentRadius!==this.radius&&(this._currentRadius=this.radius,e=!0),this._currentTail.equals(this.tail)||(this._currentTail.copy(this.tail),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){let t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<32;e++){let t=(e+1)%32;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(64+e*2,32+e,32+t),this._attrIndex.setXY(128+e*2,64+e,64+t)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},JS=new U,YS=new U,XS=new W,ZS=new W,QS=Math.sqrt(2)/2,$S=new U(0,0,-QS,QS),eC=new W(0,1,0),tC=class extends Ec{constructor(e){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=e;{let e=new KS;e.radius=.5;let t=new Kl({color:65280,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshPitch=new iu(e,t),this.add(this._meshPitch)}{let e=new KS;e.radius=.5;let t=new Kl({color:16711680,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshYaw=new iu(e,t),this.add(this._meshYaw)}{let e=new qS;e.radius=.1;let t=new zu({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new Zu(e,t),this._lineTarget.frustumCulled=!1,this.add(this._lineTarget)}}dispose(){this._meshYaw.geometry.dispose(),this._meshYaw.material.dispose(),this._meshPitch.geometry.dispose(),this._meshPitch.material.dispose(),this._lineTarget.geometry.dispose(),this._lineTarget.material.dispose()}updateMatrixWorld(e){let t=As.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=t,this._meshYaw.geometry.update();let n=As.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=n,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition(XS),this.vrmLookAt.getLookAtWorldQuaternion(JS),JS.multiply(this.vrmLookAt.getFaceFrontQuaternion(YS)),this._meshYaw.position.copy(XS),this._meshYaw.quaternion.copy(JS),this._meshPitch.position.copy(XS),this._meshPitch.quaternion.copy(JS),this._meshPitch.quaternion.multiply(YS.setFromAxisAngle(eC,t)),this._meshPitch.quaternion.multiply($S);let{target:r,autoUpdate:i}=this.vrmLookAt;r!=null&&i&&(r.getWorldPosition(ZS).sub(XS),this._lineTarget.geometry.tail.copy(ZS),this._lineTarget.geometry.update(),this._lineTarget.position.copy(XS)),super.updateMatrixWorld(e)}},nC=new W,rC=new W;function iC(e,t){return e.matrixWorld.decompose(nC,t,rC),t}function aC(e){return[Math.atan2(-e.z,e.x),Math.atan2(e.y,Math.sqrt(e.x*e.x+e.z*e.z))]}function oC(e){let t=Math.round(e/2/Math.PI);return e-2*Math.PI*t}var sC=new W(0,0,1),cC=new W,lC=new W,uC=new W,dC=new U,fC=new U,pC=new U,mC=new U,hC=new cc,gC=class e{constructor(e,t){this.offsetFromHeadBone=new W,this.autoUpdate=!0,this.faceFront=new W(0,0,1),this.humanoid=e,this.applier=t,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new U)}get yaw(){return this._yaw}set yaw(e){this._yaw=e,this._needsUpdate=!0}get pitch(){return this._pitch}set pitch(e){this._pitch=e,this._needsUpdate=!0}get euler(){return console.warn(`VRMLookAt: euler is deprecated. use getEuler() instead.`),this.getEuler(new cc)}getEuler(e){return e.set(As.DEG2RAD*this._pitch,As.DEG2RAD*this._yaw,0,`YXZ`)}copy(e){if(this.humanoid!==e.humanoid)throw Error(`VRMLookAt: humanoid must be same in order to copy`);return this.offsetFromHeadBone.copy(e.offsetFromHeadBone),this.applier=e.applier,this.autoUpdate=e.autoUpdate,this.target=e.target,this.faceFront.copy(e.faceFront),this}clone(){return new e(this.humanoid,this.applier).copy(this)}reset(){this._yaw=0,this._pitch=0,this._needsUpdate=!0}getLookAtWorldPosition(e){let t=this.humanoid.getRawBoneNode(`head`);return e.copy(this.offsetFromHeadBone).applyMatrix4(t.matrixWorld)}getLookAtWorldQuaternion(e){return iC(this.humanoid.getRawBoneNode(`head`),e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(sC)<.01)return e.copy(this._restHeadWorldQuaternion).invert();let[t,n]=aC(this.faceFront);return hC.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(hC).premultiply(mC.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(fC),this.getFaceFrontQuaternion(pC),e.copy(sC).applyQuaternion(fC).applyQuaternion(pC).applyEuler(this.getEuler(hC))}lookAt(e){let t=dC.copy(this._restHeadWorldQuaternion).multiply(NS(this.getLookAtWorldQuaternion(fC))),n=this.getLookAtWorldPosition(lC),r=uC.copy(e).sub(n).applyQuaternion(t).normalize(),[i,a]=aC(this.faceFront),[o,s]=aC(r),c=oC(o-i),l=oC(a-s);this._yaw=As.RAD2DEG*c,this._pitch=As.RAD2DEG*l,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(cC)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};gC.EULER_ORDER=`YXZ`;var _C=gC,vC=new W(0,0,1),yC=new U,bC=new U,xC=new cc(0,0,0,`YXZ`),SC=class{constructor(e,t,n,r,i){this.humanoid=e,this.rangeMapHorizontalInner=t,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=r,this.rangeMapVerticalUp=i,this.faceFront=new W(0,0,1),this._restQuatLeftEye=new U,this._restQuatRightEye=new U,this._restLeftEyeParentWorldQuat=new U,this._restRightEyeParentWorldQuat=new U;let a=this.humanoid.getRawBoneNode(`leftEye`),o=this.humanoid.getRawBoneNode(`rightEye`);a&&(this._restQuatLeftEye.copy(a.quaternion),iC(a.parent,this._restLeftEyeParentWorldQuat)),o&&(this._restQuatRightEye.copy(o.quaternion),iC(o.parent,this._restRightEyeParentWorldQuat))}applyYawPitch(e,t){let n=this.humanoid.getRawBoneNode(`leftEye`),r=this.humanoid.getRawBoneNode(`rightEye`),i=this.humanoid.getNormalizedBoneNode(`leftEye`),a=this.humanoid.getNormalizedBoneNode(`rightEye`);n&&(t<0?xC.x=-As.DEG2RAD*this.rangeMapVerticalDown.map(-t):xC.x=As.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?xC.y=-As.DEG2RAD*this.rangeMapHorizontalInner.map(-e):xC.y=As.DEG2RAD*this.rangeMapHorizontalOuter.map(e),yC.setFromEuler(xC),this._getWorldFaceFrontQuat(bC),i.quaternion.copy(bC).multiply(yC).multiply(bC.invert()),yC.copy(this._restLeftEyeParentWorldQuat),n.quaternion.copy(i.quaternion).multiply(yC).premultiply(yC.invert()).multiply(this._restQuatLeftEye)),r&&(t<0?xC.x=-As.DEG2RAD*this.rangeMapVerticalDown.map(-t):xC.x=As.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?xC.y=-As.DEG2RAD*this.rangeMapHorizontalOuter.map(-e):xC.y=As.DEG2RAD*this.rangeMapHorizontalInner.map(e),yC.setFromEuler(xC),this._getWorldFaceFrontQuat(bC),a.quaternion.copy(bC).multiply(yC).multiply(bC.invert()),yC.copy(this._restRightEyeParentWorldQuat),r.quaternion.copy(a.quaternion).multiply(yC).premultiply(yC.invert()).multiply(this._restQuatRightEye))}lookAt(e){console.warn(`VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.`);let t=As.RAD2DEG*e.y,n=As.RAD2DEG*e.x;this.applyYawPitch(t,n)}_getWorldFaceFrontQuat(e){if(this.faceFront.distanceToSquared(vC)<.01)return e.identity();let[t,n]=aC(this.faceFront);return xC.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(xC)}};SC.type=`bone`;var CC=class{constructor(e,t,n,r,i){this.expressions=e,this.rangeMapHorizontalInner=t,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=r,this.rangeMapVerticalUp=i}applyYawPitch(e,t){t<0?(this.expressions.setValue(`lookDown`,0),this.expressions.setValue(`lookUp`,this.rangeMapVerticalUp.map(-t))):(this.expressions.setValue(`lookUp`,0),this.expressions.setValue(`lookDown`,this.rangeMapVerticalDown.map(t))),e<0?(this.expressions.setValue(`lookLeft`,0),this.expressions.setValue(`lookRight`,this.rangeMapHorizontalOuter.map(-e))):(this.expressions.setValue(`lookRight`,0),this.expressions.setValue(`lookLeft`,this.rangeMapHorizontalOuter.map(e)))}lookAt(e){console.warn(`VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.`);let t=As.RAD2DEG*e.y,n=As.RAD2DEG*e.x;this.applyYawPitch(t,n)}};CC.type=`expression`;var wC=class{constructor(e,t){this.inputMaxValue=e,this.outputScale=t}map(e){return this.outputScale*lS(e/this.inputMaxValue)}},TC=new Set([`1.0`,`1.0-beta`]),EC=.01,DC=class{get name(){return`VRMLookAtLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot}afterRoot(e){return rS(this,null,function*(){let t=e.userData.vrmHumanoid;if(t===null)return;if(t===void 0)throw Error(`VRMLookAtLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first`);let n=e.userData.vrmExpressionManager;if(n!==null){if(n===void 0)throw Error(`VRMLookAtLoaderPlugin: vrmExpressionManager is undefined. VRMExpressionLoaderPlugin have to be used first`);e.userData.vrmLookAt=yield this._import(e,t,n)}})}_import(e,t,n){return rS(this,null,function*(){return t==null||n==null?null:(yield this._v1Import(e,t,n))||(yield this._v0Import(e,t,n))||null})}_v1Import(e,t,n){return rS(this,null,function*(){let e=this.parser.json;if(e.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let r=e.extensions?.VRMC_vrm;if(!r)return null;let i=r.specVersion;if(!TC.has(i))return console.warn(`VRMLookAtLoaderPlugin: Unknown VRMC_vrm specVersion "${i}"`),null;let a=r.lookAt;if(!a)return null;let o=a.type===`expression`?1:10,s=this._v1ImportRangeMap(a.rangeMapHorizontalInner,o),c=this._v1ImportRangeMap(a.rangeMapHorizontalOuter,o),l=this._v1ImportRangeMap(a.rangeMapVerticalDown,o),u=this._v1ImportRangeMap(a.rangeMapVerticalUp,o),d;d=a.type===`expression`?new CC(n,s,c,l,u):new SC(t,s,c,l,u);let f=this._importLookAt(t,d);return f.offsetFromHeadBone.fromArray(a.offsetFromHeadBone??[0,.06,0]),f})}_v1ImportRangeMap(e,t){let n=e?.inputMaxValue??90,r=e?.outputScale??t;return n<EC&&(console.warn(`VRMLookAtLoaderPlugin: inputMaxValue of a range map is too small. Consider reviewing the range map!`),n=EC),new wC(n,r)}_v0Import(e,t,n){return rS(this,null,function*(){let e=this.parser.json.extensions?.VRM;if(!e)return null;let r=e.firstPerson;if(!r)return null;let i=r.lookAtTypeName===`BlendShape`?1:10,a=this._v0ImportDegreeMap(r.lookAtHorizontalInner,i),o=this._v0ImportDegreeMap(r.lookAtHorizontalOuter,i),s=this._v0ImportDegreeMap(r.lookAtVerticalDown,i),c=this._v0ImportDegreeMap(r.lookAtVerticalUp,i),l;l=r.lookAtTypeName===`BlendShape`?new CC(n,a,o,s,c):new SC(t,a,o,s,c);let u=this._importLookAt(t,l);return r.firstPersonBoneOffset?u.offsetFromHeadBone.set(r.firstPersonBoneOffset.x??0,r.firstPersonBoneOffset.y??.06,-(r.firstPersonBoneOffset.z??0)):u.offsetFromHeadBone.set(0,.06,0),u.faceFront.set(0,0,-1),l instanceof SC&&l.faceFront.set(0,0,-1),u})}_v0ImportDegreeMap(e,t){let n=e?.curve;JSON.stringify(n)!==`[0,0,0,1,1,1,1,0]`&&console.warn(`Curves of LookAtDegreeMap defined in VRM 0.0 are not supported`);let r=e?.xRange??90,i=e?.yRange??t;return r<EC&&(console.warn(`VRMLookAtLoaderPlugin: xRange of a degree map is too small. Consider reviewing the degree map!`),r=EC),new wC(r,i)}_importLookAt(e,t){let n=new _C(e,t);if(this.helperRoot){let e=new tC(n);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return n}};function OC(e,t){return typeof e!=`string`||e===``?``:(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^/]+).*/i,`$1`)),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}var kC=new Set([`1.0`,`1.0-beta`]),AC=class{get name(){return`VRMMetaLoaderPlugin`}constructor(e,t){this.parser=e,this.needThumbnailImage=t?.needThumbnailImage??!1,this.acceptLicenseUrls=t?.acceptLicenseUrls??[`https://vrm.dev/licenses/1.0/`],this.acceptV0Meta=t?.acceptV0Meta??!0}afterRoot(e){return rS(this,null,function*(){e.userData.vrmMeta=yield this._import(e)})}_import(e){return rS(this,null,function*(){return(yield this._v1Import(e))??(yield this._v0Import(e))??null})}_v1Import(e){return rS(this,null,function*(){let e=this.parser.json;if(e.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let t=e.extensions?.VRMC_vrm;if(t==null)return null;let n=t.specVersion;if(!kC.has(n))return console.warn(`VRMMetaLoaderPlugin: Unknown VRMC_vrm specVersion "${n}"`),null;let r=t.meta;if(!r)return null;let i=r.licenseUrl;if(!new Set(this.acceptLicenseUrls).has(i))throw Error(`VRMMetaLoaderPlugin: The license url "${i}" is not accepted`);let a;return this.needThumbnailImage&&r.thumbnailImage!=null&&(a=(yield this._extractGLTFImage(r.thumbnailImage))??void 0),{metaVersion:`1`,name:r.name,version:r.version,authors:r.authors,copyrightInformation:r.copyrightInformation,contactInformation:r.contactInformation,references:r.references,thirdPartyLicenses:r.thirdPartyLicenses,thumbnailImage:a,licenseUrl:r.licenseUrl,avatarPermission:r.avatarPermission,allowExcessivelyViolentUsage:r.allowExcessivelyViolentUsage,allowExcessivelySexualUsage:r.allowExcessivelySexualUsage,commercialUsage:r.commercialUsage,allowPoliticalOrReligiousUsage:r.allowPoliticalOrReligiousUsage,allowAntisocialOrHateUsage:r.allowAntisocialOrHateUsage,creditNotation:r.creditNotation,allowRedistribution:r.allowRedistribution,modification:r.modification,otherLicenseUrl:r.otherLicenseUrl}})}_v0Import(e){return rS(this,null,function*(){let e=this.parser.json.extensions?.VRM;if(!e)return null;let t=e.meta;if(!t)return null;if(!this.acceptV0Meta)throw Error(`VRMMetaLoaderPlugin: Attempted to load VRM0.0 meta but acceptV0Meta is false`);let n;return this.needThumbnailImage&&t.texture!=null&&t.texture!==-1&&(n=yield this.parser.getDependency(`texture`,t.texture)),{metaVersion:`0`,allowedUserName:t.allowedUserName,author:t.author,commercialUssageName:t.commercialUssageName,contactInformation:t.contactInformation,licenseName:t.licenseName,otherLicenseUrl:t.otherLicenseUrl,otherPermissionUrl:t.otherPermissionUrl,reference:t.reference,sexualUssageName:t.sexualUssageName,texture:n??void 0,title:t.title,version:t.version,violentUssageName:t.violentUssageName}})}_extractGLTFImage(e){return rS(this,null,function*(){let t=this.parser.json.images?.[e];if(t==null)return console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${e}] of glTF as a thumbnail but the image doesn't exist`),null;let n=t.uri;if(t.bufferView!=null){let e=yield this.parser.getDependency(`bufferView`,t.bufferView),r=new Blob([e],{type:t.mimeType});n=URL.createObjectURL(r)}return n==null?(console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${e}] of glTF as a thumbnail but the image couldn't load properly`),null):yield new cf().loadAsync(OC(n,this.parser.options.path)).catch(e=>(console.error(e),console.warn(`VRMMetaLoaderPlugin: Failed to load a thumbnail image`),null))})}},jC=class{constructor(e){this.scene=e.scene,this.meta=e.meta,this.humanoid=e.humanoid,this.expressionManager=e.expressionManager,this.firstPerson=e.firstPerson,this.lookAt=e.lookAt}update(e){this.humanoid.update(),this.lookAt&&this.lookAt.update(e),this.expressionManager&&this.expressionManager.update()}},MC=class extends jC{constructor(e){super(e),this.materials=e.materials,this.springBoneManager=e.springBoneManager,this.nodeConstraintManager=e.nodeConstraintManager}update(e){super.update(e),this.nodeConstraintManager&&this.nodeConstraintManager.update(),this.springBoneManager&&this.springBoneManager.update(e),this.materials&&this.materials.forEach(t=>{t.update&&t.update(e)})}},NC=Object.defineProperty,PC=Object.getOwnPropertySymbols,FC=Object.prototype.hasOwnProperty,IC=Object.prototype.propertyIsEnumerable,LC=(e,t,n)=>t in e?NC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,RC=(e,t)=>{for(var n in t||={})FC.call(t,n)&&LC(e,n,t[n]);if(PC)for(var n of PC(t))IC.call(t,n)&&LC(e,n,t[n]);return e},zC=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())});function BC(e,t){e.colorSpace=t}var VC=class{get pending(){return Promise.all(this._pendings)}constructor(e,t){this._parser=e,this._materialParams=t,this._pendings=[]}assignPrimitive(e,t){t!=null&&(this._materialParams[e]=t)}assignColor(e,t,n){if(t!=null){let r=new q().fromArray(t);n&&r.convertSRGBToLinear(),this._materialParams[e]=r}}assignTexture(e,t,n){return zC(this,null,function*(){let r=zC(this,null,function*(){if(t!=null){let r=yield this._parser.assignTexture(this._materialParams,e,t);if(r==null){console.warn(`GLTFMToonMaterialParamsAssignHelper: Failed to load texture. The rendering result may be wrong`);return}n&&BC(r,`srgb`)}});return this._pendings.push(r),r})}assignTextureByIndex(e,t,n){return zC(this,null,function*(){return this.assignTexture(e,t==null?void 0:{index:t},n)})}},HC=`// #define PHONG
|
|
5772
|
+
`,colorWrite:!1,depthWrite:!0,depthTest:!1,side:2}),Cy=9.81,wy=6,Ty=.15,Ey=class extends vt{static props={water:{default:``,nodePath:!0},draft:{default:.35},stiffness:{default:3},damping:{default:3.5},drift:{default:.6},drag:{default:.9},samples:{default:4},size:{default:[1,1]}};static signals=[`submerged`,`surfaced`];water=``;draft=.35;stiffness=3;damping=3.5;drift=.6;drag=.9;samples=4;size=[1,1];surface=null;wet=!1;reportedNoImpulse=!1;update(e){if(e<=0)return;let t=this.resolveWater();if(!t)return;let n=this.node;if(!n.applyImpulse){this.reportedNoImpulse||(this.reportedNoImpulse=!0,Nt(this.node.tree?.engine??null,`error`,`[incanto] ${this.node.getPath()}: Buoyancy needs a body it can push — this node has no applyImpulse, so it will never float. Put it on a RigidBody3D.`));return}let[r,i,a]=[n.position[0]??0,n.position[1]??0,n.position[2]??0],o=[(this.size[0]??1)/2,(this.size[1]??1)/2],s=this.samplePoints(r,a,o[0],o[1]),c=n.mass??1,l=n.linearVelocity??[0,0,0],u=0,d=0,f=0,p=0;for(let[e,n]of s){let r=t.heightAt(e,n)-(i-this.draft);if(r<=0)continue;p++,u+=Cy*(1+this.stiffness*(r/Math.max(this.draft,Ty)));let a=.6;d+=t.heightAt(e+a,n)-t.heightAt(e-a,n),f+=t.heightAt(e,n+a)-t.heightAt(e,n-a)}let m=p>0;if(m!==this.wet&&(this.wet=m,this.emit(m?`submerged`:`surfaced`,this.node)),!m)return;let h=p/s.length,g=Math.min(u/s.length-this.damping*(l[1]??0),wy*Cy)*e*c,_=(-d*this.drift*12-(l[0]??0)*this.drag)*h*e*c,v=(-f*this.drift*12-(l[2]??0)*this.drag)*h*e*c;n.applyImpulse([_,g,v])}samplePoints(e,t,n,r){let i=Math.max(1,Math.round(this.samples));if(i===1)return[[e,t]];let a=[];for(let o=0;o<i;o++){let s=o/i*Math.PI*2+Math.PI/4;a.push([e+Math.cos(s)*n,t+Math.sin(s)*r])}return a}resolveWater(){if(this.surface)return this.surface;if(this.water!==``){let e=this.node.getNodeOrNull(this.water);if(!(e instanceof Uv))throw new L(`NODE_NOT_FOUND`,`Buoyancy on '${this.node.getPath()}': water '${this.water}' is not a Water3D in the tree.`,{prop:`water`});return this.surface=e,e}return this.surface=Dy(this.node.getRoot()),this.surface}};function Dy(e){if(e instanceof Uv)return e;for(let t of e.children){let e=Dy(t);if(e)return e}return null}function Oy(e,t,n){let r=e;if(typeof r.moveAndSlide!=`function`||r._physics==null||n<=0){e.position=[...t];return}let i=r.position,a=[];for(let e=0;e<i.length;e++)a.push(((t[e]??i[e]??0)-(i[e]??0))/n);r.velocity=a,r.moveAndSlide()}function ky(e){return Array.isArray(e.position)}function Ay(e){let t=e.node;if(!ky(t)){let n=e.constructor.name;throw new L(`PROP_TYPE_MISMATCH`,`${n} on '${t.getPath()}' needs a spatial node with a numeric 'position' array (a Node2D/Node3D subtype). '${t.name}' has none.`,{path:t.getPath()})}return t}function jy(e,t){let n=0,r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let r=(e[i]??0)-(t[i]??0);n+=r*r}return Math.sqrt(n)}function My(e,t){let n=Math.max(e.length,t.length),r=Array(n);for(let i=0;i<n;i++)r[i]=(e[i]??0)+(t[i]??0);return r}function Ny(e){let t=0;for(let n of e)t+=n*n;return Math.sqrt(t)}function Py(e){let t=Ny(e);return t===0?e.map(()=>0):e.map(e=>e/t)}function Fy(e,t,n){let r=Math.max(e.length,t.length),i=0;for(let n=0;n<r;n++){let r=(t[n]??0)-(e[n]??0);i+=r*r}let a=Math.sqrt(i),o=Array(r);if(a<=n||a===0){for(let e=0;e<r;e++)o[e]=t[e]??0;return{position:o,reached:!0}}let s=n/a;for(let n=0;n<r;n++){let r=e[n]??0;o[n]=r+((t[n]??0)-r)*s}return{position:o,reached:!1}}function Iy(e,t){let n=Math.min(Math.max(e,0),.99);return n<=0?1:1-n**(t*60)}function Ly(e){let t=e.position;if(!Array.isArray(t))return[];let n=t.slice();for(let t=e.parent;t;t=t.parent){let e=t.position;if(Array.isArray(e))for(let t=0;t<n.length;t++)n[t]=(n[t]??0)+(e[t]??0)}return n}function Ry(e,t){let n=t.slice();for(let t=e.parent;t;t=t.parent){let e=t.position;if(Array.isArray(e))for(let t=0;t<n.length;t++)n[t]=(n[t]??0)-(e[t]??0)}return n}var zy=class extends vt{static props={target:{default:``,nodePath:!0,required:!0},speed:{default:60},stopRange:{default:0},loseRange:{default:0},moveParent:{default:!1}};static signals=[`reachedTarget`,`lostTarget`];target=``;speed=60;stopRange=0;loseRange=0;moveParent=!1;inRange=!1;lost=!1;onReady(){if(this.target===``)throw new L(`PROP_TYPE_MISMATCH`,`Chase on '${this.node.getPath()}': "target" (a node path) is required.`,{prop:`target`});if(this.moveParent){let e=this.node.parent;if(!e||!ky(e))throw new L(`PROP_TYPE_MISMATCH`,`Chase on '${this.node.getPath()}': "moveParent" needs a spatial parent (a Node2D/Node3D) to move. '${this.node.name}' has none.`,{prop:`moveParent`,path:this.node.getPath()})}else Ay(this)}update(e){let t=this.moveParent?this.node.parent:this.node;if(!t||!ky(t))return;let n=this.node.getNodeOrNull(this.target);if(!n||!ky(n))return;let r=jy(t.position,n.position);if(this.loseRange>0&&r>this.loseRange){this.lost||(this.lost=!0,this.inRange=!1,this.emit(`lostTarget`));return}if(this.lost=!1,this.stopRange>0&&r<=this.stopRange){this.inRange||(this.inRange=!0,this.emit(`reachedTarget`));return}this.inRange=!1;let i=Math.min(this.speed*e,this.stopRange>0?r-this.stopRange:r),{position:a}=Fy(t.position,n.position,Math.max(0,i));Oy(t,a,e)}},By=class extends vt{static props={button:{default:0},maxDistance:{default:0},enabled:{default:!0}};static signals=[`clicked`,`hovered`,`unhovered`];button=0;maxDistance=0;enabled=!0;hovering=!1;pressedHere=!1;update(){let e=this.node.tree?.engine;if(!e||!this.enabled)return;let t=e.picker,n=e.input.pointerPosition();if(!t||!n){this.hovering&&this.setHover(!1);return}let r=t(n.x,n.y),i=r!==null&&this.isSelfOrDescendant(r)&&this.withinRange(r);i!==this.hovering&&this.setHover(i),e.input.mouseJustPressed(this.button)&&(this.pressedHere=i),e.input.mouseJustReleased(this.button)&&(this.pressedHere&&i&&this.emit(`clicked`,this.node),this.pressedHere=!1)}setHover(e){this.hovering=e,this.emit(e?`hovered`:`unhovered`,this.node)}isSelfOrDescendant(e){for(let t=e;t;t=t.parent)if(t===this.node)return!0;return!1}withinRange(e){if(this.maxDistance<=0||!this.node.tree?.engine?.scene?.root)return!0;let t=this.node.position,n=e.position;if(!Array.isArray(t)||!Array.isArray(n))return!0;let r=0;for(let e=0;e<Math.max(t.length,n.length);e++){let i=(t[e]??0)-(n[e]??0);r+=i*i}return Math.sqrt(r)<=this.maxDistance}},Vy=class extends vt{static props={group:{default:`player`}};static signals=[`totalChanged`];group=`player`;total=0;onReady(){this.node.addToGroup(this.group)}collect(e){this.total+=e,this.emit(`totalChanged`,this.total)}serialize(){return{total:this.total}}deserialize(e){let t=e;typeof t.total==`number`&&(this.total=t.total)}},Hy=class extends vt{static props={max:{default:100},regenPerSec:{default:0},invulnerableFor:{default:0},freeOnDeath:{default:!1}};static signals=[`damaged`,`healed`,`died`,`revived`,`healthChanged`];max=100;regenPerSec=0;invulnerableFor=0;freeOnDeath=!1;current=0;invulnTimer=0;dead=!1;get isDead(){return this.dead}get invulnerableRemaining(){return this.invulnTimer}onReady(){if(!(this.max>0))throw new L(`PROP_TYPE_MISMATCH`,`Health on '${this.node.getPath()}': "max" must be > 0, got ${this.max}.`,{prop:`max`});if(this.regenPerSec<0)throw new L(`PROP_TYPE_MISMATCH`,`Health on '${this.node.getPath()}': "regenPerSec" must be >= 0, got ${this.regenPerSec}.`,{prop:`regenPerSec`});if(this.invulnerableFor<0)throw new L(`PROP_TYPE_MISMATCH`,`Health on '${this.node.getPath()}': "invulnerableFor" must be >= 0, got ${this.invulnerableFor}.`,{prop:`invulnerableFor`});this.current=this.max}update(e){this.invulnTimer>0&&(this.invulnTimer=Math.max(0,this.invulnTimer-e)),this.regenPerSec>0&&!this.dead&&this.current<this.max&&this.setCurrent(this.current+this.regenPerSec*e)}damage(e){this.dead||e<=0||this.invulnTimer>0||(this.setCurrent(this.current-e),this.emit(`damaged`,e,this.current),this.invulnerableFor>0&&(this.invulnTimer=this.invulnerableFor),this.current<=0&&this.die())}heal(e){this.dead||e<=0||(this.setCurrent(this.current+e),this.emit(`healed`,e,this.current))}revive(e){this.dead&&(this.dead=!1,this.current=0,this.setCurrent(e===void 0?this.max:e),this.invulnTimer=this.invulnerableFor,this.emit(`revived`,this.current))}kill(){this.dead||(this.setCurrent(0),this.die())}setCurrent(e){let t=Math.max(0,Math.min(this.max,e));t!==this.current&&(this.current=t,this.emit(`healthChanged`,this.current,this.max))}die(){this.dead||(this.dead=!0,this.setCurrent(0),this.emit(`died`),this.freeOnDeath&&this.node.queueFree())}serialize(){return{current:this.current,dead:this.dead}}deserialize(e){let t=e;typeof t.current==`number`&&(this.current=Math.min(this.max,Math.max(0,t.current))),typeof t.dead==`boolean`&&(this.dead=t.dead)}};function Uy(e,t){let n=e.node;if(!n.declaredSignalNames().includes(`triggerEnter`)){let t=e.constructor.name;throw new L(`UNKNOWN_SIGNAL`,`${t} on '${n.getPath()}' needs a node that emits 'triggerEnter' — attach it to an Area2D/Area3D (or another body that declares the collision signals). '${n.name}' declares: [${n.declaredSignalNames().join(`, `)}].`,{signal:`triggerEnter`,path:n.getPath()})}n.on(`triggerEnter`,e=>t(e))}var Wy=class extends vt{static props={amount:{default:10},targetGroup:{default:``},oncePerTarget:{default:!0},repeatEvery:{default:0},destroySelf:{default:!1}};static signals=[`dealtDamage`];amount=10;targetGroup=``;oncePerTarget=!0;repeatEvery=0;destroySelf=!1;hit=new WeakSet;inside=new Map;onReady(){Uy(this,e=>{this.inside.set(e,this.repeatEvery),this.tryDamage(e)}),this.node.on(`triggerExit`,e=>{this.inside.delete(e)})}update(e){if(!(this.repeatEvery<=0||this.inside.size===0))for(let[t,n]of this.inside){if(!t.tree){this.inside.delete(t);continue}let r=n-e;r>0?this.inside.set(t,r):(this.inside.set(t,this.repeatEvery),this.tryDamage(t,{repeat:!0}))}}tryDamage(e,t){if(!t?.repeat&&this.oncePerTarget&&this.hit.has(e))return;let n=Gy(e);n&&(this.targetGroup!==``&&!n.owner.isInGroup(this.targetGroup)&&!e.isInGroup(this.targetGroup)||(this.oncePerTarget&&this.hit.add(e),n.health.damage(this.amount),this.emit(`dealtDamage`,this.amount,n.owner),this.destroySelf&&this.node.queueFree()))}};function Gy(e){let t=[e];for(;t.length>0;){let e=t.shift();if(e.behavior instanceof Hy)return{health:e.behavior,owner:e};t.push(...e.children)}for(let t=e.parent;t;t=t.parent)if(t.behavior instanceof Hy)return{health:t.behavior,owner:t};return null}var Ky=class extends vt{static signals=[`dayPhaseChanged`];static props={daySeconds:{default:240},startHour:{default:10},maxSunElevationDeg:{default:55},nightDarkness:{default:.75},paused:{default:!1}};daySeconds=240;startHour=10;maxSunElevationDeg=55;nightDarkness=.75;paused=!1;hour=0;phase=``;applyClock=0;baseAmbient=.3;baseExposure=1;captured=!1;onReady(){this.hour=this.startHour}update(e){if(this.paused||(this.hour=(this.hour+e/this.daySeconds*24)%24),this.applyClock-=e,this.applyClock>0)return;this.applyClock=.2,this.applyHour();let t=qy(this.hour);t!==this.phase&&(this.phase=t,this.emit(`dayPhaseChanged`,t))}applyHour(){let e=this.node.tree?.engine,t=e?.scene?.environment;if(!e||!t?.sky)return;this.captured||(this.captured=!0,this.baseAmbient=t.ambient?.intensity??.3,this.baseExposure=t.exposure??1);let n=(this.hour-6)/12*Math.PI,r=Math.sin(n);t.sky.elevationDeg=r*this.maxSunElevationDeg+(r<0?r*10:0),t.sky.azimuthDeg=this.hour/24*360+90;let i=Math.max(0,r),a=this.nightDarkness;t.ambient={...t.ambient??{},intensity:this.baseAmbient*(1-a+a*i)},t.exposure=this.baseExposure*(1-a*.55*(1-i))}};function qy(e){return e<5||e>=20?`night`:e<7.5?`dawn`:e<17.5?`day`:`dusk`}var Jy=class extends vt{static props={rise:{default:1},seconds:{default:.7},hold:{default:.3},drift:{default:0},freeOnEnd:{default:!0}};rise=1;seconds=.7;hold=.3;drift=0;freeOnEnd=!0;elapsed=0;start=[];done=!1;onReady(){let e=this.node;this.start=[...e.position??[]],e.opacity===void 0&&Nt(this.node.tree?.engine,`warn`,`[incanto] FloatAway on '${this.node.getPath()}' will not fade — ${this.node.constructor.name} has no "opacity" prop, so it pops out at full brightness instead. Use a node that has one (Label, Label3D, Sprite2D, Sprite3D).`)}update(e){if(this.done)return;let t=this.node;if(!t.position)return;this.elapsed+=e;let n=Math.max(.001,this.seconds),r=Math.min(1,this.elapsed/n),i=[...this.start],a=1-(1-r)*(1-r);if(i[1]=(this.start[1]??0)+this.rise*a,this.drift!==0&&(i[0]=(this.start[0]??0)+this.drift*a),t.position=i,t.opacity!==void 0){let e=Math.min(.99,Math.max(0,this.hold));t.opacity=r<=e?1:1-(r-e)/(1-e)}r>=1&&(this.done=!0,this.freeOnEnd&&this.node.queueFree())}},Yy=class extends vt{static props={target:{default:``,nodePath:!0,required:!0},offset:{default:[]},smoothing:{default:0,range:{min:0,max:1}},deadzone:{default:0,range:{min:0}}};static signals=[];target=``;offset=[];smoothing=0;deadzone=0;onReady(){if(this.target===``)throw new L(`PROP_TYPE_MISMATCH`,`FollowCamera on '${this.node.getPath()}': "target" (a node path) is required.`,{prop:`target`});if(this.deadzone<0)throw new L(`PROP_TYPE_MISMATCH`,`FollowCamera on '${this.node.getPath()}': "deadzone" must be >= 0, got ${this.deadzone}.`,{prop:`deadzone`});Ay(this)}shakeMag=0;shakeT=0;shakeFalloff=.28;shake(e,t=.28){this.shakeMag=Math.max(this.shakeMag,e),this.shakeT=t,this.shakeFalloff=t}update(e){let t=this.node;if(!ky(t))return;let n=t.getNodeOrNull(this.target);if(!n||!ky(n))return;let r=Ly(t),i=My(Ly(n),this.offset);if(!(this.deadzone>0&&jy(r,i)<=this.deadzone)){let n=Iy(this.smoothing,e);n>=1?t.position=Ry(t,i):t.position=Ry(t,r.map((e,t)=>e+((i[t]??e)-e)*n))}if(this.shakeT>0){this.shakeT-=e;let n=this.shakeMag*Math.max(0,this.shakeT)/this.shakeFalloff;this.shakeT<=0&&(this.shakeMag=0);let r=t.position.slice();for(let e=0;e<r.length;e++){let t=r.length>=3&&e===1?.5:1;r[e]=(r[e]??0)+(this.engine.rng.next()*2-1)*n*t}t.position=r}}};function Xy(e,t,n,r){try{return n()}catch(n){if(e.authored&&!e.reported.has(t)){e.reported.add(t);let r=n instanceof Error?n.message:String(n);Nt(e.engine??null,`error`,`[incanto] ${e.who}: ${r} ${e.consequence}`)}return r}}function Zy(e){let t=e.scene?.source;t&&e.setScene(Ai(R(t)))}function Qy(e,t,n){let r=n?.fadeSeconds??.4,i=()=>{e.setScene(Ai(R(t)))};if(typeof document>`u`||r<=0){i();return}let a=`incanto-scene-fade`,o=document.getElementById(a);o||(o=document.createElement(`div`),o.id=a,o.style.cssText=`position:fixed;inset:0;z-index:10001;background:#000;opacity:0;pointer-events:none;`,document.body.appendChild(o)),o.style.transition=`opacity ${r/2}s`,o.style.opacity=`1`,setTimeout(()=>{i();let e=document.getElementById(a);e&&(e.style.opacity=`0`,setTimeout(()=>e.remove(),r*500+60))},r*500+30)}var $y=class e extends vt{static signals=[`flowChanged`];static props={restartAction:{default:`restart`},pauseAction:{default:`pause`},freezeOnEnd:{default:!0},bannerPath:{default:`%Banner`,nodePath:!0},pausePanelPath:{default:`%PauseMenu`,nodePath:!0}};restartAction=`restart`;freezeOnEnd=!0;bannerPath=`%Banner`;pauseAction=`pause`;reportedActions=new Set;readAction(t,n){let r=this[t],i=e.props[t];return Xy({engine:this.engine,who:this.node.getPath(),reported:this.reportedActions,consequence:n,authored:r!==(typeof i?.default==`string`?i.default:``)},r,()=>this.engine.input.justPressed(r),!1)}pausePanelPath=`%PauseMenu`;state=`playing`;frozeScale=!1;onReady(){this.syncPausePanel()}syncPausePanel(){if(this.pausePanelPath===``)return;let e=this.node.getNodeOrNull(this.pausePanelPath);e&&`visible`in e&&(e.visible=this.state===`paused`)}gameOver(e=`GAME OVER`,t=`#ef4444`){this.transition(`gameover`,e,t)}win(e=`YOU WIN`,t=`#4ade80`){this.transition(`won`,e,t)}pause(){this.state===`playing`&&(this.state=`paused`,this.freeze(),this.syncPausePanel(),this.node.emit(`flowChanged`,this.state))}resume(){this.state===`paused`&&(this.state=`playing`,this.thaw(),this.syncPausePanel(),this.node.emit(`flowChanged`,this.state))}restart(){this.thaw(),Zy(this.engine)}goToScene(e,t){this.thaw(),Qy(this.engine,e,t)}transition(e,t,n){this.state===`gameover`||this.state===`won`||(this.state=e,this.freezeOnEnd&&this.freeze(),this.bannerPath!==``&&this.node.getNodeOrNull(this.bannerPath)?.show(t,{color:n,seconds:0}),this.node.emit(`flowChanged`,e))}freeze(){this.frozeScale||(this.frozeScale=!0,this.engine.timeScale=0)}thaw(){this.frozeScale&&(this.frozeScale=!1,this.engine.timeScale=1)}update(){if(this.state===`playing`||this.state===`paused`){this.readAction(`pauseAction`,`The pause key will do nothing.`)&&(this.state===`playing`?this.pause():this.resume());return}this.state!==`gameover`&&this.state!==`won`||this.readAction(`restartAction`,`The restart key will do nothing.`)&&this.restart()}};function eb(e){return Array.isArray(e.position)}function tb(e,t){let n=0,r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let r=(e[i]??0)-(t[i]??0);n+=r*r}return Math.sqrt(n)}var nb=class extends vt{static props={action:{default:`interact`},range:{default:2},actorGroup:{default:`player`}};static signals=[`interacted`];action=`interact`;range=2;actorGroup=`player`;update(){let e=this.node.tree?.engine;if(!e?.scene||!e.input.justPressed(this.action)||!eb(this.node))return;let t=this.node.position,n=null,r=1/0,i=this.node.tree?.getNodesInGroup(this.actorGroup)??rb(this.node.getRoot(),this.actorGroup);for(let e of i){if(!eb(e))continue;let i=tb(t,e.position);i<=this.range&&i<r&&(n=e,r=i)}n&&this.emit(`interacted`,n)}};function rb(e,t){let n=[],r=e=>{e.isInGroup(t)&&n.push(e);for(let t of e.children)r(t)};return r(e),n}var ib=.28;function ab(e,t,n,r,i){e?.effects.record({kind:t,name:n,from:r,amount:i,at:e.time})}var ob=class extends vt{static props={falloff:{default:ib}};falloff=ib;magnitude=0;t=0;prev=[];shake(e,t){this.engine?.settings.get(`reduceMotion`)!==!0&&(this.magnitude=Math.max(this.magnitude,e),this.t=t??this.falloff,ab(this.engine,`shake`,``,this.node?.getPath()??`engine`,e))}update(e){let t=Ay(this),n=t.position;for(let e=0;e<this.prev.length;e++)n[e]=(n[e]??0)-(this.prev[e]??0);if(this.t<=0){this.prev.length>0&&(t.position=n.slice(),this.prev.length=0);return}this.t-=e;let r=this.magnitude*Math.max(0,this.t)/this.falloff;this.t<=0&&(this.magnitude=0);let i=n.slice();this.prev.length!==i.length&&(this.prev=Array(i.length).fill(0));for(let e=0;e<i.length;e++){let t=i.length>=3&&e===1?.5:1;this.prev[e]=(this.engine.rng.next()*2-1)*r*t,i[e]=(i[e]??0)+this.prev[e]}t.position=i}},sb=class extends vt{static props={seconds:{default:1},startOnSignal:{default:!1}};static signals=[`expired`];seconds=1;startOnSignal=!1;elapsed=0;running=!1;fired=!1;onReady(){if(!(this.seconds>0))throw new L(`PROP_TYPE_MISMATCH`,`Lifetime on '${this.node.getPath()}': "seconds" must be > 0, got ${this.seconds}.`,{prop:`seconds`});this.running=!this.startOnSignal}startTimer(){this.elapsed=0,this.fired=!1,this.running=!0}update(e){!this.running||this.fired||(this.elapsed+=e,this.elapsed>=this.seconds&&(this.fired=!0,this.running=!1,this.emit(`expired`),this.node.queueFree()))}},cb=[`linear`,`easeIn`,`easeOut`,`easeInOut`];function lb(e,t){let n=t<0?0:t>1?1:t;switch(e){case`linear`:return n;case`easeIn`:return n*n;case`easeOut`:return 1-(1-n)*(1-n);case`easeInOut`:return n<.5?2*n*n:1-(-2*n+2)**2/2}}var ub=class extends vt{static props={to:{default:[],required:!0},duration:{default:1},ease:{default:`easeInOut`,options:[...cb]},startOnSignal:{default:!1}};static signals=[`arrived`];to=[];duration=1;ease=`easeInOut`;startOnSignal=!1;from=[];elapsed=0;running=!1;arrivedFired=!1;onReady(){if(!(this.duration>0))throw new L(`PROP_TYPE_MISMATCH`,`MoveTo on '${this.node.getPath()}': "duration" must be > 0, got ${this.duration}.`,{prop:`duration`});if(!cb.includes(this.ease))throw new L(`PROP_TYPE_MISMATCH`,`MoveTo on '${this.node.getPath()}': "ease" must be one of [${cb.join(`, `)}], got '${this.ease}'.`,{prop:`ease`});let e=Ay(this);this.from=[...e.position],this.startOnSignal||(this.running=!0)}start(){let e=this.node;this.from=[...e.position],this.elapsed=0,this.arrivedFired=!1,this.running=!0}update(e){if(!this.running)return;let t=this.node;this.elapsed+=e;let n=Math.min(1,this.elapsed/this.duration),r=lb(this.ease,n);t.position=this.from.map((e,t)=>e+((this.to[t]??e)-e)*r),n>=1&&!this.arrivedFired&&(this.arrivedFired=!0,this.running=!1,this.emit(`arrived`))}},db=[`x`,`y`,`z`],fb=[`position`,`rotation`,`scale`],pb={x:0,y:1,z:2},mb=class extends vt{static props={axis:{default:`y`,options:[...db]},amplitude:{default:1},frequency:{default:1},mode:{default:`position`,options:[...fb]}};static signals=[];axis=`y`;amplitude=1;frequency=1;mode=`position`;base=0;time=0;onReady(){if(!db.includes(this.axis))throw new L(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': "axis" must be one of [${db.join(`, `)}], got '${this.axis}'.`,{prop:`axis`});if(!fb.includes(this.mode))throw new L(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': "mode" must be one of [${fb.join(`, `)}], got '${this.mode}'.`,{prop:`mode`});this.base=this.readChannel()}update(e){this.time+=e;let t=this.amplitude*Math.sin(2*Math.PI*this.frequency*this.time);this.writeChannel(this.base+t)}isScalarRotation(){return this.mode===`rotation`&&typeof this.node.rotation==`number`}readChannel(){if(this.isScalarRotation())return this.node.rotation;let e=this.node[this.mode];if(!Array.isArray(e))throw new L(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': node has no '${this.mode}' array to oscillate.`,{prop:`mode`});return e[pb[this.axis]]??0}writeChannel(e){if(this.isScalarRotation()){this.node.rotation=e;return}let t=[...this.node[this.mode]];t[pb[this.axis]]=e,this.node[this.mode]=t}},hb=class extends vt{static signals=[`waypointReached`,`arrived`];static props={speed:{default:120},loop:{default:!1}};speed=120;loop=!1;waypoints=[];index=0;get moving(){return this.index<this.waypoints.length}setPath(e){this.waypoints=e.map(e=>[...e]),this.index=0}stop(){this.waypoints=[],this.index=0}update(e){if(!this.moving)return;let t=Ay(this),n=this.speed*e;for(;n>0&&this.index<this.waypoints.length;){let e=this.waypoints[this.index],r=Fy(t.position,e,n),i=gb(t.position,r.position);if(t.position=r.position,n-=i,r.reached){if(this.node.emit(`waypointReached`,this.index),this.index+=1,this.index>=this.waypoints.length)if(this.loop&&this.waypoints.length>1)this.index=0;else{this.node.emit(`arrived`);return}}else return}}};function gb(e,t){let n=0,r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let r=(t[i]??0)-(e[i]??0);n+=r*r}return Math.sqrt(n)}var _b=class extends vt{static props={points:{default:[],required:!0},speed:{default:60},loop:{default:!0},mode:{default:`loop`,options:[`loop`,`pingpong`]},pauseAt:{default:0}};static signals=[`reachedPoint`];points=[];speed=60;loop=!0;mode=`loop`;pauseAt=0;index=0;direction=1;pauseTimer=0;onReady(){if(!Array.isArray(this.points)||this.points.length===0)throw new L(`PROP_TYPE_MISMATCH`,`Patrol on '${this.node.getPath()}': "points" must be a non-empty array of position arrays or node paths.`,{prop:`points`});if(this.mode!==`loop`&&this.mode!==`pingpong`)throw new L(`PROP_TYPE_MISMATCH`,`Patrol on '${this.node.getPath()}': "mode" must be 'loop' or 'pingpong', got '${this.mode}'.`,{prop:`mode`});Ay(this)}update(e){if(this.pauseTimer>0){this.pauseTimer=Math.max(0,this.pauseTimer-e);return}let t=this.node,n=this.pointAt(this.index);if(!n){this.reportDeadWaypoint(this.index);return}let{position:r,reached:i}=Fy(t.position,n,this.speed*e);Oy(t,r,e),i&&(this.emit(`reachedPoint`,this.index),this.advance(),this.pauseAt>0&&(this.pauseTimer=this.pauseAt))}reportedDead=new Set;reportDeadWaypoint(e){if(this.reportedDead.has(e))return;this.reportedDead.add(e);let t=this.points[e];Nt(this.node.tree?.engine??null,`error`,`[incanto] ${this.node.getPath()}: waypoint ${e} (${JSON.stringify(t)}) resolves to nothing — the patrol stops here and never moves again.`)}pointAt(e){let t=this.points[e];if(Array.isArray(t))return t;if(typeof t==`string`){let e=this.node.getNodeOrNull(t);return Array.isArray(e?.position)?e.position:null}return null}advance(){let e=this.points.length-1;if(this.mode===`pingpong`){this.index>=e?this.direction=-1:this.index<=0&&(this.direction=1),this.index=Math.min(e,Math.max(0,this.index+this.direction));return}this.index<e?this.index+=1:this.loop&&(this.index=0)}},vb=class extends vt{static props={value:{default:1},kind:{default:`coin`},collectorGroup:{default:`player`}};static signals=[`collected`];value=1;kind=`coin`;collectorGroup=`player`;collectedAlready=!1;onReady(){Uy(this,e=>this.tryCollect(e))}tryCollect(e){if(this.collectedAlready)return;let t=yb(e,this.collectorGroup);t&&(this.collectedAlready=!0,this.node.queueFree(),this.emit(`collected`,this.value,t))}};function yb(e,t){let n=[e];for(;n.length>0;){let e=n.shift();if(e.isInGroup(t))return e;n.push(...e.children)}for(let n=e.parent;n;n=n.parent)if(n.isInGroup(t))return n;return null}var bb=class extends vt{static props={speed:{default:300},direction:{default:null},gravity:{default:0}};static signals=[];speed=300;direction=null;gravity=0;velocity=[];onReady(){if(this.speed===0&&this.gravity===0)throw new L(`PROP_TYPE_MISMATCH`,`Projectile on '${this.node.getPath()}': a projectile with "speed" 0 and "gravity" 0 never moves — set one of them.`,{prop:`speed`});let e=Ay(this),t=this.resolveDirection();for(this.velocity=t.map(e=>e*this.speed);this.velocity.length<e.position.length;)this.velocity.push(0)}update(e){let t=this.node;this.gravity!==0&&(this.velocity[1]=(this.velocity[1]??0)+this.gravity*e);let n=t.position,r=Math.max(n.length,this.velocity.length),i=Array(r);for(let t=0;t<r;t++)i[t]=(n[t]??0)+(this.velocity[t]??0)*e;t.position=i}resolveDirection(){if(Array.isArray(this.direction))return Py(this.direction);if(this.direction===null||this.direction===`forward`)return this.forwardFromRotation();throw new L(`PROP_TYPE_MISMATCH`,`Projectile on '${this.node.getPath()}': "direction" must be a vector or 'forward', got ${JSON.stringify(this.direction)}.`,{prop:`direction`})}forwardFromRotation(){let e=this.node.rotation;if(typeof e==`number`){let t=e*Math.PI/180;return[Math.cos(t),Math.sin(t)]}if(Array.isArray(e)){let t=(e[1]??0)*Math.PI/180,n=(e[0]??0)*Math.PI/180;return Py([Math.sin(t),-Math.sin(n)*Math.cos(t),Math.cos(n)*Math.cos(t)])}return[1,0]}},xb=class extends vt{static props={game:{default:`game`},slot:{default:`1`},label:{default:``},scene:{default:``},restoreOnReady:{default:!1},probeOnReady:{default:!1}};static signals=[`saved`,`restored`,`noSave`,`hasSave`];game=`game`;slot=`1`;label=``;scene=``;restoreOnReady=!1;probeOnReady=!1;elapsed=0;slots=null;store(){return this.slots??=new kn(this.game),this.slots}pendingRestore=!1;pendingProbe=!1;onReady(){this.pendingRestore=this.restoreOnReady,this.pendingProbe=this.probeOnReady}update(e){this.pendingProbe&&(this.pendingProbe=!1,this.probe()),this.pendingRestore&&(this.pendingRestore=!1,this.restore()),this.elapsed+=e}probe(){let e=this.store().read(this.slot);if(!e){this.emit(`noSave`);return}this.emit(`hasSave`,e.label||e.scene,e.playtime,e.scene)}get playtime(){return Math.round(this.elapsed)}slotScene(){return this.store().read(this.slot)?.scene??null}save(){let e=this.engine;this.store().write(this.slot,{scene:this.scene||(e.scene?.source.name??``),state:e.captureState(),label:this.label,savedAt:Date.now(),playtime:Math.round(this.elapsed)}),this.emit(`saved`,this.slot)}restore(){let e=this.store().read(this.slot);if(!e){this.emit(`noSave`);return}let t=this.engine.restoreState(e.state);this.emit(`restored`,t.restored)}clear(){this.store().remove(this.slot)}serialize(){return{playtime:Math.round(this.elapsed)}}deserialize(e){let t=e;typeof t.playtime==`number`&&t.playtime>=0&&(this.elapsed=t.playtime)}},Sb=class extends vt{static props={score:{default:0},lives:{default:0},scoreToWin:{default:0}};static signals=[`scoreChanged`,`won`,`lost`,`lifeLost`];score=0;lives=0;scoreToWin=0;hasWon=!1;hasLost=!1;onReady(){if(this.lives<0)throw new L(`PROP_TYPE_MISMATCH`,`ScoreKeeper on '${this.node.getPath()}': "lives" must be >= 0, got ${this.lives}.`,{prop:`lives`});if(this.scoreToWin<0)throw new L(`PROP_TYPE_MISMATCH`,`ScoreKeeper on '${this.node.getPath()}': "scoreToWin" must be >= 0, got ${this.scoreToWin}.`,{prop:`scoreToWin`})}addScore(e){this.setScore(this.score+e)}setScore(e){this.score=e,this.emit(`scoreChanged`,this.score),this.scoreToWin>0&&!this.hasWon&&this.score>=this.scoreToWin&&(this.hasWon=!0,this.emit(`won`))}loseLife(){this.lives<=0||this.hasLost||(--this.lives,this.emit(`lifeLost`,this.lives),this.lives<=0&&(this.hasLost=!0,this.emit(`lost`)))}serialize(){return{score:this.score,lives:this.lives,hasWon:this.hasWon,hasLost:this.hasLost}}deserialize(e){let t=e;typeof t.score==`number`&&(this.score=t.score),typeof t.lives==`number`&&(this.lives=t.lives),typeof t.hasWon==`boolean`&&(this.hasWon=t.hasWon),typeof t.hasLost==`boolean`&&(this.hasLost=t.hasLost)}},Cb=class{behavior;detached=new Map;constructor(e){this.behavior=e}resolveTemplate(e){let t=this.detached.get(e);if(t)return t;let n=this.behavior.node,r=e===``?null:n.getNodeOrNull(e);if(!r){let t=this.behavior.constructor.name;throw new L(`NODE_NOT_FOUND`,`${t} on '${n.getPath()}': "prefab" '${e}' does not resolve to a template node. Point it at a (usually hidden) child node to clone.`,{prop:`prefab`,path:n.getPath()})}return r.parent&&r.parent.removeChild(r),this.detached.set(e,r),r}spawn(e,t){let n=Xi(e),r=t?.at;return r&&r.length>0&&ky(n)&&(n.position=My((t?.parent??this.behavior.node)===this.behavior.node||!ky(this.behavior.node)?[]:this.behavior.node.position,r)),typeof n.visible==`boolean`&&(n.visible=!0),(t?.parent??this.behavior.node).addChild(n),n}},wb={CameraShake:ob,DayNight:Ky,GameFlow:$y,PathFollow:hb,Health:Hy,Lifetime:sb,ScoreKeeper:Sb,Pickup:vb,Collector:Vy,DamageOnContact:Wy,Interactable:nb,Clickable:By,SavePoint:xb,FollowCamera:Yy,Patrol:_b,Chase:zy,Wander:class extends vt{static props={speed:{default:40},radius:{default:50},changeEvery:{default:2}};static signals=[];speed=40;radius=50;changeEvery=2;origin=[];goal=[];timer=0;onReady(){if(!(this.radius>0))throw new L(`PROP_TYPE_MISMATCH`,`Wander on '${this.node.getPath()}': "radius" must be > 0, got ${this.radius}.`,{prop:`radius`});let e=Ay(this);this.origin=[...e.position],this.goal=[...e.position],this.pickGoal()}update(e){let t=this.node;this.timer-=e;let{position:n,reached:r}=Fy(t.position,this.goal,this.speed*e);t.position=n,(r||this.timer<=0)&&this.pickGoal()}pickGoal(){this.timer=this.changeEvery;let e=this.origin.length,t=Array(e);for(let n=0;n<8;n++){for(let n=0;n<e;n++)t[n]=(this.origin[n]??0)+this.rng.range(-this.radius,this.radius);if(jy(t,this.origin)<=this.radius){this.goal=t;return}}this.goal=t.map((e,n)=>{let r=this.origin[n]??0,i=jy(t,this.origin)||1;return r+(e-r)/i*this.radius})}},ZombieAI:class extends vt{static props={aggroTarget:{default:``,nodePath:!0},aggroRange:{default:12},deAggroRange:{default:0},chaseSpeed:{default:4},wanderSpeed:{default:1.4},wanderRadius:{default:8},wanderChangeEvery:{default:3},goalTarget:{default:``,nodePath:!0},stopRange:{default:1.2},moveParent:{default:!1}};static signals=[`enteredAggro`,`exitedAggro`,`movementStateChanged`];aggroTarget=``;aggroRange=12;deAggroRange=0;chaseSpeed=4;wanderSpeed=1.4;wanderRadius=8;wanderChangeEvery=3;goalTarget=``;stopRange=1.2;moveParent=!1;aggro=!1;started=!1;home=[];goal=[];timer=0;lastState=``;mover(){let e=this.moveParent?this.node.parent:this.node;return e&&ky(e)?e:null}effectiveDeAggro(){return this.deAggroRange>0?this.deAggroRange:this.aggroRange*1.5}onReady(){if(this.moveParent){let e=this.node.parent;if(!e||!ky(e))throw new L(`PROP_TYPE_MISMATCH`,`ZombieAI on '${this.node.getPath()}': "moveParent" needs a spatial parent (a Node2D/Node3D) to move. '${this.node.name}' has none.`,{prop:`moveParent`,path:this.node.getPath()})}else Ay(this)}update(e){let t=this.mover();if(!t)return;this.started||(this.started=!0,this.home=[...t.position],this.pickGoal());let n=this.aggroTarget?this.node.getNodeOrNull(this.aggroTarget):null,r=n&&ky(n)?n.position:null,i=r?this.groundDistance(t.position,r):1/0;if(!this.aggro&&i<=this.aggroRange?(this.aggro=!0,this.emit(`enteredAggro`)):this.aggro&&i>=this.effectiveDeAggro()&&(this.aggro=!1,this.emit(`exitedAggro`),this.pickGoal()),this.aggro&&r){let n=this.approach(t,r,this.chaseSpeed,e);this.setState(n?`idle`:`run`);return}this.timer-=e;let a=this.approach(t,this.goal,this.wanderSpeed,e);this.setState(a?`idle`:`walk`),(a||this.timer<=0)&&this.pickGoal()}approach(e,t,n,r){let i=e.position;if(this.groundDistance(i,t)<=this.stopRange)return!0;let a=i.length>=3?1:-1,o=[...t];a>=0&&(o[a]=i[a]??0);let s=this.groundDistance(i,o),{position:c}=Fy(i,o,Math.min(n*r,Math.max(0,s-this.stopRange)));return e.position=c,!1}groundDistance(e,t){if(e.length>=3){let n=(e[0]??0)-(t[0]??0),r=(e[2]??0)-(t[2]??0);return Math.hypot(n,r)}return jy(e,t)}setState(e){e!==this.lastState&&(this.lastState=e,this.emit(`movementStateChanged`,e))}pickGoal(){this.timer=this.wanderChangeEvery;let e=this.mover(),t=e?e.position:this.home,n=t.length>=3?1:-1,r=this.home,i=this.goalTarget?this.node.getNodeOrNull(this.goalTarget):null;if(i&&ky(i)){let e=i.position;r=t.map((t,n)=>t+((e[n]??0)-t)*.4)}let a=[...r];for(let e=0;e<a.length;e++)e!==n&&(a[e]=(r[e]??0)+this.rng.range(-this.wanderRadius,this.wanderRadius));n>=0&&(a[n]=t[n]??0),this.goal=a}},MoveTo:ub,Oscillate:mb,Spawner:class extends vt{static props={prefab:{default:``,nodePath:!0,required:!0},interval:{default:1},max:{default:0},at:{default:[]},autoStart:{default:!0},total:{default:0}};static signals=[`spawned`,`finished`];prefab=``;interval=1;max=0;at=[];autoStart=!0;total=0;source=new Cb(this);template;live=new Set;timer=0;running=!1;spawnedCount=0;done=!1;get liveCount(){return this.prune(),this.live.size}_templateForTest(){return this.template}onReady(){this.template=this.source.resolveTemplate(this.prefab),this.running=this.autoStart,this.timer=this.interval}start(){this.done||(this.running=!0)}stop(){this.running=!1}spawn(){if(this.prune(),this.done||this.max>0&&this.live.size>=this.max)return null;let e=this.source.spawn(this.template,this.at.length>0?{at:this.at}:void 0);return this.live.add(e),this.spawnedCount+=1,this.emit(`spawned`,e),this.total>0&&this.spawnedCount>=this.total&&(this.done=!0,this.running=!1,this.emit(`finished`)),e}update(e){this.running&&(this.timer-=e,!(this.timer>0)&&(this.timer+=this.interval,this.spawn()))}prune(){for(let e of this.live)e.parent===null&&this.live.delete(e)}},WaveSpawner:class extends vt{static props={waves:{default:[],required:!0},autoStart:{default:!0}};static signals=[`waveStarted`,`waveCleared`,`allCleared`];waves=[];autoStart=!0;source=new Cb(this);parsed=[];live=new Set;waveIndex=-1;phase=`idle`;timer=0;spawnedThisWave=0;announced=!1;onReady(){if(!Array.isArray(this.waves)||this.waves.length===0)throw new L(`PROP_TYPE_MISMATCH`,`WaveSpawner on '${this.node.getPath()}': "waves" must be a non-empty array of { prefab, count, interval, delayBefore }.`,{prop:`waves`});this.parsed=this.waves.map((e,t)=>this.parseWave(e,t));for(let e of this.parsed)this.source.resolveTemplate(e.prefab);this.autoStart&&this.beginWave(0)}start(){this.beginWave(0)}update(e){if(this.phase===`idle`||this.phase===`done`)return;let t=this.parsed[this.waveIndex];if(t){if(this.announced||(this.announced=!0,this.emit(`waveStarted`,this.waveIndex)),this.phase===`delay`){this.timer-=e,this.timer<=0&&(this.phase=`spawning`,this.timer=0);return}if(this.phase===`spawning`){for(this.timer-=e;this.timer<=0&&this.spawnedThisWave<t.count;){let e=this.source.spawn(this.source.resolveTemplate(t.prefab));this.live.add(e),this.spawnedThisWave+=1,this.timer+=t.interval}this.spawnedThisWave>=t.count&&(this.phase=`clearing`);return}if(this.phase===`clearing`&&(this.prune(),this.live.size===0)){this.emit(`waveCleared`,this.waveIndex);let e=this.waveIndex+1;e<this.parsed.length?this.beginWave(e):(this.phase=`done`,this.emit(`allCleared`))}}}beginWave(e){this.waveIndex=e,this.spawnedThisWave=0,this.announced=!1,this.live.clear();let t=this.parsed[e];t&&(t.delayBefore>0?(this.phase=`delay`,this.timer=t.delayBefore):(this.phase=`spawning`,this.timer=0))}prune(){for(let e of this.live)e.parent===null&&this.live.delete(e)}parseWave(e,t){let n=e,r=typeof n?.prefab==`string`?n.prefab:``;if(r===``)throw new L(`PROP_TYPE_MISMATCH`,`WaveSpawner on '${this.node.getPath()}': wave ${t} needs a "prefab" template path.`,{prop:`waves`});return{prefab:r,count:typeof n?.count==`number`?n.count:1,interval:typeof n?.interval==`number`?n.interval:.5,delayBefore:typeof n?.delayBefore==`number`?n.delayBefore:0}}},Projectile:bb,Buoyancy:Ey,FloatAway:Jy};function Tb(e){let t=e?.replace??!0;for(let[e,n]of Object.entries(wb))St(e,n,{replace:t})}function Eb(e,t){let n=e.shape;if(n!==void 0){if(e.oneWay!==void 0&&typeof e.oneWay!=`boolean`)throw new L(`BAD_FORMAT`,`Collider on '${t}': "oneWay" must be a boolean (platforms you jump up through), got ${JSON.stringify(e.oneWay)}.`);if(n===`rect`){let n=e.size;if(!Array.isArray(n)||n.length!==2||n.some(e=>typeof e!=`number`))throw new L(`BAD_FORMAT`,`Collider on '${t}': rect needs "size": [width, height].`);return}if(n===`circle`){if(typeof e.radius!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${t}': circle needs "radius".`);return}if(n===`capsule`){if(typeof e.radius!=`number`||typeof e.height!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${t}': capsule needs "radius" and "height".`);return}throw new L(`BAD_FORMAT`,`Collider on '${t}': "shape" must be 'rect', 'circle', or 'capsule', got ${JSON.stringify(n)}.`)}}var Db=class extends Ft{static typeName=`Node2D`;static props={position:{default:[0,0]},rotation:{default:0},static:{default:!1},scale:{default:[1,1]},renderOrder:{default:0},orderGroup:{default:`default`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},visible:{default:!0}};static propAliases={zIndex:`renderOrder`};position=[0,0];rotation=0;static=!1;scale=[1,1];renderOrder=0;orderGroup=`default`;get effectiveRenderOrder(){return gn(this.orderGroup,this.renderOrder,this.tree?.engine?.orderGroups)}visible=!0;_object2D=null;_ensureObject2D(){return this._object2D||(this._object2D=this._createObject2D(),this._object2D.userData.incantoNode=this),this._object2D}_createObject2D(){return new Tc}_staticReady(e){return!0}_syncObject2D(e){let t=this._ensureObject2D();t.position.set(this.position[0]??0,-(this.position[1]??0),0),t.rotation.z=-As.degToRad(this.rotation),t.scale.set(this.scale[0]??1,this.scale[1]??1,1),t.visible=this.visible}free(){super.free(),this._object2D?.removeFromParent(),this._object2D=null}},Ob=class extends Db{static props={collider:{default:{},variants:{tag:`shape`,byTag:{rect:{shape:`rect`,size:[32,32]},circle:{shape:`circle`,radius:16},capsule:{shape:`capsule`,radius:12,height:32}}}},enabled:{default:!0}};static signals=[`triggerEnter`,`triggerExit`];_collider={};_colliderChanged=!1;_enabled=!0;_enabledChanged=!1;get collider(){return this._collider}set collider(e){this._collider=e,this._colliderChanged=!0}get enabled(){return this._enabled}set enabled(e){e!==this._enabled&&(this._enabled=e,this._enabledChanged=!0)}static validateJson(e){Eb(e.collider,e.name)}_physics=null},kb=class extends Ob{static typeName=`StaticBody2D`},Ab=class extends Ob{static typeName=`Area2D`},jb=class extends Ob{static typeName=`RigidBody2D`;static props={mass:{default:1},gravityScale:{default:1},fixedRotation:{default:!1},friction:{default:.5},restitution:{default:0},linearVelocity:{default:[0,0]}};mass=1;gravityScale=1;fixedRotation=!1;friction=.5;restitution=0;linearVelocity=[0,0]},Mb=class extends Ob{static typeName=`CharacterBody2D`;static props={velocity:{default:[0,0]},stickToGround:{default:!0},slopeLimitDeg:{default:45}};static propAliases={snapToGround:`stickToGround`};velocity=[0,0];stickToGround=!0;slopeLimitDeg=45;_grounded=!1;moveAndSlide(){if(!this._physics)throw new L(`TREE_VIOLATION`,this.collider.shape===void 0?`CharacterBody2D '${this.name}' has no collider — set a collider prop (physics skips collider-less bodies).`:`CharacterBody2D '${this.name}' has no physics world — await enablePhysics2D(engine) first.`);this._physics.moveAndSlide(this)}_onWall=0;_onCeiling=!1;isOnWall(){return this._onWall!==0}wallSide(){return this._onWall}isOnCeiling(){return this._onCeiling}isOnFloor(){return this._grounded}},Nb=new Set;function Pb(e){return Nb.add(e),()=>Nb.delete(e)}function Fb(e,t){return[...Nb].filter(n=>n.dimension===e&&(t===void 0||n.engine===t))}var Ib=`using deprecated parameters for the initialization function`;async function Lb(e,t=console){let n=t.warn;t.warn=(...e)=>{typeof e[0]==`string`&&e[0].includes(Ib)||n.apply(t,e)};try{await e()}finally{t.warn=n}}var Rb=class extends Db{static typeName=`Joint2D`;static props={type:{default:`revolute`,options:[`fixed`,`revolute`,`rope`,`spring`]},target:{default:``,nodePath:!0,required:!0},anchor:{default:[0,0]},targetAnchor:{default:[0,0]},length:{default:0},stiffness:{default:50},damping:{default:5}};type=`revolute`;target=``;anchor=[0,0];targetAnchor=[0,0];length=0;stiffness=50;damping=5;onEnterTree(){if(!(this.parent instanceof Ob))throw new L(`TREE_VIOLATION`,`Joint2D '${this.name}' must be a child of a physics body (its body A); parent is '${this.parent?.name??`none`}'.`);if(this.target===``)throw new L(`BAD_FORMAT`,`Joint2D '${this.name}' needs a "target" node path to the body it links to.`)}_resolveBodies(){let e=this.parent,t=this.getNodeOrNull(this.target);if(!(t instanceof Ob))throw new L(`NODE_NOT_FOUND`,`Joint2D '${this.name}': target '${this.target}' is not a physics body.`);return{a:e,b:t}}},Z=100,zb=Math.PI/180;async function Bb(e,t){let n=await Vg(()=>import(`./rapier-CEuLKeCu.js`),[],import.meta.url);return await Lb(()=>n.init()),new Vb(n,e,t)}var Vb=class{R;engine;debugDraw=!1;debugScope=null;dimension=`2d`;unregisterDebug;warnedNoCollider=new WeakSet;entries=new Map;byColliderHandle=new Map;world;events;kcc;disconnectScene;disconnect;lastDt=1/60;optsGravity;lastScene=null;constructor(e,t,n){this.R=e,this.engine=t,this.optsGravity=n?.gravity,this.simulate=n?.simulate??!0,this.lastScene=t.scene;let r=t.scene?.physics?.gravity,i=n?.gravity??r??[0,980];this.world=new e.World({x:(i[0]??0)/Z,y:(i[1]??0)/Z}),this.kcc=this.world.createCharacterController(.01),this.kcc.setUp({x:0,y:-1}),this.events=new e.EventQueue(!0),this.unregisterDebug=Pb(this),this.disconnect=t.fixedUpdated.connect(e=>this.step(e)),this.disconnectScene=t.sceneChanged.connect(()=>{t.scene&&this.syncBodies()}),this.syncBodies()}simulate;step(e){if(this.lastDt=e,!this.simulate){this.syncBodies(),this.poseFromTree();return}if(this.engine.scene!==this.lastScene&&(this.lastScene=this.engine.scene,!this.optsGravity)){let e=this.engine.scene?.physics?.gravity??[0,980];this.world.gravity={x:(e[0]??0)/Z,y:(e[1]??0)/Z}}this.syncBodies(),this.world.timestep=e,this.world.step(this.events);for(let[e,t]of this.entries){let n=t.body.translation();if(!t.body.isFixed()&&!(e instanceof Ab)){let[t,r]=Jb(e);e.position=[n.x*Z-t,n.y*Z-r]}if(e instanceof jb){e.fixedRotation||(e.rotation=t.body.rotation()/zb,t.lastRot=e.rotation);let n=t.body.linvel();e.linearVelocity=[n.x*Z,n.y*Z],t.lastVX=e.linearVelocity[0]??0,t.lastVY=e.linearVelocity[1]??0}let r=t.body.translation();t.lastX=r.x*Z,t.lastY=r.y*Z}this.events.drainCollisionEvents((e,t,n)=>{let r=this.byColliderHandle.get(e),i=this.byColliderHandle.get(t);if(!r||!i)return;let a=n?`triggerEnter`:`triggerExit`;try{r.emit(a,i),i.emit(a,r)}catch(e){Nt(this.engine,`error`,`incanto: error in a '${a}' handler (${r.name} ↔ ${i.name}):`,e)}})}moveAndSlide(e){let t=this.ensureEntry(e),n=e.velocity[1]??0;e.stickToGround&&n>=0?this.kcc.enableSnapToGround(.05):this.kcc.disableSnapToGround(),this.kcc.setMaxSlopeClimbAngle(e.slopeLimitDeg*zb);let r=0,i=0;if(t.ground&&t.ground._physics===this){let[e,n]=qb(t.ground);r=e-(t.groundX??e),i=n-(t.groundY??n)}else t.ground=null;let a={x:((e.velocity[0]??0)*this.lastDt+r)/Z*1,y:(n*this.lastDt+i)/Z*1},o=t.body.translation().y*Z+Gb(e);this.kcc.computeColliderMovement(t.collider,a,this.R.QueryFilterFlags.EXCLUDE_SENSORS,void 0,t=>{let r=this.byColliderHandle.get(t.handle);return!(r&&r!==e&&r.collider.oneWay===!0&&(n<0||o>Kb(r)+Wb))});let s=this.kcc.computedMovement(),c=t.body.translation();t.body.setNextKinematicTranslation({x:c.x+s.x,y:c.y+s.y}),e._grounded=this.kcc.computedGrounded(),e._onWall=0,e._onCeiling=!1;let l=this.kcc.numComputedCollisions();for(let t=0;t<l;t++){let n=this.kcc.computedCollision(t)?.normal1;n&&(Math.abs(n.y)>.7?e._grounded||(e._onCeiling=!0):Math.abs(n.x)>.7&&(e._onWall=n.x>0?-1:1))}if(e._grounded){let n=(c.x+s.x)*Z,r=(c.y+s.y)*Z+Gb(e)-2,i=this.castRay([n,r],[0,1],8,e);if(i?.node&&!(i.node instanceof Mb)){t.ground=i.node;let[e,n]=qb(i.node);t.groundX=e,t.groundY=n}else t.ground=null}else t.ground=null}debugLines(){if(!this.debugDraw)return null;let e=this.debugScope?this.scopedLines(this.debugScope):this.world.debugRender().vertices,t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n]*Z;return t}scopedLines(e){let t=[],n=[],r=e=>{let t=this.entries.get(e);t&&n.push(t.body);for(let t of e.children)r(t)};r(e);for(let t=e.parent;t&&n.length===0;t=t.parent){let e=this.entries.get(t);e&&n.push(e.body)}for(let e of n)for(let n=0;n<e.numColliders();n++){let r=e.collider(n);if(!r)continue;let i=r.translation(),a=r.rotation(),o=Math.cos(a),s=Math.sin(a),c=(e,n)=>{t.push(i.x+e*o-n*s,i.y+e*s+n*o)},l=(e,t,n,r)=>{c(e,t),c(n,r)},u=r.shape;if(u.halfExtents){let{x:e,y:t}=u.halfExtents;l(-e,-t,e,-t),l(e,-t,e,t),l(e,t,-e,t),l(-e,t,-e,-t)}else if(u.radius!==void 0){let e=u.radius,t=u.halfHeight??0;for(let n=0;n<24;n++){let r=n/24*Math.PI*2,i=(n+1)/24*Math.PI*2,a=e=>e>=0?t:-t;l(Math.cos(r)*e,Math.sin(r)*e+a(Math.sin(r)),Math.cos(i)*e,Math.sin(i)*e+a(Math.sin(i)))}t>0&&(l(-e,-t,-e,t),l(e,-t,e,t))}}return new Float32Array(t)}syncJoints(e){let t=this.R;if(e)for(let[e,t]of this.joints)this.jointSet.has(e)||(this.world.removeImpulseJoint(t,!0),this.joints.delete(e));for(let e of this.jointSet){if(this.joints.has(e))continue;let{a:n,b:r}=e._resolveBodies(),i=this.entries.get(n),a=this.entries.get(r);if(!i||!a)continue;let o={x:(e.anchor[0]??0)/Z,y:(e.anchor[1]??0)/Z},s={x:(e.targetAnchor[0]??0)/Z,y:(e.targetAnchor[1]??0)/Z},c=e.length/Z;if(e.length===0&&(e.type===`rope`||e.type===`spring`)){let e=i.body.translation(),t=a.body.translation();c=Math.hypot(t.x-e.x,t.y-e.y)}let l;l=e.type===`fixed`?t.JointData.fixed(o,0,s,0):e.type===`rope`?t.JointData.rope(c,o,s):e.type===`spring`?t.JointData.spring(c,e.stiffness,e.damping,o,s):t.JointData.revolute(o,s),this.joints.set(e,this.world.createImpulseJoint(l,i.body,a.body,!0))}}castRay(e,t,n,r,i){let a=Math.hypot(t[0],t[1])||1,o=new this.R.Ray({x:e[0]/Z,y:e[1]/Z},{x:t[0]/a,y:t[1]/a}),s=r?this.entries.get(r)?.collider:void 0,c=i?.staticOnly?this.R.QueryFilterFlags.EXCLUDE_DYNAMIC|this.R.QueryFilterFlags.EXCLUDE_KINEMATIC:void 0,l=this.world.castRayAndGetNormal(o,n/Z,!0,c,void 0,s,void 0,e=>!e.isSensor());return l?{distance:l.timeOfImpact*Z,normal:[l.normal.x,l.normal.y],node:this.byColliderHandle.get(l.collider.handle)??null}:null}dispose(){this.disconnect(),this.disconnectScene(),this.unregisterDebug(),this.world.free()}lastStructure=-1;lastRoot=null;jointSet=new Set;joints=new Map;bodySet=new Set;poseFromTree(){for(let[e,t]of this.entries){let[n,r]=qb(e);t.body.setTranslation({x:n/Z,y:r/Z},!1),t.body.setRotation(e.rotation*zb,!1)}this.world.propagateModifiedBodyPositionsToColliders()}syncBodies(){let e=this.engine.scene;if(!e)return;let t=e.tree._structureVersion,n=e.root===this.lastRoot,r=t!==this.lastStructure||!n;if(r){let r=n?e.tree._structureSince(this.lastStructure):null;if(this.lastStructure=t,this.lastRoot=e.root,r){let t=!1;for(let{node:e,added:n}of r)e instanceof Ob&&(n?this.bodySet.add(e):this.bodySet.delete(e)),e instanceof Rb&&(t=!0);t&&(this.jointSet.clear(),Hb(e.root,this.jointSet))}else this.bodySet.clear(),Ub(e.root,this.bodySet),this.jointSet.clear(),Hb(e.root,this.jointSet)}let i=this.bodySet;for(let e of i){if(e.collider.shape===void 0){let t=this.entries.get(e);t&&(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null),this.warnedNoCollider.has(e)||(this.warnedNoCollider.add(e),Nt(this.engine,`warn`,`[incanto] '${e.name}' has no collider — physics skips it.`));continue}let t=this.entries.get(e);t&&e._colliderChanged&&(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null),this.ensureEntry(e)}if(this.syncJoints(r),r)for(let[e,t]of this.entries)i.has(e)||(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null)}ensureEntry(e){let t=this.entries.get(e),n=this.R;if(!t){let[r,i]=qb(e),a=r/Z,o=i/Z,s;s=e instanceof jb?n.RigidBodyDesc.dynamic():e instanceof Mb||e instanceof Ab?n.RigidBodyDesc.kinematicPositionBased():n.RigidBodyDesc.fixed(),s.setTranslation(a,o).setRotation(e.rotation*zb),e instanceof jb&&(s.setGravityScale(e.gravityScale),s.setLinvel((e.linearVelocity[0]??0)/Z,(e.linearVelocity[1]??0)/Z),e.fixedRotation&&s.lockRotations());let c=this.world.createRigidBody(s),l=Yb(n,e.collider,e.name);l.setActiveEvents(n.ActiveEvents.COLLISION_EVENTS),l.setActiveCollisionTypes(n.ActiveCollisionTypes.ALL),e instanceof Ab&&l.setSensor(!0),e instanceof jb&&l.setMass(e.mass).setFriction(e.friction).setRestitution(e.restitution);let u=this.world.createCollider(l,c);return t={body:c,collider:u,lastX:r,lastY:i,lastRot:e.rotation,lastVX:0,lastVY:0},this.entries.set(e,t),this.byColliderHandle.set(u.handle,e),e.enabled||(u.setEnabled(!1),c.setEnabled(!1)),e._colliderChanged=!1,e._enabledChanged=!1,e._physics=this,t}e._enabledChanged&&=(t.collider.setEnabled(e.enabled),t.body.setEnabled(e.enabled),!1);let[r,i]=qb(e);if((r!==t.lastX||i!==t.lastY)&&(t.body.setTranslation({x:r/Z,y:i/Z},!0),t.lastX=r,t.lastY=i),e.rotation!==t.lastRot&&(t.body.setRotation(e.rotation*zb,!0),t.lastRot=e.rotation),e instanceof jb){let n=e.linearVelocity[0]??0,r=e.linearVelocity[1]??0;(n!==t.lastVX||r!==t.lastVY)&&(t.body.setLinvel({x:n/Z,y:r/Z},!0),t.lastVX=n,t.lastVY=r)}return t}};function Hb(e,t){e instanceof Rb&&t.add(e);for(let n of e.children)Hb(n,t)}function Ub(e,t){e instanceof Ob&&t.add(e);for(let n of e.children)Ub(n,t)}var Wb=4;function Gb(e){let t=e.collider;return t.shape===`rect`?(t.size?.[1]??32)/2:t.shape===`capsule`?(t.height??32)/2+(t.radius??8):t.radius??16}function Kb(e){let[,t]=qb(e),n=e.collider;return t-(n.shape===`rect`?(n.size?.[1]??32)/2:n.shape===`capsule`?(n.height??32)/2+(n.radius??8):n.radius??16)}function qb(e){let t=0,n=0;for(let r=e;r;r=r.parent)r instanceof Db&&(t+=r.position[0]??0,n+=r.position[1]??0);return[t,n]}function Jb(e){let t=0,n=0;for(let r=e.parent;r;r=r.parent)r instanceof Db&&(t+=r.position[0]??0,n+=r.position[1]??0);return[t,n]}function Yb(e,t,n){Eb(t,n);let r=Xb(e,t,n),i=t.offset;return Array.isArray(i)&&r.setTranslation((i[0]??0)/Z,(i[1]??0)/Z),r}function Xb(e,t,n){let r=t.shape;if(r===`rect`){let r=t.size;if(!Array.isArray(r)||r.length!==2||r.some(e=>typeof e!=`number`))throw new L(`BAD_FORMAT`,`Collider on '${n}': rect needs "size": [width, height].`);return e.ColliderDesc.cuboid(r[0]/2/Z,r[1]/2/Z)}if(r===`circle`){if(typeof t.radius!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${n}': circle needs "radius".`);return e.ColliderDesc.ball(t.radius/Z)}if(r===`capsule`){if(typeof t.radius!=`number`||typeof t.height!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${n}': capsule needs "radius" and "height".`);return e.ColliderDesc.capsule(t.height/2/Z,t.radius/Z)}throw new L(`BAD_FORMAT`,`Collider on '${n}': "shape" must be 'rect', 'circle', or 'capsule', got ${JSON.stringify(r)}.`)}function Zb(e){let t=[];for(let n=2;n<=32;n++)e%n===0&&t.push(e/n);return t.sort((e,t)=>t-e).slice(0,6)}function Qb(e,t,n,r,i,a){if(!r||!i||!t||!n)return null;if(r%t!==0||i%n!==0){let a=[];if(r%t!==0){let e=Zb(r);a.push(`${r} px wide is not a whole number of ${t} px frames`+(e.length>0?` (${e.join(`, `)} would divide it)`:``))}if(i%n!==0){let e=Zb(i);a.push(`${i} px tall is not a whole number of ${n} px frames`+(e.length>0?` (${e.join(`, `)} would divide it)`:``))}return`[incanto] spritesheet '${e}' does not fit its frame size: ${a.join(`; `)}. Every row after the first is cut off centre.`}if(a!==void 0){let o=r/t*(i/n);if(a>=o)return`[incanto] spritesheet '${e}' has ${o} frames (0–${o-1}), and an animation asks for frame ${a}. Those frames draw whatever is at the wrong end of the sheet.`}return null}var $b=new _d(1,1),ex=class extends Db{static typeName=`Sprite2D`;static props={texture:{default:``,asset:{kind:`texture`,refOnly:!0}},anchor:{default:[.5,.5]},flipX:{default:!1},flipY:{default:!1},tint:{default:`#ffffff`},opacity:{default:1}};texture=``;anchor=[.5,.5];flipX=!1;flipY=!1;tint=`#ffffff`;opacity=1;quadMesh=null;_quad(){return this.quadMesh||(this.quadMesh=new iu($b,new Kl({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_createObject2D(){return super._createObject2D()}resolveTexture(e){if(!this.texture||!e)return null;let t=e.getTexture(this.texture),n=t.image;return!n?.width||!n.height?null:{texture:t,width:n.width,height:n.height}}_staticReady(e){return this.texture===``||this.resolveTexture(e)!==null}_syncObject2D(e){super._syncObject2D(e);let t=this._quad(),n=t.material,r=this.resolveTexture(e);if(!r){t.visible=!1;return}t.visible=!0,n.map!==r.texture&&(n.map=r.texture,n.needsUpdate=!0);let i=r.width,a=r.height;t.scale.set(this.flipX?-i:i,this.flipY?-a:a,1);let o=this.anchor[0]??.5,s=this.anchor[1]??.5;t.position.set((.5-o)*i,(s-.5)*a,0),t.renderOrder=this.effectiveRenderOrder,n.color.set(this.tint),n.opacity=this.opacity}},tx=class extends ex{static typeName=`AnimatedSprite2D`;static signals=[`animationFinished`];static props={sheet:{default:``,asset:{kind:`spritesheet`,refOnly:!0}},animations:{default:{}},autoplay:{default:``}};sheet=``;animations={};autoplay=``;playing=!1;currentFrame=0;currentAnimation=``;frameList=[];frameIndex=0;frameTime=0;currentDef=null;ownTexture=null;loadedSheetRef=``;play(e){let{name:t,def:n}=Zi(this.animations,e,this.name);this.currentAnimation=t,this.currentDef=n,this.frameList=$i(n.frames,t),this.frameIndex=0,this.currentFrame=this.frameList[0]??0,this.frameTime=0,this.playing=!0}stop(){this.playing=!1}onReady(){Qi(this.animations,this.name),this.autoplay&&this.play(this.autoplay)}update(e){if(!this.playing||this.currentAnimation===``)return;let t=this.currentDef;if(!t||!Number.isFinite(t.fps)||t.fps<=0)return;let n=1/t.fps;for(this.frameTime+=e;this.frameTime>=n;)if(this.frameTime-=n,this.frameIndex+=1,this.frameIndex>=this.frameList.length)if(t.loop)this.frameIndex=0;else{this.frameIndex=this.frameList.length-1,this.playing=!1,this.emit(`animationFinished`,this.currentAnimation);break}this.currentFrame=this.frameList[this.frameIndex]??0}gridChecked=``;checkGrid(e,t,n,r,i){if(this.gridChecked===e)return;this.gridChecked=e;let a=0;for(let[e,t]of Object.entries(this.animations))if(typeof t!=`string`)try{for(let n of $i(t.frames,e))n>a&&(a=n)}catch{return}let o=Qb(e,t,n,r,i,a);o&&Nt(this.tree?.engine??null,`error`,o)}resolveTexture(e){if(!this.sheet||!e)return null;let t=e.getSheet(this.sheet);this.loadedSheetRef!==this.sheet&&(this.ownTexture=t.texture.clone(),this.ownTexture.needsUpdate=!0,this.loadedSheetRef=this.sheet);let n=this.ownTexture,r=t.texture.image;if(!r?.width||!r.height)return null;this.checkGrid(this.sheet,t.frameWidth,t.frameHeight,r.width,r.height);let i=Math.max(1,Math.floor(r.width/t.frameWidth)),a=this.currentFrame%i,o=Math.floor(this.currentFrame/i);return n.repeat.set(t.frameWidth/r.width,t.frameHeight/r.height),n.offset.set(a*t.frameWidth/r.width,1-(o+1)*t.frameHeight/r.height),{texture:n,width:t.frameWidth,height:t.frameHeight}}},nx=class extends Db{static typeName=`Camera2D`;static props={follow:{default:``,nodePath:!0},smoothing:{default:0},zoom:{default:1},limits:{default:[]},current:{default:!1}};follow=``;smoothing=0;zoom=1;limits=[];current=!1;get effectiveZoom(){return Math.max(.01,this.zoom)}update(e){if(!this.follow)return;let t=this.getNodeOrNull(this.follow);if(!(t instanceof Db))return;let[n=0,r=0]=Ly(t),[i=0,a=0]=Ly(this),o=Math.min(Math.max(this.smoothing,0),.99),s=o<=0?1:1-o**(e*60),[c=0,l=0]=Ry(this,[i+(n-i)*s,a+(r-a)*s]);this.position=[c,l]}clampedCenter(e,t){let n=Ly(this),r=n[0]??0,i=n[1]??0;if(this.limits.length!==0&&this.limits.length!==4)throw new L(`BAD_FORMAT`,`Camera2D '${this.name}' limits must be [] or [minX,minY,maxX,maxY], got length ${this.limits.length}.`);if(this.limits.length===4){let[n,a,o,s]=this.limits,c=e/(2*this.effectiveZoom),l=t/(2*this.effectiveZoom);r=rx(r,n+c,o-c),i=rx(i,a+l,s-l)}return{x:r,y:i}}};function rx(e,t,n){return t>n?(t+n)/2:Math.min(n,Math.max(t,e))}var ix=class extends Ft{static typeName=`CharacterController2D`;static props={mode:{default:`platformer`,options:[`platformer`,`topDown`]},maxSpeed:{default:220},jumpHeight:{default:64},moveAction:{default:`move`},jumpAction:{default:`jump`},coyoteSeconds:{default:0},jumpBufferSeconds:{default:0},jumpCutMultiplier:{default:1},maxJumps:{default:1},dashSpeed:{default:0},dashSeconds:{default:.15},dashAction:{default:`dash`},wallSlideSpeed:{default:0},wallJumpImpulse:{default:[0,0]}};static signals=[`movementStateChanged`];mode=`platformer`;maxSpeed=220;jumpHeight=64;moveAction=`move`;jumpAction=`jump`;coyoteSeconds=0;jumpBufferSeconds=0;jumpCutMultiplier=1;maxJumps=1;dashSpeed=0;dashSeconds=.15;dashAction=`dash`;wallSlideSpeed=0;wallJumpImpulse=[0,0];state=`idle`;coyoteLeft=0;bufferLeft=0;jumpsUsed=0;dashLeft=0;dashDir=1;rising=!1;onReady(){if(!(this.parent instanceof Mb))throw new L(`TREE_VIOLATION`,`CharacterController2D '${this.name}' must be a child of a CharacterBody2D (parent is '${this.parent?.name??`none`}').`);if(this.mode!==`platformer`&&this.mode!==`topDown`)throw new L(`PROP_TYPE_MISMATCH`,`CharacterController2D.mode must be 'platformer' or 'topDown', got '${this.mode}'.`)}fixedUpdate(e){let t=this.tree?.engine;if(!t?.scene)return;let n=this.parent;if(!(n instanceof Mb))return;let r=t.input,i=r.getVector(this.moveAction);if(this.mode===`topDown`){n.velocity=[i.x*this.maxSpeed,i.y*this.maxSpeed],n.moveAndSlide();return}let a=t.scene.physics?.gravity?.[1]??980,o=n.isOnFloor(),s=-Math.sqrt(2*a*this.jumpHeight);if(this.dashLeft>0){this.dashLeft-=e,n.velocity[0]=this.dashDir*this.dashSpeed,n.velocity[1]=0,n.moveAndSlide(),this.setState(`dash`);return}if(this.dashSpeed>0&&r.justPressed(this.dashAction)){this.dashLeft=this.dashSeconds,this.dashDir=i.x===0?this.dashDir:Math.sign(i.x),n.velocity[0]=this.dashDir*this.dashSpeed,n.velocity[1]=0,n.moveAndSlide(),this.setState(`dash`);return}n.velocity[0]=i.x*this.maxSpeed,o?(this.coyoteLeft=this.coyoteSeconds,this.jumpsUsed=0):(this.coyoteLeft=Math.max(0,this.coyoteLeft-e),this.coyoteLeft<=0&&this.jumpsUsed===0&&(this.jumpsUsed=1)),r.justPressed(this.jumpAction)?this.bufferLeft=Math.max(this.jumpBufferSeconds,0):this.bufferLeft=Math.max(0,this.bufferLeft-e);let c=this.bufferLeft>0||r.justPressed(this.jumpAction),l=this.wallSlideSpeed>0||this.wallJumpImpulse.some(e=>e!==0)?n.isOnWall():!1;if(c&&l&&!o&&this.wallJumpImpulse.some(e=>e!==0)){let e=-n.wallSide();n.velocity[0]=e*(this.wallJumpImpulse[0]??0),n.velocity[1]=-(this.wallJumpImpulse[1]??0),this.bufferLeft=0,this.rising=!0,this.jumpsUsed=1}else c&&(o||this.coyoteLeft>0||this.jumpsUsed<this.maxJumps)?(n.velocity[1]=s,this.bufferLeft=0,this.coyoteLeft=0,this.rising=!0,this.jumpsUsed=o?1:this.jumpsUsed+1):o?(n.velocity[1]=20,this.rising=!1):(n.velocity[1]=(n.velocity[1]??0)+a*e,this.rising&&this.jumpCutMultiplier<1&&!r.isPressed(this.jumpAction)&&(n.velocity[1]=(n.velocity[1]??0)*this.jumpCutMultiplier,this.rising=!1),(n.velocity[1]??0)>=0&&(this.rising=!1),this.wallSlideSpeed>0&&l&&(n.velocity[1]??0)>this.wallSlideSpeed&&(n.velocity[1]=this.wallSlideSpeed));n.isOnCeiling()&&(n.velocity[1]??0)<0&&(n.velocity[1]=0,this.rising=!1),n.moveAndSlide();let u=n.velocity[1]??0;this.wallSlideSpeed>0&&!n.isOnFloor()&&n.isOnWall()&&u>0?this.setState(`wallSlide`):n.isOnFloor()?this.setState(Math.abs(i.x)>.01?`run`:`idle`):this.setState(u<0?`jump`:`fall`)}setState(e){e!==this.state&&(this.state=e,this.emit(`movementStateChanged`,e))}},ax=new _d(1,1),ox=class extends Db{static typeName=`ColorRect2D`;static props={size:{default:[100,100]},color:{default:`#ffffff`},opacity:{default:1},anchor:{default:[.5,.5]}};size=[100,100];color=`#ffffff`;opacity=1;anchor=[.5,.5];quadMesh=null;_quad(){return this.quadMesh||(this.quadMesh=new iu(ax,new Kl({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_syncObject2D(e){super._syncObject2D(e);let t=this._quad(),n=this.size[0]??0,r=this.size[1]??0;t.visible=n>0&&r>0&&this.opacity>0,t.scale.set(n,r,1);let i=this.anchor[0]??.5,a=this.anchor[1]??.5;t.position.set((.5-i)*n,(a-.5)*r,0),t.renderOrder=this.effectiveRenderOrder;let o=t.material;o.color.set(this.color),o.opacity=this.opacity}},sx=new _d(1,1),cx=class extends Db{static typeName=`Label`;static props={text:{default:``},fontSize:{default:16},color:{default:`#ffffff`},font:{default:`monospace`},align:{default:`left`},opacity:{default:1,range:{min:0,max:1}}};text=``;fontSize=16;color=`#ffffff`;font=`monospace`;align=`left`;opacity=1;quadMesh=null;canvas=null;lastKey=``;_quad(){return this.quadMesh||(this.quadMesh=new iu(sx,new Kl({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_syncObject2D(e){super._syncObject2D(e);let t=this._quad(),n=Qe(this,this.text);if(typeof document>`u`||n===``){t.visible=!1;return}let r=`${n}\0${this.fontSize}\0${this.color}\0${this.font}\0${this.align}`;r!==this.lastKey&&(this.lastKey=r,this.rasterize()),t.visible=this.opacity>0,t.material.opacity=this.opacity,t.renderOrder=this.effectiveRenderOrder}rasterize(){let e=Qe(this,this.text),t=Math.min(globalThis.devicePixelRatio??1,2);this.canvas??=document.createElement(`canvas`);let n=this.canvas.getContext(`2d`);if(!n)return;let r=`${this.fontSize*t}px ${this.font}`;n.font=r;let i=n.measureText(e),a=Math.max(1,Math.ceil(i.width)),o=Math.ceil(this.fontSize*t*1.4);this.canvas.width=a,this.canvas.height=o,n.font=r,n.fillStyle=this.color,n.textBaseline=`middle`,n.fillText(e,0,o/2);let s=this._quad(),c=s.material;c.map?.dispose();let l=new sd(this.canvas);l.colorSpace=Ro,c.map=l,c.needsUpdate=!0;let u=a/t,d=o/t;s.scale.set(u,d,1);let f=this.align===`center`?.5:+(this.align===`right`);s.position.set((.5-f)*u,0,0)}free(){let e=this.quadMesh;if(e){let t=e.material;t.map?.dispose(),t.dispose(),e.removeFromParent(),this.quadMesh=null}this.canvas=null,super.free()}},lx=new _d(1,1),ux=class e extends Db{orderGroup=`effects`;static typeName=`Particles2D`;static signals=[`finished`];static props={orderGroup:{default:`effects`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},preset:{default:`custom`,options:[`custom`,...wr]},emitting:{default:!0},worldSpace:{default:!1},rate:{default:40},burst:{default:0},lifetime:{default:[.6,1.2]},speed:{default:[40,120]},directionDeg:{default:-90},spreadDeg:{default:30},gravity:{default:[0,0]},drag:{default:0},sizeStart:{default:8},sizeEnd:{default:2},colorStart:{default:`#ffffff`},colorEnd:{default:`#ffffff`},paletteColors:{default:[]},alphaStart:{default:1},alphaEnd:{default:0},shimmer:{default:0},blend:{default:`add`,options:[`add`,`normal`]},maxParticles:{default:256}};preset=`custom`;emitting=!0;worldSpace=!1;rate=40;burst=0;lifetime=[.6,1.2];speed=[40,120];directionDeg=-90;spreadDeg=30;gravity=[0,0];drag=0;sizeStart=8;sizeEnd=2;colorStart=`#ffffff`;colorEnd=`#ffffff`;paletteColors=[];alphaStart=1;alphaEnd=0;shimmer=0;blend=`add`;maxParticles=256;static validateJson(e){let t=e;if(t.preset!==`custom`&&!wr.includes(t.preset))throw new L(`BAD_FORMAT`,`Particles2D '${e.name}' preset must be 'custom' or one of [${wr.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:wr});if(t.blend!==`add`&&t.blend!==`normal`)throw new L(`BAD_FORMAT`,`Particles2D '${e.name}' blend must be 'add' or 'normal', got '${t.blend}'.`,{prop:`blend`,validOptions:[`add`,`normal`]})}sim=null;bursted=!1;finishedEmitted=!1;_ensureSim(){if(!this.sim){Tr(this,this.preset,ct(e.typeName));let t=this.tree?.engine?.rng??new Ee(4660);this.sim=new Dr({rate:this.emitting?this.rate:0,lifetime:[this.lifetime[0]??1,this.lifetime[1]??1],speed:[this.speed[0]??0,this.speed[1]??0],directionDeg:this.directionDeg,spreadDeg:this.spreadDeg,gravity:[this.gravity[0]??0,this.gravity[1]??0,0],drag:this.drag,maxParticles:this.maxParticles},t)}return this.sim}get aliveCount(){return this.sim?.count??0}particles(){let e=[];return this.sim?.forEach(t=>{e.push({...t})}),e}lastWorld=null;wasEmitting=!1;update(e){let t=this._ensureSim();this.holdWorldSpace(t),t.setRate(this.emitting?this.rate:0),this.burst>0&&!this.bursted&&(this.emitting||this.armedByReplay)&&(this.bursted=!0,this.armedByReplay=!1,t.burst(this.burst),this.report(`burst`,this.burst));let n=this.emitting&&this.rate>0;n!==this.wasEmitting&&(this.wasEmitting=n,n&&this.report(`emit`,this.rate)),t.update(e),(!this.emitting||this.rate===0)&&this.bursted&&t.done&&!this.finishedEmitted&&(this.finishedEmitted=!0,this.emit(`finished`))}holdWorldSpace(e){if(!this.worldSpace){this.lastWorld=null;return}let t=0,n=0;for(let e=this;e;e=e.parent)e instanceof Db&&(t+=e.position[0]??0,n+=e.position[1]??0);let r=this.lastWorld;r&&e.translateAll(r[0]-t,r[1]-n,r[2]-0),this.lastWorld=[t,n,0]}meshKey=``;free(){this.mesh&&=(this.mesh.removeFromParent(),dx(this.mesh),null),super.free()}report(e,t){let n=this.tree?.engine;n?.effects.record({kind:e,name:this.preset,from:this.getPath(),amount:t,at:n.time})}replay(){this.bursted=!1,this.finishedEmitted=!1,this.armedByReplay=!0}armedByReplay=!1;mesh=null;paletteCache=[];paletteCacheKey=``;refreshPalette(){let e=this.paletteColors;if(e.length===0)return null;let t=e.join(`|`);if(t!==this.paletteCacheKey){this.paletteCacheKey=t;for(let t=0;t<e.length;t++){let n=this.paletteCache[t];n||(n=new q,this.paletteCache[t]=n),n.set(e[t])}this.paletteCache.length=e.length}return this.paletteCache}_syncObject2D(e){super._syncObject2D(e);let t=this._ensureSim(),n=`${this.maxParticles}|${this.blend}`;if(!this.mesh||this.meshKey!==n){this.mesh&&(this.mesh.removeFromParent(),dx(this.mesh)),this.meshKey=n;let e=new Kl({transparent:!0,depthWrite:!1,blending:this.blend===`add`?2:1});this.mesh=new Au(lx,e,this.maxParticles),this.mesh.instanceMatrix.setUsage(Wo),this.mesh.frustumCulled=!1,this._ensureObject2D().add(this.mesh)}let r=this.mesh,i=this.refreshPalette(),a=i?null:px.set(this.colorStart),o=mx.set(this.colorEnd),s=this.shimmer,c=0;t.forEach(e=>{let t=this.sizeStart+(this.sizeEnd-this.sizeStart)*e.t;fx.makeScale(t,t,1),fx.setPosition(e.x,-e.y,0),r.setMatrixAt(c,fx);let n=i?i[Math.floor(e.seed*i.length)]:a,l=Math.max(0,this.alphaStart+(this.alphaEnd-this.alphaStart)*e.t);s>0&&(l*=.5+.5*Math.sin(2*Math.PI*(e.age*s+e.seed))),hx.copy(n).lerp(o,e.t).multiplyScalar(l),r.setColorAt(c,hx),c+=1}),r.count=c,r.instanceMatrix.needsUpdate=!0,r.instanceColor&&(r.instanceColor.needsUpdate=!0),r.renderOrder=this.effectiveRenderOrder}};function dx(e){e.dispose();let t=e.material;for(let e of Array.isArray(t)?t:[t])e.dispose()}var fx=new K,px=new q,mx=new q,hx=new q;function gx(e,t){let n=[],r=0;for(let i of e){let e=[];if(typeof i==`string`)for(let n of i){let r=t[n];if(r!==void 0)e.push(r);else if(n===`.`||n===` `)e.push(-1);else if(n>=`0`&&n<=`9`)e.push(n.charCodeAt(0)-48);else throw new L(`BAD_FORMAT`,`TileMap2D: unknown tile char '${n}' — add it to "legend" (char → tile index), or use '.'/' ' for empty and digits 0-9.`)}else for(let t of i)e.push(t);r=Math.max(r,e.length),n.push(e)}for(let e of n)for(;e.length<r;)e.push(-1);return n}function _x(e,t){let n=e.length,r=n>0?e[0].length:0,i=e.map(e=>e.map(()=>!1)),a=(n,r)=>t.has(e[r][n]),o=[];for(let e=0;e<n;e++)for(let t=0;t<r;t++){if(!a(t,e)||i[e][t])continue;let s=1;for(;t+s<r&&a(t+s,e)&&!i[e][t+s];)s++;let c=1;grow:for(;e+c<n;){for(let n=0;n<s;n++)if(!a(t+n,e+c)||i[e+c][t+n])break grow;c++}for(let n=0;n<c;n++)for(let r=0;r<s;r++)i[e+n][t+r]=!0;o.push({x:t,y:e,w:s,h:c})}return o}var vx=class extends Db{static typeName=`TileMap2D`;static props={texture:{default:``,asset:{kind:`texture`,refOnly:!0}},tileSize:{default:32},columns:{default:0},cells:{default:[]},legend:{default:{}},solid:{default:[]},opacity:{default:1}};texture=``;tileSize=32;columns=0;_cells=[];_legend={};_solid=[];geometryDirty=!0;gridChecked=``;collidersDirty=!0;get cells(){return this._cells}set cells(e){this._cells=e,this.geometryDirty=!0,this.collidersDirty=!0}get legend(){return this._legend}set legend(e){this._legend=e,this.geometryDirty=!0,this.collidersDirty=!0}get solid(){return this._solid}set solid(e){this._solid=e,this.collidersDirty=!0}opacity=1;tileMesh=null;builtColumns=0;builtRows=0;static validateJson(e){let t=e;gx(t._cells,t._legend)}grid(){return gx(this._cells,this._legend)}onReady(){this.rebuildColliders()}update(e){this.collidersDirty&&this.rebuildColliders()}rebuildColliders(){this.collidersDirty=!1;for(let e of[...this.children])e.name.startsWith(`__tileSolid`)&&e.free();if(this._solid.length===0)return;let e=this.tileSize;_x(this.grid(),new Set(this._solid)).forEach((t,n)=>{let r=new kb(`__tileSolid${n}`);r.position=[(t.x+t.w/2)*e,(t.y+t.h/2)*e],r.collider={shape:`rect`,size:[t.w*e,t.h*e]},this.addChild(r)})}_mesh(){return this.tileMesh||(this.tileMesh=new iu(new Y,new Kl({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.tileMesh)),this.tileMesh}_staticReady(e){return this.texture===``||!e?this.texture===``:!!e.getTexture(this.texture).image?.width}_syncObject2D(e){super._syncObject2D(e);let t=this._mesh(),n=t.material;if(!this.texture||!e){t.visible=!1;return}let r=e.getTexture(this.texture),i=r.image;if(!i?.width||!i.height){t.visible=!1;return}if(t.visible=this.opacity>0,t.renderOrder=this.effectiveRenderOrder,n.opacity=this.opacity,n.map!==r&&(r.magFilter=fa,n.map=r,n.needsUpdate=!0,this.geometryDirty=!0),this.gridChecked!==this.texture){this.gridChecked=this.texture;let e=Qb(this.texture,this.tileSize,this.tileSize,i.width,i.height);e&&Nt(this.tree?.engine??null,`error`,e)}let a=this.columns>0?this.columns:Math.max(1,Math.floor(i.width/this.tileSize)),o=Math.max(1,Math.floor(i.height/this.tileSize));(a!==this.builtColumns||o!==this.builtRows)&&(this.geometryDirty=!0),this.geometryDirty&&(this.geometryDirty=!1,this.builtColumns=a,this.builtRows=o,this.buildGeometry(t.geometry,a,o))}buildGeometry(e,t,n){let r=this.grid(),i=this.tileSize,a=[],o=[],s=[];for(let e=0;e<r.length;e++){let c=r[e];for(let r=0;r<c.length;r++){let l=c[r];if(l<0)continue;let u=r*i,d=u+i,f=-(e*i),p=-((e+1)*i),m=a.length/3;a.push(u,f,0,d,f,0,d,p,0,u,p,0);let h=l%t,g=Math.floor(l/t),_=h/t,v=(h+1)/t,y=1-g/n,b=1-(g+1)/n;o.push(_,y,v,y,v,b,_,b),s.push(m,m+2,m+1,m,m+3,m+2)}}e.setAttribute(`position`,new J(new Float32Array(a),3)),e.setAttribute(`uv`,new J(new Float32Array(o),2)),e.setIndex(s),e.computeBoundingSphere()}get renderedTileCount(){let e=this.tileMesh?.geometry.getAttribute(`position`);return e?e.count/4:0}free(){this.tileMesh?.geometry.dispose(),super.free()}},yx=[`top-left`,`top`,`top-right`,`left`,`center`,`right`,`bottom-left`,`bottom`,`bottom-right`],bx=class extends Ft{static typeName=`UILayer`;static props={anchor:{default:`top-left`,options:yx}};anchor=`top-left`;group=null;_ensureGroup(){return this.group||(this.group=new Ec,this.group.userData.incantoNode=this),this.group}static validateJson(e){let t=e.anchor;if(!yx.includes(t))throw new L(`BAD_FORMAT`,`UILayer '${e.name}' anchor must be one of [${yx.join(`, `)}], got '${t}'.`,{prop:`anchor`,validOptions:yx})}_anchorOrigin(e,t){let n=this.anchor;return{x:n.includes(`right`)?e:n===`top`||n===`center`||n===`bottom`?e/2:0,y:n.includes(`bottom`)?t:n===`left`||n===`center`||n===`right`?t/2:0}}};function xx(){Or(),z(Db),z(ex),z(ox),z(ux),z(tx),z(nx),z(cx),z(bx),z(kb),z(jb),z(Ab),z(Mb),z(ix),z(Rb),z(vx)}function Sx(e,t,n){return{x:(t-e.cx)*e.zoom+e.w/2,y:(n-e.cy)*e.zoom+e.h/2}}function Cx(e,t,n){return{x:(t-e.w/2)/e.zoom+e.cx,y:(n-e.h/2)/e.zoom+e.cy}}function wx(e,t,n){return{x:e.offsetX+t/e.uiW*e.contentW,y:e.offsetY+n/e.uiH*e.contentH}}function Tx(e,t,n){return{x:(t-e.offsetX)/e.contentW*e.uiW,y:(n-e.offsetY)/e.contentH*e.uiH}}var Ex=new Xc,Dx=new W,Ox=12,kx=new Float32Array(16);function Ax(e){if(!(e instanceof Db))return null;let t=e._ensureObject2D();t.updateWorldMatrix(!0,!0),Ex.setFromObject(t),Ex.getSize(Dx);let n,r,i,a;if(!Number.isFinite(Dx.x)||Dx.x===0&&Dx.y===0){let e=new W().setFromMatrixPosition(t.matrixWorld);n=e.x-Ox,i=e.x+Ox,r=e.y-Ox,a=e.y+Ox}else n=Ex.min.x-2,i=Ex.max.x+2,r=Ex.min.y-2,a=Ex.max.y+2;let o=[n,r,i,r,i,r,i,a,i,a,n,a,n,a,n,r];return kx.set(o),kx}function jx(){return{visited:new Set,cameras:[],emitters:[]}}function Mx(e){return e.spatial===!0&&typeof e._setSpatialPose==`function`}function Nx(e,t,n,r,i,a,o){let s=a??jx();s.visited.clear(),s.cameras.length=0,s.emitters.length=0,Rx(e,t,n,!1,s.visited,s.cameras,s.emitters,r,i,o?.ignoreStatic===!0),zx(t,s.visited),zx(n,s.visited);let c=null;for(let e=0;e<s.cameras.length;e++){let t=s.cameras[e];if(t.current){c=t;break}}return c||=s.cameras[0]??null,Lx(s.emitters,c),{activeCamera:c}}var Px=new W,Fx=new W,Ix=new W;function Lx(e,t){if(e.length===0||!t)return;let n=t._ensureObject2D();n.updateWorldMatrix(!0,!1),n.getWorldPosition(Fx),Ix.set(0,1,0).applyQuaternion(n.quaternion);let r={position:[Fx.x,Fx.y,0],forward:[0,0,-1],up:[Ix.x,Ix.y,Ix.z]};for(let{node:t,parent:n}of e)n.updateWorldMatrix(!0,!1),n.getWorldPosition(Px),t._setSpatialPose({position:[Px.x,Px.y,0],listener:r})}function Rx(e,t,n,r,i,a,o,s,c,l){let u=t,d=r;if(e instanceof Db&&!(e instanceof bx)){let t=e._ensureObject2D();if(e.static&&!l&&t.userData.incantoStaticSynced===!0){t.userData.incantoStatic=!0,i.add(t);return}}if(e instanceof bx){let t=e._ensureGroup();t.parent!==n&&n.add(t);let r=c?e._anchorOrigin(c.width,c.height):{x:0,y:0};t.position.set(r.x,-r.y,0),i.add(t),d=!0,u=t}else if(e instanceof Db){let n=e._ensureObject2D();n.parent!==t&&t.add(n),e._syncObject2D(s),i.add(n),e instanceof nx&&!r&&a.push(e),u=n}else Mx(e)&&o.push({node:e,parent:u});for(let t of e.children)Rx(t,u,n,d,i,a,o,s,c,l);if(e instanceof Db&&!(e instanceof bx)){let t=e._ensureObject2D();e.static&&!l&&e._staticReady(s)?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}function zx(e,t){let n=e.children;for(let r=n.length-1;r>=0;r--){let i=n[r];i.userData.incantoNode&&!t.has(i)?e.remove(i):i.userData.incantoStatic!==!0&&zx(i,t)}}var Bx=120,Vx=class{viewOverride=null;webgl;captureFrame(){return new Promise((e,t)=>{this.pendingCaptures.push({resolve:e,reject:t}),setTimeout(()=>{if(this.pendingCaptures.length>0)try{this.render()}catch(e){let t=e instanceof Error?e:Error(String(e));for(let e of this.pendingCaptures.splice(0))e.reject(t)}},Bx)})}pendingCaptures=[];drainFrameCapture(){if(this.pendingCaptures.length===0)return;let e=this.pendingCaptures;this.pendingCaptures=[];try{let t=this.webgl.getContext(),n=this.webgl.domElement.width,r=this.webgl.domElement.height,i=new Uint8Array(n*r*4);this.webgl.setRenderTarget(null),t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,i);for(let e=0;e<Math.floor(r/2);e++){let t=e*n*4,a=(r-1-e)*n*4;for(let e=0;e<n*4;e++){let n=i[t+e];i[t+e]=i[a+e],i[a+e]=n}}for(let t of e)t.resolve({pixels:i,width:n,height:r})}catch(t){let n=t instanceof Error?t:Error(String(t));for(let t of e)t.reject(n)}}basePixelRatio=1;setRenderScale(e){let t=Number.isFinite(e)&&e>0?Math.min(2,Math.max(.25,e)):1;this.webgl.setPixelRatio(this.basePixelRatio*t)}worldScene=new Fc;syncScratch=jx();ignoreStatic=!1;uiScene=new Fc;worldCam=new Of(-1,1,1,-1,-1e3,1e3);uiCam=new Of(-1,1,1,-1,-1e3,1e3);engine;assets;loadedAssetScenes=new WeakSet;disconnect;canvas;constructor(e){this.canvas=e.canvas,this.engine=e.engine,this.assets=e.assets??new Eg(void 0,this.engine);let t=kr(e.engine.scene?.environment,{antialias:!0,pixelRatio:1,preserveDrawingBuffer:!1},globalThis.devicePixelRatio??1,e);this.webgl=new Tg({canvas:e.canvas,antialias:t.antialias,preserveDrawingBuffer:t.preserveDrawingBuffer}),this.webgl.info.autoReset=!1,this.engine.picker=(e,t)=>this.pick(e,t),this.basePixelRatio=t.pixelRatio,this.webgl.setPixelRatio(t.pixelRatio),this.webgl.info.autoReset=!1,this.debugLines=new Zu(new Y,new zu({color:`#00ff6e`,transparent:!0,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.worldScene.add(this.debugLines),this.selectionLines=new Zu(new Y,new zu({color:`#ffb020`,transparent:!0,depthTest:!1})),this.selectionLines.frustumCulled=!1,this.selectionLines.renderOrder=1e4,this.selectionLines.visible=!1,this.worldScene.add(this.selectionLines),this.disconnect=this.engine.updated.connect(()=>{let e=performance.now();this.render(),this.engine.noteRenderMs(performance.now()-e)})}debugLines;selectionLines;syncSelectionOutline(){let e=this.engine.debugSelection;e&&e.tree!==this.engine.scene?.tree&&(this.engine.debugSelection=null);let t=this.engine.debugSelection,n=t?Ax(t):null;if(this.selectionLines.visible=n!==null,!n)return;let r=new Float32Array(n.length/2*3);for(let e=0,t=0;e<n.length;e+=2,t+=3)r[t]=n[e],r[t+1]=n[e+1],r[t+2]=0;this.selectionLines.geometry.setAttribute(`position`,new J(r,3)),this.selectionLines.geometry.getAttribute(`position`).needsUpdate=!0}syncDebugLines(){let e=null;for(let t of Fb(`2d`,this.engine))if(e=t.debugLines(),e)break;if(this.debugLines.visible=e!==null,!e)return;let t=new Float32Array(e.length/2*3);for(let n=0,r=0;n<e.length;n+=2,r+=3)t[r]=e[n],t[r+1]=e[n+1],t[r+2]=0;this.debugLines.geometry.setAttribute(`position`,new J(t,3))}render(){let e=this.engine.scene;if(!e)return;this.webgl.info.reset(),this.syncDebugLines(),this.syncSelectionOutline(),e.assets&&!this.loadedAssetScenes.has(e)&&(this.assets.load(e.assets),this.loadedAssetScenes.add(e));let t=e.environment?.background;this.worldScene.background=typeof t==`string`?new q(t):null;let n=this.canvas.clientWidth||this.canvas.width,r=this.canvas.clientHeight||this.canvas.height,i=this.webgl.getSize(Ux);(i.x!==n||i.y!==r)&&this.webgl.setSize(n,r,!1);let a=this.viewOverride?null:Ir(e.viewport),o=a?Lr(n,r,a):null,s=o?o.viewW:n,c=o?o.viewH:r;this.lastUi={w:s,h:c};let{activeCamera:l}=Nx(e.root,this.worldScene,this.uiScene,this.assets,{width:s,height:c},this.syncScratch,{ignoreStatic:this.ignoreStatic}),u=a?{x:a.design[0]/2,y:a.design[1]/2}:{x:n/2,y:r/2},d=1;this.viewOverride?(u={x:this.viewOverride.cx,y:this.viewOverride.cy},d=this.viewOverride.zoom):l&&(u=l.clampedCenter(s,c),d=l.effectiveZoom);let f=o?.scale??1;this.lastView={cx:u.x,cy:u.y,zoom:d*f,w:n,h:r},this.lastViewport=o,o&&(o.offsetX>.5||o.offsetY>.5)?(this.webgl.setScissorTest(!1),this.webgl.setViewport(0,0,n,r),this.webgl.clear(),this.webgl.setViewport(o.offsetX,o.offsetY,o.contentW,o.contentH),this.webgl.setScissor(o.offsetX,o.offsetY,o.contentW,o.contentH),this.webgl.setScissorTest(!0)):(this.webgl.setScissorTest(!1),this.webgl.setViewport(0,0,n,r)),Hx(this.worldCam,u.x,u.y,s/d,c/d),Hx(this.uiCam,s/2,c/2,s,c),this.webgl.info.reset(),this.webgl.autoClear=!0,this.webgl.render(this.worldScene,this.worldCam),this.webgl.autoClear=!1,this.webgl.render(this.uiScene,this.uiCam),this.webgl.autoClear=!0,this.drainFrameCapture()}lastUi={w:1,h:1};lastViewport=null;lastView={cx:0,cy:0,zoom:1,w:1,h:1};view(){return{...this.lastView}}stats(){let e=this.webgl.info;return{triangles:e.render.triangles,drawCalls:e.render.calls,geometries:e.memory.geometries,textures:e.memory.textures}}worldFromScreen(e,t){return Cx(this.lastView,e,t)}screenFromWorld(e,t){return Sx(this.lastView,e,t)}pick(e,t){let{w:n,h:r}=this.lastView,i=this.lastViewport?.offsetX??0,a=this.lastViewport?.offsetY??0,o=this.lastViewport?.contentW??n,s=this.lastViewport?.contentH??r;return Gx.set((e-i)/o*2-1,-((t-a)/s*2-1)),this.hit(this.uiScene,this.uiCam)||this.hit(this.worldScene,this.worldCam)}hit(e,t){Kx.setFromCamera(Gx,t);let n=Kx.intersectObjects(e.children,!0),r=null;for(let e of n){let t=e.object;for(;t&&!t.userData.incantoNode;)t=t.parent;let n=t?.userData.incantoNode;if(!n)continue;let i=e.object.renderOrder??0;(!r||i>=r.order)&&(r={node:n,order:i})}return r?.node??null}isUiNode(e){let t=e._object2D??e._group??null;for(;t;){if(t===this.uiScene)return!0;t=t.parent}return!1}screenFromUi(e,t){return wx(this.uiView(),e,t)}uiFromScreen(e,t){return Tx(this.uiView(),e,t)}uiView(){return{offsetX:this.lastViewport?.offsetX??0,offsetY:this.lastViewport?.offsetY??0,contentW:this.lastViewport?.contentW??this.lastView.w,contentH:this.lastViewport?.contentH??this.lastView.h,uiW:this.lastUi.w,uiH:this.lastUi.h}}boundsOf(e){let t=e._object2D;if(!t||(qx.makeEmpty(),qx.expandByObject(t),qx.isEmpty())||(qx.getSize(Wx),Wx.x===0&&Wx.y===0))return null;let n=this.isUiNode(e)?(e,t)=>this.screenFromUi(e,t):(e,t)=>this.screenFromWorld(e,t),r=n(qx.min.x,-qx.max.y),i=n(qx.max.x,-qx.min.y);return{x:r.x,y:r.y,w:i.x-r.x,h:i.y-r.y}}dispose(){this.engine.picker&&(this.engine.picker=null),this.disconnect();for(let e of[this.worldScene,this.uiScene])e.traverse(e=>{let t=e;if(!t.isMesh)return;let n=Array.isArray(t.material)?t.material:[t.material];for(let e of n)e?.map?.dispose(),e?.dispose()});this.webgl.dispose()}};function Hx(e,t,n,r,i){e.position.set(t,-n,10),e.left=-r/2,e.right=r/2,e.top=i/2,e.bottom=-i/2,e.updateProjectionMatrix()}var Ux=new H,Wx=new W,Gx=new H,Kx=new rp,qx=new Xc;async function Jx(e){xx(),(e.gameplay??!0)&&Tb();for(let[t,n]of Object.entries(e.behaviors??{}))St(t,n,{replace:!0});let t=new Hn({seed:e.seed,fixedHz:e.fixedHz,...e._scheduler?{scheduler:e._scheduler}:{}}),n=Yx(e.scene),r=Ai(Yx(n),{resolveScene:e.resolveScene,engine:t});t.setScene(r);let i=null;(e.physics===!0||(e.physics??`auto`)===`auto`&&Xx(r.root))&&(i=await Bb(t));let a=[],o=e.keyboard??(typeof window<`u`?window:!1);if(o&&t.input.attachKeyboard(o),e.pointer){let n=typeof e.pointer==`object`?e.pointer.lockOnClick??!1:!1;t.input.attachPointer(e.canvas,{lockOnClick:n})}a.push(Zx(t,r.root,e.canvas)),a.push(t.settings.bindAudio(t.audio)),a.push(e_(t)),a.push(t.settings.bindLocale(t.locale)),e.pageGestures||Og(e.canvas);let s=e.touch??`auto`;if(s!==!1){let n=e.touchContainer??e.canvas.parentElement??null;if(n){let r={force:s===!0,...e._touchDoc?{doc:e._touchDoc}:{}},i=na(t,n,r),o=t.sceneChanged.connect(()=>{i?.dispose(),i=na(t,n,r)});a.push(()=>{o(),i?.dispose()})}}let c=e._rendererFactory?e._rendererFactory(t,e.canvas):new Vx({canvas:e.canvas,engine:t,...e.pixelRatio===void 0?{}:{pixelRatio:e.pixelRatio},...e.antialias===void 0?{}:{antialias:e.antialias}});a.push(t.settings.bindFrameCap(e=>{t.maxFps=e})),a.push(t.settings.bindRenderScale(e=>{c.setRenderScale?.(e)})),a.push(...Lg({engine:t,applyDrive:async e=>{let n=0,r=!0,i=()=>{r&&(n+=1,requestAnimationFrame(i))};typeof requestAnimationFrame==`function`&&requestAnimationFrame(i);for(let n of e)switch(n.kind){case`press`:t.input.pressAction(n.action);break;case`release`:t.input.releaseAction(n.action);break;case`vector`:t.input.setActionVector(n.action,n.x,n.y);break;case`key`:t.input.handleKey(n.code,n.down);break;case`pointer`:t.input.handlePointerMove(n.dx,n.dy);break;case`step`:await new Promise(e=>setTimeout(e,n.ms));break}return r=!1,n},captureFramePixels:()=>{let e=c.captureFrame;return e?e.call(c):Promise.reject(new L(`TREE_VIOLATION`,`this renderer cannot capture frames`))},rendererStats:()=>c.stats?.(),assetErrors:()=>[...c.assets?.errors()??[],...Dg(t.scene?.tree.root)]}));let l=e.debug??!1,u=e.editor??l,d=u===!0?{}:u||null,f={label:`✎ edit this scene`,run:async()=>{if(!d)return;let t=d.open??Zg,r=async t=>{await Jx({...e,scene:t})};await Qg(async()=>{p();try{await t({scene:n,play:r,exit:()=>r(n),...d.save?{save:d.save}:{},...d.library?{library:d.library===!0?Gg():d.library}:{}})}catch(e){console.error(`[incanto] could not open the editor:`,e),await r(n)}},`opening the editor…`)}};if(l){let n=e.touchContainer??e.canvas.parentElement??(typeof document<`u`?document.body:null);if(n){let{attachDebugOverlay:r}=await Vg(async()=>{let{attachDebugOverlay:e}=await import(`./debug-DWztJ5_y.js`);return{attachDebugOverlay:e}},[],import.meta.url),i=r(t,{container:n,statsSource:()=>c.stats?.()??{},...d?{actions:[f]}:{},...e._debugDoc?{doc:e._debugDoc}:{}});i&&a.push(()=>i.dispose())}}t.start();function p(){t_([i?[`physics`,()=>i?.dispose()]:null,[`app cleanups`,()=>{for(let e of a)e()}],[`engine`,()=>t.dispose()],[`renderer`,()=>c.dispose()]])}return{engine:t,scene:r,sourceJson:n,renderer:c,physics:i,pick(e,n){return t.picker?.(e,n)??null},async frame(e){let t=c.captureFrame;if(!t)throw new L(`TREE_VIOLATION`,`this renderer cannot capture frames`);let n=await t.call(c);return Ig(n.pixels,n.width,n.height,e)},assetErrors(){return[...c.assets?.errors()??[],...Dg(t.scene?.tree.root)]},stats(){return{triangles:0,drawCalls:0,geometries:0,textures:0,...t.stats(),...c.stats?.()}},openEditor:d?f.run:null,dispose:p}}function Yx(e){try{return structuredClone(e)}catch{throw new L(`BAD_FORMAT`,`createGame "scene" must be plain scene JSON (the imported *.scene.json object) — got something unclonable (a loaded Scene, class instances, or functions).`)}}function Xx(e){if(e instanceof Ob)return!0;for(let t of e.children)if(Xx(t))return!0;return!1}function Zx(e,t,n){let r=[],i=n;if(i.addEventListener&&r.push({target:i,type:`pointerdown`}),typeof window<`u`){let e=window;r.push({target:e,type:`keydown`}),r.push({target:e,type:`pointerdown`})}if(r.length===0)return()=>{};function a(){for(let e of r)e.target.removeEventListener?.(e.type,o)}function o(){e.sfx.unlock(),e.music.unlock();let n=!1,r=e=>{e instanceof Kn&&(e.retryPending(),e.pendingGesture&&(n=!0));for(let t of e.children)r(t)};r(t),n||a()}for(let e of r)e.target.addEventListener?.(e.type,o,{passive:!0});return a}var Qx=[[`run`,[`run`,`move`,`walk`]],[`jump`,[`jump`,`idle`]],[`fall`,[`fall`,`jump`,`idle`]],[`wallSlide`,[`wallSlide`,`idle`]],[`dash`,[`dash`,`run`,`move`,`idle`]]];function $x(e){let t=new Set(Object.keys(e));if(t.has(`idle`))for(let[n,r]of Qx){if(t.has(n))continue;let i=r.find(e=>e!==n&&t.has(e));i&&(e[n]=i)}}function eS(e,t){let n=e;if(typeof n?.frame?.width!=`number`||typeof n.frame.height!=`number`||!n.animations||Object.keys(n.animations).length===0)throw new L(`BAD_FORMAT`,`Library sprite metadata needs {frame: {width, height}, animations: {<name>: {start, end, frameRate, repeat}}} — got ${JSON.stringify(e).slice(0,120)}.`);let r={},i=null,a=null;for(let[e,t]of Object.entries(n.animations)){if(typeof t.start!=`number`||typeof t.end!=`number`||typeof t.frameRate!=`number`)throw new L(`BAD_FORMAT`,`Library animation '${e}' needs numeric start/end/frameRate, got ${JSON.stringify(t)}.`);let n=t.repeat===-1;r[e]={frames:[t.start,t.end],fps:t.frameRate,loop:n},i??=e,n&&a===null&&(a=e)}$x(r);let o=t.autoplay??a??i;return{asset:{type:`spritesheet`,url:t.url,frameWidth:n.frame.width,frameHeight:n.frame.height},props:{sheet:`$${t.assetKey}`,autoplay:o,animations:r}}}var tS=e({createGame2D:()=>Jx,enablePhysics2D:()=>Bb}),nS=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),rS=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),iS=class extends Tc{constructor(e){super(),this.weight=0,this.isBinary=!1,this.overrideBlink=`none`,this.overrideLookAt=`none`,this.overrideMouth=`none`,this._binds=[],this.name=`VRMExpression_${e}`,this.expressionName=e,this.type=`VRMExpression`,this.visible=!1}get binds(){return this._binds}get overrideBlinkAmount(){return this.overrideBlink===`block`?+(0<this.outputWeight):this.overrideBlink===`blend`?this.outputWeight:0}get overrideLookAtAmount(){return this.overrideLookAt===`block`?+(0<this.outputWeight):this.overrideLookAt===`blend`?this.outputWeight:0}get overrideMouthAmount(){return this.overrideMouth===`block`?+(0<this.outputWeight):this.overrideMouth===`blend`?this.outputWeight:0}get outputWeight(){return this.isBinary?+(this.weight>.5):this.weight}addBind(e){this._binds.push(e)}deleteBind(e){let t=this._binds.indexOf(e);t>=0&&this._binds.splice(t,1)}applyWeight(e){let t=this.outputWeight;t*=e?.multiplier??1,this.isBinary&&t<1&&(t=0),this._binds.forEach(e=>e.applyWeight(t))}clearAppliedWeight(){this._binds.forEach(e=>e.clearAppliedWeight())}};function aS(e,t,n){let r=e.parser.json,i=r.nodes?.[t];if(i==null)return console.warn(`extractPrimitivesInternal: Attempt to use nodes[${t}] of glTF but the node doesn't exist`),null;let a=i.mesh;if(a==null)return null;let o=r.meshes?.[a];if(o==null)return console.warn(`extractPrimitivesInternal: Attempt to use meshes[${a}] of glTF but the mesh doesn't exist`),null;let s=o.primitives.length,c=[];return n.traverse(e=>{c.length<s&&e.isMesh&&c.push(e)}),c}function oS(e,t){return rS(this,null,function*(){return aS(e,t,yield e.parser.getDependency(`node`,t))})}function sS(e){return rS(this,null,function*(){let t=yield e.parser.getDependencies(`node`),n=new Map;return t.forEach((t,r)=>{let i=aS(e,r,t);i!=null&&n.set(r,i)}),n})}var cS={Aa:`aa`,Ih:`ih`,Ou:`ou`,Ee:`ee`,Oh:`oh`,Blink:`blink`,Happy:`happy`,Angry:`angry`,Sad:`sad`,Relaxed:`relaxed`,LookUp:`lookUp`,Surprised:`surprised`,LookDown:`lookDown`,LookLeft:`lookLeft`,LookRight:`lookRight`,BlinkLeft:`blinkLeft`,BlinkRight:`blinkRight`,Neutral:`neutral`};function lS(e){return Math.max(Math.min(e,1),0)}var uS=class e{constructor(){this.blinkExpressionNames=[`blink`,`blinkLeft`,`blinkRight`],this.lookAtExpressionNames=[`lookLeft`,`lookRight`,`lookUp`,`lookDown`],this.mouthExpressionNames=[`aa`,`ee`,`ih`,`oh`,`ou`],this._expressions=[],this._expressionMap={}}get expressions(){return this._expressions.concat()}get expressionMap(){return Object.assign({},this._expressionMap)}get presetExpressionMap(){let e={},t=new Set(Object.values(cS));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)&&(e[n]=r)}),e}get customExpressionMap(){let e={},t=new Set(Object.values(cS));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)||(e[n]=r)}),e}copy(e){return this._expressions.concat().forEach(e=>{this.unregisterExpression(e)}),e._expressions.forEach(e=>{this.registerExpression(e)}),this.blinkExpressionNames=e.blinkExpressionNames.concat(),this.lookAtExpressionNames=e.lookAtExpressionNames.concat(),this.mouthExpressionNames=e.mouthExpressionNames.concat(),this}clone(){return new e().copy(this)}getExpression(e){return this._expressionMap[e]??null}registerExpression(e){this._expressions.push(e),this._expressionMap[e.expressionName]=e}unregisterExpression(e){let t=this._expressions.indexOf(e);t===-1&&console.warn(`VRMExpressionManager: The specified expressions is not registered`),this._expressions.splice(t,1),delete this._expressionMap[e.expressionName]}getValue(e){return this.getExpression(e)?.weight??null}setValue(e,t){let n=this.getExpression(e);n&&(n.weight=lS(t))}resetValues(){this._expressions.forEach(e=>{e.weight=0})}getExpressionTrackName(e){let t=this.getExpression(e);return t?`${t.name}.weight`:null}update(){let e=this._calculateWeightMultipliers();this._expressions.forEach(e=>{e.clearAppliedWeight()}),this._expressions.forEach(t=>{let n=1,r=t.expressionName;this.blinkExpressionNames.indexOf(r)!==-1&&(n*=e.blink),this.lookAtExpressionNames.indexOf(r)!==-1&&(n*=e.lookAt),this.mouthExpressionNames.indexOf(r)!==-1&&(n*=e.mouth),t.applyWeight({multiplier:n})})}_calculateWeightMultipliers(){let e=1,t=1,n=1;return this._expressions.forEach(r=>{e-=r.overrideBlinkAmount,t-=r.overrideLookAtAmount,n-=r.overrideMouthAmount}),e=Math.max(0,e),t=Math.max(0,t),n=Math.max(0,n),{blink:e,lookAt:t,mouth:n}}},dS={Color:`color`,EmissionColor:`emissionColor`,ShadeColor:`shadeColor`,MatcapColor:`matcapColor`,RimColor:`rimColor`,OutlineColor:`outlineColor`},fS={_Color:dS.Color,_EmissionColor:dS.EmissionColor,_ShadeColor:dS.ShadeColor,_RimColor:dS.RimColor,_OutlineColor:dS.OutlineColor},pS=new q,mS=class e{constructor({material:e,type:t,targetValue:n,targetAlpha:r}){this.material=e,this.type=t,this.targetValue=n,this.targetAlpha=r??1;let i=this._initColorBindState(),a=this._initAlphaBindState();this._state={color:i,alpha:a}}applyWeight(e){let{color:t,alpha:n}=this._state;if(t!=null){let{propertyName:n,deltaValue:r}=t;this.material[n]?.add(pS.copy(r).multiplyScalar(e))}if(n!=null){let{propertyName:t,deltaValue:r}=n;this.material[t]!=null&&(this.material[t]+=r*e)}}clearAppliedWeight(){let{color:e,alpha:t}=this._state;if(e!=null){let{propertyName:t,initialValue:n}=e;this.material[t]?.copy(n)}if(t!=null){let{propertyName:e,initialValue:n}=t;this.material[e]!=null&&(this.material[e]=n)}}_initColorBindState(){let{material:e,type:t,targetValue:n}=this,r=this._getPropertyNameMap()?.[t]?.[0]??null;if(r==null)return console.warn(`Tried to add a material color bind to the material ${e.name??`(no name)`}, the type ${t} but the material or the type is not supported.`),null;let i=e[r].clone();return{propertyName:r,initialValue:i,deltaValue:new q(n.r-i.r,n.g-i.g,n.b-i.b)}}_initAlphaBindState(){let{material:e,type:t,targetAlpha:n}=this,r=this._getPropertyNameMap()?.[t]?.[1]??null;if(r==null&&n!==1)return console.warn(`Tried to add a material alpha bind to the material ${e.name??`(no name)`}, the type ${t} but the material or the type does not support alpha.`),null;if(r==null)return null;let i=e[r];return{propertyName:r,initialValue:i,deltaValue:n-i}}_getPropertyNameMap(){return Object.entries(e._propertyNameMapMap).find(([e])=>this.material[e]===!0)?.[1]??null}};mS._propertyNameMapMap={isMeshStandardMaterial:{color:[`color`,`opacity`],emissionColor:[`emissive`,null]},isMeshBasicMaterial:{color:[`color`,`opacity`]},isMToonMaterial:{color:[`color`,`opacity`],emissionColor:[`emissive`,null],outlineColor:[`outlineColorFactor`,null],matcapColor:[`matcapFactor`,null],rimColor:[`parametricRimColorFactor`,null],shadeColor:[`shadeColorFactor`,null]}};var hS=mS,gS=class{constructor({primitives:e,index:t,weight:n}){this.primitives=e,this.index=t,this.weight=n}applyWeight(e){this.primitives.forEach(t=>{t.morphTargetInfluences?.[this.index]!=null&&(t.morphTargetInfluences[this.index]+=this.weight*e)})}clearAppliedWeight(){this.primitives.forEach(e=>{e.morphTargetInfluences?.[this.index]!=null&&(e.morphTargetInfluences[this.index]=0)})}},_S=new H,vS=class e{constructor({material:t,scale:n,offset:r}){this.material=t,this.scale=n,this.offset=r;let i=Object.entries(e._propertyNamesMap).find(([e])=>t[e]===!0)?.[1];i==null?(console.warn(`Tried to add a texture transform bind to the material ${t.name??`(no name)`} but the material is not supported.`),this._properties=[]):(this._properties=[],i.forEach(e=>{let i=t[e]?.clone();if(!i)return null;t[e]=i;let a=i.offset.clone(),o=i.repeat.clone(),s=r.clone().sub(a),c=n.clone().sub(o);this._properties.push({name:e,initialOffset:a,deltaOffset:s,initialScale:o,deltaScale:c})}))}applyWeight(e){this._properties.forEach(t=>{let n=this.material[t.name];n!==void 0&&(n.offset.add(_S.copy(t.deltaOffset).multiplyScalar(e)),n.repeat.add(_S.copy(t.deltaScale).multiplyScalar(e)))})}clearAppliedWeight(){this._properties.forEach(e=>{let t=this.material[e.name];t!==void 0&&(t.offset.copy(e.initialOffset),t.repeat.copy(e.initialScale))})}};vS._propertyNamesMap={isMeshStandardMaterial:[`map`,`emissiveMap`,`bumpMap`,`normalMap`,`displacementMap`,`roughnessMap`,`metalnessMap`,`alphaMap`],isMeshBasicMaterial:[`map`,`specularMap`,`alphaMap`],isMToonMaterial:[`map`,`normalMap`,`emissiveMap`,`shadeMultiplyTexture`,`rimMultiplyTexture`,`outlineWidthMultiplyTexture`,`uvAnimationMaskTexture`]};var yS=vS,bS=new Set([`1.0`,`1.0-beta`]),xS=class e{get name(){return`VRMExpressionLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return rS(this,null,function*(){e.userData.vrmExpressionManager=yield this._import(e)})}_import(e){return rS(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return rS(this,null,function*(){let t=this.parser.json;if(t.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let n=t.extensions?.VRMC_vrm;if(!n)return null;let r=n.specVersion;if(!bS.has(r))return console.warn(`VRMExpressionLoaderPlugin: Unknown VRMC_vrm specVersion "${r}"`),null;let i=n.expressions;if(!i)return null;let a=new Set(Object.values(cS)),o=new Map;i.preset!=null&&Object.entries(i.preset).forEach(([e,t])=>{if(t!=null){if(!a.has(e)){console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${e}" detected. Ignoring the expression`);return}o.set(e,t)}}),i.custom!=null&&Object.entries(i.custom).forEach(([e,t])=>{if(a.has(e)){console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${e}". Ignoring the expression`);return}o.set(e,t)});let s=new uS;return yield Promise.all(Array.from(o.entries()).map(t=>rS(this,[t],function*([t,n]){var r,i,a;let o=new iS(t);if(e.scene.add(o),o.isBinary=n.isBinary??!1,o.overrideBlink=n.overrideBlink??`none`,o.overrideLookAt=n.overrideLookAt??`none`,o.overrideMouth=n.overrideMouth??`none`,(r=n.morphTargetBinds)==null||r.forEach(t=>rS(this,null,function*(){if(t.node===void 0||t.index===void 0)return;let r=yield oS(e,t.node),i=t.index;if(!r.every(e=>Array.isArray(e.morphTargetInfluences)&&i<e.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${n.name} attempts to index morph #${i} but not found.`);return}o.addBind(new gS({primitives:r,index:i,weight:t.weight??1}))})),n.materialColorBinds||n.textureTransformBinds){let t=[];e.scene.traverse(e=>{let n=e.material;n&&(Array.isArray(n)?t.push(...n):t.push(n))}),(i=n.materialColorBinds)==null||i.forEach(e=>rS(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new hS({material:t,type:e.type,targetValue:new q().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}))})})),(a=n.textureTransformBinds)==null||a.forEach(e=>rS(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new yS({material:t,offset:new H().fromArray(e.offset??[0,0]),scale:new H().fromArray(e.scale??[1,1])}))})}))}s.registerExpression(o)}))),s})}_v0Import(t){return rS(this,null,function*(){let n=this.parser.json,r=n.extensions?.VRM;if(!r)return null;let i=r.blendShapeMaster;if(!i)return null;let a=new uS,o=i.blendShapeGroups;if(!o)return a;let s=new Set;return yield Promise.all(o.map(r=>rS(this,null,function*(){let i=r.presetName,o=(i!=null&&e.v0v1PresetNameMap[i]||null)??r.name;if(o==null){console.warn(`VRMExpressionLoaderPlugin: One of custom expressions has no name. Ignoring the expression`);return}if(s.has(o)){console.warn(`VRMExpressionLoaderPlugin: An expression preset ${i} has duplicated entries. Ignoring the expression`);return}s.add(o);let c=new iS(o);t.scene.add(c),c.isBinary=r.isBinary??!1,r.binds&&r.binds.forEach(e=>rS(this,null,function*(){var i;if(e.mesh===void 0||e.index===void 0)return;let a=[];(i=n.nodes)==null||i.forEach((t,n)=>{t.mesh===e.mesh&&a.push(n)});let o=e.index;yield Promise.all(a.map(n=>rS(this,null,function*(){let i=yield oS(t,n);if(!i.every(e=>Array.isArray(e.morphTargetInfluences)&&o<e.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${r.name} attempts to index ${o}th morph but not found.`);return}c.addBind(new gS({primitives:i,index:o,weight:.01*(e.weight??100)}))})))}));let l=r.materialValues;l&&l.length!==0&&l.forEach(e=>{if(e.materialName===void 0||e.propertyName===void 0||e.targetValue===void 0)return;let n=[];t.scene.traverse(t=>{if(t.material){let r=t.material;Array.isArray(r)?n.push(...r.filter(t=>(t.name===e.materialName||t.name===e.materialName+` (Outline)`)&&n.indexOf(t)===-1)):r.name===e.materialName&&n.indexOf(r)===-1&&n.push(r)}});let r=e.propertyName;n.forEach(t=>{if(r===`_MainTex_ST`){let n=new H(e.targetValue[0],e.targetValue[1]),r=new H(e.targetValue[2],e.targetValue[3]);r.y=1-r.y-n.y,c.addBind(new yS({material:t,scale:n,offset:r}));return}let n=fS[r];if(n){c.addBind(new hS({material:t,type:n,targetValue:new q().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}));return}console.warn(r+` is not supported`)})}),a.registerExpression(c)}))),a})}};xS.v0v1PresetNameMap={a:`aa`,e:`ee`,i:`ih`,o:`oh`,u:`ou`,blink:`blink`,joy:`happy`,angry:`angry`,sorrow:`sad`,fun:`relaxed`,lookup:`lookUp`,lookdown:`lookDown`,lookleft:`lookLeft`,lookright:`lookRight`,blink_l:`blinkLeft`,blink_r:`blinkRight`,neutral:`neutral`};var SS=xS,CS=class e{constructor(t,n){this._firstPersonOnlyLayer=e.DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=e.DEFAULT_THIRDPERSON_ONLY_LAYER,this._initializedLayers=!1,this.humanoid=t,this.meshAnnotations=n}copy(e){if(this.humanoid!==e.humanoid)throw Error(`VRMFirstPerson: humanoid must be same in order to copy`);return this.meshAnnotations=e.meshAnnotations.map(e=>({meshes:e.meshes.concat(),type:e.type})),this}clone(){return new e(this.humanoid,this.meshAnnotations).copy(this)}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}setup({firstPersonOnlyLayer:t=e.DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:n=e.DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initializedLayers||=(this._firstPersonOnlyLayer=t,this._thirdPersonOnlyLayer=n,this.meshAnnotations.forEach(e=>{e.meshes.forEach(t=>{e.type===`firstPersonOnly`?(t.layers.set(this._firstPersonOnlyLayer),t.traverse(e=>e.layers.set(this._firstPersonOnlyLayer))):e.type===`thirdPersonOnly`?(t.layers.set(this._thirdPersonOnlyLayer),t.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer))):e.type===`auto`&&this._createHeadlessModel(t)})}),!0)}_excludeTriangles(e,t,n,r){let i=0;if(t!=null&&t.length>0)for(let a=0;a<e.length;a+=3){let o=e[a],s=e[a+1],c=e[a+2],l=t[o],u=n[o];if(l[0]>0&&r.includes(u[0])||l[1]>0&&r.includes(u[1])||l[2]>0&&r.includes(u[2])||l[3]>0&&r.includes(u[3]))continue;let d=t[s],f=n[s];if(d[0]>0&&r.includes(f[0])||d[1]>0&&r.includes(f[1])||d[2]>0&&r.includes(f[2])||d[3]>0&&r.includes(f[3]))continue;let p=t[c],m=n[c];p[0]>0&&r.includes(m[0])||p[1]>0&&r.includes(m[1])||p[2]>0&&r.includes(m[2])||p[3]>0&&r.includes(m[3])||(e[i++]=o,e[i++]=s,e[i++]=c)}return i}_createErasedMesh(e,t){let n=new gu(e.geometry.clone(),e.material);n.name=`${e.name}(erase)`,n.frustumCulled=e.frustumCulled,n.layers.set(this._firstPersonOnlyLayer);let r=n.geometry,i=r.getAttribute(`skinIndex`),a=i instanceof tp?[]:i.array,o=[];for(let e=0;e<a.length;e+=4)o.push([a[e],a[e+1],a[e+2],a[e+3]]);let s=r.getAttribute(`skinWeight`),c=s instanceof tp?[]:s.array,l=[];for(let e=0;e<c.length;e+=4)l.push([c[e],c[e+1],c[e+2],c[e+3]]);let u=r.getIndex();if(!u)throw Error(`The geometry doesn't have an index buffer`);let d=Array.from(u.array),f=this._excludeTriangles(d,l,o,t),p=[];for(let e=0;e<f;e++)p[e]=d[e];return r.setIndex(p),e.onBeforeRender&&(n.onBeforeRender=e.onBeforeRender),n.bind(new xu(e.skeleton.bones,e.skeleton.boneInverses),new K),n}_createHeadlessModelForSkinnedMesh(e,t){let n=[];if(t.skeleton.bones.forEach((e,t)=>{this._isEraseTarget(e)&&n.push(t)}),!n.length){t.layers.enable(this._thirdPersonOnlyLayer),t.layers.enable(this._firstPersonOnlyLayer);return}t.layers.set(this._thirdPersonOnlyLayer);let r=this._createErasedMesh(t,n);e.add(r)}_createHeadlessModel(e){if(e.type===`Group`)if(e.layers.set(this._thirdPersonOnlyLayer),this._isEraseTarget(e))e.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer));else{let t=new Ec;t.name=`_headless_${e.name}`,t.layers.set(this._firstPersonOnlyLayer),e.parent.add(t),e.children.filter(e=>e.type===`SkinnedMesh`).forEach(e=>{let n=e;this._createHeadlessModelForSkinnedMesh(t,n)})}else if(e.type===`SkinnedMesh`){let t=e;this._createHeadlessModelForSkinnedMesh(e.parent,t)}else this._isEraseTarget(e)&&(e.layers.set(this._thirdPersonOnlyLayer),e.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer)))}_isEraseTarget(e){return e===this.humanoid.getRawBoneNode(`head`)?!0:e.parent?this._isEraseTarget(e.parent):!1}};CS.DEFAULT_FIRSTPERSON_ONLY_LAYER=9,CS.DEFAULT_THIRDPERSON_ONLY_LAYER=10;var wS=CS,TS=new Set([`1.0`,`1.0-beta`]),ES=class{get name(){return`VRMFirstPersonLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return rS(this,null,function*(){let t=e.userData.vrmHumanoid;if(t!==null){if(t===void 0)throw Error(`VRMFirstPersonLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first`);e.userData.vrmFirstPerson=yield this._import(e,t)}})}_import(e,t){return rS(this,null,function*(){return t==null?null:(yield this._v1Import(e,t))||(yield this._v0Import(e,t))||null})}_v1Import(e,t){return rS(this,null,function*(){let n=this.parser.json;if(n.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let r=n.extensions?.VRMC_vrm;if(!r)return null;let i=r.specVersion;if(!TS.has(i))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${i}"`),null;let a=r.firstPerson,o=[],s=yield sS(e);return Array.from(s.entries()).forEach(([e,t])=>{let n=(a?.meshAnnotations)?.find(t=>t.node===e);o.push({meshes:t,type:n?.type??`auto`})}),new wS(t,o)})}_v0Import(e,t){return rS(this,null,function*(){let n=this.parser.json,r=n.extensions?.VRM;if(!r)return null;let i=r.firstPerson;if(!i)return null;let a=[],o=yield sS(e);return Array.from(o.entries()).forEach(([e,t])=>{let r=n.nodes[e],o=i.meshAnnotations?i.meshAnnotations.find(e=>e.mesh===r.mesh):void 0;a.push({meshes:t,type:this._convertV0FlagToV1Type(o?.firstPersonFlag)})}),new wS(t,a)})}_convertV0FlagToV1Type(e){return e===`FirstPersonOnly`?`firstPersonOnly`:e===`ThirdPersonOnly`?`thirdPersonOnly`:e===`Both`?`both`:`auto`}},DS=new W,OS=new W,kS=new U,AS=class extends Ec{constructor(e){super(),this.vrmHumanoid=e,this._boneAxesMap=new Map,Object.values(e.humanBones).forEach(e=>{let t=new op(1);t.matrixAutoUpdate=!1,t.material.depthTest=!1,t.material.depthWrite=!1,this.add(t),this._boneAxesMap.set(e,t)})}dispose(){Array.from(this._boneAxesMap.values()).forEach(e=>{e.geometry.dispose(),e.material.dispose()})}updateMatrixWorld(e){Array.from(this._boneAxesMap.entries()).forEach(([e,t])=>{e.node.updateWorldMatrix(!0,!1),e.node.matrixWorld.decompose(DS,kS,OS);let n=DS.set(.1,.1,.1).divide(OS);t.matrix.copy(e.node.matrixWorld).scale(n)}),super.updateMatrixWorld(e)}},jS=`hips.spine.chest.upperChest.neck.head.leftEye.rightEye.jaw.leftUpperLeg.leftLowerLeg.leftFoot.leftToes.rightUpperLeg.rightLowerLeg.rightFoot.rightToes.leftShoulder.leftUpperArm.leftLowerArm.leftHand.rightShoulder.rightUpperArm.rightLowerArm.rightHand.leftThumbMetacarpal.leftThumbProximal.leftThumbDistal.leftIndexProximal.leftIndexIntermediate.leftIndexDistal.leftMiddleProximal.leftMiddleIntermediate.leftMiddleDistal.leftRingProximal.leftRingIntermediate.leftRingDistal.leftLittleProximal.leftLittleIntermediate.leftLittleDistal.rightThumbMetacarpal.rightThumbProximal.rightThumbDistal.rightIndexProximal.rightIndexIntermediate.rightIndexDistal.rightMiddleProximal.rightMiddleIntermediate.rightMiddleDistal.rightRingProximal.rightRingIntermediate.rightRingDistal.rightLittleProximal.rightLittleIntermediate.rightLittleDistal`.split(`.`),MS={hips:null,spine:`hips`,chest:`spine`,upperChest:`chest`,neck:`upperChest`,head:`neck`,leftEye:`head`,rightEye:`head`,jaw:`head`,leftUpperLeg:`hips`,leftLowerLeg:`leftUpperLeg`,leftFoot:`leftLowerLeg`,leftToes:`leftFoot`,rightUpperLeg:`hips`,rightLowerLeg:`rightUpperLeg`,rightFoot:`rightLowerLeg`,rightToes:`rightFoot`,leftShoulder:`upperChest`,leftUpperArm:`leftShoulder`,leftLowerArm:`leftUpperArm`,leftHand:`leftLowerArm`,rightShoulder:`upperChest`,rightUpperArm:`rightShoulder`,rightLowerArm:`rightUpperArm`,rightHand:`rightLowerArm`,leftThumbMetacarpal:`leftHand`,leftThumbProximal:`leftThumbMetacarpal`,leftThumbDistal:`leftThumbProximal`,leftIndexProximal:`leftHand`,leftIndexIntermediate:`leftIndexProximal`,leftIndexDistal:`leftIndexIntermediate`,leftMiddleProximal:`leftHand`,leftMiddleIntermediate:`leftMiddleProximal`,leftMiddleDistal:`leftMiddleIntermediate`,leftRingProximal:`leftHand`,leftRingIntermediate:`leftRingProximal`,leftRingDistal:`leftRingIntermediate`,leftLittleProximal:`leftHand`,leftLittleIntermediate:`leftLittleProximal`,leftLittleDistal:`leftLittleIntermediate`,rightThumbMetacarpal:`rightHand`,rightThumbProximal:`rightThumbMetacarpal`,rightThumbDistal:`rightThumbProximal`,rightIndexProximal:`rightHand`,rightIndexIntermediate:`rightIndexProximal`,rightIndexDistal:`rightIndexIntermediate`,rightMiddleProximal:`rightHand`,rightMiddleIntermediate:`rightMiddleProximal`,rightMiddleDistal:`rightMiddleIntermediate`,rightRingProximal:`rightHand`,rightRingIntermediate:`rightRingProximal`,rightRingDistal:`rightRingIntermediate`,rightLittleProximal:`rightHand`,rightLittleIntermediate:`rightLittleProximal`,rightLittleDistal:`rightLittleIntermediate`};function NS(e){return e.invert?e.invert():e.inverse(),e}var PS=new W,FS=new U,IS=class{constructor(e){this.humanBones=e,this.restPose=this.getAbsolutePose()}getAbsolutePose(){let e={};return Object.keys(this.humanBones).forEach(t=>{let n=t,r=this.getBoneNode(n);r&&(PS.copy(r.position),FS.copy(r.quaternion),e[n]={position:PS.toArray(),rotation:FS.toArray()})}),e}getPose(){let e={};return Object.keys(this.humanBones).forEach(t=>{let n=t,r=this.getBoneNode(n);if(!r)return;PS.set(0,0,0),FS.identity();let i=this.restPose[n];i?.position&&PS.fromArray(i.position).negate(),i?.rotation&&NS(FS.fromArray(i.rotation)),PS.add(r.position),FS.premultiply(r.quaternion),e[n]={position:PS.toArray(),rotation:FS.toArray()}}),e}setPose(e){Object.entries(e).forEach(([e,t])=>{let n=e,r=this.getBoneNode(n);if(!r)return;let i=this.restPose[n];i&&(t?.position&&(r.position.fromArray(t.position),i.position&&r.position.add(PS.fromArray(i.position))),t?.rotation&&(r.quaternion.fromArray(t.rotation),i.rotation&&r.quaternion.multiply(FS.fromArray(i.rotation))))})}resetPose(){Object.entries(this.restPose).forEach(([e,t])=>{let n=this.getBoneNode(e);n&&(t?.position&&n.position.fromArray(t.position),t?.rotation&&n.quaternion.fromArray(t.rotation))})}getBone(e){return this.humanBones[e]??void 0}getBoneNode(e){return this.humanBones[e]?.node??null}},LS=new W,RS=new U,zS=new W,BS=class e extends IS{static _setupTransforms(e){let t=new Tc;t.name=`VRMHumanoidRig`;let n={},r={},i={},a={};jS.forEach(t=>{var o;let s=e.getBoneNode(t);if(s){let e=new W,c=new U;s.updateWorldMatrix(!0,!1),s.matrixWorld.decompose(e,c,LS),n[t]=e,r[t]=c,i[t]=s.quaternion.clone();let l=new U;(o=s.parent)==null||o.matrixWorld.decompose(LS,l,LS),a[t]=l}});let o={};return jS.forEach(r=>{let i=e.getBoneNode(r);if(i){let e=n[r],a=r,s;for(;s==null&&(a=MS[a],a!=null);)s=n[a];let c=new Tc;c.name=`Normalized_`+i.name,(a?o[a]?.node:t).add(c),c.position.copy(e),s&&c.position.sub(s),o[r]={node:c}}}),{rigBones:o,root:t,parentWorldRotations:a,boneRotations:i}}constructor(t){let{rigBones:n,root:r,parentWorldRotations:i,boneRotations:a}=e._setupTransforms(t);super(n),this.original=t,this.root=r,this._parentWorldRotations=i,this._boneRotations=a}update(){jS.forEach(e=>{let t=this.original.getBoneNode(e);if(t!=null){let n=this.getBoneNode(e),r=this._parentWorldRotations[e],i=RS.copy(r).invert(),a=this._boneRotations[e];if(t.quaternion.copy(n.quaternion).multiply(r).premultiply(i).multiply(a),e===`hips`){let e=n.getWorldPosition(zS);t.parent.updateWorldMatrix(!0,!1);let r=t.parent.matrixWorld,i=e.applyMatrix4(r.invert());t.position.copy(i)}}})}},VS=class e{get restPose(){return console.warn(`VRMHumanoid: restPose is deprecated. Use either rawRestPose or normalizedRestPose instead.`),this.rawRestPose}get rawRestPose(){return this._rawHumanBones.restPose}get normalizedRestPose(){return this._normalizedHumanBones.restPose}get humanBones(){return this._rawHumanBones.humanBones}get rawHumanBones(){return this._rawHumanBones.humanBones}get normalizedHumanBones(){return this._normalizedHumanBones.humanBones}get normalizedHumanBonesRoot(){return this._normalizedHumanBones.root}constructor(e,t){this.autoUpdateHumanBones=t?.autoUpdateHumanBones??!0,this._rawHumanBones=new IS(e),this._normalizedHumanBones=new BS(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new IS(e.humanBones),this._normalizedHumanBones=new BS(this._rawHumanBones),this}clone(){return new e(this.humanBones,{autoUpdateHumanBones:this.autoUpdateHumanBones}).copy(this)}getAbsolutePose(){return console.warn(`VRMHumanoid: getAbsolutePose() is deprecated. Use either getRawAbsolutePose() or getNormalizedAbsolutePose() instead.`),this.getRawAbsolutePose()}getRawAbsolutePose(){return this._rawHumanBones.getAbsolutePose()}getNormalizedAbsolutePose(){return this._normalizedHumanBones.getAbsolutePose()}getPose(){return console.warn(`VRMHumanoid: getPose() is deprecated. Use either getRawPose() or getNormalizedPose() instead.`),this.getRawPose()}getRawPose(){return this._rawHumanBones.getPose()}getNormalizedPose(){return this._normalizedHumanBones.getPose()}setPose(e){return console.warn(`VRMHumanoid: setPose() is deprecated. Use either setRawPose() or setNormalizedPose() instead.`),this.setRawPose(e)}setRawPose(e){return this._rawHumanBones.setPose(e)}setNormalizedPose(e){return this._normalizedHumanBones.setPose(e)}resetPose(){return console.warn(`VRMHumanoid: resetPose() is deprecated. Use either resetRawPose() or resetNormalizedPose() instead.`),this.resetRawPose()}resetRawPose(){return this._rawHumanBones.resetPose()}resetNormalizedPose(){return this._normalizedHumanBones.resetPose()}getBone(e){return console.warn(`VRMHumanoid: getBone() is deprecated. Use either getRawBone() or getNormalizedBone() instead.`),this.getRawBone(e)}getRawBone(e){return this._rawHumanBones.getBone(e)}getNormalizedBone(e){return this._normalizedHumanBones.getBone(e)}getBoneNode(e){return console.warn(`VRMHumanoid: getBoneNode() is deprecated. Use either getRawBoneNode() or getNormalizedBoneNode() instead.`),this.getRawBoneNode(e)}getRawBoneNode(e){return this._rawHumanBones.getBoneNode(e)}getNormalizedBoneNode(e){return this._normalizedHumanBones.getBoneNode(e)}update(){this.autoUpdateHumanBones&&this._normalizedHumanBones.update()}},HS={Hips:`hips`,Spine:`spine`,Head:`head`,LeftUpperLeg:`leftUpperLeg`,LeftLowerLeg:`leftLowerLeg`,LeftFoot:`leftFoot`,RightUpperLeg:`rightUpperLeg`,RightLowerLeg:`rightLowerLeg`,RightFoot:`rightFoot`,LeftUpperArm:`leftUpperArm`,LeftLowerArm:`leftLowerArm`,LeftHand:`leftHand`,RightUpperArm:`rightUpperArm`,RightLowerArm:`rightLowerArm`,RightHand:`rightHand`},US=new Set([`1.0`,`1.0-beta`]),WS={leftThumbProximal:`leftThumbMetacarpal`,leftThumbIntermediate:`leftThumbProximal`,rightThumbProximal:`rightThumbMetacarpal`,rightThumbIntermediate:`rightThumbProximal`},GS=class{get name(){return`VRMHumanoidLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot,this.autoUpdateHumanBones=t?.autoUpdateHumanBones}afterRoot(e){return rS(this,null,function*(){e.userData.vrmHumanoid=yield this._import(e)})}_import(e){return rS(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return rS(this,null,function*(){let t=this.parser.json;if(t.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let n=t.extensions?.VRMC_vrm;if(!n)return null;let r=n.specVersion;if(!US.has(r))return console.warn(`VRMHumanoidLoaderPlugin: Unknown VRMC_vrm specVersion "${r}"`),null;let i=n.humanoid;if(!i)return null;let a=i.humanBones.leftThumbIntermediate!=null||i.humanBones.rightThumbIntermediate!=null,o={};i.humanBones!=null&&(yield Promise.all(Object.entries(i.humanBones).map(e=>rS(this,[e],function*([e,t]){let n=e,r=t.node;if(a){let e=WS[n];e!=null&&(n=e)}let i=yield this.parser.getDependency(`node`,r);if(i==null){console.warn(`A glTF node bound to the humanoid bone ${n} (index = ${r}) does not exist`);return}o[n]={node:i}}))));let s=new VS(this._ensureRequiredBonesExist(o),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(s.normalizedHumanBonesRoot),this.helperRoot){let e=new AS(s);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return s})}_v0Import(e){return rS(this,null,function*(){let t=this.parser.json.extensions?.VRM;if(!t)return null;let n=t.humanoid;if(!n)return null;let r={};n.humanBones!=null&&(yield Promise.all(n.humanBones.map(e=>rS(this,null,function*(){let t=e.bone,n=e.node;if(t==null||n==null)return;let i=yield this.parser.getDependency(`node`,n);if(i==null){console.warn(`A glTF node bound to the humanoid bone ${t} (index = ${n}) does not exist`);return}let a=WS[t]??t;if(r[a]!=null){console.warn(`Multiple bone entries for ${a} detected (index = ${n}), ignoring duplicated entries.`);return}r[a]={node:i}}))));let i=new VS(this._ensureRequiredBonesExist(r),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(i.normalizedHumanBonesRoot),this.helperRoot){let e=new AS(i);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return i})}_ensureRequiredBonesExist(e){let t=Object.values(HS).filter(t=>e[t]==null);if(t.length>0)throw Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${t.join(`, `)}`);return e}},KS=class extends Y{constructor(){super(),this._currentTheta=0,this._currentRadius=0,this.theta=0,this.radius=0,this._currentTheta=0,this._currentRadius=0,this._attrPos=new J(new Float32Array(195),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new J(new Uint16Array(189),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentTheta!==this.theta&&(this._currentTheta=this.theta,e=!0),this._currentRadius!==this.radius&&(this._currentRadius=this.radius,e=!0),e&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,0,0,0);for(let e=0;e<64;e++){let t=e/63*this._currentTheta;this._attrPos.setXYZ(e+1,this._currentRadius*Math.sin(t),0,this._currentRadius*Math.cos(t))}this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<63;e++)this._attrIndex.setXYZ(e*3,0,e+1,e+2);this._attrIndex.needsUpdate=!0}},qS=class extends Y{constructor(){super(),this.radius=0,this._currentRadius=0,this.tail=new W,this._currentTail=new W,this._attrPos=new J(new Float32Array(294),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new J(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentRadius!==this.radius&&(this._currentRadius=this.radius,e=!0),this._currentTail.equals(this.tail)||(this._currentTail.copy(this.tail),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){let t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<32;e++){let t=(e+1)%32;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(64+e*2,32+e,32+t),this._attrIndex.setXY(128+e*2,64+e,64+t)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},JS=new U,YS=new U,XS=new W,ZS=new W,QS=Math.sqrt(2)/2,$S=new U(0,0,-QS,QS),eC=new W(0,1,0),tC=class extends Ec{constructor(e){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=e;{let e=new KS;e.radius=.5;let t=new Kl({color:65280,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshPitch=new iu(e,t),this.add(this._meshPitch)}{let e=new KS;e.radius=.5;let t=new Kl({color:16711680,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshYaw=new iu(e,t),this.add(this._meshYaw)}{let e=new qS;e.radius=.1;let t=new zu({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new Zu(e,t),this._lineTarget.frustumCulled=!1,this.add(this._lineTarget)}}dispose(){this._meshYaw.geometry.dispose(),this._meshYaw.material.dispose(),this._meshPitch.geometry.dispose(),this._meshPitch.material.dispose(),this._lineTarget.geometry.dispose(),this._lineTarget.material.dispose()}updateMatrixWorld(e){let t=As.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=t,this._meshYaw.geometry.update();let n=As.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=n,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition(XS),this.vrmLookAt.getLookAtWorldQuaternion(JS),JS.multiply(this.vrmLookAt.getFaceFrontQuaternion(YS)),this._meshYaw.position.copy(XS),this._meshYaw.quaternion.copy(JS),this._meshPitch.position.copy(XS),this._meshPitch.quaternion.copy(JS),this._meshPitch.quaternion.multiply(YS.setFromAxisAngle(eC,t)),this._meshPitch.quaternion.multiply($S);let{target:r,autoUpdate:i}=this.vrmLookAt;r!=null&&i&&(r.getWorldPosition(ZS).sub(XS),this._lineTarget.geometry.tail.copy(ZS),this._lineTarget.geometry.update(),this._lineTarget.position.copy(XS)),super.updateMatrixWorld(e)}},nC=new W,rC=new W;function iC(e,t){return e.matrixWorld.decompose(nC,t,rC),t}function aC(e){return[Math.atan2(-e.z,e.x),Math.atan2(e.y,Math.sqrt(e.x*e.x+e.z*e.z))]}function oC(e){let t=Math.round(e/2/Math.PI);return e-2*Math.PI*t}var sC=new W(0,0,1),cC=new W,lC=new W,uC=new W,dC=new U,fC=new U,pC=new U,mC=new U,hC=new cc,gC=class e{constructor(e,t){this.offsetFromHeadBone=new W,this.autoUpdate=!0,this.faceFront=new W(0,0,1),this.humanoid=e,this.applier=t,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new U)}get yaw(){return this._yaw}set yaw(e){this._yaw=e,this._needsUpdate=!0}get pitch(){return this._pitch}set pitch(e){this._pitch=e,this._needsUpdate=!0}get euler(){return console.warn(`VRMLookAt: euler is deprecated. use getEuler() instead.`),this.getEuler(new cc)}getEuler(e){return e.set(As.DEG2RAD*this._pitch,As.DEG2RAD*this._yaw,0,`YXZ`)}copy(e){if(this.humanoid!==e.humanoid)throw Error(`VRMLookAt: humanoid must be same in order to copy`);return this.offsetFromHeadBone.copy(e.offsetFromHeadBone),this.applier=e.applier,this.autoUpdate=e.autoUpdate,this.target=e.target,this.faceFront.copy(e.faceFront),this}clone(){return new e(this.humanoid,this.applier).copy(this)}reset(){this._yaw=0,this._pitch=0,this._needsUpdate=!0}getLookAtWorldPosition(e){let t=this.humanoid.getRawBoneNode(`head`);return e.copy(this.offsetFromHeadBone).applyMatrix4(t.matrixWorld)}getLookAtWorldQuaternion(e){return iC(this.humanoid.getRawBoneNode(`head`),e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(sC)<.01)return e.copy(this._restHeadWorldQuaternion).invert();let[t,n]=aC(this.faceFront);return hC.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(hC).premultiply(mC.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(fC),this.getFaceFrontQuaternion(pC),e.copy(sC).applyQuaternion(fC).applyQuaternion(pC).applyEuler(this.getEuler(hC))}lookAt(e){let t=dC.copy(this._restHeadWorldQuaternion).multiply(NS(this.getLookAtWorldQuaternion(fC))),n=this.getLookAtWorldPosition(lC),r=uC.copy(e).sub(n).applyQuaternion(t).normalize(),[i,a]=aC(this.faceFront),[o,s]=aC(r),c=oC(o-i),l=oC(a-s);this._yaw=As.RAD2DEG*c,this._pitch=As.RAD2DEG*l,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(cC)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};gC.EULER_ORDER=`YXZ`;var _C=gC,vC=new W(0,0,1),yC=new U,bC=new U,xC=new cc(0,0,0,`YXZ`),SC=class{constructor(e,t,n,r,i){this.humanoid=e,this.rangeMapHorizontalInner=t,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=r,this.rangeMapVerticalUp=i,this.faceFront=new W(0,0,1),this._restQuatLeftEye=new U,this._restQuatRightEye=new U,this._restLeftEyeParentWorldQuat=new U,this._restRightEyeParentWorldQuat=new U;let a=this.humanoid.getRawBoneNode(`leftEye`),o=this.humanoid.getRawBoneNode(`rightEye`);a&&(this._restQuatLeftEye.copy(a.quaternion),iC(a.parent,this._restLeftEyeParentWorldQuat)),o&&(this._restQuatRightEye.copy(o.quaternion),iC(o.parent,this._restRightEyeParentWorldQuat))}applyYawPitch(e,t){let n=this.humanoid.getRawBoneNode(`leftEye`),r=this.humanoid.getRawBoneNode(`rightEye`),i=this.humanoid.getNormalizedBoneNode(`leftEye`),a=this.humanoid.getNormalizedBoneNode(`rightEye`);n&&(t<0?xC.x=-As.DEG2RAD*this.rangeMapVerticalDown.map(-t):xC.x=As.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?xC.y=-As.DEG2RAD*this.rangeMapHorizontalInner.map(-e):xC.y=As.DEG2RAD*this.rangeMapHorizontalOuter.map(e),yC.setFromEuler(xC),this._getWorldFaceFrontQuat(bC),i.quaternion.copy(bC).multiply(yC).multiply(bC.invert()),yC.copy(this._restLeftEyeParentWorldQuat),n.quaternion.copy(i.quaternion).multiply(yC).premultiply(yC.invert()).multiply(this._restQuatLeftEye)),r&&(t<0?xC.x=-As.DEG2RAD*this.rangeMapVerticalDown.map(-t):xC.x=As.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?xC.y=-As.DEG2RAD*this.rangeMapHorizontalOuter.map(-e):xC.y=As.DEG2RAD*this.rangeMapHorizontalInner.map(e),yC.setFromEuler(xC),this._getWorldFaceFrontQuat(bC),a.quaternion.copy(bC).multiply(yC).multiply(bC.invert()),yC.copy(this._restRightEyeParentWorldQuat),r.quaternion.copy(a.quaternion).multiply(yC).premultiply(yC.invert()).multiply(this._restQuatRightEye))}lookAt(e){console.warn(`VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.`);let t=As.RAD2DEG*e.y,n=As.RAD2DEG*e.x;this.applyYawPitch(t,n)}_getWorldFaceFrontQuat(e){if(this.faceFront.distanceToSquared(vC)<.01)return e.identity();let[t,n]=aC(this.faceFront);return xC.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(xC)}};SC.type=`bone`;var CC=class{constructor(e,t,n,r,i){this.expressions=e,this.rangeMapHorizontalInner=t,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=r,this.rangeMapVerticalUp=i}applyYawPitch(e,t){t<0?(this.expressions.setValue(`lookDown`,0),this.expressions.setValue(`lookUp`,this.rangeMapVerticalUp.map(-t))):(this.expressions.setValue(`lookUp`,0),this.expressions.setValue(`lookDown`,this.rangeMapVerticalDown.map(t))),e<0?(this.expressions.setValue(`lookLeft`,0),this.expressions.setValue(`lookRight`,this.rangeMapHorizontalOuter.map(-e))):(this.expressions.setValue(`lookRight`,0),this.expressions.setValue(`lookLeft`,this.rangeMapHorizontalOuter.map(e)))}lookAt(e){console.warn(`VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.`);let t=As.RAD2DEG*e.y,n=As.RAD2DEG*e.x;this.applyYawPitch(t,n)}};CC.type=`expression`;var wC=class{constructor(e,t){this.inputMaxValue=e,this.outputScale=t}map(e){return this.outputScale*lS(e/this.inputMaxValue)}},TC=new Set([`1.0`,`1.0-beta`]),EC=.01,DC=class{get name(){return`VRMLookAtLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot}afterRoot(e){return rS(this,null,function*(){let t=e.userData.vrmHumanoid;if(t===null)return;if(t===void 0)throw Error(`VRMLookAtLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first`);let n=e.userData.vrmExpressionManager;if(n!==null){if(n===void 0)throw Error(`VRMLookAtLoaderPlugin: vrmExpressionManager is undefined. VRMExpressionLoaderPlugin have to be used first`);e.userData.vrmLookAt=yield this._import(e,t,n)}})}_import(e,t,n){return rS(this,null,function*(){return t==null||n==null?null:(yield this._v1Import(e,t,n))||(yield this._v0Import(e,t,n))||null})}_v1Import(e,t,n){return rS(this,null,function*(){let e=this.parser.json;if(e.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let r=e.extensions?.VRMC_vrm;if(!r)return null;let i=r.specVersion;if(!TC.has(i))return console.warn(`VRMLookAtLoaderPlugin: Unknown VRMC_vrm specVersion "${i}"`),null;let a=r.lookAt;if(!a)return null;let o=a.type===`expression`?1:10,s=this._v1ImportRangeMap(a.rangeMapHorizontalInner,o),c=this._v1ImportRangeMap(a.rangeMapHorizontalOuter,o),l=this._v1ImportRangeMap(a.rangeMapVerticalDown,o),u=this._v1ImportRangeMap(a.rangeMapVerticalUp,o),d;d=a.type===`expression`?new CC(n,s,c,l,u):new SC(t,s,c,l,u);let f=this._importLookAt(t,d);return f.offsetFromHeadBone.fromArray(a.offsetFromHeadBone??[0,.06,0]),f})}_v1ImportRangeMap(e,t){let n=e?.inputMaxValue??90,r=e?.outputScale??t;return n<EC&&(console.warn(`VRMLookAtLoaderPlugin: inputMaxValue of a range map is too small. Consider reviewing the range map!`),n=EC),new wC(n,r)}_v0Import(e,t,n){return rS(this,null,function*(){let e=this.parser.json.extensions?.VRM;if(!e)return null;let r=e.firstPerson;if(!r)return null;let i=r.lookAtTypeName===`BlendShape`?1:10,a=this._v0ImportDegreeMap(r.lookAtHorizontalInner,i),o=this._v0ImportDegreeMap(r.lookAtHorizontalOuter,i),s=this._v0ImportDegreeMap(r.lookAtVerticalDown,i),c=this._v0ImportDegreeMap(r.lookAtVerticalUp,i),l;l=r.lookAtTypeName===`BlendShape`?new CC(n,a,o,s,c):new SC(t,a,o,s,c);let u=this._importLookAt(t,l);return r.firstPersonBoneOffset?u.offsetFromHeadBone.set(r.firstPersonBoneOffset.x??0,r.firstPersonBoneOffset.y??.06,-(r.firstPersonBoneOffset.z??0)):u.offsetFromHeadBone.set(0,.06,0),u.faceFront.set(0,0,-1),l instanceof SC&&l.faceFront.set(0,0,-1),u})}_v0ImportDegreeMap(e,t){let n=e?.curve;JSON.stringify(n)!==`[0,0,0,1,1,1,1,0]`&&console.warn(`Curves of LookAtDegreeMap defined in VRM 0.0 are not supported`);let r=e?.xRange??90,i=e?.yRange??t;return r<EC&&(console.warn(`VRMLookAtLoaderPlugin: xRange of a degree map is too small. Consider reviewing the degree map!`),r=EC),new wC(r,i)}_importLookAt(e,t){let n=new _C(e,t);if(this.helperRoot){let e=new tC(n);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return n}};function OC(e,t){return typeof e!=`string`||e===``?``:(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^/]+).*/i,`$1`)),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}var kC=new Set([`1.0`,`1.0-beta`]),AC=class{get name(){return`VRMMetaLoaderPlugin`}constructor(e,t){this.parser=e,this.needThumbnailImage=t?.needThumbnailImage??!1,this.acceptLicenseUrls=t?.acceptLicenseUrls??[`https://vrm.dev/licenses/1.0/`],this.acceptV0Meta=t?.acceptV0Meta??!0}afterRoot(e){return rS(this,null,function*(){e.userData.vrmMeta=yield this._import(e)})}_import(e){return rS(this,null,function*(){return(yield this._v1Import(e))??(yield this._v0Import(e))??null})}_v1Import(e){return rS(this,null,function*(){let e=this.parser.json;if(e.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let t=e.extensions?.VRMC_vrm;if(t==null)return null;let n=t.specVersion;if(!kC.has(n))return console.warn(`VRMMetaLoaderPlugin: Unknown VRMC_vrm specVersion "${n}"`),null;let r=t.meta;if(!r)return null;let i=r.licenseUrl;if(!new Set(this.acceptLicenseUrls).has(i))throw Error(`VRMMetaLoaderPlugin: The license url "${i}" is not accepted`);let a;return this.needThumbnailImage&&r.thumbnailImage!=null&&(a=(yield this._extractGLTFImage(r.thumbnailImage))??void 0),{metaVersion:`1`,name:r.name,version:r.version,authors:r.authors,copyrightInformation:r.copyrightInformation,contactInformation:r.contactInformation,references:r.references,thirdPartyLicenses:r.thirdPartyLicenses,thumbnailImage:a,licenseUrl:r.licenseUrl,avatarPermission:r.avatarPermission,allowExcessivelyViolentUsage:r.allowExcessivelyViolentUsage,allowExcessivelySexualUsage:r.allowExcessivelySexualUsage,commercialUsage:r.commercialUsage,allowPoliticalOrReligiousUsage:r.allowPoliticalOrReligiousUsage,allowAntisocialOrHateUsage:r.allowAntisocialOrHateUsage,creditNotation:r.creditNotation,allowRedistribution:r.allowRedistribution,modification:r.modification,otherLicenseUrl:r.otherLicenseUrl}})}_v0Import(e){return rS(this,null,function*(){let e=this.parser.json.extensions?.VRM;if(!e)return null;let t=e.meta;if(!t)return null;if(!this.acceptV0Meta)throw Error(`VRMMetaLoaderPlugin: Attempted to load VRM0.0 meta but acceptV0Meta is false`);let n;return this.needThumbnailImage&&t.texture!=null&&t.texture!==-1&&(n=yield this.parser.getDependency(`texture`,t.texture)),{metaVersion:`0`,allowedUserName:t.allowedUserName,author:t.author,commercialUssageName:t.commercialUssageName,contactInformation:t.contactInformation,licenseName:t.licenseName,otherLicenseUrl:t.otherLicenseUrl,otherPermissionUrl:t.otherPermissionUrl,reference:t.reference,sexualUssageName:t.sexualUssageName,texture:n??void 0,title:t.title,version:t.version,violentUssageName:t.violentUssageName}})}_extractGLTFImage(e){return rS(this,null,function*(){let t=this.parser.json.images?.[e];if(t==null)return console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${e}] of glTF as a thumbnail but the image doesn't exist`),null;let n=t.uri;if(t.bufferView!=null){let e=yield this.parser.getDependency(`bufferView`,t.bufferView),r=new Blob([e],{type:t.mimeType});n=URL.createObjectURL(r)}return n==null?(console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${e}] of glTF as a thumbnail but the image couldn't load properly`),null):yield new cf().loadAsync(OC(n,this.parser.options.path)).catch(e=>(console.error(e),console.warn(`VRMMetaLoaderPlugin: Failed to load a thumbnail image`),null))})}},jC=class{constructor(e){this.scene=e.scene,this.meta=e.meta,this.humanoid=e.humanoid,this.expressionManager=e.expressionManager,this.firstPerson=e.firstPerson,this.lookAt=e.lookAt}update(e){this.humanoid.update(),this.lookAt&&this.lookAt.update(e),this.expressionManager&&this.expressionManager.update()}},MC=class extends jC{constructor(e){super(e),this.materials=e.materials,this.springBoneManager=e.springBoneManager,this.nodeConstraintManager=e.nodeConstraintManager}update(e){super.update(e),this.nodeConstraintManager&&this.nodeConstraintManager.update(),this.springBoneManager&&this.springBoneManager.update(e),this.materials&&this.materials.forEach(t=>{t.update&&t.update(e)})}},NC=Object.defineProperty,PC=Object.getOwnPropertySymbols,FC=Object.prototype.hasOwnProperty,IC=Object.prototype.propertyIsEnumerable,LC=(e,t,n)=>t in e?NC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,RC=(e,t)=>{for(var n in t||={})FC.call(t,n)&&LC(e,n,t[n]);if(PC)for(var n of PC(t))IC.call(t,n)&&LC(e,n,t[n]);return e},zC=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())});function BC(e,t){e.colorSpace=t}var VC=class{get pending(){return Promise.all(this._pendings)}constructor(e,t){this._parser=e,this._materialParams=t,this._pendings=[]}assignPrimitive(e,t){t!=null&&(this._materialParams[e]=t)}assignColor(e,t,n){if(t!=null){let r=new q().fromArray(t);n&&r.convertSRGBToLinear(),this._materialParams[e]=r}}assignTexture(e,t,n){return zC(this,null,function*(){let r=zC(this,null,function*(){if(t!=null){let r=yield this._parser.assignTexture(this._materialParams,e,t);if(r==null){console.warn(`GLTFMToonMaterialParamsAssignHelper: Failed to load texture. The rendering result may be wrong`);return}n&&BC(r,`srgb`)}});return this._pendings.push(r),r})}assignTextureByIndex(e,t,n){return zC(this,null,function*(){return this.assignTexture(e,t==null?void 0:{index:t},n)})}},HC=`// #define PHONG
|
|
5773
5773
|
|
|
5774
5774
|
varying vec3 vViewPosition;
|
|
5775
5775
|
|
|
@@ -6700,9 +6700,9 @@ void main() {
|
|
|
6700
6700
|
gl_FragColor = vec4( col, diffuseColor.a );
|
|
6701
6701
|
postCorrection();
|
|
6702
6702
|
}
|
|
6703
|
-
`,WC={None:`none`,Normal:`normal`,LitShadeRate:`litShadeRate`,UV:`uv`},GC={None:`none`,WorldCoordinates:`worldCoordinates`,ScreenCoordinates:`screenCoordinates`};function KC(e){return e.colorSpace}var qC=class extends Dd{constructor(e={}){super({vertexShader:HC,fragmentShader:UC}),this.uvAnimationScrollXSpeedFactor=0,this.uvAnimationScrollYSpeedFactor=0,this.uvAnimationRotationSpeedFactor=0,this.fog=!0,this.normalMapType=0,this._ignoreVertexColor=!0,this._v0CompatShade=!1,this._debugMode=WC.None,this._outlineWidthMode=GC.None,this._isOutline=!1,e.transparentWithZWrite&&(e.depthWrite=!0),delete e.transparentWithZWrite,e.fog=!0,e.lights=!0,e.clipping=!0,this.uniforms=wd.merge([
|
|
6703
|
+
`,WC={None:`none`,Normal:`normal`,LitShadeRate:`litShadeRate`,UV:`uv`},GC={None:`none`,WorldCoordinates:`worldCoordinates`,ScreenCoordinates:`screenCoordinates`};function KC(e){return e.colorSpace}var qC=class extends Dd{constructor(e={}){super({vertexShader:HC,fragmentShader:UC}),this.uvAnimationScrollXSpeedFactor=0,this.uvAnimationScrollYSpeedFactor=0,this.uvAnimationRotationSpeedFactor=0,this.fog=!0,this.normalMapType=0,this._ignoreVertexColor=!0,this._v0CompatShade=!1,this._debugMode=WC.None,this._outlineWidthMode=GC.None,this._isOutline=!1,e.transparentWithZWrite&&(e.depthWrite=!0),delete e.transparentWithZWrite,e.fog=!0,e.lights=!0,e.clipping=!0,this.uniforms=wd.merge([X.common,X.normalmap,X.emissivemap,X.fog,X.lights,{litFactor:{value:new q(1,1,1)},mapUvTransform:{value:new G},colorAlpha:{value:1},normalMapUvTransform:{value:new G},shadeColorFactor:{value:new q(0,0,0)},shadeMultiplyTexture:{value:null},shadeMultiplyTextureUvTransform:{value:new G},shadingShiftFactor:{value:0},shadingShiftTexture:{value:null},shadingShiftTextureUvTransform:{value:new G},shadingShiftTextureScale:{value:1},shadingToonyFactor:{value:.9},giEqualizationFactor:{value:.9},matcapFactor:{value:new q(1,1,1)},matcapTexture:{value:null},matcapTextureUvTransform:{value:new G},parametricRimColorFactor:{value:new q(0,0,0)},rimMultiplyTexture:{value:null},rimMultiplyTextureUvTransform:{value:new G},rimLightingMixFactor:{value:1},parametricRimFresnelPowerFactor:{value:5},parametricRimLiftFactor:{value:0},emissive:{value:new q(0,0,0)},emissiveIntensity:{value:1},emissiveMapUvTransform:{value:new G},outlineWidthMultiplyTexture:{value:null},outlineWidthMultiplyTextureUvTransform:{value:new G},outlineWidthFactor:{value:0},outlineColorFactor:{value:new q(0,0,0)},outlineLightingMixFactor:{value:1},uvAnimationMaskTexture:{value:null},uvAnimationMaskTextureUvTransform:{value:new G},uvAnimationScrollXOffset:{value:0},uvAnimationScrollYOffset:{value:0},uvAnimationRotationPhase:{value:0}},e.uniforms??{}]),this.setValues(e),this._uploadUniformsWorkaround(),this.customProgramCacheKey=()=>[...Object.entries(this._generateDefines()).map(([e,t])=>`${e}:${t}`),this.matcapTexture?`matcapTextureColorSpace:${KC(this.matcapTexture)}`:``,this.shadeMultiplyTexture?`shadeMultiplyTextureColorSpace:${KC(this.shadeMultiplyTexture)}`:``,this.rimMultiplyTexture?`rimMultiplyTextureColorSpace:${KC(this.rimMultiplyTexture)}`:``].join(`,`),this.onBeforeCompile=e=>{let t=Object.entries(RC(RC({},this._generateDefines()),this.defines)).filter(([e,t])=>!!t).map(([e,t])=>`#define ${e} ${t}`).join(`
|
|
6704
6704
|
`)+`
|
|
6705
|
-
`;e.vertexShader=t+e.vertexShader,e.fragmentShader=t+e.fragmentShader}}get color(){return this.uniforms.litFactor.value}set color(e){this.uniforms.litFactor.value=e}get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}get normalMap(){return this.uniforms.normalMap.value}set normalMap(e){this.uniforms.normalMap.value=e}get normalScale(){return this.uniforms.normalScale.value}set normalScale(e){this.uniforms.normalScale.value=e}get emissive(){return this.uniforms.emissive.value}set emissive(e){this.uniforms.emissive.value=e}get emissiveIntensity(){return this.uniforms.emissiveIntensity.value}set emissiveIntensity(e){this.uniforms.emissiveIntensity.value=e}get emissiveMap(){return this.uniforms.emissiveMap.value}set emissiveMap(e){this.uniforms.emissiveMap.value=e}get shadeColorFactor(){return this.uniforms.shadeColorFactor.value}set shadeColorFactor(e){this.uniforms.shadeColorFactor.value=e}get shadeMultiplyTexture(){return this.uniforms.shadeMultiplyTexture.value}set shadeMultiplyTexture(e){this.uniforms.shadeMultiplyTexture.value=e}get shadingShiftFactor(){return this.uniforms.shadingShiftFactor.value}set shadingShiftFactor(e){this.uniforms.shadingShiftFactor.value=e}get shadingShiftTexture(){return this.uniforms.shadingShiftTexture.value}set shadingShiftTexture(e){this.uniforms.shadingShiftTexture.value=e}get shadingShiftTextureScale(){return this.uniforms.shadingShiftTextureScale.value}set shadingShiftTextureScale(e){this.uniforms.shadingShiftTextureScale.value=e}get shadingToonyFactor(){return this.uniforms.shadingToonyFactor.value}set shadingToonyFactor(e){this.uniforms.shadingToonyFactor.value=e}get giEqualizationFactor(){return this.uniforms.giEqualizationFactor.value}set giEqualizationFactor(e){this.uniforms.giEqualizationFactor.value=e}get matcapFactor(){return this.uniforms.matcapFactor.value}set matcapFactor(e){this.uniforms.matcapFactor.value=e}get matcapTexture(){return this.uniforms.matcapTexture.value}set matcapTexture(e){this.uniforms.matcapTexture.value=e}get parametricRimColorFactor(){return this.uniforms.parametricRimColorFactor.value}set parametricRimColorFactor(e){this.uniforms.parametricRimColorFactor.value=e}get rimMultiplyTexture(){return this.uniforms.rimMultiplyTexture.value}set rimMultiplyTexture(e){this.uniforms.rimMultiplyTexture.value=e}get rimLightingMixFactor(){return this.uniforms.rimLightingMixFactor.value}set rimLightingMixFactor(e){this.uniforms.rimLightingMixFactor.value=e}get parametricRimFresnelPowerFactor(){return this.uniforms.parametricRimFresnelPowerFactor.value}set parametricRimFresnelPowerFactor(e){this.uniforms.parametricRimFresnelPowerFactor.value=e}get parametricRimLiftFactor(){return this.uniforms.parametricRimLiftFactor.value}set parametricRimLiftFactor(e){this.uniforms.parametricRimLiftFactor.value=e}get outlineWidthMultiplyTexture(){return this.uniforms.outlineWidthMultiplyTexture.value}set outlineWidthMultiplyTexture(e){this.uniforms.outlineWidthMultiplyTexture.value=e}get outlineWidthFactor(){return this.uniforms.outlineWidthFactor.value}set outlineWidthFactor(e){this.uniforms.outlineWidthFactor.value=e}get outlineColorFactor(){return this.uniforms.outlineColorFactor.value}set outlineColorFactor(e){this.uniforms.outlineColorFactor.value=e}get outlineLightingMixFactor(){return this.uniforms.outlineLightingMixFactor.value}set outlineLightingMixFactor(e){this.uniforms.outlineLightingMixFactor.value=e}get uvAnimationMaskTexture(){return this.uniforms.uvAnimationMaskTexture.value}set uvAnimationMaskTexture(e){this.uniforms.uvAnimationMaskTexture.value=e}get uvAnimationScrollXOffset(){return this.uniforms.uvAnimationScrollXOffset.value}set uvAnimationScrollXOffset(e){this.uniforms.uvAnimationScrollXOffset.value=e}get uvAnimationScrollYOffset(){return this.uniforms.uvAnimationScrollYOffset.value}set uvAnimationScrollYOffset(e){this.uniforms.uvAnimationScrollYOffset.value=e}get uvAnimationRotationPhase(){return this.uniforms.uvAnimationRotationPhase.value}set uvAnimationRotationPhase(e){this.uniforms.uvAnimationRotationPhase.value=e}get ignoreVertexColor(){return this._ignoreVertexColor}set ignoreVertexColor(e){this._ignoreVertexColor=e,this.needsUpdate=!0}get v0CompatShade(){return this._v0CompatShade}set v0CompatShade(e){this._v0CompatShade=e,this.needsUpdate=!0}get debugMode(){return this._debugMode}set debugMode(e){this._debugMode=e,this.needsUpdate=!0}get outlineWidthMode(){return this._outlineWidthMode}set outlineWidthMode(e){this._outlineWidthMode=e,this.needsUpdate=!0}get isOutline(){return this._isOutline}set isOutline(e){this._isOutline=e,this.needsUpdate=!0}get isMToonMaterial(){return!0}update(e){this._uploadUniformsWorkaround(),this._updateUVAnimation(e)}copy(e){return super.copy(e),this.map=e.map,this.normalMap=e.normalMap,this.emissiveMap=e.emissiveMap,this.shadeMultiplyTexture=e.shadeMultiplyTexture,this.shadingShiftTexture=e.shadingShiftTexture,this.matcapTexture=e.matcapTexture,this.rimMultiplyTexture=e.rimMultiplyTexture,this.outlineWidthMultiplyTexture=e.outlineWidthMultiplyTexture,this.uvAnimationMaskTexture=e.uvAnimationMaskTexture,this.normalMapType=e.normalMapType,this.uvAnimationScrollXSpeedFactor=e.uvAnimationScrollXSpeedFactor,this.uvAnimationScrollYSpeedFactor=e.uvAnimationScrollYSpeedFactor,this.uvAnimationRotationSpeedFactor=e.uvAnimationRotationSpeedFactor,this.ignoreVertexColor=e.ignoreVertexColor,this.v0CompatShade=e.v0CompatShade,this.debugMode=e.debugMode,this.outlineWidthMode=e.outlineWidthMode,this.isOutline=e.isOutline,this.needsUpdate=!0,this}_updateUVAnimation(e){this.uniforms.uvAnimationScrollXOffset.value+=e*this.uvAnimationScrollXSpeedFactor,this.uniforms.uvAnimationScrollYOffset.value+=e*this.uvAnimationScrollYSpeedFactor,this.uniforms.uvAnimationRotationPhase.value+=e*this.uvAnimationRotationSpeedFactor,this.uniforms.alphaTest.value=this.alphaTest,this.uniformsNeedUpdate=!0}_uploadUniformsWorkaround(){this.uniforms.opacity.value=this.opacity,this._updateTextureMatrix(this.uniforms.map,this.uniforms.mapUvTransform),this._updateTextureMatrix(this.uniforms.normalMap,this.uniforms.normalMapUvTransform),this._updateTextureMatrix(this.uniforms.emissiveMap,this.uniforms.emissiveMapUvTransform),this._updateTextureMatrix(this.uniforms.shadeMultiplyTexture,this.uniforms.shadeMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.shadingShiftTexture,this.uniforms.shadingShiftTextureUvTransform),this._updateTextureMatrix(this.uniforms.matcapTexture,this.uniforms.matcapTextureUvTransform),this._updateTextureMatrix(this.uniforms.rimMultiplyTexture,this.uniforms.rimMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.outlineWidthMultiplyTexture,this.uniforms.outlineWidthMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.uvAnimationMaskTexture,this.uniforms.uvAnimationMaskTextureUvTransform),this.uniformsNeedUpdate=!0}_generateDefines(){let e=this.outlineWidthMultiplyTexture!==null,t=this.map!==null||this.normalMap!==null||this.emissiveMap!==null||this.shadeMultiplyTexture!==null||this.shadingShiftTexture!==null||this.rimMultiplyTexture!==null||this.uvAnimationMaskTexture!==null;return{THREE_VRM_THREE_REVISION:184,OUTLINE:this._isOutline,MTOON_USE_UV:e||t,MTOON_UVS_VERTEX_ONLY:e&&!t,V0_COMPAT_SHADE:this._v0CompatShade,USE_SHADEMULTIPLYTEXTURE:this.shadeMultiplyTexture!==null,USE_SHADINGSHIFTTEXTURE:this.shadingShiftTexture!==null,USE_MATCAPTEXTURE:this.matcapTexture!==null,USE_RIMMULTIPLYTEXTURE:this.rimMultiplyTexture!==null,USE_OUTLINEWIDTHMULTIPLYTEXTURE:this._isOutline&&this.outlineWidthMultiplyTexture!==null,USE_UVANIMATIONMASKTEXTURE:this.uvAnimationMaskTexture!==null,IGNORE_VERTEX_COLOR:this._ignoreVertexColor===!0,DEBUG_NORMAL:this._debugMode===`normal`,DEBUG_LITSHADERATE:this._debugMode===`litShadeRate`,DEBUG_UV:this._debugMode===`uv`,OUTLINE_WIDTH_SCREEN:this._isOutline&&this._outlineWidthMode===GC.ScreenCoordinates}}_updateTextureMatrix(e,t){e.value&&(e.value.matrixAutoUpdate&&e.value.updateMatrix(),t.value.copy(e.value.matrix))}},JC=new Set([`1.0`,`1.0-beta`]),YC=class e{get name(){return e.EXTENSION_NAME}constructor(e,t={}){this.parser=e,this.materialType=t.materialType??qC,this.renderOrderOffset=t.renderOrderOffset??0,this.v0CompatShade=t.v0CompatShade??!1,this.debugMode=t.debugMode??`none`,this._mToonMaterialSet=new Set}beforeRoot(){return zC(this,null,function*(){this._removeUnlitExtensionIfMToonExists()})}afterRoot(e){return zC(this,null,function*(){e.userData.vrmMToonMaterials=Array.from(this._mToonMaterialSet)})}getMaterialType(e){return this._getMToonExtension(e)?this.materialType:null}extendMaterialParams(e,t){let n=this._getMToonExtension(e);return n?this._extendMaterialParams(n,t):null}loadMesh(e){return zC(this,null,function*(){let t=this.parser,n=t.json.meshes?.[e];if(n==null)throw Error(`MToonMaterialLoaderPlugin: Attempt to use meshes[${e}] of glTF but the mesh doesn't exist`);let r=n.primitives,i=yield t.loadMesh(e);if(r.length===1){let e=i,t=r[0].material;t!=null&&this._setupPrimitive(e,t)}else{let e=i;for(let t=0;t<r.length;t++){let n=e.children[t],i=r[t].material;i!=null&&this._setupPrimitive(n,i)}}return i})}_removeUnlitExtensionIfMToonExists(){this.parser.json.materials?.map((e,t)=>{this._getMToonExtension(t)&&e.extensions?.KHR_materials_unlit&&delete e.extensions.KHR_materials_unlit})}_getMToonExtension(t){let n=this.parser.json.materials?.[t];if(n==null){console.warn(`MToonMaterialLoaderPlugin: Attempt to use materials[${t}] of glTF but the material doesn't exist`);return}let r=n.extensions?.[e.EXTENSION_NAME];if(r==null)return;let i=r.specVersion;if(!JC.has(i)){console.warn(`MToonMaterialLoaderPlugin: Unknown ${e.EXTENSION_NAME} specVersion "${i}"`);return}return r}_extendMaterialParams(e,t){return zC(this,null,function*(){delete t.metalness,delete t.roughness;let n=new VC(this.parser,t);n.assignPrimitive(`transparentWithZWrite`,e.transparentWithZWrite),n.assignColor(`shadeColorFactor`,e.shadeColorFactor),n.assignTexture(`shadeMultiplyTexture`,e.shadeMultiplyTexture,!0),n.assignPrimitive(`shadingShiftFactor`,e.shadingShiftFactor),n.assignTexture(`shadingShiftTexture`,e.shadingShiftTexture,!0),n.assignPrimitive(`shadingShiftTextureScale`,e.shadingShiftTexture?.scale),n.assignPrimitive(`shadingToonyFactor`,e.shadingToonyFactor),n.assignPrimitive(`giEqualizationFactor`,e.giEqualizationFactor),n.assignColor(`matcapFactor`,e.matcapFactor),n.assignTexture(`matcapTexture`,e.matcapTexture,!0),n.assignColor(`parametricRimColorFactor`,e.parametricRimColorFactor),n.assignTexture(`rimMultiplyTexture`,e.rimMultiplyTexture,!0),n.assignPrimitive(`rimLightingMixFactor`,e.rimLightingMixFactor),n.assignPrimitive(`parametricRimFresnelPowerFactor`,e.parametricRimFresnelPowerFactor),n.assignPrimitive(`parametricRimLiftFactor`,e.parametricRimLiftFactor),n.assignPrimitive(`outlineWidthMode`,e.outlineWidthMode),n.assignPrimitive(`outlineWidthFactor`,e.outlineWidthFactor),n.assignTexture(`outlineWidthMultiplyTexture`,e.outlineWidthMultiplyTexture,!1),n.assignColor(`outlineColorFactor`,e.outlineColorFactor),n.assignPrimitive(`outlineLightingMixFactor`,e.outlineLightingMixFactor),n.assignTexture(`uvAnimationMaskTexture`,e.uvAnimationMaskTexture,!1),n.assignPrimitive(`uvAnimationScrollXSpeedFactor`,e.uvAnimationScrollXSpeedFactor),n.assignPrimitive(`uvAnimationScrollYSpeedFactor`,e.uvAnimationScrollYSpeedFactor),n.assignPrimitive(`uvAnimationRotationSpeedFactor`,e.uvAnimationRotationSpeedFactor),n.assignPrimitive(`v0CompatShade`,this.v0CompatShade),n.assignPrimitive(`debugMode`,this.debugMode),yield n.pending})}_setupPrimitive(e,t){let n=this._getMToonExtension(t);if(n){e.renderOrder=this._parseRenderOrder(n)+this.renderOrderOffset,this._generateOutline(e),this._addToMaterialSet(e);return}}_shouldGenerateOutline(e){return typeof e.outlineWidthMode==`string`&&e.outlineWidthMode!==`none`&&typeof e.outlineWidthFactor==`number`&&e.outlineWidthFactor>0}_generateOutline(e){let t=e.material;if(!(t instanceof Ll)||!this._shouldGenerateOutline(t))return;e.material=[t];let n=t.clone();n.name+=` (Outline)`,n.isOutline=!0,n.side=1,e.material.push(n);let r=e.geometry,i=r.index?r.index.count:r.attributes.position.count/3;r.addGroup(0,i,0),r.addGroup(0,i,1)}_addToMaterialSet(e){let t=e.material,n=new Set;Array.isArray(t)?t.forEach(e=>n.add(e)):n.add(t);for(let e of n)this._mToonMaterialSet.add(e)}_parseRenderOrder(e){return(e.transparentWithZWrite?0:19)+(e.renderQueueOffsetNumber??0)}};YC.EXTENSION_NAME=`VRMC_materials_mtoon`;var XC=YC,ZC=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),QC=class e{get name(){return e.EXTENSION_NAME}constructor(e){this.parser=e}extendMaterialParams(e,t){return ZC(this,null,function*(){let n=this._getHDREmissiveMultiplierExtension(e);n!=null&&(console.warn("VRMMaterialsHDREmissiveMultiplierLoaderPlugin: `VRMC_materials_hdr_emissiveMultiplier` is archived. Use `KHR_materials_emissive_strength` instead."),t.emissiveIntensity=n.emissiveMultiplier)})}_getHDREmissiveMultiplierExtension(t){let n=this.parser.json.materials?.[t];if(n==null){console.warn(`VRMMaterialsHDREmissiveMultiplierLoaderPlugin: Attempt to use materials[${t}] of glTF but the material doesn't exist`);return}let r=n.extensions?.[e.EXTENSION_NAME];if(r!=null)return r}};QC.EXTENSION_NAME=`VRMC_materials_hdr_emissiveMultiplier`;var $C=QC,ew=Object.defineProperty,tw=Object.defineProperties,nw=Object.getOwnPropertyDescriptors,rw=Object.getOwnPropertySymbols,iw=Object.prototype.hasOwnProperty,aw=Object.prototype.propertyIsEnumerable,ow=(e,t,n)=>t in e?ew(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,sw=(e,t)=>{for(var n in t||={})iw.call(t,n)&&ow(e,n,t[n]);if(rw)for(var n of rw(t))aw.call(t,n)&&ow(e,n,t[n]);return e},cw=(e,t)=>tw(e,nw(t)),lw=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())});function uw(e){return e**2.2}var dw=class{get name(){return`VRMMaterialsV0CompatPlugin`}constructor(e){this.parser=e,this._renderQueueMapTransparent=new Map,this._renderQueueMapTransparentZWrite=new Map;let t=this.parser.json;t.extensionsUsed=t.extensionsUsed??[],t.extensionsUsed.indexOf(`KHR_texture_transform`)===-1&&t.extensionsUsed.push(`KHR_texture_transform`)}beforeRoot(){return lw(this,null,function*(){let e=this.parser.json,t=e.extensions?.VRM?.materialProperties;t&&(this._populateRenderQueueMap(t),t.forEach((t,n)=>{let r=e.materials?.[n];if(r==null){console.warn(`VRMMaterialsV0CompatPlugin: Attempt to use materials[${n}] of glTF but the material doesn't exist`);return}if(t.shader===`VRM/MToon`){let i=this._parseV0MToonProperties(t,r);e.materials[n]=i}else if(t.shader?.startsWith(`VRM/Unlit`)){let i=this._parseV0UnlitProperties(t,r);e.materials[n]=i}else t.shader===`VRM_USE_GLTFSHADER`||console.warn(`VRMMaterialsV0CompatPlugin: Unknown shader: ${t.shader}`)}))})}_parseV0MToonProperties(e,t){let n=e.keywordMap?._ALPHABLEND_ON??!1,r=e.floatProperties?._ZWrite===1&&n,i=this._v0ParseRenderQueue(e),a=e.keywordMap?._ALPHATEST_ON??!1,o=n?`BLEND`:a?`MASK`:`OPAQUE`,s=a?e.floatProperties?._Cutoff??.5:void 0,c=(e.floatProperties?._CullMode??2)===0,l=this._portTextureTransform(e),u=(e.vectorProperties?._Color??[1,1,1,1]).map((e,t)=>t===3?e:uw(e)),d=e.textureProperties?._MainTex,f=d==null?void 0:{index:d,extensions:sw({},l)},p=e.floatProperties?._BumpScale??1,m=e.textureProperties?._BumpMap,h=m==null?void 0:{index:m,scale:p,extensions:sw({},l)},g=(e.vectorProperties?._EmissionColor??[0,0,0,1]).map(uw),_=e.textureProperties?._EmissionMap,v=_==null?void 0:{index:_,extensions:sw({},l)},y=(e.vectorProperties?._ShadeColor??[.97,.81,.86,1]).map(uw),b=e.textureProperties?._ShadeTexture,x=b==null?void 0:{index:b,extensions:sw({},l)},S=e.floatProperties?._ShadeShift??0,C=e.floatProperties?._ShadeToony??.9;C=As.lerp(C,1,.5+.5*S),S=-S-(1-C);let w=e.floatProperties?._IndirectLightIntensity??.1,T=w?1-w:void 0,E=e.textureProperties?._SphereAdd,D=E==null?void 0:[1,1,1],O=E==null?void 0:{index:E},k=e.floatProperties?._RimLightingMix??0,A=e.textureProperties?._RimTexture,ee=A==null?void 0:{index:A,extensions:sw({},l)},te=(e.vectorProperties?._RimColor??[0,0,0,1]).map(uw),ne=e.floatProperties?._RimFresnelPower??1,re=e.floatProperties?._RimLift??0,ie=[`none`,`worldCoordinates`,`screenCoordinates`][e.floatProperties?._OutlineWidthMode??0],ae=e.floatProperties?._OutlineWidth??0;ae=.01*ae;let j=e.textureProperties?._OutlineWidthTexture,oe=j==null?void 0:{index:j,extensions:sw({},l)},se=(e.vectorProperties?._OutlineColor??[0,0,0]).map(uw),ce=(e.floatProperties?._OutlineColorMode??0)===1?e.floatProperties?._OutlineLightingMix??1:0,le=e.textureProperties?._UvAnimMaskTexture,ue=le==null?void 0:{index:le,extensions:sw({},l)},M=e.floatProperties?._UvAnimScrollX??0,de=e.floatProperties?._UvAnimScrollY??0;de!=null&&(de=-de);let fe=e.floatProperties?._UvAnimRotation??0,pe={specVersion:`1.0`,transparentWithZWrite:r,renderQueueOffsetNumber:i,shadeColorFactor:y,shadeMultiplyTexture:x,shadingShiftFactor:S,shadingToonyFactor:C,giEqualizationFactor:T,matcapFactor:D,matcapTexture:O,rimLightingMixFactor:k,rimMultiplyTexture:ee,parametricRimColorFactor:te,parametricRimFresnelPowerFactor:ne,parametricRimLiftFactor:re,outlineWidthMode:ie,outlineWidthFactor:ae,outlineWidthMultiplyTexture:oe,outlineColorFactor:se,outlineLightingMixFactor:ce,uvAnimationMaskTexture:ue,uvAnimationScrollXSpeedFactor:M,uvAnimationScrollYSpeedFactor:de,uvAnimationRotationSpeedFactor:fe};return cw(sw({},t),{pbrMetallicRoughness:{baseColorFactor:u,baseColorTexture:f},normalTexture:h,emissiveTexture:v,emissiveFactor:g,alphaMode:o,alphaCutoff:s,doubleSided:c,extensions:{VRMC_materials_mtoon:pe}})}_parseV0UnlitProperties(e,t){let n=e.shader===`VRM/UnlitTransparentZWrite`,r=e.shader===`VRM/UnlitTransparent`||n,i=this._v0ParseRenderQueue(e),a=e.shader===`VRM/UnlitCutout`,o=r?`BLEND`:a?`MASK`:`OPAQUE`,s=a?e.floatProperties?._Cutoff??.5:void 0,c=this._portTextureTransform(e),l=(e.vectorProperties?._Color??[1,1,1,1]).map(uw),u=e.textureProperties?._MainTex,d=u==null?void 0:{index:u,extensions:sw({},c)},f={specVersion:`1.0`,transparentWithZWrite:n,renderQueueOffsetNumber:i,shadeColorFactor:l,shadeMultiplyTexture:d};return cw(sw({},t),{pbrMetallicRoughness:{baseColorFactor:l,baseColorTexture:d},alphaMode:o,alphaCutoff:s,extensions:{VRMC_materials_mtoon:f}})}_portTextureTransform(e){let t=e.vectorProperties?._MainTex;if(t==null)return{};let n=[t?.[0]??0,t?.[1]??0],r=[t?.[2]??1,t?.[3]??1];return n[1]=1-r[1]-n[1],{KHR_texture_transform:{offset:n,scale:r}}}_v0ParseRenderQueue(e){let t=e.shader===`VRM/UnlitTransparentZWrite`,n=e.keywordMap?._ALPHABLEND_ON!=null||e.shader===`VRM/UnlitTransparent`||t,r=e.floatProperties?._ZWrite===1||t,i=0;if(n){let t=e.renderQueue;t!=null&&(i=r?this._renderQueueMapTransparentZWrite.get(t):this._renderQueueMapTransparent.get(t))}return i}_populateRenderQueueMap(e){let t=new Set,n=new Set;e.forEach(e=>{let r=e.shader===`VRM/UnlitTransparentZWrite`,i=e.keywordMap?._ALPHABLEND_ON!=null||e.shader===`VRM/UnlitTransparent`||r,a=e.floatProperties?._ZWrite===1||r;if(i){let r=e.renderQueue;r!=null&&(a?n.add(r):t.add(r))}}),t.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${t.size} render queues for Transparent materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),n.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${n.size} render queues for TransparentZWrite materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),Array.from(t).sort().forEach((e,n)=>{let r=Math.min(Math.max(n-t.size+1,-9),0);this._renderQueueMapTransparent.set(e,r)}),Array.from(n).sort().forEach((e,t)=>{let n=Math.min(Math.max(t,0),9);this._renderQueueMapTransparentZWrite.set(e,n)})}},fw=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),pw=new W,mw=class extends Ec{constructor(e){super(),this._attrPosition=new J(new Float32Array([0,0,0,0,0,0]),3),this._attrPosition.setUsage(Wo);let t=new Y;t.setAttribute(`position`,this._attrPosition);let n=new zu({color:16711935,depthTest:!1,depthWrite:!1});this._line=new qu(t,n),this.add(this._line),this.constraint=e}updateMatrixWorld(e){pw.setFromMatrixPosition(this.constraint.destination.matrixWorld),this._attrPosition.setXYZ(0,pw.x,pw.y,pw.z),this.constraint.source&&pw.setFromMatrixPosition(this.constraint.source.matrixWorld),this._attrPosition.setXYZ(1,pw.x,pw.y,pw.z),this._attrPosition.needsUpdate=!0,super.updateMatrixWorld(e)}};function hw(e,t){return t.set(e.elements[12],e.elements[13],e.elements[14])}var gw=new W,_w=new W;function vw(e,t){return e.decompose(gw,t,_w),t}function yw(e){return e.invert?e.invert():e.inverse(),e}var bw=class{constructor(e,t){this.destination=e,this.source=t,this.weight=1}},xw=new W,Sw=new W,Cw=new W,ww=new U,Tw=new U,Ew=new U,Dw=class extends bw{get aimAxis(){return this._aimAxis}set aimAxis(e){this._aimAxis=e,this._v3AimAxis.set(e===`PositiveX`?1:e===`NegativeX`?-1:0,e===`PositiveY`?1:e===`NegativeY`?-1:0,e===`PositiveZ`?1:e===`NegativeZ`?-1:0)}get dependencies(){let e=new Set([this.source]);return this.destination.parent&&e.add(this.destination.parent),e}constructor(e,t){super(e,t),this._aimAxis=`PositiveX`,this._v3AimAxis=new W(1,0,0),this._dstRestQuat=new U}setInitState(){this._dstRestQuat.copy(this.destination.quaternion)}update(){this.destination.updateWorldMatrix(!0,!1),this.source.updateWorldMatrix(!0,!1);let e=ww.identity(),t=Tw.identity();this.destination.parent&&(vw(this.destination.parent.matrixWorld,e),yw(t.copy(e)));let n=xw.copy(this._v3AimAxis).applyQuaternion(this._dstRestQuat).applyQuaternion(e),r=hw(this.source.matrixWorld,Sw).sub(hw(this.destination.matrixWorld,Cw)).normalize(),i=Ew.setFromUnitVectors(n,r).premultiply(t).multiply(e).multiply(this._dstRestQuat);this.destination.quaternion.copy(this._dstRestQuat).slerp(i,this.weight)}};function Ow(e,t){let n=[e],r=e.parent;for(;r!==null;)n.unshift(r),r=r.parent;n.forEach(e=>{t(e)})}var kw=class{constructor(){this._constraints=new Set,this._objectConstraintsMap=new Map}get constraints(){return this._constraints}addConstraint(e){this._constraints.add(e);let t=this._objectConstraintsMap.get(e.destination);t??(t=new Set,this._objectConstraintsMap.set(e.destination,t)),t.add(e)}deleteConstraint(e){this._constraints.delete(e),this._objectConstraintsMap.get(e.destination).delete(e)}setInitState(){let e=new Set,t=new Set;for(let n of this._constraints)this._processConstraint(n,e,t,e=>e.setInitState())}update(){let e=new Set,t=new Set;for(let n of this._constraints)this._processConstraint(n,e,t,e=>e.update())}_processConstraint(e,t,n,r){if(n.has(e))return;if(t.has(e))throw Error(`VRMNodeConstraintManager: Circular dependency detected while updating constraints`);t.add(e);let i=e.dependencies;for(let e of i)Ow(e,e=>{let i=this._objectConstraintsMap.get(e);if(i)for(let e of i)this._processConstraint(e,t,n,r)});r(e),n.add(e)}},Aw=new U,jw=new U,Mw=class extends bw{get dependencies(){return new Set([this.source])}constructor(e,t){super(e,t),this._dstRestQuat=new U,this._invSrcRestQuat=new U}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),yw(this._invSrcRestQuat.copy(this.source.quaternion))}update(){let e=Aw.copy(this._invSrcRestQuat).multiply(this.source.quaternion),t=jw.copy(this._dstRestQuat).multiply(e);this.destination.quaternion.copy(this._dstRestQuat).slerp(t,this.weight)}},Nw=new W,Pw=new U,Fw=new U,Iw=class extends bw{get rollAxis(){return this._rollAxis}set rollAxis(e){this._rollAxis=e,this._v3RollAxis.set(+(e===`X`),+(e===`Y`),+(e===`Z`))}get dependencies(){return new Set([this.source])}constructor(e,t){super(e,t),this._rollAxis=`X`,this._v3RollAxis=new W(1,0,0),this._dstRestQuat=new U,this._invDstRestQuat=new U,this._invSrcRestQuatMulDstRestQuat=new U}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),yw(this._invDstRestQuat.copy(this._dstRestQuat)),yw(this._invSrcRestQuatMulDstRestQuat.copy(this.source.quaternion)).multiply(this._dstRestQuat)}update(){let e=Pw.copy(this._invDstRestQuat).multiply(this.source.quaternion).multiply(this._invSrcRestQuatMulDstRestQuat),t=Nw.copy(this._v3RollAxis).applyQuaternion(e),n=Fw.setFromUnitVectors(t,this._v3RollAxis).premultiply(this._dstRestQuat).multiply(e);this.destination.quaternion.copy(this._dstRestQuat).slerp(n,this.weight)}},Lw=new Set([`1.0`,`1.0-beta`]),Rw=class e{get name(){return e.EXTENSION_NAME}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot}afterRoot(e){return fw(this,null,function*(){e.userData.vrmNodeConstraintManager=yield this._import(e)})}_import(t){return fw(this,null,function*(){let n=this.parser.json;if(n.extensionsUsed?.indexOf(e.EXTENSION_NAME)===-1)return null;let r=new kw,i=yield this.parser.getDependencies(`node`);return i.forEach((t,a)=>{let o=n.nodes[a]?.extensions?.[e.EXTENSION_NAME];if(o==null)return;let s=o.specVersion;if(!Lw.has(s)){console.warn(`VRMNodeConstraintLoaderPlugin: Unknown ${e.EXTENSION_NAME} specVersion "${s}"`);return}let c=o.constraint;if(c.roll!=null){let e=this._importRollConstraint(t,i,c.roll);r.addConstraint(e)}else if(c.aim!=null){let e=this._importAimConstraint(t,i,c.aim);r.addConstraint(e)}else if(c.rotation!=null){let e=this._importRotationConstraint(t,i,c.rotation);r.addConstraint(e)}}),t.scene.updateMatrixWorld(),r.setInitState(),r})}_importRollConstraint(e,t,n){let{source:r,rollAxis:i,weight:a}=n,o=t[r],s=new Iw(e,o);if(i!=null&&(s.rollAxis=i),a!=null&&(s.weight=a),this.helperRoot){let e=new mw(s);this.helperRoot.add(e)}return s}_importAimConstraint(e,t,n){let{source:r,aimAxis:i,weight:a}=n,o=t[r],s=new Dw(e,o);if(i!=null&&(s.aimAxis=i),a!=null&&(s.weight=a),this.helperRoot){let e=new mw(s);this.helperRoot.add(e)}return s}_importRotationConstraint(e,t,n){let{source:r,weight:i}=n,a=t[r],o=new Mw(e,a);if(i!=null&&(o.weight=i),this.helperRoot){let e=new mw(o);this.helperRoot.add(e)}return o}};Rw.EXTENSION_NAME=`VRMC_node_constraint`;var zw=Rw,Bw=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),Vw=class{},Hw=new W,Uw=new W,Ww=class extends Vw{get type(){return`capsule`}constructor(e){super(),this.offset=e?.offset??new W(0,0,0),this.tail=e?.tail??new W(0,0,0),this.radius=e?.radius??0,this.inside=e?.inside??!1}calculateCollision(e,t,n,r){Hw.setFromMatrixPosition(e),Uw.subVectors(this.tail,this.offset).applyMatrix4(e),Uw.sub(Hw);let i=Uw.lengthSq();r.copy(t).sub(Hw);let a=Uw.dot(r);a<=0||(i<=a||Uw.multiplyScalar(a/i),r.sub(Uw));let o=r.length(),s=this.inside?this.radius-n-o:o-n-this.radius;return s<0&&(r.multiplyScalar(1/o),this.inside&&r.negate()),s}},Gw=new W,Kw=new G,qw=class extends Vw{get type(){return`plane`}constructor(e){super(),this.offset=e?.offset??new W(0,0,0),this.normal=e?.normal??new W(0,0,1)}calculateCollision(e,t,n,r){r.setFromMatrixPosition(e),r.negate().add(t),Kw.getNormalMatrix(e),Gw.copy(this.normal).applyNormalMatrix(Kw).normalize();let i=r.dot(Gw)-n;return r.copy(Gw),i}},Jw=new W,Yw=class extends Vw{get type(){return`sphere`}constructor(e){super(),this.offset=e?.offset??new W(0,0,0),this.radius=e?.radius??0,this.inside=e?.inside??!1}calculateCollision(e,t,n,r){r.subVectors(t,Jw.setFromMatrixPosition(e));let i=r.length(),a=this.inside?this.radius-n-i:i-n-this.radius;return a<0&&(r.multiplyScalar(1/i),this.inside&&r.negate()),a}},Xw=new W,Zw=class extends Y{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new W,this._currentTail=new W,this._shape=e,this._attrPos=new J(new Float32Array(396),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new J(new Uint16Array(264),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1,t=this._shape.radius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0);let n=Xw.copy(this._shape.tail).divideScalar(this.worldScale);this._currentTail.distanceToSquared(n)>1e-10&&(this._currentTail.copy(n),e=!0),e&&this._buildPosition()}_buildPosition(){Xw.copy(this._currentTail).sub(this._currentOffset);let e=Xw.length()/this._currentRadius;for(let t=0;t<=16;t++){let n=t/16*Math.PI;this._attrPos.setXYZ(t,-Math.sin(n),-Math.cos(n),0),this._attrPos.setXYZ(17+t,e+Math.sin(n),Math.cos(n),0),this._attrPos.setXYZ(34+t,-Math.sin(n),0,-Math.cos(n)),this._attrPos.setXYZ(51+t,e+Math.sin(n),0,Math.cos(n))}for(let t=0;t<32;t++){let n=t/16*Math.PI;this._attrPos.setXYZ(68+t,0,Math.sin(n),Math.cos(n)),this._attrPos.setXYZ(100+t,e,Math.sin(n),Math.cos(n))}let t=Math.atan2(Xw.y,Math.sqrt(Xw.x*Xw.x+Xw.z*Xw.z)),n=-Math.atan2(Xw.z,Xw.x);this.rotateZ(t),this.rotateY(n),this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<34;e++){let t=(e+1)%34;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(68+e*2,34+e,34+t)}for(let e=0;e<32;e++){let t=(e+1)%32;this._attrIndex.setXY(136+e*2,68+e,68+t),this._attrIndex.setXY(200+e*2,100+e,100+t)}this._attrIndex.needsUpdate=!0}},Qw=class extends Y{constructor(e){super(),this.worldScale=1,this._currentOffset=new W,this._currentNormal=new W,this._shape=e,this._attrPos=new J(new Float32Array(18),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new J(new Uint16Array(10),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0),this._currentNormal.equals(this._shape.normal)||(this._currentNormal.copy(this._shape.normal),e=!0),e&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,-.5,-.5,0),this._attrPos.setXYZ(1,.5,-.5,0),this._attrPos.setXYZ(2,.5,.5,0),this._attrPos.setXYZ(3,-.5,.5,0),this._attrPos.setXYZ(4,0,0,0),this._attrPos.setXYZ(5,0,0,.25),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this.lookAt(this._currentNormal),this._attrPos.needsUpdate=!0}_buildIndex(){this._attrIndex.setXY(0,0,1),this._attrIndex.setXY(2,1,2),this._attrIndex.setXY(4,2,3),this._attrIndex.setXY(6,3,0),this._attrIndex.setXY(8,4,5),this._attrIndex.needsUpdate=!0}},$w=class extends Y{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new W,this._shape=e,this._attrPos=new J(new Float32Array(288),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new J(new Uint16Array(192),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1,t=this._shape.radius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){let t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<32;e++){let t=(e+1)%32;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(64+e*2,32+e,32+t),this._attrIndex.setXY(128+e*2,64+e,64+t)}this._attrIndex.needsUpdate=!0}},eT=new W,tT=class extends Ec{constructor(e){if(super(),this.matrixAutoUpdate=!1,this.collider=e,this.collider.shape instanceof Yw)this._geometry=new $w(this.collider.shape);else if(this.collider.shape instanceof Ww)this._geometry=new Zw(this.collider.shape);else if(this.collider.shape instanceof qw)this._geometry=new Qw(this.collider.shape);else throw Error(`VRMSpringBoneColliderHelper: Unknown collider shape type detected`);let t=new zu({color:16711935,depthTest:!1,depthWrite:!1});this._line=new Zu(this._geometry,t),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.collider.updateWorldMatrix(!0,!1),this.matrix.copy(this.collider.matrixWorld);let t=this.matrix.elements;this._geometry.worldScale=eT.set(t[0],t[1],t[2]).length(),this._geometry.update(),super.updateMatrixWorld(e)}},nT=class extends Y{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentTail=new W,this._springBone=e,this._attrPos=new J(new Float32Array(294),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new J(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1,t=this._springBone.settings.hitRadius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentTail.equals(this._springBone.initialLocalChildPosition)||(this._currentTail.copy(this._springBone.initialLocalChildPosition),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){let t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<32;e++){let t=(e+1)%32;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(64+e*2,32+e,32+t),this._attrIndex.setXY(128+e*2,64+e,64+t)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},rT=new W,iT=class extends Ec{constructor(e){super(),this.matrixAutoUpdate=!1,this.springBone=e,this._geometry=new nT(this.springBone);let t=new zu({color:16776960,depthTest:!1,depthWrite:!1});this._line=new Zu(this._geometry,t),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.springBone.bone.updateWorldMatrix(!0,!1),this.matrix.copy(this.springBone.bone.matrixWorld);let t=this.matrix.elements;this._geometry.worldScale=rT.set(t[0],t[1],t[2]).length(),this._geometry.update(),super.updateMatrixWorld(e)}},aT=class extends Tc{constructor(e){super(),this.colliderMatrix=new K,this.shape=e}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),oT(this.colliderMatrix,this.matrixWorld,this.shape.offset)}};function oT(e,t,n){let r=t.elements;e.copy(t),n&&(e.elements[12]=r[0]*n.x+r[4]*n.y+r[8]*n.z+r[12],e.elements[13]=r[1]*n.x+r[5]*n.y+r[9]*n.z+r[13],e.elements[14]=r[2]*n.x+r[6]*n.y+r[10]*n.z+r[14])}var sT=new K;function cT(e){return e.invert?e.invert():e.getInverse(sT.copy(e)),e}var lT=class{constructor(e){this._inverseCache=new K,this._shouldUpdateInverse=!0,this.matrix=e;let 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&&=(cT(this._inverseCache.copy(this.matrix)),!1),this._inverseCache}revert(){this.matrix.elements=this._originalElements}},uT=new K,dT=new W,fT=new W,pT=new W,mT=new W,hT=new K,gT=class{constructor(e,t,n={},r=[]){this._currentTail=new W,this._prevTail=new W,this._boneAxis=new W,this._worldSpaceBoneLength=0,this._center=null,this._initialLocalMatrix=new K,this._initialLocalRotation=new U,this._initialLocalChildPosition=new W,this.bone=e,this.bone.matrixAutoUpdate=!1,this.child=t,this.settings={hitRadius:n.hitRadius??0,stiffness:n.stiffness??1,gravityPower:n.gravityPower??0,gravityDir:n.gravityDir?.clone()??new W(0,-1,0),dragForce:n.dragForce??.4},this.colliderGroups=r}get dependencies(){let e=new Set,t=this.bone.parent;t&&e.add(t);for(let t=0;t<this.colliderGroups.length;t++)for(let n=0;n<this.colliderGroups[t].colliders.length;n++)e.add(this.colliderGroups[t].colliders[n]);return e}get center(){return this._center}set center(e){this._center?.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 lT(this._center.matrixWorld)))}get initialLocalChildPosition(){return this._initialLocalChildPosition}get _parentMatrixWorld(){return this.bone.parent?this.bone.parent.matrixWorld:uT}setInitState(){this._initialLocalMatrix.copy(this.bone.matrix),this._initialLocalRotation.copy(this.bone.quaternion),this.child?this._initialLocalChildPosition.copy(this.child.position):this._initialLocalChildPosition.copy(this.bone.position).normalize().multiplyScalar(.07);let e=this._getMatrixWorldToCenter();this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(e),this._prevTail.copy(this._currentTail),this._boneAxis.copy(this._initialLocalChildPosition).normalize()}reset(){this.bone.quaternion.copy(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix);let e=this._getMatrixWorldToCenter();this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(e),this._prevTail.copy(this._currentTail)}update(e){if(e<=0)return;this._calcWorldSpaceBoneLength();let t=fT.copy(this._boneAxis).transformDirection(this._initialLocalMatrix).transformDirection(this._parentMatrixWorld);mT.copy(this._currentTail).add(dT.subVectors(this._currentTail,this._prevTail).multiplyScalar(1-this.settings.dragForce)).applyMatrix4(this._getMatrixCenterToWorld()).addScaledVector(t,this.settings.stiffness*e).addScaledVector(this.settings.gravityDir,this.settings.gravityPower*e),pT.setFromMatrixPosition(this.bone.matrixWorld),mT.sub(pT).normalize().multiplyScalar(this._worldSpaceBoneLength).add(pT),this._collision(mT),this._prevTail.copy(this._currentTail),this._currentTail.copy(mT).applyMatrix4(this._getMatrixWorldToCenter());let n=hT.multiplyMatrices(this._parentMatrixWorld,this._initialLocalMatrix).invert();this.bone.quaternion.setFromUnitVectors(this._boneAxis,dT.copy(mT).applyMatrix4(n).normalize()).premultiply(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix)}_collision(e){for(let t=0;t<this.colliderGroups.length;t++)for(let n=0;n<this.colliderGroups[t].colliders.length;n++){let r=this.colliderGroups[t].colliders[n],i=r.shape.calculateCollision(r.colliderMatrix,e,this.settings.hitRadius,dT);if(i<0){e.addScaledVector(dT,-i),e.sub(pT);let t=e.length();e.multiplyScalar(this._worldSpaceBoneLength/t).add(pT)}}}_calcWorldSpaceBoneLength(){dT.setFromMatrixPosition(this.bone.matrixWorld),this.child?fT.setFromMatrixPosition(this.child.matrixWorld):(fT.copy(this._initialLocalChildPosition),fT.applyMatrix4(this.bone.matrixWorld)),this._worldSpaceBoneLength=dT.sub(fT).length()}_getMatrixCenterToWorld(){return this._center?this._center.matrixWorld:uT}_getMatrixWorldToCenter(){return this._center?this._center.userData.inverseCacheProxy.inverse:uT}};function _T(e,t){let n=[],r=e;for(;r!==null;)n.unshift(r),r=r.parent;n.forEach(e=>{t(e)})}function vT(e,t){e.children.forEach(e=>{t(e)||vT(e,t)})}function yT(e){let t=new Map;for(let n of e){let r=n;do{let n=(t.get(r)??0)+1;if(n===e.size)return r;t.set(r,n),r=r.parent}while(r!==null)}return null}var bT=class{constructor(){this._joints=new Set,this._sortedJoints=[],this._hasWarnedCircularDependency=!1,this._ancestors=[],this._objectSpringBonesMap=new Map,this._isSortedJointsDirty=!1,this._relevantChildrenUpdated=this._relevantChildrenUpdated.bind(this)}get joints(){return this._joints}get springBones(){return console.warn(`VRMSpringBoneManager: springBones is deprecated. use joints instead.`),this._joints}get colliderGroups(){let e=new Set;return this._joints.forEach(t=>{t.colliderGroups.forEach(t=>{e.add(t)})}),Array.from(e)}get colliders(){let e=new Set;return this.colliderGroups.forEach(t=>{t.colliders.forEach(t=>{e.add(t)})}),Array.from(e)}addJoint(e){this._joints.add(e);let t=this._objectSpringBonesMap.get(e.bone);t??(t=new Set,this._objectSpringBonesMap.set(e.bone,t)),t.add(e),this._isSortedJointsDirty=!0}addSpringBone(e){console.warn(`VRMSpringBoneManager: addSpringBone() is deprecated. use addJoint() instead.`),this.addJoint(e)}deleteJoint(e){this._joints.delete(e),this._objectSpringBonesMap.get(e.bone).delete(e),this._isSortedJointsDirty=!0}deleteSpringBone(e){console.warn(`VRMSpringBoneManager: deleteSpringBone() is deprecated. use deleteJoint() instead.`),this.deleteJoint(e)}setInitState(){this._sortJoints();for(let e=0;e<this._sortedJoints.length;e++){let t=this._sortedJoints[e];t.bone.updateMatrix(),t.bone.updateWorldMatrix(!1,!1),t.setInitState()}}reset(){this._sortJoints();for(let e=0;e<this._sortedJoints.length;e++){let t=this._sortedJoints[e];t.bone.updateMatrix(),t.bone.updateWorldMatrix(!1,!1),t.reset()}}update(e){this._sortJoints();for(let e=0;e<this._ancestors.length;e++)this._ancestors[e].updateWorldMatrix(e===0,!1);for(let t=0;t<this._sortedJoints.length;t++){let n=this._sortedJoints[t];n.bone.updateMatrix(),n.bone.updateWorldMatrix(!1,!1),n.update(e),vT(n.bone,this._relevantChildrenUpdated)}}_sortJoints(){if(!this._isSortedJointsDirty)return;let e=[],t=new Set,n=new Set,r=new Set;for(let i of this._joints)this._insertJointSort(i,t,n,e,r);this._sortedJoints=e;let i=yT(r);this._ancestors=[],i&&(this._ancestors.push(i),vT(i,e=>(this._objectSpringBonesMap.get(e)?.size??0)>0?!0:(this._ancestors.push(e),!1))),this._isSortedJointsDirty=!1}_insertJointSort(e,t,n,r,i){if(n.has(e))return;if(t.has(e)){this._hasWarnedCircularDependency||=(console.warn(`VRMSpringBoneManager: Circular dependency detected`),!0);return}t.add(e);let a=e.dependencies;for(let e of a){let a=!1,o=null;_T(e,e=>{let s=this._objectSpringBonesMap.get(e);if(s)for(let e of s)a=!0,this._insertJointSort(e,t,n,r,i);else a||(o=e)}),o&&i.add(o)}r.push(e),n.add(e)}_relevantChildrenUpdated(e){return(this._objectSpringBonesMap.get(e)?.size??0)>0?!0:(e.updateWorldMatrix(!1,!1),!1)}},xT=`VRMC_springBone_extended_collider`,ST=new Set([`1.0`,`1.0-beta`]),CT=new Set([`1.0`]),wT=class e{get name(){return e.EXTENSION_NAME}constructor(e,t){this.parser=e,this.jointHelperRoot=t?.jointHelperRoot,this.colliderHelperRoot=t?.colliderHelperRoot,this.useExtendedColliders=t?.useExtendedColliders??!0}afterRoot(e){return Bw(this,null,function*(){e.userData.vrmSpringBoneManager=yield this._import(e)})}_import(e){return Bw(this,null,function*(){return(yield this._v1Import(e))??(yield this._v0Import(e))??null})}_v1Import(t){return Bw(this,null,function*(){var n;let r=t.parser.json;if(r.extensionsUsed?.indexOf(e.EXTENSION_NAME)===-1)return null;let i=new bT,a=yield t.parser.getDependencies(`node`),o=r.extensions?.[e.EXTENSION_NAME];if(!o)return null;let s=o.specVersion;if(!ST.has(s))return console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${e.EXTENSION_NAME} specVersion "${s}"`),null;let c=o.colliders?.map((t,n)=>{let r=a[t.node];if(r==null)return console.warn(`VRMSpringBoneLoaderPlugin: The collider #${n} attempted to reference a node #${t.node} but not found. Skipping the collider`),null;let i=t.shape,o=t.extensions?.[xT];if(this.useExtendedColliders&&o!=null){let t=o.specVersion;if(!CT.has(t))console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${xT} specVersion "${t}". Fallbacking to the ${e.EXTENSION_NAME} definition`);else{let e=o.shape;if(e.sphere)return this._importSphereCollider(r,{offset:new W().fromArray(e.sphere.offset??[0,0,0]),radius:e.sphere.radius??0,inside:e.sphere.inside??!1});if(e.capsule)return this._importCapsuleCollider(r,{offset:new W().fromArray(e.capsule.offset??[0,0,0]),radius:e.capsule.radius??0,tail:new W().fromArray(e.capsule.tail??[0,0,0]),inside:e.capsule.inside??!1});if(e.plane)return this._importPlaneCollider(r,{offset:new W().fromArray(e.plane.offset??[0,0,0]),normal:new W().fromArray(e.plane.normal??[0,0,1])})}}if(i.sphere)return this._importSphereCollider(r,{offset:new W().fromArray(i.sphere.offset??[0,0,0]),radius:i.sphere.radius??0,inside:!1});if(i.capsule)return this._importCapsuleCollider(r,{offset:new W().fromArray(i.capsule.offset??[0,0,0]),radius:i.capsule.radius??0,tail:new W().fromArray(i.capsule.tail??[0,0,0]),inside:!1});console.warn(`VRMSpringBoneLoaderPlugin: The collider #${n} has no valid shape. Skipping the collider`)}),l=o.colliderGroups?.map((e,t)=>({colliders:(e.colliders??[]).map(e=>c?.[e]??(console.warn(`VRMSpringBoneLoaderPlugin: The collider group #${t} attempted to reference a collider #${e} but not found. Skipping the collider`),null)).filter(e=>e!=null),name:e.name}));return(n=o.springs)==null||n.forEach((e,t)=>{let n=e.joints,r=e.colliderGroups?.map(e=>l?.[e]??(console.warn(`VRMSpringBoneLoaderPlugin: The spring #${t} attempted to reference a collider group #${e} but not found. Skipping the collider group`),null)).filter(e=>e!=null),o=e.center==null?void 0:a[e.center],s;n.forEach(e=>{if(s){let t=a[s.node],n=a[e.node],c={hitRadius:s.hitRadius,dragForce:s.dragForce,gravityPower:s.gravityPower,stiffness:s.stiffness,gravityDir:s.gravityDir==null?void 0:new W().fromArray(s.gravityDir)},l=this._importJoint(t,n,c,r);o&&(l.center=o),i.addJoint(l)}s=e})}),i.setInitState(),i})}_v0Import(e){return Bw(this,null,function*(){let t=e.parser.json;if(t.extensionsUsed?.indexOf(`VRM`)===-1)return null;let n=t.extensions?.VRM?.secondaryAnimation;if(!n)return null;let r=n?.boneGroups;if(!r)return null;let i=new bT,a=yield e.parser.getDependencies(`node`),o=n.colliderGroups?.map((e,t)=>{let n=a[e.node];return n==null?(console.warn(`VRMSpringBoneLoaderPlugin: The collider group #${t} attempted to reference a node #${e.node} but not found. Skipping the collider group`),null):{colliders:(e.colliders??[]).map((e,t)=>{let r=new W(0,0,0);return e.offset&&r.set(e.offset.x??0,e.offset.y??0,e.offset.z?-e.offset.z:0),this._importSphereCollider(n,{offset:r,radius:e.radius??0,inside:!1})})}});return r?.forEach((e,t)=>{let n=e.bones;n&&n.forEach(n=>{let r=a[n];if(r==null){console.warn(`VRMSpringBoneLoaderPlugin: The spring bone group #${t} attempted to reference a node #${n} but not found. Skipping the node`);return}let s=new W;e.gravityDir?s.set(e.gravityDir.x??0,e.gravityDir.y??0,e.gravityDir.z??0):s.set(0,-1,0);let c=e.center==null?void 0:a[e.center],l={hitRadius:e.hitRadius,dragForce:e.dragForce,gravityPower:e.gravityPower,stiffness:e.stiffiness,gravityDir:s},u=e.colliderGroups?.map(e=>o?.[e]??(console.warn(`VRMSpringBoneLoaderPlugin: The spring #${t} attempted to reference a collider group #${e} but not found. Skipping the collider group`),null)).filter(e=>e!=null);r.traverse(e=>{let t=e.children[0]??null,n=this._importJoint(e,t,l,u);c&&(n.center=c),i.addJoint(n)})})}),e.scene.updateMatrixWorld(),i.setInitState(),i})}_importJoint(e,t,n,r){let i=new gT(e,t,n,r);if(this.jointHelperRoot){let e=new iT(i);this.jointHelperRoot.add(e),e.renderOrder=this.jointHelperRoot.renderOrder}return i}_importSphereCollider(e,t){let n=new aT(new Yw(t));if(e.add(n),this.colliderHelperRoot){let e=new tT(n);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return n}_importCapsuleCollider(e,t){let n=new aT(new Ww(t));if(e.add(n),this.colliderHelperRoot){let e=new tT(n);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return n}_importPlaneCollider(e,t){let n=new aT(new qw(t));if(e.add(n),this.colliderHelperRoot){let e=new tT(n);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return n}};wT.EXTENSION_NAME=`VRMC_springBone`;var TT=wT,ET=class{get name(){return`VRMLoaderPlugin`}constructor(e,t){this.parser=e;let n=t?.helperRoot,r=t?.autoUpdateHumanBones;this.expressionPlugin=t?.expressionPlugin??new SS(e),this.firstPersonPlugin=t?.firstPersonPlugin??new ES(e),this.humanoidPlugin=t?.humanoidPlugin??new GS(e,{helperRoot:n,autoUpdateHumanBones:r}),this.lookAtPlugin=t?.lookAtPlugin??new DC(e,{helperRoot:n}),this.metaPlugin=t?.metaPlugin??new AC(e),this.mtoonMaterialPlugin=t?.mtoonMaterialPlugin??new XC(e),this.materialsHDREmissiveMultiplierPlugin=t?.materialsHDREmissiveMultiplierPlugin??new $C(e),this.materialsV0CompatPlugin=t?.materialsV0CompatPlugin??new dw(e),this.springBonePlugin=t?.springBonePlugin??new TT(e,{colliderHelperRoot:n,jointHelperRoot:n}),this.nodeConstraintPlugin=t?.nodeConstraintPlugin??new zw(e,{helperRoot:n})}beforeRoot(){return nS(this,null,function*(){yield this.materialsV0CompatPlugin.beforeRoot(),yield this.mtoonMaterialPlugin.beforeRoot()})}loadMesh(e){return nS(this,null,function*(){return yield this.mtoonMaterialPlugin.loadMesh(e)})}getMaterialType(e){return this.mtoonMaterialPlugin.getMaterialType(e)??null}extendMaterialParams(e,t){return nS(this,null,function*(){yield this.materialsHDREmissiveMultiplierPlugin.extendMaterialParams(e,t),yield this.mtoonMaterialPlugin.extendMaterialParams(e,t)})}afterRoot(e){return nS(this,null,function*(){yield this.metaPlugin.afterRoot(e),yield this.humanoidPlugin.afterRoot(e),yield this.expressionPlugin.afterRoot(e),yield this.lookAtPlugin.afterRoot(e),yield this.firstPersonPlugin.afterRoot(e),yield this.springBonePlugin.afterRoot(e),yield this.nodeConstraintPlugin.afterRoot(e),yield this.mtoonMaterialPlugin.afterRoot(e);let t=e.userData.vrmMeta,n=e.userData.vrmHumanoid;if(t&&n){let r=new MC({scene:e.scene,expressionManager:e.userData.vrmExpressionManager,firstPerson:e.userData.vrmFirstPerson,humanoid:n,lookAt:e.userData.vrmLookAt,meta:t,materials:e.userData.vrmMToonMaterials,springBoneManager:e.userData.vrmSpringBoneManager,nodeConstraintManager:e.userData.vrmNodeConstraintManager});e.userData.vrm=r}})}};function DT(e){let t=new Set;return e.traverse(e=>{if(!e.isMesh)return;let n=e;t.add(n)}),t}function OT(e,t,n){if(t.size===1){let n=t.values().next().value;if(n.weight===1)return e[n.index]}let r=new Float32Array(e[0].count*3),i=0;if(n)i=1;else for(let e of t)i+=e.weight;for(let n of t){let t=e[n.index],a=n.weight/i;for(let e=0;e<t.count;e++)r[e*3+0]+=t.getX(e)*a,r[e*3+1]+=t.getY(e)*a,r[e*3+2]+=t.getZ(e)*a}return new J(r,3)}function kT(e){let t=DT(e.scene),n=new Map,r=e.expressionManager?.expressionMap;if(r!=null)for(let[e,t]of Object.entries(r)){let r=new Set;for(let i of t.binds)if(i instanceof gS){if(i.weight!==0)for(let t of i.primitives){let r=n.get(t);r??(r=new Map,n.set(t,r));let a=r.get(e);a??(a=new Set,r.set(e,a)),a.add(i)}r.add(i)}for(let e of r)t.deleteBind(e)}for(let e of t){let t=n.get(e);if(t==null)continue;let i=e.geometry.morphAttributes;e.geometry.morphAttributes={};let a=e.geometry.clone();e.geometry=a;let o=a.morphTargetsRelative,s=i.position!=null,c=i.normal!=null,l={},u={},d=[];if(s||c){s&&(l.position=[]),c&&(l.normal=[]);let n=0;for(let[a,f]of t)s&&(l.position[n]=OT(i.position,f,o)),c&&(l.normal[n]=OT(i.normal,f,o)),r?.[a].addBind(new gS({index:n,weight:1,primitives:[e]})),u[a]=n,d.push(0),n++}a.morphAttributes=l,e.morphTargetDictionary=u,e.morphTargetInfluences=d}}function AT(e,t,n){if(e.getComponent)return e.getComponent(t,n);{let r=e.array[t*e.itemSize+n];return e.normalized&&(r=As.denormalize(r,e.array)),r}}function jT(e,t,n,r){e.setComponent?e.setComponent(t,n,r):(e.normalized&&(r=As.normalize(r,e.array)),e.array[t*e.itemSize+n]=r)}function MT(e){let t=NT(e),n=new Set;for(let e of t)n.has(e.geometry)&&(e.geometry=BT(e.geometry)),n.add(e.geometry);let r=new Map;for(let e of n){let t=e.getAttribute(`skinIndex`),n=r.get(t)??new Map;r.set(t,n);let i=e.getAttribute(`skinWeight`),a=PT(t,i);n.set(i,a)}let i=new Map;for(let e of t){let t=FT(e,r);i.set(e,t)}let a=[];for(let[e,t]of i){let n=!1;for(let r of a)if(IT(t,r.boneInverseMap)){n=!0,r.meshes.add(e);for(let[e,n]of t)r.boneInverseMap.set(e,n);break}n||a.push({boneInverseMap:t,meshes:new Set([e])})}let o=new Map,s=new zT,c=new zT,l=new zT;for(let e of a){let{boneInverseMap:t,meshes:n}=e,r=Array.from(t.keys()),i=new xu(r,Array.from(t.values())),a=c.getOrCreate(i);for(let e of n){let t=e.geometry.getAttribute(`skinIndex`),n=s.getOrCreate(t),i=e.skeleton.bones,c=`${n};${a};${i.map(e=>l.getOrCreate(e)).join(`,`)}`,u=o.get(c);u??(u=t.clone(),LT(u,i,r),o.set(c,u)),e.geometry.setAttribute(`skinIndex`,u)}for(let e of n)e.bind(i,new K)}}function NT(e){let t=new Set;return e.traverse(e=>{if(!e.isSkinnedMesh)return;let n=e;t.add(n)}),t}function PT(e,t){let n=new Set;for(let r=0;r<e.count;r++)for(let i=0;i<e.itemSize;i++){let a=AT(e,r,i);AT(t,r,i)!==0&&n.add(a)}return n}function FT(e,t){let n=new Map,r=e.skeleton,i=e.geometry,a=i.getAttribute(`skinIndex`),o=i.getAttribute(`skinWeight`),s=t.get(a)?.get(o);if(!s)throw Error(`Unreachable. attributeUsedIndexSetMap does not know the skin index attribute or the skin weight attribute.`);for(let e of s)n.set(r.bones[e],r.boneInverses[e]);return n}function IT(e,t){for(let[n,r]of e.entries()){let e=t.get(n);if(e!=null&&!RT(r,e))return!1}return!0}function LT(e,t,n){let r=new Map;for(let e of t)r.set(e,r.size);let i=new Map;for(let[e,t]of n.entries()){let n=r.get(t);i.set(n,e)}for(let t=0;t<e.count;t++)for(let n=0;n<e.itemSize;n++){let r=AT(e,t,n),a=i.get(r);jT(e,t,n,a)}e.needsUpdate=!0}function RT(e,t,n){if(n||=1e-4,e.elements.length!=t.elements.length)return!1;for(let r=0,i=e.elements.length;r<i;r++)if(Math.abs(e.elements[r]-t.elements[r])>n)return!1;return!0}var zT=class{constructor(){this._objectIndexMap=new Map,this._index=0}get(e){return this._objectIndexMap.get(e)}getOrCreate(e){let t=this._objectIndexMap.get(e);return t??(t=this._index,this._objectIndexMap.set(e,t),this._index++),t}};function BT(e){let t=new Y;t.name=e.name,t.setIndex(e.index);for(let[n,r]of Object.entries(e.attributes))t.setAttribute(n,r);for(let[n,r]of Object.entries(e.morphAttributes)){let e=n;t.morphAttributes[e]=r.concat()}t.morphTargetsRelative=e.morphTargetsRelative,t.groups=[];for(let n of e.groups)t.addGroup(n.start,n.count,n.materialIndex);return t.boundingSphere=e.boundingSphere?.clone()??null,t.boundingBox=e.boundingBox?.clone()??null,t.drawRange.start=e.drawRange.start,t.drawRange.count=e.drawRange.count,t.userData=e.userData,t}function VT(e){if(Object.values(e).forEach(e=>{e?.isTexture&&e.dispose()}),e.isShaderMaterial){let t=e.uniforms;t&&Object.values(t).forEach(e=>{let t=e.value;t?.isTexture&&t.dispose()})}e.dispose()}function HT(e){let t=e.geometry;t&&t.dispose();let n=e.skeleton;n&&n.dispose();let r=e.material;r&&(Array.isArray(r)?r.forEach(e=>VT(e)):r&&VT(r))}function UT(e){e.traverse(HT)}function WT(e,t){console.warn(`VRMUtils.removeUnnecessaryJoints: removeUnnecessaryJoints is deprecated. Use combineSkeletons instead. combineSkeletons contributes more to the performance improvement. This function will be removed in the next major version.`);let n=t?.experimentalSameBoneCounts??!1,r=[];e.traverse(e=>{e.type===`SkinnedMesh`&&r.push(e)});let i=new Map,a=0;for(let e of r){let t=e.geometry.getAttribute(`skinIndex`);if(i.has(t))continue;let n=new Map,r=new Map;for(let e=0;e<t.count;e++)for(let i=0;i<t.itemSize;i++){let a=AT(t,e,i),o=n.get(a);o??(o=n.size,n.set(a,o),r.set(o,a)),jT(t,e,i,o)}t.needsUpdate=!0,i.set(t,r),a=Math.max(a,n.size)}for(let e of r){let t=e.geometry.getAttribute(`skinIndex`),r=i.get(t),o=[],s=[],c=n?a:r.size;for(let t=0;t<c;t++){let n=r.get(t)??0;o.push(e.skeleton.bones[n]),s.push(e.skeleton.boneInverses[n])}let l=new xu(o,s);e.bind(l,new K)}}function GT(e,t){let n=e.position.count,r=Array(n),i=0,a=t.array;for(let e=0;e<a.length;e++){let t=a[e];r[t]||(r[t]=!0,i++)}return{isVertexUsed:r,vertexCount:n,verticesUsed:i}}function KT(e){let t=[],n=[],r=0;for(let i=0;i<e.length;i++)if(e[i]){let e=r++;t[i]=e,n[e]=i}return{originalIndexNewIndexMap:t,newIndexOriginalIndexMap:n}}function qT(e,t){t.name=e.name,t.morphTargetsRelative=e.morphTargetsRelative,e.groups.forEach(e=>{t.addGroup(e.start,e.count,e.materialIndex)}),t.boundingBox=e.boundingBox?.clone()??null,t.boundingSphere=e.boundingSphere?.clone()??null,t.setDrawRange(e.drawRange.start,e.drawRange.count),t.userData=e.userData}function JT(e,t,n){let r=t.array,i=new r.constructor(r.length);for(let e=0;e<r.length;e++)i[e]=n[r[e]];e.setIndex(new J(i,t.itemSize,t.normalized))}function YT(e,t,n){let r=e.constructor,i=new r(t.length*n),a=!0;for(let r=0;r<t.length;r++){let o=t[r]*n,s=r*n;for(let t=0;t<n;t++){let n=e[o+t];i[s+t]=n,a&&=n===0}}return[i,a]}function XT(e){let t=new Map,n=[];for(let[r,i]of Object.entries(e))if(i.isInterleavedBufferAttribute){let e=i,n=e.data,a=t.get(n)??[];t.set(n,a),a.push([r,e])}else{let e=i;n.push([r,e])}return[t,n]}function ZT(e,t,n){let[r,i]=XT(t);for(let[t,i]of r){let r=t.array,{stride:a}=t,[o,s]=YT(r,n,a),c=new Nl(o,a);c.setUsage(t.usage);for(let[t,n]of i){let{itemSize:r,offset:i,normalized:a}=n,o=new Fl(c,r,i,a);e.setAttribute(t,o)}}for(let[t,r]of i){let i=r.array,{itemSize:a,normalized:o}=r,[s,c]=YT(i,n,a);e.setAttribute(t,new J(s,a,o))}}function QT(e){let t=new Map,n=[];for(let[r,i]of Object.entries(e)){let e=r;for(let r=0;r<i.length;r++){let a=i[r];if(a.isInterleavedBufferAttribute){let n=a,i=n.data,o=t.get(i)??[];t.set(i,o),o.push([e,r,n])}else{let t=a;n.push([e,r,t])}}}return[t,n]}function $T(e,t,n){let r=!0,[i,a]=QT(t),o={};for(let[e,t]of i){let i=e.array,{stride:a}=e,[s,c]=YT(i,n,a);r&&=c;let l=new Nl(s,a);l.setUsage(e.usage);for(let[e,n,r]of t){let{itemSize:t,offset:i,normalized:a}=r,s=new Fl(l,t,i,a);o[e]??(o[e]=[]),o[e][n]=s}}for(let[e,t,i]of a){let a=i,s=a.array,{itemSize:c,normalized:l}=a,[u,d]=YT(s,n,c);r&&=d,o[e]??(o[e]=[]),o[e][t]=new J(u,c,l)}e.morphAttributes=r?{}:o}function eE(e){let t=new Map;e.traverse(e=>{if(!e.isMesh)return;let n=e,r=n.geometry,i=r.index;if(i==null)return;let a=t.get(r);if(a!=null){n.geometry=a;return}let{isVertexUsed:o,vertexCount:s,verticesUsed:c}=GT(r.attributes,i);if(c===s)return;let{originalIndexNewIndexMap:l,newIndexOriginalIndexMap:u}=KT(o),d=new Y;qT(r,d),t.set(r,d),JT(d,i,l),ZT(d,r.attributes,u),$T(d,r.morphAttributes,u),n.geometry=d}),Array.from(t.keys()).forEach(e=>{e.dispose()})}function tE(e){e.meta?.metaVersion===`0`&&(e.scene.rotation.y=Math.PI)}var nE=class{constructor(){}};nE.combineMorphs=kT,nE.combineSkeletons=MT,nE.deepDispose=UT,nE.removeUnnecessaryJoints=WT,nE.removeUnnecessaryVertices=eE,nE.rotateVRM0=tE;function rE(e,t){if(t===0)return console.warn(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.`),e;if(t===2||t===1){let n=e.getIndex();if(n===null){let t=[],r=e.getAttribute(`position`);if(r!==void 0){for(let e=0;e<r.count;e++)t.push(e);e.setIndex(t),n=e.getIndex()}else return console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.`),e}let r=n.count-2,i=[];if(t===2)for(let e=1;e<=r;e++)i.push(n.getX(0)),i.push(n.getX(e)),i.push(n.getX(e+1));else for(let e=0;e<r;e++)e%2==0?(i.push(n.getX(e)),i.push(n.getX(e+1)),i.push(n.getX(e+2))):(i.push(n.getX(e+2)),i.push(n.getX(e+1)),i.push(n.getX(e)));i.length/3!==r&&console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.`);let a=e.clone();return a.setIndex(i),a.clearGroups(),a}else return console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:`,t),e}function iE(e){let t=new Map,n=new Map,r=e.clone();return aE(e,r,function(e,r){t.set(r,e),n.set(e,r)}),r.traverse(function(e){if(!e.isSkinnedMesh)return;let r=e,i=t.get(e),a=i.skeleton.bones;r.skeleton=i.skeleton.clone(),r.bindMatrix.copy(i.bindMatrix),r.skeleton.bones=a.map(function(e){return n.get(e)}),r.bind(r.skeleton,r.bindMatrix)}),r}function aE(e,t,n){n(e,t);for(let r=0;r<e.children.length;r++)aE(e.children[r],t.children[r],n)}var oE=class extends nf{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(e){return new pE(e)}),this.register(function(e){return new mE(e)}),this.register(function(e){return new CE(e)}),this.register(function(e){return new wE(e)}),this.register(function(e){return new TE(e)}),this.register(function(e){return new gE(e)}),this.register(function(e){return new _E(e)}),this.register(function(e){return new vE(e)}),this.register(function(e){return new yE(e)}),this.register(function(e){return new fE(e)}),this.register(function(e){return new bE(e)}),this.register(function(e){return new hE(e)}),this.register(function(e){return new SE(e)}),this.register(function(e){return new xE(e)}),this.register(function(e){return new uE(e)}),this.register(function(e){return new EE(e,lE.EXT_MESHOPT_COMPRESSION)}),this.register(function(e){return new EE(e,lE.KHR_MESHOPT_COMPRESSION)}),this.register(function(e){return new DE(e)})}load(e,t,n,r){let i=this,a;if(this.resourcePath!==``)a=this.resourcePath;else if(this.path!==``){let t=Mf.extractUrlBase(e);a=Mf.resolveURL(t,this.path)}else a=Mf.extractUrlBase(e);this.manager.itemStart(e);let o=function(t){r?r(t):console.error(t),i.manager.itemError(e),i.manager.itemEnd(e)},s=new of(this.manager);s.setPath(this.path),s.setResponseType(`arraybuffer`),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(n){try{i.parse(n,a,function(n){t(n),i.manager.itemEnd(e)},o)}catch(e){o(e)}},n,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,r){let i,a={},o={},s=new TextDecoder;if(typeof e==`string`)i=JSON.parse(e);else if(e instanceof ArrayBuffer)if(s.decode(new Uint8Array(e,0,4))===OE){try{a[lE.KHR_BINARY_GLTF]=new jE(e)}catch(e){r&&r(e);return}i=JSON.parse(a[lE.KHR_BINARY_GLTF].content)}else i=JSON.parse(s.decode(e));else i=e;if(i.asset===void 0||i.asset.version[0]<2){r&&r(Error(`THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.`));return}let c=new rD(i,{path:t||this.resourcePath||``,crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let e=0;e<this.pluginCallbacks.length;e++){let t=this.pluginCallbacks[e](c);t.name||console.error(`THREE.GLTFLoader: Invalid plugin found: missing name`),o[t.name]=t,a[t.name]=!0}if(i.extensionsUsed)for(let e=0;e<i.extensionsUsed.length;++e){let t=i.extensionsUsed[e],n=i.extensionsRequired||[];switch(t){case lE.KHR_MATERIALS_UNLIT:a[t]=new dE;break;case lE.KHR_DRACO_MESH_COMPRESSION:a[t]=new ME(i,this.dracoLoader);break;case lE.KHR_TEXTURE_TRANSFORM:a[t]=new NE;break;case lE.KHR_MESH_QUANTIZATION:a[t]=new PE;break;default:n.indexOf(t)>=0&&o[t]===void 0&&console.warn(`THREE.GLTFLoader: Unknown extension "`+t+`".`)}}c.setExtensions(a),c.setPlugins(o),c.parse(n,r)}parseAsync(e,t){let n=this;return new Promise(function(r,i){n.parse(e,t,r,i)})}};function sE(){let e={};return{get:function(t){return e[t]},add:function(t,n){e[t]=n},remove:function(t){delete e[t]},removeAll:function(){e={}}}}function cE(e,t,n){let r=e.json.materials[t];return r.extensions&&r.extensions[n]?r.extensions[n]:null}var lE={KHR_BINARY_GLTF:`KHR_binary_glTF`,KHR_DRACO_MESH_COMPRESSION:`KHR_draco_mesh_compression`,KHR_LIGHTS_PUNCTUAL:`KHR_lights_punctual`,KHR_MATERIALS_CLEARCOAT:`KHR_materials_clearcoat`,KHR_MATERIALS_DISPERSION:`KHR_materials_dispersion`,KHR_MATERIALS_IOR:`KHR_materials_ior`,KHR_MATERIALS_SHEEN:`KHR_materials_sheen`,KHR_MATERIALS_SPECULAR:`KHR_materials_specular`,KHR_MATERIALS_TRANSMISSION:`KHR_materials_transmission`,KHR_MATERIALS_IRIDESCENCE:`KHR_materials_iridescence`,KHR_MATERIALS_ANISOTROPY:`KHR_materials_anisotropy`,KHR_MATERIALS_UNLIT:`KHR_materials_unlit`,KHR_MATERIALS_VOLUME:`KHR_materials_volume`,KHR_TEXTURE_BASISU:`KHR_texture_basisu`,KHR_TEXTURE_TRANSFORM:`KHR_texture_transform`,KHR_MESH_QUANTIZATION:`KHR_mesh_quantization`,KHR_MATERIALS_EMISSIVE_STRENGTH:`KHR_materials_emissive_strength`,EXT_MATERIALS_BUMP:`EXT_materials_bump`,EXT_TEXTURE_WEBP:`EXT_texture_webp`,EXT_TEXTURE_AVIF:`EXT_texture_avif`,EXT_MESHOPT_COMPRESSION:`EXT_meshopt_compression`,KHR_MESHOPT_COMPRESSION:`KHR_meshopt_compression`,EXT_MESH_GPU_INSTANCING:`EXT_mesh_gpu_instancing`},uE=class{constructor(e){this.parser=e,this.name=lE.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,r=t.length;n<r;n++){let r=t[n];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){let t=this.parser,n=`light:`+e,r=t.cache.get(n);if(r)return r;let i=t.json,a=((i.extensions&&i.extensions[this.name]||{}).lights||[])[e],o,s=new q(16777215);a.color!==void 0&&s.setRGB(a.color[0],a.color[1],a.color[2],zo);let c=a.range===void 0?0:a.range;switch(a.type){case`directional`:o=new Af(s),o.target.position.set(0,0,-1),o.add(o.target);break;case`point`:o=new Df(s),o.distance=c;break;case`spot`:o=new Tf(s),o.distance=c,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle===void 0?0:a.spot.innerConeAngle,a.spot.outerConeAngle=a.spot.outerConeAngle===void 0?Math.PI/4:a.spot.outerConeAngle,o.angle=a.spot.outerConeAngle,o.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,o.target.position.set(0,0,-1),o.add(o.target);break;default:throw Error(`THREE.GLTFLoader: Unexpected light type: `+a.type)}return o.position.set(0,0,0),YE(o,a),a.intensity!==void 0&&(o.intensity=a.intensity),o.name=t.createUniqueName(a.name||`light_`+e),r=Promise.resolve(o),t.cache.add(n,r),r}getDependency(e,t){if(e===`light`)return this._loadLight(t)}createNodeAttachment(e){let t=this,n=this.parser,r=n.json.nodes[e],i=(r.extensions&&r.extensions[this.name]||{}).light;return i===void 0?null:this._loadLight(i).then(function(e){return n._getNodeRef(t.cache,i,e)})}},dE=class{constructor(){this.name=lE.KHR_MATERIALS_UNLIT}getMaterialType(){return Kl}extendParams(e,t,n){let r=[];e.color=new q(1,1,1),e.opacity=1;let i=t.pbrMetallicRoughness;if(i){if(Array.isArray(i.baseColorFactor)){let t=i.baseColorFactor;e.color.setRGB(t[0],t[1],t[2],zo),e.opacity=t[3]}i.baseColorTexture!==void 0&&r.push(n.assignTexture(e,`map`,i.baseColorTexture,Ro))}return Promise.all(r)}},fE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);return n===null||n.emissiveStrength!==void 0&&(t.emissiveIntensity=n.emissiveStrength),Promise.resolve()}},pE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];if(n.clearcoatFactor!==void 0&&(t.clearcoat=n.clearcoatFactor),n.clearcoatTexture!==void 0&&r.push(this.parser.assignTexture(t,`clearcoatMap`,n.clearcoatTexture)),n.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=n.clearcoatRoughnessFactor),n.clearcoatRoughnessTexture!==void 0&&r.push(this.parser.assignTexture(t,`clearcoatRoughnessMap`,n.clearcoatRoughnessTexture)),n.clearcoatNormalTexture!==void 0&&(r.push(this.parser.assignTexture(t,`clearcoatNormalMap`,n.clearcoatNormalTexture)),n.clearcoatNormalTexture.scale!==void 0)){let e=n.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new H(e,e)}return Promise.all(r)}},mE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_DISPERSION}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);return n===null||(t.dispersion=n.dispersion===void 0?0:n.dispersion),Promise.resolve()}},hE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return n.iridescenceFactor!==void 0&&(t.iridescence=n.iridescenceFactor),n.iridescenceTexture!==void 0&&r.push(this.parser.assignTexture(t,`iridescenceMap`,n.iridescenceTexture)),n.iridescenceIor!==void 0&&(t.iridescenceIOR=n.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),n.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=n.iridescenceThicknessMinimum),n.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=n.iridescenceThicknessMaximum),n.iridescenceThicknessTexture!==void 0&&r.push(this.parser.assignTexture(t,`iridescenceThicknessMap`,n.iridescenceThicknessTexture)),Promise.all(r)}},gE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_SHEEN}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];if(t.sheenColor=new q(0,0,0),t.sheenRoughness=0,t.sheen=1,n.sheenColorFactor!==void 0){let e=n.sheenColorFactor;t.sheenColor.setRGB(e[0],e[1],e[2],zo)}return n.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=n.sheenRoughnessFactor),n.sheenColorTexture!==void 0&&r.push(this.parser.assignTexture(t,`sheenColorMap`,n.sheenColorTexture,Ro)),n.sheenRoughnessTexture!==void 0&&r.push(this.parser.assignTexture(t,`sheenRoughnessMap`,n.sheenRoughnessTexture)),Promise.all(r)}},_E=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return n.transmissionFactor!==void 0&&(t.transmission=n.transmissionFactor),n.transmissionTexture!==void 0&&r.push(this.parser.assignTexture(t,`transmissionMap`,n.transmissionTexture)),Promise.all(r)}},vE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_VOLUME}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];t.thickness=n.thicknessFactor===void 0?0:n.thicknessFactor,n.thicknessTexture!==void 0&&r.push(this.parser.assignTexture(t,`thicknessMap`,n.thicknessTexture)),t.attenuationDistance=n.attenuationDistance||1/0;let i=n.attenuationColor||[1,1,1];return t.attenuationColor=new q().setRGB(i[0],i[1],i[2],zo),Promise.all(r)}},yE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_IOR}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);return n===null?Promise.resolve():(t.ior=n.ior===void 0?1.5:n.ior,t.ior===0&&(t.ior=1e3),Promise.resolve())}},bE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_SPECULAR}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];t.specularIntensity=n.specularFactor===void 0?1:n.specularFactor,n.specularTexture!==void 0&&r.push(this.parser.assignTexture(t,`specularIntensityMap`,n.specularTexture));let i=n.specularColorFactor||[1,1,1];return t.specularColor=new q().setRGB(i[0],i[1],i[2],zo),n.specularColorTexture!==void 0&&r.push(this.parser.assignTexture(t,`specularColorMap`,n.specularColorTexture,Ro)),Promise.all(r)}},xE=class{constructor(e){this.parser=e,this.name=lE.EXT_MATERIALS_BUMP}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return t.bumpScale=n.bumpFactor===void 0?1:n.bumpFactor,n.bumpTexture!==void 0&&r.push(this.parser.assignTexture(t,`bumpMap`,n.bumpTexture)),Promise.all(r)}},SE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return n.anisotropyStrength!==void 0&&(t.anisotropy=n.anisotropyStrength),n.anisotropyRotation!==void 0&&(t.anisotropyRotation=n.anisotropyRotation),n.anisotropyTexture!==void 0&&r.push(this.parser.assignTexture(t,`anisotropyMap`,n.anisotropyTexture)),Promise.all(r)}},CE=class{constructor(e){this.parser=e,this.name=lE.KHR_TEXTURE_BASISU}loadTexture(e){let t=this.parser,n=t.json,r=n.textures[e];if(!r.extensions||!r.extensions[this.name])return null;let i=r.extensions[this.name],a=t.options.ktx2Loader;if(!a){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw Error(`THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures`);return null}return t.loadTextureImage(e,i.source,a)}},wE=class{constructor(e){this.parser=e,this.name=lE.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},TE=class{constructor(e){this.parser=e,this.name=lE.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},EE=class{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){let t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){let e=n.extensions[this.name],r=this.parser.getDependency(`buffer`,e.buffer),i=this.parser.options.meshoptDecoder;if(!i||!i.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw Error(`THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files`);return null}return r.then(function(t){let n=e.byteOffset||0,r=e.byteLength||0,a=e.count,o=e.byteStride,s=new Uint8Array(t,n,r);return i.decodeGltfBufferAsync?i.decodeGltfBufferAsync(a,o,s,e.mode,e.filter).then(function(e){return e.buffer}):i.ready.then(function(){let t=new ArrayBuffer(a*o);return i.decodeGltfBuffer(new Uint8Array(t),a,o,s,e.mode,e.filter),t})})}else return null}},DE=class{constructor(e){this.name=lE.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;let r=t.meshes[n.mesh];for(let e of r.primitives)if(e.mode!==RE.TRIANGLES&&e.mode!==RE.TRIANGLE_STRIP&&e.mode!==RE.TRIANGLE_FAN&&e.mode!==void 0)return null;let i=n.extensions[this.name].attributes,a=[],o={};for(let e in i)a.push(this.parser.getDependency(`accessor`,i[e]).then(t=>(o[e]=t,o[e])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(e=>{let t=e.pop(),n=t.isGroup?t.children:[t],r=e[0].count,i=[];for(let e of n){let t=new K,n=new W,a=new U,s=new W(1,1,1),c=new Au(e.geometry,e.material,r);for(let e=0;e<r;e++)o.TRANSLATION&&n.fromBufferAttribute(o.TRANSLATION,e),o.ROTATION&&a.fromBufferAttribute(o.ROTATION,e),o.SCALE&&s.fromBufferAttribute(o.SCALE,e),c.setMatrixAt(e,t.compose(n,a,s));for(let t in o)if(t===`_COLOR_0`){let e=o[t];c.instanceColor=new Su(e.array,e.itemSize,e.normalized)}else t!==`TRANSLATION`&&t!==`ROTATION`&&t!==`SCALE`&&e.geometry.setAttribute(t,o[t]);Tc.prototype.copy.call(c,e),this.parser.assignFinalMaterial(c),i.push(c)}return t.isGroup?(t.clear(),t.add(...i),t):i[0]}))}},OE=`glTF`,kE=12,AE={JSON:1313821514,BIN:5130562},jE=class{constructor(e){this.name=lE.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,kE),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==OE)throw Error(`THREE.GLTFLoader: Unsupported glTF-Binary header.`);if(this.header.version<2)throw Error(`THREE.GLTFLoader: Legacy binary file detected.`);let r=this.header.length-kE,i=new DataView(e,kE),a=0;for(;a<r;){let t=i.getUint32(a,!0);a+=4;let r=i.getUint32(a,!0);if(a+=4,r===AE.JSON){let r=new Uint8Array(e,kE+a,t);this.content=n.decode(r)}else if(r===AE.BIN){let n=kE+a;this.body=e.slice(n,n+t)}a+=t}if(this.content===null)throw Error(`THREE.GLTFLoader: JSON content not found.`)}},ME=class{constructor(e,t){if(!t)throw Error(`THREE.GLTFLoader: No DRACOLoader instance provided.`);this.name=lE.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){let n=this.json,r=this.dracoLoader,i=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},s={},c={};for(let e in a){let t=UE[e]||e.toLowerCase();o[t]=a[e]}for(let t in e.attributes){let r=UE[t]||t.toLowerCase();if(a[t]!==void 0){let i=n.accessors[e.attributes[t]];c[r]=zE[i.componentType].name,s[r]=i.normalized===!0}}return t.getDependency(`bufferView`,i).then(function(e){return new Promise(function(t,n){r.decodeDracoFile(e,function(e){for(let t in e.attributes){let n=e.attributes[t],r=s[t];r!==void 0&&(n.normalized=r)}t(e)},o,c,zo,n)})})}},NE=class{constructor(){this.name=lE.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0?e:(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0,e)}},PE=class{constructor(){this.name=lE.KHR_MESH_QUANTIZATION}},FE=class extends Ld{constructor(e,t,n,r){super(e,t,n,r)}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r*3+r;for(let e=0;e!==r;e++)t[e]=n[i+e];return t}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=o*2,c=o*3,l=r-t,u=(n-t)/l,d=u*u,f=d*u,p=e*c,m=p-c,h=-2*f+3*d,g=f-d,_=1-h,v=g-d+u;for(let e=0;e!==o;e++){let t=a[m+e+o],n=a[m+e+s]*l,r=a[p+e+o],c=a[p+e]*l;i[e]=_*t+v*n+h*r+g*c}return i}},IE=new U,LE=class extends FE{interpolate_(e,t,n,r){let i=super.interpolate_(e,t,n,r);return IE.fromArray(i).normalize().toArray(i),i}},RE={FLOAT:5126,FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123},zE={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},BE={9728:fa,9729:ha,9984:pa,9985:ga,9986:ma,9987:_a},VE={33071:ua,33648:da,10497:la},HE={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},UE={POSITION:`position`,NORMAL:`normal`,TANGENT:`tangent`,TEXCOORD_0:`uv`,TEXCOORD_1:`uv1`,TEXCOORD_2:`uv2`,TEXCOORD_3:`uv3`,COLOR_0:`color`,WEIGHTS_0:`skinWeight`,JOINTS_0:`skinIndex`},WE={scale:`scale`,translation:`position`,rotation:`quaternion`,weights:`morphTargetInfluences`},GE={CUBICSPLINE:void 0,LINEAR:Oo,STEP:Do},KE={OPAQUE:`OPAQUE`,MASK:`MASK`,BLEND:`BLEND`};function qE(e){return e.DefaultMaterial===void 0&&(e.DefaultMaterial=new kd({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:0})),e.DefaultMaterial}function JE(e,t,n){for(let r in n.extensions)e[r]===void 0&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[r]=n.extensions[r])}function YE(e,t){t.extras!==void 0&&(typeof t.extras==`object`?Object.assign(e.userData,t.extras):console.warn(`THREE.GLTFLoader: Ignoring primitive type .extras, `+t.extras))}function XE(e,t,n){let r=!1,i=!1,a=!1;for(let e=0,n=t.length;e<n;e++){let n=t[e];if(n.POSITION!==void 0&&(r=!0),n.NORMAL!==void 0&&(i=!0),n.COLOR_0!==void 0&&(a=!0),r&&i&&a)break}if(!r&&!i&&!a)return Promise.resolve(e);let o=[],s=[],c=[];for(let l=0,u=t.length;l<u;l++){let u=t[l];if(r){let t=u.POSITION===void 0?e.attributes.position:n.getDependency(`accessor`,u.POSITION);o.push(t)}if(i){let t=u.NORMAL===void 0?e.attributes.normal:n.getDependency(`accessor`,u.NORMAL);s.push(t)}if(a){let t=u.COLOR_0===void 0?e.attributes.color:n.getDependency(`accessor`,u.COLOR_0);c.push(t)}}return Promise.all([Promise.all(o),Promise.all(s),Promise.all(c)]).then(function(t){let n=t[0],o=t[1],s=t[2];return r&&(e.morphAttributes.position=n),i&&(e.morphAttributes.normal=o),a&&(e.morphAttributes.color=s),e.morphTargetsRelative=!0,e})}function ZE(e,t){if(e.updateMorphTargets(),t.weights!==void 0)for(let n=0,r=t.weights.length;n<r;n++)e.morphTargetInfluences[n]=t.weights[n];if(t.extras&&Array.isArray(t.extras.targetNames)){let n=t.extras.targetNames;if(e.morphTargetInfluences.length===n.length){e.morphTargetDictionary={};for(let t=0,r=n.length;t<r;t++)e.morphTargetDictionary[n[t]]=t}else console.warn(`THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.`)}}function QE(e){let t,n=e.extensions&&e.extensions[lE.KHR_DRACO_MESH_COMPRESSION];if(t=n?`draco:`+n.bufferView+`:`+n.indices+`:`+$E(n.attributes):e.indices+`:`+$E(e.attributes)+`:`+e.mode,e.targets!==void 0)for(let n=0,r=e.targets.length;n<r;n++)t+=`:`+$E(e.targets[n]);return t}function $E(e){let t=``,n=Object.keys(e).sort();for(let r=0,i=n.length;r<i;r++)t+=n[r]+`:`+e[n[r]]+`;`;return t}function eD(e){switch(e){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw Error(`THREE.GLTFLoader: Unsupported normalized accessor component type.`)}}function tD(e){return e.search(/\.jpe?g($|\?)/i)>0||e.search(/^data\:image\/jpeg/)===0?`image/jpeg`:e.search(/\.webp($|\?)/i)>0||e.search(/^data\:image\/webp/)===0?`image/webp`:e.search(/\.ktx2($|\?)/i)>0||e.search(/^data\:image\/ktx2/)===0?`image/ktx2`:`image/png`}var nD=new K,rD=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new sE,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,r=-1,i=!1,a=-1;if(typeof navigator<`u`&&navigator.userAgent!==void 0){let e=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(e)===!0;let t=e.match(/Version\/(\d+)/);r=n&&t?parseInt(t[1],10):-1,i=e.indexOf(`Firefox`)>-1,a=i?e.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>`u`||n&&r<17||i&&a<98?this.textureLoader=new uf(this.options.manager):this.textureLoader=new Pf(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new of(this.options.manager),this.fileLoader.setResponseType(`arraybuffer`),this.options.crossOrigin===`use-credentials`&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let n=this,r=this.json,i=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(e){return e._markDefs&&e._markDefs()}),Promise.all(this._invokeAll(function(e){return e.beforeRoot&&e.beforeRoot()})).then(function(){return Promise.all([n.getDependencies(`scene`),n.getDependencies(`animation`),n.getDependencies(`camera`)])}).then(function(t){let a={scene:t[0][r.scene||0],scenes:t[0],animations:t[1],cameras:t[2],asset:r.asset,parser:n,userData:{}};return JE(i,a,r),YE(a,r),Promise.all(n._invokeAll(function(e){return e.afterRoot&&e.afterRoot(a)})).then(function(){for(let e of a.scenes)e.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let n=0,r=t.length;n<r;n++){let r=t[n].joints;for(let t=0,n=r.length;t<n;t++)e[r[t]].isBone=!0}for(let t=0,r=e.length;t<r;t++){let r=e[t];r.mesh!==void 0&&(this._addNodeRef(this.meshCache,r.mesh),r.skin!==void 0&&(n[r.mesh].isSkinnedMesh=!0)),r.camera!==void 0&&this._addNodeRef(this.cameraCache,r.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;let r=n.clone(),i=(e,t)=>{let n=this.associations.get(e);n!=null&&this.associations.set(t,n);for(let[n,r]of e.children.entries())i(r,t.children[n])};return i(n,r),r.name+=`_instance_`+ e.uses[t]++,r}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){let r=e(t[n]);if(r)return r}return null}_invokeAll(e){let t=Object.values(this.plugins);t.unshift(this);let n=[];for(let r=0;r<t.length;r++){let i=e(t[r]);i&&n.push(i)}return n}getDependency(e,t){let n=e+`:`+t,r=this.cache.get(n);if(!r){switch(e){case`scene`:r=this.loadScene(t);break;case`node`:r=this._invokeOne(function(e){return e.loadNode&&e.loadNode(t)});break;case`mesh`:r=this._invokeOne(function(e){return e.loadMesh&&e.loadMesh(t)});break;case`accessor`:r=this.loadAccessor(t);break;case`bufferView`:r=this._invokeOne(function(e){return e.loadBufferView&&e.loadBufferView(t)});break;case`buffer`:r=this.loadBuffer(t);break;case`material`:r=this._invokeOne(function(e){return e.loadMaterial&&e.loadMaterial(t)});break;case`texture`:r=this._invokeOne(function(e){return e.loadTexture&&e.loadTexture(t)});break;case`skin`:r=this.loadSkin(t);break;case`animation`:r=this._invokeOne(function(e){return e.loadAnimation&&e.loadAnimation(t)});break;case`camera`:r=this.loadCamera(t);break;default:if(r=this._invokeOne(function(n){return n!=this&&n.getDependency&&n.getDependency(e,t)}),!r)throw Error(`Unknown type: `+e);break}this.cache.add(n,r)}return r}getDependencies(e){let t=this.cache.get(e);if(!t){let n=this,r=this.json[e+(e===`mesh`?`es`:`s`)]||[];t=Promise.all(r.map(function(t,r){return n.getDependency(e,r)})),this.cache.add(e,t)}return t}loadBuffer(e){let t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!==`arraybuffer`)throw Error(`THREE.GLTFLoader: `+t.type+` buffer type is not supported.`);if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[lE.KHR_BINARY_GLTF].body);let r=this.options;return new Promise(function(e,i){n.load(Mf.resolveURL(t.uri,r.path),e,void 0,function(){i(Error(`THREE.GLTFLoader: Failed to load buffer "`+t.uri+`".`))})})}loadBufferView(e){let t=this.json.bufferViews[e];return this.getDependency(`buffer`,t.buffer).then(function(e){let n=t.byteLength||0,r=t.byteOffset||0;return e.slice(r,r+n)})}loadAccessor(e){let t=this,n=this.json,r=this.json.accessors[e];if(r.bufferView===void 0&&r.sparse===void 0){let e=HE[r.type],t=zE[r.componentType],n=r.normalized===!0,i=new t(r.count*e);return Promise.resolve(new J(i,e,n))}let i=[];return r.bufferView===void 0?i.push(null):i.push(this.getDependency(`bufferView`,r.bufferView)),r.sparse!==void 0&&(i.push(this.getDependency(`bufferView`,r.sparse.indices.bufferView)),i.push(this.getDependency(`bufferView`,r.sparse.values.bufferView))),Promise.all(i).then(function(e){let i=e[0],a=HE[r.type],o=zE[r.componentType],s=o.BYTES_PER_ELEMENT,c=s*a,l=r.byteOffset||0,u=r.bufferView===void 0?void 0:n.bufferViews[r.bufferView].byteStride,d=r.normalized===!0,f,p;if(u&&u!==c){let e=Math.floor(l/u),n=`InterleavedBuffer:`+r.bufferView+`:`+r.componentType+`:`+e+`:`+r.count,c=t.cache.get(n);c||(f=new o(i,e*u,r.count*u/s),c=new Nl(f,u/s),t.cache.add(n,c)),p=new Fl(c,a,l%u/s,d)}else f=i===null?new o(r.count*a):new o(i,l,r.count*a),p=new J(f,a,d);if(r.sparse!==void 0){let t=HE.SCALAR,n=zE[r.sparse.indices.componentType],s=r.sparse.indices.byteOffset||0,c=r.sparse.values.byteOffset||0,l=new n(e[1],s,r.sparse.count*t),u=new o(e[2],c,r.sparse.count*a);i!==null&&(p=new J(p.array.slice(),p.itemSize,p.normalized)),p.normalized=!1;for(let e=0,t=l.length;e<t;e++){let t=l[e];if(p.setX(t,u[e*a]),a>=2&&p.setY(t,u[e*a+1]),a>=3&&p.setZ(t,u[e*a+2]),a>=4&&p.setW(t,u[e*a+3]),a>=5)throw Error(`THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.`)}p.normalized=d}return p})}loadTexture(e){let t=this.json,n=this.options,r=t.textures[e].source,i=t.images[r],a=this.textureLoader;if(i.uri){let e=n.manager.getHandler(i.uri);e!==null&&(a=e)}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,n){let r=this,i=this.json,a=i.textures[e],o=i.images[t],s=(o.uri||o.bufferView)+`:`+a.sampler;if(this.textureCache[s])return this.textureCache[s];let c=this.loadImageSource(t,n).then(function(t){t.flipY=!1,t.name=a.name||o.name||``,t.name===``&&typeof o.uri==`string`&&o.uri.startsWith(`data:image/`)===!1&&(t.name=o.uri);let n=(i.samplers||{})[a.sampler]||{};return t.magFilter=BE[n.magFilter]||1006,t.minFilter=BE[n.minFilter]||1008,t.wrapS=VE[n.wrapS]||1e3,t.wrapT=VE[n.wrapT]||1e3,t.generateMipmaps=!t.isCompressedTexture&&t.minFilter!==1003&&t.minFilter!==1006,r.associations.set(t,{textures:e}),t}).catch(function(){return null});return this.textureCache[s]=c,c}loadImageSource(e,t){let n=this,r=this.json,i=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(e=>e.clone());let a=r.images[e],o=self.URL||self.webkitURL,s=a.uri||``,c=!1;if(a.bufferView!==void 0)s=n.getDependency(`bufferView`,a.bufferView).then(function(e){c=!0;let t=new Blob([e],{type:a.mimeType});return s=o.createObjectURL(t),s});else if(a.uri===void 0)throw Error(`THREE.GLTFLoader: Image `+e+` is missing URI and bufferView`);let l=Promise.resolve(s).then(function(e){return new Promise(function(n,r){let a=n;t.isImageBitmapLoader===!0&&(a=function(e){let t=new qs(e);t.needsUpdate=!0,n(t)}),t.load(Mf.resolveURL(e,i.path),a,void 0,r)})}).then(function(e){return c===!0&&o.revokeObjectURL(s),YE(e,a),e.userData.mimeType=a.mimeType||tD(a.uri),e}).catch(function(e){throw console.error(`THREE.GLTFLoader: Couldn't load texture`,s),e});return this.sourceCache[e]=l,l}assignTexture(e,t,n,r){let i=this;return this.getDependency(`texture`,n.index).then(function(a){if(!a)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(a=a.clone(),a.channel=n.texCoord),i.extensions[lE.KHR_TEXTURE_TRANSFORM]){let e=n.extensions===void 0?void 0:n.extensions[lE.KHR_TEXTURE_TRANSFORM];if(e){let t=i.associations.get(a);a=i.extensions[lE.KHR_TEXTURE_TRANSFORM].extendTexture(a,e),i.associations.set(a,t)}}return r!==void 0&&(a.colorSpace=r),e[t]=a,a})}assignFinalMaterial(e){let t=e.geometry,n=e.material,r=t.attributes.tangent===void 0,i=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){let e=`PointsMaterial:`+n.uuid,t=this.cache.get(e);t||(t=new $u,Ll.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,t.sizeAttenuation=!1,this.cache.add(e,t)),n=t}else if(e.isLine){let e=`LineBasicMaterial:`+n.uuid,t=this.cache.get(e);t||(t=new zu,Ll.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,this.cache.add(e,t)),n=t}if(r||i||a){let e=`ClonedMaterial:`+n.uuid+`:`;r&&(e+=`derivative-tangents:`),i&&(e+=`vertex-colors:`),a&&(e+=`flat-shading:`);let t=this.cache.get(e);t||(t=n.clone(),i&&(t.vertexColors=!0),a&&(t.flatShading=!0),r&&(t.normalScale&&(t.normalScale.y*=-1),t.clearcoatNormalScale&&(t.clearcoatNormalScale.y*=-1)),this.cache.add(e,t),this.associations.set(t,this.associations.get(n))),n=t}e.material=n}getMaterialType(){return kd}loadMaterial(e){let t=this,n=this.json,r=this.extensions,i=n.materials[e],a,o={},s=i.extensions||{},c=[];if(s[lE.KHR_MATERIALS_UNLIT]){let e=r[lE.KHR_MATERIALS_UNLIT];a=e.getMaterialType(),c.push(e.extendParams(o,i,t))}else{let n=i.pbrMetallicRoughness||{};if(o.color=new q(1,1,1),o.opacity=1,Array.isArray(n.baseColorFactor)){let e=n.baseColorFactor;o.color.setRGB(e[0],e[1],e[2],zo),o.opacity=e[3]}n.baseColorTexture!==void 0&&c.push(t.assignTexture(o,`map`,n.baseColorTexture,Ro)),o.metalness=n.metallicFactor===void 0?1:n.metallicFactor,o.roughness=n.roughnessFactor===void 0?1:n.roughnessFactor,n.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,`metalnessMap`,n.metallicRoughnessTexture)),c.push(t.assignTexture(o,`roughnessMap`,n.metallicRoughnessTexture))),a=this._invokeOne(function(t){return t.getMaterialType&&t.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(t){return t.extendMaterialParams&&t.extendMaterialParams(e,o)})))}i.doubleSided===!0&&(o.side=2);let l=i.alphaMode||KE.OPAQUE;if(l===KE.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,l===KE.MASK&&(o.alphaTest=i.alphaCutoff===void 0?.5:i.alphaCutoff)),i.normalTexture!==void 0&&a!==Kl&&(c.push(t.assignTexture(o,`normalMap`,i.normalTexture)),o.normalScale=new H(1,1),i.normalTexture.scale!==void 0)){let e=i.normalTexture.scale;o.normalScale.set(e,e)}if(i.occlusionTexture!==void 0&&a!==Kl&&(c.push(t.assignTexture(o,`aoMap`,i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&a!==Kl){let e=i.emissiveFactor;o.emissive=new q().setRGB(e[0],e[1],e[2],zo)}return i.emissiveTexture!==void 0&&a!==Kl&&c.push(t.assignTexture(o,`emissiveMap`,i.emissiveTexture,Ro)),Promise.all(c).then(function(){let n=new a(o);return i.name&&(n.name=i.name),YE(n,i),t.associations.set(n,{materials:e}),i.extensions&&JE(r,n,i),n})}createUniqueName(e){let t=Zf.sanitizeNodeName(e||``);return t in this.nodeNamesUsed?t+`_`+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,n=this.extensions,r=this.primitiveCache;function i(e){return n[lE.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then(function(n){return aD(n,e,t)})}let a=[];for(let n=0,o=e.length;n<o;n++){let o=e[n],s=QE(o),c=r[s];if(c)a.push(c.promise);else{let e;e=o.extensions&&o.extensions[lE.KHR_DRACO_MESH_COMPRESSION]?i(o):aD(new Y,o,t),r[s]={primitive:o,promise:e},a.push(e)}}return Promise.all(a)}loadMesh(e){let t=this,n=this.json,r=this.extensions,i=n.meshes[e],a=i.primitives,o=[];for(let e=0,t=a.length;e<t;e++){let t=a[e].material===void 0?qE(this.cache):this.getDependency(`material`,a[e].material);o.push(t)}return o.push(t.loadGeometries(a)),Promise.all(o).then(function(n){let o=n.slice(0,n.length-1),s=n[n.length-1],c=[];for(let n=0,l=s.length;n<l;n++){let l=s[n],u=a[n],d,f=o[n];if(u.mode===RE.TRIANGLES||u.mode===RE.TRIANGLE_STRIP||u.mode===RE.TRIANGLE_FAN||u.mode===void 0)d=i.isSkinnedMesh===!0?new gu(l,f):new iu(l,f),d.isSkinnedMesh===!0&&d.normalizeSkinWeights(),u.mode===RE.TRIANGLE_STRIP?d.geometry=rE(d.geometry,1):u.mode===RE.TRIANGLE_FAN&&(d.geometry=rE(d.geometry,2));else if(u.mode===RE.LINES)d=new Zu(l,f);else if(u.mode===RE.LINE_STRIP)d=new qu(l,f);else if(u.mode===RE.LINE_LOOP)d=new Qu(l,f);else if(u.mode===RE.POINTS)d=new id(l,f);else throw Error(`THREE.GLTFLoader: Primitive mode unsupported: `+u.mode);Object.keys(d.geometry.morphAttributes).length>0&&ZE(d,i),d.name=t.createUniqueName(i.name||`mesh_`+e),YE(d,i),u.extensions&&JE(r,d,u),t.assignFinalMaterial(d),c.push(d)}for(let n=0,r=c.length;n<r;n++)t.associations.set(c[n],{meshes:e,primitives:n});if(c.length===1)return i.extensions&&JE(r,c[0],i),c[0];let l=new Ec;i.extensions&&JE(r,l,i),t.associations.set(l,{meshes:e});for(let e=0,t=c.length;e<t;e++)l.add(c[e]);return l})}loadCamera(e){let t,n=this.json.cameras[e],r=n[n.type];if(!r){console.warn(`THREE.GLTFLoader: Missing camera parameters.`);return}return n.type===`perspective`?t=new Cf(As.radToDeg(r.yfov),r.aspectRatio||1,r.znear||1,r.zfar||2e6):n.type===`orthographic`&&(t=new Of(-r.xmag,r.xmag,r.ymag,-r.ymag,r.znear,r.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),YE(t,n),Promise.resolve(t)}loadSkin(e){let t=this.json.skins[e],n=[];for(let e=0,r=t.joints.length;e<r;e++)n.push(this._loadNodeShallow(t.joints[e]));return t.inverseBindMatrices===void 0?n.push(null):n.push(this.getDependency(`accessor`,t.inverseBindMatrices)),Promise.all(n).then(function(e){let n=e.pop(),r=e,i=[],a=[];for(let e=0,o=r.length;e<o;e++){let o=r[e];if(o){i.push(o);let t=new K;n!==null&&t.fromArray(n.array,e*16),a.push(t)}else console.warn(`THREE.GLTFLoader: Joint "%s" could not be found.`,t.joints[e])}return new xu(i,a)})}loadAnimation(e){let t=this.json,n=this,r=t.animations[e],i=r.name?r.name:`animation_`+e,a=[],o=[],s=[],c=[],l=[];for(let e=0,t=r.channels.length;e<t;e++){let t=r.channels[e],n=r.samplers[t.sampler],i=t.target,u=i.node,d=r.parameters===void 0?n.input:r.parameters[n.input],f=r.parameters===void 0?n.output:r.parameters[n.output];i.node!==void 0&&(a.push(this.getDependency(`node`,u)),o.push(this.getDependency(`accessor`,d)),s.push(this.getDependency(`accessor`,f)),c.push(n),l.push(i))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(s),Promise.all(c),Promise.all(l)]).then(function(e){let t=e[0],a=e[1],o=e[2],s=e[3],c=e[4],l=[];for(let e=0,r=t.length;e<r;e++){let r=t[e],i=a[e],u=o[e],d=s[e],f=c[e];if(r===void 0)continue;r.updateMatrix&&r.updateMatrix();let p=n._createAnimationTracks(r,i,u,d,f);if(p)for(let e=0;e<p.length;e++)l.push(p[e])}let u=new Xd(i,void 0,l);return YE(u,r),u})}createNodeMesh(e){let t=this.json,n=this,r=t.nodes[e];return r.mesh===void 0?null:n.getDependency(`mesh`,r.mesh).then(function(e){let t=n._getNodeRef(n.meshCache,r.mesh,e);return r.weights!==void 0&&t.traverse(function(e){if(e.isMesh)for(let t=0,n=r.weights.length;t<n;t++)e.morphTargetInfluences[t]=r.weights[t]}),t})}loadNode(e){let t=this.json,n=this,r=t.nodes[e],i=n._loadNodeShallow(e),a=[],o=r.children||[];for(let e=0,t=o.length;e<t;e++)a.push(n.getDependency(`node`,o[e]));let s=r.skin===void 0?Promise.resolve(null):n.getDependency(`skin`,r.skin);return Promise.all([i,Promise.all(a),s]).then(function(e){let t=e[0],n=e[1],r=e[2];r!==null&&t.traverse(function(e){e.isSkinnedMesh&&e.bind(r,nD)});for(let e=0,r=n.length;e<r;e++)t.add(n[e]);if(t.userData.pivot!==void 0&&n.length>0){let e=t.userData.pivot,r=n[0];t.pivot=new W().fromArray(e),t.position.x-=e[0],t.position.y-=e[1],t.position.z-=e[2],r.position.set(0,0,0),delete t.userData.pivot}return t})}_loadNodeShallow(e){let t=this.json,n=this.extensions,r=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let i=t.nodes[e],a=i.name?r.createUniqueName(i.name):``,o=[],s=r._invokeOne(function(t){return t.createNodeMesh&&t.createNodeMesh(e)});return s&&o.push(s),i.camera!==void 0&&o.push(r.getDependency(`camera`,i.camera).then(function(e){return r._getNodeRef(r.cameraCache,i.camera,e)})),r._invokeAll(function(t){return t.createNodeAttachment&&t.createNodeAttachment(e)}).forEach(function(e){o.push(e)}),this.nodeCache[e]=Promise.all(o).then(function(t){let o;if(o=i.isBone===!0?new _u:t.length>1?new Ec:t.length===1?t[0]:new Tc,o!==t[0])for(let e=0,n=t.length;e<n;e++)o.add(t[e]);if(i.name&&(o.userData.name=i.name,o.name=a),YE(o,i),i.extensions&&JE(n,o,i),i.matrix!==void 0){let e=new K;e.fromArray(i.matrix),o.applyMatrix4(e)}else i.translation!==void 0&&o.position.fromArray(i.translation),i.rotation!==void 0&&o.quaternion.fromArray(i.rotation),i.scale!==void 0&&o.scale.fromArray(i.scale);if(!r.associations.has(o))r.associations.set(o,{});else if(i.mesh!==void 0&&r.meshCache.refs[i.mesh]>1){let e=r.associations.get(o);r.associations.set(o,{...e})}return r.associations.get(o).nodes=e,o}),this.nodeCache[e]}loadScene(e){let t=this.extensions,n=this.json.scenes[e],r=this,i=new Ec;n.name&&(i.name=r.createUniqueName(n.name)),YE(i,n),n.extensions&&JE(t,i,n);let a=n.nodes||[],o=[];for(let e=0,t=a.length;e<t;e++)o.push(r.getDependency(`node`,a[e]));return Promise.all(o).then(function(e){for(let t=0,n=e.length;t<n;t++){let n=e[t];n.parent===null?i.add(n):i.add(iE(n))}return r.associations=(e=>{let t=new Map;for(let[e,n]of r.associations)(e instanceof Ll||e instanceof qs)&&t.set(e,n);return e.traverse(e=>{let n=r.associations.get(e);n!=null&&t.set(e,n)}),t})(i),i})}_createAnimationTracks(e,t,n,r,i){let a=[],o=e.name?e.name:e.uuid,s=[];function c(e){e.morphTargetInfluences&&s.push(e.name?e.name:e.uuid)}WE[i.path]===WE.weights?(c(e),e.isGroup&&e.children.forEach(c)):s.push(o);let l;switch(WE[i.path]){case WE.weights:l=Gd;break;case WE.rotation:l=qd;break;case WE.translation:case WE.scale:l=Yd;break;default:switch(n.itemSize){case 1:l=Gd;break;default:l=Yd;break}break}let u=r.interpolation===void 0?Oo:GE[r.interpolation],d=this._getArrayFromAccessor(n);for(let e=0,n=s.length;e<n;e++){let n=new l(s[e]+`.`+WE[i.path],t.array,d,u);r.interpolation===`CUBICSPLINE`&&this._createCubicSplineTrackInterpolant(n),a.push(n)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let e=eD(t.constructor),n=new Float32Array(t.length);for(let r=0,i=t.length;r<i;r++)n[r]=t[r]*e;t=n}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(e){return new(this instanceof qd?LE:FE)(this.times,this.values,this.getValueSize()/3,e)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}};function iD(e,t,n){let r=t.attributes,i=new Xc;if(r.POSITION!==void 0){let e=n.json.accessors[r.POSITION],t=e.min,a=e.max;if(t!==void 0&&a!==void 0){if(i.set(new W(t[0],t[1],t[2]),new W(a[0],a[1],a[2])),e.normalized){let t=eD(zE[e.componentType]);i.min.multiplyScalar(t),i.max.multiplyScalar(t)}}else{console.warn(`THREE.GLTFLoader: Missing min/max properties for accessor POSITION.`);return}}else return;let a=t.targets;if(a!==void 0){let e=new W,t=new W;for(let r=0,i=a.length;r<i;r++){let i=a[r];if(i.POSITION!==void 0){let r=n.json.accessors[i.POSITION],a=r.min,o=r.max;if(a!==void 0&&o!==void 0){if(t.setX(Math.max(Math.abs(a[0]),Math.abs(o[0]))),t.setY(Math.max(Math.abs(a[1]),Math.abs(o[1]))),t.setZ(Math.max(Math.abs(a[2]),Math.abs(o[2]))),r.normalized){let e=eD(zE[r.componentType]);t.multiplyScalar(e)}e.max(t)}else console.warn(`THREE.GLTFLoader: Missing min/max properties for accessor POSITION.`)}}i.expandByVector(e)}e.boundingBox=i;let o=new Tl;i.getCenter(o.center),o.radius=i.min.distanceTo(i.max)/2,e.boundingSphere=o}function aD(e,t,n){let r=t.attributes,i=[];function a(t,r){return n.getDependency(`accessor`,t).then(function(t){e.setAttribute(r,t)})}for(let t in r){let n=UE[t]||t.toLowerCase();n in e.attributes||i.push(a(r[t],n))}if(t.indices!==void 0&&!e.index){let r=n.getDependency(`accessor`,t.indices).then(function(t){e.setIndex(t)});i.push(r)}return Ls.workingColorSpace!==`srgb-linear`&&`COLOR_0`in r&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Ls.workingColorSpace}" not supported.`),YE(e,t),iD(e,t,n),Promise.all(i).then(function(){return t.targets===void 0?e:XE(e,t.targets,n)})}var oD=(e,t)=>new uf().load(e,void 0,void 0,t);function sD(e,t){return[e,t?.colorSpace??`srgb`,t?.filter??`linear`,t?.wrap??`clamp`,String(t?.anisotropy??1),t?.process?.id??``].join(`|`)}function cD(e,t){e.colorSpace=(t?.colorSpace??`srgb`)===`srgb`?Ro:``;let n=t?.filter===`nearest`;e.magFilter=n?fa:ha,e.generateMipmaps=!n,e.minFilter=n?fa:_a;let r=t?.wrap===`repeat`?la:ua;e.wrapS=r,e.wrapT=r,t?.anisotropy&&(e.anisotropy=t.anisotropy)}var lD=class{entries=new Map;load;diagnostics;constructor(e){this.load=e?.loader??oD,this.diagnostics=e?.diagnostics??null}acquire(e,t){if(e===``||typeof document>`u`&&this.load===oD)return null;let n=sD(e,t),r=this.entries.get(n);if(r)return r.texture;let i={url:e,texture:null,error:null};return i.texture=this.load(e,t=>{i.error=t instanceof Error?t.message:String(t),this.diagnostics?.warn(`texture failed to load: ${e} — ${i.error}`)}),cD(i.texture,t),t?.process?.run(i.texture),this.entries.set(n,i),i.texture}acquireOwn(e,t){let n=this.acquire(e,t);return n?n.clone():null}noteError(e,t){let n=`external|${e}`;if(this.entries.has(n))return;let r=t instanceof Error?t.message:String(t);this.entries.set(n,{url:e,texture:null,error:r}),this.diagnostics?.warn(`texture failed to load: ${e} — ${r}`)}errors(){let e=[];for(let t of this.entries.values())t.error!==null&&e.push({url:t.url,error:t.error});return e}size(){return this.entries.size}dispose(){for(let e of this.entries.values())e.texture.dispose();this.entries.clear()}};function uD(e,t,n){return e?e.textures.acquire(t,n):fD().acquire(t,n)}function dD(e,t,n){return e?e.textures.acquireOwn(t,n):fD().acquireOwn(t,n)}function fD(){return new lD}var pD=class{engine;models=new Map;animations=new Map;modelKeys=new Map;animationKeys=new Map;loader;textures;constructor(e=null){this.engine=e,this.loader=new oE,this.loader.register(e=>new ET(e)),this.textures=new lD({diagnostics:e?{warn:(...t)=>Nt(e,`warn`,...t)}:null})}errors(){let e=[];for(let{url:t,error:n}of this.textures.errors())e.push({ref:t,url:t,error:n});for(let[t,n]of this.modelKeys){let r=this.models.get(n);r?.error&&e.push({ref:t,url:n,error:String(r.error)})}for(let[t,n]of this.animationKeys){let r=this.animations.get(n.url);r?.error&&e.push({ref:t,url:n.url,error:String(r.error)})}return e}load(e){for(let[t,n]of Object.entries(e)){let e=n;typeof e.url==`string`&&(e.type===`model`?this.modelKeys.set(`$${t}`,e.url):e.type===`animation`&&this.animationKeys.set(`$${t}`,{url:e.url,clip:e.clip}))}}animationRefs(){return[...this.animationKeys.keys()]}modelRefs(){return[...this.modelKeys.keys()]}getModel(e){let t=this.modelKeys.get(e)??e,n=this.models.get(t);return n||(n={status:`loading`,scene:null,animations:[],isVrm:!1,vrm:null,claimedBy:null,retargeted:new Map},this.models.set(t,n),this.loader.load(t,e=>{let r=e.userData.vrm;r?(nE.removeUnnecessaryVertices(e.scene),nE.combineSkeletons(e.scene),nE.rotateVRM0(r),n.scene=r.scene,n.vrm=r,n.isVrm=!0):n.scene=e.scene,n.animations=e.animations??[],n.status=`ready`,mD(n.scene)||(n.error="loaded, but it contains no meshes — this is an animation-only GLB. A clip file belongs in `animation`, not `model`.",Nt(this.engine,`error`,`incanto: '${t}' ${n.error}`))},void 0,e=>{n.status=`error`,n.error=e instanceof Error?e.message:String(e),Nt(this.engine,`error`,`incanto: failed to load model '${t}':`,e)}),n)}getAnimation(e){let t=this.animationKeys.get(e)??{url:e},n=this.animations.get(t.url);return n||(n={status:`loading`,clips:[],scene:null,clip:t.clip},this.animations.set(t.url,n),this.loader.load(t.url,e=>{n.clips=e.animations??[],n.scene=e.scene,n.status=`ready`,n.clips.length===0&&Nt(this.engine,`warn`,`incanto: animation asset '${t.url}' contains no clips`)},void 0,e=>{n.status=`error`,n.error=e instanceof Error?e.message:String(e),Nt(this.engine,`error`,`incanto: failed to load animation '${t.url}':`,e)}),n)}dispose(){this.textures.dispose();for(let e of this.models.values())e.scene?.traverse(e=>{let t=e;t.geometry?.dispose();let n=Array.isArray(t.material)?t.material:[t.material];for(let e of n)if(e){for(let t of Object.values(e))t?.isTexture&&t.dispose();e.dispose()}});this.models.clear(),this.animations.clear()}};function mD(e){let t=e?.traverse;if(!t)return!0;let n=!1;return t.call(e,e=>{e.isMesh&&(n=!0)}),n}var hD=Math.atan(1/Math.SQRT2);function gD(e,t,n,r,i,a){let o=[t[0],t[1]+n,t[2]];if(e===`firstPerson`)return{position:o,rotation:[-i,r,0]};if(e===`quarter`){let e=hD;return{position:[o[0],o[1]+a*Math.sin(e),o[2]+a*Math.cos(e)],rotation:[-e,0,0]}}if(e===`side`)return{position:[o[0],o[1],o[2]+a],rotation:[0,0,0]};let s=Math.cos(i);return{position:[o[0]+Math.sin(r)*s*a,o[1]+Math.sin(i)*a,o[2]+Math.cos(r)*s*a],rotation:[-i,r,0]}}function _D(e,t,n,r,i){let a=t[0]-e[0],o=t[1]-e[1],s=t[2]-e[2],c=Math.hypot(a,o,s);if(c<1e-4)return[t[0],t[1],t[2]];let l=[a/c,o/c,s/c],u=n(e,l,c);if(u===null)return[t[0],t[1],t[2]];let d=Math.min(c,Math.max(i,u-r));return[e[0]+l[0]*d,e[1]+l[1]*d,e[2]+l[2]*d]}function vD(e,t,n){let r=t(e,n);return r===null||r>=n?[e[0],e[1],e[2]]:[e[0],e[1]+(n-r),e[2]]}function yD(e,t,n){let r=Math.sin(n),i=Math.cos(n);return[e*i-t*r,0,-e*r-t*i]}function bD(e,t){return e?Math.min(.6+(t?.4:0),1):0}function xD(e,t){return e?t<=0?`idle`:t<.3?`walk`:t<.7?`run`:`fastRun`:`airborne`}var SD=50;function CD(e=SD,t=typeof requestAnimationFrame==`function`?requestAnimationFrame:void 0){return new Promise(n=>{let r=!1,i=()=>{r||(r=!0,n())},a=setTimeout(i,Math.max(0,e));t&&t(()=>{setTimeout(()=>{clearTimeout(a),i()},0)})})}function wD(e,t){let n=e.scene;if(!n)throw new L(`BAD_FORMAT`,`setEnvironment3D: the engine has no scene.`);let r={...n.environment??{}};for(let[e,n]of Object.entries(t))n===null?delete r[e]:typeof n==`object`&&!Array.isArray(n)&&typeof r[e]==`object`&&r[e]!==null&&!Array.isArray(r[e])?r[e]={...r[e],...n}:r[e]=n;ei(r),n.environment=r}var TD=[`color`,`metalness`,`roughness`,`emissive`,`emissiveIntensity`,`wireframe`,`flatShading`,`opacity`,`clearcoat`,`clearcoatRoughness`,`envMapIntensity`,`depthTest`,`depthWrite`,`map`,`normalMap`,`repeat`],ED=class extends Z_{static typeName=`MeshInstance3D`;static props={mesh:{default:`box`,options:[`box`,`sphere`,`capsule`,`plane`,`cylinder`,`gem`]},size:{default:[1,1,1]},material:{default:{}},castShadow:{default:!1},receiveShadow:{default:!1}};mesh=`box`;size=[1,1,1];material={};castShadow=!1;receiveShadow=!1;static validateJson(e){OD(e.material,e.name)}geometryKey=``;textureKey=``;loadedTextures=[];_createObject3D(){return new iu(new dd(1,1,1),new Ad)}_syncObject3D(e=1,t=null){super._syncObject3D(e,t);let n=this._ensureObject3D(),r=`${this.mesh}:${JSON.stringify(this.size)}`;r!==this.geometryKey&&(n.geometry.dispose(),n.geometry=kD(this.mesh,this.size),this.geometryKey=r);let i=n.material;DD(i,this.material),this.syncTextures(i,t),n.castShadow=this.castShadow,n.receiveShadow=this.receiveShadow}syncTextures(e,t){let n=JSON.stringify([this.material.map??``,this.material.normalMap??``,this.material.repeat??null]);if(n===this.textureKey)return;this.textureKey=n;for(let e of this.loadedTextures)e.dispose();this.loadedTextures=[];let r=e.map!==null||e.normalMap!==null;e.map=null,e.normalMap=null,this.material.map&&(e.map=this.loadTexture(t,this.material.map,!0)),this.material.normalMap&&(e.normalMap=this.loadTexture(t,this.material.normalMap,!1)),(r||e.map||e.normalMap)&&(e.needsUpdate=!0)}loadTexture(e,t,n){let r=dD(e,t,{wrap:`repeat`,anisotropy:4,colorSpace:n?`srgb`:`linear`});if(!r)return null;let[i,a]=this.material.repeat??[1,1];return r.repeat.set(i,a),this.loadedTextures.push(r),r}free(){for(let e of this.loadedTextures)e.dispose();this.loadedTextures=[];let e=this._builtObject3D;if(e){e.geometry?.dispose();let t=Array.isArray(e.material)?e.material:[e.material];for(let e of t)e?.dispose()}super.free()}};function DD(e,t){e.color.set(t.color??`#ffffff`),e.metalness=t.metalness??0,e.roughness=t.roughness??1,e.wireframe=t.wireframe??!1,e.emissive.set(t.emissive??`#000000`),e.emissiveIntensity=t.emissiveIntensity??1;let n=t.opacity??1;e.opacity=n,e.transparent=n<1;let r=t.clearcoat??0;e.clearcoat>0!=r>0&&(e.needsUpdate=!0),e.clearcoat=r,e.clearcoatRoughness=t.clearcoatRoughness??0,e.envMapIntensity=t.envMapIntensity??1,e.depthTest=t.depthTest??!0,e.depthWrite=t.depthWrite??!0;let i=t.flatShading??!1;e.flatShading!==i&&(e.flatShading=i,e.needsUpdate=!0)}function OD(e,t,n=`MeshInstance3D`){let r=e=>{throw new L(`BAD_FORMAT`,`${n} '${t}' ${e}`,{prop:`material`,validOptions:[...TD]})};(typeof e!=`object`||!e||Array.isArray(e))&&r(`material must be an object, got ${JSON.stringify(e)}.`);for(let t of Object.keys(e))TD.includes(t)||r(`material has unknown key '${t}' — must be one of [${TD.join(`, `)}].`);for(let t of[`map`,`normalMap`]){let n=e[t];n!==void 0&&(typeof n!=`string`||n.length===0)&&r(`material.${t} must be a non-empty texture URL string, got ${JSON.stringify(n)}.`)}if(e.repeat!==void 0){let t=e.repeat;(!Array.isArray(t)||t.length!==2||!t.every(e=>typeof e==`number`&&Number.isFinite(e)&&e>0))&&r(`material.repeat must be [u, v] with positive numbers, got ${JSON.stringify(t)}.`),!e.map&&!e.normalMap&&r(`material.repeat tiles nothing — add a 'map' and/or 'normalMap' texture URL.`)}for(let t of[`metalness`,`roughness`,`opacity`,`clearcoat`,`clearcoatRoughness`]){let n=e[t];n!==void 0&&!(typeof n==`number`&&n>=0&&n<=1)&&r(`material.${t} must be a number in 0..1, got ${JSON.stringify(n)}.`)}e.envMapIntensity!==void 0&&!(typeof e.envMapIntensity==`number`&&Number.isFinite(e.envMapIntensity)&&e.envMapIntensity>=0)&&r(`material.envMapIntensity must be a number >= 0, got ${JSON.stringify(e.envMapIntensity)}.`);for(let t of[`wireframe`,`flatShading`,`depthTest`,`depthWrite`]){let n=e[t];n!==void 0&&typeof n!=`boolean`&&r(`material.${t} must be a boolean, got ${JSON.stringify(n)}.`)}}function kD(e,t){let n=t[0]??1,r=t[1]??1,i=t[2]??1;switch(e){case`box`:return new dd(n,r,i);case`sphere`:return new vd(n,32,16);case`gem`:return new gd(n,0);case`capsule`:return new fd(n,r,8,16);case`plane`:{let e=new _d(n,i);return e.rotateX(-Math.PI/2),e}case`cylinder`:return new pd(n,n,r,24);default:throw new L(`PROP_TYPE_MISMATCH`,`MeshInstance3D.mesh must be one of box|sphere|capsule|plane|cylinder|gem, got '${e}'.`)}}var AD=class extends Z_{static typeName=`InstancedMesh3D`;static props={mesh:{default:`box`,options:[`box`,`sphere`,`capsule`,`plane`,`cylinder`,`gem`]},size:{default:[1,1,1]},material:{default:{}},transforms:{default:[]},castShadow:{default:!1},receiveShadow:{default:!1},collider:{default:null}};mesh=`box`;size=[1,1,1];material={};castShadow=!1;receiveShadow=!1;collider=null;_transforms=[];transformsDirty=!0;get transforms(){return this._transforms}set transforms(e){this._transforms=e,this.transformsDirty=!0}instanced=null;builtKey=``;static validateJson(e){let t=e;OD(t.material,e.name);for(let[n,r]of t._transforms.entries())if(!Array.isArray(r)||r.length<3||r.length>5||r.some(e=>typeof e!=`number`))throw new L(`BAD_FORMAT`,`InstancedMesh3D '${e.name}': transforms[${n}] must be [x, y, z, yawDeg?, scale?] (numbers), got ${JSON.stringify(r)}.`)}get instanceCount(){return this.instanced?.count??0}_syncObject3D(e){super._syncObject3D(e);let t=this._ensureObject3D(),n=`${this.mesh} ${JSON.stringify(this.size)} ${this._transforms.length}`;if(n!==this.builtKey){if(this.builtKey=n,this.instanced&&=(t.remove(this.instanced),this.instanced.geometry.dispose(),this.instanced.material.dispose(),null),this._transforms.length>0){let e=kD(this.mesh,this.size),n=new Ad;this.instanced=new Au(e,n,this._transforms.length),this.instanced.instanceMatrix.setUsage(Wo),t.add(this.instanced)}this.transformsDirty=!0}let r=this.instanced;if(r&&(r.castShadow=this.castShadow,r.receiveShadow=this.receiveShadow,DD(r.material,this.material),this.transformsDirty)){this.transformsDirty=!1;for(let e=0;e<this._transforms.length;e++){let t=this._transforms[e];MD.set(t[0]??0,t[1]??0,t[2]??0),ND.setFromAxisAngle(jD,(t[3]??0)*Math.PI/180);let n=t[4]??1;PD.set(n,n,n),FD.compose(MD,ND,PD),r.setMatrixAt(e,FD)}r.instanceMatrix.needsUpdate=!0,r.computeBoundingSphere()}}free(){this.instanced&&(this.instanced.geometry.dispose(),this.instanced.material.dispose()),super.free()}},jD=new W(0,1,0),MD=new W,ND=new U,PD=new W,FD=new K,ID=class extends Z_{static typeName=`Joint3D`;static props={type:{default:`spherical`,options:[`fixed`,`spherical`,`rope`,`spring`]},target:{default:``,nodePath:!0,required:!0},anchor:{default:[0,0,0]},targetAnchor:{default:[0,0,0]},length:{default:0},stiffness:{default:50},damping:{default:5}};type=`spherical`;target=``;anchor=[0,0,0];targetAnchor=[0,0,0];length=0;stiffness=50;damping=5;onEnterTree(){if(!(this.parent instanceof Q_))throw new L(`TREE_VIOLATION`,`Joint3D '${this.name}' must be a child of a physics body (its body A); parent is '${this.parent?.name??`none`}'.`);if(this.target===``)throw new L(`BAD_FORMAT`,`Joint3D '${this.name}' needs a "target" node path to the body it links to.`)}_resolveBodies(){let e=this.parent,t=this.getNodeOrNull(this.target);if(!(t instanceof Q_))throw new L(`NODE_NOT_FOUND`,`Joint3D '${this.name}': target '${this.target}' is not a physics body.`);return{a:e,b:t}}},LD=256,RD=.3,zD=.6,BD=45;function VD(e){let{width:t,depth:n,segsX:r,segsZ:i,maxHeight:a,seed:o}=e,s=e.roughness??.5,c=e.detail??4,l=e.flatThreshold??.95,u=e.islandEdge??!1,d=Math.max(0,Math.min(e.edgeWrapRadius??20,BD)),f=e.edgeBottom??-50,p=e.edgeCornerSmoothness??1,m=(e.basins??[]).map(e=>({cx:e.x+t/2,cz:e.z+n/2,radius:e.radius,depth:e.depth})),h=(e.channels??[]).map(e=>({half:Math.max(e.width,0)/2,taper:Math.max(e.taper??e.width,.001),depth:e.depth,segs:e.path.map(e=>({x:(e[0]??0)+t/2,z:(e[1]??0)+n/2})).flatMap((e,t,n)=>t===0?[]:[{ax:n[t-1].x,az:n[t-1].z,bx:e.x,bz:e.z}])})).filter(e=>e.segs.length>0&&e.depth!==0),g=Sr(o),_=(e,t)=>(g(e,t)+1)*.5,v=(e,t)=>{let n=e/LD,r=t/LD,i=0,o=.2,u=5;for(let e=0;e<5;e++)i+=_(n*o,r*o)*u,u*=.5,o*=2;let d=0;o=.5,u=.1;for(let e=0;e<c;e++)d+=_(n*o,r*o)*u,u*=s,o*=2;i=Math.abs(i)**1.5*Math.sign(i),i<RD&&(i*=.3);let f=a*(i+d*(i*.5+.5)+1)/2,p=a*l;if(Math.abs(f-p)<zD&&(f=p),m.length>0){let n=0,r=0;for(let i of m){let a=Math.hypot(e-i.cx,t-i.cz);if(a<i.radius){let e=a/i.radius,t=1-e*e*(3-2*e);i.depth>=0?n=Math.max(n,i.depth*t):r=Math.max(r,-i.depth*t)}}f+=r-n}if(h.length>0){let n=0;for(let r of h){let i=1/0;for(let n of r.segs){let a=n.bx-n.ax,o=n.bz-n.az,s=a*a+o*o,c=s>1e-9?Math.min(1,Math.max(0,((e-n.ax)*a+(t-n.az)*o)/s)):0,l=n.ax+a*c,u=n.az+o*c,d=Math.hypot(e-l,t-u);if(d<i&&(i=d),i<=r.half)break}if(i>=r.half+r.taper)continue;let a=Math.min(1,Math.max(0,(i-r.half)/r.taper));n=Math.max(n,r.depth*(1-a*a*(3-2*a)))}f-=n}return f},y=(e,a,o)=>{if(!u||d<=0)return o;let s=d,c=Math.min(e,t-e),l=Math.min(a,n-a),m=(t/r+n/i)*.002,h=Math.max(0,s-c+m),g=Math.max(0,s-l+m);if(h<=0&&g<=0)return o;let _=2+(1-Math.min(1,Math.max(0,p)))*30,v=(h**_+g**_)**(1/_),y=o-(s-Math.sqrt(Math.max(0,s*s-v*v)));return v>=s&&(y=Math.min(y,f)),y},b=r+1,x=i+1,S=new Float32Array(b*x),C=1/0,w=-1/0;for(let e=0;e<x;e++){let a=e/i*n;for(let n=0;n<b;n++){let i=n/r*t,o=v(i,a);o<C&&(C=o),o>w&&(w=o),S[e*b+n]=y(i,a,o)}}let T=(e,a)=>{let o=Math.min(Math.max((e+t/2)/t*r,0),r),s=Math.min(Math.max((a+n/2)/n*i,0),i),c=Math.min(Math.floor(o),r-1),l=Math.min(Math.floor(s),i-1),u=o-c,d=s-l,f=S[l*b+c],p=S[l*b+c+1],m=S[(l+1)*b+c],h=S[(l+1)*b+c+1];return(f*(1-u)+p*u)*(1-d)+(m*(1-u)+h*u)*d},E=(e,r)=>v(e+t/2,r+n/2);return{width:t,depth:n,segsX:r,segsZ:i,heights:S,minHeight:C,maxHeight:w,heightAt:T,baseHeight:E,slopeAt:(e,t)=>{let n=(E(e+1,t)-E(e-1,t))/2,r=(E(e,t+1)-E(e,t-1))/2;return Math.atan(Math.sqrt(n*n+r*r))}}}function HD(e,t,n,r){return e<t-r||e>n+r?0:e>=t&&e<=n?1:e<t?(e-(t-r))/r:(n+r-e)/r}function UD(e,t,n,r=1.2){let i=[0,0,0,0],a=Math.min(n.length,4),o=0;for(let s=0;s<a;s++){let a=n[s],[c,l]=a.heightRange??[0,1],[u,d]=a.slopeRange??[0,Math.PI/2],f=HD(e,c,l,a.heightBlendRange??.1)*HD(t,u,d,a.slopeBlendRange??.1);f**=1/r,i[s]=f,o+=f}if(o===0)return[1,0,0,0];for(let e=0;e<4;e++)i[e]=i[e]/o;return i}function WD(e,t,n){let r=e.indexOf(t);if(r===-1)throw new L(`BAD_FORMAT`,`Terrain3D shader patch: marker '${t}' not found in the three.js shader — the installed three version moved its chunks.`);let i=r+t.length;return`${e.slice(0,i)}\n${n}${e.slice(i)}`}var GD=`
|
|
6705
|
+
`;e.vertexShader=t+e.vertexShader,e.fragmentShader=t+e.fragmentShader}}get color(){return this.uniforms.litFactor.value}set color(e){this.uniforms.litFactor.value=e}get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}get normalMap(){return this.uniforms.normalMap.value}set normalMap(e){this.uniforms.normalMap.value=e}get normalScale(){return this.uniforms.normalScale.value}set normalScale(e){this.uniforms.normalScale.value=e}get emissive(){return this.uniforms.emissive.value}set emissive(e){this.uniforms.emissive.value=e}get emissiveIntensity(){return this.uniforms.emissiveIntensity.value}set emissiveIntensity(e){this.uniforms.emissiveIntensity.value=e}get emissiveMap(){return this.uniforms.emissiveMap.value}set emissiveMap(e){this.uniforms.emissiveMap.value=e}get shadeColorFactor(){return this.uniforms.shadeColorFactor.value}set shadeColorFactor(e){this.uniforms.shadeColorFactor.value=e}get shadeMultiplyTexture(){return this.uniforms.shadeMultiplyTexture.value}set shadeMultiplyTexture(e){this.uniforms.shadeMultiplyTexture.value=e}get shadingShiftFactor(){return this.uniforms.shadingShiftFactor.value}set shadingShiftFactor(e){this.uniforms.shadingShiftFactor.value=e}get shadingShiftTexture(){return this.uniforms.shadingShiftTexture.value}set shadingShiftTexture(e){this.uniforms.shadingShiftTexture.value=e}get shadingShiftTextureScale(){return this.uniforms.shadingShiftTextureScale.value}set shadingShiftTextureScale(e){this.uniforms.shadingShiftTextureScale.value=e}get shadingToonyFactor(){return this.uniforms.shadingToonyFactor.value}set shadingToonyFactor(e){this.uniforms.shadingToonyFactor.value=e}get giEqualizationFactor(){return this.uniforms.giEqualizationFactor.value}set giEqualizationFactor(e){this.uniforms.giEqualizationFactor.value=e}get matcapFactor(){return this.uniforms.matcapFactor.value}set matcapFactor(e){this.uniforms.matcapFactor.value=e}get matcapTexture(){return this.uniforms.matcapTexture.value}set matcapTexture(e){this.uniforms.matcapTexture.value=e}get parametricRimColorFactor(){return this.uniforms.parametricRimColorFactor.value}set parametricRimColorFactor(e){this.uniforms.parametricRimColorFactor.value=e}get rimMultiplyTexture(){return this.uniforms.rimMultiplyTexture.value}set rimMultiplyTexture(e){this.uniforms.rimMultiplyTexture.value=e}get rimLightingMixFactor(){return this.uniforms.rimLightingMixFactor.value}set rimLightingMixFactor(e){this.uniforms.rimLightingMixFactor.value=e}get parametricRimFresnelPowerFactor(){return this.uniforms.parametricRimFresnelPowerFactor.value}set parametricRimFresnelPowerFactor(e){this.uniforms.parametricRimFresnelPowerFactor.value=e}get parametricRimLiftFactor(){return this.uniforms.parametricRimLiftFactor.value}set parametricRimLiftFactor(e){this.uniforms.parametricRimLiftFactor.value=e}get outlineWidthMultiplyTexture(){return this.uniforms.outlineWidthMultiplyTexture.value}set outlineWidthMultiplyTexture(e){this.uniforms.outlineWidthMultiplyTexture.value=e}get outlineWidthFactor(){return this.uniforms.outlineWidthFactor.value}set outlineWidthFactor(e){this.uniforms.outlineWidthFactor.value=e}get outlineColorFactor(){return this.uniforms.outlineColorFactor.value}set outlineColorFactor(e){this.uniforms.outlineColorFactor.value=e}get outlineLightingMixFactor(){return this.uniforms.outlineLightingMixFactor.value}set outlineLightingMixFactor(e){this.uniforms.outlineLightingMixFactor.value=e}get uvAnimationMaskTexture(){return this.uniforms.uvAnimationMaskTexture.value}set uvAnimationMaskTexture(e){this.uniforms.uvAnimationMaskTexture.value=e}get uvAnimationScrollXOffset(){return this.uniforms.uvAnimationScrollXOffset.value}set uvAnimationScrollXOffset(e){this.uniforms.uvAnimationScrollXOffset.value=e}get uvAnimationScrollYOffset(){return this.uniforms.uvAnimationScrollYOffset.value}set uvAnimationScrollYOffset(e){this.uniforms.uvAnimationScrollYOffset.value=e}get uvAnimationRotationPhase(){return this.uniforms.uvAnimationRotationPhase.value}set uvAnimationRotationPhase(e){this.uniforms.uvAnimationRotationPhase.value=e}get ignoreVertexColor(){return this._ignoreVertexColor}set ignoreVertexColor(e){this._ignoreVertexColor=e,this.needsUpdate=!0}get v0CompatShade(){return this._v0CompatShade}set v0CompatShade(e){this._v0CompatShade=e,this.needsUpdate=!0}get debugMode(){return this._debugMode}set debugMode(e){this._debugMode=e,this.needsUpdate=!0}get outlineWidthMode(){return this._outlineWidthMode}set outlineWidthMode(e){this._outlineWidthMode=e,this.needsUpdate=!0}get isOutline(){return this._isOutline}set isOutline(e){this._isOutline=e,this.needsUpdate=!0}get isMToonMaterial(){return!0}update(e){this._uploadUniformsWorkaround(),this._updateUVAnimation(e)}copy(e){return super.copy(e),this.map=e.map,this.normalMap=e.normalMap,this.emissiveMap=e.emissiveMap,this.shadeMultiplyTexture=e.shadeMultiplyTexture,this.shadingShiftTexture=e.shadingShiftTexture,this.matcapTexture=e.matcapTexture,this.rimMultiplyTexture=e.rimMultiplyTexture,this.outlineWidthMultiplyTexture=e.outlineWidthMultiplyTexture,this.uvAnimationMaskTexture=e.uvAnimationMaskTexture,this.normalMapType=e.normalMapType,this.uvAnimationScrollXSpeedFactor=e.uvAnimationScrollXSpeedFactor,this.uvAnimationScrollYSpeedFactor=e.uvAnimationScrollYSpeedFactor,this.uvAnimationRotationSpeedFactor=e.uvAnimationRotationSpeedFactor,this.ignoreVertexColor=e.ignoreVertexColor,this.v0CompatShade=e.v0CompatShade,this.debugMode=e.debugMode,this.outlineWidthMode=e.outlineWidthMode,this.isOutline=e.isOutline,this.needsUpdate=!0,this}_updateUVAnimation(e){this.uniforms.uvAnimationScrollXOffset.value+=e*this.uvAnimationScrollXSpeedFactor,this.uniforms.uvAnimationScrollYOffset.value+=e*this.uvAnimationScrollYSpeedFactor,this.uniforms.uvAnimationRotationPhase.value+=e*this.uvAnimationRotationSpeedFactor,this.uniforms.alphaTest.value=this.alphaTest,this.uniformsNeedUpdate=!0}_uploadUniformsWorkaround(){this.uniforms.opacity.value=this.opacity,this._updateTextureMatrix(this.uniforms.map,this.uniforms.mapUvTransform),this._updateTextureMatrix(this.uniforms.normalMap,this.uniforms.normalMapUvTransform),this._updateTextureMatrix(this.uniforms.emissiveMap,this.uniforms.emissiveMapUvTransform),this._updateTextureMatrix(this.uniforms.shadeMultiplyTexture,this.uniforms.shadeMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.shadingShiftTexture,this.uniforms.shadingShiftTextureUvTransform),this._updateTextureMatrix(this.uniforms.matcapTexture,this.uniforms.matcapTextureUvTransform),this._updateTextureMatrix(this.uniforms.rimMultiplyTexture,this.uniforms.rimMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.outlineWidthMultiplyTexture,this.uniforms.outlineWidthMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.uvAnimationMaskTexture,this.uniforms.uvAnimationMaskTextureUvTransform),this.uniformsNeedUpdate=!0}_generateDefines(){let e=this.outlineWidthMultiplyTexture!==null,t=this.map!==null||this.normalMap!==null||this.emissiveMap!==null||this.shadeMultiplyTexture!==null||this.shadingShiftTexture!==null||this.rimMultiplyTexture!==null||this.uvAnimationMaskTexture!==null;return{THREE_VRM_THREE_REVISION:184,OUTLINE:this._isOutline,MTOON_USE_UV:e||t,MTOON_UVS_VERTEX_ONLY:e&&!t,V0_COMPAT_SHADE:this._v0CompatShade,USE_SHADEMULTIPLYTEXTURE:this.shadeMultiplyTexture!==null,USE_SHADINGSHIFTTEXTURE:this.shadingShiftTexture!==null,USE_MATCAPTEXTURE:this.matcapTexture!==null,USE_RIMMULTIPLYTEXTURE:this.rimMultiplyTexture!==null,USE_OUTLINEWIDTHMULTIPLYTEXTURE:this._isOutline&&this.outlineWidthMultiplyTexture!==null,USE_UVANIMATIONMASKTEXTURE:this.uvAnimationMaskTexture!==null,IGNORE_VERTEX_COLOR:this._ignoreVertexColor===!0,DEBUG_NORMAL:this._debugMode===`normal`,DEBUG_LITSHADERATE:this._debugMode===`litShadeRate`,DEBUG_UV:this._debugMode===`uv`,OUTLINE_WIDTH_SCREEN:this._isOutline&&this._outlineWidthMode===GC.ScreenCoordinates}}_updateTextureMatrix(e,t){e.value&&(e.value.matrixAutoUpdate&&e.value.updateMatrix(),t.value.copy(e.value.matrix))}},JC=new Set([`1.0`,`1.0-beta`]),YC=class e{get name(){return e.EXTENSION_NAME}constructor(e,t={}){this.parser=e,this.materialType=t.materialType??qC,this.renderOrderOffset=t.renderOrderOffset??0,this.v0CompatShade=t.v0CompatShade??!1,this.debugMode=t.debugMode??`none`,this._mToonMaterialSet=new Set}beforeRoot(){return zC(this,null,function*(){this._removeUnlitExtensionIfMToonExists()})}afterRoot(e){return zC(this,null,function*(){e.userData.vrmMToonMaterials=Array.from(this._mToonMaterialSet)})}getMaterialType(e){return this._getMToonExtension(e)?this.materialType:null}extendMaterialParams(e,t){let n=this._getMToonExtension(e);return n?this._extendMaterialParams(n,t):null}loadMesh(e){return zC(this,null,function*(){let t=this.parser,n=t.json.meshes?.[e];if(n==null)throw Error(`MToonMaterialLoaderPlugin: Attempt to use meshes[${e}] of glTF but the mesh doesn't exist`);let r=n.primitives,i=yield t.loadMesh(e);if(r.length===1){let e=i,t=r[0].material;t!=null&&this._setupPrimitive(e,t)}else{let e=i;for(let t=0;t<r.length;t++){let n=e.children[t],i=r[t].material;i!=null&&this._setupPrimitive(n,i)}}return i})}_removeUnlitExtensionIfMToonExists(){this.parser.json.materials?.map((e,t)=>{this._getMToonExtension(t)&&e.extensions?.KHR_materials_unlit&&delete e.extensions.KHR_materials_unlit})}_getMToonExtension(t){let n=this.parser.json.materials?.[t];if(n==null){console.warn(`MToonMaterialLoaderPlugin: Attempt to use materials[${t}] of glTF but the material doesn't exist`);return}let r=n.extensions?.[e.EXTENSION_NAME];if(r==null)return;let i=r.specVersion;if(!JC.has(i)){console.warn(`MToonMaterialLoaderPlugin: Unknown ${e.EXTENSION_NAME} specVersion "${i}"`);return}return r}_extendMaterialParams(e,t){return zC(this,null,function*(){delete t.metalness,delete t.roughness;let n=new VC(this.parser,t);n.assignPrimitive(`transparentWithZWrite`,e.transparentWithZWrite),n.assignColor(`shadeColorFactor`,e.shadeColorFactor),n.assignTexture(`shadeMultiplyTexture`,e.shadeMultiplyTexture,!0),n.assignPrimitive(`shadingShiftFactor`,e.shadingShiftFactor),n.assignTexture(`shadingShiftTexture`,e.shadingShiftTexture,!0),n.assignPrimitive(`shadingShiftTextureScale`,e.shadingShiftTexture?.scale),n.assignPrimitive(`shadingToonyFactor`,e.shadingToonyFactor),n.assignPrimitive(`giEqualizationFactor`,e.giEqualizationFactor),n.assignColor(`matcapFactor`,e.matcapFactor),n.assignTexture(`matcapTexture`,e.matcapTexture,!0),n.assignColor(`parametricRimColorFactor`,e.parametricRimColorFactor),n.assignTexture(`rimMultiplyTexture`,e.rimMultiplyTexture,!0),n.assignPrimitive(`rimLightingMixFactor`,e.rimLightingMixFactor),n.assignPrimitive(`parametricRimFresnelPowerFactor`,e.parametricRimFresnelPowerFactor),n.assignPrimitive(`parametricRimLiftFactor`,e.parametricRimLiftFactor),n.assignPrimitive(`outlineWidthMode`,e.outlineWidthMode),n.assignPrimitive(`outlineWidthFactor`,e.outlineWidthFactor),n.assignTexture(`outlineWidthMultiplyTexture`,e.outlineWidthMultiplyTexture,!1),n.assignColor(`outlineColorFactor`,e.outlineColorFactor),n.assignPrimitive(`outlineLightingMixFactor`,e.outlineLightingMixFactor),n.assignTexture(`uvAnimationMaskTexture`,e.uvAnimationMaskTexture,!1),n.assignPrimitive(`uvAnimationScrollXSpeedFactor`,e.uvAnimationScrollXSpeedFactor),n.assignPrimitive(`uvAnimationScrollYSpeedFactor`,e.uvAnimationScrollYSpeedFactor),n.assignPrimitive(`uvAnimationRotationSpeedFactor`,e.uvAnimationRotationSpeedFactor),n.assignPrimitive(`v0CompatShade`,this.v0CompatShade),n.assignPrimitive(`debugMode`,this.debugMode),yield n.pending})}_setupPrimitive(e,t){let n=this._getMToonExtension(t);if(n){e.renderOrder=this._parseRenderOrder(n)+this.renderOrderOffset,this._generateOutline(e),this._addToMaterialSet(e);return}}_shouldGenerateOutline(e){return typeof e.outlineWidthMode==`string`&&e.outlineWidthMode!==`none`&&typeof e.outlineWidthFactor==`number`&&e.outlineWidthFactor>0}_generateOutline(e){let t=e.material;if(!(t instanceof Ll)||!this._shouldGenerateOutline(t))return;e.material=[t];let n=t.clone();n.name+=` (Outline)`,n.isOutline=!0,n.side=1,e.material.push(n);let r=e.geometry,i=r.index?r.index.count:r.attributes.position.count/3;r.addGroup(0,i,0),r.addGroup(0,i,1)}_addToMaterialSet(e){let t=e.material,n=new Set;Array.isArray(t)?t.forEach(e=>n.add(e)):n.add(t);for(let e of n)this._mToonMaterialSet.add(e)}_parseRenderOrder(e){return(e.transparentWithZWrite?0:19)+(e.renderQueueOffsetNumber??0)}};YC.EXTENSION_NAME=`VRMC_materials_mtoon`;var XC=YC,ZC=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),QC=class e{get name(){return e.EXTENSION_NAME}constructor(e){this.parser=e}extendMaterialParams(e,t){return ZC(this,null,function*(){let n=this._getHDREmissiveMultiplierExtension(e);n!=null&&(console.warn("VRMMaterialsHDREmissiveMultiplierLoaderPlugin: `VRMC_materials_hdr_emissiveMultiplier` is archived. Use `KHR_materials_emissive_strength` instead."),t.emissiveIntensity=n.emissiveMultiplier)})}_getHDREmissiveMultiplierExtension(t){let n=this.parser.json.materials?.[t];if(n==null){console.warn(`VRMMaterialsHDREmissiveMultiplierLoaderPlugin: Attempt to use materials[${t}] of glTF but the material doesn't exist`);return}let r=n.extensions?.[e.EXTENSION_NAME];if(r!=null)return r}};QC.EXTENSION_NAME=`VRMC_materials_hdr_emissiveMultiplier`;var $C=QC,ew=Object.defineProperty,tw=Object.defineProperties,nw=Object.getOwnPropertyDescriptors,rw=Object.getOwnPropertySymbols,iw=Object.prototype.hasOwnProperty,aw=Object.prototype.propertyIsEnumerable,ow=(e,t,n)=>t in e?ew(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,sw=(e,t)=>{for(var n in t||={})iw.call(t,n)&&ow(e,n,t[n]);if(rw)for(var n of rw(t))aw.call(t,n)&&ow(e,n,t[n]);return e},cw=(e,t)=>tw(e,nw(t)),lw=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())});function uw(e){return e**2.2}var dw=class{get name(){return`VRMMaterialsV0CompatPlugin`}constructor(e){this.parser=e,this._renderQueueMapTransparent=new Map,this._renderQueueMapTransparentZWrite=new Map;let t=this.parser.json;t.extensionsUsed=t.extensionsUsed??[],t.extensionsUsed.indexOf(`KHR_texture_transform`)===-1&&t.extensionsUsed.push(`KHR_texture_transform`)}beforeRoot(){return lw(this,null,function*(){let e=this.parser.json,t=e.extensions?.VRM?.materialProperties;t&&(this._populateRenderQueueMap(t),t.forEach((t,n)=>{let r=e.materials?.[n];if(r==null){console.warn(`VRMMaterialsV0CompatPlugin: Attempt to use materials[${n}] of glTF but the material doesn't exist`);return}if(t.shader===`VRM/MToon`){let i=this._parseV0MToonProperties(t,r);e.materials[n]=i}else if(t.shader?.startsWith(`VRM/Unlit`)){let i=this._parseV0UnlitProperties(t,r);e.materials[n]=i}else t.shader===`VRM_USE_GLTFSHADER`||console.warn(`VRMMaterialsV0CompatPlugin: Unknown shader: ${t.shader}`)}))})}_parseV0MToonProperties(e,t){let n=e.keywordMap?._ALPHABLEND_ON??!1,r=e.floatProperties?._ZWrite===1&&n,i=this._v0ParseRenderQueue(e),a=e.keywordMap?._ALPHATEST_ON??!1,o=n?`BLEND`:a?`MASK`:`OPAQUE`,s=a?e.floatProperties?._Cutoff??.5:void 0,c=(e.floatProperties?._CullMode??2)===0,l=this._portTextureTransform(e),u=(e.vectorProperties?._Color??[1,1,1,1]).map((e,t)=>t===3?e:uw(e)),d=e.textureProperties?._MainTex,f=d==null?void 0:{index:d,extensions:sw({},l)},p=e.floatProperties?._BumpScale??1,m=e.textureProperties?._BumpMap,h=m==null?void 0:{index:m,scale:p,extensions:sw({},l)},g=(e.vectorProperties?._EmissionColor??[0,0,0,1]).map(uw),_=e.textureProperties?._EmissionMap,v=_==null?void 0:{index:_,extensions:sw({},l)},y=(e.vectorProperties?._ShadeColor??[.97,.81,.86,1]).map(uw),b=e.textureProperties?._ShadeTexture,x=b==null?void 0:{index:b,extensions:sw({},l)},S=e.floatProperties?._ShadeShift??0,C=e.floatProperties?._ShadeToony??.9;C=As.lerp(C,1,.5+.5*S),S=-S-(1-C);let w=e.floatProperties?._IndirectLightIntensity??.1,T=w?1-w:void 0,E=e.textureProperties?._SphereAdd,D=E==null?void 0:[1,1,1],O=E==null?void 0:{index:E},k=e.floatProperties?._RimLightingMix??0,A=e.textureProperties?._RimTexture,ee=A==null?void 0:{index:A,extensions:sw({},l)},te=(e.vectorProperties?._RimColor??[0,0,0,1]).map(uw),ne=e.floatProperties?._RimFresnelPower??1,re=e.floatProperties?._RimLift??0,ie=[`none`,`worldCoordinates`,`screenCoordinates`][e.floatProperties?._OutlineWidthMode??0],ae=e.floatProperties?._OutlineWidth??0;ae=.01*ae;let j=e.textureProperties?._OutlineWidthTexture,oe=j==null?void 0:{index:j,extensions:sw({},l)},se=(e.vectorProperties?._OutlineColor??[0,0,0]).map(uw),ce=(e.floatProperties?._OutlineColorMode??0)===1?e.floatProperties?._OutlineLightingMix??1:0,le=e.textureProperties?._UvAnimMaskTexture,ue=le==null?void 0:{index:le,extensions:sw({},l)},M=e.floatProperties?._UvAnimScrollX??0,de=e.floatProperties?._UvAnimScrollY??0;de!=null&&(de=-de);let fe=e.floatProperties?._UvAnimRotation??0,pe={specVersion:`1.0`,transparentWithZWrite:r,renderQueueOffsetNumber:i,shadeColorFactor:y,shadeMultiplyTexture:x,shadingShiftFactor:S,shadingToonyFactor:C,giEqualizationFactor:T,matcapFactor:D,matcapTexture:O,rimLightingMixFactor:k,rimMultiplyTexture:ee,parametricRimColorFactor:te,parametricRimFresnelPowerFactor:ne,parametricRimLiftFactor:re,outlineWidthMode:ie,outlineWidthFactor:ae,outlineWidthMultiplyTexture:oe,outlineColorFactor:se,outlineLightingMixFactor:ce,uvAnimationMaskTexture:ue,uvAnimationScrollXSpeedFactor:M,uvAnimationScrollYSpeedFactor:de,uvAnimationRotationSpeedFactor:fe};return cw(sw({},t),{pbrMetallicRoughness:{baseColorFactor:u,baseColorTexture:f},normalTexture:h,emissiveTexture:v,emissiveFactor:g,alphaMode:o,alphaCutoff:s,doubleSided:c,extensions:{VRMC_materials_mtoon:pe}})}_parseV0UnlitProperties(e,t){let n=e.shader===`VRM/UnlitTransparentZWrite`,r=e.shader===`VRM/UnlitTransparent`||n,i=this._v0ParseRenderQueue(e),a=e.shader===`VRM/UnlitCutout`,o=r?`BLEND`:a?`MASK`:`OPAQUE`,s=a?e.floatProperties?._Cutoff??.5:void 0,c=this._portTextureTransform(e),l=(e.vectorProperties?._Color??[1,1,1,1]).map(uw),u=e.textureProperties?._MainTex,d=u==null?void 0:{index:u,extensions:sw({},c)},f={specVersion:`1.0`,transparentWithZWrite:n,renderQueueOffsetNumber:i,shadeColorFactor:l,shadeMultiplyTexture:d};return cw(sw({},t),{pbrMetallicRoughness:{baseColorFactor:l,baseColorTexture:d},alphaMode:o,alphaCutoff:s,extensions:{VRMC_materials_mtoon:f}})}_portTextureTransform(e){let t=e.vectorProperties?._MainTex;if(t==null)return{};let n=[t?.[0]??0,t?.[1]??0],r=[t?.[2]??1,t?.[3]??1];return n[1]=1-r[1]-n[1],{KHR_texture_transform:{offset:n,scale:r}}}_v0ParseRenderQueue(e){let t=e.shader===`VRM/UnlitTransparentZWrite`,n=e.keywordMap?._ALPHABLEND_ON!=null||e.shader===`VRM/UnlitTransparent`||t,r=e.floatProperties?._ZWrite===1||t,i=0;if(n){let t=e.renderQueue;t!=null&&(i=r?this._renderQueueMapTransparentZWrite.get(t):this._renderQueueMapTransparent.get(t))}return i}_populateRenderQueueMap(e){let t=new Set,n=new Set;e.forEach(e=>{let r=e.shader===`VRM/UnlitTransparentZWrite`,i=e.keywordMap?._ALPHABLEND_ON!=null||e.shader===`VRM/UnlitTransparent`||r,a=e.floatProperties?._ZWrite===1||r;if(i){let r=e.renderQueue;r!=null&&(a?n.add(r):t.add(r))}}),t.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${t.size} render queues for Transparent materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),n.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${n.size} render queues for TransparentZWrite materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),Array.from(t).sort().forEach((e,n)=>{let r=Math.min(Math.max(n-t.size+1,-9),0);this._renderQueueMapTransparent.set(e,r)}),Array.from(n).sort().forEach((e,t)=>{let n=Math.min(Math.max(t,0),9);this._renderQueueMapTransparentZWrite.set(e,n)})}},fw=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),pw=new W,mw=class extends Ec{constructor(e){super(),this._attrPosition=new J(new Float32Array([0,0,0,0,0,0]),3),this._attrPosition.setUsage(Wo);let t=new Y;t.setAttribute(`position`,this._attrPosition);let n=new zu({color:16711935,depthTest:!1,depthWrite:!1});this._line=new qu(t,n),this.add(this._line),this.constraint=e}updateMatrixWorld(e){pw.setFromMatrixPosition(this.constraint.destination.matrixWorld),this._attrPosition.setXYZ(0,pw.x,pw.y,pw.z),this.constraint.source&&pw.setFromMatrixPosition(this.constraint.source.matrixWorld),this._attrPosition.setXYZ(1,pw.x,pw.y,pw.z),this._attrPosition.needsUpdate=!0,super.updateMatrixWorld(e)}};function hw(e,t){return t.set(e.elements[12],e.elements[13],e.elements[14])}var gw=new W,_w=new W;function vw(e,t){return e.decompose(gw,t,_w),t}function yw(e){return e.invert?e.invert():e.inverse(),e}var bw=class{constructor(e,t){this.destination=e,this.source=t,this.weight=1}},xw=new W,Sw=new W,Cw=new W,ww=new U,Tw=new U,Ew=new U,Dw=class extends bw{get aimAxis(){return this._aimAxis}set aimAxis(e){this._aimAxis=e,this._v3AimAxis.set(e===`PositiveX`?1:e===`NegativeX`?-1:0,e===`PositiveY`?1:e===`NegativeY`?-1:0,e===`PositiveZ`?1:e===`NegativeZ`?-1:0)}get dependencies(){let e=new Set([this.source]);return this.destination.parent&&e.add(this.destination.parent),e}constructor(e,t){super(e,t),this._aimAxis=`PositiveX`,this._v3AimAxis=new W(1,0,0),this._dstRestQuat=new U}setInitState(){this._dstRestQuat.copy(this.destination.quaternion)}update(){this.destination.updateWorldMatrix(!0,!1),this.source.updateWorldMatrix(!0,!1);let e=ww.identity(),t=Tw.identity();this.destination.parent&&(vw(this.destination.parent.matrixWorld,e),yw(t.copy(e)));let n=xw.copy(this._v3AimAxis).applyQuaternion(this._dstRestQuat).applyQuaternion(e),r=hw(this.source.matrixWorld,Sw).sub(hw(this.destination.matrixWorld,Cw)).normalize(),i=Ew.setFromUnitVectors(n,r).premultiply(t).multiply(e).multiply(this._dstRestQuat);this.destination.quaternion.copy(this._dstRestQuat).slerp(i,this.weight)}};function Ow(e,t){let n=[e],r=e.parent;for(;r!==null;)n.unshift(r),r=r.parent;n.forEach(e=>{t(e)})}var kw=class{constructor(){this._constraints=new Set,this._objectConstraintsMap=new Map}get constraints(){return this._constraints}addConstraint(e){this._constraints.add(e);let t=this._objectConstraintsMap.get(e.destination);t??(t=new Set,this._objectConstraintsMap.set(e.destination,t)),t.add(e)}deleteConstraint(e){this._constraints.delete(e),this._objectConstraintsMap.get(e.destination).delete(e)}setInitState(){let e=new Set,t=new Set;for(let n of this._constraints)this._processConstraint(n,e,t,e=>e.setInitState())}update(){let e=new Set,t=new Set;for(let n of this._constraints)this._processConstraint(n,e,t,e=>e.update())}_processConstraint(e,t,n,r){if(n.has(e))return;if(t.has(e))throw Error(`VRMNodeConstraintManager: Circular dependency detected while updating constraints`);t.add(e);let i=e.dependencies;for(let e of i)Ow(e,e=>{let i=this._objectConstraintsMap.get(e);if(i)for(let e of i)this._processConstraint(e,t,n,r)});r(e),n.add(e)}},Aw=new U,jw=new U,Mw=class extends bw{get dependencies(){return new Set([this.source])}constructor(e,t){super(e,t),this._dstRestQuat=new U,this._invSrcRestQuat=new U}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),yw(this._invSrcRestQuat.copy(this.source.quaternion))}update(){let e=Aw.copy(this._invSrcRestQuat).multiply(this.source.quaternion),t=jw.copy(this._dstRestQuat).multiply(e);this.destination.quaternion.copy(this._dstRestQuat).slerp(t,this.weight)}},Nw=new W,Pw=new U,Fw=new U,Iw=class extends bw{get rollAxis(){return this._rollAxis}set rollAxis(e){this._rollAxis=e,this._v3RollAxis.set(+(e===`X`),+(e===`Y`),+(e===`Z`))}get dependencies(){return new Set([this.source])}constructor(e,t){super(e,t),this._rollAxis=`X`,this._v3RollAxis=new W(1,0,0),this._dstRestQuat=new U,this._invDstRestQuat=new U,this._invSrcRestQuatMulDstRestQuat=new U}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),yw(this._invDstRestQuat.copy(this._dstRestQuat)),yw(this._invSrcRestQuatMulDstRestQuat.copy(this.source.quaternion)).multiply(this._dstRestQuat)}update(){let e=Pw.copy(this._invDstRestQuat).multiply(this.source.quaternion).multiply(this._invSrcRestQuatMulDstRestQuat),t=Nw.copy(this._v3RollAxis).applyQuaternion(e),n=Fw.setFromUnitVectors(t,this._v3RollAxis).premultiply(this._dstRestQuat).multiply(e);this.destination.quaternion.copy(this._dstRestQuat).slerp(n,this.weight)}},Lw=new Set([`1.0`,`1.0-beta`]),Rw=class e{get name(){return e.EXTENSION_NAME}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot}afterRoot(e){return fw(this,null,function*(){e.userData.vrmNodeConstraintManager=yield this._import(e)})}_import(t){return fw(this,null,function*(){let n=this.parser.json;if(n.extensionsUsed?.indexOf(e.EXTENSION_NAME)===-1)return null;let r=new kw,i=yield this.parser.getDependencies(`node`);return i.forEach((t,a)=>{let o=n.nodes[a]?.extensions?.[e.EXTENSION_NAME];if(o==null)return;let s=o.specVersion;if(!Lw.has(s)){console.warn(`VRMNodeConstraintLoaderPlugin: Unknown ${e.EXTENSION_NAME} specVersion "${s}"`);return}let c=o.constraint;if(c.roll!=null){let e=this._importRollConstraint(t,i,c.roll);r.addConstraint(e)}else if(c.aim!=null){let e=this._importAimConstraint(t,i,c.aim);r.addConstraint(e)}else if(c.rotation!=null){let e=this._importRotationConstraint(t,i,c.rotation);r.addConstraint(e)}}),t.scene.updateMatrixWorld(),r.setInitState(),r})}_importRollConstraint(e,t,n){let{source:r,rollAxis:i,weight:a}=n,o=t[r],s=new Iw(e,o);if(i!=null&&(s.rollAxis=i),a!=null&&(s.weight=a),this.helperRoot){let e=new mw(s);this.helperRoot.add(e)}return s}_importAimConstraint(e,t,n){let{source:r,aimAxis:i,weight:a}=n,o=t[r],s=new Dw(e,o);if(i!=null&&(s.aimAxis=i),a!=null&&(s.weight=a),this.helperRoot){let e=new mw(s);this.helperRoot.add(e)}return s}_importRotationConstraint(e,t,n){let{source:r,weight:i}=n,a=t[r],o=new Mw(e,a);if(i!=null&&(o.weight=i),this.helperRoot){let e=new mw(o);this.helperRoot.add(e)}return o}};Rw.EXTENSION_NAME=`VRMC_node_constraint`;var zw=Rw,Bw=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),Vw=class{},Hw=new W,Uw=new W,Ww=class extends Vw{get type(){return`capsule`}constructor(e){super(),this.offset=e?.offset??new W(0,0,0),this.tail=e?.tail??new W(0,0,0),this.radius=e?.radius??0,this.inside=e?.inside??!1}calculateCollision(e,t,n,r){Hw.setFromMatrixPosition(e),Uw.subVectors(this.tail,this.offset).applyMatrix4(e),Uw.sub(Hw);let i=Uw.lengthSq();r.copy(t).sub(Hw);let a=Uw.dot(r);a<=0||(i<=a||Uw.multiplyScalar(a/i),r.sub(Uw));let o=r.length(),s=this.inside?this.radius-n-o:o-n-this.radius;return s<0&&(r.multiplyScalar(1/o),this.inside&&r.negate()),s}},Gw=new W,Kw=new G,qw=class extends Vw{get type(){return`plane`}constructor(e){super(),this.offset=e?.offset??new W(0,0,0),this.normal=e?.normal??new W(0,0,1)}calculateCollision(e,t,n,r){r.setFromMatrixPosition(e),r.negate().add(t),Kw.getNormalMatrix(e),Gw.copy(this.normal).applyNormalMatrix(Kw).normalize();let i=r.dot(Gw)-n;return r.copy(Gw),i}},Jw=new W,Yw=class extends Vw{get type(){return`sphere`}constructor(e){super(),this.offset=e?.offset??new W(0,0,0),this.radius=e?.radius??0,this.inside=e?.inside??!1}calculateCollision(e,t,n,r){r.subVectors(t,Jw.setFromMatrixPosition(e));let i=r.length(),a=this.inside?this.radius-n-i:i-n-this.radius;return a<0&&(r.multiplyScalar(1/i),this.inside&&r.negate()),a}},Xw=new W,Zw=class extends Y{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new W,this._currentTail=new W,this._shape=e,this._attrPos=new J(new Float32Array(396),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new J(new Uint16Array(264),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1,t=this._shape.radius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0);let n=Xw.copy(this._shape.tail).divideScalar(this.worldScale);this._currentTail.distanceToSquared(n)>1e-10&&(this._currentTail.copy(n),e=!0),e&&this._buildPosition()}_buildPosition(){Xw.copy(this._currentTail).sub(this._currentOffset);let e=Xw.length()/this._currentRadius;for(let t=0;t<=16;t++){let n=t/16*Math.PI;this._attrPos.setXYZ(t,-Math.sin(n),-Math.cos(n),0),this._attrPos.setXYZ(17+t,e+Math.sin(n),Math.cos(n),0),this._attrPos.setXYZ(34+t,-Math.sin(n),0,-Math.cos(n)),this._attrPos.setXYZ(51+t,e+Math.sin(n),0,Math.cos(n))}for(let t=0;t<32;t++){let n=t/16*Math.PI;this._attrPos.setXYZ(68+t,0,Math.sin(n),Math.cos(n)),this._attrPos.setXYZ(100+t,e,Math.sin(n),Math.cos(n))}let t=Math.atan2(Xw.y,Math.sqrt(Xw.x*Xw.x+Xw.z*Xw.z)),n=-Math.atan2(Xw.z,Xw.x);this.rotateZ(t),this.rotateY(n),this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<34;e++){let t=(e+1)%34;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(68+e*2,34+e,34+t)}for(let e=0;e<32;e++){let t=(e+1)%32;this._attrIndex.setXY(136+e*2,68+e,68+t),this._attrIndex.setXY(200+e*2,100+e,100+t)}this._attrIndex.needsUpdate=!0}},Qw=class extends Y{constructor(e){super(),this.worldScale=1,this._currentOffset=new W,this._currentNormal=new W,this._shape=e,this._attrPos=new J(new Float32Array(18),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new J(new Uint16Array(10),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0),this._currentNormal.equals(this._shape.normal)||(this._currentNormal.copy(this._shape.normal),e=!0),e&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,-.5,-.5,0),this._attrPos.setXYZ(1,.5,-.5,0),this._attrPos.setXYZ(2,.5,.5,0),this._attrPos.setXYZ(3,-.5,.5,0),this._attrPos.setXYZ(4,0,0,0),this._attrPos.setXYZ(5,0,0,.25),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this.lookAt(this._currentNormal),this._attrPos.needsUpdate=!0}_buildIndex(){this._attrIndex.setXY(0,0,1),this._attrIndex.setXY(2,1,2),this._attrIndex.setXY(4,2,3),this._attrIndex.setXY(6,3,0),this._attrIndex.setXY(8,4,5),this._attrIndex.needsUpdate=!0}},$w=class extends Y{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new W,this._shape=e,this._attrPos=new J(new Float32Array(288),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new J(new Uint16Array(192),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1,t=this._shape.radius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){let t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<32;e++){let t=(e+1)%32;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(64+e*2,32+e,32+t),this._attrIndex.setXY(128+e*2,64+e,64+t)}this._attrIndex.needsUpdate=!0}},eT=new W,tT=class extends Ec{constructor(e){if(super(),this.matrixAutoUpdate=!1,this.collider=e,this.collider.shape instanceof Yw)this._geometry=new $w(this.collider.shape);else if(this.collider.shape instanceof Ww)this._geometry=new Zw(this.collider.shape);else if(this.collider.shape instanceof qw)this._geometry=new Qw(this.collider.shape);else throw Error(`VRMSpringBoneColliderHelper: Unknown collider shape type detected`);let t=new zu({color:16711935,depthTest:!1,depthWrite:!1});this._line=new Zu(this._geometry,t),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.collider.updateWorldMatrix(!0,!1),this.matrix.copy(this.collider.matrixWorld);let t=this.matrix.elements;this._geometry.worldScale=eT.set(t[0],t[1],t[2]).length(),this._geometry.update(),super.updateMatrixWorld(e)}},nT=class extends Y{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentTail=new W,this._springBone=e,this._attrPos=new J(new Float32Array(294),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new J(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1,t=this._springBone.settings.hitRadius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentTail.equals(this._springBone.initialLocalChildPosition)||(this._currentTail.copy(this._springBone.initialLocalChildPosition),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){let t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<32;e++){let t=(e+1)%32;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(64+e*2,32+e,32+t),this._attrIndex.setXY(128+e*2,64+e,64+t)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},rT=new W,iT=class extends Ec{constructor(e){super(),this.matrixAutoUpdate=!1,this.springBone=e,this._geometry=new nT(this.springBone);let t=new zu({color:16776960,depthTest:!1,depthWrite:!1});this._line=new Zu(this._geometry,t),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.springBone.bone.updateWorldMatrix(!0,!1),this.matrix.copy(this.springBone.bone.matrixWorld);let t=this.matrix.elements;this._geometry.worldScale=rT.set(t[0],t[1],t[2]).length(),this._geometry.update(),super.updateMatrixWorld(e)}},aT=class extends Tc{constructor(e){super(),this.colliderMatrix=new K,this.shape=e}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),oT(this.colliderMatrix,this.matrixWorld,this.shape.offset)}};function oT(e,t,n){let r=t.elements;e.copy(t),n&&(e.elements[12]=r[0]*n.x+r[4]*n.y+r[8]*n.z+r[12],e.elements[13]=r[1]*n.x+r[5]*n.y+r[9]*n.z+r[13],e.elements[14]=r[2]*n.x+r[6]*n.y+r[10]*n.z+r[14])}var sT=new K;function cT(e){return e.invert?e.invert():e.getInverse(sT.copy(e)),e}var lT=class{constructor(e){this._inverseCache=new K,this._shouldUpdateInverse=!0,this.matrix=e;let 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&&=(cT(this._inverseCache.copy(this.matrix)),!1),this._inverseCache}revert(){this.matrix.elements=this._originalElements}},uT=new K,dT=new W,fT=new W,pT=new W,mT=new W,hT=new K,gT=class{constructor(e,t,n={},r=[]){this._currentTail=new W,this._prevTail=new W,this._boneAxis=new W,this._worldSpaceBoneLength=0,this._center=null,this._initialLocalMatrix=new K,this._initialLocalRotation=new U,this._initialLocalChildPosition=new W,this.bone=e,this.bone.matrixAutoUpdate=!1,this.child=t,this.settings={hitRadius:n.hitRadius??0,stiffness:n.stiffness??1,gravityPower:n.gravityPower??0,gravityDir:n.gravityDir?.clone()??new W(0,-1,0),dragForce:n.dragForce??.4},this.colliderGroups=r}get dependencies(){let e=new Set,t=this.bone.parent;t&&e.add(t);for(let t=0;t<this.colliderGroups.length;t++)for(let n=0;n<this.colliderGroups[t].colliders.length;n++)e.add(this.colliderGroups[t].colliders[n]);return e}get center(){return this._center}set center(e){this._center?.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 lT(this._center.matrixWorld)))}get initialLocalChildPosition(){return this._initialLocalChildPosition}get _parentMatrixWorld(){return this.bone.parent?this.bone.parent.matrixWorld:uT}setInitState(){this._initialLocalMatrix.copy(this.bone.matrix),this._initialLocalRotation.copy(this.bone.quaternion),this.child?this._initialLocalChildPosition.copy(this.child.position):this._initialLocalChildPosition.copy(this.bone.position).normalize().multiplyScalar(.07);let e=this._getMatrixWorldToCenter();this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(e),this._prevTail.copy(this._currentTail),this._boneAxis.copy(this._initialLocalChildPosition).normalize()}reset(){this.bone.quaternion.copy(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix);let e=this._getMatrixWorldToCenter();this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(e),this._prevTail.copy(this._currentTail)}update(e){if(e<=0)return;this._calcWorldSpaceBoneLength();let t=fT.copy(this._boneAxis).transformDirection(this._initialLocalMatrix).transformDirection(this._parentMatrixWorld);mT.copy(this._currentTail).add(dT.subVectors(this._currentTail,this._prevTail).multiplyScalar(1-this.settings.dragForce)).applyMatrix4(this._getMatrixCenterToWorld()).addScaledVector(t,this.settings.stiffness*e).addScaledVector(this.settings.gravityDir,this.settings.gravityPower*e),pT.setFromMatrixPosition(this.bone.matrixWorld),mT.sub(pT).normalize().multiplyScalar(this._worldSpaceBoneLength).add(pT),this._collision(mT),this._prevTail.copy(this._currentTail),this._currentTail.copy(mT).applyMatrix4(this._getMatrixWorldToCenter());let n=hT.multiplyMatrices(this._parentMatrixWorld,this._initialLocalMatrix).invert();this.bone.quaternion.setFromUnitVectors(this._boneAxis,dT.copy(mT).applyMatrix4(n).normalize()).premultiply(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix)}_collision(e){for(let t=0;t<this.colliderGroups.length;t++)for(let n=0;n<this.colliderGroups[t].colliders.length;n++){let r=this.colliderGroups[t].colliders[n],i=r.shape.calculateCollision(r.colliderMatrix,e,this.settings.hitRadius,dT);if(i<0){e.addScaledVector(dT,-i),e.sub(pT);let t=e.length();e.multiplyScalar(this._worldSpaceBoneLength/t).add(pT)}}}_calcWorldSpaceBoneLength(){dT.setFromMatrixPosition(this.bone.matrixWorld),this.child?fT.setFromMatrixPosition(this.child.matrixWorld):(fT.copy(this._initialLocalChildPosition),fT.applyMatrix4(this.bone.matrixWorld)),this._worldSpaceBoneLength=dT.sub(fT).length()}_getMatrixCenterToWorld(){return this._center?this._center.matrixWorld:uT}_getMatrixWorldToCenter(){return this._center?this._center.userData.inverseCacheProxy.inverse:uT}};function _T(e,t){let n=[],r=e;for(;r!==null;)n.unshift(r),r=r.parent;n.forEach(e=>{t(e)})}function vT(e,t){e.children.forEach(e=>{t(e)||vT(e,t)})}function yT(e){let t=new Map;for(let n of e){let r=n;do{let n=(t.get(r)??0)+1;if(n===e.size)return r;t.set(r,n),r=r.parent}while(r!==null)}return null}var bT=class{constructor(){this._joints=new Set,this._sortedJoints=[],this._hasWarnedCircularDependency=!1,this._ancestors=[],this._objectSpringBonesMap=new Map,this._isSortedJointsDirty=!1,this._relevantChildrenUpdated=this._relevantChildrenUpdated.bind(this)}get joints(){return this._joints}get springBones(){return console.warn(`VRMSpringBoneManager: springBones is deprecated. use joints instead.`),this._joints}get colliderGroups(){let e=new Set;return this._joints.forEach(t=>{t.colliderGroups.forEach(t=>{e.add(t)})}),Array.from(e)}get colliders(){let e=new Set;return this.colliderGroups.forEach(t=>{t.colliders.forEach(t=>{e.add(t)})}),Array.from(e)}addJoint(e){this._joints.add(e);let t=this._objectSpringBonesMap.get(e.bone);t??(t=new Set,this._objectSpringBonesMap.set(e.bone,t)),t.add(e),this._isSortedJointsDirty=!0}addSpringBone(e){console.warn(`VRMSpringBoneManager: addSpringBone() is deprecated. use addJoint() instead.`),this.addJoint(e)}deleteJoint(e){this._joints.delete(e),this._objectSpringBonesMap.get(e.bone).delete(e),this._isSortedJointsDirty=!0}deleteSpringBone(e){console.warn(`VRMSpringBoneManager: deleteSpringBone() is deprecated. use deleteJoint() instead.`),this.deleteJoint(e)}setInitState(){this._sortJoints();for(let e=0;e<this._sortedJoints.length;e++){let t=this._sortedJoints[e];t.bone.updateMatrix(),t.bone.updateWorldMatrix(!1,!1),t.setInitState()}}reset(){this._sortJoints();for(let e=0;e<this._sortedJoints.length;e++){let t=this._sortedJoints[e];t.bone.updateMatrix(),t.bone.updateWorldMatrix(!1,!1),t.reset()}}update(e){this._sortJoints();for(let e=0;e<this._ancestors.length;e++)this._ancestors[e].updateWorldMatrix(e===0,!1);for(let t=0;t<this._sortedJoints.length;t++){let n=this._sortedJoints[t];n.bone.updateMatrix(),n.bone.updateWorldMatrix(!1,!1),n.update(e),vT(n.bone,this._relevantChildrenUpdated)}}_sortJoints(){if(!this._isSortedJointsDirty)return;let e=[],t=new Set,n=new Set,r=new Set;for(let i of this._joints)this._insertJointSort(i,t,n,e,r);this._sortedJoints=e;let i=yT(r);this._ancestors=[],i&&(this._ancestors.push(i),vT(i,e=>(this._objectSpringBonesMap.get(e)?.size??0)>0?!0:(this._ancestors.push(e),!1))),this._isSortedJointsDirty=!1}_insertJointSort(e,t,n,r,i){if(n.has(e))return;if(t.has(e)){this._hasWarnedCircularDependency||=(console.warn(`VRMSpringBoneManager: Circular dependency detected`),!0);return}t.add(e);let a=e.dependencies;for(let e of a){let a=!1,o=null;_T(e,e=>{let s=this._objectSpringBonesMap.get(e);if(s)for(let e of s)a=!0,this._insertJointSort(e,t,n,r,i);else a||(o=e)}),o&&i.add(o)}r.push(e),n.add(e)}_relevantChildrenUpdated(e){return(this._objectSpringBonesMap.get(e)?.size??0)>0?!0:(e.updateWorldMatrix(!1,!1),!1)}},xT=`VRMC_springBone_extended_collider`,ST=new Set([`1.0`,`1.0-beta`]),CT=new Set([`1.0`]),wT=class e{get name(){return e.EXTENSION_NAME}constructor(e,t){this.parser=e,this.jointHelperRoot=t?.jointHelperRoot,this.colliderHelperRoot=t?.colliderHelperRoot,this.useExtendedColliders=t?.useExtendedColliders??!0}afterRoot(e){return Bw(this,null,function*(){e.userData.vrmSpringBoneManager=yield this._import(e)})}_import(e){return Bw(this,null,function*(){return(yield this._v1Import(e))??(yield this._v0Import(e))??null})}_v1Import(t){return Bw(this,null,function*(){var n;let r=t.parser.json;if(r.extensionsUsed?.indexOf(e.EXTENSION_NAME)===-1)return null;let i=new bT,a=yield t.parser.getDependencies(`node`),o=r.extensions?.[e.EXTENSION_NAME];if(!o)return null;let s=o.specVersion;if(!ST.has(s))return console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${e.EXTENSION_NAME} specVersion "${s}"`),null;let c=o.colliders?.map((t,n)=>{let r=a[t.node];if(r==null)return console.warn(`VRMSpringBoneLoaderPlugin: The collider #${n} attempted to reference a node #${t.node} but not found. Skipping the collider`),null;let i=t.shape,o=t.extensions?.[xT];if(this.useExtendedColliders&&o!=null){let t=o.specVersion;if(!CT.has(t))console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${xT} specVersion "${t}". Fallbacking to the ${e.EXTENSION_NAME} definition`);else{let e=o.shape;if(e.sphere)return this._importSphereCollider(r,{offset:new W().fromArray(e.sphere.offset??[0,0,0]),radius:e.sphere.radius??0,inside:e.sphere.inside??!1});if(e.capsule)return this._importCapsuleCollider(r,{offset:new W().fromArray(e.capsule.offset??[0,0,0]),radius:e.capsule.radius??0,tail:new W().fromArray(e.capsule.tail??[0,0,0]),inside:e.capsule.inside??!1});if(e.plane)return this._importPlaneCollider(r,{offset:new W().fromArray(e.plane.offset??[0,0,0]),normal:new W().fromArray(e.plane.normal??[0,0,1])})}}if(i.sphere)return this._importSphereCollider(r,{offset:new W().fromArray(i.sphere.offset??[0,0,0]),radius:i.sphere.radius??0,inside:!1});if(i.capsule)return this._importCapsuleCollider(r,{offset:new W().fromArray(i.capsule.offset??[0,0,0]),radius:i.capsule.radius??0,tail:new W().fromArray(i.capsule.tail??[0,0,0]),inside:!1});console.warn(`VRMSpringBoneLoaderPlugin: The collider #${n} has no valid shape. Skipping the collider`)}),l=o.colliderGroups?.map((e,t)=>({colliders:(e.colliders??[]).map(e=>c?.[e]??(console.warn(`VRMSpringBoneLoaderPlugin: The collider group #${t} attempted to reference a collider #${e} but not found. Skipping the collider`),null)).filter(e=>e!=null),name:e.name}));return(n=o.springs)==null||n.forEach((e,t)=>{let n=e.joints,r=e.colliderGroups?.map(e=>l?.[e]??(console.warn(`VRMSpringBoneLoaderPlugin: The spring #${t} attempted to reference a collider group #${e} but not found. Skipping the collider group`),null)).filter(e=>e!=null),o=e.center==null?void 0:a[e.center],s;n.forEach(e=>{if(s){let t=a[s.node],n=a[e.node],c={hitRadius:s.hitRadius,dragForce:s.dragForce,gravityPower:s.gravityPower,stiffness:s.stiffness,gravityDir:s.gravityDir==null?void 0:new W().fromArray(s.gravityDir)},l=this._importJoint(t,n,c,r);o&&(l.center=o),i.addJoint(l)}s=e})}),i.setInitState(),i})}_v0Import(e){return Bw(this,null,function*(){let t=e.parser.json;if(t.extensionsUsed?.indexOf(`VRM`)===-1)return null;let n=t.extensions?.VRM?.secondaryAnimation;if(!n)return null;let r=n?.boneGroups;if(!r)return null;let i=new bT,a=yield e.parser.getDependencies(`node`),o=n.colliderGroups?.map((e,t)=>{let n=a[e.node];return n==null?(console.warn(`VRMSpringBoneLoaderPlugin: The collider group #${t} attempted to reference a node #${e.node} but not found. Skipping the collider group`),null):{colliders:(e.colliders??[]).map((e,t)=>{let r=new W(0,0,0);return e.offset&&r.set(e.offset.x??0,e.offset.y??0,e.offset.z?-e.offset.z:0),this._importSphereCollider(n,{offset:r,radius:e.radius??0,inside:!1})})}});return r?.forEach((e,t)=>{let n=e.bones;n&&n.forEach(n=>{let r=a[n];if(r==null){console.warn(`VRMSpringBoneLoaderPlugin: The spring bone group #${t} attempted to reference a node #${n} but not found. Skipping the node`);return}let s=new W;e.gravityDir?s.set(e.gravityDir.x??0,e.gravityDir.y??0,e.gravityDir.z??0):s.set(0,-1,0);let c=e.center==null?void 0:a[e.center],l={hitRadius:e.hitRadius,dragForce:e.dragForce,gravityPower:e.gravityPower,stiffness:e.stiffiness,gravityDir:s},u=e.colliderGroups?.map(e=>o?.[e]??(console.warn(`VRMSpringBoneLoaderPlugin: The spring #${t} attempted to reference a collider group #${e} but not found. Skipping the collider group`),null)).filter(e=>e!=null);r.traverse(e=>{let t=e.children[0]??null,n=this._importJoint(e,t,l,u);c&&(n.center=c),i.addJoint(n)})})}),e.scene.updateMatrixWorld(),i.setInitState(),i})}_importJoint(e,t,n,r){let i=new gT(e,t,n,r);if(this.jointHelperRoot){let e=new iT(i);this.jointHelperRoot.add(e),e.renderOrder=this.jointHelperRoot.renderOrder}return i}_importSphereCollider(e,t){let n=new aT(new Yw(t));if(e.add(n),this.colliderHelperRoot){let e=new tT(n);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return n}_importCapsuleCollider(e,t){let n=new aT(new Ww(t));if(e.add(n),this.colliderHelperRoot){let e=new tT(n);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return n}_importPlaneCollider(e,t){let n=new aT(new qw(t));if(e.add(n),this.colliderHelperRoot){let e=new tT(n);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return n}};wT.EXTENSION_NAME=`VRMC_springBone`;var TT=wT,ET=class{get name(){return`VRMLoaderPlugin`}constructor(e,t){this.parser=e;let n=t?.helperRoot,r=t?.autoUpdateHumanBones;this.expressionPlugin=t?.expressionPlugin??new SS(e),this.firstPersonPlugin=t?.firstPersonPlugin??new ES(e),this.humanoidPlugin=t?.humanoidPlugin??new GS(e,{helperRoot:n,autoUpdateHumanBones:r}),this.lookAtPlugin=t?.lookAtPlugin??new DC(e,{helperRoot:n}),this.metaPlugin=t?.metaPlugin??new AC(e),this.mtoonMaterialPlugin=t?.mtoonMaterialPlugin??new XC(e),this.materialsHDREmissiveMultiplierPlugin=t?.materialsHDREmissiveMultiplierPlugin??new $C(e),this.materialsV0CompatPlugin=t?.materialsV0CompatPlugin??new dw(e),this.springBonePlugin=t?.springBonePlugin??new TT(e,{colliderHelperRoot:n,jointHelperRoot:n}),this.nodeConstraintPlugin=t?.nodeConstraintPlugin??new zw(e,{helperRoot:n})}beforeRoot(){return nS(this,null,function*(){yield this.materialsV0CompatPlugin.beforeRoot(),yield this.mtoonMaterialPlugin.beforeRoot()})}loadMesh(e){return nS(this,null,function*(){return yield this.mtoonMaterialPlugin.loadMesh(e)})}getMaterialType(e){return this.mtoonMaterialPlugin.getMaterialType(e)??null}extendMaterialParams(e,t){return nS(this,null,function*(){yield this.materialsHDREmissiveMultiplierPlugin.extendMaterialParams(e,t),yield this.mtoonMaterialPlugin.extendMaterialParams(e,t)})}afterRoot(e){return nS(this,null,function*(){yield this.metaPlugin.afterRoot(e),yield this.humanoidPlugin.afterRoot(e),yield this.expressionPlugin.afterRoot(e),yield this.lookAtPlugin.afterRoot(e),yield this.firstPersonPlugin.afterRoot(e),yield this.springBonePlugin.afterRoot(e),yield this.nodeConstraintPlugin.afterRoot(e),yield this.mtoonMaterialPlugin.afterRoot(e);let t=e.userData.vrmMeta,n=e.userData.vrmHumanoid;if(t&&n){let r=new MC({scene:e.scene,expressionManager:e.userData.vrmExpressionManager,firstPerson:e.userData.vrmFirstPerson,humanoid:n,lookAt:e.userData.vrmLookAt,meta:t,materials:e.userData.vrmMToonMaterials,springBoneManager:e.userData.vrmSpringBoneManager,nodeConstraintManager:e.userData.vrmNodeConstraintManager});e.userData.vrm=r}})}};function DT(e){let t=new Set;return e.traverse(e=>{if(!e.isMesh)return;let n=e;t.add(n)}),t}function OT(e,t,n){if(t.size===1){let n=t.values().next().value;if(n.weight===1)return e[n.index]}let r=new Float32Array(e[0].count*3),i=0;if(n)i=1;else for(let e of t)i+=e.weight;for(let n of t){let t=e[n.index],a=n.weight/i;for(let e=0;e<t.count;e++)r[e*3+0]+=t.getX(e)*a,r[e*3+1]+=t.getY(e)*a,r[e*3+2]+=t.getZ(e)*a}return new J(r,3)}function kT(e){let t=DT(e.scene),n=new Map,r=e.expressionManager?.expressionMap;if(r!=null)for(let[e,t]of Object.entries(r)){let r=new Set;for(let i of t.binds)if(i instanceof gS){if(i.weight!==0)for(let t of i.primitives){let r=n.get(t);r??(r=new Map,n.set(t,r));let a=r.get(e);a??(a=new Set,r.set(e,a)),a.add(i)}r.add(i)}for(let e of r)t.deleteBind(e)}for(let e of t){let t=n.get(e);if(t==null)continue;let i=e.geometry.morphAttributes;e.geometry.morphAttributes={};let a=e.geometry.clone();e.geometry=a;let o=a.morphTargetsRelative,s=i.position!=null,c=i.normal!=null,l={},u={},d=[];if(s||c){s&&(l.position=[]),c&&(l.normal=[]);let n=0;for(let[a,f]of t)s&&(l.position[n]=OT(i.position,f,o)),c&&(l.normal[n]=OT(i.normal,f,o)),r?.[a].addBind(new gS({index:n,weight:1,primitives:[e]})),u[a]=n,d.push(0),n++}a.morphAttributes=l,e.morphTargetDictionary=u,e.morphTargetInfluences=d}}function AT(e,t,n){if(e.getComponent)return e.getComponent(t,n);{let r=e.array[t*e.itemSize+n];return e.normalized&&(r=As.denormalize(r,e.array)),r}}function jT(e,t,n,r){e.setComponent?e.setComponent(t,n,r):(e.normalized&&(r=As.normalize(r,e.array)),e.array[t*e.itemSize+n]=r)}function MT(e){let t=NT(e),n=new Set;for(let e of t)n.has(e.geometry)&&(e.geometry=BT(e.geometry)),n.add(e.geometry);let r=new Map;for(let e of n){let t=e.getAttribute(`skinIndex`),n=r.get(t)??new Map;r.set(t,n);let i=e.getAttribute(`skinWeight`),a=PT(t,i);n.set(i,a)}let i=new Map;for(let e of t){let t=FT(e,r);i.set(e,t)}let a=[];for(let[e,t]of i){let n=!1;for(let r of a)if(IT(t,r.boneInverseMap)){n=!0,r.meshes.add(e);for(let[e,n]of t)r.boneInverseMap.set(e,n);break}n||a.push({boneInverseMap:t,meshes:new Set([e])})}let o=new Map,s=new zT,c=new zT,l=new zT;for(let e of a){let{boneInverseMap:t,meshes:n}=e,r=Array.from(t.keys()),i=new xu(r,Array.from(t.values())),a=c.getOrCreate(i);for(let e of n){let t=e.geometry.getAttribute(`skinIndex`),n=s.getOrCreate(t),i=e.skeleton.bones,c=`${n};${a};${i.map(e=>l.getOrCreate(e)).join(`,`)}`,u=o.get(c);u??(u=t.clone(),LT(u,i,r),o.set(c,u)),e.geometry.setAttribute(`skinIndex`,u)}for(let e of n)e.bind(i,new K)}}function NT(e){let t=new Set;return e.traverse(e=>{if(!e.isSkinnedMesh)return;let n=e;t.add(n)}),t}function PT(e,t){let n=new Set;for(let r=0;r<e.count;r++)for(let i=0;i<e.itemSize;i++){let a=AT(e,r,i);AT(t,r,i)!==0&&n.add(a)}return n}function FT(e,t){let n=new Map,r=e.skeleton,i=e.geometry,a=i.getAttribute(`skinIndex`),o=i.getAttribute(`skinWeight`),s=t.get(a)?.get(o);if(!s)throw Error(`Unreachable. attributeUsedIndexSetMap does not know the skin index attribute or the skin weight attribute.`);for(let e of s)n.set(r.bones[e],r.boneInverses[e]);return n}function IT(e,t){for(let[n,r]of e.entries()){let e=t.get(n);if(e!=null&&!RT(r,e))return!1}return!0}function LT(e,t,n){let r=new Map;for(let e of t)r.set(e,r.size);let i=new Map;for(let[e,t]of n.entries()){let n=r.get(t);i.set(n,e)}for(let t=0;t<e.count;t++)for(let n=0;n<e.itemSize;n++){let r=AT(e,t,n),a=i.get(r);jT(e,t,n,a)}e.needsUpdate=!0}function RT(e,t,n){if(n||=1e-4,e.elements.length!=t.elements.length)return!1;for(let r=0,i=e.elements.length;r<i;r++)if(Math.abs(e.elements[r]-t.elements[r])>n)return!1;return!0}var zT=class{constructor(){this._objectIndexMap=new Map,this._index=0}get(e){return this._objectIndexMap.get(e)}getOrCreate(e){let t=this._objectIndexMap.get(e);return t??(t=this._index,this._objectIndexMap.set(e,t),this._index++),t}};function BT(e){let t=new Y;t.name=e.name,t.setIndex(e.index);for(let[n,r]of Object.entries(e.attributes))t.setAttribute(n,r);for(let[n,r]of Object.entries(e.morphAttributes)){let e=n;t.morphAttributes[e]=r.concat()}t.morphTargetsRelative=e.morphTargetsRelative,t.groups=[];for(let n of e.groups)t.addGroup(n.start,n.count,n.materialIndex);return t.boundingSphere=e.boundingSphere?.clone()??null,t.boundingBox=e.boundingBox?.clone()??null,t.drawRange.start=e.drawRange.start,t.drawRange.count=e.drawRange.count,t.userData=e.userData,t}function VT(e){if(Object.values(e).forEach(e=>{e?.isTexture&&e.dispose()}),e.isShaderMaterial){let t=e.uniforms;t&&Object.values(t).forEach(e=>{let t=e.value;t?.isTexture&&t.dispose()})}e.dispose()}function HT(e){let t=e.geometry;t&&t.dispose();let n=e.skeleton;n&&n.dispose();let r=e.material;r&&(Array.isArray(r)?r.forEach(e=>VT(e)):r&&VT(r))}function UT(e){e.traverse(HT)}function WT(e,t){console.warn(`VRMUtils.removeUnnecessaryJoints: removeUnnecessaryJoints is deprecated. Use combineSkeletons instead. combineSkeletons contributes more to the performance improvement. This function will be removed in the next major version.`);let n=t?.experimentalSameBoneCounts??!1,r=[];e.traverse(e=>{e.type===`SkinnedMesh`&&r.push(e)});let i=new Map,a=0;for(let e of r){let t=e.geometry.getAttribute(`skinIndex`);if(i.has(t))continue;let n=new Map,r=new Map;for(let e=0;e<t.count;e++)for(let i=0;i<t.itemSize;i++){let a=AT(t,e,i),o=n.get(a);o??(o=n.size,n.set(a,o),r.set(o,a)),jT(t,e,i,o)}t.needsUpdate=!0,i.set(t,r),a=Math.max(a,n.size)}for(let e of r){let t=e.geometry.getAttribute(`skinIndex`),r=i.get(t),o=[],s=[],c=n?a:r.size;for(let t=0;t<c;t++){let n=r.get(t)??0;o.push(e.skeleton.bones[n]),s.push(e.skeleton.boneInverses[n])}let l=new xu(o,s);e.bind(l,new K)}}function GT(e,t){let n=e.position.count,r=Array(n),i=0,a=t.array;for(let e=0;e<a.length;e++){let t=a[e];r[t]||(r[t]=!0,i++)}return{isVertexUsed:r,vertexCount:n,verticesUsed:i}}function KT(e){let t=[],n=[],r=0;for(let i=0;i<e.length;i++)if(e[i]){let e=r++;t[i]=e,n[e]=i}return{originalIndexNewIndexMap:t,newIndexOriginalIndexMap:n}}function qT(e,t){t.name=e.name,t.morphTargetsRelative=e.morphTargetsRelative,e.groups.forEach(e=>{t.addGroup(e.start,e.count,e.materialIndex)}),t.boundingBox=e.boundingBox?.clone()??null,t.boundingSphere=e.boundingSphere?.clone()??null,t.setDrawRange(e.drawRange.start,e.drawRange.count),t.userData=e.userData}function JT(e,t,n){let r=t.array,i=new r.constructor(r.length);for(let e=0;e<r.length;e++)i[e]=n[r[e]];e.setIndex(new J(i,t.itemSize,t.normalized))}function YT(e,t,n){let r=e.constructor,i=new r(t.length*n),a=!0;for(let r=0;r<t.length;r++){let o=t[r]*n,s=r*n;for(let t=0;t<n;t++){let n=e[o+t];i[s+t]=n,a&&=n===0}}return[i,a]}function XT(e){let t=new Map,n=[];for(let[r,i]of Object.entries(e))if(i.isInterleavedBufferAttribute){let e=i,n=e.data,a=t.get(n)??[];t.set(n,a),a.push([r,e])}else{let e=i;n.push([r,e])}return[t,n]}function ZT(e,t,n){let[r,i]=XT(t);for(let[t,i]of r){let r=t.array,{stride:a}=t,[o,s]=YT(r,n,a),c=new Nl(o,a);c.setUsage(t.usage);for(let[t,n]of i){let{itemSize:r,offset:i,normalized:a}=n,o=new Fl(c,r,i,a);e.setAttribute(t,o)}}for(let[t,r]of i){let i=r.array,{itemSize:a,normalized:o}=r,[s,c]=YT(i,n,a);e.setAttribute(t,new J(s,a,o))}}function QT(e){let t=new Map,n=[];for(let[r,i]of Object.entries(e)){let e=r;for(let r=0;r<i.length;r++){let a=i[r];if(a.isInterleavedBufferAttribute){let n=a,i=n.data,o=t.get(i)??[];t.set(i,o),o.push([e,r,n])}else{let t=a;n.push([e,r,t])}}}return[t,n]}function $T(e,t,n){let r=!0,[i,a]=QT(t),o={};for(let[e,t]of i){let i=e.array,{stride:a}=e,[s,c]=YT(i,n,a);r&&=c;let l=new Nl(s,a);l.setUsage(e.usage);for(let[e,n,r]of t){let{itemSize:t,offset:i,normalized:a}=r,s=new Fl(l,t,i,a);o[e]??(o[e]=[]),o[e][n]=s}}for(let[e,t,i]of a){let a=i,s=a.array,{itemSize:c,normalized:l}=a,[u,d]=YT(s,n,c);r&&=d,o[e]??(o[e]=[]),o[e][t]=new J(u,c,l)}e.morphAttributes=r?{}:o}function eE(e){let t=new Map;e.traverse(e=>{if(!e.isMesh)return;let n=e,r=n.geometry,i=r.index;if(i==null)return;let a=t.get(r);if(a!=null){n.geometry=a;return}let{isVertexUsed:o,vertexCount:s,verticesUsed:c}=GT(r.attributes,i);if(c===s)return;let{originalIndexNewIndexMap:l,newIndexOriginalIndexMap:u}=KT(o),d=new Y;qT(r,d),t.set(r,d),JT(d,i,l),ZT(d,r.attributes,u),$T(d,r.morphAttributes,u),n.geometry=d}),Array.from(t.keys()).forEach(e=>{e.dispose()})}function tE(e){e.meta?.metaVersion===`0`&&(e.scene.rotation.y=Math.PI)}var nE=class{constructor(){}};nE.combineMorphs=kT,nE.combineSkeletons=MT,nE.deepDispose=UT,nE.removeUnnecessaryJoints=WT,nE.removeUnnecessaryVertices=eE,nE.rotateVRM0=tE;function rE(e,t){if(t===0)return console.warn(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.`),e;if(t===2||t===1){let n=e.getIndex();if(n===null){let t=[],r=e.getAttribute(`position`);if(r!==void 0){for(let e=0;e<r.count;e++)t.push(e);e.setIndex(t),n=e.getIndex()}else return console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.`),e}let r=n.count-2,i=[];if(t===2)for(let e=1;e<=r;e++)i.push(n.getX(0)),i.push(n.getX(e)),i.push(n.getX(e+1));else for(let e=0;e<r;e++)e%2==0?(i.push(n.getX(e)),i.push(n.getX(e+1)),i.push(n.getX(e+2))):(i.push(n.getX(e+2)),i.push(n.getX(e+1)),i.push(n.getX(e)));i.length/3!==r&&console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.`);let a=e.clone();return a.setIndex(i),a.clearGroups(),a}else return console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:`,t),e}function iE(e){let t=new Map,n=new Map,r=e.clone();return aE(e,r,function(e,r){t.set(r,e),n.set(e,r)}),r.traverse(function(e){if(!e.isSkinnedMesh)return;let r=e,i=t.get(e),a=i.skeleton.bones;r.skeleton=i.skeleton.clone(),r.bindMatrix.copy(i.bindMatrix),r.skeleton.bones=a.map(function(e){return n.get(e)}),r.bind(r.skeleton,r.bindMatrix)}),r}function aE(e,t,n){n(e,t);for(let r=0;r<e.children.length;r++)aE(e.children[r],t.children[r],n)}var oE=class extends nf{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(e){return new pE(e)}),this.register(function(e){return new mE(e)}),this.register(function(e){return new CE(e)}),this.register(function(e){return new wE(e)}),this.register(function(e){return new TE(e)}),this.register(function(e){return new gE(e)}),this.register(function(e){return new _E(e)}),this.register(function(e){return new vE(e)}),this.register(function(e){return new yE(e)}),this.register(function(e){return new fE(e)}),this.register(function(e){return new bE(e)}),this.register(function(e){return new hE(e)}),this.register(function(e){return new SE(e)}),this.register(function(e){return new xE(e)}),this.register(function(e){return new uE(e)}),this.register(function(e){return new EE(e,lE.EXT_MESHOPT_COMPRESSION)}),this.register(function(e){return new EE(e,lE.KHR_MESHOPT_COMPRESSION)}),this.register(function(e){return new DE(e)})}load(e,t,n,r){let i=this,a;if(this.resourcePath!==``)a=this.resourcePath;else if(this.path!==``){let t=Mf.extractUrlBase(e);a=Mf.resolveURL(t,this.path)}else a=Mf.extractUrlBase(e);this.manager.itemStart(e);let o=function(t){r?r(t):console.error(t),i.manager.itemError(e),i.manager.itemEnd(e)},s=new of(this.manager);s.setPath(this.path),s.setResponseType(`arraybuffer`),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(n){try{i.parse(n,a,function(n){t(n),i.manager.itemEnd(e)},o)}catch(e){o(e)}},n,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,r){let i,a={},o={},s=new TextDecoder;if(typeof e==`string`)i=JSON.parse(e);else if(e instanceof ArrayBuffer)if(s.decode(new Uint8Array(e,0,4))===OE){try{a[lE.KHR_BINARY_GLTF]=new jE(e)}catch(e){r&&r(e);return}i=JSON.parse(a[lE.KHR_BINARY_GLTF].content)}else i=JSON.parse(s.decode(e));else i=e;if(i.asset===void 0||i.asset.version[0]<2){r&&r(Error(`THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.`));return}let c=new rD(i,{path:t||this.resourcePath||``,crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let e=0;e<this.pluginCallbacks.length;e++){let t=this.pluginCallbacks[e](c);t.name||console.error(`THREE.GLTFLoader: Invalid plugin found: missing name`),o[t.name]=t,a[t.name]=!0}if(i.extensionsUsed)for(let e=0;e<i.extensionsUsed.length;++e){let t=i.extensionsUsed[e],n=i.extensionsRequired||[];switch(t){case lE.KHR_MATERIALS_UNLIT:a[t]=new dE;break;case lE.KHR_DRACO_MESH_COMPRESSION:a[t]=new ME(i,this.dracoLoader);break;case lE.KHR_TEXTURE_TRANSFORM:a[t]=new NE;break;case lE.KHR_MESH_QUANTIZATION:a[t]=new PE;break;default:n.indexOf(t)>=0&&o[t]===void 0&&console.warn(`THREE.GLTFLoader: Unknown extension "`+t+`".`)}}c.setExtensions(a),c.setPlugins(o),c.parse(n,r)}parseAsync(e,t){let n=this;return new Promise(function(r,i){n.parse(e,t,r,i)})}};function sE(){let e={};return{get:function(t){return e[t]},add:function(t,n){e[t]=n},remove:function(t){delete e[t]},removeAll:function(){e={}}}}function cE(e,t,n){let r=e.json.materials[t];return r.extensions&&r.extensions[n]?r.extensions[n]:null}var lE={KHR_BINARY_GLTF:`KHR_binary_glTF`,KHR_DRACO_MESH_COMPRESSION:`KHR_draco_mesh_compression`,KHR_LIGHTS_PUNCTUAL:`KHR_lights_punctual`,KHR_MATERIALS_CLEARCOAT:`KHR_materials_clearcoat`,KHR_MATERIALS_DISPERSION:`KHR_materials_dispersion`,KHR_MATERIALS_IOR:`KHR_materials_ior`,KHR_MATERIALS_SHEEN:`KHR_materials_sheen`,KHR_MATERIALS_SPECULAR:`KHR_materials_specular`,KHR_MATERIALS_TRANSMISSION:`KHR_materials_transmission`,KHR_MATERIALS_IRIDESCENCE:`KHR_materials_iridescence`,KHR_MATERIALS_ANISOTROPY:`KHR_materials_anisotropy`,KHR_MATERIALS_UNLIT:`KHR_materials_unlit`,KHR_MATERIALS_VOLUME:`KHR_materials_volume`,KHR_TEXTURE_BASISU:`KHR_texture_basisu`,KHR_TEXTURE_TRANSFORM:`KHR_texture_transform`,KHR_MESH_QUANTIZATION:`KHR_mesh_quantization`,KHR_MATERIALS_EMISSIVE_STRENGTH:`KHR_materials_emissive_strength`,EXT_MATERIALS_BUMP:`EXT_materials_bump`,EXT_TEXTURE_WEBP:`EXT_texture_webp`,EXT_TEXTURE_AVIF:`EXT_texture_avif`,EXT_MESHOPT_COMPRESSION:`EXT_meshopt_compression`,KHR_MESHOPT_COMPRESSION:`KHR_meshopt_compression`,EXT_MESH_GPU_INSTANCING:`EXT_mesh_gpu_instancing`},uE=class{constructor(e){this.parser=e,this.name=lE.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,r=t.length;n<r;n++){let r=t[n];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){let t=this.parser,n=`light:`+e,r=t.cache.get(n);if(r)return r;let i=t.json,a=((i.extensions&&i.extensions[this.name]||{}).lights||[])[e],o,s=new q(16777215);a.color!==void 0&&s.setRGB(a.color[0],a.color[1],a.color[2],zo);let c=a.range===void 0?0:a.range;switch(a.type){case`directional`:o=new Af(s),o.target.position.set(0,0,-1),o.add(o.target);break;case`point`:o=new Df(s),o.distance=c;break;case`spot`:o=new Tf(s),o.distance=c,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle===void 0?0:a.spot.innerConeAngle,a.spot.outerConeAngle=a.spot.outerConeAngle===void 0?Math.PI/4:a.spot.outerConeAngle,o.angle=a.spot.outerConeAngle,o.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,o.target.position.set(0,0,-1),o.add(o.target);break;default:throw Error(`THREE.GLTFLoader: Unexpected light type: `+a.type)}return o.position.set(0,0,0),YE(o,a),a.intensity!==void 0&&(o.intensity=a.intensity),o.name=t.createUniqueName(a.name||`light_`+e),r=Promise.resolve(o),t.cache.add(n,r),r}getDependency(e,t){if(e===`light`)return this._loadLight(t)}createNodeAttachment(e){let t=this,n=this.parser,r=n.json.nodes[e],i=(r.extensions&&r.extensions[this.name]||{}).light;return i===void 0?null:this._loadLight(i).then(function(e){return n._getNodeRef(t.cache,i,e)})}},dE=class{constructor(){this.name=lE.KHR_MATERIALS_UNLIT}getMaterialType(){return Kl}extendParams(e,t,n){let r=[];e.color=new q(1,1,1),e.opacity=1;let i=t.pbrMetallicRoughness;if(i){if(Array.isArray(i.baseColorFactor)){let t=i.baseColorFactor;e.color.setRGB(t[0],t[1],t[2],zo),e.opacity=t[3]}i.baseColorTexture!==void 0&&r.push(n.assignTexture(e,`map`,i.baseColorTexture,Ro))}return Promise.all(r)}},fE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);return n===null||n.emissiveStrength!==void 0&&(t.emissiveIntensity=n.emissiveStrength),Promise.resolve()}},pE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];if(n.clearcoatFactor!==void 0&&(t.clearcoat=n.clearcoatFactor),n.clearcoatTexture!==void 0&&r.push(this.parser.assignTexture(t,`clearcoatMap`,n.clearcoatTexture)),n.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=n.clearcoatRoughnessFactor),n.clearcoatRoughnessTexture!==void 0&&r.push(this.parser.assignTexture(t,`clearcoatRoughnessMap`,n.clearcoatRoughnessTexture)),n.clearcoatNormalTexture!==void 0&&(r.push(this.parser.assignTexture(t,`clearcoatNormalMap`,n.clearcoatNormalTexture)),n.clearcoatNormalTexture.scale!==void 0)){let e=n.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new H(e,e)}return Promise.all(r)}},mE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_DISPERSION}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);return n===null||(t.dispersion=n.dispersion===void 0?0:n.dispersion),Promise.resolve()}},hE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return n.iridescenceFactor!==void 0&&(t.iridescence=n.iridescenceFactor),n.iridescenceTexture!==void 0&&r.push(this.parser.assignTexture(t,`iridescenceMap`,n.iridescenceTexture)),n.iridescenceIor!==void 0&&(t.iridescenceIOR=n.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),n.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=n.iridescenceThicknessMinimum),n.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=n.iridescenceThicknessMaximum),n.iridescenceThicknessTexture!==void 0&&r.push(this.parser.assignTexture(t,`iridescenceThicknessMap`,n.iridescenceThicknessTexture)),Promise.all(r)}},gE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_SHEEN}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];if(t.sheenColor=new q(0,0,0),t.sheenRoughness=0,t.sheen=1,n.sheenColorFactor!==void 0){let e=n.sheenColorFactor;t.sheenColor.setRGB(e[0],e[1],e[2],zo)}return n.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=n.sheenRoughnessFactor),n.sheenColorTexture!==void 0&&r.push(this.parser.assignTexture(t,`sheenColorMap`,n.sheenColorTexture,Ro)),n.sheenRoughnessTexture!==void 0&&r.push(this.parser.assignTexture(t,`sheenRoughnessMap`,n.sheenRoughnessTexture)),Promise.all(r)}},_E=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return n.transmissionFactor!==void 0&&(t.transmission=n.transmissionFactor),n.transmissionTexture!==void 0&&r.push(this.parser.assignTexture(t,`transmissionMap`,n.transmissionTexture)),Promise.all(r)}},vE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_VOLUME}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];t.thickness=n.thicknessFactor===void 0?0:n.thicknessFactor,n.thicknessTexture!==void 0&&r.push(this.parser.assignTexture(t,`thicknessMap`,n.thicknessTexture)),t.attenuationDistance=n.attenuationDistance||1/0;let i=n.attenuationColor||[1,1,1];return t.attenuationColor=new q().setRGB(i[0],i[1],i[2],zo),Promise.all(r)}},yE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_IOR}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);return n===null?Promise.resolve():(t.ior=n.ior===void 0?1.5:n.ior,t.ior===0&&(t.ior=1e3),Promise.resolve())}},bE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_SPECULAR}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];t.specularIntensity=n.specularFactor===void 0?1:n.specularFactor,n.specularTexture!==void 0&&r.push(this.parser.assignTexture(t,`specularIntensityMap`,n.specularTexture));let i=n.specularColorFactor||[1,1,1];return t.specularColor=new q().setRGB(i[0],i[1],i[2],zo),n.specularColorTexture!==void 0&&r.push(this.parser.assignTexture(t,`specularColorMap`,n.specularColorTexture,Ro)),Promise.all(r)}},xE=class{constructor(e){this.parser=e,this.name=lE.EXT_MATERIALS_BUMP}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return t.bumpScale=n.bumpFactor===void 0?1:n.bumpFactor,n.bumpTexture!==void 0&&r.push(this.parser.assignTexture(t,`bumpMap`,n.bumpTexture)),Promise.all(r)}},SE=class{constructor(e){this.parser=e,this.name=lE.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return cE(this.parser,e,this.name)===null?null:Ad}extendMaterialParams(e,t){let n=cE(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return n.anisotropyStrength!==void 0&&(t.anisotropy=n.anisotropyStrength),n.anisotropyRotation!==void 0&&(t.anisotropyRotation=n.anisotropyRotation),n.anisotropyTexture!==void 0&&r.push(this.parser.assignTexture(t,`anisotropyMap`,n.anisotropyTexture)),Promise.all(r)}},CE=class{constructor(e){this.parser=e,this.name=lE.KHR_TEXTURE_BASISU}loadTexture(e){let t=this.parser,n=t.json,r=n.textures[e];if(!r.extensions||!r.extensions[this.name])return null;let i=r.extensions[this.name],a=t.options.ktx2Loader;if(!a){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw Error(`THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures`);return null}return t.loadTextureImage(e,i.source,a)}},wE=class{constructor(e){this.parser=e,this.name=lE.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},TE=class{constructor(e){this.parser=e,this.name=lE.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},EE=class{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){let t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){let e=n.extensions[this.name],r=this.parser.getDependency(`buffer`,e.buffer),i=this.parser.options.meshoptDecoder;if(!i||!i.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw Error(`THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files`);return null}return r.then(function(t){let n=e.byteOffset||0,r=e.byteLength||0,a=e.count,o=e.byteStride,s=new Uint8Array(t,n,r);return i.decodeGltfBufferAsync?i.decodeGltfBufferAsync(a,o,s,e.mode,e.filter).then(function(e){return e.buffer}):i.ready.then(function(){let t=new ArrayBuffer(a*o);return i.decodeGltfBuffer(new Uint8Array(t),a,o,s,e.mode,e.filter),t})})}else return null}},DE=class{constructor(e){this.name=lE.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;let r=t.meshes[n.mesh];for(let e of r.primitives)if(e.mode!==RE.TRIANGLES&&e.mode!==RE.TRIANGLE_STRIP&&e.mode!==RE.TRIANGLE_FAN&&e.mode!==void 0)return null;let i=n.extensions[this.name].attributes,a=[],o={};for(let e in i)a.push(this.parser.getDependency(`accessor`,i[e]).then(t=>(o[e]=t,o[e])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(e=>{let t=e.pop(),n=t.isGroup?t.children:[t],r=e[0].count,i=[];for(let e of n){let t=new K,n=new W,a=new U,s=new W(1,1,1),c=new Au(e.geometry,e.material,r);for(let e=0;e<r;e++)o.TRANSLATION&&n.fromBufferAttribute(o.TRANSLATION,e),o.ROTATION&&a.fromBufferAttribute(o.ROTATION,e),o.SCALE&&s.fromBufferAttribute(o.SCALE,e),c.setMatrixAt(e,t.compose(n,a,s));for(let t in o)if(t===`_COLOR_0`){let e=o[t];c.instanceColor=new Su(e.array,e.itemSize,e.normalized)}else t!==`TRANSLATION`&&t!==`ROTATION`&&t!==`SCALE`&&e.geometry.setAttribute(t,o[t]);Tc.prototype.copy.call(c,e),this.parser.assignFinalMaterial(c),i.push(c)}return t.isGroup?(t.clear(),t.add(...i),t):i[0]}))}},OE=`glTF`,kE=12,AE={JSON:1313821514,BIN:5130562},jE=class{constructor(e){this.name=lE.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,kE),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==OE)throw Error(`THREE.GLTFLoader: Unsupported glTF-Binary header.`);if(this.header.version<2)throw Error(`THREE.GLTFLoader: Legacy binary file detected.`);let r=this.header.length-kE,i=new DataView(e,kE),a=0;for(;a<r;){let t=i.getUint32(a,!0);a+=4;let r=i.getUint32(a,!0);if(a+=4,r===AE.JSON){let r=new Uint8Array(e,kE+a,t);this.content=n.decode(r)}else if(r===AE.BIN){let n=kE+a;this.body=e.slice(n,n+t)}a+=t}if(this.content===null)throw Error(`THREE.GLTFLoader: JSON content not found.`)}},ME=class{constructor(e,t){if(!t)throw Error(`THREE.GLTFLoader: No DRACOLoader instance provided.`);this.name=lE.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){let n=this.json,r=this.dracoLoader,i=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},s={},c={};for(let e in a){let t=UE[e]||e.toLowerCase();o[t]=a[e]}for(let t in e.attributes){let r=UE[t]||t.toLowerCase();if(a[t]!==void 0){let i=n.accessors[e.attributes[t]];c[r]=zE[i.componentType].name,s[r]=i.normalized===!0}}return t.getDependency(`bufferView`,i).then(function(e){return new Promise(function(t,n){r.decodeDracoFile(e,function(e){for(let t in e.attributes){let n=e.attributes[t],r=s[t];r!==void 0&&(n.normalized=r)}t(e)},o,c,zo,n)})})}},NE=class{constructor(){this.name=lE.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0?e:(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0,e)}},PE=class{constructor(){this.name=lE.KHR_MESH_QUANTIZATION}},FE=class extends Ld{constructor(e,t,n,r){super(e,t,n,r)}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r*3+r;for(let e=0;e!==r;e++)t[e]=n[i+e];return t}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=o*2,c=o*3,l=r-t,u=(n-t)/l,d=u*u,f=d*u,p=e*c,m=p-c,h=-2*f+3*d,g=f-d,_=1-h,v=g-d+u;for(let e=0;e!==o;e++){let t=a[m+e+o],n=a[m+e+s]*l,r=a[p+e+o],c=a[p+e]*l;i[e]=_*t+v*n+h*r+g*c}return i}},IE=new U,LE=class extends FE{interpolate_(e,t,n,r){let i=super.interpolate_(e,t,n,r);return IE.fromArray(i).normalize().toArray(i),i}},RE={FLOAT:5126,FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123},zE={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},BE={9728:fa,9729:ha,9984:pa,9985:ga,9986:ma,9987:_a},VE={33071:ua,33648:da,10497:la},HE={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},UE={POSITION:`position`,NORMAL:`normal`,TANGENT:`tangent`,TEXCOORD_0:`uv`,TEXCOORD_1:`uv1`,TEXCOORD_2:`uv2`,TEXCOORD_3:`uv3`,COLOR_0:`color`,WEIGHTS_0:`skinWeight`,JOINTS_0:`skinIndex`},WE={scale:`scale`,translation:`position`,rotation:`quaternion`,weights:`morphTargetInfluences`},GE={CUBICSPLINE:void 0,LINEAR:Oo,STEP:Do},KE={OPAQUE:`OPAQUE`,MASK:`MASK`,BLEND:`BLEND`};function qE(e){return e.DefaultMaterial===void 0&&(e.DefaultMaterial=new kd({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:0})),e.DefaultMaterial}function JE(e,t,n){for(let r in n.extensions)e[r]===void 0&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[r]=n.extensions[r])}function YE(e,t){t.extras!==void 0&&(typeof t.extras==`object`?Object.assign(e.userData,t.extras):console.warn(`THREE.GLTFLoader: Ignoring primitive type .extras, `+t.extras))}function XE(e,t,n){let r=!1,i=!1,a=!1;for(let e=0,n=t.length;e<n;e++){let n=t[e];if(n.POSITION!==void 0&&(r=!0),n.NORMAL!==void 0&&(i=!0),n.COLOR_0!==void 0&&(a=!0),r&&i&&a)break}if(!r&&!i&&!a)return Promise.resolve(e);let o=[],s=[],c=[];for(let l=0,u=t.length;l<u;l++){let u=t[l];if(r){let t=u.POSITION===void 0?e.attributes.position:n.getDependency(`accessor`,u.POSITION);o.push(t)}if(i){let t=u.NORMAL===void 0?e.attributes.normal:n.getDependency(`accessor`,u.NORMAL);s.push(t)}if(a){let t=u.COLOR_0===void 0?e.attributes.color:n.getDependency(`accessor`,u.COLOR_0);c.push(t)}}return Promise.all([Promise.all(o),Promise.all(s),Promise.all(c)]).then(function(t){let n=t[0],o=t[1],s=t[2];return r&&(e.morphAttributes.position=n),i&&(e.morphAttributes.normal=o),a&&(e.morphAttributes.color=s),e.morphTargetsRelative=!0,e})}function ZE(e,t){if(e.updateMorphTargets(),t.weights!==void 0)for(let n=0,r=t.weights.length;n<r;n++)e.morphTargetInfluences[n]=t.weights[n];if(t.extras&&Array.isArray(t.extras.targetNames)){let n=t.extras.targetNames;if(e.morphTargetInfluences.length===n.length){e.morphTargetDictionary={};for(let t=0,r=n.length;t<r;t++)e.morphTargetDictionary[n[t]]=t}else console.warn(`THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.`)}}function QE(e){let t,n=e.extensions&&e.extensions[lE.KHR_DRACO_MESH_COMPRESSION];if(t=n?`draco:`+n.bufferView+`:`+n.indices+`:`+$E(n.attributes):e.indices+`:`+$E(e.attributes)+`:`+e.mode,e.targets!==void 0)for(let n=0,r=e.targets.length;n<r;n++)t+=`:`+$E(e.targets[n]);return t}function $E(e){let t=``,n=Object.keys(e).sort();for(let r=0,i=n.length;r<i;r++)t+=n[r]+`:`+e[n[r]]+`;`;return t}function eD(e){switch(e){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw Error(`THREE.GLTFLoader: Unsupported normalized accessor component type.`)}}function tD(e){return e.search(/\.jpe?g($|\?)/i)>0||e.search(/^data\:image\/jpeg/)===0?`image/jpeg`:e.search(/\.webp($|\?)/i)>0||e.search(/^data\:image\/webp/)===0?`image/webp`:e.search(/\.ktx2($|\?)/i)>0||e.search(/^data\:image\/ktx2/)===0?`image/ktx2`:`image/png`}var nD=new K,rD=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new sE,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,r=-1,i=!1,a=-1;if(typeof navigator<`u`&&navigator.userAgent!==void 0){let e=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(e)===!0;let t=e.match(/Version\/(\d+)/);r=n&&t?parseInt(t[1],10):-1,i=e.indexOf(`Firefox`)>-1,a=i?e.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>`u`||n&&r<17||i&&a<98?this.textureLoader=new uf(this.options.manager):this.textureLoader=new Pf(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new of(this.options.manager),this.fileLoader.setResponseType(`arraybuffer`),this.options.crossOrigin===`use-credentials`&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let n=this,r=this.json,i=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(e){return e._markDefs&&e._markDefs()}),Promise.all(this._invokeAll(function(e){return e.beforeRoot&&e.beforeRoot()})).then(function(){return Promise.all([n.getDependencies(`scene`),n.getDependencies(`animation`),n.getDependencies(`camera`)])}).then(function(t){let a={scene:t[0][r.scene||0],scenes:t[0],animations:t[1],cameras:t[2],asset:r.asset,parser:n,userData:{}};return JE(i,a,r),YE(a,r),Promise.all(n._invokeAll(function(e){return e.afterRoot&&e.afterRoot(a)})).then(function(){for(let e of a.scenes)e.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let n=0,r=t.length;n<r;n++){let r=t[n].joints;for(let t=0,n=r.length;t<n;t++)e[r[t]].isBone=!0}for(let t=0,r=e.length;t<r;t++){let r=e[t];r.mesh!==void 0&&(this._addNodeRef(this.meshCache,r.mesh),r.skin!==void 0&&(n[r.mesh].isSkinnedMesh=!0)),r.camera!==void 0&&this._addNodeRef(this.cameraCache,r.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;let r=n.clone(),i=(e,t)=>{let n=this.associations.get(e);n!=null&&this.associations.set(t,n);for(let[n,r]of e.children.entries())i(r,t.children[n])};return i(n,r),r.name+=`_instance_`+ e.uses[t]++,r}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){let r=e(t[n]);if(r)return r}return null}_invokeAll(e){let t=Object.values(this.plugins);t.unshift(this);let n=[];for(let r=0;r<t.length;r++){let i=e(t[r]);i&&n.push(i)}return n}getDependency(e,t){let n=e+`:`+t,r=this.cache.get(n);if(!r){switch(e){case`scene`:r=this.loadScene(t);break;case`node`:r=this._invokeOne(function(e){return e.loadNode&&e.loadNode(t)});break;case`mesh`:r=this._invokeOne(function(e){return e.loadMesh&&e.loadMesh(t)});break;case`accessor`:r=this.loadAccessor(t);break;case`bufferView`:r=this._invokeOne(function(e){return e.loadBufferView&&e.loadBufferView(t)});break;case`buffer`:r=this.loadBuffer(t);break;case`material`:r=this._invokeOne(function(e){return e.loadMaterial&&e.loadMaterial(t)});break;case`texture`:r=this._invokeOne(function(e){return e.loadTexture&&e.loadTexture(t)});break;case`skin`:r=this.loadSkin(t);break;case`animation`:r=this._invokeOne(function(e){return e.loadAnimation&&e.loadAnimation(t)});break;case`camera`:r=this.loadCamera(t);break;default:if(r=this._invokeOne(function(n){return n!=this&&n.getDependency&&n.getDependency(e,t)}),!r)throw Error(`Unknown type: `+e);break}this.cache.add(n,r)}return r}getDependencies(e){let t=this.cache.get(e);if(!t){let n=this,r=this.json[e+(e===`mesh`?`es`:`s`)]||[];t=Promise.all(r.map(function(t,r){return n.getDependency(e,r)})),this.cache.add(e,t)}return t}loadBuffer(e){let t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!==`arraybuffer`)throw Error(`THREE.GLTFLoader: `+t.type+` buffer type is not supported.`);if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[lE.KHR_BINARY_GLTF].body);let r=this.options;return new Promise(function(e,i){n.load(Mf.resolveURL(t.uri,r.path),e,void 0,function(){i(Error(`THREE.GLTFLoader: Failed to load buffer "`+t.uri+`".`))})})}loadBufferView(e){let t=this.json.bufferViews[e];return this.getDependency(`buffer`,t.buffer).then(function(e){let n=t.byteLength||0,r=t.byteOffset||0;return e.slice(r,r+n)})}loadAccessor(e){let t=this,n=this.json,r=this.json.accessors[e];if(r.bufferView===void 0&&r.sparse===void 0){let e=HE[r.type],t=zE[r.componentType],n=r.normalized===!0,i=new t(r.count*e);return Promise.resolve(new J(i,e,n))}let i=[];return r.bufferView===void 0?i.push(null):i.push(this.getDependency(`bufferView`,r.bufferView)),r.sparse!==void 0&&(i.push(this.getDependency(`bufferView`,r.sparse.indices.bufferView)),i.push(this.getDependency(`bufferView`,r.sparse.values.bufferView))),Promise.all(i).then(function(e){let i=e[0],a=HE[r.type],o=zE[r.componentType],s=o.BYTES_PER_ELEMENT,c=s*a,l=r.byteOffset||0,u=r.bufferView===void 0?void 0:n.bufferViews[r.bufferView].byteStride,d=r.normalized===!0,f,p;if(u&&u!==c){let e=Math.floor(l/u),n=`InterleavedBuffer:`+r.bufferView+`:`+r.componentType+`:`+e+`:`+r.count,c=t.cache.get(n);c||(f=new o(i,e*u,r.count*u/s),c=new Nl(f,u/s),t.cache.add(n,c)),p=new Fl(c,a,l%u/s,d)}else f=i===null?new o(r.count*a):new o(i,l,r.count*a),p=new J(f,a,d);if(r.sparse!==void 0){let t=HE.SCALAR,n=zE[r.sparse.indices.componentType],s=r.sparse.indices.byteOffset||0,c=r.sparse.values.byteOffset||0,l=new n(e[1],s,r.sparse.count*t),u=new o(e[2],c,r.sparse.count*a);i!==null&&(p=new J(p.array.slice(),p.itemSize,p.normalized)),p.normalized=!1;for(let e=0,t=l.length;e<t;e++){let t=l[e];if(p.setX(t,u[e*a]),a>=2&&p.setY(t,u[e*a+1]),a>=3&&p.setZ(t,u[e*a+2]),a>=4&&p.setW(t,u[e*a+3]),a>=5)throw Error(`THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.`)}p.normalized=d}return p})}loadTexture(e){let t=this.json,n=this.options,r=t.textures[e].source,i=t.images[r],a=this.textureLoader;if(i.uri){let e=n.manager.getHandler(i.uri);e!==null&&(a=e)}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,n){let r=this,i=this.json,a=i.textures[e],o=i.images[t],s=(o.uri||o.bufferView)+`:`+a.sampler;if(this.textureCache[s])return this.textureCache[s];let c=this.loadImageSource(t,n).then(function(t){t.flipY=!1,t.name=a.name||o.name||``,t.name===``&&typeof o.uri==`string`&&o.uri.startsWith(`data:image/`)===!1&&(t.name=o.uri);let n=(i.samplers||{})[a.sampler]||{};return t.magFilter=BE[n.magFilter]||1006,t.minFilter=BE[n.minFilter]||1008,t.wrapS=VE[n.wrapS]||1e3,t.wrapT=VE[n.wrapT]||1e3,t.generateMipmaps=!t.isCompressedTexture&&t.minFilter!==1003&&t.minFilter!==1006,r.associations.set(t,{textures:e}),t}).catch(function(){return null});return this.textureCache[s]=c,c}loadImageSource(e,t){let n=this,r=this.json,i=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(e=>e.clone());let a=r.images[e],o=self.URL||self.webkitURL,s=a.uri||``,c=!1;if(a.bufferView!==void 0)s=n.getDependency(`bufferView`,a.bufferView).then(function(e){c=!0;let t=new Blob([e],{type:a.mimeType});return s=o.createObjectURL(t),s});else if(a.uri===void 0)throw Error(`THREE.GLTFLoader: Image `+e+` is missing URI and bufferView`);let l=Promise.resolve(s).then(function(e){return new Promise(function(n,r){let a=n;t.isImageBitmapLoader===!0&&(a=function(e){let t=new qs(e);t.needsUpdate=!0,n(t)}),t.load(Mf.resolveURL(e,i.path),a,void 0,r)})}).then(function(e){return c===!0&&o.revokeObjectURL(s),YE(e,a),e.userData.mimeType=a.mimeType||tD(a.uri),e}).catch(function(e){throw console.error(`THREE.GLTFLoader: Couldn't load texture`,s),e});return this.sourceCache[e]=l,l}assignTexture(e,t,n,r){let i=this;return this.getDependency(`texture`,n.index).then(function(a){if(!a)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(a=a.clone(),a.channel=n.texCoord),i.extensions[lE.KHR_TEXTURE_TRANSFORM]){let e=n.extensions===void 0?void 0:n.extensions[lE.KHR_TEXTURE_TRANSFORM];if(e){let t=i.associations.get(a);a=i.extensions[lE.KHR_TEXTURE_TRANSFORM].extendTexture(a,e),i.associations.set(a,t)}}return r!==void 0&&(a.colorSpace=r),e[t]=a,a})}assignFinalMaterial(e){let t=e.geometry,n=e.material,r=t.attributes.tangent===void 0,i=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){let e=`PointsMaterial:`+n.uuid,t=this.cache.get(e);t||(t=new $u,Ll.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,t.sizeAttenuation=!1,this.cache.add(e,t)),n=t}else if(e.isLine){let e=`LineBasicMaterial:`+n.uuid,t=this.cache.get(e);t||(t=new zu,Ll.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,this.cache.add(e,t)),n=t}if(r||i||a){let e=`ClonedMaterial:`+n.uuid+`:`;r&&(e+=`derivative-tangents:`),i&&(e+=`vertex-colors:`),a&&(e+=`flat-shading:`);let t=this.cache.get(e);t||(t=n.clone(),i&&(t.vertexColors=!0),a&&(t.flatShading=!0),r&&(t.normalScale&&(t.normalScale.y*=-1),t.clearcoatNormalScale&&(t.clearcoatNormalScale.y*=-1)),this.cache.add(e,t),this.associations.set(t,this.associations.get(n))),n=t}e.material=n}getMaterialType(){return kd}loadMaterial(e){let t=this,n=this.json,r=this.extensions,i=n.materials[e],a,o={},s=i.extensions||{},c=[];if(s[lE.KHR_MATERIALS_UNLIT]){let e=r[lE.KHR_MATERIALS_UNLIT];a=e.getMaterialType(),c.push(e.extendParams(o,i,t))}else{let n=i.pbrMetallicRoughness||{};if(o.color=new q(1,1,1),o.opacity=1,Array.isArray(n.baseColorFactor)){let e=n.baseColorFactor;o.color.setRGB(e[0],e[1],e[2],zo),o.opacity=e[3]}n.baseColorTexture!==void 0&&c.push(t.assignTexture(o,`map`,n.baseColorTexture,Ro)),o.metalness=n.metallicFactor===void 0?1:n.metallicFactor,o.roughness=n.roughnessFactor===void 0?1:n.roughnessFactor,n.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,`metalnessMap`,n.metallicRoughnessTexture)),c.push(t.assignTexture(o,`roughnessMap`,n.metallicRoughnessTexture))),a=this._invokeOne(function(t){return t.getMaterialType&&t.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(t){return t.extendMaterialParams&&t.extendMaterialParams(e,o)})))}i.doubleSided===!0&&(o.side=2);let l=i.alphaMode||KE.OPAQUE;if(l===KE.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,l===KE.MASK&&(o.alphaTest=i.alphaCutoff===void 0?.5:i.alphaCutoff)),i.normalTexture!==void 0&&a!==Kl&&(c.push(t.assignTexture(o,`normalMap`,i.normalTexture)),o.normalScale=new H(1,1),i.normalTexture.scale!==void 0)){let e=i.normalTexture.scale;o.normalScale.set(e,e)}if(i.occlusionTexture!==void 0&&a!==Kl&&(c.push(t.assignTexture(o,`aoMap`,i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&a!==Kl){let e=i.emissiveFactor;o.emissive=new q().setRGB(e[0],e[1],e[2],zo)}return i.emissiveTexture!==void 0&&a!==Kl&&c.push(t.assignTexture(o,`emissiveMap`,i.emissiveTexture,Ro)),Promise.all(c).then(function(){let n=new a(o);return i.name&&(n.name=i.name),YE(n,i),t.associations.set(n,{materials:e}),i.extensions&&JE(r,n,i),n})}createUniqueName(e){let t=Zf.sanitizeNodeName(e||``);return t in this.nodeNamesUsed?t+`_`+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,n=this.extensions,r=this.primitiveCache;function i(e){return n[lE.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then(function(n){return aD(n,e,t)})}let a=[];for(let n=0,o=e.length;n<o;n++){let o=e[n],s=QE(o),c=r[s];if(c)a.push(c.promise);else{let e;e=o.extensions&&o.extensions[lE.KHR_DRACO_MESH_COMPRESSION]?i(o):aD(new Y,o,t),r[s]={primitive:o,promise:e},a.push(e)}}return Promise.all(a)}loadMesh(e){let t=this,n=this.json,r=this.extensions,i=n.meshes[e],a=i.primitives,o=[];for(let e=0,t=a.length;e<t;e++){let t=a[e].material===void 0?qE(this.cache):this.getDependency(`material`,a[e].material);o.push(t)}return o.push(t.loadGeometries(a)),Promise.all(o).then(function(n){let o=n.slice(0,n.length-1),s=n[n.length-1],c=[];for(let n=0,l=s.length;n<l;n++){let l=s[n],u=a[n],d,f=o[n];if(u.mode===RE.TRIANGLES||u.mode===RE.TRIANGLE_STRIP||u.mode===RE.TRIANGLE_FAN||u.mode===void 0)d=i.isSkinnedMesh===!0?new gu(l,f):new iu(l,f),d.isSkinnedMesh===!0&&d.normalizeSkinWeights(),u.mode===RE.TRIANGLE_STRIP?d.geometry=rE(d.geometry,1):u.mode===RE.TRIANGLE_FAN&&(d.geometry=rE(d.geometry,2));else if(u.mode===RE.LINES)d=new Zu(l,f);else if(u.mode===RE.LINE_STRIP)d=new qu(l,f);else if(u.mode===RE.LINE_LOOP)d=new Qu(l,f);else if(u.mode===RE.POINTS)d=new id(l,f);else throw Error(`THREE.GLTFLoader: Primitive mode unsupported: `+u.mode);Object.keys(d.geometry.morphAttributes).length>0&&ZE(d,i),d.name=t.createUniqueName(i.name||`mesh_`+e),YE(d,i),u.extensions&&JE(r,d,u),t.assignFinalMaterial(d),c.push(d)}for(let n=0,r=c.length;n<r;n++)t.associations.set(c[n],{meshes:e,primitives:n});if(c.length===1)return i.extensions&&JE(r,c[0],i),c[0];let l=new Ec;i.extensions&&JE(r,l,i),t.associations.set(l,{meshes:e});for(let e=0,t=c.length;e<t;e++)l.add(c[e]);return l})}loadCamera(e){let t,n=this.json.cameras[e],r=n[n.type];if(!r){console.warn(`THREE.GLTFLoader: Missing camera parameters.`);return}return n.type===`perspective`?t=new Cf(As.radToDeg(r.yfov),r.aspectRatio||1,r.znear||1,r.zfar||2e6):n.type===`orthographic`&&(t=new Of(-r.xmag,r.xmag,r.ymag,-r.ymag,r.znear,r.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),YE(t,n),Promise.resolve(t)}loadSkin(e){let t=this.json.skins[e],n=[];for(let e=0,r=t.joints.length;e<r;e++)n.push(this._loadNodeShallow(t.joints[e]));return t.inverseBindMatrices===void 0?n.push(null):n.push(this.getDependency(`accessor`,t.inverseBindMatrices)),Promise.all(n).then(function(e){let n=e.pop(),r=e,i=[],a=[];for(let e=0,o=r.length;e<o;e++){let o=r[e];if(o){i.push(o);let t=new K;n!==null&&t.fromArray(n.array,e*16),a.push(t)}else console.warn(`THREE.GLTFLoader: Joint "%s" could not be found.`,t.joints[e])}return new xu(i,a)})}loadAnimation(e){let t=this.json,n=this,r=t.animations[e],i=r.name?r.name:`animation_`+e,a=[],o=[],s=[],c=[],l=[];for(let e=0,t=r.channels.length;e<t;e++){let t=r.channels[e],n=r.samplers[t.sampler],i=t.target,u=i.node,d=r.parameters===void 0?n.input:r.parameters[n.input],f=r.parameters===void 0?n.output:r.parameters[n.output];i.node!==void 0&&(a.push(this.getDependency(`node`,u)),o.push(this.getDependency(`accessor`,d)),s.push(this.getDependency(`accessor`,f)),c.push(n),l.push(i))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(s),Promise.all(c),Promise.all(l)]).then(function(e){let t=e[0],a=e[1],o=e[2],s=e[3],c=e[4],l=[];for(let e=0,r=t.length;e<r;e++){let r=t[e],i=a[e],u=o[e],d=s[e],f=c[e];if(r===void 0)continue;r.updateMatrix&&r.updateMatrix();let p=n._createAnimationTracks(r,i,u,d,f);if(p)for(let e=0;e<p.length;e++)l.push(p[e])}let u=new Xd(i,void 0,l);return YE(u,r),u})}createNodeMesh(e){let t=this.json,n=this,r=t.nodes[e];return r.mesh===void 0?null:n.getDependency(`mesh`,r.mesh).then(function(e){let t=n._getNodeRef(n.meshCache,r.mesh,e);return r.weights!==void 0&&t.traverse(function(e){if(e.isMesh)for(let t=0,n=r.weights.length;t<n;t++)e.morphTargetInfluences[t]=r.weights[t]}),t})}loadNode(e){let t=this.json,n=this,r=t.nodes[e],i=n._loadNodeShallow(e),a=[],o=r.children||[];for(let e=0,t=o.length;e<t;e++)a.push(n.getDependency(`node`,o[e]));let s=r.skin===void 0?Promise.resolve(null):n.getDependency(`skin`,r.skin);return Promise.all([i,Promise.all(a),s]).then(function(e){let t=e[0],n=e[1],r=e[2];r!==null&&t.traverse(function(e){e.isSkinnedMesh&&e.bind(r,nD)});for(let e=0,r=n.length;e<r;e++)t.add(n[e]);if(t.userData.pivot!==void 0&&n.length>0){let e=t.userData.pivot,r=n[0];t.pivot=new W().fromArray(e),t.position.x-=e[0],t.position.y-=e[1],t.position.z-=e[2],r.position.set(0,0,0),delete t.userData.pivot}return t})}_loadNodeShallow(e){let t=this.json,n=this.extensions,r=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let i=t.nodes[e],a=i.name?r.createUniqueName(i.name):``,o=[],s=r._invokeOne(function(t){return t.createNodeMesh&&t.createNodeMesh(e)});return s&&o.push(s),i.camera!==void 0&&o.push(r.getDependency(`camera`,i.camera).then(function(e){return r._getNodeRef(r.cameraCache,i.camera,e)})),r._invokeAll(function(t){return t.createNodeAttachment&&t.createNodeAttachment(e)}).forEach(function(e){o.push(e)}),this.nodeCache[e]=Promise.all(o).then(function(t){let o;if(o=i.isBone===!0?new _u:t.length>1?new Ec:t.length===1?t[0]:new Tc,o!==t[0])for(let e=0,n=t.length;e<n;e++)o.add(t[e]);if(i.name&&(o.userData.name=i.name,o.name=a),YE(o,i),i.extensions&&JE(n,o,i),i.matrix!==void 0){let e=new K;e.fromArray(i.matrix),o.applyMatrix4(e)}else i.translation!==void 0&&o.position.fromArray(i.translation),i.rotation!==void 0&&o.quaternion.fromArray(i.rotation),i.scale!==void 0&&o.scale.fromArray(i.scale);if(!r.associations.has(o))r.associations.set(o,{});else if(i.mesh!==void 0&&r.meshCache.refs[i.mesh]>1){let e=r.associations.get(o);r.associations.set(o,{...e})}return r.associations.get(o).nodes=e,o}),this.nodeCache[e]}loadScene(e){let t=this.extensions,n=this.json.scenes[e],r=this,i=new Ec;n.name&&(i.name=r.createUniqueName(n.name)),YE(i,n),n.extensions&&JE(t,i,n);let a=n.nodes||[],o=[];for(let e=0,t=a.length;e<t;e++)o.push(r.getDependency(`node`,a[e]));return Promise.all(o).then(function(e){for(let t=0,n=e.length;t<n;t++){let n=e[t];n.parent===null?i.add(n):i.add(iE(n))}return r.associations=(e=>{let t=new Map;for(let[e,n]of r.associations)(e instanceof Ll||e instanceof qs)&&t.set(e,n);return e.traverse(e=>{let n=r.associations.get(e);n!=null&&t.set(e,n)}),t})(i),i})}_createAnimationTracks(e,t,n,r,i){let a=[],o=e.name?e.name:e.uuid,s=[];function c(e){e.morphTargetInfluences&&s.push(e.name?e.name:e.uuid)}WE[i.path]===WE.weights?(c(e),e.isGroup&&e.children.forEach(c)):s.push(o);let l;switch(WE[i.path]){case WE.weights:l=Gd;break;case WE.rotation:l=qd;break;case WE.translation:case WE.scale:l=Yd;break;default:switch(n.itemSize){case 1:l=Gd;break;default:l=Yd;break}break}let u=r.interpolation===void 0?Oo:GE[r.interpolation],d=this._getArrayFromAccessor(n);for(let e=0,n=s.length;e<n;e++){let n=new l(s[e]+`.`+WE[i.path],t.array,d,u);r.interpolation===`CUBICSPLINE`&&this._createCubicSplineTrackInterpolant(n),a.push(n)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let e=eD(t.constructor),n=new Float32Array(t.length);for(let r=0,i=t.length;r<i;r++)n[r]=t[r]*e;t=n}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(e){return new(this instanceof qd?LE:FE)(this.times,this.values,this.getValueSize()/3,e)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}};function iD(e,t,n){let r=t.attributes,i=new Xc;if(r.POSITION!==void 0){let e=n.json.accessors[r.POSITION],t=e.min,a=e.max;if(t!==void 0&&a!==void 0){if(i.set(new W(t[0],t[1],t[2]),new W(a[0],a[1],a[2])),e.normalized){let t=eD(zE[e.componentType]);i.min.multiplyScalar(t),i.max.multiplyScalar(t)}}else{console.warn(`THREE.GLTFLoader: Missing min/max properties for accessor POSITION.`);return}}else return;let a=t.targets;if(a!==void 0){let e=new W,t=new W;for(let r=0,i=a.length;r<i;r++){let i=a[r];if(i.POSITION!==void 0){let r=n.json.accessors[i.POSITION],a=r.min,o=r.max;if(a!==void 0&&o!==void 0){if(t.setX(Math.max(Math.abs(a[0]),Math.abs(o[0]))),t.setY(Math.max(Math.abs(a[1]),Math.abs(o[1]))),t.setZ(Math.max(Math.abs(a[2]),Math.abs(o[2]))),r.normalized){let e=eD(zE[r.componentType]);t.multiplyScalar(e)}e.max(t)}else console.warn(`THREE.GLTFLoader: Missing min/max properties for accessor POSITION.`)}}i.expandByVector(e)}e.boundingBox=i;let o=new Tl;i.getCenter(o.center),o.radius=i.min.distanceTo(i.max)/2,e.boundingSphere=o}function aD(e,t,n){let r=t.attributes,i=[];function a(t,r){return n.getDependency(`accessor`,t).then(function(t){e.setAttribute(r,t)})}for(let t in r){let n=UE[t]||t.toLowerCase();n in e.attributes||i.push(a(r[t],n))}if(t.indices!==void 0&&!e.index){let r=n.getDependency(`accessor`,t.indices).then(function(t){e.setIndex(t)});i.push(r)}return Ls.workingColorSpace!==`srgb-linear`&&`COLOR_0`in r&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Ls.workingColorSpace}" not supported.`),YE(e,t),iD(e,t,n),Promise.all(i).then(function(){return t.targets===void 0?e:XE(e,t.targets,n)})}var oD=(e,t)=>new uf().load(e,void 0,void 0,t);function sD(e,t){return[e,t?.colorSpace??`srgb`,t?.filter??`linear`,t?.wrap??`clamp`,String(t?.anisotropy??1),t?.process?.id??``].join(`|`)}function cD(e,t){e.colorSpace=(t?.colorSpace??`srgb`)===`srgb`?Ro:``;let n=t?.filter===`nearest`;e.magFilter=n?fa:ha,e.generateMipmaps=!n,e.minFilter=n?fa:_a;let r=t?.wrap===`repeat`?la:ua;e.wrapS=r,e.wrapT=r,t?.anisotropy&&(e.anisotropy=t.anisotropy)}var lD=class{entries=new Map;load;diagnostics;constructor(e){this.load=e?.loader??oD,this.diagnostics=e?.diagnostics??null}acquire(e,t){if(e===``||typeof document>`u`&&this.load===oD)return null;let n=sD(e,t),r=this.entries.get(n);if(r)return r.texture;let i={url:e,texture:null,error:null};return i.texture=this.load(e,t=>{i.error=t instanceof Error?t.message:String(t),this.diagnostics?.warn(`texture failed to load: ${e} — ${i.error}`)}),cD(i.texture,t),t?.process?.run(i.texture),this.entries.set(n,i),i.texture}acquireOwn(e,t){let n=this.acquire(e,t);return n?n.clone():null}noteError(e,t){let n=`external|${e}`;if(this.entries.has(n))return;let r=t instanceof Error?t.message:String(t);this.entries.set(n,{url:e,texture:null,error:r}),this.diagnostics?.warn(`texture failed to load: ${e} — ${r}`)}errors(){let e=[];for(let t of this.entries.values())t.error!==null&&e.push({url:t.url,error:t.error});return e}size(){return this.entries.size}dispose(){for(let e of this.entries.values())e.texture.dispose();this.entries.clear()}};function uD(e,t,n){return e?e.textures.acquire(t,n):fD().acquire(t,n)}function dD(e,t,n){return e?e.textures.acquireOwn(t,n):fD().acquireOwn(t,n)}function fD(){return new lD}var pD=class{engine;models=new Map;animations=new Map;modelKeys=new Map;animationKeys=new Map;loader;textures;constructor(e=null){this.engine=e,this.loader=new oE,this.loader.register(e=>new ET(e)),this.textures=new lD({diagnostics:e?{warn:(...t)=>Nt(e,`warn`,...t)}:null})}errors(){let e=[];for(let{url:t,error:n}of this.textures.errors())e.push({ref:t,url:t,error:n});for(let[t,n]of this.modelKeys){let r=this.models.get(n);r?.error&&e.push({ref:t,url:n,error:String(r.error)})}for(let[t,n]of this.animationKeys){let r=this.animations.get(n.url);r?.error&&e.push({ref:t,url:n.url,error:String(r.error)})}return e}load(e){for(let[t,n]of Object.entries(e)){let e=n;typeof e.url==`string`&&(e.type===`model`?this.modelKeys.set(`$${t}`,e.url):e.type===`animation`&&this.animationKeys.set(`$${t}`,{url:e.url,clip:e.clip}))}}animationRefs(){return[...this.animationKeys.keys()]}modelRefs(){return[...this.modelKeys.keys()]}getModel(e){let t=this.modelKeys.get(e)??e,n=this.models.get(t);return n||(n={status:`loading`,scene:null,animations:[],isVrm:!1,vrm:null,claimedBy:null,retargeted:new Map},this.models.set(t,n),this.loader.load(t,e=>{let r=e.userData.vrm;r?(nE.removeUnnecessaryVertices(e.scene),nE.combineSkeletons(e.scene),nE.rotateVRM0(r),n.scene=r.scene,n.vrm=r,n.isVrm=!0):n.scene=e.scene,n.animations=e.animations??[],n.status=`ready`,mD(n.scene)||(n.error="loaded, but it contains no meshes — this is an animation-only GLB. A clip file belongs in `animation`, not `model`.",Nt(this.engine,`error`,`incanto: '${t}' ${n.error}`))},void 0,e=>{n.status=`error`,n.error=e instanceof Error?e.message:String(e),Nt(this.engine,`error`,`incanto: failed to load model '${t}':`,e)}),n)}getAnimation(e){let t=this.animationKeys.get(e)??{url:e},n=this.animations.get(t.url);return n||(n={status:`loading`,clips:[],scene:null,clip:t.clip},this.animations.set(t.url,n),this.loader.load(t.url,e=>{n.clips=e.animations??[],n.scene=e.scene,n.status=`ready`,n.clips.length===0&&Nt(this.engine,`warn`,`incanto: animation asset '${t.url}' contains no clips`)},void 0,e=>{n.status=`error`,n.error=e instanceof Error?e.message:String(e),Nt(this.engine,`error`,`incanto: failed to load animation '${t.url}':`,e)}),n)}dispose(){this.textures.dispose();for(let e of this.models.values())e.scene?.traverse(e=>{let t=e;t.geometry?.dispose();let n=Array.isArray(t.material)?t.material:[t.material];for(let e of n)if(e){for(let t of Object.values(e))t?.isTexture&&t.dispose();e.dispose()}});this.models.clear(),this.animations.clear()}};function mD(e){let t=e?.traverse;if(!t)return!0;let n=!1;return t.call(e,e=>{e.isMesh&&(n=!0)}),n}var hD=Math.atan(1/Math.SQRT2);function gD(e,t,n,r,i,a){let o=[t[0],t[1]+n,t[2]];if(e===`firstPerson`)return{position:o,rotation:[-i,r,0]};if(e===`quarter`){let e=hD;return{position:[o[0],o[1]+a*Math.sin(e),o[2]+a*Math.cos(e)],rotation:[-e,0,0]}}if(e===`side`)return{position:[o[0],o[1],o[2]+a],rotation:[0,0,0]};let s=Math.cos(i);return{position:[o[0]+Math.sin(r)*s*a,o[1]+Math.sin(i)*a,o[2]+Math.cos(r)*s*a],rotation:[-i,r,0]}}function _D(e,t,n,r,i){let a=t[0]-e[0],o=t[1]-e[1],s=t[2]-e[2],c=Math.hypot(a,o,s);if(c<1e-4)return[t[0],t[1],t[2]];let l=[a/c,o/c,s/c],u=n(e,l,c);if(u===null)return[t[0],t[1],t[2]];let d=Math.min(c,Math.max(i,u-r));return[e[0]+l[0]*d,e[1]+l[1]*d,e[2]+l[2]*d]}function vD(e,t,n){let r=t(e,n);return r===null||r>=n?[e[0],e[1],e[2]]:[e[0],e[1]+(n-r),e[2]]}function yD(e,t,n){let r=Math.sin(n),i=Math.cos(n);return[e*i-t*r,0,-e*r-t*i]}function bD(e,t){return e?Math.min(.6+(t?.4:0),1):0}function xD(e,t){return e?t<=0?`idle`:t<.3?`walk`:t<.7?`run`:`fastRun`:`airborne`}var SD=50;function CD(e=SD,t=typeof requestAnimationFrame==`function`?requestAnimationFrame:void 0){return new Promise(n=>{let r=!1,i=()=>{r||(r=!0,n())},a=setTimeout(i,Math.max(0,e));t&&t(()=>{setTimeout(()=>{clearTimeout(a),i()},0)})})}function wD(e,t){let n=e.scene;if(!n)throw new L(`BAD_FORMAT`,`setEnvironment3D: the engine has no scene.`);let r={...n.environment??{}};for(let[e,n]of Object.entries(t))n===null?delete r[e]:typeof n==`object`&&!Array.isArray(n)&&typeof r[e]==`object`&&r[e]!==null&&!Array.isArray(r[e])?r[e]={...r[e],...n}:r[e]=n;ei(r),n.environment=r}var TD=[`color`,`metalness`,`roughness`,`emissive`,`emissiveIntensity`,`wireframe`,`flatShading`,`opacity`,`clearcoat`,`clearcoatRoughness`,`envMapIntensity`,`depthTest`,`depthWrite`,`map`,`normalMap`,`repeat`],ED=class extends Q_{static typeName=`MeshInstance3D`;static props={mesh:{default:`box`,options:[`box`,`sphere`,`capsule`,`plane`,`cylinder`,`gem`]},size:{default:[1,1,1]},material:{default:{}},castShadow:{default:!1},receiveShadow:{default:!1}};mesh=`box`;size=[1,1,1];material={};castShadow=!1;receiveShadow=!1;static validateJson(e){OD(e.material,e.name)}geometryKey=``;textureKey=``;loadedTextures=[];_createObject3D(){return new iu(new dd(1,1,1),new Ad)}_syncObject3D(e=1,t=null){super._syncObject3D(e,t);let n=this._ensureObject3D(),r=`${this.mesh}:${JSON.stringify(this.size)}`;r!==this.geometryKey&&(n.geometry.dispose(),n.geometry=kD(this.mesh,this.size),this.geometryKey=r);let i=n.material;DD(i,this.material),this.syncTextures(i,t),n.castShadow=this.castShadow,n.receiveShadow=this.receiveShadow}syncTextures(e,t){let n=JSON.stringify([this.material.map??``,this.material.normalMap??``,this.material.repeat??null]);if(n===this.textureKey)return;this.textureKey=n;for(let e of this.loadedTextures)e.dispose();this.loadedTextures=[];let r=e.map!==null||e.normalMap!==null;e.map=null,e.normalMap=null,this.material.map&&(e.map=this.loadTexture(t,this.material.map,!0)),this.material.normalMap&&(e.normalMap=this.loadTexture(t,this.material.normalMap,!1)),(r||e.map||e.normalMap)&&(e.needsUpdate=!0)}loadTexture(e,t,n){let r=dD(e,t,{wrap:`repeat`,anisotropy:4,colorSpace:n?`srgb`:`linear`});if(!r)return null;let[i,a]=this.material.repeat??[1,1];return r.repeat.set(i,a),this.loadedTextures.push(r),r}free(){for(let e of this.loadedTextures)e.dispose();this.loadedTextures=[];let e=this._builtObject3D;if(e){e.geometry?.dispose();let t=Array.isArray(e.material)?e.material:[e.material];for(let e of t)e?.dispose()}super.free()}};function DD(e,t){e.color.set(t.color??`#ffffff`),e.metalness=t.metalness??0,e.roughness=t.roughness??1,e.wireframe=t.wireframe??!1,e.emissive.set(t.emissive??`#000000`),e.emissiveIntensity=t.emissiveIntensity??1;let n=t.opacity??1;e.opacity=n,e.transparent=n<1;let r=t.clearcoat??0;e.clearcoat>0!=r>0&&(e.needsUpdate=!0),e.clearcoat=r,e.clearcoatRoughness=t.clearcoatRoughness??0,e.envMapIntensity=t.envMapIntensity??1,e.depthTest=t.depthTest??!0,e.depthWrite=t.depthWrite??!0;let i=t.flatShading??!1;e.flatShading!==i&&(e.flatShading=i,e.needsUpdate=!0)}function OD(e,t,n=`MeshInstance3D`){let r=e=>{throw new L(`BAD_FORMAT`,`${n} '${t}' ${e}`,{prop:`material`,validOptions:[...TD]})};(typeof e!=`object`||!e||Array.isArray(e))&&r(`material must be an object, got ${JSON.stringify(e)}.`);for(let t of Object.keys(e))TD.includes(t)||r(`material has unknown key '${t}' — must be one of [${TD.join(`, `)}].`);for(let t of[`map`,`normalMap`]){let n=e[t];n!==void 0&&(typeof n!=`string`||n.length===0)&&r(`material.${t} must be a non-empty texture URL string, got ${JSON.stringify(n)}.`)}if(e.repeat!==void 0){let t=e.repeat;(!Array.isArray(t)||t.length!==2||!t.every(e=>typeof e==`number`&&Number.isFinite(e)&&e>0))&&r(`material.repeat must be [u, v] with positive numbers, got ${JSON.stringify(t)}.`),!e.map&&!e.normalMap&&r(`material.repeat tiles nothing — add a 'map' and/or 'normalMap' texture URL.`)}for(let t of[`metalness`,`roughness`,`opacity`,`clearcoat`,`clearcoatRoughness`]){let n=e[t];n!==void 0&&!(typeof n==`number`&&n>=0&&n<=1)&&r(`material.${t} must be a number in 0..1, got ${JSON.stringify(n)}.`)}e.envMapIntensity!==void 0&&!(typeof e.envMapIntensity==`number`&&Number.isFinite(e.envMapIntensity)&&e.envMapIntensity>=0)&&r(`material.envMapIntensity must be a number >= 0, got ${JSON.stringify(e.envMapIntensity)}.`);for(let t of[`wireframe`,`flatShading`,`depthTest`,`depthWrite`]){let n=e[t];n!==void 0&&typeof n!=`boolean`&&r(`material.${t} must be a boolean, got ${JSON.stringify(n)}.`)}}function kD(e,t){let n=t[0]??1,r=t[1]??1,i=t[2]??1;switch(e){case`box`:return new dd(n,r,i);case`sphere`:return new vd(n,32,16);case`gem`:return new gd(n,0);case`capsule`:return new fd(n,r,8,16);case`plane`:{let e=new _d(n,i);return e.rotateX(-Math.PI/2),e}case`cylinder`:return new pd(n,n,r,24);default:throw new L(`PROP_TYPE_MISMATCH`,`MeshInstance3D.mesh must be one of box|sphere|capsule|plane|cylinder|gem, got '${e}'.`)}}var AD=class extends Q_{static typeName=`InstancedMesh3D`;static props={mesh:{default:`box`,options:[`box`,`sphere`,`capsule`,`plane`,`cylinder`,`gem`]},size:{default:[1,1,1]},material:{default:{}},transforms:{default:[]},castShadow:{default:!1},receiveShadow:{default:!1},collider:{default:null}};mesh=`box`;size=[1,1,1];material={};castShadow=!1;receiveShadow=!1;collider=null;_transforms=[];transformsDirty=!0;get transforms(){return this._transforms}set transforms(e){this._transforms=e,this.transformsDirty=!0}instanced=null;builtKey=``;static validateJson(e){let t=e;OD(t.material,e.name);for(let[n,r]of t._transforms.entries())if(!Array.isArray(r)||r.length<3||r.length>5||r.some(e=>typeof e!=`number`))throw new L(`BAD_FORMAT`,`InstancedMesh3D '${e.name}': transforms[${n}] must be [x, y, z, yawDeg?, scale?] (numbers), got ${JSON.stringify(r)}.`)}get instanceCount(){return this.instanced?.count??0}_syncObject3D(e){super._syncObject3D(e);let t=this._ensureObject3D(),n=`${this.mesh} ${JSON.stringify(this.size)} ${this._transforms.length}`;if(n!==this.builtKey){if(this.builtKey=n,this.instanced&&=(t.remove(this.instanced),this.instanced.geometry.dispose(),this.instanced.material.dispose(),null),this._transforms.length>0){let e=kD(this.mesh,this.size),n=new Ad;this.instanced=new Au(e,n,this._transforms.length),this.instanced.instanceMatrix.setUsage(Wo),t.add(this.instanced)}this.transformsDirty=!0}let r=this.instanced;if(r&&(r.castShadow=this.castShadow,r.receiveShadow=this.receiveShadow,DD(r.material,this.material),this.transformsDirty)){this.transformsDirty=!1;for(let e=0;e<this._transforms.length;e++){let t=this._transforms[e];MD.set(t[0]??0,t[1]??0,t[2]??0),ND.setFromAxisAngle(jD,(t[3]??0)*Math.PI/180);let n=t[4]??1;PD.set(n,n,n),FD.compose(MD,ND,PD),r.setMatrixAt(e,FD)}r.instanceMatrix.needsUpdate=!0,r.computeBoundingSphere()}}free(){this.instanced&&(this.instanced.geometry.dispose(),this.instanced.material.dispose()),super.free()}},jD=new W(0,1,0),MD=new W,ND=new U,PD=new W,FD=new K,ID=class extends Q_{static typeName=`Joint3D`;static props={type:{default:`spherical`,options:[`fixed`,`spherical`,`rope`,`spring`]},target:{default:``,nodePath:!0,required:!0},anchor:{default:[0,0,0]},targetAnchor:{default:[0,0,0]},length:{default:0},stiffness:{default:50},damping:{default:5}};type=`spherical`;target=``;anchor=[0,0,0];targetAnchor=[0,0,0];length=0;stiffness=50;damping=5;onEnterTree(){if(!(this.parent instanceof $_))throw new L(`TREE_VIOLATION`,`Joint3D '${this.name}' must be a child of a physics body (its body A); parent is '${this.parent?.name??`none`}'.`);if(this.target===``)throw new L(`BAD_FORMAT`,`Joint3D '${this.name}' needs a "target" node path to the body it links to.`)}_resolveBodies(){let e=this.parent,t=this.getNodeOrNull(this.target);if(!(t instanceof $_))throw new L(`NODE_NOT_FOUND`,`Joint3D '${this.name}': target '${this.target}' is not a physics body.`);return{a:e,b:t}}},LD=256,RD=.3,zD=.6,BD=45;function VD(e){let{width:t,depth:n,segsX:r,segsZ:i,maxHeight:a,seed:o}=e,s=e.roughness??.5,c=e.detail??4,l=e.flatThreshold??.95,u=e.islandEdge??!1,d=Math.max(0,Math.min(e.edgeWrapRadius??20,BD)),f=e.edgeBottom??-50,p=e.edgeCornerSmoothness??1,m=(e.basins??[]).map(e=>({cx:e.x+t/2,cz:e.z+n/2,radius:e.radius,depth:e.depth})),h=(e.channels??[]).map(e=>({half:Math.max(e.width,0)/2,taper:Math.max(e.taper??e.width,.001),depth:e.depth,segs:e.path.map(e=>({x:(e[0]??0)+t/2,z:(e[1]??0)+n/2})).flatMap((e,t,n)=>t===0?[]:[{ax:n[t-1].x,az:n[t-1].z,bx:e.x,bz:e.z}])})).filter(e=>e.segs.length>0&&e.depth!==0),g=Sr(o),_=(e,t)=>(g(e,t)+1)*.5,v=(e,t)=>{let n=e/LD,r=t/LD,i=0,o=.2,u=5;for(let e=0;e<5;e++)i+=_(n*o,r*o)*u,u*=.5,o*=2;let d=0;o=.5,u=.1;for(let e=0;e<c;e++)d+=_(n*o,r*o)*u,u*=s,o*=2;i=Math.abs(i)**1.5*Math.sign(i),i<RD&&(i*=.3);let f=a*(i+d*(i*.5+.5)+1)/2,p=a*l;if(Math.abs(f-p)<zD&&(f=p),m.length>0){let n=0,r=0;for(let i of m){let a=Math.hypot(e-i.cx,t-i.cz);if(a<i.radius){let e=a/i.radius,t=1-e*e*(3-2*e);i.depth>=0?n=Math.max(n,i.depth*t):r=Math.max(r,-i.depth*t)}}f+=r-n}if(h.length>0){let n=0;for(let r of h){let i=1/0;for(let n of r.segs){let a=n.bx-n.ax,o=n.bz-n.az,s=a*a+o*o,c=s>1e-9?Math.min(1,Math.max(0,((e-n.ax)*a+(t-n.az)*o)/s)):0,l=n.ax+a*c,u=n.az+o*c,d=Math.hypot(e-l,t-u);if(d<i&&(i=d),i<=r.half)break}if(i>=r.half+r.taper)continue;let a=Math.min(1,Math.max(0,(i-r.half)/r.taper));n=Math.max(n,r.depth*(1-a*a*(3-2*a)))}f-=n}return f},y=(e,a,o)=>{if(!u||d<=0)return o;let s=d,c=Math.min(e,t-e),l=Math.min(a,n-a),m=(t/r+n/i)*.002,h=Math.max(0,s-c+m),g=Math.max(0,s-l+m);if(h<=0&&g<=0)return o;let _=2+(1-Math.min(1,Math.max(0,p)))*30,v=(h**_+g**_)**(1/_),y=o-(s-Math.sqrt(Math.max(0,s*s-v*v)));return v>=s&&(y=Math.min(y,f)),y},b=r+1,x=i+1,S=new Float32Array(b*x),C=1/0,w=-1/0;for(let e=0;e<x;e++){let a=e/i*n;for(let n=0;n<b;n++){let i=n/r*t,o=v(i,a);o<C&&(C=o),o>w&&(w=o),S[e*b+n]=y(i,a,o)}}let T=(e,a)=>{let o=Math.min(Math.max((e+t/2)/t*r,0),r),s=Math.min(Math.max((a+n/2)/n*i,0),i),c=Math.min(Math.floor(o),r-1),l=Math.min(Math.floor(s),i-1),u=o-c,d=s-l,f=S[l*b+c],p=S[l*b+c+1],m=S[(l+1)*b+c],h=S[(l+1)*b+c+1];return(f*(1-u)+p*u)*(1-d)+(m*(1-u)+h*u)*d},E=(e,r)=>v(e+t/2,r+n/2);return{width:t,depth:n,segsX:r,segsZ:i,heights:S,minHeight:C,maxHeight:w,heightAt:T,baseHeight:E,slopeAt:(e,t)=>{let n=(E(e+1,t)-E(e-1,t))/2,r=(E(e,t+1)-E(e,t-1))/2;return Math.atan(Math.sqrt(n*n+r*r))}}}function HD(e,t,n,r){return e<t-r||e>n+r?0:e>=t&&e<=n?1:e<t?(e-(t-r))/r:(n+r-e)/r}function UD(e,t,n,r=1.2){let i=[0,0,0,0],a=Math.min(n.length,4),o=0;for(let s=0;s<a;s++){let a=n[s],[c,l]=a.heightRange??[0,1],[u,d]=a.slopeRange??[0,Math.PI/2],f=HD(e,c,l,a.heightBlendRange??.1)*HD(t,u,d,a.slopeBlendRange??.1);f**=1/r,i[s]=f,o+=f}if(o===0)return[1,0,0,0];for(let e=0;e<4;e++)i[e]=i[e]/o;return i}function WD(e,t,n){let r=e.indexOf(t);if(r===-1)throw new L(`BAD_FORMAT`,`Terrain3D shader patch: marker '${t}' not found in the three.js shader — the installed three version moved its chunks.`);let i=r+t.length;return`${e.slice(0,i)}\n${n}${e.slice(i)}`}var GD=`
|
|
6706
6706
|
varying vec3 vSplatColor;
|
|
6707
6707
|
varying vec3 vWorldPosition;
|
|
6708
6708
|
varying vec2 vUvSplat;
|
|
@@ -6989,7 +6989,7 @@ if (splatDetailAmount > 0.001) {
|
|
|
6989
6989
|
|
|
6990
6990
|
normal = perturbSplatNormal(normal, vViewPosition, vUvSplat, blendedNormalSample);
|
|
6991
6991
|
#endif
|
|
6992
|
-
`;function $D(e,t){for(let n=0;n<4;n++){let r=n+1;e.uniforms[`splatTexture${r}`]={value:t.textures[n]??t.textures[0]??null},e.uniforms[`splatNormalMap${r}`]={value:t.normalMaps[n]??null},e.uniforms[`splatTextureRepeat${r}`]={value:t.repeats[n]??1},e.uniforms[`splatRoughness${r}`]={value:t.roughness[n]??1},e.uniforms[`splatMetalness${r}`]={value:t.metalness[n]??0},e.uniforms[`uvNoiseIntensity${r}`]={value:t.uvNoiseIntensity[n]??.15}}e.uniforms.splatTextureCount={value:Math.min(4,t.layerCount)},e.uniforms.uWetlineY={value:-1e9},e.uniforms.uWetlineBand={value:1.1},e.uniforms.uWetTime={value:0},e.uniforms.splatEnvCut={value:t.envCut},e.vertexShader=WD(e.vertexShader,`#include <common>`,GD),e.vertexShader=WD(e.vertexShader,`#include <begin_vertex>`,KD);let n=e.fragmentShader;n=WD(n,`#include <common>`,qD),n=WD(n,`#include <color_fragment>`,JD),n=WD(n,`#include <roughnessmap_fragment>`,YD),n=WD(n,`#include <metalnessmap_fragment>`,ZD),n=WD(n,`#include <normal_fragment_maps>`,QD),n=WD(n,`#include <lights_fragment_maps>`,XD),t.hasNormalMaps&&(n=`#define USE_TERRAIN_NORMALMAP\n${n}`),e.fragmentShader=n}var eO=[`island`,`alpine`,`plains`,`desert`,`grassland`,`forest`,`savanna`,`snow`,`wetland`,`volcanic`,`custom`],tO=`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,nO=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/ground`,rO=1/3,iO=Math.PI/4;function aO(e,t,n){return{texture:`${e}/${t}.png`,normalMap:`${e}/${t}_normal.png`,...n}}function oO(e,t){let n=t.replace(/\/$/,``);switch(e){case`island`:return[aO(n,`sand`,{heightRange:[0,.12],slopeRange:[0,Math.PI/2],heightBlendRange:.05,roughness:.9}),aO(n,`grass`,{heightRange:[.1,.7],slopeRange:[0,iO],heightBlendRange:.1,slopeBlendRange:.1,roughness:.8}),aO(n,`stone`,{heightRange:[0,1],slopeRange:[iO,Math.PI],heightBlendRange:.5,slopeBlendRange:.5,roughness:.85}),aO(n,`snow`,{heightRange:[.8,1],slopeRange:[0,Math.PI/3],heightBlendRange:.1,roughness:.6})];case`alpine`:return[aO(n,`grass`,{heightRange:[0,.45],slopeRange:[0,Math.PI/5],heightBlendRange:.1,roughness:.8}),aO(n,`stone`,{heightRange:[.3,1],slopeRange:[0,Math.PI],heightBlendRange:.25,slopeBlendRange:.5,roughness:.85}),aO(n,`gravel`,{heightRange:[0,1],slopeRange:[Math.PI/5,Math.PI],heightBlendRange:.5,slopeBlendRange:.15,roughness:.9}),aO(n,`snow`,{heightRange:[.55,1],slopeRange:[0,Math.PI/3],heightBlendRange:.12,roughness:.55})];case`plains`:return[aO(n,`grass`,{heightRange:[0,1],slopeRange:[0,iO],heightBlendRange:.1,slopeBlendRange:.1,roughness:.8}),aO(n,`dirt`,{heightRange:[.35,.65],slopeRange:[0,Math.PI/5],heightBlendRange:.2,roughness:.9}),aO(n,`gravel`,{heightRange:[0,1],slopeRange:[iO,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.9})];case`desert`:return[aO(n,`sand`,{heightRange:[0,1],slopeRange:[0,iO],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),aO(n,`gravel`,{heightRange:[0,.15],slopeRange:[0,Math.PI/3],heightBlendRange:.08,roughness:.9}),aO(n,`stone`,{heightRange:[0,1],slopeRange:[iO,Math.PI],heightBlendRange:.5,slopeBlendRange:.4,roughness:.85})];case`grassland`:return n===`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`?[{texture:`${nO}/grass.jpg`,heightRange:[0,1],slopeRange:[0,iO],heightBlendRange:.1,slopeBlendRange:.15,roughness:1,repeat:rO,uvNoiseIntensity:0},{texture:`${nO}/dirt_color.jpg`,heightRange:[0,1],slopeRange:[iO,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:1,repeat:rO,uvNoiseIntensity:0}]:[aO(n,`grass`,{heightRange:[0,1],slopeRange:[0,iO],heightBlendRange:.1,slopeBlendRange:.15,roughness:.8}),aO(n,`dirt`,{heightRange:[0,1],slopeRange:[iO,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.9})];case`forest`:return n===`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`?[{texture:`${nO}/dirt_color.jpg`,heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:1,repeat:rO,uvNoiseIntensity:0},{texture:`${nO}/grass.jpg`,heightRange:[-2,-1],roughness:1,repeat:rO,uvNoiseIntensity:0}]:[aO(n,`dirt`,{heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:.9}),aO(n,`grass`,{heightRange:[-2,-1],roughness:.8})];case`savanna`:return[aO(n,`grass`,{heightRange:[0,1],slopeRange:[0,iO],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),aO(n,`sand`,{heightRange:[0,.22],slopeRange:[0,Math.PI/4],heightBlendRange:.12,roughness:.95}),aO(n,`dirt`,{heightRange:[0,1],slopeRange:[iO,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.95})];case`snow`:return[aO(n,`snow`,{heightRange:[0,1],slopeRange:[0,iO],heightBlendRange:.1,slopeBlendRange:.18,roughness:.55}),aO(n,`stone`,{heightRange:[0,1],slopeRange:[iO,Math.PI],heightBlendRange:.5,slopeBlendRange:.35,roughness:.85})];case`wetland`:return[aO(n,`grass`,{heightRange:[0,1],slopeRange:[0,iO],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),aO(n,`dirt`,{heightRange:[0,1],slopeRange:[iO,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.95})];case`volcanic`:return[aO(n,`stone`,{heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:.95}),aO(n,`gravel`,{heightRange:[0,.28],slopeRange:[0,Math.PI/3],heightBlendRange:.14,slopeBlendRange:.2,roughness:.95})];case`custom`:return[]}}var sO={scale:100,threshold:.7,blend:.1},cO={scale:55,threshold:.58,blend:.12},lO={scale:85,threshold:.62,blend:.12},uO={scale:48,threshold:.5,blend:.14};function dO(e,t){let n=Sr(e+27927);return(e,r)=>{let i=(.5+.5*n(e/t.scale,r/t.scale)-(t.threshold-t.blend))/(2*t.blend),a=Math.min(1,Math.max(0,i));return a*a*(3-2*a)}}function fO(e,t){return e===`grassland`?dO(t,sO):e===`forest`?dO(t,cO):e===`savanna`?dO(t,lO):e===`wetland`?dO(t,uO):null}function pO(e){return e===`savanna`?{from:0,to:2}:e===`grassland`||e===`forest`||e===`wetland`?{from:0,to:1}:null}var mO=256,hO=class extends Z_{orderGroup=`terrain`;static typeName=`Terrain3D`;static props={orderGroup:{default:`terrain`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},size:{default:[200,200]},maxHeight:{default:28},seed:{default:1},resolution:{default:128},theme:{default:`island`,options:eO},roughness:{default:.5},detail:{default:4},flatThreshold:{default:.95},islandEdge:{default:null},layers:{default:[]},textureBase:{default:tO},basins:{default:[]},channels:{default:[]},wetline:{default:null}};size=[200,200];maxHeight=28;seed=1;resolution=128;theme=`island`;roughness=.5;detail=4;flatThreshold=.95;islandEdge=null;layers=[];textureBase=tO;basins=[];channels=[];externalChannels=new Map;externalRev=0;shapeStamp=null;wetline=null;splatUniforms=null;wetTime=0;update(e){this.wetTime+=e;let t=this.splatUniforms;if(!t)return;let n=this.wetline;t.uWetlineY&&(t.uWetlineY.value=typeof n?.y==`number`?n.y:-1e9),t.uWetlineBand&&(t.uWetlineBand.value=typeof n?.band==`number`?n.band:1.1),t.uWetTime&&(t.uWetTime.value=this.wetTime)}static validateJson(e){rv(e,`heightAt(), the heightfield collider, drape and terrain-nav all`);let t=e;if(!eO.includes(t.theme))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' theme must be one of [${eO.join(`, `)}], got '${t.theme}'.`,{prop:`theme`,validOptions:eO});if(!((t.size[0]??0)>0)||!((t.size[1]??0)>0))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' size must be positive [width, depth] meters, got ${JSON.stringify(t.size)}.`,{prop:`size`});if(!(t.maxHeight>0))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' maxHeight must be > 0, got ${t.maxHeight}.`,{prop:`maxHeight`});if(!Number.isInteger(t.resolution)||t.resolution<2||t.resolution>mO)throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' resolution must be an integer in [2, ${mO}] (grid segments per side), got ${t.resolution}.`,{prop:`resolution`});if(!(t.roughness>0)||!Number.isFinite(t.roughness))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' roughness must be a finite number > 0, got ${t.roughness}.`,{prop:`roughness`});if(!Number.isInteger(t.detail)||t.detail<0)throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' detail must be an integer ≥ 0 (octave count), got ${t.detail}.`,{prop:`detail`});if(!(t.flatThreshold>=0)||!Number.isFinite(t.flatThreshold))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' flatThreshold must be a finite number ≥ 0, got ${t.flatThreshold}.`,{prop:`flatThreshold`});if(t.islandEdge!==null&&typeof t.islandEdge!=`boolean`)throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' islandEdge must be true, false or null (null = theme default), got ${JSON.stringify(t.islandEdge)}.`,{prop:`islandEdge`});let n=t.wetline;if(n!==null){if(typeof n!=`object`||Array.isArray(n)||!Number.isFinite(n.y))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' wetline must be null or { y, band? } with a finite y, got ${JSON.stringify(t.wetline)}.`,{prop:`wetline`});if(n.band!==void 0&&!(n.band>0))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' wetline.band must be > 0 meters, got ${JSON.stringify(n.band)}.`,{prop:`wetline`})}if(!Array.isArray(t.basins))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' basins must be an array of { x, z, radius, depth }, got ${JSON.stringify(t.basins)}.`,{prop:`basins`});if(t.basins.forEach((t,n)=>{if(!t||typeof t!=`object`||!Number.isFinite(t.x)||!Number.isFinite(t.z)||!(t.radius>0)||!Number.isFinite(t.depth)||t.depth===0)throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' basins[${n}] needs finite x, z, positive radius and nonzero depth (negative = mound), got ${JSON.stringify(t)}.`,{prop:`basins`})}),!Array.isArray(t.channels))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' channels must be an array of { path, width, depth, taper? }, got ${JSON.stringify(t.channels)}.`,{prop:`channels`});if(t.channels.forEach((t,n)=>{let r=t.path;if(!(t&&typeof t==`object`&&Array.isArray(r)&&r.length>=2&&r.every(e=>Array.isArray(e)&&Number.isFinite(e[0])&&Number.isFinite(e[1]))&&t.width>0&&t.depth>0&&(t.taper===void 0||t.taper>0)))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' channels[${n}] needs a path of 2+ [x, z] points plus positive width and depth, got ${JSON.stringify(t)}.`,{prop:`channels`})}),t.theme===`custom`){if(!Array.isArray(t.layers)||t.layers.length<1||t.layers.length>4)throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' theme 'custom' needs 1–4 layers, got ${Array.isArray(t.layers)?t.layers.length:typeof t.layers}.`,{prop:`layers`});t.layers.forEach((t,n)=>{vO(e.name,t,n)})}else if(Array.isArray(t.layers)&&t.layers.length>0)throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' layers is only read with theme 'custom' — preset theme '${t.theme}' defines its own. Drop layers or switch to theme: 'custom'.`,{prop:`layers`})}heightmap=null;heightmapKey=``;builtKey=``;_createObject3D(){let e=new Y;return e.setAttribute(`position`,new J(new Float32Array,3)),new iu(e,new kd({vertexColors:!0}))}heightAt(e,t){let n=0,r=0,i=0;for(let e=this;e;e=e.parent)e instanceof Z_&&(n+=e.position[0]??0,r+=e.position[1]??0,i+=e.position[2]??0);return this._heightmap().heightAt(e-n,t-i)+r}_setExternalChannel(e,t){t===null||t.length===0?this.externalChannels.delete(e):this.externalChannels.set(e,t),this.externalRev++}allChannels(){return this.externalChannels.size===0?this.channels:[...this.channels,...[...this.externalChannels.values()].flat()]}_heightmap(){if(this.heightmap&&this.shapeUnchanged())return this.heightmap;let e=this.segments(),t=JSON.stringify([this.size,this.maxHeight,this.seed,e,this.roughness,this.detail,this.flatThreshold,this.effectiveIslandEdge(),this.basins,this.allChannels()]);return(!this.heightmap||t!==this.heightmapKey)&&(this.heightmap=VD({width:this.size[0]??1,depth:this.size[1]??1,segsX:e,segsZ:e,maxHeight:this.maxHeight,seed:this.seed,roughness:this.roughness,detail:this.detail,flatThreshold:this.flatThreshold,islandEdge:this.effectiveIslandEdge(),basins:this.basins,channels:this.allChannels()}),this.heightmapKey=t),this.rememberShape(),this.heightmap}shapeUnchanged(){let e=this.shapeStamp;return e!==null&&e.sizeX===(this.size[0]??0)&&e.sizeZ===(this.size[1]??0)&&e.maxHeight===this.maxHeight&&e.seed===this.seed&&e.segments===this.segments()&&e.roughness===this.roughness&&e.detail===this.detail&&e.flatThreshold===this.flatThreshold&&e.islandEdge===this.effectiveIslandEdge()&&e.basins===this.basins&&e.channels===this.channels&&e.externalRev===this.externalRev}rememberShape(){this.shapeStamp={sizeX:this.size[0]??0,sizeZ:this.size[1]??0,maxHeight:this.maxHeight,seed:this.seed,segments:this.segments(),roughness:this.roughness,detail:this.detail,flatThreshold:this.flatThreshold,islandEdge:this.effectiveIslandEdge(),basins:this.basins,channels:this.channels,externalRev:this.externalRev}}resolvedLayers(){return this.theme===`custom`?this.layers:oO(this.theme,this.textureBase)}_syncObject3D(e=1,t=null){super._syncObject3D(e,t),this.rebuildIfNeeded(t)}effectiveIslandEdge(){return this.islandEdge??this.theme===`island`}segments(){return Math.max(2,Math.min(Math.floor(this.resolution),mO))}rebuildIfNeeded(e){let t=JSON.stringify([this.size,this.maxHeight,this.seed,this.segments(),this.theme,this.roughness,this.detail,this.flatThreshold,this.islandEdge,this.layers,this.textureBase,this.basins,this.allChannels()]);if(t===this.builtKey)return;this.builtKey=t;let n=this._ensureObject3D();n.geometry.dispose(),n.geometry=this.buildGeometry(),n.material.dispose(),n.material=this.buildMaterial(e),n.receiveShadow=!0,n.castShadow=!0}buildGeometry(){let e=this._heightmap(),t=new _d(e.width,e.depth,e.segsX,e.segsZ);t.rotateX(-Math.PI/2);let n=t.getAttribute(`position`);for(let t=0;t<n.count;t++)n.setY(t,e.heights[t]);n.needsUpdate=!0,t.computeVertexNormals();let r=this.resolvedLayers(),i=e.maxHeight-e.minHeight||1,a=new Float32Array(n.count*3),o=this.theme===`custom`?null:pO(this.theme),s=o?fO(this.theme,this.seed):null;for(let t=0;t<n.count;t++){let c=n.getX(t),l=n.getZ(t),u=UD(Math.min(1,Math.max(0,(n.getY(t)-e.minHeight)/i)),e.slopeAt(c,l),r);if(s&&o){let e=(u[o.from]??0)*s(c,l);u[o.from]=(u[o.from]??0)-e,u[o.to]=(u[o.to]??0)+e}a[t*3]=u[0],a[t*3+1]=u[1],a[t*3+2]=u[2]}return t.setAttribute(`color`,new J(a,3)),t}buildMaterial(e){let t=this.resolvedLayers(),n=new kd({vertexColors:!0}),r=(t,n)=>t?uD(e,t,{wrap:`repeat`,anisotropy:8,colorSpace:n?`srgb`:`linear`}):null,i=t.map(e=>r(e.texture,!0)),a=t.map(e=>r(e.normalMap,!1)),o=a.some(e=>e!==null);if(o)for(let e=0;e<a.length;e++)a[e]||(a[e]=_O());let s={textures:i,normalMaps:a,repeats:t.map(e=>e.repeat??2),roughness:t.map(e=>e.roughness??1),metalness:t.map(e=>e.metalness??0),uvNoiseIntensity:t.map(e=>e.uvNoiseIntensity??.15),envCut:.45,layerCount:Math.min(4,t.length),hasNormalMaps:o};return n.onBeforeCompile=e=>{$D(e,s),this.splatUniforms=e.uniforms},n.customProgramCacheKey=()=>`incanto-terrain-splat:${+!!o}`,n}free(){let e=this._ensureObject3D();e.geometry.dispose(),e.material.dispose(),this.heightmap=null,super.free()}},gO=null;function _O(){return gO||(gO=new vu(new Uint8Array([128,128,255,255]),1,1),gO.needsUpdate=!0),gO}function vO(e,t,n){let r=`layers[${n}]`;if(typeof t!=`object`||!t||Array.isArray(t))throw new L(`BAD_FORMAT`,`Terrain3D '${e}' ${r} must be an object ({texture, heightRange?, slopeRange?, …}).`,{prop:`layers`});let i=t;if(typeof i.texture!=`string`||i.texture.length===0)throw new L(`BAD_FORMAT`,`Terrain3D '${e}' ${r} needs "texture": a texture URL string.`,{prop:`layers`});for(let t of[`heightRange`,`slopeRange`]){let n=i[t];if(n!==void 0&&(!Array.isArray(n)||n.length!==2||n.some(e=>typeof e!=`number`||!Number.isFinite(e))))throw new L(`BAD_FORMAT`,`Terrain3D '${e}' ${r}.${t} must be [min, max] numbers, got ${JSON.stringify(n)}.`,{prop:`layers`})}}var yO=16,bO=new W,xO=new U;function SO(e,t){let n=e.translation(),r=e.rotation();xO.set(r.x,r.y,r.z,r.w);let i=(e,r,i)=>{bO.set(e,r,i).applyQuaternion(xO),t.push(bO.x+n.x,bO.y+n.y,bO.z+n.z)};return(e,t,n,r,a,o)=>{i(e,t,n),i(r,a,o)}}function CO(e,t,n,r,i=Math.PI*2,a=0){let o=e=>{let i=Math.cos(e)*t,a=Math.sin(e)*t;return n===`xy`?[i,a,r]:n===`xz`?[i,r,a]:[r,i,a]},s=Math.max(3,Math.round(yO*i/(Math.PI*2)));for(let t=0;t<s;t++){let[n,r,c]=o(a+i*t/s),[l,u,d]=o(a+i*(t+1)/s);e(n,r,c,l,u,d)}}function wO(e,t,n){let r=e=>[t[e*3],t[e*3+1],t[e*3+2]];if(n){for(let t=0;t<n.length;t+=3){let i=r(n[t]),a=r(n[t+1]),o=r(n[t+2]);e(...i,...a),e(...a,...o),e(...o,...i)}return}for(let n=0;n+5<t.length;n+=9){let t=r(n/3),i=r(n/3+1),a=r(n/3+2);e(...t,...i),e(...i,...a),e(...a,...t)}}function TO(e,t){let{nrows:n,ncols:r,heights:i,scale:a}=t,o=n+1,s=r+1,c=(e,t)=>[(e/n-.5)*a.x,i[t*o+e]*a.y,(t/r-.5)*a.z];for(let t=0;t<s;t++)for(let n=0;n<o;n++)n+1<o&&e(...c(n,t),...c(n+1,t)),t+1<s&&e(...c(n,t),...c(n,t+1))}function EO(e,t){let n=SO(e,t),r=e.shape;switch(e.shape.type){case 0:{let e=r.radius;CO(n,e,`xy`,0),CO(n,e,`xz`,0),CO(n,e,`yz`,0);return}case 1:{let e=r.halfExtents;for(let[t,r]of[[-1,-1],[-1,1],[1,-1],[1,1]])n(-e.x,t*e.y,r*e.z,e.x,t*e.y,r*e.z);for(let[t,r]of[[-1,-1],[-1,1],[1,-1],[1,1]])n(t*e.x,-e.y,r*e.z,t*e.x,e.y,r*e.z);for(let[t,r]of[[-1,-1],[-1,1],[1,-1],[1,1]])n(t*e.x,r*e.y,-e.z,t*e.x,r*e.y,e.z);return}case 2:{let{radius:e,halfHeight:t}=r;for(let r of[-1,1]){CO(n,e,`xz`,r*t);for(let i of[`xy`,`yz`])CO((e,i,a,o,s,c)=>n(e,i+r*t,a,o,s+r*t,c),e,i,0,Math.PI,r>0?0:Math.PI)}for(let[r,i]of[[1,0],[-1,0],[0,1],[0,-1]])n(r*e,-t,i*e,r*e,t,i*e);return}case 3:{let e=r;n(e.a.x,e.a.y,e.a.z,e.b.x,e.b.y,e.b.z);return}case 6:case 9:case 16:{let e=r;wO(n,e.vertices,e.indices);return}case 7:TO(n,r);return;case 10:case 14:{let{radius:e,halfHeight:t}=r;CO(n,e,`xz`,-t),CO(n,e,`xz`,t);for(let[r,i]of[[1,0],[-1,0],[0,1],[0,-1]])n(r*e,-t,i*e,r*e,t,i*e);return}case 11:case 15:{let{radius:e,halfHeight:t}=r;CO(n,e,`xz`,-t);for(let r=0;r<4;r++){let i=r/4*Math.PI*2;n(Math.cos(i)*e,-t,Math.sin(i)*e,0,t,0)}return}default:if(e.shape.type===12||e.shape.type===13){let e=r.halfExtents;e&&n(-e.x,-e.y,-e.z,e.x,e.y,e.z)}return}}var DO=Math.PI/180;async function OO(e,t){let n=await Bg(()=>import(`./rapier-DE6a0vmv.js`),[],import.meta.url);return await Ib(()=>n.init()),new kO(n,e,t)}var kO=class{R;engine;debugDraw=!1;debugScope=null;dimension=`3d`;unregisterDebug;warnedNoCollider=new WeakSet;entries=new Map;byColliderHandle=new Map;world;events;kcc;disconnectScene;disconnect;lastDt=1/60;optsGravity;lastScene=null;constructor(e,t,n){this.R=e,this.engine=t,this.optsGravity=n?.gravity,this.simulate=n?.simulate??!0,this.lastScene=t.scene;let r=t.scene?.physics?.gravity,i=n?.gravity??r??[0,-9.81,0];this.world=new e.World({x:i[0]??0,y:i[1]??0,z:i[2]??0}),this.kcc=this.world.createCharacterController(.01),this.events=new e.EventQueue(!0),this.unregisterDebug=Nb(this),this.disconnect=t.fixedUpdated.connect(e=>this.step(e)),this.disconnectScene=t.sceneChanged.connect(()=>{t.scene&&this.syncBodies()}),this.syncBodies()}simulate;step(e){if(this.lastDt=e,!this.simulate){this.syncBodies(),this.poseFromTree();return}if(this.engine.scene!==this.lastScene&&(this.lastScene=this.engine.scene,!this.optsGravity)){let e=this.engine.scene?.physics?.gravity??[0,-9.81,0];this.world.gravity={x:e[0]??0,y:e[1]??0,z:e[2]??0}}this.syncBodies(),this.world.timestep=e,this.world.step(this.events);for(let[e,t]of this.entries){let n=t.body.translation();if(!t.body.isFixed()&&!(e instanceof ev)){let[t,r,i]=YO(e),a=[n.x-t,n.y-r,n.z-i];e._interpPrev=e._interpCurr??a,e._interpCurr=a;let o=e.position;o[0]=a[0],o[1]=a[1],o[2]=a[2]}if(e instanceof tv){if(!e.fixedRotation){let n=t.body.rotation();jO.setFromQuaternion(AO.set(n.x,n.y,n.z,n.w),`XYZ`);let r=e.rotation;r[0]=jO.x/DO,r[1]=jO.y/DO,r[2]=jO.z/DO,t.lastRot[0]=r[0],t.lastRot[1]=r[1],t.lastRot[2]=r[2]}let n=t.body.linvel(),r=e.linearVelocity;r[0]=n.x,r[1]=n.y,r[2]=n.z,t.lastV[0]=n.x,t.lastV[1]=n.y,t.lastV[2]=n.z}let r=t.body.translation();t.last[0]=r.x,t.last[1]=r.y,t.last[2]=r.z}this.events.drainCollisionEvents((e,t,n)=>{let r=this.byColliderHandle.get(e),i=this.byColliderHandle.get(t);if(!r||!i)return;let a=n?`triggerEnter`:`triggerExit`;try{r.emit(a,i),i.emit(a,r)}catch(e){Nt(this.engine,`error`,`incanto: error in a '${a}' handler (${r.name} ↔ ${i.name}):`,e)}})}poseFromTree(){for(let[e,t]of this.entries){let[n,r,i]=qO(e);t.body.setTranslation({x:n,y:r,z:i},!1),AO.setFromEuler(jO.set((e.rotation[0]??0)*DO,(e.rotation[1]??0)*DO,(e.rotation[2]??0)*DO,`XYZ`)),t.body.setRotation({x:AO.x,y:AO.y,z:AO.z,w:AO.w},!1)}this.world.propagateModifiedBodyPositionsToColliders()}moveAndSlide(e){let t=this.ensureEntry(e);if(!t)return;let n=e.velocity[1]??0;e.stickToGround&&n<=0?this.kcc.enableSnapToGround(.1):this.kcc.disableSnapToGround(),this.kcc.setMaxSlopeClimbAngle(e.slopeLimitDeg*DO),e.stepHeight>0?this.kcc.enableAutostep(e.stepHeight,e.stepHeight/2,!1):this.kcc.disableAutostep();let r=0,i=0,a=0;if(t.ground&&t.ground._physics===this&&t.groundAt){let[e,n,o]=qO(t.ground);r=e-t.groundAt[0],i=n-t.groundAt[1],a=o-t.groundAt[2]}else t.ground=null;let o={x:(e.velocity[0]??0)*this.lastDt+r,y:n*this.lastDt+i,z:(e.velocity[2]??0)*this.lastDt+a};this.kcc.computeColliderMovement(t.collider,o,this.R.QueryFilterFlags.EXCLUDE_SENSORS);let s=this.kcc.computedMovement(),c=t.body.translation(),l=c.x+s.x,u=c.y+s.y,d=c.z+s.z;if(t.body.setNextKinematicTranslation({x:l,y:u,z:d}),e._grounded=this.kcc.computedGrounded(),e._grounded){let n=KO(e),r=this.castRay([l,u-n+.05,d],[0,-1,0],.4,e);if(r?.node&&!(r.node instanceof nv)){t.ground=r.node;let e=qO(r.node);t.groundAt=[e[0],e[1],e[2]]}else t.ground=null}else t.ground=null}debugLines(){if(!this.debugDraw)return null;let e=this.debugScope;if(!e)return this.world.debugRender().vertices;let t=this.scopedBodies(e),n=[];for(let e of t)for(let t=0;t<e.numColliders();t++){let r=e.collider(t);r&&EO(r,n)}return new Float32Array(n)}scopedBodies(e){let t=[],n=e=>{let r=this.entries.get(e);r&&t.push(r.body);let i=this.scatterBodies.get(e);i&&t.push(i);for(let t of e.children)n(t)};n(e);for(let n=e.parent;n&&t.length===0;n=n.parent){let e=this.entries.get(n);e&&t.push(e.body)}return t}dispose(){this.disconnect(),this.disconnectScene(),this.unregisterDebug(),this.world.free()}lastStructure=-1;lastRoot=null;jointSet=new Set;joints=new Map;scatterBodies=new Map;bodySet=new Set;syncScatters(e){for(let[,e]of this.scatterBodies)this.world.removeRigidBody(e);this.scatterBodies.clear();let t=new Set;WO(e,t);for(let e of t){let t=e.collider;if(!t)continue;let[n,r,i]=qO(e),a=this.world.createRigidBody(this.R.RigidBodyDesc.fixed().setTranslation(0,0,0)),[o,s,c]=e.size,l=null;for(let u of e.transforms){let d=u[4]??1,f=n+(u[0]??0),p=r+(u[1]??0),m=i+(u[2]??0),h=null;if(t.shape===`sphere`)h=this.R.ColliderDesc.ball(Math.max((t.radius??Math.max(o,c)/2)*d,.01));else if(t.shape===`box`){let e=t.size??[o,s,c];h=this.R.ColliderDesc.cuboid(Math.max((e[0]??1)*d/2,.01),Math.max((e[1]??1)*d/2,.01),Math.max((e[2]??1)*d/2,.01))}else{l??=FO(e.mesh,e.size);let t=new Float32Array(l.length);for(let e=0;e<t.length;e++)t[e]=l[e]*d;h=this.R.ColliderDesc.convexHull(t)}if(!h)continue;h.setTranslation(f,p,m);let g=(u[3]??0)*Math.PI/180;g!==0&&h.setRotation({x:0,y:Math.sin(g/2),z:0,w:Math.cos(g/2)}),this.world.createCollider(h,a)}this.scatterBodies.set(e,a)}}syncBodies(){let e=this.engine.scene;if(!e)return;let t=e.tree._structureVersion,n=e.root===this.lastRoot,r=t!==this.lastStructure||!n;if(r){let r=n?e.tree._structureSince(this.lastStructure):null;if(this.lastStructure=t,this.lastRoot=e.root,r){let t=!1,n=!1;for(let{node:e,added:i}of r)e instanceof Q_&&(i?this.bodySet.add(e):this.bodySet.delete(e)),e instanceof ID&&(t=!0),e instanceof AD&&(n=!0);t&&(this.jointSet.clear(),MO(e.root,this.jointSet)),n&&this.syncScatters(e.root)}else this.bodySet.clear(),NO(e.root,this.bodySet),this.jointSet.clear(),MO(e.root,this.jointSet),this.syncScatters(e.root)}let i=this.bodySet;for(let e of i){if(e.collider.shape===void 0){let t=this.entries.get(e);t&&(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null,e._interpPrev=e._interpCurr=null),this.warnedNoCollider.has(e)||(this.warnedNoCollider.add(e),Nt(this.engine,`warn`,`[incanto] '${e.name}' has no collider — physics skips it.`));continue}let t=this.entries.get(e);t&&e._colliderChanged&&(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null,e._interpPrev=e._interpCurr=null),this.ensureEntry(e)}if(this.syncJoints(r),r)for(let[e,t]of this.entries)i.has(e)||(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null,e._interpPrev=e._interpCurr=null)}ensureEntry(e){let t=this.entries.get(e),n=this.R;if(!t){let r=XO(n,e);if(!r)return null;let i;i=e instanceof tv?n.RigidBodyDesc.dynamic():e instanceof nv||e instanceof ev?n.RigidBodyDesc.kinematicPositionBased():n.RigidBodyDesc.fixed();let[a,o,s]=qO(e);i.setTranslation(a,o,s),AO.setFromEuler(jO.set((e.rotation[0]??0)*DO,(e.rotation[1]??0)*DO,(e.rotation[2]??0)*DO,`XYZ`)),i.setRotation({x:AO.x,y:AO.y,z:AO.z,w:AO.w}),e instanceof tv&&(i.setGravityScale(e.gravityScale),i.setLinvel(e.linearVelocity[0]??0,e.linearVelocity[1]??0,e.linearVelocity[2]??0),e.fixedRotation&&i.lockRotations());let c=this.world.createRigidBody(i);r.setActiveEvents(n.ActiveEvents.COLLISION_EVENTS),r.setActiveCollisionTypes(n.ActiveCollisionTypes.ALL),e instanceof ev&&r.setSensor(!0),e instanceof tv&&r.setMass(e.mass).setFriction(e.friction).setRestitution(e.restitution);let l=this.world.createCollider(r,c);return t={body:c,collider:l,last:[a,o,s],lastRot:[e.rotation[0]??0,e.rotation[1]??0,e.rotation[2]??0],lastV:[0,0,0]},this.entries.set(e,t),this.byColliderHandle.set(l.handle,e),e.enabled||(l.setEnabled(!1),c.setEnabled(!1)),e._colliderChanged=!1,e._enabledChanged=!1,e._physics=this,e instanceof tv&&(e._physics3d=this),t}e._enabledChanged&&=(t.collider.setEnabled(e.enabled),t.body.setEnabled(e.enabled),!1);let r=qO(e);(r[0]!==t.last[0]||r[1]!==t.last[1]||r[2]!==t.last[2])&&(t.body.setTranslation({x:r[0],y:r[1],z:r[2]},!0),t.last[0]=r[0],t.last[1]=r[1],t.last[2]=r[2],e._interpPrev=e._interpCurr=null);let i=e.rotation[0]??0,a=e.rotation[1]??0,o=e.rotation[2]??0;if((i!==t.lastRot[0]||a!==t.lastRot[1]||o!==t.lastRot[2])&&(AO.setFromEuler(jO.set(i*DO,a*DO,o*DO,`XYZ`)),t.body.setRotation({x:AO.x,y:AO.y,z:AO.z,w:AO.w},!0),t.lastRot[0]=i,t.lastRot[1]=a,t.lastRot[2]=o),e instanceof tv){let n=[e.linearVelocity[0]??0,e.linearVelocity[1]??0,e.linearVelocity[2]??0];(n[0]!==t.lastV[0]||n[1]!==t.lastV[1]||n[2]!==t.lastV[2])&&(t.body.setLinvel({x:n[0],y:n[1],z:n[2]},!0),t.lastV=n),e.gravityScale!==t.body.gravityScale()&&t.body.setGravityScale(e.gravityScale,!0)}return t}applyImpulse(e,t){this.entries.get(e)?.body.applyImpulse({x:t[0],y:t[1],z:t[2]},!0)}massOf(e){return this.entries.get(e)?.body.mass()??1}velocityOf(e){let t=this.entries.get(e)?.body.linvel();return t?[t.x,t.y,t.z]:[0,0,0]}syncJoints(e){let t=this.R;if(e)for(let[e,t]of this.joints)this.jointSet.has(e)||(this.world.removeImpulseJoint(t,!0),this.joints.delete(e));for(let e of this.jointSet){if(this.joints.has(e))continue;let{a:n,b:r}=e._resolveBodies(),i=this.entries.get(n),a=this.entries.get(r);if(!i||!a)continue;let o={x:e.anchor[0]??0,y:e.anchor[1]??0,z:e.anchor[2]??0},s={x:e.targetAnchor[0]??0,y:e.targetAnchor[1]??0,z:e.targetAnchor[2]??0},c=e.length;if(e.length===0&&(e.type===`rope`||e.type===`spring`)){let e=i.body.translation(),t=a.body.translation();c=Math.hypot(t.x-e.x,t.y-e.y,t.z-e.z)}let l={x:0,y:0,z:0,w:1},u;u=e.type===`fixed`?t.JointData.fixed(o,l,s,l):e.type===`rope`?t.JointData.rope(c,o,s):e.type===`spring`?t.JointData.spring(c,e.stiffness,e.damping,o,s):t.JointData.spherical(o,s),this.joints.set(e,this.world.createImpulseJoint(u,i.body,a.body,!0))}}castRay(e,t,n,r,i){let a=new this.R.Ray({x:e[0],y:e[1],z:e[2]},{x:t[0],y:t[1],z:t[2]}),o=r?this.entries.get(r)?.collider:void 0,s=i?.staticOnly?this.R.QueryFilterFlags.EXCLUDE_DYNAMIC|this.R.QueryFilterFlags.EXCLUDE_KINEMATIC:void 0,c=this.world.castRayAndGetNormal(a,n,!0,s,void 0,o,void 0,e=>!e.isSensor());return c?{distance:c.timeOfImpact,normal:[c.normal.x,c.normal.y,c.normal.z],node:this.byColliderHandle.get(c.collider.handle)??null}:null}castSphere(e,t,n,r,i,a){let o=this.R,s=i?this.entries.get(i):void 0,c=a?.staticOnly?o.QueryFilterFlags.EXCLUDE_DYNAMIC|o.QueryFilterFlags.EXCLUDE_KINEMATIC:void 0,l=this.world.castShape({x:e[0],y:e[1],z:e[2]},{x:0,y:0,z:0,w:1},{x:t[0],y:t[1],z:t[2]},new o.Ball(n),0,r,!0,c,void 0,s?.collider,s?.body,e=>!e.isSensor());return l?{distance:l.time_of_impact,node:this.byColliderHandle.get(l.collider.handle)??null}:null}},AO=new U,jO=new cc;function MO(e,t){e instanceof ID&&t.add(e);for(let n of e.children)MO(n,t)}function NO(e,t){e instanceof Q_&&t.add(e);for(let n of e.children)NO(n,t)}function PO(e,t,n,r,i){let a=r[0]??1,o=r[1]??1,s=r[2]??1,c=(n[0]??1)*a,l=(n[1]??1)*o,u=(n[2]??1)*s,d=Math.max(Math.abs(a),Math.abs(s));switch(i&&t!==`box`&&t!==`plane`&&Math.abs(a-s)>1e-6&&console.warn(`[incanto] Collider on '${i}': shape 'auto' fits a ${t} to a mesh scaled [${a}, ${o}, ${s}]. A ${t} has one radius, so the widest of x/z (${d}) is used. Use a box, or scale x and z the same.`),t){case`box`:return e.ColliderDesc.cuboid(c/2,l/2,u/2);case`sphere`:return e.ColliderDesc.ball((n[0]??1)*Math.max(d,Math.abs(o)));case`capsule`:return e.ColliderDesc.capsule(l/2,(n[0]??1)*d);case`cylinder`:return e.ColliderDesc.cylinder(l/2,(n[0]??1)*d);case`plane`:return e.ColliderDesc.cuboid(c/2,.01,u/2);default:return e.ColliderDesc.convexHull(FO(t,[c,l,u]))}}function FO(e,t){let n=kD(e,t),r=n.getAttribute(`position`),i=new Float32Array(r.count*3);for(let e=0;e<r.count;e++)i[e*3]=r.getX(e),i[e*3+1]=r.getY(e),i[e*3+2]=r.getZ(e);return n.dispose(),i}function IO(e){return typeof e._mountedObject3D==`function`}var LO=new K,RO=new K,zO=new W;function BO(e,t){let n=t._mountedObject3D();if(!n)return null;let r=e._ensureObject3D();r.updateWorldMatrix(!0,!0),LO.copy(r.matrixWorld).invert();let i=[],a=[];return n.traverse(e=>{let t=e;if(!t.isMesh)return;let n=t.geometry?.getAttribute(`position`);if(!n)return;RO.multiplyMatrices(LO,t.matrixWorld);let r=i.length/3;for(let e=0;e<n.count;e++)zO.set(n.getX(e),n.getY(e),n.getZ(e)).applyMatrix4(RO),i.push(zO.x,zO.y,zO.z);let o=t.geometry.getIndex();if(o)for(let e=0;e<o.count;e++)a.push(r+o.getX(e));else for(let e=0;e<n.count;e++)a.push(r+e)}),a.length<3?null:{vertices:new Float32Array(i),indices:new Uint32Array(a),triangles:a.length/3}}var VO=2e4;function HO(e){return!(e instanceof tv||e instanceof nv)}function UO(e,t,n,r=[0,0,0],i=[0,0,0],a=[1,1,1]){if(IO(e))n.push(e);else{let n=e;typeof n.mesh==`string`&&Array.isArray(n.size)&&t.push({name:e.name,mesh:n.mesh,size:n.size,at:[...r],turn:[...i],scale:[...a]})}for(let o of e.children){let e=o,s=Array.isArray(e.position)?e.position:[],c=Array.isArray(e.rotation)?e.rotation:[],l=Array.isArray(e.scale)?e.scale:[];UO(o,t,n,[r[0]+(s[0]??0)*a[0],r[1]+(s[1]??0)*a[1],r[2]+(s[2]??0)*a[2]],[i[0]+(c[0]??0),i[1]+(c[1]??0),i[2]+(c[2]??0)],[a[0]*(l[0]??1),a[1]*(l[1]??1),a[2]*(l[2]??1)])}}function WO(e,t){e instanceof AD&&e.collider&&t.add(e);for(let n of e.children)WO(n,t)}var GO=[0,0,0];function KO(e){let t=e.collider;return t?t.shape===`capsule`&&typeof t.height==`number`?t.height/2+(t.radius??0):t.shape===`box`&&Array.isArray(t.size)?(t.size[1]??2)/2:t.shape===`sphere`&&typeof t.radius==`number`?t.radius:1:1}function qO(e){let t=0,n=0,r=0;for(let i=e;i;i=i.parent)i instanceof Z_&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return GO[0]=t,GO[1]=n,GO[2]=r,GO}var JO=[0,0,0];function YO(e){let t=0,n=0,r=0;for(let i=e.parent;i;i=i.parent)i instanceof Z_&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return JO[0]=t,JO[1]=n,JO[2]=r,JO}function XO(e,t){let n=t.collider;if(Y_(n,t.name),n.shape===`heightfield`)return ZO(e,t);let r=QO(e,n,t.name,t);if(!r)return null;let i=n.offset;if(Array.isArray(i)){let e=r.translation;r.setTranslation(e.x+(i[0]??0),e.y+(i[1]??0),e.z+(i[2]??0))}return r}function ZO(e,t){let n=t.children.find(e=>e instanceof hO);if(!n)throw new L(`BAD_FORMAT`,`Collider on '${t.name}': heightfield needs a Terrain3D CHILD of this body — add { "type": "Terrain3D" } under the StaticBody3D; the collider reads its height grid.`,{prop:`collider`});let r=n._heightmap(),i=r.segsZ,a=r.segsX,o=new Float32Array((i+1)*(a+1));for(let e=0;e<=a;e++)for(let t=0;t<=i;t++)o[e*(i+1)+t]=r.heights[t*(a+1)+e];let s=e.ColliderDesc.heightfield(i,a,o,{x:r.width,y:1,z:r.depth}),c=Array.isArray(t.collider.offset)?t.collider.offset:[];return s.setTranslation((n.position[0]??0)+(c[0]??0),(n.position[1]??0)+(c[1]??0),(n.position[2]??0)+(c[2]??0)),s}function QO(e,t,n,r){let i=t.shape;if(i===`box`){let r=t.size;if(!Array.isArray(r)||r.length!==3||r.some(e=>typeof e!=`number`))throw new L(`BAD_FORMAT`,`Collider on '${n}': box needs "size": [x, y, z].`);return e.ColliderDesc.cuboid(r[0]/2,r[1]/2,r[2]/2)}if(i===`sphere`){if(typeof t.radius!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${n}': sphere needs "radius".`);return e.ColliderDesc.ball(t.radius)}if(i===`capsule`){if(typeof t.radius!=`number`||typeof t.height!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${n}': capsule needs "radius" and "height".`);return e.ColliderDesc.capsule(t.height/2,t.radius)}if(i===`auto`){let t=[],i=[];r&&UO(r,t,i);let a=t[0],o=i[0];if(!a&&!o)throw new L(`BAD_FORMAT`,`Collider on '${n}': shape 'auto' needs a MeshInstance3D or ModelInstance3D on the body (or as a child) to take its shape from.`);let s=t.length+i.length;if(s>1&&console.warn(`[incanto] Collider on '${n}': shape 'auto' fits ONE mesh and took '${(a??o)?.name}'; ${s-1} other mesh(es) here are not solid. Give each part its own body.`),a){let t=PO(e,a.mesh,a.size,a.scale,n);if(t)return t.setTranslation(a.at[0],a.at[1],a.at[2]),(a.turn[0]!==0||a.turn[1]!==0||a.turn[2]!==0)&&(AO.setFromEuler(jO.set(a.turn[0]*DO,a.turn[1]*DO,a.turn[2]*DO,`XYZ`)),t.setRotation({x:AO.x,y:AO.y,z:AO.z,w:AO.w})),t}else if(o&&r){let t=BO(r,o);return t?HO(r)?(t.triangles>VO&&console.warn(`[incanto] Collider on '${n}': shape 'auto' built a ${t.triangles}-triangle mesh from '${o.name}'. Consider a low-poly collision model or an explicit box.`),e.ColliderDesc.trimesh(t.vertices,t.indices)):e.ColliderDesc.convexHull(t.vertices):null}}if(i===`trimesh`){let r=t.vertices,i=t.indices;if(!Array.isArray(r)||!Array.isArray(i))throw new L(`BAD_FORMAT`,`Collider on '${n}': trimesh needs "vertices" (flat xyz) and "indices" (triangles).`);return e.ColliderDesc.trimesh(new Float32Array(r),new Uint32Array(i))}throw new L(`BAD_FORMAT`,`Collider on '${n}': "shape" must be 'auto', 'box', 'sphere', 'capsule', 'trimesh', or 'heightfield', got ${JSON.stringify(i)}.`)}var $O=new _d(1,1),ek=null;function tk(){if(ek)return ek;if(typeof document>`u`)return null;let e=document.createElement(`canvas`);e.width=64,e.height=64;let t=e.getContext(`2d`);if(!t)return null;let n=t.createRadialGradient(32,32,0,32,32,31);return n.addColorStop(0,`rgba(0,0,0,0.55)`),n.addColorStop(.55,`rgba(0,0,0,0.34)`),n.addColorStop(1,`rgba(0,0,0,0)`),t.fillStyle=n,t.fillRect(0,0,64,64),ek=new sd(e),ek}var nk=new W(0,0,1),rk=new W,ik=new W,ak=new U,ok=new U,sk=new W,ck=.5,lk=class extends Z_{static typeName=`Sprite3D`;static props={texture:{default:``},size:{default:[1,1]},billboard:{default:`y`,options:[`y`,`full`,`none`]},anchor:{default:[.5,0]},tint:{default:`#ffffff`},opacity:{default:1},flipX:{default:!1},pixelArt:{default:!0},alphaTest:{default:.5},castShadow:{default:!1},shadowMode:{default:`silhouette`,options:[`silhouette`,`blob`]}};texture=``;size=[1,1];billboard=`y`;anchor=[.5,0];tint=`#ffffff`;opacity=1;flipX=!1;pixelArt=!0;alphaTest=.5;castShadow=!1;shadowMode=`silhouette`;quadMesh=null;textureRef=``;loadedTexture=null;shadowMesh=null;blobMesh=null;_quad(){return this.quadMesh||(this.quadMesh=new iu($O,new Kl({transparent:!1,depthWrite:!0,side:2})),this._ensureObject3D().add(this.quadMesh)),this.quadMesh}resolveTexture(e){return this.texture?(this.textureRef!==this.texture&&(this.textureRef=this.texture,this.loadedTexture=uD(e,this.texture,{filter:this.pixelArt?`nearest`:`linear`})),this.loadedTexture):null}_syncObject3D(e=1,t=null){super._syncObject3D(e,t);let n=this._quad(),r=n.material,i=this.size[0]??1,a=this.size[1]??1;n.scale.set(this.flipX?-i:i,a,1);let o=this.anchor[0]??.5,s=this.anchor[1]??0;n.position.set((.5-o)*i,(.5-s)*a,0);let c=this.resolveTexture(t);r.map!==c&&(r.map=c,r.needsUpdate=!0),n.visible=c!==null,r.color.set(this.tint),r.opacity=this.opacity,r.transparent=this.opacity<1,r.alphaTest=this.alphaTest,n.renderOrder=this.renderOrder;let l=this.castShadow&&c!==null;if(n.castShadow=!1,l&&this.shadowMode===`silhouette`){let e=this._shadowCaster();e.visible=!0,e.castShadow=!0,e.scale.set(this.flipX?-i:i,a,1),e.position.set((.5-o)*i,(.5-s)*a,0);let t=e.material;t.map!==c&&(t.map=c,t.needsUpdate=!0);let n=e.customDepthMaterial;n.map!==c&&(n.map=c,n.needsUpdate=!0),t.alphaTest=this.alphaTest,n.alphaTest=this.alphaTest}else this.shadowMesh&&(this.shadowMesh.visible=!1,this.shadowMesh.castShadow=!1);if(l&&this.shadowMode===`blob`){let e=this._blob();e.visible=!0,e.scale.set(i*.52,i*.52,1)}else this.blobMesh&&(this.blobMesh.visible=!1)}_shadowCaster(){return this.shadowMesh||(this.shadowMesh=new iu($O,new Kl({colorWrite:!1,depthWrite:!1,side:2})),this.shadowMesh.customDepthMaterial=new jd({depthPacking:Lo,side:2}),this._ensureObject3D().add(this.shadowMesh)),this.shadowMesh}_blob(){return this.blobMesh||(this.blobMesh=new iu($O,new Kl({map:tk(),color:0,transparent:!0,depthWrite:!1})),this.blobMesh.rotation.x=-Math.PI/2,this.blobMesh.position.y=.02,this.blobMesh.renderOrder=-1,this._ensureObject3D().add(this.blobMesh)),this.blobMesh}_onRender3D(e){this.billboard===`y`?(e.camera.getWorldDirection(ik),ik.y=0,ik.lengthSq()>=1e-6&&this._faceDir(this._quad(),ik.negate())):this.billboard===`full`&&this._faceToward(this._quad(),e.camera.position);let t=this.shadowMesh;t?.castShadow&&e.sunDir&&(this._faceDir(t,e.sunDir),t.parent?.getWorldQuaternion(ok),sk.copy(e.sunDir).applyQuaternion(ok.invert()),t.position.addScaledVector(sk,ck))}_faceToward(e,t){e.getWorldPosition(rk),ik.copy(t).sub(rk),this.billboard===`y`&&(ik.y=0),!(ik.lengthSq()<1e-12)&&(ik.normalize(),ak.setFromUnitVectors(nk,ik),e.parent?.getWorldQuaternion(ok),e.quaternion.copy(ok.invert()).multiply(ak))}_faceDir(e,t){ik.copy(t),this.billboard===`y`&&(ik.y=0),!(ik.lengthSq()<1e-12)&&(ik.normalize(),ak.setFromUnitVectors(nk,ik),e.parent?.getWorldQuaternion(ok),e.quaternion.copy(ok.invert()).multiply(ak))}free(){this.loadedTexture?.dispose(),this.loadedTexture=null,this.shadowMesh&&(this.shadowMesh.material.dispose(),this.shadowMesh.customDepthMaterial?.dispose()),this.blobMesh&&this.blobMesh.material.dispose(),super.free()}},uk=class extends lk{static typeName=`AnimatedSprite3D`;static signals=[`animationFinished`];static props={sheet:{default:``},frameWidth:{default:0},frameHeight:{default:0},animations:{default:{}},autoplay:{default:``}};sheet=``;frameWidth=0;frameHeight=0;animations={};autoplay=``;playing=!1;currentFrame=0;currentAnimation=``;frameList=[];frameIndex=0;frameTime=0;currentDef=null;sheetTexture=null;loadedSheetRef=``;play(e){let{name:t,def:n}=Zi(this.animations,e,this.name);this.currentAnimation=t,this.currentDef=n,this.frameList=$i(n.frames,t),this.frameIndex=0,this.currentFrame=this.frameList[0]??0,this.frameTime=0,this.playing=!0}stop(){this.playing=!1}onReady(){Qi(this.animations,this.name),this.autoplay&&this.play(this.autoplay)}update(e){if(!this.playing||this.currentAnimation===``)return;let t=this.currentDef;if(!t||!Number.isFinite(t.fps)||t.fps<=0)return;let n=1/t.fps;for(this.frameTime+=e;this.frameTime>=n;)if(this.frameTime-=n,this.frameIndex+=1,this.frameIndex>=this.frameList.length)if(t.loop)this.frameIndex=0;else{this.frameIndex=this.frameList.length-1,this.playing=!1,this.emit(`animationFinished`,this.currentAnimation);break}this.currentFrame=this.frameList[this.frameIndex]??0}checkGrid(e,t){if(this.gridChecked===this.sheet)return;this.gridChecked=this.sheet;let n=0;for(let[e,t]of Object.entries(this.animations))if(typeof t!=`string`)try{for(let r of $i(t.frames,e))r>n&&(n=r)}catch{return}let r=Qb(this.sheet,this.frameWidth,this.frameHeight,e,t,n);r&&Nt(this.tree?.engine??null,`error`,r)}gridChecked=``;sizeReported=!1;resolveTexture(e){if(!this.sheet)return null;if(this.frameWidth<=0||this.frameHeight<=0)return this.sizeReported||(this.sizeReported=!0,Nt(this.tree?.engine??null,`error`,`[incanto] AnimatedSprite3D '${this.name}' has a sheet ('${this.sheet}') but frameWidth/frameHeight are 0 — it draws nothing. Set both to one frame's pixel size (bunx incanto-assets info <name> prints it for a built-in).`)),null;this.loadedSheetRef!==this.sheet&&(this.sheetTexture?.dispose(),this.loadedSheetRef=this.sheet,this.sheetTexture=dD(e,this.sheet,{filter:this.pixelArt?`nearest`:`linear`}));let t=this.sheetTexture;if(!t)return null;let n=t.image;if(!n?.width||!n.height)return t;this.checkGrid(n.width,n.height);let r=Math.max(1,Math.floor(n.width/this.frameWidth)),i=this.currentFrame%r,a=Math.floor(this.currentFrame/r);return t.repeat.set(this.frameWidth/n.width,this.frameHeight/n.height),t.offset.set(i*this.frameWidth/n.width,1-(a+1)*this.frameHeight/n.height),t}free(){this.sheetTexture?.dispose(),this.sheetTexture=null,super.free()}},dk=new U,fk=new U,pk=new W,mk=new W(0,0,1),hk=[`screen`,`y`,`none`],gk=class extends Z_{static typeName=`Billboard3D`;static props={mode:{default:`screen`,options:hk}};mode=`screen`;_lastDesired=null;static validateJson(e){let t=e;if(!hk.includes(t.mode))throw new L(`BAD_FORMAT`,`Billboard3D '${e.name}' mode must be one of [${hk.join(`, `)}], got '${t.mode}'.`,{prop:`mode`,validOptions:hk})}_onRender3D(e){if(this.mode===`none`)return;let t=this._ensureObject3D();if(this.mode===`screen`)e.camera.getWorldQuaternion(fk);else if(e.camera.getWorldDirection(pk),pk.y=0,pk.lengthSq()>=1e-6)fk.setFromUnitVectors(mk,pk.negate().normalize());else if(this._lastDesired)fk.copy(this._lastDesired);else return;this._lastDesired||=new U,this._lastDesired.copy(fk),t.parent?.getWorldQuaternion(dk),t.parent?t.quaternion.copy(dk.invert()).multiply(fk):t.quaternion.copy(fk)}},_k=class extends Z_{static typeName=`BoneAttachment3D`;static props={target:{default:``,nodePath:!0,required:!0},bone:{default:``}};target=``;bone=``;boneObj=null;lookedUpFor=``;get attachedBone(){return this.boneObj}_onRender3D(e){if(this.target===``||this.bone===``)return;let t=`${this.target} ${this.bone}`;if(this.lookedUpFor!==t||this.boneObj===null||!this.boneObj.parent){this.lookedUpFor=t,this.boneObj=null;let e=this.getNodeOrNull(this.target);this.source=e,e&&typeof e.findBone==`function`&&(this.boneObj=e.findBone(this.bone))}let n=this.boneObj;if(!n){this.reportMissingBone();return}let r=this._ensureObject3D(),i=r.parent;i&&(n.updateWorldMatrix(!0,!1),i.updateWorldMatrix(!0,!1),r.matrixAutoUpdate=!1,n.matrixWorld.decompose(bk,xk,Sk),yk.compose(bk,xk,Ck),r.updateMatrix(),vk.copy(r.matrix),r.matrix.copy(i.matrixWorld).invert().multiply(yk).multiply(vk))}free(){this.boneObj=null,super.free()}source=null;reportedBone=``;reportMissingBone(){if(this.reportedBone===this.bone)return;let e=this.source?.boneNames?.()??[];if(e.length===0)return;this.reportedBone=this.bone;let t=e.slice(0,8).join(`, `);Nt(this.tree?.engine??null,`error`,`[incanto] ${this.getPath()}: '${this.target}' has no bone '${this.bone}'. It has ${e.length}: [${t}${e.length>8?`, …`:``}].`)}},vk=new K,yk=new K,bk=new W,xk=new U,Sk=new W,Ck=new W(1,1,1),wk=class extends Z_{static typeName=`BoneLookAt3D`;static props={target:{default:``,nodePath:!0,required:!0},bone:{default:`Head`},lookAt:{default:``,nodePath:!0},maxAngleDeg:{default:75},weight:{default:.85,range:{min:0,max:1}},forwardAxis:{default:`+z`,options:[`+x`,`-x`,`+y`,`-y`,`+z`,`-z`]}};target=``;bone=`Head`;lookAt=``;maxAngleDeg=75;weight=.85;forwardAxis=`+z`;boneObj=null;lookedUpFor=``;engage=0;get attachedBone(){return this.boneObj}_onRender3D(e){if(this.target===``||this.bone===``)return;let t=`${this.target} ${this.bone}`;if(this.lookedUpFor!==t||this.boneObj===null||!this.boneObj.parent){this.lookedUpFor=t,this.boneObj=null;let e=this.getNodeOrNull(this.target);e&&typeof e.findBone==`function`&&(this.boneObj=e.findBone(this.bone))}let n=this.boneObj;if(!n?.parent)return;let r=this.lookAt===``?null:this.getNodeOrNull(this.lookAt),i=!1;if(r&&Array.isArray(r.position)&&(n.updateWorldMatrix(!0,!1),n.getWorldPosition(Ak),jk.set(r.position[0]??0,r.position[1]??0,r.position[2]??0),Mk.copy(jk).sub(Ak),Mk.lengthSq()>1e-6&&(Mk.normalize(),Nk.copy(Ek[this.forwardAxis]??Ok),Pk.copy(Nk).applyQuaternion(n.getWorldQuaternion(zk)),Pk.angleTo(Mk)<this.maxAngleDeg*Math.PI/180))){i=!0,Fk.lookAt(Ak,jk,Dk),Ik.setFromRotationMatrix(Fk),Lk.setFromUnitVectors(Nk,kk),Ik.multiply(Lk),n.parent.getWorldQuaternion(Rk).invert(),Ik.premultiply(Rk);let e=this.weight*this.engage;n.quaternion.slerp(Ik,e)}this.engage+=(+!!i-this.engage)*Tk}},Tk=.18,Ek={"+x":new W(1,0,0),"-x":new W(-1,0,0),"+y":new W(0,1,0),"-y":new W(0,-1,0),"+z":new W(0,0,1),"-z":new W(0,0,-1)},Dk=new W(0,1,0),Ok=new W(0,0,1),kk=new W(0,0,-1),Ak=new W,jk=new W,Mk=new W,Nk=new W,Pk=new W,Fk=new K,Ik=new U,Lk=new U,Rk=new U,zk=new U,Bk=class extends Z_{static typeName=`Camera3D`;static props={fov:{default:60},near:{default:.1},far:{default:1e3},current:{default:!1}};fov=60;near=.1;far=1e3;current=!1;_createObject3D(){return new Cf(this.fov,1,this.near,this.far)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();(e.fov!==this.fov||e.near!==this.near||e.far!==this.far)&&(e.fov=this.fov,e.near=this.near,e.far=this.far,e.updateProjectionMatrix())}},Vk=8,Hk=.15,Uk=1.2,Wk=.08,Gk=-20;function Kk(e){let t=aA.props[e];return typeof t?.default==`string`?t.default:``}var qk=.002,Jk=180/Math.PI,Yk=.3,Xk=.4,Zk=.3,Qk=.25,$k=new cc,eA=new U,tA=new K,nA=new W,rA=new W,iA=new W(0,1,0),aA=class extends Z_{static typeName=`CharacterController3D`;static signals=[`movementStateChanged`];static props={view:{default:`free`,options:[`free`,`firstPerson`,`quarter`,`side`]},camDistance:{default:4},eyeHeight:{default:.64},maxSpeed:{default:2.5},sprintMultiplier:{default:2},jumpVelocity:{default:4},sprintJumpMultiplier:{default:1.2},coyoteSeconds:{default:0},jumpBufferSeconds:{default:0},jumpCutMultiplier:{default:1},maxJumps:{default:1},airControl:{default:.2},fallGravity:{default:2.5},floatHeight:{default:.01},mouseLook:{default:!0},zoomMin:{default:0},zoomMax:{default:0},pitchMin:{default:-1.3},pitchMax:{default:1.5},cameraCollision:{default:!0},turnSpeed:{default:100},camLerp:{default:25},moveAction:{default:`move`},jumpAction:{default:`jump`},sprintAction:{default:`sprint`},skinPath:{default:`../Skin`,nodePath:!0},skinYawOffset:{default:0},animations:{default:{}}};view=`free`;camDistance=4;eyeHeight=.64;maxSpeed=2.5;sprintMultiplier=2;jumpVelocity=4;sprintJumpMultiplier=1.2;coyoteSeconds=0;jumpBufferSeconds=0;jumpCutMultiplier=1;maxJumps=1;airControl=.2;fallGravity=2.5;floatHeight=.01;mouseLook=!0;zoomMin=0;zoomMax=0;pitchMin=-1.3;pitchMax=1.5;cameraCollision=!0;turnSpeed=100;camLerp=25;moveAction=`move`;jumpAction=`jump`;sprintAction=`sprint`;skinPath=`../Skin`;skinYawOffset=0;animations={};yaw=0;pitch=0;state=`idle`;grounded=!1;coyoteLeft=0;bufferLeft=0;jumpsUsed=0;rising=!1;jumping=!1;get body(){let e=this.parent;if(!(e instanceof tv))throw new L(`TREE_VIOLATION`,`CharacterController3D '${this.name}' must be a child of a RigidBody3D (parent is '${e?.name??`none`}').`);return e}onEnterTree(){if(this.body,this.skinPath!==``){let e=this.getNodeOrNull(this.skinPath);e&&(e.rotation=[e.rotation[0]??0,180+this.skinYawOffset,e.rotation[2]??0])}}fixedUpdate(e){let t=this.body,n=t._physics3d,r=this.tree?.engine?.input;if(!n||!r)return;let i=t.collider.radius??.32,a=(t.collider.height??1)/2,o=sA(t),s=n.velocityOf(t),c=n.massOf(t),l=i+this.floatHeight,u=i+2,d=o[1]-a,f=null;for(let[e,r]of[[0,0],[i,0],[-i,0],[0,i],[0,-i]]){let i=n.castRay([o[0]+e,d,o[2]+r],[0,-1,0],u,t);if(i){let t=i.distance;if(f=f===null?t:Math.min(f,t),e===0&&r===0)break}}this.grounded=f!==null&&f<l*2;let p=f!==null&&f<l*1.3&&(s[1]??0)<=.5,m=0,h=0,g=!1;try{let e=r.getVector(this.moveAction);g=e.x!==0||e.y!==0;let t=this.view===`free`||this.view===`firstPerson`?this.yaw:0,n=this.view===`side`?[e.x,0,0]:yD(e.x,-e.y,t),i=Math.hypot(n[0],n[2])||1;m=n[0]/i,h=n[2]/i}catch(e){this.reportMissingAction(`moveAction`,e,`The character will not move.`)}let _=this.readAction(`sprintAction`,()=>r.isPressed(this.sprintAction),!1,`Sprint will never engage.`),v=bD(g,_),y=1+(this.sprintMultiplier-1)*v,b=g?this.maxSpeed*y:0,x=this.grounded?1:this.airControl,S=(m*b-s[0])/Vk*x,C=(h*b-s[2])/Vk*x;if(t.applyImpulse([S*c,0,C*c]),!g&&this.grounded&&t.applyImpulse([-s[0]*Hk*c,0,-s[2]*Hk*c]),f!==null&&f<l*2&&!this.jumping){let e=Uk*(l-f)-s[1]*Wk;t.applyImpulse([0,e*c,0])}p?(this.coyoteLeft=this.coyoteSeconds,this.jumpsUsed=0,this.rising=!1,this.jumping=!1):(this.coyoteLeft=Math.max(0,this.coyoteLeft-e),!this.grounded&&this.coyoteLeft<=0&&this.jumpsUsed===0&&(this.jumpsUsed=1));let w=this.readAction(`jumpAction`,()=>r.justPressed(this.jumpAction),!1,`The character will never jump.`);if(w?this.bufferLeft=Math.max(this.jumpBufferSeconds,0):this.bufferLeft=Math.max(0,this.bufferLeft-e),(this.bufferLeft>0||w)&&(p||this.coyoteLeft>0||this.jumpsUsed<this.maxJumps)){let e=this.jumpVelocity*(1+(this.sprintJumpMultiplier-1)*v);t.linearVelocity=[s[0],e,s[2]],this.grounded=!1,this.jumpsUsed+=1,this.bufferLeft=0,this.coyoteLeft=0,this.rising=!0,this.jumping=!0,s[1]=e}if(this.rising){if((s[1]??0)<=0)this.rising=!1;else if(this.jumpCutMultiplier<1&&!this.readAction(`jumpAction`,()=>r.isPressed(this.jumpAction),!1,`The character will never jump.`)){let e=(s[1]??0)*this.jumpCutMultiplier;t.linearVelocity=[s[0],e,s[2]],s[1]=e,this.rising=!1}}(s[1]??0)<Gk?t.gravityScale=0:(s[1]??0)<0&&!p?t.gravityScale=this.fallGravity:t.gravityScale=1,this.view===`side`&&Math.abs(o[2])>.01&&(t.position=[t.position[0]??0,t.position[1]??0,0]);let T=xD(!(this.jumping||!this.grounded),g?v:0);if(T!==this.state){this.state=T;let e=this.animations[T];if(e&&this.skinPath!==``){let t=this.getNodeOrNull(this.skinPath);t&&`animation`in t&&(t.animation=e)}this.emit(`movementStateChanged`,T)}if(g&&this.skinPath!==``){let t=this.getNodeOrNull(this.skinPath);if(t){let n=Math.atan2(m,h)*Jk+this.skinYawOffset,r=t.rotation[1]??0,i=(n-r+540)%360-180,a=this.turnSpeed*e*Jk;Math.abs(i)>a&&(i=Math.sign(i)*a),t.rotation=[t.rotation[0]??0,r+i,t.rotation[2]??0]}}}reportedActions=new Set;readAction(e,t,n,r){let i=this[e];return Yy({engine:this.tree?.engine,who:this.getPath(),reported:this.reportedActions,consequence:r,authored:i!==Kk(e)},i,t,n)}reportMissingAction(e,t,n){this.readAction(e,()=>{throw t},void 0,n)}update(e){let t=this.tree?.engine?.input;if(!t)return;if(this.mouseLook){let e=t.pointerDelta(),n=this.tree?.engine?.settings,r=n?.get(`sensitivity`)??1,i=n?.get(`invertY`)??!1,a=qk*(typeof r==`number`&&r>0?r:1);this.yaw-=e.x*a,this.pitch=oA(this.pitch+(i===!0?-e.y:e.y)*a,-this.pitchMax,-this.pitchMin);let o=t.wheelDelta();o!==0&&this.zoomMax>this.zoomMin&&(this.camDistance=oA(this.camDistance+o*qk,this.zoomMin,this.zoomMax))}let n=this.findCamera();if(!n)return;let r=this.parent instanceof tv?this.parent:null;if(!r)return;let i=sA(r),a=this.view===`free`?11:1e3,o=1-Math.exp(-a*e),s=this.pivot??[i[0],i[1],i[2]];this.pivot=s,s[0]+=(i[0]-s[0])*o,s[1]+=(i[1]-s[1])*o,s[2]+=(i[2]-s[2])*o;let c=gD(this.view,s,this.eyeHeight,this.yaw,this.pitch,this.camDistance),l=[s[0],s[1]+this.eyeHeight,s[2]],u=[c.position[0],c.position[1],c.position[2]];if(this.cameraCollision&&this.view!==`firstPerson`){let e=r._physics3d;e&&(u=_D(l,u,(t,n,i)=>e.castSphere(t,n,Qk,i,r,{staticOnly:!0})?.distance??null,Yk,Xk),u=vD(u,(t,n)=>e.castRay(t,[0,-1,0],n,r,{staticOnly:!0})?.distance??null,Zk))}let d=this.view===`firstPerson`?1e3:this.camLerp,f=1-Math.exp(-d*e),p=n.position;n.position=[(p[0]??0)+(u[0]-(p[0]??0))*f,(p[1]??0)+(u[1]-(p[1]??0))*f,(p[2]??0)+(u[2]-(p[2]??0))*f],this.view===`free`?(nA.set(n.position[0]??0,n.position[1]??0,n.position[2]??0),rA.set(l[0],l[1],l[2]),tA.lookAt(nA,rA,iA),eA.setFromRotationMatrix(tA),$k.setFromQuaternion(eA,`XYZ`)):($k.set(c.rotation[0],c.rotation[1],c.rotation[2],`YXZ`),eA.setFromEuler($k),$k.setFromQuaternion(eA,`XYZ`)),n.rotation=[$k.x*Jk,$k.y*Jk,$k.z*Jk]}pivot=null;cameraCache=null;findCamera(){if(this.cameraCache?.tree===this.tree&&this.cameraCache.current)return this.cameraCache;this.cameraCache=null;let e=this.tree?.root;if(!e)return null;let t=e=>{if(!this.cameraCache){if(e instanceof Bk&&e.current){this.cameraCache=e;return}for(let n of e.children)t(n)}};return t(e),this.cameraCache}};function oA(e,t,n){return Math.min(n,Math.max(t,e))}function sA(e){let t=0,n=0,r=0;for(let i=e;i&&i instanceof Z_;i=i.parent)t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0;return[t,n,r]}var cA=.15,lA=.7,uA=.5,dA=.7,fA=.5;function pA(e,t,n=3){let r=0,i=1,a=1,o=.65;for(let s=0;s<n;s++){let n=e*a,s=t*a,c=Math.sin(n*.1+s*.2)*.5+.5,l=Math.cos(n*.3+s*.1)*.5+.5,u=Math.sin((n+s)*.15)*.5+.5,d=Math.cos(n*n*.01+s*.2)*.5+.5,f=c*l*.7+u*d*.3;r+=f*i,i*=o,a*=2}return r/((1-o**n)/(1-o))}function mA(e,t){let n=pA(e*cA,t*cA,4),r=pA(e*cA*.2,t*cA*.2,2);return n>uA-lA*.5-r*fA}var hA=.9;function gA(e,t,n){let r=(Math.imul(e,2246822507)^Math.imul(t,3266489909)^Math.imul(n+1,668265263))>>>0;return r=Math.imul(r^r>>>15,739982445)>>>0,r=Math.imul(r^r>>>12,695872825)>>>0,r^=r>>>15,(r>>>0)/4294967296}function _A(e,t,n=hA){let r=Math.floor(e/n),i=Math.floor(t/n),a=1/0,o=r,s=i;for(let c=-1;c<=1;c++)for(let l=-1;l<=1;l++){let u=r+l,d=i+c,f=(u+gA(u,d,0))*n,p=(d+gA(u,d,1))*n,m=(e-f)*(e-f)+(t-p)*(t-p);m<a&&(a=m,o=u,s=d)}return{id:Math.imul(o,2654435761)^Math.imul(s,2246822519)|0,hue:gA(o,s,2)*2-1,leanDir:gA(o,s,3)*Math.PI*2,lean:gA(o,s,4)}}function vA(e,t,n,r){let i=e*r,a=t*r,o=Math.floor(i),s=Math.floor(a),c=i-o,l=a-s,u=c*c*(3-2*c),d=l*l*(3-2*l),f=gA(o,s,n),p=gA(o+1,s,n),m=gA(o,s+1,n),h=gA(o+1,s+1,n),g=f+(p-f)*u;return g+(m+(h-m)*u-g)*d}var yA=[.55,1.7],bA=.17,xA=.23,SA=.28;function CA(e,t,n){let r=vA(e,t,n^6877377|0,bA),i=r*r*(3-2*r);return yA[0]+(yA[1]-yA[0])*i}function wA(e,t,n){return vA(e,t,n^3001105|0,xA)}function TA(e,t,n){let r=vA(e,t,n^7840757|0,SA)*.72+vA(e,t,n^1688295|0,SA*3.1)*.28,i=Math.min(1,Math.max(0,(r-.18)/.64));return i*i*(3-2*i)}function EA(e){let{seed:t,areaX:n,areaZ:r,count:i,density:a}=e,o=new Ee(t),s=n/2,c=r/2,l=[],u=Math.floor(i*dA);for(let e=0;e<u&&l.length<i;e++){let e=o.range(-s,s),t=o.range(-c,c),n=o.next()<.3,r=mA(e,t);if(!n&&!r&&o.next()>.15)continue;let i=o.next()*Math.PI*2,a=.5+o.next()*.7,u=r?a*(1+o.next()*.2):a*(.9+o.next()*.2);l.push({x:e,z:t,rotY:i,scale:u})}let d=Math.min(3,Math.max(1,a*10)),f=Math.ceil(Math.sqrt(i*d)),p=n/f,m=r/f,h=Math.floor((i-l.length)*.8),g=0;for(let e=0;e<f&&l.length<i;e++)for(let t=0;t<f&&l.length<i;t++){let i=t/f*n-s+p/2,a=e/f*r-c+m/2,u=i+(o.next()-.5)*p*1.5,d=a+(o.next()-.5)*m*1.5;if(u<-s||u>s||d<-c||d>c)continue;let _=mA(u,d);if(g<h){if(!_&&o.next()>.05)continue}else if(_){if(o.next()>.2)continue}else if(o.next()>.4)continue;if(o.next()<.2)continue;let v=o.next()*Math.PI*2,y=_?.5:.3;l.push({x:u,z:d,rotY:v,scale:.5+o.next()*y}),g++}for(;l.length<i;)l.push({x:o.range(-s,s),z:o.range(-c,c),rotY:o.next()*Math.PI*2,scale:.4+o.next()*.6});return l.sort((e,t)=>t.z-e.z),l}var DA=[`daisy`,`cosmos`,`bellflower`],OA={daisy:{petals:8,blooms:3,leaves:3,petalLength:.1,petalWidth:.052,cupDeg:16,nodDeg:14,centerRadius:.024,centerColor:`#e0a72e`},cosmos:{petals:8,blooms:2,leaves:2,petalLength:.12,petalWidth:.064,cupDeg:26,nodDeg:18,centerRadius:.023,centerColor:`#d2941f`},bellflower:{petals:5,blooms:3,leaves:2,petalLength:.088,petalWidth:.058,cupDeg:46,nodDeg:52,centerRadius:.015,centerColor:`#cfe06a`}},kA=[1,.78,.62],AA=[0,.07,.11],jA=[.6,2.7,4.9],MA=.07,NA=.011,PA=.17,FA=.05,IA=[.12,.2,.28],LA=new q(`#3e6a26`),RA=new q(`#548331`);function zA(e){let t=OA[e],n=new BA(!0),r=new BA(!1),i=new q(t.centerColor);for(let e=0;e<t.blooms;e++){let a=kA[e],o=jA[e],s=AA[e]*Math.cos(o),c=AA[e]*Math.sin(o),l=MA*Math.cos(o),u=MA*Math.sin(o),d=new W(s,0,c),f=new W(s+l,a,c+u),p=new W(s+l*.25,a*.55,c+u*.25);n.addStem(d,p,f,NA,LA);let m=t.nodDeg*Math.PI/180,h=new W(Math.sin(m)*Math.cos(o),Math.cos(m),Math.sin(m)*Math.sin(o)),g=new W(-Math.sin(o),0,Math.cos(o)),_=new W().crossVectors(h,g).normalize(),v=f.clone().addScaledVector(h,.012),y=t.cupDeg*Math.PI/180,b=e*.45;for(let e=0;e<t.petals;e++){let n=e/t.petals*Math.PI*2+b,i=g.clone().multiplyScalar(Math.cos(n)).addScaledVector(_,Math.sin(n)).normalize();r.addPetal(v,i,h,t,y)}n.addDisc(v.clone().addScaledVector(h,.004),g,_,t.centerRadius,i)}for(let e=0;e<t.leaves;e++){let t=IA[e%IA.length],r=1.1+e*2.3;n.addLeaf(new W(0,t,0),r,RA)}return{structure:n.build(),petals:r.build()}}var BA=class{positions=[];colors;indices=[];constructor(e){this.colors=e?[]:null}vertex(e,t){let n=this.positions.length/3;return this.positions.push(e.x,e.y,e.z),this.colors&&t&&this.colors.push(t.r,t.g,t.b),n}addStem(e,t,n,r,i){for(let a of[0,Math.PI/2]){let o=new W(Math.cos(a),0,Math.sin(a)),s=[];for(let a=0;a<=5;a++){let c=a/5,l=1-c,u=new W(l*l*e.x+2*l*c*t.x+c*c*n.x,l*l*e.y+2*l*c*t.y+c*c*n.y,l*l*e.z+2*l*c*t.z+c*c*n.z),d=r/2*(1-.4*c);s.push(this.vertex(u.clone().addScaledVector(o,-d),i),this.vertex(u.clone().addScaledVector(o,d),i))}for(let e=0;e<5;e++){let t=s[e*2],n=s[e*2+1],r=s[e*2+2],i=s[e*2+3];this.indices.push(t,n,r,r,n,i)}}}addPetal(e,t,n,r,i){let a=new W().crossVectors(n,t).normalize(),o=r.centerRadius*.85,s=Math.sin(i)*r.petalLength*.45,c=Math.sin(i)*r.petalLength*.95,l=Math.cos(i),u=e.clone().addScaledVector(t,o),d=o+r.petalLength*l*.55,f=o+r.petalLength*l,p=e.clone().addScaledVector(t,d).addScaledVector(a,r.petalWidth/2).addScaledVector(n,s),m=e.clone().addScaledVector(t,d).addScaledVector(a,-r.petalWidth/2).addScaledVector(n,s),h=e.clone().addScaledVector(t,f).addScaledVector(n,c),g=this.vertex(u,null),_=this.vertex(p,null),v=this.vertex(m,null),y=this.vertex(h,null);this.indices.push(g,_,y,g,y,v)}addDisc(e,t,n,r,i){let a=this.vertex(e,i),o=[];for(let a=0;a<6;a++){let s=a/6*Math.PI*2;o.push(this.vertex(e.clone().addScaledVector(t,Math.cos(s)*r).addScaledVector(n,Math.sin(s)*r),i))}for(let e=0;e<6;e++)this.indices.push(a,o[e],o[(e+1)%6])}addLeaf(e,t,n){let r=new W(Math.cos(t),0,Math.sin(t)),i=new W(-Math.sin(t),0,Math.cos(t)),a=Math.sin(.6),o=Math.cos(.6),s=e.clone().addScaledVector(r,PA*o*.5).add(new W(0,PA*a*.5,0)),c=e.clone().addScaledVector(r,PA*o).add(new W(0,PA*a*.8,0)),l=this.vertex(e,n),u=this.vertex(s.clone().addScaledVector(i,FA/2),n),d=this.vertex(s.clone().addScaledVector(i,-.05/2),n),f=this.vertex(c,n);this.indices.push(l,u,f,l,f,d)}build(){let e=new Y;return e.setAttribute(`position`,new J(new Float32Array(this.positions),3)),this.colors&&e.setAttribute(`color`,new J(new Float32Array(this.colors),3)),e.setIndex(this.indices),e.computeVertexNormals(),e}},VA=2.6;function HA(e){let{seed:t,areaX:n,areaZ:r,count:i,clustering:a}=e,o=new Ee(t),s=n/2,c=r/2,l=1-.74*Math.min(Math.max(a,0),1),u=[];for(let e=0;e<i*16&&u.length<i;e++){let e=o.range(-s,s),t=o.range(-c,c),n=_A(e,t,VA);n.lean>l&&o.next()>.06||u.push({x:e,z:t,rotY:o.next()*Math.PI*2,scale:.75+o.next()*.5,variety01:(n.hue+1)/2,color01:n.leanDir/(Math.PI*2)})}return u}var UA=1.05,WA=1;function GA(e,t=WA){e.computeBoundingSphere();let n=e.boundingSphere;n&&n.radius>=0&&(n.radius=n.radius*UA+t),e.frustumCulled=!0}function KA(e){let t=0,n=0,r=0;for(let i=e;i;i=i.parent)i instanceof Z_&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return[t,n,r]}function qA(e,t){if(t!==``){let n=e.getNodeOrNull(t);return n instanceof hO?n:null}return JA(e.getRoot())}function JA(e){if(e instanceof hO)return e;for(let t of e.children){let e=JA(t);if(e)return e}return null}function YA(e){return typeof e?._waterYAt==`function`}function XA(e){let t=e;for(;t.parent;)t=t.parent;let n=[],r=e=>{e.visible!==!1&&YA(e)&&n.push(e);for(let t of e.children)r(t)};return r(t),n}function ZA(e,t,n,r,i=.06){for(let a=0;a<e.length;a++){let o=e[a]?._waterYAt(t,n);if(o!=null&&o-r>i)return!0}return!1}var QA={lush:2.2,sparse:.35,none:0},$A=[`lush`,`sparse`,`none`];function ej(e){if(typeof e==`number`)return e;let t=QA[e];if(t===void 0)throw new L(`BAD_FORMAT`,`Flowers3D density must be one of [${$A.join(`, `)}] or a number (plants/m²), got '${e}'.`,{prop:`density`,validOptions:$A});return t}var tj=1e4,nj=[`#f5f1e2`,`#e9d052`,`#8d7bd9`],rj=/^#[0-9a-fA-F]{6}$/,ij=class extends Z_{static typeName=`Flowers3D`;static props={density:{default:`sparse`,options:$A},area:{default:[20,20]},seed:{default:1},varieties:{default:[]},palette:{default:[]},height:{default:.45},clustering:{default:.6},sway:{default:.5},drape:{default:null},avoidWater:{default:!0},terrain:{default:``,nodePath:!0}};density=`sparse`;area=[20,20];seed=1;varieties=[];palette=[];height=.45;clustering=.6;sway=.5;drape=null;avoidWater=!0;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(typeof t.density==`string`)ej(t.density);else if(!(Number.isFinite(t.density)&&t.density>=0))throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' density must be one of [${$A.join(`, `)}] or a number >= 0 (plants/m²), got ${t.density}.`,{prop:`density`,validOptions:$A});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' area must be positive [x, z] meters, got ${JSON.stringify(t.area)}.`,{prop:`area`});let n=Math.floor((t.area[0]??0)*(t.area[1]??0)*ej(t.density));if(n>tj)throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' blows the plant budget: area ${t.area[0]}×${t.area[1]} m × density ${ej(t.density)} = ${n} plants > ${tj}. Lower the density or split the field into multiple nodes.`,{prop:`density`});if(!Array.isArray(t.varieties)||new Set(t.varieties).size!==t.varieties.length||!t.varieties.every(e=>DA.includes(e)))throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' varieties must be a unique subset of [${DA.join(`, `)}] ([] = all three), got ${JSON.stringify(t.varieties)}.`,{prop:`varieties`,validOptions:[...DA]});if(!Array.isArray(t.palette)||!t.palette.every(e=>typeof e==`string`&&rj.test(e)))throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' palette must be an array of '#rrggbb' head colors ([] = white/yellow/violet), got ${JSON.stringify(t.palette)}.`,{prop:`palette`});if(!(t.height>0))throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' height must be > 0 meters, got ${t.height}.`,{prop:`height`});if(!(t.clustering>=0)||!(t.clustering<=1))throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' clustering must be in [0, 1] (0 uniform … 1 tight patches), got ${t.clustering}.`,{prop:`clustering`});if(!(t.sway>=0))throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' sway must be >= 0, got ${t.sway}.`,{prop:`sway`});if(t.drape!==null&&typeof t.drape!=`boolean`)throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' drape must be true, false or null (null = auto: drape whenever the scene has a Terrain3D), got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' terrain must be a node-path string (empty = auto-find), got ${JSON.stringify(t.terrain)}.`,{prop:`terrain`})}time=0;field=null;varietyMeshes=[];fieldKey=``;timeUniform={value:0};swayUniform={value:.5};_createObject3D(){return new Ec}_varietyMeshes(){return this.rebuildIfNeeded(),this.varietyMeshes}update(e){this.time+=e,this.timeUniform.value=this.time}_syncObject3D(){super._syncObject3D(),this.rebuildIfNeeded(),this.swayUniform.value=this.sway}rebuildIfNeeded(){this.field||(this.field=new Ec,this._ensureObject3D().add(this.field));let e=JSON.stringify([this.density,this.area,this.seed,this.varieties,this.palette,this.height,this.clustering,this.drape,this.avoidWater,this.terrain]);e!==this.fieldKey&&(this.fieldKey=e,this.disposeMeshes(),this.resolveDrape(),this.buildField())}resolveDrape(){if(this.drapeTerrain=null,this.drape===!1)return;let e=qA(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=KA(this);else if(this.terrain!==``)throw new L(`NODE_NOT_FOUND`,`Flowers3D '${this.name}' drape terrain '${this.terrain}' is not a Terrain3D in the tree.`,{prop:`terrain`})}bedY(e,t){let n=this.drapeTerrain;return n?n.heightAt(this.drapeWorld[0]+e,this.drapeWorld[2]+t)-this.drapeWorld[1]:0}buildField(){let e=ej(this.density),t=Math.min(Math.floor((this.area[0]??0)*(this.area[1]??0)*e),tj);if(t<=0)return;let n=HA({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:t,clustering:this.clustering});if(this.avoidWater){let e=XA(this);if(e.length>0){let[t,r,i]=KA(this);n=n.filter(n=>!ZA(e,n.x+t,n.z+i,this.bedY(n.x,n.z)+r))}}let r=this.varieties.length>0?this.varieties:DA,i=r.map(()=>[]);for(let e of n)i[Math.min(Math.floor(e.variety01*r.length),r.length-1)].push(e);let a=this.palette.length>0?this.palette:nj,o=new Ee(this.seed+15797765);for(let e=0;e<r.length;e++){let t=i[e];if(t.length===0)continue;let{structure:n,petals:s}=zA(r[e]),c=new kd({vertexColors:!0,roughness:1,side:2}),l=new kd({roughness:.85,side:2});aj(c,this.timeUniform,this.swayUniform),aj(l,this.timeUniform,this.swayUniform);let u=new Au(n,c,t.length),d=new Au(s,l,t.length);u.receiveShadow=!0,d.receiveShadow=!0;for(let e=0;e<t.length;e++){let n=t[e];cj.set(n.x,this.bedY(n.x,n.z),n.z),lj.setFromAxisAngle(oj,n.rotY),uj.setScalar(this.height*n.scale),sj.compose(cj,lj,uj),u.setMatrixAt(e,sj),d.setMatrixAt(e,sj);let r=Math.min(Math.floor(n.color01*a.length),a.length-1);dj.set(a[r]).offsetHSL(o.range(-.02,.02),0,o.range(-.05,.05)),d.setColorAt(e,dj),dj.setRGB(1,1,1).offsetHSL(o.range(-.02,.02),0,o.range(-.06,.04)),u.setColorAt(e,dj)}u.instanceMatrix.needsUpdate=!0,d.instanceMatrix.needsUpdate=!0,u.instanceColor&&(u.instanceColor.needsUpdate=!0),d.instanceColor&&(d.instanceColor.needsUpdate=!0),GA(u),GA(d),this.varietyMeshes.push({variety:r[e],structure:u,petals:d}),this.field.add(u),this.field.add(d)}}disposeMeshes(){for(let{structure:e,petals:t}of this.varietyMeshes)for(let n of[e,t])n.removeFromParent(),n.geometry.dispose(),n.material.dispose(),n.dispose();this.varietyMeshes=[]}free(){this.disposeMeshes(),this.field=null,super.free()}};function aj(e,t,n){e.userData.sway=!0,e.userData.timeUniform=t,e.onBeforeCompile=e=>{e.uniforms.uFlowerTime=t,e.uniforms.uFlowerSway=n,e.vertexShader=`uniform float uFlowerTime;\nuniform float uFlowerSway;\n${e.vertexShader}`.replace(`#include <project_vertex>`,`
|
|
6992
|
+
`;function $D(e,t){for(let n=0;n<4;n++){let r=n+1;e.uniforms[`splatTexture${r}`]={value:t.textures[n]??t.textures[0]??null},e.uniforms[`splatNormalMap${r}`]={value:t.normalMaps[n]??null},e.uniforms[`splatTextureRepeat${r}`]={value:t.repeats[n]??1},e.uniforms[`splatRoughness${r}`]={value:t.roughness[n]??1},e.uniforms[`splatMetalness${r}`]={value:t.metalness[n]??0},e.uniforms[`uvNoiseIntensity${r}`]={value:t.uvNoiseIntensity[n]??.15}}e.uniforms.splatTextureCount={value:Math.min(4,t.layerCount)},e.uniforms.uWetlineY={value:-1e9},e.uniforms.uWetlineBand={value:1.1},e.uniforms.uWetTime={value:0},e.uniforms.splatEnvCut={value:t.envCut},e.vertexShader=WD(e.vertexShader,`#include <common>`,GD),e.vertexShader=WD(e.vertexShader,`#include <begin_vertex>`,KD);let n=e.fragmentShader;n=WD(n,`#include <common>`,qD),n=WD(n,`#include <color_fragment>`,JD),n=WD(n,`#include <roughnessmap_fragment>`,YD),n=WD(n,`#include <metalnessmap_fragment>`,ZD),n=WD(n,`#include <normal_fragment_maps>`,QD),n=WD(n,`#include <lights_fragment_maps>`,XD),t.hasNormalMaps&&(n=`#define USE_TERRAIN_NORMALMAP\n${n}`),e.fragmentShader=n}var eO=[`island`,`alpine`,`plains`,`desert`,`grassland`,`forest`,`savanna`,`snow`,`wetland`,`volcanic`,`custom`],tO=`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,nO=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/ground`,rO=1/3,iO=Math.PI/4;function aO(e,t,n){return{texture:`${e}/${t}.png`,normalMap:`${e}/${t}_normal.png`,...n}}function oO(e,t){let n=t.replace(/\/$/,``);switch(e){case`island`:return[aO(n,`sand`,{heightRange:[0,.12],slopeRange:[0,Math.PI/2],heightBlendRange:.05,roughness:.9}),aO(n,`grass`,{heightRange:[.1,.7],slopeRange:[0,iO],heightBlendRange:.1,slopeBlendRange:.1,roughness:.8}),aO(n,`stone`,{heightRange:[0,1],slopeRange:[iO,Math.PI],heightBlendRange:.5,slopeBlendRange:.5,roughness:.85}),aO(n,`snow`,{heightRange:[.8,1],slopeRange:[0,Math.PI/3],heightBlendRange:.1,roughness:.6})];case`alpine`:return[aO(n,`grass`,{heightRange:[0,.45],slopeRange:[0,Math.PI/5],heightBlendRange:.1,roughness:.8}),aO(n,`stone`,{heightRange:[.3,1],slopeRange:[0,Math.PI],heightBlendRange:.25,slopeBlendRange:.5,roughness:.85}),aO(n,`gravel`,{heightRange:[0,1],slopeRange:[Math.PI/5,Math.PI],heightBlendRange:.5,slopeBlendRange:.15,roughness:.9}),aO(n,`snow`,{heightRange:[.55,1],slopeRange:[0,Math.PI/3],heightBlendRange:.12,roughness:.55})];case`plains`:return[aO(n,`grass`,{heightRange:[0,1],slopeRange:[0,iO],heightBlendRange:.1,slopeBlendRange:.1,roughness:.8}),aO(n,`dirt`,{heightRange:[.35,.65],slopeRange:[0,Math.PI/5],heightBlendRange:.2,roughness:.9}),aO(n,`gravel`,{heightRange:[0,1],slopeRange:[iO,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.9})];case`desert`:return[aO(n,`sand`,{heightRange:[0,1],slopeRange:[0,iO],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),aO(n,`gravel`,{heightRange:[0,.15],slopeRange:[0,Math.PI/3],heightBlendRange:.08,roughness:.9}),aO(n,`stone`,{heightRange:[0,1],slopeRange:[iO,Math.PI],heightBlendRange:.5,slopeBlendRange:.4,roughness:.85})];case`grassland`:return n===`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`?[{texture:`${nO}/grass.jpg`,heightRange:[0,1],slopeRange:[0,iO],heightBlendRange:.1,slopeBlendRange:.15,roughness:1,repeat:rO,uvNoiseIntensity:0},{texture:`${nO}/dirt_color.jpg`,heightRange:[0,1],slopeRange:[iO,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:1,repeat:rO,uvNoiseIntensity:0}]:[aO(n,`grass`,{heightRange:[0,1],slopeRange:[0,iO],heightBlendRange:.1,slopeBlendRange:.15,roughness:.8}),aO(n,`dirt`,{heightRange:[0,1],slopeRange:[iO,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.9})];case`forest`:return n===`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`?[{texture:`${nO}/dirt_color.jpg`,heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:1,repeat:rO,uvNoiseIntensity:0},{texture:`${nO}/grass.jpg`,heightRange:[-2,-1],roughness:1,repeat:rO,uvNoiseIntensity:0}]:[aO(n,`dirt`,{heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:.9}),aO(n,`grass`,{heightRange:[-2,-1],roughness:.8})];case`savanna`:return[aO(n,`grass`,{heightRange:[0,1],slopeRange:[0,iO],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),aO(n,`sand`,{heightRange:[0,.22],slopeRange:[0,Math.PI/4],heightBlendRange:.12,roughness:.95}),aO(n,`dirt`,{heightRange:[0,1],slopeRange:[iO,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.95})];case`snow`:return[aO(n,`snow`,{heightRange:[0,1],slopeRange:[0,iO],heightBlendRange:.1,slopeBlendRange:.18,roughness:.55}),aO(n,`stone`,{heightRange:[0,1],slopeRange:[iO,Math.PI],heightBlendRange:.5,slopeBlendRange:.35,roughness:.85})];case`wetland`:return[aO(n,`grass`,{heightRange:[0,1],slopeRange:[0,iO],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),aO(n,`dirt`,{heightRange:[0,1],slopeRange:[iO,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.95})];case`volcanic`:return[aO(n,`stone`,{heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:.95}),aO(n,`gravel`,{heightRange:[0,.28],slopeRange:[0,Math.PI/3],heightBlendRange:.14,slopeBlendRange:.2,roughness:.95})];case`custom`:return[]}}var sO={scale:100,threshold:.7,blend:.1},cO={scale:55,threshold:.58,blend:.12},lO={scale:85,threshold:.62,blend:.12},uO={scale:48,threshold:.5,blend:.14};function dO(e,t){let n=Sr(e+27927);return(e,r)=>{let i=(.5+.5*n(e/t.scale,r/t.scale)-(t.threshold-t.blend))/(2*t.blend),a=Math.min(1,Math.max(0,i));return a*a*(3-2*a)}}function fO(e,t){return e===`grassland`?dO(t,sO):e===`forest`?dO(t,cO):e===`savanna`?dO(t,lO):e===`wetland`?dO(t,uO):null}function pO(e){return e===`savanna`?{from:0,to:2}:e===`grassland`||e===`forest`||e===`wetland`?{from:0,to:1}:null}var mO=256,hO=class extends Q_{orderGroup=`terrain`;static typeName=`Terrain3D`;static props={orderGroup:{default:`terrain`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},size:{default:[200,200]},maxHeight:{default:28},seed:{default:1},resolution:{default:128},theme:{default:`island`,options:eO},roughness:{default:.5},detail:{default:4},flatThreshold:{default:.95},islandEdge:{default:null},layers:{default:[]},textureBase:{default:tO},basins:{default:[]},channels:{default:[]},wetline:{default:null}};size=[200,200];maxHeight=28;seed=1;resolution=128;theme=`island`;roughness=.5;detail=4;flatThreshold=.95;islandEdge=null;layers=[];textureBase=tO;basins=[];channels=[];externalChannels=new Map;externalRev=0;shapeStamp=null;wetline=null;splatUniforms=null;wetTime=0;update(e){this.wetTime+=e;let t=this.splatUniforms;if(!t)return;let n=this.wetline;t.uWetlineY&&(t.uWetlineY.value=typeof n?.y==`number`?n.y:-1e9),t.uWetlineBand&&(t.uWetlineBand.value=typeof n?.band==`number`?n.band:1.1),t.uWetTime&&(t.uWetTime.value=this.wetTime)}static validateJson(e){iv(e,`heightAt(), the heightfield collider, drape and terrain-nav all`);let t=e;if(!eO.includes(t.theme))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' theme must be one of [${eO.join(`, `)}], got '${t.theme}'.`,{prop:`theme`,validOptions:eO});if(!((t.size[0]??0)>0)||!((t.size[1]??0)>0))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' size must be positive [width, depth] meters, got ${JSON.stringify(t.size)}.`,{prop:`size`});if(!(t.maxHeight>0))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' maxHeight must be > 0, got ${t.maxHeight}.`,{prop:`maxHeight`});if(!Number.isInteger(t.resolution)||t.resolution<2||t.resolution>mO)throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' resolution must be an integer in [2, ${mO}] (grid segments per side), got ${t.resolution}.`,{prop:`resolution`});if(!(t.roughness>0)||!Number.isFinite(t.roughness))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' roughness must be a finite number > 0, got ${t.roughness}.`,{prop:`roughness`});if(!Number.isInteger(t.detail)||t.detail<0)throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' detail must be an integer ≥ 0 (octave count), got ${t.detail}.`,{prop:`detail`});if(!(t.flatThreshold>=0)||!Number.isFinite(t.flatThreshold))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' flatThreshold must be a finite number ≥ 0, got ${t.flatThreshold}.`,{prop:`flatThreshold`});if(t.islandEdge!==null&&typeof t.islandEdge!=`boolean`)throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' islandEdge must be true, false or null (null = theme default), got ${JSON.stringify(t.islandEdge)}.`,{prop:`islandEdge`});let n=t.wetline;if(n!==null){if(typeof n!=`object`||Array.isArray(n)||!Number.isFinite(n.y))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' wetline must be null or { y, band? } with a finite y, got ${JSON.stringify(t.wetline)}.`,{prop:`wetline`});if(n.band!==void 0&&!(n.band>0))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' wetline.band must be > 0 meters, got ${JSON.stringify(n.band)}.`,{prop:`wetline`})}if(!Array.isArray(t.basins))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' basins must be an array of { x, z, radius, depth }, got ${JSON.stringify(t.basins)}.`,{prop:`basins`});if(t.basins.forEach((t,n)=>{if(!t||typeof t!=`object`||!Number.isFinite(t.x)||!Number.isFinite(t.z)||!(t.radius>0)||!Number.isFinite(t.depth)||t.depth===0)throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' basins[${n}] needs finite x, z, positive radius and nonzero depth (negative = mound), got ${JSON.stringify(t)}.`,{prop:`basins`})}),!Array.isArray(t.channels))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' channels must be an array of { path, width, depth, taper? }, got ${JSON.stringify(t.channels)}.`,{prop:`channels`});if(t.channels.forEach((t,n)=>{let r=t.path;if(!(t&&typeof t==`object`&&Array.isArray(r)&&r.length>=2&&r.every(e=>Array.isArray(e)&&Number.isFinite(e[0])&&Number.isFinite(e[1]))&&t.width>0&&t.depth>0&&(t.taper===void 0||t.taper>0)))throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' channels[${n}] needs a path of 2+ [x, z] points plus positive width and depth, got ${JSON.stringify(t)}.`,{prop:`channels`})}),t.theme===`custom`){if(!Array.isArray(t.layers)||t.layers.length<1||t.layers.length>4)throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' theme 'custom' needs 1–4 layers, got ${Array.isArray(t.layers)?t.layers.length:typeof t.layers}.`,{prop:`layers`});t.layers.forEach((t,n)=>{vO(e.name,t,n)})}else if(Array.isArray(t.layers)&&t.layers.length>0)throw new L(`BAD_FORMAT`,`Terrain3D '${e.name}' layers is only read with theme 'custom' — preset theme '${t.theme}' defines its own. Drop layers or switch to theme: 'custom'.`,{prop:`layers`})}heightmap=null;heightmapKey=``;builtKey=``;_createObject3D(){let e=new Y;return e.setAttribute(`position`,new J(new Float32Array,3)),new iu(e,new kd({vertexColors:!0}))}heightAt(e,t){let n=0,r=0,i=0;for(let e=this;e;e=e.parent)e instanceof Q_&&(n+=e.position[0]??0,r+=e.position[1]??0,i+=e.position[2]??0);return this._heightmap().heightAt(e-n,t-i)+r}_setExternalChannel(e,t){t===null||t.length===0?this.externalChannels.delete(e):this.externalChannels.set(e,t),this.externalRev++}allChannels(){return this.externalChannels.size===0?this.channels:[...this.channels,...[...this.externalChannels.values()].flat()]}_heightmap(){if(this.heightmap&&this.shapeUnchanged())return this.heightmap;let e=this.segments(),t=JSON.stringify([this.size,this.maxHeight,this.seed,e,this.roughness,this.detail,this.flatThreshold,this.effectiveIslandEdge(),this.basins,this.allChannels()]);return(!this.heightmap||t!==this.heightmapKey)&&(this.heightmap=VD({width:this.size[0]??1,depth:this.size[1]??1,segsX:e,segsZ:e,maxHeight:this.maxHeight,seed:this.seed,roughness:this.roughness,detail:this.detail,flatThreshold:this.flatThreshold,islandEdge:this.effectiveIslandEdge(),basins:this.basins,channels:this.allChannels()}),this.heightmapKey=t),this.rememberShape(),this.heightmap}shapeUnchanged(){let e=this.shapeStamp;return e!==null&&e.sizeX===(this.size[0]??0)&&e.sizeZ===(this.size[1]??0)&&e.maxHeight===this.maxHeight&&e.seed===this.seed&&e.segments===this.segments()&&e.roughness===this.roughness&&e.detail===this.detail&&e.flatThreshold===this.flatThreshold&&e.islandEdge===this.effectiveIslandEdge()&&e.basins===this.basins&&e.channels===this.channels&&e.externalRev===this.externalRev}rememberShape(){this.shapeStamp={sizeX:this.size[0]??0,sizeZ:this.size[1]??0,maxHeight:this.maxHeight,seed:this.seed,segments:this.segments(),roughness:this.roughness,detail:this.detail,flatThreshold:this.flatThreshold,islandEdge:this.effectiveIslandEdge(),basins:this.basins,channels:this.channels,externalRev:this.externalRev}}resolvedLayers(){return this.theme===`custom`?this.layers:oO(this.theme,this.textureBase)}_syncObject3D(e=1,t=null){super._syncObject3D(e,t),this.rebuildIfNeeded(t)}effectiveIslandEdge(){return this.islandEdge??this.theme===`island`}segments(){return Math.max(2,Math.min(Math.floor(this.resolution),mO))}rebuildIfNeeded(e){let t=JSON.stringify([this.size,this.maxHeight,this.seed,this.segments(),this.theme,this.roughness,this.detail,this.flatThreshold,this.islandEdge,this.layers,this.textureBase,this.basins,this.allChannels()]);if(t===this.builtKey)return;this.builtKey=t;let n=this._ensureObject3D();n.geometry.dispose(),n.geometry=this.buildGeometry(),n.material.dispose(),n.material=this.buildMaterial(e),n.receiveShadow=!0,n.castShadow=!0}buildGeometry(){let e=this._heightmap(),t=new _d(e.width,e.depth,e.segsX,e.segsZ);t.rotateX(-Math.PI/2);let n=t.getAttribute(`position`);for(let t=0;t<n.count;t++)n.setY(t,e.heights[t]);n.needsUpdate=!0,t.computeVertexNormals();let r=this.resolvedLayers(),i=e.maxHeight-e.minHeight||1,a=new Float32Array(n.count*3),o=this.theme===`custom`?null:pO(this.theme),s=o?fO(this.theme,this.seed):null;for(let t=0;t<n.count;t++){let c=n.getX(t),l=n.getZ(t),u=UD(Math.min(1,Math.max(0,(n.getY(t)-e.minHeight)/i)),e.slopeAt(c,l),r);if(s&&o){let e=(u[o.from]??0)*s(c,l);u[o.from]=(u[o.from]??0)-e,u[o.to]=(u[o.to]??0)+e}a[t*3]=u[0],a[t*3+1]=u[1],a[t*3+2]=u[2]}return t.setAttribute(`color`,new J(a,3)),t}buildMaterial(e){let t=this.resolvedLayers(),n=new kd({vertexColors:!0}),r=(t,n)=>t?uD(e,t,{wrap:`repeat`,anisotropy:8,colorSpace:n?`srgb`:`linear`}):null,i=t.map(e=>r(e.texture,!0)),a=t.map(e=>r(e.normalMap,!1)),o=a.some(e=>e!==null);if(o)for(let e=0;e<a.length;e++)a[e]||(a[e]=_O());let s={textures:i,normalMaps:a,repeats:t.map(e=>e.repeat??2),roughness:t.map(e=>e.roughness??1),metalness:t.map(e=>e.metalness??0),uvNoiseIntensity:t.map(e=>e.uvNoiseIntensity??.15),envCut:.45,layerCount:Math.min(4,t.length),hasNormalMaps:o};return n.onBeforeCompile=e=>{$D(e,s),this.splatUniforms=e.uniforms},n.customProgramCacheKey=()=>`incanto-terrain-splat:${+!!o}`,n}free(){let e=this._ensureObject3D();e.geometry.dispose(),e.material.dispose(),this.heightmap=null,super.free()}},gO=null;function _O(){return gO||(gO=new vu(new Uint8Array([128,128,255,255]),1,1),gO.needsUpdate=!0),gO}function vO(e,t,n){let r=`layers[${n}]`;if(typeof t!=`object`||!t||Array.isArray(t))throw new L(`BAD_FORMAT`,`Terrain3D '${e}' ${r} must be an object ({texture, heightRange?, slopeRange?, …}).`,{prop:`layers`});let i=t;if(typeof i.texture!=`string`||i.texture.length===0)throw new L(`BAD_FORMAT`,`Terrain3D '${e}' ${r} needs "texture": a texture URL string.`,{prop:`layers`});for(let t of[`heightRange`,`slopeRange`]){let n=i[t];if(n!==void 0&&(!Array.isArray(n)||n.length!==2||n.some(e=>typeof e!=`number`||!Number.isFinite(e))))throw new L(`BAD_FORMAT`,`Terrain3D '${e}' ${r}.${t} must be [min, max] numbers, got ${JSON.stringify(n)}.`,{prop:`layers`})}}var yO=16,bO=new W,xO=new U;function SO(e,t){let n=e.translation(),r=e.rotation();xO.set(r.x,r.y,r.z,r.w);let i=(e,r,i)=>{bO.set(e,r,i).applyQuaternion(xO),t.push(bO.x+n.x,bO.y+n.y,bO.z+n.z)};return(e,t,n,r,a,o)=>{i(e,t,n),i(r,a,o)}}function CO(e,t,n,r,i=Math.PI*2,a=0){let o=e=>{let i=Math.cos(e)*t,a=Math.sin(e)*t;return n===`xy`?[i,a,r]:n===`xz`?[i,r,a]:[r,i,a]},s=Math.max(3,Math.round(yO*i/(Math.PI*2)));for(let t=0;t<s;t++){let[n,r,c]=o(a+i*t/s),[l,u,d]=o(a+i*(t+1)/s);e(n,r,c,l,u,d)}}function wO(e,t,n){let r=e=>[t[e*3],t[e*3+1],t[e*3+2]];if(n){for(let t=0;t<n.length;t+=3){let i=r(n[t]),a=r(n[t+1]),o=r(n[t+2]);e(...i,...a),e(...a,...o),e(...o,...i)}return}for(let n=0;n+5<t.length;n+=9){let t=r(n/3),i=r(n/3+1),a=r(n/3+2);e(...t,...i),e(...i,...a),e(...a,...t)}}function TO(e,t){let{nrows:n,ncols:r,heights:i,scale:a}=t,o=n+1,s=r+1,c=(e,t)=>[(e/n-.5)*a.x,i[t*o+e]*a.y,(t/r-.5)*a.z];for(let t=0;t<s;t++)for(let n=0;n<o;n++)n+1<o&&e(...c(n,t),...c(n+1,t)),t+1<s&&e(...c(n,t),...c(n,t+1))}function EO(e,t){let n=SO(e,t),r=e.shape;switch(e.shape.type){case 0:{let e=r.radius;CO(n,e,`xy`,0),CO(n,e,`xz`,0),CO(n,e,`yz`,0);return}case 1:{let e=r.halfExtents;for(let[t,r]of[[-1,-1],[-1,1],[1,-1],[1,1]])n(-e.x,t*e.y,r*e.z,e.x,t*e.y,r*e.z);for(let[t,r]of[[-1,-1],[-1,1],[1,-1],[1,1]])n(t*e.x,-e.y,r*e.z,t*e.x,e.y,r*e.z);for(let[t,r]of[[-1,-1],[-1,1],[1,-1],[1,1]])n(t*e.x,r*e.y,-e.z,t*e.x,r*e.y,e.z);return}case 2:{let{radius:e,halfHeight:t}=r;for(let r of[-1,1]){CO(n,e,`xz`,r*t);for(let i of[`xy`,`yz`])CO((e,i,a,o,s,c)=>n(e,i+r*t,a,o,s+r*t,c),e,i,0,Math.PI,r>0?0:Math.PI)}for(let[r,i]of[[1,0],[-1,0],[0,1],[0,-1]])n(r*e,-t,i*e,r*e,t,i*e);return}case 3:{let e=r;n(e.a.x,e.a.y,e.a.z,e.b.x,e.b.y,e.b.z);return}case 6:case 9:case 16:{let e=r;wO(n,e.vertices,e.indices);return}case 7:TO(n,r);return;case 10:case 14:{let{radius:e,halfHeight:t}=r;CO(n,e,`xz`,-t),CO(n,e,`xz`,t);for(let[r,i]of[[1,0],[-1,0],[0,1],[0,-1]])n(r*e,-t,i*e,r*e,t,i*e);return}case 11:case 15:{let{radius:e,halfHeight:t}=r;CO(n,e,`xz`,-t);for(let r=0;r<4;r++){let i=r/4*Math.PI*2;n(Math.cos(i)*e,-t,Math.sin(i)*e,0,t,0)}return}default:if(e.shape.type===12||e.shape.type===13){let e=r.halfExtents;e&&n(-e.x,-e.y,-e.z,e.x,e.y,e.z)}return}}var DO=Math.PI/180;async function OO(e,t){let n=await Vg(()=>import(`./rapier-DE6a0vmv.js`),[],import.meta.url);return await Lb(()=>n.init()),new kO(n,e,t)}var kO=class{R;engine;debugDraw=!1;debugScope=null;dimension=`3d`;unregisterDebug;warnedNoCollider=new WeakSet;entries=new Map;byColliderHandle=new Map;world;events;kcc;disconnectScene;disconnect;lastDt=1/60;optsGravity;lastScene=null;constructor(e,t,n){this.R=e,this.engine=t,this.optsGravity=n?.gravity,this.simulate=n?.simulate??!0,this.lastScene=t.scene;let r=t.scene?.physics?.gravity,i=n?.gravity??r??[0,-9.81,0];this.world=new e.World({x:i[0]??0,y:i[1]??0,z:i[2]??0}),this.kcc=this.world.createCharacterController(.01),this.events=new e.EventQueue(!0),this.unregisterDebug=Pb(this),this.disconnect=t.fixedUpdated.connect(e=>this.step(e)),this.disconnectScene=t.sceneChanged.connect(()=>{t.scene&&this.syncBodies()}),this.syncBodies()}simulate;step(e){if(this.lastDt=e,!this.simulate){this.syncBodies(),this.poseFromTree();return}if(this.engine.scene!==this.lastScene&&(this.lastScene=this.engine.scene,!this.optsGravity)){let e=this.engine.scene?.physics?.gravity??[0,-9.81,0];this.world.gravity={x:e[0]??0,y:e[1]??0,z:e[2]??0}}this.syncBodies(),this.world.timestep=e,this.world.step(this.events);for(let[e,t]of this.entries){let n=t.body.translation();if(!t.body.isFixed()&&!(e instanceof tv)){let[t,r,i]=YO(e),a=[n.x-t,n.y-r,n.z-i];e._interpPrev=e._interpCurr??a,e._interpCurr=a;let o=e.position;o[0]=a[0],o[1]=a[1],o[2]=a[2]}if(e instanceof nv){if(!e.fixedRotation){let n=t.body.rotation();jO.setFromQuaternion(AO.set(n.x,n.y,n.z,n.w),`XYZ`);let r=e.rotation;r[0]=jO.x/DO,r[1]=jO.y/DO,r[2]=jO.z/DO,t.lastRot[0]=r[0],t.lastRot[1]=r[1],t.lastRot[2]=r[2]}let n=t.body.linvel(),r=e.linearVelocity;r[0]=n.x,r[1]=n.y,r[2]=n.z,t.lastV[0]=n.x,t.lastV[1]=n.y,t.lastV[2]=n.z}let r=t.body.translation();t.last[0]=r.x,t.last[1]=r.y,t.last[2]=r.z}this.events.drainCollisionEvents((e,t,n)=>{let r=this.byColliderHandle.get(e),i=this.byColliderHandle.get(t);if(!r||!i)return;let a=n?`triggerEnter`:`triggerExit`;try{r.emit(a,i),i.emit(a,r)}catch(e){Nt(this.engine,`error`,`incanto: error in a '${a}' handler (${r.name} ↔ ${i.name}):`,e)}})}poseFromTree(){for(let[e,t]of this.entries){let[n,r,i]=qO(e);t.body.setTranslation({x:n,y:r,z:i},!1),AO.setFromEuler(jO.set((e.rotation[0]??0)*DO,(e.rotation[1]??0)*DO,(e.rotation[2]??0)*DO,`XYZ`)),t.body.setRotation({x:AO.x,y:AO.y,z:AO.z,w:AO.w},!1)}this.world.propagateModifiedBodyPositionsToColliders()}moveAndSlide(e){let t=this.ensureEntry(e);if(!t)return;let n=e.velocity[1]??0;e.stickToGround&&n<=0?this.kcc.enableSnapToGround(.1):this.kcc.disableSnapToGround(),this.kcc.setMaxSlopeClimbAngle(e.slopeLimitDeg*DO),e.stepHeight>0?this.kcc.enableAutostep(e.stepHeight,e.stepHeight/2,!1):this.kcc.disableAutostep();let r=0,i=0,a=0;if(t.ground&&t.ground._physics===this&&t.groundAt){let[e,n,o]=qO(t.ground);r=e-t.groundAt[0],i=n-t.groundAt[1],a=o-t.groundAt[2]}else t.ground=null;let o={x:(e.velocity[0]??0)*this.lastDt+r,y:n*this.lastDt+i,z:(e.velocity[2]??0)*this.lastDt+a};this.kcc.computeColliderMovement(t.collider,o,this.R.QueryFilterFlags.EXCLUDE_SENSORS);let s=this.kcc.computedMovement(),c=t.body.translation(),l=c.x+s.x,u=c.y+s.y,d=c.z+s.z;if(t.body.setNextKinematicTranslation({x:l,y:u,z:d}),e._grounded=this.kcc.computedGrounded(),e._grounded){let n=KO(e),r=this.castRay([l,u-n+.05,d],[0,-1,0],.4,e);if(r?.node&&!(r.node instanceof rv)){t.ground=r.node;let e=qO(r.node);t.groundAt=[e[0],e[1],e[2]]}else t.ground=null}else t.ground=null}debugLines(){if(!this.debugDraw)return null;let e=this.debugScope;if(!e)return this.world.debugRender().vertices;let t=this.scopedBodies(e),n=[];for(let e of t)for(let t=0;t<e.numColliders();t++){let r=e.collider(t);r&&EO(r,n)}return new Float32Array(n)}scopedBodies(e){let t=[],n=e=>{let r=this.entries.get(e);r&&t.push(r.body);let i=this.scatterBodies.get(e);i&&t.push(i);for(let t of e.children)n(t)};n(e);for(let n=e.parent;n&&t.length===0;n=n.parent){let e=this.entries.get(n);e&&t.push(e.body)}return t}dispose(){this.disconnect(),this.disconnectScene(),this.unregisterDebug(),this.world.free()}lastStructure=-1;lastRoot=null;jointSet=new Set;joints=new Map;scatterBodies=new Map;bodySet=new Set;syncScatters(e){for(let[,e]of this.scatterBodies)this.world.removeRigidBody(e);this.scatterBodies.clear();let t=new Set;WO(e,t);for(let e of t){let t=e.collider;if(!t)continue;let[n,r,i]=qO(e),a=this.world.createRigidBody(this.R.RigidBodyDesc.fixed().setTranslation(0,0,0)),[o,s,c]=e.size,l=null;for(let u of e.transforms){let d=u[4]??1,f=n+(u[0]??0),p=r+(u[1]??0),m=i+(u[2]??0),h=null;if(t.shape===`sphere`)h=this.R.ColliderDesc.ball(Math.max((t.radius??Math.max(o,c)/2)*d,.01));else if(t.shape===`box`){let e=t.size??[o,s,c];h=this.R.ColliderDesc.cuboid(Math.max((e[0]??1)*d/2,.01),Math.max((e[1]??1)*d/2,.01),Math.max((e[2]??1)*d/2,.01))}else{l??=FO(e.mesh,e.size);let t=new Float32Array(l.length);for(let e=0;e<t.length;e++)t[e]=l[e]*d;h=this.R.ColliderDesc.convexHull(t)}if(!h)continue;h.setTranslation(f,p,m);let g=(u[3]??0)*Math.PI/180;g!==0&&h.setRotation({x:0,y:Math.sin(g/2),z:0,w:Math.cos(g/2)}),this.world.createCollider(h,a)}this.scatterBodies.set(e,a)}}syncBodies(){let e=this.engine.scene;if(!e)return;let t=e.tree._structureVersion,n=e.root===this.lastRoot,r=t!==this.lastStructure||!n;if(r){let r=n?e.tree._structureSince(this.lastStructure):null;if(this.lastStructure=t,this.lastRoot=e.root,r){let t=!1,n=!1;for(let{node:e,added:i}of r)e instanceof $_&&(i?this.bodySet.add(e):this.bodySet.delete(e)),e instanceof ID&&(t=!0),e instanceof AD&&(n=!0);t&&(this.jointSet.clear(),MO(e.root,this.jointSet)),n&&this.syncScatters(e.root)}else this.bodySet.clear(),NO(e.root,this.bodySet),this.jointSet.clear(),MO(e.root,this.jointSet),this.syncScatters(e.root)}let i=this.bodySet;for(let e of i){if(e.collider.shape===void 0){let t=this.entries.get(e);t&&(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null,e._interpPrev=e._interpCurr=null),this.warnedNoCollider.has(e)||(this.warnedNoCollider.add(e),Nt(this.engine,`warn`,`[incanto] '${e.name}' has no collider — physics skips it.`));continue}let t=this.entries.get(e);t&&e._colliderChanged&&(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null,e._interpPrev=e._interpCurr=null),this.ensureEntry(e)}if(this.syncJoints(r),r)for(let[e,t]of this.entries)i.has(e)||(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null,e._interpPrev=e._interpCurr=null)}ensureEntry(e){let t=this.entries.get(e),n=this.R;if(!t){let r=XO(n,e);if(!r)return null;let i;i=e instanceof nv?n.RigidBodyDesc.dynamic():e instanceof rv||e instanceof tv?n.RigidBodyDesc.kinematicPositionBased():n.RigidBodyDesc.fixed();let[a,o,s]=qO(e);i.setTranslation(a,o,s),AO.setFromEuler(jO.set((e.rotation[0]??0)*DO,(e.rotation[1]??0)*DO,(e.rotation[2]??0)*DO,`XYZ`)),i.setRotation({x:AO.x,y:AO.y,z:AO.z,w:AO.w}),e instanceof nv&&(i.setGravityScale(e.gravityScale),i.setLinvel(e.linearVelocity[0]??0,e.linearVelocity[1]??0,e.linearVelocity[2]??0),e.fixedRotation&&i.lockRotations());let c=this.world.createRigidBody(i);r.setActiveEvents(n.ActiveEvents.COLLISION_EVENTS),r.setActiveCollisionTypes(n.ActiveCollisionTypes.ALL),e instanceof tv&&r.setSensor(!0),e instanceof nv&&r.setMass(e.mass).setFriction(e.friction).setRestitution(e.restitution);let l=this.world.createCollider(r,c);return t={body:c,collider:l,last:[a,o,s],lastRot:[e.rotation[0]??0,e.rotation[1]??0,e.rotation[2]??0],lastV:[0,0,0]},this.entries.set(e,t),this.byColliderHandle.set(l.handle,e),e.enabled||(l.setEnabled(!1),c.setEnabled(!1)),e._colliderChanged=!1,e._enabledChanged=!1,e._physics=this,e instanceof nv&&(e._physics3d=this),t}e._enabledChanged&&=(t.collider.setEnabled(e.enabled),t.body.setEnabled(e.enabled),!1);let r=qO(e);(r[0]!==t.last[0]||r[1]!==t.last[1]||r[2]!==t.last[2])&&(t.body.setTranslation({x:r[0],y:r[1],z:r[2]},!0),t.last[0]=r[0],t.last[1]=r[1],t.last[2]=r[2],e._interpPrev=e._interpCurr=null);let i=e.rotation[0]??0,a=e.rotation[1]??0,o=e.rotation[2]??0;if((i!==t.lastRot[0]||a!==t.lastRot[1]||o!==t.lastRot[2])&&(AO.setFromEuler(jO.set(i*DO,a*DO,o*DO,`XYZ`)),t.body.setRotation({x:AO.x,y:AO.y,z:AO.z,w:AO.w},!0),t.lastRot[0]=i,t.lastRot[1]=a,t.lastRot[2]=o),e instanceof nv){let n=[e.linearVelocity[0]??0,e.linearVelocity[1]??0,e.linearVelocity[2]??0];(n[0]!==t.lastV[0]||n[1]!==t.lastV[1]||n[2]!==t.lastV[2])&&(t.body.setLinvel({x:n[0],y:n[1],z:n[2]},!0),t.lastV=n),e.gravityScale!==t.body.gravityScale()&&t.body.setGravityScale(e.gravityScale,!0)}return t}applyImpulse(e,t){this.entries.get(e)?.body.applyImpulse({x:t[0],y:t[1],z:t[2]},!0)}massOf(e){return this.entries.get(e)?.body.mass()??1}velocityOf(e){let t=this.entries.get(e)?.body.linvel();return t?[t.x,t.y,t.z]:[0,0,0]}syncJoints(e){let t=this.R;if(e)for(let[e,t]of this.joints)this.jointSet.has(e)||(this.world.removeImpulseJoint(t,!0),this.joints.delete(e));for(let e of this.jointSet){if(this.joints.has(e))continue;let{a:n,b:r}=e._resolveBodies(),i=this.entries.get(n),a=this.entries.get(r);if(!i||!a)continue;let o={x:e.anchor[0]??0,y:e.anchor[1]??0,z:e.anchor[2]??0},s={x:e.targetAnchor[0]??0,y:e.targetAnchor[1]??0,z:e.targetAnchor[2]??0},c=e.length;if(e.length===0&&(e.type===`rope`||e.type===`spring`)){let e=i.body.translation(),t=a.body.translation();c=Math.hypot(t.x-e.x,t.y-e.y,t.z-e.z)}let l={x:0,y:0,z:0,w:1},u;u=e.type===`fixed`?t.JointData.fixed(o,l,s,l):e.type===`rope`?t.JointData.rope(c,o,s):e.type===`spring`?t.JointData.spring(c,e.stiffness,e.damping,o,s):t.JointData.spherical(o,s),this.joints.set(e,this.world.createImpulseJoint(u,i.body,a.body,!0))}}castRay(e,t,n,r,i){let a=new this.R.Ray({x:e[0],y:e[1],z:e[2]},{x:t[0],y:t[1],z:t[2]}),o=r?this.entries.get(r)?.collider:void 0,s=i?.staticOnly?this.R.QueryFilterFlags.EXCLUDE_DYNAMIC|this.R.QueryFilterFlags.EXCLUDE_KINEMATIC:void 0,c=this.world.castRayAndGetNormal(a,n,!0,s,void 0,o,void 0,e=>!e.isSensor());return c?{distance:c.timeOfImpact,normal:[c.normal.x,c.normal.y,c.normal.z],node:this.byColliderHandle.get(c.collider.handle)??null}:null}castSphere(e,t,n,r,i,a){let o=this.R,s=i?this.entries.get(i):void 0,c=a?.staticOnly?o.QueryFilterFlags.EXCLUDE_DYNAMIC|o.QueryFilterFlags.EXCLUDE_KINEMATIC:void 0,l=this.world.castShape({x:e[0],y:e[1],z:e[2]},{x:0,y:0,z:0,w:1},{x:t[0],y:t[1],z:t[2]},new o.Ball(n),0,r,!0,c,void 0,s?.collider,s?.body,e=>!e.isSensor());return l?{distance:l.time_of_impact,node:this.byColliderHandle.get(l.collider.handle)??null}:null}},AO=new U,jO=new cc;function MO(e,t){e instanceof ID&&t.add(e);for(let n of e.children)MO(n,t)}function NO(e,t){e instanceof $_&&t.add(e);for(let n of e.children)NO(n,t)}function PO(e,t,n,r,i){let a=r[0]??1,o=r[1]??1,s=r[2]??1,c=(n[0]??1)*a,l=(n[1]??1)*o,u=(n[2]??1)*s,d=Math.max(Math.abs(a),Math.abs(s));switch(i&&t!==`box`&&t!==`plane`&&Math.abs(a-s)>1e-6&&console.warn(`[incanto] Collider on '${i}': shape 'auto' fits a ${t} to a mesh scaled [${a}, ${o}, ${s}]. A ${t} has one radius, so the widest of x/z (${d}) is used. Use a box, or scale x and z the same.`),t){case`box`:return e.ColliderDesc.cuboid(c/2,l/2,u/2);case`sphere`:return e.ColliderDesc.ball((n[0]??1)*Math.max(d,Math.abs(o)));case`capsule`:return e.ColliderDesc.capsule(l/2,(n[0]??1)*d);case`cylinder`:return e.ColliderDesc.cylinder(l/2,(n[0]??1)*d);case`plane`:return e.ColliderDesc.cuboid(c/2,.01,u/2);default:return e.ColliderDesc.convexHull(FO(t,[c,l,u]))}}function FO(e,t){let n=kD(e,t),r=n.getAttribute(`position`),i=new Float32Array(r.count*3);for(let e=0;e<r.count;e++)i[e*3]=r.getX(e),i[e*3+1]=r.getY(e),i[e*3+2]=r.getZ(e);return n.dispose(),i}function IO(e){return typeof e._mountedObject3D==`function`}var LO=new K,RO=new K,zO=new W;function BO(e,t){let n=t._mountedObject3D();if(!n)return null;let r=e._ensureObject3D();r.updateWorldMatrix(!0,!0),LO.copy(r.matrixWorld).invert();let i=[],a=[];return n.traverse(e=>{let t=e;if(!t.isMesh)return;let n=t.geometry?.getAttribute(`position`);if(!n)return;RO.multiplyMatrices(LO,t.matrixWorld);let r=i.length/3;for(let e=0;e<n.count;e++)zO.set(n.getX(e),n.getY(e),n.getZ(e)).applyMatrix4(RO),i.push(zO.x,zO.y,zO.z);let o=t.geometry.getIndex();if(o)for(let e=0;e<o.count;e++)a.push(r+o.getX(e));else for(let e=0;e<n.count;e++)a.push(r+e)}),a.length<3?null:{vertices:new Float32Array(i),indices:new Uint32Array(a),triangles:a.length/3}}var VO=2e4;function HO(e){return!(e instanceof nv||e instanceof rv)}function UO(e,t,n,r=[0,0,0],i=[0,0,0],a=[1,1,1]){if(IO(e))n.push(e);else{let n=e;typeof n.mesh==`string`&&Array.isArray(n.size)&&t.push({name:e.name,mesh:n.mesh,size:n.size,at:[...r],turn:[...i],scale:[...a]})}for(let o of e.children){let e=o,s=Array.isArray(e.position)?e.position:[],c=Array.isArray(e.rotation)?e.rotation:[],l=Array.isArray(e.scale)?e.scale:[];UO(o,t,n,[r[0]+(s[0]??0)*a[0],r[1]+(s[1]??0)*a[1],r[2]+(s[2]??0)*a[2]],[i[0]+(c[0]??0),i[1]+(c[1]??0),i[2]+(c[2]??0)],[a[0]*(l[0]??1),a[1]*(l[1]??1),a[2]*(l[2]??1)])}}function WO(e,t){e instanceof AD&&e.collider&&t.add(e);for(let n of e.children)WO(n,t)}var GO=[0,0,0];function KO(e){let t=e.collider;return t?t.shape===`capsule`&&typeof t.height==`number`?t.height/2+(t.radius??0):t.shape===`box`&&Array.isArray(t.size)?(t.size[1]??2)/2:t.shape===`sphere`&&typeof t.radius==`number`?t.radius:1:1}function qO(e){let t=0,n=0,r=0;for(let i=e;i;i=i.parent)i instanceof Q_&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return GO[0]=t,GO[1]=n,GO[2]=r,GO}var JO=[0,0,0];function YO(e){let t=0,n=0,r=0;for(let i=e.parent;i;i=i.parent)i instanceof Q_&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return JO[0]=t,JO[1]=n,JO[2]=r,JO}function XO(e,t){let n=t.collider;if(X_(n,t.name),n.shape===`heightfield`)return ZO(e,t);let r=QO(e,n,t.name,t);if(!r)return null;let i=n.offset;if(Array.isArray(i)){let e=r.translation;r.setTranslation(e.x+(i[0]??0),e.y+(i[1]??0),e.z+(i[2]??0))}return r}function ZO(e,t){let n=t.children.find(e=>e instanceof hO);if(!n)throw new L(`BAD_FORMAT`,`Collider on '${t.name}': heightfield needs a Terrain3D CHILD of this body — add { "type": "Terrain3D" } under the StaticBody3D; the collider reads its height grid.`,{prop:`collider`});let r=n._heightmap(),i=r.segsZ,a=r.segsX,o=new Float32Array((i+1)*(a+1));for(let e=0;e<=a;e++)for(let t=0;t<=i;t++)o[e*(i+1)+t]=r.heights[t*(a+1)+e];let s=e.ColliderDesc.heightfield(i,a,o,{x:r.width,y:1,z:r.depth}),c=Array.isArray(t.collider.offset)?t.collider.offset:[];return s.setTranslation((n.position[0]??0)+(c[0]??0),(n.position[1]??0)+(c[1]??0),(n.position[2]??0)+(c[2]??0)),s}function QO(e,t,n,r){let i=t.shape;if(i===`box`){let r=t.size;if(!Array.isArray(r)||r.length!==3||r.some(e=>typeof e!=`number`))throw new L(`BAD_FORMAT`,`Collider on '${n}': box needs "size": [x, y, z].`);return e.ColliderDesc.cuboid(r[0]/2,r[1]/2,r[2]/2)}if(i===`sphere`){if(typeof t.radius!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${n}': sphere needs "radius".`);return e.ColliderDesc.ball(t.radius)}if(i===`capsule`){if(typeof t.radius!=`number`||typeof t.height!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${n}': capsule needs "radius" and "height".`);return e.ColliderDesc.capsule(t.height/2,t.radius)}if(i===`auto`){let t=[],i=[];r&&UO(r,t,i);let a=t[0],o=i[0];if(!a&&!o)throw new L(`BAD_FORMAT`,`Collider on '${n}': shape 'auto' needs a MeshInstance3D or ModelInstance3D on the body (or as a child) to take its shape from.`);let s=t.length+i.length;if(s>1&&console.warn(`[incanto] Collider on '${n}': shape 'auto' fits ONE mesh and took '${(a??o)?.name}'; ${s-1} other mesh(es) here are not solid. Give each part its own body.`),a){let t=PO(e,a.mesh,a.size,a.scale,n);if(t)return t.setTranslation(a.at[0],a.at[1],a.at[2]),(a.turn[0]!==0||a.turn[1]!==0||a.turn[2]!==0)&&(AO.setFromEuler(jO.set(a.turn[0]*DO,a.turn[1]*DO,a.turn[2]*DO,`XYZ`)),t.setRotation({x:AO.x,y:AO.y,z:AO.z,w:AO.w})),t}else if(o&&r){let t=BO(r,o);return t?HO(r)?(t.triangles>VO&&console.warn(`[incanto] Collider on '${n}': shape 'auto' built a ${t.triangles}-triangle mesh from '${o.name}'. Consider a low-poly collision model or an explicit box.`),e.ColliderDesc.trimesh(t.vertices,t.indices)):e.ColliderDesc.convexHull(t.vertices):null}}if(i===`trimesh`){let r=t.vertices,i=t.indices;if(!Array.isArray(r)||!Array.isArray(i))throw new L(`BAD_FORMAT`,`Collider on '${n}': trimesh needs "vertices" (flat xyz) and "indices" (triangles).`);return e.ColliderDesc.trimesh(new Float32Array(r),new Uint32Array(i))}throw new L(`BAD_FORMAT`,`Collider on '${n}': "shape" must be 'auto', 'box', 'sphere', 'capsule', 'trimesh', or 'heightfield', got ${JSON.stringify(i)}.`)}var $O=new _d(1,1),ek=null;function tk(){if(ek)return ek;if(typeof document>`u`)return null;let e=document.createElement(`canvas`);e.width=64,e.height=64;let t=e.getContext(`2d`);if(!t)return null;let n=t.createRadialGradient(32,32,0,32,32,31);return n.addColorStop(0,`rgba(0,0,0,0.55)`),n.addColorStop(.55,`rgba(0,0,0,0.34)`),n.addColorStop(1,`rgba(0,0,0,0)`),t.fillStyle=n,t.fillRect(0,0,64,64),ek=new sd(e),ek}var nk=new W(0,0,1),rk=new W,ik=new W,ak=new U,ok=new U,sk=new W,ck=.5,lk=class extends Q_{static typeName=`Sprite3D`;static props={texture:{default:``},size:{default:[1,1]},billboard:{default:`y`,options:[`y`,`full`,`none`]},anchor:{default:[.5,0]},tint:{default:`#ffffff`},opacity:{default:1},flipX:{default:!1},pixelArt:{default:!0},alphaTest:{default:.5},castShadow:{default:!1},shadowMode:{default:`silhouette`,options:[`silhouette`,`blob`]}};texture=``;size=[1,1];billboard=`y`;anchor=[.5,0];tint=`#ffffff`;opacity=1;flipX=!1;pixelArt=!0;alphaTest=.5;castShadow=!1;shadowMode=`silhouette`;quadMesh=null;textureRef=``;loadedTexture=null;shadowMesh=null;blobMesh=null;_quad(){return this.quadMesh||(this.quadMesh=new iu($O,new Kl({transparent:!1,depthWrite:!0,side:2})),this._ensureObject3D().add(this.quadMesh)),this.quadMesh}resolveTexture(e){return this.texture?(this.textureRef!==this.texture&&(this.textureRef=this.texture,this.loadedTexture=uD(e,this.texture,{filter:this.pixelArt?`nearest`:`linear`})),this.loadedTexture):null}_syncObject3D(e=1,t=null){super._syncObject3D(e,t);let n=this._quad(),r=n.material,i=this.size[0]??1,a=this.size[1]??1;n.scale.set(this.flipX?-i:i,a,1);let o=this.anchor[0]??.5,s=this.anchor[1]??0;n.position.set((.5-o)*i,(.5-s)*a,0);let c=this.resolveTexture(t);r.map!==c&&(r.map=c,r.needsUpdate=!0),n.visible=c!==null,r.color.set(this.tint),r.opacity=this.opacity,r.transparent=this.opacity<1,r.alphaTest=this.alphaTest,n.renderOrder=this.renderOrder;let l=this.castShadow&&c!==null;if(n.castShadow=!1,l&&this.shadowMode===`silhouette`){let e=this._shadowCaster();e.visible=!0,e.castShadow=!0,e.scale.set(this.flipX?-i:i,a,1),e.position.set((.5-o)*i,(.5-s)*a,0);let t=e.material;t.map!==c&&(t.map=c,t.needsUpdate=!0);let n=e.customDepthMaterial;n.map!==c&&(n.map=c,n.needsUpdate=!0),t.alphaTest=this.alphaTest,n.alphaTest=this.alphaTest}else this.shadowMesh&&(this.shadowMesh.visible=!1,this.shadowMesh.castShadow=!1);if(l&&this.shadowMode===`blob`){let e=this._blob();e.visible=!0,e.scale.set(i*.52,i*.52,1)}else this.blobMesh&&(this.blobMesh.visible=!1)}_shadowCaster(){return this.shadowMesh||(this.shadowMesh=new iu($O,new Kl({colorWrite:!1,depthWrite:!1,side:2})),this.shadowMesh.customDepthMaterial=new jd({depthPacking:Lo,side:2}),this._ensureObject3D().add(this.shadowMesh)),this.shadowMesh}_blob(){return this.blobMesh||(this.blobMesh=new iu($O,new Kl({map:tk(),color:0,transparent:!0,depthWrite:!1})),this.blobMesh.rotation.x=-Math.PI/2,this.blobMesh.position.y=.02,this.blobMesh.renderOrder=-1,this._ensureObject3D().add(this.blobMesh)),this.blobMesh}_onRender3D(e){this.billboard===`y`?(e.camera.getWorldDirection(ik),ik.y=0,ik.lengthSq()>=1e-6&&this._faceDir(this._quad(),ik.negate())):this.billboard===`full`&&this._faceToward(this._quad(),e.camera.position);let t=this.shadowMesh;t?.castShadow&&e.sunDir&&(this._faceDir(t,e.sunDir),t.parent?.getWorldQuaternion(ok),sk.copy(e.sunDir).applyQuaternion(ok.invert()),t.position.addScaledVector(sk,ck))}_faceToward(e,t){e.getWorldPosition(rk),ik.copy(t).sub(rk),this.billboard===`y`&&(ik.y=0),!(ik.lengthSq()<1e-12)&&(ik.normalize(),ak.setFromUnitVectors(nk,ik),e.parent?.getWorldQuaternion(ok),e.quaternion.copy(ok.invert()).multiply(ak))}_faceDir(e,t){ik.copy(t),this.billboard===`y`&&(ik.y=0),!(ik.lengthSq()<1e-12)&&(ik.normalize(),ak.setFromUnitVectors(nk,ik),e.parent?.getWorldQuaternion(ok),e.quaternion.copy(ok.invert()).multiply(ak))}free(){this.loadedTexture?.dispose(),this.loadedTexture=null,this.shadowMesh&&(this.shadowMesh.material.dispose(),this.shadowMesh.customDepthMaterial?.dispose()),this.blobMesh&&this.blobMesh.material.dispose(),super.free()}},uk=class extends lk{static typeName=`AnimatedSprite3D`;static signals=[`animationFinished`];static props={sheet:{default:``},frameWidth:{default:0},frameHeight:{default:0},animations:{default:{}},autoplay:{default:``}};sheet=``;frameWidth=0;frameHeight=0;animations={};autoplay=``;playing=!1;currentFrame=0;currentAnimation=``;frameList=[];frameIndex=0;frameTime=0;currentDef=null;sheetTexture=null;loadedSheetRef=``;play(e){let{name:t,def:n}=Zi(this.animations,e,this.name);this.currentAnimation=t,this.currentDef=n,this.frameList=$i(n.frames,t),this.frameIndex=0,this.currentFrame=this.frameList[0]??0,this.frameTime=0,this.playing=!0}stop(){this.playing=!1}onReady(){Qi(this.animations,this.name),this.autoplay&&this.play(this.autoplay)}update(e){if(!this.playing||this.currentAnimation===``)return;let t=this.currentDef;if(!t||!Number.isFinite(t.fps)||t.fps<=0)return;let n=1/t.fps;for(this.frameTime+=e;this.frameTime>=n;)if(this.frameTime-=n,this.frameIndex+=1,this.frameIndex>=this.frameList.length)if(t.loop)this.frameIndex=0;else{this.frameIndex=this.frameList.length-1,this.playing=!1,this.emit(`animationFinished`,this.currentAnimation);break}this.currentFrame=this.frameList[this.frameIndex]??0}checkGrid(e,t){if(this.gridChecked===this.sheet)return;this.gridChecked=this.sheet;let n=0;for(let[e,t]of Object.entries(this.animations))if(typeof t!=`string`)try{for(let r of $i(t.frames,e))r>n&&(n=r)}catch{return}let r=Qb(this.sheet,this.frameWidth,this.frameHeight,e,t,n);r&&Nt(this.tree?.engine??null,`error`,r)}gridChecked=``;sizeReported=!1;resolveTexture(e){if(!this.sheet)return null;if(this.frameWidth<=0||this.frameHeight<=0)return this.sizeReported||(this.sizeReported=!0,Nt(this.tree?.engine??null,`error`,`[incanto] AnimatedSprite3D '${this.name}' has a sheet ('${this.sheet}') but frameWidth/frameHeight are 0 — it draws nothing. Set both to one frame's pixel size (bunx incanto-assets info <name> prints it for a built-in).`)),null;this.loadedSheetRef!==this.sheet&&(this.sheetTexture?.dispose(),this.loadedSheetRef=this.sheet,this.sheetTexture=dD(e,this.sheet,{filter:this.pixelArt?`nearest`:`linear`}));let t=this.sheetTexture;if(!t)return null;let n=t.image;if(!n?.width||!n.height)return t;this.checkGrid(n.width,n.height);let r=Math.max(1,Math.floor(n.width/this.frameWidth)),i=this.currentFrame%r,a=Math.floor(this.currentFrame/r);return t.repeat.set(this.frameWidth/n.width,this.frameHeight/n.height),t.offset.set(i*this.frameWidth/n.width,1-(a+1)*this.frameHeight/n.height),t}free(){this.sheetTexture?.dispose(),this.sheetTexture=null,super.free()}},dk=new U,fk=new U,pk=new W,mk=new W(0,0,1),hk=[`screen`,`y`,`none`],gk=class extends Q_{static typeName=`Billboard3D`;static props={mode:{default:`screen`,options:hk}};mode=`screen`;_lastDesired=null;static validateJson(e){let t=e;if(!hk.includes(t.mode))throw new L(`BAD_FORMAT`,`Billboard3D '${e.name}' mode must be one of [${hk.join(`, `)}], got '${t.mode}'.`,{prop:`mode`,validOptions:hk})}_onRender3D(e){if(this.mode===`none`)return;let t=this._ensureObject3D();if(this.mode===`screen`)e.camera.getWorldQuaternion(fk);else if(e.camera.getWorldDirection(pk),pk.y=0,pk.lengthSq()>=1e-6)fk.setFromUnitVectors(mk,pk.negate().normalize());else if(this._lastDesired)fk.copy(this._lastDesired);else return;this._lastDesired||=new U,this._lastDesired.copy(fk),t.parent?.getWorldQuaternion(dk),t.parent?t.quaternion.copy(dk.invert()).multiply(fk):t.quaternion.copy(fk)}},_k=class extends Q_{static typeName=`BoneAttachment3D`;static props={target:{default:``,nodePath:!0,required:!0},bone:{default:``}};target=``;bone=``;boneObj=null;lookedUpFor=``;get attachedBone(){return this.boneObj}_onRender3D(e){if(this.target===``||this.bone===``)return;let t=`${this.target} ${this.bone}`;if(this.lookedUpFor!==t||this.boneObj===null||!this.boneObj.parent){this.lookedUpFor=t,this.boneObj=null;let e=this.getNodeOrNull(this.target);this.source=e,e&&typeof e.findBone==`function`&&(this.boneObj=e.findBone(this.bone))}let n=this.boneObj;if(!n){this.reportMissingBone();return}let r=this._ensureObject3D(),i=r.parent;i&&(n.updateWorldMatrix(!0,!1),i.updateWorldMatrix(!0,!1),r.matrixAutoUpdate=!1,n.matrixWorld.decompose(bk,xk,Sk),yk.compose(bk,xk,Ck),r.updateMatrix(),vk.copy(r.matrix),r.matrix.copy(i.matrixWorld).invert().multiply(yk).multiply(vk))}free(){this.boneObj=null,super.free()}source=null;reportedBone=``;reportMissingBone(){if(this.reportedBone===this.bone)return;let e=this.source?.boneNames?.()??[];if(e.length===0)return;this.reportedBone=this.bone;let t=e.slice(0,8).join(`, `);Nt(this.tree?.engine??null,`error`,`[incanto] ${this.getPath()}: '${this.target}' has no bone '${this.bone}'. It has ${e.length}: [${t}${e.length>8?`, …`:``}].`)}},vk=new K,yk=new K,bk=new W,xk=new U,Sk=new W,Ck=new W(1,1,1),wk=class extends Q_{static typeName=`BoneLookAt3D`;static props={target:{default:``,nodePath:!0,required:!0},bone:{default:`Head`},lookAt:{default:``,nodePath:!0},maxAngleDeg:{default:75},weight:{default:.85,range:{min:0,max:1}},forwardAxis:{default:`+z`,options:[`+x`,`-x`,`+y`,`-y`,`+z`,`-z`]}};target=``;bone=`Head`;lookAt=``;maxAngleDeg=75;weight=.85;forwardAxis=`+z`;boneObj=null;lookedUpFor=``;engage=0;get attachedBone(){return this.boneObj}_onRender3D(e){if(this.target===``||this.bone===``)return;let t=`${this.target} ${this.bone}`;if(this.lookedUpFor!==t||this.boneObj===null||!this.boneObj.parent){this.lookedUpFor=t,this.boneObj=null;let e=this.getNodeOrNull(this.target);e&&typeof e.findBone==`function`&&(this.boneObj=e.findBone(this.bone))}let n=this.boneObj;if(!n?.parent)return;let r=this.lookAt===``?null:this.getNodeOrNull(this.lookAt),i=!1;if(r&&Array.isArray(r.position)&&(n.updateWorldMatrix(!0,!1),n.getWorldPosition(Ak),jk.set(r.position[0]??0,r.position[1]??0,r.position[2]??0),Mk.copy(jk).sub(Ak),Mk.lengthSq()>1e-6&&(Mk.normalize(),Nk.copy(Ek[this.forwardAxis]??Ok),Pk.copy(Nk).applyQuaternion(n.getWorldQuaternion(zk)),Pk.angleTo(Mk)<this.maxAngleDeg*Math.PI/180))){i=!0,Fk.lookAt(Ak,jk,Dk),Ik.setFromRotationMatrix(Fk),Lk.setFromUnitVectors(Nk,kk),Ik.multiply(Lk),n.parent.getWorldQuaternion(Rk).invert(),Ik.premultiply(Rk);let e=this.weight*this.engage;n.quaternion.slerp(Ik,e)}this.engage+=(+!!i-this.engage)*Tk}},Tk=.18,Ek={"+x":new W(1,0,0),"-x":new W(-1,0,0),"+y":new W(0,1,0),"-y":new W(0,-1,0),"+z":new W(0,0,1),"-z":new W(0,0,-1)},Dk=new W(0,1,0),Ok=new W(0,0,1),kk=new W(0,0,-1),Ak=new W,jk=new W,Mk=new W,Nk=new W,Pk=new W,Fk=new K,Ik=new U,Lk=new U,Rk=new U,zk=new U,Bk=class extends Q_{static typeName=`Camera3D`;static props={fov:{default:60},near:{default:.1},far:{default:1e3},current:{default:!1}};fov=60;near=.1;far=1e3;current=!1;_createObject3D(){return new Cf(this.fov,1,this.near,this.far)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();(e.fov!==this.fov||e.near!==this.near||e.far!==this.far)&&(e.fov=this.fov,e.near=this.near,e.far=this.far,e.updateProjectionMatrix())}},Vk=8,Hk=.15,Uk=1.2,Wk=.08,Gk=-20;function Kk(e){let t=aA.props[e];return typeof t?.default==`string`?t.default:``}var qk=.002,Jk=180/Math.PI,Yk=.3,Xk=.4,Zk=.3,Qk=.25,$k=new cc,eA=new U,tA=new K,nA=new W,rA=new W,iA=new W(0,1,0),aA=class extends Q_{static typeName=`CharacterController3D`;static signals=[`movementStateChanged`];static props={view:{default:`free`,options:[`free`,`firstPerson`,`quarter`,`side`]},camDistance:{default:4},eyeHeight:{default:.64},maxSpeed:{default:2.5},sprintMultiplier:{default:2},jumpVelocity:{default:4},sprintJumpMultiplier:{default:1.2},coyoteSeconds:{default:0},jumpBufferSeconds:{default:0},jumpCutMultiplier:{default:1},maxJumps:{default:1},airControl:{default:.2},fallGravity:{default:2.5},floatHeight:{default:.01},mouseLook:{default:!0},zoomMin:{default:0},zoomMax:{default:0},pitchMin:{default:-1.3},pitchMax:{default:1.5},cameraCollision:{default:!0},turnSpeed:{default:100},camLerp:{default:25},moveAction:{default:`move`},jumpAction:{default:`jump`},sprintAction:{default:`sprint`},skinPath:{default:`../Skin`,nodePath:!0},skinYawOffset:{default:0},animations:{default:{}}};view=`free`;camDistance=4;eyeHeight=.64;maxSpeed=2.5;sprintMultiplier=2;jumpVelocity=4;sprintJumpMultiplier=1.2;coyoteSeconds=0;jumpBufferSeconds=0;jumpCutMultiplier=1;maxJumps=1;airControl=.2;fallGravity=2.5;floatHeight=.01;mouseLook=!0;zoomMin=0;zoomMax=0;pitchMin=-1.3;pitchMax=1.5;cameraCollision=!0;turnSpeed=100;camLerp=25;moveAction=`move`;jumpAction=`jump`;sprintAction=`sprint`;skinPath=`../Skin`;skinYawOffset=0;animations={};yaw=0;pitch=0;state=`idle`;grounded=!1;coyoteLeft=0;bufferLeft=0;jumpsUsed=0;rising=!1;jumping=!1;get body(){let e=this.parent;if(!(e instanceof nv))throw new L(`TREE_VIOLATION`,`CharacterController3D '${this.name}' must be a child of a RigidBody3D (parent is '${e?.name??`none`}').`);return e}onEnterTree(){if(this.body,this.skinPath!==``){let e=this.getNodeOrNull(this.skinPath);e&&(e.rotation=[e.rotation[0]??0,180+this.skinYawOffset,e.rotation[2]??0])}}fixedUpdate(e){let t=this.body,n=t._physics3d,r=this.tree?.engine?.input;if(!n||!r)return;let i=t.collider.radius??.32,a=(t.collider.height??1)/2,o=sA(t),s=n.velocityOf(t),c=n.massOf(t),l=i+this.floatHeight,u=i+2,d=o[1]-a,f=null;for(let[e,r]of[[0,0],[i,0],[-i,0],[0,i],[0,-i]]){let i=n.castRay([o[0]+e,d,o[2]+r],[0,-1,0],u,t);if(i){let t=i.distance;if(f=f===null?t:Math.min(f,t),e===0&&r===0)break}}this.grounded=f!==null&&f<l*2;let p=f!==null&&f<l*1.3&&(s[1]??0)<=.5,m=0,h=0,g=!1;try{let e=r.getVector(this.moveAction);g=e.x!==0||e.y!==0;let t=this.view===`free`||this.view===`firstPerson`?this.yaw:0,n=this.view===`side`?[e.x,0,0]:yD(e.x,-e.y,t),i=Math.hypot(n[0],n[2])||1;m=n[0]/i,h=n[2]/i}catch(e){this.reportMissingAction(`moveAction`,e,`The character will not move.`)}let _=this.readAction(`sprintAction`,()=>r.isPressed(this.sprintAction),!1,`Sprint will never engage.`),v=bD(g,_),y=1+(this.sprintMultiplier-1)*v,b=g?this.maxSpeed*y:0,x=this.grounded?1:this.airControl,S=(m*b-s[0])/Vk*x,C=(h*b-s[2])/Vk*x;if(t.applyImpulse([S*c,0,C*c]),!g&&this.grounded&&t.applyImpulse([-s[0]*Hk*c,0,-s[2]*Hk*c]),f!==null&&f<l*2&&!this.jumping){let e=Uk*(l-f)-s[1]*Wk;t.applyImpulse([0,e*c,0])}p?(this.coyoteLeft=this.coyoteSeconds,this.jumpsUsed=0,this.rising=!1,this.jumping=!1):(this.coyoteLeft=Math.max(0,this.coyoteLeft-e),!this.grounded&&this.coyoteLeft<=0&&this.jumpsUsed===0&&(this.jumpsUsed=1));let w=this.readAction(`jumpAction`,()=>r.justPressed(this.jumpAction),!1,`The character will never jump.`);if(w?this.bufferLeft=Math.max(this.jumpBufferSeconds,0):this.bufferLeft=Math.max(0,this.bufferLeft-e),(this.bufferLeft>0||w)&&(p||this.coyoteLeft>0||this.jumpsUsed<this.maxJumps)){let e=this.jumpVelocity*(1+(this.sprintJumpMultiplier-1)*v);t.linearVelocity=[s[0],e,s[2]],this.grounded=!1,this.jumpsUsed+=1,this.bufferLeft=0,this.coyoteLeft=0,this.rising=!0,this.jumping=!0,s[1]=e}if(this.rising){if((s[1]??0)<=0)this.rising=!1;else if(this.jumpCutMultiplier<1&&!this.readAction(`jumpAction`,()=>r.isPressed(this.jumpAction),!1,`The character will never jump.`)){let e=(s[1]??0)*this.jumpCutMultiplier;t.linearVelocity=[s[0],e,s[2]],s[1]=e,this.rising=!1}}(s[1]??0)<Gk?t.gravityScale=0:(s[1]??0)<0&&!p?t.gravityScale=this.fallGravity:t.gravityScale=1,this.view===`side`&&Math.abs(o[2])>.01&&(t.position=[t.position[0]??0,t.position[1]??0,0]);let T=xD(!(this.jumping||!this.grounded),g?v:0);if(T!==this.state){this.state=T;let e=this.animations[T];if(e&&this.skinPath!==``){let t=this.getNodeOrNull(this.skinPath);t&&`animation`in t&&(t.animation=e)}this.emit(`movementStateChanged`,T)}if(g&&this.skinPath!==``){let t=this.getNodeOrNull(this.skinPath);if(t){let n=Math.atan2(m,h)*Jk+this.skinYawOffset,r=t.rotation[1]??0,i=(n-r+540)%360-180,a=this.turnSpeed*e*Jk;Math.abs(i)>a&&(i=Math.sign(i)*a),t.rotation=[t.rotation[0]??0,r+i,t.rotation[2]??0]}}}reportedActions=new Set;readAction(e,t,n,r){let i=this[e];return Xy({engine:this.tree?.engine,who:this.getPath(),reported:this.reportedActions,consequence:r,authored:i!==Kk(e)},i,t,n)}reportMissingAction(e,t,n){this.readAction(e,()=>{throw t},void 0,n)}update(e){let t=this.tree?.engine?.input;if(!t)return;if(this.mouseLook){let e=t.pointerDelta(),n=this.tree?.engine?.settings,r=n?.get(`sensitivity`)??1,i=n?.get(`invertY`)??!1,a=qk*(typeof r==`number`&&r>0?r:1);this.yaw-=e.x*a,this.pitch=oA(this.pitch+(i===!0?-e.y:e.y)*a,-this.pitchMax,-this.pitchMin);let o=t.wheelDelta();o!==0&&this.zoomMax>this.zoomMin&&(this.camDistance=oA(this.camDistance+o*qk,this.zoomMin,this.zoomMax))}let n=this.findCamera();if(!n)return;let r=this.parent instanceof nv?this.parent:null;if(!r)return;let i=sA(r),a=this.view===`free`?11:1e3,o=1-Math.exp(-a*e),s=this.pivot??[i[0],i[1],i[2]];this.pivot=s,s[0]+=(i[0]-s[0])*o,s[1]+=(i[1]-s[1])*o,s[2]+=(i[2]-s[2])*o;let c=gD(this.view,s,this.eyeHeight,this.yaw,this.pitch,this.camDistance),l=[s[0],s[1]+this.eyeHeight,s[2]],u=[c.position[0],c.position[1],c.position[2]];if(this.cameraCollision&&this.view!==`firstPerson`){let e=r._physics3d;e&&(u=_D(l,u,(t,n,i)=>e.castSphere(t,n,Qk,i,r,{staticOnly:!0})?.distance??null,Yk,Xk),u=vD(u,(t,n)=>e.castRay(t,[0,-1,0],n,r,{staticOnly:!0})?.distance??null,Zk))}let d=this.view===`firstPerson`?1e3:this.camLerp,f=1-Math.exp(-d*e),p=n.position;n.position=[(p[0]??0)+(u[0]-(p[0]??0))*f,(p[1]??0)+(u[1]-(p[1]??0))*f,(p[2]??0)+(u[2]-(p[2]??0))*f],this.view===`free`?(nA.set(n.position[0]??0,n.position[1]??0,n.position[2]??0),rA.set(l[0],l[1],l[2]),tA.lookAt(nA,rA,iA),eA.setFromRotationMatrix(tA),$k.setFromQuaternion(eA,`XYZ`)):($k.set(c.rotation[0],c.rotation[1],c.rotation[2],`YXZ`),eA.setFromEuler($k),$k.setFromQuaternion(eA,`XYZ`)),n.rotation=[$k.x*Jk,$k.y*Jk,$k.z*Jk]}pivot=null;cameraCache=null;findCamera(){if(this.cameraCache?.tree===this.tree&&this.cameraCache.current)return this.cameraCache;this.cameraCache=null;let e=this.tree?.root;if(!e)return null;let t=e=>{if(!this.cameraCache){if(e instanceof Bk&&e.current){this.cameraCache=e;return}for(let n of e.children)t(n)}};return t(e),this.cameraCache}};function oA(e,t,n){return Math.min(n,Math.max(t,e))}function sA(e){let t=0,n=0,r=0;for(let i=e;i&&i instanceof Q_;i=i.parent)t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0;return[t,n,r]}var cA=.15,lA=.7,uA=.5,dA=.7,fA=.5;function pA(e,t,n=3){let r=0,i=1,a=1,o=.65;for(let s=0;s<n;s++){let n=e*a,s=t*a,c=Math.sin(n*.1+s*.2)*.5+.5,l=Math.cos(n*.3+s*.1)*.5+.5,u=Math.sin((n+s)*.15)*.5+.5,d=Math.cos(n*n*.01+s*.2)*.5+.5,f=c*l*.7+u*d*.3;r+=f*i,i*=o,a*=2}return r/((1-o**n)/(1-o))}function mA(e,t){let n=pA(e*cA,t*cA,4),r=pA(e*cA*.2,t*cA*.2,2);return n>uA-lA*.5-r*fA}var hA=.9;function gA(e,t,n){let r=(Math.imul(e,2246822507)^Math.imul(t,3266489909)^Math.imul(n+1,668265263))>>>0;return r=Math.imul(r^r>>>15,739982445)>>>0,r=Math.imul(r^r>>>12,695872825)>>>0,r^=r>>>15,(r>>>0)/4294967296}function _A(e,t,n=hA){let r=Math.floor(e/n),i=Math.floor(t/n),a=1/0,o=r,s=i;for(let c=-1;c<=1;c++)for(let l=-1;l<=1;l++){let u=r+l,d=i+c,f=(u+gA(u,d,0))*n,p=(d+gA(u,d,1))*n,m=(e-f)*(e-f)+(t-p)*(t-p);m<a&&(a=m,o=u,s=d)}return{id:Math.imul(o,2654435761)^Math.imul(s,2246822519)|0,hue:gA(o,s,2)*2-1,leanDir:gA(o,s,3)*Math.PI*2,lean:gA(o,s,4)}}function vA(e,t,n,r){let i=e*r,a=t*r,o=Math.floor(i),s=Math.floor(a),c=i-o,l=a-s,u=c*c*(3-2*c),d=l*l*(3-2*l),f=gA(o,s,n),p=gA(o+1,s,n),m=gA(o,s+1,n),h=gA(o+1,s+1,n),g=f+(p-f)*u;return g+(m+(h-m)*u-g)*d}var yA=[.55,1.7],bA=.17,xA=.23,SA=.28;function CA(e,t,n){let r=vA(e,t,n^6877377|0,bA),i=r*r*(3-2*r);return yA[0]+(yA[1]-yA[0])*i}function wA(e,t,n){return vA(e,t,n^3001105|0,xA)}function TA(e,t,n){let r=vA(e,t,n^7840757|0,SA)*.72+vA(e,t,n^1688295|0,SA*3.1)*.28,i=Math.min(1,Math.max(0,(r-.18)/.64));return i*i*(3-2*i)}function EA(e){let{seed:t,areaX:n,areaZ:r,count:i,density:a}=e,o=new Ee(t),s=n/2,c=r/2,l=[],u=Math.floor(i*dA);for(let e=0;e<u&&l.length<i;e++){let e=o.range(-s,s),t=o.range(-c,c),n=o.next()<.3,r=mA(e,t);if(!n&&!r&&o.next()>.15)continue;let i=o.next()*Math.PI*2,a=.5+o.next()*.7,u=r?a*(1+o.next()*.2):a*(.9+o.next()*.2);l.push({x:e,z:t,rotY:i,scale:u})}let d=Math.min(3,Math.max(1,a*10)),f=Math.ceil(Math.sqrt(i*d)),p=n/f,m=r/f,h=Math.floor((i-l.length)*.8),g=0;for(let e=0;e<f&&l.length<i;e++)for(let t=0;t<f&&l.length<i;t++){let i=t/f*n-s+p/2,a=e/f*r-c+m/2,u=i+(o.next()-.5)*p*1.5,d=a+(o.next()-.5)*m*1.5;if(u<-s||u>s||d<-c||d>c)continue;let _=mA(u,d);if(g<h){if(!_&&o.next()>.05)continue}else if(_){if(o.next()>.2)continue}else if(o.next()>.4)continue;if(o.next()<.2)continue;let v=o.next()*Math.PI*2,y=_?.5:.3;l.push({x:u,z:d,rotY:v,scale:.5+o.next()*y}),g++}for(;l.length<i;)l.push({x:o.range(-s,s),z:o.range(-c,c),rotY:o.next()*Math.PI*2,scale:.4+o.next()*.6});return l.sort((e,t)=>t.z-e.z),l}var DA=[`daisy`,`cosmos`,`bellflower`],OA={daisy:{petals:8,blooms:3,leaves:3,petalLength:.1,petalWidth:.052,cupDeg:16,nodDeg:14,centerRadius:.024,centerColor:`#e0a72e`},cosmos:{petals:8,blooms:2,leaves:2,petalLength:.12,petalWidth:.064,cupDeg:26,nodDeg:18,centerRadius:.023,centerColor:`#d2941f`},bellflower:{petals:5,blooms:3,leaves:2,petalLength:.088,petalWidth:.058,cupDeg:46,nodDeg:52,centerRadius:.015,centerColor:`#cfe06a`}},kA=[1,.78,.62],AA=[0,.07,.11],jA=[.6,2.7,4.9],MA=.07,NA=.011,PA=.17,FA=.05,IA=[.12,.2,.28],LA=new q(`#3e6a26`),RA=new q(`#548331`);function zA(e){let t=OA[e],n=new BA(!0),r=new BA(!1),i=new q(t.centerColor);for(let e=0;e<t.blooms;e++){let a=kA[e],o=jA[e],s=AA[e]*Math.cos(o),c=AA[e]*Math.sin(o),l=MA*Math.cos(o),u=MA*Math.sin(o),d=new W(s,0,c),f=new W(s+l,a,c+u),p=new W(s+l*.25,a*.55,c+u*.25);n.addStem(d,p,f,NA,LA);let m=t.nodDeg*Math.PI/180,h=new W(Math.sin(m)*Math.cos(o),Math.cos(m),Math.sin(m)*Math.sin(o)),g=new W(-Math.sin(o),0,Math.cos(o)),_=new W().crossVectors(h,g).normalize(),v=f.clone().addScaledVector(h,.012),y=t.cupDeg*Math.PI/180,b=e*.45;for(let e=0;e<t.petals;e++){let n=e/t.petals*Math.PI*2+b,i=g.clone().multiplyScalar(Math.cos(n)).addScaledVector(_,Math.sin(n)).normalize();r.addPetal(v,i,h,t,y)}n.addDisc(v.clone().addScaledVector(h,.004),g,_,t.centerRadius,i)}for(let e=0;e<t.leaves;e++){let t=IA[e%IA.length],r=1.1+e*2.3;n.addLeaf(new W(0,t,0),r,RA)}return{structure:n.build(),petals:r.build()}}var BA=class{positions=[];colors;indices=[];constructor(e){this.colors=e?[]:null}vertex(e,t){let n=this.positions.length/3;return this.positions.push(e.x,e.y,e.z),this.colors&&t&&this.colors.push(t.r,t.g,t.b),n}addStem(e,t,n,r,i){for(let a of[0,Math.PI/2]){let o=new W(Math.cos(a),0,Math.sin(a)),s=[];for(let a=0;a<=5;a++){let c=a/5,l=1-c,u=new W(l*l*e.x+2*l*c*t.x+c*c*n.x,l*l*e.y+2*l*c*t.y+c*c*n.y,l*l*e.z+2*l*c*t.z+c*c*n.z),d=r/2*(1-.4*c);s.push(this.vertex(u.clone().addScaledVector(o,-d),i),this.vertex(u.clone().addScaledVector(o,d),i))}for(let e=0;e<5;e++){let t=s[e*2],n=s[e*2+1],r=s[e*2+2],i=s[e*2+3];this.indices.push(t,n,r,r,n,i)}}}addPetal(e,t,n,r,i){let a=new W().crossVectors(n,t).normalize(),o=r.centerRadius*.85,s=Math.sin(i)*r.petalLength*.45,c=Math.sin(i)*r.petalLength*.95,l=Math.cos(i),u=e.clone().addScaledVector(t,o),d=o+r.petalLength*l*.55,f=o+r.petalLength*l,p=e.clone().addScaledVector(t,d).addScaledVector(a,r.petalWidth/2).addScaledVector(n,s),m=e.clone().addScaledVector(t,d).addScaledVector(a,-r.petalWidth/2).addScaledVector(n,s),h=e.clone().addScaledVector(t,f).addScaledVector(n,c),g=this.vertex(u,null),_=this.vertex(p,null),v=this.vertex(m,null),y=this.vertex(h,null);this.indices.push(g,_,y,g,y,v)}addDisc(e,t,n,r,i){let a=this.vertex(e,i),o=[];for(let a=0;a<6;a++){let s=a/6*Math.PI*2;o.push(this.vertex(e.clone().addScaledVector(t,Math.cos(s)*r).addScaledVector(n,Math.sin(s)*r),i))}for(let e=0;e<6;e++)this.indices.push(a,o[e],o[(e+1)%6])}addLeaf(e,t,n){let r=new W(Math.cos(t),0,Math.sin(t)),i=new W(-Math.sin(t),0,Math.cos(t)),a=Math.sin(.6),o=Math.cos(.6),s=e.clone().addScaledVector(r,PA*o*.5).add(new W(0,PA*a*.5,0)),c=e.clone().addScaledVector(r,PA*o).add(new W(0,PA*a*.8,0)),l=this.vertex(e,n),u=this.vertex(s.clone().addScaledVector(i,FA/2),n),d=this.vertex(s.clone().addScaledVector(i,-.05/2),n),f=this.vertex(c,n);this.indices.push(l,u,f,l,f,d)}build(){let e=new Y;return e.setAttribute(`position`,new J(new Float32Array(this.positions),3)),this.colors&&e.setAttribute(`color`,new J(new Float32Array(this.colors),3)),e.setIndex(this.indices),e.computeVertexNormals(),e}},VA=2.6;function HA(e){let{seed:t,areaX:n,areaZ:r,count:i,clustering:a}=e,o=new Ee(t),s=n/2,c=r/2,l=1-.74*Math.min(Math.max(a,0),1),u=[];for(let e=0;e<i*16&&u.length<i;e++){let e=o.range(-s,s),t=o.range(-c,c),n=_A(e,t,VA);n.lean>l&&o.next()>.06||u.push({x:e,z:t,rotY:o.next()*Math.PI*2,scale:.75+o.next()*.5,variety01:(n.hue+1)/2,color01:n.leanDir/(Math.PI*2)})}return u}var UA=1.05,WA=1;function GA(e,t=WA){e.computeBoundingSphere();let n=e.boundingSphere;n&&n.radius>=0&&(n.radius=n.radius*UA+t),e.frustumCulled=!0}function KA(e){let t=0,n=0,r=0;for(let i=e;i;i=i.parent)i instanceof Q_&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return[t,n,r]}function qA(e,t){if(t!==``){let n=e.getNodeOrNull(t);return n instanceof hO?n:null}return JA(e.getRoot())}function JA(e){if(e instanceof hO)return e;for(let t of e.children){let e=JA(t);if(e)return e}return null}function YA(e){return typeof e?._waterYAt==`function`}function XA(e){let t=e;for(;t.parent;)t=t.parent;let n=[],r=e=>{e.visible!==!1&&YA(e)&&n.push(e);for(let t of e.children)r(t)};return r(t),n}function ZA(e,t,n,r,i=.06){for(let a=0;a<e.length;a++){let o=e[a]?._waterYAt(t,n);if(o!=null&&o-r>i)return!0}return!1}var QA={lush:2.2,sparse:.35,none:0},$A=[`lush`,`sparse`,`none`];function ej(e){if(typeof e==`number`)return e;let t=QA[e];if(t===void 0)throw new L(`BAD_FORMAT`,`Flowers3D density must be one of [${$A.join(`, `)}] or a number (plants/m²), got '${e}'.`,{prop:`density`,validOptions:$A});return t}var tj=1e4,nj=[`#f5f1e2`,`#e9d052`,`#8d7bd9`],rj=/^#[0-9a-fA-F]{6}$/,ij=class extends Q_{static typeName=`Flowers3D`;static props={density:{default:`sparse`,options:$A},area:{default:[20,20]},seed:{default:1},varieties:{default:[]},palette:{default:[]},height:{default:.45},clustering:{default:.6},sway:{default:.5},drape:{default:null},avoidWater:{default:!0},terrain:{default:``,nodePath:!0}};density=`sparse`;area=[20,20];seed=1;varieties=[];palette=[];height=.45;clustering=.6;sway=.5;drape=null;avoidWater=!0;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(typeof t.density==`string`)ej(t.density);else if(!(Number.isFinite(t.density)&&t.density>=0))throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' density must be one of [${$A.join(`, `)}] or a number >= 0 (plants/m²), got ${t.density}.`,{prop:`density`,validOptions:$A});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' area must be positive [x, z] meters, got ${JSON.stringify(t.area)}.`,{prop:`area`});let n=Math.floor((t.area[0]??0)*(t.area[1]??0)*ej(t.density));if(n>tj)throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' blows the plant budget: area ${t.area[0]}×${t.area[1]} m × density ${ej(t.density)} = ${n} plants > ${tj}. Lower the density or split the field into multiple nodes.`,{prop:`density`});if(!Array.isArray(t.varieties)||new Set(t.varieties).size!==t.varieties.length||!t.varieties.every(e=>DA.includes(e)))throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' varieties must be a unique subset of [${DA.join(`, `)}] ([] = all three), got ${JSON.stringify(t.varieties)}.`,{prop:`varieties`,validOptions:[...DA]});if(!Array.isArray(t.palette)||!t.palette.every(e=>typeof e==`string`&&rj.test(e)))throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' palette must be an array of '#rrggbb' head colors ([] = white/yellow/violet), got ${JSON.stringify(t.palette)}.`,{prop:`palette`});if(!(t.height>0))throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' height must be > 0 meters, got ${t.height}.`,{prop:`height`});if(!(t.clustering>=0)||!(t.clustering<=1))throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' clustering must be in [0, 1] (0 uniform … 1 tight patches), got ${t.clustering}.`,{prop:`clustering`});if(!(t.sway>=0))throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' sway must be >= 0, got ${t.sway}.`,{prop:`sway`});if(t.drape!==null&&typeof t.drape!=`boolean`)throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' drape must be true, false or null (null = auto: drape whenever the scene has a Terrain3D), got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new L(`BAD_FORMAT`,`Flowers3D '${e.name}' terrain must be a node-path string (empty = auto-find), got ${JSON.stringify(t.terrain)}.`,{prop:`terrain`})}time=0;field=null;varietyMeshes=[];fieldKey=``;timeUniform={value:0};swayUniform={value:.5};_createObject3D(){return new Ec}_varietyMeshes(){return this.rebuildIfNeeded(),this.varietyMeshes}update(e){this.time+=e,this.timeUniform.value=this.time}_syncObject3D(){super._syncObject3D(),this.rebuildIfNeeded(),this.swayUniform.value=this.sway}rebuildIfNeeded(){this.field||(this.field=new Ec,this._ensureObject3D().add(this.field));let e=JSON.stringify([this.density,this.area,this.seed,this.varieties,this.palette,this.height,this.clustering,this.drape,this.avoidWater,this.terrain]);e!==this.fieldKey&&(this.fieldKey=e,this.disposeMeshes(),this.resolveDrape(),this.buildField())}resolveDrape(){if(this.drapeTerrain=null,this.drape===!1)return;let e=qA(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=KA(this);else if(this.terrain!==``)throw new L(`NODE_NOT_FOUND`,`Flowers3D '${this.name}' drape terrain '${this.terrain}' is not a Terrain3D in the tree.`,{prop:`terrain`})}bedY(e,t){let n=this.drapeTerrain;return n?n.heightAt(this.drapeWorld[0]+e,this.drapeWorld[2]+t)-this.drapeWorld[1]:0}buildField(){let e=ej(this.density),t=Math.min(Math.floor((this.area[0]??0)*(this.area[1]??0)*e),tj);if(t<=0)return;let n=HA({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:t,clustering:this.clustering});if(this.avoidWater){let e=XA(this);if(e.length>0){let[t,r,i]=KA(this);n=n.filter(n=>!ZA(e,n.x+t,n.z+i,this.bedY(n.x,n.z)+r))}}let r=this.varieties.length>0?this.varieties:DA,i=r.map(()=>[]);for(let e of n)i[Math.min(Math.floor(e.variety01*r.length),r.length-1)].push(e);let a=this.palette.length>0?this.palette:nj,o=new Ee(this.seed+15797765);for(let e=0;e<r.length;e++){let t=i[e];if(t.length===0)continue;let{structure:n,petals:s}=zA(r[e]),c=new kd({vertexColors:!0,roughness:1,side:2}),l=new kd({roughness:.85,side:2});aj(c,this.timeUniform,this.swayUniform),aj(l,this.timeUniform,this.swayUniform);let u=new Au(n,c,t.length),d=new Au(s,l,t.length);u.receiveShadow=!0,d.receiveShadow=!0;for(let e=0;e<t.length;e++){let n=t[e];cj.set(n.x,this.bedY(n.x,n.z),n.z),lj.setFromAxisAngle(oj,n.rotY),uj.setScalar(this.height*n.scale),sj.compose(cj,lj,uj),u.setMatrixAt(e,sj),d.setMatrixAt(e,sj);let r=Math.min(Math.floor(n.color01*a.length),a.length-1);dj.set(a[r]).offsetHSL(o.range(-.02,.02),0,o.range(-.05,.05)),d.setColorAt(e,dj),dj.setRGB(1,1,1).offsetHSL(o.range(-.02,.02),0,o.range(-.06,.04)),u.setColorAt(e,dj)}u.instanceMatrix.needsUpdate=!0,d.instanceMatrix.needsUpdate=!0,u.instanceColor&&(u.instanceColor.needsUpdate=!0),d.instanceColor&&(d.instanceColor.needsUpdate=!0),GA(u),GA(d),this.varietyMeshes.push({variety:r[e],structure:u,petals:d}),this.field.add(u),this.field.add(d)}}disposeMeshes(){for(let{structure:e,petals:t}of this.varietyMeshes)for(let n of[e,t])n.removeFromParent(),n.geometry.dispose(),n.material.dispose(),n.dispose();this.varietyMeshes=[]}free(){this.disposeMeshes(),this.field=null,super.free()}};function aj(e,t,n){e.userData.sway=!0,e.userData.timeUniform=t,e.onBeforeCompile=e=>{e.uniforms.uFlowerTime=t,e.uniforms.uFlowerSway=n,e.vertexShader=`uniform float uFlowerTime;\nuniform float uFlowerSway;\n${e.vertexShader}`.replace(`#include <project_vertex>`,`
|
|
6993
6993
|
vec4 mvPosition = vec4(transformed, 1.0);
|
|
6994
6994
|
#ifdef USE_INSTANCING
|
|
6995
6995
|
mvPosition = instanceMatrix * mvPosition;
|
|
@@ -7414,7 +7414,7 @@ void main() {
|
|
|
7414
7414
|
#include <colorspace_fragment>
|
|
7415
7415
|
#include <fog_fragment>
|
|
7416
7416
|
}
|
|
7417
|
-
`,bj=.4;function xj(e){if(typeof e.radius==`number`)return e.radius;let t=e.size;if(Array.isArray(t)){let e=typeof t[0]==`number`?t[0]:0,n=typeof t[2]==`number`?t[2]:0;if(e>0||n>0)return Math.max(e,n)/2}return bj}function Sj(e){let t=typeof e.radius==`number`?e.radius:0,n=typeof e.height==`number`?e.height:0;if(n>0)return n/2+t;if(t>0)return t;let r=e.size;return Array.isArray(r)&&typeof r[1]==`number`?r[1]/2:bj}function Cj(e,t){t.length=0,wj(e,t)}function wj(e,t){if(e instanceof
|
|
7417
|
+
`,bj=.4;function xj(e){if(typeof e.radius==`number`)return e.radius;let t=e.size;if(Array.isArray(t)){let e=typeof t[0]==`number`?t[0]:0,n=typeof t[2]==`number`?t[2]:0;if(e>0||n>0)return Math.max(e,n)/2}return bj}function Sj(e){let t=typeof e.radius==`number`?e.radius:0,n=typeof e.height==`number`?e.height:0;if(n>0)return n/2+t;if(t>0)return t;let r=e.size;return Array.isArray(r)&&typeof r[1]==`number`?r[1]/2:bj}function Cj(e,t){t.length=0,wj(e,t)}function wj(e,t){if(e instanceof rv||e instanceof nv){let[n,r,i]=KA(e);t.push({x:n,y:r,z:i,radius:xj(e.collider),footY:r-Sj(e.collider)})}for(let n of e.children)wj(n,t)}function Tj(e){let t=e.tree;if(!t){let t=[];return Cj(e.getRoot(),t),t}let n=t._frameScratch;if(n&&n.frameId===t.frameId)return n.bodies;let r=n?.bodies??[],i=t.root;return i?Cj(i,r):r.length=0,t._frameScratch={frameId:t.frameId,bodies:r},r}var Ej=6,Dj=512;function Oj(e,t=`grass`){if(t===`fern`)return kj(e);let n=new Ee(e+28919),r=[];for(let e=0;e<180;e++){let e=.5+(n.next()+n.next()-1)*.17,t=(e>=.5?1:-1)*n.range(.04,.5)+n.range(-.1,.1),i=n.range(.45,1),a=Math.min(1,Math.max(0,e+t*(1.5-.9*i)));r.push({rootX:e,tipX:a,height:i,width:n.range(.0028,.0085),shade:n.range(.45,.98),bow:t*n.range(.25,.6)})}return r}function kj(e){let t=new Ee(e+65121),n=[];for(let e=0;e<56;e++){let r=.5+(t.next()+t.next()-1)*.1,i=(e%2==0?1:-1)*t.range(.12,.55)+t.range(-.06,.06),a=t.range(.32,.85),o=Math.min(1,Math.max(0,r+i*(1.6-.7*a)));n.push({rootX:r,tipX:o,height:a,width:t.range(.014,.03),shade:t.range(.4,.85),bow:i*t.range(.5,.85)})}return n}function Aj(e,t=`grass`){let n=e.shade,r=Math.max(.3,e.shade*.62);if(t===`fern`){let e=[{offset:0,gray:r,alpha:0}],t=.14;for(let i=0;i<Ej;i++){let a=t+(1-t)*i/Ej,o=t+(1-t)*(i+1)/Ej,s=r+(n-r)*((a+o)/2);e.push({offset:a+(o-a)*.12,gray:s,alpha:1}),e.push({offset:a+(o-a)*.74,gray:s,alpha:1}),i<Ej-1&&e.push({offset:a+(o-a)*.92,gray:s,alpha:.2})}return e[e.length-1].offset<1&&e.push({offset:1,gray:n,alpha:1}),e}return[{offset:0,gray:r,alpha:0},{offset:.22,gray:r,alpha:1},{offset:1,gray:n,alpha:1}]}function jj(e,t=`grass`){if(typeof document>`u`)return null;let n=Dj,r=document.createElement(`canvas`);r.width=n,r.height=n;let i=r.getContext(`2d`);if(!i)return null;i.clearRect(0,0,n,n);for(let r of Oj(e,t)){let e=r.rootX*n,a=n,o=r.tipX*n,s=(1-r.height)*n,c=(e+o)/2+r.bow*n,l=(a+s)/2,u=Math.max(r.width*n,.75);i.beginPath(),i.moveTo(e-u,a),i.quadraticCurveTo(c-u*.55,l,o,s),i.quadraticCurveTo(c+u*.55,l,e+u,a),i.closePath();let d=i.createLinearGradient(e,a,o,s);for(let e of Aj(r,t)){let t=Math.round(e.gray*255);d.addColorStop(e.offset,`rgba(${t},${t},${t},${e.alpha})`)}i.fillStyle=d,i.fill()}let a=new sd(r);return a.colorSpace=Ro,a}var Mj=.08,Nj=.5,Pj=12,Fj=`
|
|
7418
7418
|
// GLSL Simplex Noise 3D — https://github.com/ashima/webgl-noise (MIT)
|
|
7419
7419
|
vec3 ezMod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
|
|
7420
7420
|
vec4 ezMod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
|
|
@@ -7491,7 +7491,7 @@ attribute vec3 anchor;
|
|
|
7491
7491
|
);${a}
|
|
7492
7492
|
mvPosition = modelViewMatrix * mvPosition;
|
|
7493
7493
|
gl_Position = projectionMatrix * mvPosition;
|
|
7494
|
-
`),e.fragmentShader=e.fragmentShader.replace(`#include <normal_fragment_begin>`,
|
|
7494
|
+
`),e.fragmentShader=e.fragmentShader.replace(`#include <normal_fragment_begin>`,dp.normal_fragment_begin.replace(`normal *= faceDirection;`,``)).replace(`#include <alphatest_fragment>`,`
|
|
7495
7495
|
#ifdef USE_ALPHATEST
|
|
7496
7496
|
float ezCutoff = alphaTest * mix(1.0, 0.25, smoothstep(40.0, 240.0, length(vViewPosition)));
|
|
7497
7497
|
#ifdef ALPHA_TO_COVERAGE
|
|
@@ -7512,7 +7512,7 @@ attribute vec3 anchor;
|
|
|
7512
7512
|
cos(uTuftTime * ${(1.4*Bj).toFixed(1)} + tuftPhase) * vec2(1.0, 0.8);
|
|
7513
7513
|
mvPosition = modelViewMatrix * mvPosition;
|
|
7514
7514
|
gl_Position = projectionMatrix * mvPosition;
|
|
7515
|
-
`)},e.customProgramCacheKey=()=>`incanto-tuft-wind`}var Hj=[`grass`,`flowers`,`reeds`],Uj=[`blades`,`simple`,`mesh`,`tufts`],Wj=[`grass`,`fern`],Gj={grass:.08,flowers:.14,reeds:.05},Kj=[.75,1.25],qj=.05,Jj=.25,Yj=2e5,Xj=8,Zj=.05,Qj=.38,$j=[.75,1.3],eM=.1,tM=.42,nM=[.6,1.6],rM=.8,iM=.9,aM=.04,oM=[`#f5f1e2`,`#e9d052`,`#8d7bd9`],sM=1/3,cM=1.5,lM=1.45,uM=.4,dM=.13,fM=[.85,1.2],pM=[.8,1.3],mM=`#b3a24e`,hM=.8,gM=.5,_M=class e extends Z_{static typeName=`Foliage3D`;static props={kind:{default:`grass`,options:Hj},style:{default:`mesh`,options:Uj},tuftStyle:{default:`grass`,options:Wj},area:{default:[20,20]},density:{default:12},maxInstances:{default:5e4},height:{default:.25},colorA:{default:`#4d7232`},colorB:{default:`#9aab55`},groundColor:{default:`#1f3015`},sunDirection:{default:[.5,.8,.3]},fadeStart:{default:60},fadeEnd:{default:90},sway:{default:.6},interaction:{default:!0},coverage:{default:.85},flowers:{default:0},seed:{default:1},drape:{default:null},avoidWater:{default:!0},terrain:{default:``,nodePath:!0},renderOrder:{default:2}};renderOrder=2;kind=`grass`;style=`mesh`;tuftStyle=`grass`;area=[20,20];density=12;maxInstances=5e4;height=.25;colorA=`#4d7232`;colorB=`#9aab55`;groundColor=`#1f3015`;sunDirection=[.5,.8,.3];fadeStart=60;fadeEnd=90;sway=.6;interaction=!0;coverage=.85;flowers=0;seed=1;drape=null;avoidWater=!0;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(!Hj.includes(t.kind))throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' kind must be one of [${Hj.join(`, `)}], got '${t.kind}'.`,{prop:`kind`,validOptions:Hj});if(!Uj.includes(t.style))throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' style must be one of [${Uj.join(`, `)}], got '${t.style}'.`,{prop:`style`,validOptions:Uj});if(!Wj.includes(t.tuftStyle))throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' tuftStyle must be one of [${Wj.join(`, `)}], got '${t.tuftStyle}'.`,{prop:`tuftStyle`,validOptions:Wj});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' area must be positive [x, z] meters, got ${JSON.stringify(t.area)}.`,{prop:`area`});if(!(t.density>0)||!(t.maxInstances>=1))throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' needs density > 0 and maxInstances >= 1, got density ${t.density}, maxInstances ${t.maxInstances}.`,{prop:`density`});if(t.maxInstances>Yj)throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' maxInstances is capped at ${Yj} (got ${t.maxInstances}) — split giant fields into multiple nodes.`,{prop:`maxInstances`});if(!(t.fadeStart>=0)||!(t.fadeEnd>t.fadeStart))throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' needs fadeStart >= 0 and fadeEnd > fadeStart (the LOD fade window), got fadeStart ${t.fadeStart}, fadeEnd ${t.fadeEnd}.`,{prop:`fadeStart`});let n=t.sunDirection;if(!Array.isArray(n)||n.length!==3||!n.every(e=>Number.isFinite(e))||Math.hypot(n[0]??0,n[1]??0,n[2]??0)===0)throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' sunDirection must be a non-zero [x, y, z] vector, got ${JSON.stringify(n)}.`,{prop:`sunDirection`});if(!(t.coverage>0)||!(t.coverage<=1))throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' coverage must be in (0, 1] (carpet fill — 1 is solid, lower carves dirt patches), got ${t.coverage}.`,{prop:`coverage`});if(!(t.flowers>=0)||!(t.flowers<=.2))throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' flowers must be in [0, 0.2] (fraction of instances rendered as flower heads — for a whole flower FIELD use kind: 'flowers'), got ${t.flowers}.`,{prop:`flowers`});if(t.drape!==null&&typeof t.drape!=`boolean`)throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' drape must be true, false or null (null = auto: drape whenever the scene has a Terrain3D), got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' terrain must be a node-path string (empty = auto-find), got ${JSON.stringify(t.terrain)}.`,{prop:`terrain`})}time=0;pivot=null;meshes=[];bladesMaterial=null;benderSlots=null;pickedBenders=[];fieldKey=``;tuftTime=null;tuftStrength=null;tuftTexture=null;_createObject3D(){return new Ec}get isBlades(){return this.kind===`grass`&&this.style===`blades`}get isMesh(){return this.kind===`grass`&&this.style===`mesh`}get isTufts(){return this.kind===`grass`&&this.style===`tufts`}get isShaderField(){return this.isMesh||this.isBlades}_field(){return this.rebuildIfNeeded(),this.meshes[0]}_fields(){return this.rebuildIfNeeded(),this.meshes}update(e){this.time+=e,this.pickedBenders=this.computeBenders(),this.writeAnimationUniforms()}writeAnimationUniforms(){if(this.isShaderField&&this.bladesMaterial){let e=this.bladesMaterial.uniforms;e.time&&(e.time.value=this.time),e.windStrength&&(e.windStrength.value=this.sway*(this.isMesh?Qj:Jj));let t=this.benderSlots;if(t)for(let e=0;e<4;e++){let n=this.pickedBenders[e];n?t[e]?.set(n.x,n.y,n.z,n.radius):t[e]?.set(0,0,0,0)}}else this.isTufts&&(this.tuftTime&&(this.tuftTime.value=this.time),this.tuftStrength&&(this.tuftStrength.value=this.sway*dM))}_syncObject3D(){super._syncObject3D(),this.rebuildIfNeeded();let e=this.pivot;if(this.writeAnimationUniforms(),this.isShaderField){e.matrix.identity();let t=this.bladesMaterial.uniforms;(t.bottomColor?.value).set(this.colorA),(t.topColor?.value).set(this.colorB),this.isMesh&&((t.groundColor?.value).set(this.groundColor),(t.sunDirection?.value).set(this.sunDirection[0]??0,this.sunDirection[1]??1,this.sunDirection[2]??0).normalize(),t.fadeStart&&(t.fadeStart.value=this.fadeStart),t.fadeEnd&&(t.fadeEnd.value=this.fadeEnd))}else if(this.isTufts)e.matrix.identity();else if(this.sway>0){let t=Math.sin(this.time*1.7)*qj*this.sway,n=Math.sin(this.time*1.3+1.7)*qj*this.sway*.6;e.matrix.makeShear(0,0,t,n,0,0)}else e.matrix.identity();e.matrixWorldNeedsUpdate=!0}_applySunDirection(t){if(!this.isMesh||!this.bladesMaterial)return;let n=e.props.sunDirection?.default;this.sunDirection.every((e,t)=>e===n[t])&&(this.bladesMaterial.uniforms.sunDirection?.value)?.set(t[0],t[1],t[2])}computeBenders(){if(!this.interaction||!this.isShaderField)return[];let[e,t,n]=KA(this);this.drape===!0&&!this.drapeTerrain&&this.resolveDrape();let r=this.drapeTerrain,i=[];for(let e of Tj(this)){let n=r?r.heightAt(e.x,e.z):t,a=e.footY-n;a<=gM&&a>=-2.5&&i.push({x:e.x,y:e.y,z:e.z,radius:e.radius+hM})}return fj(i,{x:e,z:n,areaX:this.area[0]??0,areaZ:this.area[1]??0})}rebuildIfNeeded(){this.pivot||(this.pivot=new Ec,this.pivot.matrixAutoUpdate=!1,this._ensureObject3D().add(this.pivot));let e=JSON.stringify([this.kind,this.style,this.tuftStyle,this.area,this.density,this.maxInstances,this.height,this.colorA,this.colorB,this.coverage,this.avoidWater,this.flowers,this.seed,this.drape,this.terrain]);if(e===this.fieldKey&&this.meshes.length>0)return;this.fieldKey=e,this.disposeMeshes(),this.resolveDrape();let t=this.isMesh?Xj:this.isTufts?sM:1,n=Math.min(Math.floor((this.area[0]??0)*(this.area[1]??0)*this.density*t),this.maxInstances);this.isMesh?this.buildMeshField(n):this.isTufts?this.buildTuftField(n):this.isBlades?this.buildBladesField(n):this.buildSimpleField(n);for(let e of this.meshes)GA(e),this.pivot.add(e)}resolveDrape(){if(this.drapeTerrain=null,this.drape===!1)return;let e=qA(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=KA(this);else if(this.terrain!==``)throw new L(`NODE_NOT_FOUND`,`Foliage3D '${this.name}' drape terrain '${this.terrain}' is not a Terrain3D in the tree.`,{prop:`terrain`})}bedY(e,t){let n=this.drapeTerrain;return n?n.heightAt(this.drapeWorld[0]+e,this.drapeWorld[2]+t)-this.drapeWorld[1]:0}dryOnly(e){if(!this.avoidWater)return e;let t=XA(this);if(t.length===0)return e;let[n,,r]=KA(this);return e.filter(e=>!ZA(t,e.x+n,e.z+r,this.bedY(e.x,e.z)+this.worldY()))}worldY(){return KA(this)[1]}buildMeshField(e){let t=EA({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:e,density:this.density*Xj}),n=this.dryOnly(this.coverage>=1?t:t.filter(e=>TA(e.x,e.z,this.seed)<=this.coverage)),r=this.flowers>0?Math.floor(n.length*this.flowers):0,i=new Set;for(let e=0;e<r;e++)i.add(Math.floor((e+.5)*n.length/r));let a=n.filter((e,t)=>!i.has(t)),o=n.filter((e,t)=>i.has(t));this.benderSlots=Array.from({length:4},()=>new Js(0,0,0,0));let s=wd.merge([Z.lights,Z.fog]);Object.assign(s,{time:{value:0},windStrength:{value:this.sway*Qj},topColor:{value:new q(this.colorB)},bottomColor:{value:new q(this.colorA)},groundColor:{value:new q(this.groundColor)},sunDirection:{value:new W(this.sunDirection[0]??0,this.sunDirection[1]??1,this.sunDirection[2]??0).normalize()},fadeStart:{value:this.fadeStart},fadeEnd:{value:this.fadeEnd},benders:{value:this.benderSlots}}),this.bladesMaterial=new Dd({vertexShader:vj,fragmentShader:yj,uniforms:s,fog:!0,lights:!0,side:2});let c=mj(Zj),l=a.length,u=Math.max(l,1),d=new Au(c,this.bladesMaterial,u);d.count=l,d.receiveShadow=!0;let f=new Ee(this.seed+5352221),p=new Float32Array(u*4),m=new Float32Array(u),h=new Float32Array(u);for(let e=0;e<l;e++){let t=a[e],n=_A(t.x,t.z),r=CA(t.x,t.z,this.seed),i=(r-.55)/1.15,o=f.range($j[0],$j[1]),s=this.height*r*(.55+t.scale*.6);CM.set(t.x,this.bedY(t.x,t.z),t.z),wM.setFromAxisAngle(xM,t.rotY),TM.set(o,s,o),d.setMatrixAt(e,SM.compose(CM,wM,TM));let c=n.leanDir+f.range(-.6,.6),l=(eM+tM*(.5*n.lean+.5*f.next()))*(1+rM*i);p[e*4]=Math.cos(c)*l,p[e*4+1]=Math.sin(c)*l,p[e*4+2]=f.range(nM[0],nM[1])*(1+iM*i),p[e*4+3]=f.next(),m[e]=n.hue;let u=wA(t.x,t.z,this.seed)*.85+(f.next()-.5)*.3;h[e]=Math.min(1,Math.max(0,u))}c.setAttribute(`aBlade`,new Su(p,4)),c.setAttribute(`aClumpHue`,new Su(m,1)),c.setAttribute(`aDry`,new Su(h,1)),d.instanceMatrix.needsUpdate=!0,this.meshes=[d],o.length>0&&this.meshes.push(this.buildFlowerMesh(o))}buildFlowerMesh(e){let t=new Au(hj(aM),new kd({roughness:1,side:2}),Math.max(e.length,1));t.count=e.length,t.receiveShadow=!0;let n=new Ee(this.seed+15797765);for(let r=0;r<e.length;r++){let i=e[r],a=CA(i.x,i.z,this.seed),o=this.height*a*(.85+n.next()*.35);CM.set(i.x,this.bedY(i.x,i.z),i.z),wM.setFromAxisAngle(xM,i.rotY),TM.set(1,o,1),t.setMatrixAt(r,SM.compose(CM,wM,TM));let s=n.next(),c=oM[s<.45?0:s<.75?1:2];t.setColorAt(r,OM.set(c))}return t.instanceMatrix.needsUpdate=!0,t.instanceColor&&(t.instanceColor.needsUpdate=!0),t}buildTuftField(e){let t=EA({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:e,density:this.density*sM}),n=this.dryOnly(this.coverage>=1?t:t.filter(e=>TA(e.x,e.z,this.seed)<=this.coverage));this.tuftTime={value:this.time},this.tuftStrength={value:this.sway*dM};let r=new kd({alphaTest:.5,side:2,roughness:1}),i=jj(this.seed,this.tuftStyle);i&&(r.map=i,this.tuftTexture=i),Vj(r,this.tuftTime,this.tuftStrength);let a=new Au(yM(),r,Math.max(n.length,1));a.count=n.length,a.castShadow=!1,a.receiveShadow=!0;let o=new Ee(this.seed+7403357),s=EM.set(this.colorA),c=DM.set(this.colorB);for(let e=0;e<n.length;e++){let t=n[e],r=1+(CA(t.x,t.z,this.seed)-1)*uM,i=this.height*cM*r*o.range(fM[0],fM[1]),l=i*lM*o.range(pM[0],pM[1]);CM.set(t.x,this.bedY(t.x,t.z),t.z),wM.setFromAxisAngle(xM,t.rotY),TM.set(l,i,l),a.setMatrixAt(e,SM.compose(CM,wM,TM));let u=_A(t.x,t.z),d=Math.min(1,Math.max(0,.5+.35*u.hue+(o.next()-.5)*.3)),f=Math.min(1,Math.max(0,wA(t.x,t.z,this.seed)*.8-.1));OM.copy(s).lerp(c,d).lerp(kM.set(mM),f*.5).multiplyScalar(o.range(.62,1.18)),a.setColorAt(e,OM)}a.instanceMatrix.needsUpdate=!0,a.instanceColor&&(a.instanceColor.needsUpdate=!0),this.meshes=[a]}buildBladesField(e){let t=EA({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:e,density:this.density});this.benderSlots=Array.from({length:4},()=>new Js(0,0,0,0));let n=wd.merge([Z.fog]);Object.assign(n,{time:{value:0},windStrength:{value:this.sway*Jj},topColor:{value:new q(this.colorB)},bottomColor:{value:new q(this.colorA)},grassHeight:{value:this.height},grassScale:{value:1},benders:{value:this.benderSlots}}),this.bladesMaterial=new Dd({vertexShader:gj,fragmentShader:_j,uniforms:n,fog:!0,transparent:!0,side:2,depthWrite:!0,depthTest:!0,alphaTest:.1,blending:0});let r=vM(this.height),i=new Au(r,this.bladesMaterial,Math.max(e,1)),a=new Au(r,this.bladesMaterial,Math.max(e,1));i.count=e,a.count=e,i.renderOrder=this.renderOrder,a.renderOrder=this.renderOrder;for(let n=0;n<e;n++){let e=t[n];CM.set(e.x,this.bedY(e.x,e.z),e.z),TM.setScalar(e.scale),wM.setFromAxisAngle(xM,e.rotY),i.setMatrixAt(n,SM.compose(CM,wM,TM)),wM.setFromAxisAngle(xM,e.rotY+Math.PI/2),a.setMatrixAt(n,SM.compose(CM,wM,TM))}i.instanceMatrix.needsUpdate=!0,a.instanceMatrix.needsUpdate=!0,this.meshes=[i,a]}buildSimpleField(e){let t=new kd({side:2,roughness:1}),n=new Au(bM(Gj[this.kind]??.08),t,Math.max(e,1));n.receiveShadow=!0;let r=new Ee(this.seed),i=(this.area[0]??0)/2,a=(this.area[1]??0)/2,o=EM.set(this.colorA),s=DM.set(this.colorB),c=this.avoidWater?XA(this):[],[l,u,d]=KA(this),f=0;for(let t=0;t<e;t++){let e=r.range(-i,i),t=r.range(-a,a),p=r.range(0,Math.PI*2),m=r.range(Kj[0],Kj[1]),h=r.next(),g=this.bedY(e,t);c.length>0&&ZA(c,e+l,t+d,g+u)||(CM.set(e,g,t),wM.setFromAxisAngle(xM,p),TM.set(1,this.height*m,1),SM.compose(CM,wM,TM),n.setMatrixAt(f,SM),n.setColorAt(f,OM.copy(o).lerp(s,h)),f++)}n.count=f,n.instanceMatrix.needsUpdate=!0,n.instanceColor&&(n.instanceColor.needsUpdate=!0),this.meshes=[n]}disposeMeshes(){let e=new Set(this.meshes.map(e=>e.geometry)),t=new Set(this.meshes.map(e=>e.material));for(let e of this.meshes)e.removeFromParent(),e.dispose();for(let t of e)t.dispose();for(let e of t)e.dispose?.();this.bladesMaterial?.dispose(),this.bladesMaterial=null,this.benderSlots=null,this.tuftTexture?.dispose(),this.tuftTexture=null,this.tuftTime=null,this.tuftStrength=null,this.meshes=[]}free(){this.disposeMeshes(),this.pivot=null,super.free()}};function vM(e){let t=new _d(1,e,1,1);return t.translate(0,e/2,0),t}function yM(){let e=[],t=[],n=[],r=[];for(let i=0;i<3;i++){let a=i*Math.PI/3,o=Math.cos(a)/2,s=Math.sin(a)/2,c=-Math.sin(a),l=Math.cos(a),u=i*4;e.push(-o,0,-s,o,0,s,-o,1,-s,o,1,s);for(let e=0;e<4;e++)t.push(c,0,l);n.push(0,0,1,0,0,1,1,1),r.push(u,u+1,u+3,u,u+3,u+2)}let i=new Y;return i.setAttribute(`position`,new J(new Float32Array(e),3)),i.setAttribute(`normal`,new J(new Float32Array(t),3)),i.setAttribute(`uv`,new J(new Float32Array(n),2)),i.setIndex(r),i}function bM(e){let t=e/2,n=new Float32Array([-t,0,0,t,0,0,-t,1,0,t,1,0,0,0,-t,0,0,t,0,1,-t,0,1,t]),r=new Float32Array([0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0]),i=new Y;return i.setAttribute(`position`,new J(n,3)),i.setAttribute(`normal`,new J(r,3)),i.setIndex([0,1,2,2,1,3,4,5,6,6,5,7]),i}var xM=new W(0,1,0),SM=new K,CM=new W,wM=new U,TM=new W,EM=new q,DM=new q,OM=new q,kM=new q,AM=class extends lk{static typeName=`Label3D`;static props={...lk.props,text:{default:``},height:{default:.3},color:{default:`#ffffff`},font:{default:`sans-serif`},outline:{default:`#000000`},billboard:{default:`full`,options:[`y`,`full`,`none`]}};text=``;height=.3;color=`#ffffff`;font=`sans-serif`;outline=`#000000`;billboard=`full`;static validateJson(e){let t=e;if(t.texture)throw new L(`BAD_FORMAT`,`Label3D '${t.name}' has a "texture" — a label draws its own text, so the image would never be used. Set "text" instead, or use a Sprite3D.`,{prop:`texture`})}canvas=null;canvasTexture=null;lastKey=``;resolveTexture(e){let t=Qe(this,this.text);if(t===``||typeof document>`u`)return null;let n=`${t}\0${this.height}\0${this.color}\0${this.font}\0${this.outline}`;return n!==this.lastKey&&(this.lastKey=n,this.rasterize()),this.canvasTexture}rasterize(){let e=Qe(this,this.text),t=Math.max(8,Math.round(this.height*256));this.canvas??=document.createElement(`canvas`);let n=this.canvas.getContext(`2d`);if(!n)return;let r=Math.max(1,Math.round(t*.14)),i=`bold ${t}px ${this.font}`;n.font=i;let a=Math.max(1,Math.ceil(n.measureText(e).width)+r*2),o=Math.ceil(t*1.35)+r*2;this.canvas.width=a,this.canvas.height=o,n.font=i,n.textBaseline=`middle`,n.textAlign=`center`,this.outline!==``&&(n.lineWidth=r,n.lineJoin=`round`,n.strokeStyle=this.outline,n.strokeText(e,a/2,o/2)),n.fillStyle=this.color,n.fillText(e,a/2,o/2),this.canvasTexture?.dispose();let s=new sd(this.canvas);s.colorSpace=Ro,this.canvasTexture=s,this.size=[a/o*this.height*1.35,this.height*1.35]}free(){this.canvasTexture?.dispose(),this.canvasTexture=null,super.free()}},jM=class extends Z_{static typeName=`DirectionalLight3D`;static props={color:{default:`#ffffff`},intensity:{default:1},castShadow:{default:!1},shadowArea:{default:75},shadowMapSize:{default:2048},shadowFollowsCamera:{default:!1}};color=`#ffffff`;intensity=1;castShadow=!1;shadowArea=75;shadowMapSize=2048;shadowFollowsCamera=!1;_createObject3D(){return new Af}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();if(e.color.set(this.color),e.intensity=this.intensity,e.castShadow=this.castShadow,this.castShadow&&`shadow`in e){let t=e.shadow.camera;`left`in t&&(t.left=-this.shadowArea,t.right=this.shadowArea,t.top=this.shadowArea,t.bottom=-this.shadowArea,t.near=.5,t.far=500,t.updateProjectionMatrix()),e.shadow.mapSize.set(this.shadowMapSize,this.shadowMapSize),e.shadow.bias=-2e-4,e.shadow.normalBias=.002}}},MM=class extends Z_{static typeName=`OmniLight3D`;static props={color:{default:`#ffffff`},intensity:{default:1},range:{default:0}};color=`#ffffff`;intensity=1;range=0;_createObject3D(){return new Df}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();e.color.set(this.color),e.intensity=this.intensity,e.distance=this.range}},NM=class extends Z_{static typeName=`LoftMesh3D`;static props={sections:{default:[]},slices:{default:24},smooth:{default:4},material:{default:{}},castShadow:{default:!1},receiveShadow:{default:!1}};sections=[];slices=24;smooth=4;material={};castShadow=!1;receiveShadow=!1;static validateJson(e){let t=e;PM(t.sections,e.name),OD(t.material,e.name,`LoftMesh3D`);for(let n of[`map`,`normalMap`,`repeat`])if(t.material[n]!==void 0)throw new L(`BAD_FORMAT`,`LoftMesh3D '${e.name}' material does not support '${n}' — a loft has no UVs; use color/metalness/roughness/clearcoat/envMapIntensity instead.`,{prop:`material`})}geometryKey=``;_createObject3D(){return new iu(new Y,new Ad)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D(),t=JSON.stringify([this.sections,this.slices,this.smooth]);t!==this.geometryKey&&this.sections.length>=2&&(e.geometry.dispose(),e.geometry=LM(this.sections,this.slices,this.smooth),this.geometryKey=t),DD(e.material,this.material),e.castShadow=this.castShadow,e.receiveShadow=this.receiveShadow}free(){let e=this._builtObject3D;e&&e.traverse(e=>{let t=e;t.geometry?.dispose();let n=t.material,r=Array.isArray(n)?n:n?[n]:[];for(let e of r)e.dispose?.()}),super.free()}};function PM(e,t){let n=e=>{throw new L(`BAD_FORMAT`,`LoftMesh3D '${t}' ${e}`,{prop:`sections`})};(!Array.isArray(e)||e.length<2)&&n(`sections needs at least 2 stations, got ${JSON.stringify(e)}.`);for(let[t,r]of e.entries()){(typeof r!=`object`||!r)&&n(`sections[${t}] must be an object.`);for(let e of[`z`,`width`,`height`,`y`])(typeof r[e]!=`number`||!Number.isFinite(r[e]))&&n(`sections[${t}].${e} must be a finite number, got ${JSON.stringify(r[e])}.`);(r.width<=0||r.height<=0)&&n(`sections[${t}] width/height must be positive, got ${r.width}×${r.height}.`),r.corner!==void 0&&!(typeof r.corner==`number`&&r.corner>=0&&r.corner<=1)&&n(`sections[${t}].corner must be in 0..1, got ${JSON.stringify(r.corner)}.`),t>0&&r.z<=e[t-1].z&&n(`sections[].z must be strictly ascending (sections[${t}].z=${r.z}).`)}}function FM(e,t,n,r,i){let a=i*i,o=a*i;return .5*(2*t+(n-e)*i+(2*e-5*t+4*n-r)*a+(-e+3*t-3*n+r)*o)}function IM(e,t){let n=t=>{let n=e[Math.max(0,Math.min(e.length-1,t))];return{z:n.z,width:n.width,height:n.height,y:n.y,corner:n.corner??.7}},r=[];for(let i=0;i<e.length-1;i++){let a=n(i-1),o=n(i),s=n(i+1),c=n(i+2),l=i===e.length-2?t+1:t;for(let e=0;e<l;e++){let n=e/t;r.push({z:FM(a.z,o.z,s.z,c.z,n),width:Math.max(1e-4,FM(a.width,o.width,s.width,c.width,n)),height:Math.max(1e-4,FM(a.height,o.height,s.height,c.height,n)),y:FM(a.y,o.y,s.y,c.y,n),corner:Math.min(1,Math.max(0,FM(a.corner,o.corner,s.corner,c.corner,n)))})}}return r}function LM(e,t,n){let r=Math.max(8,Math.min(64,Math.round(t))),i=IM(e,Math.max(1,Math.min(16,Math.round(n)))),a=i.length,o=new Float32Array((a*r+2)*3),s=i[0],c=i[a-1];o.set([0,s.y,s.z],0),o.set([0,c.y,c.z],3);for(let e=0;e<a;e++){let t=i[e],n=8-6*t.corner,a=Math.max(n,5);for(let i=0;i<r;i++){let s=i/r*Math.PI*2,c=Math.cos(s),l=Math.sin(s),u=l>=0?n:a,d=t.width/2*Math.sign(c)*Math.abs(c)**(2/u),f=t.height/2*Math.sign(l)*Math.abs(l)**(2/u),p=(2+e*r+i)*3;o[p]=d,o[p+1]=t.y+f,o[p+2]=t.z}}let l=[],u=(e,t)=>2+e*r+t%r;for(let e=0;e<a-1;e++)for(let t=0;t<r;t++){let n=u(e,t),r=u(e,t+1),i=u(e+1,t),a=u(e+1,t+1);l.push(n,r,i,r,a,i)}for(let e=0;e<r;e++)l.push(0,u(0,e+1),u(0,e)),l.push(1,u(a-1,e),u(a-1,e+1));let d=new Y;return d.setAttribute(`position`,new J(o,3)),d.setIndex(l),d.computeVertexNormals(),d}function RM(e){let t=e.lastIndexOf(`.`);return t===-1?e:e.slice(0,t)}function zM(e,t,n){let r=e.tracks.filter(e=>{let r=t.has(RM(e.name));return n===`keep`?r:!r});return new Xd(`${e.name}#${n}`,e.duration,r)}function BM(e){let t=new Set,n=e=>{t.add(e.name);for(let t of e.children)n(t)};return n(e),t}function VM(e){let t=null;return e.traverse(e=>{t||(/^mixamorig[:_]?hips$/i.test(e.name)||/^hips$/i.test(e.name))&&(t=e)}),t}function HM(e,t){e.updateMatrixWorld(!0);let n=t.matrixWorld.clone().premultiply(e.matrixWorld.clone().invert());return Math.abs(n.elements[13]??0)}var UM=e=>e.split(`.`)[0]??``,WM=e=>e.split(`.`).pop()??``;function GM(e,t,n){let r=new Set;if(n.traverse(e=>r.add(e.name)),e.tracks.filter(e=>WM(e.name)===`quaternion`&&r.has(UM(e.name))).length===0)return{clip:e,droppedTracks:0,hipsScale:1,passthrough:!0,reason:`no bone in this clip matches the model — played as authored`};let i=VM(t),a=VM(n),o=i?HM(t,i):0,s=a?HM(n,a):0,c=o>1e-6&&s>1e-6?s/o:1,l=a?.name??``,u=[],d=0;for(let t of e.tracks){let e=UM(t.name),n=WM(t.name);if(!r.has(e)){d+=1;continue}if(n===`quaternion`){u.push(t);continue}if(n===`position`&&e===l){let e=Array.from(t.values,e=>e*c);u.push(new Yd(t.name,Array.from(t.times),e));continue}d+=1}return{clip:new Xd(`${e.name} (retargeted)`,e.duration,u),droppedTracks:d,hipsScale:c,passthrough:!1}}var KM={Hips:`hips`,Spine:`spine`,Spine1:`chest`,Spine2:`upperChest`,Neck:`neck`,Head:`head`,LeftShoulder:`leftShoulder`,LeftArm:`leftUpperArm`,LeftForeArm:`leftLowerArm`,LeftHand:`leftHand`,RightShoulder:`rightShoulder`,RightArm:`rightUpperArm`,RightForeArm:`rightLowerArm`,RightHand:`rightHand`,LeftUpLeg:`leftUpperLeg`,LeftLeg:`leftLowerLeg`,LeftFoot:`leftFoot`,LeftToeBase:`leftToes`,RightUpLeg:`rightUpperLeg`,RightLeg:`rightLowerLeg`,RightFoot:`rightFoot`,RightToeBase:`rightToes`,LeftHandThumb1:`leftThumbMetacarpal`,LeftHandThumb2:`leftThumbProximal`,LeftHandThumb3:`leftThumbDistal`,LeftHandIndex1:`leftIndexProximal`,LeftHandIndex2:`leftIndexIntermediate`,LeftHandIndex3:`leftIndexDistal`,LeftHandMiddle1:`leftMiddleProximal`,LeftHandMiddle2:`leftMiddleIntermediate`,LeftHandMiddle3:`leftMiddleDistal`,LeftHandRing1:`leftRingProximal`,LeftHandRing2:`leftRingIntermediate`,LeftHandRing3:`leftRingDistal`,LeftHandPinky1:`leftLittleProximal`,LeftHandPinky2:`leftLittleIntermediate`,LeftHandPinky3:`leftLittleDistal`,RightHandThumb1:`rightThumbMetacarpal`,RightHandThumb2:`rightThumbProximal`,RightHandThumb3:`rightThumbDistal`,RightHandIndex1:`rightIndexProximal`,RightHandIndex2:`rightIndexIntermediate`,RightHandIndex3:`rightIndexDistal`,RightHandMiddle1:`rightMiddleProximal`,RightHandMiddle2:`rightMiddleIntermediate`,RightHandMiddle3:`rightMiddleDistal`,RightHandRing1:`rightRingProximal`,RightHandRing2:`rightRingIntermediate`,RightHandRing3:`rightRingDistal`,RightHandPinky1:`rightLittleProximal`,RightHandPinky2:`rightLittleIntermediate`,RightHandPinky3:`rightLittleDistal`},qM={};for(let[e,t]of Object.entries(KM))qM[`mixamorig${e}`]=t,qM[`mixamorig:${e}`]=t;function JM(e,t,n){let r=[],i=new Set,a=new U,o=new U,s=new U,c=n.meta?.metaVersion===`0`,l=t.getObjectByName(`mixamorigHips`)??t.getObjectByName(`mixamorig:Hips`),u=n.humanoid?.getNormalizedBoneNode(`hips`),d=l&&u?Math.abs(u.getWorldPosition(new W).y)/Math.max(1e-6,Math.abs(l.getWorldPosition(new W).y)):1;for(let l of e.tracks){let e=l.name.lastIndexOf(`.`),u=l.name.slice(0,e),f=l.name.slice(e+1),p=qM[u],m=p?n.humanoid?.getNormalizedBoneNode(p)?.name:void 0,h=t.getObjectByName(u);if(!m||!h){i.add(u);continue}if(h.getWorldQuaternion(a).invert(),h.parent?h.parent.getWorldQuaternion(o):o.identity(),l instanceof qd&&f===`quaternion`){let e=Float32Array.from(l.values);for(let t=0;t<e.length;t+=4)s.set(e[t]??0,e[t+1]??0,e[t+2]??0,e[t+3]??1),s.premultiply(o).multiply(a),e[t]=c?-s.x:s.x,e[t+1]=s.y,e[t+2]=c?-s.z:s.z,e[t+3]=s.w;r.push(new qd(`${m}.quaternion`,[...l.times],[...e]))}else if(l instanceof Yd&&f===`position`){let e=Float32Array.from(l.values);for(let t=0;t<e.length;t+=3)e[t]=(c?-(e[t]??0):e[t]??0)*d,e[t+1]=(e[t+1]??0)*d,e[t+2]=(c?-(e[t+2]??0):e[t+2]??0)*d;r.push(new Yd(`${m}.position`,[...l.times],[...e]))}}return{clip:new Xd(`${e.name} (VRM)`,e.duration,r),retargetedTracks:r.length,skippedBones:[...i]}}function YM(e,t){let n=e.getClip().duration;if(!Number.isFinite(t)||t===0||n<=0)return 0;let r=t%n;return r<0?r+n:r}var XM=.2,ZM=.12,QM=class extends Z_{static typeName=`ModelInstance3D`;static signals=[`animationFinished`];static props={...Z_.props,model:{default:``,asset:{kind:`model`,refOnly:!0}},animation:{default:``,asset:{kind:`animation`}},targetHeight:{default:0,range:{min:0}},castShadow:{default:!1},animationLoop:{default:!0},animationSpeed:{default:1},animationOffset:{default:0},animationUpper:{default:``},animationUpperLoop:{default:!1},upperBodyRoot:{default:`Spine`},receiveShadow:{default:!1},tint:{default:``},metalness:{default:-1,range:{min:0,max:1,allow:[-1]}},roughness:{default:-1,range:{min:0,max:1,allow:[-1]}}};model=``;animation=``;targetHeight=0;castShadow=!1;animationLoop=!0;animationSpeed=1;animationOffset=0;animationUpper=``;animationUpperLoop=!1;upperBodyRoot=`Spine`;receiveShadow=!1;tint=``;metalness=-1;roughness=-1;store=null;entry=null;mountedRef=``;fittedHeight=-1;fitPending=!1;fitGroup=null;_mountedObject3D(){return this.fitGroup}mixer=null;appliedOffset=0;get _mixer(){return this.mixer}get _playingClip(){return this.playing}get _currentActionTime(){return this.currentAction?.time??0}playing=``;currentAction=null;playingUpper=``;upperAction=null;baseMode=`full`;maskCache=new Map;actionKeys=new WeakMap;warnedClaim=!1;tintTargets=[];tintedClones=[];appliedMods=``;nodePoses=new Map;poseNode(e,t){this.nodePoses.set(e,t),this.applyPoses()}_createObject3D(){return new Ec}findBone(e){let t=this.fitGroup;if(!t||e===``)return null;let n=t.getObjectByName(e)??t.getObjectByName(`mixamorig${e}`)??t.getObjectByName(`mixamorig:${e}`);if(n)return n;let r=e.toLowerCase(),i=null;return t.traverse(e=>{!i&&e.name.toLowerCase().endsWith(r)&&(i=e)}),i}boneNames(){let e=[];return this.fitGroup?.traverse(t=>{t.isBone&&e.push(t.name)}),e}availableAnimations(){let e=this.entry?.animations.map(e=>e.name)??[],t=this.store?.animationRefs()??[];return[...e,...t]}_syncModel(e){this.store=e;let t=this._ensureObject3D();if(this.model===``){this.fitGroup&&this.unmount(t);return}let n=e.getModel(this.model);if(!(n.status!==`ready`||!n.scene)){if(this.mountedRef!==this.model){this.unmount(t);let e;if(n.isVrm){if(n.claimedBy&&n.claimedBy!==this){this.warnedClaim||(this.warnedClaim=!0,this.diagnose(`warn`,`incanto: VRM '${this.model}' is already displayed by another node — a VRM asset can back only one ModelInstance3D.`));return}n.claimedBy=this,e=n.scene}else e=iE(n.scene);let r=new Ec;r.add(e),t.add(r),this.fitGroup=r,this.entry=n,this.mountedRef=this.model,this.mixer=new ep(e),this.mixer.addEventListener(`finished`,e=>{let t=e.action,n=(t&&this.actionKeys.get(t))??this.animation;t&&t===this.upperAction&&(t.fadeOut(ZM),this.upperAction=null,this.playingUpper=``,this.animationUpper=``),this.emit(`animationFinished`,n)}),this.playing=``,this.currentAction=null,this.fittedHeight=-1,e.traverse(e=>{e.userData.incantoModelShared=!0}),this.tintTargets=[],this.tintedClones=[],this.appliedMods=``,e.traverse(e=>{let t=e;t.isMesh&&t.material&&this.tintTargets.push({mesh:t,original:t.material})})}this.fitGroup&&this.fittedHeight!==this.targetHeight&&(this.fittedHeight=this.targetHeight,this.targetHeight<=0?(this.fitGroup.scale.setScalar(1),this.fitPending=!1):$M(this.fitGroup)?this.fitPending=!0:this.applyFit()),this.fitGroup&&this.fitGroup.traverse(e=>{let t=e;t.isMesh&&(t.castShadow=this.castShadow,t.receiveShadow=this.receiveShadow)}),this.applyMaterialMods(),this.applyPoses(),this.syncAnimation(e),this.syncUpperAnimation(e)}}applyFit(){let e=this.fitGroup;if(!e)return;this.fitPending=!1;let t=e.scale.x;e.scale.setScalar(1);let n=eN(e).getSize(new W).y,r=n>0?this.targetHeight/n:t;if(r<.05||r>20){e.scale.setScalar(1),this.diagnose(`warn`,`[incanto] ModelInstance3D '${this.name}': targetHeight fit measured an implausible scale (${r.toFixed(2)}x) — the model may have no geometry. Rendering at the model's authored scale instead.`);return}e.scale.setScalar(r)}applyMaterialMods(){let e=`${this.tint}|${this.metalness}|${this.roughness}`;if(e===this.appliedMods)return;for(let e of this.tintedClones)e.dispose();this.tintedClones=[];let t=this.tint?new q(this.tint):null,n=t!==null||this.metalness>=0||this.roughness>=0;for(let e of this.tintTargets){if(!n){e.mesh.material=e.original;continue}let r=e=>{let n=e.clone();if(t){let r=n,i=e.color;r.color&&=i?i.clone().multiply(t):t.clone()}let r=n;return this.metalness>=0&&typeof r.metalness==`number`&&(r.metalness=this.metalness),this.roughness>=0&&typeof r.roughness==`number`&&(r.roughness=this.roughness),n.userData.incantoTinted=!0,this.tintedClones.push(n),n};e.mesh.material=Array.isArray(e.original)?e.original.map(r):r(e.original)}this.appliedMods=e}applyPoses(){if(!this.fitGroup||this.nodePoses.size===0)return;let e=Math.PI/180;for(let[t,n]of this.nodePoses){let r=this.fitGroup.getObjectByName(t);r&&r.rotation.set(n[0]*e,n[1]*e,n[2]*e)}}resolveClip(e,t){if(!this.entry)return null;let n=this.entry.animations.find(t=>t.name===e);if(n)return n;if(!(e.startsWith(`$`)||/\.(glb|gltf)$/i.test(e)))return null;let r=t.getAnimation(e);if(r.status===`loading`)return`loading`;if(r.status!==`ready`||!r.scene)return null;let i=(r.clip?r.clips.find(e=>e.name===r.clip):void 0)??r.clips[0];if(!i)return null;let a=i.uuid;if(this.entry.isVrm&&this.entry.vrm){let t=this.entry.retargeted.get(a);if(t)return t;let n=JM(i,r.scene,this.entry.vrm);return n.skippedBones.length>0&&this.diagnose(`warn`,`incanto: retarget '${e}' skipped bones: ${n.skippedBones.join(`, `)}`),this.entry.retargeted.set(a,n.clip),n.clip}let o=this.entry.retargeted.get(a);if(o)return o;let s=GM(i,r.scene,this.fitGroup??this._ensureObject3D());return s.passthrough&&this.diagnose(`warn`,`incanto: animation '${e}' — ${s.reason}`),this.entry.retargeted.set(a,s.clip),s.clip}layerVariants(e){let t=this.findBone(this.upperBodyRoot);if(!t)return null;let n=`${e.uuid} ${t.name}`,r=this.maskCache.get(n);if(!r){let i=BM(t);r={upper:zM(e,i,`keep`),lower:zM(e,i,`drop`)},this.maskCache.set(n,r)}return r}upperLayerActive(){return this.animationUpper!==``||this.upperAction!==null}syncAnimation(e){if(!this.mixer||!this.entry)return;let t=this.upperLayerActive()?`lower`:`full`;if(this.playing===this.animation&&this.baseMode===t)return;if(this.animation===``){this.currentAction&&this.currentAction.fadeOut(XM),this.currentAction=null,this.playing=``,this.baseMode=t;return}let n=this.resolveClip(this.animation,e);if(n===`loading`)return;let r=n;if(r&&t===`lower`){let e=this.layerVariants(r);e&&(r=e.lower)}let i=this.playing===this.animation;if(this.playing=this.animation,this.baseMode=t,r){let e=this.mixer.clipAction(r);if(e.reset(),this.animationLoop?e.setLoop(To,1/0):(e.setLoop(wo,1),e.clampWhenFinished=!0),e.setEffectiveWeight(1),e.time=YM(e,this.animationOffset),this.appliedOffset=this.animationOffset,e.play(),this.actionKeys.set(e,this.animation),this.currentAction&&this.currentAction!==e){i&&r.duration>0&&(e.time=this.currentAction.time%r.duration);let t=r.duration>0&&this.currentAction.getClip().duration>0;e.crossFadeFrom(this.currentAction,XM,t)}this.currentAction=e}else this.diagnose(`warn`,`incanto: model '${this.model}' has no animation '${this.animation}' — embedded: ${this.entry.animations.map(e=>e.name).join(`, `)||`(none)`}; assets: ${e.animationRefs().join(`, `)||`(none)`}`)}syncUpperAnimation(e){if(!this.mixer||!this.entry||this.playingUpper===this.animationUpper)return;if(this.animationUpper===``){this.upperAction?.fadeOut(ZM),this.upperAction=null,this.playingUpper=``;return}let t=this.resolveClip(this.animationUpper,e);if(t===`loading`)return;if(!t){this.diagnose(`warn`,`incanto: model '${this.model}' has no animation '${this.animationUpper}' for the upper layer.`),this.playingUpper=this.animationUpper;return}let n=this.layerVariants(t);if(!n){this.diagnose(`warn`,`incanto: upperBodyRoot '${this.upperBodyRoot}' not found in '${this.model}' — upper layer skipped.`),this.playingUpper=this.animationUpper;return}let r=this.mixer.clipAction(n.upper);r.reset(),this.animationUpperLoop?r.setLoop(To,1/0):(r.setLoop(wo,1),r.clampWhenFinished=!0),r.setEffectiveWeight(1),r.time=YM(r,this.animationOffset),r.fadeIn(ZM),r.play(),this.actionKeys.set(r,this.animationUpper),this.upperAction&&this.upperAction!==r&&this.upperAction.fadeOut(ZM),this.upperAction=r,this.playingUpper=this.animationUpper}update(e){this.mixer&&this.mixer.timeScale!==this.animationSpeed&&(this.mixer.timeScale=this.animationSpeed),this.currentAction&&this.animationOffset!==this.appliedOffset&&(this.appliedOffset=this.animationOffset,this.currentAction.time=YM(this.currentAction,this.animationOffset)),this.mixer?.update(e),this.entry?.isVrm&&this.entry.claimedBy===this&&this.entry.vrm?.update(e),this.fitPending&&this.applyFit()}onExitTree(){this.unmount(this._ensureObject3D())}unmount(e){this.entry?.claimedBy===this&&(this.entry.claimedBy=null),this.fitGroup&&e.remove(this.fitGroup);for(let e of this.tintedClones)e.dispose();this.tintedClones=[],this.tintTargets=[],this.appliedMods=``,this.fitGroup=null,this.mixer=null,this.currentAction=null,this.upperAction=null,this.playingUpper=``,this.baseMode=`full`,this.maskCache.clear(),this.entry=null,this.mountedRef=``,this.playing=``,this.fittedHeight=-1}};function $M(e){let t=!1;return e.traverse(e=>{e.isSkinnedMesh&&(t=!0)}),t}function eN(e){e.updateMatrixWorld(!0);let t=new Xc,n=new Xc,r=new W,i=e.matrixWorld.clone().invert();return e.traverse(e=>{let a=e;if(!a.isMesh||!a.geometry)return;let o=a.geometry.getAttribute(`position`);if(a.isSkinnedMesh&&typeof a.getVertexPosition==`function`&&o&&a.geometry.getAttribute(`skinIndex`)&&a.geometry.getAttribute(`skinWeight`)&&o){for(let e=0;e<o.count;e++)a.getVertexPosition?.(e,r),t.expandByPoint(r.applyMatrix4(a.matrixWorld).applyMatrix4(i));return}a.geometry.computeBoundingBox(),a.geometry.boundingBox&&t.union(n.copy(a.geometry.boundingBox).applyMatrix4(a.matrixWorld).applyMatrix4(i))}),t}var tN=.01,nN=class e extends Z_{orderGroup=`effects`;static typeName=`Particles3D`;static signals=[`finished`];static props={orderGroup:{default:`effects`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},preset:{default:`custom`,options:[`custom`,...wr]},emitting:{default:!0},worldSpace:{default:!1},rate:{default:40},burst:{default:0},lifetime:{default:[.6,1.2]},speed:{default:[40,120]},directionDeg:{default:-90},spreadDeg:{default:30},gravity:{default:[0,0]},drag:{default:0},sizeStart:{default:8},sizeEnd:{default:2},colorStart:{default:`#ffffff`},colorEnd:{default:`#ffffff`},paletteColors:{default:[]},alphaStart:{default:1},alphaEnd:{default:0},shimmer:{default:0},blend:{default:`add`,options:[`add`,`normal`]},depthTest:{default:!0},maxParticles:{default:256}};preset=`custom`;emitting=!0;worldSpace=!1;rate=40;burst=0;lifetime=[.6,1.2];speed=[40,120];directionDeg=-90;spreadDeg=30;gravity=[0,0];drag=0;sizeStart=8;sizeEnd=2;colorStart=`#ffffff`;colorEnd=`#ffffff`;paletteColors=[];alphaStart=1;alphaEnd=0;shimmer=0;blend=`add`;depthTest=!0;maxParticles=256;static validateJson(e){let t=e;if(t.preset!==`custom`&&!wr.includes(t.preset))throw new L(`BAD_FORMAT`,`Particles3D '${e.name}' preset must be 'custom' or one of [${wr.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:wr});if(t.blend!==`add`&&t.blend!==`normal`)throw new L(`BAD_FORMAT`,`Particles3D '${e.name}' blend must be 'add' or 'normal', got '${t.blend}'.`,{prop:`blend`,validOptions:[`add`,`normal`]})}sim=null;bursted=!1;finishedEmitted=!1;_ensureSim(){if(!this.sim){Tr(this,this.preset,ct(e.typeName));let t=this.tree?.engine?.rng??new Ee(4660);this.sim=new Dr({rate:this.emitting?this.rate:0,lifetime:[this.lifetime[0]??1,this.lifetime[1]??1],speed:[(this.speed[0]??0)*tN,(this.speed[1]??0)*tN],directionDeg:this.directionDeg,spreadDeg:this.spreadDeg,gravity:[(this.gravity[0]??0)*tN,(this.gravity[1]??0)*tN,(this.gravity[2]??0)*tN],drag:this.drag,maxParticles:this.maxParticles,spreadZ:!0},t)}return this.sim}get aliveCount(){return this.sim?.count??0}particles(){let e=[];return this.sim?.forEach(t=>{e.push({...t})}),e}lastWorld=null;wasEmitting=!1;update(e){let t=this._ensureSim();this.holdWorldSpace(t),t.setRate(this.emitting?this.rate:0),this.burst>0&&!this.bursted&&(this.emitting||this.armedByReplay)&&(this.bursted=!0,this.armedByReplay=!1,t.burst(this.burst),this.report(`burst`,this.burst));let n=this.emitting&&this.rate>0;n!==this.wasEmitting&&(this.wasEmitting=n,n&&this.report(`emit`,this.rate)),t.update(e),(!this.emitting||this.rate===0)&&this.bursted&&t.done&&!this.finishedEmitted&&(this.finishedEmitted=!0,this.emit(`finished`))}holdWorldSpace(e){if(!this.worldSpace){this.lastWorld=null;return}let t=0,n=0,r=0;for(let e=this;e;e=e.parent)e instanceof Z_&&(t+=e.position[0]??0,n+=e.position[1]??0,r+=e.position[2]??0);let i=this.lastWorld;i&&e.translateAll(i[0]-t,i[1]-n,i[2]-r),this.lastWorld=[t,n,r]}report(e,t){let n=this.tree?.engine;n?.effects.record({kind:e,name:this.preset,from:this.getPath(),amount:t,at:n.time})}replay(){this.bursted=!1,this.finishedEmitted=!1,this.armedByReplay=!0}armedByReplay=!1;points=null;positions=null;colors=null;paletteCache=[];paletteCacheKey=``;_syncObject3D(){super._syncObject3D(),this.syncParticles()}refreshPalette(){let e=this.paletteColors;if(e.length===0)return null;let t=e.join(`|`);if(t!==this.paletteCacheKey){this.paletteCacheKey=t;for(let t=0;t<e.length;t++){let n=this.paletteCache[t];n||(n=new q,this.paletteCache[t]=n),n.set(e[t])}this.paletteCache.length=e.length}return this.paletteCache}syncParticles(){let e=this._ensureSim();if(!this.points||(this.positions?.length??0)!==this.maxParticles*3){this.points?.removeFromParent(),this.positions=new Float32Array(this.maxParticles*3),this.colors=new Float32Array(this.maxParticles*4);let e=new Y;e.setAttribute(`position`,new J(this.positions,3)),e.setAttribute(`color`,new J(this.colors,4));let t=new $u({size:(this.sizeStart+this.sizeEnd)/2*tN,map:sN(),vertexColors:!0,transparent:!0,depthWrite:!1,depthTest:this.depthTest,alphaTest:.02,sizeAttenuation:!0,blending:this.blend===`add`?2:1});this.points=new id(e,t),this.points.frustumCulled=!1,this._ensureObject3D().add(this.points)}this.points.renderOrder=this.renderOrder;let t=this.points.material;t.depthTest=this.depthTest,t.blending=this.blend===`add`?2:1;let n=this.positions,r=this.colors,i=this.refreshPalette(),a=i?null:rN.set(this.colorStart),o=iN.set(this.colorEnd),s=this.shimmer,c=0;e.forEach(e=>{n[c*3]=e.x,n[c*3+1]=-e.y,n[c*3+2]=e.z;let t=i?i[Math.floor(e.seed*i.length)]:a,l=Math.max(0,this.alphaStart+(this.alphaEnd-this.alphaStart)*e.t);s>0&&(l*=.5+.5*Math.sin(2*Math.PI*(e.age*s+e.seed))),aN.copy(t).lerp(o,e.t),r[c*4]=aN.r,r[c*4+1]=aN.g,r[c*4+2]=aN.b,r[c*4+3]=l,c+=1});let l=this.points.geometry;l.setDrawRange(0,c),l.getAttribute(`position`).needsUpdate=!0,l.getAttribute(`color`).needsUpdate=!0}free(){let e=this._builtObject3D;e&&e.traverse(e=>{let t=e;t.geometry?.dispose();let n=t.material,r=Array.isArray(n)?n:n?[n]:[];for(let e of r)e.dispose?.()}),super.free()}},rN=new q,iN=new q,aN=new q,oN=null;function sN(){if(oN)return oN;let e=63/2,t=new Uint8Array(4096*4);for(let n=0;n<64;n++)for(let r=0;r<64;r++){let i=(r-e)/e,a=(n-e)/e,o=Math.hypot(i,a),s=.35,c;if(o<=s)c=1;else{let e=Math.max(0,1-(o-s)/(1-s));c=e*e}let l=Math.round(c*255),u=(n*64+r)*4;t[u]=255,t[u+1]=255,t[u+2]=255,t[u+3]=l}let n=new vu(t,64,64,Na);return n.magFilter=ha,n.minFilter=ha,n.generateMipmaps=!1,n.needsUpdate=!0,oN=n,n}var cN=2.2,lN=2,uN=.52,dN=.3,fN=1.5,pN=7,mN=.004;function hN(e){if(e.path.length<2)return[];let t=kN(e.path,Math.max(e.cell,e.depth));if(t.length<2)return[];let n=t[t.length-1].along||1,r=t.map(t=>Math.max(AN(e.widths,t.along/n),.05)/2);gN(t,r);let i=t.map(t=>e.groundAt(t.x,t.z)),a=e.depth*cN,o=e.depth*pN,s=Array(t.length);for(let e=0;e<t.length;e++){let n=i[e]-a;if(e===0){s[e]=n;continue}let r=t[e].along-t[e-1].along,c=s[e-1]-r*mN;s[e]=Math.max(Math.min(n,c),i[e]-o)}let c=[];for(let n=1;n<t.length;n++){let a=t[n-1],o=t[n],l=Math.max((i[n-1]+i[n])/2-(s[n-1]+s[n])/2,0);if(l<=.001)continue;let u=Math.min(r[n-1],r[n]),d=Math.max(e.depth*lN,e.cell*fN),f=Math.max(u-d*uN,u*dN,e.cell*.5);c.push({path:[[a.x,a.z],[o.x,o.z]],width:f*2,depth:l,taper:d})}return c}function gN(e,t){let n=e.length,r=Array(n).fill(1/0),i=Array(n).fill(1/0);if(n<3)return{left:r,right:i};let a=t=>e[t].along,o=Array(n).fill(0);for(let t=1;t<n-1;t++){let n=e[t-1],r=e[t],i=e[t+1],a=r.x-n.x,s=r.z-n.z,c=i.x-r.x,l=i.z-r.z,u=Math.hypot(a,s),d=Math.hypot(c,l);if(u<1e-4||d<1e-4)continue;let f=(a*l-s*c)/(u*d);o[t]=Math.asin(Math.max(-1,Math.min(1,f)))/((u+d)/2)}let s=(e,t)=>{let r=Array(n);for(let i=0;i<n;i++){let o=0,s=0;for(let n=i;n>=0&&a(i)-a(n)<=3;n--){let r=e(n);o=t===`max`?Math.max(o,r):o+r,s++}for(let r=i+1;r<n&&a(r)-a(i)<=3;r++){let n=e(r);o=t===`max`?Math.max(o,n):o+n,s++}r[i]=t===`max`?o:o/Math.max(s,1)}return r},c=s(e=>Math.max(o[e],0),`max`),l=s(e=>Math.max(-o[e],0),`max`),u=s(e=>c[e],`mean`),d=s(e=>l[e],`mean`),f=e=>e>1e-5?Math.min(1/e*jN,MN):MN;for(let e=0;e<n;e++)r[e]=f(Math.max(u[e],c[e]*.6)),i[e]=f(Math.max(d[e],l[e]*.6));for(let e=0;e<n;e++)t[e]=Math.min(t[e],Math.max(r[e],i[e]));return{left:r,right:i}}function _N(e,t=.6){let n=[];for(let r of e){let e=Math.max(r.wettedLeft??r.halfLeft,r.wettedRight??r.halfRight),i=Math.max(r.halfLeft,r.halfRight);e-i>t&&n.push({along:r.along,wettedHalfWidth:e,carriedHalfWidth:i})}return n}var vN=24,yN=3,bN=4,xN=.05,SN=12,CN=14,wN=3,TN=5,EN=.04,DN=2;function ON(e,t){return Math.max(e*wN,e+t*TN)}function kN(e,t){let n=e.map(e=>({x:e[0]??0,z:e[1]??0})).filter((e,t,n)=>t===0||Math.hypot(e.x-(n[t-1]?.x??0),e.z-(n[t-1]?.z??0))>1e-6);if(n.length<2||t<=0)return[];let r=[],i=0;for(let e=0;e<n.length-1;e++){let t=n[Math.max(0,e-1)],a=n[e],o=n[e+1],s=n[Math.min(n.length-1,e+2)];for(let e=0;e<vN;e++){let n=e/vN,c=WN(t.x,a.x,o.x,s.x,n),l=WN(t.z,a.z,o.z,s.z,n),u=r[r.length-1];u&&(i+=Math.hypot(c-u.x,l-u.z)),r.push({x:c,z:l,along:i})}}let a=n[n.length-1],o=r[r.length-1];o&&(i+=Math.hypot(a.x-o.x,a.z-o.z)),r.push({x:a.x,z:a.z,along:i});let s=i;if(s<1e-6)return[];let c=Math.max(1,Math.round(s/t)),l=s/c,u=[],d=0;for(let e=0;e<=c;e++){let t=Math.min(e*l,s);for(;d<r.length-2&&r[d+1].along<t;)d++;let n=r[d],i=r[Math.min(d+1,r.length-1)],a=i.along-n.along,o=a>1e-9?(t-n.along)/a:0;u.push({x:n.x+(i.x-n.x)*o,z:n.z+(i.z-n.z)*o,tx:1,tz:0,along:t})}for(let e=0;e<u.length;e++){let t=u[Math.max(0,e-1)],n=u[Math.min(u.length-1,e+1)],r=n.x-t.x,i=n.z-t.z,a=Math.hypot(r,i)||1,o=u[e];o.tx=r/a,o.tz=i/a}return u}function AN(e,t){if(e.length===0)return 0;if(e.length===1)return e[0];let n=Math.min(Math.max(t,0),1)*(e.length-1),r=Math.min(Math.floor(n),e.length-2),i=n-r,a=e[r];return a+(e[r+1]-a)*i}var jN=.85,MN=1e4,NN=1.2,PN=.35,FN=.4;function IN(e,t){let n=Math.min(...e);return Math.min(Math.max(Math.min(n*.45,t*.45),.3),2.5)}function LN(e){let t=kN(e.path,e.step);if(t.length===0)return[];let n=t[t.length-1].along||1,r=t.map(t=>Math.max(AN(e.widths,t.along/n),.05)/2),i=gN(t,r),a=t.map(t=>e.bedAt(t.x,t.z)),o=Array(a.length);for(let e=0;e<a.length;e++){let t=a[e];o[e]=e===0?t:Math.min(t,o[e-1])}let s=Math.max(.5,e.depth*1.5),c=o.map((e,t)=>{let n=0,r=0;for(let i=-3;i<=yN;i++){let a=o[Math.min(Math.max(t+i,0),o.length-1)];Math.abs(a-e)>s||(n+=a,r++)}return r>0?n/r:e}),l=Array(c.length);for(let e=0;e<c.length;e++){let t=c[e];l[e]=e===0?t:Math.min(t,l[e-1])}let u=e.fit===!0,d=Array(t.length),f=Array(t.length);for(let n=0;n<t.length;n++){let i=t[n],a=l[n]+e.depth;if(!u){f[n]=[1/0,1/0],d[n]=a;continue}let o=ON(r[n],e.depth),s=-i.tz,c=i.tx,p=-1/0,m=-1/0;for(let t=1;t<=CN;t++){let n=t/CN*o;p=Math.max(p,e.bedAt(i.x+s*n,i.z+c*n)),m=Math.max(m,e.bedAt(i.x-s*n,i.z-c*n))}f[n]=[p,m],d[n]=Math.min(a,p,m)}for(let e=0;e<d.length;e++){let t=d[e];u&&(t=Math.max(t,a[e]+EN)),e>0&&(t=Math.min(t,d[e-1]));let n=f[e];t=Math.min(t,Math.max(Math.min(n[0],n[1]),a[e]+EN)),d[e]=t}let p=t.map((t,n)=>{let i=r[n];if(!u)return[i,i];let a=ON(i,e.depth),o=d[n],s=-t.tz,c=t.tx,l=n=>{for(let r=1;r<=CN;r++){let i=r/CN*a;if(e.bedAt(t.x+s*i*n,t.z+c*i*n)>=o)return i}return-i};return[l(1),l(-1)]}),m=p.map(e=>[Math.abs(e[0]),Math.abs(e[1])]);for(let e of[0,1]){for(let n=1;n<m.length;n++){let r=Math.max(t[n].along-t[n-1].along,1e-4),i=m[n-1][e],a=m[n][e];m[n][e]=Math.min(a,i+r*NN)}for(let n=m.length-2;n>=0;n--){let r=Math.max(t[n+1].along-t[n].along,1e-4),i=m[n+1][e],a=m[n][e];m[n][e]=Math.min(a,i+r*NN)}}let h=m.map((e,t)=>{let n=0,r=0,i=0;for(let e=-2;e<=DN;e++){let a=m[Math.min(Math.max(t+e,0),m.length-1)];n+=Math.abs(a[0]),r+=Math.abs(a[1]),i++}let a=m[t];return[Math.min(n/i,Math.abs(a[0])),Math.min(r/i,Math.abs(a[1]))]}),g=t.map((e,t)=>[Math.min(h[t][0],i.left[t]),Math.min(h[t][1],i.right[t])]),_=g.reduce((e,t)=>Math.max(e,t[0],t[1]),0);for(let e=0;e<t.length;e++){let n=g[e];for(let r=e+1;r<t.length;r++){let i=g[r],a=Math.max(n[0],n[1],i[0],i[1]);if(t[r].along-t[e].along<a*3)continue;let o=Math.hypot(t[e].x-t[r].x,t[e].z-t[r].z);if(!(o>_*2+PN))for(let e of[0,1]){if(o>=n[e]+i[e]+PN)continue;let t=Math.max((o-PN)/2,FN);n[e]>t&&(n[e]=t),i[e]>t&&(i[e]=t)}}}for(let e of[0,1]){for(let n=1;n<g.length;n++){let r=Math.max(t[n].along-t[n-1].along,1e-4),i=g[n-1][e],a=g[n][e];g[n][e]=Math.min(a,i+r*NN)}for(let n=g.length-2;n>=0;n--){let r=Math.max(t[n+1].along-t[n].along,1e-4),i=g[n+1][e],a=g[n][e];g[n][e]=Math.min(a,i+r*NN)}}let v=r.reduce((e,t)=>e+t,0)/r.length||1;return t.map((n,i)=>{let a=d[i],o=Math.max(0,i-1),s=Math.min(t.length-1,i+1),c=t[s].along-t[o].along,l=(d[o]-d[s])/(c||1),u=Math.max(0,l),f=r[i],m=h[i],_=Math.min(Math.max(e.flowSpeed*Math.sqrt(v/f)*(1+bN*u),xN),SN),y=p[i];return{...n,halfWidth:f,halfLeft:Math.max(g[i][0],.05),halfRight:Math.max(g[i][1],.05),wettedLeft:Math.max(m[0],.05),wettedRight:Math.max(m[1],.05),spillLeft:y[0]<0,spillRight:y[1]<0,surfaceY:a,slope:u,speed:_}})}function RN(e,t){let n=Math.max(1,Math.round(t.acrossSegments)),r=n+1,i=e.length*r,a=new Float32Array(i*3),o=new Float32Array(i*3),s=new Float32Array(i*2),c=new Float32Array(i*2),l=new Float32Array(i*4),u=Math.max(0,e.length-1)*n,d=new Uint32Array(u*6);for(let i=0;i<e.length;i++){let u=e[i],d=Math.max(u.surfaceY-zN(t,u.x,u.z),EN),f=-u.tz,p=u.tx,m=Math.hypot(u.slope,1),h=u.tx*u.slope/m,g=1/m,_=u.tz*u.slope/m;for(let e=0;e<=n;e++){let m=e/n*2-1,v=m*(m<0?u.halfRight:u.halfLeft)*t.bankOvershoot,y=u.x+f*v,b=u.z+p*v,x=i*r+e,S=zN(t,y,b),C=(m<0?u.spillRight:u.spillLeft)?d+(EN-d)*Math.abs(m):d,w=Math.min(u.surfaceY,S+C);a[x*3]=y,a[x*3+1]=w,a[x*3+2]=b,o[x*3]=h,o[x*3+1]=g,o[x*3+2]=_,s[x*2]=u.along,s[x*2+1]=v,c[x*2]=u.tx,c[x*2+1]=u.tz,l[x*4]=u.speed,l[x*4+1]=Math.max(0,w-S),l[x*4+2]=u.slope,l[x*4+3]=m*t.bankOvershoot}}let f=0;for(let t=0;t+1<e.length;t++)for(let e=0;e<n;e++){let n=t*r+e,i=n+1,a=n+r,o=a+1;d[f++]=n,d[f++]=i,d[f++]=a,d[f++]=i,d[f++]=o,d[f++]=a}return{positions:a,normals:o,uvs:s,flow:c,river:l,indices:d}}function zN(e,t,n){let r=e.bedBlur??0;return r<=0?e.bedAt(t,n):(e.bedAt(t,n)+e.bedAt(t+r,n)+e.bedAt(t-r,n)+e.bedAt(t,n+r)+e.bedAt(t,n-r))/5}function BN(e,t,n){if(e.length===0)return null;let r=0,i=1/0,a=Math.max(1,Math.floor(Math.sqrt(e.length)/2));if(a>1){for(let o=0;o<e.length;o+=a){let a=e[o],s=(a.x-t)**2+(a.z-n)**2;s<i&&(i=s,r=o)}let o=Math.max(0,r-a),s=Math.min(e.length-1,r+a);i=1/0;for(let a=o;a<=s;a++){let o=e[a],s=(o.x-t)**2+(o.z-n)**2;s<i&&(i=s,r=a)}return VN(e,r,t,n)}for(let a=0;a<e.length;a++){let o=e[a],s=(o.x-t)**2+(o.z-n)**2;s<i&&(i=s,r=a)}if(e.length===1){let r=e[0];return HN(r,r,0,t,n,!1)}return VN(e,r,t,n)}function VN(e,t,n,r){let i=null,a=1/0;for(let o of[t-1,t]){if(o<0||o+1>=e.length)continue;let t=e[o],s=e[o+1],c=s.x-t.x,l=s.z-t.z,u=c*c+l*l,d=u>1e-9?((n-t.x)*c+(r-t.z)*l)/u:0,f=Math.min(Math.max(d,0),1),p=o===0&&d<0||o+2===e.length&&d>1,m=t.x+c*f,h=t.z+l*f,g=(m-n)**2+(h-r)**2;g<a&&(a=g,i=HN(t,s,f,n,r,p))}return i}function HN(e,t,n,r,i,a){let o=e.x+(t.x-e.x)*n,s=e.z+(t.z-e.z)*n,c=e.tx+(t.tx-e.tx)*n,l=e.tz+(t.tz-e.tz)*n,u=Math.hypot(c,l)||1;c/=u,l/=u;let d=(r-o)*-l+(i-s)*c,f=(e,t)=>e+(t-e)*n,p=d<0?f(e.halfRight,t.halfRight):f(e.halfLeft,t.halfLeft),m=d/(p||1);return{inside:!a&&Math.abs(m)<=1,across:m,along:e.along+(t.along-e.along)*n,surfaceY:e.surfaceY+(t.surfaceY-e.surfaceY)*n,dirX:c,dirZ:l,speed:e.speed+(t.speed-e.speed)*n,halfWidth:p}}function UN(e,t={}){let n=t.minGrade??.45,r=t.minDrop??1.2,i=[],a=-1;for(let t=0;t<=e.length;t++){let o=t<e.length&&e[t].slope>=n;if(o&&a<0&&(a=t),o||a<0)continue;let s=e[Math.max(0,a-1)],c=e[Math.min(e.length-1,t)],l=s.surfaceY-c.surfaceY;l>=r&&i.push({x:c.x,z:c.z,lipX:s.x,lipZ:s.z,lipHalfWidth:Math.min((s.halfLeft+s.halfRight)/2,s.halfWidth),lipDirX:s.tx,lipDirZ:s.tz,lipSpeed:s.speed,topY:s.surfaceY,baseY:c.surfaceY,drop:l,halfWidth:(c.halfLeft+c.halfRight)/2,dirX:c.tx,dirZ:c.tz,speed:c.speed}),a=-1}return i}function WN(e,t,n,r,i){let a=i*i,o=a*i;return .5*(2*t+(-e+n)*i+(2*e-5*t+4*n-r)*a+(-e+3*t-3*n+r)*o)}var GN=`
|
|
7515
|
+
`)},e.customProgramCacheKey=()=>`incanto-tuft-wind`}var Hj=[`grass`,`flowers`,`reeds`],Uj=[`blades`,`simple`,`mesh`,`tufts`],Wj=[`grass`,`fern`],Gj={grass:.08,flowers:.14,reeds:.05},Kj=[.75,1.25],qj=.05,Jj=.25,Yj=2e5,Xj=8,Zj=.05,Qj=.38,$j=[.75,1.3],eM=.1,tM=.42,nM=[.6,1.6],rM=.8,iM=.9,aM=.04,oM=[`#f5f1e2`,`#e9d052`,`#8d7bd9`],sM=1/3,cM=1.5,lM=1.45,uM=.4,dM=.13,fM=[.85,1.2],pM=[.8,1.3],mM=`#b3a24e`,hM=.8,gM=.5,_M=class e extends Q_{static typeName=`Foliage3D`;static props={kind:{default:`grass`,options:Hj},style:{default:`mesh`,options:Uj},tuftStyle:{default:`grass`,options:Wj},area:{default:[20,20]},density:{default:12},maxInstances:{default:5e4},height:{default:.25},colorA:{default:`#4d7232`},colorB:{default:`#9aab55`},groundColor:{default:`#1f3015`},sunDirection:{default:[.5,.8,.3]},fadeStart:{default:60},fadeEnd:{default:90},sway:{default:.6},interaction:{default:!0},coverage:{default:.85},flowers:{default:0},seed:{default:1},drape:{default:null},avoidWater:{default:!0},terrain:{default:``,nodePath:!0},renderOrder:{default:2}};renderOrder=2;kind=`grass`;style=`mesh`;tuftStyle=`grass`;area=[20,20];density=12;maxInstances=5e4;height=.25;colorA=`#4d7232`;colorB=`#9aab55`;groundColor=`#1f3015`;sunDirection=[.5,.8,.3];fadeStart=60;fadeEnd=90;sway=.6;interaction=!0;coverage=.85;flowers=0;seed=1;drape=null;avoidWater=!0;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(!Hj.includes(t.kind))throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' kind must be one of [${Hj.join(`, `)}], got '${t.kind}'.`,{prop:`kind`,validOptions:Hj});if(!Uj.includes(t.style))throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' style must be one of [${Uj.join(`, `)}], got '${t.style}'.`,{prop:`style`,validOptions:Uj});if(!Wj.includes(t.tuftStyle))throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' tuftStyle must be one of [${Wj.join(`, `)}], got '${t.tuftStyle}'.`,{prop:`tuftStyle`,validOptions:Wj});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' area must be positive [x, z] meters, got ${JSON.stringify(t.area)}.`,{prop:`area`});if(!(t.density>0)||!(t.maxInstances>=1))throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' needs density > 0 and maxInstances >= 1, got density ${t.density}, maxInstances ${t.maxInstances}.`,{prop:`density`});if(t.maxInstances>Yj)throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' maxInstances is capped at ${Yj} (got ${t.maxInstances}) — split giant fields into multiple nodes.`,{prop:`maxInstances`});if(!(t.fadeStart>=0)||!(t.fadeEnd>t.fadeStart))throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' needs fadeStart >= 0 and fadeEnd > fadeStart (the LOD fade window), got fadeStart ${t.fadeStart}, fadeEnd ${t.fadeEnd}.`,{prop:`fadeStart`});let n=t.sunDirection;if(!Array.isArray(n)||n.length!==3||!n.every(e=>Number.isFinite(e))||Math.hypot(n[0]??0,n[1]??0,n[2]??0)===0)throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' sunDirection must be a non-zero [x, y, z] vector, got ${JSON.stringify(n)}.`,{prop:`sunDirection`});if(!(t.coverage>0)||!(t.coverage<=1))throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' coverage must be in (0, 1] (carpet fill — 1 is solid, lower carves dirt patches), got ${t.coverage}.`,{prop:`coverage`});if(!(t.flowers>=0)||!(t.flowers<=.2))throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' flowers must be in [0, 0.2] (fraction of instances rendered as flower heads — for a whole flower FIELD use kind: 'flowers'), got ${t.flowers}.`,{prop:`flowers`});if(t.drape!==null&&typeof t.drape!=`boolean`)throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' drape must be true, false or null (null = auto: drape whenever the scene has a Terrain3D), got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new L(`BAD_FORMAT`,`Foliage3D '${e.name}' terrain must be a node-path string (empty = auto-find), got ${JSON.stringify(t.terrain)}.`,{prop:`terrain`})}time=0;pivot=null;meshes=[];bladesMaterial=null;benderSlots=null;pickedBenders=[];fieldKey=``;tuftTime=null;tuftStrength=null;tuftTexture=null;_createObject3D(){return new Ec}get isBlades(){return this.kind===`grass`&&this.style===`blades`}get isMesh(){return this.kind===`grass`&&this.style===`mesh`}get isTufts(){return this.kind===`grass`&&this.style===`tufts`}get isShaderField(){return this.isMesh||this.isBlades}_field(){return this.rebuildIfNeeded(),this.meshes[0]}_fields(){return this.rebuildIfNeeded(),this.meshes}update(e){this.time+=e,this.pickedBenders=this.computeBenders(),this.writeAnimationUniforms()}writeAnimationUniforms(){if(this.isShaderField&&this.bladesMaterial){let e=this.bladesMaterial.uniforms;e.time&&(e.time.value=this.time),e.windStrength&&(e.windStrength.value=this.sway*(this.isMesh?Qj:Jj));let t=this.benderSlots;if(t)for(let e=0;e<4;e++){let n=this.pickedBenders[e];n?t[e]?.set(n.x,n.y,n.z,n.radius):t[e]?.set(0,0,0,0)}}else this.isTufts&&(this.tuftTime&&(this.tuftTime.value=this.time),this.tuftStrength&&(this.tuftStrength.value=this.sway*dM))}_syncObject3D(){super._syncObject3D(),this.rebuildIfNeeded();let e=this.pivot;if(this.writeAnimationUniforms(),this.isShaderField){e.matrix.identity();let t=this.bladesMaterial.uniforms;(t.bottomColor?.value).set(this.colorA),(t.topColor?.value).set(this.colorB),this.isMesh&&((t.groundColor?.value).set(this.groundColor),(t.sunDirection?.value).set(this.sunDirection[0]??0,this.sunDirection[1]??1,this.sunDirection[2]??0).normalize(),t.fadeStart&&(t.fadeStart.value=this.fadeStart),t.fadeEnd&&(t.fadeEnd.value=this.fadeEnd))}else if(this.isTufts)e.matrix.identity();else if(this.sway>0){let t=Math.sin(this.time*1.7)*qj*this.sway,n=Math.sin(this.time*1.3+1.7)*qj*this.sway*.6;e.matrix.makeShear(0,0,t,n,0,0)}else e.matrix.identity();e.matrixWorldNeedsUpdate=!0}_applySunDirection(t){if(!this.isMesh||!this.bladesMaterial)return;let n=e.props.sunDirection?.default;this.sunDirection.every((e,t)=>e===n[t])&&(this.bladesMaterial.uniforms.sunDirection?.value)?.set(t[0],t[1],t[2])}computeBenders(){if(!this.interaction||!this.isShaderField)return[];let[e,t,n]=KA(this);this.drape===!0&&!this.drapeTerrain&&this.resolveDrape();let r=this.drapeTerrain,i=[];for(let e of Tj(this)){let n=r?r.heightAt(e.x,e.z):t,a=e.footY-n;a<=gM&&a>=-2.5&&i.push({x:e.x,y:e.y,z:e.z,radius:e.radius+hM})}return fj(i,{x:e,z:n,areaX:this.area[0]??0,areaZ:this.area[1]??0})}rebuildIfNeeded(){this.pivot||(this.pivot=new Ec,this.pivot.matrixAutoUpdate=!1,this._ensureObject3D().add(this.pivot));let e=JSON.stringify([this.kind,this.style,this.tuftStyle,this.area,this.density,this.maxInstances,this.height,this.colorA,this.colorB,this.coverage,this.avoidWater,this.flowers,this.seed,this.drape,this.terrain]);if(e===this.fieldKey&&this.meshes.length>0)return;this.fieldKey=e,this.disposeMeshes(),this.resolveDrape();let t=this.isMesh?Xj:this.isTufts?sM:1,n=Math.min(Math.floor((this.area[0]??0)*(this.area[1]??0)*this.density*t),this.maxInstances);this.isMesh?this.buildMeshField(n):this.isTufts?this.buildTuftField(n):this.isBlades?this.buildBladesField(n):this.buildSimpleField(n);for(let e of this.meshes)GA(e),this.pivot.add(e)}resolveDrape(){if(this.drapeTerrain=null,this.drape===!1)return;let e=qA(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=KA(this);else if(this.terrain!==``)throw new L(`NODE_NOT_FOUND`,`Foliage3D '${this.name}' drape terrain '${this.terrain}' is not a Terrain3D in the tree.`,{prop:`terrain`})}bedY(e,t){let n=this.drapeTerrain;return n?n.heightAt(this.drapeWorld[0]+e,this.drapeWorld[2]+t)-this.drapeWorld[1]:0}dryOnly(e){if(!this.avoidWater)return e;let t=XA(this);if(t.length===0)return e;let[n,,r]=KA(this);return e.filter(e=>!ZA(t,e.x+n,e.z+r,this.bedY(e.x,e.z)+this.worldY()))}worldY(){return KA(this)[1]}buildMeshField(e){let t=EA({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:e,density:this.density*Xj}),n=this.dryOnly(this.coverage>=1?t:t.filter(e=>TA(e.x,e.z,this.seed)<=this.coverage)),r=this.flowers>0?Math.floor(n.length*this.flowers):0,i=new Set;for(let e=0;e<r;e++)i.add(Math.floor((e+.5)*n.length/r));let a=n.filter((e,t)=>!i.has(t)),o=n.filter((e,t)=>i.has(t));this.benderSlots=Array.from({length:4},()=>new Js(0,0,0,0));let s=wd.merge([X.lights,X.fog]);Object.assign(s,{time:{value:0},windStrength:{value:this.sway*Qj},topColor:{value:new q(this.colorB)},bottomColor:{value:new q(this.colorA)},groundColor:{value:new q(this.groundColor)},sunDirection:{value:new W(this.sunDirection[0]??0,this.sunDirection[1]??1,this.sunDirection[2]??0).normalize()},fadeStart:{value:this.fadeStart},fadeEnd:{value:this.fadeEnd},benders:{value:this.benderSlots}}),this.bladesMaterial=new Dd({vertexShader:vj,fragmentShader:yj,uniforms:s,fog:!0,lights:!0,side:2});let c=mj(Zj),l=a.length,u=Math.max(l,1),d=new Au(c,this.bladesMaterial,u);d.count=l,d.receiveShadow=!0;let f=new Ee(this.seed+5352221),p=new Float32Array(u*4),m=new Float32Array(u),h=new Float32Array(u);for(let e=0;e<l;e++){let t=a[e],n=_A(t.x,t.z),r=CA(t.x,t.z,this.seed),i=(r-.55)/1.15,o=f.range($j[0],$j[1]),s=this.height*r*(.55+t.scale*.6);CM.set(t.x,this.bedY(t.x,t.z),t.z),wM.setFromAxisAngle(xM,t.rotY),TM.set(o,s,o),d.setMatrixAt(e,SM.compose(CM,wM,TM));let c=n.leanDir+f.range(-.6,.6),l=(eM+tM*(.5*n.lean+.5*f.next()))*(1+rM*i);p[e*4]=Math.cos(c)*l,p[e*4+1]=Math.sin(c)*l,p[e*4+2]=f.range(nM[0],nM[1])*(1+iM*i),p[e*4+3]=f.next(),m[e]=n.hue;let u=wA(t.x,t.z,this.seed)*.85+(f.next()-.5)*.3;h[e]=Math.min(1,Math.max(0,u))}c.setAttribute(`aBlade`,new Su(p,4)),c.setAttribute(`aClumpHue`,new Su(m,1)),c.setAttribute(`aDry`,new Su(h,1)),d.instanceMatrix.needsUpdate=!0,this.meshes=[d],o.length>0&&this.meshes.push(this.buildFlowerMesh(o))}buildFlowerMesh(e){let t=new Au(hj(aM),new kd({roughness:1,side:2}),Math.max(e.length,1));t.count=e.length,t.receiveShadow=!0;let n=new Ee(this.seed+15797765);for(let r=0;r<e.length;r++){let i=e[r],a=CA(i.x,i.z,this.seed),o=this.height*a*(.85+n.next()*.35);CM.set(i.x,this.bedY(i.x,i.z),i.z),wM.setFromAxisAngle(xM,i.rotY),TM.set(1,o,1),t.setMatrixAt(r,SM.compose(CM,wM,TM));let s=n.next(),c=oM[s<.45?0:s<.75?1:2];t.setColorAt(r,OM.set(c))}return t.instanceMatrix.needsUpdate=!0,t.instanceColor&&(t.instanceColor.needsUpdate=!0),t}buildTuftField(e){let t=EA({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:e,density:this.density*sM}),n=this.dryOnly(this.coverage>=1?t:t.filter(e=>TA(e.x,e.z,this.seed)<=this.coverage));this.tuftTime={value:this.time},this.tuftStrength={value:this.sway*dM};let r=new kd({alphaTest:.5,side:2,roughness:1}),i=jj(this.seed,this.tuftStyle);i&&(r.map=i,this.tuftTexture=i),Vj(r,this.tuftTime,this.tuftStrength);let a=new Au(yM(),r,Math.max(n.length,1));a.count=n.length,a.castShadow=!1,a.receiveShadow=!0;let o=new Ee(this.seed+7403357),s=EM.set(this.colorA),c=DM.set(this.colorB);for(let e=0;e<n.length;e++){let t=n[e],r=1+(CA(t.x,t.z,this.seed)-1)*uM,i=this.height*cM*r*o.range(fM[0],fM[1]),l=i*lM*o.range(pM[0],pM[1]);CM.set(t.x,this.bedY(t.x,t.z),t.z),wM.setFromAxisAngle(xM,t.rotY),TM.set(l,i,l),a.setMatrixAt(e,SM.compose(CM,wM,TM));let u=_A(t.x,t.z),d=Math.min(1,Math.max(0,.5+.35*u.hue+(o.next()-.5)*.3)),f=Math.min(1,Math.max(0,wA(t.x,t.z,this.seed)*.8-.1));OM.copy(s).lerp(c,d).lerp(kM.set(mM),f*.5).multiplyScalar(o.range(.62,1.18)),a.setColorAt(e,OM)}a.instanceMatrix.needsUpdate=!0,a.instanceColor&&(a.instanceColor.needsUpdate=!0),this.meshes=[a]}buildBladesField(e){let t=EA({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:e,density:this.density});this.benderSlots=Array.from({length:4},()=>new Js(0,0,0,0));let n=wd.merge([X.fog]);Object.assign(n,{time:{value:0},windStrength:{value:this.sway*Jj},topColor:{value:new q(this.colorB)},bottomColor:{value:new q(this.colorA)},grassHeight:{value:this.height},grassScale:{value:1},benders:{value:this.benderSlots}}),this.bladesMaterial=new Dd({vertexShader:gj,fragmentShader:_j,uniforms:n,fog:!0,transparent:!0,side:2,depthWrite:!0,depthTest:!0,alphaTest:.1,blending:0});let r=vM(this.height),i=new Au(r,this.bladesMaterial,Math.max(e,1)),a=new Au(r,this.bladesMaterial,Math.max(e,1));i.count=e,a.count=e,i.renderOrder=this.renderOrder,a.renderOrder=this.renderOrder;for(let n=0;n<e;n++){let e=t[n];CM.set(e.x,this.bedY(e.x,e.z),e.z),TM.setScalar(e.scale),wM.setFromAxisAngle(xM,e.rotY),i.setMatrixAt(n,SM.compose(CM,wM,TM)),wM.setFromAxisAngle(xM,e.rotY+Math.PI/2),a.setMatrixAt(n,SM.compose(CM,wM,TM))}i.instanceMatrix.needsUpdate=!0,a.instanceMatrix.needsUpdate=!0,this.meshes=[i,a]}buildSimpleField(e){let t=new kd({side:2,roughness:1}),n=new Au(bM(Gj[this.kind]??.08),t,Math.max(e,1));n.receiveShadow=!0;let r=new Ee(this.seed),i=(this.area[0]??0)/2,a=(this.area[1]??0)/2,o=EM.set(this.colorA),s=DM.set(this.colorB),c=this.avoidWater?XA(this):[],[l,u,d]=KA(this),f=0;for(let t=0;t<e;t++){let e=r.range(-i,i),t=r.range(-a,a),p=r.range(0,Math.PI*2),m=r.range(Kj[0],Kj[1]),h=r.next(),g=this.bedY(e,t);c.length>0&&ZA(c,e+l,t+d,g+u)||(CM.set(e,g,t),wM.setFromAxisAngle(xM,p),TM.set(1,this.height*m,1),SM.compose(CM,wM,TM),n.setMatrixAt(f,SM),n.setColorAt(f,OM.copy(o).lerp(s,h)),f++)}n.count=f,n.instanceMatrix.needsUpdate=!0,n.instanceColor&&(n.instanceColor.needsUpdate=!0),this.meshes=[n]}disposeMeshes(){let e=new Set(this.meshes.map(e=>e.geometry)),t=new Set(this.meshes.map(e=>e.material));for(let e of this.meshes)e.removeFromParent(),e.dispose();for(let t of e)t.dispose();for(let e of t)e.dispose?.();this.bladesMaterial?.dispose(),this.bladesMaterial=null,this.benderSlots=null,this.tuftTexture?.dispose(),this.tuftTexture=null,this.tuftTime=null,this.tuftStrength=null,this.meshes=[]}free(){this.disposeMeshes(),this.pivot=null,super.free()}};function vM(e){let t=new _d(1,e,1,1);return t.translate(0,e/2,0),t}function yM(){let e=[],t=[],n=[],r=[];for(let i=0;i<3;i++){let a=i*Math.PI/3,o=Math.cos(a)/2,s=Math.sin(a)/2,c=-Math.sin(a),l=Math.cos(a),u=i*4;e.push(-o,0,-s,o,0,s,-o,1,-s,o,1,s);for(let e=0;e<4;e++)t.push(c,0,l);n.push(0,0,1,0,0,1,1,1),r.push(u,u+1,u+3,u,u+3,u+2)}let i=new Y;return i.setAttribute(`position`,new J(new Float32Array(e),3)),i.setAttribute(`normal`,new J(new Float32Array(t),3)),i.setAttribute(`uv`,new J(new Float32Array(n),2)),i.setIndex(r),i}function bM(e){let t=e/2,n=new Float32Array([-t,0,0,t,0,0,-t,1,0,t,1,0,0,0,-t,0,0,t,0,1,-t,0,1,t]),r=new Float32Array([0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0]),i=new Y;return i.setAttribute(`position`,new J(n,3)),i.setAttribute(`normal`,new J(r,3)),i.setIndex([0,1,2,2,1,3,4,5,6,6,5,7]),i}var xM=new W(0,1,0),SM=new K,CM=new W,wM=new U,TM=new W,EM=new q,DM=new q,OM=new q,kM=new q,AM=class extends lk{static typeName=`Label3D`;static props={...lk.props,text:{default:``},height:{default:.3},color:{default:`#ffffff`},font:{default:`sans-serif`},outline:{default:`#000000`},billboard:{default:`full`,options:[`y`,`full`,`none`]}};text=``;height=.3;color=`#ffffff`;font=`sans-serif`;outline=`#000000`;billboard=`full`;static validateJson(e){let t=e;if(t.texture)throw new L(`BAD_FORMAT`,`Label3D '${t.name}' has a "texture" — a label draws its own text, so the image would never be used. Set "text" instead, or use a Sprite3D.`,{prop:`texture`})}canvas=null;canvasTexture=null;lastKey=``;resolveTexture(e){let t=Qe(this,this.text);if(t===``||typeof document>`u`)return null;let n=`${t}\0${this.height}\0${this.color}\0${this.font}\0${this.outline}`;return n!==this.lastKey&&(this.lastKey=n,this.rasterize()),this.canvasTexture}rasterize(){let e=Qe(this,this.text),t=Math.max(8,Math.round(this.height*256));this.canvas??=document.createElement(`canvas`);let n=this.canvas.getContext(`2d`);if(!n)return;let r=Math.max(1,Math.round(t*.14)),i=`bold ${t}px ${this.font}`;n.font=i;let a=Math.max(1,Math.ceil(n.measureText(e).width)+r*2),o=Math.ceil(t*1.35)+r*2;this.canvas.width=a,this.canvas.height=o,n.font=i,n.textBaseline=`middle`,n.textAlign=`center`,this.outline!==``&&(n.lineWidth=r,n.lineJoin=`round`,n.strokeStyle=this.outline,n.strokeText(e,a/2,o/2)),n.fillStyle=this.color,n.fillText(e,a/2,o/2),this.canvasTexture?.dispose();let s=new sd(this.canvas);s.colorSpace=Ro,this.canvasTexture=s,this.size=[a/o*this.height*1.35,this.height*1.35]}free(){this.canvasTexture?.dispose(),this.canvasTexture=null,super.free()}},jM=class extends Q_{static typeName=`DirectionalLight3D`;static props={color:{default:`#ffffff`},intensity:{default:1},castShadow:{default:!1},shadowArea:{default:75},shadowMapSize:{default:2048},shadowFollowsCamera:{default:!1}};color=`#ffffff`;intensity=1;castShadow=!1;shadowArea=75;shadowMapSize=2048;shadowFollowsCamera=!1;_createObject3D(){return new Af}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();if(e.color.set(this.color),e.intensity=this.intensity,e.castShadow=this.castShadow,this.castShadow&&`shadow`in e){let t=e.shadow.camera;`left`in t&&(t.left=-this.shadowArea,t.right=this.shadowArea,t.top=this.shadowArea,t.bottom=-this.shadowArea,t.near=.5,t.far=500,t.updateProjectionMatrix()),e.shadow.mapSize.set(this.shadowMapSize,this.shadowMapSize),e.shadow.bias=-2e-4,e.shadow.normalBias=.002}}},MM=class extends Q_{static typeName=`OmniLight3D`;static props={color:{default:`#ffffff`},intensity:{default:1},range:{default:0}};color=`#ffffff`;intensity=1;range=0;_createObject3D(){return new Df}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();e.color.set(this.color),e.intensity=this.intensity,e.distance=this.range}},NM=class extends Q_{static typeName=`LoftMesh3D`;static props={sections:{default:[]},slices:{default:24},smooth:{default:4},material:{default:{}},castShadow:{default:!1},receiveShadow:{default:!1}};sections=[];slices=24;smooth=4;material={};castShadow=!1;receiveShadow=!1;static validateJson(e){let t=e;PM(t.sections,e.name),OD(t.material,e.name,`LoftMesh3D`);for(let n of[`map`,`normalMap`,`repeat`])if(t.material[n]!==void 0)throw new L(`BAD_FORMAT`,`LoftMesh3D '${e.name}' material does not support '${n}' — a loft has no UVs; use color/metalness/roughness/clearcoat/envMapIntensity instead.`,{prop:`material`})}geometryKey=``;_createObject3D(){return new iu(new Y,new Ad)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D(),t=JSON.stringify([this.sections,this.slices,this.smooth]);t!==this.geometryKey&&this.sections.length>=2&&(e.geometry.dispose(),e.geometry=LM(this.sections,this.slices,this.smooth),this.geometryKey=t),DD(e.material,this.material),e.castShadow=this.castShadow,e.receiveShadow=this.receiveShadow}free(){let e=this._builtObject3D;e&&e.traverse(e=>{let t=e;t.geometry?.dispose();let n=t.material,r=Array.isArray(n)?n:n?[n]:[];for(let e of r)e.dispose?.()}),super.free()}};function PM(e,t){let n=e=>{throw new L(`BAD_FORMAT`,`LoftMesh3D '${t}' ${e}`,{prop:`sections`})};(!Array.isArray(e)||e.length<2)&&n(`sections needs at least 2 stations, got ${JSON.stringify(e)}.`);for(let[t,r]of e.entries()){(typeof r!=`object`||!r)&&n(`sections[${t}] must be an object.`);for(let e of[`z`,`width`,`height`,`y`])(typeof r[e]!=`number`||!Number.isFinite(r[e]))&&n(`sections[${t}].${e} must be a finite number, got ${JSON.stringify(r[e])}.`);(r.width<=0||r.height<=0)&&n(`sections[${t}] width/height must be positive, got ${r.width}×${r.height}.`),r.corner!==void 0&&!(typeof r.corner==`number`&&r.corner>=0&&r.corner<=1)&&n(`sections[${t}].corner must be in 0..1, got ${JSON.stringify(r.corner)}.`),t>0&&r.z<=e[t-1].z&&n(`sections[].z must be strictly ascending (sections[${t}].z=${r.z}).`)}}function FM(e,t,n,r,i){let a=i*i,o=a*i;return .5*(2*t+(n-e)*i+(2*e-5*t+4*n-r)*a+(-e+3*t-3*n+r)*o)}function IM(e,t){let n=t=>{let n=e[Math.max(0,Math.min(e.length-1,t))];return{z:n.z,width:n.width,height:n.height,y:n.y,corner:n.corner??.7}},r=[];for(let i=0;i<e.length-1;i++){let a=n(i-1),o=n(i),s=n(i+1),c=n(i+2),l=i===e.length-2?t+1:t;for(let e=0;e<l;e++){let n=e/t;r.push({z:FM(a.z,o.z,s.z,c.z,n),width:Math.max(1e-4,FM(a.width,o.width,s.width,c.width,n)),height:Math.max(1e-4,FM(a.height,o.height,s.height,c.height,n)),y:FM(a.y,o.y,s.y,c.y,n),corner:Math.min(1,Math.max(0,FM(a.corner,o.corner,s.corner,c.corner,n)))})}}return r}function LM(e,t,n){let r=Math.max(8,Math.min(64,Math.round(t))),i=IM(e,Math.max(1,Math.min(16,Math.round(n)))),a=i.length,o=new Float32Array((a*r+2)*3),s=i[0],c=i[a-1];o.set([0,s.y,s.z],0),o.set([0,c.y,c.z],3);for(let e=0;e<a;e++){let t=i[e],n=8-6*t.corner,a=Math.max(n,5);for(let i=0;i<r;i++){let s=i/r*Math.PI*2,c=Math.cos(s),l=Math.sin(s),u=l>=0?n:a,d=t.width/2*Math.sign(c)*Math.abs(c)**(2/u),f=t.height/2*Math.sign(l)*Math.abs(l)**(2/u),p=(2+e*r+i)*3;o[p]=d,o[p+1]=t.y+f,o[p+2]=t.z}}let l=[],u=(e,t)=>2+e*r+t%r;for(let e=0;e<a-1;e++)for(let t=0;t<r;t++){let n=u(e,t),r=u(e,t+1),i=u(e+1,t),a=u(e+1,t+1);l.push(n,r,i,r,a,i)}for(let e=0;e<r;e++)l.push(0,u(0,e+1),u(0,e)),l.push(1,u(a-1,e),u(a-1,e+1));let d=new Y;return d.setAttribute(`position`,new J(o,3)),d.setIndex(l),d.computeVertexNormals(),d}function RM(e){let t=e.lastIndexOf(`.`);return t===-1?e:e.slice(0,t)}function zM(e,t,n){let r=e.tracks.filter(e=>{let r=t.has(RM(e.name));return n===`keep`?r:!r});return new Xd(`${e.name}#${n}`,e.duration,r)}function BM(e){let t=new Set,n=e=>{t.add(e.name);for(let t of e.children)n(t)};return n(e),t}function VM(e){let t=null;return e.traverse(e=>{t||(/^mixamorig[:_]?hips$/i.test(e.name)||/^hips$/i.test(e.name))&&(t=e)}),t}function HM(e,t){e.updateMatrixWorld(!0);let n=t.matrixWorld.clone().premultiply(e.matrixWorld.clone().invert());return Math.abs(n.elements[13]??0)}var UM=e=>e.split(`.`)[0]??``,WM=e=>e.split(`.`).pop()??``;function GM(e,t,n){let r=new Set;if(n.traverse(e=>r.add(e.name)),e.tracks.filter(e=>WM(e.name)===`quaternion`&&r.has(UM(e.name))).length===0)return{clip:e,droppedTracks:0,hipsScale:1,passthrough:!0,reason:`no bone in this clip matches the model — played as authored`};let i=VM(t),a=VM(n),o=i?HM(t,i):0,s=a?HM(n,a):0,c=o>1e-6&&s>1e-6?s/o:1,l=a?.name??``,u=[],d=0;for(let t of e.tracks){let e=UM(t.name),n=WM(t.name);if(!r.has(e)){d+=1;continue}if(n===`quaternion`){u.push(t);continue}if(n===`position`&&e===l){let e=Array.from(t.values,e=>e*c);u.push(new Yd(t.name,Array.from(t.times),e));continue}d+=1}return{clip:new Xd(`${e.name} (retargeted)`,e.duration,u),droppedTracks:d,hipsScale:c,passthrough:!1}}var KM={Hips:`hips`,Spine:`spine`,Spine1:`chest`,Spine2:`upperChest`,Neck:`neck`,Head:`head`,LeftShoulder:`leftShoulder`,LeftArm:`leftUpperArm`,LeftForeArm:`leftLowerArm`,LeftHand:`leftHand`,RightShoulder:`rightShoulder`,RightArm:`rightUpperArm`,RightForeArm:`rightLowerArm`,RightHand:`rightHand`,LeftUpLeg:`leftUpperLeg`,LeftLeg:`leftLowerLeg`,LeftFoot:`leftFoot`,LeftToeBase:`leftToes`,RightUpLeg:`rightUpperLeg`,RightLeg:`rightLowerLeg`,RightFoot:`rightFoot`,RightToeBase:`rightToes`,LeftHandThumb1:`leftThumbMetacarpal`,LeftHandThumb2:`leftThumbProximal`,LeftHandThumb3:`leftThumbDistal`,LeftHandIndex1:`leftIndexProximal`,LeftHandIndex2:`leftIndexIntermediate`,LeftHandIndex3:`leftIndexDistal`,LeftHandMiddle1:`leftMiddleProximal`,LeftHandMiddle2:`leftMiddleIntermediate`,LeftHandMiddle3:`leftMiddleDistal`,LeftHandRing1:`leftRingProximal`,LeftHandRing2:`leftRingIntermediate`,LeftHandRing3:`leftRingDistal`,LeftHandPinky1:`leftLittleProximal`,LeftHandPinky2:`leftLittleIntermediate`,LeftHandPinky3:`leftLittleDistal`,RightHandThumb1:`rightThumbMetacarpal`,RightHandThumb2:`rightThumbProximal`,RightHandThumb3:`rightThumbDistal`,RightHandIndex1:`rightIndexProximal`,RightHandIndex2:`rightIndexIntermediate`,RightHandIndex3:`rightIndexDistal`,RightHandMiddle1:`rightMiddleProximal`,RightHandMiddle2:`rightMiddleIntermediate`,RightHandMiddle3:`rightMiddleDistal`,RightHandRing1:`rightRingProximal`,RightHandRing2:`rightRingIntermediate`,RightHandRing3:`rightRingDistal`,RightHandPinky1:`rightLittleProximal`,RightHandPinky2:`rightLittleIntermediate`,RightHandPinky3:`rightLittleDistal`},qM={};for(let[e,t]of Object.entries(KM))qM[`mixamorig${e}`]=t,qM[`mixamorig:${e}`]=t;function JM(e,t,n){let r=[],i=new Set,a=new U,o=new U,s=new U,c=n.meta?.metaVersion===`0`,l=t.getObjectByName(`mixamorigHips`)??t.getObjectByName(`mixamorig:Hips`),u=n.humanoid?.getNormalizedBoneNode(`hips`),d=l&&u?Math.abs(u.getWorldPosition(new W).y)/Math.max(1e-6,Math.abs(l.getWorldPosition(new W).y)):1;for(let l of e.tracks){let e=l.name.lastIndexOf(`.`),u=l.name.slice(0,e),f=l.name.slice(e+1),p=qM[u],m=p?n.humanoid?.getNormalizedBoneNode(p)?.name:void 0,h=t.getObjectByName(u);if(!m||!h){i.add(u);continue}if(h.getWorldQuaternion(a).invert(),h.parent?h.parent.getWorldQuaternion(o):o.identity(),l instanceof qd&&f===`quaternion`){let e=Float32Array.from(l.values);for(let t=0;t<e.length;t+=4)s.set(e[t]??0,e[t+1]??0,e[t+2]??0,e[t+3]??1),s.premultiply(o).multiply(a),e[t]=c?-s.x:s.x,e[t+1]=s.y,e[t+2]=c?-s.z:s.z,e[t+3]=s.w;r.push(new qd(`${m}.quaternion`,[...l.times],[...e]))}else if(l instanceof Yd&&f===`position`){let e=Float32Array.from(l.values);for(let t=0;t<e.length;t+=3)e[t]=(c?-(e[t]??0):e[t]??0)*d,e[t+1]=(e[t+1]??0)*d,e[t+2]=(c?-(e[t+2]??0):e[t+2]??0)*d;r.push(new Yd(`${m}.position`,[...l.times],[...e]))}}return{clip:new Xd(`${e.name} (VRM)`,e.duration,r),retargetedTracks:r.length,skippedBones:[...i]}}function YM(e,t){let n=e.getClip().duration;if(!Number.isFinite(t)||t===0||n<=0)return 0;let r=t%n;return r<0?r+n:r}var XM=.2,ZM=.12,QM=class extends Q_{static typeName=`ModelInstance3D`;static signals=[`animationFinished`];static props={...Q_.props,model:{default:``,asset:{kind:`model`,refOnly:!0}},animation:{default:``,asset:{kind:`animation`}},targetHeight:{default:0,range:{min:0}},castShadow:{default:!1},animationLoop:{default:!0},animationSpeed:{default:1},animationOffset:{default:0},animationUpper:{default:``},animationUpperLoop:{default:!1},upperBodyRoot:{default:`Spine`},receiveShadow:{default:!1},tint:{default:``},metalness:{default:-1,range:{min:0,max:1,allow:[-1]}},roughness:{default:-1,range:{min:0,max:1,allow:[-1]}}};model=``;animation=``;targetHeight=0;castShadow=!1;animationLoop=!0;animationSpeed=1;animationOffset=0;animationUpper=``;animationUpperLoop=!1;upperBodyRoot=`Spine`;receiveShadow=!1;tint=``;metalness=-1;roughness=-1;store=null;entry=null;mountedRef=``;fittedHeight=-1;fitPending=!1;fitGroup=null;_mountedObject3D(){return this.fitGroup}mixer=null;appliedOffset=0;get _mixer(){return this.mixer}get _playingClip(){return this.playing}get _currentActionTime(){return this.currentAction?.time??0}playing=``;currentAction=null;playingUpper=``;upperAction=null;baseMode=`full`;maskCache=new Map;actionKeys=new WeakMap;warnedClaim=!1;tintTargets=[];tintedClones=[];appliedMods=``;nodePoses=new Map;poseNode(e,t){this.nodePoses.set(e,t),this.applyPoses()}_createObject3D(){return new Ec}findBone(e){let t=this.fitGroup;if(!t||e===``)return null;let n=t.getObjectByName(e)??t.getObjectByName(`mixamorig${e}`)??t.getObjectByName(`mixamorig:${e}`);if(n)return n;let r=e.toLowerCase(),i=null;return t.traverse(e=>{!i&&e.name.toLowerCase().endsWith(r)&&(i=e)}),i}boneNames(){let e=[];return this.fitGroup?.traverse(t=>{t.isBone&&e.push(t.name)}),e}availableAnimations(){let e=this.entry?.animations.map(e=>e.name)??[],t=this.store?.animationRefs()??[];return[...e,...t]}_syncModel(e){this.store=e;let t=this._ensureObject3D();if(this.model===``){this.fitGroup&&this.unmount(t);return}let n=e.getModel(this.model);if(!(n.status!==`ready`||!n.scene)){if(this.mountedRef!==this.model){this.unmount(t);let e;if(n.isVrm){if(n.claimedBy&&n.claimedBy!==this){this.warnedClaim||(this.warnedClaim=!0,this.diagnose(`warn`,`incanto: VRM '${this.model}' is already displayed by another node — a VRM asset can back only one ModelInstance3D.`));return}n.claimedBy=this,e=n.scene}else e=iE(n.scene);let r=new Ec;r.add(e),t.add(r),this.fitGroup=r,this.entry=n,this.mountedRef=this.model,this.mixer=new ep(e),this.mixer.addEventListener(`finished`,e=>{let t=e.action,n=(t&&this.actionKeys.get(t))??this.animation;t&&t===this.upperAction&&(t.fadeOut(ZM),this.upperAction=null,this.playingUpper=``,this.animationUpper=``),this.emit(`animationFinished`,n)}),this.playing=``,this.currentAction=null,this.fittedHeight=-1,e.traverse(e=>{e.userData.incantoModelShared=!0}),this.tintTargets=[],this.tintedClones=[],this.appliedMods=``,e.traverse(e=>{let t=e;t.isMesh&&t.material&&this.tintTargets.push({mesh:t,original:t.material})})}this.fitGroup&&this.fittedHeight!==this.targetHeight&&(this.fittedHeight=this.targetHeight,this.targetHeight<=0?(this.fitGroup.scale.setScalar(1),this.fitPending=!1):$M(this.fitGroup)?this.fitPending=!0:this.applyFit()),this.fitGroup&&this.fitGroup.traverse(e=>{let t=e;t.isMesh&&(t.castShadow=this.castShadow,t.receiveShadow=this.receiveShadow)}),this.applyMaterialMods(),this.applyPoses(),this.syncAnimation(e),this.syncUpperAnimation(e)}}applyFit(){let e=this.fitGroup;if(!e)return;this.fitPending=!1;let t=e.scale.x;e.scale.setScalar(1);let n=eN(e).getSize(new W).y,r=n>0?this.targetHeight/n:t;if(r<.05||r>20){e.scale.setScalar(1),this.diagnose(`warn`,`[incanto] ModelInstance3D '${this.name}': targetHeight fit measured an implausible scale (${r.toFixed(2)}x) — the model may have no geometry. Rendering at the model's authored scale instead.`);return}e.scale.setScalar(r)}applyMaterialMods(){let e=`${this.tint}|${this.metalness}|${this.roughness}`;if(e===this.appliedMods)return;for(let e of this.tintedClones)e.dispose();this.tintedClones=[];let t=this.tint?new q(this.tint):null,n=t!==null||this.metalness>=0||this.roughness>=0;for(let e of this.tintTargets){if(!n){e.mesh.material=e.original;continue}let r=e=>{let n=e.clone();if(t){let r=n,i=e.color;r.color&&=i?i.clone().multiply(t):t.clone()}let r=n;return this.metalness>=0&&typeof r.metalness==`number`&&(r.metalness=this.metalness),this.roughness>=0&&typeof r.roughness==`number`&&(r.roughness=this.roughness),n.userData.incantoTinted=!0,this.tintedClones.push(n),n};e.mesh.material=Array.isArray(e.original)?e.original.map(r):r(e.original)}this.appliedMods=e}applyPoses(){if(!this.fitGroup||this.nodePoses.size===0)return;let e=Math.PI/180;for(let[t,n]of this.nodePoses){let r=this.fitGroup.getObjectByName(t);r&&r.rotation.set(n[0]*e,n[1]*e,n[2]*e)}}resolveClip(e,t){if(!this.entry)return null;let n=this.entry.animations.find(t=>t.name===e);if(n)return n;if(!(e.startsWith(`$`)||/\.(glb|gltf)$/i.test(e)))return null;let r=t.getAnimation(e);if(r.status===`loading`)return`loading`;if(r.status!==`ready`||!r.scene)return null;let i=(r.clip?r.clips.find(e=>e.name===r.clip):void 0)??r.clips[0];if(!i)return null;let a=i.uuid;if(this.entry.isVrm&&this.entry.vrm){let t=this.entry.retargeted.get(a);if(t)return t;let n=JM(i,r.scene,this.entry.vrm);return n.skippedBones.length>0&&this.diagnose(`warn`,`incanto: retarget '${e}' skipped bones: ${n.skippedBones.join(`, `)}`),this.entry.retargeted.set(a,n.clip),n.clip}let o=this.entry.retargeted.get(a);if(o)return o;let s=GM(i,r.scene,this.fitGroup??this._ensureObject3D());return s.passthrough&&this.diagnose(`warn`,`incanto: animation '${e}' — ${s.reason}`),this.entry.retargeted.set(a,s.clip),s.clip}layerVariants(e){let t=this.findBone(this.upperBodyRoot);if(!t)return null;let n=`${e.uuid} ${t.name}`,r=this.maskCache.get(n);if(!r){let i=BM(t);r={upper:zM(e,i,`keep`),lower:zM(e,i,`drop`)},this.maskCache.set(n,r)}return r}upperLayerActive(){return this.animationUpper!==``||this.upperAction!==null}syncAnimation(e){if(!this.mixer||!this.entry)return;let t=this.upperLayerActive()?`lower`:`full`;if(this.playing===this.animation&&this.baseMode===t)return;if(this.animation===``){this.currentAction&&this.currentAction.fadeOut(XM),this.currentAction=null,this.playing=``,this.baseMode=t;return}let n=this.resolveClip(this.animation,e);if(n===`loading`)return;let r=n;if(r&&t===`lower`){let e=this.layerVariants(r);e&&(r=e.lower)}let i=this.playing===this.animation;if(this.playing=this.animation,this.baseMode=t,r){let e=this.mixer.clipAction(r);if(e.reset(),this.animationLoop?e.setLoop(To,1/0):(e.setLoop(wo,1),e.clampWhenFinished=!0),e.setEffectiveWeight(1),e.time=YM(e,this.animationOffset),this.appliedOffset=this.animationOffset,e.play(),this.actionKeys.set(e,this.animation),this.currentAction&&this.currentAction!==e){i&&r.duration>0&&(e.time=this.currentAction.time%r.duration);let t=r.duration>0&&this.currentAction.getClip().duration>0;e.crossFadeFrom(this.currentAction,XM,t)}this.currentAction=e}else this.diagnose(`warn`,`incanto: model '${this.model}' has no animation '${this.animation}' — embedded: ${this.entry.animations.map(e=>e.name).join(`, `)||`(none)`}; assets: ${e.animationRefs().join(`, `)||`(none)`}`)}syncUpperAnimation(e){if(!this.mixer||!this.entry||this.playingUpper===this.animationUpper)return;if(this.animationUpper===``){this.upperAction?.fadeOut(ZM),this.upperAction=null,this.playingUpper=``;return}let t=this.resolveClip(this.animationUpper,e);if(t===`loading`)return;if(!t){this.diagnose(`warn`,`incanto: model '${this.model}' has no animation '${this.animationUpper}' for the upper layer.`),this.playingUpper=this.animationUpper;return}let n=this.layerVariants(t);if(!n){this.diagnose(`warn`,`incanto: upperBodyRoot '${this.upperBodyRoot}' not found in '${this.model}' — upper layer skipped.`),this.playingUpper=this.animationUpper;return}let r=this.mixer.clipAction(n.upper);r.reset(),this.animationUpperLoop?r.setLoop(To,1/0):(r.setLoop(wo,1),r.clampWhenFinished=!0),r.setEffectiveWeight(1),r.time=YM(r,this.animationOffset),r.fadeIn(ZM),r.play(),this.actionKeys.set(r,this.animationUpper),this.upperAction&&this.upperAction!==r&&this.upperAction.fadeOut(ZM),this.upperAction=r,this.playingUpper=this.animationUpper}update(e){this.mixer&&this.mixer.timeScale!==this.animationSpeed&&(this.mixer.timeScale=this.animationSpeed),this.currentAction&&this.animationOffset!==this.appliedOffset&&(this.appliedOffset=this.animationOffset,this.currentAction.time=YM(this.currentAction,this.animationOffset)),this.mixer?.update(e),this.entry?.isVrm&&this.entry.claimedBy===this&&this.entry.vrm?.update(e),this.fitPending&&this.applyFit()}onExitTree(){this.unmount(this._ensureObject3D())}unmount(e){this.entry?.claimedBy===this&&(this.entry.claimedBy=null),this.fitGroup&&e.remove(this.fitGroup);for(let e of this.tintedClones)e.dispose();this.tintedClones=[],this.tintTargets=[],this.appliedMods=``,this.fitGroup=null,this.mixer=null,this.currentAction=null,this.upperAction=null,this.playingUpper=``,this.baseMode=`full`,this.maskCache.clear(),this.entry=null,this.mountedRef=``,this.playing=``,this.fittedHeight=-1}};function $M(e){let t=!1;return e.traverse(e=>{e.isSkinnedMesh&&(t=!0)}),t}function eN(e){e.updateMatrixWorld(!0);let t=new Xc,n=new Xc,r=new W,i=e.matrixWorld.clone().invert();return e.traverse(e=>{let a=e;if(!a.isMesh||!a.geometry)return;let o=a.geometry.getAttribute(`position`);if(a.isSkinnedMesh&&typeof a.getVertexPosition==`function`&&o&&a.geometry.getAttribute(`skinIndex`)&&a.geometry.getAttribute(`skinWeight`)&&o){for(let e=0;e<o.count;e++)a.getVertexPosition?.(e,r),t.expandByPoint(r.applyMatrix4(a.matrixWorld).applyMatrix4(i));return}a.geometry.computeBoundingBox(),a.geometry.boundingBox&&t.union(n.copy(a.geometry.boundingBox).applyMatrix4(a.matrixWorld).applyMatrix4(i))}),t}var tN=.01,nN=class e extends Q_{orderGroup=`effects`;static typeName=`Particles3D`;static signals=[`finished`];static props={orderGroup:{default:`effects`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},preset:{default:`custom`,options:[`custom`,...wr]},emitting:{default:!0},worldSpace:{default:!1},rate:{default:40},burst:{default:0},lifetime:{default:[.6,1.2]},speed:{default:[40,120]},directionDeg:{default:-90},spreadDeg:{default:30},gravity:{default:[0,0]},drag:{default:0},sizeStart:{default:8},sizeEnd:{default:2},colorStart:{default:`#ffffff`},colorEnd:{default:`#ffffff`},paletteColors:{default:[]},alphaStart:{default:1},alphaEnd:{default:0},shimmer:{default:0},blend:{default:`add`,options:[`add`,`normal`]},depthTest:{default:!0},maxParticles:{default:256}};preset=`custom`;emitting=!0;worldSpace=!1;rate=40;burst=0;lifetime=[.6,1.2];speed=[40,120];directionDeg=-90;spreadDeg=30;gravity=[0,0];drag=0;sizeStart=8;sizeEnd=2;colorStart=`#ffffff`;colorEnd=`#ffffff`;paletteColors=[];alphaStart=1;alphaEnd=0;shimmer=0;blend=`add`;depthTest=!0;maxParticles=256;static validateJson(e){let t=e;if(t.preset!==`custom`&&!wr.includes(t.preset))throw new L(`BAD_FORMAT`,`Particles3D '${e.name}' preset must be 'custom' or one of [${wr.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:wr});if(t.blend!==`add`&&t.blend!==`normal`)throw new L(`BAD_FORMAT`,`Particles3D '${e.name}' blend must be 'add' or 'normal', got '${t.blend}'.`,{prop:`blend`,validOptions:[`add`,`normal`]})}sim=null;bursted=!1;finishedEmitted=!1;_ensureSim(){if(!this.sim){Tr(this,this.preset,ct(e.typeName));let t=this.tree?.engine?.rng??new Ee(4660);this.sim=new Dr({rate:this.emitting?this.rate:0,lifetime:[this.lifetime[0]??1,this.lifetime[1]??1],speed:[(this.speed[0]??0)*tN,(this.speed[1]??0)*tN],directionDeg:this.directionDeg,spreadDeg:this.spreadDeg,gravity:[(this.gravity[0]??0)*tN,(this.gravity[1]??0)*tN,(this.gravity[2]??0)*tN],drag:this.drag,maxParticles:this.maxParticles,spreadZ:!0},t)}return this.sim}get aliveCount(){return this.sim?.count??0}particles(){let e=[];return this.sim?.forEach(t=>{e.push({...t})}),e}lastWorld=null;wasEmitting=!1;update(e){let t=this._ensureSim();this.holdWorldSpace(t),t.setRate(this.emitting?this.rate:0),this.burst>0&&!this.bursted&&(this.emitting||this.armedByReplay)&&(this.bursted=!0,this.armedByReplay=!1,t.burst(this.burst),this.report(`burst`,this.burst));let n=this.emitting&&this.rate>0;n!==this.wasEmitting&&(this.wasEmitting=n,n&&this.report(`emit`,this.rate)),t.update(e),(!this.emitting||this.rate===0)&&this.bursted&&t.done&&!this.finishedEmitted&&(this.finishedEmitted=!0,this.emit(`finished`))}holdWorldSpace(e){if(!this.worldSpace){this.lastWorld=null;return}let t=0,n=0,r=0;for(let e=this;e;e=e.parent)e instanceof Q_&&(t+=e.position[0]??0,n+=e.position[1]??0,r+=e.position[2]??0);let i=this.lastWorld;i&&e.translateAll(i[0]-t,i[1]-n,i[2]-r),this.lastWorld=[t,n,r]}report(e,t){let n=this.tree?.engine;n?.effects.record({kind:e,name:this.preset,from:this.getPath(),amount:t,at:n.time})}replay(){this.bursted=!1,this.finishedEmitted=!1,this.armedByReplay=!0}armedByReplay=!1;points=null;positions=null;colors=null;paletteCache=[];paletteCacheKey=``;_syncObject3D(){super._syncObject3D(),this.syncParticles()}refreshPalette(){let e=this.paletteColors;if(e.length===0)return null;let t=e.join(`|`);if(t!==this.paletteCacheKey){this.paletteCacheKey=t;for(let t=0;t<e.length;t++){let n=this.paletteCache[t];n||(n=new q,this.paletteCache[t]=n),n.set(e[t])}this.paletteCache.length=e.length}return this.paletteCache}syncParticles(){let e=this._ensureSim();if(!this.points||(this.positions?.length??0)!==this.maxParticles*3){this.points?.removeFromParent(),this.positions=new Float32Array(this.maxParticles*3),this.colors=new Float32Array(this.maxParticles*4);let e=new Y;e.setAttribute(`position`,new J(this.positions,3)),e.setAttribute(`color`,new J(this.colors,4));let t=new $u({size:(this.sizeStart+this.sizeEnd)/2*tN,map:sN(),vertexColors:!0,transparent:!0,depthWrite:!1,depthTest:this.depthTest,alphaTest:.02,sizeAttenuation:!0,blending:this.blend===`add`?2:1});this.points=new id(e,t),this.points.frustumCulled=!1,this._ensureObject3D().add(this.points)}this.points.renderOrder=this.renderOrder;let t=this.points.material;t.depthTest=this.depthTest,t.blending=this.blend===`add`?2:1;let n=this.positions,r=this.colors,i=this.refreshPalette(),a=i?null:rN.set(this.colorStart),o=iN.set(this.colorEnd),s=this.shimmer,c=0;e.forEach(e=>{n[c*3]=e.x,n[c*3+1]=-e.y,n[c*3+2]=e.z;let t=i?i[Math.floor(e.seed*i.length)]:a,l=Math.max(0,this.alphaStart+(this.alphaEnd-this.alphaStart)*e.t);s>0&&(l*=.5+.5*Math.sin(2*Math.PI*(e.age*s+e.seed))),aN.copy(t).lerp(o,e.t),r[c*4]=aN.r,r[c*4+1]=aN.g,r[c*4+2]=aN.b,r[c*4+3]=l,c+=1});let l=this.points.geometry;l.setDrawRange(0,c),l.getAttribute(`position`).needsUpdate=!0,l.getAttribute(`color`).needsUpdate=!0}free(){let e=this._builtObject3D;e&&e.traverse(e=>{let t=e;t.geometry?.dispose();let n=t.material,r=Array.isArray(n)?n:n?[n]:[];for(let e of r)e.dispose?.()}),super.free()}},rN=new q,iN=new q,aN=new q,oN=null;function sN(){if(oN)return oN;let e=63/2,t=new Uint8Array(4096*4);for(let n=0;n<64;n++)for(let r=0;r<64;r++){let i=(r-e)/e,a=(n-e)/e,o=Math.hypot(i,a),s=.35,c;if(o<=s)c=1;else{let e=Math.max(0,1-(o-s)/(1-s));c=e*e}let l=Math.round(c*255),u=(n*64+r)*4;t[u]=255,t[u+1]=255,t[u+2]=255,t[u+3]=l}let n=new vu(t,64,64,Na);return n.magFilter=ha,n.minFilter=ha,n.generateMipmaps=!1,n.needsUpdate=!0,oN=n,n}var cN=2.2,lN=2,uN=.52,dN=.3,fN=1.5,pN=7,mN=.004;function hN(e){if(e.path.length<2)return[];let t=kN(e.path,Math.max(e.cell,e.depth));if(t.length<2)return[];let n=t[t.length-1].along||1,r=t.map(t=>Math.max(AN(e.widths,t.along/n),.05)/2);gN(t,r);let i=t.map(t=>e.groundAt(t.x,t.z)),a=e.depth*cN,o=e.depth*pN,s=Array(t.length);for(let e=0;e<t.length;e++){let n=i[e]-a;if(e===0){s[e]=n;continue}let r=t[e].along-t[e-1].along,c=s[e-1]-r*mN;s[e]=Math.max(Math.min(n,c),i[e]-o)}let c=[];for(let n=1;n<t.length;n++){let a=t[n-1],o=t[n],l=Math.max((i[n-1]+i[n])/2-(s[n-1]+s[n])/2,0);if(l<=.001)continue;let u=Math.min(r[n-1],r[n]),d=Math.max(e.depth*lN,e.cell*fN),f=Math.max(u-d*uN,u*dN,e.cell*.5);c.push({path:[[a.x,a.z],[o.x,o.z]],width:f*2,depth:l,taper:d})}return c}function gN(e,t){let n=e.length,r=Array(n).fill(1/0),i=Array(n).fill(1/0);if(n<3)return{left:r,right:i};let a=t=>e[t].along,o=Array(n).fill(0);for(let t=1;t<n-1;t++){let n=e[t-1],r=e[t],i=e[t+1],a=r.x-n.x,s=r.z-n.z,c=i.x-r.x,l=i.z-r.z,u=Math.hypot(a,s),d=Math.hypot(c,l);if(u<1e-4||d<1e-4)continue;let f=(a*l-s*c)/(u*d);o[t]=Math.asin(Math.max(-1,Math.min(1,f)))/((u+d)/2)}let s=(e,t)=>{let r=Array(n);for(let i=0;i<n;i++){let o=0,s=0;for(let n=i;n>=0&&a(i)-a(n)<=3;n--){let r=e(n);o=t===`max`?Math.max(o,r):o+r,s++}for(let r=i+1;r<n&&a(r)-a(i)<=3;r++){let n=e(r);o=t===`max`?Math.max(o,n):o+n,s++}r[i]=t===`max`?o:o/Math.max(s,1)}return r},c=s(e=>Math.max(o[e],0),`max`),l=s(e=>Math.max(-o[e],0),`max`),u=s(e=>c[e],`mean`),d=s(e=>l[e],`mean`),f=e=>e>1e-5?Math.min(1/e*jN,MN):MN;for(let e=0;e<n;e++)r[e]=f(Math.max(u[e],c[e]*.6)),i[e]=f(Math.max(d[e],l[e]*.6));for(let e=0;e<n;e++)t[e]=Math.min(t[e],Math.max(r[e],i[e]));return{left:r,right:i}}function _N(e,t=.6){let n=[];for(let r of e){let e=Math.max(r.wettedLeft??r.halfLeft,r.wettedRight??r.halfRight),i=Math.max(r.halfLeft,r.halfRight);e-i>t&&n.push({along:r.along,wettedHalfWidth:e,carriedHalfWidth:i})}return n}var vN=24,yN=3,bN=4,xN=.05,SN=12,CN=14,wN=3,TN=5,EN=.04,DN=2;function ON(e,t){return Math.max(e*wN,e+t*TN)}function kN(e,t){let n=e.map(e=>({x:e[0]??0,z:e[1]??0})).filter((e,t,n)=>t===0||Math.hypot(e.x-(n[t-1]?.x??0),e.z-(n[t-1]?.z??0))>1e-6);if(n.length<2||t<=0)return[];let r=[],i=0;for(let e=0;e<n.length-1;e++){let t=n[Math.max(0,e-1)],a=n[e],o=n[e+1],s=n[Math.min(n.length-1,e+2)];for(let e=0;e<vN;e++){let n=e/vN,c=WN(t.x,a.x,o.x,s.x,n),l=WN(t.z,a.z,o.z,s.z,n),u=r[r.length-1];u&&(i+=Math.hypot(c-u.x,l-u.z)),r.push({x:c,z:l,along:i})}}let a=n[n.length-1],o=r[r.length-1];o&&(i+=Math.hypot(a.x-o.x,a.z-o.z)),r.push({x:a.x,z:a.z,along:i});let s=i;if(s<1e-6)return[];let c=Math.max(1,Math.round(s/t)),l=s/c,u=[],d=0;for(let e=0;e<=c;e++){let t=Math.min(e*l,s);for(;d<r.length-2&&r[d+1].along<t;)d++;let n=r[d],i=r[Math.min(d+1,r.length-1)],a=i.along-n.along,o=a>1e-9?(t-n.along)/a:0;u.push({x:n.x+(i.x-n.x)*o,z:n.z+(i.z-n.z)*o,tx:1,tz:0,along:t})}for(let e=0;e<u.length;e++){let t=u[Math.max(0,e-1)],n=u[Math.min(u.length-1,e+1)],r=n.x-t.x,i=n.z-t.z,a=Math.hypot(r,i)||1,o=u[e];o.tx=r/a,o.tz=i/a}return u}function AN(e,t){if(e.length===0)return 0;if(e.length===1)return e[0];let n=Math.min(Math.max(t,0),1)*(e.length-1),r=Math.min(Math.floor(n),e.length-2),i=n-r,a=e[r];return a+(e[r+1]-a)*i}var jN=.85,MN=1e4,NN=1.2,PN=.35,FN=.4;function IN(e,t){let n=Math.min(...e);return Math.min(Math.max(Math.min(n*.45,t*.45),.3),2.5)}function LN(e){let t=kN(e.path,e.step);if(t.length===0)return[];let n=t[t.length-1].along||1,r=t.map(t=>Math.max(AN(e.widths,t.along/n),.05)/2),i=gN(t,r),a=t.map(t=>e.bedAt(t.x,t.z)),o=Array(a.length);for(let e=0;e<a.length;e++){let t=a[e];o[e]=e===0?t:Math.min(t,o[e-1])}let s=Math.max(.5,e.depth*1.5),c=o.map((e,t)=>{let n=0,r=0;for(let i=-3;i<=yN;i++){let a=o[Math.min(Math.max(t+i,0),o.length-1)];Math.abs(a-e)>s||(n+=a,r++)}return r>0?n/r:e}),l=Array(c.length);for(let e=0;e<c.length;e++){let t=c[e];l[e]=e===0?t:Math.min(t,l[e-1])}let u=e.fit===!0,d=Array(t.length),f=Array(t.length);for(let n=0;n<t.length;n++){let i=t[n],a=l[n]+e.depth;if(!u){f[n]=[1/0,1/0],d[n]=a;continue}let o=ON(r[n],e.depth),s=-i.tz,c=i.tx,p=-1/0,m=-1/0;for(let t=1;t<=CN;t++){let n=t/CN*o;p=Math.max(p,e.bedAt(i.x+s*n,i.z+c*n)),m=Math.max(m,e.bedAt(i.x-s*n,i.z-c*n))}f[n]=[p,m],d[n]=Math.min(a,p,m)}for(let e=0;e<d.length;e++){let t=d[e];u&&(t=Math.max(t,a[e]+EN)),e>0&&(t=Math.min(t,d[e-1]));let n=f[e];t=Math.min(t,Math.max(Math.min(n[0],n[1]),a[e]+EN)),d[e]=t}let p=t.map((t,n)=>{let i=r[n];if(!u)return[i,i];let a=ON(i,e.depth),o=d[n],s=-t.tz,c=t.tx,l=n=>{for(let r=1;r<=CN;r++){let i=r/CN*a;if(e.bedAt(t.x+s*i*n,t.z+c*i*n)>=o)return i}return-i};return[l(1),l(-1)]}),m=p.map(e=>[Math.abs(e[0]),Math.abs(e[1])]);for(let e of[0,1]){for(let n=1;n<m.length;n++){let r=Math.max(t[n].along-t[n-1].along,1e-4),i=m[n-1][e],a=m[n][e];m[n][e]=Math.min(a,i+r*NN)}for(let n=m.length-2;n>=0;n--){let r=Math.max(t[n+1].along-t[n].along,1e-4),i=m[n+1][e],a=m[n][e];m[n][e]=Math.min(a,i+r*NN)}}let h=m.map((e,t)=>{let n=0,r=0,i=0;for(let e=-2;e<=DN;e++){let a=m[Math.min(Math.max(t+e,0),m.length-1)];n+=Math.abs(a[0]),r+=Math.abs(a[1]),i++}let a=m[t];return[Math.min(n/i,Math.abs(a[0])),Math.min(r/i,Math.abs(a[1]))]}),g=t.map((e,t)=>[Math.min(h[t][0],i.left[t]),Math.min(h[t][1],i.right[t])]),_=g.reduce((e,t)=>Math.max(e,t[0],t[1]),0);for(let e=0;e<t.length;e++){let n=g[e];for(let r=e+1;r<t.length;r++){let i=g[r],a=Math.max(n[0],n[1],i[0],i[1]);if(t[r].along-t[e].along<a*3)continue;let o=Math.hypot(t[e].x-t[r].x,t[e].z-t[r].z);if(!(o>_*2+PN))for(let e of[0,1]){if(o>=n[e]+i[e]+PN)continue;let t=Math.max((o-PN)/2,FN);n[e]>t&&(n[e]=t),i[e]>t&&(i[e]=t)}}}for(let e of[0,1]){for(let n=1;n<g.length;n++){let r=Math.max(t[n].along-t[n-1].along,1e-4),i=g[n-1][e],a=g[n][e];g[n][e]=Math.min(a,i+r*NN)}for(let n=g.length-2;n>=0;n--){let r=Math.max(t[n+1].along-t[n].along,1e-4),i=g[n+1][e],a=g[n][e];g[n][e]=Math.min(a,i+r*NN)}}let v=r.reduce((e,t)=>e+t,0)/r.length||1;return t.map((n,i)=>{let a=d[i],o=Math.max(0,i-1),s=Math.min(t.length-1,i+1),c=t[s].along-t[o].along,l=(d[o]-d[s])/(c||1),u=Math.max(0,l),f=r[i],m=h[i],_=Math.min(Math.max(e.flowSpeed*Math.sqrt(v/f)*(1+bN*u),xN),SN),y=p[i];return{...n,halfWidth:f,halfLeft:Math.max(g[i][0],.05),halfRight:Math.max(g[i][1],.05),wettedLeft:Math.max(m[0],.05),wettedRight:Math.max(m[1],.05),spillLeft:y[0]<0,spillRight:y[1]<0,surfaceY:a,slope:u,speed:_}})}function RN(e,t){let n=Math.max(1,Math.round(t.acrossSegments)),r=n+1,i=e.length*r,a=new Float32Array(i*3),o=new Float32Array(i*3),s=new Float32Array(i*2),c=new Float32Array(i*2),l=new Float32Array(i*4),u=Math.max(0,e.length-1)*n,d=new Uint32Array(u*6);for(let i=0;i<e.length;i++){let u=e[i],d=Math.max(u.surfaceY-zN(t,u.x,u.z),EN),f=-u.tz,p=u.tx,m=Math.hypot(u.slope,1),h=u.tx*u.slope/m,g=1/m,_=u.tz*u.slope/m;for(let e=0;e<=n;e++){let m=e/n*2-1,v=m*(m<0?u.halfRight:u.halfLeft)*t.bankOvershoot,y=u.x+f*v,b=u.z+p*v,x=i*r+e,S=zN(t,y,b),C=(m<0?u.spillRight:u.spillLeft)?d+(EN-d)*Math.abs(m):d,w=Math.min(u.surfaceY,S+C);a[x*3]=y,a[x*3+1]=w,a[x*3+2]=b,o[x*3]=h,o[x*3+1]=g,o[x*3+2]=_,s[x*2]=u.along,s[x*2+1]=v,c[x*2]=u.tx,c[x*2+1]=u.tz,l[x*4]=u.speed,l[x*4+1]=Math.max(0,w-S),l[x*4+2]=u.slope,l[x*4+3]=m*t.bankOvershoot}}let f=0;for(let t=0;t+1<e.length;t++)for(let e=0;e<n;e++){let n=t*r+e,i=n+1,a=n+r,o=a+1;d[f++]=n,d[f++]=i,d[f++]=a,d[f++]=i,d[f++]=o,d[f++]=a}return{positions:a,normals:o,uvs:s,flow:c,river:l,indices:d}}function zN(e,t,n){let r=e.bedBlur??0;return r<=0?e.bedAt(t,n):(e.bedAt(t,n)+e.bedAt(t+r,n)+e.bedAt(t-r,n)+e.bedAt(t,n+r)+e.bedAt(t,n-r))/5}function BN(e,t,n){if(e.length===0)return null;let r=0,i=1/0,a=Math.max(1,Math.floor(Math.sqrt(e.length)/2));if(a>1){for(let o=0;o<e.length;o+=a){let a=e[o],s=(a.x-t)**2+(a.z-n)**2;s<i&&(i=s,r=o)}let o=Math.max(0,r-a),s=Math.min(e.length-1,r+a);i=1/0;for(let a=o;a<=s;a++){let o=e[a],s=(o.x-t)**2+(o.z-n)**2;s<i&&(i=s,r=a)}return VN(e,r,t,n)}for(let a=0;a<e.length;a++){let o=e[a],s=(o.x-t)**2+(o.z-n)**2;s<i&&(i=s,r=a)}if(e.length===1){let r=e[0];return HN(r,r,0,t,n,!1)}return VN(e,r,t,n)}function VN(e,t,n,r){let i=null,a=1/0;for(let o of[t-1,t]){if(o<0||o+1>=e.length)continue;let t=e[o],s=e[o+1],c=s.x-t.x,l=s.z-t.z,u=c*c+l*l,d=u>1e-9?((n-t.x)*c+(r-t.z)*l)/u:0,f=Math.min(Math.max(d,0),1),p=o===0&&d<0||o+2===e.length&&d>1,m=t.x+c*f,h=t.z+l*f,g=(m-n)**2+(h-r)**2;g<a&&(a=g,i=HN(t,s,f,n,r,p))}return i}function HN(e,t,n,r,i,a){let o=e.x+(t.x-e.x)*n,s=e.z+(t.z-e.z)*n,c=e.tx+(t.tx-e.tx)*n,l=e.tz+(t.tz-e.tz)*n,u=Math.hypot(c,l)||1;c/=u,l/=u;let d=(r-o)*-l+(i-s)*c,f=(e,t)=>e+(t-e)*n,p=d<0?f(e.halfRight,t.halfRight):f(e.halfLeft,t.halfLeft),m=d/(p||1);return{inside:!a&&Math.abs(m)<=1,across:m,along:e.along+(t.along-e.along)*n,surfaceY:e.surfaceY+(t.surfaceY-e.surfaceY)*n,dirX:c,dirZ:l,speed:e.speed+(t.speed-e.speed)*n,halfWidth:p}}function UN(e,t={}){let n=t.minGrade??.45,r=t.minDrop??1.2,i=[],a=-1;for(let t=0;t<=e.length;t++){let o=t<e.length&&e[t].slope>=n;if(o&&a<0&&(a=t),o||a<0)continue;let s=e[Math.max(0,a-1)],c=e[Math.min(e.length-1,t)],l=s.surfaceY-c.surfaceY;l>=r&&i.push({x:c.x,z:c.z,lipX:s.x,lipZ:s.z,lipHalfWidth:Math.min((s.halfLeft+s.halfRight)/2,s.halfWidth),lipDirX:s.tx,lipDirZ:s.tz,lipSpeed:s.speed,topY:s.surfaceY,baseY:c.surfaceY,drop:l,halfWidth:(c.halfLeft+c.halfRight)/2,dirX:c.tx,dirZ:c.tz,speed:c.speed}),a=-1}return i}function WN(e,t,n,r,i){let a=i*i,o=a*i;return .5*(2*t+(-e+n)*i+(2*e-5*t+4*n-r)*a+(-e+3*t-3*n+r)*o)}var GN=`
|
|
7516
7516
|
float riverHash(vec2 p) {
|
|
7517
7517
|
p = fract(p * vec2(127.31, 311.7));
|
|
7518
7518
|
p += dot(p, p + 34.23);
|
|
@@ -7910,7 +7910,7 @@ void main() {
|
|
|
7910
7910
|
#include <colorspace_fragment>
|
|
7911
7911
|
#include <fog_fragment>
|
|
7912
7912
|
}
|
|
7913
|
-
`,JN=1.25,YN=4,XN=12,ZN=1.5,QN=.35,$N=1.2,eP=8,tP=.5,nP=.35,rP=42,iP=26,aP=6,oP=.05,sP=1.5,cP={shallow:`#74b2a2`,deep:`#123f4b`,sky:`#8ab6d8`,horizon:`#9fb6c2`,bank:`#465447`},lP=`#e9f2ef`,uP=new W,dP={rippleScale:.85,rippleStrength:.09,flowRate:.42,fresnelScale:.95,standingAmp:.11,glideAmp:.025},fP=class e extends Z_{static typeName=`River3D`;static props={path:{default:[]},width:{default:6},widths:{default:[]},depth:{default:.8},flowSpeed:{default:1.6},colors:{default:{}},absorption:{default:.5},opacity:{default:.85},foam:{default:1},ripples:{default:1},sunDirection:{default:[.5,.8,.3]},sunColor:{default:`#fff6e0`},sunIntensity:{default:1},terrain:{default:``,nodePath:!0},carve:{default:!0},flowForce:{default:1},spray:{default:1}};path=[];width=6;widths=[];depth=.8;flowSpeed=1.6;colors={};absorption=.5;opacity=.85;foam=1;ripples=1;sunDirection=[.5,.8,.3];sunColor=`#fff6e0`;sunIntensity=1;terrain=``;carve=!0;flowForce=1;spray=1;renderOrder=1;time=0;rings=[];falls=[];sprayKey=``;courseKey=``;bedAt=null;fitted=!1;bounds=null;boundsKey=``;rocks=[];rockScanAt=-1;world=[0,0,0];_bodies=[];static validateJson(e){rv(e,`the flow query and its collider both`);let t=e;if(!Array.isArray(t.path))throw new L(`BAD_FORMAT`,`River3D '${e.name}' path must be an array of [x, z] points, got ${JSON.stringify(t.path)}.`,{prop:`path`});if(t.path.length>0&&t.path.length<2)throw new L(`BAD_FORMAT`,`River3D '${e.name}' path needs at least 2 points (source → mouth), got ${t.path.length}.`,{prop:`path`});if(t.path.forEach((t,n)=>{if(!Array.isArray(t)||t.length<2||!Number.isFinite(t[0])||!Number.isFinite(t[1]))throw new L(`BAD_FORMAT`,`River3D '${e.name}' path[${n}] must be [x, z] with finite numbers, got ${JSON.stringify(t)}.`,{prop:`path`})}),!(typeof t.width==`number`&&t.width>0))throw new L(`BAD_FORMAT`,`River3D '${e.name}' width must be a positive number of meters, got ${JSON.stringify(t.width)}.`,{prop:`width`});if(!Array.isArray(t.widths)||t.widths.some(e=>!(typeof e==`number`&&e>0)))throw new L(`BAD_FORMAT`,`River3D '${e.name}' widths must be a list of positive meters (source→mouth), got ${JSON.stringify(t.widths)}.`,{prop:`widths`});if(!(t.depth>0))throw new L(`BAD_FORMAT`,`River3D '${e.name}' depth must be > 0 meters, got ${JSON.stringify(t.depth)}.`,{prop:`depth`});if(!(t.flowSpeed>=0))throw new L(`BAD_FORMAT`,`River3D '${e.name}' flowSpeed must be >= 0 m/s, got ${JSON.stringify(t.flowSpeed)}.`,{prop:`flowSpeed`});for(let n of[`absorption`,`foam`,`ripples`,`flowForce`,`spray`,`sunIntensity`]){let r=t[n];if(!(typeof r==`number`&&r>=0))throw new L(`BAD_FORMAT`,`River3D '${e.name}' ${n} must be a number >= 0, got ${JSON.stringify(r)}.`,{prop:n})}if(!(t.opacity>=0&&t.opacity<=1))throw new L(`BAD_FORMAT`,`River3D '${e.name}' opacity must be within [0, 1], got ${JSON.stringify(t.opacity)}.`,{prop:`opacity`});let n=t.colors;if(typeof n!=`object`||!n||Array.isArray(n))throw new L(`BAD_FORMAT`,`River3D '${e.name}' colors must be an object of { shallow, deep, sky, horizon, bank } hex strings.`,{prop:`colors`});for(let t of Object.keys(n)){if(!(t in cP))throw new L(`BAD_FORMAT`,`River3D '${e.name}' colors has unknown key '${t}' — expected shallow, deep, sky, horizon or bank.`,{prop:`colors`});if(typeof n[t]!=`string`)throw new L(`BAD_FORMAT`,`River3D '${e.name}' colors.${t} must be a hex string, got ${JSON.stringify(n[t])}.`,{prop:`colors`})}}_createObject3D(){return new iu(new Y,this.buildMaterial())}onReady(){this.ensureCourse()}onExitTree(){qA(this,this.terrain)?._setExternalChannel(this,null)}update(e){this.time+=e,this.ensureCourse(),this.syncSpray(),this.flowForce>0&&this.rings.length>1&&this.sweepBodies(e)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();this.rebuildIfNeeded(e),this.syncUniforms(e)}_onRender3D(e){if(this.rings.length===0)return;(this.rockScanAt<0||this.time-this.rockScanAt>tP)&&(this.rockScanAt=this.time,this.scanRocks());let t=this._ensureObject3D().material.uniforms;this.syncRocks(t,e.camera.getWorldPosition(uP))}_waterYAt(e,t){if(this.rings.length===0)return null;let[n,r,i]=this.world,a=e-n,o=t-i,s=this.ringBounds();if(a<s.minX||a>s.maxX||o<s.minZ||o>s.maxZ)return null;let c=BN(this.rings,a,o);return c?.inside?c.surfaceY+r:null}ringBounds(){if(this.boundsKey===this.courseKey&&this.bounds)return this.bounds;let e=1/0,t=-1/0,n=1/0,r=-1/0,i=0;for(let a of this.rings)a.x<e&&(e=a.x),a.x>t&&(t=a.x),a.z<n&&(n=a.z),a.z>r&&(r=a.z),i=Math.max(i,a.halfLeft,a.halfRight);return this.bounds={minX:e-i,maxX:t+i,minZ:n-i,maxZ:r+i},this.boundsKey=this.courseKey,this.bounds}sampleAt(e,t){if(this.ensureCourse(),this.rings.length===0)return null;let[n,r,i]=this.world,a=BN(this.rings,e-n,t-i);return a?{...a,surfaceY:a.surfaceY+r}:null}fallsAt(){this.ensureCourse();let[e,t,n]=this.world;return this.falls.map(r=>({...r,worldX:r.x+e,worldY:r.baseY+t,worldZ:r.z+n}))}_rings(){return this.rings}_applySunDirection(t){let n=e.props.sunDirection?.default;this.sunDirection.every((e,t)=>e===n[t])&&(this._ensureObject3D().material.uniforms?.uSunDirection?.value)?.set(t[0],t[1],t[2])}free(){let e=this._ensureObject3D();e.geometry?.dispose(),e.material?.dispose?.(),super.free()}widthProfile(){return this.widths.length>0?this.widths:[this.width]}applyCarve(e){if(!e)return;if(!this.carve||this.path.length<2){e._setExternalChannel(this,null);return}e._setExternalChannel(this,null);let[t,,n]=KA(this),[r,,i]=KA(e),a=e._heightmap();e._setExternalChannel(this,hN({path:this.path.map(e=>[(e[0]??0)+t-r,(e[1]??0)+n-i]),widths:this.widthProfile(),depth:this.depth,cell:(e.size[0]??1)/Math.max(1,a.segsX),groundAt:(e,t)=>a.heightAt(e,t)}))}resolveTerrain(){let e=qA(this,this.terrain);if(!e&&this.terrain!==``)throw new L(`NODE_NOT_FOUND`,`River3D '${this.name}' terrain '${this.terrain}' is not a Terrain3D in the tree.`,{prop:`terrain`});return e}ensureCourse(){let e=this.resolveTerrain(),t=KA(this),n=JSON.stringify([this.path,this.width,this.widths,this.depth,this.flowSpeed,this.carve,e?e.name:``,t]);if(n===this.courseKey)return!1;if(this.courseKey=n,this.world=t,this.bedAt=null,this.applyCarve(e),this.path.length<2)return this.rings=[],this.falls=[],!0;let[r,i,a]=t;this.bedAt=e?(t,n)=>e.heightAt(t+r,n+a)-i:()=>-this.depth,this.fitted=e!==null;let o=this.widthProfile();return this.rings=LN({path:this.path,widths:o,depth:this.depth,flowSpeed:this.flowSpeed,step:IN(o,this.depth),bedAt:this.bedAt,fit:this.fitted}),this.falls=UN(this.rings),this.warnUncoveredWater(),!0}warnUncoveredWater(){if(this.warnedCoverage)return;let e=_N(this.rings);if(e.length*3<this.rings.length)return;this.warnedCoverage=!0;let t=e.reduce((e,t)=>t.wettedHalfWidth-t.carriedHalfWidth>e.wettedHalfWidth-e.carriedHalfWidth?t:e);this.diagnose(`warn`,`[incanto] River3D '${this.name}': the course is too tight for the water it holds — ${e.length} of ${this.rings.length} stations leave bare channel beside the ribbon (worst at ${t.along.toFixed(0)} m: ground wet to ${t.wettedHalfWidth.toFixed(1)} m from the centre, a bend that can only carry ${t.carriedHalfWidth.toFixed(1)} m). Fix by EASING THE BENDS in \`path\` (fewer, straighter points), NARROWING \`widths\` there, or placing standing water (a Water3D) if that reach is really a pool.`)}warnedCoverage=!1;rebuildIfNeeded(e){if(!this.ensureCourse()&&e.geometry.getAttribute(`position`))return;if(this.rings.length===0||!this.bedAt){e.geometry.dispose();let t=new Y;t.setAttribute(`position`,new J(new Float32Array,3)),e.geometry=t;return}let t=this.widthProfile(),n=Math.min(...t),r=Math.max(...t),i=RN(this.rings,{acrossSegments:Math.min(XN,Math.max(YN,Math.round(r/ZN))),bankOvershoot:this.fitted?1:JN,bedBlur:Math.min(n/2*QN,$N),bedAt:this.bedAt}),a=new Y;a.setAttribute(`position`,new J(i.positions,3)),a.setAttribute(`normal`,new J(i.normals,3)),a.setAttribute(`aFlowUv`,new J(i.uvs,2)),a.setAttribute(`aFlow`,new J(i.flow,2)),a.setAttribute(`aRiver`,new J(i.river,4)),a.setIndex(new J(i.indices,1)),a.computeBoundingSphere(),e.geometry.dispose(),e.geometry=a}buildMaterial(){return new Dd({vertexShader:KN,fragmentShader:qN,fog:!0,uniforms:{fogColor:{value:new q(`#ffffff`)},fogNear:{value:1},fogFar:{value:1e3},fogDensity:{value:25e-5},uTime:{value:0},uShallowColor:{value:new q(cP.shallow)},uDeepColor:{value:new q(cP.deep)},uFoamColor:{value:new q(lP)},uSkyColor:{value:new q(cP.sky)},uHorizonColor:{value:new q(cP.horizon)},uBankColor:{value:new q(cP.bank)},uSunDirection:{value:new W(.5,.8,.3)},uSunColor:{value:new q(this.sunColor)},uSunIntensity:{value:this.sunIntensity},uMaxDepth:{value:this.depth},uAbsorption:{value:this.absorption},uOpacity:{value:this.opacity},uFoam:{value:this.foam},uRippleScale:{value:dP.rippleScale},uRippleStrength:{value:dP.rippleStrength*this.ripples},uFlowRate:{value:dP.flowRate},uSparkle:{value:this.ripples},uRockCount:{value:0},uRocks:{value:Array.from({length:eP},()=>new Js)},uFresnelScale:{value:dP.fresnelScale},uStandingAmp:{value:dP.standingAmp},uGlideAmp:{value:dP.glideAmp}},transparent:!0,depthTest:!0,depthWrite:!1,side:2})}scanRocks(){let e=[],[t,n,r]=this.world,i=(i,a,o,s,c)=>{if(o<=.02)return;let l=BN(this.rings,i-t,a-r);if(!l?.inside)return;let u=l.surfaceY+n;if(s>u||c<u-this.depth)return;let d=(c-u)/Math.max(this.depth*nP,.02),f=Math.min(Math.max(d+1,0),1);e.push({x:i,z:a,radius:o,breaks:f})},a=this;for(;a.parent;)a=a.parent;let o=e=>{if(e instanceof nv||e instanceof tv){let t=e.collider,n=o_(t),[r,a,o]=KA(e);i(r,o,t?.shape===`box`?Math.max(t.size?.[0]??.4,t.size?.[2]??.4)/2:t?.radius??.35,a-n,a+n)}else if(e instanceof AD){let[t,n,r]=e.size,[a,o,s]=KA(e);for(let c of e.transforms){let e=c[4]??1,l=a+(c[0]??0),u=o+(c[1]??0),d=s+(c[2]??0),f=(n??1)*e/2;i(l,d,Math.max(t,r)*e/2,u-f,u+f)}}else if(e instanceof ED){let[t,n,r]=e.size,[a,o,s]=KA(e),c=(n??1)/2;i(a,s,Math.max(t,r)/2,o-c,o+c)}for(let t of e.children)o(t)};o(a),this.rocks=e}syncRocks(e,t){let n=e.uRocks?.value,r=e.uRockCount;if(!n||!r)return;if(this.rocks.length===0){r.value=0;return}let i=[...this.rocks].map(e=>({r:e,d:(e.x-t.x)**2+(e.z-t.z)**2})).sort((e,t)=>e.d-t.d).slice(0,eP),a=0;for(let{r:e,d:t}of i){let r=Math.max(e.radius*rP,iP),i=Math.min(Math.sqrt(t)/r,1),o=Math.min(Math.max((i-.6)/.4,0),1),s=1-o*o*(3-2*o);s<=.01||(n[a]?.set(e.x,e.z,e.radius,e.breaks*s),a++)}r.value=a}syncUniforms(e){let t=e.material.uniforms,n=(e,n)=>{let r=t[e];r&&(r.value=n)},r=(e,n)=>{(t[e]?.value)?.set(n)},i=this.colors;n(`uTime`,this.time),r(`uShallowColor`,i.shallow??cP.shallow),r(`uDeepColor`,i.deep??cP.deep),r(`uSkyColor`,i.sky??cP.sky),r(`uHorizonColor`,i.horizon??cP.horizon),r(`uBankColor`,i.bank??cP.bank),r(`uSunColor`,this.sunColor),(t.uSunDirection?.value)?.set(this.sunDirection[0]??.5,this.sunDirection[1]??.8,this.sunDirection[2]??.3),n(`uSunIntensity`,this.sunIntensity),n(`uMaxDepth`,this.depth),n(`uAbsorption`,this.absorption),n(`uOpacity`,this.opacity),n(`uFoam`,this.foam),n(`uRippleStrength`,dP.rippleStrength*this.ripples),n(`uSparkle`,this.ripples)}syncSpray(){let e=this.spray>0?`${this.spray}|${JSON.stringify(this.falls)}`:``;if(e!==this.sprayKey){this.sprayKey=e;for(let e of[...this.children])e.name.startsWith(`__spray`)&&e.free();this.spray<=0||this.falls.forEach((e,t)=>{let n=new nN(`__spray${t}`);n.position=[e.x+e.dirX*.6,e.baseY+.15,e.z+e.dirZ*.6];let r=Math.min(1.6,.4+e.drop*.12)*this.spray;n.rate=Math.round(Math.min(22,5+e.drop*1.6)*this.spray),n.maxParticles=160,n.lifetime=[1,2.1],n.speed=[45*r,130*r],n.directionDeg=-90,n.spreadDeg=52,n.gravity=[0,-240,0],n.drag=1.2,n.sizeStart=7*r,n.sizeEnd=30*r,n.colorStart=`#ffffff`,n.colorEnd=`#dfe9ec`,n.alphaStart=.085,n.alphaEnd=0,n.blend=`normal`,n.depthTest=!0,this.addChild(n)})}}sweepBodies(e){let t=this;for(;t.parent;)t=t.parent;let n=this._bodies;if(n.length=0,pP(t,n),n.length===0)return;let[r,i,a]=this.world;for(let t of n){let n=KA(t),o=BN(this.rings,n[0]-r,n[2]-a);if(!o?.inside)continue;let s=o.surfaceY+i,c=n[1]-o_(t.collider);if(c>s+oP||c<s-this.depth-sP)continue;let l=mP(t);if(!l)continue;let u=Math.min(1,this.flowForce*aP*e),d=(o.dirX*o.speed-(l[0]??0))*u,f=(o.dirZ*o.speed-(l[2]??0))*u;if(t instanceof tv){let e=t.mass||1;t.applyImpulse([d*e,0,f*e])}else l[0]=(l[0]??0)+d,l[2]=(l[2]??0)+f}}};function pP(e,t){(e instanceof nv||e instanceof tv)&&t.push(e);for(let n of e.children)pP(n,t)}function mP(e){return e.velocity??e.linearVelocity}var hP=128,gP=class extends Z_{static typeName=`Trail3D`;static props={width:{default:.3},color:{default:`#ffffff`},opacity:{default:.8},seconds:{default:.6},emitting:{default:!0},additive:{default:!1},minDistance:{default:.05}};width=.3;color=`#ffffff`;opacity=.8;seconds=.6;emitting=!0;additive=!1;minDistance=.05;points=[];clock=0;mesh=null;lastColor=``;_createObject3D(){let e=new Ec,t=new Y;t.setAttribute(`position`,new J(new Float32Array(hP*2*3),3));let n=new Kl({color:this.color,transparent:!0,opacity:this.opacity,side:2,depthWrite:!1,blending:this.additive?2:1});return this.mesh=new iu(t,n),this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrixWorld.identity(),this.mesh.updateMatrixWorld=()=>{},e.add(this.mesh),e}wasEmitting=!1;update(e){if(this.clock+=e,this.emitting!==this.wasEmitting){this.wasEmitting=this.emitting;let e=this.tree?.engine;this.emitting&&e&&e.effects.record({kind:`trail`,name:this.color,from:this.getPath(),amount:this.seconds,at:e.time})}for(;this.points.length>0&&this.clock-this.points[0].t>this.seconds;)this.points.shift()}_onRender3D(e){let t=this._ensureObject3D();if(this.emitting){t.getWorldPosition(_P);let e=this.points[this.points.length-1];(!e||(e.x-_P.x)**2+(e.y-_P.y)**2+(e.z-_P.z)**2>this.minDistance*this.minDistance)&&(this.points.push({x:_P.x,y:_P.y,z:_P.z,t:this.clock}),this.points.length>hP&&this.points.shift())}let n=this.mesh;if(!n)return;n.matrixWorld.identity();let r=n.material;this.color!==this.lastColor&&(this.lastColor=this.color,r.color=new q(this.color)),r.opacity=this.opacity;let i=this.points.length,a=n.geometry,o=a.getAttribute(`position`);if(i<2){a.setDrawRange(0,0);return}for(let t=0;t<i;t++){let n=this.points[t],r=this.points[Math.min(t+1,i-1)]??n;vP.set(r.x-n.x,r.y-n.y,r.z-n.z),vP.lengthSq()<1e-8&&vP.set(0,1,0),yP.set(e.camera.position.x-n.x,e.camera.position.y-n.y,e.camera.position.z-n.z),bP.crossVectors(vP,yP).normalize();let a=(this.clock-n.t)/this.seconds,s=this.width/2*Math.max(0,1-a);o.setXYZ(t*2,n.x+bP.x*s,n.y+bP.y*s,n.z+bP.z*s),o.setXYZ(t*2+1,n.x-bP.x*s,n.y-bP.y*s,n.z-bP.z*s)}if(o.needsUpdate=!0,!a.index||a.index.count<(hP-1)*6){let e=[];for(let t=0;t<hP-1;t++){let n=t*2;e.push(n,n+1,n+2,n+1,n+3,n+2)}a.setIndex(e)}a.setDrawRange(0,(i-1)*6)}get pointCount(){return this.points.length}free(){let e=this._builtObject3D;e&&e.traverse(e=>{let t=e;t.geometry?.dispose();let n=t.material,r=Array.isArray(n)?n:n?[n]:[];for(let e of r)e.dispose?.()}),super.free()}},_P=new W,vP=new W,yP=new W,bP=new W;function xP(e){let{branch:t,leaves:n,type:r}=e,i=0,a=0,o=[{level:0,sections:t.sections[0],segments:t.segments[0]}];for(;o.length>0;){let e=o.shift();if(i+=e.sections*e.segments*2,e.level>=t.levels){a+=n.count===0?0:n.count+ +(r===`deciduous`);continue}r===`deciduous`&&o.push({level:e.level+1,sections:e.sections,segments:e.segments});let s=t.children[e.level]??0;for(let n=0;n<s;n++)o.push({level:e.level+1,sections:t.sections[e.level+1]??1,segments:t.segments[e.level+1]??3})}let s=n.billboard===`double`?2:1,c=a*s*2;return{branches:i,leaves:c,total:i+c}}var SP={ash:{type:`deciduous`,branch:{levels:3,angle:[0,48,75,60],children:[7,4,3,0],force:{direction:{x:0,y:1,z:0},strength:-.06},gnarliness:[.03,.25,.2,.09],length:[43.47,27.14,9.51,4.6],radius:[2,.63,.76,.7],sections:[12,8,6,4],segments:[12,6,4,3],start:[0,.23,.33,0],taper:[.7,.7,.7,.7],twist:[.09,-.07,0,0]},leaves:{style:`ash`,billboard:`double`,angle:55,count:16,start:0,size:2.67,sizeVariance:.72,alphaTest:.5}},aspen:{type:`deciduous`,branch:{levels:2,angle:[0,75,32,7],children:[10,3,3,0],force:{direction:{x:0,y:1,z:0},strength:.0148},gnarliness:[.05,.12,.12,.02],length:[50,6.07,11.19,1],radius:[.72,.41,.7,.7],sections:[12,10,8,6],segments:[8,6,4,3],start:[0,.59,.35,0],taper:[.37,.13,.7,.7],twist:[0,0,0,0]},leaves:{style:`aspen`,billboard:`double`,angle:30,count:11,start:.124,size:2.5,sizeVariance:.7,alphaTest:.5}},oak:{type:`deciduous`,branch:{levels:3,angle:[0,54,58,32],children:[6,4,3,0],force:{direction:{x:0,y:1,z:0},strength:-.01},gnarliness:[0,-.1,-.15,.09],length:[37.24,11.08,12.39,7.16],radius:[1.41,.9,.69,1.19],sections:[8,6,3,1],segments:[7,5,3,3],start:[0,.49,.06,.12],taper:[.73,.42,.69,.75],twist:[-.23,.42,0,0]},leaves:{style:`oak`,billboard:`double`,angle:42,count:18,start:.16,size:2.5,sizeVariance:.7,alphaTest:.5}},pine:{type:`evergreen`,branch:{levels:1,angle:[0,110,16,60],children:[82,3,5,0],force:{direction:{x:0,y:1,z:0},strength:-.003},gnarliness:[.05,.08,0,0],length:[50,23.87,14.08,1],radius:[1.05,.36,.7,.7],sections:[12,10,8,6],segments:[8,6,4,3],start:[0,.27,.14,.3],taper:[.7,.7,.7,.7],twist:[0,0,0,0]},leaves:{style:`pine`,billboard:`double`,angle:39,count:30,start:.09,size:1.435,sizeVariance:.201,alphaTest:.3}},bush:{type:`deciduous`,branch:{levels:3,angle:[0,21.5,62.6,60],children:[7,3,2,0],force:{direction:{x:0,y:1,z:0},strength:-.02},gnarliness:[.11,.09,.05,.09],length:[.1,15.3,5.59,4.6],radius:[.58,.95,.76,.7],sections:[6,6,4,3],segments:[4,4,4,3],start:[0,.53,.33,0],taper:[.7,.7,.7,.7],twist:[.3,-.07,0,0]},leaves:{style:`ash`,billboard:`double`,angle:55,count:8,start:0,size:2.45,sizeVariance:.717,alphaTest:.5}},"ash-forest":{type:`deciduous`,branch:{levels:2,angle:[0,48,75,60],children:[5,3,0,0],force:{direction:{x:0,y:1,z:0},strength:-.06},gnarliness:[.03,.25,.2,.09],length:[43.47,27.14,9.51,4.6],radius:[2,.63,.76,.7],sections:[6,5,4,4],segments:[6,4,3,3],start:[0,.3,.33,0],taper:[.7,.7,.7,.7],twist:[.09,-.07,0,0]},leaves:{style:`ash`,billboard:`double`,angle:55,count:15,start:0,size:3,sizeVariance:.6,alphaTest:.5}},"oak-forest":{type:`deciduous`,branch:{levels:2,angle:[0,54,58,32],children:[5,3,0,0],force:{direction:{x:0,y:1,z:0},strength:-.01},gnarliness:[0,-.1,-.15,.09],length:[37.24,11.08,12.39,7.16],radius:[1.41,.9,.69,1.19],sections:[6,4,3,1],segments:[6,4,3,3],start:[0,.49,.06,.12],taper:[.73,.42,.69,.75],twist:[-.23,.42,0,0]},leaves:{style:`oak`,billboard:`double`,angle:42,count:16,start:.1,size:2.9,sizeVariance:.7,alphaTest:.5}},"pine-forest":{type:`evergreen`,branch:{levels:1,angle:[0,110,16,60],children:[44,3,5,0],force:{direction:{x:0,y:1,z:0},strength:-.005},gnarliness:[.07,.09,0,0],length:[50,23.87,14.08,1],radius:[1.05,.36,.7,.7],sections:[6,5,8,6],segments:[6,3,4,3],start:[0,.27,.14,.3],taper:[.7,.7,.7,.7],twist:[0,0,0,0]},leaves:{style:`pine`,billboard:`double`,angle:39,count:9,start:.09,size:1.8,sizeVariance:.201,alphaTest:.3}},"bush-forest":{type:`deciduous`,branch:{levels:2,angle:[0,21.5,62.6,60],children:[6,3,0,0],force:{direction:{x:0,y:1,z:0},strength:-.02},gnarliness:[.11,.09,.05,.09],length:[.1,15.3,5.59,4.6],radius:[.58,.95,.76,.7],sections:[5,4,3,3],segments:[4,3,3,3],start:[0,.53,.33,0],taper:[.7,.7,.7,.7],twist:[.3,-.07,0,0]},leaves:{style:`ash`,billboard:`double`,angle:55,count:10,start:0,size:3.2,sizeVariance:.6,alphaTest:.5}}},CP=[`ash`,`aspen`,`oak`,`pine`,`bush`,`ash-forest`,`oak-forest`,`pine-forest`,`bush-forest`];function wP(e){let t=SP[e];if(!t)throw new L(`BAD_FORMAT`,`Unknown eztree preset '${e}' — must be one of [${CP.join(`, `)}].`,{prop:`preset`,validOptions:CP});return structuredClone(t)}var TP={ash:{texture:`oak`,tint:`#cecbbe`,repeat:[.5,1/5]},aspen:{texture:`birch`,tint:`#ffffff`,repeat:[1,1]},oak:{texture:`oak`,tint:`#fff3d1`,repeat:[1,1/10]},pine:{texture:`pine`,tint:`#ffffff`,repeat:[1,1]},bush:{texture:`oak`,tint:`#cecbbe`,repeat:[.5,1/5]}};function EP(e){if(!CP.includes(e))throw new L(`BAD_FORMAT`,`Unknown eztree preset '${e}' — must be one of [${CP.join(`, `)}].`,{prop:`preset`,validOptions:CP});return structuredClone(TP[e.replace(/-forest$/,``)])}var DP=.45,OP=.45,kP=.55,AP=.15,jP=.07,MP=.035;function NP(e,t){let n=Math.imul(e+1,374761393)+Math.imul(t+1,668265263)>>>0;return n=Math.imul(n^n>>>13,1274126177)>>>0,((n^n>>>16)>>>0)/4294967296}function PP(e,t,n){let r=e.length/3,i=new Float32Array(e.length),a=new Float32Array(e.length),o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let t=0;t<r;t++){let n=e[t*3],r=e[t*3+1],i=e[t*3+2];n<o&&(o=n),n>l&&(l=n),r<s&&(s=r),r>u&&(u=r),i<c&&(c=i),i>d&&(d=i)}let f=(o+l)/2,p=(s+u)/2,m=(c+d)/2,h=Math.max((l-o)/2,.001),g=Math.max((u-s)/2,.001),_=Math.max((d-c)/2,.001),v=new Map;for(let n=0;n<r;n++){let r=t[n],i=v.get(r);i||(i={x:0,y:0,z:0,n:0},v.set(r,i)),i.x+=e[n*3],i.y+=e[n*3+1],i.z+=e[n*3+2],i.n++}for(let e of v.values())e.x/=e.n,e.y/=e.n,e.z/=e.n;for(let o=0;o<r;o++){let r=e[o*3],c=e[o*3+1],l=e[o*3+2],d=(r-f)/h,y=(c-p)/g,b=(l-m)/_,x,S,C,w;if(n===`evergreen`){let e=Math.hypot(r-f,l-m);if(e<1e-6)x=0,S=1,C=0;else{let t=1/Math.hypot(1,OP);x=(r-f)/e*t,S=OP*t,C=(l-m)/e*t}let t=(c-s)/Math.max(u-s,.001),n=Math.max(AP,1-t);w=Math.min(1,Math.hypot(d,b)/n)}else{let e=d/h,t=y/g,n=b/_,r=Math.hypot(e,t,n);r<1e-6?(x=0,S=1,C=0):(x=e/r,S=t/r,C=n/r),w=Math.min(1,Math.hypot(d,y,b))}let T=v.get(t[o]);if(T){let e=r-T.x,t=c-T.y,n=l-T.z,i=Math.hypot(e,t,n);if(i>1e-6){x=x*(1-kP)+e/i*kP,S=S*(1-kP)+t/i*kP,C=C*(1-kP)+n/i*kP;let r=Math.hypot(x,S,C);r>1e-6?(x/=r,S/=r,C/=r):(x=0,S=1,C=0)}}i[o*3]=x,i[o*3+1]=S,i[o*3+2]=C;let E=DP+(1-DP)*w,D=t[o],O=E*(1-jP*NP(D,1)),k=(NP(D,2)-.5)*2*MP;a[o*3]=O*(1+k),a[o*3+1]=O,a[o*3+2]=O*(1-k)}return{normals:i,colors:a}}var FP=class e{static MASK=4294967295;mW;mZ;constructor(t){this.mW=123456789+t&e.MASK,this.mZ=987654321-t&e.MASK}random(t=1,n=0){this.mZ=36969*(this.mZ&65535)+(this.mZ>>16)&e.MASK,this.mW=18e3*(this.mW&65535)+(this.mW>>16)&e.MASK;let r=((this.mZ<<16)+(this.mW&65535)>>>0)/4294967296;return(t-n)*r+n}};function IP(e,t,n){let r=new FP(t),i={branchVerts:[],branchNormals:[],branchUvs:[],branchIndices:[],leafVerts:[],leafIndices:[],leafUvs:[],leafAnchors:[],leafClusters:[],leafClusterNext:0},a=[{origin:new W,orientation:new cc,length:e.branch.length[0],radius:e.branch.radius[0],level:0,sectionCount:e.branch.sections[0],segmentCount:e.branch.segments[0]}];for(;a.length>0;)LP(e,r,i,a,a.shift());WP(i,n);let o=new Y;o.setAttribute(`position`,new J(new Float32Array(i.branchVerts),3)),o.setAttribute(`normal`,new J(new Float32Array(i.branchNormals),3)),o.setAttribute(`uv`,new J(new Float32Array(i.branchUvs),2)),o.setIndex(new J(GP(i.branchIndices,i.branchVerts),1)),o.computeBoundingSphere();let s=null;if(i.leafVerts.length>0){s=new Y,s.setAttribute(`position`,new J(new Float32Array(i.leafVerts),3)),s.setAttribute(`anchor`,new J(new Float32Array(i.leafAnchors),3)),s.setAttribute(`uv`,new J(new Float32Array(i.leafUvs),2)),s.setIndex(new J(GP(i.leafIndices,i.leafVerts),1));let t=PP(i.leafVerts,i.leafClusters,e.type);s.setAttribute(`normal`,new J(t.normals,3)),s.setAttribute(`color`,new J(t.colors,3)),s.computeBoundingSphere()}return{branches:o,leaves:s}}function LP(e,t,n,r,i){let a=n.branchVerts.length/3,o=i.orientation.clone(),s=i.origin.clone(),c=i.length/i.sectionCount,l=[];for(let r=0;r<=i.sectionCount;r++){let a=i.radius;r===i.sectionCount&&i.level===e.branch.levels?a=.001:e.type===`deciduous`?a*=1-(e.branch.taper[i.level]??0)*(r/i.sectionCount):a*=1-r/i.sectionCount;let u=new W,d=new W,f=0;for(let e=0;e<i.segmentCount;e++){let t=2*Math.PI*e/i.segmentCount,c=new W(Math.cos(t),0,Math.sin(t)).multiplyScalar(a).applyEuler(o).add(s),l=new W(Math.cos(t),0,Math.sin(t)).applyEuler(o).normalize(),p=r%2==0?0:1;n.branchVerts.push(c.x,c.y,c.z),n.branchNormals.push(l.x,l.y,l.z),n.branchUvs.push(e/i.segmentCount,p),e===0&&(u=c,d=l,f=p)}n.branchVerts.push(u.x,u.y,u.z),n.branchNormals.push(d.x,d.y,d.z),n.branchUvs.push(1,f),l.push({origin:s.clone(),orientation:o.clone(),radius:a}),s.add(new W(0,c,0).applyEuler(o));let p=Math.max(1,1/Math.sqrt(a))*(e.branch.gnarliness[i.level]??0);o.x+=t.random(p,-p),o.z+=t.random(p,-p);let m=new U().setFromEuler(o),h=new U().setFromAxisAngle(new W(0,1,0),e.branch.twist[i.level]??0),g=e.branch.force,_=new U().setFromUnitVectors(new W(0,1,0),new W(g.direction.x,g.direction.y,g.direction.z));m.multiply(h),m.rotateTowards(_,g.strength/a),o.setFromQuaternion(m)}UP(n,a,i);let u=i.level===e.branch.levels?n.leafClusterNext++:0;if(e.type===`deciduous`){let a=l[l.length-1];i.level<e.branch.levels?r.push({origin:a.origin,orientation:a.orientation,length:e.branch.length[i.level+1]??0,radius:a.radius,level:i.level+1,sectionCount:i.sectionCount,segmentCount:i.segmentCount}):e.leaves.count>0&&HP(e,t,n,a.origin,a.orientation,u)}i.level===e.branch.levels?VP(e,t,n,l,u):i.level<e.branch.levels&&BP(e,t,r,e.branch.children[i.level]??0,i.level+1,l)}function RP(e,t){let n=Math.floor(t*(e.length-1)),r=e[n],i=n===e.length-1?r:e[n+1],a=(t-n/(e.length-1))/(1/(e.length-1)),o=new W().lerpVectors(r.origin,i.origin,a),s=new U().setFromEuler(r.orientation),c=new U().setFromEuler(i.orientation);return{origin:o,orientation:new cc().setFromQuaternion(c.slerp(s,a)),radius:{a:r.radius,b:i.radius,alpha:a}}}function zP(e,t,n){let r=new U().setFromAxisAngle(new W(1,0,0),t/(180/Math.PI)),i=new U().setFromAxisAngle(new W(0,1,0),n),a=new U().setFromEuler(e);return new cc().setFromQuaternion(a.multiply(i.multiply(r)))}function BP(e,t,n,r,i,a){let o=t.random();for(let s=0;s<r;s++){let c=t.random(1,e.branch.start[i]??0),l=RP(a,c),u=(e.branch.radius[i]??0)*((1-l.radius.alpha)*l.radius.a+l.radius.alpha*l.radius.b),d=2*Math.PI*(o+s/r),f=zP(l.orientation,e.branch.angle[i]??0,d),p=(e.branch.length[i]??0)*(e.type===`evergreen`?1-c:1);n.push({origin:l.origin,orientation:f,length:p,radius:u,level:i,sectionCount:e.branch.sections[i]??1,segmentCount:e.branch.segments[i]??3})}}function VP(e,t,n,r,i){let a=t.random();for(let o=0;o<e.leaves.count;o++){let s=RP(r,t.random(1,e.leaves.start)),c=2*Math.PI*(a+o/e.leaves.count),l=zP(s.orientation,e.leaves.angle,c);HP(e,t,n,s.origin,l,i)}}function HP(e,t,n,r,i,a){let o=n.leafVerts.length/3,s=e.leaves.size*(1+t.random(e.leaves.sizeVariance,-e.leaves.sizeVariance)),c=e=>{let t=s/2,c=[new W(-t,s,0),new W(-t,0,0),new W(t,0,0),new W(t,s,0)];for(let t of c)t.applyEuler(new cc(0,e,0)).applyEuler(i).add(r),n.leafVerts.push(t.x,t.y,t.z),n.leafAnchors.push(r.x,r.y,r.z),n.leafClusters.push(a);n.leafUvs.push(0,1,0,0,1,0,1,1),n.leafIndices.push(o,o+1,o+2,o,o+2,o+3),o+=4};c(0),e.leaves.billboard===`double`&&c(Math.PI/2)}function UP(e,t,n){let r=n.segmentCount+1;for(let i=0;i<n.sectionCount;i++)for(let a=0;a<n.segmentCount;a++){let n=t+i*r+a,o=t+i*r+(a+1),s=n+r,c=o+r;e.branchIndices.push(n,s,o,o,s,c)}}function WP(e,t){let n=0;for(let t=1;t<e.branchVerts.length;t+=3){let r=e.branchVerts[t];r>n&&(n=r)}for(let t=1;t<e.leafVerts.length;t+=3){let r=e.leafVerts[t];r>n&&(n=r)}if(n<=0)return;let r=t/n;for(let t=0;t<e.branchVerts.length;t++)e.branchVerts[t]=e.branchVerts[t]*r;for(let t=0;t<e.leafVerts.length;t++)e.leafVerts[t]=e.leafVerts[t]*r;for(let t=0;t<e.leafAnchors.length;t++)e.leafAnchors[t]=e.leafAnchors[t]*r}function GP(e,t){return t.length/3>65535?new Uint32Array(e):new Uint16Array(e)}var KP=[`simple`,`medium`,`high`],qP=[`conifer`,`broadleaf`,`dead`,`bush`];function JP(e,t,n){return new L(`BAD_FORMAT`,`Tree3D ${e} must be one of [${n.join(`, `)}], got '${t}'.`,{prop:e,validOptions:n})}var YP={simple:0,medium:1,high:2},XP=[5,7,10],ZP=[2,3,4],QP=[6,8,12],$P=[2,3,3],eF=[0,1,2],tF=[3,4,5],nF=3;function rF(e,t){if(!KP.includes(e))throw JP(`tier`,e,KP);if(!qP.includes(t))throw JP(`type`,t,qP);let n=e,r=t,i=YP[n];return{tier:n,type:r,trunkRadialSegments:XP[i],canopyLayers:r===`conifer`?ZP[i]:0,canopySegments:QP[i],blobCount:r===`broadleaf`||r===`bush`?$P[i]:0,blobDetail:eF[i],branchCount:r===`dead`?tF[i]:r===`conifer`&&n===`high`?nF:0,hasCanopy:r!==`dead`,canopySway:n!==`simple`}}var iF=.02,aF={conifer:{trunkHeight:.4,trunkRadiusBottom:.05,trunkRadiusTop:.035},broadleaf:{trunkHeight:.42,trunkRadiusBottom:.05,trunkRadiusTop:.032},dead:{trunkHeight:.72,trunkRadiusBottom:.045,trunkRadiusTop:.018},bush:{trunkHeight:.14,trunkRadiusBottom:.045,trunkRadiusTop:.035}};function oF(e,t,n){let{trunkHeight:r,trunkRadiusBottom:i,trunkRadiusTop:a}=aF[e.type],o=[],s=new pd(a,i,r,e.trunkRadialSegments).toNonIndexed();if(s.translate(0,r/2,0),o.push(s),e.type===`dead`)for(let n=0;n<e.branchCount;n++){let r=.22+t.next()*.14,a=new pd(.006,.02,r,5).toNonIndexed();a.translate(0,r/2,0);let s=.7+t.next()*.6,c=n/e.branchCount*Math.PI*2+t.next()*.8,l=.34+(n+t.next())/e.branchCount*.34;a.applyMatrix4(new K().makeRotationY(c).multiply(new K().makeRotationX(s)).setPosition(Math.sin(c)*i*.6,l,Math.cos(c)*i*.6)),o.push(a)}let c=cF(o);return uF(c,new q(n),.7,1.05,t),c}function sF(e,t,n){if(!e.hasCanopy)return null;let r=[];if(e.type===`conifer`){let n=.74;for(let i=0;i<e.canopyLayers;i++){let a=i/e.canopyLayers,o=.3*(1-a*.62)*(.92+t.next()*.16),s=n/e.canopyLayers*1.7,c=new md(o,s,e.canopySegments).toNonIndexed();lF(c,t,iF),c.translate(0,.26+n*a+s/2,0),r.push(c)}for(let n=0;n<e.branchCount;n++){let i=new md(.06,.2,5).toNonIndexed(),a=n/Math.max(e.branchCount,1)*Math.PI*2+t.next(),o=1.1+t.next()*.4;i.applyMatrix4(new K().makeRotationY(a).multiply(new K().makeRotationX(o)).setPosition(Math.sin(a)*.22,.34+t.next()*.18,Math.cos(a)*.22)),r.push(i)}}else{let{trunkHeight:n}=aF[e.type];for(let i=0;i<e.blobCount;i++){let a=new gd((i===0?.3:.24-i*.02)*(.92+t.next()*.16),e.blobDetail).toNonIndexed();a.scale(1,.72,1),lF(a,t,iF);let o=i===0?0:.13,s=t.next()*Math.PI*2;a.translate(Math.cos(s)*o,n+.16+i*.1+t.next()*.05,Math.sin(s)*o),r.push(a)}}let i=cF(r);return uF(i,new q(n),.62,1.18,t),i}function cF(e){let t=0;for(let n of e)t+=n.getAttribute(`position`).count;let n=new Float32Array(t*3),r=new Float32Array(t*3),i=0;for(let t of e)n.set(t.getAttribute(`position`).array,i),r.set(t.getAttribute(`normal`).array,i),i+=t.getAttribute(`position`).count*3,t.dispose();let a=new Y;return a.setAttribute(`position`,new J(n,3)),a.setAttribute(`normal`,new J(r,3)),a}function lF(e,t,n){let r=e.getAttribute(`position`);for(let e=0;e<r.count;e++)r.setXYZ(e,r.getX(e)+t.range(-n,n),r.getY(e)+t.range(-n,n),r.getZ(e)+t.range(-n,n))}function uF(e,t,n,r,i){let a=e.getAttribute(`position`),o=new Float32Array(a.count*3),s=1/0,c=-1/0;for(let e=0;e<a.count;e++){let t=a.getY(e);t<s&&(s=t),t>c&&(c=t)}let l=Math.max(c-s,1e-6),u=new q;for(let e=0;e<a.count;e++){let c=(a.getY(e)-s)/l,d=(n+(r-n)*c)*(.96+i.next()*.08);u.copy(t).multiplyScalar(d),o[e*3]=u.r,o[e*3+1]=u.g,o[e*3+2]=u.b}e.setAttribute(`color`,new J(o,3))}var dF=500,fF=15e5,pF=[.8,1.2],mF=.28,hF=.12,gF=.055,_F=.11,vF=3,yF=101,bF=[.78,.7,.45],xF=.45,SF=.55,CF=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation`,wF=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark`,TF={high:{conifer:[`pine`,`pine`,`pine`],broadleaf:[`oak`,`ash`,`oak`],dead:[`ash`,`ash`,`ash`],bush:[`bush`,`bush`,`bush`]},medium:{conifer:[`pine-forest`,`pine-forest`,`pine-forest`],broadleaf:[`oak-forest`,`ash-forest`,`oak-forest`],dead:[`ash-forest`,`ash-forest`,`ash-forest`],bush:[`bush-forest`,`bush-forest`,`bush-forest`]}},EF=class e extends Z_{static typeName=`Tree3D`;static props={tier:{default:`medium`,options:KP},type:{default:`conifer`,options:qP},seed:{default:1},height:{default:6},count:{default:1},area:{default:[10,10]},trunkColor:{default:`#7a5a3a`},canopyColor:{default:`#4a7c3f`},leafTexture:{default:``},leafFadeStart:{default:0},leafFadeEnd:{default:0},leafShadows:{default:!0},drape:{default:null},terrain:{default:``,nodePath:!0}};tier=`medium`;type=`conifer`;seed=1;height=6;count=1;area=[10,10];trunkColor=`#7a5a3a`;canopyColor=`#4a7c3f`;leafTexture=``;leafFadeStart=0;leafFadeEnd=0;leafShadows=!0;drape=null;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(rF(t.tier,t.type),!(t.height>0))throw new L(`BAD_FORMAT`,`Tree3D '${e.name}' height must be > 0 meters, got ${t.height}.`,{prop:`height`});if(!Number.isInteger(t.count)||t.count<1||t.count>dF)throw new L(`BAD_FORMAT`,`Tree3D '${e.name}' count must be an integer in 1..${dF}, got ${t.count}.`,{prop:`count`});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new L(`BAD_FORMAT`,`Tree3D '${e.name}' area must be positive [x, z] meters, got ${JSON.stringify(t.area)}.`,{prop:`area`});if(t.leafFadeEnd!==0&&!(t.leafFadeEnd>t.leafFadeStart&&t.leafFadeStart>=0))throw new L(`BAD_FORMAT`,`Tree3D '${e.name}' needs leafFadeEnd > leafFadeStart >= 0 (the leaf LOD window) or 0/0 to disable, got start ${t.leafFadeStart}, end ${t.leafFadeEnd}.`,{prop:`leafFadeStart`});if(typeof t.leafShadows!=`boolean`)throw new L(`BAD_FORMAT`,`Tree3D '${e.name}' leafShadows must be a boolean, got ${JSON.stringify(t.leafShadows)}.`,{prop:`leafShadows`});if(t.drape!==null&&typeof t.drape!=`boolean`)throw new L(`BAD_FORMAT`,`Tree3D '${e.name}' drape must be true, false or null (null = auto: drape whenever the scene has a Terrain3D), got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new L(`BAD_FORMAT`,`Tree3D '${e.name}' terrain must be a node-path string (empty = auto-find), got ${JSON.stringify(t.terrain)}.`,{prop:`terrain`});if(t.tier===`simple`)return;let n=kF(t.tier,t.type),r=n*t.count;if(r>fF)throw new L(`BAD_FORMAT`,`Tree3D '${e.name}' blows the grove triangle budget: count ${t.count} × ${n} tris/tree (tier '${t.tier}', type '${t.type}') = ${r} > ${fF}. Lower count (max ${Math.floor(fF/n)} at this tier), drop tier to 'medium'/'simple', or split the grove into multiple nodes.`,{prop:`count`})}time=0;grove=null;variants=[];simpleTrunk=null;simpleCanopy=null;swayUniform=null;leafFadeUniform=null;loadedTextures=[];groveKey=``;_createObject3D(){return new Ec}_trunk(){return this.rebuildIfNeeded(),this.simpleTrunk??this.variants[0]?.branches}_canopy(){return this.rebuildIfNeeded(),this.simpleTrunk?this.simpleCanopy:this.variants[0]?.leaves??null}_variantMeshes(){return this.rebuildIfNeeded(),this.variants}update(e){this.time+=e,this.swayUniform&&(this.swayUniform.value=this.time),this.leafFadeUniform&&(this.leafFadeUniform.start.value=this.leafFadeStart,this.leafFadeUniform.end.value=this.leafFadeEnd)}assets=null;_syncObject3D(e=1,t=null){super._syncObject3D(e,t),this.assets=t,this.rebuildIfNeeded()}noteTextureError=(e,t)=>{this.assets?.textures.noteError(e,t)};rebuildIfNeeded(){this.grove||(this.grove=new Ec,this._ensureObject3D().add(this.grove));let e=JSON.stringify([this.tier,this.type,this.seed,this.height,this.count,this.area,this.trunkColor,this.canopyColor,this.leafTexture,this.leafShadows,this.leafFadeEnd>this.leafFadeStart,this.drape,this.terrain]);e===this.groveKey&&(this.simpleTrunk||this.variants.length>0)||(this.groveKey=e,this.disposeMeshes(),this.resolveDrape(),this.tier===`simple`?this.buildSimpleGrove():this.buildEzGrove())}resolveDrape(){if(this.drapeTerrain=null,this.drape===!1)return;let e=qA(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=KA(this);else if(this.terrain!==``)throw new L(`NODE_NOT_FOUND`,`Tree3D '${this.name}' drape terrain '${this.terrain}' is not a Terrain3D in the tree.`,{prop:`terrain`})}bedY(e,t){let n=this.drapeTerrain;return n?n.heightAt(this.drapeWorld[0]+e,this.drapeWorld[2]+t)-this.drapeWorld[1]:0}buildSimpleGrove(){let e=rF(this.tier,this.type),t=new Ee(this.seed),n=oF(e,t,this.trunkColor),r=sF(e,t,this.canopyColor),i=new Au(n,FF(),this.count);LF(i);let a=null;r&&(a=new Au(r,FF(),this.count),LF(a)),this.scatter(t,(e,t,n)=>{i.setMatrixAt(e,t),i.setColorAt(e,n),a?.setMatrixAt(e,t),a?.setColorAt(e,n)}),IF(i),a&&IF(a),this.simpleTrunk=i,this.simpleCanopy=a,this.grove.add(i),a&&this.grove.add(a)}buildEzGrove(){let e=TF[this.tier][this.type],t=Math.min(vF,this.count),n=Array.from({length:t},(e,n)=>Math.floor(this.count/t)+ +(n<this.count%t));this.swayUniform={value:this.time},this.leafFadeUniform=this.leafFadeEnd>this.leafFadeStart?{start:{value:this.leafFadeStart},end:{value:this.leafFadeEnd}}:null;let r=MF(this.canopyColor),i=null;typeof document<`u`&&typeof createImageBitmap==`function`&&(i=new Pf,i.setOptions({imageOrientation:`flipY`}));for(let a=0;a<t;a++){let t=n[a],o=e[a],s=wP(o);this.type===`dead`&&(s.leaves.count=0);let c=IP(s,this.seed+a*yF,1),l=this.buildBarkMaterial(o,i),u=new Au(c.branches,l,t);LF(u);let d=null;if(c.leaves){let e=new kd({color:r.clone().multiply(new q(bF[0],bF[1],bF[2])),roughness:1,side:2,vertexColors:!0,alphaTest:s.leaves.alphaTest}),n=this.leafTexture||AF(s.leaves.style);i&&(e.map=OF(i,n,e=>{e.colorSpace=Ro,e.flipY=!1},e=>jF(e),this.noteTextureError)),Rj(e,this.swayUniform,xF,this.leafFadeUniform??void 0),d=new Au(c.leaves,e,t),d.userData.incantoWaterPassSkip=!0,LF(d),this.leafShadows||(d.castShadow=!1)}this.variants.push({branches:u,leaves:d}),this.grove.add(u),d&&this.grove.add(d)}let a=Array(t).fill(0),o=new Ee(this.seed);this.scatter(o,(e,n,r)=>{let i=e%t,o=this.variants[i],s=a[i];a[i]=s+1,o.branches.setMatrixAt(s,n),o.branches.setColorAt(s,r),o.leaves?.setMatrixAt(s,n),o.leaves?.setColorAt(s,r)});for(let e of this.variants)IF(e.branches),e.leaves&&IF(e.leaves)}buildBarkMaterial(t,n){if(this.type===`dead`||!n)return new kd({color:new q(this.trunkColor),roughness:1});let r=EP(t),i=new kd({color:this.trunkColor===e.props.trunkColor?.default?new q(r.tint):PF(this.trunkColor),roughness:1});return Lj(i,SF),i.map=this.loadBarkTexture(n,r,`color`,!0),i.normalMap=this.loadBarkTexture(n,r,`normal`,!1),i.roughnessMap=this.loadBarkTexture(n,r,`roughness`,!1),i}loadBarkTexture(e,t,n,r){return OF(e,`${wF}/${t.texture}_${n}_1k.jpg`,e=>{e.wrapS=la,e.wrapT=la,e.repeat.set(t.repeat[0],t.repeat[1]),e.anisotropy=4,e.flipY=!1,r&&(e.colorSpace=Ro)},void 0,this.noteTextureError)}scatter(e,t){let n=(this.area[0]??0)/2,r=(this.area[1]??0)/2;for(let i=0;i<this.count;i++){let a=this.count===1?0:e.range(-n,n),o=this.count===1?0:e.range(-r,r);BF.set(a,this.drape?this.bedY(a,o):0,o),VF.setFromAxisAngle(RF,e.range(0,Math.PI*2));let s=this.height*e.range(pF[0],pF[1]),c=s*e.range(.9,1.1);HF.set(c,s,c),zF.compose(BF,VF,HF),UF.setHSL(mF,hF,.92).offsetHSL(e.range(-.055,gF),0,e.range(-.11,_F)),t(i,zF,UF)}}disposeMeshes(){let e=[this.simpleTrunk,this.simpleCanopy];for(let t of this.variants)e.push(t.branches,t.leaves);let t=new Set;for(let n of e)n&&(n.removeFromParent(),n.geometry.dispose(),t.add(n.material),n.dispose());for(let e of t)e.dispose();for(let e of this.loadedTextures)e.dispose();this.loadedTextures=[],this.simpleTrunk=null,this.simpleCanopy=null,this.variants=[],this.swayUniform=null,this.leafFadeUniform=null}free(){this.disposeMeshes(),this.grove=null,super.free()}},DF=new Map;function OF(e,t,n,r,i){let a=DF.get(t);if(a)return a;let o=new qs;return n(o),e.load(t,e=>{o.image=e,r?r(o):o.needsUpdate=!0},void 0,e=>i?.(t,e)),DF.set(t,o),o}function kF(e,t){let n=0;for(let r of new Set(TF[e][t]??[])){let e=wP(r);t===`dead`&&(e.leaves.count=0),n=Math.max(n,xP(e).total)}return n}function AF(e){return`${CF}/${e}_color.png`}function jF(e){let t=e.image;if(!t||typeof document>`u`)return;let n=document.createElement(`canvas`);n.width=t.naturalWidth||t.width,n.height=t.naturalHeight||t.height;let r=n.getContext(`2d`,{willReadFrequently:!0});if(!r)return;r.drawImage(t,0,0);let i;try{i=r.getImageData(0,0,n.width,n.height)}catch{return}let a=i.data,o=0,s=0,c=0,l=0;for(let e=0;e<a.length;e+=4)a[e+3]>240&&(o+=a[e],s+=a[e+1],c+=a[e+2],l++);if(l!==0){o=Math.round(o/l),s=Math.round(s/l),c=Math.round(c/l);for(let e=0;e<a.length;e+=4)a[e+3]<=240&&(a[e]=o,a[e+1]=s,a[e+2]=c);r.putImageData(i,0,0),e.image=n,e.needsUpdate=!0}}function MF(e){let t=new q(e),n=Math.max(t.r,t.g,t.b);return n>0?t.multiplyScalar(1/n):t.setRGB(1,1,1),t.lerp(NF,.18)}var NF=new q(1,1,1);function PF(e){let t=new q(e),n=Math.max(t.r,t.g,t.b);return n>0?t.multiplyScalar(1/n):t.setRGB(1,1,1),t}function FF(){return new kd({vertexColors:!0,roughness:1,flatShading:!0})}function IF(e){e.instanceMatrix.needsUpdate=!0,e.instanceColor&&(e.instanceColor.needsUpdate=!0),GA(e)}function LF(e){e.castShadow=!0,e.receiveShadow=!0}var RF=new W(0,1,0),zF=new K,BF=new W,VF=new U,HF=new W,UF=new q,WF=[[[.4,.4,.4],[.4,.4,.4],[.4,.4,.4],[.4,.4,.4],[.4,.4,.4],[.4,.4,.4]],[[.6,.3,0],[.6,.3,0],[.6,.3,0],[.6,.3,0],[0,.8,0],[.6,.3,0]],[[.6,.3,0],[.6,.3,0],[.6,.3,0],[.6,.3,0],[.6,.3,0],[.6,.3,0]],[[.6,.55,.5],[.55,.5,.45],[.5,.45,.4],[.55,.5,.45],[.65,.6,.55],[.5,.45,.4]],[[.45,.45,.4],[.4,.4,.35],[.35,.35,.3],[.4,.4,.35],[.5,.5,.45],[.35,.35,.3]],[[.2,.2,.2],[.2,.2,.2],[.2,.2,.2],[.2,.2,.2],[.2,.2,.2],[.2,.2,.2]],[[.8,.5,.2],[.75,.45,.15],[.7,.4,.1],[.75,.45,.15],[.85,.55,.25],[.7,.4,.1]],[[0,.7,.1],[0,.65,.1],[0,.6,.1],[0,.65,.1],[0,.75,.1],[0,.6,.1]],[[.3,.3,.3],[.3,.3,.3],[.3,.3,.3],[.3,.3,.3],[.3,.3,.3],[.3,.3,.3]],[[0,0,.7],[0,0,.7],[0,0,.7],[0,0,.7],[0,.2,.9],[0,0,.6]],[[.9,.3,0],[.9,.3,0],[.9,.3,0],[.9,.3,0],[1,.4,0],[.7,.2,0]],[[.9,.8,.2],[.85,.75,.18],[.85,.75,.18],[.85,.75,.18],[.95,.85,.25],[.85,.75,.18]],[[.6,.6,.6],[.55,.55,.55],[.5,.5,.5],[.55,.55,.55],[.65,.65,.65],[.5,.5,.5]],[[.7,.7,.4],[.65,.65,.35],[.6,.6,.3],[.65,.65,.35],[.75,.75,.45],[.6,.6,.3]],[[.7,.5,.5],[.65,.45,.45],[.6,.4,.4],[.65,.45,.45],[.75,.55,.55],[.6,.4,.4]],[[.35,.3,.25],[.3,.25,.2],[.25,.2,.15],[.3,.25,.2],[.4,.35,.3],[.25,.2,.15]],[[.5,.3,0],[.5,.3,0],[.5,.3,0],[.5,.3,0],[.7,.4,.1],[.7,.4,.1]],[[0,.5,0],[0,.45,0],[0,.45,0],[0,.45,0],[0,.6,0],[0,.4,0]],[[.2,.8,.8],[.15,.7,.7],[.1,.6,.6],[.15,.7,.7],[.3,.9,.9],[.1,.6,.6]],[[1,.5,.8],[.9,.4,.7],[.8,.3,.6],[.9,.4,.7],[1,.6,.9],[.8,.3,.6]],[[1,.9,.3],[.95,.85,.25],[.9,.8,.2],[.95,.85,.25],[1,1,.4],[.9,.8,.2]],[[1,0,0],[.9,0,0],[.8,0,0],[.9,0,0],[1,.2,.2],[.8,0,0]],[[.6,.4,.2],[.5,.3,.15],[.4,.25,.1],[.5,.3,.15],[.7,.45,.25],[.4,.25,.1]],[[.6,.2,.8],[.5,.15,.7],[.4,.1,.6],[.5,.15,.7],[.7,.25,.9],[.4,.1,.6]],[[1,.8,0],[.95,.75,0],[.95,.75,0],[.95,.75,0],[1,.9,0],[.9,.7,0]],[[.6,.65,.7],[.55,.6,.65],[.5,.55,.6],[.55,.6,.65],[.65,.7,.75],[.5,.55,.6]]],GF=2e5,KF=class extends Z_{static typeName=`VoxelGrid3D`;static signals=[`blocksChanged`];static props={voxels:{default:[]}};voxels=[];appliedVoxels=null;map=new Map;mesh=null;dirty=!1;blockCount(){return this.map.size}tileAt(e,t,n){return this.map.get(`${e},${t},${n}`)}setBlocks(e){this.map.clear();for(let t of e)this.map.set(`${t.x},${t.y},${t.z}`,t.tile);this.dirty=!0,this.emit(`blocksChanged`)}addBlock(e){this.map.set(`${e.x},${e.y},${e.z}`,e.tile),this.dirty=!0,this.emit(`blocksChanged`)}removeBlockAt(e,t,n){let r=this.map.delete(`${e},${t},${n}`);return r&&(this.dirty=!0,this.emit(`blocksChanged`)),r}blocks(){let e=[];for(let[t,n]of this.map){let[r,i,a]=t.split(`,`).map(Number);e.push({x:r,y:i,z:a,tile:n})}return e}_createObject3D(){let e=new dd(1,1,1),t=new Dd({vertexShader:JF,fragmentShader:YF});this.mesh=new Au(e,t,GF),this.mesh.count=0,this.mesh.frustumCulled=!1;for(let e of qF)this.mesh.geometry.setAttribute(e,new Su(new Float32Array(GF*3),3));return this.dirty=!0,this.mesh}update(){if(this.voxels.length>0&&this.voxels!==this.appliedVoxels&&(this.appliedVoxels=this.voxels,this.setBlocks(this.voxels.map(e=>({x:e[0]??0,y:e[1]??0,z:e[2]??0,tile:e[3]??0})))),!this.dirty||!this.mesh)return;this.dirty=!1;let e=new K,t=0;for(let[n,r]of this.map){if(t>=GF)break;let[i,a,o]=n.split(`,`).map(Number);e.setPosition(i,a,o),this.mesh.setMatrixAt(t,e);let s=WF[r]??WF[0];for(let e=0;e<6;e++){let n=this.mesh.geometry.getAttribute(qF[e]),r=s[e];n.setXYZ(t,r[0],r[1],r[2]),n.needsUpdate=!0}t++}this.mesh.count=t,this.mesh.instanceMatrix.needsUpdate=!0}free(){let e=this._builtObject3D;e&&e.traverse(e=>{let t=e;t.geometry?.dispose();let n=t.material,r=Array.isArray(n)?n:n?[n]:[];for(let e of r)e.dispose?.()}),super.free()}},qF=[`colorFront`,`colorRight`,`colorBack`,`colorLeft`,`colorTop`,`colorBottom`],JF=`
|
|
7913
|
+
`,JN=1.25,YN=4,XN=12,ZN=1.5,QN=.35,$N=1.2,eP=8,tP=.5,nP=.35,rP=42,iP=26,aP=6,oP=.05,sP=1.5,cP={shallow:`#74b2a2`,deep:`#123f4b`,sky:`#8ab6d8`,horizon:`#9fb6c2`,bank:`#465447`},lP=`#e9f2ef`,uP=new W,dP={rippleScale:.85,rippleStrength:.09,flowRate:.42,fresnelScale:.95,standingAmp:.11,glideAmp:.025},fP=class e extends Q_{static typeName=`River3D`;static props={path:{default:[]},width:{default:6},widths:{default:[]},depth:{default:.8},flowSpeed:{default:1.6},colors:{default:{}},absorption:{default:.5},opacity:{default:.85},foam:{default:1},ripples:{default:1},sunDirection:{default:[.5,.8,.3]},sunColor:{default:`#fff6e0`},sunIntensity:{default:1},terrain:{default:``,nodePath:!0},carve:{default:!0},flowForce:{default:1},spray:{default:1}};path=[];width=6;widths=[];depth=.8;flowSpeed=1.6;colors={};absorption=.5;opacity=.85;foam=1;ripples=1;sunDirection=[.5,.8,.3];sunColor=`#fff6e0`;sunIntensity=1;terrain=``;carve=!0;flowForce=1;spray=1;renderOrder=1;time=0;rings=[];falls=[];sprayKey=``;courseKey=``;bedAt=null;fitted=!1;bounds=null;boundsKey=``;rocks=[];rockScanAt=-1;world=[0,0,0];_bodies=[];static validateJson(e){iv(e,`the flow query and its collider both`);let t=e;if(!Array.isArray(t.path))throw new L(`BAD_FORMAT`,`River3D '${e.name}' path must be an array of [x, z] points, got ${JSON.stringify(t.path)}.`,{prop:`path`});if(t.path.length>0&&t.path.length<2)throw new L(`BAD_FORMAT`,`River3D '${e.name}' path needs at least 2 points (source → mouth), got ${t.path.length}.`,{prop:`path`});if(t.path.forEach((t,n)=>{if(!Array.isArray(t)||t.length<2||!Number.isFinite(t[0])||!Number.isFinite(t[1]))throw new L(`BAD_FORMAT`,`River3D '${e.name}' path[${n}] must be [x, z] with finite numbers, got ${JSON.stringify(t)}.`,{prop:`path`})}),!(typeof t.width==`number`&&t.width>0))throw new L(`BAD_FORMAT`,`River3D '${e.name}' width must be a positive number of meters, got ${JSON.stringify(t.width)}.`,{prop:`width`});if(!Array.isArray(t.widths)||t.widths.some(e=>!(typeof e==`number`&&e>0)))throw new L(`BAD_FORMAT`,`River3D '${e.name}' widths must be a list of positive meters (source→mouth), got ${JSON.stringify(t.widths)}.`,{prop:`widths`});if(!(t.depth>0))throw new L(`BAD_FORMAT`,`River3D '${e.name}' depth must be > 0 meters, got ${JSON.stringify(t.depth)}.`,{prop:`depth`});if(!(t.flowSpeed>=0))throw new L(`BAD_FORMAT`,`River3D '${e.name}' flowSpeed must be >= 0 m/s, got ${JSON.stringify(t.flowSpeed)}.`,{prop:`flowSpeed`});for(let n of[`absorption`,`foam`,`ripples`,`flowForce`,`spray`,`sunIntensity`]){let r=t[n];if(!(typeof r==`number`&&r>=0))throw new L(`BAD_FORMAT`,`River3D '${e.name}' ${n} must be a number >= 0, got ${JSON.stringify(r)}.`,{prop:n})}if(!(t.opacity>=0&&t.opacity<=1))throw new L(`BAD_FORMAT`,`River3D '${e.name}' opacity must be within [0, 1], got ${JSON.stringify(t.opacity)}.`,{prop:`opacity`});let n=t.colors;if(typeof n!=`object`||!n||Array.isArray(n))throw new L(`BAD_FORMAT`,`River3D '${e.name}' colors must be an object of { shallow, deep, sky, horizon, bank } hex strings.`,{prop:`colors`});for(let t of Object.keys(n)){if(!(t in cP))throw new L(`BAD_FORMAT`,`River3D '${e.name}' colors has unknown key '${t}' — expected shallow, deep, sky, horizon or bank.`,{prop:`colors`});if(typeof n[t]!=`string`)throw new L(`BAD_FORMAT`,`River3D '${e.name}' colors.${t} must be a hex string, got ${JSON.stringify(n[t])}.`,{prop:`colors`})}}_createObject3D(){return new iu(new Y,this.buildMaterial())}onReady(){this.ensureCourse()}onExitTree(){qA(this,this.terrain)?._setExternalChannel(this,null)}update(e){this.time+=e,this.ensureCourse(),this.syncSpray(),this.flowForce>0&&this.rings.length>1&&this.sweepBodies(e)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();this.rebuildIfNeeded(e),this.syncUniforms(e)}_onRender3D(e){if(this.rings.length===0)return;(this.rockScanAt<0||this.time-this.rockScanAt>tP)&&(this.rockScanAt=this.time,this.scanRocks());let t=this._ensureObject3D().material.uniforms;this.syncRocks(t,e.camera.getWorldPosition(uP))}_waterYAt(e,t){if(this.rings.length===0)return null;let[n,r,i]=this.world,a=e-n,o=t-i,s=this.ringBounds();if(a<s.minX||a>s.maxX||o<s.minZ||o>s.maxZ)return null;let c=BN(this.rings,a,o);return c?.inside?c.surfaceY+r:null}ringBounds(){if(this.boundsKey===this.courseKey&&this.bounds)return this.bounds;let e=1/0,t=-1/0,n=1/0,r=-1/0,i=0;for(let a of this.rings)a.x<e&&(e=a.x),a.x>t&&(t=a.x),a.z<n&&(n=a.z),a.z>r&&(r=a.z),i=Math.max(i,a.halfLeft,a.halfRight);return this.bounds={minX:e-i,maxX:t+i,minZ:n-i,maxZ:r+i},this.boundsKey=this.courseKey,this.bounds}sampleAt(e,t){if(this.ensureCourse(),this.rings.length===0)return null;let[n,r,i]=this.world,a=BN(this.rings,e-n,t-i);return a?{...a,surfaceY:a.surfaceY+r}:null}fallsAt(){this.ensureCourse();let[e,t,n]=this.world;return this.falls.map(r=>({...r,worldX:r.x+e,worldY:r.baseY+t,worldZ:r.z+n}))}_rings(){return this.rings}_applySunDirection(t){let n=e.props.sunDirection?.default;this.sunDirection.every((e,t)=>e===n[t])&&(this._ensureObject3D().material.uniforms?.uSunDirection?.value)?.set(t[0],t[1],t[2])}free(){let e=this._ensureObject3D();e.geometry?.dispose(),e.material?.dispose?.(),super.free()}widthProfile(){return this.widths.length>0?this.widths:[this.width]}applyCarve(e){if(!e)return;if(!this.carve||this.path.length<2){e._setExternalChannel(this,null);return}e._setExternalChannel(this,null);let[t,,n]=KA(this),[r,,i]=KA(e),a=e._heightmap();e._setExternalChannel(this,hN({path:this.path.map(e=>[(e[0]??0)+t-r,(e[1]??0)+n-i]),widths:this.widthProfile(),depth:this.depth,cell:(e.size[0]??1)/Math.max(1,a.segsX),groundAt:(e,t)=>a.heightAt(e,t)}))}resolveTerrain(){let e=qA(this,this.terrain);if(!e&&this.terrain!==``)throw new L(`NODE_NOT_FOUND`,`River3D '${this.name}' terrain '${this.terrain}' is not a Terrain3D in the tree.`,{prop:`terrain`});return e}ensureCourse(){let e=this.resolveTerrain(),t=KA(this),n=JSON.stringify([this.path,this.width,this.widths,this.depth,this.flowSpeed,this.carve,e?e.name:``,t]);if(n===this.courseKey)return!1;if(this.courseKey=n,this.world=t,this.bedAt=null,this.applyCarve(e),this.path.length<2)return this.rings=[],this.falls=[],!0;let[r,i,a]=t;this.bedAt=e?(t,n)=>e.heightAt(t+r,n+a)-i:()=>-this.depth,this.fitted=e!==null;let o=this.widthProfile();return this.rings=LN({path:this.path,widths:o,depth:this.depth,flowSpeed:this.flowSpeed,step:IN(o,this.depth),bedAt:this.bedAt,fit:this.fitted}),this.falls=UN(this.rings),this.warnUncoveredWater(),!0}warnUncoveredWater(){if(this.warnedCoverage)return;let e=_N(this.rings);if(e.length*3<this.rings.length)return;this.warnedCoverage=!0;let t=e.reduce((e,t)=>t.wettedHalfWidth-t.carriedHalfWidth>e.wettedHalfWidth-e.carriedHalfWidth?t:e);this.diagnose(`warn`,`[incanto] River3D '${this.name}': the course is too tight for the water it holds — ${e.length} of ${this.rings.length} stations leave bare channel beside the ribbon (worst at ${t.along.toFixed(0)} m: ground wet to ${t.wettedHalfWidth.toFixed(1)} m from the centre, a bend that can only carry ${t.carriedHalfWidth.toFixed(1)} m). Fix by EASING THE BENDS in \`path\` (fewer, straighter points), NARROWING \`widths\` there, or placing standing water (a Water3D) if that reach is really a pool.`)}warnedCoverage=!1;rebuildIfNeeded(e){if(!this.ensureCourse()&&e.geometry.getAttribute(`position`))return;if(this.rings.length===0||!this.bedAt){e.geometry.dispose();let t=new Y;t.setAttribute(`position`,new J(new Float32Array,3)),e.geometry=t;return}let t=this.widthProfile(),n=Math.min(...t),r=Math.max(...t),i=RN(this.rings,{acrossSegments:Math.min(XN,Math.max(YN,Math.round(r/ZN))),bankOvershoot:this.fitted?1:JN,bedBlur:Math.min(n/2*QN,$N),bedAt:this.bedAt}),a=new Y;a.setAttribute(`position`,new J(i.positions,3)),a.setAttribute(`normal`,new J(i.normals,3)),a.setAttribute(`aFlowUv`,new J(i.uvs,2)),a.setAttribute(`aFlow`,new J(i.flow,2)),a.setAttribute(`aRiver`,new J(i.river,4)),a.setIndex(new J(i.indices,1)),a.computeBoundingSphere(),e.geometry.dispose(),e.geometry=a}buildMaterial(){return new Dd({vertexShader:KN,fragmentShader:qN,fog:!0,uniforms:{fogColor:{value:new q(`#ffffff`)},fogNear:{value:1},fogFar:{value:1e3},fogDensity:{value:25e-5},uTime:{value:0},uShallowColor:{value:new q(cP.shallow)},uDeepColor:{value:new q(cP.deep)},uFoamColor:{value:new q(lP)},uSkyColor:{value:new q(cP.sky)},uHorizonColor:{value:new q(cP.horizon)},uBankColor:{value:new q(cP.bank)},uSunDirection:{value:new W(.5,.8,.3)},uSunColor:{value:new q(this.sunColor)},uSunIntensity:{value:this.sunIntensity},uMaxDepth:{value:this.depth},uAbsorption:{value:this.absorption},uOpacity:{value:this.opacity},uFoam:{value:this.foam},uRippleScale:{value:dP.rippleScale},uRippleStrength:{value:dP.rippleStrength*this.ripples},uFlowRate:{value:dP.flowRate},uSparkle:{value:this.ripples},uRockCount:{value:0},uRocks:{value:Array.from({length:eP},()=>new Js)},uFresnelScale:{value:dP.fresnelScale},uStandingAmp:{value:dP.standingAmp},uGlideAmp:{value:dP.glideAmp}},transparent:!0,depthTest:!0,depthWrite:!1,side:2})}scanRocks(){let e=[],[t,n,r]=this.world,i=(i,a,o,s,c)=>{if(o<=.02)return;let l=BN(this.rings,i-t,a-r);if(!l?.inside)return;let u=l.surfaceY+n;if(s>u||c<u-this.depth)return;let d=(c-u)/Math.max(this.depth*nP,.02),f=Math.min(Math.max(d+1,0),1);e.push({x:i,z:a,radius:o,breaks:f})},a=this;for(;a.parent;)a=a.parent;let o=e=>{if(e instanceof rv||e instanceof nv){let t=e.collider,n=s_(t),[r,a,o]=KA(e);i(r,o,t?.shape===`box`?Math.max(t.size?.[0]??.4,t.size?.[2]??.4)/2:t?.radius??.35,a-n,a+n)}else if(e instanceof AD){let[t,n,r]=e.size,[a,o,s]=KA(e);for(let c of e.transforms){let e=c[4]??1,l=a+(c[0]??0),u=o+(c[1]??0),d=s+(c[2]??0),f=(n??1)*e/2;i(l,d,Math.max(t,r)*e/2,u-f,u+f)}}else if(e instanceof ED){let[t,n,r]=e.size,[a,o,s]=KA(e),c=(n??1)/2;i(a,s,Math.max(t,r)/2,o-c,o+c)}for(let t of e.children)o(t)};o(a),this.rocks=e}syncRocks(e,t){let n=e.uRocks?.value,r=e.uRockCount;if(!n||!r)return;if(this.rocks.length===0){r.value=0;return}let i=[...this.rocks].map(e=>({r:e,d:(e.x-t.x)**2+(e.z-t.z)**2})).sort((e,t)=>e.d-t.d).slice(0,eP),a=0;for(let{r:e,d:t}of i){let r=Math.max(e.radius*rP,iP),i=Math.min(Math.sqrt(t)/r,1),o=Math.min(Math.max((i-.6)/.4,0),1),s=1-o*o*(3-2*o);s<=.01||(n[a]?.set(e.x,e.z,e.radius,e.breaks*s),a++)}r.value=a}syncUniforms(e){let t=e.material.uniforms,n=(e,n)=>{let r=t[e];r&&(r.value=n)},r=(e,n)=>{(t[e]?.value)?.set(n)},i=this.colors;n(`uTime`,this.time),r(`uShallowColor`,i.shallow??cP.shallow),r(`uDeepColor`,i.deep??cP.deep),r(`uSkyColor`,i.sky??cP.sky),r(`uHorizonColor`,i.horizon??cP.horizon),r(`uBankColor`,i.bank??cP.bank),r(`uSunColor`,this.sunColor),(t.uSunDirection?.value)?.set(this.sunDirection[0]??.5,this.sunDirection[1]??.8,this.sunDirection[2]??.3),n(`uSunIntensity`,this.sunIntensity),n(`uMaxDepth`,this.depth),n(`uAbsorption`,this.absorption),n(`uOpacity`,this.opacity),n(`uFoam`,this.foam),n(`uRippleStrength`,dP.rippleStrength*this.ripples),n(`uSparkle`,this.ripples)}syncSpray(){let e=this.spray>0?`${this.spray}|${JSON.stringify(this.falls)}`:``;if(e!==this.sprayKey){this.sprayKey=e;for(let e of[...this.children])e.name.startsWith(`__spray`)&&e.free();this.spray<=0||this.falls.forEach((e,t)=>{let n=new nN(`__spray${t}`);n.position=[e.x+e.dirX*.6,e.baseY+.15,e.z+e.dirZ*.6];let r=Math.min(1.6,.4+e.drop*.12)*this.spray;n.rate=Math.round(Math.min(22,5+e.drop*1.6)*this.spray),n.maxParticles=160,n.lifetime=[1,2.1],n.speed=[45*r,130*r],n.directionDeg=-90,n.spreadDeg=52,n.gravity=[0,-240,0],n.drag=1.2,n.sizeStart=7*r,n.sizeEnd=30*r,n.colorStart=`#ffffff`,n.colorEnd=`#dfe9ec`,n.alphaStart=.085,n.alphaEnd=0,n.blend=`normal`,n.depthTest=!0,this.addChild(n)})}}sweepBodies(e){let t=this;for(;t.parent;)t=t.parent;let n=this._bodies;if(n.length=0,pP(t,n),n.length===0)return;let[r,i,a]=this.world;for(let t of n){let n=KA(t),o=BN(this.rings,n[0]-r,n[2]-a);if(!o?.inside)continue;let s=o.surfaceY+i,c=n[1]-s_(t.collider);if(c>s+oP||c<s-this.depth-sP)continue;let l=mP(t);if(!l)continue;let u=Math.min(1,this.flowForce*aP*e),d=(o.dirX*o.speed-(l[0]??0))*u,f=(o.dirZ*o.speed-(l[2]??0))*u;if(t instanceof nv){let e=t.mass||1;t.applyImpulse([d*e,0,f*e])}else l[0]=(l[0]??0)+d,l[2]=(l[2]??0)+f}}};function pP(e,t){(e instanceof rv||e instanceof nv)&&t.push(e);for(let n of e.children)pP(n,t)}function mP(e){return e.velocity??e.linearVelocity}var hP=128,gP=class extends Q_{static typeName=`Trail3D`;static props={width:{default:.3},color:{default:`#ffffff`},opacity:{default:.8},seconds:{default:.6},emitting:{default:!0},additive:{default:!1},minDistance:{default:.05}};width=.3;color=`#ffffff`;opacity=.8;seconds=.6;emitting=!0;additive=!1;minDistance=.05;points=[];clock=0;mesh=null;lastColor=``;_createObject3D(){let e=new Ec,t=new Y;t.setAttribute(`position`,new J(new Float32Array(hP*2*3),3));let n=new Kl({color:this.color,transparent:!0,opacity:this.opacity,side:2,depthWrite:!1,blending:this.additive?2:1});return this.mesh=new iu(t,n),this.mesh.frustumCulled=!1,this.mesh.matrixAutoUpdate=!1,this.mesh.matrixWorld.identity(),this.mesh.updateMatrixWorld=()=>{},e.add(this.mesh),e}wasEmitting=!1;update(e){if(this.clock+=e,this.emitting!==this.wasEmitting){this.wasEmitting=this.emitting;let e=this.tree?.engine;this.emitting&&e&&e.effects.record({kind:`trail`,name:this.color,from:this.getPath(),amount:this.seconds,at:e.time})}for(;this.points.length>0&&this.clock-this.points[0].t>this.seconds;)this.points.shift()}_onRender3D(e){let t=this._ensureObject3D();if(this.emitting){t.getWorldPosition(_P);let e=this.points[this.points.length-1];(!e||(e.x-_P.x)**2+(e.y-_P.y)**2+(e.z-_P.z)**2>this.minDistance*this.minDistance)&&(this.points.push({x:_P.x,y:_P.y,z:_P.z,t:this.clock}),this.points.length>hP&&this.points.shift())}let n=this.mesh;if(!n)return;n.matrixWorld.identity();let r=n.material;this.color!==this.lastColor&&(this.lastColor=this.color,r.color=new q(this.color)),r.opacity=this.opacity;let i=this.points.length,a=n.geometry,o=a.getAttribute(`position`);if(i<2){a.setDrawRange(0,0);return}for(let t=0;t<i;t++){let n=this.points[t],r=this.points[Math.min(t+1,i-1)]??n;vP.set(r.x-n.x,r.y-n.y,r.z-n.z),vP.lengthSq()<1e-8&&vP.set(0,1,0),yP.set(e.camera.position.x-n.x,e.camera.position.y-n.y,e.camera.position.z-n.z),bP.crossVectors(vP,yP).normalize();let a=(this.clock-n.t)/this.seconds,s=this.width/2*Math.max(0,1-a);o.setXYZ(t*2,n.x+bP.x*s,n.y+bP.y*s,n.z+bP.z*s),o.setXYZ(t*2+1,n.x-bP.x*s,n.y-bP.y*s,n.z-bP.z*s)}if(o.needsUpdate=!0,!a.index||a.index.count<(hP-1)*6){let e=[];for(let t=0;t<hP-1;t++){let n=t*2;e.push(n,n+1,n+2,n+1,n+3,n+2)}a.setIndex(e)}a.setDrawRange(0,(i-1)*6)}get pointCount(){return this.points.length}free(){let e=this._builtObject3D;e&&e.traverse(e=>{let t=e;t.geometry?.dispose();let n=t.material,r=Array.isArray(n)?n:n?[n]:[];for(let e of r)e.dispose?.()}),super.free()}},_P=new W,vP=new W,yP=new W,bP=new W;function xP(e){let{branch:t,leaves:n,type:r}=e,i=0,a=0,o=[{level:0,sections:t.sections[0],segments:t.segments[0]}];for(;o.length>0;){let e=o.shift();if(i+=e.sections*e.segments*2,e.level>=t.levels){a+=n.count===0?0:n.count+ +(r===`deciduous`);continue}r===`deciduous`&&o.push({level:e.level+1,sections:e.sections,segments:e.segments});let s=t.children[e.level]??0;for(let n=0;n<s;n++)o.push({level:e.level+1,sections:t.sections[e.level+1]??1,segments:t.segments[e.level+1]??3})}let s=n.billboard===`double`?2:1,c=a*s*2;return{branches:i,leaves:c,total:i+c}}var SP={ash:{type:`deciduous`,branch:{levels:3,angle:[0,48,75,60],children:[7,4,3,0],force:{direction:{x:0,y:1,z:0},strength:-.06},gnarliness:[.03,.25,.2,.09],length:[43.47,27.14,9.51,4.6],radius:[2,.63,.76,.7],sections:[12,8,6,4],segments:[12,6,4,3],start:[0,.23,.33,0],taper:[.7,.7,.7,.7],twist:[.09,-.07,0,0]},leaves:{style:`ash`,billboard:`double`,angle:55,count:16,start:0,size:2.67,sizeVariance:.72,alphaTest:.5}},aspen:{type:`deciduous`,branch:{levels:2,angle:[0,75,32,7],children:[10,3,3,0],force:{direction:{x:0,y:1,z:0},strength:.0148},gnarliness:[.05,.12,.12,.02],length:[50,6.07,11.19,1],radius:[.72,.41,.7,.7],sections:[12,10,8,6],segments:[8,6,4,3],start:[0,.59,.35,0],taper:[.37,.13,.7,.7],twist:[0,0,0,0]},leaves:{style:`aspen`,billboard:`double`,angle:30,count:11,start:.124,size:2.5,sizeVariance:.7,alphaTest:.5}},oak:{type:`deciduous`,branch:{levels:3,angle:[0,54,58,32],children:[6,4,3,0],force:{direction:{x:0,y:1,z:0},strength:-.01},gnarliness:[0,-.1,-.15,.09],length:[37.24,11.08,12.39,7.16],radius:[1.41,.9,.69,1.19],sections:[8,6,3,1],segments:[7,5,3,3],start:[0,.49,.06,.12],taper:[.73,.42,.69,.75],twist:[-.23,.42,0,0]},leaves:{style:`oak`,billboard:`double`,angle:42,count:18,start:.16,size:2.5,sizeVariance:.7,alphaTest:.5}},pine:{type:`evergreen`,branch:{levels:1,angle:[0,110,16,60],children:[82,3,5,0],force:{direction:{x:0,y:1,z:0},strength:-.003},gnarliness:[.05,.08,0,0],length:[50,23.87,14.08,1],radius:[1.05,.36,.7,.7],sections:[12,10,8,6],segments:[8,6,4,3],start:[0,.27,.14,.3],taper:[.7,.7,.7,.7],twist:[0,0,0,0]},leaves:{style:`pine`,billboard:`double`,angle:39,count:30,start:.09,size:1.435,sizeVariance:.201,alphaTest:.3}},bush:{type:`deciduous`,branch:{levels:3,angle:[0,21.5,62.6,60],children:[7,3,2,0],force:{direction:{x:0,y:1,z:0},strength:-.02},gnarliness:[.11,.09,.05,.09],length:[.1,15.3,5.59,4.6],radius:[.58,.95,.76,.7],sections:[6,6,4,3],segments:[4,4,4,3],start:[0,.53,.33,0],taper:[.7,.7,.7,.7],twist:[.3,-.07,0,0]},leaves:{style:`ash`,billboard:`double`,angle:55,count:8,start:0,size:2.45,sizeVariance:.717,alphaTest:.5}},"ash-forest":{type:`deciduous`,branch:{levels:2,angle:[0,48,75,60],children:[5,3,0,0],force:{direction:{x:0,y:1,z:0},strength:-.06},gnarliness:[.03,.25,.2,.09],length:[43.47,27.14,9.51,4.6],radius:[2,.63,.76,.7],sections:[6,5,4,4],segments:[6,4,3,3],start:[0,.3,.33,0],taper:[.7,.7,.7,.7],twist:[.09,-.07,0,0]},leaves:{style:`ash`,billboard:`double`,angle:55,count:15,start:0,size:3,sizeVariance:.6,alphaTest:.5}},"oak-forest":{type:`deciduous`,branch:{levels:2,angle:[0,54,58,32],children:[5,3,0,0],force:{direction:{x:0,y:1,z:0},strength:-.01},gnarliness:[0,-.1,-.15,.09],length:[37.24,11.08,12.39,7.16],radius:[1.41,.9,.69,1.19],sections:[6,4,3,1],segments:[6,4,3,3],start:[0,.49,.06,.12],taper:[.73,.42,.69,.75],twist:[-.23,.42,0,0]},leaves:{style:`oak`,billboard:`double`,angle:42,count:16,start:.1,size:2.9,sizeVariance:.7,alphaTest:.5}},"pine-forest":{type:`evergreen`,branch:{levels:1,angle:[0,110,16,60],children:[44,3,5,0],force:{direction:{x:0,y:1,z:0},strength:-.005},gnarliness:[.07,.09,0,0],length:[50,23.87,14.08,1],radius:[1.05,.36,.7,.7],sections:[6,5,8,6],segments:[6,3,4,3],start:[0,.27,.14,.3],taper:[.7,.7,.7,.7],twist:[0,0,0,0]},leaves:{style:`pine`,billboard:`double`,angle:39,count:9,start:.09,size:1.8,sizeVariance:.201,alphaTest:.3}},"bush-forest":{type:`deciduous`,branch:{levels:2,angle:[0,21.5,62.6,60],children:[6,3,0,0],force:{direction:{x:0,y:1,z:0},strength:-.02},gnarliness:[.11,.09,.05,.09],length:[.1,15.3,5.59,4.6],radius:[.58,.95,.76,.7],sections:[5,4,3,3],segments:[4,3,3,3],start:[0,.53,.33,0],taper:[.7,.7,.7,.7],twist:[.3,-.07,0,0]},leaves:{style:`ash`,billboard:`double`,angle:55,count:10,start:0,size:3.2,sizeVariance:.6,alphaTest:.5}}},CP=[`ash`,`aspen`,`oak`,`pine`,`bush`,`ash-forest`,`oak-forest`,`pine-forest`,`bush-forest`];function wP(e){let t=SP[e];if(!t)throw new L(`BAD_FORMAT`,`Unknown eztree preset '${e}' — must be one of [${CP.join(`, `)}].`,{prop:`preset`,validOptions:CP});return structuredClone(t)}var TP={ash:{texture:`oak`,tint:`#cecbbe`,repeat:[.5,1/5]},aspen:{texture:`birch`,tint:`#ffffff`,repeat:[1,1]},oak:{texture:`oak`,tint:`#fff3d1`,repeat:[1,1/10]},pine:{texture:`pine`,tint:`#ffffff`,repeat:[1,1]},bush:{texture:`oak`,tint:`#cecbbe`,repeat:[.5,1/5]}};function EP(e){if(!CP.includes(e))throw new L(`BAD_FORMAT`,`Unknown eztree preset '${e}' — must be one of [${CP.join(`, `)}].`,{prop:`preset`,validOptions:CP});return structuredClone(TP[e.replace(/-forest$/,``)])}var DP=.45,OP=.45,kP=.55,AP=.15,jP=.07,MP=.035;function NP(e,t){let n=Math.imul(e+1,374761393)+Math.imul(t+1,668265263)>>>0;return n=Math.imul(n^n>>>13,1274126177)>>>0,((n^n>>>16)>>>0)/4294967296}function PP(e,t,n){let r=e.length/3,i=new Float32Array(e.length),a=new Float32Array(e.length),o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let t=0;t<r;t++){let n=e[t*3],r=e[t*3+1],i=e[t*3+2];n<o&&(o=n),n>l&&(l=n),r<s&&(s=r),r>u&&(u=r),i<c&&(c=i),i>d&&(d=i)}let f=(o+l)/2,p=(s+u)/2,m=(c+d)/2,h=Math.max((l-o)/2,.001),g=Math.max((u-s)/2,.001),_=Math.max((d-c)/2,.001),v=new Map;for(let n=0;n<r;n++){let r=t[n],i=v.get(r);i||(i={x:0,y:0,z:0,n:0},v.set(r,i)),i.x+=e[n*3],i.y+=e[n*3+1],i.z+=e[n*3+2],i.n++}for(let e of v.values())e.x/=e.n,e.y/=e.n,e.z/=e.n;for(let o=0;o<r;o++){let r=e[o*3],c=e[o*3+1],l=e[o*3+2],d=(r-f)/h,y=(c-p)/g,b=(l-m)/_,x,S,C,w;if(n===`evergreen`){let e=Math.hypot(r-f,l-m);if(e<1e-6)x=0,S=1,C=0;else{let t=1/Math.hypot(1,OP);x=(r-f)/e*t,S=OP*t,C=(l-m)/e*t}let t=(c-s)/Math.max(u-s,.001),n=Math.max(AP,1-t);w=Math.min(1,Math.hypot(d,b)/n)}else{let e=d/h,t=y/g,n=b/_,r=Math.hypot(e,t,n);r<1e-6?(x=0,S=1,C=0):(x=e/r,S=t/r,C=n/r),w=Math.min(1,Math.hypot(d,y,b))}let T=v.get(t[o]);if(T){let e=r-T.x,t=c-T.y,n=l-T.z,i=Math.hypot(e,t,n);if(i>1e-6){x=x*(1-kP)+e/i*kP,S=S*(1-kP)+t/i*kP,C=C*(1-kP)+n/i*kP;let r=Math.hypot(x,S,C);r>1e-6?(x/=r,S/=r,C/=r):(x=0,S=1,C=0)}}i[o*3]=x,i[o*3+1]=S,i[o*3+2]=C;let E=DP+(1-DP)*w,D=t[o],O=E*(1-jP*NP(D,1)),k=(NP(D,2)-.5)*2*MP;a[o*3]=O*(1+k),a[o*3+1]=O,a[o*3+2]=O*(1-k)}return{normals:i,colors:a}}var FP=class e{static MASK=4294967295;mW;mZ;constructor(t){this.mW=123456789+t&e.MASK,this.mZ=987654321-t&e.MASK}random(t=1,n=0){this.mZ=36969*(this.mZ&65535)+(this.mZ>>16)&e.MASK,this.mW=18e3*(this.mW&65535)+(this.mW>>16)&e.MASK;let r=((this.mZ<<16)+(this.mW&65535)>>>0)/4294967296;return(t-n)*r+n}};function IP(e,t,n){let r=new FP(t),i={branchVerts:[],branchNormals:[],branchUvs:[],branchIndices:[],leafVerts:[],leafIndices:[],leafUvs:[],leafAnchors:[],leafClusters:[],leafClusterNext:0},a=[{origin:new W,orientation:new cc,length:e.branch.length[0],radius:e.branch.radius[0],level:0,sectionCount:e.branch.sections[0],segmentCount:e.branch.segments[0]}];for(;a.length>0;)LP(e,r,i,a,a.shift());WP(i,n);let o=new Y;o.setAttribute(`position`,new J(new Float32Array(i.branchVerts),3)),o.setAttribute(`normal`,new J(new Float32Array(i.branchNormals),3)),o.setAttribute(`uv`,new J(new Float32Array(i.branchUvs),2)),o.setIndex(new J(GP(i.branchIndices,i.branchVerts),1)),o.computeBoundingSphere();let s=null;if(i.leafVerts.length>0){s=new Y,s.setAttribute(`position`,new J(new Float32Array(i.leafVerts),3)),s.setAttribute(`anchor`,new J(new Float32Array(i.leafAnchors),3)),s.setAttribute(`uv`,new J(new Float32Array(i.leafUvs),2)),s.setIndex(new J(GP(i.leafIndices,i.leafVerts),1));let t=PP(i.leafVerts,i.leafClusters,e.type);s.setAttribute(`normal`,new J(t.normals,3)),s.setAttribute(`color`,new J(t.colors,3)),s.computeBoundingSphere()}return{branches:o,leaves:s}}function LP(e,t,n,r,i){let a=n.branchVerts.length/3,o=i.orientation.clone(),s=i.origin.clone(),c=i.length/i.sectionCount,l=[];for(let r=0;r<=i.sectionCount;r++){let a=i.radius;r===i.sectionCount&&i.level===e.branch.levels?a=.001:e.type===`deciduous`?a*=1-(e.branch.taper[i.level]??0)*(r/i.sectionCount):a*=1-r/i.sectionCount;let u=new W,d=new W,f=0;for(let e=0;e<i.segmentCount;e++){let t=2*Math.PI*e/i.segmentCount,c=new W(Math.cos(t),0,Math.sin(t)).multiplyScalar(a).applyEuler(o).add(s),l=new W(Math.cos(t),0,Math.sin(t)).applyEuler(o).normalize(),p=r%2==0?0:1;n.branchVerts.push(c.x,c.y,c.z),n.branchNormals.push(l.x,l.y,l.z),n.branchUvs.push(e/i.segmentCount,p),e===0&&(u=c,d=l,f=p)}n.branchVerts.push(u.x,u.y,u.z),n.branchNormals.push(d.x,d.y,d.z),n.branchUvs.push(1,f),l.push({origin:s.clone(),orientation:o.clone(),radius:a}),s.add(new W(0,c,0).applyEuler(o));let p=Math.max(1,1/Math.sqrt(a))*(e.branch.gnarliness[i.level]??0);o.x+=t.random(p,-p),o.z+=t.random(p,-p);let m=new U().setFromEuler(o),h=new U().setFromAxisAngle(new W(0,1,0),e.branch.twist[i.level]??0),g=e.branch.force,_=new U().setFromUnitVectors(new W(0,1,0),new W(g.direction.x,g.direction.y,g.direction.z));m.multiply(h),m.rotateTowards(_,g.strength/a),o.setFromQuaternion(m)}UP(n,a,i);let u=i.level===e.branch.levels?n.leafClusterNext++:0;if(e.type===`deciduous`){let a=l[l.length-1];i.level<e.branch.levels?r.push({origin:a.origin,orientation:a.orientation,length:e.branch.length[i.level+1]??0,radius:a.radius,level:i.level+1,sectionCount:i.sectionCount,segmentCount:i.segmentCount}):e.leaves.count>0&&HP(e,t,n,a.origin,a.orientation,u)}i.level===e.branch.levels?VP(e,t,n,l,u):i.level<e.branch.levels&&BP(e,t,r,e.branch.children[i.level]??0,i.level+1,l)}function RP(e,t){let n=Math.floor(t*(e.length-1)),r=e[n],i=n===e.length-1?r:e[n+1],a=(t-n/(e.length-1))/(1/(e.length-1)),o=new W().lerpVectors(r.origin,i.origin,a),s=new U().setFromEuler(r.orientation),c=new U().setFromEuler(i.orientation);return{origin:o,orientation:new cc().setFromQuaternion(c.slerp(s,a)),radius:{a:r.radius,b:i.radius,alpha:a}}}function zP(e,t,n){let r=new U().setFromAxisAngle(new W(1,0,0),t/(180/Math.PI)),i=new U().setFromAxisAngle(new W(0,1,0),n),a=new U().setFromEuler(e);return new cc().setFromQuaternion(a.multiply(i.multiply(r)))}function BP(e,t,n,r,i,a){let o=t.random();for(let s=0;s<r;s++){let c=t.random(1,e.branch.start[i]??0),l=RP(a,c),u=(e.branch.radius[i]??0)*((1-l.radius.alpha)*l.radius.a+l.radius.alpha*l.radius.b),d=2*Math.PI*(o+s/r),f=zP(l.orientation,e.branch.angle[i]??0,d),p=(e.branch.length[i]??0)*(e.type===`evergreen`?1-c:1);n.push({origin:l.origin,orientation:f,length:p,radius:u,level:i,sectionCount:e.branch.sections[i]??1,segmentCount:e.branch.segments[i]??3})}}function VP(e,t,n,r,i){let a=t.random();for(let o=0;o<e.leaves.count;o++){let s=RP(r,t.random(1,e.leaves.start)),c=2*Math.PI*(a+o/e.leaves.count),l=zP(s.orientation,e.leaves.angle,c);HP(e,t,n,s.origin,l,i)}}function HP(e,t,n,r,i,a){let o=n.leafVerts.length/3,s=e.leaves.size*(1+t.random(e.leaves.sizeVariance,-e.leaves.sizeVariance)),c=e=>{let t=s/2,c=[new W(-t,s,0),new W(-t,0,0),new W(t,0,0),new W(t,s,0)];for(let t of c)t.applyEuler(new cc(0,e,0)).applyEuler(i).add(r),n.leafVerts.push(t.x,t.y,t.z),n.leafAnchors.push(r.x,r.y,r.z),n.leafClusters.push(a);n.leafUvs.push(0,1,0,0,1,0,1,1),n.leafIndices.push(o,o+1,o+2,o,o+2,o+3),o+=4};c(0),e.leaves.billboard===`double`&&c(Math.PI/2)}function UP(e,t,n){let r=n.segmentCount+1;for(let i=0;i<n.sectionCount;i++)for(let a=0;a<n.segmentCount;a++){let n=t+i*r+a,o=t+i*r+(a+1),s=n+r,c=o+r;e.branchIndices.push(n,s,o,o,s,c)}}function WP(e,t){let n=0;for(let t=1;t<e.branchVerts.length;t+=3){let r=e.branchVerts[t];r>n&&(n=r)}for(let t=1;t<e.leafVerts.length;t+=3){let r=e.leafVerts[t];r>n&&(n=r)}if(n<=0)return;let r=t/n;for(let t=0;t<e.branchVerts.length;t++)e.branchVerts[t]=e.branchVerts[t]*r;for(let t=0;t<e.leafVerts.length;t++)e.leafVerts[t]=e.leafVerts[t]*r;for(let t=0;t<e.leafAnchors.length;t++)e.leafAnchors[t]=e.leafAnchors[t]*r}function GP(e,t){return t.length/3>65535?new Uint32Array(e):new Uint16Array(e)}var KP=[`simple`,`medium`,`high`],qP=[`conifer`,`broadleaf`,`dead`,`bush`];function JP(e,t,n){return new L(`BAD_FORMAT`,`Tree3D ${e} must be one of [${n.join(`, `)}], got '${t}'.`,{prop:e,validOptions:n})}var YP={simple:0,medium:1,high:2},XP=[5,7,10],ZP=[2,3,4],QP=[6,8,12],$P=[2,3,3],eF=[0,1,2],tF=[3,4,5],nF=3;function rF(e,t){if(!KP.includes(e))throw JP(`tier`,e,KP);if(!qP.includes(t))throw JP(`type`,t,qP);let n=e,r=t,i=YP[n];return{tier:n,type:r,trunkRadialSegments:XP[i],canopyLayers:r===`conifer`?ZP[i]:0,canopySegments:QP[i],blobCount:r===`broadleaf`||r===`bush`?$P[i]:0,blobDetail:eF[i],branchCount:r===`dead`?tF[i]:r===`conifer`&&n===`high`?nF:0,hasCanopy:r!==`dead`,canopySway:n!==`simple`}}var iF=.02,aF={conifer:{trunkHeight:.4,trunkRadiusBottom:.05,trunkRadiusTop:.035},broadleaf:{trunkHeight:.42,trunkRadiusBottom:.05,trunkRadiusTop:.032},dead:{trunkHeight:.72,trunkRadiusBottom:.045,trunkRadiusTop:.018},bush:{trunkHeight:.14,trunkRadiusBottom:.045,trunkRadiusTop:.035}};function oF(e,t,n){let{trunkHeight:r,trunkRadiusBottom:i,trunkRadiusTop:a}=aF[e.type],o=[],s=new pd(a,i,r,e.trunkRadialSegments).toNonIndexed();if(s.translate(0,r/2,0),o.push(s),e.type===`dead`)for(let n=0;n<e.branchCount;n++){let r=.22+t.next()*.14,a=new pd(.006,.02,r,5).toNonIndexed();a.translate(0,r/2,0);let s=.7+t.next()*.6,c=n/e.branchCount*Math.PI*2+t.next()*.8,l=.34+(n+t.next())/e.branchCount*.34;a.applyMatrix4(new K().makeRotationY(c).multiply(new K().makeRotationX(s)).setPosition(Math.sin(c)*i*.6,l,Math.cos(c)*i*.6)),o.push(a)}let c=cF(o);return uF(c,new q(n),.7,1.05,t),c}function sF(e,t,n){if(!e.hasCanopy)return null;let r=[];if(e.type===`conifer`){let n=.74;for(let i=0;i<e.canopyLayers;i++){let a=i/e.canopyLayers,o=.3*(1-a*.62)*(.92+t.next()*.16),s=n/e.canopyLayers*1.7,c=new md(o,s,e.canopySegments).toNonIndexed();lF(c,t,iF),c.translate(0,.26+n*a+s/2,0),r.push(c)}for(let n=0;n<e.branchCount;n++){let i=new md(.06,.2,5).toNonIndexed(),a=n/Math.max(e.branchCount,1)*Math.PI*2+t.next(),o=1.1+t.next()*.4;i.applyMatrix4(new K().makeRotationY(a).multiply(new K().makeRotationX(o)).setPosition(Math.sin(a)*.22,.34+t.next()*.18,Math.cos(a)*.22)),r.push(i)}}else{let{trunkHeight:n}=aF[e.type];for(let i=0;i<e.blobCount;i++){let a=new gd((i===0?.3:.24-i*.02)*(.92+t.next()*.16),e.blobDetail).toNonIndexed();a.scale(1,.72,1),lF(a,t,iF);let o=i===0?0:.13,s=t.next()*Math.PI*2;a.translate(Math.cos(s)*o,n+.16+i*.1+t.next()*.05,Math.sin(s)*o),r.push(a)}}let i=cF(r);return uF(i,new q(n),.62,1.18,t),i}function cF(e){let t=0;for(let n of e)t+=n.getAttribute(`position`).count;let n=new Float32Array(t*3),r=new Float32Array(t*3),i=0;for(let t of e)n.set(t.getAttribute(`position`).array,i),r.set(t.getAttribute(`normal`).array,i),i+=t.getAttribute(`position`).count*3,t.dispose();let a=new Y;return a.setAttribute(`position`,new J(n,3)),a.setAttribute(`normal`,new J(r,3)),a}function lF(e,t,n){let r=e.getAttribute(`position`);for(let e=0;e<r.count;e++)r.setXYZ(e,r.getX(e)+t.range(-n,n),r.getY(e)+t.range(-n,n),r.getZ(e)+t.range(-n,n))}function uF(e,t,n,r,i){let a=e.getAttribute(`position`),o=new Float32Array(a.count*3),s=1/0,c=-1/0;for(let e=0;e<a.count;e++){let t=a.getY(e);t<s&&(s=t),t>c&&(c=t)}let l=Math.max(c-s,1e-6),u=new q;for(let e=0;e<a.count;e++){let c=(a.getY(e)-s)/l,d=(n+(r-n)*c)*(.96+i.next()*.08);u.copy(t).multiplyScalar(d),o[e*3]=u.r,o[e*3+1]=u.g,o[e*3+2]=u.b}e.setAttribute(`color`,new J(o,3))}var dF=500,fF=15e5,pF=[.8,1.2],mF=.28,hF=.12,gF=.055,_F=.11,vF=3,yF=101,bF=[.78,.7,.45],xF=.45,SF=.55,CF=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation`,wF=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark`,TF={high:{conifer:[`pine`,`pine`,`pine`],broadleaf:[`oak`,`ash`,`oak`],dead:[`ash`,`ash`,`ash`],bush:[`bush`,`bush`,`bush`]},medium:{conifer:[`pine-forest`,`pine-forest`,`pine-forest`],broadleaf:[`oak-forest`,`ash-forest`,`oak-forest`],dead:[`ash-forest`,`ash-forest`,`ash-forest`],bush:[`bush-forest`,`bush-forest`,`bush-forest`]}},EF=class e extends Q_{static typeName=`Tree3D`;static props={tier:{default:`medium`,options:KP},type:{default:`conifer`,options:qP},seed:{default:1},height:{default:6},count:{default:1},area:{default:[10,10]},trunkColor:{default:`#7a5a3a`},canopyColor:{default:`#4a7c3f`},leafTexture:{default:``},leafFadeStart:{default:0},leafFadeEnd:{default:0},leafShadows:{default:!0},drape:{default:null},terrain:{default:``,nodePath:!0}};tier=`medium`;type=`conifer`;seed=1;height=6;count=1;area=[10,10];trunkColor=`#7a5a3a`;canopyColor=`#4a7c3f`;leafTexture=``;leafFadeStart=0;leafFadeEnd=0;leafShadows=!0;drape=null;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(rF(t.tier,t.type),!(t.height>0))throw new L(`BAD_FORMAT`,`Tree3D '${e.name}' height must be > 0 meters, got ${t.height}.`,{prop:`height`});if(!Number.isInteger(t.count)||t.count<1||t.count>dF)throw new L(`BAD_FORMAT`,`Tree3D '${e.name}' count must be an integer in 1..${dF}, got ${t.count}.`,{prop:`count`});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new L(`BAD_FORMAT`,`Tree3D '${e.name}' area must be positive [x, z] meters, got ${JSON.stringify(t.area)}.`,{prop:`area`});if(t.leafFadeEnd!==0&&!(t.leafFadeEnd>t.leafFadeStart&&t.leafFadeStart>=0))throw new L(`BAD_FORMAT`,`Tree3D '${e.name}' needs leafFadeEnd > leafFadeStart >= 0 (the leaf LOD window) or 0/0 to disable, got start ${t.leafFadeStart}, end ${t.leafFadeEnd}.`,{prop:`leafFadeStart`});if(typeof t.leafShadows!=`boolean`)throw new L(`BAD_FORMAT`,`Tree3D '${e.name}' leafShadows must be a boolean, got ${JSON.stringify(t.leafShadows)}.`,{prop:`leafShadows`});if(t.drape!==null&&typeof t.drape!=`boolean`)throw new L(`BAD_FORMAT`,`Tree3D '${e.name}' drape must be true, false or null (null = auto: drape whenever the scene has a Terrain3D), got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new L(`BAD_FORMAT`,`Tree3D '${e.name}' terrain must be a node-path string (empty = auto-find), got ${JSON.stringify(t.terrain)}.`,{prop:`terrain`});if(t.tier===`simple`)return;let n=kF(t.tier,t.type),r=n*t.count;if(r>fF)throw new L(`BAD_FORMAT`,`Tree3D '${e.name}' blows the grove triangle budget: count ${t.count} × ${n} tris/tree (tier '${t.tier}', type '${t.type}') = ${r} > ${fF}. Lower count (max ${Math.floor(fF/n)} at this tier), drop tier to 'medium'/'simple', or split the grove into multiple nodes.`,{prop:`count`})}time=0;grove=null;variants=[];simpleTrunk=null;simpleCanopy=null;swayUniform=null;leafFadeUniform=null;loadedTextures=[];groveKey=``;_createObject3D(){return new Ec}_trunk(){return this.rebuildIfNeeded(),this.simpleTrunk??this.variants[0]?.branches}_canopy(){return this.rebuildIfNeeded(),this.simpleTrunk?this.simpleCanopy:this.variants[0]?.leaves??null}_variantMeshes(){return this.rebuildIfNeeded(),this.variants}update(e){this.time+=e,this.swayUniform&&(this.swayUniform.value=this.time),this.leafFadeUniform&&(this.leafFadeUniform.start.value=this.leafFadeStart,this.leafFadeUniform.end.value=this.leafFadeEnd)}assets=null;_syncObject3D(e=1,t=null){super._syncObject3D(e,t),this.assets=t,this.rebuildIfNeeded()}noteTextureError=(e,t)=>{this.assets?.textures.noteError(e,t)};rebuildIfNeeded(){this.grove||(this.grove=new Ec,this._ensureObject3D().add(this.grove));let e=JSON.stringify([this.tier,this.type,this.seed,this.height,this.count,this.area,this.trunkColor,this.canopyColor,this.leafTexture,this.leafShadows,this.leafFadeEnd>this.leafFadeStart,this.drape,this.terrain]);e===this.groveKey&&(this.simpleTrunk||this.variants.length>0)||(this.groveKey=e,this.disposeMeshes(),this.resolveDrape(),this.tier===`simple`?this.buildSimpleGrove():this.buildEzGrove())}resolveDrape(){if(this.drapeTerrain=null,this.drape===!1)return;let e=qA(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=KA(this);else if(this.terrain!==``)throw new L(`NODE_NOT_FOUND`,`Tree3D '${this.name}' drape terrain '${this.terrain}' is not a Terrain3D in the tree.`,{prop:`terrain`})}bedY(e,t){let n=this.drapeTerrain;return n?n.heightAt(this.drapeWorld[0]+e,this.drapeWorld[2]+t)-this.drapeWorld[1]:0}buildSimpleGrove(){let e=rF(this.tier,this.type),t=new Ee(this.seed),n=oF(e,t,this.trunkColor),r=sF(e,t,this.canopyColor),i=new Au(n,FF(),this.count);LF(i);let a=null;r&&(a=new Au(r,FF(),this.count),LF(a)),this.scatter(t,(e,t,n)=>{i.setMatrixAt(e,t),i.setColorAt(e,n),a?.setMatrixAt(e,t),a?.setColorAt(e,n)}),IF(i),a&&IF(a),this.simpleTrunk=i,this.simpleCanopy=a,this.grove.add(i),a&&this.grove.add(a)}buildEzGrove(){let e=TF[this.tier][this.type],t=Math.min(vF,this.count),n=Array.from({length:t},(e,n)=>Math.floor(this.count/t)+ +(n<this.count%t));this.swayUniform={value:this.time},this.leafFadeUniform=this.leafFadeEnd>this.leafFadeStart?{start:{value:this.leafFadeStart},end:{value:this.leafFadeEnd}}:null;let r=MF(this.canopyColor),i=null;typeof document<`u`&&typeof createImageBitmap==`function`&&(i=new Pf,i.setOptions({imageOrientation:`flipY`}));for(let a=0;a<t;a++){let t=n[a],o=e[a],s=wP(o);this.type===`dead`&&(s.leaves.count=0);let c=IP(s,this.seed+a*yF,1),l=this.buildBarkMaterial(o,i),u=new Au(c.branches,l,t);LF(u);let d=null;if(c.leaves){let e=new kd({color:r.clone().multiply(new q(bF[0],bF[1],bF[2])),roughness:1,side:2,vertexColors:!0,alphaTest:s.leaves.alphaTest}),n=this.leafTexture||AF(s.leaves.style);i&&(e.map=OF(i,n,e=>{e.colorSpace=Ro,e.flipY=!1},e=>jF(e),this.noteTextureError)),Rj(e,this.swayUniform,xF,this.leafFadeUniform??void 0),d=new Au(c.leaves,e,t),d.userData.incantoWaterPassSkip=!0,LF(d),this.leafShadows||(d.castShadow=!1)}this.variants.push({branches:u,leaves:d}),this.grove.add(u),d&&this.grove.add(d)}let a=Array(t).fill(0),o=new Ee(this.seed);this.scatter(o,(e,n,r)=>{let i=e%t,o=this.variants[i],s=a[i];a[i]=s+1,o.branches.setMatrixAt(s,n),o.branches.setColorAt(s,r),o.leaves?.setMatrixAt(s,n),o.leaves?.setColorAt(s,r)});for(let e of this.variants)IF(e.branches),e.leaves&&IF(e.leaves)}buildBarkMaterial(t,n){if(this.type===`dead`||!n)return new kd({color:new q(this.trunkColor),roughness:1});let r=EP(t),i=new kd({color:this.trunkColor===e.props.trunkColor?.default?new q(r.tint):PF(this.trunkColor),roughness:1});return Lj(i,SF),i.map=this.loadBarkTexture(n,r,`color`,!0),i.normalMap=this.loadBarkTexture(n,r,`normal`,!1),i.roughnessMap=this.loadBarkTexture(n,r,`roughness`,!1),i}loadBarkTexture(e,t,n,r){return OF(e,`${wF}/${t.texture}_${n}_1k.jpg`,e=>{e.wrapS=la,e.wrapT=la,e.repeat.set(t.repeat[0],t.repeat[1]),e.anisotropy=4,e.flipY=!1,r&&(e.colorSpace=Ro)},void 0,this.noteTextureError)}scatter(e,t){let n=(this.area[0]??0)/2,r=(this.area[1]??0)/2;for(let i=0;i<this.count;i++){let a=this.count===1?0:e.range(-n,n),o=this.count===1?0:e.range(-r,r);BF.set(a,this.drape?this.bedY(a,o):0,o),VF.setFromAxisAngle(RF,e.range(0,Math.PI*2));let s=this.height*e.range(pF[0],pF[1]),c=s*e.range(.9,1.1);HF.set(c,s,c),zF.compose(BF,VF,HF),UF.setHSL(mF,hF,.92).offsetHSL(e.range(-.055,gF),0,e.range(-.11,_F)),t(i,zF,UF)}}disposeMeshes(){let e=[this.simpleTrunk,this.simpleCanopy];for(let t of this.variants)e.push(t.branches,t.leaves);let t=new Set;for(let n of e)n&&(n.removeFromParent(),n.geometry.dispose(),t.add(n.material),n.dispose());for(let e of t)e.dispose();for(let e of this.loadedTextures)e.dispose();this.loadedTextures=[],this.simpleTrunk=null,this.simpleCanopy=null,this.variants=[],this.swayUniform=null,this.leafFadeUniform=null}free(){this.disposeMeshes(),this.grove=null,super.free()}},DF=new Map;function OF(e,t,n,r,i){let a=DF.get(t);if(a)return a;let o=new qs;return n(o),e.load(t,e=>{o.image=e,r?r(o):o.needsUpdate=!0},void 0,e=>i?.(t,e)),DF.set(t,o),o}function kF(e,t){let n=0;for(let r of new Set(TF[e][t]??[])){let e=wP(r);t===`dead`&&(e.leaves.count=0),n=Math.max(n,xP(e).total)}return n}function AF(e){return`${CF}/${e}_color.png`}function jF(e){let t=e.image;if(!t||typeof document>`u`)return;let n=document.createElement(`canvas`);n.width=t.naturalWidth||t.width,n.height=t.naturalHeight||t.height;let r=n.getContext(`2d`,{willReadFrequently:!0});if(!r)return;r.drawImage(t,0,0);let i;try{i=r.getImageData(0,0,n.width,n.height)}catch{return}let a=i.data,o=0,s=0,c=0,l=0;for(let e=0;e<a.length;e+=4)a[e+3]>240&&(o+=a[e],s+=a[e+1],c+=a[e+2],l++);if(l!==0){o=Math.round(o/l),s=Math.round(s/l),c=Math.round(c/l);for(let e=0;e<a.length;e+=4)a[e+3]<=240&&(a[e]=o,a[e+1]=s,a[e+2]=c);r.putImageData(i,0,0),e.image=n,e.needsUpdate=!0}}function MF(e){let t=new q(e),n=Math.max(t.r,t.g,t.b);return n>0?t.multiplyScalar(1/n):t.setRGB(1,1,1),t.lerp(NF,.18)}var NF=new q(1,1,1);function PF(e){let t=new q(e),n=Math.max(t.r,t.g,t.b);return n>0?t.multiplyScalar(1/n):t.setRGB(1,1,1),t}function FF(){return new kd({vertexColors:!0,roughness:1,flatShading:!0})}function IF(e){e.instanceMatrix.needsUpdate=!0,e.instanceColor&&(e.instanceColor.needsUpdate=!0),GA(e)}function LF(e){e.castShadow=!0,e.receiveShadow=!0}var RF=new W(0,1,0),zF=new K,BF=new W,VF=new U,HF=new W,UF=new q,WF=[[[.4,.4,.4],[.4,.4,.4],[.4,.4,.4],[.4,.4,.4],[.4,.4,.4],[.4,.4,.4]],[[.6,.3,0],[.6,.3,0],[.6,.3,0],[.6,.3,0],[0,.8,0],[.6,.3,0]],[[.6,.3,0],[.6,.3,0],[.6,.3,0],[.6,.3,0],[.6,.3,0],[.6,.3,0]],[[.6,.55,.5],[.55,.5,.45],[.5,.45,.4],[.55,.5,.45],[.65,.6,.55],[.5,.45,.4]],[[.45,.45,.4],[.4,.4,.35],[.35,.35,.3],[.4,.4,.35],[.5,.5,.45],[.35,.35,.3]],[[.2,.2,.2],[.2,.2,.2],[.2,.2,.2],[.2,.2,.2],[.2,.2,.2],[.2,.2,.2]],[[.8,.5,.2],[.75,.45,.15],[.7,.4,.1],[.75,.45,.15],[.85,.55,.25],[.7,.4,.1]],[[0,.7,.1],[0,.65,.1],[0,.6,.1],[0,.65,.1],[0,.75,.1],[0,.6,.1]],[[.3,.3,.3],[.3,.3,.3],[.3,.3,.3],[.3,.3,.3],[.3,.3,.3],[.3,.3,.3]],[[0,0,.7],[0,0,.7],[0,0,.7],[0,0,.7],[0,.2,.9],[0,0,.6]],[[.9,.3,0],[.9,.3,0],[.9,.3,0],[.9,.3,0],[1,.4,0],[.7,.2,0]],[[.9,.8,.2],[.85,.75,.18],[.85,.75,.18],[.85,.75,.18],[.95,.85,.25],[.85,.75,.18]],[[.6,.6,.6],[.55,.55,.55],[.5,.5,.5],[.55,.55,.55],[.65,.65,.65],[.5,.5,.5]],[[.7,.7,.4],[.65,.65,.35],[.6,.6,.3],[.65,.65,.35],[.75,.75,.45],[.6,.6,.3]],[[.7,.5,.5],[.65,.45,.45],[.6,.4,.4],[.65,.45,.45],[.75,.55,.55],[.6,.4,.4]],[[.35,.3,.25],[.3,.25,.2],[.25,.2,.15],[.3,.25,.2],[.4,.35,.3],[.25,.2,.15]],[[.5,.3,0],[.5,.3,0],[.5,.3,0],[.5,.3,0],[.7,.4,.1],[.7,.4,.1]],[[0,.5,0],[0,.45,0],[0,.45,0],[0,.45,0],[0,.6,0],[0,.4,0]],[[.2,.8,.8],[.15,.7,.7],[.1,.6,.6],[.15,.7,.7],[.3,.9,.9],[.1,.6,.6]],[[1,.5,.8],[.9,.4,.7],[.8,.3,.6],[.9,.4,.7],[1,.6,.9],[.8,.3,.6]],[[1,.9,.3],[.95,.85,.25],[.9,.8,.2],[.95,.85,.25],[1,1,.4],[.9,.8,.2]],[[1,0,0],[.9,0,0],[.8,0,0],[.9,0,0],[1,.2,.2],[.8,0,0]],[[.6,.4,.2],[.5,.3,.15],[.4,.25,.1],[.5,.3,.15],[.7,.45,.25],[.4,.25,.1]],[[.6,.2,.8],[.5,.15,.7],[.4,.1,.6],[.5,.15,.7],[.7,.25,.9],[.4,.1,.6]],[[1,.8,0],[.95,.75,0],[.95,.75,0],[.95,.75,0],[1,.9,0],[.9,.7,0]],[[.6,.65,.7],[.55,.6,.65],[.5,.55,.6],[.55,.6,.65],[.65,.7,.75],[.5,.55,.6]]],GF=2e5,KF=class extends Q_{static typeName=`VoxelGrid3D`;static signals=[`blocksChanged`];static props={voxels:{default:[]}};voxels=[];appliedVoxels=null;map=new Map;mesh=null;dirty=!1;blockCount(){return this.map.size}tileAt(e,t,n){return this.map.get(`${e},${t},${n}`)}setBlocks(e){this.map.clear();for(let t of e)this.map.set(`${t.x},${t.y},${t.z}`,t.tile);this.dirty=!0,this.emit(`blocksChanged`)}addBlock(e){this.map.set(`${e.x},${e.y},${e.z}`,e.tile),this.dirty=!0,this.emit(`blocksChanged`)}removeBlockAt(e,t,n){let r=this.map.delete(`${e},${t},${n}`);return r&&(this.dirty=!0,this.emit(`blocksChanged`)),r}blocks(){let e=[];for(let[t,n]of this.map){let[r,i,a]=t.split(`,`).map(Number);e.push({x:r,y:i,z:a,tile:n})}return e}_createObject3D(){let e=new dd(1,1,1),t=new Dd({vertexShader:JF,fragmentShader:YF});this.mesh=new Au(e,t,GF),this.mesh.count=0,this.mesh.frustumCulled=!1;for(let e of qF)this.mesh.geometry.setAttribute(e,new Su(new Float32Array(GF*3),3));return this.dirty=!0,this.mesh}update(){if(this.voxels.length>0&&this.voxels!==this.appliedVoxels&&(this.appliedVoxels=this.voxels,this.setBlocks(this.voxels.map(e=>({x:e[0]??0,y:e[1]??0,z:e[2]??0,tile:e[3]??0})))),!this.dirty||!this.mesh)return;this.dirty=!1;let e=new K,t=0;for(let[n,r]of this.map){if(t>=GF)break;let[i,a,o]=n.split(`,`).map(Number);e.setPosition(i,a,o),this.mesh.setMatrixAt(t,e);let s=WF[r]??WF[0];for(let e=0;e<6;e++){let n=this.mesh.geometry.getAttribute(qF[e]),r=s[e];n.setXYZ(t,r[0],r[1],r[2]),n.needsUpdate=!0}t++}this.mesh.count=t,this.mesh.instanceMatrix.needsUpdate=!0}free(){let e=this._builtObject3D;e&&e.traverse(e=>{let t=e;t.geometry?.dispose();let n=t.material,r=Array.isArray(n)?n:n?[n]:[];for(let e of r)e.dispose?.()}),super.free()}},qF=[`colorFront`,`colorRight`,`colorBack`,`colorLeft`,`colorTop`,`colorBottom`],JF=`
|
|
7914
7914
|
attribute vec3 colorFront;
|
|
7915
7915
|
attribute vec3 colorRight;
|
|
7916
7916
|
attribute vec3 colorBack;
|
|
@@ -7942,7 +7942,7 @@ void main() {
|
|
|
7942
7942
|
if (vUv2.x < edge || vUv2.x > 1.0 - edge || vUv2.y < edge || vUv2.y > 1.0 - edge) color *= 0.75;
|
|
7943
7943
|
gl_FragColor = vec4(color, 1.0);
|
|
7944
7944
|
}
|
|
7945
|
-
`;function XF(){Or(),z(
|
|
7945
|
+
`;function XF(){Or(),z(Q_),z(nN),z(ED),z(NM),z(lk),z(AM),z(uk),z(gk),z(aA),z(KF),z(ID),z(gP),z(_k),z(wk),z(AD),z(fP),z(hO),z(Uv),z(av),z(_M),z(ij),z(EF),z(QM),z(Bk),z(jM),z(MM),z(ev),z(nv),z(tv),z(rv)}var ZF={slowMs:20,fastMs:13,minScale:.6,step:.15,window:45},QF=class{opts;samples=[];scale=1;pinned;constructor(e={}){this.opts={...ZF,...e},this.pinned={slowMs:e.slowMs!==void 0,fastMs:e.fastMs!==void 0}}setTarget(e){let t=1e3/(e>0?e:60);this.pinned.slowMs||(this.opts.slowMs=t*1.2),this.pinned.fastMs||(this.opts.fastMs=t*.8)}current(){return this.scale}push(e){if(!(e>0)||!Number.isFinite(e)||(this.samples.push(e),this.samples.length<this.opts.window))return null;let t=[...this.samples].sort((e,t)=>e-t),n=t[Math.floor(t.length/2)];this.samples=[];let r=this.scale;return n>this.opts.slowMs?this.scale=Math.max(this.opts.minScale,this.scale-this.opts.step):n<this.opts.fastMs&&this.scale<1&&(this.scale=Math.min(1,this.scale+this.opts.step)),this.scale===r?null:this.scale}reset(){this.samples=[]}},$F=`
|
|
7946
7946
|
varying vec2 vUv;
|
|
7947
7947
|
void main() {
|
|
7948
7948
|
vUv = uv;
|
|
@@ -8426,7 +8426,7 @@ void main() {
|
|
|
8426
8426
|
#include <tonemapping_fragment>
|
|
8427
8427
|
#include <colorspace_fragment>
|
|
8428
8428
|
|
|
8429
|
-
}`};var _I=`https://agent8-games.verse8.io/assets/3D/default/textures/hdri`,vI={apartment:`lebombo_1k.hdr`,city:`potsdamer_platz_1k.hdr`,dawn:`kiara_1_dawn_1k.hdr`,forest:`forest_slope_1k.hdr`,lobby:`st_fagans_interior_1k.hdr`,night:`dikhololo_night_1k.hdr`,park:`rooitou_park_1k.hdr`,studio:`studio_small_03_1k.hdr`,sunset:`venice_sunset_1k.hdr`,warehouse:`empty_warehouse_01_1k.hdr`};function yI(e){if(typeof e.hdri==`string`&&e.hdri!==``)return e.hdri;if(typeof e.preset==`string`){let t=vI[e.preset];if(!t)throw Error(`Unknown environment preset '${e.preset}'. Available: ${Object.keys(vI).join(`, `)}.`);return`${_I}/${t}`}return null}var bI=75,xI=class{scene;ambient=new jf(`#ffffff`,0);envKey=null;config=ei(void 0);hdriUrl=null;hdriTexture=null;_sky=null;skyKey=``;skyEnvKey=``;skyEnvTarget=null;fog=new Pc(`#ffffff`,1,1e3);underwaterFog=null;underwaterBg=new q;onHdriError=null;constructor(e){this.scene=e,this.scene.add(this.ambient)}get sunDirection(){return this.config.sky?ni(this.config.sky):null}get clouds(){return this.config.clouds}get bloom(){return this.config.bloom}get post(){return this.config.post}get sceneFog(){return this.scene.fog instanceof Pc?this.scene.fog:null}apply(e,t){let n=e===void 0?``:JSON.stringify(e);n!==this.envKey&&(this.envKey=n,this.config=ei(e));let r=this.config,i=e?.ambient;if(this.ambient.color.set(i?.color??`#ffffff`),this.ambient.intensity=i?.intensity??0,t&&(t.toneMappingExposure=r.exposure,t.shadowMap.enabled=r.shadows!==!1,r.shadows!==!1&&r.shadows!==null&&r.shadows.static?t.shadowMap.autoUpdate&&(t.shadowMap.autoUpdate=!1,t.shadowMap.needsUpdate=!0):t.shadowMap.autoUpdate||(t.shadowMap.autoUpdate=!0)),this.applyHdri(e),this.applySky(r.sky,t),this._sky&&(this._sky.visible=!0),this.applyFog(r),this.scene.environment=this.hdriTexture??this.skyEnvTarget?.texture??null,this.scene.environmentIntensity=(this.scene.environment===this.skyEnvTarget?.texture&&this.skyEnvTarget?.55:1)*SI(e?.iblIntensity),e?.skybox===!0&&this.hdriTexture)this.scene.background=this.hdriTexture;else{let t=e?.background;this.scene.background=typeof t==`string`?new q(t):null}}applySunLight(e,t=null){if(!e)return;let n=this.sunDirection;if(t){let r=e.position.length()||100,i,a,o;if(n)[i,a,o]=n;else{i=e.position.x-e.target.position.x,a=e.position.y-e.target.position.y,o=e.position.z-e.target.position.z;let t=Math.hypot(i,a,o)||1;i/=t,a/=t,o/=t}e.target.position.set(t.x,t.y,t.z),e.target.updateMatrixWorld(),e.position.set(t.x+i*r,t.y+a*r,t.z+o*r)}else if(n){let t=e.position.length()||100;e.position.set(n[0],n[1],n[2]).multiplyScalar(t)}let r=this.config.shadows;if(r&&typeof r==`object`){if(!e.castShadow){let t=e.shadow.camera;`left`in t&&t.left===-5&&(t.left=-75,t.right=bI,t.top=bI,t.bottom=-75,t.near=.5,t.far=500,t.updateProjectionMatrix()),e.castShadow=!0}e.shadow.mapSize.x!==r.mapSize&&(e.shadow.mapSize.set(r.mapSize,r.mapSize),e.shadow.map?.dispose(),e.shadow.map=null),e.shadow.radius=r.radius}}applyUnderwater(e){e&&(this.underwaterFog||=new Pc(`#000000`,.5,e.visibility),this.underwaterFog.color.set(e.color),this.underwaterFog.near=.5,this.underwaterFog.far=e.visibility,this.scene.fog=this.underwaterFog,this.scene.background=this.underwaterBg.set(e.color),this._sky&&(this._sky.visible=!1))}applyHdri(e){let t=yI(e??{});t!==this.hdriUrl&&(this.hdriUrl=t,this.hdriTexture?.dispose(),this.hdriTexture=null,t&&new hI().load(t,e=>{if(this.hdriUrl!==t){e.dispose();return}e.mapping=303,this.hdriTexture=e},void 0,e=>{this.onHdriError?.(t,e)}))}applySky(e,t){let n=e?JSON.stringify(e):``;if(n!==this.skyKey&&(this.skyKey=n,this._sky&&=(this.scene.remove(this._sky),this._sky.material.dispose(),this._sky.geometry.dispose(),null),e)){this._sky=new gI,this._sky.scale.setScalar(45e4);let t=this._sky.material.uniforms;(t.sunPosition?.value).set(...e.sunPosition),t.turbidity&&(t.turbidity.value=e.turbidity),t.rayleigh&&(t.rayleigh.value=e.rayleigh),this.scene.add(this._sky)}if(e&&t&&this._sky&&this.skyEnvKey!==n){this.skyEnvKey=n,this.skyEnvTarget?.dispose();let e=new jp(t),r=new Fc;r.add(this._sky),this.skyEnvTarget=e.fromScene(r),e.dispose(),this.scene.add(this._sky)}!e&&this.skyEnvTarget&&(this.skyEnvTarget.dispose(),this.skyEnvTarget=null,this.skyEnvKey=``)}applyFog(e){if(!e.fog){this.scene.fog=null;return}let t=e.fog.color||(e.sky?ri(e.sky):`#cfd8e0`);this.fog.color.set(t),this.fog.near=e.fog.near,this.fog.far=e.fog.far,this.scene.fog=this.fog}dispose(){this.hdriTexture?.dispose(),this.hdriTexture=null,this.skyEnvTarget?.dispose(),this.skyEnvTarget=null,this._sky&&=(this.scene.remove(this._sky),this._sky.material.dispose(),this._sky.geometry.dispose(),null)}};function SI(e){if(e===void 0)return 1;if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw new L(`BAD_FORMAT`,`environment.iblIntensity must be a finite number >= 0 (multiplies the image-based ambience: sky-derived base 0.55, HDRI base 1; default 1), got ${JSON.stringify(e)}.`,{prop:`iblIntensity`});return e}var CI=new Xc,wI=new Xc,TI=new K,EI=new K,DI=new W,OI=Array.from({length:8},()=>new W),kI=.4,AI=new Float32Array(72),jI=[[0,0,0],[1,0,0],[1,0,1],[0,0,1],[0,1,0],[1,1,0],[1,1,1],[0,1,1]],MI=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]];function NI(e,t){t.makeEmpty(),TI.copy(e.matrixWorld).invert(),e.traverse(e=>{let n=e,r;n.isInstancedMesh?(n.boundingBox||n.computeBoundingBox?.(),r=n.boundingBox):n.geometry&&(n.geometry.boundingBox||n.geometry.computeBoundingBox(),r=n.geometry.boundingBox),r&&(wI.copy(r).applyMatrix4(EI.multiplyMatrices(TI,e.matrixWorld)),t.union(wI))})}function PI(e){if(!(e instanceof Z_))return null;let t=e._ensureObject3D();t.updateWorldMatrix(!0,!0),NI(t,CI);let n=!0;CI.isEmpty()?(n=!1,DI.setFromMatrixPosition(t.matrixWorld),CI.min.set(DI.x-kI,DI.y-kI,DI.z-kI),CI.max.set(DI.x+kI,DI.y+kI,DI.z+kI)):CI.expandByScalar(.02);let{min:r,max:i}=CI;for(let e=0;e<8;e++){let[a,o,s]=jI[e],c=OI[e].set(a?i.x:r.x,o?i.y:r.y,s?i.z:r.z);n&&c.applyMatrix4(t.matrixWorld)}let a=0;for(let[e,t]of MI){let n=OI[e],r=OI[t];AI[a++]=n.x,AI[a++]=n.y,AI[a++]=n.z,AI[a++]=r.x,AI[a++]=r.y,AI[a++]=r.z}return AI}function FI(e){return e.spatial===!0&&typeof e._setSpatialPose==`function`}function II(){let e=new Set,t=[],n=[],r=[];return{visited:e,cameras:t,renderHooks:n,emitters:r,state:{visited:e,cameras:t,renderHooks:n,emitters:r,assets:void 0,sunDirection:null,sunLight:null,alpha:1,ignoreStatic:!1,quality:null}}}function LI(e,t,n,r,i){let a=i??II();a.visited.clear(),a.cameras.length=0,a.renderHooks.length=0,a.emitters.length=0;let o=a.state;o.assets=n,o.sunDirection=r?.sunDirection??null,o.ignoreStatic=r?.ignoreStatic===!0,o.sunLight=null,o.alpha=r?.alpha??1,o.quality=r?.quality??null,UI(e,t,o),KI(t,a.visited);let s=null;for(let e=0;e<a.cameras.length;e++){let t=a.cameras[e];if(t.current){s=t;break}}s||=a.cameras[0]??null;let c=s?s._ensureObject3D():null;return HI(a.emitters,c),{activeCamera:c,renderHooks:a.renderHooks,sunLight:o.sunLight}}var RI=new W,zI=new W,BI=new W,VI=new W;function HI(e,t){if(e.length===0||!t)return;t.updateWorldMatrix(!0,!1),t.getWorldPosition(zI),t.getWorldDirection(BI),VI.set(0,1,0).applyQuaternion(t.quaternion);let n={position:[zI.x,zI.y,zI.z],forward:[BI.x,BI.y,BI.z],up:[VI.x,VI.y,VI.z]};for(let{node:t,parent:r}of e)r.updateWorldMatrix(!0,!1),r.getWorldPosition(RI),t._setSpatialPose({position:[RI.x,RI.y,RI.z],listener:n})}function UI(e,t,n){let r=t;if(e instanceof Z_){let i=e._ensureObject3D();if(e.static&&!n.ignoreStatic&&i.userData.incantoStaticSynced===!0){i.userData.incantoStatic=!0,n.visited.add(i);return}if(i.parent!==t&&t.add(i),n.quality){let t=e._applyQualityCaps;typeof t==`function`&&t.call(e,n.quality)}if(e._syncObject3D(n.alpha,n.assets??null),n.assets&&e instanceof QM&&e._syncModel(n.assets),typeof e._onRender3D==`function`&&n.renderHooks.push(e),n.sunDirection){let t=e._applySunDirection;typeof t==`function`&&t.call(e,n.sunDirection)}e instanceof jM&&(!n.sunLight||e.intensity>n.sunLight.intensity)&&(n.sunLight=e),n.visited.add(i),e instanceof Bk&&n.cameras.push(e),r=i}else FI(e)&&n.emitters.push({node:e,parent:r});for(let t of e.children)UI(t,r,n);if(e instanceof Z_){let t=e._ensureObject3D();e.static&&!n.ignoreStatic?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0,GI(e)):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}var WI=new WeakSet;function GI(e){if(WI.has(e))return;WI.add(e);let t=[],n=e=>{(typeof e._onRender3D==`function`||e instanceof Bk)&&t.push(`${e.name} (${e.constructor.typeName??`?`})`);for(let t of e.children)n(t)};n(e),t.length>0&&console.warn(`[incanto] static subtree '${e.name}' freezes animated/per-frame nodes: ${t.join(`, `)} — they will stop updating. Unmark static or move them out.`)}function KI(e,t){let n=e.children;for(let r=n.length-1;r>=0;r--){let i=n[r];i.userData.incantoNode&&!t.has(i)?e.remove(i):i.userData.incantoStatic!==!0&&KI(i,t)}}var qI=120,JI=class{viewOverride=null;overrideCam=new Cf(60,1,.05,5e3);lastCamera=null;lastSize={w:1,h:1};webgl;threeScene=new Fc;environment=(()=>{let e=new xI(this.threeScene);return e.onHdriError=(e,t)=>{this.assets.textures.noteError(e,t),Nt(this.engine,`error`,`[incanto] the scene's lighting (${e}) could not be loaded — nothing else lights it.`)},e})();engine;disconnect;canvas;assets;ownsAssets;loadedAssetScenes=new WeakSet;compiledScene=null;warmCamera=null;deferCompile=!1;syncScratch=II();ignoreStatic=!1;renderCtx=null;causticsTarget=null;causticsScene=null;causticsUniforms=null;cloudsTarget=null;cloudsHalfTarget=null;cloudsBlurTarget=null;cloudsScene=null;cloudsUniforms=null;cloudsBlurScene=null;cloudsBlurUniforms=null;cloudsCompositeScene=null;cloudsCompositeUniforms=null;bloomTarget=null;bloomBrightTarget=null;bloomBlurTarget=null;bloomBrightScene=null;bloomBrightUniforms=null;bloomBlurScene=null;bloomBlurUniforms=null;bloomCompositeScene=null;bloomCompositeUniforms=null;constructor(e){this.canvas=e.canvas,this.engine=e.engine,this.ownsAssets=!e.assets,this.assets=e.assets??new pD(this.engine);let t=kr(e.engine.scene?.environment,{antialias:e.qualityDefaults?.antialias??!0,pixelRatio:e.qualityDefaults?.pixelRatio??Math.min(globalThis.devicePixelRatio??1,2),preserveDrawingBuffer:!1},globalThis.devicePixelRatio??1,{pixelRatio:e.pixelRatio,preserveDrawingBuffer:e.preserveDrawingBuffer});this.webgl=new wg({canvas:e.canvas,antialias:t.antialias,preserveDrawingBuffer:t.preserveDrawingBuffer}),this.webgl.info.autoReset=!1,this.engine.picker=(e,t)=>this.pick(e,t),this.basePixelRatio=t.pixelRatio,this.webgl.setPixelRatio(t.pixelRatio),this.adaptive=e.adaptiveResolution===!1?null:new QF,this.webgl.shadowMap.enabled=!0,this.webgl.shadowMap.type=1,this.webgl.toneMapping=4,this.webgl.toneMappingExposure=1,this.debugLines=new Zu(new Y,new zu({color:`#00ff6e`,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.threeScene.add(this.debugLines),this.selectionLines=new Zu(new Y,new zu({color:`#ffb020`,transparent:!0,depthTest:!1})),this.selectionLines.frustumCulled=!1,this.selectionLines.renderOrder=1e4,this.selectionLines.visible=!1,this.threeScene.add(this.selectionLines),this.disconnect=this.engine.updated.connect(()=>{let e=performance.now();this.render(),this.engine.noteRenderMs(performance.now()-e)})}basePixelRatio;adaptive;renderScale=1;adaptiveScale=1;lastFrameAt=0;debugLines;selectionLines;syncSelectionOutline(){let e=this.engine.debugSelection;e&&e.tree!==this.engine.scene?.tree&&(this.engine.debugSelection=null);let t=this.engine.debugSelection,n=t?PI(t):null;if(this.selectionLines.visible=n!==null,n){this.selectionLines.geometry.setAttribute(`position`,new J(n,3));let e=this.selectionLines.geometry.getAttribute(`position`);e.needsUpdate=!0}}syncDebugLines(){let e=null;for(let t of Pb(`3d`,this.engine))if(e=t.debugLines(),e)break;this.debugLines.visible=e!==null,e&&this.debugLines.geometry.setAttribute(`position`,new J(e,3))}governResolution(){let e=this.adaptive;if(!e)return;let t=globalThis.performance?.now?.()??0,n=this.lastFrameAt;if(this.lastFrameAt=t,n===0)return;let r=t-n;if(r>500){e.reset();return}let i=e.push(r);i!==null&&(this.adaptiveScale=i,this.applyPixelRatio())}setRenderScale(e){let t=Math.min(2,Math.max(.25,e>0?e:1));t!==this.renderScale&&(this.renderScale=t,this.applyPixelRatio())}setFrameTarget(e){this.adaptive?.setTarget(e)}applyPixelRatio(){this.webgl.setPixelRatio(this.basePixelRatio*this.renderScale*this.adaptiveScale);let e=this.lastSize;e.w>0&&e.h>0&&this.webgl.setSize(e.w,e.h,!1)}deferFirstCompile(){this.deferCompile=!0}async warmUp(e){this.deferCompile=!1;let t=this.warmCamera;if(!t)return;let n=[];this.threeScene.traverse(e=>{(e.isMesh||e.isPoints)&&n.push(e)});let r=n.filter(e=>e.visible);if(r.length===0){this.webgl.compile(this.threeScene,t),e?.(1);return}for(let e of r)e.visible=!1;let i=Math.min(YI,r.length),a=Math.ceil(r.length/i);try{for(let n=0;n<i;n++){for(let e=n*a;e<Math.min((n+1)*a,r.length);e++)r[e].visible=!0;this.webgl.compile(this.threeScene,t),e?.((n+1)/i),await CD()}}finally{for(let e of r)e.visible=!0}}render(){let e=this.engine.scene;if(!e)return;this.webgl.info.reset(),this.governResolution(),this.syncDebugLines(),this.syncSelectionOutline(),e.assets&&!this.loadedAssetScenes.has(e)&&(this.assets.load(e.assets),this.loadedAssetScenes.add(e)),this.environment.apply(e.environment,this.webgl);let{activeCamera:t,renderHooks:n,sunLight:r}=LI(e.root,this.threeScene,this.assets,{sunDirection:this.environment.sunDirection,alpha:this.engine.interpolationAlpha,ignoreStatic:this.ignoreStatic,quality:Rn(this.engine.settings.get(`quality`))},this.syncScratch),i=t;if(this.viewOverride){let[e,t,n]=this.viewOverride.position,[r,a,o]=this.viewOverride.target;this.overrideCam.position.set(e,t,n),this.overrideCam.lookAt(ZI.set(r,a,o)),i=this.overrideCam}if(!i)return;this.lastCamera=i,i.updateWorldMatrix(!0,!1);let a=i.getWorldPosition(rL),o=r?r._ensureObject3D():null,s=!!o&&r.shadowFollowsCamera===!0;this.environment.applySunLight(o,s?a:null),this.compiledScene!==e&&!this.deferCompile&&(this.compiledScene=e,this.webgl.compile(this.threeScene,i)),this.warmCamera=i;let c=this.canvas.clientWidth||this.canvas.width,l=this.canvas.clientHeight||this.canvas.height,u=this.webgl.getSize(XI);(u.x!==c||u.y!==l)&&this.webgl.setSize(c,l,!1),this.lastSize={w:c,h:l};let d=l===0?1:c/l;i.aspect!==d&&(i.aspect=d,i.updateProjectionMatrix()),this.renderCtx||={gl:this.webgl,scene:this.threeScene,camera:i};let f=this.renderCtx;f.camera=i,o?(o.updateWorldMatrix(!0,!1),o.target.updateWorldMatrix(!0,!1),f.sunDir=$I.setFromMatrixPosition(o.matrixWorld).sub(eL.setFromMatrixPosition(o.target.matrixWorld)).normalize()):f.sunDir=null;for(let e=0;e<n.length;e++)n[e]?._onRender3D(f);let p=null;for(let e=0;e<n.length;e++){let t=n[e].underwaterAt?.(a.x,a.y,a.z);if(t){p=t;break}}this.environment.applyUnderwater(p);let m=this.environment.clouds,h=this.environment.bloom,g=this.environment.post;p?.caustics.enabled?this.renderWithCaustics(i,p):m&&!p?this.renderWithClouds(i,m,o):(h||g)&&!p?this.renderWithBloom(i,h,g):this.webgl.render(this.threeScene,i),this.drainFrameCapture()}captureFrame(){return new Promise((e,t)=>{this.pendingCaptures.push({resolve:e,reject:t}),setTimeout(()=>{if(this.pendingCaptures.length>0)try{this.render()}catch(e){let t=e instanceof Error?e:Error(String(e));for(let e of this.pendingCaptures.splice(0))e.reject(t)}},qI)})}pendingCaptures=[];drainFrameCapture(){if(this.pendingCaptures.length===0)return;let e=this.pendingCaptures;this.pendingCaptures=[];try{let t=this.webgl.getContext(),n=this.webgl.domElement.width,r=this.webgl.domElement.height,i=new Uint8Array(n*r*4);this.webgl.setRenderTarget(null),t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,i),oL(i,n,r);for(let t of e)t.resolve({pixels:i,width:n,height:r})}catch(t){let n=t instanceof Error?t:Error(String(t));for(let t of e)t.reject(n)}}renderWithBloom(e,t,n=null){let r=this.webgl.getDrawingBufferSize(XI),i=Math.max(1,r.x),a=Math.max(1,r.y),o=Math.max(1,Math.ceil(i/2)),s=Math.max(1,Math.ceil(a/2));if(this.bloomTarget&&(this.bloomTarget.width!==i||this.bloomTarget.height!==a)&&(this.bloomTarget.dispose(),this.bloomTarget=null,this.bloomBrightTarget?.dispose(),this.bloomBrightTarget=null,this.bloomBlurTarget?.dispose(),this.bloomBlurTarget=null),this.bloomTarget||(this.bloomTarget=new Xs(i,a,{type:Ta,samples:4}),this.bloomBrightTarget=new Xs(o,s,{type:Ta}),this.bloomBlurTarget=new Xs(o,s,{type:Ta})),!this.bloomBrightScene){let e=iI();this.bloomBrightScene=new Fc,this.bloomBrightScene.add(e.mesh),this.bloomBrightUniforms=e.uniforms;let t=aI();this.bloomBlurScene=new Fc,this.bloomBlurScene.add(t.mesh),this.bloomBlurUniforms=t.uniforms;let n=oI();this.bloomCompositeScene=new Fc,this.bloomCompositeScene.add(n.mesh),this.bloomCompositeUniforms=n.uniforms}let c=this.bloomBrightTarget,l=this.bloomBlurTarget;if(this.webgl.setRenderTarget(this.bloomTarget),this.webgl.render(this.threeScene,e),t){let n=this.bloomBrightUniforms;n.tScene.value=this.bloomTarget.texture,n.uThreshold.value=t.threshold,this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBrightScene,e);let r=this.bloomBlurUniforms;r.tTex.value=c.texture,r.uDir.value.set(1/o,0),this.webgl.setRenderTarget(l),this.webgl.render(this.bloomBlurScene,e),r.tTex.value=l.texture,r.uDir.value.set(0,1/s),this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBlurScene,e)}let u=this.bloomCompositeUniforms;u.tScene.value=this.bloomTarget.texture,u.tBloom.value=t?c.texture:this.bloomTarget.texture,u.uStrength.value=t?t.strength:0,u.uVignette.value=n?.vignette??0,u.uSaturation.value=n?.saturation??1,u.uContrast.value=n?.contrast??1,this.webgl.setRenderTarget(null),this.webgl.render(this.bloomCompositeScene,e)}renderWithClouds(e,t,n){let r=this.webgl.getDrawingBufferSize(XI),i=Math.max(1,r.x),a=Math.max(1,r.y),o=Math.max(1,Math.ceil(i/3)),s=Math.max(1,Math.ceil(a/3));if(this.cloudsTarget&&(this.cloudsTarget.width!==i||this.cloudsTarget.height!==a)&&(this.cloudsTarget.depthTexture?.dispose(),this.cloudsTarget.dispose(),this.cloudsTarget=null,this.cloudsHalfTarget?.dispose(),this.cloudsHalfTarget=null,this.cloudsBlurTarget?.dispose(),this.cloudsBlurTarget=null),!this.cloudsTarget){let e=new cd(i,a);e.type=wa,this.cloudsTarget=new Xs(i,a,{depthTexture:e,depthBuffer:!0})}if(this.cloudsHalfTarget||(this.cloudsHalfTarget=new Xs(o,s,{depthBuffer:!1}),this.cloudsBlurTarget=new Xs(o,s,{depthBuffer:!1})),!this.cloudsScene){let{mesh:e,uniforms:t}=fI();this.cloudsScene=new Fc,this.cloudsScene.add(e),this.cloudsUniforms=t}if(!this.cloudsBlurScene){let{mesh:e,uniforms:t}=dI();this.cloudsBlurScene=new Fc,this.cloudsBlurScene.add(e),this.cloudsBlurUniforms=t}if(!this.cloudsCompositeScene){let{mesh:e,uniforms:t}=pI();this.cloudsCompositeScene=new Fc,this.cloudsCompositeScene.add(e),this.cloudsCompositeUniforms=t}this.webgl.setRenderTarget(this.cloudsTarget),this.webgl.render(this.threeScene,e);let c=this.cloudsUniforms;c.tDepth.value=this.cloudsTarget.depthTexture,c.uInvViewProj.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse).invert(),e.getWorldPosition(c.uCameraPos.value),c.uTime.value=(globalThis.performance?.now()??0)*.001*t.speed;let l=this.environment.sunDirection??[.4,.8,.3];c.uSunDir.value.set(l[0],l[1],l[2]).normalize(),n&&c.uSunColor.value.copy(n.color),c.uCloudColor.value.set(t.color),c.uShadeColor.value.set(t.shadeColor);let u=this.environment.sceneFog;u?(c.uHorizonColor.value.copy(u.color),c.uFarFade.value=u.far):(c.uHorizonColor.value.set(`#cdd9e6`),c.uFarFade.value=6e3),c.uBase.value=t.base,c.uTop.value=t.top,c.uCoverage.value=t.coverage,c.uDensity.value=t.density,c.uScale.value=t.scale,c.uWind.value.set(1,.35),this.webgl.setRenderTarget(this.cloudsHalfTarget),this.webgl.render(this.cloudsScene,e);let d=this.cloudsBlurUniforms,f=this.cloudsBlurScene;d.tTex.value=this.cloudsHalfTarget.texture,d.uDir.value.set(1/o,0),this.webgl.setRenderTarget(this.cloudsBlurTarget),this.webgl.render(f,e),d.tTex.value=this.cloudsBlurTarget.texture,d.uDir.value.set(0,1/s),this.webgl.setRenderTarget(this.cloudsHalfTarget),this.webgl.render(f,e),this.webgl.setRenderTarget(null);let p=this.cloudsCompositeUniforms;p.tScene.value=this.cloudsTarget.texture,p.tClouds.value=this.cloudsHalfTarget.texture,this.webgl.render(this.cloudsCompositeScene,e)}renderWithCaustics(e,t){let n=this.webgl.getDrawingBufferSize(XI),r=Math.max(1,n.x),i=Math.max(1,n.y);if(this.causticsTarget&&(this.causticsTarget.width!==r||this.causticsTarget.height!==i)&&(this.causticsTarget.depthTexture?.dispose(),this.causticsTarget.dispose(),this.causticsTarget=null),!this.causticsTarget){let e=new cd(r,i);e.type=wa,this.causticsTarget=new Xs(r,i,{depthTexture:e,depthBuffer:!0})}if(!this.causticsScene){let{mesh:e,uniforms:t}=S_();this.causticsScene=new Fc,this.causticsScene.add(e),this.causticsUniforms=t}this.webgl.setRenderTarget(this.causticsTarget),this.webgl.render(this.threeScene,e),this.webgl.setRenderTarget(null);let a=this.causticsUniforms;a.tColor.value=this.causticsTarget.texture,a.tDepth.value=this.causticsTarget.depthTexture,a.uInvViewProj.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse).invert(),e.getWorldPosition(a.uCameraPos.value),a.uWaterLevel.value=t.surfaceY,a.uTime.value=(globalThis.performance?.now()??0)*.001*t.caustics.speed,a.uCausticColor.value.set(t.caustics.color),a.uCausticIntensity.value=t.caustics.intensity,a.uCausticScale.value=t.caustics.scale,a.uMaxDist.value=t.visibility;let o=this.environment.sunDirection;o&&a.uSunDirection.value.set(o[0],o[1],o[2]),a.uRayStrength.value=t.rays.enabled?t.rays.strength:0,this.webgl.render(this.causticsScene,e)}screenFromWorld(e,t,n){let r=this.lastCamera;return r?(QI.set(e,t,n).project(r),{x:(QI.x+1)/2*this.lastSize.w,y:(1-QI.y)/2*this.lastSize.h,behind:QI.z>1}):{x:0,y:0,behind:!0}}pick(e,t){let n=this.lastCamera;if(!n)return null;aL.set(e/this.lastSize.w*2-1,-(t/this.lastSize.h*2-1)),iL.setFromCamera(aL,n);let r=iL.intersectObjects(this.threeScene.children,!0);for(let e of r){let t=e.object;for(;t&&!t.userData.incantoNode;)t=t.parent;let n=t?.userData.incantoNode;if(n)return n}return null}stats(){let e=this.webgl.info;return{triangles:e.render.triangles,drawCalls:e.render.calls,geometries:e.memory.geometries,textures:e.memory.textures}}lastCameraPosition(){let e=this.lastCamera;return e?(e.getWorldPosition(nL),{x:nL.x,y:nL.y,z:nL.z}):null}cameraBasis(){let e=this.lastCamera,t=e?e.getWorldQuaternion(tL):tL.identity();return{right:new W(1,0,0).applyQuaternion(t),up:new W(0,1,0).applyQuaternion(t),forward:new W(0,0,-1).applyQuaternion(t)}}refreshShadows(){this.webgl.shadowMap.needsUpdate=!0}dispose(){this.engine.picker&&(this.engine.picker=null),this.disconnect(),this.threeScene.traverse(e=>{let t=e;if(!(!t.isMesh||t.userData?.incantoModelShared))if(t.geometry?.dispose(),Array.isArray(t.material))for(let e of t.material)e.dispose();else t.material?.dispose()}),this.causticsTarget?.depthTexture?.dispose(),this.causticsTarget?.dispose();let e=this.causticsScene?.children[0];e?.geometry?.dispose(),e?.material?.dispose(),this.cloudsTarget?.depthTexture?.dispose(),this.cloudsTarget?.dispose(),this.cloudsHalfTarget?.dispose(),this.cloudsBlurTarget?.dispose(),this.bloomTarget?.dispose(),this.bloomBrightTarget?.dispose(),this.bloomBlurTarget?.dispose();for(let e of[this.cloudsScene,this.cloudsBlurScene,this.cloudsCompositeScene,this.bloomBrightScene,this.bloomBlurScene,this.bloomCompositeScene]){let t=e?.children[0];t?.geometry?.dispose(),t?.material?.dispose()}this.ownsAssets&&this.assets.dispose(),this.environment.dispose(),this.webgl.dispose()}},YI=12,XI=new H,ZI=new W,QI=new W,$I=new W,eL=new W,tL=new U,nL=new W,rL=new W,iL=new rp,aL=new H;function oL(e,t,n){let r=t*4,i=new Uint8Array(r);for(let t=0;t<Math.floor(n/2);t++){let a=t*r,o=(n-1-t)*r;i.set(e.subarray(a,a+r)),e.copyWithin(a,o,o+r),e.set(i,o)}}async function sL(e){let t=async(t,n)=>{e.onProgress&&(e.onProgress(t,n),await CD())};XF(),(e.gameplay??!0)&&wb();for(let[t,n]of Object.entries(e.behaviors??{}))St(t,n,{replace:!0});let n=new Hn({seed:e.seed,fixedHz:e.fixedHz,...e._scheduler?{scheduler:e._scheduler}:{}}),r=cL(e.scene),i=Ai(cL(r),{resolveScene:e.resolveScene,engine:n});n.setScene(i),await t(.06,`scene`);let a=null;(e.physics===!0||(e.physics??`auto`)===`auto`&&lL(i.root))&&(a=await OO(n)),await t(.1,`physics`);let o=[],s=e.keyboard??(typeof window<`u`?window:!1);if(s&&n.input.attachKeyboard(s),e.pointer){let t=typeof e.pointer==`object`?e.pointer.lockOnClick??!0:!0;n.input.attachPointer(e.canvas,{lockOnClick:t})}o.push(uL(n,i.root,e.canvas)),e.pageGestures||Dg(e.canvas);let c=e.touch??`auto`;if(c!==!1){let t=e.touchContainer??e.canvas.parentElement??null;if(t){let r={force:c===!0,...e._touchDoc?{doc:e._touchDoc}:{}},i=na(n,t,r),a=n.sceneChanged.connect(()=>{i?.dispose(),i=na(n,t,r)});o.push(()=>{a(),i?.dispose()})}}let l=zn(n.settings.autoQuality()),u=e._rendererFactory?e._rendererFactory(n,e.canvas):new JI({canvas:e.canvas,engine:n,qualityDefaults:{antialias:l.antialias,pixelRatio:l.pixelRatio},...e.pixelRatio===void 0?{}:{pixelRatio:e.pixelRatio},...e.adaptiveResolution===void 0?{}:{adaptiveResolution:e.adaptiveResolution},...e.preserveDrawingBuffer===void 0?{}:{preserveDrawingBuffer:e.preserveDrawingBuffer}});await t(.14,`renderer`);let d=e.debug??!1,f=e.editor??d,p=f===!0?{}:f||null,m={label:`✎ edit this scene`,run:async()=>{if(!p)return;let t=Qg(u),n=p.open??Xg,i=async t=>{await sL({...e,scene:t})};await Zg(async()=>{g();try{await n({scene:r,...t?{camera:t}:{},play:i,exit:()=>i(r),...p.save?{save:p.save}:{},...p.library?{library:p.library===!0?Wg():p.library}:{}})}catch(e){console.error(`[incanto] could not open the editor:`,e),await i(r)}},`opening the editor…`)}};if(d){let t=e.touchContainer??e.canvas.parentElement??(typeof document<`u`?document.body:null);if(t){let{attachDebugOverlay:r}=await Bg(async()=>{let{attachDebugOverlay:e}=await import(`./debug-eaSKFAKW.js`);return{attachDebugOverlay:e}},[],import.meta.url),i=r(n,{container:t,statsSource:()=>u.stats?.()??{},...u.captureFrame?{frameSource:()=>h()}:{},...p?{actions:[m]}:{},...e._debugDoc?{doc:e._debugDoc}:{}});i&&o.push(()=>i.dispose())}}n.start(),await t(.16,`shaders`);try{u.deferFirstCompile?.();let t=globalThis.performance?.now?.()??0;n.tick(t),n.tick(t+16),await u.warmUp?.(t=>{e.onProgress?.(.16+t*.82,`shaders`)})}catch{}o.push(n.settings.bindAudio(n.audio)),o.push(n.settings.bindLocale(n.locale)),o.push(n.settings.bindQuality(e=>{wD(n,e)})),o.push(n.settings.bindFrameCap(e=>{n.maxFps=e,u.setFrameTarget?.(e||60)})),o.push(n.settings.bindRenderScale(e=>{u.setRenderScale?.(e)}));let h=()=>{let e=u.captureFrame;if(!e)throw new L(`TREE_VIOLATION`,`this renderer cannot capture frames`);return e.call(u)};o.push(...Ig({engine:n,applyDrive:async e=>{let t=0,r=!0,i=()=>{r&&(t+=1,requestAnimationFrame(i))};requestAnimationFrame(i);for(let t of e)switch(t.kind){case`press`:n.input.pressAction(t.action);break;case`release`:n.input.releaseAction(t.action);break;case`vector`:n.input.setActionVector(t.action,t.x,t.y);break;case`key`:n.input.handleKey(t.code,t.down);break;case`pointer`:n.input.handlePointerMove(t.dx,t.dy);break;case`step`:await new Promise(e=>setTimeout(e,t.ms));break}return r=!1,t},captureFramePixels:h,rendererStats:()=>u.stats?.(),assetErrors:()=>u.assets?.errors()??[]})),o.push($g(n)),await t(1,`ready`);function g(){e_([a?[`physics`,()=>a?.dispose()]:null,[`app cleanups`,()=>{for(let e of o)e()}],[`engine`,()=>n.dispose()],[`renderer`,()=>u.dispose()]])}return{engine:n,scene:i,sourceJson:r,renderer:u,physics:a,assetErrors(){return[...u.assets?.errors()??[],...Eg(n.scene?.tree.root)]},async frame(e){let t=u.captureFrame;if(!t)throw new L(`TREE_VIOLATION`,`this renderer cannot capture frames`);let n=await t.call(u);return Fg(n.pixels,n.width,n.height,e)},pick(e,t){return n.picker?.(e,t)??null},stats(){return{triangles:0,drawCalls:0,geometries:0,textures:0,...n.stats(),...u.stats?.()}},openEditor:p?m.run:null,dispose:g}}function cL(e){try{return structuredClone(e)}catch{throw new L(`BAD_FORMAT`,`createGame "scene" must be plain scene JSON (the imported *.scene.json object) — got something unclonable (a loaded Scene, class instances, or functions).`)}}function lL(e){if(e instanceof Q_)return!0;for(let t of e.children)if(lL(t))return!0;return!1}function uL(e,t,n){let r=[],i=n;if(i.addEventListener&&r.push({target:i,type:`pointerdown`}),typeof window<`u`){let e=window;r.push({target:e,type:`keydown`}),r.push({target:e,type:`pointerdown`})}if(r.length===0)return()=>{};function a(){for(let e of r)e.target.removeEventListener?.(e.type,o)}function o(){e.sfx.unlock(),e.music.unlock();let n=!1,r=e=>{e instanceof Kn&&(e.retryPending(),e.pendingGesture&&(n=!0));for(let t of e.children)r(t)};r(t),n||a()}for(let e of r)e.target.addEventListener?.(e.type,o,{passive:!0});return a}var dL=e({DEFAULT_TERRAIN_TEXTURE_BASE:()=>tO,WATER_CUTOUT_MAX:()=>4,WATER_MAX_RIPPLES:()=>8,createGame3D:()=>sL,enablePhysics3D:()=>OO}),fL=500,pL=2e3,mL=new WeakMap,hL=class e{account;roomId;roomState=new M;allUserStates=new M;userJoined=new M;userLeft=new M;globalState=new M;globalMyState=new M;asset=new M;latestUserStates={};latestRoomState={};latestGlobalState={};latestGlobalMyState={};latestAsset={};server;engine;throttleMs;keyframeMs;subs=[];messageSignals=new Map;collectionSignals=new Map;latestCollections=new Map;globalMessageSignals=new Map;globalCollectionSignals=new Map;latestGlobalCollections=new Map;scenes=new Map;lastSent=new Map;reportedDeadKeys=new Set;reportDeadSyncKey(e,t){this.reportedDeadKeys.has(t)||this.aliveMs<fL||(this.reportedDeadKeys.add(t),Nt(e.tree?.engine??null,`error`,`[incanto] ${e.getPath()}: sync key '${t}' reads as undefined — it is never sent, so remote players never see it change. Check the prop name and the node path.`))}sendAccumulator=0;keyframeAccumulator=0;aliveMs=0;detachReplication=null;lastOwner=null;boundScene=null;static get(e){return mL.get(e)??null}static async create(t,n={}){await mL.get(t)?.dispose();let r=n.transport??await bL(n.config);await r.connect();let i=n.room??t.scene?.multiplayer?.room??`auto`,a=new e(t,r,await r.remoteFunction(`joinRoom`,[i===`auto`?void 0:i],{needResponse:!0}),n.throttleMs??50,n.keyframeMs??pL);return mL.set(t,a),a}constructor(e,t,n,r,i){this.engine=e,this.server=t,this.roomId=n,this.account=t.account,this.throttleMs=Math.max(30,r),this.keyframeMs=Math.max(0,i),this.boundScene=e.scene,this.subs.push(t.subscribeRoomState(n,e=>{this.latestRoomState=e,this.roomState.emit(e)}),t.subscribeRoomAllUserStates(n,e=>{this.latestUserStates=e,this.allUserStates.emit(e)}),t.onRoomUserJoin(n,e=>this.userJoined.emit(e)),t.onRoomUserLeave(n,e=>this.userLeft.emit(e))),t.subscribeGlobalState&&this.subs.push(t.subscribeGlobalState(e=>{this.latestGlobalState=e,this.globalState.emit(e)})),t.subscribeGlobalMyState&&this.subs.push(t.subscribeGlobalMyState(e=>{this.latestGlobalMyState=e,this.globalMyState.emit(e)})),t.subscribeAsset&&this.subs.push(t.subscribeAsset(this.account,e=>{this.latestAsset=e,this.asset.emit(e)})),this.detachReplication=e.fixedUpdated.connect(e=>this.replicate(e))}message(e){let t=this.messageSignals.get(e);return t||(t=new M,this.messageSignals.set(e,t),this.subs.push(this.server.onRoomMessage(this.roomId,e,e=>t?.emit(e)))),t}collection(e){let t=this.collectionSignals.get(e);return t||(t=new M,this.collectionSignals.set(e,t),this.subs.push(this.server.subscribeRoomCollection(this.roomId,e,n=>{this.latestCollections.set(e,n),t?.emit(n)}))),t}latestCollection(e){return this.collection(e),this.latestCollections.get(e)??{}}globalMessage(e){let t=this.globalMessageSignals.get(e);if(!t){t=new M,this.globalMessageSignals.set(e,t);let n=this.server.onGlobalMessage?.(e,e=>t?.emit(e));n&&this.subs.push(n)}return t}globalCollection(e){let t=this.globalCollectionSignals.get(e);if(!t){t=new M,this.globalCollectionSignals.set(e,t);let n=this.server.subscribeGlobalCollection?.(e,n=>{this.latestGlobalCollections.set(e,n),t?.emit(n)});n&&this.subs.push(n)}return t}latestGlobalCollection(e){return this.globalCollection(e),this.latestGlobalCollections.get(e)??{}}setMyState(e){return this.server.remoteFunction(`setMyState`,[this.roomId,e],{throttle:this.throttleMs,throttleKey:`incanto:myState`})}patchRoomState(e){return this.server.remoteFunction(`patchRoomState`,[this.roomId,e])}addEntity(e,t){return this.server.remoteFunction(`addEntity`,[this.roomId,e,t])}updateEntity(e,t,n){return this.server.remoteFunction(`updateEntity`,[this.roomId,e,t,n])}removeEntity(e,t){return this.server.remoteFunction(`removeEntity`,[this.roomId,e,t])}sendEvent(e,t){return this.server.remoteFunction(`sendEvent`,[this.roomId,e,t])}call(e,...t){return this.server.remoteFunction(e,[this.roomId,...t],{needResponse:!0})}registerScene(e,t){this.scenes.set(e,t)}resolveScene(e){let t=this.scenes.get(e);if(!t)throw new L(`UNRESOLVED_INSTANCE`,`No scene registered for '${e}'. Registered: [${[...this.scenes.keys()].join(`, `)}]. Call manager.registerScene('${e}', sceneJson).`);return t}async dispose(){this.detachReplication?.();for(let e of this.subs)e();await this.server.remoteFunction(`leaveRoom`,[this.roomId]),mL.delete(this.engine)}replicate(e){let t=this.engine.scene;if(!t||t!==this.boundScene)return;this.sendAccumulator+=e*1e3,this.aliveMs+=e*1e3;let n=gL(t.root,!0);if(!n)return;n!==this.lastOwner&&(this.lastOwner=n,this.lastSent.clear());let r=n.network,i=Math.max(30,typeof r.throttleMs==`number`?r.throttleMs:this.throttleMs),a=Array.isArray(r.sync)?r.sync:[],o={},s=!1;for(let e of a){let t=vL(n,e);if(t===void 0){this.reportDeadSyncKey(n,e);continue}o[e]=R(t),et(this.lastSent.get(e)??null,t)||(s=!0)}this.keyframeAccumulator+=e*1e3;let c=this.keyframeMs>0&&this.keyframeAccumulator>=this.keyframeMs;if(!(this.sendAccumulator<i)&&!(!s&&!c)&&Object.keys(o).length!==0){for(let[e,t]of Object.entries(o))this.lastSent.set(e,R(t));this.keyframeAccumulator=0,this.sendAccumulator=0,this.setMyState({sync:o})}}};function gL(e,t=!1){let n=[];if(_L(e,n),t&&n.length>1)throw new L(`BAD_FORMAT`,`Multiple network owner nodes found (${n.map(e=>e.getPath()).join(`, `)}). Exactly ONE node per player may declare network.mode 'owner' — replicate spawned entities through collections instead.`);return n[0]??null}function _L(e,t){e.network?.mode===`owner`&&t.push(e);for(let n of e.children)_L(n,t)}function vL(e,t){let n=t.lastIndexOf(`.`),r=n===-1?e:e.getNodeOrNull(t.slice(0,n))??void 0,i=n===-1?t:t.slice(n+1);if(r)return r[i]}function yL(e,t,n,r){for(let[i,a]of Object.entries(t)){let t=i.lastIndexOf(`.`),o=t===-1?e:e.getNodeOrNull(i.slice(0,t)),s=t===-1?i:i.slice(t+1);o?n(o,s,a):r?.(i)}}async function bL(e){let{createAgent8Server:t}=await Bg(async()=>{let{createAgent8Server:e}=await import(`./agent8-CLZXBRoM.js`);return{createAgent8Server:e}},[],import.meta.url);return t(e)}var xL=new Set([`__id`,`__roomId`,`__updated`,`__leaved`,`account`,`roomId`]),SL=class extends Ft{static typeName=`NetworkSpawner`;static signals=[`spawned`,`despawned`];static props={source:{default:`users`},scene:{default:``},interpolate:{default:!0}};source=`users`;scene=``;interpolate=!0;spawned=new Map;positionTargets=new Map;failedKeys=new Set;reported=new Set;update(e){let t=this.tree?.engine;if(!t)return;let n=hL.get(t);if(!n||this.scene===``)return;let r=this.currentEntries(n);for(let[e,t]of Object.entries(r)){let r=this.spawned.get(e);if(!r){if(this.failedKeys.has(e))continue;try{r=Fi(n.resolveScene(this.scene).root)}catch(t){throw this.failedKeys.add(e),t}r.name=CL(e),this.addChild(r),this.spawned.set(e,r),this.emit(`spawned`,r,e)}let i=this.patchOf(t);i&&yL(r,i,(e,t,n)=>this.setProp(e,t,n),e=>this.report(`'${e}' names a node this scene does not have`))}for(let[e,t]of[...this.spawned.entries()])e in r||(this.spawned.delete(e),this.positionTargets.delete(t),this.emit(`despawned`,t,e),t.free());this.interpolate&&this.stepInterpolation(e)}currentEntries(e){if(this.source===`users`){let t={};for(let[n,r]of Object.entries(e.latestUserStates))n!==e.account&&(t[n]=r);return t}return this.source.startsWith(`collection:`)?e.latestCollection(this.source.slice(11)):{}}patchOf(e){if(e.sync!==void 0)return e.sync;if(this.source===`users`)return;let t={};for(let[n,r]of Object.entries(e))xL.has(n)||n.startsWith(`$`)||(t[n]=r);return Object.keys(t).length>0?t:void 0}report(e){this.reported.has(e)||(this.reported.add(e),Nt(this.tree?.engine??null,`error`,`[incanto] NetworkSpawner '${this.name}': ${e} — that value replicates to nothing.`))}setProp(e,t,n){if(this.interpolate&&t===`position`&&Array.isArray(n)){this.positionTargets.set(e,n);return}e[t]=n}stepInterpolation(e){let t=Math.min(1,e*8);for(let[e,n]of this.positionTargets){let r=e.position;Array.isArray(r)&&(e.position=r.map((e,r)=>e+((n[r]??e)-e)*t))}}};function CL(e){return e.replace(/[/%]/g,`_`)||`remote`}function wL(){Or(),z(SL)}function TL(){try{return typeof localStorage>`u`?null:localStorage}catch{return null}}var EL=TL()?.getItem(`incanto-editor-lang`)??`en`,DL=new Set;function OL(){return EL}function kL(e){EL=e,TL()?.setItem(`incanto-editor-lang`,e);for(let e of DL)e()}function AL(e){DL.add(e)}function jL(e){return e[EL]}var ML={node:{paths:[`M5 5h14v14H5z`]},move:{paths:[`M12 3v18M3 12h18`,`M8 7l4-4 4 4M8 17l4 4 4-4M7 8l-4 4 4 4M17 8l4 4-4 4`]},image:{paths:[`M4 5h16v14H4z`,`M4 15l5-5 4 4 3-3 4 4`],circles:[[9,9,1.6]]},film:{paths:[`M4 4h16v16H4z`,`M4 9h16M4 15h16`,`M9 4v16M15 4v16`]},video:{paths:[`M3 7h12v10H3z`,`M15 10l6-3v10l-6-3`]},text:{paths:[`M5 7V5h14v2`,`M12 5v14`,`M9 19h6`]},layers:{paths:[`M12 3 3 8l9 5 9-5-9-5z`,`M3 12l9 5 9-5`,`M3 16l9 5 9-5`]},square:{paths:[`M5 5h14v14H5z`,`M5 12h14`]},ball:{paths:[`M12 8v0`],circles:[[12,12,8],[12,12,1.4]]},person:{paths:[`M5 21v-1a7 7 0 0 1 14 0v1`],circles:[[12,7,4]]},area:{paths:[`M5 5h14v14H5z`],dashed:!0},gamepad:{paths:[`M7 9h-0M6 12h4M8 10v4`,`M4 8h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2z`],circles:[[16,11,1],[18.5,13.5,1]]},clock:{paths:[`M12 7v5l3 2`],circles:[[12,12,9]]},cube:{paths:[`M21 16V8l-9-5-9 5v8l9 5 9-5z`,`M3.3 7.5 12 12.5l8.7-5`,`M12 22V12.5`]},sun:{paths:[`M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M19.1 4.9 17 7M7 17l-2.1 2.1`],circles:[[12,12,4]]},bulb:{paths:[`M9 18h6M10 21h4`,`M8 13a6 6 0 1 1 8 0c-1 1-1.5 2-1.5 3h-5c0-1-.5-2-1.5-3z`]},globe:{paths:[`M2 12h20`,`M12 2a15 15 0 0 1 0 20a15 15 0 0 1 0-20z`],circles:[[12,12,10]]},link:{paths:[`M10 14a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1`,`M14 10a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1`]},speaker:{paths:[`M11 5 6 9H3v6h3l5 4V5z`,`M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13`]},swatch:{paths:[`M4 4h16v16H4z`,`M4 4l16 16`]},sparkles:{paths:[`M12 4v5M12 15v5M5 12h5M14 12h5`],circles:[[6,5,1],[18,19,1]]},waves:{paths:[`M2 8c3-3 5 3 8 0s5 3 8 0`,`M2 14c3-3 5 3 8 0s5 3 8 0`,`M2 20c3-3 5 3 8 0s5 3 8 0`]},plant:{paths:[`M12 21v-8`,`M12 13c0-4-3-6-7-6 0 4 3 6 7 6z`,`M12 11c0-4 3-6 7-6 0 4-3 6-7 6z`]},flower:{paths:[`M12 21v-7`],circles:[[12,9,2],[12,4.5,2.2],[16.3,7.5,2.2],[14.7,12.6,2.2],[9.3,12.6,2.2],[7.7,7.5,2.2]]},voxels:{paths:[`M4 14h8v8H4z`,`M12 14h8v8h-8z`,`M8 6h8v8H8z`]}},NL={Node:`node`,Timer:`clock`,AudioPlayer:`speaker`,ColorRect2D:`swatch`,Particles2D:`sparkles`,Particles3D:`sparkles`,Water3D:`waves`,Foliage3D:`plant`,Flowers3D:`flower`,VoxelGrid3D:`voxels`,ModelInstance3D:`person`,CharacterController3D:`gamepad`,Node2D:`move`,Sprite2D:`image`,AnimatedSprite2D:`film`,Camera2D:`video`,Label:`text`,UILayer:`layers`,StaticBody2D:`square`,RigidBody2D:`ball`,CharacterBody2D:`person`,Area2D:`area`,CharacterController2D:`gamepad`,Node3D:`move`,Billboard3D:`layers`,MeshInstance3D:`cube`,LoftMesh3D:`cube`,Camera3D:`video`,DirectionalLight3D:`sun`,OmniLight3D:`bulb`,StaticBody3D:`square`,RigidBody3D:`ball`,CharacterBody3D:`person`,Area3D:`area`,NetworkSpawner:`globe`};function PL(e){let t=ML[NL[e??``]??(e?`node`:`link`)],n=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);n.setAttribute(`viewBox`,`0 0 24 24`),n.setAttribute(`width`,`13`),n.setAttribute(`height`,`13`),n.setAttribute(`fill`,`none`),n.setAttribute(`stroke`,`currentColor`),n.setAttribute(`stroke-width`,`2`),n.setAttribute(`stroke-linecap`,`round`),n.setAttribute(`stroke-linejoin`,`round`),t.dashed&&n.setAttribute(`stroke-dasharray`,`3 2.4`);for(let e of t.paths){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);t.setAttribute(`d`,e),n.appendChild(t)}for(let[e,r,i]of t.circles??[]){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`circle`);t.setAttribute(`cx`,String(e)),t.setAttribute(`cy`,String(r)),t.setAttribute(`r`,String(i)),n.appendChild(t)}return n}function FL(){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`width`,`12`),e.setAttribute(`height`,`12`),e.setAttribute(`fill`,`none`),e.setAttribute(`stroke`,`currentColor`),e.setAttribute(`stroke-width`,`2.4`),e.setAttribute(`aria-hidden`,`true`);let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return t.setAttribute(`d`,`m6 9 6 6 6-6`),e.appendChild(t),e}var IL=[{type:`texture`,label:`image (texture)`,metaHints:[`filter`]},{type:`spritesheet`,label:`spritesheet`,metaHints:[`filter`,`frameWidth`,`frameHeight`]},{type:`model`,label:`3D model (GLB/VRM)`,metaHints:[]},{type:`animation`,label:`animation (GLB clips)`,metaHints:[`clip`]}],LL=new Set,RL=null,zL=null;function BL(e,t,n){let r=document.createElement(`input`);r.className=`rename-input`,r.value=e;let i=()=>{let i=r.value.trim().replace(/\//g,``);i&&i!==e?t(i):n()};r.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`/`&&e.preventDefault(),e.key===`Enter`&&i(),e.key===`Escape`&&n()});for(let e of[`click`,`pointerdown`,`dblclick`,`mousedown`])r.addEventListener(e,e=>e.stopPropagation());return r.addEventListener(`blur`,i),queueMicrotask(()=>{r.focus(),r.select()}),r}function VL(e,t){let n={path:``,name:``,folders:new Map,assets:[]},r=e=>{let t=n;if(e===``)return t;for(let n of e.split(`/`)){let e=t.folders.get(n);e||(e={path:t.path?`${t.path}/${n}`:n,name:n,folders:new Map,assets:[]},t.folders.set(n,e)),t=e}return t};for(let t of e){let e=t.lastIndexOf(`/`);r(e===-1?``:t.slice(0,e)).assets.push(t)}for(let e of t)r(e);return n}function HL(e){let t=e.assets.length;for(let n of e.folders.values())t+=HL(n);return t}function UL(e,t){e.textContent=``;let n=t.working.assets??{},r=Object.keys(n);if(r.length===0&&t.pendingGroups.size===0&&!t.addingAsset&&!t.addingGroup){let t=document.createElement(`div`);t.className=`muted-note explorer-empty`,t.textContent=`no assets yet — + adds textures, models, animations`,e.appendChild(t);return}let i=(e,n)=>{e.addEventListener(`dragover`,t=>{t.preventDefault(),t.stopPropagation(),e.classList.add(`drop-target`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-target`)),e.addEventListener(`drop`,r=>{r.preventDefault(),r.stopPropagation(),e.classList.remove(`drop-target`);let i=r.dataTransfer?.getData(`text/incanto-asset`);i&&t.moveAsset(i,n);let a=r.dataTransfer?.getData(`text/incanto-group`);a&&t.moveGroup(a,n)})};i(e,``);let a=(e,r)=>{let i=n[e],a=e.includes(`/`)?e.slice(e.lastIndexOf(`/`)+1):e,o=t.assetErrors.get(e),s=document.createElement(`div`);s.className=`tree-row asset-row${t.selectedAsset===e?` selected`:``}${o===void 0?``:` asset-failed`}`,o!==void 0&&(s.title=`failed to load: ${o}`),s.draggable=!0,s.addEventListener(`dragstart`,t=>{t.dataTransfer?.setData(`text/incanto-asset`,e)});let c=document.createElement(`span`);if(c.className=`tree-icon`,c.appendChild(aR(i.type??``)),c.addEventListener(`click`,e=>{e.stopPropagation(),oR(c,i.type??``)}),RL===e){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;s.appendChild(BL(a,r=>{RL=null,t.renameAssetKey(e,n+r)},()=>{RL=null,t.selectAsset(t.selectedAsset)})),s.draggable=!1,s.insertBefore(c,s.firstChild),r.appendChild(s);return}let l=document.createElement(`span`);l.className=`tree-name asset-key`,l.textContent=`$${a}`,l.title=o===void 0?`$${e}`:`$${e} — failed to load: ${o}`,l.addEventListener(`dblclick`,n=>{n.stopPropagation(),RL=e,t.selectAsset(e)}),s.append(c,l),s.addEventListener(`click`,()=>t.selectAsset(e)),r.appendChild(s)},o=(e,n)=>{let r=LL.has(e.path),s=document.createElement(`div`);s.className=`asset-folder${r?` collapsed`:``}${t.selectedGroup===e.path?` selected`:``}`,s.draggable=!0,s.addEventListener(`dragstart`,t=>{t.stopPropagation(),t.dataTransfer?.setData(`text/incanto-group`,e.path)});let c=document.createElement(`span`);c.className=`chev`,c.appendChild(FL());let l=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);l.setAttribute(`viewBox`,`0 0 24 24`),l.setAttribute(`width`,`12`),l.setAttribute(`height`,`12`),l.setAttribute(`fill`,`none`),l.setAttribute(`stroke`,`currentColor`),l.setAttribute(`stroke-width`,`1.8`),l.setAttribute(`aria-hidden`,`true`);let u=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);if(u.setAttribute(`d`,`M3 6a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`),l.appendChild(u),zL===e.path){let i=e.path.includes(`/`)?e.path.slice(0,e.path.lastIndexOf(`/`)+1):``;if(s.append(c,l,BL(e.name,n=>{zL=null,t.renameGroup(e.path,i+n)},()=>{zL=null,t.selectGroup(t.selectedGroup)})),s.draggable=!1,n.appendChild(s),!r){let t=document.createElement(`div`);t.className=`tree-children`;for(let n of e.folders.values())o(n,t);for(let n of e.assets)a(n,t);t.children.length>0&&n.appendChild(t)}return}let d=document.createElement(`span`);d.textContent=e.name,d.addEventListener(`dblclick`,n=>{n.stopPropagation(),zL=e.path,t.selectGroup(e.path)});let f=document.createElement(`span`);if(f.className=`count`,f.textContent=`(${HL(e)})`,s.append(c,l,d,f),s.addEventListener(`click`,()=>{LL.has(e.path)?LL.delete(e.path):LL.add(e.path),t.selectGroup(e.path)}),i(s,e.path),n.appendChild(s),!r){let t=document.createElement(`div`);t.className=`tree-children`;for(let n of e.folders.values())o(n,t);for(let n of e.assets)a(n,t);t.children.length>0&&n.appendChild(t)}},s=VL(r,t.pendingGroups);for(let t of s.assets)a(t,e);for(let t of s.folders.values())o(t,e)}function WL(e,t,n,r){if(t.selection!==null)return!1;if(t.addingGroup){e.appendChild(uR(t.newGroupParent?`NEW GROUP IN ${t.newGroupParent}/`:`NEW GROUP`));let n=document.createElement(`input`);n.placeholder=t.newGroupParent?`heroes`:`characters (or a/b to nest)`,n.className=`mono`,e.appendChild(eR(`name`,n));let r=document.createElement(`button`);r.type=`button`,r.className=`primary`,r.textContent=`add`;let i=()=>{let e=n.value.trim().replace(/^\/+|\/+$/g,``);e&&(t.cancelAddForms(),t.addGroup(t.newGroupParent?`${t.newGroupParent}/${e}`:e))};r.addEventListener(`click`,i),n.addEventListener(`keydown`,e=>{e.key===`Enter`&&i()});let a=document.createElement(`div`);return a.className=`pop-actions`,a.appendChild(r),e.appendChild(a),setTimeout(()=>n.focus(),0),!0}if(t.addingAsset)return JL(e,t,r);if(t.selectedGroup!==null){let r=t.selectedGroup,i=t.groupCount(r);e.appendChild(uR(`GROUP (${i} asset${i===1?``:`s`})`));let a=r.includes(`/`)?r.slice(0,r.lastIndexOf(`/`)+1):``,o=r.includes(`/`)?r.slice(r.lastIndexOf(`/`)+1):r;e.appendChild(tR(`name`,o,e=>{let n=e.trim().replace(/\/+/g,``);n&&n!==o&&t.renameGroup(r,a+n)}));let s=document.createElement(`button`);return s.type=`button`,s.className=`ghost danger`,s.textContent=`delete group`,s.addEventListener(`click`,()=>{if(i===0){t.deleteGroup(r);return}n(`'${r}/' contains ${i} asset${i===1?``:`s`} — deleting the group deletes them too.`,`delete group & assets`,()=>t.deleteGroup(r))}),e.appendChild(s),!0}let i=t.selectedAsset;if(i===null)return!1;let a=t.working.assets??{};if(!(i in a))return!1;e.appendChild(uR(`ASSET — ${String(a[i].type??`?`)}`)),e.appendChild(sR(i)),e.appendChild(cR(t,i)),e.appendChild(GL(t,a,i,r));let o=document.createElement(`button`);return o.type=`button`,o.className=`ghost danger`,o.textContent=`delete asset`,o.addEventListener(`click`,()=>{t.selectAsset(null),t.mutate(()=>{delete a[i],Object.keys(a).length===0&&delete t.working.assets})}),e.appendChild(o),!0}function GL(e,t,n,r){let i=t[n],a=document.createElement(`div`);a.className=`asset-editor`;let o=n.includes(`/`)?n.slice(n.lastIndexOf(`/`)+1):n,s=n.includes(`/`)?n.slice(0,n.lastIndexOf(`/`)+1):``,c=tR(`name`,o,t=>{let r=t.trim().replace(/^\$/,``).replace(/\//g,``);r&&r!==o&&e.renameAssetKey(n,s+r)});lR(c.querySelector(`input`)),a.appendChild(c);let l=tR(`url`,String(i.url??``),t=>{e.mutate(()=>{i.url=t.trim()})}),u=l.querySelector(`input`);if(r&&u){let t=XL(String(i.type??``));l.classList.add(`has-lib`),l.appendChild($L(()=>t,`asset url`,r,t=>{u.value=t,e.mutate(()=>{i.url=t})},()=>QL(t,e,String(i.type??``)),()=>String(i.type??``)||void 0))}a.appendChild(l);let d=e.assetErrors.get(n);if(d!==void 0){let e=document.createElement(`div`);e.className=`conn-warn`,e.textContent=`failed to load — every node using $${n} draws nothing. Check the url: ${d}`,a.appendChild(e)}let f=document.createElement(`div`);f.className=`muted-note`,f.textContent=`meta (key · value)`,a.appendChild(f);for(let[t,n]of Object.entries(i))t===`type`||t===`url`||a.appendChild(KL(e,i,t,n));return a.appendChild(qL(e,i)),a}function KL(e,t,n,r){let i=document.createElement(`div`);i.className=`meta-row`;let a=document.createElement(`input`);a.value=n,a.className=`mono`;let o=document.createElement(`input`);o.value=typeof r==`string`?r:JSON.stringify(r),o.className=`mono`;let s=()=>{let r=a.value.trim();e.mutate(()=>{delete t[n],r&&(t[r]=nR(o.value))})};a.addEventListener(`change`,s),o.addEventListener(`change`,s);let c=document.createElement(`button`);return c.type=`button`,c.className=`linklike danger-link`,c.textContent=`✕`,c.addEventListener(`click`,()=>{e.mutate(()=>{delete t[n]})}),i.append(a,o,c),i}function qL(e,t){let n=document.createElement(`div`);n.className=`meta-row`;let r=document.createElement(`input`);r.placeholder=`filter…`,r.className=`mono`;let i=document.createElement(`input`);i.placeholder=`nearest`,i.className=`mono`;let a=()=>{let n=r.value.trim();!n||i.value.trim()===``||e.mutate(()=>{t[n]=nR(i.value)})};return r.addEventListener(`change`,a),i.addEventListener(`change`,a),n.append(r,i,document.createElement(`span`)),n}function JL(e,t,n){return e.appendChild(uR(`NEW ASSET`)),e.appendChild(YL(t,n)),!0}function YL(e,t){let n=document.createElement(`div`);n.className=`asset-editor`;let r=document.createElement(`select`);for(let e of IL){let t=document.createElement(`option`);t.value=e.type,t.textContent=e.label,r.appendChild(t)}n.appendChild(eR(`type`,r));let i=document.createElement(`input`);i.placeholder=`(optional) characters`,i.className=`mono`,i.value=e.newAssetGroup;let a=`asset-groups-list`;i.setAttribute(`list`,a);let o=document.createElement(`datalist`);o.id=a;let s=new Set;for(let t of Object.keys(e.working.assets??{})){let e=t.lastIndexOf(`/`);e!==-1&&s.add(t.slice(0,e))}for(let t of e.pendingGroups)s.add(t);for(let e of s){let t=document.createElement(`option`);t.value=e,o.appendChild(t)}n.appendChild(eR(`group`,i)),n.appendChild(o);let c=document.createElement(`input`);c.placeholder=`coin`,c.className=`mono`,lR(c),n.appendChild(eR(`key`,c));let l=document.createElement(`input`);l.placeholder=`/textures/coin.png · https://… · data:…`,l.className=`mono`;let u=eR(`url`,l);t&&(u.classList.add(`has-lib`),u.appendChild($L(()=>XL(r.value),`new asset`,t,e=>{l.value=e,c.value.trim()||(c.value=ZL(e))},()=>QL(XL(r.value),e,r.value),()=>r.value||void 0))),n.appendChild(u);let d=document.createElement(`textarea`);d.rows=2,d.placeholder=`or paste a JSON object: { "type": "model", "url": "/m.glb" }`,n.appendChild(d);let f=document.createElement(`button`);f.type=`button`,f.className=`primary`,f.textContent=`add`,f.addEventListener(`click`,()=>{let t=c.value.trim().replace(/^\$/,``);if(!t)return;let n=i.value.trim().replace(/\/+$/,``),a=n?`${n}/${t}`:t,o=null,s=d.value.trim();if(s)try{o=JSON.parse(s)}catch{d.classList.add(`invalid`);return}else l.value.trim()&&(o={type:r.value,url:l.value.trim()});o&&(e.cancelAddForms(),e.selectedAsset=a,e.mutate(()=>{e.working.assets||(e.working.assets={});let t=e.working.assets;t[a]=o}))});let p=document.createElement(`div`);return p.className=`pop-actions`,p.appendChild(f),n.appendChild(p),n}function XL(e){return e===`model`||e===`animation`?`model`:e===`audio`?`audio`:e===`texture`||e===`spritesheet`?`image`:`any`}function ZL(e){return((e.split(/[?#]/)[0]??``).split(`/`).pop()??``).replace(/\.[^.]+$/,``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/_{2,}/g,`_`).replace(/^_+|_+$/g,``).toLowerCase()||`asset`}function QL(e,t,n){if(n===`animation`)return[`3d`,`animations`];let r=(t.working.dimension??`2d`)===`3d`;if(e===`image`)return r?[`3d`,`textures`]:[`2d`,`sprite_characters`];if(e===`model`)return[`3d`,`characters`]}function $L(e,t,n,r,i,a){let o=document.createElement(`button`);return o.type=`button`,o.className=`asset-lib`,o.textContent=`📚 library`,o.title=`Browse the agent8 asset library`,o.addEventListener(`click`,o=>{o.preventDefault();let s=i?.(),c=a?.();n({kind:e(),target:t,...s?{shelf:s}:{},...c?{assetType:c}:{}}).then(e=>{e&&r(e)})}),o}function eR(e,t){let n=document.createElement(`label`);n.className=`field`;let r=document.createElement(`span`);return r.textContent=e,n.append(r,t),n}function tR(e,t,n){let r=document.createElement(`input`);return r.value=t,r.className=`mono`,r.addEventListener(`change`,()=>n(r.value)),eR(e,r)}function nR(e){let t=e.trim();if(t===`true`)return!0;if(t===`false`)return!1;if(t!==``&&Number.isFinite(Number(t)))return Number(t);if(t.startsWith(`{`)||t.startsWith(`[`))try{return JSON.parse(t)}catch{return e}return e}var rR={texture:`M3 5h18v14H3z M3 15l5-5 4 4 3-3 6 6 M8.5 9.5h.01`,spritesheet:`M3 4h18v16H3z M9 4v16 M15 4v16 M3 12h18`,model:`M12 2l9 5v10l-9 5-9-5V7z M12 12l9-5 M12 12L3 7 M12 12v10`,animation:`M12 2a10 10 0 1 0 10 10 M22 12l-3-3m3 3l3-3 M12 7v5l3 3`},iR={texture:{en:`image (texture) — Sprite2D.texture references it as "$key".`,ko:`이미지(텍스처) — Sprite2D.texture에서 "$키"로 참조합니다.`},spritesheet:{en:`spritesheet — AnimatedSprite2D slices it into named frame animations.`,ko:`스프라이트시트 — AnimatedSprite2D가 이름 붙은 프레임 애니메이션으로 자릅니다.`},model:{en:`3D model (GLB/glTF/VRM) — ModelInstance3D.model references it as "$key".`,ko:`3D 모델(GLB/glTF/VRM) — ModelInstance3D.model에서 "$키"로 참조합니다.`},animation:{en:`animation clips (GLB, in memory — drawn nowhere) — any model can play them; mixamo retargets onto VRM.`,ko:`애니메이션 클립(GLB, 메모리 전용 — 그려지지 않음) — 어떤 모델이든 재생 가능, mixamo는 VRM에 자동 리타게팅.`}};function aR(e){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);t.setAttribute(`viewBox`,`0 0 24 24`),t.setAttribute(`width`,`13`),t.setAttribute(`height`,`13`),t.setAttribute(`fill`,`none`),t.setAttribute(`stroke`,`currentColor`),t.setAttribute(`stroke-width`,`1.8`),t.setAttribute(`aria-hidden`,`true`);let n=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return n.setAttribute(`d`,rR[e]??`M4 4h16v16H4z`),t.appendChild(n),t.classList.add(`asset-icon-${e}`),t}function oR(e,t){document.querySelector(`.balloon`)?.remove();let n=iR[t];if(!n)return;let r=document.createElement(`div`);r.className=`balloon floating`;let i=document.createElement(`div`);i.className=`balloon-title`,i.textContent=t;let a=document.createElement(`span`);a.textContent=jL(n),r.append(i,a),document.body.appendChild(r);let o=e.getBoundingClientRect();r.style.left=`${o.right+8}px`,r.style.top=`${Math.max(8,o.top-8)}px`;let s=()=>{r.remove(),document.removeEventListener(`pointerdown`,s,!0)};setTimeout(()=>document.addEventListener(`pointerdown`,s,!0),0)}function sR(e){let t=document.createElement(`div`);t.className=`field uid-line`;let n=document.createElement(`span`);n.textContent=`key`;let r=document.createElement(`div`);r.className=`uid-value`;let i=document.createElement(`code`);i.textContent=`$${e}`;let a=document.createElement(`button`);return a.type=`button`,a.className=`uid-copy`,a.title=`Copy key`,a.innerHTML=`<svg aria-hidden="true" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`,a.addEventListener(`click`,()=>{navigator.clipboard?.writeText(`$${e}`),a.classList.add(`copied`),setTimeout(()=>a.classList.remove(`copied`),600)}),r.append(i,a),t.append(n,r),t}function cR(e,t){let n=t.includes(`/`)?t.slice(0,t.lastIndexOf(`/`)):``,r=document.createElement(`select`),i=new Set([``]);for(let t of Object.keys(e.working.assets??{})){let e=t.split(`/`);for(let t=1;t<e.length;t++)i.add(e.slice(0,t).join(`/`))}for(let t of e.pendingGroups)i.add(t);for(let e of[...i].sort()){let t=document.createElement(`option`);t.value=e,t.textContent=e===``?`(root)`:`${e}/`,e===n&&(t.selected=!0),r.appendChild(t)}r.addEventListener(`change`,()=>{e.moveAsset(t,r.value)});let a=document.createElement(`label`);a.className=`field`;let o=document.createElement(`span`);return o.textContent=`group`,a.append(o,r),a}function lR(e){e&&(e.addEventListener(`keydown`,e=>{e.key===`/`&&e.preventDefault()}),e.addEventListener(`input`,()=>{e.value.includes(`/`)&&(e.value=e.value.replace(/\//g,``))}))}function uR(e){let t=document.createElement(`div`);t.className=`section-title`,t.textContent=e;let n=document.createElement(`span`);return n.className=`rule`,t.appendChild(n),t}var dR=window.parent!==window,fR=new URLSearchParams(window.location.search).get(`parentOrigin`),pR=!1;function mR(e){if(dR){if(!fR){pR||(pR=!0,console.warn(`incanto-editor: embedded without ?parentOrigin=<origin> — postMessage disabled`));return}window.parent.postMessage(e,fR)}}var hR={ready(e,t,n){mR({type:`incanto-editor:ready`,input:e,output:t,version:n})},open(e,t){mR({type:`incanto-editor:open`,input:e,output:t})},change(e){mR({type:`incanto-editor:change`,dirty:e})},save(e,t,n){mR({type:`incanto-editor:save`,input:e,output:t,data:n})},error(e){mR({type:`incanto-editor:error`,message:e})}},gR=[[`Core`,e=>!e.endsWith(`2D`)&&!e.endsWith(`3D`)&&e!==`Label`&&e!==`UILayer`&&e!==`NetworkSpawner`],[`2D`,e=>e.endsWith(`2D`)&&!/Body|Area|Controller/.test(e)||e===`Label`||e===`UILayer`],[`2D Physics`,e=>e.endsWith(`2D`)&&/Body|Area|Controller/.test(e)],[`3D`,e=>e.endsWith(`3D`)&&!/Body|Area|Controller/.test(e)],[`3D Physics`,e=>e.endsWith(`3D`)&&/Body|Area|Controller/.test(e)],[`Network`,e=>e===`NetworkSpawner`]],_R=[...gR,[`Other`,e=>gR.every(([,t])=>!t(e))]],vR={title:{en:`How Incanto scenes work`,ko:`Incanto 씬은 어떻게 동작하나`},sections:[{heading:{en:`Everything is a node in a tree`,ko:`모든 것은 트리 위의 노드`},text:{en:`A scene is ONE tree of typed nodes (Godot-style). Each node has a name (unique among its siblings), a type that defines its props and behavior, optional children, and an optional scene-wide-unique uid. The whole structure lives in a *.scene.json file — there is no hidden state: what you see in this editor IS the file.`,ko:`씬은 타입을 가진 노드들의 단일 트리입니다(Godot 방식). 각 노드는 이름(형제 간 유일), props와 동작을 결정하는 타입, 선택적 자식들, 그리고 선택적인 씬 전역 유일 uid를 가집니다. 전체 구조가 *.scene.json 파일 하나에 들어있고 숨겨진 상태는 없습니다 — 이 에디터에서 보는 것이 곧 파일 그 자체입니다.`}},{heading:{en:`Props are delta-only`,ko:`Props는 변경분만 기록`},text:{en:`Every prop has a default defined by the engine. The JSON only stores values that DIFFER from the default — so files stay small and diffs stay meaningful. This editor follows the same rule: set a value back to its default and it disappears from the file.`,ko:`모든 prop에는 엔진이 정의한 기본값이 있습니다. JSON에는 기본값과 다른 값만 기록되어 파일이 작고 diff가 의미를 가집니다. 이 에디터도 같은 규칙을 따릅니다 — 값을 기본값으로 되돌리면 파일에서 사라집니다.`}},{heading:{en:`Addressing: paths, names, uid, groups`,ko:`노드 찾기: 경로·이름·uid·그룹`},text:{en:`Code reaches nodes four ways: a path like "Player/Skin" (relative) or "%Unique" (marked-unique name), getNodesByName("Enemy") which returns a LIST (names repeat across the tree), getNodeByUid("n_x1y2") which returns exactly one node and survives moves/renames, and groups — free tags for queries like "every coin".`,ko:`코드는 네 가지 방법으로 노드에 접근합니다: "Player/Skin" 같은 경로(상대) 또는 "%Unique"(유일 표시 이름), 트리 전체에서 같은 이름을 모두 찾는 getNodesByName("Enemy") — 이름은 중복될 수 있어 리스트가 돌아옵니다 —, 정확히 한 노드를 돌려주고 이동/개명에도 살아남는 getNodeByUid("n_x1y2"), 그리고 "모든 코인"처럼 묶어 조회하는 자유 태그 groups.`}},{heading:{en:`Signals connect, behaviors act`,ko:`시그널로 잇고 비헤이비어로 움직인다`},text:{en:`Nodes emit signals (an Area2D fires triggerEnter, a Timer fires timeout). The scene's "connections" wire a signal to a handler — declaratively, in JSON. Game logic itself is a Behavior: a TypeScript class in YOUR game, attached by name via "script". The inspector's CONNECTIONS section shows and edits these links on the selected node — what it emits, what reaches it, and any end that no longer resolves. The handler code itself lives in your game.`,ko:`노드는 시그널을 발산합니다(Area2D의 triggerEnter, Timer의 timeout). 씬의 "connections"가 시그널을 핸들러에 선언적으로(JSON으로) 연결합니다. 게임 로직 자체는 Behavior — 게임 쪽 TypeScript 클래스이며 "script"에 이름으로 연결됩니다. 인스펙터의 CONNECTIONS 섹션이 선택한 노드의 연결을 보여주고 편집합니다 — 나가는 것, 들어오는 것, 그리고 더 이상 찾을 수 없는 끝. 핸들러 코드 자체는 게임에 있습니다.`}},{heading:{en:`Assets are declared, then referenced`,ko:`에셋은 선언하고 $키로 참조`},text:{en:`The scene header declares assets (textures, spritesheets, 3D models, animation clips) under a key; nodes reference them as "$key". Animations are data too: an {type:"animation"} asset loads GLB clips into memory and any ModelInstance3D can play them — Mixamo clips retarget onto VRM avatars automatically.`,ko:`씬 헤더에서 에셋(텍스처·스프라이트시트·3D 모델·애니메이션 클립)을 키로 선언하고, 노드는 "$key"로 참조합니다. 애니메이션도 데이터입니다 — {type:"animation"} 에셋이 GLB 클립을 메모리에 올리고 어떤 ModelInstance3D든 재생할 수 있으며, Mixamo 클립은 VRM 아바타에 자동 리타게팅됩니다.`}}]},Q=(e,t,...n)=>({type:e,summary:t,body:n}),yR=[{id:`core`,label:{en:`Core`,ko:`Core`},intro:{en:`Dimension-free building blocks: plain containers and the game clock. They render nothing themselves.`,ko:`차원과 무관한 기본 블록 — 순수 컨테이너와 게임 시계입니다. 스스로는 아무것도 그리지 않습니다.`},nodes:[Q(`Node`,{en:`A plain container with no transform.`,ko:`변환 없이 자식을 묶는 순수 컨테이너.`},{en:`Use it to group related nodes (all coins, all UI) without affecting their positions. Lifecycle, signals, groups, script — everything works; it just has no visual or spatial meaning of its own.`,ko:`위치에 영향을 주지 않으면서 관련 노드(코인 전부, UI 전부)를 묶을 때 씁니다. 라이프사이클·시그널·그룹·스크립트가 모두 동작하며, 시각적·공간적 의미만 없습니다.`}),Q(`Timer`,{en:"A serializable countdown that emits `timeout`.",ko:"`timeout` 시그널을 쏘는 직렬화 가능한 카운트다운."},{en:`Set waitTime (seconds), optionally autostart or oneShot, and connect its timeout signal to any handler. Because it is a node, the whole timing setup lives in the scene file — agents can read and tune it.`,ko:`waitTime(초)을 정하고 autostart·oneShot을 선택한 뒤 timeout 시그널을 핸들러에 연결하세요. 노드이기 때문에 타이밍 설정 전체가 씬 파일에 남아 에이전트가 읽고 조정할 수 있습니다.`}),Q(`Respawn`,{en:`Catches whatever it hangs off when it leaves the world, and puts it back.`,ko:`부모가 월드 밖으로 떨어지면 붙잡아 원래 자리로 되돌립니다.`},{en:`Make it a child of the player. With no props it catches its parent 50 m under the spawn (1000 px in 2D — the same line incanto-playtest calls "fell"), returns it to where it started and zeroes the velocity the fall built up. below names the line, to names the landing, target picks a different node. It emits respawned, and deliberately does not decide what falling COSTS — wire that to a ScoreKeeper or a Health if it should hurt.`,ko:`플레이어의 자식으로 두세요. 프롭 없이도 스폰 50 m 아래(2D는 1000 px — incanto-playtest가 "fell"로 부르는 그 선)에서 부모를 붙잡아 처음 위치로 되돌리고, 낙하로 쌓인 속도를 0으로 만듭니다. below는 그 선, to는 착지 지점, target은 다른 노드를 지정합니다. respawned 시그널을 쏘며, 추락의 "대가"는 일부러 정하지 않습니다 — 피해를 주려면 ScoreKeeper나 Health에 연결하세요.`}),Q(`HudLayer`,{en:`Screen-space HUD overlay above the canvas — parent for UiText/UiBar/UiBanner.`,ko:`캔버스 위 화면 고정 HUD 오버레이 — UiText/UiBar/UiBanner의 부모.`},{en:`A DOM overlay (position:fixed) that never blocks pointer input. Put UI widgets as children; each picks one of 9 anchors (topLeft…bottomRight). Works identically over 2D and 3D renderers; in headless/tests it is a silent no-op. zIndex lifts it above the canvas.`,ko:`포인터 입력을 가로막지 않는 DOM 오버레이(position:fixed)입니다. UI 위젯을 자식으로 두면 각자 9개 앵커(topLeft…bottomRight) 중 하나에 붙습니다. 2D·3D 렌더러 어디서나 동일하게 동작하고, 헤드리스/테스트에서는 조용히 no-op입니다. zIndex로 캔버스 위에 올립니다.`}),Q(`UiText`,{en:`A HUD text line — score, timers, hints.`,ko:`HUD 텍스트 한 줄 — 점수, 타이머, 힌트.`},{en:`Child of HudLayer. Set text/size/color in JSON; update from behaviors: (getNode('%Score') as UiText).text = String(score). shadow adds a soft outline for readability over any scene.`,ko:`HudLayer의 자식. text/size/color를 JSON으로 정하고, 비헤이비어에서 (getNode('%Score') as UiText).text = String(score) 로 갱신하세요. shadow는 어떤 화면 위에서도 읽히도록 부드러운 그림자를 더합니다.`}),Q(`UiBar`,{en:`A labeled progress bar — health, stamina, reload, boss HP.`,ko:`라벨 달린 진행 바 — 체력, 스태미나, 재장전, 보스 HP.`},{en:`Child of HudLayer. Drive value/max from behaviors; the fill animates and turns lowColor under lowThreshold (default 30%). width/height/color/background style it; label prefixes a small caption.`,ko:`HudLayer의 자식. 비헤이비어에서 value/max를 갱신하면 채움이 애니메이션되고 lowThreshold(기본 30%) 아래로 떨어지면 lowColor로 바뀝니다. width/height/color/background로 스타일, label로 작은 캡션을 붙입니다.`}),Q(`UiBanner`,{en:`Center-screen announcements with fade and a queue — "WAVE 2", "YOU DIED".`,ko:`페이드·큐가 있는 중앙 공지 — "WAVE 2", "YOU DIED".`},{en:`Child of HudLayer. Call show('WAVE 2', { color, seconds }) from behaviors; messages queue and fade in/out. seconds 0 = sticky until the next show(). clear() drops everything. Emits bannerShown(text).`,ko:`HudLayer의 자식. 비헤이비어에서 show('WAVE 2', { color, seconds })를 호출하면 메시지가 큐에 쌓여 페이드 인/아웃됩니다. seconds 0이면 다음 show()까지 고정, clear()로 전부 제거. bannerShown(text) 시그널을 냅니다.`}),Q(`UiButton`,{en:`A clickable HUD button — menus, START screens, dialog choices.`,ko:`클릭 가능한 HUD 버튼 — 메뉴, 시작 화면, 대화 선택지.`},{en:`Child of HudLayer. Set text/size/color/background; disabled greys it out. Emits the 'pressed' signal (behaviors: node.on('pressed', ...)); press() triggers it programmatically (gamepad menus, tests).`,ko:`HudLayer의 자식. text/size/color/background를 설정하고 disabled로 비활성화합니다. 'pressed' 시그널을 내며(비헤이비어에서 node.on('pressed', ...)), press()로 코드에서도 누를 수 있습니다(게임패드 메뉴, 테스트).`}),Q(`UiPanel`,{en:`A box that holds other widgets — the thing a menu, options screen or inventory actually is.`,ko:`다른 위젯을 담는 상자 — 메뉴·설정 화면·인벤토리가 실제로 이것입니다.`},{en:`Child of HudLayer. Widgets under it mount INSIDE it, so tree structure becomes screen structure; panels nest. layout column|row|grid with columns (an inventory is a grid panel, one child per slot), plus gap/padding/background/radius/width/height/border. width or height 0 = size to the contents.`,ko:`HudLayer의 자식. 그 아래 위젯들이 이 안에 마운트되어 트리 구조가 화면 구조가 됩니다(중첩 가능). layout은 column|row|grid이고 columns와 함께 씁니다(인벤토리 = grid 패널, 슬롯당 자식 하나). gap/padding/background/radius/width/height/border 지원. width·height가 0이면 내용에 맞춰집니다.`}),Q(`UiImage`,{en:`A picture in the HUD — item icons, portraits, a logo.`,ko:`HUD 안의 그림 — 아이템 아이콘, 초상화, 로고.`},{en:`src takes a url or a $assetKey (declare the icon once like any other asset). fit contain|cover|fill; tint multiplies through the picture, which is how an unaffordable item greys out in one prop; opacity for disabled states.`,ko:`src는 url 또는 $assetKey(아이콘도 다른 에셋처럼 한 번만 선언). fit은 contain|cover|fill, tint는 그림에 곱해져서 살 수 없는 아이템을 프롭 하나로 회색 처리합니다. opacity로 비활성 표현.`}),Q(`UiSlider`,{en:`A value the player sets — volume, sensitivity, difficulty.`,ko:`플레이어가 조절하는 값 — 볼륨, 감도, 난이도.`},{en:`Emits changed(value). label/value/min/max/step/width/color. Setting .value from a behavior updates the control WITHOUT re-emitting, so restoring a saved setting does not fire the handler that saved it.`,ko:`changed(value) 시그널. label/value/min/max/step/width/color. 비헤이비어에서 .value를 설정하면 컨트롤만 갱신되고 changed는 다시 발생하지 않습니다 — 저장된 설정을 복원할 때 저장 핸들러가 다시 도는 것을 막습니다.`}),Q(`UiToggle`,{en:`An on/off switch — mute, invert-Y, fullscreen.`,ko:`켜기/끄기 스위치 — 음소거, Y축 반전, 전체화면.`},{en:`Emits changed(boolean). label/value. Same no-re-emit rule as UiSlider when set from code.`,ko:`changed(boolean) 시그널. label/value. 코드에서 설정할 때 재발생하지 않는 규칙은 UiSlider와 같습니다.`}),Q(`UiLanguageSelect`,{en:`The language picker, already wired.`,ko:`이미 연결된 언어 선택기.`},{en:`Options are the locales the scene declares in "strings", each labeled with its own endonym. Picking one switches the game live and persists it. English is the base: any key a locale omits falls back to it, on purpose.`,ko:`옵션은 씬의 "strings"가 선언한 로케일이며, 각 언어의 자기 이름으로 표시됩니다. 선택하면 즉시 바뀌고 저장됩니다. 영어가 기준이라 로케일이 빠뜨린 키는 의도적으로 영어로 표시됩니다.`}),Q(`Label3D`,{en:`Text standing in the world — a nameplate, a sign, a damage number.`,ko:`월드에 서 있는 텍스트 — 이름표, 표지판, 데미지 숫자.`},{en:`height is the cap height in METRES and the quad follows what the text measures, so a sign is as wide as its words. Faces the camera by default (a damage number read from behind is a bug) and carries a dark outline so it stays readable over anything. Everything else a sprite knows — anchor, tint, opacity, renderOrder — it inherits. For a damage number: set text, then float it up and fade opacity to 0 and queueFree().`,ko:`height는 글자 높이(미터)이고 가로 폭은 텍스트 실측을 따라갑니다. 기본으로 카메라를 향하며(뒤에서 읽히는 데미지 숫자는 버그니까요) 어두운 외곽선이 있어 어떤 배경에서도 읽힙니다. 앵커·틴트·투명도·renderOrder 등 스프라이트의 나머지 기능은 그대로 상속합니다. 데미지 숫자는 text를 넣고 위로 띄우며 opacity를 0으로 보낸 뒤 queueFree() 하면 됩니다.`}),Q(`UiVolumeSlider`,{en:`A volume slider, already wired to a bus.`,ko:`볼륨 슬라이더 — 버스에 이미 연결되어 있습니다.`},{en:`bus picks which one it owns: master (everything), sfx or music. It writes engine.audio, which persists itself, so nothing needs saving. Left unlabelled it names its own bus. Two of them (music + sfx) is the audio menu most games ship.`,ko:`bus로 어느 볼륨을 맡을지 고릅니다 — master(전체), sfx, music. engine.audio에 쓰면 자동 저장되므로 따로 저장할 게 없습니다. label을 비워두면 버스 이름이 표시됩니다. 대부분의 게임은 music + sfx 두 개면 충분합니다.`}),Q(`UiMuteToggle`,{en:`The mute switch — checked means silent.`,ko:`음소거 스위치 — 체크하면 소리가 꺼집니다.`},{en:`Writes engine.audio.muted and persists with the volumes. Follows a mute made anywhere else, so two menus can never disagree.`,ko:`engine.audio.muted에 쓰고 볼륨과 함께 저장됩니다. 다른 곳에서 음소거해도 따라가므로 두 메뉴가 어긋나지 않습니다.`}),Q(`UiQualitySelect`,{en:`Graphics quality — Low, Medium, High. Already wired.`,ko:`그래픽 품질 — Low, Medium, High. 이미 연결되어 있습니다.`},{en:`Low turns off shadows, bloom, post and clouds; Medium keeps shadows but makes them static and drops post; High is everything. Applies live and persists. Antialiasing follows the tier on the NEXT launch — it is a WebGL context attribute and cannot change while a context exists. Picking records a human choice, so device detection never overrides it later.`,ko:`Low는 그림자·블룸·포스트·구름을 끄고, Medium은 그림자를 정적으로 유지하며 포스트를 끄고, High는 전부 켭니다. 즉시 적용되고 저장됩니다. 안티에일리어싱만 다음 실행부터 반영됩니다(WebGL 컨텍스트 속성이라 생성 후에는 못 바꿉니다). 사람이 고른 값으로 기록되어 이후 자동 감지가 덮어쓰지 않습니다.`}),Q(`UiFrameCapSelect`,{en:`Frame rate cap — 30, 60, 120 or Unlimited.`,ko:`프레임 제한 — 30, 60, 120 또는 무제한.`},{en:`Gates the whole frame, not just the render, so it saves CPU as well as GPU — a cooler phone and a longer battery. Unlimited (0) is the default. Restrict the list with options, e.g. "60,120,0".`,ko:`렌더뿐 아니라 프레임 전체를 제한하므로 GPU와 CPU를 함께 아낍니다 — 발열과 배터리에 유리합니다. 기본값은 무제한(0). options로 목록을 줄일 수 있습니다(예: "60,120,0").`}),Q(`UiRenderScaleSelect`,{en:`Resolution scale — 50%, 75%, 100%.`,ko:`해상도 배율 — 50%, 75%, 100%.`},{en:`The cheapest frames on a weak GPU: at 75% the fragment shaders run over 56% of the pixels for a slightly softer image and nothing else, where dropping a quality tier costs the shadows outright. Multiplies with the engine's automatic resolution governor rather than fighting it.`,ko:`저사양 GPU에서 가장 값싼 프레임: 75%면 픽셀의 약 56%만 셰이딩하므로 이미지가 약간 부드러워질 뿐이지만, 품질 단계를 낮추면 그림자가 통째로 사라집니다. 엔진의 자동 해상도 조절과 충돌하지 않고 곱해집니다.`}),Q(`UiSelect`,{en:`One of several — quality, resolution, language.`,ko:`여러 개 중 하나 — 품질, 해상도, 언어.`},{en:`options is a comma-separated list ("low,medium,high"); value is the current one. Emits changed(value).`,ko:`options는 쉼표로 구분된 목록("low,medium,high"), value가 현재 선택입니다. changed(value) 시그널.`}),Q(`UiDialogue`,{en:`A typewriter dialogue box with a queue and choice buttons — the RPG conversation layer.`,ko:`타자기 효과·큐·선택지 버튼을 갖춘 대화창 — RPG 대화 레이어.`},{en:`Child of HudLayer (anchor bottom by default). say(speaker, text, choices?) queues lines; clicking (or advance()) reveals then advances; choice lines wait for choose(i). Signals: lineShown(text), choiceMade(index), dialogueFinished. charsPerSecond 0 = instant. Check .active to pause player input during conversations.`,ko:`HudLayer의 자식(기본 anchor bottom). say(화자, 텍스트, 선택지?)로 줄을 큐에 넣고, 클릭(또는 advance())이 전체 공개→다음 줄로 진행하며, 선택지 줄은 choose(i)를 기다립니다. 시그널: lineShown(text), choiceMade(index), dialogueFinished. charsPerSecond 0이면 즉시 표시. 대화 중 플레이어 입력을 멈추려면 .active를 확인하세요.`}),Q(`AudioPlayer`,{en:`Plays a sound: zero-asset procedural SFX, BGM loops, or one-shot effects.`,ko:`소리 재생 — 무에셋 절차적 효과음, 배경음 루프, 단발 효과음.`},{en:`Set preset (coin/jump/hurt/explosion/…) for an instant zero-asset SFX (pitch/seed vary it), or leave it "custom" and set src (URL or "$assetKey"). volume 0..1; bus routes through engine.audio (sfx|music) for global volume/mute; loop for music; autoplay starts on ready (browsers may hold it until the first user gesture). Call play()/stop() from game code. Dimension-free — 2D and 3D alike.`,ko:`preset(coin/jump/hurt/explosion/…)을 설정하면 즉시 무에셋 효과음이 납니다(pitch·seed로 변형). 아니면 "custom"으로 두고 src(URL 또는 "$에셋키")를 쓰세요. volume은 0..1, bus는 engine.audio(sfx|music)를 통해 전역 볼륨/음소거에 연결, 음악은 loop, autoplay는 준비되면 재생합니다(브라우저가 첫 입력까지 보류 가능). 게임 코드에서 play()/stop()을 부르세요. 2D·3D 어디서나 동작합니다.`})]},{id:`2d`,label:{en:`2D`,ko:`2D`},intro:{en:`The 2D world is y-down pixels: 1 unit = 1 px, (0,0) top-left, rotation in clockwise degrees. Rendering needs a current Camera2D.`,ko:`2D 세계는 y-아래 픽셀 좌표입니다: 1유닛=1px, (0,0)은 좌상단, 회전은 시계방향 도(degree). 렌더링에는 current 카메라(Camera2D)가 필요합니다.`},nodes:[Q(`Node2D`,{en:`The 2D transform container (position/rotation/scale).`,ko:`2D 변환 컨테이너(position/rotation/scale).`},{en:`Children inherit its transform — move the parent, everything follows. renderOrder orders drawing; visible hides the subtree.`,ko:`자식은 변환을 상속합니다 — 부모를 움직이면 전부 따라옵니다. renderOrder로 그리기 순서를, visible로 서브트리 표시를 제어합니다.`}),Q(`Sprite2D`,{en:`A textured quad.`,ko:`텍스처 사각형(스프라이트).`},{en:`texture is "$assetKey" from the scene assets. anchor [0.5,0.5] centers; flipX/flipY mirror; tint multiplies color; opacity fades. Size comes from the texture × scale.`,ko:`texture는 씬 에셋의 "$키"입니다. anchor [0.5,0.5]면 중앙 기준, flipX/flipY로 반전, tint로 색 곱, opacity로 투명도. 크기는 텍스처 × scale로 정해집니다.`}),Q(`ColorRect2D`,{en:`A flat colored rectangle — no texture needed.`,ko:`단색 사각형 — 텍스처 불필요.`},{en:`size [w,h] px, color, opacity, anchor. Backgrounds, platforms, walls, UI panels, generated-level tiles (maze2d/dungeon2d emit these) — blocky art without any asset.`,ko:`size [w,h] px, color, opacity, anchor. 배경·플랫폼·벽·UI 패널·생성 레벨 타일(maze2d/dungeon2d가 이걸 만듭니다) — 에셋 없이 만드는 블록 그래픽입니다.`}),Q(`TileMap2D`,{en:`A whole tile level as ONE node — grid render + merged static colliders.`,ko:`타일 레벨 전체를 노드 하나로 — 그리드 렌더 + 병합된 정적 콜라이더.`},{en:`Author cells as rows of characters: "." / space = empty, digits 0-9 = atlas tile index, other chars map through legend ({"G": 12}). texture is a "$atlas" asset read left-to-right top-to-bottom in tileSize squares (columns: 0 derives from the texture width). Tile indices listed in solid become static colliders, greedy-merged into a few rectangles. Cell (0,0) hangs its top-left on the node origin.`,ko:`cells를 문자 행으로 작성합니다: "."/공백 = 빈 칸, 숫자 0-9 = 아틀라스 타일 번호, 그 외 문자는 legend({"G": 12})로 매핑. texture는 tileSize 정사각형을 좌→우, 상→하로 읽는 "$아틀라스" 에셋입니다(columns: 0이면 텍스처 폭에서 유도). solid에 나열된 타일 번호는 정적 콜라이더가 되며 소수의 직사각형으로 탐욕 병합됩니다. (0,0) 칸의 좌상단이 노드 원점에 걸립니다.`}),Q(`AnimatedSprite2D`,{en:`Spritesheet animation player.`,ko:`스프라이트시트 애니메이션 플레이어.`},{en:`Point sheet at a "$sheet" asset, define animations as named frame ranges with fps/loop in JSON, set autoplay. Emits animationFinished(name) for one-shot chains.`,ko:`sheet에 "$시트" 에셋을 연결하고, JSON에 fps/loop를 가진 이름별 프레임 구간으로 animations를 정의한 뒤 autoplay를 지정하세요. 단발 애니메이션 연결을 위해 animationFinished(name)를 발산합니다.`}),Q(`Camera2D`,{en:`The 2D view: follow, zoom, limits.`,ko:`2D 시점 — 추적·줌·경계.`},{en:`position is the view CENTER. follow tracks a node path with smoothing (0..1, higher = snappier). limits [minX,minY,maxX,maxY] clamps the view inside a world region. current: true makes it THE camera.`,ko:`position은 화면의 중심입니다. follow가 노드 경로를 smoothing(0..1, 높을수록 빠릿)으로 추적합니다. limits [minX,minY,maxX,maxY]가 시점을 월드 영역 안에 가둡니다. current: true인 카메라가 실제 시점이 됩니다.`}),Q(`Particles2D`,{en:`A 2D particle emitter (fire, sparks, smoke…).`,ko:`2D 파티클 이미터(불·스파크·연기…).`},{en:`Start from a preset (fire/smoke/sparks/…) then override any prop: rate, lifetime/speed ranges, direction + spread, gravity, size/color/alpha start→end, additive blend. burst > 0 with emitting: false makes a one-shot that emits finished. Animates LIVE in this editor.`,ko:`preset(fire/smoke/sparks/…)에서 시작해 어떤 prop이든 덮어쓰세요: rate, lifetime/speed 구간, direction+spread, gravity, size/color/alpha 시작→끝, additive blend. emitting: false에 burst > 0이면 단발 발사 후 finished를 발산합니다. 이 에디터에서 라이브로 움직입니다.`}),Q(`Label`,{en:`Text rendered to a quad.`,ko:`텍스트를 그리는 노드.`},{en:`text/fontSize/color/font/align — rendered via CanvasTexture, so any system font string works. Inside a UILayer it pins to the screen (HUD).`,ko:`text/fontSize/color/font/align — CanvasTexture로 그려져 시스템 폰트 문자열을 그대로 쓸 수 있습니다. UILayer 아래에 두면 화면에 고정됩니다(HUD).`}),Q(`UILayer`,{en:`A screen-space subtree (HUD).`,ko:`화면 고정 서브트리(HUD).`},{en:`Everything under it ignores the camera: positions are screen pixels from the top-left. Score counters, prompts, menus go here.`,ko:`이 아래의 모든 것은 카메라를 무시합니다 — 좌상단 기준 화면 픽셀 좌표입니다. 점수, 안내 문구, 메뉴를 여기에 둡니다.`})]},{id:`2d-physics`,label:{en:`2D Physics`,ko:`2D 물리`},intro:{en:`Rapier-backed. Colliders are PROPS ({shape, …}) — the green dashed wireframes in this editor. Physics runs when the game calls enablePhysics2D (and in play mode). Gravity lives on the scene row.`,ko:`Rapier 기반입니다. 콜라이더는 prop({shape, …})이며 에디터의 초록 점선이 그것입니다. 물리는 게임이 enablePhysics2D를 부를 때(그리고 플레이 모드에서) 돌고, 중력은 씬 행에 있습니다.`},nodes:[Q(`StaticBody2D`,{en:`Immovable collision: ground, walls, platforms.`,ko:`움직이지 않는 충돌체 — 바닥·벽·플랫폼.`},{en:`Other bodies collide with it; it never moves. Cheapest body type — use it for all level geometry.`,ko:`다른 바디가 부딪히지만 자신은 절대 움직이지 않습니다. 가장 저렴한 바디 — 레벨 지형 전부에 쓰세요.`}),Q(`RigidBody2D`,{en:`Fully simulated: falls, bounces, pushes.`,ko:`완전 시뮬레이션 — 떨어지고 튕기고 밀립니다.`},{en:`Gravity and collisions drive it. Set linearVelocity to launch. For player characters prefer CharacterBody2D (direct control).`,ko:`중력과 충돌이 움직임을 결정합니다. linearVelocity로 발사하세요. 플레이어 캐릭터에는 직접 제어가 가능한 CharacterBody2D를 권합니다.`}),Q(`CharacterBody2D`,{en:`Kinematic character: you set velocity, it slides.`,ko:`키네마틱 캐릭터 — 속도를 주면 미끄러지듯 이동.`},{en:`moveAndSlide() resolves collisions without physics pushing back; isOnFloor() gates jumps. Sensors (Area2D) do not block it but still fire triggers.`,ko:`moveAndSlide()가 밀려나지 않으면서 충돌을 처리하고 isOnFloor()로 점프를 판정합니다. 센서(Area2D)는 길을 막지 않으면서 트리거를 발사합니다.`}),Q(`Area2D`,{en:`A sensor: overlap triggers, no collision response.`,ko:`센서 — 겹침 감지만, 충돌 반응 없음.`},{en:`Fires triggerEnter(other)/triggerExit(other). Coins, checkpoints, damage zones. Filter with other.isInGroup("player").`,ko:`triggerEnter(other)/triggerExit(other)를 발산합니다. 코인·체크포인트·데미지 존에 쓰고, other.isInGroup("player")로 거릅니다.`}),Q(`CharacterController2D`,{en:`Zero-code platformer/top-down movement.`,ko:`코드 없는 플랫포머/탑다운 이동.`},{en:`Put it UNDER a CharacterBody2D. mode "platformer" (gravity + jump via jumpAction) or "topDown" (free 2-axis). Reads the scene input map actions (moveAction/jumpAction). maxSpeed/jumpHeight are intent-level numbers.`,ko:`CharacterBody2D의 자식으로 두세요. mode는 "platformer"(중력+jumpAction 점프) 또는 "topDown"(자유 2축)이며 씬 입력 맵의 액션(moveAction/jumpAction)을 읽습니다. maxSpeed/jumpHeight는 의도 그대로의 숫자입니다.`}),Q(`Joint2D`,{en:`A physics joint linking its parent body to a target body — weld, hinge, rope, spring.`,ko:`부모 바디와 대상 바디를 잇는 물리 조인트 — 용접, 힌지, 로프, 스프링.`},{en:`Child of body A (a physics body); "target" is a node path to body B. type: fixed (rigid weld) / revolute (pin at the anchors) / rope (caps anchor distance at length px; 0 = measured at creation) / spring (pulls toward length with stiffness/damping). anchor/targetAnchor are LOCAL px offsets.`,ko:`바디 A(물리 바디)의 자식으로 두고 "target"에 바디 B의 노드 경로를 줍니다. type: fixed(강체 용접) / revolute(앵커 핀 힌지) / rope(앵커 간 거리를 length px로 제한, 0이면 생성 시 실측) / spring(stiffness/damping으로 length를 향해 당김). anchor/targetAnchor는 로컬 px 오프셋.`})]},{id:`3d`,label:{en:`3D`,ko:`3D`},intro:{en:`Meters, y-up, rotations in degrees. Standard materials need LIGHT — add a DirectionalLight3D or scene ambient, or you get silhouettes.`,ko:`미터 단위, y-위, 회전은 도(degree)입니다. 표준 머티리얼은 빛이 필요합니다 — DirectionalLight3D나 씬 ambient가 없으면 실루엣만 보입니다.`},nodes:[Q(`Node3D`,{en:`The 3D transform container.`,ko:`3D 변환 컨테이너.`},{en:`position [x,y,z] in meters, rotation [x,y,z] in degrees, scale per axis. Children inherit.`,ko:`position [x,y,z] 미터, rotation [x,y,z] 도, scale은 축별. 자식이 상속합니다.`}),Q(`MeshInstance3D`,{en:`A primitive mesh + material.`,ko:`프리미티브 메시 + 머티리얼.`},{en:`mesh: box/sphere/plane/cylinder…, size per primitive, material {color, roughness, metalness, emissive, emissiveIntensity, wireframe, map, normalMap, repeat} (this editor gives it swatches, sliders, texture-URL fields, and a repeat [u,v] tiling vector). map/normalMap are texture URLs; repeat only takes effect with a map. castShadow/receiveShadow per node.`,ko:`mesh: box/sphere/plane/cylinder…, 프리미티브별 size, material {color, roughness, metalness, emissive, emissiveIntensity, wireframe, map, normalMap, repeat}(에디터가 스와치·슬라이더·텍스처 URL 입력·repeat [u,v] 타일링 벡터 제공). map/normalMap은 텍스처 URL, repeat는 map이 있을 때만 적용. 그림자는 castShadow/receiveShadow.`}),Q(`LoftMesh3D`,{en:`A smooth swept hull (loft).`,ko:`부드러운 스윕 선체(로프트).`},{en:`sections: ≥2 cross-section stations {z, width, height, y, corner 0..1} interpolated into ONE smooth curved surface — vehicle bodies, glass canopies, boat hulls. slices/smooth control tessellation. Same material as MeshInstance3D minus textures (no UVs); pair clearcoat paint or high-envMapIntensity glass with the smooth normals for the automotive look.`,ko:`sections: 단면 스테이션 {z, width, height, y, corner 0..1} 2개 이상을 보간해 하나의 매끈한 곡면을 만듭니다 — 차체, 유리 캐노피, 선체. slices/smooth로 테셀레이션 조절. material은 MeshInstance3D와 동일하되 텍스처 제외(UV 없음). clearcoat 도장이나 높은 envMapIntensity 유리를 곡면 법선과 조합하면 자동차 룩이 납니다.`}),Q(`ModelInstance3D`,{en:`A GLB/glTF/VRM model file.`,ko:`GLB/glTF/VRM 모델 파일.`},{en:'model: "$assetKey" or URL. targetHeight scales the model to stand N units tall (run `npx incanto-model file.glb` to read its real size first). animation plays an embedded clip name OR an "$animation" asset — Mixamo clips retarget onto VRM humanoids automatically. One node per VRM asset (the avatar runtime mounts live). To make it SOLID, park it under a body with collider {shape:"auto"}: the collider is built from the model\'s own triangles — a triangle mesh on a static body (keeps its holes, so you walk through an archway) and a convex hull on a moving one.',ko:'model은 "$에셋키" 또는 URL입니다. targetHeight가 모델을 N유닛 높이로 맞춥니다(먼저 `npx incanto-model 파일.glb`로 실제 크기를 확인하세요). animation은 내장 클립 이름 또는 "$애니메이션" 에셋을 재생하며, Mixamo 클립은 VRM 휴머노이드에 자동 리타게팅됩니다. VRM 에셋은 노드 하나만 쓸 수 있습니다(아바타 런타임이 라이브로 마운트됨). 단단하게 만들려면 collider {shape:"auto"}인 바디 아래에 두세요 — 모델 자신의 삼각형에서 콜라이더가 만들어집니다(정적 바디는 트라이메시라 아치 구멍도 그대로, 움직이는 바디는 볼록 껍질).'}),Q(`Sprite3D`,{en:`A 2D image as a camera-facing billboard (the 2.5D look).`,ko:`카메라를 향하는 2D 빌보드 스프라이트(2.5D 룩).`},{en:`A textured quad that turns to face the camera inside the 3D world (Octopath / Don't Starve / MapleStory-in-3D). texture is an image URL; size is [w,h] in METERS. billboard: "y" stays upright with a screen-aligned yaw — off-center sprites never roll (characters/props), "full" faces it completely (items/FX), "none" is fixed to the node rotation. anchor [0.5,0] plants the feet on the ground. pixelArt nearest-filters for crisp pixels; alphaTest is a hard cutout that depth-sorts against 3D geometry (a tree occludes it); flipX mirrors left/right; tint/opacity recolor.`,ko:`3D 월드 안에서 카메라를 향해 도는 텍스처 쿼드(Octopath/Don't Starve, 3D 속 메이플스토리 룩). texture는 이미지 URL, size는 [너비,높이] 미터. billboard: "y"는 세로로 선 채 카메라 방향과 정렬된 yaw — 화면 가장자리에서도 기울지 않음(캐릭터/사물), "full"은 완전히 향함(아이템/FX), "none"은 노드 회전에 고정. anchor [0.5,0]은 발을 바닥에 둡니다. pixelArt는 nearest 필터로 픽셀을 또렷하게, alphaTest는 3D 지형과 깊이정렬되는 하드 컷아웃(나무가 가림), flipX는 좌우 반전, tint/opacity로 색·투명도.`}),Q(`AnimatedSprite3D`,{en:`A billboard sprite that plays spritesheet animations.`,ko:`스프라이트시트 애니를 재생하는 빌보드 스프라이트.`},{en:`Everything Sprite3D does, plus frame animation. sheet is a spritesheet image URL whose cells are frameWidth×frameHeight; animations maps a name to {frames, fps, loop} where frames is an inclusive [start,end] range or an explicit list; autoplay starts one on load. Game code calls play("walk") / stop(); a non-looping clip clamps on its last frame and emits animationFinished(name) — chain attack→idle from it.`,ko:`Sprite3D의 모든 기능 + 프레임 애니. sheet는 frameWidth×frameHeight 칸을 가진 스프라이트시트 URL, animations는 이름→{frames, fps, loop}(frames는 포함 [시작,끝] 범위 또는 명시 목록), autoplay는 로드 시 하나를 시작. 게임 코드에서 play("walk")/stop() 호출, 비반복 클립은 마지막 프레임에 머물며 animationFinished(name)를 emit(attack→idle 연결).`}),Q(`Billboard3D`,{en:`A group that turns toward the camera — children follow.`,ko:`카메라를 향해 도는 그룹 — 자식들이 함께 회전.`},{en:`A transform container that orients itself toward the camera every frame; children inherit the rotation, so hang world-space UI under it — HP bars, markers, floating icons (text is a canvas-rendered texture on a child Sprite3D). mode: "screen" (default) copies the camera orientation so a child rectangle stays an upright rectangle anywhere on screen (a yaw-only look-at visibly tilts off-center shapes under a pitched camera); "y" stays upright with a screen-aligned yaw (no off-center roll); "none" turns billboarding off. While billboarding, the node's own rotation prop (and the rotate gizmo) is overwritten every frame — switch to "none" to pose children, then switch back. Unlike Sprite3D (a textured quad that spins only its own image), Billboard3D rotates the whole group.`,ko:`매 프레임 카메라를 향해 자신을 회전시키는 변환 컨테이너로, 자식이 회전을 상속합니다 — HP바·마커·아이콘 같은 월드 UI를 자식으로 붙이세요(텍스트는 캔버스로 그린 텍스처를 자식 Sprite3D에). mode: "screen"(기본)은 카메라 자세를 그대로 복사해 자식 직사각형이 화면 어디서든 똑바른 직사각형으로 보입니다(yaw만 도는 look-at은 기울어진 카메라에서 중앙 밖 도형이 눈에 띄게 비스듬해짐); "y"는 세로로 선 채 카메라로 yaw만; "none"은 빌보드 끔. 빌보드 중에는 노드 자신의 rotation(회전 기즈모 포함)이 매 프레임 덮어써집니다 — 자식을 배치할 땐 "none"으로 바꿨다가 되돌리세요. 자기 그림만 도는 Sprite3D(텍스처 쿼드)와 달리 그룹 전체가 회전합니다.`}),Q(`Camera3D`,{en:`The 3D view.`,ko:`3D 시점.`},{en:`Perspective camera; fov in degrees; current: true selects it. Use the editor's "game cam" (0) to preview exactly what it renders.`,ko:`원근 카메라이며 fov는 도 단위, current: true가 실제 시점이 됩니다. 에디터의 "game cam"(0)으로 정확한 렌더 결과를 미리 보세요.`}),Q(`DirectionalLight3D`,{en:`Sun-like light from a direction.`,ko:`태양광 — 방향에서 평행하게.`},{en:`Position sets the direction toward the origin. intensity/color; pair with scene ambient for soft fill.`,ko:`위치가 원점을 향한 방향을 정합니다. intensity/color를 조절하고 부드러운 채움광은 씬 ambient와 함께 쓰세요.`}),Q(`OmniLight3D`,{en:`A point light radiating everywhere.`,ko:`점광 — 사방으로 퍼지는 빛.`},{en:`Lamps, torches, glows. range limits reach; intensity/color shape the falloff.`,ko:`램프·횃불·발광체. range로 도달 거리를, intensity/color로 감쇠를 만듭니다.`}),Q(`Particles3D`,{en:`A 3D particle emitter (fire, magic, weather…).`,ko:`3D 파티클 이미터(불·마법·날씨…).`},{en:`The same preset + override model as Particles2D, in meters with [x,y,z] gravity. Camera-facing billboard quads, instanced — hundreds are cheap. Animates LIVE in this editor.`,ko:`Particles2D와 같은 preset+덮어쓰기 모델을 미터 단위와 [x,y,z] 중력으로. 카메라를 향하는 빌보드 쿼드를 인스턴싱해 수백 개도 가볍습니다. 이 에디터에서 라이브로 움직입니다.`}),Q(`Terrain3D`,{en:`Procedural heightfield terrain with biome texture splatting.`,ko:`바이옴 텍스처 스플래팅이 적용된 절차적 하이트필드 지형.`},{en:`Seeded simplex hills displaced once on the CPU; theme (island/alpine/plains/desert/custom) picks the 4 blended biome textures by height and slope. heightAt(x,z) answers the surface height anywhere. For physics, parent it under a StaticBody3D with collider {shape:'heightfield'}.`,ko:`시드 기반 심플렉스 언덕을 CPU에서 한 번 변위합니다. theme(island/alpine/plains/desert/custom)이 높이·경사로 블렌딩되는 바이옴 텍스처 4장을 고릅니다. heightAt(x,z)로 어디서든 지표 높이를 얻고, 물리는 StaticBody3D 아래에 두고 collider {shape:'heightfield'}를 쓰세요.`}),Q(`Water3D`,{en:`A shader-water surface with splash signals.`,ko:`스플래시 신호를 내는 셰이더 물 표면.`},{en:`size [w,d] meters on XZ. quality 'fancy' (default) = FBM wave shader with a trough/surface/peak ramp (colors), CubeCamera reflections (reflection/reflectionInterval) and opt-in shoreline foam; 'simple' = the cheap sine material (color). Bodies crossing the surface emit entered/exited(body) and raise ripples (interaction). Volumetric gameplay still wants an Area3D. Waves animate LIVE in this editor.`,ko:`XZ 평면에 size [w,d] 미터. quality 'fancy'(기본)는 FBM 파도 셰이더 — trough/surface/peak 램프(colors), CubeCamera 반사(reflection/reflectionInterval), 옵트인 해안 거품(foam). 'simple'은 저사양용 사인파 머티리얼(color). 바디가 수면을 지나면 entered/exited(body) 신호와 물결이 일어납니다(interaction). 부피 기반 게임플레이엔 여전히 Area3D를 쓰세요. 이 에디터에서 파도가 라이브로 움직입니다.`}),Q(`River3D`,{en:`Running water derived from a path and the ground under it.`,ko:`경로와 그 아래 지형에서 유도되는 흐르는 물.`},{en:`Author a centerline path [[x,z],…] plus width/widths (a profile source→mouth) and depth; the node samples the Terrain3D underneath and derives the rest. It CARVES ITS OWN BED by default (carve): a trench per reach that heightAt, the collider, the splat and draped vegetation all see, with a floor that only ever falls, so a path over a rise digs through instead of burying the water. Its surface is then FITTED to that ground — never higher than the lowest rim holding it, ending where the ground comes up to meet it (asymmetric on a sloping reach), lying down as a film where a bank has fallen away, so a river can never hang in the air. Plus a current that speeds up where the channel pinches or tips (flowSpeed is the mean) and whitewater from grade, bank shear and thinning column. Boulders in the channel are answered without wiring: the node finds MeshInstance3D/InstancedMesh3D footprints standing in the water column and the current piles a white cushion on the upstream face, tears a wake downstream and bends its sheen around them. A trench thinner than a terrain cell cannot survive the grid: a 2.4 m creek on a 260 m map wants Terrain3D resolution 256. flowForce drags bodies downstream (drag, never thrust) and sampleAt(x,z) answers where a world point sits in the channel. No extra render passes — a map can carry a dozen.`,ko:`중심선 path [[x,z],…]와 width/widths(상류→하류 프로파일), depth만 주면 나머지는 아래 Terrain3D를 샘플링해 유도합니다. 기본적으로 강이 자기 바닥을 직접 팝니다(carve) — 구간마다 하나씩 도랑을 내고, heightAt·콜라이더·스플랫·식생 드레이프가 모두 그 지형을 봅니다. 파낸 바닥은 계속 내려가기만 하므로 경로가 언덕을 넘어도 물이 묻히지 않고 뚫고 흐릅니다. 그리고 수면은 그 지형에 맞춰집니다 — 자기를 담는 가장 낮은 둑보다 높아질 수 없고, 지면이 올라오는 지점에서 끝나며(비스듬한 구간에서는 좌우 폭이 다릅니다), 둑이 아예 없는 쪽에서는 경사면에 얇은 막처럼 누워버립니다. 그래서 강이 공중에 뜨는 일이 없습니다. 여기에 폭이 좁아지거나 경사가 급해지면 빨라지는 유속(flowSpeed는 평균)과 경사·둑 전단·얕아지는 수심에서 나오는 흰 물살이 더해집니다. 수로에 놓인 바위도 배선 없이 반응합니다 — MeshInstance3D/InstancedMesh3D 중 실제로 물기둥과 겹치는 것을 찾아, 상류면에 흰 물이 쌓이고 하류로 후류가 찢어지며 수면 광택이 바위를 돌아 휩니다. 지형 셀보다 얇은 도랑은 그리드에서 살아남지 못합니다 — 260 m 맵의 2.4 m 개울이라면 Terrain3D resolution 256이 필요합니다. flowForce가 바디를 하류로 끌고(밀지 않고 끌어당김), sampleAt(x,z)로 월드 좌표가 수로 어디에 있는지 알 수 있습니다. 추가 렌더 패스가 없어 한 맵에 여러 개를 둘 수 있습니다.`}),Q(`WaterCutout3D`,{en:`Marks its parent as something that holds the water back — a dry hull, a diving bell, a well.`,ko:`부모 오브젝트가 물을 막는다고 표시 — 마른 선실, 잠수종, 우물.`},{en:`Water is ONE surface and knows nothing about interiors, so an open hull floating on it fills with sea every time a crest clears its floor — freeboard alone can never promise otherwise. This node names the geometry that keeps the water out: it MUST be a CHILD of that thing (a hull, a bell, a dock's well, a cave mouth), and the water re-draws the part of it inside the box into its depth pre-pass, then hides behind it exactly as it hides behind any solid object. Nothing is ever cut OUT of the water, so a hole in open sea is impossible: overshoot the box and more of that hull holds water back, undershoot and water stands in the bow. size is the box extent in meters; enabled toggles it live (a scuttled hull starts letting the sea in). Four per water surface; needs quality fancy.`,ko:`물은 하나의 표면이라 '안쪽'이라는 개념이 없습니다. 그래서 뚜껑 없는 배를 띄우면 파도 마루가 바닥을 넘을 때마다 배 안에 바다가 차 보이고, 건현(freeboard)만으로는 절대 막을 수 없습니다. 이 노드는 '물을 막는 지오메트리'를 지정합니다. 반드시 그 물체(선체·잠수종·부두 우물·동굴 입구)의 자식이어야 하며, 물이 상자 안쪽의 그 지오메트리를 자기 깊이 프리패스에 다시 그린 뒤 평범한 불투명 물체 뒤에 숨듯 그 뒤로 숨습니다. 물에서 무언가를 '도려내지' 않으므로 열린 바다에 구멍이 나는 일은 원리적으로 불가능합니다 — 상자가 크면 그 배가 물을 더 많이 막을 뿐이고, 작으면 뱃머리에 물이 남습니다. size는 미터 단위 상자 크기, enabled는 런타임 토글(침수 시작 연출). 수면 하나당 4개, quality fancy 필요.`}),Q(`Foliage3D`,{en:`An instanced grass/flower carpet that sways.`,ko:`바람에 흔들리는 인스턴스 풀밭/꽃밭. `},{en:`kind grass/flowers/reeds scattered over area [w,d] at density (capped by maxInstances — instanced, tens of thousands of blades cheap). Grass defaults to style 'mesh': every instance is a REAL tapered blade curved by a bezier vertex shader — Voronoi-clump hue/lean, groundColor soil roots (match the terrain), sunDirection tip sheen, 2-octave rolling wind, fadeStart/fadeEnd camera LOD, and (interaction) blade-bending around moving bodies. style 'blades' keeps the 8-SDF-blades-per-quad ported shader, 'simple' the legacy quads. colorA/colorB tint bottom→top, sway sets the wind, seed makes the scatter reproducible. avoidWater (on by default) keeps blades OUT of standing and running water — a creek cutting its bed through the field gets banks, not blades waving in the current; turn it off for reeds and paddy fields.`,ko:`kind grass/flowers/reeds를 area [w,d]에 density로 흩뿌립니다(maxInstances 상한 — 인스턴싱이라 수만 가닥도 가벼움). grass는 기본 style 'mesh': 인스턴스 하나하나가 베지어 버텍스 셰이더로 휘어지는 진짜 잎 메시 — 보로노이 클럼프 색/기울기, groundColor 흙빛 뿌리(지형 색에 맞추세요), sunDirection 잎끝 광택, 2옥타브 굽이치는 바람, fadeStart/fadeEnd 카메라 LOD, (interaction) 움직이는 바디 주변 풀 눕힘까지. style 'blades'는 쿼드당 8가닥 SDF 셰이더, 'simple'은 기존 쿼드 룩. colorA/colorB가 아래→위 색, sway가 바람 세기, seed가 배치를 재현 가능하게 합니다. avoidWater(기본 켜짐)는 고인 물·흐르는 물 안에 잎을 심지 않습니다 — 개울이 들판을 가르고 지나가면 물살 속에 풀이 서 있는 대신 둑이 생깁니다. 갈대·논은 꺼서 쓰세요.`}),Q(`Flowers3D`,{en:`Instanced flower PLANTS — stems, leaves, multi-petal heads.`,ko:`인스턴스 꽃밭 — 줄기·잎·여러 장 꽃잎의 진짜 꽃 식물.`},{en:`Real procedural flower plants (curved stem, 2-3 leaves, a 5-8 petal head around a contrasting center disc, 1-3 blooms per plant) scattered over area [w,d]. density is the vibe dial: 'lush' / 'sparse' (default) / 'none', or a number in plants/m². varieties picks a subset of daisy/cosmos/bellflower ([] = all three); palette sets the head colors ([] = white/yellow/violet). clustering 0-1 gathers plants into Voronoi patches that bloom one species + color together; sway bobs the heads in a gentle wind; seed makes the field reproducible. ≤3 varieties → ≤6 draw calls. avoidWater (on by default) keeps plants out of standing and running water — a meadow a stream runs through has a bank of flowers, not flowers in the current.`,ko:`진짜 프로시저럴 꽃 식물(휘어진 줄기, 잎 2-3장, 대비되는 중심 원반을 두른 꽃잎 5-8장 머리, 포기당 꽃 1-3송이)을 area [w,d]에 흩뿌립니다. density가 바이브 다이얼: 'lush'(풍성하게) / 'sparse'(듬성듬성, 기본) / 'none'(없게) 또는 m²당 개수. varieties는 daisy/cosmos/bellflower 부분집합([] = 셋 다), palette는 꽃 색([] = 흰/노랑/보라). clustering 0-1이 보로노이 패치로 모아 한 패치가 같은 종·같은 색으로 피고, sway가 바람에 머리를 끄덕이며, seed로 배치가 재현됩니다. 품종 ≤3 → 드로우 콜 ≤6. avoidWater(기본 켜짐)는 고인 물·흐르는 물 안에 꽃을 심지 않습니다 — 시내가 지나는 들판에는 물살 속 꽃이 아니라 꽃이 핀 둑이 생깁니다.`}),Q(`Tree3D`,{en:`Procedural tree groves — real branching trunks, textured leaves, one node per forest.`,ko:`프로시저럴 나무 숲 — 진짜 가지가 뻗은 줄기와 텍스처 잎, 숲 하나가 노드 하나.`},{en:`type conifer/broadleaf/dead picks the recipe family; tier is the cost dial: simple = primitive low-poly, medium = light forest presets (≤3k tris/tree), high = full ez-tree presets (8–20k, hero trees). count > 1 scatters a forest patch over area [w,d] — up to 3 seed variants, each branches + leaves InstancedMesh (≤6 draw calls); count × tris/tree is budget-checked at load. seed makes every branch and leaf reproducible; height jitters ±20% per instance; leaves sway in a simplex wind.`,ko:`type conifer/broadleaf/dead가 수종을, tier가 비용을 정합니다: simple = 기존 로우폴리, medium = 가벼운 forest 프리셋(나무당 ≤3k tris), high = 풀 ez-tree 프리셋(8–20k, 주인공 나무). count > 1이면 area [w,d]에 숲 패치를 흩뿌립니다 — 시드 변형 최대 3종, 변형마다 가지+잎 InstancedMesh(드로우 콜 ≤6), count × tris는 로드 시 예산 검사. seed로 가지와 잎이 전부 재현되고 height는 인스턴스마다 ±20% 지터링, 잎은 심플렉스 바람에 흔들립니다.`}),Q(`VoxelGrid3D`,{en:`A Minecraft-style block grid in ONE node.`,ko:`마인크래프트식 블록 그리드 — 노드 하나로.`},{en:`voxels is a list of [x,y,z,palette] integer cells (terrain/island generators emit these). Greedy-meshed and instanced — large worlds stay one draw batch. Game code edits blocks via setBlock/getBlock; emits blocksChanged.`,ko:`voxels는 [x,y,z,팔레트] 정수 셀 목록입니다(terrain/island 생성기가 만들어 냅니다). 그리디 메싱+인스턴싱으로 큰 월드도 드로우 배치 하나를 유지합니다. 게임 코드는 setBlock/getBlock으로 수정하고 blocksChanged가 발산됩니다.`})]},{id:`3d-physics`,label:{en:`3D Physics`,ko:`3D 물리`},intro:{en:`Same model as 2D, in meters with y-up gravity ([0,-9.81,0] default). Colliders: box {size}, sphere {radius}, capsule {radius,height}.`,ko:`2D와 같은 모델을 미터·y-위 중력([0,-9.81,0] 기본)으로. 콜라이더는 box {size}, sphere {radius}, capsule {radius,height}.`},nodes:[Q(`StaticBody3D`,{en:`Immovable 3D collision.`,ko:`움직이지 않는 3D 충돌체.`},{en:`Floors, walls, level geometry. collider {shape:"auto"} takes the shape from the MeshInstance3D or ModelInstance3D the body carries as a child, so the blocker can never be bigger or smaller than what the player sees — the fix for hand-typed extents that leave you stopping in mid-air. A GLB becomes a triangle mesh here, holes and all.`,ko:`바닥·벽·레벨 지형. collider {shape:"auto"}는 바디가 자식으로 들고 있는 MeshInstance3D 또는 ModelInstance3D의 생김새를 그대로 씁니다 — 보이는 것보다 크거나 작은 콜라이더가 생길 수 없습니다. 손으로 적은 크기 때문에 허공에서 막히는 문제의 해법입니다. GLB는 여기서 구멍까지 살아있는 트라이메시가 됩니다.`}),Q(`RigidBody3D`,{en:`Simulated 3D body.`,ko:`시뮬레이션되는 3D 바디.`},{en:`Crates, balls, debris — gravity and impacts drive it.`,ko:`상자·공·파편 — 중력과 충격이 움직입니다.`}),Q(`CharacterBody3D`,{en:`Kinematic 3D character.`,ko:`키네마틱 3D 캐릭터.`},{en:`moveAndSlide with up = +y; isOnFloor for jumps.`,ko:`+y를 위로 moveAndSlide, 점프 판정은 isOnFloor.`}),Q(`Area3D`,{en:`3D overlap sensor.`,ko:`3D 겹침 센서.`},{en:`triggerEnter/Exit — pickups, zones, goals.`,ko:`triggerEnter/Exit — 아이템·존·골인 지점.`}),Q(`CharacterController3D`,{en:`Zero-code 3D movement + camera rig.`,ko:`코드 없는 3D 이동 + 카메라 리그.`},{en:`Put it UNDER a CharacterBody3D. view: thirdPerson (orbit + zoom), firstPerson (eyeHeight, mouseLook), sideView or flightView. Reads moveAction/jumpAction/sprintAction from the scene input map; skinPath turns the visual child to face travel. Intent-level numbers: maxSpeed, jumpVelocity, camDistance.`,ko:`CharacterBody3D의 자식으로 두세요. view는 thirdPerson(궤도+줌), firstPerson(eyeHeight, mouseLook), sideView, flightView 중 하나입니다. 씬 입력 맵의 moveAction/jumpAction/sprintAction을 읽고 skinPath의 비주얼 자식을 진행 방향으로 돌립니다. maxSpeed·jumpVelocity·camDistance 같은 의도 수준의 숫자만 만집니다.`}),Q(`BoneLookAt3D`,{en:`Look-at IK for one bone — the head turns toward a target on top of the animation.`,ko:`본 하나의 룩앳 IK — 애니메이션 위에서 머리가 대상을 향해 돌아갑니다.`},{en:`"target" = ModelInstance3D path, "bone" = bone name (default Head), "lookAt" = the node to watch (e.g. "%Player"). Blends in/out smoothly and DISENGAGES beyond maxAngleDeg (no owl necks); weight sets how far it commits. forwardAxis names the bone's facing axis (mixamo heads: +z). Purely visual — headless no-op.`,ko:`"target"에 ModelInstance3D 경로, "bone"에 본 이름(기본 Head), "lookAt"에 바라볼 노드(예: "%Player")를 줍니다. 부드럽게 페이드 인/아웃하고 maxAngleDeg 밖에서는 해제됩니다(목이 돌아가지 않음). weight로 몰입도를 조절하고 forwardAxis는 본의 정면 축입니다(mixamo 머리: +z). 순수 시각 기능 — 헤드리스에서는 no-op.`}),Q(`InstancedMesh3D`,{en:`Hundreds of copies of one mesh in ONE draw call — rocks, posts, crates.`,ko:`메시 하나의 수백 개 복사본을 드로우콜 1개로 — 바위, 말뚝, 상자.`},{en:`Same mesh/size/material surface as MeshInstance3D; "transforms" places the copies — each row [x, y, z, yawDeg?, scale?]. Replace the whole array to update (mutations are not watched). The scattering workhorse for open worlds. collider: {} makes the whole field solid — every row gets its own collider SHAPED LIKE THE MESH (a faceted gem stone collides as that stone's hull, not as a ball tucked inside it), all hanging off one fixed body. A boulder field the player walks straight through is the tell that a world is scenery rather than a place.`,ko:`MeshInstance3D와 같은 mesh/size/material 표면에 "transforms"로 복사본을 배치합니다 — 각 행은 [x, y, z, yawDeg?, scale?]. 갱신은 배열 전체 교체로 하세요(내부 변경은 감지되지 않음). 오픈월드 스캐터링의 주력입니다. collider: {}를 주면 필드 전체가 단단해집니다 — 행마다 메시 생김새 그대로의 콜라이더가 생기고(각진 gem 바위는 안에 박힌 구가 아니라 그 바위 자신의 볼록 껍질로 부딪힙니다), 전부 하나의 고정 바디에 붙습니다. 플레이어가 통과해버리는 바위밭은 그 세계가 배경 그림이라는 신호입니다.`}),Q(`BoneAttachment3D`,{en:`Rides a skeleton bone of an animated model — swords in hands, hats on heads.`,ko:`애니메이션 모델의 스켈레톤 본을 따라다님 — 손에 쥔 검, 머리 위 모자.`},{en:`"target" is a node path to the ModelInstance3D, "bone" the bone name ("RightHand" also matches the Mixamo spellings). Children inherit the live animated transform; this node's own position/rotation become a bone-space offset. Purely visual — headless it stays where its props put it, so keep gameplay checks range-based.`,ko:`"target"에 ModelInstance3D 노드 경로, "bone"에 본 이름을 줍니다("RightHand"는 Mixamo 표기도 자동 매칭). 자식들이 살아있는 애니메이션 트랜스폼을 물려받고, 이 노드의 position/rotation은 본 기준 오프셋이 됩니다. 순수 시각 기능 — 헤드리스에서는 prop 위치에 머무니 게임 판정은 거리 기반으로 유지하세요.`}),Q(`Trail3D`,{en:`A fading world-space ribbon behind the parent — wingtip trails, sword arcs, tyre streaks.`,ko:`부모 뒤로 남는 페이드아웃 월드 리본 — 날개끝 궤적, 검격 궤적, 타이어 자국.`},{en:"Child of the moving node. Records the world position over `seconds` and renders a camera-facing strip that tapers and fades to the tail. width (m), color, opacity, additive for glowing energy trails, minDistance filters jitter. emitting: false stops laying new ribbon while the old tail fades out.",ko:`움직이는 노드의 자식으로 두세요. seconds 동안의 월드 위치를 기록해 꼬리로 갈수록 가늘어지고 투명해지는 카메라 지향 스트립을 그립니다. width(m), color, opacity, 빛나는 에너지 궤적에는 additive, minDistance로 떨림을 걸러냅니다. emitting: false면 새 리본만 멈추고 기존 꼬리는 자연스럽게 사라집니다.`}),Q(`Joint3D`,{en:`A physics joint linking its parent body to a target body — weld, ball joint, rope, spring.`,ko:`부모 바디와 대상 바디를 잇는 물리 조인트 — 용접, 볼 조인트, 로프, 스프링.`},{en:`Child of body A; "target" is a node path to body B. type: fixed (rigid weld) / spherical (ball joint at the anchors) / rope (caps anchor distance at length m; 0 = measured at creation) / spring (pulls toward length with stiffness/damping). anchor/targetAnchor are LOCAL meter offsets.`,ko:`바디 A의 자식으로 두고 "target"에 바디 B의 노드 경로를 줍니다. type: fixed(강체 용접) / spherical(앵커 볼 조인트) / rope(앵커 간 거리를 length m로 제한, 0이면 생성 시 실측) / spring(stiffness/damping으로 length를 향해 당김). anchor/targetAnchor는 로컬 미터 오프셋.`})]},{id:`network`,label:{en:`Network`,ko:`네트워크`},intro:{en:`Multiplayer is transport-agnostic: the engine speaks one NetworkTransport interface (built-in offline Loopback + an @agent8/gameserver adapter). The scene declares replication; one owner node per player broadcasts its sync keys.`,ko:`멀티플레이어는 트랜스포트 불가지론입니다 — 엔진은 NetworkTransport 인터페이스 하나만 사용합니다(내장 오프라인 Loopback + @agent8/gameserver 어댑터). 복제는 씬이 선언하며, 플레이어당 하나의 owner 노드가 sync 키를 송출합니다.`},nodes:[Q(`NetworkSpawner`,{en:`Spawns a registered scene per remote player/entity.`,ko:`원격 플레이어/엔티티마다 등록된 씬을 생성.`},{en:`source "users" mirrors every OTHER account in the room (self skipped); "collection:<id>" mirrors a room collection. Replicated sync patches apply to each instance; position interpolates. Emits spawned/despawned.`,ko:`source "users"는 방의 다른 모든 계정을 미러링하고(자신 제외) "collection:<id>"는 방 컬렉션을 미러링합니다. 복제 sync 패치가 인스턴스에 적용되고 position은 보간됩니다. spawned/despawned를 발산합니다.`})]}],bR=`overview`,xR=null;function SR(){document.querySelector(`#docs`)?.removeAttribute(`hidden`),TR()}function CR(){document.querySelector(`#docs`)?.setAttribute(`hidden`,``)}function wR(){let e=document.querySelector(`#docs`);e&&(e.addEventListener(`pointerdown`,t=>{t.target===e&&CR()}),document.querySelector(`#docs-close`)?.addEventListener(`click`,CR))}function TR(){let e=document.querySelector(`#docs-tabs`),t=document.querySelector(`#docs-body`);if(!e||!t)return;e.textContent=``;let n=(t,n)=>{let r=document.createElement(`button`);r.type=`button`,r.className=`docs-tab${bR===t?` active`:``}`,r.textContent=n,r.addEventListener(`click`,()=>{bR=t,xR=null,TR()}),e.appendChild(r)};n(`overview`,jL({en:`Overview`,ko:`개요`}));for(let e of yR)n(e.id,jL(e.label));if(t.textContent=``,bR===`overview`){ER(t);return}let r=yR.find(e=>e.id===bR);r&&DR(t,r)}function ER(e){let t=document.createElement(`h2`);t.textContent=jL(vR.title),e.appendChild(t);for(let t of vR.sections){let n=document.createElement(`h3`);n.textContent=jL(t.heading);let r=document.createElement(`p`);r.textContent=jL(t.text),e.append(n,r)}}function DR(e,t){let n=document.createElement(`p`);n.className=`docs-intro`,n.textContent=jL(t.intro),e.appendChild(n);for(let n of t.nodes){let t=document.createElement(`div`);t.className=`docs-node${xR===n.type?` open`:``}`;let r=document.createElement(`button`);r.type=`button`,r.className=`docs-node-head`;let i=document.createElement(`span`);i.className=`tree-icon`,i.appendChild(PL(n.type));let a=document.createElement(`strong`);a.textContent=n.type;let o=document.createElement(`span`);if(o.className=`docs-summary`,o.textContent=jL(n.summary),r.append(i,a,o),r.addEventListener(`click`,()=>{xR=xR===n.type?null:n.type,TR()}),t.appendChild(r),xR===n.type){let e=document.createElement(`div`);e.className=`docs-detail`;for(let t of n.body){let n=document.createElement(`p`);n.textContent=jL(t),e.appendChild(n)}e.appendChild(OR(n.type)),t.appendChild(e)}e.appendChild(t)}}function OR(e){let t=document.createElement(`table`);t.className=`docs-props`;let n=document.createElement(`tr`);for(let e of[jL({en:`prop`,ko:`prop`}),jL({en:`default`,ko:`기본값`})]){let t=document.createElement(`th`);t.textContent=e,n.appendChild(t)}t.appendChild(n);try{let n=ct(e);for(let[e,r]of Object.entries(n)){let n=document.createElement(`tr`),i=document.createElement(`td`);i.className=`mono`,i.textContent=e;let a=document.createElement(`td`);a.className=`mono`,a.textContent=JSON.stringify(r.default),n.append(i,a),t.appendChild(n)}}catch{}return t}function $(e){return Math.round(e*100)/100}function kR(e,t,n,r,i){return{name:e,type:`StaticBody3D`,props:{collider:{shape:`box`,size:t},position:n,...i?{rotation:i}:{}},children:[{name:`Skin`,type:`MeshInstance3D`,props:{mesh:`box`,size:t,...r}}]}}function AR(e,t,n,r,i,a){let o=$(r.range(i[0],i[1])),s=$(r.range(.5,.7));return{name:`Rock${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[t,$(o*s*.6),n],rotation:[0,r.int(0,359),0],scale:[o,$(o*s),$(o*r.range(.8,1.1))],material:{color:a??jR(r),roughness:1},castShadow:!0}}}function jR(e){let t=Math.round(e.range(110,160)).toString(16).padStart(2,`0`);return`#${t}${t}${t}`}function MR(e){return[{name:`Sun`,type:`DirectionalLight3D`,props:{position:[$(e*.8),$(e*1.5),$(e*.6)],intensity:1,castShadow:!0,shadowArea:$(e*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[$(-e*.8),$(e*.8),$(-e*.6)],intensity:.4,color:`#b9d4ff`}}]}function NR(e,t){return e===void 0?t:typeof e==`number`?[e,e]:e}function PR(e,t,n){return Math.min(Math.max(e,t),n)}var FR=[`boxes`,`ruins`,`garden`],IR=.5,LR=.1,RR=2,zR={boxes:{floor:`#3f3f3f`,wall:`#55504a`,obstacles:[`#b0413e`,`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#878787`]},ruins:{floor:`#7d766b`,wall:`#8a8378`,obstacles:[`#8a8378`,`#979085`,`#a39a8d`,`#7b746a`]},garden:{floor:`#4d7c3a`,wall:`#2f6b2f`,obstacles:[`#2f6b2f`,`#3a7a38`,`#356e33`]}};function BR(e){let{seed:t,width:n=30,depth:r=30,wallHeight:i=3,obstacles:a=8,theme:o=`boxes`}=e;if(!FR.includes(o))throw new L(`BAD_FORMAT`,`generateArena theme must be one of [${FR.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...FR]});let s=zR[o],c=new Ee(t),l=[kR(`Floor`,[n,LR,r],[0,-.1/2,0],{material:{color:s.floor,roughness:1},receiveShadow:!0})],u=i/2,d=[n+IR*2,i,IR],f=[IR,i,r],p={material:{color:s.wall,roughness:.9},receiveShadow:!0};l.push(kR(`Wall1`,d,[0,u,-(r+IR)/2],p),kR(`Wall2`,d,[0,u,(r+IR)/2],p),kR(`Wall3`,f,[-(n+IR)/2,u,0],p),kR(`Wall4`,f,[(n+IR)/2,u,0],p)),o===`ruins`?l.push(...HR(c,s,n,r,i,a)):l.push(...VR(c,s,n,r,i,a,o)),o===`garden`&&l.push(...UR(c,n,r));let m=Math.max(n,r);return l.push({name:`Sun`,type:`DirectionalLight3D`,props:{position:[$(m*.8),$(m*1.5),$(m*.6)],intensity:1,castShadow:!0,shadowArea:$(m*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[$(-m*.8),$(m*.8),$(-m*.6)],intensity:.4,color:`#b9d4ff`}},{name:`Lamp`,type:`OmniLight3D`,props:{position:[0,$(i+2),0],intensity:.5,color:`#fff3d6`,range:$(m)}}),{name:`Arena`,type:`Node3D`,children:l}}function VR(e,t,n,r,i,a,o){let s=[],c=o===`garden`?Math.min(n,r)*.16:0;for(let o=1;o<=a;o++){let a=[$(e.range(.8,2.6)),$(e.range(.8,Math.max(1.2,i*.8))),$(e.range(.8,2.6))],l=$(e.range(-(n/2-RR),n/2-RR)),u=$(e.range(-(r/2-RR),r/2-RR));if(c>0&&Math.hypot(l,u)<c+1.5){let t=Math.max(Math.hypot(l,u),.001);l=$(l/t*(c+1.5+e.range(0,2))),u=$(u/t*(c+1.5+e.range(0,2)))}let d=e.int(0,359);s.push(kR(`Obstacle${o}`,a,[l,$(a[1]/2),u],{material:{color:e.pick(t.obstacles),roughness:.8},castShadow:!0},[0,d,0]))}return s}function HR(e,t,n,r,i,a){let o=[];if(a<=0)return o;let s=Math.max(1,Math.round(Math.sqrt(a/2))),c=Math.ceil(a/s),l=n-RR*2,u=r-RR*2,d=0;for(let n=0;n<s&&d<a;n++){let r=$(s===1?0:-u/2+n/(s-1)*u);for(let n=0;n<c&&d<a;n++){d++;let a=$((c===1?0:-l/2+n/(c-1)*l)+e.range(-.4,.4)),s=$(e.next()>.35?e.range(i*.7,i*1.2):e.range(.4,.9)),u=$(e.range(.8,1.2));o.push(kR(`Obstacle${d}`,[u,s,u],[a,$(s/2),$(r+e.range(-.4,.4))],{material:{color:e.pick(t.obstacles),roughness:.95},castShadow:!0},[0,e.int(-8,8),0]))}}return o}function UR(e,t,n){let r=[],i=Math.min(t,n)*.16,a=r=>{let a=Math.min(t,n)/2-r/2-1,o=$(e.range(-a,a)),s=$(e.range(-a,a)),c=Math.max(Math.hypot(o,s),.001);return c<i+r/2&&(o=$(o/c*(i+r/2+.5)),s=$(s/c*(i+r/2+.5))),[o,s]};for(let i=1;i<=3;i++){let o=$(Math.min(t,n)*e.range(.18,.26)),[s,c]=a(o);r.push({name:`Grass${i}`,type:`Foliage3D`,props:{kind:`grass`,area:[o,o],density:10,seed:e.int(1,1e9),position:[s,0,c]}})}for(let i=1;i<=2;i++){let o=$(Math.min(t,n)*e.range(.12,.18)),[s,c]=a(o);r.push({name:`FlowerBed${i}`,type:`Flowers3D`,props:{density:`lush`,clustering:.3,area:[o,o],seed:e.int(1,1e9),position:[s,0,c]}})}return r.push({name:`Pool`,type:`Water3D`,props:{size:[$(i*2),$(i*2)],position:[0,.3,0],waveHeight:.04}}),r}var WR=32,GR=[4,8],KR=`#332f3a`,qR=`#6b6357`;function JR(e){let{seed:t,rooms:n=5}=e,[r,i]=NR(e.size,[960,720]),a=Math.max(8,Math.floor(r/WR)),o=Math.max(8,Math.floor(i/WR)),s=new Ee(t),c=[];for(let e=0;e<n*12&&c.length<n;e++){let e=s.int(GR[0],GR[1]),t=s.int(GR[0],GR[1]),n={x:s.int(1,Math.max(1,a-e-1)),y:s.int(1,Math.max(1,o-t-1)),w:e,h:t};c.some(e=>YR(e,n,1))||c.push(n)}let l=new Set,u=e=>{for(let t=e.y;t<e.y+e.h;t++)for(let n=e.x;n<e.x+e.w;n++)l.add(`${n},${t}`)};for(let e of c)u(e);let d=[];for(let e=1;e<c.length;e++){let[t,n]=XR(c[e-1]),[r,i]=XR(c[e]),a={x:Math.min(t,r),y:n,w:Math.abs(t-r)+1,h:1},o={x:r,y:Math.min(n,i),w:1,h:Math.abs(n-i)+1};for(let[t,n]of[[`H`,a],[`V`,o]])u(n),(n.w>1||n.h>1)&&d.push({name:`Corridor${e}${t}`,rect:n})}let f=new Set;for(let e of l){let[t,n]=e.split(`,`).map(Number);for(let e=-1;e<=1;e++)for(let r=-1;r<=1;r++){let i=`${t+r},${n+e}`;l.has(i)||f.add(i)}}let p=-(a*WR)/2,m=-(o*WR)/2,h=(e,t,n)=>({name:e,type:`ColorRect2D`,props:{position:[p+(t.x+t.w/2)*WR,m+(t.y+t.h/2)*WR],size:[t.w*WR,t.h*WR],color:n}}),g=c.map((e,t)=>h(`Room${t+1}`,e,KR));for(let e of d)g.push(h(e.name,e.rect,KR));let _=0;for(let e=-1;e<=o;e++){let t=-1;for(;t<=a;){if(!f.has(`${t},${e}`)){t++;continue}let n=1;for(;t+n<=a&&f.has(`${t+n},${e}`);)n++;_++;let r=[n*WR,WR];g.push({name:`Wall${_}`,type:`StaticBody2D`,props:{position:[p+(t+n/2)*WR,m+(e+.5)*WR],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:qR}}]}),t+=n}}return{name:`Dungeon`,type:`Node2D`,children:g}}function YR(e,t,n){return e.x-n<t.x+t.w&&e.x+e.w+n>t.x&&e.y-n<t.y+t.h&&e.y+e.h+n>t.y}function XR(e){return[Math.floor(e.x+e.w/2),Math.floor(e.y+e.h/2)]}var ZR=[[0,-1],[1,0],[0,1],[-1,0]];function QR(e,t,n){let r=2*t+1,i=2*n+1,a=Array.from({length:i},()=>Array(r).fill(!1)),o=(e,t)=>{a[t][e]=!0};o(1,1);let s=new Set([`0,0`]),c=[[0,0]];for(;c.length>0;){let[r,i]=c[c.length-1],a=[];for(let[e,o]of ZR){let c=r+e,l=i+o;c>=0&&c<t&&l>=0&&l<n&&!s.has(`${c},${l}`)&&a.push([c,l])}if(a.length===0){c.pop();continue}let[l,u]=e.pick(a);s.add(`${l},${u}`),o(2*l+1,2*u+1),o(r+l+1,i+u+1),c.push([l,u])}return o(0,1),o(2*t,2*n-1),{cols:t,rows:n,cells:a}}var $R=[`stone`,`hedge`,`canyon`],ez=.1,tz=`https://agent8-games.verse8.io/assets/3D/default/textures/wall`,nz=`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,rz={stone:{wall:{color:`#e8e2d8`,map:`${tz}/blocks.png`,normalMap:`${tz}/blocks_normal.png`,tile:2,roughness:.95},floor:{color:`#99938a`,map:`${nz}/stone.png`,normalMap:`${nz}/stone_normal.png`,tile:3,roughness:1},cap:`#6b5848`,pillar:`#cfc8bb`,path:`#665f55`,sun:{color:`#c9d6ea`,intensity:.75,height:.5},fill:`#9fb4cc`,mood:{sky:{elevationDeg:10,azimuthDeg:150,turbidity:16,rayleigh:3.2},fog:{near:.5,far:3.5,color:`#86909c`},exposure:.82,ambient:{color:`#c9d4e2`,intensity:.12}}},hedge:{wall:{color:`#55a83e`,map:`${nz}/grass.png`,normalMap:`${nz}/grass_normal.png`,tile:1.4,roughness:1},floor:{color:`#86b06d`,map:`${nz}/grass.png`,normalMap:`${nz}/grass_normal.png`,tile:3,roughness:1},pillar:`#3d7531`,path:`#7d6845`,sun:{color:`#e9eee6`,intensity:.7,height:1},fill:`#b9c8b4`,mood:{sky:{elevationDeg:35,azimuthDeg:150,turbidity:18,rayleigh:4.2},fog:{near:.8,far:5,color:`#aab8a6`},exposure:.88,ambient:{color:`#dde5d8`,intensity:.15}}},canyon:{wall:{color:`#f0b070`,map:`${nz}/stone.png`,normalMap:`${nz}/stone_normal.png`,tile:2.4,roughness:1},floor:{color:`#e3c193`,map:`${nz}/sand.png`,normalMap:`${nz}/sand_normal.png`,tile:3.5,roughness:1},pillar:`#d8a868`,path:`#a98a58`,sun:{color:`#ffb572`,intensity:1.15,height:.35},fill:`#caa37e`,mood:{sky:{elevationDeg:9,azimuthDeg:230,turbidity:9,rayleigh:3.5},fog:{near:.7,far:4.5,color:`#c79c6e`},exposure:.92,ambient:{color:`#ffdcb6`,intensity:.13}}}};function iz(e,t,n){return{color:e.color,roughness:e.roughness,map:e.map,...e.normalMap?{normalMap:e.normalMap}:{},repeat:[$(t/e.tile),$(n/e.tile)]}}var az=10;function oz(e){let{seed:t,width:n=8,depth:r=8,cellSize:i=2,wallHeight:a=2.5,theme:o=`stone`}=e;if(!$R.includes(o))throw new L(`BAD_FORMAT`,`generateMaze theme must be one of [${$R.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...$R]});let s=rz[o],c=new Ee(t),l=QR(c,n,r),u=2*n+1,d=2*r+1,f=$(u*i),p=$(d*i),m=(e,t)=>[$((e+.5)*i-f/2),$((t+.5)*i-p/2)],h=[kR(`Floor`,[f,ez,p],[0,-.1/2,0],{material:iz(s.floor,f,p),receiveShadow:!0})],g=[],_=0;for(let e=0;e<d;e++){let t=0;for(;t<u;){if(l.cells[e]?.[t]){t++;continue}let n=1;for(;t+n<u&&!l.cells[e]?.[t+n];)n++;g.push({gx:t,gz:e,run:n}),_++;let r=$(n*i);h.push(kR(`Wall${_}`,[r,a,i],[$((t+n/2)*i-f/2),$(a/2),$((e+.5)*i-p/2)],{material:iz(s.wall,r,a),castShadow:!0,receiveShadow:!0})),t+=n}}return s.cap&&h.push(...sz(g,i,a,f,p,s.cap)),h.push(...cz(c,l,i,a,m,s)),o===`hedge`?(h.push(...fz(c,g,i,a,m)),h.push(...pz(c,l,i,m,n,r))):o===`canyon`&&h.push(...mz(c,g,i,a,m)),h.push(...uz(l,i,a,m,s)),h.push(...MR(Math.max(f,p)).map((e,t)=>{if(t!==0)return{...e,props:{...e.props,color:s.fill}};let n=e.props?.position;return{...e,props:{...e.props,color:s.sun.color,intensity:s.sun.intensity,position:[n[0]??0,$((n[1]??0)*s.sun.height),n[2]??0]}}})),{name:`Maze`,type:`Node3D`,children:h}}function sz(e,t,n,r,i,a){return e.map((e,o)=>({name:`Cap${o+1}`,type:`MeshInstance3D`,props:{mesh:`box`,size:[$(e.run*t+.16),.12,$(t+.16)],position:[$((e.gx+e.run/2)*t-r/2),$(n+.06),$((e.gz+.5)*t-i/2)],material:{color:a,roughness:1},castShadow:!0,receiveShadow:!0}}))}function cz(e,t,n,r,i,a){let o=[],s=(e,n)=>t.cells[n]?.[e]===!1;for(let e=2;e<t.cells.length-1;e+=2)for(let n=2;n<(t.cells[e]?.length??0)-1;n+=2)s(n,e)&&Number(s(n-1,e))+Number(s(n+1,e))+Number(s(n,e-1))+Number(s(n,e+1))>=3&&o.push([n,e]);let c=Math.min(az,o.length),l=[],u=new Set,d=$(n*1.2),f=$(r*1.12);for(let t=1;t<=c;t++){let n=e.int(0,o.length-1);for(;u.has(n);)n=(n+1)%o.length;u.add(n);let[r,s]=o[n],[c,p]=i(r,s);l.push(lz(`Pillar${t}`,c,p,d,f,a))}return l}function lz(e,t,n,r,i,a){return{name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[r,i,r],position:[t,$(i/2),n],material:{...iz(a.wall,r,i),color:a.pillar},castShadow:!0,receiveShadow:!0}}}function uz(e,t,n,r,i){let a=2*e.cols,o=2*e.rows-1,s=$(t*1.1),c=$(n*1.25),l=[[0,0],[0,2],[a,o-1],[a,o+1]].map(([e,t],n)=>{let[a,o]=r(e,t);return lz(`Gate${n+1}`,a,o,s,c,i)});for(let[e,n,s]of[[`EntrancePath`,0,1],[`ExitPath`,a,o]]){let[a,o]=r(n,s);l.push({name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[$(t*.96),.04,$(t*.96)],position:[a,.02,o],material:{...iz(i.floor,t,t),color:i.path},receiveShadow:!0}})}return l}var dz=10;function fz(e,t,n,r,i){return[...t].filter(e=>e.run>=2).sort((e,t)=>t.run-e.run||e.gz-t.gz||e.gx-t.gx).slice(0,dz).map((t,a)=>{let[,o]=i(t.gx,t.gz),[s]=i(t.gx,t.gz),[c]=i(t.gx+t.run-1,t.gz);return{name:`HedgeTop${a+1}`,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,area:[$(t.run*n*.92),$(n*.7)],density:14,height:.35,sway:.4,colorA:`#2f5e26`,colorB:`#5d8a3c`,seed:e.int(1,1e9),position:[$((s+c)/2),r,o]}}})}function pz(e,t,n,r,i,a){let o=[];for(let e=0;e<t.cells.length;e++)for(let n=0;n<(t.cells[e]?.length??0);n++)t.cells[e]?.[n]&&o.push([n,e]);let s=Math.min(o.length,Math.max(3,Math.floor(i*a/12))),c=[],l=new Set;for(let t=1;t<=s&&l.size<o.length;t++){let i=e.int(0,o.length-1);for(;l.has(i);)i=(i+1)%o.length;l.add(i);let[a,s]=o[i],[u,d]=r(a,s),f=$(n*.8);c.push({name:`Grass${t}`,type:`Foliage3D`,props:{kind:`grass`,area:[f,f],density:8,seed:e.int(1,1e9),position:[u,0,d]}})}return c}function mz(e,t,n,r,i){let a=[];if(t.length===0)return a;let o=Math.min(8,t.length);for(let s=1;s<=o;s++){let o=e.pick(t),[c,l]=i(o.gx+e.int(0,o.run-1),o.gz),u=AR(s,c,l,e,[.3,$(n*.35)],`#8f7355`),d=u.props?.position;d[1]=$(d[1]+r),a.push(u)}return a}var hz=`#23222b`,gz=`#5f6672`;function _z(e){let{seed:t,cols:n=10,rows:r=8,cellPx:i=64}=e,a=QR(new Ee(t),n,r),o=2*n+1,s=2*r+1,c=$(o*i),l=$(s*i),u=[{name:`Floor`,type:`ColorRect2D`,props:{size:[c,l],color:hz}}],d=0;for(let e=0;e<s;e++){let t=0;for(;t<o;){if(a.cells[e]?.[t]){t++;continue}let n=1;for(;t+n<o&&!a.cells[e]?.[t+n];)n++;d++;let r=[$(n*i),i];u.push({name:`Wall${d}`,type:`StaticBody2D`,props:{position:[$((t+n/2)*i-c/2),$((e+.5)*i-l/2)],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:gz}}]}),t+=n}}return{name:`Maze2D`,type:`Node2D`,children:u}}var vz=16,yz=[`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#b0413e`];function bz(e){let{seed:t,count:n=10,width:r=[80,160],gapX:i=[40,120],stepY:a=[-80,40],start:o=[0,300]}=e,s=new Ee(t),c=[],l=$(s.range(r[0],r[1])),u=o[0],d=o[1];for(let e=1;e<=n&&(c.push(xz(e,u,d,l,s.pick(yz))),e!==n);e++){let e=$(s.range(r[0],r[1])),t=$(s.range(i[0],i[1]));u=$(u+l/2+t+e/2),d=$(d+s.range(a[0],a[1])),l=e}return{name:`Platforms`,type:`Node2D`,children:c}}function xz(e,t,n,r,i){return{name:`Platform${e}`,type:`StaticBody2D`,props:{position:[t,n],collider:{shape:`rect`,size:[r,vz]}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:[r,vz],color:i}}]}}var Sz=[3,5],Cz=3,wz={color:`#ffffff`,roughness:1,emissive:`#ffffff`,emissiveIntensity:.25};function Tz(e){let{seed:t,count:n=8,altitude:r=18}=e,[i,a]=NR(e.area,[60,60]),o=new Ee(t),s=[];for(let e=1;e<=n;e++){let t=o.int(Sz[0],Sz[1]),n=[];for(let e=1;e<=t;e++){let r=$(o.range(1,2.2));n.push({name:`Puff${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[$((e-(t+1)/2)*o.range(1,1.6)),$(o.range(-.3,.3)),$(o.range(-.6,.6))],scale:[$(r*o.range(1.1,1.6)),$(r*.55),r],material:wz}})}s.push({name:`Cloud${e}`,type:`Node3D`,props:{position:[$(o.range(-i/2,i/2)),$(r+o.range(-3,Cz)),$(o.range(-a/2,a/2))]},children:n})}return{name:`Clouds`,type:`Node3D`,children:s}}var Ez=[`island`,`alpine`,`plains`,`desert`,`meadow`,`forest`,`savanna`,`snow`,`wetland`,`volcanic`],Dz=128,Oz=20,kz=.8,Az=.12,jz={island:{splat:`island`,maxHeight:4.5,sun:`#fff4d6`,fill:`#b9d4ff`,sky:{elevationDeg:38,azimuthDeg:145,turbidity:2.6,rayleigh:1.1},fog:{near:1,far:4},iblIntensity:.72},alpine:{splat:`alpine`,maxHeight:8,roughness:.65,detail:5,sun:`#f4f7ff`,fill:`#c9d8f2`,sky:{elevationDeg:45,azimuthDeg:35,turbidity:1.4,rayleigh:1.3},fog:{near:1.8,far:6.5},sunIntensity:1.1,exposure:.92,iblIntensity:.72},plains:{splat:`plains`,maxHeight:4,sun:`#fff2cf`,fill:`#bcd3ef`,sky:{elevationDeg:36,azimuthDeg:140,turbidity:2.4,rayleigh:1},fog:{near:.9,far:4},iblIntensity:.58},desert:{splat:`desert`,maxHeight:5,sun:`#ffe3b3`,fill:`#e8c9a6`,sky:{elevationDeg:42,azimuthDeg:160,turbidity:7,rayleigh:.6},fog:{near:.8,far:3.2,color:`#e8d3ae`},sunIntensity:1.35,iblIntensity:.75},meadow:{splat:`grassland`,maxHeight:1.2,sun:`#fff8e2`,fill:`#bfe0c9`,sky:{elevationDeg:55,azimuthDeg:125,turbidity:2.4,rayleigh:.95},fog:{near:1,far:4.4},sunIntensity:2.6,exposure:1.12,iblIntensity:.62},forest:{splat:`forest`,maxHeight:2.5,sun:`#ffdca8`,fill:`#a9c8b4`,sky:{elevationDeg:29,azimuthDeg:120,turbidity:5.5,rayleigh:1},fog:{near:.22,far:1.8,color:`#9fb494`},sunIntensity:2.6,ambient:.26,iblIntensity:.55},savanna:{splat:`savanna`,maxHeight:3,sun:`#ffdca0`,fill:`#e6d2a4`,sky:{elevationDeg:34,azimuthDeg:150,turbidity:5,rayleigh:.7},fog:{near:1,far:4.2,color:`#e3cf9f`},sunIntensity:2,exposure:1.05,iblIntensity:.6},snow:{splat:`snow`,maxHeight:2.2,sun:`#dfe9ff`,fill:`#c2d2f0`,sky:{elevationDeg:22,azimuthDeg:35,turbidity:1.6,rayleigh:1.6},fog:{near:1.2,far:5,color:`#dbe6f5`},sunIntensity:1,exposure:.9,iblIntensity:.72},wetland:{splat:`wetland`,maxHeight:1.4,sun:`#d6ddc8`,fill:`#9fb29a`,sky:{elevationDeg:24,azimuthDeg:115,turbidity:9,rayleigh:1.1},fog:{near:.5,far:2,color:`#92a288`},sunIntensity:1.5,exposure:.94,ambient:.24,iblIntensity:.66},volcanic:{splat:`volcanic`,maxHeight:4,roughness:.7,sun:`#ff8a4a`,fill:`#7a4a3a`,sky:{elevationDeg:14,azimuthDeg:135,turbidity:10,rayleigh:.3},fog:{near:.18,far:1.4,color:`#2a211c`},sunIntensity:1.7,exposure:.86,ambient:.22,iblIntensity:.5}};function Mz(e){let{seed:t,theme:n=`island`,size:r=200,water:i=!1}=e,a=jz[n];if(!a)throw new L(`BAD_FORMAT`,`generateTerrain theme must be one of [${Ez.join(`, `)}], got '${n}'.`,{prop:`theme`,validOptions:[...Ez]});let o=Math.max(2,Math.round(e.resolution??Dz)),s=e.maxHeight||a.maxHeight,c=new Ee(t),l=n===`island`,u=e=>VD({width:r,depth:r,segsX:o,segsZ:o,maxHeight:e,seed:t,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail},islandEdge:l}),d=u(s);if(l)for(let e=0;e<3;e++){let e=Pz(d)-Oz,t=d.maxHeight-d.minHeight,n=d.minHeight+Az*t;if(e+kz<=n)break;let r=Oz-kz,i=Pz(d)-d.minHeight-Az*t;s=$(s*Math.min(r/i*.95,.9)),d=u(s)}let f=[{name:`Ground`,type:`StaticBody3D`,props:{collider:{shape:`heightfield`}},children:[{name:`Surface`,type:`Terrain3D`,props:{size:[r,r],maxHeight:s,seed:t,theme:a.splat,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail},...o===Dz?{}:{resolution:o}}}]}],p=n===`wetland`;if(l)f.push({name:`Sea`,type:`Water3D`,props:{size:[r*8,r*8],position:[0,Nz(d),0],opacity:1}});else if(p){let e=d.maxHeight-d.minHeight||1,t=$(d.minHeight+.22*e);f.push({name:`Swamp`,type:`Water3D`,props:{size:[r,r],position:[0,t,0],waveHeight:.02,quality:`simple`,color:`#3a4a30`,opacity:.95}})}else if(i){let e=$(d.minHeight+.1*(d.maxHeight-d.minHeight));f.push({name:`Lake`,type:`Water3D`,props:{size:[r,r],position:[0,e,0],waveHeight:.04}})}return f.push(...Xz(n,c,d,r)),l&&f.push(Tz({seed:c.int(1,1e9),count:6,area:r,altitude:Math.round(d.maxHeight+12)})),f.push(...MR(r).map((e,t)=>Zz(e,t===0?a.sun:a.fill,t===0?a.sunIntensity??1.7:void 0))),{name:`Terrain`,type:`Node3D`,children:f}}function Nz(e){let t=Pz(e)-Oz,n=e.minHeight+Az*(e.maxHeight-e.minHeight);return $(Math.max(Math.min(t+kz,n),t+.55))}function Pz(e){let t=-1/0,n=e.width/2,r=e.depth/2,i=e.segsX;for(let a=0;a<=i;a++){let o=-n+a/i*e.width,s=-r+a/i*e.depth;t=Math.max(t,e.baseHeight(o,-r),e.baseHeight(o,r),e.baseHeight(-n,s),e.baseHeight(n,s))}return t}function Fz(e,t,n){let r=Math.min(t.width/2-n.margin,n.within??1/0),i=t.maxHeight-t.minHeight||1,a=[];for(let o=0;o<n.count*30&&a.length<n.count;o++){let o=$(e.range(-r,r)),s=$(e.range(-r,r));if(n.clearing&&Math.hypot(o,s)<n.clearing||n.within&&Math.hypot(o,s)>n.within)continue;let c=t.heightAt(o,s),l=(c-t.minHeight)/i;l<n.band[0]||l>n.band[1]||t.slopeAt(o,s)>n.maxSlope||a.push({x:o,z:s,y:c})}return a}var Iz=[{canopy:`#2f5d44`,trunk:`#6e4a32`},{canopy:`#356a4c`,trunk:`#71503a`},{canopy:`#2c5740`,trunk:`#5f4530`},{canopy:`#3a6b4a`,trunk:`#6a4c34`}],Lz=[{canopy:`#4a7c3f`,trunk:`#7a5a3a`},{canopy:`#56883c`,trunk:`#806044`},{canopy:`#7a9d3e`,trunk:`#9a9488`},{canopy:`#86a346`,trunk:`#a39c8e`},{canopy:`#b8862f`,trunk:`#7e5e38`},{canopy:`#a8702c`,trunk:`#74552f`}],Rz={canopy:`#9aa052`,trunk:`#8a6a44`},zz={canopy:`#39513f`,trunk:`#5a5650`};function Bz(e,t){return e===`conifer`?t.pick(Iz):e===`broadleaf`?t.pick(Lz):null}function Vz(e,t,n,r,i){let a=i?.height??[4.5,7],o=i?.sink??(i?.count===void 0?.05:.3),s={};i?.tier!==void 0&&(s.tier=i.tier),i?.count!==void 0&&i.area!==void 0&&(s.count=i.count,s.area=[i.area,i.area]);let c=Bz(r,n),l=i?.palette??c;return l&&(s.canopyColor=l.canopy,s.trunkColor=l.trunk),{name:e,type:`Tree3D`,props:{type:r,seed:n.int(1,1e9),height:$(n.range(a[0],a[1])),position:[t.x,$(t.y-o),t.z],...s}}}function Hz(e,t,n,r,i,a=0,o){return{name:e,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,area:[r,r],density:i,height:o?.height??.3,...o?.colors?{colorA:o.colors[0],colorB:o.colors[1]}:{},seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z],...a>0?{flowers:a}:{}}}}function Uz(e,t,n,r,i){return{name:e,type:`Foliage3D`,props:{kind:`reeds`,style:`simple`,area:[r,r],density:i,height:.9,colorA:`#2f4a26`,colorB:`#5a6f33`,seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z]}}}function Wz(e,t,n,r,i){return{name:e,type:`Flowers3D`,props:{density:i,area:[r,r],seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z]}}}function Gz(e,t,n,r){return e.map((e,i)=>{let a=AR(i+1,e.x,e.z,t,n,r?.(t)),o=a.props?.position;return o[1]=$(o[1]+e.y),a})}function Kz(e){let t=Math.round(e.range(104,128)),n=Math.round(t-e.range(10,18)),r=Math.round(t-e.range(20,30)),i=e=>e.toString(16).padStart(2,`0`);return`#${i(n)}${i(t)}${i(r)}`}function qz(e){let t=Math.round(e.range(196,224)),n=Math.min(255,t+Math.round(e.range(4,12))),r=e=>e.toString(16).padStart(2,`0`);return`#${r(t)}${r(t)}${r(n)}`}function Jz(e){let t=Math.round(e.range(34,56)),n=Math.min(255,t+Math.round(e.range(2,8))),r=e=>e.toString(16).padStart(2,`0`);return`#${r(n)}${r(t)}${r(t)}`}var Yz=[`#6f5b41`,`#7a644a`,`#665439`];function Xz(e,t,n,r){let i=[];switch(e){case`island`:{let e=Fz(t,n,{count:7,band:[.18,.6],maxSlope:.5,margin:26});i.push(...e.map((e,n)=>Vz(`Tree${n+1}`,e,t,`conifer`)));break}case`alpine`:{let e=Fz(t,n,{count:10,band:[.2,.5],maxSlope:.55,margin:6});i.push(...e.map((e,n)=>Vz(`Tree${n+1}`,e,t,`conifer`)));let r=Fz(t,n,{count:8,band:[.55,1],maxSlope:.9,margin:6});i.push(...Gz(r,t,[.6,1.8]));break}case`plains`:{let e=Fz(t,n,{count:8,band:[0,1],maxSlope:.4,margin:6});i.push(...e.map((e,n)=>Vz(`Tree${n+1}`,e,t,`broadleaf`)));let r=Fz(t,n,{count:6,band:[0,1],maxSlope:.5,margin:6});i.push(...Gz(r,t,[.4,1.2]));break}case`desert`:{let e=Fz(t,n,{count:6,band:[0,1],maxSlope:.45,margin:6});i.push(...e.map((e,n)=>Vz(`Tree${n+1}`,e,t,`dead`)));let r=Fz(t,n,{count:8,band:[0,1],maxSlope:.6,margin:6});i.push(...Gz(r,t,[.5,1.6]));break}case`meadow`:{let e=$(r*.09),a=Fz(t,n,{count:7,band:[0,1],maxSlope:.05,margin:e/2+8});i.push(...a.map((n,r)=>Hz(`Carpet${r+1}`,n,t,e,30)));let o=$(r*.07),s=Fz(t,n,{count:3,band:[0,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>Wz(`Flowers${n+1}`,e,t,o,`sparse`)));let c=Fz(t,n,{count:4,band:[0,1],maxSlope:.1,margin:12});i.push(...c.map((e,n)=>Vz(`Grove${n+1}`,e,t,`broadleaf`,{count:3,area:6})));let l=Fz(t,n,{count:6,band:[0,1],maxSlope:.2,margin:8});i.push(...Gz(l,t,[.3,.9]));break}case`forest`:{let e=$(r*.12),a=r/2-8,o=Sr(t.int(1,1e9)),s=(e,t,n)=>{let r=o(e/70,t/70);return r>.12?`conifer`:r<-.12?`broadleaf`:n%2==0?`conifer`:`broadleaf`},c=Fz(t,n,{count:40,band:[0,1],maxSlope:.18,margin:8,clearing:e+6}),l=c.map((e,t)=>s(e.x,e.z,t));i.push(...c.map((e,n)=>Vz(`Grove${n+1}`,e,t,l[n],{count:12,area:13,height:[5.5,8]}))),c.forEach((e,n)=>{n%3==0&&i.push(Vz(`Sapling${n+1}`,e,t,l[n],{count:4,area:19,height:[2.5,3.4],sink:.12}))});let u=Fz(t,n,{count:6,band:[0,1],maxSlope:.2,margin:12,clearing:e+4});i.push(...u.map((e,n)=>Vz(`Elder${n+1}`,e,t,s(e.x,e.z,n),{tier:`high`,height:[8.4,9.8]})));let d=Fz(t,n,{count:3,band:[0,1],maxSlope:.18,margin:10,clearing:e+6});i.push(...d.map((e,n)=>Vz(`Accent${n+1}`,e,t,`broadleaf`,{tier:`high`,count:3,area:7,height:[5.6,6.8]})));let f=Fz(t,n,{count:10,band:[0,1],maxSlope:.14,margin:9,clearing:e+2});i.push(...f.map((e,n)=>Vz(`Bush${n+1}`,e,t,`bush`,{count:4,area:10,height:[2.1,3.1],sink:.12})));let p=0;c.forEach((e,r)=>{if(r%3==2)return;let o=t.range(0,Math.PI*2),s=t.range(2,4.5),c=t.int(1,1e9),l=$(PR(e.x+Math.cos(o)*s,-a,a)),u=$(PR(e.z+Math.sin(o)*s,-a,a));n.slopeAt(l,u)>.09||(p++,i.push({name:`Fern${p}`,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,tuftStyle:`fern`,area:[8,8],density:9,height:.4,colorA:`#4a6b34`,colorB:`#82a258`,seed:c,position:[l,$(n.heightAt(l,u)+.02),u]}}))});let m=$(r*.08),h=Fz(t,n,{count:5,band:[0,1],maxSlope:.06,margin:m/2+8});i.push(...h.map((e,n)=>Hz(`Grass${n+1}`,e,t,m,20,0,{height:.24,colors:[`#4f7034`,`#85a154`]})));let g=u.length>0?t.int(3,5):0;for(let e=0;e<g;e++){let r=u[e%u.length],o=t.range(0,Math.PI*2),s=t.range(2.5,4.5),c=$(PR(r.x+Math.cos(o)*s,-a,a)),l=$(PR(r.z+Math.sin(o)*s,-a,a));i.push({name:`Log${e+1}`,type:`Tree3D`,props:{type:`dead`,seed:t.int(1,1e9),height:$(t.range(4.2,5.6)),trunkColor:`#4a4236`,position:[c,$(n.heightAt(c,l)+.12),l],rotation:[0,t.int(0,359),$(t.range(81,97))]}})}Fz(t,n,{count:5,band:[0,1],maxSlope:.25,margin:9,clearing:e}).forEach((e,n)=>{let r=$(t.range(.16,.28)),a=$(t.range(.3,.55));i.push({name:`Stump${n+1}`,type:`MeshInstance3D`,props:{mesh:`cylinder`,size:[r,a,r],position:[e.x,$(e.y+a/2-.06),e.z],rotation:[0,t.int(0,359),0],material:{color:t.pick(Yz),roughness:1},castShadow:!0}})});let _=Fz(t,n,{count:8,band:[0,1],maxSlope:.2,margin:8});i.push(...Gz(_,t,[.3,1],Kz));let v=$(e*.75),y=Fz(t,n,{count:3,band:[0,1],maxSlope:.06,margin:8,within:e-$(v/Math.SQRT2)});i.push(...y.map((e,n)=>Hz(`Clearing${n+1}`,e,t,v,30,0,{colors:[`#5d8438`,`#a8bc60`]})));let b=$(e*.45),x=Fz(t,n,{count:2,band:[0,1],maxSlope:.06,margin:8,within:e-$(b/Math.SQRT2)});i.push(...x.map((e,n)=>Wz(`Flowers${n+1}`,e,t,b,`sparse`)));break}case`savanna`:{let e=Fz(t,n,{count:7,band:[0,.85],maxSlope:.35,margin:8});i.push(...e.map((e,n)=>Vz(`Tree${n+1}`,e,t,`broadleaf`,{height:[3.5,5],palette:Rz})));let a=$(r*.09),o=Fz(t,n,{count:6,band:[0,1],maxSlope:.05,margin:a/2+8});i.push(...o.map((e,n)=>Hz(`Carpet${n+1}`,e,t,a,26,0,{height:.34,colors:[`#9a8f43`,`#c9bd6a`]})));let s=Fz(t,n,{count:7,band:[0,1],maxSlope:.5,margin:8});i.push(...Gz(s,t,[.4,1.4]));let c=Fz(t,n,{count:4,band:[0,1],maxSlope:.2,margin:9});i.push(...c.map((e,n)=>Vz(`Scrub${n+1}`,e,t,`bush`,{count:3,area:8,height:[1.4,2.2]})));break}case`snow`:{let e=Fz(t,n,{count:8,band:[0,.9],maxSlope:.4,margin:8});i.push(...e.map((e,n)=>Vz(`Tree${n+1}`,e,t,`conifer`,{height:[4,6.5],palette:zz})));let r=Fz(t,n,{count:10,band:[0,1],maxSlope:.7,margin:8});i.push(...Gz(r,t,[.5,1.8],qz));break}case`wetland`:{let e=$(r*.08),a=Fz(t,n,{count:6,band:[0,.5],maxSlope:.06,margin:e/2+8});i.push(...a.map((n,r)=>Uz(`Reeds${r+1}`,n,t,e,4)));let o=$(r*.08),s=Fz(t,n,{count:4,band:[.2,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>Hz(`Moss${n+1}`,e,t,o,22,0,{height:.22,colors:[`#3a5a2c`,`#6f8a48`]})));let c=Fz(t,n,{count:6,band:[.25,1],maxSlope:.35,margin:9});i.push(...c.map((e,n)=>Vz(`Snag${n+1}`,e,t,`dead`,{height:[4,6]})));let l=Fz(t,n,{count:6,band:[.2,1],maxSlope:.2,margin:9});i.push(...l.map((e,n)=>Vz(`Bush${n+1}`,e,t,`bush`,{count:3,area:7,height:[1.6,2.6]})));let u=Fz(t,n,{count:5,band:[.2,1],maxSlope:.3,margin:8});i.push(...Gz(u,t,[.3,1],Kz));break}case`volcanic`:{let e=Fz(t,n,{count:7,band:[0,1],maxSlope:.45,margin:8});i.push(...e.map((e,n)=>Vz(`Tree${n+1}`,e,t,`dead`,{height:[4,6.5]})));let r=Fz(t,n,{count:12,band:[0,1],maxSlope:.7,margin:8});i.push(...Gz(r,t,[.4,1.8],Jz)),Fz(t,n,{count:3,band:[0,.6],maxSlope:.18,margin:12}).forEach((e,n)=>{t.int(1,1e9),i.push({name:`Smoke${n+1}`,type:`Particles3D`,props:{preset:`smoke`,position:[e.x,$(e.y+.2),e.z],rate:8,maxParticles:64,colorStart:`#5a5048`,colorEnd:`#2a2422`,sizeStart:18,sizeEnd:44}}),i.push({name:`Embers${n+1}`,type:`Particles3D`,props:{position:[e.x,$(e.y+.1),e.z],rate:10,maxParticles:48,lifetime:[.8,1.8],speed:[12,34],directionDeg:-90,spreadDeg:40,gravity:[0,-18],sizeStart:4,sizeEnd:1,colorStart:`#ffce6a`,colorEnd:`#d83a14`,blend:`add`}})});break}}return i}function Zz(e,t,n){return{...e,props:{...e.props,color:t,...n===void 0?{}:{intensity:n}}}}var Qz={arena:{description:`FPS stage: floor, 4 perimeter walls, obstacles, lights — themes: boxes (crates), ruins (broken stone rows), garden (hedges, grass, pool)`,dimension:`3d`,params:{theme:{type:`string`,default:`boxes`,options:[...FR]},width:{type:`number`,default:30,min:4},depth:{type:`number`,default:30,min:4},wallHeight:{type:`number`,default:3,min:.5},obstacles:{type:`number`,default:8,min:0}}},terrain:{description:`Heightfield world: StaticBody3D{heightfield} + Terrain3D + theme dressing (trees, rocks, grass, sea/clouds on island, broad swamp water on wetland, smoke/ember emitters on volcanic; maxHeight 0 = theme default; water adds a lake to non-island themes)`,dimension:`3d`,params:{theme:{type:`string`,default:`island`,options:[...Ez]},size:{type:`number`,default:200,min:40,max:400},maxHeight:{type:`number`,default:0,min:0},water:{type:`boolean`,default:!1}}},maze:{description:`Recursive-backtracker 3D maze, west→east — themes: stone, hedge (green + grass), canyon (sandstone + rim rocks)`,dimension:`3d`,params:{theme:{type:`string`,default:`stone`,options:[...$R]},width:{type:`number`,default:8,min:2,max:40},depth:{type:`number`,default:8,min:2,max:40},cellSize:{type:`number`,default:2,min:.5},wallHeight:{type:`number`,default:2.5,min:.5}}},maze2d:{description:`The same maze algorithm as 2D ColorRect2D + StaticBody2D tiles`,dimension:`2d`,params:{cols:{type:`number`,default:10,min:2,max:40},rows:{type:`number`,default:8,min:2,max:40},cellPx:{type:`number`,default:64,min:8}}},dungeon2d:{description:`Roguelike rooms + L-corridors: floor rects, wall bodies (32px tiles)`,dimension:`2d`,params:{rooms:{type:`number`,default:5,min:1,max:20},size:{type:`number`,default:960,min:256}}},platforms2d:{description:`Left-to-right 2D platform course (tune ranges via the library)`,dimension:`2d`,params:{count:{type:`number`,default:10,min:1}}}},$z={arena:BR,terrain:Mz,maze:oz,maze2d:_z,dungeon2d:JR,platforms2d:bz};function eB(e,t){let n=$z[e];if(!n){let t=Object.keys($z);throw new L(`BAD_FORMAT`,`Unknown generator '${e}'. Valid: [${t.join(`, `)}] — the old meadow/forest/island/rocks/clouds generators became themes (e.g. terrain theme: 'meadow', arena theme: 'garden'); scatter is library-only (needs item templates).`,{validOptions:t})}return n(t)}function tB(e){return Object.entries(Qz).filter(([,t])=>t.dimension===e).map(([e,t])=>({name:e,meta:t}))}function nB(e,t){if(e.type===`boolean`)return t===!0||t===`true`;if(e.type===`number`){let n=typeof t==`boolean`?NaN:Number(t);return(t===``||!Number.isFinite(n))&&(n=e.default),e.min!==void 0&&(n=Math.max(e.min,n)),e.max!==void 0&&(n=Math.min(e.max,n)),n}let n=String(t);return e.options&&!e.options.includes(n)?e.default:n}function rB(){return Math.floor(Math.random()*1e6)}var iB=[],aB=new Map,oB=null;function sB(e){let t=document.querySelector(`#generate`);t&&(uB(e),t.removeAttribute(`hidden`))}function cB(){document.querySelector(`#generate`)?.setAttribute(`hidden`,``)}function lB(e){let t=document.querySelector(`#generate`);t&&(t.addEventListener(`pointerdown`,e=>{e.target===t&&cB()}),document.querySelector(`#generate-close`)?.addEventListener(`click`,cB),document.querySelector(`#generate-cancel`)?.addEventListener(`click`,cB),document.querySelector(`#generate-insert`)?.addEventListener(`click`,()=>dB(e)))}function uB(e){let t=document.querySelector(`#generate-body`),n=document.querySelector(`#generate-status`);if(!t)return;n&&(n.textContent=``),t.textContent=``;let r=e.working.dimension??`2d`;iB=tB(r);let i=document.createElement(`p`);i.className=`gen-hint`,i.textContent=jL({en:`Deterministic ${r.toUpperCase()} environment generators — the subtree inserts under the selected node (the root when nothing is selected). The same seed always generates the same level.`,ko:`결정적 ${r.toUpperCase()} 환경 생성기 — 생성된 서브트리는 선택한 노드 아래에(선택이 없으면 루트에) 들어갑니다. 같은 시드는 항상 같은 레벨을 만듭니다.`}),t.appendChild(i);let a=fB(jL({en:`generator`,ko:`생성기`})),o=document.createElement(`select`);o.id=`generate-name`;for(let{name:e}of iB){let t=document.createElement(`option`);t.value=e,t.textContent=e,o.appendChild(t)}a.appendChild(o),t.appendChild(a);let s=document.createElement(`p`);s.className=`gen-desc`,t.appendChild(s);let c=document.createElement(`div`);c.id=`generate-params`,t.appendChild(c);let l=fB(`seed`);oB=document.createElement(`input`),oB.type=`number`,oB.step=`1`,oB.value=String(rB());let u=document.createElement(`button`);u.type=`button`,u.className=`ghost`,u.textContent=`↻`,u.title=jL({en:`New random seed`,ko:`새 랜덤 시드`}),u.addEventListener(`click`,()=>{oB&&(oB.value=String(rB()))});let d=document.createElement(`div`);d.className=`gen-seed-row`,d.append(oB,u),l.appendChild(d),t.appendChild(l);let f=()=>{let e=iB.find(e=>e.name===o.value)??iB[0];if(e){s.textContent=e.meta.description,c.textContent=``,aB=new Map;for(let[t,n]of Object.entries(e.meta.params)){let e=fB(t),r;if(n.type===`boolean`)r=document.createElement(`input`),r.type=`checkbox`,r.checked=n.default===!0;else if(n.type===`string`&&n.options){r=document.createElement(`select`);for(let e of n.options){let t=document.createElement(`option`);t.value=e,t.textContent=e,r.appendChild(t)}r.value=String(n.default)}else r=document.createElement(`input`),r.type=n.type===`number`?`number`:`text`,n.type===`number`&&(r.step=`any`,n.min!==void 0&&(r.min=String(n.min)),n.max!==void 0&&(r.max=String(n.max))),r.value=String(n.default),(n.min!==void 0||n.max!==void 0)&&(r.title=`${n.min??``}–${n.max??``}`);aB.set(t,r),e.appendChild(r),c.appendChild(e)}}};o.addEventListener(`change`,f),f()}function dB(e){let t=document.querySelector(`#generate-status`),n=document.querySelector(`#generate-name`),r=iB.find(e=>e.name===n?.value);if(!r||!oB)return;let i={seed:nB({type:`number`,default:rB(),min:0},oB.value)};for(let[e,t]of aB){let n=r.meta.params[e];n&&(i[e]=nB(n,t.type===`checkbox`?t.checked:t.value))}let a;try{a=eB(r.name,i)}catch(e){t&&(t.textContent=e instanceof Error?e.message:String(e));return}let o=e.insertNode(a,e.selection??[]);if(o===null){t&&(t.textContent=jL({en:`Insert failed — see the error banner.`,ko:`삽입 실패 — 에러 배너를 확인하세요.`}));return}e.select(o),oB&&(oB.value=String(rB())),cB()}function fB(e){let t=document.createElement(`label`);t.className=`field`;let n=document.createElement(`span`);return n.textContent=e,t.appendChild(n),t}var pB={connections:{title:{en:`connections — wire a signal to a handler`,ko:`connections — 시그널을 핸들러에 연결`},body:{en:'A connection says "when THIS node emits THIS signal, call THIS method on THAT node" — declaratively, in the scene JSON, with no TypeScript. emits = leaving this node; receives = arriving at it. Paths resolve from the scene ROOT (`Player/Sword`, `.` for the root itself). A red target does not resolve and the game will refuse to load the scene. Handlers on a scripted node are free text: they live in your behavior, which the editor never loads.',ko:'연결은 "이 노드가 이 시그널을 보내면, 저 노드의 이 메서드를 호출한다"를 씬 JSON에 선언합니다 — TypeScript 없이. emits는 이 노드에서 나가는 것, receives는 들어오는 것입니다. 경로는 씬 루트 기준입니다(`Player/Sword`, 루트 자신은 `.`). 빨간 대상은 찾을 수 없다는 뜻이고, 게임은 그 씬을 열지 못합니다. 스크립트가 있는 노드의 핸들러는 자유 입력입니다 — 에디터가 읽지 않는 게임 코드에 있기 때문입니다.'}},groups:{title:{en:`groups — tag nodes for queries`,ko:`groups — 조회용 태그`},body:{en:`Free-form tags. Game code finds nodes with tree-wide queries like getNodesInGroup("coins"), and triggers can filter by group (e.g. only react to "player"). Type a name and press Enter.`,ko:`자유 형식 태그입니다. 게임 코드가 getNodesInGroup("coins")처럼 트리 전체에서 노드를 찾고, 트리거는 그룹으로 거릅니다(예: "player"에만 반응). 이름을 입력하고 Enter를 누르세요.`},example:`triggerEnter → if (other.isInGroup("player")) collect()`},script:{title:{en:`script — attach YOUR game logic`,ko:`script — 게임 로직 연결`},body:{en:`A Behavior is a TypeScript class living in YOUR game code, linked by name. The editor stores the link; the class itself must be registered in the game before loadScene. Props here are passed to the behavior instance.`,ko:`Behavior는 게임 코드에 있는 TypeScript 클래스이며 이름으로 연결됩니다. 에디터는 연결만 저장하고, 클래스 자체는 loadScene 전에 게임에서 등록되어야 합니다. 여기의 props가 비헤이비어 인스턴스로 전달됩니다.`},example:`registerBehavior('CoinCounter', CoinCounter) // in your main.ts`,copy:{label:`copy behavior boilerplate`,text:`import { Behavior, registerBehavior } from 'incanto';
|
|
8429
|
+
}`};var _I=`https://agent8-games.verse8.io/assets/3D/default/textures/hdri`,vI={apartment:`lebombo_1k.hdr`,city:`potsdamer_platz_1k.hdr`,dawn:`kiara_1_dawn_1k.hdr`,forest:`forest_slope_1k.hdr`,lobby:`st_fagans_interior_1k.hdr`,night:`dikhololo_night_1k.hdr`,park:`rooitou_park_1k.hdr`,studio:`studio_small_03_1k.hdr`,sunset:`venice_sunset_1k.hdr`,warehouse:`empty_warehouse_01_1k.hdr`};function yI(e){if(typeof e.hdri==`string`&&e.hdri!==``)return e.hdri;if(typeof e.preset==`string`){let t=vI[e.preset];if(!t)throw Error(`Unknown environment preset '${e.preset}'. Available: ${Object.keys(vI).join(`, `)}.`);return`${_I}/${t}`}return null}var bI=75,xI=class{scene;ambient=new jf(`#ffffff`,0);envKey=null;config=ei(void 0);hdriUrl=null;hdriTexture=null;_sky=null;skyKey=``;skyEnvKey=``;skyEnvTarget=null;fog=new Pc(`#ffffff`,1,1e3);underwaterFog=null;underwaterBg=new q;onHdriError=null;constructor(e){this.scene=e,this.scene.add(this.ambient)}get sunDirection(){return this.config.sky?ni(this.config.sky):null}get clouds(){return this.config.clouds}get bloom(){return this.config.bloom}get post(){return this.config.post}get sceneFog(){return this.scene.fog instanceof Pc?this.scene.fog:null}apply(e,t){let n=e===void 0?``:JSON.stringify(e);n!==this.envKey&&(this.envKey=n,this.config=ei(e));let r=this.config,i=e?.ambient;if(this.ambient.color.set(i?.color??`#ffffff`),this.ambient.intensity=i?.intensity??0,t&&(t.toneMappingExposure=r.exposure,t.shadowMap.enabled=r.shadows!==!1,r.shadows!==!1&&r.shadows!==null&&r.shadows.static?t.shadowMap.autoUpdate&&(t.shadowMap.autoUpdate=!1,t.shadowMap.needsUpdate=!0):t.shadowMap.autoUpdate||(t.shadowMap.autoUpdate=!0)),this.applyHdri(e),this.applySky(r.sky,t),this._sky&&(this._sky.visible=!0),this.applyFog(r),this.scene.environment=this.hdriTexture??this.skyEnvTarget?.texture??null,this.scene.environmentIntensity=(this.scene.environment===this.skyEnvTarget?.texture&&this.skyEnvTarget?.55:1)*SI(e?.iblIntensity),e?.skybox===!0&&this.hdriTexture)this.scene.background=this.hdriTexture;else{let t=e?.background;this.scene.background=typeof t==`string`?new q(t):null}}applySunLight(e,t=null){if(!e)return;let n=this.sunDirection;if(t){let r=e.position.length()||100,i,a,o;if(n)[i,a,o]=n;else{i=e.position.x-e.target.position.x,a=e.position.y-e.target.position.y,o=e.position.z-e.target.position.z;let t=Math.hypot(i,a,o)||1;i/=t,a/=t,o/=t}e.target.position.set(t.x,t.y,t.z),e.target.updateMatrixWorld(),e.position.set(t.x+i*r,t.y+a*r,t.z+o*r)}else if(n){let t=e.position.length()||100;e.position.set(n[0],n[1],n[2]).multiplyScalar(t)}let r=this.config.shadows;if(r&&typeof r==`object`){if(!e.castShadow){let t=e.shadow.camera;`left`in t&&t.left===-5&&(t.left=-75,t.right=bI,t.top=bI,t.bottom=-75,t.near=.5,t.far=500,t.updateProjectionMatrix()),e.castShadow=!0}e.shadow.mapSize.x!==r.mapSize&&(e.shadow.mapSize.set(r.mapSize,r.mapSize),e.shadow.map?.dispose(),e.shadow.map=null),e.shadow.radius=r.radius}}applyUnderwater(e){e&&(this.underwaterFog||=new Pc(`#000000`,.5,e.visibility),this.underwaterFog.color.set(e.color),this.underwaterFog.near=.5,this.underwaterFog.far=e.visibility,this.scene.fog=this.underwaterFog,this.scene.background=this.underwaterBg.set(e.color),this._sky&&(this._sky.visible=!1))}applyHdri(e){let t=yI(e??{});t!==this.hdriUrl&&(this.hdriUrl=t,this.hdriTexture?.dispose(),this.hdriTexture=null,t&&new hI().load(t,e=>{if(this.hdriUrl!==t){e.dispose();return}e.mapping=303,this.hdriTexture=e},void 0,e=>{this.onHdriError?.(t,e)}))}applySky(e,t){let n=e?JSON.stringify(e):``;if(n!==this.skyKey&&(this.skyKey=n,this._sky&&=(this.scene.remove(this._sky),this._sky.material.dispose(),this._sky.geometry.dispose(),null),e)){this._sky=new gI,this._sky.scale.setScalar(45e4);let t=this._sky.material.uniforms;(t.sunPosition?.value).set(...e.sunPosition),t.turbidity&&(t.turbidity.value=e.turbidity),t.rayleigh&&(t.rayleigh.value=e.rayleigh),this.scene.add(this._sky)}if(e&&t&&this._sky&&this.skyEnvKey!==n){this.skyEnvKey=n,this.skyEnvTarget?.dispose();let e=new Mp(t),r=new Fc;r.add(this._sky),this.skyEnvTarget=e.fromScene(r),e.dispose(),this.scene.add(this._sky)}!e&&this.skyEnvTarget&&(this.skyEnvTarget.dispose(),this.skyEnvTarget=null,this.skyEnvKey=``)}applyFog(e){if(!e.fog){this.scene.fog=null;return}let t=e.fog.color||(e.sky?ri(e.sky):`#cfd8e0`);this.fog.color.set(t),this.fog.near=e.fog.near,this.fog.far=e.fog.far,this.scene.fog=this.fog}dispose(){this.hdriTexture?.dispose(),this.hdriTexture=null,this.skyEnvTarget?.dispose(),this.skyEnvTarget=null,this._sky&&=(this.scene.remove(this._sky),this._sky.material.dispose(),this._sky.geometry.dispose(),null)}};function SI(e){if(e===void 0)return 1;if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw new L(`BAD_FORMAT`,`environment.iblIntensity must be a finite number >= 0 (multiplies the image-based ambience: sky-derived base 0.55, HDRI base 1; default 1), got ${JSON.stringify(e)}.`,{prop:`iblIntensity`});return e}var CI=new Xc,wI=new Xc,TI=new K,EI=new K,DI=new W,OI=Array.from({length:8},()=>new W),kI=.4,AI=new Float32Array(72),jI=[[0,0,0],[1,0,0],[1,0,1],[0,0,1],[0,1,0],[1,1,0],[1,1,1],[0,1,1]],MI=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]];function NI(e,t){t.makeEmpty(),TI.copy(e.matrixWorld).invert(),e.traverse(e=>{let n=e,r;n.isInstancedMesh?(n.boundingBox||n.computeBoundingBox?.(),r=n.boundingBox):n.geometry&&(n.geometry.boundingBox||n.geometry.computeBoundingBox(),r=n.geometry.boundingBox),r&&(wI.copy(r).applyMatrix4(EI.multiplyMatrices(TI,e.matrixWorld)),t.union(wI))})}function PI(e){if(!(e instanceof Q_))return null;let t=e._ensureObject3D();t.updateWorldMatrix(!0,!0),NI(t,CI);let n=!0;CI.isEmpty()?(n=!1,DI.setFromMatrixPosition(t.matrixWorld),CI.min.set(DI.x-kI,DI.y-kI,DI.z-kI),CI.max.set(DI.x+kI,DI.y+kI,DI.z+kI)):CI.expandByScalar(.02);let{min:r,max:i}=CI;for(let e=0;e<8;e++){let[a,o,s]=jI[e],c=OI[e].set(a?i.x:r.x,o?i.y:r.y,s?i.z:r.z);n&&c.applyMatrix4(t.matrixWorld)}let a=0;for(let[e,t]of MI){let n=OI[e],r=OI[t];AI[a++]=n.x,AI[a++]=n.y,AI[a++]=n.z,AI[a++]=r.x,AI[a++]=r.y,AI[a++]=r.z}return AI}function FI(e){return e.spatial===!0&&typeof e._setSpatialPose==`function`}function II(){let e=new Set,t=[],n=[],r=[];return{visited:e,cameras:t,renderHooks:n,emitters:r,state:{visited:e,cameras:t,renderHooks:n,emitters:r,assets:void 0,sunDirection:null,sunLight:null,alpha:1,ignoreStatic:!1,quality:null}}}function LI(e,t,n,r,i){let a=i??II();a.visited.clear(),a.cameras.length=0,a.renderHooks.length=0,a.emitters.length=0;let o=a.state;o.assets=n,o.sunDirection=r?.sunDirection??null,o.ignoreStatic=r?.ignoreStatic===!0,o.sunLight=null,o.alpha=r?.alpha??1,o.quality=r?.quality??null,UI(e,t,o),KI(t,a.visited);let s=null;for(let e=0;e<a.cameras.length;e++){let t=a.cameras[e];if(t.current){s=t;break}}s||=a.cameras[0]??null;let c=s?s._ensureObject3D():null;return HI(a.emitters,c),{activeCamera:c,renderHooks:a.renderHooks,sunLight:o.sunLight}}var RI=new W,zI=new W,BI=new W,VI=new W;function HI(e,t){if(e.length===0||!t)return;t.updateWorldMatrix(!0,!1),t.getWorldPosition(zI),t.getWorldDirection(BI),VI.set(0,1,0).applyQuaternion(t.quaternion);let n={position:[zI.x,zI.y,zI.z],forward:[BI.x,BI.y,BI.z],up:[VI.x,VI.y,VI.z]};for(let{node:t,parent:r}of e)r.updateWorldMatrix(!0,!1),r.getWorldPosition(RI),t._setSpatialPose({position:[RI.x,RI.y,RI.z],listener:n})}function UI(e,t,n){let r=t;if(e instanceof Q_){let i=e._ensureObject3D();if(e.static&&!n.ignoreStatic&&i.userData.incantoStaticSynced===!0){i.userData.incantoStatic=!0,n.visited.add(i);return}if(i.parent!==t&&t.add(i),n.quality){let t=e._applyQualityCaps;typeof t==`function`&&t.call(e,n.quality)}if(e._syncObject3D(n.alpha,n.assets??null),n.assets&&e instanceof QM&&e._syncModel(n.assets),typeof e._onRender3D==`function`&&n.renderHooks.push(e),n.sunDirection){let t=e._applySunDirection;typeof t==`function`&&t.call(e,n.sunDirection)}e instanceof jM&&(!n.sunLight||e.intensity>n.sunLight.intensity)&&(n.sunLight=e),n.visited.add(i),e instanceof Bk&&n.cameras.push(e),r=i}else FI(e)&&n.emitters.push({node:e,parent:r});for(let t of e.children)UI(t,r,n);if(e instanceof Q_){let t=e._ensureObject3D();e.static&&!n.ignoreStatic?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0,GI(e)):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}var WI=new WeakSet;function GI(e){if(WI.has(e))return;WI.add(e);let t=[],n=e=>{(typeof e._onRender3D==`function`||e instanceof Bk)&&t.push(`${e.name} (${e.constructor.typeName??`?`})`);for(let t of e.children)n(t)};n(e),t.length>0&&console.warn(`[incanto] static subtree '${e.name}' freezes animated/per-frame nodes: ${t.join(`, `)} — they will stop updating. Unmark static or move them out.`)}function KI(e,t){let n=e.children;for(let r=n.length-1;r>=0;r--){let i=n[r];i.userData.incantoNode&&!t.has(i)?e.remove(i):i.userData.incantoStatic!==!0&&KI(i,t)}}var qI=120,JI=class{viewOverride=null;overrideCam=new Cf(60,1,.05,5e3);lastCamera=null;lastSize={w:1,h:1};webgl;threeScene=new Fc;environment=(()=>{let e=new xI(this.threeScene);return e.onHdriError=(e,t)=>{this.assets.textures.noteError(e,t),Nt(this.engine,`error`,`[incanto] the scene's lighting (${e}) could not be loaded — nothing else lights it.`)},e})();engine;disconnect;canvas;assets;ownsAssets;loadedAssetScenes=new WeakSet;compiledScene=null;warmCamera=null;deferCompile=!1;syncScratch=II();ignoreStatic=!1;renderCtx=null;causticsTarget=null;causticsScene=null;causticsUniforms=null;cloudsTarget=null;cloudsHalfTarget=null;cloudsBlurTarget=null;cloudsScene=null;cloudsUniforms=null;cloudsBlurScene=null;cloudsBlurUniforms=null;cloudsCompositeScene=null;cloudsCompositeUniforms=null;bloomTarget=null;bloomBrightTarget=null;bloomBlurTarget=null;bloomBrightScene=null;bloomBrightUniforms=null;bloomBlurScene=null;bloomBlurUniforms=null;bloomCompositeScene=null;bloomCompositeUniforms=null;constructor(e){this.canvas=e.canvas,this.engine=e.engine,this.ownsAssets=!e.assets,this.assets=e.assets??new pD(this.engine);let t=kr(e.engine.scene?.environment,{antialias:e.qualityDefaults?.antialias??!0,pixelRatio:e.qualityDefaults?.pixelRatio??Math.min(globalThis.devicePixelRatio??1,2),preserveDrawingBuffer:!1},globalThis.devicePixelRatio??1,{pixelRatio:e.pixelRatio,preserveDrawingBuffer:e.preserveDrawingBuffer});this.webgl=new Tg({canvas:e.canvas,antialias:t.antialias,preserveDrawingBuffer:t.preserveDrawingBuffer}),this.webgl.info.autoReset=!1,this.engine.picker=(e,t)=>this.pick(e,t),this.basePixelRatio=t.pixelRatio,this.webgl.setPixelRatio(t.pixelRatio),this.adaptive=e.adaptiveResolution===!1?null:new QF,this.webgl.shadowMap.enabled=!0,this.webgl.shadowMap.type=1,this.webgl.toneMapping=4,this.webgl.toneMappingExposure=1,this.debugLines=new Zu(new Y,new zu({color:`#00ff6e`,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.threeScene.add(this.debugLines),this.selectionLines=new Zu(new Y,new zu({color:`#ffb020`,transparent:!0,depthTest:!1})),this.selectionLines.frustumCulled=!1,this.selectionLines.renderOrder=1e4,this.selectionLines.visible=!1,this.threeScene.add(this.selectionLines),this.disconnect=this.engine.updated.connect(()=>{let e=performance.now();this.render(),this.engine.noteRenderMs(performance.now()-e)})}basePixelRatio;adaptive;renderScale=1;adaptiveScale=1;lastFrameAt=0;debugLines;selectionLines;syncSelectionOutline(){let e=this.engine.debugSelection;e&&e.tree!==this.engine.scene?.tree&&(this.engine.debugSelection=null);let t=this.engine.debugSelection,n=t?PI(t):null;if(this.selectionLines.visible=n!==null,n){this.selectionLines.geometry.setAttribute(`position`,new J(n,3));let e=this.selectionLines.geometry.getAttribute(`position`);e.needsUpdate=!0}}syncDebugLines(){let e=null;for(let t of Fb(`3d`,this.engine))if(e=t.debugLines(),e)break;this.debugLines.visible=e!==null,e&&this.debugLines.geometry.setAttribute(`position`,new J(e,3))}governResolution(){let e=this.adaptive;if(!e)return;let t=globalThis.performance?.now?.()??0,n=this.lastFrameAt;if(this.lastFrameAt=t,n===0)return;let r=t-n;if(r>500){e.reset();return}let i=e.push(r);i!==null&&(this.adaptiveScale=i,this.applyPixelRatio())}setRenderScale(e){let t=Math.min(2,Math.max(.25,e>0?e:1));t!==this.renderScale&&(this.renderScale=t,this.applyPixelRatio())}setFrameTarget(e){this.adaptive?.setTarget(e)}applyPixelRatio(){this.webgl.setPixelRatio(this.basePixelRatio*this.renderScale*this.adaptiveScale);let e=this.lastSize;e.w>0&&e.h>0&&this.webgl.setSize(e.w,e.h,!1)}deferFirstCompile(){this.deferCompile=!0}async warmUp(e){this.deferCompile=!1;let t=this.warmCamera;if(!t)return;let n=[];this.threeScene.traverse(e=>{(e.isMesh||e.isPoints)&&n.push(e)});let r=n.filter(e=>e.visible);if(r.length===0){this.webgl.compile(this.threeScene,t),e?.(1);return}for(let e of r)e.visible=!1;let i=Math.min(YI,r.length),a=Math.ceil(r.length/i);try{for(let n=0;n<i;n++){for(let e=n*a;e<Math.min((n+1)*a,r.length);e++)r[e].visible=!0;this.webgl.compile(this.threeScene,t),e?.((n+1)/i),await CD()}}finally{for(let e of r)e.visible=!0}}render(){let e=this.engine.scene;if(!e)return;this.webgl.info.reset(),this.governResolution(),this.syncDebugLines(),this.syncSelectionOutline(),e.assets&&!this.loadedAssetScenes.has(e)&&(this.assets.load(e.assets),this.loadedAssetScenes.add(e)),this.environment.apply(e.environment,this.webgl);let{activeCamera:t,renderHooks:n,sunLight:r}=LI(e.root,this.threeScene,this.assets,{sunDirection:this.environment.sunDirection,alpha:this.engine.interpolationAlpha,ignoreStatic:this.ignoreStatic,quality:Rn(this.engine.settings.get(`quality`))},this.syncScratch),i=t;if(this.viewOverride){let[e,t,n]=this.viewOverride.position,[r,a,o]=this.viewOverride.target;this.overrideCam.position.set(e,t,n),this.overrideCam.lookAt(ZI.set(r,a,o)),i=this.overrideCam}if(!i)return;this.lastCamera=i,i.updateWorldMatrix(!0,!1);let a=i.getWorldPosition(rL),o=r?r._ensureObject3D():null,s=!!o&&r.shadowFollowsCamera===!0;this.environment.applySunLight(o,s?a:null),this.compiledScene!==e&&!this.deferCompile&&(this.compiledScene=e,this.webgl.compile(this.threeScene,i)),this.warmCamera=i;let c=this.canvas.clientWidth||this.canvas.width,l=this.canvas.clientHeight||this.canvas.height,u=this.webgl.getSize(XI);(u.x!==c||u.y!==l)&&this.webgl.setSize(c,l,!1),this.lastSize={w:c,h:l};let d=l===0?1:c/l;i.aspect!==d&&(i.aspect=d,i.updateProjectionMatrix()),this.renderCtx||={gl:this.webgl,scene:this.threeScene,camera:i};let f=this.renderCtx;f.camera=i,o?(o.updateWorldMatrix(!0,!1),o.target.updateWorldMatrix(!0,!1),f.sunDir=$I.setFromMatrixPosition(o.matrixWorld).sub(eL.setFromMatrixPosition(o.target.matrixWorld)).normalize()):f.sunDir=null;for(let e=0;e<n.length;e++)n[e]?._onRender3D(f);let p=null;for(let e=0;e<n.length;e++){let t=n[e].underwaterAt?.(a.x,a.y,a.z);if(t){p=t;break}}this.environment.applyUnderwater(p);let m=this.environment.clouds,h=this.environment.bloom,g=this.environment.post;p?.caustics.enabled?this.renderWithCaustics(i,p):m&&!p?this.renderWithClouds(i,m,o):(h||g)&&!p?this.renderWithBloom(i,h,g):this.webgl.render(this.threeScene,i),this.drainFrameCapture()}captureFrame(){return new Promise((e,t)=>{this.pendingCaptures.push({resolve:e,reject:t}),setTimeout(()=>{if(this.pendingCaptures.length>0)try{this.render()}catch(e){let t=e instanceof Error?e:Error(String(e));for(let e of this.pendingCaptures.splice(0))e.reject(t)}},qI)})}pendingCaptures=[];drainFrameCapture(){if(this.pendingCaptures.length===0)return;let e=this.pendingCaptures;this.pendingCaptures=[];try{let t=this.webgl.getContext(),n=this.webgl.domElement.width,r=this.webgl.domElement.height,i=new Uint8Array(n*r*4);this.webgl.setRenderTarget(null),t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,i),oL(i,n,r);for(let t of e)t.resolve({pixels:i,width:n,height:r})}catch(t){let n=t instanceof Error?t:Error(String(t));for(let t of e)t.reject(n)}}renderWithBloom(e,t,n=null){let r=this.webgl.getDrawingBufferSize(XI),i=Math.max(1,r.x),a=Math.max(1,r.y),o=Math.max(1,Math.ceil(i/2)),s=Math.max(1,Math.ceil(a/2));if(this.bloomTarget&&(this.bloomTarget.width!==i||this.bloomTarget.height!==a)&&(this.bloomTarget.dispose(),this.bloomTarget=null,this.bloomBrightTarget?.dispose(),this.bloomBrightTarget=null,this.bloomBlurTarget?.dispose(),this.bloomBlurTarget=null),this.bloomTarget||(this.bloomTarget=new Xs(i,a,{type:Ta,samples:4}),this.bloomBrightTarget=new Xs(o,s,{type:Ta}),this.bloomBlurTarget=new Xs(o,s,{type:Ta})),!this.bloomBrightScene){let e=iI();this.bloomBrightScene=new Fc,this.bloomBrightScene.add(e.mesh),this.bloomBrightUniforms=e.uniforms;let t=aI();this.bloomBlurScene=new Fc,this.bloomBlurScene.add(t.mesh),this.bloomBlurUniforms=t.uniforms;let n=oI();this.bloomCompositeScene=new Fc,this.bloomCompositeScene.add(n.mesh),this.bloomCompositeUniforms=n.uniforms}let c=this.bloomBrightTarget,l=this.bloomBlurTarget;if(this.webgl.setRenderTarget(this.bloomTarget),this.webgl.render(this.threeScene,e),t){let n=this.bloomBrightUniforms;n.tScene.value=this.bloomTarget.texture,n.uThreshold.value=t.threshold,this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBrightScene,e);let r=this.bloomBlurUniforms;r.tTex.value=c.texture,r.uDir.value.set(1/o,0),this.webgl.setRenderTarget(l),this.webgl.render(this.bloomBlurScene,e),r.tTex.value=l.texture,r.uDir.value.set(0,1/s),this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBlurScene,e)}let u=this.bloomCompositeUniforms;u.tScene.value=this.bloomTarget.texture,u.tBloom.value=t?c.texture:this.bloomTarget.texture,u.uStrength.value=t?t.strength:0,u.uVignette.value=n?.vignette??0,u.uSaturation.value=n?.saturation??1,u.uContrast.value=n?.contrast??1,this.webgl.setRenderTarget(null),this.webgl.render(this.bloomCompositeScene,e)}renderWithClouds(e,t,n){let r=this.webgl.getDrawingBufferSize(XI),i=Math.max(1,r.x),a=Math.max(1,r.y),o=Math.max(1,Math.ceil(i/3)),s=Math.max(1,Math.ceil(a/3));if(this.cloudsTarget&&(this.cloudsTarget.width!==i||this.cloudsTarget.height!==a)&&(this.cloudsTarget.depthTexture?.dispose(),this.cloudsTarget.dispose(),this.cloudsTarget=null,this.cloudsHalfTarget?.dispose(),this.cloudsHalfTarget=null,this.cloudsBlurTarget?.dispose(),this.cloudsBlurTarget=null),!this.cloudsTarget){let e=new cd(i,a);e.type=wa,this.cloudsTarget=new Xs(i,a,{depthTexture:e,depthBuffer:!0})}if(this.cloudsHalfTarget||(this.cloudsHalfTarget=new Xs(o,s,{depthBuffer:!1}),this.cloudsBlurTarget=new Xs(o,s,{depthBuffer:!1})),!this.cloudsScene){let{mesh:e,uniforms:t}=fI();this.cloudsScene=new Fc,this.cloudsScene.add(e),this.cloudsUniforms=t}if(!this.cloudsBlurScene){let{mesh:e,uniforms:t}=dI();this.cloudsBlurScene=new Fc,this.cloudsBlurScene.add(e),this.cloudsBlurUniforms=t}if(!this.cloudsCompositeScene){let{mesh:e,uniforms:t}=pI();this.cloudsCompositeScene=new Fc,this.cloudsCompositeScene.add(e),this.cloudsCompositeUniforms=t}this.webgl.setRenderTarget(this.cloudsTarget),this.webgl.render(this.threeScene,e);let c=this.cloudsUniforms;c.tDepth.value=this.cloudsTarget.depthTexture,c.uInvViewProj.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse).invert(),e.getWorldPosition(c.uCameraPos.value),c.uTime.value=(globalThis.performance?.now()??0)*.001*t.speed;let l=this.environment.sunDirection??[.4,.8,.3];c.uSunDir.value.set(l[0],l[1],l[2]).normalize(),n&&c.uSunColor.value.copy(n.color),c.uCloudColor.value.set(t.color),c.uShadeColor.value.set(t.shadeColor);let u=this.environment.sceneFog;u?(c.uHorizonColor.value.copy(u.color),c.uFarFade.value=u.far):(c.uHorizonColor.value.set(`#cdd9e6`),c.uFarFade.value=6e3),c.uBase.value=t.base,c.uTop.value=t.top,c.uCoverage.value=t.coverage,c.uDensity.value=t.density,c.uScale.value=t.scale,c.uWind.value.set(1,.35),this.webgl.setRenderTarget(this.cloudsHalfTarget),this.webgl.render(this.cloudsScene,e);let d=this.cloudsBlurUniforms,f=this.cloudsBlurScene;d.tTex.value=this.cloudsHalfTarget.texture,d.uDir.value.set(1/o,0),this.webgl.setRenderTarget(this.cloudsBlurTarget),this.webgl.render(f,e),d.tTex.value=this.cloudsBlurTarget.texture,d.uDir.value.set(0,1/s),this.webgl.setRenderTarget(this.cloudsHalfTarget),this.webgl.render(f,e),this.webgl.setRenderTarget(null);let p=this.cloudsCompositeUniforms;p.tScene.value=this.cloudsTarget.texture,p.tClouds.value=this.cloudsHalfTarget.texture,this.webgl.render(this.cloudsCompositeScene,e)}renderWithCaustics(e,t){let n=this.webgl.getDrawingBufferSize(XI),r=Math.max(1,n.x),i=Math.max(1,n.y);if(this.causticsTarget&&(this.causticsTarget.width!==r||this.causticsTarget.height!==i)&&(this.causticsTarget.depthTexture?.dispose(),this.causticsTarget.dispose(),this.causticsTarget=null),!this.causticsTarget){let e=new cd(r,i);e.type=wa,this.causticsTarget=new Xs(r,i,{depthTexture:e,depthBuffer:!0})}if(!this.causticsScene){let{mesh:e,uniforms:t}=C_();this.causticsScene=new Fc,this.causticsScene.add(e),this.causticsUniforms=t}this.webgl.setRenderTarget(this.causticsTarget),this.webgl.render(this.threeScene,e),this.webgl.setRenderTarget(null);let a=this.causticsUniforms;a.tColor.value=this.causticsTarget.texture,a.tDepth.value=this.causticsTarget.depthTexture,a.uInvViewProj.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse).invert(),e.getWorldPosition(a.uCameraPos.value),a.uWaterLevel.value=t.surfaceY,a.uTime.value=(globalThis.performance?.now()??0)*.001*t.caustics.speed,a.uCausticColor.value.set(t.caustics.color),a.uCausticIntensity.value=t.caustics.intensity,a.uCausticScale.value=t.caustics.scale,a.uMaxDist.value=t.visibility;let o=this.environment.sunDirection;o&&a.uSunDirection.value.set(o[0],o[1],o[2]),a.uRayStrength.value=t.rays.enabled?t.rays.strength:0,this.webgl.render(this.causticsScene,e)}screenFromWorld(e,t,n){let r=this.lastCamera;return r?(QI.set(e,t,n).project(r),{x:(QI.x+1)/2*this.lastSize.w,y:(1-QI.y)/2*this.lastSize.h,behind:QI.z>1}):{x:0,y:0,behind:!0}}pick(e,t){let n=this.lastCamera;if(!n)return null;aL.set(e/this.lastSize.w*2-1,-(t/this.lastSize.h*2-1)),iL.setFromCamera(aL,n);let r=iL.intersectObjects(this.threeScene.children,!0);for(let e of r){let t=e.object;for(;t&&!t.userData.incantoNode;)t=t.parent;let n=t?.userData.incantoNode;if(n)return n}return null}stats(){let e=this.webgl.info;return{triangles:e.render.triangles,drawCalls:e.render.calls,geometries:e.memory.geometries,textures:e.memory.textures}}lastCameraPosition(){let e=this.lastCamera;return e?(e.getWorldPosition(nL),{x:nL.x,y:nL.y,z:nL.z}):null}cameraBasis(){let e=this.lastCamera,t=e?e.getWorldQuaternion(tL):tL.identity();return{right:new W(1,0,0).applyQuaternion(t),up:new W(0,1,0).applyQuaternion(t),forward:new W(0,0,-1).applyQuaternion(t)}}refreshShadows(){this.webgl.shadowMap.needsUpdate=!0}dispose(){this.engine.picker&&(this.engine.picker=null),this.disconnect(),this.threeScene.traverse(e=>{let t=e;if(!(!t.isMesh||t.userData?.incantoModelShared))if(t.geometry?.dispose(),Array.isArray(t.material))for(let e of t.material)e.dispose();else t.material?.dispose()}),this.causticsTarget?.depthTexture?.dispose(),this.causticsTarget?.dispose();let e=this.causticsScene?.children[0];e?.geometry?.dispose(),e?.material?.dispose(),this.cloudsTarget?.depthTexture?.dispose(),this.cloudsTarget?.dispose(),this.cloudsHalfTarget?.dispose(),this.cloudsBlurTarget?.dispose(),this.bloomTarget?.dispose(),this.bloomBrightTarget?.dispose(),this.bloomBlurTarget?.dispose();for(let e of[this.cloudsScene,this.cloudsBlurScene,this.cloudsCompositeScene,this.bloomBrightScene,this.bloomBlurScene,this.bloomCompositeScene]){let t=e?.children[0];t?.geometry?.dispose(),t?.material?.dispose()}this.ownsAssets&&this.assets.dispose(),this.environment.dispose(),this.webgl.dispose()}},YI=12,XI=new H,ZI=new W,QI=new W,$I=new W,eL=new W,tL=new U,nL=new W,rL=new W,iL=new rp,aL=new H;function oL(e,t,n){let r=t*4,i=new Uint8Array(r);for(let t=0;t<Math.floor(n/2);t++){let a=t*r,o=(n-1-t)*r;i.set(e.subarray(a,a+r)),e.copyWithin(a,o,o+r),e.set(i,o)}}async function sL(e){let t=async(t,n)=>{e.onProgress&&(e.onProgress(t,n),await CD())};XF(),(e.gameplay??!0)&&Tb();for(let[t,n]of Object.entries(e.behaviors??{}))St(t,n,{replace:!0});let n=new Hn({seed:e.seed,fixedHz:e.fixedHz,...e._scheduler?{scheduler:e._scheduler}:{}}),r=cL(e.scene),i=Ai(cL(r),{resolveScene:e.resolveScene,engine:n});n.setScene(i),await t(.06,`scene`);let a=null;(e.physics===!0||(e.physics??`auto`)===`auto`&&lL(i.root))&&(a=await OO(n)),await t(.1,`physics`);let o=[],s=e.keyboard??(typeof window<`u`?window:!1);if(s&&n.input.attachKeyboard(s),e.pointer){let t=typeof e.pointer==`object`?e.pointer.lockOnClick??!0:!0;n.input.attachPointer(e.canvas,{lockOnClick:t})}o.push(uL(n,i.root,e.canvas)),e.pageGestures||Og(e.canvas);let c=e.touch??`auto`;if(c!==!1){let t=e.touchContainer??e.canvas.parentElement??null;if(t){let r={force:c===!0,...e._touchDoc?{doc:e._touchDoc}:{}},i=na(n,t,r),a=n.sceneChanged.connect(()=>{i?.dispose(),i=na(n,t,r)});o.push(()=>{a(),i?.dispose()})}}let l=zn(n.settings.autoQuality()),u=e._rendererFactory?e._rendererFactory(n,e.canvas):new JI({canvas:e.canvas,engine:n,qualityDefaults:{antialias:l.antialias,pixelRatio:l.pixelRatio},...e.pixelRatio===void 0?{}:{pixelRatio:e.pixelRatio},...e.adaptiveResolution===void 0?{}:{adaptiveResolution:e.adaptiveResolution},...e.preserveDrawingBuffer===void 0?{}:{preserveDrawingBuffer:e.preserveDrawingBuffer}});await t(.14,`renderer`);let d=e.debug??!1,f=e.editor??d,p=f===!0?{}:f||null,m={label:`✎ edit this scene`,run:async()=>{if(!p)return;let t=$g(u),n=p.open??Zg,i=async t=>{await sL({...e,scene:t})};await Qg(async()=>{g();try{await n({scene:r,...t?{camera:t}:{},play:i,exit:()=>i(r),...p.save?{save:p.save}:{},...p.library?{library:p.library===!0?Gg():p.library}:{}})}catch(e){console.error(`[incanto] could not open the editor:`,e),await i(r)}},`opening the editor…`)}};if(d){let t=e.touchContainer??e.canvas.parentElement??(typeof document<`u`?document.body:null);if(t){let{attachDebugOverlay:r}=await Vg(async()=>{let{attachDebugOverlay:e}=await import(`./debug-DWztJ5_y.js`);return{attachDebugOverlay:e}},[],import.meta.url),i=r(n,{container:t,statsSource:()=>u.stats?.()??{},...u.captureFrame?{frameSource:()=>h()}:{},...p?{actions:[m]}:{},...e._debugDoc?{doc:e._debugDoc}:{}});i&&o.push(()=>i.dispose())}}n.start(),await t(.16,`shaders`);try{u.deferFirstCompile?.();let t=globalThis.performance?.now?.()??0;n.tick(t),n.tick(t+16),await u.warmUp?.(t=>{e.onProgress?.(.16+t*.82,`shaders`)})}catch{}o.push(n.settings.bindAudio(n.audio)),o.push(n.settings.bindLocale(n.locale)),o.push(n.settings.bindQuality(e=>{wD(n,e)})),o.push(n.settings.bindFrameCap(e=>{n.maxFps=e,u.setFrameTarget?.(e||60)})),o.push(n.settings.bindRenderScale(e=>{u.setRenderScale?.(e)}));let h=()=>{let e=u.captureFrame;if(!e)throw new L(`TREE_VIOLATION`,`this renderer cannot capture frames`);return e.call(u)};o.push(...Lg({engine:n,applyDrive:async e=>{let t=0,r=!0,i=()=>{r&&(t+=1,requestAnimationFrame(i))};requestAnimationFrame(i);for(let t of e)switch(t.kind){case`press`:n.input.pressAction(t.action);break;case`release`:n.input.releaseAction(t.action);break;case`vector`:n.input.setActionVector(t.action,t.x,t.y);break;case`key`:n.input.handleKey(t.code,t.down);break;case`pointer`:n.input.handlePointerMove(t.dx,t.dy);break;case`step`:await new Promise(e=>setTimeout(e,t.ms));break}return r=!1,t},captureFramePixels:h,rendererStats:()=>u.stats?.(),assetErrors:()=>u.assets?.errors()??[]})),o.push(e_(n)),await t(1,`ready`);function g(){t_([a?[`physics`,()=>a?.dispose()]:null,[`app cleanups`,()=>{for(let e of o)e()}],[`engine`,()=>n.dispose()],[`renderer`,()=>u.dispose()]])}return{engine:n,scene:i,sourceJson:r,renderer:u,physics:a,assetErrors(){return[...u.assets?.errors()??[],...Dg(n.scene?.tree.root)]},async frame(e){let t=u.captureFrame;if(!t)throw new L(`TREE_VIOLATION`,`this renderer cannot capture frames`);let n=await t.call(u);return Ig(n.pixels,n.width,n.height,e)},pick(e,t){return n.picker?.(e,t)??null},stats(){return{triangles:0,drawCalls:0,geometries:0,textures:0,...n.stats(),...u.stats?.()}},openEditor:p?m.run:null,dispose:g}}function cL(e){try{return structuredClone(e)}catch{throw new L(`BAD_FORMAT`,`createGame "scene" must be plain scene JSON (the imported *.scene.json object) — got something unclonable (a loaded Scene, class instances, or functions).`)}}function lL(e){if(e instanceof $_)return!0;for(let t of e.children)if(lL(t))return!0;return!1}function uL(e,t,n){let r=[],i=n;if(i.addEventListener&&r.push({target:i,type:`pointerdown`}),typeof window<`u`){let e=window;r.push({target:e,type:`keydown`}),r.push({target:e,type:`pointerdown`})}if(r.length===0)return()=>{};function a(){for(let e of r)e.target.removeEventListener?.(e.type,o)}function o(){e.sfx.unlock(),e.music.unlock();let n=!1,r=e=>{e instanceof Kn&&(e.retryPending(),e.pendingGesture&&(n=!0));for(let t of e.children)r(t)};r(t),n||a()}for(let e of r)e.target.addEventListener?.(e.type,o,{passive:!0});return a}var dL=e({DEFAULT_TERRAIN_TEXTURE_BASE:()=>tO,WATER_CUTOUT_MAX:()=>4,WATER_MAX_RIPPLES:()=>8,createGame3D:()=>sL,enablePhysics3D:()=>OO}),fL=500,pL=2e3,mL=new WeakMap,hL=class e{account;roomId;roomState=new M;allUserStates=new M;userJoined=new M;userLeft=new M;globalState=new M;globalMyState=new M;asset=new M;latestUserStates={};latestRoomState={};latestGlobalState={};latestGlobalMyState={};latestAsset={};server;engine;throttleMs;keyframeMs;subs=[];messageSignals=new Map;collectionSignals=new Map;latestCollections=new Map;globalMessageSignals=new Map;globalCollectionSignals=new Map;latestGlobalCollections=new Map;scenes=new Map;lastSent=new Map;reportedDeadKeys=new Set;reportDeadSyncKey(e,t){this.reportedDeadKeys.has(t)||this.aliveMs<fL||(this.reportedDeadKeys.add(t),Nt(e.tree?.engine??null,`error`,`[incanto] ${e.getPath()}: sync key '${t}' reads as undefined — it is never sent, so remote players never see it change. Check the prop name and the node path.`))}sendAccumulator=0;keyframeAccumulator=0;aliveMs=0;detachReplication=null;lastOwner=null;boundScene=null;static get(e){return mL.get(e)??null}static async create(t,n={}){await mL.get(t)?.dispose();let r=n.transport??await bL(n.config);await r.connect();let i=n.room??t.scene?.multiplayer?.room??`auto`,a=new e(t,r,await r.remoteFunction(`joinRoom`,[i===`auto`?void 0:i],{needResponse:!0}),n.throttleMs??50,n.keyframeMs??pL);return mL.set(t,a),a}constructor(e,t,n,r,i){this.engine=e,this.server=t,this.roomId=n,this.account=t.account,this.throttleMs=Math.max(30,r),this.keyframeMs=Math.max(0,i),this.boundScene=e.scene,this.subs.push(t.subscribeRoomState(n,e=>{this.latestRoomState=e,this.roomState.emit(e)}),t.subscribeRoomAllUserStates(n,e=>{this.latestUserStates=e,this.allUserStates.emit(e)}),t.onRoomUserJoin(n,e=>this.userJoined.emit(e)),t.onRoomUserLeave(n,e=>this.userLeft.emit(e))),t.subscribeGlobalState&&this.subs.push(t.subscribeGlobalState(e=>{this.latestGlobalState=e,this.globalState.emit(e)})),t.subscribeGlobalMyState&&this.subs.push(t.subscribeGlobalMyState(e=>{this.latestGlobalMyState=e,this.globalMyState.emit(e)})),t.subscribeAsset&&this.subs.push(t.subscribeAsset(this.account,e=>{this.latestAsset=e,this.asset.emit(e)})),this.detachReplication=e.fixedUpdated.connect(e=>this.replicate(e))}message(e){let t=this.messageSignals.get(e);return t||(t=new M,this.messageSignals.set(e,t),this.subs.push(this.server.onRoomMessage(this.roomId,e,e=>t?.emit(e)))),t}collection(e){let t=this.collectionSignals.get(e);return t||(t=new M,this.collectionSignals.set(e,t),this.subs.push(this.server.subscribeRoomCollection(this.roomId,e,n=>{this.latestCollections.set(e,n),t?.emit(n)}))),t}latestCollection(e){return this.collection(e),this.latestCollections.get(e)??{}}globalMessage(e){let t=this.globalMessageSignals.get(e);if(!t){t=new M,this.globalMessageSignals.set(e,t);let n=this.server.onGlobalMessage?.(e,e=>t?.emit(e));n&&this.subs.push(n)}return t}globalCollection(e){let t=this.globalCollectionSignals.get(e);if(!t){t=new M,this.globalCollectionSignals.set(e,t);let n=this.server.subscribeGlobalCollection?.(e,n=>{this.latestGlobalCollections.set(e,n),t?.emit(n)});n&&this.subs.push(n)}return t}latestGlobalCollection(e){return this.globalCollection(e),this.latestGlobalCollections.get(e)??{}}setMyState(e){return this.server.remoteFunction(`setMyState`,[this.roomId,e],{throttle:this.throttleMs,throttleKey:`incanto:myState`})}patchRoomState(e){return this.server.remoteFunction(`patchRoomState`,[this.roomId,e])}addEntity(e,t){return this.server.remoteFunction(`addEntity`,[this.roomId,e,t])}updateEntity(e,t,n){return this.server.remoteFunction(`updateEntity`,[this.roomId,e,t,n])}removeEntity(e,t){return this.server.remoteFunction(`removeEntity`,[this.roomId,e,t])}sendEvent(e,t){return this.server.remoteFunction(`sendEvent`,[this.roomId,e,t])}call(e,...t){return this.server.remoteFunction(e,[this.roomId,...t],{needResponse:!0})}registerScene(e,t){this.scenes.set(e,t)}resolveScene(e){let t=this.scenes.get(e);if(!t)throw new L(`UNRESOLVED_INSTANCE`,`No scene registered for '${e}'. Registered: [${[...this.scenes.keys()].join(`, `)}]. Call manager.registerScene('${e}', sceneJson).`);return t}async dispose(){this.detachReplication?.();for(let e of this.subs)e();await this.server.remoteFunction(`leaveRoom`,[this.roomId]),mL.delete(this.engine)}replicate(e){let t=this.engine.scene;if(!t||t!==this.boundScene)return;this.sendAccumulator+=e*1e3,this.aliveMs+=e*1e3;let n=gL(t.root,!0);if(!n)return;n!==this.lastOwner&&(this.lastOwner=n,this.lastSent.clear());let r=n.network,i=Math.max(30,typeof r.throttleMs==`number`?r.throttleMs:this.throttleMs),a=Array.isArray(r.sync)?r.sync:[],o={},s=!1;for(let e of a){let t=vL(n,e);if(t===void 0){this.reportDeadSyncKey(n,e);continue}o[e]=R(t),et(this.lastSent.get(e)??null,t)||(s=!0)}this.keyframeAccumulator+=e*1e3;let c=this.keyframeMs>0&&this.keyframeAccumulator>=this.keyframeMs;if(!(this.sendAccumulator<i)&&!(!s&&!c)&&Object.keys(o).length!==0){for(let[e,t]of Object.entries(o))this.lastSent.set(e,R(t));this.keyframeAccumulator=0,this.sendAccumulator=0,this.setMyState({sync:o})}}};function gL(e,t=!1){let n=[];if(_L(e,n),t&&n.length>1)throw new L(`BAD_FORMAT`,`Multiple network owner nodes found (${n.map(e=>e.getPath()).join(`, `)}). Exactly ONE node per player may declare network.mode 'owner' — replicate spawned entities through collections instead.`);return n[0]??null}function _L(e,t){e.network?.mode===`owner`&&t.push(e);for(let n of e.children)_L(n,t)}function vL(e,t){let n=t.lastIndexOf(`.`),r=n===-1?e:e.getNodeOrNull(t.slice(0,n))??void 0,i=n===-1?t:t.slice(n+1);if(r)return r[i]}function yL(e,t,n,r){for(let[i,a]of Object.entries(t)){let t=i.lastIndexOf(`.`),o=t===-1?e:e.getNodeOrNull(i.slice(0,t)),s=t===-1?i:i.slice(t+1);o?n(o,s,a):r?.(i)}}async function bL(e){let{createAgent8Server:t}=await Vg(async()=>{let{createAgent8Server:e}=await import(`./agent8-Di-UEn5O.js`);return{createAgent8Server:e}},[],import.meta.url);return t(e)}var xL=new Set([`__id`,`__roomId`,`__updated`,`__leaved`,`account`,`roomId`]),SL=class extends Ft{static typeName=`NetworkSpawner`;static signals=[`spawned`,`despawned`];static props={source:{default:`users`},scene:{default:``},interpolate:{default:!0}};source=`users`;scene=``;interpolate=!0;spawned=new Map;positionTargets=new Map;failedKeys=new Set;reported=new Set;update(e){let t=this.tree?.engine;if(!t)return;let n=hL.get(t);if(!n||this.scene===``)return;let r=this.currentEntries(n);for(let[e,t]of Object.entries(r)){let r=this.spawned.get(e);if(!r){if(this.failedKeys.has(e))continue;try{r=Fi(n.resolveScene(this.scene).root)}catch(t){throw this.failedKeys.add(e),t}r.name=CL(e),this.addChild(r),this.spawned.set(e,r),this.emit(`spawned`,r,e)}let i=this.patchOf(t);i&&yL(r,i,(e,t,n)=>this.setProp(e,t,n),e=>this.report(`'${e}' names a node this scene does not have`))}for(let[e,t]of[...this.spawned.entries()])e in r||(this.spawned.delete(e),this.positionTargets.delete(t),this.emit(`despawned`,t,e),t.free());this.interpolate&&this.stepInterpolation(e)}currentEntries(e){if(this.source===`users`){let t={};for(let[n,r]of Object.entries(e.latestUserStates))n!==e.account&&(t[n]=r);return t}return this.source.startsWith(`collection:`)?e.latestCollection(this.source.slice(11)):{}}patchOf(e){if(e.sync!==void 0)return e.sync;if(this.source===`users`)return;let t={};for(let[n,r]of Object.entries(e))xL.has(n)||n.startsWith(`$`)||(t[n]=r);return Object.keys(t).length>0?t:void 0}report(e){this.reported.has(e)||(this.reported.add(e),Nt(this.tree?.engine??null,`error`,`[incanto] NetworkSpawner '${this.name}': ${e} — that value replicates to nothing.`))}setProp(e,t,n){if(this.interpolate&&t===`position`&&Array.isArray(n)){this.positionTargets.set(e,n);return}e[t]=n}stepInterpolation(e){let t=Math.min(1,e*8);for(let[e,n]of this.positionTargets){let r=e.position;Array.isArray(r)&&(e.position=r.map((e,r)=>e+((n[r]??e)-e)*t))}}};function CL(e){return e.replace(/[/%]/g,`_`)||`remote`}function wL(){Or(),z(SL)}function TL(){try{return typeof localStorage>`u`?null:localStorage}catch{return null}}var EL=TL()?.getItem(`incanto-editor-lang`)??`en`,DL=new Set;function OL(){return EL}function kL(e){EL=e,TL()?.setItem(`incanto-editor-lang`,e);for(let e of DL)e()}function AL(e){DL.add(e)}function jL(e){return e[EL]}var ML={node:{paths:[`M5 5h14v14H5z`]},move:{paths:[`M12 3v18M3 12h18`,`M8 7l4-4 4 4M8 17l4 4 4-4M7 8l-4 4 4 4M17 8l4 4-4 4`]},image:{paths:[`M4 5h16v14H4z`,`M4 15l5-5 4 4 3-3 4 4`],circles:[[9,9,1.6]]},film:{paths:[`M4 4h16v16H4z`,`M4 9h16M4 15h16`,`M9 4v16M15 4v16`]},video:{paths:[`M3 7h12v10H3z`,`M15 10l6-3v10l-6-3`]},text:{paths:[`M5 7V5h14v2`,`M12 5v14`,`M9 19h6`]},layers:{paths:[`M12 3 3 8l9 5 9-5-9-5z`,`M3 12l9 5 9-5`,`M3 16l9 5 9-5`]},square:{paths:[`M5 5h14v14H5z`,`M5 12h14`]},ball:{paths:[`M12 8v0`],circles:[[12,12,8],[12,12,1.4]]},person:{paths:[`M5 21v-1a7 7 0 0 1 14 0v1`],circles:[[12,7,4]]},area:{paths:[`M5 5h14v14H5z`],dashed:!0},gamepad:{paths:[`M7 9h-0M6 12h4M8 10v4`,`M4 8h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2z`],circles:[[16,11,1],[18.5,13.5,1]]},clock:{paths:[`M12 7v5l3 2`],circles:[[12,12,9]]},cube:{paths:[`M21 16V8l-9-5-9 5v8l9 5 9-5z`,`M3.3 7.5 12 12.5l8.7-5`,`M12 22V12.5`]},sun:{paths:[`M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M19.1 4.9 17 7M7 17l-2.1 2.1`],circles:[[12,12,4]]},bulb:{paths:[`M9 18h6M10 21h4`,`M8 13a6 6 0 1 1 8 0c-1 1-1.5 2-1.5 3h-5c0-1-.5-2-1.5-3z`]},globe:{paths:[`M2 12h20`,`M12 2a15 15 0 0 1 0 20a15 15 0 0 1 0-20z`],circles:[[12,12,10]]},link:{paths:[`M10 14a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1`,`M14 10a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1`]},speaker:{paths:[`M11 5 6 9H3v6h3l5 4V5z`,`M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13`]},swatch:{paths:[`M4 4h16v16H4z`,`M4 4l16 16`]},sparkles:{paths:[`M12 4v5M12 15v5M5 12h5M14 12h5`],circles:[[6,5,1],[18,19,1]]},waves:{paths:[`M2 8c3-3 5 3 8 0s5 3 8 0`,`M2 14c3-3 5 3 8 0s5 3 8 0`,`M2 20c3-3 5 3 8 0s5 3 8 0`]},plant:{paths:[`M12 21v-8`,`M12 13c0-4-3-6-7-6 0 4 3 6 7 6z`,`M12 11c0-4 3-6 7-6 0 4-3 6-7 6z`]},flower:{paths:[`M12 21v-7`],circles:[[12,9,2],[12,4.5,2.2],[16.3,7.5,2.2],[14.7,12.6,2.2],[9.3,12.6,2.2],[7.7,7.5,2.2]]},voxels:{paths:[`M4 14h8v8H4z`,`M12 14h8v8h-8z`,`M8 6h8v8H8z`]}},NL={Node:`node`,Timer:`clock`,AudioPlayer:`speaker`,ColorRect2D:`swatch`,Particles2D:`sparkles`,Particles3D:`sparkles`,Water3D:`waves`,Foliage3D:`plant`,Flowers3D:`flower`,VoxelGrid3D:`voxels`,ModelInstance3D:`person`,CharacterController3D:`gamepad`,Node2D:`move`,Sprite2D:`image`,AnimatedSprite2D:`film`,Camera2D:`video`,Label:`text`,UILayer:`layers`,StaticBody2D:`square`,RigidBody2D:`ball`,CharacterBody2D:`person`,Area2D:`area`,CharacterController2D:`gamepad`,Node3D:`move`,Billboard3D:`layers`,MeshInstance3D:`cube`,LoftMesh3D:`cube`,Camera3D:`video`,DirectionalLight3D:`sun`,OmniLight3D:`bulb`,StaticBody3D:`square`,RigidBody3D:`ball`,CharacterBody3D:`person`,Area3D:`area`,NetworkSpawner:`globe`};function PL(e){let t=ML[NL[e??``]??(e?`node`:`link`)],n=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);n.setAttribute(`viewBox`,`0 0 24 24`),n.setAttribute(`width`,`13`),n.setAttribute(`height`,`13`),n.setAttribute(`fill`,`none`),n.setAttribute(`stroke`,`currentColor`),n.setAttribute(`stroke-width`,`2`),n.setAttribute(`stroke-linecap`,`round`),n.setAttribute(`stroke-linejoin`,`round`),t.dashed&&n.setAttribute(`stroke-dasharray`,`3 2.4`);for(let e of t.paths){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);t.setAttribute(`d`,e),n.appendChild(t)}for(let[e,r,i]of t.circles??[]){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`circle`);t.setAttribute(`cx`,String(e)),t.setAttribute(`cy`,String(r)),t.setAttribute(`r`,String(i)),n.appendChild(t)}return n}function FL(){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`width`,`12`),e.setAttribute(`height`,`12`),e.setAttribute(`fill`,`none`),e.setAttribute(`stroke`,`currentColor`),e.setAttribute(`stroke-width`,`2.4`),e.setAttribute(`aria-hidden`,`true`);let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return t.setAttribute(`d`,`m6 9 6 6 6-6`),e.appendChild(t),e}var IL=[{type:`texture`,label:`image (texture)`,metaHints:[`filter`]},{type:`spritesheet`,label:`spritesheet`,metaHints:[`filter`,`frameWidth`,`frameHeight`]},{type:`model`,label:`3D model (GLB/VRM)`,metaHints:[]},{type:`animation`,label:`animation (GLB clips)`,metaHints:[`clip`]}],LL=new Set,RL=null,zL=null;function BL(e,t,n){let r=document.createElement(`input`);r.className=`rename-input`,r.value=e;let i=()=>{let i=r.value.trim().replace(/\//g,``);i&&i!==e?t(i):n()};r.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`/`&&e.preventDefault(),e.key===`Enter`&&i(),e.key===`Escape`&&n()});for(let e of[`click`,`pointerdown`,`dblclick`,`mousedown`])r.addEventListener(e,e=>e.stopPropagation());return r.addEventListener(`blur`,i),queueMicrotask(()=>{r.focus(),r.select()}),r}function VL(e,t){let n={path:``,name:``,folders:new Map,assets:[]},r=e=>{let t=n;if(e===``)return t;for(let n of e.split(`/`)){let e=t.folders.get(n);e||(e={path:t.path?`${t.path}/${n}`:n,name:n,folders:new Map,assets:[]},t.folders.set(n,e)),t=e}return t};for(let t of e){let e=t.lastIndexOf(`/`);r(e===-1?``:t.slice(0,e)).assets.push(t)}for(let e of t)r(e);return n}function HL(e){let t=e.assets.length;for(let n of e.folders.values())t+=HL(n);return t}function UL(e,t){e.textContent=``;let n=t.working.assets??{},r=Object.keys(n);if(r.length===0&&t.pendingGroups.size===0&&!t.addingAsset&&!t.addingGroup){let t=document.createElement(`div`);t.className=`muted-note explorer-empty`,t.textContent=`no assets yet — + adds textures, models, animations`,e.appendChild(t);return}let i=(e,n)=>{e.addEventListener(`dragover`,t=>{t.preventDefault(),t.stopPropagation(),e.classList.add(`drop-target`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-target`)),e.addEventListener(`drop`,r=>{r.preventDefault(),r.stopPropagation(),e.classList.remove(`drop-target`);let i=r.dataTransfer?.getData(`text/incanto-asset`);i&&t.moveAsset(i,n);let a=r.dataTransfer?.getData(`text/incanto-group`);a&&t.moveGroup(a,n)})};i(e,``);let a=(e,r)=>{let i=n[e],a=e.includes(`/`)?e.slice(e.lastIndexOf(`/`)+1):e,o=t.assetErrors.get(e),s=document.createElement(`div`);s.className=`tree-row asset-row${t.selectedAsset===e?` selected`:``}${o===void 0?``:` asset-failed`}`,o!==void 0&&(s.title=`failed to load: ${o}`),s.draggable=!0,s.addEventListener(`dragstart`,t=>{t.dataTransfer?.setData(`text/incanto-asset`,e)});let c=document.createElement(`span`);if(c.className=`tree-icon`,c.appendChild(aR(i.type??``)),c.addEventListener(`click`,e=>{e.stopPropagation(),oR(c,i.type??``)}),RL===e){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;s.appendChild(BL(a,r=>{RL=null,t.renameAssetKey(e,n+r)},()=>{RL=null,t.selectAsset(t.selectedAsset)})),s.draggable=!1,s.insertBefore(c,s.firstChild),r.appendChild(s);return}let l=document.createElement(`span`);l.className=`tree-name asset-key`,l.textContent=`$${a}`,l.title=o===void 0?`$${e}`:`$${e} — failed to load: ${o}`,l.addEventListener(`dblclick`,n=>{n.stopPropagation(),RL=e,t.selectAsset(e)}),s.append(c,l),s.addEventListener(`click`,()=>t.selectAsset(e)),r.appendChild(s)},o=(e,n)=>{let r=LL.has(e.path),s=document.createElement(`div`);s.className=`asset-folder${r?` collapsed`:``}${t.selectedGroup===e.path?` selected`:``}`,s.draggable=!0,s.addEventListener(`dragstart`,t=>{t.stopPropagation(),t.dataTransfer?.setData(`text/incanto-group`,e.path)});let c=document.createElement(`span`);c.className=`chev`,c.appendChild(FL());let l=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);l.setAttribute(`viewBox`,`0 0 24 24`),l.setAttribute(`width`,`12`),l.setAttribute(`height`,`12`),l.setAttribute(`fill`,`none`),l.setAttribute(`stroke`,`currentColor`),l.setAttribute(`stroke-width`,`1.8`),l.setAttribute(`aria-hidden`,`true`);let u=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);if(u.setAttribute(`d`,`M3 6a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`),l.appendChild(u),zL===e.path){let i=e.path.includes(`/`)?e.path.slice(0,e.path.lastIndexOf(`/`)+1):``;if(s.append(c,l,BL(e.name,n=>{zL=null,t.renameGroup(e.path,i+n)},()=>{zL=null,t.selectGroup(t.selectedGroup)})),s.draggable=!1,n.appendChild(s),!r){let t=document.createElement(`div`);t.className=`tree-children`;for(let n of e.folders.values())o(n,t);for(let n of e.assets)a(n,t);t.children.length>0&&n.appendChild(t)}return}let d=document.createElement(`span`);d.textContent=e.name,d.addEventListener(`dblclick`,n=>{n.stopPropagation(),zL=e.path,t.selectGroup(e.path)});let f=document.createElement(`span`);if(f.className=`count`,f.textContent=`(${HL(e)})`,s.append(c,l,d,f),s.addEventListener(`click`,()=>{LL.has(e.path)?LL.delete(e.path):LL.add(e.path),t.selectGroup(e.path)}),i(s,e.path),n.appendChild(s),!r){let t=document.createElement(`div`);t.className=`tree-children`;for(let n of e.folders.values())o(n,t);for(let n of e.assets)a(n,t);t.children.length>0&&n.appendChild(t)}},s=VL(r,t.pendingGroups);for(let t of s.assets)a(t,e);for(let t of s.folders.values())o(t,e)}function WL(e,t,n,r){if(t.selection!==null)return!1;if(t.addingGroup){e.appendChild(uR(t.newGroupParent?`NEW GROUP IN ${t.newGroupParent}/`:`NEW GROUP`));let n=document.createElement(`input`);n.placeholder=t.newGroupParent?`heroes`:`characters (or a/b to nest)`,n.className=`mono`,e.appendChild(eR(`name`,n));let r=document.createElement(`button`);r.type=`button`,r.className=`primary`,r.textContent=`add`;let i=()=>{let e=n.value.trim().replace(/^\/+|\/+$/g,``);e&&(t.cancelAddForms(),t.addGroup(t.newGroupParent?`${t.newGroupParent}/${e}`:e))};r.addEventListener(`click`,i),n.addEventListener(`keydown`,e=>{e.key===`Enter`&&i()});let a=document.createElement(`div`);return a.className=`pop-actions`,a.appendChild(r),e.appendChild(a),setTimeout(()=>n.focus(),0),!0}if(t.addingAsset)return JL(e,t,r);if(t.selectedGroup!==null){let r=t.selectedGroup,i=t.groupCount(r);e.appendChild(uR(`GROUP (${i} asset${i===1?``:`s`})`));let a=r.includes(`/`)?r.slice(0,r.lastIndexOf(`/`)+1):``,o=r.includes(`/`)?r.slice(r.lastIndexOf(`/`)+1):r;e.appendChild(tR(`name`,o,e=>{let n=e.trim().replace(/\/+/g,``);n&&n!==o&&t.renameGroup(r,a+n)}));let s=document.createElement(`button`);return s.type=`button`,s.className=`ghost danger`,s.textContent=`delete group`,s.addEventListener(`click`,()=>{if(i===0){t.deleteGroup(r);return}n(`'${r}/' contains ${i} asset${i===1?``:`s`} — deleting the group deletes them too.`,`delete group & assets`,()=>t.deleteGroup(r))}),e.appendChild(s),!0}let i=t.selectedAsset;if(i===null)return!1;let a=t.working.assets??{};if(!(i in a))return!1;e.appendChild(uR(`ASSET — ${String(a[i].type??`?`)}`)),e.appendChild(sR(i)),e.appendChild(cR(t,i)),e.appendChild(GL(t,a,i,r));let o=document.createElement(`button`);return o.type=`button`,o.className=`ghost danger`,o.textContent=`delete asset`,o.addEventListener(`click`,()=>{t.selectAsset(null),t.mutate(()=>{delete a[i],Object.keys(a).length===0&&delete t.working.assets})}),e.appendChild(o),!0}function GL(e,t,n,r){let i=t[n],a=document.createElement(`div`);a.className=`asset-editor`;let o=n.includes(`/`)?n.slice(n.lastIndexOf(`/`)+1):n,s=n.includes(`/`)?n.slice(0,n.lastIndexOf(`/`)+1):``,c=tR(`name`,o,t=>{let r=t.trim().replace(/^\$/,``).replace(/\//g,``);r&&r!==o&&e.renameAssetKey(n,s+r)});lR(c.querySelector(`input`)),a.appendChild(c);let l=tR(`url`,String(i.url??``),t=>{e.mutate(()=>{i.url=t.trim()})}),u=l.querySelector(`input`);if(r&&u){let t=XL(String(i.type??``));l.classList.add(`has-lib`),l.appendChild($L(()=>t,`asset url`,r,t=>{u.value=t,e.mutate(()=>{i.url=t})},()=>QL(t,e,String(i.type??``)),()=>String(i.type??``)||void 0))}a.appendChild(l);let d=e.assetErrors.get(n);if(d!==void 0){let e=document.createElement(`div`);e.className=`conn-warn`,e.textContent=`failed to load — every node using $${n} draws nothing. Check the url: ${d}`,a.appendChild(e)}let f=document.createElement(`div`);f.className=`muted-note`,f.textContent=`meta (key · value)`,a.appendChild(f);for(let[t,n]of Object.entries(i))t===`type`||t===`url`||a.appendChild(KL(e,i,t,n));return a.appendChild(qL(e,i)),a}function KL(e,t,n,r){let i=document.createElement(`div`);i.className=`meta-row`;let a=document.createElement(`input`);a.value=n,a.className=`mono`;let o=document.createElement(`input`);o.value=typeof r==`string`?r:JSON.stringify(r),o.className=`mono`;let s=()=>{let r=a.value.trim();e.mutate(()=>{delete t[n],r&&(t[r]=nR(o.value))})};a.addEventListener(`change`,s),o.addEventListener(`change`,s);let c=document.createElement(`button`);return c.type=`button`,c.className=`linklike danger-link`,c.textContent=`✕`,c.addEventListener(`click`,()=>{e.mutate(()=>{delete t[n]})}),i.append(a,o,c),i}function qL(e,t){let n=document.createElement(`div`);n.className=`meta-row`;let r=document.createElement(`input`);r.placeholder=`filter…`,r.className=`mono`;let i=document.createElement(`input`);i.placeholder=`nearest`,i.className=`mono`;let a=()=>{let n=r.value.trim();!n||i.value.trim()===``||e.mutate(()=>{t[n]=nR(i.value)})};return r.addEventListener(`change`,a),i.addEventListener(`change`,a),n.append(r,i,document.createElement(`span`)),n}function JL(e,t,n){return e.appendChild(uR(`NEW ASSET`)),e.appendChild(YL(t,n)),!0}function YL(e,t){let n=document.createElement(`div`);n.className=`asset-editor`;let r=document.createElement(`select`);for(let e of IL){let t=document.createElement(`option`);t.value=e.type,t.textContent=e.label,r.appendChild(t)}n.appendChild(eR(`type`,r));let i=document.createElement(`input`);i.placeholder=`(optional) characters`,i.className=`mono`,i.value=e.newAssetGroup;let a=`asset-groups-list`;i.setAttribute(`list`,a);let o=document.createElement(`datalist`);o.id=a;let s=new Set;for(let t of Object.keys(e.working.assets??{})){let e=t.lastIndexOf(`/`);e!==-1&&s.add(t.slice(0,e))}for(let t of e.pendingGroups)s.add(t);for(let e of s){let t=document.createElement(`option`);t.value=e,o.appendChild(t)}n.appendChild(eR(`group`,i)),n.appendChild(o);let c=document.createElement(`input`);c.placeholder=`coin`,c.className=`mono`,lR(c),n.appendChild(eR(`key`,c));let l=document.createElement(`input`);l.placeholder=`/textures/coin.png · https://… · data:…`,l.className=`mono`;let u=eR(`url`,l);t&&(u.classList.add(`has-lib`),u.appendChild($L(()=>XL(r.value),`new asset`,t,e=>{l.value=e,c.value.trim()||(c.value=ZL(e))},()=>QL(XL(r.value),e,r.value),()=>r.value||void 0))),n.appendChild(u);let d=document.createElement(`textarea`);d.rows=2,d.placeholder=`or paste a JSON object: { "type": "model", "url": "/m.glb" }`,n.appendChild(d);let f=document.createElement(`button`);f.type=`button`,f.className=`primary`,f.textContent=`add`,f.addEventListener(`click`,()=>{let t=c.value.trim().replace(/^\$/,``);if(!t)return;let n=i.value.trim().replace(/\/+$/,``),a=n?`${n}/${t}`:t,o=null,s=d.value.trim();if(s)try{o=JSON.parse(s)}catch{d.classList.add(`invalid`);return}else l.value.trim()&&(o={type:r.value,url:l.value.trim()});o&&(e.cancelAddForms(),e.selectedAsset=a,e.mutate(()=>{e.working.assets||(e.working.assets={});let t=e.working.assets;t[a]=o}))});let p=document.createElement(`div`);return p.className=`pop-actions`,p.appendChild(f),n.appendChild(p),n}function XL(e){return e===`model`||e===`animation`?`model`:e===`audio`?`audio`:e===`texture`||e===`spritesheet`?`image`:`any`}function ZL(e){return((e.split(/[?#]/)[0]??``).split(`/`).pop()??``).replace(/\.[^.]+$/,``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/_{2,}/g,`_`).replace(/^_+|_+$/g,``).toLowerCase()||`asset`}function QL(e,t,n){if(n===`animation`)return[`3d`,`animations`];let r=(t.working.dimension??`2d`)===`3d`;if(e===`image`)return r?[`3d`,`textures`]:[`2d`,`sprite_characters`];if(e===`model`)return[`3d`,`characters`]}function $L(e,t,n,r,i,a){let o=document.createElement(`button`);return o.type=`button`,o.className=`asset-lib`,o.textContent=`📚 library`,o.title=`Browse the agent8 asset library`,o.addEventListener(`click`,o=>{o.preventDefault();let s=i?.(),c=a?.();n({kind:e(),target:t,...s?{shelf:s}:{},...c?{assetType:c}:{}}).then(e=>{e&&r(e)})}),o}function eR(e,t){let n=document.createElement(`label`);n.className=`field`;let r=document.createElement(`span`);return r.textContent=e,n.append(r,t),n}function tR(e,t,n){let r=document.createElement(`input`);return r.value=t,r.className=`mono`,r.addEventListener(`change`,()=>n(r.value)),eR(e,r)}function nR(e){let t=e.trim();if(t===`true`)return!0;if(t===`false`)return!1;if(t!==``&&Number.isFinite(Number(t)))return Number(t);if(t.startsWith(`{`)||t.startsWith(`[`))try{return JSON.parse(t)}catch{return e}return e}var rR={texture:`M3 5h18v14H3z M3 15l5-5 4 4 3-3 6 6 M8.5 9.5h.01`,spritesheet:`M3 4h18v16H3z M9 4v16 M15 4v16 M3 12h18`,model:`M12 2l9 5v10l-9 5-9-5V7z M12 12l9-5 M12 12L3 7 M12 12v10`,animation:`M12 2a10 10 0 1 0 10 10 M22 12l-3-3m3 3l3-3 M12 7v5l3 3`},iR={texture:{en:`image (texture) — Sprite2D.texture references it as "$key".`,ko:`이미지(텍스처) — Sprite2D.texture에서 "$키"로 참조합니다.`},spritesheet:{en:`spritesheet — AnimatedSprite2D slices it into named frame animations.`,ko:`스프라이트시트 — AnimatedSprite2D가 이름 붙은 프레임 애니메이션으로 자릅니다.`},model:{en:`3D model (GLB/glTF/VRM) — ModelInstance3D.model references it as "$key".`,ko:`3D 모델(GLB/glTF/VRM) — ModelInstance3D.model에서 "$키"로 참조합니다.`},animation:{en:`animation clips (GLB, in memory — drawn nowhere) — any model can play them; mixamo retargets onto VRM.`,ko:`애니메이션 클립(GLB, 메모리 전용 — 그려지지 않음) — 어떤 모델이든 재생 가능, mixamo는 VRM에 자동 리타게팅.`}};function aR(e){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);t.setAttribute(`viewBox`,`0 0 24 24`),t.setAttribute(`width`,`13`),t.setAttribute(`height`,`13`),t.setAttribute(`fill`,`none`),t.setAttribute(`stroke`,`currentColor`),t.setAttribute(`stroke-width`,`1.8`),t.setAttribute(`aria-hidden`,`true`);let n=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return n.setAttribute(`d`,rR[e]??`M4 4h16v16H4z`),t.appendChild(n),t.classList.add(`asset-icon-${e}`),t}function oR(e,t){document.querySelector(`.balloon`)?.remove();let n=iR[t];if(!n)return;let r=document.createElement(`div`);r.className=`balloon floating`;let i=document.createElement(`div`);i.className=`balloon-title`,i.textContent=t;let a=document.createElement(`span`);a.textContent=jL(n),r.append(i,a),document.body.appendChild(r);let o=e.getBoundingClientRect();r.style.left=`${o.right+8}px`,r.style.top=`${Math.max(8,o.top-8)}px`;let s=()=>{r.remove(),document.removeEventListener(`pointerdown`,s,!0)};setTimeout(()=>document.addEventListener(`pointerdown`,s,!0),0)}function sR(e){let t=document.createElement(`div`);t.className=`field uid-line`;let n=document.createElement(`span`);n.textContent=`key`;let r=document.createElement(`div`);r.className=`uid-value`;let i=document.createElement(`code`);i.textContent=`$${e}`;let a=document.createElement(`button`);return a.type=`button`,a.className=`uid-copy`,a.title=`Copy key`,a.innerHTML=`<svg aria-hidden="true" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`,a.addEventListener(`click`,()=>{navigator.clipboard?.writeText(`$${e}`),a.classList.add(`copied`),setTimeout(()=>a.classList.remove(`copied`),600)}),r.append(i,a),t.append(n,r),t}function cR(e,t){let n=t.includes(`/`)?t.slice(0,t.lastIndexOf(`/`)):``,r=document.createElement(`select`),i=new Set([``]);for(let t of Object.keys(e.working.assets??{})){let e=t.split(`/`);for(let t=1;t<e.length;t++)i.add(e.slice(0,t).join(`/`))}for(let t of e.pendingGroups)i.add(t);for(let e of[...i].sort()){let t=document.createElement(`option`);t.value=e,t.textContent=e===``?`(root)`:`${e}/`,e===n&&(t.selected=!0),r.appendChild(t)}r.addEventListener(`change`,()=>{e.moveAsset(t,r.value)});let a=document.createElement(`label`);a.className=`field`;let o=document.createElement(`span`);return o.textContent=`group`,a.append(o,r),a}function lR(e){e&&(e.addEventListener(`keydown`,e=>{e.key===`/`&&e.preventDefault()}),e.addEventListener(`input`,()=>{e.value.includes(`/`)&&(e.value=e.value.replace(/\//g,``))}))}function uR(e){let t=document.createElement(`div`);t.className=`section-title`,t.textContent=e;let n=document.createElement(`span`);return n.className=`rule`,t.appendChild(n),t}var dR=window.parent!==window,fR=new URLSearchParams(window.location.search).get(`parentOrigin`),pR=!1;function mR(e){if(dR){if(!fR){pR||(pR=!0,console.warn(`incanto-editor: embedded without ?parentOrigin=<origin> — postMessage disabled`));return}window.parent.postMessage(e,fR)}}var hR={ready(e,t,n){mR({type:`incanto-editor:ready`,input:e,output:t,version:n})},open(e,t){mR({type:`incanto-editor:open`,input:e,output:t})},change(e){mR({type:`incanto-editor:change`,dirty:e})},save(e,t,n){mR({type:`incanto-editor:save`,input:e,output:t,data:n})},error(e){mR({type:`incanto-editor:error`,message:e})}},gR=[[`Core`,e=>!e.endsWith(`2D`)&&!e.endsWith(`3D`)&&e!==`Label`&&e!==`UILayer`&&e!==`NetworkSpawner`],[`2D`,e=>e.endsWith(`2D`)&&!/Body|Area|Controller/.test(e)||e===`Label`||e===`UILayer`],[`2D Physics`,e=>e.endsWith(`2D`)&&/Body|Area|Controller/.test(e)],[`3D`,e=>e.endsWith(`3D`)&&!/Body|Area|Controller/.test(e)],[`3D Physics`,e=>e.endsWith(`3D`)&&/Body|Area|Controller/.test(e)],[`Network`,e=>e===`NetworkSpawner`]],_R=[...gR,[`Other`,e=>gR.every(([,t])=>!t(e))]],vR={title:{en:`How Incanto scenes work`,ko:`Incanto 씬은 어떻게 동작하나`},sections:[{heading:{en:`Everything is a node in a tree`,ko:`모든 것은 트리 위의 노드`},text:{en:`A scene is ONE tree of typed nodes (Godot-style). Each node has a name (unique among its siblings), a type that defines its props and behavior, optional children, and an optional scene-wide-unique uid. The whole structure lives in a *.scene.json file — there is no hidden state: what you see in this editor IS the file.`,ko:`씬은 타입을 가진 노드들의 단일 트리입니다(Godot 방식). 각 노드는 이름(형제 간 유일), props와 동작을 결정하는 타입, 선택적 자식들, 그리고 선택적인 씬 전역 유일 uid를 가집니다. 전체 구조가 *.scene.json 파일 하나에 들어있고 숨겨진 상태는 없습니다 — 이 에디터에서 보는 것이 곧 파일 그 자체입니다.`}},{heading:{en:`Props are delta-only`,ko:`Props는 변경분만 기록`},text:{en:`Every prop has a default defined by the engine. The JSON only stores values that DIFFER from the default — so files stay small and diffs stay meaningful. This editor follows the same rule: set a value back to its default and it disappears from the file.`,ko:`모든 prop에는 엔진이 정의한 기본값이 있습니다. JSON에는 기본값과 다른 값만 기록되어 파일이 작고 diff가 의미를 가집니다. 이 에디터도 같은 규칙을 따릅니다 — 값을 기본값으로 되돌리면 파일에서 사라집니다.`}},{heading:{en:`Addressing: paths, names, uid, groups`,ko:`노드 찾기: 경로·이름·uid·그룹`},text:{en:`Code reaches nodes four ways: a path like "Player/Skin" (relative) or "%Unique" (marked-unique name), getNodesByName("Enemy") which returns a LIST (names repeat across the tree), getNodeByUid("n_x1y2") which returns exactly one node and survives moves/renames, and groups — free tags for queries like "every coin".`,ko:`코드는 네 가지 방법으로 노드에 접근합니다: "Player/Skin" 같은 경로(상대) 또는 "%Unique"(유일 표시 이름), 트리 전체에서 같은 이름을 모두 찾는 getNodesByName("Enemy") — 이름은 중복될 수 있어 리스트가 돌아옵니다 —, 정확히 한 노드를 돌려주고 이동/개명에도 살아남는 getNodeByUid("n_x1y2"), 그리고 "모든 코인"처럼 묶어 조회하는 자유 태그 groups.`}},{heading:{en:`Signals connect, behaviors act`,ko:`시그널로 잇고 비헤이비어로 움직인다`},text:{en:`Nodes emit signals (an Area2D fires triggerEnter, a Timer fires timeout). The scene's "connections" wire a signal to a handler — declaratively, in JSON. Game logic itself is a Behavior: a TypeScript class in YOUR game, attached by name via "script". The inspector's CONNECTIONS section shows and edits these links on the selected node — what it emits, what reaches it, and any end that no longer resolves. The handler code itself lives in your game.`,ko:`노드는 시그널을 발산합니다(Area2D의 triggerEnter, Timer의 timeout). 씬의 "connections"가 시그널을 핸들러에 선언적으로(JSON으로) 연결합니다. 게임 로직 자체는 Behavior — 게임 쪽 TypeScript 클래스이며 "script"에 이름으로 연결됩니다. 인스펙터의 CONNECTIONS 섹션이 선택한 노드의 연결을 보여주고 편집합니다 — 나가는 것, 들어오는 것, 그리고 더 이상 찾을 수 없는 끝. 핸들러 코드 자체는 게임에 있습니다.`}},{heading:{en:`Assets are declared, then referenced`,ko:`에셋은 선언하고 $키로 참조`},text:{en:`The scene header declares assets (textures, spritesheets, 3D models, animation clips) under a key; nodes reference them as "$key". Animations are data too: an {type:"animation"} asset loads GLB clips into memory and any ModelInstance3D can play them — Mixamo clips retarget onto VRM avatars automatically.`,ko:`씬 헤더에서 에셋(텍스처·스프라이트시트·3D 모델·애니메이션 클립)을 키로 선언하고, 노드는 "$key"로 참조합니다. 애니메이션도 데이터입니다 — {type:"animation"} 에셋이 GLB 클립을 메모리에 올리고 어떤 ModelInstance3D든 재생할 수 있으며, Mixamo 클립은 VRM 아바타에 자동 리타게팅됩니다.`}}]},Q=(e,t,...n)=>({type:e,summary:t,body:n}),yR=[{id:`core`,label:{en:`Core`,ko:`Core`},intro:{en:`Dimension-free building blocks: plain containers and the game clock. They render nothing themselves.`,ko:`차원과 무관한 기본 블록 — 순수 컨테이너와 게임 시계입니다. 스스로는 아무것도 그리지 않습니다.`},nodes:[Q(`Node`,{en:`A plain container with no transform.`,ko:`변환 없이 자식을 묶는 순수 컨테이너.`},{en:`Use it to group related nodes (all coins, all UI) without affecting their positions. Lifecycle, signals, groups, script — everything works; it just has no visual or spatial meaning of its own.`,ko:`위치에 영향을 주지 않으면서 관련 노드(코인 전부, UI 전부)를 묶을 때 씁니다. 라이프사이클·시그널·그룹·스크립트가 모두 동작하며, 시각적·공간적 의미만 없습니다.`}),Q(`Timer`,{en:"A serializable countdown that emits `timeout`.",ko:"`timeout` 시그널을 쏘는 직렬화 가능한 카운트다운."},{en:`Set waitTime (seconds), optionally autostart or oneShot, and connect its timeout signal to any handler. Because it is a node, the whole timing setup lives in the scene file — agents can read and tune it.`,ko:`waitTime(초)을 정하고 autostart·oneShot을 선택한 뒤 timeout 시그널을 핸들러에 연결하세요. 노드이기 때문에 타이밍 설정 전체가 씬 파일에 남아 에이전트가 읽고 조정할 수 있습니다.`}),Q(`Respawn`,{en:`Catches whatever it hangs off when it leaves the world, and puts it back.`,ko:`부모가 월드 밖으로 떨어지면 붙잡아 원래 자리로 되돌립니다.`},{en:`Make it a child of the player. With no props it catches its parent 50 m under the spawn (1000 px in 2D — the same line incanto-playtest calls "fell"), returns it to where it started and zeroes the velocity the fall built up. below names the line, to names the landing, target picks a different node. It emits respawned, and deliberately does not decide what falling COSTS — wire that to a ScoreKeeper or a Health if it should hurt.`,ko:`플레이어의 자식으로 두세요. 프롭 없이도 스폰 50 m 아래(2D는 1000 px — incanto-playtest가 "fell"로 부르는 그 선)에서 부모를 붙잡아 처음 위치로 되돌리고, 낙하로 쌓인 속도를 0으로 만듭니다. below는 그 선, to는 착지 지점, target은 다른 노드를 지정합니다. respawned 시그널을 쏘며, 추락의 "대가"는 일부러 정하지 않습니다 — 피해를 주려면 ScoreKeeper나 Health에 연결하세요.`}),Q(`HudLayer`,{en:`Screen-space HUD overlay above the canvas — parent for UiText/UiBar/UiBanner.`,ko:`캔버스 위 화면 고정 HUD 오버레이 — UiText/UiBar/UiBanner의 부모.`},{en:`A DOM overlay (position:fixed) that never blocks pointer input. Put UI widgets as children; each picks one of 9 anchors (topLeft…bottomRight). Works identically over 2D and 3D renderers; in headless/tests it is a silent no-op. zIndex lifts it above the canvas.`,ko:`포인터 입력을 가로막지 않는 DOM 오버레이(position:fixed)입니다. UI 위젯을 자식으로 두면 각자 9개 앵커(topLeft…bottomRight) 중 하나에 붙습니다. 2D·3D 렌더러 어디서나 동일하게 동작하고, 헤드리스/테스트에서는 조용히 no-op입니다. zIndex로 캔버스 위에 올립니다.`}),Q(`UiText`,{en:`A HUD text line — score, timers, hints.`,ko:`HUD 텍스트 한 줄 — 점수, 타이머, 힌트.`},{en:`Child of HudLayer. Set text/size/color in JSON; update from behaviors: (getNode('%Score') as UiText).text = String(score). shadow adds a soft outline for readability over any scene.`,ko:`HudLayer의 자식. text/size/color를 JSON으로 정하고, 비헤이비어에서 (getNode('%Score') as UiText).text = String(score) 로 갱신하세요. shadow는 어떤 화면 위에서도 읽히도록 부드러운 그림자를 더합니다.`}),Q(`UiBar`,{en:`A labeled progress bar — health, stamina, reload, boss HP.`,ko:`라벨 달린 진행 바 — 체력, 스태미나, 재장전, 보스 HP.`},{en:`Child of HudLayer. Drive value/max from behaviors; the fill animates and turns lowColor under lowThreshold (default 30%). width/height/color/background style it; label prefixes a small caption.`,ko:`HudLayer의 자식. 비헤이비어에서 value/max를 갱신하면 채움이 애니메이션되고 lowThreshold(기본 30%) 아래로 떨어지면 lowColor로 바뀝니다. width/height/color/background로 스타일, label로 작은 캡션을 붙입니다.`}),Q(`UiBanner`,{en:`Center-screen announcements with fade and a queue — "WAVE 2", "YOU DIED".`,ko:`페이드·큐가 있는 중앙 공지 — "WAVE 2", "YOU DIED".`},{en:`Child of HudLayer. Call show('WAVE 2', { color, seconds }) from behaviors; messages queue and fade in/out. seconds 0 = sticky until the next show(). clear() drops everything. Emits bannerShown(text).`,ko:`HudLayer의 자식. 비헤이비어에서 show('WAVE 2', { color, seconds })를 호출하면 메시지가 큐에 쌓여 페이드 인/아웃됩니다. seconds 0이면 다음 show()까지 고정, clear()로 전부 제거. bannerShown(text) 시그널을 냅니다.`}),Q(`UiButton`,{en:`A clickable HUD button — menus, START screens, dialog choices.`,ko:`클릭 가능한 HUD 버튼 — 메뉴, 시작 화면, 대화 선택지.`},{en:`Child of HudLayer. Set text/size/color/background; disabled greys it out. Emits the 'pressed' signal (behaviors: node.on('pressed', ...)); press() triggers it programmatically (gamepad menus, tests).`,ko:`HudLayer의 자식. text/size/color/background를 설정하고 disabled로 비활성화합니다. 'pressed' 시그널을 내며(비헤이비어에서 node.on('pressed', ...)), press()로 코드에서도 누를 수 있습니다(게임패드 메뉴, 테스트).`}),Q(`UiPanel`,{en:`A box that holds other widgets — the thing a menu, options screen or inventory actually is.`,ko:`다른 위젯을 담는 상자 — 메뉴·설정 화면·인벤토리가 실제로 이것입니다.`},{en:`Child of HudLayer. Widgets under it mount INSIDE it, so tree structure becomes screen structure; panels nest. layout column|row|grid with columns (an inventory is a grid panel, one child per slot), plus gap/padding/background/radius/width/height/border. width or height 0 = size to the contents.`,ko:`HudLayer의 자식. 그 아래 위젯들이 이 안에 마운트되어 트리 구조가 화면 구조가 됩니다(중첩 가능). layout은 column|row|grid이고 columns와 함께 씁니다(인벤토리 = grid 패널, 슬롯당 자식 하나). gap/padding/background/radius/width/height/border 지원. width·height가 0이면 내용에 맞춰집니다.`}),Q(`UiImage`,{en:`A picture in the HUD — item icons, portraits, a logo.`,ko:`HUD 안의 그림 — 아이템 아이콘, 초상화, 로고.`},{en:`src takes a url or a $assetKey (declare the icon once like any other asset). fit contain|cover|fill; tint multiplies through the picture, which is how an unaffordable item greys out in one prop; opacity for disabled states.`,ko:`src는 url 또는 $assetKey(아이콘도 다른 에셋처럼 한 번만 선언). fit은 contain|cover|fill, tint는 그림에 곱해져서 살 수 없는 아이템을 프롭 하나로 회색 처리합니다. opacity로 비활성 표현.`}),Q(`UiSlider`,{en:`A value the player sets — volume, sensitivity, difficulty.`,ko:`플레이어가 조절하는 값 — 볼륨, 감도, 난이도.`},{en:`Emits changed(value). label/value/min/max/step/width/color. Setting .value from a behavior updates the control WITHOUT re-emitting, so restoring a saved setting does not fire the handler that saved it.`,ko:`changed(value) 시그널. label/value/min/max/step/width/color. 비헤이비어에서 .value를 설정하면 컨트롤만 갱신되고 changed는 다시 발생하지 않습니다 — 저장된 설정을 복원할 때 저장 핸들러가 다시 도는 것을 막습니다.`}),Q(`UiToggle`,{en:`An on/off switch — mute, invert-Y, fullscreen.`,ko:`켜기/끄기 스위치 — 음소거, Y축 반전, 전체화면.`},{en:`Emits changed(boolean). label/value. Same no-re-emit rule as UiSlider when set from code.`,ko:`changed(boolean) 시그널. label/value. 코드에서 설정할 때 재발생하지 않는 규칙은 UiSlider와 같습니다.`}),Q(`UiLanguageSelect`,{en:`The language picker, already wired.`,ko:`이미 연결된 언어 선택기.`},{en:`Options are the locales the scene declares in "strings", each labeled with its own endonym. Picking one switches the game live and persists it. English is the base: any key a locale omits falls back to it, on purpose.`,ko:`옵션은 씬의 "strings"가 선언한 로케일이며, 각 언어의 자기 이름으로 표시됩니다. 선택하면 즉시 바뀌고 저장됩니다. 영어가 기준이라 로케일이 빠뜨린 키는 의도적으로 영어로 표시됩니다.`}),Q(`Label3D`,{en:`Text standing in the world — a nameplate, a sign, a damage number.`,ko:`월드에 서 있는 텍스트 — 이름표, 표지판, 데미지 숫자.`},{en:`height is the cap height in METRES and the quad follows what the text measures, so a sign is as wide as its words. Faces the camera by default (a damage number read from behind is a bug) and carries a dark outline so it stays readable over anything. Everything else a sprite knows — anchor, tint, opacity, renderOrder — it inherits. For a damage number: set text, then float it up and fade opacity to 0 and queueFree().`,ko:`height는 글자 높이(미터)이고 가로 폭은 텍스트 실측을 따라갑니다. 기본으로 카메라를 향하며(뒤에서 읽히는 데미지 숫자는 버그니까요) 어두운 외곽선이 있어 어떤 배경에서도 읽힙니다. 앵커·틴트·투명도·renderOrder 등 스프라이트의 나머지 기능은 그대로 상속합니다. 데미지 숫자는 text를 넣고 위로 띄우며 opacity를 0으로 보낸 뒤 queueFree() 하면 됩니다.`}),Q(`UiVolumeSlider`,{en:`A volume slider, already wired to a bus.`,ko:`볼륨 슬라이더 — 버스에 이미 연결되어 있습니다.`},{en:`bus picks which one it owns: master (everything), sfx or music. It writes engine.audio, which persists itself, so nothing needs saving. Left unlabelled it names its own bus. Two of them (music + sfx) is the audio menu most games ship.`,ko:`bus로 어느 볼륨을 맡을지 고릅니다 — master(전체), sfx, music. engine.audio에 쓰면 자동 저장되므로 따로 저장할 게 없습니다. label을 비워두면 버스 이름이 표시됩니다. 대부분의 게임은 music + sfx 두 개면 충분합니다.`}),Q(`UiMuteToggle`,{en:`The mute switch — checked means silent.`,ko:`음소거 스위치 — 체크하면 소리가 꺼집니다.`},{en:`Writes engine.audio.muted and persists with the volumes. Follows a mute made anywhere else, so two menus can never disagree.`,ko:`engine.audio.muted에 쓰고 볼륨과 함께 저장됩니다. 다른 곳에서 음소거해도 따라가므로 두 메뉴가 어긋나지 않습니다.`}),Q(`UiQualitySelect`,{en:`Graphics quality — Low, Medium, High. Already wired.`,ko:`그래픽 품질 — Low, Medium, High. 이미 연결되어 있습니다.`},{en:`Low turns off shadows, bloom, post and clouds; Medium keeps shadows but makes them static and drops post; High is everything. Applies live and persists. Antialiasing follows the tier on the NEXT launch — it is a WebGL context attribute and cannot change while a context exists. Picking records a human choice, so device detection never overrides it later.`,ko:`Low는 그림자·블룸·포스트·구름을 끄고, Medium은 그림자를 정적으로 유지하며 포스트를 끄고, High는 전부 켭니다. 즉시 적용되고 저장됩니다. 안티에일리어싱만 다음 실행부터 반영됩니다(WebGL 컨텍스트 속성이라 생성 후에는 못 바꿉니다). 사람이 고른 값으로 기록되어 이후 자동 감지가 덮어쓰지 않습니다.`}),Q(`UiFrameCapSelect`,{en:`Frame rate cap — 30, 60, 120 or Unlimited.`,ko:`프레임 제한 — 30, 60, 120 또는 무제한.`},{en:`Gates the whole frame, not just the render, so it saves CPU as well as GPU — a cooler phone and a longer battery. Unlimited (0) is the default. Restrict the list with options, e.g. "60,120,0".`,ko:`렌더뿐 아니라 프레임 전체를 제한하므로 GPU와 CPU를 함께 아낍니다 — 발열과 배터리에 유리합니다. 기본값은 무제한(0). options로 목록을 줄일 수 있습니다(예: "60,120,0").`}),Q(`UiRenderScaleSelect`,{en:`Resolution scale — 50%, 75%, 100%.`,ko:`해상도 배율 — 50%, 75%, 100%.`},{en:`The cheapest frames on a weak GPU: at 75% the fragment shaders run over 56% of the pixels for a slightly softer image and nothing else, where dropping a quality tier costs the shadows outright. Multiplies with the engine's automatic resolution governor rather than fighting it.`,ko:`저사양 GPU에서 가장 값싼 프레임: 75%면 픽셀의 약 56%만 셰이딩하므로 이미지가 약간 부드러워질 뿐이지만, 품질 단계를 낮추면 그림자가 통째로 사라집니다. 엔진의 자동 해상도 조절과 충돌하지 않고 곱해집니다.`}),Q(`UiSelect`,{en:`One of several — quality, resolution, language.`,ko:`여러 개 중 하나 — 품질, 해상도, 언어.`},{en:`options is a comma-separated list ("low,medium,high"); value is the current one. Emits changed(value).`,ko:`options는 쉼표로 구분된 목록("low,medium,high"), value가 현재 선택입니다. changed(value) 시그널.`}),Q(`UiDialogue`,{en:`A typewriter dialogue box with a queue and choice buttons — the RPG conversation layer.`,ko:`타자기 효과·큐·선택지 버튼을 갖춘 대화창 — RPG 대화 레이어.`},{en:`Child of HudLayer (anchor bottom by default). say(speaker, text, choices?) queues lines; clicking (or advance()) reveals then advances; choice lines wait for choose(i). Signals: lineShown(text), choiceMade(index), dialogueFinished. charsPerSecond 0 = instant. Check .active to pause player input during conversations.`,ko:`HudLayer의 자식(기본 anchor bottom). say(화자, 텍스트, 선택지?)로 줄을 큐에 넣고, 클릭(또는 advance())이 전체 공개→다음 줄로 진행하며, 선택지 줄은 choose(i)를 기다립니다. 시그널: lineShown(text), choiceMade(index), dialogueFinished. charsPerSecond 0이면 즉시 표시. 대화 중 플레이어 입력을 멈추려면 .active를 확인하세요.`}),Q(`AudioPlayer`,{en:`Plays a sound: zero-asset procedural SFX, BGM loops, or one-shot effects.`,ko:`소리 재생 — 무에셋 절차적 효과음, 배경음 루프, 단발 효과음.`},{en:`Set preset (coin/jump/hurt/explosion/…) for an instant zero-asset SFX (pitch/seed vary it), or leave it "custom" and set src (URL or "$assetKey"). volume 0..1; bus routes through engine.audio (sfx|music) for global volume/mute; loop for music; autoplay starts on ready (browsers may hold it until the first user gesture). Call play()/stop() from game code. Dimension-free — 2D and 3D alike.`,ko:`preset(coin/jump/hurt/explosion/…)을 설정하면 즉시 무에셋 효과음이 납니다(pitch·seed로 변형). 아니면 "custom"으로 두고 src(URL 또는 "$에셋키")를 쓰세요. volume은 0..1, bus는 engine.audio(sfx|music)를 통해 전역 볼륨/음소거에 연결, 음악은 loop, autoplay는 준비되면 재생합니다(브라우저가 첫 입력까지 보류 가능). 게임 코드에서 play()/stop()을 부르세요. 2D·3D 어디서나 동작합니다.`})]},{id:`2d`,label:{en:`2D`,ko:`2D`},intro:{en:`The 2D world is y-down pixels: 1 unit = 1 px, (0,0) top-left, rotation in clockwise degrees. Rendering needs a current Camera2D.`,ko:`2D 세계는 y-아래 픽셀 좌표입니다: 1유닛=1px, (0,0)은 좌상단, 회전은 시계방향 도(degree). 렌더링에는 current 카메라(Camera2D)가 필요합니다.`},nodes:[Q(`Node2D`,{en:`The 2D transform container (position/rotation/scale).`,ko:`2D 변환 컨테이너(position/rotation/scale).`},{en:`Children inherit its transform — move the parent, everything follows. renderOrder orders drawing; visible hides the subtree.`,ko:`자식은 변환을 상속합니다 — 부모를 움직이면 전부 따라옵니다. renderOrder로 그리기 순서를, visible로 서브트리 표시를 제어합니다.`}),Q(`Sprite2D`,{en:`A textured quad.`,ko:`텍스처 사각형(스프라이트).`},{en:`texture is "$assetKey" from the scene assets. anchor [0.5,0.5] centers; flipX/flipY mirror; tint multiplies color; opacity fades. Size comes from the texture × scale.`,ko:`texture는 씬 에셋의 "$키"입니다. anchor [0.5,0.5]면 중앙 기준, flipX/flipY로 반전, tint로 색 곱, opacity로 투명도. 크기는 텍스처 × scale로 정해집니다.`}),Q(`ColorRect2D`,{en:`A flat colored rectangle — no texture needed.`,ko:`단색 사각형 — 텍스처 불필요.`},{en:`size [w,h] px, color, opacity, anchor. Backgrounds, platforms, walls, UI panels, generated-level tiles (maze2d/dungeon2d emit these) — blocky art without any asset.`,ko:`size [w,h] px, color, opacity, anchor. 배경·플랫폼·벽·UI 패널·생성 레벨 타일(maze2d/dungeon2d가 이걸 만듭니다) — 에셋 없이 만드는 블록 그래픽입니다.`}),Q(`TileMap2D`,{en:`A whole tile level as ONE node — grid render + merged static colliders.`,ko:`타일 레벨 전체를 노드 하나로 — 그리드 렌더 + 병합된 정적 콜라이더.`},{en:`Author cells as rows of characters: "." / space = empty, digits 0-9 = atlas tile index, other chars map through legend ({"G": 12}). texture is a "$atlas" asset read left-to-right top-to-bottom in tileSize squares (columns: 0 derives from the texture width). Tile indices listed in solid become static colliders, greedy-merged into a few rectangles. Cell (0,0) hangs its top-left on the node origin.`,ko:`cells를 문자 행으로 작성합니다: "."/공백 = 빈 칸, 숫자 0-9 = 아틀라스 타일 번호, 그 외 문자는 legend({"G": 12})로 매핑. texture는 tileSize 정사각형을 좌→우, 상→하로 읽는 "$아틀라스" 에셋입니다(columns: 0이면 텍스처 폭에서 유도). solid에 나열된 타일 번호는 정적 콜라이더가 되며 소수의 직사각형으로 탐욕 병합됩니다. (0,0) 칸의 좌상단이 노드 원점에 걸립니다.`}),Q(`AnimatedSprite2D`,{en:`Spritesheet animation player.`,ko:`스프라이트시트 애니메이션 플레이어.`},{en:`Point sheet at a "$sheet" asset, define animations as named frame ranges with fps/loop in JSON, set autoplay. Emits animationFinished(name) for one-shot chains.`,ko:`sheet에 "$시트" 에셋을 연결하고, JSON에 fps/loop를 가진 이름별 프레임 구간으로 animations를 정의한 뒤 autoplay를 지정하세요. 단발 애니메이션 연결을 위해 animationFinished(name)를 발산합니다.`}),Q(`Camera2D`,{en:`The 2D view: follow, zoom, limits.`,ko:`2D 시점 — 추적·줌·경계.`},{en:`position is the view CENTER. follow tracks a node path with smoothing (0..1, higher = snappier). limits [minX,minY,maxX,maxY] clamps the view inside a world region. current: true makes it THE camera.`,ko:`position은 화면의 중심입니다. follow가 노드 경로를 smoothing(0..1, 높을수록 빠릿)으로 추적합니다. limits [minX,minY,maxX,maxY]가 시점을 월드 영역 안에 가둡니다. current: true인 카메라가 실제 시점이 됩니다.`}),Q(`Particles2D`,{en:`A 2D particle emitter (fire, sparks, smoke…).`,ko:`2D 파티클 이미터(불·스파크·연기…).`},{en:`Start from a preset (fire/smoke/sparks/…) then override any prop: rate, lifetime/speed ranges, direction + spread, gravity, size/color/alpha start→end, additive blend. burst > 0 with emitting: false makes a one-shot that emits finished. Animates LIVE in this editor.`,ko:`preset(fire/smoke/sparks/…)에서 시작해 어떤 prop이든 덮어쓰세요: rate, lifetime/speed 구간, direction+spread, gravity, size/color/alpha 시작→끝, additive blend. emitting: false에 burst > 0이면 단발 발사 후 finished를 발산합니다. 이 에디터에서 라이브로 움직입니다.`}),Q(`Label`,{en:`Text rendered to a quad.`,ko:`텍스트를 그리는 노드.`},{en:`text/fontSize/color/font/align — rendered via CanvasTexture, so any system font string works. Inside a UILayer it pins to the screen (HUD).`,ko:`text/fontSize/color/font/align — CanvasTexture로 그려져 시스템 폰트 문자열을 그대로 쓸 수 있습니다. UILayer 아래에 두면 화면에 고정됩니다(HUD).`}),Q(`UILayer`,{en:`A screen-space subtree (HUD).`,ko:`화면 고정 서브트리(HUD).`},{en:`Everything under it ignores the camera: positions are screen pixels from the top-left. Score counters, prompts, menus go here.`,ko:`이 아래의 모든 것은 카메라를 무시합니다 — 좌상단 기준 화면 픽셀 좌표입니다. 점수, 안내 문구, 메뉴를 여기에 둡니다.`})]},{id:`2d-physics`,label:{en:`2D Physics`,ko:`2D 물리`},intro:{en:`Rapier-backed. Colliders are PROPS ({shape, …}) — the green dashed wireframes in this editor. Physics runs when the game calls enablePhysics2D (and in play mode). Gravity lives on the scene row.`,ko:`Rapier 기반입니다. 콜라이더는 prop({shape, …})이며 에디터의 초록 점선이 그것입니다. 물리는 게임이 enablePhysics2D를 부를 때(그리고 플레이 모드에서) 돌고, 중력은 씬 행에 있습니다.`},nodes:[Q(`StaticBody2D`,{en:`Immovable collision: ground, walls, platforms.`,ko:`움직이지 않는 충돌체 — 바닥·벽·플랫폼.`},{en:`Other bodies collide with it; it never moves. Cheapest body type — use it for all level geometry.`,ko:`다른 바디가 부딪히지만 자신은 절대 움직이지 않습니다. 가장 저렴한 바디 — 레벨 지형 전부에 쓰세요.`}),Q(`RigidBody2D`,{en:`Fully simulated: falls, bounces, pushes.`,ko:`완전 시뮬레이션 — 떨어지고 튕기고 밀립니다.`},{en:`Gravity and collisions drive it. Set linearVelocity to launch. For player characters prefer CharacterBody2D (direct control).`,ko:`중력과 충돌이 움직임을 결정합니다. linearVelocity로 발사하세요. 플레이어 캐릭터에는 직접 제어가 가능한 CharacterBody2D를 권합니다.`}),Q(`CharacterBody2D`,{en:`Kinematic character: you set velocity, it slides.`,ko:`키네마틱 캐릭터 — 속도를 주면 미끄러지듯 이동.`},{en:`moveAndSlide() resolves collisions without physics pushing back; isOnFloor() gates jumps. Sensors (Area2D) do not block it but still fire triggers.`,ko:`moveAndSlide()가 밀려나지 않으면서 충돌을 처리하고 isOnFloor()로 점프를 판정합니다. 센서(Area2D)는 길을 막지 않으면서 트리거를 발사합니다.`}),Q(`Area2D`,{en:`A sensor: overlap triggers, no collision response.`,ko:`센서 — 겹침 감지만, 충돌 반응 없음.`},{en:`Fires triggerEnter(other)/triggerExit(other). Coins, checkpoints, damage zones. Filter with other.isInGroup("player").`,ko:`triggerEnter(other)/triggerExit(other)를 발산합니다. 코인·체크포인트·데미지 존에 쓰고, other.isInGroup("player")로 거릅니다.`}),Q(`CharacterController2D`,{en:`Zero-code platformer/top-down movement.`,ko:`코드 없는 플랫포머/탑다운 이동.`},{en:`Put it UNDER a CharacterBody2D. mode "platformer" (gravity + jump via jumpAction) or "topDown" (free 2-axis). Reads the scene input map actions (moveAction/jumpAction). maxSpeed/jumpHeight are intent-level numbers.`,ko:`CharacterBody2D의 자식으로 두세요. mode는 "platformer"(중력+jumpAction 점프) 또는 "topDown"(자유 2축)이며 씬 입력 맵의 액션(moveAction/jumpAction)을 읽습니다. maxSpeed/jumpHeight는 의도 그대로의 숫자입니다.`}),Q(`Joint2D`,{en:`A physics joint linking its parent body to a target body — weld, hinge, rope, spring.`,ko:`부모 바디와 대상 바디를 잇는 물리 조인트 — 용접, 힌지, 로프, 스프링.`},{en:`Child of body A (a physics body); "target" is a node path to body B. type: fixed (rigid weld) / revolute (pin at the anchors) / rope (caps anchor distance at length px; 0 = measured at creation) / spring (pulls toward length with stiffness/damping). anchor/targetAnchor are LOCAL px offsets.`,ko:`바디 A(물리 바디)의 자식으로 두고 "target"에 바디 B의 노드 경로를 줍니다. type: fixed(강체 용접) / revolute(앵커 핀 힌지) / rope(앵커 간 거리를 length px로 제한, 0이면 생성 시 실측) / spring(stiffness/damping으로 length를 향해 당김). anchor/targetAnchor는 로컬 px 오프셋.`})]},{id:`3d`,label:{en:`3D`,ko:`3D`},intro:{en:`Meters, y-up, rotations in degrees. Standard materials need LIGHT — add a DirectionalLight3D or scene ambient, or you get silhouettes.`,ko:`미터 단위, y-위, 회전은 도(degree)입니다. 표준 머티리얼은 빛이 필요합니다 — DirectionalLight3D나 씬 ambient가 없으면 실루엣만 보입니다.`},nodes:[Q(`Node3D`,{en:`The 3D transform container.`,ko:`3D 변환 컨테이너.`},{en:`position [x,y,z] in meters, rotation [x,y,z] in degrees, scale per axis. Children inherit.`,ko:`position [x,y,z] 미터, rotation [x,y,z] 도, scale은 축별. 자식이 상속합니다.`}),Q(`MeshInstance3D`,{en:`A primitive mesh + material.`,ko:`프리미티브 메시 + 머티리얼.`},{en:`mesh: box/sphere/plane/cylinder…, size per primitive, material {color, roughness, metalness, emissive, emissiveIntensity, wireframe, map, normalMap, repeat} (this editor gives it swatches, sliders, texture-URL fields, and a repeat [u,v] tiling vector). map/normalMap are texture URLs; repeat only takes effect with a map. castShadow/receiveShadow per node.`,ko:`mesh: box/sphere/plane/cylinder…, 프리미티브별 size, material {color, roughness, metalness, emissive, emissiveIntensity, wireframe, map, normalMap, repeat}(에디터가 스와치·슬라이더·텍스처 URL 입력·repeat [u,v] 타일링 벡터 제공). map/normalMap은 텍스처 URL, repeat는 map이 있을 때만 적용. 그림자는 castShadow/receiveShadow.`}),Q(`LoftMesh3D`,{en:`A smooth swept hull (loft).`,ko:`부드러운 스윕 선체(로프트).`},{en:`sections: ≥2 cross-section stations {z, width, height, y, corner 0..1} interpolated into ONE smooth curved surface — vehicle bodies, glass canopies, boat hulls. slices/smooth control tessellation. Same material as MeshInstance3D minus textures (no UVs); pair clearcoat paint or high-envMapIntensity glass with the smooth normals for the automotive look.`,ko:`sections: 단면 스테이션 {z, width, height, y, corner 0..1} 2개 이상을 보간해 하나의 매끈한 곡면을 만듭니다 — 차체, 유리 캐노피, 선체. slices/smooth로 테셀레이션 조절. material은 MeshInstance3D와 동일하되 텍스처 제외(UV 없음). clearcoat 도장이나 높은 envMapIntensity 유리를 곡면 법선과 조합하면 자동차 룩이 납니다.`}),Q(`ModelInstance3D`,{en:`A GLB/glTF/VRM model file.`,ko:`GLB/glTF/VRM 모델 파일.`},{en:'model: "$assetKey" or URL. targetHeight scales the model to stand N units tall (run `npx incanto-model file.glb` to read its real size first). animation plays an embedded clip name OR an "$animation" asset — Mixamo clips retarget onto VRM humanoids automatically. One node per VRM asset (the avatar runtime mounts live). To make it SOLID, park it under a body with collider {shape:"auto"}: the collider is built from the model\'s own triangles — a triangle mesh on a static body (keeps its holes, so you walk through an archway) and a convex hull on a moving one.',ko:'model은 "$에셋키" 또는 URL입니다. targetHeight가 모델을 N유닛 높이로 맞춥니다(먼저 `npx incanto-model 파일.glb`로 실제 크기를 확인하세요). animation은 내장 클립 이름 또는 "$애니메이션" 에셋을 재생하며, Mixamo 클립은 VRM 휴머노이드에 자동 리타게팅됩니다. VRM 에셋은 노드 하나만 쓸 수 있습니다(아바타 런타임이 라이브로 마운트됨). 단단하게 만들려면 collider {shape:"auto"}인 바디 아래에 두세요 — 모델 자신의 삼각형에서 콜라이더가 만들어집니다(정적 바디는 트라이메시라 아치 구멍도 그대로, 움직이는 바디는 볼록 껍질).'}),Q(`Sprite3D`,{en:`A 2D image as a camera-facing billboard (the 2.5D look).`,ko:`카메라를 향하는 2D 빌보드 스프라이트(2.5D 룩).`},{en:`A textured quad that turns to face the camera inside the 3D world (Octopath / Don't Starve / MapleStory-in-3D). texture is an image URL; size is [w,h] in METERS. billboard: "y" stays upright with a screen-aligned yaw — off-center sprites never roll (characters/props), "full" faces it completely (items/FX), "none" is fixed to the node rotation. anchor [0.5,0] plants the feet on the ground. pixelArt nearest-filters for crisp pixels; alphaTest is a hard cutout that depth-sorts against 3D geometry (a tree occludes it); flipX mirrors left/right; tint/opacity recolor.`,ko:`3D 월드 안에서 카메라를 향해 도는 텍스처 쿼드(Octopath/Don't Starve, 3D 속 메이플스토리 룩). texture는 이미지 URL, size는 [너비,높이] 미터. billboard: "y"는 세로로 선 채 카메라 방향과 정렬된 yaw — 화면 가장자리에서도 기울지 않음(캐릭터/사물), "full"은 완전히 향함(아이템/FX), "none"은 노드 회전에 고정. anchor [0.5,0]은 발을 바닥에 둡니다. pixelArt는 nearest 필터로 픽셀을 또렷하게, alphaTest는 3D 지형과 깊이정렬되는 하드 컷아웃(나무가 가림), flipX는 좌우 반전, tint/opacity로 색·투명도.`}),Q(`AnimatedSprite3D`,{en:`A billboard sprite that plays spritesheet animations.`,ko:`스프라이트시트 애니를 재생하는 빌보드 스프라이트.`},{en:`Everything Sprite3D does, plus frame animation. sheet is a spritesheet image URL whose cells are frameWidth×frameHeight; animations maps a name to {frames, fps, loop} where frames is an inclusive [start,end] range or an explicit list; autoplay starts one on load. Game code calls play("walk") / stop(); a non-looping clip clamps on its last frame and emits animationFinished(name) — chain attack→idle from it.`,ko:`Sprite3D의 모든 기능 + 프레임 애니. sheet는 frameWidth×frameHeight 칸을 가진 스프라이트시트 URL, animations는 이름→{frames, fps, loop}(frames는 포함 [시작,끝] 범위 또는 명시 목록), autoplay는 로드 시 하나를 시작. 게임 코드에서 play("walk")/stop() 호출, 비반복 클립은 마지막 프레임에 머물며 animationFinished(name)를 emit(attack→idle 연결).`}),Q(`Billboard3D`,{en:`A group that turns toward the camera — children follow.`,ko:`카메라를 향해 도는 그룹 — 자식들이 함께 회전.`},{en:`A transform container that orients itself toward the camera every frame; children inherit the rotation, so hang world-space UI under it — HP bars, markers, floating icons (text is a canvas-rendered texture on a child Sprite3D). mode: "screen" (default) copies the camera orientation so a child rectangle stays an upright rectangle anywhere on screen (a yaw-only look-at visibly tilts off-center shapes under a pitched camera); "y" stays upright with a screen-aligned yaw (no off-center roll); "none" turns billboarding off. While billboarding, the node's own rotation prop (and the rotate gizmo) is overwritten every frame — switch to "none" to pose children, then switch back. Unlike Sprite3D (a textured quad that spins only its own image), Billboard3D rotates the whole group.`,ko:`매 프레임 카메라를 향해 자신을 회전시키는 변환 컨테이너로, 자식이 회전을 상속합니다 — HP바·마커·아이콘 같은 월드 UI를 자식으로 붙이세요(텍스트는 캔버스로 그린 텍스처를 자식 Sprite3D에). mode: "screen"(기본)은 카메라 자세를 그대로 복사해 자식 직사각형이 화면 어디서든 똑바른 직사각형으로 보입니다(yaw만 도는 look-at은 기울어진 카메라에서 중앙 밖 도형이 눈에 띄게 비스듬해짐); "y"는 세로로 선 채 카메라로 yaw만; "none"은 빌보드 끔. 빌보드 중에는 노드 자신의 rotation(회전 기즈모 포함)이 매 프레임 덮어써집니다 — 자식을 배치할 땐 "none"으로 바꿨다가 되돌리세요. 자기 그림만 도는 Sprite3D(텍스처 쿼드)와 달리 그룹 전체가 회전합니다.`}),Q(`Camera3D`,{en:`The 3D view.`,ko:`3D 시점.`},{en:`Perspective camera; fov in degrees; current: true selects it. Use the editor's "game cam" (0) to preview exactly what it renders.`,ko:`원근 카메라이며 fov는 도 단위, current: true가 실제 시점이 됩니다. 에디터의 "game cam"(0)으로 정확한 렌더 결과를 미리 보세요.`}),Q(`DirectionalLight3D`,{en:`Sun-like light from a direction.`,ko:`태양광 — 방향에서 평행하게.`},{en:`Position sets the direction toward the origin. intensity/color; pair with scene ambient for soft fill.`,ko:`위치가 원점을 향한 방향을 정합니다. intensity/color를 조절하고 부드러운 채움광은 씬 ambient와 함께 쓰세요.`}),Q(`OmniLight3D`,{en:`A point light radiating everywhere.`,ko:`점광 — 사방으로 퍼지는 빛.`},{en:`Lamps, torches, glows. range limits reach; intensity/color shape the falloff.`,ko:`램프·횃불·발광체. range로 도달 거리를, intensity/color로 감쇠를 만듭니다.`}),Q(`Particles3D`,{en:`A 3D particle emitter (fire, magic, weather…).`,ko:`3D 파티클 이미터(불·마법·날씨…).`},{en:`The same preset + override model as Particles2D, in meters with [x,y,z] gravity. Camera-facing billboard quads, instanced — hundreds are cheap. Animates LIVE in this editor.`,ko:`Particles2D와 같은 preset+덮어쓰기 모델을 미터 단위와 [x,y,z] 중력으로. 카메라를 향하는 빌보드 쿼드를 인스턴싱해 수백 개도 가볍습니다. 이 에디터에서 라이브로 움직입니다.`}),Q(`Terrain3D`,{en:`Procedural heightfield terrain with biome texture splatting.`,ko:`바이옴 텍스처 스플래팅이 적용된 절차적 하이트필드 지형.`},{en:`Seeded simplex hills displaced once on the CPU; theme (island/alpine/plains/desert/custom) picks the 4 blended biome textures by height and slope. heightAt(x,z) answers the surface height anywhere. For physics, parent it under a StaticBody3D with collider {shape:'heightfield'}.`,ko:`시드 기반 심플렉스 언덕을 CPU에서 한 번 변위합니다. theme(island/alpine/plains/desert/custom)이 높이·경사로 블렌딩되는 바이옴 텍스처 4장을 고릅니다. heightAt(x,z)로 어디서든 지표 높이를 얻고, 물리는 StaticBody3D 아래에 두고 collider {shape:'heightfield'}를 쓰세요.`}),Q(`Water3D`,{en:`A shader-water surface with splash signals.`,ko:`스플래시 신호를 내는 셰이더 물 표면.`},{en:`size [w,d] meters on XZ. quality 'fancy' (default) = FBM wave shader with a trough/surface/peak ramp (colors), CubeCamera reflections (reflection/reflectionInterval) and opt-in shoreline foam; 'simple' = the cheap sine material (color). Bodies crossing the surface emit entered/exited(body) and raise ripples (interaction). Volumetric gameplay still wants an Area3D. Waves animate LIVE in this editor.`,ko:`XZ 평면에 size [w,d] 미터. quality 'fancy'(기본)는 FBM 파도 셰이더 — trough/surface/peak 램프(colors), CubeCamera 반사(reflection/reflectionInterval), 옵트인 해안 거품(foam). 'simple'은 저사양용 사인파 머티리얼(color). 바디가 수면을 지나면 entered/exited(body) 신호와 물결이 일어납니다(interaction). 부피 기반 게임플레이엔 여전히 Area3D를 쓰세요. 이 에디터에서 파도가 라이브로 움직입니다.`}),Q(`River3D`,{en:`Running water derived from a path and the ground under it.`,ko:`경로와 그 아래 지형에서 유도되는 흐르는 물.`},{en:`Author a centerline path [[x,z],…] plus width/widths (a profile source→mouth) and depth; the node samples the Terrain3D underneath and derives the rest. It CARVES ITS OWN BED by default (carve): a trench per reach that heightAt, the collider, the splat and draped vegetation all see, with a floor that only ever falls, so a path over a rise digs through instead of burying the water. Its surface is then FITTED to that ground — never higher than the lowest rim holding it, ending where the ground comes up to meet it (asymmetric on a sloping reach), lying down as a film where a bank has fallen away, so a river can never hang in the air. Plus a current that speeds up where the channel pinches or tips (flowSpeed is the mean) and whitewater from grade, bank shear and thinning column. Boulders in the channel are answered without wiring: the node finds MeshInstance3D/InstancedMesh3D footprints standing in the water column and the current piles a white cushion on the upstream face, tears a wake downstream and bends its sheen around them. A trench thinner than a terrain cell cannot survive the grid: a 2.4 m creek on a 260 m map wants Terrain3D resolution 256. flowForce drags bodies downstream (drag, never thrust) and sampleAt(x,z) answers where a world point sits in the channel. No extra render passes — a map can carry a dozen.`,ko:`중심선 path [[x,z],…]와 width/widths(상류→하류 프로파일), depth만 주면 나머지는 아래 Terrain3D를 샘플링해 유도합니다. 기본적으로 강이 자기 바닥을 직접 팝니다(carve) — 구간마다 하나씩 도랑을 내고, heightAt·콜라이더·스플랫·식생 드레이프가 모두 그 지형을 봅니다. 파낸 바닥은 계속 내려가기만 하므로 경로가 언덕을 넘어도 물이 묻히지 않고 뚫고 흐릅니다. 그리고 수면은 그 지형에 맞춰집니다 — 자기를 담는 가장 낮은 둑보다 높아질 수 없고, 지면이 올라오는 지점에서 끝나며(비스듬한 구간에서는 좌우 폭이 다릅니다), 둑이 아예 없는 쪽에서는 경사면에 얇은 막처럼 누워버립니다. 그래서 강이 공중에 뜨는 일이 없습니다. 여기에 폭이 좁아지거나 경사가 급해지면 빨라지는 유속(flowSpeed는 평균)과 경사·둑 전단·얕아지는 수심에서 나오는 흰 물살이 더해집니다. 수로에 놓인 바위도 배선 없이 반응합니다 — MeshInstance3D/InstancedMesh3D 중 실제로 물기둥과 겹치는 것을 찾아, 상류면에 흰 물이 쌓이고 하류로 후류가 찢어지며 수면 광택이 바위를 돌아 휩니다. 지형 셀보다 얇은 도랑은 그리드에서 살아남지 못합니다 — 260 m 맵의 2.4 m 개울이라면 Terrain3D resolution 256이 필요합니다. flowForce가 바디를 하류로 끌고(밀지 않고 끌어당김), sampleAt(x,z)로 월드 좌표가 수로 어디에 있는지 알 수 있습니다. 추가 렌더 패스가 없어 한 맵에 여러 개를 둘 수 있습니다.`}),Q(`WaterCutout3D`,{en:`Marks its parent as something that holds the water back — a dry hull, a diving bell, a well.`,ko:`부모 오브젝트가 물을 막는다고 표시 — 마른 선실, 잠수종, 우물.`},{en:`Water is ONE surface and knows nothing about interiors, so an open hull floating on it fills with sea every time a crest clears its floor — freeboard alone can never promise otherwise. This node names the geometry that keeps the water out: it MUST be a CHILD of that thing (a hull, a bell, a dock's well, a cave mouth), and the water re-draws the part of it inside the box into its depth pre-pass, then hides behind it exactly as it hides behind any solid object. Nothing is ever cut OUT of the water, so a hole in open sea is impossible: overshoot the box and more of that hull holds water back, undershoot and water stands in the bow. size is the box extent in meters; enabled toggles it live (a scuttled hull starts letting the sea in). Four per water surface; needs quality fancy.`,ko:`물은 하나의 표면이라 '안쪽'이라는 개념이 없습니다. 그래서 뚜껑 없는 배를 띄우면 파도 마루가 바닥을 넘을 때마다 배 안에 바다가 차 보이고, 건현(freeboard)만으로는 절대 막을 수 없습니다. 이 노드는 '물을 막는 지오메트리'를 지정합니다. 반드시 그 물체(선체·잠수종·부두 우물·동굴 입구)의 자식이어야 하며, 물이 상자 안쪽의 그 지오메트리를 자기 깊이 프리패스에 다시 그린 뒤 평범한 불투명 물체 뒤에 숨듯 그 뒤로 숨습니다. 물에서 무언가를 '도려내지' 않으므로 열린 바다에 구멍이 나는 일은 원리적으로 불가능합니다 — 상자가 크면 그 배가 물을 더 많이 막을 뿐이고, 작으면 뱃머리에 물이 남습니다. size는 미터 단위 상자 크기, enabled는 런타임 토글(침수 시작 연출). 수면 하나당 4개, quality fancy 필요.`}),Q(`Foliage3D`,{en:`An instanced grass/flower carpet that sways.`,ko:`바람에 흔들리는 인스턴스 풀밭/꽃밭. `},{en:`kind grass/flowers/reeds scattered over area [w,d] at density (capped by maxInstances — instanced, tens of thousands of blades cheap). Grass defaults to style 'mesh': every instance is a REAL tapered blade curved by a bezier vertex shader — Voronoi-clump hue/lean, groundColor soil roots (match the terrain), sunDirection tip sheen, 2-octave rolling wind, fadeStart/fadeEnd camera LOD, and (interaction) blade-bending around moving bodies. style 'blades' keeps the 8-SDF-blades-per-quad ported shader, 'simple' the legacy quads. colorA/colorB tint bottom→top, sway sets the wind, seed makes the scatter reproducible. avoidWater (on by default) keeps blades OUT of standing and running water — a creek cutting its bed through the field gets banks, not blades waving in the current; turn it off for reeds and paddy fields.`,ko:`kind grass/flowers/reeds를 area [w,d]에 density로 흩뿌립니다(maxInstances 상한 — 인스턴싱이라 수만 가닥도 가벼움). grass는 기본 style 'mesh': 인스턴스 하나하나가 베지어 버텍스 셰이더로 휘어지는 진짜 잎 메시 — 보로노이 클럼프 색/기울기, groundColor 흙빛 뿌리(지형 색에 맞추세요), sunDirection 잎끝 광택, 2옥타브 굽이치는 바람, fadeStart/fadeEnd 카메라 LOD, (interaction) 움직이는 바디 주변 풀 눕힘까지. style 'blades'는 쿼드당 8가닥 SDF 셰이더, 'simple'은 기존 쿼드 룩. colorA/colorB가 아래→위 색, sway가 바람 세기, seed가 배치를 재현 가능하게 합니다. avoidWater(기본 켜짐)는 고인 물·흐르는 물 안에 잎을 심지 않습니다 — 개울이 들판을 가르고 지나가면 물살 속에 풀이 서 있는 대신 둑이 생깁니다. 갈대·논은 꺼서 쓰세요.`}),Q(`Flowers3D`,{en:`Instanced flower PLANTS — stems, leaves, multi-petal heads.`,ko:`인스턴스 꽃밭 — 줄기·잎·여러 장 꽃잎의 진짜 꽃 식물.`},{en:`Real procedural flower plants (curved stem, 2-3 leaves, a 5-8 petal head around a contrasting center disc, 1-3 blooms per plant) scattered over area [w,d]. density is the vibe dial: 'lush' / 'sparse' (default) / 'none', or a number in plants/m². varieties picks a subset of daisy/cosmos/bellflower ([] = all three); palette sets the head colors ([] = white/yellow/violet). clustering 0-1 gathers plants into Voronoi patches that bloom one species + color together; sway bobs the heads in a gentle wind; seed makes the field reproducible. ≤3 varieties → ≤6 draw calls. avoidWater (on by default) keeps plants out of standing and running water — a meadow a stream runs through has a bank of flowers, not flowers in the current.`,ko:`진짜 프로시저럴 꽃 식물(휘어진 줄기, 잎 2-3장, 대비되는 중심 원반을 두른 꽃잎 5-8장 머리, 포기당 꽃 1-3송이)을 area [w,d]에 흩뿌립니다. density가 바이브 다이얼: 'lush'(풍성하게) / 'sparse'(듬성듬성, 기본) / 'none'(없게) 또는 m²당 개수. varieties는 daisy/cosmos/bellflower 부분집합([] = 셋 다), palette는 꽃 색([] = 흰/노랑/보라). clustering 0-1이 보로노이 패치로 모아 한 패치가 같은 종·같은 색으로 피고, sway가 바람에 머리를 끄덕이며, seed로 배치가 재현됩니다. 품종 ≤3 → 드로우 콜 ≤6. avoidWater(기본 켜짐)는 고인 물·흐르는 물 안에 꽃을 심지 않습니다 — 시내가 지나는 들판에는 물살 속 꽃이 아니라 꽃이 핀 둑이 생깁니다.`}),Q(`Tree3D`,{en:`Procedural tree groves — real branching trunks, textured leaves, one node per forest.`,ko:`프로시저럴 나무 숲 — 진짜 가지가 뻗은 줄기와 텍스처 잎, 숲 하나가 노드 하나.`},{en:`type conifer/broadleaf/dead picks the recipe family; tier is the cost dial: simple = primitive low-poly, medium = light forest presets (≤3k tris/tree), high = full ez-tree presets (8–20k, hero trees). count > 1 scatters a forest patch over area [w,d] — up to 3 seed variants, each branches + leaves InstancedMesh (≤6 draw calls); count × tris/tree is budget-checked at load. seed makes every branch and leaf reproducible; height jitters ±20% per instance; leaves sway in a simplex wind.`,ko:`type conifer/broadleaf/dead가 수종을, tier가 비용을 정합니다: simple = 기존 로우폴리, medium = 가벼운 forest 프리셋(나무당 ≤3k tris), high = 풀 ez-tree 프리셋(8–20k, 주인공 나무). count > 1이면 area [w,d]에 숲 패치를 흩뿌립니다 — 시드 변형 최대 3종, 변형마다 가지+잎 InstancedMesh(드로우 콜 ≤6), count × tris는 로드 시 예산 검사. seed로 가지와 잎이 전부 재현되고 height는 인스턴스마다 ±20% 지터링, 잎은 심플렉스 바람에 흔들립니다.`}),Q(`VoxelGrid3D`,{en:`A Minecraft-style block grid in ONE node.`,ko:`마인크래프트식 블록 그리드 — 노드 하나로.`},{en:`voxels is a list of [x,y,z,palette] integer cells (terrain/island generators emit these). Greedy-meshed and instanced — large worlds stay one draw batch. Game code edits blocks via setBlock/getBlock; emits blocksChanged.`,ko:`voxels는 [x,y,z,팔레트] 정수 셀 목록입니다(terrain/island 생성기가 만들어 냅니다). 그리디 메싱+인스턴싱으로 큰 월드도 드로우 배치 하나를 유지합니다. 게임 코드는 setBlock/getBlock으로 수정하고 blocksChanged가 발산됩니다.`})]},{id:`3d-physics`,label:{en:`3D Physics`,ko:`3D 물리`},intro:{en:`Same model as 2D, in meters with y-up gravity ([0,-9.81,0] default). Colliders: box {size}, sphere {radius}, capsule {radius,height}.`,ko:`2D와 같은 모델을 미터·y-위 중력([0,-9.81,0] 기본)으로. 콜라이더는 box {size}, sphere {radius}, capsule {radius,height}.`},nodes:[Q(`StaticBody3D`,{en:`Immovable 3D collision.`,ko:`움직이지 않는 3D 충돌체.`},{en:`Floors, walls, level geometry. collider {shape:"auto"} takes the shape from the MeshInstance3D or ModelInstance3D the body carries as a child, so the blocker can never be bigger or smaller than what the player sees — the fix for hand-typed extents that leave you stopping in mid-air. A GLB becomes a triangle mesh here, holes and all.`,ko:`바닥·벽·레벨 지형. collider {shape:"auto"}는 바디가 자식으로 들고 있는 MeshInstance3D 또는 ModelInstance3D의 생김새를 그대로 씁니다 — 보이는 것보다 크거나 작은 콜라이더가 생길 수 없습니다. 손으로 적은 크기 때문에 허공에서 막히는 문제의 해법입니다. GLB는 여기서 구멍까지 살아있는 트라이메시가 됩니다.`}),Q(`RigidBody3D`,{en:`Simulated 3D body.`,ko:`시뮬레이션되는 3D 바디.`},{en:`Crates, balls, debris — gravity and impacts drive it.`,ko:`상자·공·파편 — 중력과 충격이 움직입니다.`}),Q(`CharacterBody3D`,{en:`Kinematic 3D character.`,ko:`키네마틱 3D 캐릭터.`},{en:`moveAndSlide with up = +y; isOnFloor for jumps.`,ko:`+y를 위로 moveAndSlide, 점프 판정은 isOnFloor.`}),Q(`Area3D`,{en:`3D overlap sensor.`,ko:`3D 겹침 센서.`},{en:`triggerEnter/Exit — pickups, zones, goals.`,ko:`triggerEnter/Exit — 아이템·존·골인 지점.`}),Q(`CharacterController3D`,{en:`Zero-code 3D movement + camera rig.`,ko:`코드 없는 3D 이동 + 카메라 리그.`},{en:`Put it UNDER a CharacterBody3D. view: thirdPerson (orbit + zoom), firstPerson (eyeHeight, mouseLook), sideView or flightView. Reads moveAction/jumpAction/sprintAction from the scene input map; skinPath turns the visual child to face travel. Intent-level numbers: maxSpeed, jumpVelocity, camDistance.`,ko:`CharacterBody3D의 자식으로 두세요. view는 thirdPerson(궤도+줌), firstPerson(eyeHeight, mouseLook), sideView, flightView 중 하나입니다. 씬 입력 맵의 moveAction/jumpAction/sprintAction을 읽고 skinPath의 비주얼 자식을 진행 방향으로 돌립니다. maxSpeed·jumpVelocity·camDistance 같은 의도 수준의 숫자만 만집니다.`}),Q(`BoneLookAt3D`,{en:`Look-at IK for one bone — the head turns toward a target on top of the animation.`,ko:`본 하나의 룩앳 IK — 애니메이션 위에서 머리가 대상을 향해 돌아갑니다.`},{en:`"target" = ModelInstance3D path, "bone" = bone name (default Head), "lookAt" = the node to watch (e.g. "%Player"). Blends in/out smoothly and DISENGAGES beyond maxAngleDeg (no owl necks); weight sets how far it commits. forwardAxis names the bone's facing axis (mixamo heads: +z). Purely visual — headless no-op.`,ko:`"target"에 ModelInstance3D 경로, "bone"에 본 이름(기본 Head), "lookAt"에 바라볼 노드(예: "%Player")를 줍니다. 부드럽게 페이드 인/아웃하고 maxAngleDeg 밖에서는 해제됩니다(목이 돌아가지 않음). weight로 몰입도를 조절하고 forwardAxis는 본의 정면 축입니다(mixamo 머리: +z). 순수 시각 기능 — 헤드리스에서는 no-op.`}),Q(`InstancedMesh3D`,{en:`Hundreds of copies of one mesh in ONE draw call — rocks, posts, crates.`,ko:`메시 하나의 수백 개 복사본을 드로우콜 1개로 — 바위, 말뚝, 상자.`},{en:`Same mesh/size/material surface as MeshInstance3D; "transforms" places the copies — each row [x, y, z, yawDeg?, scale?]. Replace the whole array to update (mutations are not watched). The scattering workhorse for open worlds. collider: {} makes the whole field solid — every row gets its own collider SHAPED LIKE THE MESH (a faceted gem stone collides as that stone's hull, not as a ball tucked inside it), all hanging off one fixed body. A boulder field the player walks straight through is the tell that a world is scenery rather than a place.`,ko:`MeshInstance3D와 같은 mesh/size/material 표면에 "transforms"로 복사본을 배치합니다 — 각 행은 [x, y, z, yawDeg?, scale?]. 갱신은 배열 전체 교체로 하세요(내부 변경은 감지되지 않음). 오픈월드 스캐터링의 주력입니다. collider: {}를 주면 필드 전체가 단단해집니다 — 행마다 메시 생김새 그대로의 콜라이더가 생기고(각진 gem 바위는 안에 박힌 구가 아니라 그 바위 자신의 볼록 껍질로 부딪힙니다), 전부 하나의 고정 바디에 붙습니다. 플레이어가 통과해버리는 바위밭은 그 세계가 배경 그림이라는 신호입니다.`}),Q(`BoneAttachment3D`,{en:`Rides a skeleton bone of an animated model — swords in hands, hats on heads.`,ko:`애니메이션 모델의 스켈레톤 본을 따라다님 — 손에 쥔 검, 머리 위 모자.`},{en:`"target" is a node path to the ModelInstance3D, "bone" the bone name ("RightHand" also matches the Mixamo spellings). Children inherit the live animated transform; this node's own position/rotation become a bone-space offset. Purely visual — headless it stays where its props put it, so keep gameplay checks range-based.`,ko:`"target"에 ModelInstance3D 노드 경로, "bone"에 본 이름을 줍니다("RightHand"는 Mixamo 표기도 자동 매칭). 자식들이 살아있는 애니메이션 트랜스폼을 물려받고, 이 노드의 position/rotation은 본 기준 오프셋이 됩니다. 순수 시각 기능 — 헤드리스에서는 prop 위치에 머무니 게임 판정은 거리 기반으로 유지하세요.`}),Q(`Trail3D`,{en:`A fading world-space ribbon behind the parent — wingtip trails, sword arcs, tyre streaks.`,ko:`부모 뒤로 남는 페이드아웃 월드 리본 — 날개끝 궤적, 검격 궤적, 타이어 자국.`},{en:"Child of the moving node. Records the world position over `seconds` and renders a camera-facing strip that tapers and fades to the tail. width (m), color, opacity, additive for glowing energy trails, minDistance filters jitter. emitting: false stops laying new ribbon while the old tail fades out.",ko:`움직이는 노드의 자식으로 두세요. seconds 동안의 월드 위치를 기록해 꼬리로 갈수록 가늘어지고 투명해지는 카메라 지향 스트립을 그립니다. width(m), color, opacity, 빛나는 에너지 궤적에는 additive, minDistance로 떨림을 걸러냅니다. emitting: false면 새 리본만 멈추고 기존 꼬리는 자연스럽게 사라집니다.`}),Q(`Joint3D`,{en:`A physics joint linking its parent body to a target body — weld, ball joint, rope, spring.`,ko:`부모 바디와 대상 바디를 잇는 물리 조인트 — 용접, 볼 조인트, 로프, 스프링.`},{en:`Child of body A; "target" is a node path to body B. type: fixed (rigid weld) / spherical (ball joint at the anchors) / rope (caps anchor distance at length m; 0 = measured at creation) / spring (pulls toward length with stiffness/damping). anchor/targetAnchor are LOCAL meter offsets.`,ko:`바디 A의 자식으로 두고 "target"에 바디 B의 노드 경로를 줍니다. type: fixed(강체 용접) / spherical(앵커 볼 조인트) / rope(앵커 간 거리를 length m로 제한, 0이면 생성 시 실측) / spring(stiffness/damping으로 length를 향해 당김). anchor/targetAnchor는 로컬 미터 오프셋.`})]},{id:`network`,label:{en:`Network`,ko:`네트워크`},intro:{en:`Multiplayer is transport-agnostic: the engine speaks one NetworkTransport interface (built-in offline Loopback + an @agent8/gameserver adapter). The scene declares replication; one owner node per player broadcasts its sync keys.`,ko:`멀티플레이어는 트랜스포트 불가지론입니다 — 엔진은 NetworkTransport 인터페이스 하나만 사용합니다(내장 오프라인 Loopback + @agent8/gameserver 어댑터). 복제는 씬이 선언하며, 플레이어당 하나의 owner 노드가 sync 키를 송출합니다.`},nodes:[Q(`NetworkSpawner`,{en:`Spawns a registered scene per remote player/entity.`,ko:`원격 플레이어/엔티티마다 등록된 씬을 생성.`},{en:`source "users" mirrors every OTHER account in the room (self skipped); "collection:<id>" mirrors a room collection. Replicated sync patches apply to each instance; position interpolates. Emits spawned/despawned.`,ko:`source "users"는 방의 다른 모든 계정을 미러링하고(자신 제외) "collection:<id>"는 방 컬렉션을 미러링합니다. 복제 sync 패치가 인스턴스에 적용되고 position은 보간됩니다. spawned/despawned를 발산합니다.`})]}],bR=`overview`,xR=null;function SR(){document.querySelector(`#docs`)?.removeAttribute(`hidden`),TR()}function CR(){document.querySelector(`#docs`)?.setAttribute(`hidden`,``)}function wR(){let e=document.querySelector(`#docs`);e&&(e.addEventListener(`pointerdown`,t=>{t.target===e&&CR()}),document.querySelector(`#docs-close`)?.addEventListener(`click`,CR))}function TR(){let e=document.querySelector(`#docs-tabs`),t=document.querySelector(`#docs-body`);if(!e||!t)return;e.textContent=``;let n=(t,n)=>{let r=document.createElement(`button`);r.type=`button`,r.className=`docs-tab${bR===t?` active`:``}`,r.textContent=n,r.addEventListener(`click`,()=>{bR=t,xR=null,TR()}),e.appendChild(r)};n(`overview`,jL({en:`Overview`,ko:`개요`}));for(let e of yR)n(e.id,jL(e.label));if(t.textContent=``,bR===`overview`){ER(t);return}let r=yR.find(e=>e.id===bR);r&&DR(t,r)}function ER(e){let t=document.createElement(`h2`);t.textContent=jL(vR.title),e.appendChild(t);for(let t of vR.sections){let n=document.createElement(`h3`);n.textContent=jL(t.heading);let r=document.createElement(`p`);r.textContent=jL(t.text),e.append(n,r)}}function DR(e,t){let n=document.createElement(`p`);n.className=`docs-intro`,n.textContent=jL(t.intro),e.appendChild(n);for(let n of t.nodes){let t=document.createElement(`div`);t.className=`docs-node${xR===n.type?` open`:``}`;let r=document.createElement(`button`);r.type=`button`,r.className=`docs-node-head`;let i=document.createElement(`span`);i.className=`tree-icon`,i.appendChild(PL(n.type));let a=document.createElement(`strong`);a.textContent=n.type;let o=document.createElement(`span`);if(o.className=`docs-summary`,o.textContent=jL(n.summary),r.append(i,a,o),r.addEventListener(`click`,()=>{xR=xR===n.type?null:n.type,TR()}),t.appendChild(r),xR===n.type){let e=document.createElement(`div`);e.className=`docs-detail`;for(let t of n.body){let n=document.createElement(`p`);n.textContent=jL(t),e.appendChild(n)}e.appendChild(OR(n.type)),t.appendChild(e)}e.appendChild(t)}}function OR(e){let t=document.createElement(`table`);t.className=`docs-props`;let n=document.createElement(`tr`);for(let e of[jL({en:`prop`,ko:`prop`}),jL({en:`default`,ko:`기본값`})]){let t=document.createElement(`th`);t.textContent=e,n.appendChild(t)}t.appendChild(n);try{let n=ct(e);for(let[e,r]of Object.entries(n)){let n=document.createElement(`tr`),i=document.createElement(`td`);i.className=`mono`,i.textContent=e;let a=document.createElement(`td`);a.className=`mono`,a.textContent=JSON.stringify(r.default),n.append(i,a),t.appendChild(n)}}catch{}return t}function $(e){return Math.round(e*100)/100}function kR(e,t,n,r,i){return{name:e,type:`StaticBody3D`,props:{collider:{shape:`box`,size:t},position:n,...i?{rotation:i}:{}},children:[{name:`Skin`,type:`MeshInstance3D`,props:{mesh:`box`,size:t,...r}}]}}function AR(e,t,n,r,i,a){let o=$(r.range(i[0],i[1])),s=$(r.range(.5,.7));return{name:`Rock${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[t,$(o*s*.6),n],rotation:[0,r.int(0,359),0],scale:[o,$(o*s),$(o*r.range(.8,1.1))],material:{color:a??jR(r),roughness:1},castShadow:!0}}}function jR(e){let t=Math.round(e.range(110,160)).toString(16).padStart(2,`0`);return`#${t}${t}${t}`}function MR(e){return[{name:`Sun`,type:`DirectionalLight3D`,props:{position:[$(e*.8),$(e*1.5),$(e*.6)],intensity:1,castShadow:!0,shadowArea:$(e*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[$(-e*.8),$(e*.8),$(-e*.6)],intensity:.4,color:`#b9d4ff`}}]}function NR(e,t){return e===void 0?t:typeof e==`number`?[e,e]:e}function PR(e,t,n){return Math.min(Math.max(e,t),n)}var FR=[`boxes`,`ruins`,`garden`],IR=.5,LR=.1,RR=2,zR={boxes:{floor:`#3f3f3f`,wall:`#55504a`,obstacles:[`#b0413e`,`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#878787`]},ruins:{floor:`#7d766b`,wall:`#8a8378`,obstacles:[`#8a8378`,`#979085`,`#a39a8d`,`#7b746a`]},garden:{floor:`#4d7c3a`,wall:`#2f6b2f`,obstacles:[`#2f6b2f`,`#3a7a38`,`#356e33`]}};function BR(e){let{seed:t,width:n=30,depth:r=30,wallHeight:i=3,obstacles:a=8,theme:o=`boxes`}=e;if(!FR.includes(o))throw new L(`BAD_FORMAT`,`generateArena theme must be one of [${FR.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...FR]});let s=zR[o],c=new Ee(t),l=[kR(`Floor`,[n,LR,r],[0,-.1/2,0],{material:{color:s.floor,roughness:1},receiveShadow:!0})],u=i/2,d=[n+IR*2,i,IR],f=[IR,i,r],p={material:{color:s.wall,roughness:.9},receiveShadow:!0};l.push(kR(`Wall1`,d,[0,u,-(r+IR)/2],p),kR(`Wall2`,d,[0,u,(r+IR)/2],p),kR(`Wall3`,f,[-(n+IR)/2,u,0],p),kR(`Wall4`,f,[(n+IR)/2,u,0],p)),o===`ruins`?l.push(...HR(c,s,n,r,i,a)):l.push(...VR(c,s,n,r,i,a,o)),o===`garden`&&l.push(...UR(c,n,r));let m=Math.max(n,r);return l.push({name:`Sun`,type:`DirectionalLight3D`,props:{position:[$(m*.8),$(m*1.5),$(m*.6)],intensity:1,castShadow:!0,shadowArea:$(m*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[$(-m*.8),$(m*.8),$(-m*.6)],intensity:.4,color:`#b9d4ff`}},{name:`Lamp`,type:`OmniLight3D`,props:{position:[0,$(i+2),0],intensity:.5,color:`#fff3d6`,range:$(m)}}),{name:`Arena`,type:`Node3D`,children:l}}function VR(e,t,n,r,i,a,o){let s=[],c=o===`garden`?Math.min(n,r)*.16:0;for(let o=1;o<=a;o++){let a=[$(e.range(.8,2.6)),$(e.range(.8,Math.max(1.2,i*.8))),$(e.range(.8,2.6))],l=$(e.range(-(n/2-RR),n/2-RR)),u=$(e.range(-(r/2-RR),r/2-RR));if(c>0&&Math.hypot(l,u)<c+1.5){let t=Math.max(Math.hypot(l,u),.001);l=$(l/t*(c+1.5+e.range(0,2))),u=$(u/t*(c+1.5+e.range(0,2)))}let d=e.int(0,359);s.push(kR(`Obstacle${o}`,a,[l,$(a[1]/2),u],{material:{color:e.pick(t.obstacles),roughness:.8},castShadow:!0},[0,d,0]))}return s}function HR(e,t,n,r,i,a){let o=[];if(a<=0)return o;let s=Math.max(1,Math.round(Math.sqrt(a/2))),c=Math.ceil(a/s),l=n-RR*2,u=r-RR*2,d=0;for(let n=0;n<s&&d<a;n++){let r=$(s===1?0:-u/2+n/(s-1)*u);for(let n=0;n<c&&d<a;n++){d++;let a=$((c===1?0:-l/2+n/(c-1)*l)+e.range(-.4,.4)),s=$(e.next()>.35?e.range(i*.7,i*1.2):e.range(.4,.9)),u=$(e.range(.8,1.2));o.push(kR(`Obstacle${d}`,[u,s,u],[a,$(s/2),$(r+e.range(-.4,.4))],{material:{color:e.pick(t.obstacles),roughness:.95},castShadow:!0},[0,e.int(-8,8),0]))}}return o}function UR(e,t,n){let r=[],i=Math.min(t,n)*.16,a=r=>{let a=Math.min(t,n)/2-r/2-1,o=$(e.range(-a,a)),s=$(e.range(-a,a)),c=Math.max(Math.hypot(o,s),.001);return c<i+r/2&&(o=$(o/c*(i+r/2+.5)),s=$(s/c*(i+r/2+.5))),[o,s]};for(let i=1;i<=3;i++){let o=$(Math.min(t,n)*e.range(.18,.26)),[s,c]=a(o);r.push({name:`Grass${i}`,type:`Foliage3D`,props:{kind:`grass`,area:[o,o],density:10,seed:e.int(1,1e9),position:[s,0,c]}})}for(let i=1;i<=2;i++){let o=$(Math.min(t,n)*e.range(.12,.18)),[s,c]=a(o);r.push({name:`FlowerBed${i}`,type:`Flowers3D`,props:{density:`lush`,clustering:.3,area:[o,o],seed:e.int(1,1e9),position:[s,0,c]}})}return r.push({name:`Pool`,type:`Water3D`,props:{size:[$(i*2),$(i*2)],position:[0,.3,0],waveHeight:.04}}),r}var WR=32,GR=[4,8],KR=`#332f3a`,qR=`#6b6357`;function JR(e){let{seed:t,rooms:n=5}=e,[r,i]=NR(e.size,[960,720]),a=Math.max(8,Math.floor(r/WR)),o=Math.max(8,Math.floor(i/WR)),s=new Ee(t),c=[];for(let e=0;e<n*12&&c.length<n;e++){let e=s.int(GR[0],GR[1]),t=s.int(GR[0],GR[1]),n={x:s.int(1,Math.max(1,a-e-1)),y:s.int(1,Math.max(1,o-t-1)),w:e,h:t};c.some(e=>YR(e,n,1))||c.push(n)}let l=new Set,u=e=>{for(let t=e.y;t<e.y+e.h;t++)for(let n=e.x;n<e.x+e.w;n++)l.add(`${n},${t}`)};for(let e of c)u(e);let d=[];for(let e=1;e<c.length;e++){let[t,n]=XR(c[e-1]),[r,i]=XR(c[e]),a={x:Math.min(t,r),y:n,w:Math.abs(t-r)+1,h:1},o={x:r,y:Math.min(n,i),w:1,h:Math.abs(n-i)+1};for(let[t,n]of[[`H`,a],[`V`,o]])u(n),(n.w>1||n.h>1)&&d.push({name:`Corridor${e}${t}`,rect:n})}let f=new Set;for(let e of l){let[t,n]=e.split(`,`).map(Number);for(let e=-1;e<=1;e++)for(let r=-1;r<=1;r++){let i=`${t+r},${n+e}`;l.has(i)||f.add(i)}}let p=-(a*WR)/2,m=-(o*WR)/2,h=(e,t,n)=>({name:e,type:`ColorRect2D`,props:{position:[p+(t.x+t.w/2)*WR,m+(t.y+t.h/2)*WR],size:[t.w*WR,t.h*WR],color:n}}),g=c.map((e,t)=>h(`Room${t+1}`,e,KR));for(let e of d)g.push(h(e.name,e.rect,KR));let _=0;for(let e=-1;e<=o;e++){let t=-1;for(;t<=a;){if(!f.has(`${t},${e}`)){t++;continue}let n=1;for(;t+n<=a&&f.has(`${t+n},${e}`);)n++;_++;let r=[n*WR,WR];g.push({name:`Wall${_}`,type:`StaticBody2D`,props:{position:[p+(t+n/2)*WR,m+(e+.5)*WR],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:qR}}]}),t+=n}}return{name:`Dungeon`,type:`Node2D`,children:g}}function YR(e,t,n){return e.x-n<t.x+t.w&&e.x+e.w+n>t.x&&e.y-n<t.y+t.h&&e.y+e.h+n>t.y}function XR(e){return[Math.floor(e.x+e.w/2),Math.floor(e.y+e.h/2)]}var ZR=[[0,-1],[1,0],[0,1],[-1,0]];function QR(e,t,n){let r=2*t+1,i=2*n+1,a=Array.from({length:i},()=>Array(r).fill(!1)),o=(e,t)=>{a[t][e]=!0};o(1,1);let s=new Set([`0,0`]),c=[[0,0]];for(;c.length>0;){let[r,i]=c[c.length-1],a=[];for(let[e,o]of ZR){let c=r+e,l=i+o;c>=0&&c<t&&l>=0&&l<n&&!s.has(`${c},${l}`)&&a.push([c,l])}if(a.length===0){c.pop();continue}let[l,u]=e.pick(a);s.add(`${l},${u}`),o(2*l+1,2*u+1),o(r+l+1,i+u+1),c.push([l,u])}return o(0,1),o(2*t,2*n-1),{cols:t,rows:n,cells:a}}var $R=[`stone`,`hedge`,`canyon`],ez=.1,tz=`https://agent8-games.verse8.io/assets/3D/default/textures/wall`,nz=`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,rz={stone:{wall:{color:`#e8e2d8`,map:`${tz}/blocks.png`,normalMap:`${tz}/blocks_normal.png`,tile:2,roughness:.95},floor:{color:`#99938a`,map:`${nz}/stone.png`,normalMap:`${nz}/stone_normal.png`,tile:3,roughness:1},cap:`#6b5848`,pillar:`#cfc8bb`,path:`#665f55`,sun:{color:`#c9d6ea`,intensity:.75,height:.5},fill:`#9fb4cc`,mood:{sky:{elevationDeg:10,azimuthDeg:150,turbidity:16,rayleigh:3.2},fog:{near:.5,far:3.5,color:`#86909c`},exposure:.82,ambient:{color:`#c9d4e2`,intensity:.12}}},hedge:{wall:{color:`#55a83e`,map:`${nz}/grass.png`,normalMap:`${nz}/grass_normal.png`,tile:1.4,roughness:1},floor:{color:`#86b06d`,map:`${nz}/grass.png`,normalMap:`${nz}/grass_normal.png`,tile:3,roughness:1},pillar:`#3d7531`,path:`#7d6845`,sun:{color:`#e9eee6`,intensity:.7,height:1},fill:`#b9c8b4`,mood:{sky:{elevationDeg:35,azimuthDeg:150,turbidity:18,rayleigh:4.2},fog:{near:.8,far:5,color:`#aab8a6`},exposure:.88,ambient:{color:`#dde5d8`,intensity:.15}}},canyon:{wall:{color:`#f0b070`,map:`${nz}/stone.png`,normalMap:`${nz}/stone_normal.png`,tile:2.4,roughness:1},floor:{color:`#e3c193`,map:`${nz}/sand.png`,normalMap:`${nz}/sand_normal.png`,tile:3.5,roughness:1},pillar:`#d8a868`,path:`#a98a58`,sun:{color:`#ffb572`,intensity:1.15,height:.35},fill:`#caa37e`,mood:{sky:{elevationDeg:9,azimuthDeg:230,turbidity:9,rayleigh:3.5},fog:{near:.7,far:4.5,color:`#c79c6e`},exposure:.92,ambient:{color:`#ffdcb6`,intensity:.13}}}};function iz(e,t,n){return{color:e.color,roughness:e.roughness,map:e.map,...e.normalMap?{normalMap:e.normalMap}:{},repeat:[$(t/e.tile),$(n/e.tile)]}}var az=10;function oz(e){let{seed:t,width:n=8,depth:r=8,cellSize:i=2,wallHeight:a=2.5,theme:o=`stone`}=e;if(!$R.includes(o))throw new L(`BAD_FORMAT`,`generateMaze theme must be one of [${$R.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...$R]});let s=rz[o],c=new Ee(t),l=QR(c,n,r),u=2*n+1,d=2*r+1,f=$(u*i),p=$(d*i),m=(e,t)=>[$((e+.5)*i-f/2),$((t+.5)*i-p/2)],h=[kR(`Floor`,[f,ez,p],[0,-.1/2,0],{material:iz(s.floor,f,p),receiveShadow:!0})],g=[],_=0;for(let e=0;e<d;e++){let t=0;for(;t<u;){if(l.cells[e]?.[t]){t++;continue}let n=1;for(;t+n<u&&!l.cells[e]?.[t+n];)n++;g.push({gx:t,gz:e,run:n}),_++;let r=$(n*i);h.push(kR(`Wall${_}`,[r,a,i],[$((t+n/2)*i-f/2),$(a/2),$((e+.5)*i-p/2)],{material:iz(s.wall,r,a),castShadow:!0,receiveShadow:!0})),t+=n}}return s.cap&&h.push(...sz(g,i,a,f,p,s.cap)),h.push(...cz(c,l,i,a,m,s)),o===`hedge`?(h.push(...fz(c,g,i,a,m)),h.push(...pz(c,l,i,m,n,r))):o===`canyon`&&h.push(...mz(c,g,i,a,m)),h.push(...uz(l,i,a,m,s)),h.push(...MR(Math.max(f,p)).map((e,t)=>{if(t!==0)return{...e,props:{...e.props,color:s.fill}};let n=e.props?.position;return{...e,props:{...e.props,color:s.sun.color,intensity:s.sun.intensity,position:[n[0]??0,$((n[1]??0)*s.sun.height),n[2]??0]}}})),{name:`Maze`,type:`Node3D`,children:h}}function sz(e,t,n,r,i,a){return e.map((e,o)=>({name:`Cap${o+1}`,type:`MeshInstance3D`,props:{mesh:`box`,size:[$(e.run*t+.16),.12,$(t+.16)],position:[$((e.gx+e.run/2)*t-r/2),$(n+.06),$((e.gz+.5)*t-i/2)],material:{color:a,roughness:1},castShadow:!0,receiveShadow:!0}}))}function cz(e,t,n,r,i,a){let o=[],s=(e,n)=>t.cells[n]?.[e]===!1;for(let e=2;e<t.cells.length-1;e+=2)for(let n=2;n<(t.cells[e]?.length??0)-1;n+=2)s(n,e)&&Number(s(n-1,e))+Number(s(n+1,e))+Number(s(n,e-1))+Number(s(n,e+1))>=3&&o.push([n,e]);let c=Math.min(az,o.length),l=[],u=new Set,d=$(n*1.2),f=$(r*1.12);for(let t=1;t<=c;t++){let n=e.int(0,o.length-1);for(;u.has(n);)n=(n+1)%o.length;u.add(n);let[r,s]=o[n],[c,p]=i(r,s);l.push(lz(`Pillar${t}`,c,p,d,f,a))}return l}function lz(e,t,n,r,i,a){return{name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[r,i,r],position:[t,$(i/2),n],material:{...iz(a.wall,r,i),color:a.pillar},castShadow:!0,receiveShadow:!0}}}function uz(e,t,n,r,i){let a=2*e.cols,o=2*e.rows-1,s=$(t*1.1),c=$(n*1.25),l=[[0,0],[0,2],[a,o-1],[a,o+1]].map(([e,t],n)=>{let[a,o]=r(e,t);return lz(`Gate${n+1}`,a,o,s,c,i)});for(let[e,n,s]of[[`EntrancePath`,0,1],[`ExitPath`,a,o]]){let[a,o]=r(n,s);l.push({name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[$(t*.96),.04,$(t*.96)],position:[a,.02,o],material:{...iz(i.floor,t,t),color:i.path},receiveShadow:!0}})}return l}var dz=10;function fz(e,t,n,r,i){return[...t].filter(e=>e.run>=2).sort((e,t)=>t.run-e.run||e.gz-t.gz||e.gx-t.gx).slice(0,dz).map((t,a)=>{let[,o]=i(t.gx,t.gz),[s]=i(t.gx,t.gz),[c]=i(t.gx+t.run-1,t.gz);return{name:`HedgeTop${a+1}`,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,area:[$(t.run*n*.92),$(n*.7)],density:14,height:.35,sway:.4,colorA:`#2f5e26`,colorB:`#5d8a3c`,seed:e.int(1,1e9),position:[$((s+c)/2),r,o]}}})}function pz(e,t,n,r,i,a){let o=[];for(let e=0;e<t.cells.length;e++)for(let n=0;n<(t.cells[e]?.length??0);n++)t.cells[e]?.[n]&&o.push([n,e]);let s=Math.min(o.length,Math.max(3,Math.floor(i*a/12))),c=[],l=new Set;for(let t=1;t<=s&&l.size<o.length;t++){let i=e.int(0,o.length-1);for(;l.has(i);)i=(i+1)%o.length;l.add(i);let[a,s]=o[i],[u,d]=r(a,s),f=$(n*.8);c.push({name:`Grass${t}`,type:`Foliage3D`,props:{kind:`grass`,area:[f,f],density:8,seed:e.int(1,1e9),position:[u,0,d]}})}return c}function mz(e,t,n,r,i){let a=[];if(t.length===0)return a;let o=Math.min(8,t.length);for(let s=1;s<=o;s++){let o=e.pick(t),[c,l]=i(o.gx+e.int(0,o.run-1),o.gz),u=AR(s,c,l,e,[.3,$(n*.35)],`#8f7355`),d=u.props?.position;d[1]=$(d[1]+r),a.push(u)}return a}var hz=`#23222b`,gz=`#5f6672`;function _z(e){let{seed:t,cols:n=10,rows:r=8,cellPx:i=64}=e,a=QR(new Ee(t),n,r),o=2*n+1,s=2*r+1,c=$(o*i),l=$(s*i),u=[{name:`Floor`,type:`ColorRect2D`,props:{size:[c,l],color:hz}}],d=0;for(let e=0;e<s;e++){let t=0;for(;t<o;){if(a.cells[e]?.[t]){t++;continue}let n=1;for(;t+n<o&&!a.cells[e]?.[t+n];)n++;d++;let r=[$(n*i),i];u.push({name:`Wall${d}`,type:`StaticBody2D`,props:{position:[$((t+n/2)*i-c/2),$((e+.5)*i-l/2)],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:gz}}]}),t+=n}}return{name:`Maze2D`,type:`Node2D`,children:u}}var vz=16,yz=[`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#b0413e`];function bz(e){let{seed:t,count:n=10,width:r=[80,160],gapX:i=[40,120],stepY:a=[-80,40],start:o=[0,300]}=e,s=new Ee(t),c=[],l=$(s.range(r[0],r[1])),u=o[0],d=o[1];for(let e=1;e<=n&&(c.push(xz(e,u,d,l,s.pick(yz))),e!==n);e++){let e=$(s.range(r[0],r[1])),t=$(s.range(i[0],i[1]));u=$(u+l/2+t+e/2),d=$(d+s.range(a[0],a[1])),l=e}return{name:`Platforms`,type:`Node2D`,children:c}}function xz(e,t,n,r,i){return{name:`Platform${e}`,type:`StaticBody2D`,props:{position:[t,n],collider:{shape:`rect`,size:[r,vz]}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:[r,vz],color:i}}]}}var Sz=[3,5],Cz=3,wz={color:`#ffffff`,roughness:1,emissive:`#ffffff`,emissiveIntensity:.25};function Tz(e){let{seed:t,count:n=8,altitude:r=18}=e,[i,a]=NR(e.area,[60,60]),o=new Ee(t),s=[];for(let e=1;e<=n;e++){let t=o.int(Sz[0],Sz[1]),n=[];for(let e=1;e<=t;e++){let r=$(o.range(1,2.2));n.push({name:`Puff${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[$((e-(t+1)/2)*o.range(1,1.6)),$(o.range(-.3,.3)),$(o.range(-.6,.6))],scale:[$(r*o.range(1.1,1.6)),$(r*.55),r],material:wz}})}s.push({name:`Cloud${e}`,type:`Node3D`,props:{position:[$(o.range(-i/2,i/2)),$(r+o.range(-3,Cz)),$(o.range(-a/2,a/2))]},children:n})}return{name:`Clouds`,type:`Node3D`,children:s}}var Ez=[`island`,`alpine`,`plains`,`desert`,`meadow`,`forest`,`savanna`,`snow`,`wetland`,`volcanic`],Dz=128,Oz=20,kz=.8,Az=.12,jz={island:{splat:`island`,maxHeight:4.5,sun:`#fff4d6`,fill:`#b9d4ff`,sky:{elevationDeg:38,azimuthDeg:145,turbidity:2.6,rayleigh:1.1},fog:{near:1,far:4},iblIntensity:.72},alpine:{splat:`alpine`,maxHeight:8,roughness:.65,detail:5,sun:`#f4f7ff`,fill:`#c9d8f2`,sky:{elevationDeg:45,azimuthDeg:35,turbidity:1.4,rayleigh:1.3},fog:{near:1.8,far:6.5},sunIntensity:1.1,exposure:.92,iblIntensity:.72},plains:{splat:`plains`,maxHeight:4,sun:`#fff2cf`,fill:`#bcd3ef`,sky:{elevationDeg:36,azimuthDeg:140,turbidity:2.4,rayleigh:1},fog:{near:.9,far:4},iblIntensity:.58},desert:{splat:`desert`,maxHeight:5,sun:`#ffe3b3`,fill:`#e8c9a6`,sky:{elevationDeg:42,azimuthDeg:160,turbidity:7,rayleigh:.6},fog:{near:.8,far:3.2,color:`#e8d3ae`},sunIntensity:1.35,iblIntensity:.75},meadow:{splat:`grassland`,maxHeight:1.2,sun:`#fff8e2`,fill:`#bfe0c9`,sky:{elevationDeg:55,azimuthDeg:125,turbidity:2.4,rayleigh:.95},fog:{near:1,far:4.4},sunIntensity:2.6,exposure:1.12,iblIntensity:.62},forest:{splat:`forest`,maxHeight:2.5,sun:`#ffdca8`,fill:`#a9c8b4`,sky:{elevationDeg:29,azimuthDeg:120,turbidity:5.5,rayleigh:1},fog:{near:.22,far:1.8,color:`#9fb494`},sunIntensity:2.6,ambient:.26,iblIntensity:.55},savanna:{splat:`savanna`,maxHeight:3,sun:`#ffdca0`,fill:`#e6d2a4`,sky:{elevationDeg:34,azimuthDeg:150,turbidity:5,rayleigh:.7},fog:{near:1,far:4.2,color:`#e3cf9f`},sunIntensity:2,exposure:1.05,iblIntensity:.6},snow:{splat:`snow`,maxHeight:2.2,sun:`#dfe9ff`,fill:`#c2d2f0`,sky:{elevationDeg:22,azimuthDeg:35,turbidity:1.6,rayleigh:1.6},fog:{near:1.2,far:5,color:`#dbe6f5`},sunIntensity:1,exposure:.9,iblIntensity:.72},wetland:{splat:`wetland`,maxHeight:1.4,sun:`#d6ddc8`,fill:`#9fb29a`,sky:{elevationDeg:24,azimuthDeg:115,turbidity:9,rayleigh:1.1},fog:{near:.5,far:2,color:`#92a288`},sunIntensity:1.5,exposure:.94,ambient:.24,iblIntensity:.66},volcanic:{splat:`volcanic`,maxHeight:4,roughness:.7,sun:`#ff8a4a`,fill:`#7a4a3a`,sky:{elevationDeg:14,azimuthDeg:135,turbidity:10,rayleigh:.3},fog:{near:.18,far:1.4,color:`#2a211c`},sunIntensity:1.7,exposure:.86,ambient:.22,iblIntensity:.5}};function Mz(e){let{seed:t,theme:n=`island`,size:r=200,water:i=!1}=e,a=jz[n];if(!a)throw new L(`BAD_FORMAT`,`generateTerrain theme must be one of [${Ez.join(`, `)}], got '${n}'.`,{prop:`theme`,validOptions:[...Ez]});let o=Math.max(2,Math.round(e.resolution??Dz)),s=e.maxHeight||a.maxHeight,c=new Ee(t),l=n===`island`,u=e=>VD({width:r,depth:r,segsX:o,segsZ:o,maxHeight:e,seed:t,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail},islandEdge:l}),d=u(s);if(l)for(let e=0;e<3;e++){let e=Pz(d)-Oz,t=d.maxHeight-d.minHeight,n=d.minHeight+Az*t;if(e+kz<=n)break;let r=Oz-kz,i=Pz(d)-d.minHeight-Az*t;s=$(s*Math.min(r/i*.95,.9)),d=u(s)}let f=[{name:`Ground`,type:`StaticBody3D`,props:{collider:{shape:`heightfield`}},children:[{name:`Surface`,type:`Terrain3D`,props:{size:[r,r],maxHeight:s,seed:t,theme:a.splat,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail},...o===Dz?{}:{resolution:o}}}]}],p=n===`wetland`;if(l)f.push({name:`Sea`,type:`Water3D`,props:{size:[r*8,r*8],position:[0,Nz(d),0],opacity:1}});else if(p){let e=d.maxHeight-d.minHeight||1,t=$(d.minHeight+.22*e);f.push({name:`Swamp`,type:`Water3D`,props:{size:[r,r],position:[0,t,0],waveHeight:.02,quality:`simple`,color:`#3a4a30`,opacity:.95}})}else if(i){let e=$(d.minHeight+.1*(d.maxHeight-d.minHeight));f.push({name:`Lake`,type:`Water3D`,props:{size:[r,r],position:[0,e,0],waveHeight:.04}})}return f.push(...Xz(n,c,d,r)),l&&f.push(Tz({seed:c.int(1,1e9),count:6,area:r,altitude:Math.round(d.maxHeight+12)})),f.push(...MR(r).map((e,t)=>Zz(e,t===0?a.sun:a.fill,t===0?a.sunIntensity??1.7:void 0))),{name:`Terrain`,type:`Node3D`,children:f}}function Nz(e){let t=Pz(e)-Oz,n=e.minHeight+Az*(e.maxHeight-e.minHeight);return $(Math.max(Math.min(t+kz,n),t+.55))}function Pz(e){let t=-1/0,n=e.width/2,r=e.depth/2,i=e.segsX;for(let a=0;a<=i;a++){let o=-n+a/i*e.width,s=-r+a/i*e.depth;t=Math.max(t,e.baseHeight(o,-r),e.baseHeight(o,r),e.baseHeight(-n,s),e.baseHeight(n,s))}return t}function Fz(e,t,n){let r=Math.min(t.width/2-n.margin,n.within??1/0),i=t.maxHeight-t.minHeight||1,a=[];for(let o=0;o<n.count*30&&a.length<n.count;o++){let o=$(e.range(-r,r)),s=$(e.range(-r,r));if(n.clearing&&Math.hypot(o,s)<n.clearing||n.within&&Math.hypot(o,s)>n.within)continue;let c=t.heightAt(o,s),l=(c-t.minHeight)/i;l<n.band[0]||l>n.band[1]||t.slopeAt(o,s)>n.maxSlope||a.push({x:o,z:s,y:c})}return a}var Iz=[{canopy:`#2f5d44`,trunk:`#6e4a32`},{canopy:`#356a4c`,trunk:`#71503a`},{canopy:`#2c5740`,trunk:`#5f4530`},{canopy:`#3a6b4a`,trunk:`#6a4c34`}],Lz=[{canopy:`#4a7c3f`,trunk:`#7a5a3a`},{canopy:`#56883c`,trunk:`#806044`},{canopy:`#7a9d3e`,trunk:`#9a9488`},{canopy:`#86a346`,trunk:`#a39c8e`},{canopy:`#b8862f`,trunk:`#7e5e38`},{canopy:`#a8702c`,trunk:`#74552f`}],Rz={canopy:`#9aa052`,trunk:`#8a6a44`},zz={canopy:`#39513f`,trunk:`#5a5650`};function Bz(e,t){return e===`conifer`?t.pick(Iz):e===`broadleaf`?t.pick(Lz):null}function Vz(e,t,n,r,i){let a=i?.height??[4.5,7],o=i?.sink??(i?.count===void 0?.05:.3),s={};i?.tier!==void 0&&(s.tier=i.tier),i?.count!==void 0&&i.area!==void 0&&(s.count=i.count,s.area=[i.area,i.area]);let c=Bz(r,n),l=i?.palette??c;return l&&(s.canopyColor=l.canopy,s.trunkColor=l.trunk),{name:e,type:`Tree3D`,props:{type:r,seed:n.int(1,1e9),height:$(n.range(a[0],a[1])),position:[t.x,$(t.y-o),t.z],...s}}}function Hz(e,t,n,r,i,a=0,o){return{name:e,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,area:[r,r],density:i,height:o?.height??.3,...o?.colors?{colorA:o.colors[0],colorB:o.colors[1]}:{},seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z],...a>0?{flowers:a}:{}}}}function Uz(e,t,n,r,i){return{name:e,type:`Foliage3D`,props:{kind:`reeds`,style:`simple`,area:[r,r],density:i,height:.9,colorA:`#2f4a26`,colorB:`#5a6f33`,seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z]}}}function Wz(e,t,n,r,i){return{name:e,type:`Flowers3D`,props:{density:i,area:[r,r],seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z]}}}function Gz(e,t,n,r){return e.map((e,i)=>{let a=AR(i+1,e.x,e.z,t,n,r?.(t)),o=a.props?.position;return o[1]=$(o[1]+e.y),a})}function Kz(e){let t=Math.round(e.range(104,128)),n=Math.round(t-e.range(10,18)),r=Math.round(t-e.range(20,30)),i=e=>e.toString(16).padStart(2,`0`);return`#${i(n)}${i(t)}${i(r)}`}function qz(e){let t=Math.round(e.range(196,224)),n=Math.min(255,t+Math.round(e.range(4,12))),r=e=>e.toString(16).padStart(2,`0`);return`#${r(t)}${r(t)}${r(n)}`}function Jz(e){let t=Math.round(e.range(34,56)),n=Math.min(255,t+Math.round(e.range(2,8))),r=e=>e.toString(16).padStart(2,`0`);return`#${r(n)}${r(t)}${r(t)}`}var Yz=[`#6f5b41`,`#7a644a`,`#665439`];function Xz(e,t,n,r){let i=[];switch(e){case`island`:{let e=Fz(t,n,{count:7,band:[.18,.6],maxSlope:.5,margin:26});i.push(...e.map((e,n)=>Vz(`Tree${n+1}`,e,t,`conifer`)));break}case`alpine`:{let e=Fz(t,n,{count:10,band:[.2,.5],maxSlope:.55,margin:6});i.push(...e.map((e,n)=>Vz(`Tree${n+1}`,e,t,`conifer`)));let r=Fz(t,n,{count:8,band:[.55,1],maxSlope:.9,margin:6});i.push(...Gz(r,t,[.6,1.8]));break}case`plains`:{let e=Fz(t,n,{count:8,band:[0,1],maxSlope:.4,margin:6});i.push(...e.map((e,n)=>Vz(`Tree${n+1}`,e,t,`broadleaf`)));let r=Fz(t,n,{count:6,band:[0,1],maxSlope:.5,margin:6});i.push(...Gz(r,t,[.4,1.2]));break}case`desert`:{let e=Fz(t,n,{count:6,band:[0,1],maxSlope:.45,margin:6});i.push(...e.map((e,n)=>Vz(`Tree${n+1}`,e,t,`dead`)));let r=Fz(t,n,{count:8,band:[0,1],maxSlope:.6,margin:6});i.push(...Gz(r,t,[.5,1.6]));break}case`meadow`:{let e=$(r*.09),a=Fz(t,n,{count:7,band:[0,1],maxSlope:.05,margin:e/2+8});i.push(...a.map((n,r)=>Hz(`Carpet${r+1}`,n,t,e,30)));let o=$(r*.07),s=Fz(t,n,{count:3,band:[0,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>Wz(`Flowers${n+1}`,e,t,o,`sparse`)));let c=Fz(t,n,{count:4,band:[0,1],maxSlope:.1,margin:12});i.push(...c.map((e,n)=>Vz(`Grove${n+1}`,e,t,`broadleaf`,{count:3,area:6})));let l=Fz(t,n,{count:6,band:[0,1],maxSlope:.2,margin:8});i.push(...Gz(l,t,[.3,.9]));break}case`forest`:{let e=$(r*.12),a=r/2-8,o=Sr(t.int(1,1e9)),s=(e,t,n)=>{let r=o(e/70,t/70);return r>.12?`conifer`:r<-.12?`broadleaf`:n%2==0?`conifer`:`broadleaf`},c=Fz(t,n,{count:40,band:[0,1],maxSlope:.18,margin:8,clearing:e+6}),l=c.map((e,t)=>s(e.x,e.z,t));i.push(...c.map((e,n)=>Vz(`Grove${n+1}`,e,t,l[n],{count:12,area:13,height:[5.5,8]}))),c.forEach((e,n)=>{n%3==0&&i.push(Vz(`Sapling${n+1}`,e,t,l[n],{count:4,area:19,height:[2.5,3.4],sink:.12}))});let u=Fz(t,n,{count:6,band:[0,1],maxSlope:.2,margin:12,clearing:e+4});i.push(...u.map((e,n)=>Vz(`Elder${n+1}`,e,t,s(e.x,e.z,n),{tier:`high`,height:[8.4,9.8]})));let d=Fz(t,n,{count:3,band:[0,1],maxSlope:.18,margin:10,clearing:e+6});i.push(...d.map((e,n)=>Vz(`Accent${n+1}`,e,t,`broadleaf`,{tier:`high`,count:3,area:7,height:[5.6,6.8]})));let f=Fz(t,n,{count:10,band:[0,1],maxSlope:.14,margin:9,clearing:e+2});i.push(...f.map((e,n)=>Vz(`Bush${n+1}`,e,t,`bush`,{count:4,area:10,height:[2.1,3.1],sink:.12})));let p=0;c.forEach((e,r)=>{if(r%3==2)return;let o=t.range(0,Math.PI*2),s=t.range(2,4.5),c=t.int(1,1e9),l=$(PR(e.x+Math.cos(o)*s,-a,a)),u=$(PR(e.z+Math.sin(o)*s,-a,a));n.slopeAt(l,u)>.09||(p++,i.push({name:`Fern${p}`,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,tuftStyle:`fern`,area:[8,8],density:9,height:.4,colorA:`#4a6b34`,colorB:`#82a258`,seed:c,position:[l,$(n.heightAt(l,u)+.02),u]}}))});let m=$(r*.08),h=Fz(t,n,{count:5,band:[0,1],maxSlope:.06,margin:m/2+8});i.push(...h.map((e,n)=>Hz(`Grass${n+1}`,e,t,m,20,0,{height:.24,colors:[`#4f7034`,`#85a154`]})));let g=u.length>0?t.int(3,5):0;for(let e=0;e<g;e++){let r=u[e%u.length],o=t.range(0,Math.PI*2),s=t.range(2.5,4.5),c=$(PR(r.x+Math.cos(o)*s,-a,a)),l=$(PR(r.z+Math.sin(o)*s,-a,a));i.push({name:`Log${e+1}`,type:`Tree3D`,props:{type:`dead`,seed:t.int(1,1e9),height:$(t.range(4.2,5.6)),trunkColor:`#4a4236`,position:[c,$(n.heightAt(c,l)+.12),l],rotation:[0,t.int(0,359),$(t.range(81,97))]}})}Fz(t,n,{count:5,band:[0,1],maxSlope:.25,margin:9,clearing:e}).forEach((e,n)=>{let r=$(t.range(.16,.28)),a=$(t.range(.3,.55));i.push({name:`Stump${n+1}`,type:`MeshInstance3D`,props:{mesh:`cylinder`,size:[r,a,r],position:[e.x,$(e.y+a/2-.06),e.z],rotation:[0,t.int(0,359),0],material:{color:t.pick(Yz),roughness:1},castShadow:!0}})});let _=Fz(t,n,{count:8,band:[0,1],maxSlope:.2,margin:8});i.push(...Gz(_,t,[.3,1],Kz));let v=$(e*.75),y=Fz(t,n,{count:3,band:[0,1],maxSlope:.06,margin:8,within:e-$(v/Math.SQRT2)});i.push(...y.map((e,n)=>Hz(`Clearing${n+1}`,e,t,v,30,0,{colors:[`#5d8438`,`#a8bc60`]})));let b=$(e*.45),x=Fz(t,n,{count:2,band:[0,1],maxSlope:.06,margin:8,within:e-$(b/Math.SQRT2)});i.push(...x.map((e,n)=>Wz(`Flowers${n+1}`,e,t,b,`sparse`)));break}case`savanna`:{let e=Fz(t,n,{count:7,band:[0,.85],maxSlope:.35,margin:8});i.push(...e.map((e,n)=>Vz(`Tree${n+1}`,e,t,`broadleaf`,{height:[3.5,5],palette:Rz})));let a=$(r*.09),o=Fz(t,n,{count:6,band:[0,1],maxSlope:.05,margin:a/2+8});i.push(...o.map((e,n)=>Hz(`Carpet${n+1}`,e,t,a,26,0,{height:.34,colors:[`#9a8f43`,`#c9bd6a`]})));let s=Fz(t,n,{count:7,band:[0,1],maxSlope:.5,margin:8});i.push(...Gz(s,t,[.4,1.4]));let c=Fz(t,n,{count:4,band:[0,1],maxSlope:.2,margin:9});i.push(...c.map((e,n)=>Vz(`Scrub${n+1}`,e,t,`bush`,{count:3,area:8,height:[1.4,2.2]})));break}case`snow`:{let e=Fz(t,n,{count:8,band:[0,.9],maxSlope:.4,margin:8});i.push(...e.map((e,n)=>Vz(`Tree${n+1}`,e,t,`conifer`,{height:[4,6.5],palette:zz})));let r=Fz(t,n,{count:10,band:[0,1],maxSlope:.7,margin:8});i.push(...Gz(r,t,[.5,1.8],qz));break}case`wetland`:{let e=$(r*.08),a=Fz(t,n,{count:6,band:[0,.5],maxSlope:.06,margin:e/2+8});i.push(...a.map((n,r)=>Uz(`Reeds${r+1}`,n,t,e,4)));let o=$(r*.08),s=Fz(t,n,{count:4,band:[.2,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>Hz(`Moss${n+1}`,e,t,o,22,0,{height:.22,colors:[`#3a5a2c`,`#6f8a48`]})));let c=Fz(t,n,{count:6,band:[.25,1],maxSlope:.35,margin:9});i.push(...c.map((e,n)=>Vz(`Snag${n+1}`,e,t,`dead`,{height:[4,6]})));let l=Fz(t,n,{count:6,band:[.2,1],maxSlope:.2,margin:9});i.push(...l.map((e,n)=>Vz(`Bush${n+1}`,e,t,`bush`,{count:3,area:7,height:[1.6,2.6]})));let u=Fz(t,n,{count:5,band:[.2,1],maxSlope:.3,margin:8});i.push(...Gz(u,t,[.3,1],Kz));break}case`volcanic`:{let e=Fz(t,n,{count:7,band:[0,1],maxSlope:.45,margin:8});i.push(...e.map((e,n)=>Vz(`Tree${n+1}`,e,t,`dead`,{height:[4,6.5]})));let r=Fz(t,n,{count:12,band:[0,1],maxSlope:.7,margin:8});i.push(...Gz(r,t,[.4,1.8],Jz)),Fz(t,n,{count:3,band:[0,.6],maxSlope:.18,margin:12}).forEach((e,n)=>{t.int(1,1e9),i.push({name:`Smoke${n+1}`,type:`Particles3D`,props:{preset:`smoke`,position:[e.x,$(e.y+.2),e.z],rate:8,maxParticles:64,colorStart:`#5a5048`,colorEnd:`#2a2422`,sizeStart:18,sizeEnd:44}}),i.push({name:`Embers${n+1}`,type:`Particles3D`,props:{position:[e.x,$(e.y+.1),e.z],rate:10,maxParticles:48,lifetime:[.8,1.8],speed:[12,34],directionDeg:-90,spreadDeg:40,gravity:[0,-18],sizeStart:4,sizeEnd:1,colorStart:`#ffce6a`,colorEnd:`#d83a14`,blend:`add`}})});break}}return i}function Zz(e,t,n){return{...e,props:{...e.props,color:t,...n===void 0?{}:{intensity:n}}}}var Qz={arena:{description:`FPS stage: floor, 4 perimeter walls, obstacles, lights — themes: boxes (crates), ruins (broken stone rows), garden (hedges, grass, pool)`,dimension:`3d`,params:{theme:{type:`string`,default:`boxes`,options:[...FR]},width:{type:`number`,default:30,min:4},depth:{type:`number`,default:30,min:4},wallHeight:{type:`number`,default:3,min:.5},obstacles:{type:`number`,default:8,min:0}}},terrain:{description:`Heightfield world: StaticBody3D{heightfield} + Terrain3D + theme dressing (trees, rocks, grass, sea/clouds on island, broad swamp water on wetland, smoke/ember emitters on volcanic; maxHeight 0 = theme default; water adds a lake to non-island themes)`,dimension:`3d`,params:{theme:{type:`string`,default:`island`,options:[...Ez]},size:{type:`number`,default:200,min:40,max:400},maxHeight:{type:`number`,default:0,min:0},water:{type:`boolean`,default:!1}}},maze:{description:`Recursive-backtracker 3D maze, west→east — themes: stone, hedge (green + grass), canyon (sandstone + rim rocks)`,dimension:`3d`,params:{theme:{type:`string`,default:`stone`,options:[...$R]},width:{type:`number`,default:8,min:2,max:40},depth:{type:`number`,default:8,min:2,max:40},cellSize:{type:`number`,default:2,min:.5},wallHeight:{type:`number`,default:2.5,min:.5}}},maze2d:{description:`The same maze algorithm as 2D ColorRect2D + StaticBody2D tiles`,dimension:`2d`,params:{cols:{type:`number`,default:10,min:2,max:40},rows:{type:`number`,default:8,min:2,max:40},cellPx:{type:`number`,default:64,min:8}}},dungeon2d:{description:`Roguelike rooms + L-corridors: floor rects, wall bodies (32px tiles)`,dimension:`2d`,params:{rooms:{type:`number`,default:5,min:1,max:20},size:{type:`number`,default:960,min:256}}},platforms2d:{description:`Left-to-right 2D platform course (tune ranges via the library)`,dimension:`2d`,params:{count:{type:`number`,default:10,min:1}}}},$z={arena:BR,terrain:Mz,maze:oz,maze2d:_z,dungeon2d:JR,platforms2d:bz};function eB(e,t){let n=$z[e];if(!n){let t=Object.keys($z);throw new L(`BAD_FORMAT`,`Unknown generator '${e}'. Valid: [${t.join(`, `)}] — the old meadow/forest/island/rocks/clouds generators became themes (e.g. terrain theme: 'meadow', arena theme: 'garden'); scatter is library-only (needs item templates).`,{validOptions:t})}return n(t)}function tB(e){return Object.entries(Qz).filter(([,t])=>t.dimension===e).map(([e,t])=>({name:e,meta:t}))}function nB(e,t){if(e.type===`boolean`)return t===!0||t===`true`;if(e.type===`number`){let n=typeof t==`boolean`?NaN:Number(t);return(t===``||!Number.isFinite(n))&&(n=e.default),e.min!==void 0&&(n=Math.max(e.min,n)),e.max!==void 0&&(n=Math.min(e.max,n)),n}let n=String(t);return e.options&&!e.options.includes(n)?e.default:n}function rB(){return Math.floor(Math.random()*1e6)}var iB=[],aB=new Map,oB=null;function sB(e){let t=document.querySelector(`#generate`);t&&(uB(e),t.removeAttribute(`hidden`))}function cB(){document.querySelector(`#generate`)?.setAttribute(`hidden`,``)}function lB(e){let t=document.querySelector(`#generate`);t&&(t.addEventListener(`pointerdown`,e=>{e.target===t&&cB()}),document.querySelector(`#generate-close`)?.addEventListener(`click`,cB),document.querySelector(`#generate-cancel`)?.addEventListener(`click`,cB),document.querySelector(`#generate-insert`)?.addEventListener(`click`,()=>dB(e)))}function uB(e){let t=document.querySelector(`#generate-body`),n=document.querySelector(`#generate-status`);if(!t)return;n&&(n.textContent=``),t.textContent=``;let r=e.working.dimension??`2d`;iB=tB(r);let i=document.createElement(`p`);i.className=`gen-hint`,i.textContent=jL({en:`Deterministic ${r.toUpperCase()} environment generators — the subtree inserts under the selected node (the root when nothing is selected). The same seed always generates the same level.`,ko:`결정적 ${r.toUpperCase()} 환경 생성기 — 생성된 서브트리는 선택한 노드 아래에(선택이 없으면 루트에) 들어갑니다. 같은 시드는 항상 같은 레벨을 만듭니다.`}),t.appendChild(i);let a=fB(jL({en:`generator`,ko:`생성기`})),o=document.createElement(`select`);o.id=`generate-name`;for(let{name:e}of iB){let t=document.createElement(`option`);t.value=e,t.textContent=e,o.appendChild(t)}a.appendChild(o),t.appendChild(a);let s=document.createElement(`p`);s.className=`gen-desc`,t.appendChild(s);let c=document.createElement(`div`);c.id=`generate-params`,t.appendChild(c);let l=fB(`seed`);oB=document.createElement(`input`),oB.type=`number`,oB.step=`1`,oB.value=String(rB());let u=document.createElement(`button`);u.type=`button`,u.className=`ghost`,u.textContent=`↻`,u.title=jL({en:`New random seed`,ko:`새 랜덤 시드`}),u.addEventListener(`click`,()=>{oB&&(oB.value=String(rB()))});let d=document.createElement(`div`);d.className=`gen-seed-row`,d.append(oB,u),l.appendChild(d),t.appendChild(l);let f=()=>{let e=iB.find(e=>e.name===o.value)??iB[0];if(e){s.textContent=e.meta.description,c.textContent=``,aB=new Map;for(let[t,n]of Object.entries(e.meta.params)){let e=fB(t),r;if(n.type===`boolean`)r=document.createElement(`input`),r.type=`checkbox`,r.checked=n.default===!0;else if(n.type===`string`&&n.options){r=document.createElement(`select`);for(let e of n.options){let t=document.createElement(`option`);t.value=e,t.textContent=e,r.appendChild(t)}r.value=String(n.default)}else r=document.createElement(`input`),r.type=n.type===`number`?`number`:`text`,n.type===`number`&&(r.step=`any`,n.min!==void 0&&(r.min=String(n.min)),n.max!==void 0&&(r.max=String(n.max))),r.value=String(n.default),(n.min!==void 0||n.max!==void 0)&&(r.title=`${n.min??``}–${n.max??``}`);aB.set(t,r),e.appendChild(r),c.appendChild(e)}}};o.addEventListener(`change`,f),f()}function dB(e){let t=document.querySelector(`#generate-status`),n=document.querySelector(`#generate-name`),r=iB.find(e=>e.name===n?.value);if(!r||!oB)return;let i={seed:nB({type:`number`,default:rB(),min:0},oB.value)};for(let[e,t]of aB){let n=r.meta.params[e];n&&(i[e]=nB(n,t.type===`checkbox`?t.checked:t.value))}let a;try{a=eB(r.name,i)}catch(e){t&&(t.textContent=e instanceof Error?e.message:String(e));return}let o=e.insertNode(a,e.selection??[]);if(o===null){t&&(t.textContent=jL({en:`Insert failed — see the error banner.`,ko:`삽입 실패 — 에러 배너를 확인하세요.`}));return}e.select(o),oB&&(oB.value=String(rB())),cB()}function fB(e){let t=document.createElement(`label`);t.className=`field`;let n=document.createElement(`span`);return n.textContent=e,t.appendChild(n),t}var pB={connections:{title:{en:`connections — wire a signal to a handler`,ko:`connections — 시그널을 핸들러에 연결`},body:{en:'A connection says "when THIS node emits THIS signal, call THIS method on THAT node" — declaratively, in the scene JSON, with no TypeScript. emits = leaving this node; receives = arriving at it. Paths resolve from the scene ROOT (`Player/Sword`, `.` for the root itself). A red target does not resolve and the game will refuse to load the scene. Handlers on a scripted node are free text: they live in your behavior, which the editor never loads.',ko:'연결은 "이 노드가 이 시그널을 보내면, 저 노드의 이 메서드를 호출한다"를 씬 JSON에 선언합니다 — TypeScript 없이. emits는 이 노드에서 나가는 것, receives는 들어오는 것입니다. 경로는 씬 루트 기준입니다(`Player/Sword`, 루트 자신은 `.`). 빨간 대상은 찾을 수 없다는 뜻이고, 게임은 그 씬을 열지 못합니다. 스크립트가 있는 노드의 핸들러는 자유 입력입니다 — 에디터가 읽지 않는 게임 코드에 있기 때문입니다.'}},groups:{title:{en:`groups — tag nodes for queries`,ko:`groups — 조회용 태그`},body:{en:`Free-form tags. Game code finds nodes with tree-wide queries like getNodesInGroup("coins"), and triggers can filter by group (e.g. only react to "player"). Type a name and press Enter.`,ko:`자유 형식 태그입니다. 게임 코드가 getNodesInGroup("coins")처럼 트리 전체에서 노드를 찾고, 트리거는 그룹으로 거릅니다(예: "player"에만 반응). 이름을 입력하고 Enter를 누르세요.`},example:`triggerEnter → if (other.isInGroup("player")) collect()`},script:{title:{en:`script — attach YOUR game logic`,ko:`script — 게임 로직 연결`},body:{en:`A Behavior is a TypeScript class living in YOUR game code, linked by name. The editor stores the link; the class itself must be registered in the game before loadScene. Props here are passed to the behavior instance.`,ko:`Behavior는 게임 코드에 있는 TypeScript 클래스이며 이름으로 연결됩니다. 에디터는 연결만 저장하고, 클래스 자체는 loadScene 전에 게임에서 등록되어야 합니다. 여기의 props가 비헤이비어 인스턴스로 전달됩니다.`},example:`registerBehavior('CoinCounter', CoinCounter) // in your main.ts`,copy:{label:`copy behavior boilerplate`,text:`import { Behavior, registerBehavior } from 'incanto';
|
|
8430
8430
|
|
|
8431
8431
|
export class MyBehavior extends Behavior {
|
|
8432
8432
|
static props = { speed: { default: 100 } };
|
|
@@ -10955,4 +10955,4 @@ body.playing #gameview-btn {
|
|
|
10955
10955
|
opacity: 0.4;
|
|
10956
10956
|
cursor: default;
|
|
10957
10957
|
}
|
|
10958
|
-
`,xU=new Map(yR.flatMap(e=>e.nodes.map(e=>[e.type,e.summary]))),SU=new Set,CU=null,wU=null,TU=null;function EU(e){wU=e}function DU(e){CU=e}function OU(e){TU=e}var kU=null,AU=null,jU=null;function MU(e){return e?e.includes(`Body`)||e.includes(`Area`)||e.includes(`Controller`)?`cat-body`:e===`NetworkSpawner`?`cat-net`:e.endsWith(`3D`)?`cat-3d`:e.endsWith(`2D`)||e===`Label`||e===`UILayer`?`cat-2d`:`cat-core`:`cat-core`}function NU(e,t){e.textContent=``;let n=document.createElement(`div`);n.className=`tree-row scene-row${t.selection===null&&t.selectedAsset===null&&t.selectedGroup===null&&!t.addingAsset&&!t.addingGroup?` selected`:``}`,n.textContent=`⚙ ${String(t.working.name??`scene`)}`,n.addEventListener(`click`,()=>t.select(null)),e.appendChild(n);let r=t.working.root;if(!r){let t=document.createElement(`div`);t.className=`muted-note explorer-empty`,t.textContent=`no root node — pick a type below and + to start the scene`,e.appendChild(t);return}LU(r,t.selection),e.appendChild(RU(r,[],t,``)),FU(e,t.selection)}var PU=null;function FU(e,t){let n=JSON.stringify(t);n!==PU&&(PU=n,e.querySelector(`.tree-row.selected`)?.scrollIntoView?.({block:`nearest`,inline:`nearest`}))}function IU(){PU=null}function LU(e,t){if(!t)return;let n=e,r=``;for(let e of t){r=r?`${r}/${n.name}`:String(n.name),SU.delete(r);let t=n.children?.[e];if(!t)return;n=t}}function RU(e,t,n,r){let i=r?`${r}/${e.name}`:String(e.name),a=(e.children?.length??0)>0,o=SU.has(i),s=document.createElement(`div`);s.className=`tree-branch`;let c=document.createElement(`div`);c.className=`tree-row${n.isSelected(t)?` selected`:``}`,c.draggable=t.length>0&&jU!==i;let l=document.createElement(`span`);l.className=`chevron${a?``:` leaf`}${o?` collapsed`:``}`,a?l.appendChild(FL()):l.textContent=`·`,a&&l.addEventListener(`click`,e=>{e.stopPropagation(),o?SU.delete(i):SU.add(i),n.select(n.selection)});let u=document.createElement(`span`);if(u.className=`tree-icon ${MU(e.type)}`,u.appendChild(PL(e.type)),u.title=e.type??`instance`,u.addEventListener(`click`,t=>{t.stopPropagation(),zU(u,e.type??`instance`)}),c.append(l,u),jU===i){let r=document.createElement(`input`);r.className=`rename-input`,r.value=e.name??``;let i=()=>{jU=null;let i=r.value.trim();if(i&&i!==e.name){let e=n.renameNode(t,i)??[];e.length>0&&TU?.(e)}else n.select(n.selection)};r.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Enter`&&i(),e.key===`Escape`&&(jU=null,n.select(n.selection))});for(let e of[`click`,`pointerdown`,`dblclick`,`mousedown`])r.addEventListener(e,e=>e.stopPropagation());r.addEventListener(`blur`,i),c.appendChild(r),queueMicrotask(()=>{r.focus(),r.select()})}else{let r=document.createElement(`span`);r.className=`tree-name`,r.textContent=e.name??`(unnamed)`,r.addEventListener(`dblclick`,e=>{e.stopPropagation(),jU=i,n.select(t)}),c.appendChild(r)}if(c.addEventListener(`click`,e=>{a&&!e.metaKey&&!e.ctrlKey&&(o?SU.delete(i):SU.add(i)),n.select(t,{toggle:e.metaKey||e.ctrlKey})}),c.addEventListener(`contextmenu`,e=>{e.preventDefault(),n.isSelected(t)||n.select(t),BU(e.clientX,e.clientY,n,t,i)}),YU(c,t,n),s.appendChild(c),a&&!o){let r=document.createElement(`div`);r.className=`tree-children`,(e.children??[]).forEach((e,a)=>{r.appendChild(RU(e,[...t,a],n,i))}),s.appendChild(r)}return s}function zU(e,t){GU();let n=document.createElement(`div`);n.className=`balloon floating`;let r=document.createElement(`span`);r.className=`balloon-title`,r.textContent=t,n.appendChild(r);let i=xU.get(t);if(i){let e=document.createElement(`span`);e.textContent=jL(i),n.appendChild(e)}document.body.appendChild(n);let a=e.getBoundingClientRect();n.style.left=`${Math.min(innerWidth-240,a.right+8)}px`,n.style.top=`${Math.max(8,a.top-6)}px`,KU(n)}function BU(e,t,n,r,i){GU();let a=n.allSelections(),o=a.length===1&&r.length>0,s=document.createElement(`div`);s.className=`context-menu floating`;let c=(e,t,n)=>{let r=document.createElement(`button`);r.type=`button`,r.className=`menu-item${n?.danger?` danger`:``}`,r.disabled=t===null;let i=document.createElement(`span`);if(i.textContent=e,r.appendChild(i),n?.kbd){let e=document.createElement(`kbd`);e.textContent=n.kbd,r.appendChild(e)}t&&r.addEventListener(`click`,()=>{GU(),t()}),s.appendChild(r)};c(`duplicate${a.length>1?` ×${a.length}`:``}`,()=>{for(let e of[...a].reverse())n.duplicateNode(e)}),c(`frame in view`,wU&&r.length>0?()=>{n.select(r),wU?.()}:null,{kbd:`F`}),c(`rename`,o?()=>{jU=i,n.select(r)}:null,{kbd:`dbl-click`}),s.appendChild(VU()),c(`cut`,r.length>0?()=>HU(n,!0):null),c(`copy`,r.length>0?()=>HU(n,!1):null),c(`paste as child${AU?` (${AU.nodes.length})`:``}`,AU?()=>UU(n,r):null),s.appendChild(VU()),c(`delete`,r.length>0?()=>(CU??(e=>n.removeNodes(e)))(a):null,{danger:!0}),document.body.appendChild(s),s.style.left=`${Math.min(innerWidth-200-8,e)}px`,s.style.top=`${Math.min(innerHeight-s.offsetHeight-8,t)}px`,KU(s)}function VU(){let e=document.createElement(`div`);return e.className=`menu-divider`,e}function HU(e,t){let n=e.allSelections().filter(e=>e.length>0).map(t=>e.nodeAt(t)).filter(e=>e!==null);AU={nodes:n.map(e=>JSON.parse(JSON.stringify(e))),cut:t?n:null}}function UU(e,t){if(AU){for(let n of AU.nodes)e.insertNode(n,t);if(AU.cut){let t=e.working.root,n=AU.cut.map(e=>WU(t,e)).filter(e=>e!==null);n.length>0&&e.removeNodes(n),AU={nodes:AU.nodes,cut:null}}}}function WU(e,t){if(e===t)return[];for(let[n,r]of(e.children??[]).entries()){let e=WU(r,t);if(e)return[n,...e]}return null}function GU(){for(let e of document.querySelectorAll(`.floating`))e.remove()}function KU(e){let t=r=>{e.contains(r.target)||(e.remove(),document.removeEventListener(`pointerdown`,t,!0),document.removeEventListener(`keydown`,n,!0))},n=r=>{r.key===`Escape`&&(e.remove(),document.removeEventListener(`pointerdown`,t,!0),document.removeEventListener(`keydown`,n,!0))};setTimeout(()=>{document.addEventListener(`pointerdown`,t,!0),document.addEventListener(`keydown`,n,!0)},0)}function qU(e,t){let n=t.getBoundingClientRect(),r=(e.clientY-n.top)/n.height;return r<.25?`before`:r>.75?`after`:`into`}function JU(e){e.classList.remove(`drop-into`,`drop-before`,`drop-after`)}function YU(e,t,n){e.addEventListener(`dragstart`,r=>{kU=n.isSelected(t)?n.allSelections():[t],r.dataTransfer?.setData(`text/plain`,``),r.dataTransfer&&(r.dataTransfer.effectAllowed=`move`),e.classList.add(`dragging`)}),e.addEventListener(`dragend`,()=>{kU=null,e.classList.remove(`dragging`)}),e.addEventListener(`dragover`,n=>{if(!kU||kU.some(e=>e.length<=t.length&&e.every((e,n)=>e===t[n])))return;n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect=`move`),JU(e);let r=t.length===0?`into`:qU(n,e);e.classList.add(`drop-${r}`)}),e.addEventListener(`dragleave`,()=>JU(e)),e.addEventListener(`drop`,r=>{if(JU(e),!kU)return;r.preventDefault();let i=t.length===0?`into`:qU(r,e),a=n.moveNodes(kU,t,i);kU=null,a?.[0]&&n.select(a[0])})}var XU={x:`#fb7185`,y:`#86efac`,z:`#7aa2ff`};function ZU(e,t,n){let r=t-e.origin.x,i=n-e.origin.y;if(Math.abs(r)<=e.centerSize&&Math.abs(i)<=e.centerSize)return{kind:`center`};for(let t of e.axes){let e=t.sx*t.sx+t.sy*t.sy;if(e<1)continue;let n=Math.max(0,Math.min(1,(r*t.sx+i*t.sy)/e)),a=r-t.sx*n,o=i-t.sy*n;if(n>.25&&Math.hypot(a,o)<=8)return{kind:`axis`,axis:t.axis}}return null}function QU(e,t,n){let r=e.sx*e.sx+e.sy*e.sy;return r<1?0:(t*e.sx+n*e.sy)/r*e.worldPerUnit}function $U(e,t,n,r=!1){let{origin:i,axes:a,centerSize:o}=t;for(let t of a){let a=n?.kind===`axis`&&n.axis===t.axis;e.strokeStyle=t.color,e.fillStyle=t.color,e.globalAlpha=a?1:.9,e.lineWidth=a?3:2,e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(i.x+t.sx,i.y+t.sy),e.stroke();let o=Math.hypot(t.sx,t.sy)||1,s=t.sx/o,c=t.sy/o,l=i.x+t.sx,u=i.y+t.sy;e.beginPath(),r?e.rect(l-5,u-5,10,10):(e.moveTo(l+s*9,u+c*9),e.lineTo(l-c*4.5,u+s*4.5),e.lineTo(l+c*4.5,u-s*4.5),e.closePath()),e.fill(),e.font=`700 9px Inter, system-ui, sans-serif`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(t.axis.toUpperCase(),l+s*18,u+c*18)}let s=n?.kind===`center`;e.globalAlpha=s?1:.95,e.fillStyle=s?`#ffffff`:`#e2e6f0`,e.strokeStyle=`#0b0d14`,e.lineWidth=1.5,e.beginPath(),e.rect(i.x-o,i.y-o,o*2,o*2),e.fill(),e.stroke(),e.globalAlpha=1}function eW(e,t,n){return Math.atan2(n-e.y,t-e.x)*180/Math.PI}function tW(e,t){let n=t-e;for(;n>180;)n-=360;for(;n<=-180;)n+=360;return n}function nW(e,t,n,r){let i=null,a=r;for(let r of e)for(let e of r.points){let o=Math.hypot(t-e.x,n-e.y);o<a&&(a=o,i=r.axis)}return i}function rW(e,t,n){for(let r of t){if(r.points.length<2)continue;let t=n===r.axis;e.strokeStyle=XU[r.axis],e.globalAlpha=t?1:.75,e.lineWidth=t?3:2,e.beginPath();let i=r.points[0];e.moveTo(i.x,i.y);for(let t of r.points.slice(1))e.lineTo(t.x,t.y);e.closePath(),e.stroke()}e.globalAlpha=1}function iW(e,t,n,r){e.font=`600 11px ui-monospace, Menlo, monospace`;let i=e.measureText(r).width+14;e.fillStyle=`rgba(16, 19, 29, 0.92)`,e.strokeStyle=`rgba(110, 231, 220, 0.5)`,e.lineWidth=1,e.beginPath(),e.roundRect(t+14,n-26,i,20,5),e.fill(),e.stroke(),e.fillStyle=`#6ee7dc`,e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(r,t+21,n-16)}var aW=class{engine;editCanvas;overlay;playCanvas;cb;editUiHost=null;playUiHost=null;renderer2d=null;renderer3d=null;rendererDim=null;orbit={yaw:.6,pitch:.35,dist:10,target:[0,1,0]};pathOf=new Map;reindexNeeded=!1;nodeAtPath=new Map;selectedPath=null;paintHandler=null;extraPaths=[];hoveredNode=null;hoveredGizmo=null;lastGood=null;lastAppliedKey=null;playEngine=null;playRenderer=null;playPhysics=null;setPaintHandler(e){this.paintHandler=e}get playing(){return this.playEngine!==null}constructor(e,t,n,r){this.editCanvas=e,this.overlay=t,this.playCanvas=n,this.cb=r;let i=this;this.engine=new Hn({scheduler:e=>{let t=0,n=performance.now(),r=requestAnimationFrame(function a(o){t+=.001;let s=Math.min(.1,(o-n)/1e3);n=o;try{e(t),i.tickAmbientPreviews(s),i.reportAssetErrors()}catch(e){console.error(`incanto-editor viewport:`,e)}r=requestAnimationFrame(a)});return()=>cancelAnimationFrame(r)}}),this.editUiHost=this.makeUiHost(e.parentElement,4),this.playUiHost=this.makeUiHost(n.parentElement,5),this.engine.uiHost=this.editUiHost,this.engine.start(),this.engine.updated.connect(()=>this.drawOverlay());let a=e=>{e.key===`Shift`&&(this.shiftHeld=!0)},o=e=>{e.key===`Shift`&&(this.shiftHeld=!1)};window.addEventListener(`keydown`,a),window.addEventListener(`keyup`,o),this.cleanups.push(()=>{window.removeEventListener(`keydown`,a),window.removeEventListener(`keyup`,o)}),this.bindPointer()}cleanups=[];makeUiHost(e,t){if(!e)return null;let n=document.createElement(`div`);return n.style.cssText=`position:absolute;inset:0;pointer-events:none;z-index:${t};`,e.appendChild(n),this.cleanups.push(()=>n.remove()),n}dispose(){this.stop(),this.editPhysics?.dispose(),this.editPhysics=null,this.engine.stop(),this.engine.dispose(),this.renderer2d?.dispose(),this.renderer3d?.dispose(),this.renderer2d=null,this.renderer3d=null;for(let e of this.cleanups.splice(0))e()}setEditCamera(e,t){let n=(e[0]??0)-(t[0]??0),r=(e[1]??0)-(t[1]??0),i=(e[2]??0)-(t[2]??0),a=Math.hypot(n,r,i);a>.01&&(this.orbit.target=[t[0]??0,t[1]??0,t[2]??0],this.orbit.dist=Math.min(800,Math.max(.3,a)),this.orbit.yaw=Math.atan2(n,i),this.orbit.pitch=Math.asin(Math.max(-.99,Math.min(.99,r/a))),this.syncOrbit())}editCamera(){let{pos:e}=this.orbitVectors();return{position:[e.x,e.y,e.z],target:[...this.orbit.target]}}apply(e){e.root||(e={...e,root:{name:`__empty`,type:(e.dimension??`2d`)===`3d`?`Node3D`:`Node2D`}});let t=JSON.stringify(e);if(t===this.lastAppliedKey&&this.rendererDim===(e.dimension??`2d`))return null;let n;try{let t=structuredClone(e);SW(t),n=Ai(t,{stubAllBehaviors:!0})}catch(e){return e instanceof Error?e.message:String(e)}this.lastGood=e,this.lastAppliedKey=t;let r=e.dimension??`2d`;if(this.rendererDim!==r){if(this.renderer2d?.dispose(),this.renderer3d?.dispose(),this.renderer2d=null,this.renderer3d=null,r===`2d`)this.renderer2d=new Vx({canvas:this.editCanvas,engine:this.engine}),this.renderer2d.ignoreStatic=!0,this.renderer2d.viewOverride=this.defaultView(e);else{this.renderer3d=new JI({canvas:this.editCanvas,engine:this.engine}),this.renderer3d.ignoreStatic=!0;let t=vW(e.root);if(t){let[e,n,r]=t;this.orbit.dist=Math.max(2,Math.hypot(e,n,r)),this.orbit.yaw=Math.atan2(e,r),this.orbit.pitch=Math.asin(Math.max(-.99,Math.min(.99,n/this.orbit.dist))),this.orbit.target=[0,Math.min(2,Math.abs(n)/2),0]}this.syncOrbit()}this.rendererDim=r}return this.engine.setScene(n),this.indexTree(n.root),this.hoveredNode=null,null}setSelection(e,t=[]){this.selectedPath=e,this.extraPaths=t}validate(e){if(!e.root)return null;try{let t=structuredClone(e);return SW(t),Ai(t,{stubAllBehaviors:!0}),null}catch(e){return e instanceof Error?e.message:String(e)}}defaultView(e){let t=yW(e.root);if(t)return{cx:t[0],cy:t[1],zoom:1};let n=this.editCanvas.clientWidth||960,r=this.editCanvas.clientHeight||540;return{cx:n/2,cy:r/2,zoom:1}}indexTree(e){this.pathOf=new Map,this.nodeAtPath=new Map;let t=(e,n)=>{this.pathOf.set(e,n),this.nodeAtPath.set(n.join(`.`),e),e.children.forEach((e,r)=>{t(e,[...n,r])})};t(e,[])}liveSelected(){return this.selectedPath===null?null:this.nodeAtPath.get(this.selectedPath.join(`.`))??null}patchProp(e,t,n,r){if(this.playing)return!1;let i=this.nodeAtPath.get(t.join(`.`));if(!i)return!1;try{i[n]=r===void 0?void 0:structuredClone(r)}catch{return!1}return this.reindexNeeded=!0,this.lastAppliedKey=JSON.stringify(e),!0}gizmoActive=null;gizmoMode=`move`;activeRing=null;readout=null;cancelActiveDrag=()=>{};shiftHeld=!1;get showColliders(){return this.collidersOn}set showColliders(e){this.collidersOn=e,this.editPhysics&&(this.editPhysics.debugDraw=e),e&&this.ensureOutlinePhysics()}collidersOn=!0;editPhysics=null;outlinePending=null;async ensureOutlinePhysics(){if(this.editPhysics||this.outlinePending)return this.outlinePending??void 0;let e=this.rendererDim;if(e)return this.outlinePending=(async()=>{try{if(e===`2d`){let{enablePhysics2D:e}=await Bg(async()=>{let{enablePhysics2D:e}=await Promise.resolve().then(()=>tS);return{enablePhysics2D:e}},void 0,import.meta.url),t=await e(this.engine,{simulate:!1});t.debugDraw=this.collidersOn,this.editPhysics=t}else{let{enablePhysics3D:e}=await Bg(async()=>{let{enablePhysics3D:e}=await Promise.resolve().then(()=>dL);return{enablePhysics3D:e}},void 0,import.meta.url),t=await e(this.engine,{simulate:!1});t.debugDraw=this.collidersOn,this.editPhysics=t}}catch(e){console.warn(`[incanto] collider outlines unavailable:`,e)}finally{this.outlinePending=null}})(),this.outlinePending}get mode(){return this.gizmoMode}setMode(e){this.gizmoMode=e,this.cb.onModeChanged(e)}screen2D(e){let t=_W(e);return this.renderer2d?this.renderer2d.isUiNode(e)?this.renderer2d.screenFromUi(t.x,t.y):this.renderer2d.screenFromWorld(t.x,t.y):t}point2D(e,t,n){return this.renderer2d?this.renderer2d.isUiNode(e)?this.renderer2d.uiFromScreen(t,n):this.renderer2d.worldFromScreen(t,n):{x:t,y:n}}gizmoLayout(){let e=this.liveSelected();if(!e)return null;if(this.rendererDim===`2d`&&this.renderer2d){let t=e.position;if(!Array.isArray(t))return null;let n=this.screen2D(e),r=this.renderer2d.isUiNode(e)?1:this.renderer2d.view().zoom;return{origin:n,centerSize:7,axes:[{axis:`x`,sx:64,sy:0,worldPerUnit:64/r,color:XU.x},{axis:`y`,sx:0,sy:64,worldPerUnit:64/r,color:XU.y}]}}if(this.rendererDim===`3d`&&this.renderer3d){let t=e._object3D,n=e.position;if(!t||!Array.isArray(n))return null;t.getWorldPosition(dW);let r=this.renderer3d.screenFromWorld(dW.x,dW.y,dW.z);if(r.behind)return null;let i=[],a=this.orbit.dist,o=Math.max(.2,a*.18);for(let[e,t]of[[`x`,[1,0,0]],[`y`,[0,1,0]],[`z`,[0,0,1]]]){let n=this.renderer3d.screenFromWorld(dW.x+t[0]*o,dW.y+t[1]*o,dW.z+t[2]*o);n.behind||i.push({axis:e,sx:n.x-r.x,sy:n.y-r.y,worldPerUnit:o,color:XU[e]})}return{origin:{x:r.x,y:r.y},centerSize:7,axes:i}}return null}ringLayout(){let e=this.liveSelected();if(!e)return null;if(this.rendererDim===`2d`&&this.renderer2d){let t=this.screen2D(e),n=[];for(let e=0;e<48;e++){let r=e/48*Math.PI*2;n.push({x:t.x+56*Math.cos(r),y:t.y+56*Math.sin(r)})}return{origin:t,rings:[{axis:`z`,points:n}]}}if(this.rendererDim===`3d`&&this.renderer3d){let t=e._object3D;if(!t)return null;t.getWorldPosition(dW);let n={x:dW.x,y:dW.y,z:dW.z},r=this.renderer3d.screenFromWorld(n.x,n.y,n.z);if(r.behind)return null;let i=Math.max(.2,this.orbit.dist*.16),a=[];for(let e of[`x`,`y`,`z`]){let t=[];for(let r=0;r<48;r++){let a=r/48*Math.PI*2,o=Math.cos(a)*i,s=Math.sin(a)*i,c=e===`x`?this.renderer3d.screenFromWorld(n.x,n.y+o,n.z+s):e===`y`?this.renderer3d.screenFromWorld(n.x+o,n.y,n.z+s):this.renderer3d.screenFromWorld(n.x+o,n.y+s,n.z);c.behind||t.push({x:c.x,y:c.y})}a.push({axis:e,points:t})}return{origin:{x:r.x,y:r.y},rings:a}}return null}orbitVectors(){let{yaw:e,pitch:t,dist:n,target:r}=this.orbit,i=Math.cos(t),a=new W(r[0]+n*i*Math.sin(e),r[1]+n*Math.sin(t),r[2]+n*i*Math.cos(e)),o=new W(r[0],r[1],r[2]).sub(a).normalize(),s=new W().crossVectors(o,sW).normalize();return{pos:a,right:s,up:new W().crossVectors(s,o).normalize(),forward:o}}syncOrbit(){if(!this.renderer3d)return;let{pos:e}=this.orbitVectors();this.renderer3d.viewOverride={position:[e.x,e.y,e.z],target:[...this.orbit.target]}}gameView(){if(this.rendererDim===`3d`&&this.renderer3d){let e=null;for(let[t]of this.pathOf)if(t instanceof Bk&&(t.current||!e)&&(e=t,t.current))break;let t=e?e._ensureObject3D():null;if(t){t.getWorldPosition(cW),lW.set(0,0,-1).applyQuaternion(t.getWorldQuaternion(uW));let e=Math.min(40,Math.max(3,this.orbit.dist));this.orbit.target=[cW.x+lW.x*e,cW.y+lW.y*e,cW.z+lW.z*e],this.orbit.dist=e,this.orbit.yaw=Math.atan2(-lW.x,-lW.z),this.orbit.pitch=Math.asin(Math.max(-.99,Math.min(.99,-lW.y)))}this.renderer3d.viewOverride=null;return}this.renderer2d&&(this.renderer2d.viewOverride=null)}snapView(e,t){e===`y`?(this.orbit.pitch=t*1.45,this.orbit.yaw=0):(this.orbit.pitch=0,this.orbit.yaw=e===`z`?t===1?0:Math.PI:Math.PI/2*t),this.syncOrbit()}gizmoCenter(){return{x:this.overlay.clientWidth-58,y:58,r:36}}gizmoHandles(){let{right:e,up:t,forward:n}=this.orbitVectors(),r=this.gizmoCenter(),i=[];for(let[a,o]of[[`x`,new W(1,0,0)],[`y`,new W(0,1,0)],[`z`,new W(0,0,1)]])for(let s of[1,-1]){let c=o.clone().multiplyScalar(s);i.push({axis:a,sign:s,x:r.x+c.dot(e)*26,y:r.y-c.dot(t)*26,z:-c.dot(n)})}return i.sort((e,t)=>e.z-t.z)}gizmoHit(e,t){let n=this.gizmoCenter();if(Math.hypot(e-n.x,t-n.y)>n.r+8)return null;let r=null,i=14;for(let n of this.gizmoHandles()){let a=Math.hypot(e-n.x,t-n.y);a<i&&(i=a,r={axis:n.axis,sign:n.sign})}return r??{axis:`z`,sign:1}}gizmoHandleAt(e,t){let n=this.gizmoCenter();if(Math.hypot(e-n.x,t-n.y)>n.r+8)return null;let r=null,i=12;for(let n of this.gizmoHandles()){let a=Math.hypot(e-n.x,t-n.y);a<i&&(i=a,r={axis:n.axis,sign:n.sign})}return r}assetErrorSignature=``;reportAssetErrors(){let e=this.assetErrors(),t=e.map(e=>e.ref).join(`|`);t!==this.assetErrorSignature&&(this.assetErrorSignature=t,this.cb.onAssetErrors(e))}assetErrors(){return this.renderer2d?.assets.errors()??this.renderer3d?.assets.errors()??[]}tickAmbientPreviews(e){if(!this.playing)for(let[t]of this.pathOf)(t instanceof QM||t instanceof ux||t instanceof nN||t instanceof Hv||t instanceof _M)&&t.update(e)}modelAnimationsAt(e){let t=this.nodeAtPath.get(e.join(`.`));return t instanceof QM?t.availableAnimations():[]}boneNamesAt(e,t){let n=this.nodeAtPath.get(e.join(`.`));if(!n||t===``)return[];let r=n.getNodeOrNull(t);return r instanceof QM?r.boneNames():[]}drawOverlay(){if(this.reindexNeeded){this.reindexNeeded=!1;let e=this.engine.scene?.tree.root;e&&this.indexTree(e)}let e=this.overlay.getContext(`2d`);if(!e)return;let t=this.overlay.clientWidth,n=this.overlay.clientHeight,r=Math.min(devicePixelRatio||1,2);if((this.overlay.width!==t*r||this.overlay.height!==n*r)&&(this.overlay.width=t*r,this.overlay.height=n*r),e.setTransform(r,0,0,r,0,0),e.clearRect(0,0,t,n),this.playing)return;if(this.rendererDim===`3d`){this.drawGizmo(e),this.drawModeGizmo(e),this.readout&&iW(e,this.readout.x,this.readout.y,this.readout.text);return}if(!this.renderer2d)return;if(this.drawAxes2D(e),this.hoveredNode&&this.hoveredNode!==this.liveSelected()){let t=this.renderer2d.boundsOf(this.hoveredNode);t&&(e.strokeStyle=`rgba(110, 231, 220, 0.45)`,e.lineWidth=1.5,e.setLineDash([]),e.strokeRect(t.x,t.y,t.w,t.h))}for(let t of this.extraPaths){let n=this.nodeAtPath.get(t.join(`.`)),r=n?this.renderer2d.boundsOf(n):null;r&&(e.strokeStyle=`rgba(110, 231, 220, 0.7)`,e.lineWidth=1.5,e.setLineDash([4,3]),e.strokeRect(r.x-2,r.y-2,r.w+4,r.h+4),e.setLineDash([]))}let i=this.liveSelected();if(i){let t=this.renderer2d.boundsOf(i)??this.pointBounds(i);if(t){e.strokeStyle=`#6ee7dc`,e.lineWidth=2,e.setLineDash([6,4]),e.lineDashOffset=-(performance.now()/50%10),e.strokeRect(t.x-2,t.y-2,t.w+4,t.h+4),e.setLineDash([]),e.fillStyle=`#6ee7dc`;for(let[n,r]of[[t.x-2,t.y-2],[t.x+t.w+2,t.y-2],[t.x-2,t.y+t.h+2],[t.x+t.w+2,t.y+t.h+2]])e.fillRect(n-3,r-3,6,6)}}this.drawModeGizmo(e),this.readout&&iW(e,this.readout.x,this.readout.y,this.readout.text)}drawModeGizmo(e){if(this.gizmoMode===`rotate`){let t=this.ringLayout();t&&rW(e,t.rings,this.activeRing);return}let t=this.gizmoLayout();t&&$U(e,t,this.gizmoActive,this.gizmoMode===`scale`)}pointBounds(e){if(!this.renderer2d)return null;let t=e.position;if(!Array.isArray(t))return null;let n=this.screen2D(e);return{x:n.x-12,y:n.y-12,w:24,h:24}}drawGizmo(e){let t=this.gizmoCenter();e.beginPath(),e.arc(t.x,t.y,t.r,0,Math.PI*2),e.fillStyle=`rgba(16, 19, 29, 0.72)`,e.fill(),e.strokeStyle=`rgba(52, 60, 84, 0.9)`,e.lineWidth=1,e.stroke();let n={x:`#fb7185`,y:`#86efac`,z:`#7aa2ff`},r={x1:`right`,"x-1":`left`,y1:`top`,"y-1":`bottom`,z1:`front`,"z-1":`back`};for(let r of this.gizmoHandles()){let i=this.hoveredGizmo?.axis===r.axis&&this.hoveredGizmo?.sign===r.sign,a=n[r.axis],o=(r.z+1)/2;e.globalAlpha=i?1:.45+o*.55,e.strokeStyle=a,e.lineWidth=1.5,e.beginPath(),e.moveTo(t.x,t.y),e.lineTo(r.x,r.y),e.stroke(),e.beginPath(),e.arc(r.x,r.y,(r.sign===1?7:5)+(i?2:0),0,Math.PI*2),r.sign===1?(e.fillStyle=a,e.fill(),e.fillStyle=`#0b0d14`,e.font=`700 8px ui-monospace, monospace`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(r.axis.toUpperCase(),r.x,r.y+.5)):(e.fillStyle=`rgba(16, 19, 29, 0.9)`,e.fill(),e.stroke())}if(e.globalAlpha=1,this.hoveredGizmo){let n=r[`${this.hoveredGizmo.axis}${this.hoveredGizmo.sign}`];e.fillStyle=`#9aa3bd`,e.font=`600 10px Inter, system-ui, sans-serif`,e.textAlign=`center`,e.textBaseline=`bottom`,e.fillText(`${n} view`,t.x,t.y-t.r-6)}}drawAxes2D(e){let t=this.gizmoCenter();e.save(),e.shadowColor=`rgba(0, 0, 0, 0.25)`,e.shadowBlur=10,e.shadowOffsetY=2,e.beginPath(),e.arc(t.x,t.y,31,0,Math.PI*2),e.fillStyle=`rgba(13, 16, 24, 0.42)`,e.fill(),e.shadowColor=`transparent`,e.strokeStyle=`rgba(255, 255, 255, 0.16)`,e.lineWidth=1,e.stroke();let n=t.x-9,r=t.y-9;e.lineCap=`round`;let i=(t,i,a,o)=>{let s=n+t*21,c=r+i*21,l=e.createLinearGradient(n,r,s,c);l.addColorStop(0,`${a}55`),l.addColorStop(1,a),e.strokeStyle=l,e.lineWidth=2,e.beginPath(),e.moveTo(n,r),e.lineTo(s,c),e.stroke(),e.beginPath(),e.arc(s,c,6.5,0,Math.PI*2),e.fillStyle=a,e.fill(),e.font=`800 8px Inter, system-ui, sans-serif`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillStyle=`#0b0d14`,e.fillText(o,s,c+.5)};i(1,0,`#fb7185`,`X`),i(0,1,`#86efac`,`Y`),e.beginPath(),e.arc(n,r,2.5,0,Math.PI*2),e.fillStyle=`#e2e6f0`,e.fill(),e.restore()}bindPointer(){let e=this.overlay,t=null,n=null,r=!1,i=null,a=null,o=null,s=null,c=null,l=t=>{let n=this.ringLayout();if(!n)return!1;let r=nW(n.rings,t.offsetX,t.offsetY,9);if(!r)return!1;let i=this.liveSelected();if(!i)return!1;e.setPointerCapture(t.pointerId);let a=i.rotation,o=1;if(this.rendererDim===`3d`&&this.renderer3d){let{forward:e}=this.renderer3d.cameraBasis();o=(r===`x`?e.x:r===`y`?e.y:e.z)>0?1:-1}return c={axis:r,node:i,origin:n.origin,startAngle:eW(n.origin,t.offsetX,t.offsetY),startRotation:Array.isArray(a)?[...a]:a??0,sign:o},this.activeRing=r,!0},u=e=>{if(!c)return;let{axis:t,node:n,origin:r,startAngle:i,startRotation:a,sign:o}=c,s=tW(i,eW(r,e.offsetX,e.offsetY))*o,l=e.shiftKey||this.shiftHeld?15:null,u=e=>{let t=e+s;return l?Math.round(t/l)*l:Math.round(t*10)/10},d;if(Array.isArray(a)){let e={x:0,y:1,z:2}[t],r=[...a];r[e]=u(a[e]??0),d=r[e],n.rotation=r}else{let e=u(a);d=e,n.rotation=e}this.readout={x:e.offsetX,y:e.offsetY,text:`${d}°${l?` ⌁15°`:``}`}},d=e=>{if(!c)return;let{node:t,startRotation:n}=c;if(!e)t.rotation=n;else{let e=this.pathOf.get(t),n=t.rotation;e!==void 0&&n!==void 0&&(Array.isArray(n)?this.cb.onNodeRotated3D(e,[n[0]??0,n[1]??0,n[2]??0]):this.cb.onNodeRotated2D(e,n))}c=null,this.activeRing=null,this.readout=null};this.cancelActiveDrag=()=>{d(!1),s&&(s.node.position=s.startPos,s.node.scale=s.startScale,s=null,this.gizmoActive=null,this.readout=null)};let f=t=>{if(this.gizmoMode===`rotate`)return l(t);let n=this.gizmoLayout();if(!n)return!1;let r=ZU(n,t.offsetX,t.offsetY);if(!r)return!1;let i=this.liveSelected();if(!i)return!1;e.setPointerCapture(t.pointerId);let a=[...i.position??[]],o=[...i.scale??[]];return s={hit:r,mode:this.gizmoMode===`scale`||t.button===2?`scale`:`move`,startX:t.offsetX,startY:t.offsetY,layout:n,node:i,startPos:a,startScale:o},this.gizmoActive=r,!0},p=e=>{if(!s)return;let{hit:t,mode:n,layout:r,node:i,startPos:a,startScale:o}=s,c=e.offsetX-s.startX,l=e.offsetY-s.startY,u=this.rendererDim===`3d`,d={x:0,y:1,z:2},f=e.shiftKey||this.shiftHeld,p=f?u?.5:10:null,m=f?.25:null,h=e=>p?Math.round(e/p)*p:e,g=e=>m?Math.max(m,Math.round(e/m)*m):e;if(n===`scale`){let n=Math.max(.05,1+(c-l)*.005),r=[...o];if(t.kind===`axis`)r[d[t.axis]]=oW(g((o[d[t.axis]]??1)*n));else for(let e=0;e<r.length;e++)r[e]=oW(g((o[e]??1)*n));i.scale=r,this.readout={x:e.offsetX,y:e.offsetY,text:`×${r.map(e=>oW(e)).join(`, `)}`};return}let _=[...a];if(t.kind===`axis`){let e=r.axes.find(e=>e.axis===t.axis);if(!e)return;let n=QU(e,c,l);if(u)_[d[t.axis]]=oW(h((a[d[t.axis]]??0)+n));else{let e=hW(i,t.axis===`x`?n:0,t.axis===`y`?n:0),r=t.axis===`x`?e.x:e.y;_[d[t.axis]]=Math.round(h((a[d[t.axis]]??0)+r))}}else if(u&&this.renderer3d){let{right:e,up:t}=this.renderer3d.cameraBasis(),n=this.orbit.dist*.0016;_[0]=oW(h((a[0]??0)+(e.x*c-t.x*l)*n)),_[1]=oW(h((a[1]??0)+(e.y*c-t.y*l)*n)),_[2]=oW(h((a[2]??0)+(e.z*c-t.z*l)*n))}else if(this.renderer2d){let e=this.renderer2d.view(),t=hW(i,c/e.zoom,l/e.zoom);_[0]=Math.round(h((a[0]??0)+t.x)),_[1]=Math.round(h((a[1]??0)+t.y))}i.position=_,this.readout={x:e.offsetX,y:e.offsetY,text:`[${_.map(e=>oW(e)).join(`, `)}]`}},m=()=>{if(!s)return;let{node:e,mode:t}=s,n=this.pathOf.get(e);if(n)if(t===`scale`){let t=e.scale??[];this.rendererDim===`3d`?this.cb.onNodeScaled3D(n,[t[0]??1,t[1]??1,t[2]??1]):this.cb.onNodeScaled(n,[t[0]??1,t[1]??1])}else{let t=e.position??[];this.rendererDim===`3d`?this.cb.onNodeMoved3D(n,[t[0]??0,t[1]??0,t[2]??0]):this.cb.onNodeMoved(n,[t[0]??0,t[1]??0])}s=null,this.gizmoActive=null};e.addEventListener(`pointerdown`,s=>{if(this.playing||f(s))return;if(this.rendererDim===`3d`){let t=this.gizmoHit(s.offsetX,s.offsetY);if(t){this.snapView(t.axis,t.sign);return}e.setPointerCapture(s.pointerId),s.button===1||s.button===2||s.shiftKey?a={x:s.offsetX,y:s.offsetY,target:[...this.orbit.target]}:(i={x:s.offsetX,y:s.offsetY,yaw:this.orbit.yaw,pitch:this.orbit.pitch},o={x:s.offsetX,y:s.offsetY,toggle:s.ctrlKey||s.metaKey});return}if(!this.renderer2d)return;if(e.setPointerCapture(s.pointerId),s.button===1||s.button===2||s.shiftKey){let e=this.renderer2d.view();n={startX:s.offsetX,startY:s.offsetY,cx:e.cx,cy:e.cy};return}if(this.paintHandler&&s.button===0){let e=this.renderer2d.worldFromScreen(s.offsetX,s.offsetY);this.paintHandler(e.x,e.y,!0),r=!0;return}let c=this.renderer2d.pick(s.offsetX,s.offsetY),l=c?this.pathOf.get(c)??null:null;if(this.cb.onPick(l,{toggle:s.ctrlKey||s.metaKey}),this.selectedPath=l,c&&l&&Array.isArray(c.position)){let e=c.position;t={node:c,startWorld:this.point2D(c,s.offsetX,s.offsetY),startPos:[e[0]??0,e[1]??0]}}}),e.addEventListener(`pointermove`,o=>{if(!this.playing){if(c){u(o);return}if(s){p(o);return}if(this.rendererDim===`3d`){if(!i&&!a?(this.hoveredGizmo=this.gizmoHandleAt(o.offsetX,o.offsetY),e.style.cursor=this.hoveredGizmo?`pointer`:`grab`):e.style.cursor=`grabbing`,i)this.orbit.yaw=i.yaw-(o.offsetX-i.x)*.006,this.orbit.pitch=Math.max(-1.5,Math.min(1.5,i.pitch+(o.offsetY-i.y)*.006)),this.syncOrbit();else if(a){let{right:e,up:t}=this.orbitVectors(),n=this.orbit.dist*.0016,r=(o.offsetX-a.x)*n,i=(o.offsetY-a.y)*n;this.orbit.target=[a.target[0]-e.x*r+t.x*i,a.target[1]-e.y*r+t.y*i,a.target[2]-e.z*r+t.z*i],this.syncOrbit()}return}if(this.renderer2d){if(e.style.cursor=`crosshair`,r&&this.paintHandler){let e=this.renderer2d.worldFromScreen(o.offsetX,o.offsetY);this.paintHandler(e.x,e.y,!1);return}if(n){let e=this.renderer2d.view();this.renderer2d.viewOverride={cx:n.cx-(o.offsetX-n.startX)/e.zoom,cy:n.cy-(o.offsetY-n.startY)/e.zoom,zoom:e.zoom};return}if(t){let e=this.point2D(t.node,o.offsetX,o.offsetY),n=hW(t.node,e.x-t.startWorld.x,e.y-t.startWorld.y),r=Math.round(t.startPos[0]+n.x),i=Math.round(t.startPos[1]+n.y);t.node.position=[r,i];return}this.hoveredNode=this.renderer2d.pick(o.offsetX,o.offsetY)}}});let h=e=>{if(r=!1,d(!0),m(),this.readout=null,o&&e&&this.renderer3d&&Math.hypot(e.offsetX-o.x,e.offsetY-o.y)<4){let e=this.renderer3d.pick(o.x,o.y),t=e?this.pathOf.get(e)??null:null;t&&(this.cb.onPick(t,{toggle:o.toggle}),this.selectedPath=t)}if(o=null,i=null,a=null,t){let e=this.pathOf.get(t.node),n=t.node.position;e&&(n[0]!==t.startPos[0]||n[1]!==t.startPos[1])&&this.cb.onNodeMoved(e,[n[0]??0,n[1]??0]),t=null}n=null};e.addEventListener(`pointerup`,h),e.addEventListener(`pointercancel`,h),e.addEventListener(`contextmenu`,e=>e.preventDefault()),e.addEventListener(`dblclick`,e=>{if(this.playing)return;let t=this.rendererDim===`3d`?this.renderer3d?.pick(e.offsetX,e.offsetY)??null:this.renderer2d?.pick(e.offsetX,e.offsetY)??null,n=t?this.pathOf.get(t)??null:null;n&&(this.cb.onPick(n,{toggle:e.ctrlKey||e.metaKey}),this.selectedPath=n)}),e.addEventListener(`wheel`,e=>{if(this.playing)return;e.preventDefault();let t=e.deltaY<0?1.1:1/1.1;if(this.rendererDim===`3d`){this.orbit.dist=Math.max(.3,Math.min(800,this.orbit.dist/t)),this.syncOrbit();return}if(!this.renderer2d)return;let n=this.liveSelected();if(e.altKey&&n&&Array.isArray(n.scale)){let e=n.scale,r=[Math.round((e[0]??1)*t*100)/100,Math.round((e[1]??1)*t*100)/100];n.scale=r;let i=this.pathOf.get(n);i&&this.cb.onNodeScaled(i,r);return}let r=this.renderer2d.view(),i=this.renderer2d.worldFromScreen(e.offsetX,e.offsetY),a=Math.min(8,Math.max(.1,r.zoom*t));this.renderer2d.viewOverride={cx:i.x-(e.offsetX-r.w/2)/a,cy:i.y-(e.offsetY-r.h/2)/a,zoom:a}},{passive:!1})}zoomToFit(){let e=this.liveSelected();if(this.rendererDim===`3d`){let t=new Xc;for(let[n]of this.pathOf){if(e&&n!==e&&!gW(n,e))continue;let r=n._object3D;r&&(t.expandByObject(r),t.expandByPoint(r.getWorldPosition(dW)))}if(t.isEmpty()&&e){let t=e._object3D,n=t?t.getWorldPosition(dW):null;this.orbit.target=n?[n.x,n.y,n.z]:[0,1,0],this.orbit.dist=6}else if(t.isEmpty())this.orbit.target=[0,1,0],this.orbit.dist=10;else{let e=t.getCenter(new W),n=t.getSize(new W);this.orbit.target=[e.x,e.y,e.z],this.orbit.dist=Math.max(2.5,n.length()*.85)}this.syncOrbit();return}if(!this.renderer2d)return;let t=this.editCanvas.clientWidth||960,n=this.editCanvas.clientHeight||540,r=1/0,i=1/0,a=-1/0,o=-1/0;for(let[t]of this.pathOf){if(e&&t!==e&&!gW(t,e))continue;let n=t.position;if(!Array.isArray(n))continue;let s=_W(t);r=Math.min(r,s.x),i=Math.min(i,s.y),a=Math.max(a,s.x),o=Math.max(o,s.y)}if(!Number.isFinite(r))return;let s=(r+a)/2,c=(i+o)/2,l=e?600:200,u=Math.max(a-r+l,l),d=Math.max(o-i+l,l),f=Math.min(2,Math.min(t/u,n/d));this.renderer2d.viewOverride={cx:s,cy:c,zoom:f}}async play(e){if(this.playing)return null;let t=structuredClone(e);SW(t);let n;try{n=Ai(t,{stubAllBehaviors:!0,declareConnectionSignals:!0})}catch(e){return e instanceof Error?e.message:String(e)}let r=new Hn;r.uiHost=this.playUiHost,this.editUiHost&&(this.editUiHost.style.display=`none`),r.setScene(n),r.input.attachKeyboard(window),this.playCanvas.hidden=!1;let i=e.dimension??`2d`;try{if(i===`2d`){this.playRenderer=new Vx({canvas:this.playCanvas,engine:r});let{enablePhysics2D:e}=await Bg(async()=>{let{enablePhysics2D:e}=await Promise.resolve().then(()=>tS);return{enablePhysics2D:e}},void 0,import.meta.url),t=await e(r);t.debugDraw=this.showColliders,this.playPhysics=t}else{this.playRenderer=new JI({canvas:this.playCanvas,engine:r,assets:this.renderer3d?.assets});let{enablePhysics3D:e}=await Bg(async()=>{let{enablePhysics3D:e}=await Promise.resolve().then(()=>dL);return{enablePhysics3D:e}},void 0,import.meta.url),t=await e(r);t.debugDraw=this.showColliders,this.playPhysics=t}}catch(e){return this.stop(),e instanceof Error?e.message:String(e)}return r.start(),this.playEngine=r,this.cb.onPlayStateChanged(!0),null}stop(){this.playEngine?.input.dispose(),this.playEngine?.stop(),this.playEngine?.dispose(),this.playEngine=null,this.playPhysics?.dispose(),this.playPhysics=null,this.editUiHost&&(this.editUiHost.style.display=``),this.playRenderer?.dispose(),this.playRenderer=null,this.playCanvas.hidden=!0,this.cb.onPlayStateChanged(!1),this.lastAppliedKey=null,this.lastGood&&this.apply(this.lastGood)}};function oW(e){return Math.round(e*100)/100}var sW=new W(0,1,0),cW=new W,lW=new W,uW=new U,dW=new W,fW=new K,pW=new W,mW=new W;function hW(e,t,n){let r=e._object2D?.parent;return r?(fW.copy(r.matrixWorld).invert(),pW.set(t,-n,0).applyMatrix4(fW),mW.set(0,0,0).applyMatrix4(fW),{x:pW.x-mW.x,y:-(pW.y-mW.y)}):{x:t,y:n}}function gW(e,t){for(let n=e.parent;n;n=n.parent)if(n===t)return!0;return!1}function _W(e){let t=e._object2D;if(t)return t.getWorldPosition(dW),{x:dW.x,y:-dW.y};let n=0,r=0,i=e;for(;i;)Array.isArray(i.position)&&(n+=i.position[0]??0,r+=i.position[1]??0),i=i.parent;return{x:n,y:r}}function vW(e){if(!e)return null;if(e.type===`Camera3D`){let t=e.props?.position??[0,2,8];return[t[0]??0,t[1]??2,t[2]??8]}for(let t of e.children??[]){let e=vW(t);if(e)return e}return null}function yW(e){if(!e)return null;if(e.type===`Camera2D`){let t=e.props?.position??[0,0];return[t[0]??0,t[1]??0]}for(let t of e.children??[]){let e=yW(t);if(e)return e}return null}var bW=null;function xW(){if(bW)return bW;let e=document.createElement(`canvas`);e.width=16,e.height=16;let t=e.getContext(`2d`);for(let e=0;e<2;e++)for(let n=0;n<2;n++)t.fillStyle=(n+e)%2==0?`#c252c2`:`#2b2b3b`,t.fillRect(n*8,e*8,8,8);return bW=e.toDataURL(),bW}function SW(e){let t=e.assets;if(t)for(let e of Object.values(t))typeof e?.url==`string`&&!e.url.includes(`/`)&&!e.url.includes(`.`)&&(e.url=xW())}var CW=e({formatSceneJson:()=>r,httpEditorApi:()=>ue,mountEditor:()=>TW}),wW=new Set([`Terrain3D`,`Water3D`,`River3D`]);Or(),xx(),XF(),wL(),wb();async function TW(e={}){let t=e.api??ue,n=[],r=document.createElement(`style`);r.dataset.incantoEditor=`true`,r.textContent=bU,document.head.appendChild(r),n.push(()=>r.remove());let i=document.createElement(`div`);i.className=`incanto-editor-root`,i.innerHTML=WH,(e.host??document.body).appendChild(i),n.push(()=>i.remove());let a=e=>{let t=i.querySelector(e);if(!t)throw Error(`missing ${e}`);return t},o=await t.meta();a(`#engine-version`).textContent=`incanto@${o.version}`,hB(a(`#popover`)),wR(),a(`#docs-btn`).addEventListener(`click`,()=>SR());let s=a(`#lang-btn`),c=[{code:`en`,label:`English`},{code:`ko`,label:`한국어`}],l=()=>{a(`#lang-current`).textContent=OL()===`ko`?`한국어`:`EN`};l(),s.addEventListener(`click`,()=>{document.querySelector(`.lang-menu`)?.remove();let e=document.createElement(`div`);e.className=`context-menu floating lang-menu`;for(let{code:t,label:n}of c){let r=document.createElement(`button`);r.type=`button`,r.className=`menu-item`;let i=document.createElement(`span`);i.textContent=n;let a=document.createElement(`span`);a.textContent=OL()===t?`✓`:``,a.className=`lang-check`,r.append(i,a),r.addEventListener(`click`,()=>{e.remove(),kL(t)}),e.appendChild(r)}document.body.appendChild(e);let t=s.getBoundingClientRect();e.style.left=`${t.left}px`,e.style.top=`${t.bottom+6}px`;let n=t=>{e.contains(t.target)||t.target===s||(e.remove(),document.removeEventListener(`pointerdown`,n,!0))};setTimeout(()=>document.addEventListener(`pointerdown`,n,!0),0)}),AL(()=>{l(),TR(),u.select(u.selection)});let u=new lU({format:1,type:`scene`,name:``,root:null}),d=a(`#tree`),f=a(`#inspector`),p=a(`#save-btn`),m=a(`#undo-btn`),h=a(`#play-btn`),g=a(`#error-banner`),_=a(`#play-notice`),v=a(`#add-type`),y=a(`#picker`),b=a(`#picker-list`),x=a(`#scenes-btn`),S=o.input,C=o.output,w,T=!1,E=a(`#error-text`),D=e=>{g.hidden=!1,E.textContent=e,hR.error(e)},O=()=>{g.hidden=!0,E.textContent=``};a(`#error-close`).addEventListener(`click`,O);let k=a(`#edit-notice`),A=null,ee=e=>{k.hidden=!1,k.textContent=e,A&&clearTimeout(A),A=setTimeout(()=>{k.hidden=!0,k.textContent=``},6e3)},te={on:!1,brush:`0`},ne=e=>{let t=0,n=0,r=u.working.root,i=e=>{let r=e?.props?.position;Array.isArray(r)&&(t+=Number(r[0]??0),n+=Number(r[1]??0))};i(r);for(let t of e)r=r?.children?.[t],i(r);return{x:t,y:n}},re=!1,ie=(e,t,n=!0)=>{n&&(re=!1);let r=u.selection,i=u.nodeAt(r);if(!r||i?.type!==`TileMap2D`)return;let{cx:a,cy:o}=qB(ne(r),Number(i.props?.tileSize??32),e,t),s=i.props?.cells??[],c=JB(s,a,o,te.brush);!c||JSON.stringify(c)===JSON.stringify(s)||(u.mutate(()=>{i.props||={},i.props.cells=c},{path:r,key:`cells`,value:c},{coalesce:re}),re=!0)},ae=()=>{let e=u.nodeAt(u.selection);te.on&&e?.type!==`TileMap2D`&&(te.on=!1),j.setPaintHandler(te.on?ie:null)},j=new aW(a(`#viewport`),a(`#overlay`),a(`#play-canvas`),{onPick:(e,t)=>u.select(e??null,t),onNodeMoved:(e,t)=>me(e,`position`,t,[0,0]),onNodeScaled:(e,t)=>me(e,`scale`,t,[1,1]),onNodeMoved3D:(e,t)=>me(e,`position`,t,[0,0,0]),onNodeScaled3D:(e,t)=>{let n=u.nodeAt(e);if(n&&wW.has(String(n.type))){D(`${n.type} '${n.name}' cannot be scaled — scale would move only the mesh. Resize it with its "size" prop in the inspector.`);return}me(e,`scale`,t,[1,1,1])},onNodeRotated2D:(e,t)=>pe(e,`rotation`,t,0),onNodeRotated3D:(e,t)=>me(e,`rotation`,t,[0,0,0]),onModeChanged:e=>{for(let t of[`move`,`rotate`,`scale`])a(`#tool-${t}`).classList.toggle(`active`,t===e)},onAssetErrors:e=>{u.assetErrors.clear();for(let t of e)u.assetErrors.set(t.ref.replace(/^\$/,``),t.url);fe(),e.length!==0&&D(e.length===1?`asset '${e[0]?.ref}' failed to load (${e[0]?.url}) — it draws as nothing.`:`${e.length} assets failed to load — they draw as nothing: ${e.map(e=>e.ref).join(`, `)}`)},onPlayStateChanged:e=>{document.body.classList.toggle(`playing`,e),n.push(()=>document.body.classList.remove(`playing`)),h.classList.toggle(`stop`,e),h.innerHTML=e?`<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="6" width="12" height="12"/></svg> stop`:`<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg> play`,_.hidden=!e,e&&(_.textContent=`▶ simulating — physics + input live; game scripts run only in your real game. Esc or stop to return.`)},onError:D}),oe=st().sort(),se=``,ce=e=>{if(e===se)return;se=e,v.textContent=``;let t=e===`3d`?[`3D`,`3D Physics`,`Core`,`Network`,`2D`,`2D Physics`]:[`2D`,`2D Physics`,`Core`,`Network`,`3D`,`3D Physics`];for(let[e]of _R)t.includes(e)||t.push(e);for(let e of t){let t=_R.find(([t])=>t===e)?.[1];if(!t)continue;let n=document.createElement(`optgroup`);n.label=e;for(let e of oe.filter(t)){let t=document.createElement(`option`);t.value=e,t.textContent=e,n.appendChild(t)}n.children.length>0&&v.appendChild(n)}v.value=e===`3d`?`MeshInstance3D`:`Sprite2D`};ce(`2d`);let le=()=>{let e=u.selection??[];if(j.validate(u.working)!==null){for(let e of v.querySelectorAll(`option`))e.disabled=!1;return}for(let t of v.querySelectorAll(`option`)){let n=structuredClone(u.working),r=n.root;if(!n.root)n.root={name:`__probe`,type:t.value};else{for(let t of e)r=r?.children?.[t];if(!r)continue;r.children||=[],r.children.push({name:`__probe`,type:t.value})}t.disabled=j.validate(n)!==null}};v.addEventListener(`mousedown`,le),v.addEventListener(`focus`,le);let M=t.library?e=>DH(t,{kind:e.kind,...e.target?{target:e.target}:{},...e.shelf?{shelf:e.shelf}:{},...e.assetType?{assetType:e.assetType}:{},...e.onProps?{onProps:e.onProps}:{},...e.asAsset?{onAsset:(e,t,n)=>kW(u,n,t)}:{}}):void 0,de=!1,fe=()=>{if(!T)return;NU(d,u),UL(a(`#asset-tree`),u),f.textContent=``,WL(f,u,P,M)||QB(f,u,{modelRefs:()=>DW(u,`model`),animationsForSelection:()=>u.selection?j.modelAnimationsAt(u.selection):[],bonesForSelection:e=>u.selection?j.boneNamesAt(u.selection,e):[],assetRefs:e=>OW(u,e),addAsset:(e,t)=>kW(u,e,t),...M?{openLibrary:M}:{},confirm:P,paint:{active:()=>te.on,brush:()=>te.brush,toggle:()=>{te.on=!te.on,ae(),fe()},setBrush:e=>{te.brush=e,fe()}}}),ce(u.working.dimension??`2d`),a(`#hints`).hidden=(u.working.dimension??`2d`)===`3d`,a(`#hints-3d`).hidden=(u.working.dimension??`2d`)!==`3d`,j.setSelection(u.selection,u.extra),ae();let e=u.pendingLivePatch;if(u.pendingLivePatch=null,!j.playing)if(e&&j.patchProp(u.working,e.path,e.key,e.value))g.hidden=!0;else{let e=j.apply(u.working);g.hidden=e===null,e!==null&&D(e)}p.disabled=!u.dirty||!u.working.root,p.title=u.working.root?``:`Add a root node before saving`,m.disabled=!u.canUndo,u.dirty!==de&&(de=u.dirty,hR.change(u.dirty))};u.onChange(fe),u.validator=e=>j.validate(e),u.onError=D;let pe=(e,t,n,r)=>{let i=u.nodeAt(e);i&&u.mutate(()=>{i.props||={},n===r?(delete i.props[t],Object.keys(i.props).length===0&&delete i.props):i.props[t]=n},{path:e,key:t,value:n})},me=(e,t,n,r)=>{let i=u.nodeAt(e);i&&u.mutate(()=>{i.props||={},JSON.stringify(n)===JSON.stringify(r)?(delete i.props[t],Object.keys(i.props).length===0&&delete i.props):i.props[t]=n},{path:e,key:t,value:n})},he=async(e,n,r)=>{j.playing&&j.stop();let i=await t.loadScene(e);w=e,S=n,C=r,T=!0;let s=e??n;a(`#file-chip`).hidden=!s,a(`#file-path`).textContent=s??``,a(`#file-chip`).title=`input: ${n}\noutput: ${r}`,y.hidden=!0,O(),IU(),u.reset(i),o.mode===`project`&&n&&hR.open(n,r)},ge=UH({list:b,search:a(`#picker-search`),count:a(`#picker-count`),path:a(`#picker-path`)},{entries:async()=>t.scenes?await t.scenes():[],current:()=>w,open:e=>_e(e.rel,e.abs)}),_e=(e,t)=>{let n=()=>{he(e,t,t).catch(e=>D(e instanceof Error?e.message:String(e)))};if(!u.dirty||!u.canUndo){n();return}P(`'${w??`This scene`}' has unsaved changes. Opening '${e}' discards them.`,`discard & open`,n,p.hidden?void 0:{label:`save & open`,run:()=>{Te().then(e=>{e&&n()})}})},ve=async()=>{y.hidden=!1,await ge.refresh()},ye=()=>{y.hidden=!0};if(a(`#picker-close`).addEventListener(`click`,ye),y.addEventListener(`pointerdown`,e=>{e.target===y&&ye()}),a(`#picker-create`).addEventListener(`click`,()=>{(async()=>{let e=a(`#picker-path`),n=(e.value.trim()||e.placeholder).trim();if(n)try{if(!t.createScene)return;let e=await t.createScene(n.endsWith(`.scene.json`)?n:`${n}.scene.json`);await he(e.rel,e.abs,e.abs)}catch(e){D(e instanceof Error?e.message:String(e))}})()}),o.mode===`project`&&t.scenes&&(x.hidden=!1,x.addEventListener(`click`,()=>void ve())),o.mode===`project`&&o.hasScene)await he(void 0,``,``);else if(o.mode===`project`&&t.scenes){let e=await t.scenes(),n=e.length===1?e[0]:void 0;n?await he(n.rel,n.abs,n.abs):await ve()}else await he(void 0,o.input,o.output);a(`#add-btn`).addEventListener(`click`,()=>{let e=u.selection??[],t=v.value,n=u.insertNode({name:t,type:t},e);n&&u.select(n)});let be=a(`#generate`);lB(u),a(`#generate-btn`).addEventListener(`click`,()=>sB(u));let xe=a(`#confirm`),N=e=>{if(u.selection===null&&e.length===0){D(`The scene itself cannot be deleted — it IS the file.`);return}if(e.length===0){let e=u.working.root;if(!e)return;let t=EW(e);P(`This deletes the ROOT '${String(e.name??``)}'${t>0?` AND its ${t} descendant node${t===1?``:`s`}`:``} — the scene goes empty, and the next node you add becomes the new root.`,`delete root`,()=>u.deleteRoot());return}let t=e[0]?.slice(0,-1)??[],n=u.findRemovalReferences(e);if(n.length===0){let n=e.reduce((e,t)=>{let n=u.nodeAt(t);return e+(n?EW(n):0)},0);if(n>0){P(`This deletes ${e.length>1?`${e.length} nodes`:`'${String(u.nodeAt(e[0]??[])?.name??``)}'`} AND ${n} descendant node${n===1?``:`s`}.`,`delete ${e.length+n} nodes`,()=>{u.removeNodes(e)&&u.select(t)});return}u.removeNodes(e)&&u.select(t);return}a(`#confirm-text`).textContent=`${n.length} reference${n.length>1?`s`:``} still point at the node(s) you are deleting. Unlink them and delete, or cancel.`;let r=a(`#confirm-list`);r.textContent=``;for(let e of n){let t=document.createElement(`div`);t.textContent=`${e.kind===`uid`?`◆ uid`:e.kind===`prop`?`→ node path`:`⇄ connection`} ${e.where}`,r.appendChild(t)}a(`#confirm-title`).textContent=`still referenced`,a(`#confirm-delete`).textContent=`unlink & delete`,xe.hidden=!1,Se={selections:e,parentOfFirst:t}},Se=null,Ce=null,we=null;function P(e,t,n,r){a(`#confirm-title`).textContent=`are you sure?`,a(`#confirm-text`).textContent=e,a(`#confirm-list`).textContent=``,a(`#confirm-delete`).textContent=t;let i=a(`#confirm-alt`);i.hidden=r===void 0,r&&(i.textContent=r.label),we=r?.run??null,Ce=n,xe.hidden=!1}async function Te(){try{return await t.saveScene?.(u.working,w),u.markSaved(),hR.save(S,C,u.working),!0}catch(e){return D(e instanceof Error?e.message:String(e)),!1}}function F(){xe.hidden=!0,Se=null,Ce=null,we=null,a(`#confirm-alt`).hidden=!0}a(`#confirm-alt`).addEventListener(`click`,()=>{let e=we;F(),e?.()}),a(`#confirm-close`).addEventListener(`click`,F),a(`#confirm-cancel`).addEventListener(`click`,F),xe.addEventListener(`pointerdown`,e=>{e.target===xe&&F()}),a(`#confirm-delete`).addEventListener(`click`,()=>{if(Ce){Ce(),F();return}Se&&u.removeNodesUnlinking(Se.selections)&&u.select(Se.parentOfFirst),F()}),DU(N),OU(e=>{ee(`${jL({en:`Rename: repaired ${e.length} reference${e.length===1?``:`s`}`,ko:`이름 변경: 참조 ${e.length}건 수정`})} — ${e.map(e=>e.where).join(`, `)}`)}),a(`#asset-add-btn`).addEventListener(`click`,e=>{e.stopPropagation(),u.startAddingAsset()}),a(`#group-add-btn`).addEventListener(`click`,e=>{e.stopPropagation(),u.startAddingGroup()});for(let e of document.querySelectorAll(`.section-toggle`)){let t=e.dataset.section??``,n=document.querySelector(`[data-body="${t}"]`),r=`incanto-editor-section-${t}`,i=t=>{e.classList.toggle(`collapsed`,t),n&&(n.hidden=t),localStorage.setItem(r,t?`1`:``)};i(localStorage.getItem(r)===`1`),e.addEventListener(`click`,()=>i(!e.classList.contains(`collapsed`)))}a(`#delete-btn`).addEventListener(`click`,()=>{N(u.allSelections().filter(e=>e.length>0))});let I=()=>{g.hidden=!0,j.play(u.working).then(e=>{e&&D(e)})};if(h.addEventListener(`click`,()=>{if(j.playing){j.stop(),fe();return}if(!e.onPlay){I();return}i.querySelector(`.play-menu`)?.remove();let t=document.createElement(`div`);t.className=`context-menu floating play-menu`;let r=[[`preview`,`▶ preview here`,e.playHints?.preview??`simulate in the editor · scripts stripped`],[`debug`,`⤢ run as the game`,e.playHints?.debug??`this page becomes the game, with the debug overlay`]];for(let[n,i,a]of r){let r=document.createElement(`button`);r.type=`button`,r.className=`menu-item play-menu-item`;let o=document.createElement(`span`);o.textContent=i;let s=document.createElement(`span`);s.className=`play-menu-hint`,s.textContent=a,r.append(o,s),r.addEventListener(`click`,()=>{t.remove(),n===`preview`?I():e.onPlay?.(n,u.working)}),t.appendChild(r)}i.appendChild(t);let a=h.getBoundingClientRect(),o=t.getBoundingClientRect().width;t.style.left=`${Math.min(Math.max(8,a.right-o),window.innerWidth-o-8)}px`,t.style.top=`${a.bottom+6}px`;let s=e=>{e.type===`keydown`&&e.key!==`Escape`||e.type!==`keydown`&&(t.contains(e.target)||e.target===h)||(t.remove(),document.removeEventListener(`pointerdown`,s,!0),document.removeEventListener(`keydown`,s,!0))};setTimeout(()=>{document.addEventListener(`pointerdown`,s,!0),document.addEventListener(`keydown`,s,!0)},0),n.push(()=>{document.removeEventListener(`pointerdown`,s,!0),document.removeEventListener(`keydown`,s,!0)})}),e.onExit){let t=document.createElement(`button`);t.type=`button`,t.className=`ghost`,t.id=`exit-btn`,t.title=`Back to the game`,t.textContent=`✕ exit`,h.parentElement?.insertBefore(t,h),t.addEventListener(`click`,()=>void e.onExit?.())}for(let e of[`move`,`rotate`,`scale`])a(`#tool-${e}`).addEventListener(`click`,()=>j.setMode(e));j.setMode(`move`);let L=a(`#tool-colliders`),Ee=`incanto-editor-show-colliders`,De=e=>{j.showColliders=e,L.classList.toggle(`active`,e),localStorage.setItem(Ee,e?``:`0`)};De(localStorage.getItem(Ee)!==`0`),L.addEventListener(`click`,()=>De(!j.showColliders));let Oe=a(`#hints-dock`),ke=`incanto-editor-hints-open`;Oe.classList.toggle(`open`,localStorage.getItem(ke)===`1`),a(`#hints-toggle`).addEventListener(`click`,()=>{let e=Oe.classList.toggle(`open`);localStorage.setItem(ke,e?`1`:``)}),a(`#fit-btn`).addEventListener(`click`,()=>j.zoomToFit()),EU(()=>j.zoomToFit()),a(`#gameview-btn`).addEventListener(`click`,()=>j.gameView()),t.saveScene||(p.hidden=!0),p.addEventListener(`click`,()=>{Te()}),m.addEventListener(`click`,()=>u.undo());let Ae=e=>{if(e.key===`Escape`&&j.cancelActiveDrag(),e.key===`Escape`&&!g.hidden&&a(`#docs`).hidden&&xe.hidden&&be.hidden&&y.hidden&&!j.playing){O();return}if(e.key===`Escape`&&!a(`#docs`).hidden){CR();return}if(e.key===`Escape`&&!xe.hidden){F();return}if(e.key===`Escape`&&!be.hidden){cB();return}if(e.key===`Escape`&&!y.hidden){ye();return}if(e.key===`Escape`&&j.playing){j.stop(),fe();return}if(j.playing)return;let t=e.target.matches(`input, textarea, select`);(e.metaKey||e.ctrlKey)&&e.key===`z`?(e.preventDefault(),u.undo()):(e.metaKey||e.ctrlKey)&&e.key===`s`?(e.preventDefault(),p.disabled||p.click()):!t&&e.code===`KeyF`?j.zoomToFit():!t&&(e.code===`Digit0`||e.code===`Numpad0`)?j.gameView():!t&&e.code===`KeyW`?j.setMode(`move`):!t&&e.code===`KeyE`?j.setMode(`rotate`):!t&&e.code===`KeyR`&&j.setMode(`scale`)};return window.addEventListener(`keydown`,Ae),n.push(()=>window.removeEventListener(`keydown`,Ae)),fe(),e.camera&&j.setEditCamera(e.camera.position,e.camera.target),hR.ready(S,C,o.version),{working:()=>u.working,camera:()=>j.editCamera(),showError:D,dispose(){j.dispose();for(let e of document.querySelectorAll(`.context-menu, .balloon`))e.remove();for(let e of n.splice(0).reverse())e()}}}function EW(e){let t=0;for(let n of e.children??[])t+=1+EW(n);return t}function DW(e,t){let n=e.working.assets;return n?Object.entries(n).filter(([,e])=>e?.type===t).map(([e])=>`$${e}`):[]}function OW(e,t){let n=e.working.assets;return n?Object.entries(n).filter(([,e])=>!t||e?.type!==void 0&&t.includes(e.type)).map(([e])=>`$${e}`):[]}function kW(e,t,n){let r=e.working.assets??{};for(let[e,t]of Object.entries(r))if(t?.url===n.url)return`$${e}`;let i=t;for(let e=2;i in r;e++)i=`${t}-${e}`;return e.mutate(()=>{e.working.assets||(e.working.assets={}),e.working.assets[i]=n}),`$${i}`}var AW=null,jW=null;function MW(){return jW||(jW=document.createElement(`canvas`),jW.style.cssText=`position:fixed; inset:0; width:100%; height:100%; display:block;`,document.body.appendChild(jW)),jW.style.visibility=``,jW}async function NW(e,t){return AW=await TW({api:ue,...e?{camera:e}:{},onPlay:(e,t)=>{e===`debug`&&PW(t)},playHints:{debug:`this page becomes the game — needs a scene with no project behaviors`},...t?{onExit:()=>(AW?.dispose(),AW=null,MW(),t())}:{}}),AW}async function PW(e){let t=e.dimension??`2d`;AW?.dispose(),AW=null;let n=async e=>{jW&&(jW.style.visibility=`hidden`),await NW(e.camera,e.exit)};try{if(t===`3d`){let{createGame3D:t}=await Bg(async()=>{let{createGame3D:e}=await Promise.resolve().then(()=>dL);return{createGame3D:e}},void 0,import.meta.url);await t({canvas:MW(),scene:e,debug:!0,editor:{open:n}})}else{let{createGame2D:t}=await Bg(async()=>{let{createGame2D:e}=await Promise.resolve().then(()=>tS);return{createGame2D:e}},void 0,import.meta.url);await t({canvas:MW(),scene:e,debug:!0,editor:{open:n}})}}catch(e){jW&&(jW.style.visibility=`hidden`),(await NW()).showError(`${e instanceof Error?e.message:String(e)}\n\nRunning as the game needs your project's behaviors, which live in your app, not in this page. Start your own dev server with debug enabled and use the ☰ debug menu's "✎ edit this scene" — the switch works both ways from there, with every behavior loaded.`)}}NW().catch(e=>{let t=document.createElement(`div`);t.id=`error-banner`,t.style.cssText=`position:fixed;inset:0 0 auto 0;z-index:99;padding:10px 14px;background:#5b1a24;color:#ffd9df;font:13px ui-monospace,monospace`,t.textContent=e instanceof Error?e.message:String(e),document.body.appendChild(t)});export{R as i,Bg as n,dt as r,Pb as t};
|
|
10958
|
+
`,xU=new Map(yR.flatMap(e=>e.nodes.map(e=>[e.type,e.summary]))),SU=new Set,CU=null,wU=null,TU=null;function EU(e){wU=e}function DU(e){CU=e}function OU(e){TU=e}var kU=null,AU=null,jU=null;function MU(e){return e?e.includes(`Body`)||e.includes(`Area`)||e.includes(`Controller`)?`cat-body`:e===`NetworkSpawner`?`cat-net`:e.endsWith(`3D`)?`cat-3d`:e.endsWith(`2D`)||e===`Label`||e===`UILayer`?`cat-2d`:`cat-core`:`cat-core`}function NU(e,t){e.textContent=``;let n=document.createElement(`div`);n.className=`tree-row scene-row${t.selection===null&&t.selectedAsset===null&&t.selectedGroup===null&&!t.addingAsset&&!t.addingGroup?` selected`:``}`,n.textContent=`⚙ ${String(t.working.name??`scene`)}`,n.addEventListener(`click`,()=>t.select(null)),e.appendChild(n);let r=t.working.root;if(!r){let t=document.createElement(`div`);t.className=`muted-note explorer-empty`,t.textContent=`no root node — pick a type below and + to start the scene`,e.appendChild(t);return}LU(r,t.selection),e.appendChild(RU(r,[],t,``)),FU(e,t.selection)}var PU=null;function FU(e,t){let n=JSON.stringify(t);n!==PU&&(PU=n,e.querySelector(`.tree-row.selected`)?.scrollIntoView?.({block:`nearest`,inline:`nearest`}))}function IU(){PU=null}function LU(e,t){if(!t)return;let n=e,r=``;for(let e of t){r=r?`${r}/${n.name}`:String(n.name),SU.delete(r);let t=n.children?.[e];if(!t)return;n=t}}function RU(e,t,n,r){let i=r?`${r}/${e.name}`:String(e.name),a=(e.children?.length??0)>0,o=SU.has(i),s=document.createElement(`div`);s.className=`tree-branch`;let c=document.createElement(`div`);c.className=`tree-row${n.isSelected(t)?` selected`:``}`,c.draggable=t.length>0&&jU!==i;let l=document.createElement(`span`);l.className=`chevron${a?``:` leaf`}${o?` collapsed`:``}`,a?l.appendChild(FL()):l.textContent=`·`,a&&l.addEventListener(`click`,e=>{e.stopPropagation(),o?SU.delete(i):SU.add(i),n.select(n.selection)});let u=document.createElement(`span`);if(u.className=`tree-icon ${MU(e.type)}`,u.appendChild(PL(e.type)),u.title=e.type??`instance`,u.addEventListener(`click`,t=>{t.stopPropagation(),zU(u,e.type??`instance`)}),c.append(l,u),jU===i){let r=document.createElement(`input`);r.className=`rename-input`,r.value=e.name??``;let i=()=>{jU=null;let i=r.value.trim();if(i&&i!==e.name){let e=n.renameNode(t,i)??[];e.length>0&&TU?.(e)}else n.select(n.selection)};r.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Enter`&&i(),e.key===`Escape`&&(jU=null,n.select(n.selection))});for(let e of[`click`,`pointerdown`,`dblclick`,`mousedown`])r.addEventListener(e,e=>e.stopPropagation());r.addEventListener(`blur`,i),c.appendChild(r),queueMicrotask(()=>{r.focus(),r.select()})}else{let r=document.createElement(`span`);r.className=`tree-name`,r.textContent=e.name??`(unnamed)`,r.addEventListener(`dblclick`,e=>{e.stopPropagation(),jU=i,n.select(t)}),c.appendChild(r)}if(c.addEventListener(`click`,e=>{a&&!e.metaKey&&!e.ctrlKey&&(o?SU.delete(i):SU.add(i)),n.select(t,{toggle:e.metaKey||e.ctrlKey})}),c.addEventListener(`contextmenu`,e=>{e.preventDefault(),n.isSelected(t)||n.select(t),BU(e.clientX,e.clientY,n,t,i)}),YU(c,t,n),s.appendChild(c),a&&!o){let r=document.createElement(`div`);r.className=`tree-children`,(e.children??[]).forEach((e,a)=>{r.appendChild(RU(e,[...t,a],n,i))}),s.appendChild(r)}return s}function zU(e,t){GU();let n=document.createElement(`div`);n.className=`balloon floating`;let r=document.createElement(`span`);r.className=`balloon-title`,r.textContent=t,n.appendChild(r);let i=xU.get(t);if(i){let e=document.createElement(`span`);e.textContent=jL(i),n.appendChild(e)}document.body.appendChild(n);let a=e.getBoundingClientRect();n.style.left=`${Math.min(innerWidth-240,a.right+8)}px`,n.style.top=`${Math.max(8,a.top-6)}px`,KU(n)}function BU(e,t,n,r,i){GU();let a=n.allSelections(),o=a.length===1&&r.length>0,s=document.createElement(`div`);s.className=`context-menu floating`;let c=(e,t,n)=>{let r=document.createElement(`button`);r.type=`button`,r.className=`menu-item${n?.danger?` danger`:``}`,r.disabled=t===null;let i=document.createElement(`span`);if(i.textContent=e,r.appendChild(i),n?.kbd){let e=document.createElement(`kbd`);e.textContent=n.kbd,r.appendChild(e)}t&&r.addEventListener(`click`,()=>{GU(),t()}),s.appendChild(r)};c(`duplicate${a.length>1?` ×${a.length}`:``}`,()=>{for(let e of[...a].reverse())n.duplicateNode(e)}),c(`frame in view`,wU&&r.length>0?()=>{n.select(r),wU?.()}:null,{kbd:`F`}),c(`rename`,o?()=>{jU=i,n.select(r)}:null,{kbd:`dbl-click`}),s.appendChild(VU()),c(`cut`,r.length>0?()=>HU(n,!0):null),c(`copy`,r.length>0?()=>HU(n,!1):null),c(`paste as child${AU?` (${AU.nodes.length})`:``}`,AU?()=>UU(n,r):null),s.appendChild(VU()),c(`delete`,r.length>0?()=>(CU??(e=>n.removeNodes(e)))(a):null,{danger:!0}),document.body.appendChild(s),s.style.left=`${Math.min(innerWidth-200-8,e)}px`,s.style.top=`${Math.min(innerHeight-s.offsetHeight-8,t)}px`,KU(s)}function VU(){let e=document.createElement(`div`);return e.className=`menu-divider`,e}function HU(e,t){let n=e.allSelections().filter(e=>e.length>0).map(t=>e.nodeAt(t)).filter(e=>e!==null);AU={nodes:n.map(e=>JSON.parse(JSON.stringify(e))),cut:t?n:null}}function UU(e,t){if(AU){for(let n of AU.nodes)e.insertNode(n,t);if(AU.cut){let t=e.working.root,n=AU.cut.map(e=>WU(t,e)).filter(e=>e!==null);n.length>0&&e.removeNodes(n),AU={nodes:AU.nodes,cut:null}}}}function WU(e,t){if(e===t)return[];for(let[n,r]of(e.children??[]).entries()){let e=WU(r,t);if(e)return[n,...e]}return null}function GU(){for(let e of document.querySelectorAll(`.floating`))e.remove()}function KU(e){let t=r=>{e.contains(r.target)||(e.remove(),document.removeEventListener(`pointerdown`,t,!0),document.removeEventListener(`keydown`,n,!0))},n=r=>{r.key===`Escape`&&(e.remove(),document.removeEventListener(`pointerdown`,t,!0),document.removeEventListener(`keydown`,n,!0))};setTimeout(()=>{document.addEventListener(`pointerdown`,t,!0),document.addEventListener(`keydown`,n,!0)},0)}function qU(e,t){let n=t.getBoundingClientRect(),r=(e.clientY-n.top)/n.height;return r<.25?`before`:r>.75?`after`:`into`}function JU(e){e.classList.remove(`drop-into`,`drop-before`,`drop-after`)}function YU(e,t,n){e.addEventListener(`dragstart`,r=>{kU=n.isSelected(t)?n.allSelections():[t],r.dataTransfer?.setData(`text/plain`,``),r.dataTransfer&&(r.dataTransfer.effectAllowed=`move`),e.classList.add(`dragging`)}),e.addEventListener(`dragend`,()=>{kU=null,e.classList.remove(`dragging`)}),e.addEventListener(`dragover`,n=>{if(!kU||kU.some(e=>e.length<=t.length&&e.every((e,n)=>e===t[n])))return;n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect=`move`),JU(e);let r=t.length===0?`into`:qU(n,e);e.classList.add(`drop-${r}`)}),e.addEventListener(`dragleave`,()=>JU(e)),e.addEventListener(`drop`,r=>{if(JU(e),!kU)return;r.preventDefault();let i=t.length===0?`into`:qU(r,e),a=n.moveNodes(kU,t,i);kU=null,a?.[0]&&n.select(a[0])})}var XU={x:`#fb7185`,y:`#86efac`,z:`#7aa2ff`};function ZU(e,t,n){let r=t-e.origin.x,i=n-e.origin.y;if(Math.abs(r)<=e.centerSize&&Math.abs(i)<=e.centerSize)return{kind:`center`};for(let t of e.axes){let e=t.sx*t.sx+t.sy*t.sy;if(e<1)continue;let n=Math.max(0,Math.min(1,(r*t.sx+i*t.sy)/e)),a=r-t.sx*n,o=i-t.sy*n;if(n>.25&&Math.hypot(a,o)<=8)return{kind:`axis`,axis:t.axis}}return null}function QU(e,t,n){let r=e.sx*e.sx+e.sy*e.sy;return r<1?0:(t*e.sx+n*e.sy)/r*e.worldPerUnit}function $U(e,t,n,r=!1){let{origin:i,axes:a,centerSize:o}=t;for(let t of a){let a=n?.kind===`axis`&&n.axis===t.axis;e.strokeStyle=t.color,e.fillStyle=t.color,e.globalAlpha=a?1:.9,e.lineWidth=a?3:2,e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(i.x+t.sx,i.y+t.sy),e.stroke();let o=Math.hypot(t.sx,t.sy)||1,s=t.sx/o,c=t.sy/o,l=i.x+t.sx,u=i.y+t.sy;e.beginPath(),r?e.rect(l-5,u-5,10,10):(e.moveTo(l+s*9,u+c*9),e.lineTo(l-c*4.5,u+s*4.5),e.lineTo(l+c*4.5,u-s*4.5),e.closePath()),e.fill(),e.font=`700 9px Inter, system-ui, sans-serif`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(t.axis.toUpperCase(),l+s*18,u+c*18)}let s=n?.kind===`center`;e.globalAlpha=s?1:.95,e.fillStyle=s?`#ffffff`:`#e2e6f0`,e.strokeStyle=`#0b0d14`,e.lineWidth=1.5,e.beginPath(),e.rect(i.x-o,i.y-o,o*2,o*2),e.fill(),e.stroke(),e.globalAlpha=1}function eW(e,t,n){return Math.atan2(n-e.y,t-e.x)*180/Math.PI}function tW(e,t){let n=t-e;for(;n>180;)n-=360;for(;n<=-180;)n+=360;return n}function nW(e,t,n,r){let i=null,a=r;for(let r of e)for(let e of r.points){let o=Math.hypot(t-e.x,n-e.y);o<a&&(a=o,i=r.axis)}return i}function rW(e,t,n){for(let r of t){if(r.points.length<2)continue;let t=n===r.axis;e.strokeStyle=XU[r.axis],e.globalAlpha=t?1:.75,e.lineWidth=t?3:2,e.beginPath();let i=r.points[0];e.moveTo(i.x,i.y);for(let t of r.points.slice(1))e.lineTo(t.x,t.y);e.closePath(),e.stroke()}e.globalAlpha=1}function iW(e,t,n,r){e.font=`600 11px ui-monospace, Menlo, monospace`;let i=e.measureText(r).width+14;e.fillStyle=`rgba(16, 19, 29, 0.92)`,e.strokeStyle=`rgba(110, 231, 220, 0.5)`,e.lineWidth=1,e.beginPath(),e.roundRect(t+14,n-26,i,20,5),e.fill(),e.stroke(),e.fillStyle=`#6ee7dc`,e.textAlign=`left`,e.textBaseline=`middle`,e.fillText(r,t+21,n-16)}var aW=class{engine;editCanvas;overlay;playCanvas;cb;editUiHost=null;playUiHost=null;renderer2d=null;renderer3d=null;rendererDim=null;orbit={yaw:.6,pitch:.35,dist:10,target:[0,1,0]};pathOf=new Map;reindexNeeded=!1;nodeAtPath=new Map;selectedPath=null;paintHandler=null;extraPaths=[];hoveredNode=null;hoveredGizmo=null;lastGood=null;lastAppliedKey=null;playEngine=null;playRenderer=null;playPhysics=null;setPaintHandler(e){this.paintHandler=e}get playing(){return this.playEngine!==null}constructor(e,t,n,r){this.editCanvas=e,this.overlay=t,this.playCanvas=n,this.cb=r;let i=this;this.engine=new Hn({scheduler:e=>{let t=0,n=performance.now(),r=requestAnimationFrame(function a(o){t+=.001;let s=Math.min(.1,(o-n)/1e3);n=o;try{e(t),i.tickAmbientPreviews(s),i.reportAssetErrors()}catch(e){console.error(`incanto-editor viewport:`,e)}r=requestAnimationFrame(a)});return()=>cancelAnimationFrame(r)}}),this.editUiHost=this.makeUiHost(e.parentElement,4),this.playUiHost=this.makeUiHost(n.parentElement,5),this.engine.uiHost=this.editUiHost,this.engine.start(),this.engine.updated.connect(()=>this.drawOverlay());let a=e=>{e.key===`Shift`&&(this.shiftHeld=!0)},o=e=>{e.key===`Shift`&&(this.shiftHeld=!1)};window.addEventListener(`keydown`,a),window.addEventListener(`keyup`,o),this.cleanups.push(()=>{window.removeEventListener(`keydown`,a),window.removeEventListener(`keyup`,o)}),this.bindPointer()}cleanups=[];makeUiHost(e,t){if(!e)return null;let n=document.createElement(`div`);return n.style.cssText=`position:absolute;inset:0;pointer-events:none;z-index:${t};`,e.appendChild(n),this.cleanups.push(()=>n.remove()),n}dispose(){this.stop(),this.editPhysics?.dispose(),this.editPhysics=null,this.engine.stop(),this.engine.dispose(),this.renderer2d?.dispose(),this.renderer3d?.dispose(),this.renderer2d=null,this.renderer3d=null;for(let e of this.cleanups.splice(0))e()}setEditCamera(e,t){let n=(e[0]??0)-(t[0]??0),r=(e[1]??0)-(t[1]??0),i=(e[2]??0)-(t[2]??0),a=Math.hypot(n,r,i);a>.01&&(this.orbit.target=[t[0]??0,t[1]??0,t[2]??0],this.orbit.dist=Math.min(800,Math.max(.3,a)),this.orbit.yaw=Math.atan2(n,i),this.orbit.pitch=Math.asin(Math.max(-.99,Math.min(.99,r/a))),this.syncOrbit())}editCamera(){let{pos:e}=this.orbitVectors();return{position:[e.x,e.y,e.z],target:[...this.orbit.target]}}apply(e){e.root||(e={...e,root:{name:`__empty`,type:(e.dimension??`2d`)===`3d`?`Node3D`:`Node2D`}});let t=JSON.stringify(e);if(t===this.lastAppliedKey&&this.rendererDim===(e.dimension??`2d`))return null;let n;try{let t=structuredClone(e);SW(t),n=Ai(t,{stubAllBehaviors:!0})}catch(e){return e instanceof Error?e.message:String(e)}this.lastGood=e,this.lastAppliedKey=t;let r=e.dimension??`2d`;if(this.rendererDim!==r){if(this.renderer2d?.dispose(),this.renderer3d?.dispose(),this.renderer2d=null,this.renderer3d=null,r===`2d`)this.renderer2d=new Vx({canvas:this.editCanvas,engine:this.engine}),this.renderer2d.ignoreStatic=!0,this.renderer2d.viewOverride=this.defaultView(e);else{this.renderer3d=new JI({canvas:this.editCanvas,engine:this.engine}),this.renderer3d.ignoreStatic=!0;let t=vW(e.root);if(t){let[e,n,r]=t;this.orbit.dist=Math.max(2,Math.hypot(e,n,r)),this.orbit.yaw=Math.atan2(e,r),this.orbit.pitch=Math.asin(Math.max(-.99,Math.min(.99,n/this.orbit.dist))),this.orbit.target=[0,Math.min(2,Math.abs(n)/2),0]}this.syncOrbit()}this.rendererDim=r}return this.engine.setScene(n),this.indexTree(n.root),this.hoveredNode=null,null}setSelection(e,t=[]){this.selectedPath=e,this.extraPaths=t}validate(e){if(!e.root)return null;try{let t=structuredClone(e);return SW(t),Ai(t,{stubAllBehaviors:!0}),null}catch(e){return e instanceof Error?e.message:String(e)}}defaultView(e){let t=yW(e.root);if(t)return{cx:t[0],cy:t[1],zoom:1};let n=this.editCanvas.clientWidth||960,r=this.editCanvas.clientHeight||540;return{cx:n/2,cy:r/2,zoom:1}}indexTree(e){this.pathOf=new Map,this.nodeAtPath=new Map;let t=(e,n)=>{this.pathOf.set(e,n),this.nodeAtPath.set(n.join(`.`),e),e.children.forEach((e,r)=>{t(e,[...n,r])})};t(e,[])}liveSelected(){return this.selectedPath===null?null:this.nodeAtPath.get(this.selectedPath.join(`.`))??null}patchProp(e,t,n,r){if(this.playing)return!1;let i=this.nodeAtPath.get(t.join(`.`));if(!i)return!1;try{i[n]=r===void 0?void 0:structuredClone(r)}catch{return!1}return this.reindexNeeded=!0,this.lastAppliedKey=JSON.stringify(e),!0}gizmoActive=null;gizmoMode=`move`;activeRing=null;readout=null;cancelActiveDrag=()=>{};shiftHeld=!1;get showColliders(){return this.collidersOn}set showColliders(e){this.collidersOn=e,this.editPhysics&&(this.editPhysics.debugDraw=e),e&&this.ensureOutlinePhysics()}collidersOn=!0;editPhysics=null;outlinePending=null;async ensureOutlinePhysics(){if(this.editPhysics||this.outlinePending)return this.outlinePending??void 0;let e=this.rendererDim;if(e)return this.outlinePending=(async()=>{try{if(e===`2d`){let{enablePhysics2D:e}=await Vg(async()=>{let{enablePhysics2D:e}=await Promise.resolve().then(()=>tS);return{enablePhysics2D:e}},void 0,import.meta.url),t=await e(this.engine,{simulate:!1});t.debugDraw=this.collidersOn,this.editPhysics=t}else{let{enablePhysics3D:e}=await Vg(async()=>{let{enablePhysics3D:e}=await Promise.resolve().then(()=>dL);return{enablePhysics3D:e}},void 0,import.meta.url),t=await e(this.engine,{simulate:!1});t.debugDraw=this.collidersOn,this.editPhysics=t}}catch(e){console.warn(`[incanto] collider outlines unavailable:`,e)}finally{this.outlinePending=null}})(),this.outlinePending}get mode(){return this.gizmoMode}setMode(e){this.gizmoMode=e,this.cb.onModeChanged(e)}screen2D(e){let t=_W(e);return this.renderer2d?this.renderer2d.isUiNode(e)?this.renderer2d.screenFromUi(t.x,t.y):this.renderer2d.screenFromWorld(t.x,t.y):t}point2D(e,t,n){return this.renderer2d?this.renderer2d.isUiNode(e)?this.renderer2d.uiFromScreen(t,n):this.renderer2d.worldFromScreen(t,n):{x:t,y:n}}gizmoLayout(){let e=this.liveSelected();if(!e)return null;if(this.rendererDim===`2d`&&this.renderer2d){let t=e.position;if(!Array.isArray(t))return null;let n=this.screen2D(e),r=this.renderer2d.isUiNode(e)?1:this.renderer2d.view().zoom;return{origin:n,centerSize:7,axes:[{axis:`x`,sx:64,sy:0,worldPerUnit:64/r,color:XU.x},{axis:`y`,sx:0,sy:64,worldPerUnit:64/r,color:XU.y}]}}if(this.rendererDim===`3d`&&this.renderer3d){let t=e._object3D,n=e.position;if(!t||!Array.isArray(n))return null;t.getWorldPosition(dW);let r=this.renderer3d.screenFromWorld(dW.x,dW.y,dW.z);if(r.behind)return null;let i=[],a=this.orbit.dist,o=Math.max(.2,a*.18);for(let[e,t]of[[`x`,[1,0,0]],[`y`,[0,1,0]],[`z`,[0,0,1]]]){let n=this.renderer3d.screenFromWorld(dW.x+t[0]*o,dW.y+t[1]*o,dW.z+t[2]*o);n.behind||i.push({axis:e,sx:n.x-r.x,sy:n.y-r.y,worldPerUnit:o,color:XU[e]})}return{origin:{x:r.x,y:r.y},centerSize:7,axes:i}}return null}ringLayout(){let e=this.liveSelected();if(!e)return null;if(this.rendererDim===`2d`&&this.renderer2d){let t=this.screen2D(e),n=[];for(let e=0;e<48;e++){let r=e/48*Math.PI*2;n.push({x:t.x+56*Math.cos(r),y:t.y+56*Math.sin(r)})}return{origin:t,rings:[{axis:`z`,points:n}]}}if(this.rendererDim===`3d`&&this.renderer3d){let t=e._object3D;if(!t)return null;t.getWorldPosition(dW);let n={x:dW.x,y:dW.y,z:dW.z},r=this.renderer3d.screenFromWorld(n.x,n.y,n.z);if(r.behind)return null;let i=Math.max(.2,this.orbit.dist*.16),a=[];for(let e of[`x`,`y`,`z`]){let t=[];for(let r=0;r<48;r++){let a=r/48*Math.PI*2,o=Math.cos(a)*i,s=Math.sin(a)*i,c=e===`x`?this.renderer3d.screenFromWorld(n.x,n.y+o,n.z+s):e===`y`?this.renderer3d.screenFromWorld(n.x+o,n.y,n.z+s):this.renderer3d.screenFromWorld(n.x+o,n.y+s,n.z);c.behind||t.push({x:c.x,y:c.y})}a.push({axis:e,points:t})}return{origin:{x:r.x,y:r.y},rings:a}}return null}orbitVectors(){let{yaw:e,pitch:t,dist:n,target:r}=this.orbit,i=Math.cos(t),a=new W(r[0]+n*i*Math.sin(e),r[1]+n*Math.sin(t),r[2]+n*i*Math.cos(e)),o=new W(r[0],r[1],r[2]).sub(a).normalize(),s=new W().crossVectors(o,sW).normalize();return{pos:a,right:s,up:new W().crossVectors(s,o).normalize(),forward:o}}syncOrbit(){if(!this.renderer3d)return;let{pos:e}=this.orbitVectors();this.renderer3d.viewOverride={position:[e.x,e.y,e.z],target:[...this.orbit.target]}}gameView(){if(this.rendererDim===`3d`&&this.renderer3d){let e=null;for(let[t]of this.pathOf)if(t instanceof Bk&&(t.current||!e)&&(e=t,t.current))break;let t=e?e._ensureObject3D():null;if(t){t.getWorldPosition(cW),lW.set(0,0,-1).applyQuaternion(t.getWorldQuaternion(uW));let e=Math.min(40,Math.max(3,this.orbit.dist));this.orbit.target=[cW.x+lW.x*e,cW.y+lW.y*e,cW.z+lW.z*e],this.orbit.dist=e,this.orbit.yaw=Math.atan2(-lW.x,-lW.z),this.orbit.pitch=Math.asin(Math.max(-.99,Math.min(.99,-lW.y)))}this.renderer3d.viewOverride=null;return}this.renderer2d&&(this.renderer2d.viewOverride=null)}snapView(e,t){e===`y`?(this.orbit.pitch=t*1.45,this.orbit.yaw=0):(this.orbit.pitch=0,this.orbit.yaw=e===`z`?t===1?0:Math.PI:Math.PI/2*t),this.syncOrbit()}gizmoCenter(){return{x:this.overlay.clientWidth-58,y:58,r:36}}gizmoHandles(){let{right:e,up:t,forward:n}=this.orbitVectors(),r=this.gizmoCenter(),i=[];for(let[a,o]of[[`x`,new W(1,0,0)],[`y`,new W(0,1,0)],[`z`,new W(0,0,1)]])for(let s of[1,-1]){let c=o.clone().multiplyScalar(s);i.push({axis:a,sign:s,x:r.x+c.dot(e)*26,y:r.y-c.dot(t)*26,z:-c.dot(n)})}return i.sort((e,t)=>e.z-t.z)}gizmoHit(e,t){let n=this.gizmoCenter();if(Math.hypot(e-n.x,t-n.y)>n.r+8)return null;let r=null,i=14;for(let n of this.gizmoHandles()){let a=Math.hypot(e-n.x,t-n.y);a<i&&(i=a,r={axis:n.axis,sign:n.sign})}return r??{axis:`z`,sign:1}}gizmoHandleAt(e,t){let n=this.gizmoCenter();if(Math.hypot(e-n.x,t-n.y)>n.r+8)return null;let r=null,i=12;for(let n of this.gizmoHandles()){let a=Math.hypot(e-n.x,t-n.y);a<i&&(i=a,r={axis:n.axis,sign:n.sign})}return r}assetErrorSignature=``;reportAssetErrors(){let e=this.assetErrors(),t=e.map(e=>e.ref).join(`|`);t!==this.assetErrorSignature&&(this.assetErrorSignature=t,this.cb.onAssetErrors(e))}assetErrors(){return this.renderer2d?.assets.errors()??this.renderer3d?.assets.errors()??[]}tickAmbientPreviews(e){if(!this.playing)for(let[t]of this.pathOf)(t instanceof QM||t instanceof ux||t instanceof nN||t instanceof Uv||t instanceof _M)&&t.update(e)}modelAnimationsAt(e){let t=this.nodeAtPath.get(e.join(`.`));return t instanceof QM?t.availableAnimations():[]}boneNamesAt(e,t){let n=this.nodeAtPath.get(e.join(`.`));if(!n||t===``)return[];let r=n.getNodeOrNull(t);return r instanceof QM?r.boneNames():[]}drawOverlay(){if(this.reindexNeeded){this.reindexNeeded=!1;let e=this.engine.scene?.tree.root;e&&this.indexTree(e)}let e=this.overlay.getContext(`2d`);if(!e)return;let t=this.overlay.clientWidth,n=this.overlay.clientHeight,r=Math.min(devicePixelRatio||1,2);if((this.overlay.width!==t*r||this.overlay.height!==n*r)&&(this.overlay.width=t*r,this.overlay.height=n*r),e.setTransform(r,0,0,r,0,0),e.clearRect(0,0,t,n),this.playing)return;if(this.rendererDim===`3d`){this.drawGizmo(e),this.drawModeGizmo(e),this.readout&&iW(e,this.readout.x,this.readout.y,this.readout.text);return}if(!this.renderer2d)return;if(this.drawAxes2D(e),this.hoveredNode&&this.hoveredNode!==this.liveSelected()){let t=this.renderer2d.boundsOf(this.hoveredNode);t&&(e.strokeStyle=`rgba(110, 231, 220, 0.45)`,e.lineWidth=1.5,e.setLineDash([]),e.strokeRect(t.x,t.y,t.w,t.h))}for(let t of this.extraPaths){let n=this.nodeAtPath.get(t.join(`.`)),r=n?this.renderer2d.boundsOf(n):null;r&&(e.strokeStyle=`rgba(110, 231, 220, 0.7)`,e.lineWidth=1.5,e.setLineDash([4,3]),e.strokeRect(r.x-2,r.y-2,r.w+4,r.h+4),e.setLineDash([]))}let i=this.liveSelected();if(i){let t=this.renderer2d.boundsOf(i)??this.pointBounds(i);if(t){e.strokeStyle=`#6ee7dc`,e.lineWidth=2,e.setLineDash([6,4]),e.lineDashOffset=-(performance.now()/50%10),e.strokeRect(t.x-2,t.y-2,t.w+4,t.h+4),e.setLineDash([]),e.fillStyle=`#6ee7dc`;for(let[n,r]of[[t.x-2,t.y-2],[t.x+t.w+2,t.y-2],[t.x-2,t.y+t.h+2],[t.x+t.w+2,t.y+t.h+2]])e.fillRect(n-3,r-3,6,6)}}this.drawModeGizmo(e),this.readout&&iW(e,this.readout.x,this.readout.y,this.readout.text)}drawModeGizmo(e){if(this.gizmoMode===`rotate`){let t=this.ringLayout();t&&rW(e,t.rings,this.activeRing);return}let t=this.gizmoLayout();t&&$U(e,t,this.gizmoActive,this.gizmoMode===`scale`)}pointBounds(e){if(!this.renderer2d)return null;let t=e.position;if(!Array.isArray(t))return null;let n=this.screen2D(e);return{x:n.x-12,y:n.y-12,w:24,h:24}}drawGizmo(e){let t=this.gizmoCenter();e.beginPath(),e.arc(t.x,t.y,t.r,0,Math.PI*2),e.fillStyle=`rgba(16, 19, 29, 0.72)`,e.fill(),e.strokeStyle=`rgba(52, 60, 84, 0.9)`,e.lineWidth=1,e.stroke();let n={x:`#fb7185`,y:`#86efac`,z:`#7aa2ff`},r={x1:`right`,"x-1":`left`,y1:`top`,"y-1":`bottom`,z1:`front`,"z-1":`back`};for(let r of this.gizmoHandles()){let i=this.hoveredGizmo?.axis===r.axis&&this.hoveredGizmo?.sign===r.sign,a=n[r.axis],o=(r.z+1)/2;e.globalAlpha=i?1:.45+o*.55,e.strokeStyle=a,e.lineWidth=1.5,e.beginPath(),e.moveTo(t.x,t.y),e.lineTo(r.x,r.y),e.stroke(),e.beginPath(),e.arc(r.x,r.y,(r.sign===1?7:5)+(i?2:0),0,Math.PI*2),r.sign===1?(e.fillStyle=a,e.fill(),e.fillStyle=`#0b0d14`,e.font=`700 8px ui-monospace, monospace`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(r.axis.toUpperCase(),r.x,r.y+.5)):(e.fillStyle=`rgba(16, 19, 29, 0.9)`,e.fill(),e.stroke())}if(e.globalAlpha=1,this.hoveredGizmo){let n=r[`${this.hoveredGizmo.axis}${this.hoveredGizmo.sign}`];e.fillStyle=`#9aa3bd`,e.font=`600 10px Inter, system-ui, sans-serif`,e.textAlign=`center`,e.textBaseline=`bottom`,e.fillText(`${n} view`,t.x,t.y-t.r-6)}}drawAxes2D(e){let t=this.gizmoCenter();e.save(),e.shadowColor=`rgba(0, 0, 0, 0.25)`,e.shadowBlur=10,e.shadowOffsetY=2,e.beginPath(),e.arc(t.x,t.y,31,0,Math.PI*2),e.fillStyle=`rgba(13, 16, 24, 0.42)`,e.fill(),e.shadowColor=`transparent`,e.strokeStyle=`rgba(255, 255, 255, 0.16)`,e.lineWidth=1,e.stroke();let n=t.x-9,r=t.y-9;e.lineCap=`round`;let i=(t,i,a,o)=>{let s=n+t*21,c=r+i*21,l=e.createLinearGradient(n,r,s,c);l.addColorStop(0,`${a}55`),l.addColorStop(1,a),e.strokeStyle=l,e.lineWidth=2,e.beginPath(),e.moveTo(n,r),e.lineTo(s,c),e.stroke(),e.beginPath(),e.arc(s,c,6.5,0,Math.PI*2),e.fillStyle=a,e.fill(),e.font=`800 8px Inter, system-ui, sans-serif`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillStyle=`#0b0d14`,e.fillText(o,s,c+.5)};i(1,0,`#fb7185`,`X`),i(0,1,`#86efac`,`Y`),e.beginPath(),e.arc(n,r,2.5,0,Math.PI*2),e.fillStyle=`#e2e6f0`,e.fill(),e.restore()}bindPointer(){let e=this.overlay,t=null,n=null,r=!1,i=null,a=null,o=null,s=null,c=null,l=t=>{let n=this.ringLayout();if(!n)return!1;let r=nW(n.rings,t.offsetX,t.offsetY,9);if(!r)return!1;let i=this.liveSelected();if(!i)return!1;e.setPointerCapture(t.pointerId);let a=i.rotation,o=1;if(this.rendererDim===`3d`&&this.renderer3d){let{forward:e}=this.renderer3d.cameraBasis();o=(r===`x`?e.x:r===`y`?e.y:e.z)>0?1:-1}return c={axis:r,node:i,origin:n.origin,startAngle:eW(n.origin,t.offsetX,t.offsetY),startRotation:Array.isArray(a)?[...a]:a??0,sign:o},this.activeRing=r,!0},u=e=>{if(!c)return;let{axis:t,node:n,origin:r,startAngle:i,startRotation:a,sign:o}=c,s=tW(i,eW(r,e.offsetX,e.offsetY))*o,l=e.shiftKey||this.shiftHeld?15:null,u=e=>{let t=e+s;return l?Math.round(t/l)*l:Math.round(t*10)/10},d;if(Array.isArray(a)){let e={x:0,y:1,z:2}[t],r=[...a];r[e]=u(a[e]??0),d=r[e],n.rotation=r}else{let e=u(a);d=e,n.rotation=e}this.readout={x:e.offsetX,y:e.offsetY,text:`${d}°${l?` ⌁15°`:``}`}},d=e=>{if(!c)return;let{node:t,startRotation:n}=c;if(!e)t.rotation=n;else{let e=this.pathOf.get(t),n=t.rotation;e!==void 0&&n!==void 0&&(Array.isArray(n)?this.cb.onNodeRotated3D(e,[n[0]??0,n[1]??0,n[2]??0]):this.cb.onNodeRotated2D(e,n))}c=null,this.activeRing=null,this.readout=null};this.cancelActiveDrag=()=>{d(!1),s&&(s.node.position=s.startPos,s.node.scale=s.startScale,s=null,this.gizmoActive=null,this.readout=null)};let f=t=>{if(this.gizmoMode===`rotate`)return l(t);let n=this.gizmoLayout();if(!n)return!1;let r=ZU(n,t.offsetX,t.offsetY);if(!r)return!1;let i=this.liveSelected();if(!i)return!1;e.setPointerCapture(t.pointerId);let a=[...i.position??[]],o=[...i.scale??[]];return s={hit:r,mode:this.gizmoMode===`scale`||t.button===2?`scale`:`move`,startX:t.offsetX,startY:t.offsetY,layout:n,node:i,startPos:a,startScale:o},this.gizmoActive=r,!0},p=e=>{if(!s)return;let{hit:t,mode:n,layout:r,node:i,startPos:a,startScale:o}=s,c=e.offsetX-s.startX,l=e.offsetY-s.startY,u=this.rendererDim===`3d`,d={x:0,y:1,z:2},f=e.shiftKey||this.shiftHeld,p=f?u?.5:10:null,m=f?.25:null,h=e=>p?Math.round(e/p)*p:e,g=e=>m?Math.max(m,Math.round(e/m)*m):e;if(n===`scale`){let n=Math.max(.05,1+(c-l)*.005),r=[...o];if(t.kind===`axis`)r[d[t.axis]]=oW(g((o[d[t.axis]]??1)*n));else for(let e=0;e<r.length;e++)r[e]=oW(g((o[e]??1)*n));i.scale=r,this.readout={x:e.offsetX,y:e.offsetY,text:`×${r.map(e=>oW(e)).join(`, `)}`};return}let _=[...a];if(t.kind===`axis`){let e=r.axes.find(e=>e.axis===t.axis);if(!e)return;let n=QU(e,c,l);if(u)_[d[t.axis]]=oW(h((a[d[t.axis]]??0)+n));else{let e=hW(i,t.axis===`x`?n:0,t.axis===`y`?n:0),r=t.axis===`x`?e.x:e.y;_[d[t.axis]]=Math.round(h((a[d[t.axis]]??0)+r))}}else if(u&&this.renderer3d){let{right:e,up:t}=this.renderer3d.cameraBasis(),n=this.orbit.dist*.0016;_[0]=oW(h((a[0]??0)+(e.x*c-t.x*l)*n)),_[1]=oW(h((a[1]??0)+(e.y*c-t.y*l)*n)),_[2]=oW(h((a[2]??0)+(e.z*c-t.z*l)*n))}else if(this.renderer2d){let e=this.renderer2d.view(),t=hW(i,c/e.zoom,l/e.zoom);_[0]=Math.round(h((a[0]??0)+t.x)),_[1]=Math.round(h((a[1]??0)+t.y))}i.position=_,this.readout={x:e.offsetX,y:e.offsetY,text:`[${_.map(e=>oW(e)).join(`, `)}]`}},m=()=>{if(!s)return;let{node:e,mode:t}=s,n=this.pathOf.get(e);if(n)if(t===`scale`){let t=e.scale??[];this.rendererDim===`3d`?this.cb.onNodeScaled3D(n,[t[0]??1,t[1]??1,t[2]??1]):this.cb.onNodeScaled(n,[t[0]??1,t[1]??1])}else{let t=e.position??[];this.rendererDim===`3d`?this.cb.onNodeMoved3D(n,[t[0]??0,t[1]??0,t[2]??0]):this.cb.onNodeMoved(n,[t[0]??0,t[1]??0])}s=null,this.gizmoActive=null};e.addEventListener(`pointerdown`,s=>{if(this.playing||f(s))return;if(this.rendererDim===`3d`){let t=this.gizmoHit(s.offsetX,s.offsetY);if(t){this.snapView(t.axis,t.sign);return}e.setPointerCapture(s.pointerId),s.button===1||s.button===2||s.shiftKey?a={x:s.offsetX,y:s.offsetY,target:[...this.orbit.target]}:(i={x:s.offsetX,y:s.offsetY,yaw:this.orbit.yaw,pitch:this.orbit.pitch},o={x:s.offsetX,y:s.offsetY,toggle:s.ctrlKey||s.metaKey});return}if(!this.renderer2d)return;if(e.setPointerCapture(s.pointerId),s.button===1||s.button===2||s.shiftKey){let e=this.renderer2d.view();n={startX:s.offsetX,startY:s.offsetY,cx:e.cx,cy:e.cy};return}if(this.paintHandler&&s.button===0){let e=this.renderer2d.worldFromScreen(s.offsetX,s.offsetY);this.paintHandler(e.x,e.y,!0),r=!0;return}let c=this.renderer2d.pick(s.offsetX,s.offsetY),l=c?this.pathOf.get(c)??null:null;if(this.cb.onPick(l,{toggle:s.ctrlKey||s.metaKey}),this.selectedPath=l,c&&l&&Array.isArray(c.position)){let e=c.position;t={node:c,startWorld:this.point2D(c,s.offsetX,s.offsetY),startPos:[e[0]??0,e[1]??0]}}}),e.addEventListener(`pointermove`,o=>{if(!this.playing){if(c){u(o);return}if(s){p(o);return}if(this.rendererDim===`3d`){if(!i&&!a?(this.hoveredGizmo=this.gizmoHandleAt(o.offsetX,o.offsetY),e.style.cursor=this.hoveredGizmo?`pointer`:`grab`):e.style.cursor=`grabbing`,i)this.orbit.yaw=i.yaw-(o.offsetX-i.x)*.006,this.orbit.pitch=Math.max(-1.5,Math.min(1.5,i.pitch+(o.offsetY-i.y)*.006)),this.syncOrbit();else if(a){let{right:e,up:t}=this.orbitVectors(),n=this.orbit.dist*.0016,r=(o.offsetX-a.x)*n,i=(o.offsetY-a.y)*n;this.orbit.target=[a.target[0]-e.x*r+t.x*i,a.target[1]-e.y*r+t.y*i,a.target[2]-e.z*r+t.z*i],this.syncOrbit()}return}if(this.renderer2d){if(e.style.cursor=`crosshair`,r&&this.paintHandler){let e=this.renderer2d.worldFromScreen(o.offsetX,o.offsetY);this.paintHandler(e.x,e.y,!1);return}if(n){let e=this.renderer2d.view();this.renderer2d.viewOverride={cx:n.cx-(o.offsetX-n.startX)/e.zoom,cy:n.cy-(o.offsetY-n.startY)/e.zoom,zoom:e.zoom};return}if(t){let e=this.point2D(t.node,o.offsetX,o.offsetY),n=hW(t.node,e.x-t.startWorld.x,e.y-t.startWorld.y),r=Math.round(t.startPos[0]+n.x),i=Math.round(t.startPos[1]+n.y);t.node.position=[r,i];return}this.hoveredNode=this.renderer2d.pick(o.offsetX,o.offsetY)}}});let h=e=>{if(r=!1,d(!0),m(),this.readout=null,o&&e&&this.renderer3d&&Math.hypot(e.offsetX-o.x,e.offsetY-o.y)<4){let e=this.renderer3d.pick(o.x,o.y),t=e?this.pathOf.get(e)??null:null;t&&(this.cb.onPick(t,{toggle:o.toggle}),this.selectedPath=t)}if(o=null,i=null,a=null,t){let e=this.pathOf.get(t.node),n=t.node.position;e&&(n[0]!==t.startPos[0]||n[1]!==t.startPos[1])&&this.cb.onNodeMoved(e,[n[0]??0,n[1]??0]),t=null}n=null};e.addEventListener(`pointerup`,h),e.addEventListener(`pointercancel`,h),e.addEventListener(`contextmenu`,e=>e.preventDefault()),e.addEventListener(`dblclick`,e=>{if(this.playing)return;let t=this.rendererDim===`3d`?this.renderer3d?.pick(e.offsetX,e.offsetY)??null:this.renderer2d?.pick(e.offsetX,e.offsetY)??null,n=t?this.pathOf.get(t)??null:null;n&&(this.cb.onPick(n,{toggle:e.ctrlKey||e.metaKey}),this.selectedPath=n)}),e.addEventListener(`wheel`,e=>{if(this.playing)return;e.preventDefault();let t=e.deltaY<0?1.1:1/1.1;if(this.rendererDim===`3d`){this.orbit.dist=Math.max(.3,Math.min(800,this.orbit.dist/t)),this.syncOrbit();return}if(!this.renderer2d)return;let n=this.liveSelected();if(e.altKey&&n&&Array.isArray(n.scale)){let e=n.scale,r=[Math.round((e[0]??1)*t*100)/100,Math.round((e[1]??1)*t*100)/100];n.scale=r;let i=this.pathOf.get(n);i&&this.cb.onNodeScaled(i,r);return}let r=this.renderer2d.view(),i=this.renderer2d.worldFromScreen(e.offsetX,e.offsetY),a=Math.min(8,Math.max(.1,r.zoom*t));this.renderer2d.viewOverride={cx:i.x-(e.offsetX-r.w/2)/a,cy:i.y-(e.offsetY-r.h/2)/a,zoom:a}},{passive:!1})}zoomToFit(){let e=this.liveSelected();if(this.rendererDim===`3d`){let t=new Xc;for(let[n]of this.pathOf){if(e&&n!==e&&!gW(n,e))continue;let r=n._object3D;r&&(t.expandByObject(r),t.expandByPoint(r.getWorldPosition(dW)))}if(t.isEmpty()&&e){let t=e._object3D,n=t?t.getWorldPosition(dW):null;this.orbit.target=n?[n.x,n.y,n.z]:[0,1,0],this.orbit.dist=6}else if(t.isEmpty())this.orbit.target=[0,1,0],this.orbit.dist=10;else{let e=t.getCenter(new W),n=t.getSize(new W);this.orbit.target=[e.x,e.y,e.z],this.orbit.dist=Math.max(2.5,n.length()*.85)}this.syncOrbit();return}if(!this.renderer2d)return;let t=this.editCanvas.clientWidth||960,n=this.editCanvas.clientHeight||540,r=1/0,i=1/0,a=-1/0,o=-1/0;for(let[t]of this.pathOf){if(e&&t!==e&&!gW(t,e))continue;let n=t.position;if(!Array.isArray(n))continue;let s=_W(t);r=Math.min(r,s.x),i=Math.min(i,s.y),a=Math.max(a,s.x),o=Math.max(o,s.y)}if(!Number.isFinite(r))return;let s=(r+a)/2,c=(i+o)/2,l=e?600:200,u=Math.max(a-r+l,l),d=Math.max(o-i+l,l),f=Math.min(2,Math.min(t/u,n/d));this.renderer2d.viewOverride={cx:s,cy:c,zoom:f}}async play(e){if(this.playing)return null;let t=structuredClone(e);SW(t);let n;try{n=Ai(t,{stubAllBehaviors:!0,declareConnectionSignals:!0})}catch(e){return e instanceof Error?e.message:String(e)}let r=new Hn;r.uiHost=this.playUiHost,this.editUiHost&&(this.editUiHost.style.display=`none`),r.setScene(n),r.input.attachKeyboard(window),this.playCanvas.hidden=!1;let i=e.dimension??`2d`;try{if(i===`2d`){this.playRenderer=new Vx({canvas:this.playCanvas,engine:r});let{enablePhysics2D:e}=await Vg(async()=>{let{enablePhysics2D:e}=await Promise.resolve().then(()=>tS);return{enablePhysics2D:e}},void 0,import.meta.url),t=await e(r);t.debugDraw=this.showColliders,this.playPhysics=t}else{this.playRenderer=new JI({canvas:this.playCanvas,engine:r,assets:this.renderer3d?.assets});let{enablePhysics3D:e}=await Vg(async()=>{let{enablePhysics3D:e}=await Promise.resolve().then(()=>dL);return{enablePhysics3D:e}},void 0,import.meta.url),t=await e(r);t.debugDraw=this.showColliders,this.playPhysics=t}}catch(e){return this.stop(),e instanceof Error?e.message:String(e)}return r.start(),this.playEngine=r,this.cb.onPlayStateChanged(!0),null}stop(){this.playEngine?.input.dispose(),this.playEngine?.stop(),this.playEngine?.dispose(),this.playEngine=null,this.playPhysics?.dispose(),this.playPhysics=null,this.editUiHost&&(this.editUiHost.style.display=``),this.playRenderer?.dispose(),this.playRenderer=null,this.playCanvas.hidden=!0,this.cb.onPlayStateChanged(!1),this.lastAppliedKey=null,this.lastGood&&this.apply(this.lastGood)}};function oW(e){return Math.round(e*100)/100}var sW=new W(0,1,0),cW=new W,lW=new W,uW=new U,dW=new W,fW=new K,pW=new W,mW=new W;function hW(e,t,n){let r=e._object2D?.parent;return r?(fW.copy(r.matrixWorld).invert(),pW.set(t,-n,0).applyMatrix4(fW),mW.set(0,0,0).applyMatrix4(fW),{x:pW.x-mW.x,y:-(pW.y-mW.y)}):{x:t,y:n}}function gW(e,t){for(let n=e.parent;n;n=n.parent)if(n===t)return!0;return!1}function _W(e){let t=e._object2D;if(t)return t.getWorldPosition(dW),{x:dW.x,y:-dW.y};let n=0,r=0,i=e;for(;i;)Array.isArray(i.position)&&(n+=i.position[0]??0,r+=i.position[1]??0),i=i.parent;return{x:n,y:r}}function vW(e){if(!e)return null;if(e.type===`Camera3D`){let t=e.props?.position??[0,2,8];return[t[0]??0,t[1]??2,t[2]??8]}for(let t of e.children??[]){let e=vW(t);if(e)return e}return null}function yW(e){if(!e)return null;if(e.type===`Camera2D`){let t=e.props?.position??[0,0];return[t[0]??0,t[1]??0]}for(let t of e.children??[]){let e=yW(t);if(e)return e}return null}var bW=null;function xW(){if(bW)return bW;let e=document.createElement(`canvas`);e.width=16,e.height=16;let t=e.getContext(`2d`);for(let e=0;e<2;e++)for(let n=0;n<2;n++)t.fillStyle=(n+e)%2==0?`#c252c2`:`#2b2b3b`,t.fillRect(n*8,e*8,8,8);return bW=e.toDataURL(),bW}function SW(e){let t=e.assets;if(t)for(let e of Object.values(t))typeof e?.url==`string`&&!e.url.includes(`/`)&&!e.url.includes(`.`)&&(e.url=xW())}var CW=e({formatSceneJson:()=>r,httpEditorApi:()=>ue,mountEditor:()=>TW}),wW=new Set([`Terrain3D`,`Water3D`,`River3D`]);Or(),xx(),XF(),wL(),Tb();async function TW(e={}){let t=e.api??ue,n=[],r=document.createElement(`style`);r.dataset.incantoEditor=`true`,r.textContent=bU,document.head.appendChild(r),n.push(()=>r.remove());let i=document.createElement(`div`);i.className=`incanto-editor-root`,i.innerHTML=WH,(e.host??document.body).appendChild(i),n.push(()=>i.remove());let a=e=>{let t=i.querySelector(e);if(!t)throw Error(`missing ${e}`);return t},o=await t.meta();a(`#engine-version`).textContent=`incanto@${o.version}`,hB(a(`#popover`)),wR(),a(`#docs-btn`).addEventListener(`click`,()=>SR());let s=a(`#lang-btn`),c=[{code:`en`,label:`English`},{code:`ko`,label:`한국어`}],l=()=>{a(`#lang-current`).textContent=OL()===`ko`?`한국어`:`EN`};l(),s.addEventListener(`click`,()=>{document.querySelector(`.lang-menu`)?.remove();let e=document.createElement(`div`);e.className=`context-menu floating lang-menu`;for(let{code:t,label:n}of c){let r=document.createElement(`button`);r.type=`button`,r.className=`menu-item`;let i=document.createElement(`span`);i.textContent=n;let a=document.createElement(`span`);a.textContent=OL()===t?`✓`:``,a.className=`lang-check`,r.append(i,a),r.addEventListener(`click`,()=>{e.remove(),kL(t)}),e.appendChild(r)}document.body.appendChild(e);let t=s.getBoundingClientRect();e.style.left=`${t.left}px`,e.style.top=`${t.bottom+6}px`;let n=t=>{e.contains(t.target)||t.target===s||(e.remove(),document.removeEventListener(`pointerdown`,n,!0))};setTimeout(()=>document.addEventListener(`pointerdown`,n,!0),0)}),AL(()=>{l(),TR(),u.select(u.selection)});let u=new lU({format:1,type:`scene`,name:``,root:null}),d=a(`#tree`),f=a(`#inspector`),p=a(`#save-btn`),m=a(`#undo-btn`),h=a(`#play-btn`),g=a(`#error-banner`),_=a(`#play-notice`),v=a(`#add-type`),y=a(`#picker`),b=a(`#picker-list`),x=a(`#scenes-btn`),S=o.input,C=o.output,w,T=!1,E=a(`#error-text`),D=e=>{g.hidden=!1,E.textContent=e,hR.error(e)},O=()=>{g.hidden=!0,E.textContent=``};a(`#error-close`).addEventListener(`click`,O);let k=a(`#edit-notice`),A=null,ee=e=>{k.hidden=!1,k.textContent=e,A&&clearTimeout(A),A=setTimeout(()=>{k.hidden=!0,k.textContent=``},6e3)},te={on:!1,brush:`0`},ne=e=>{let t=0,n=0,r=u.working.root,i=e=>{let r=e?.props?.position;Array.isArray(r)&&(t+=Number(r[0]??0),n+=Number(r[1]??0))};i(r);for(let t of e)r=r?.children?.[t],i(r);return{x:t,y:n}},re=!1,ie=(e,t,n=!0)=>{n&&(re=!1);let r=u.selection,i=u.nodeAt(r);if(!r||i?.type!==`TileMap2D`)return;let{cx:a,cy:o}=qB(ne(r),Number(i.props?.tileSize??32),e,t),s=i.props?.cells??[],c=JB(s,a,o,te.brush);!c||JSON.stringify(c)===JSON.stringify(s)||(u.mutate(()=>{i.props||={},i.props.cells=c},{path:r,key:`cells`,value:c},{coalesce:re}),re=!0)},ae=()=>{let e=u.nodeAt(u.selection);te.on&&e?.type!==`TileMap2D`&&(te.on=!1),j.setPaintHandler(te.on?ie:null)},j=new aW(a(`#viewport`),a(`#overlay`),a(`#play-canvas`),{onPick:(e,t)=>u.select(e??null,t),onNodeMoved:(e,t)=>me(e,`position`,t,[0,0]),onNodeScaled:(e,t)=>me(e,`scale`,t,[1,1]),onNodeMoved3D:(e,t)=>me(e,`position`,t,[0,0,0]),onNodeScaled3D:(e,t)=>{let n=u.nodeAt(e);if(n&&wW.has(String(n.type))){D(`${n.type} '${n.name}' cannot be scaled — scale would move only the mesh. Resize it with its "size" prop in the inspector.`);return}me(e,`scale`,t,[1,1,1])},onNodeRotated2D:(e,t)=>pe(e,`rotation`,t,0),onNodeRotated3D:(e,t)=>me(e,`rotation`,t,[0,0,0]),onModeChanged:e=>{for(let t of[`move`,`rotate`,`scale`])a(`#tool-${t}`).classList.toggle(`active`,t===e)},onAssetErrors:e=>{u.assetErrors.clear();for(let t of e)u.assetErrors.set(t.ref.replace(/^\$/,``),t.url);fe(),e.length!==0&&D(e.length===1?`asset '${e[0]?.ref}' failed to load (${e[0]?.url}) — it draws as nothing.`:`${e.length} assets failed to load — they draw as nothing: ${e.map(e=>e.ref).join(`, `)}`)},onPlayStateChanged:e=>{document.body.classList.toggle(`playing`,e),n.push(()=>document.body.classList.remove(`playing`)),h.classList.toggle(`stop`,e),h.innerHTML=e?`<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="6" width="12" height="12"/></svg> stop`:`<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg> play`,_.hidden=!e,e&&(_.textContent=`▶ simulating — physics + input live; game scripts run only in your real game. Esc or stop to return.`)},onError:D}),oe=st().sort(),se=``,ce=e=>{if(e===se)return;se=e,v.textContent=``;let t=e===`3d`?[`3D`,`3D Physics`,`Core`,`Network`,`2D`,`2D Physics`]:[`2D`,`2D Physics`,`Core`,`Network`,`3D`,`3D Physics`];for(let[e]of _R)t.includes(e)||t.push(e);for(let e of t){let t=_R.find(([t])=>t===e)?.[1];if(!t)continue;let n=document.createElement(`optgroup`);n.label=e;for(let e of oe.filter(t)){let t=document.createElement(`option`);t.value=e,t.textContent=e,n.appendChild(t)}n.children.length>0&&v.appendChild(n)}v.value=e===`3d`?`MeshInstance3D`:`Sprite2D`};ce(`2d`);let le=()=>{let e=u.selection??[];if(j.validate(u.working)!==null){for(let e of v.querySelectorAll(`option`))e.disabled=!1;return}for(let t of v.querySelectorAll(`option`)){let n=structuredClone(u.working),r=n.root;if(!n.root)n.root={name:`__probe`,type:t.value};else{for(let t of e)r=r?.children?.[t];if(!r)continue;r.children||=[],r.children.push({name:`__probe`,type:t.value})}t.disabled=j.validate(n)!==null}};v.addEventListener(`mousedown`,le),v.addEventListener(`focus`,le);let M=t.library?e=>DH(t,{kind:e.kind,...e.target?{target:e.target}:{},...e.shelf?{shelf:e.shelf}:{},...e.assetType?{assetType:e.assetType}:{},...e.onProps?{onProps:e.onProps}:{},...e.asAsset?{onAsset:(e,t,n)=>kW(u,n,t)}:{}}):void 0,de=!1,fe=()=>{if(!T)return;NU(d,u),UL(a(`#asset-tree`),u),f.textContent=``,WL(f,u,P,M)||QB(f,u,{modelRefs:()=>DW(u,`model`),animationsForSelection:()=>u.selection?j.modelAnimationsAt(u.selection):[],bonesForSelection:e=>u.selection?j.boneNamesAt(u.selection,e):[],assetRefs:e=>OW(u,e),addAsset:(e,t)=>kW(u,e,t),...M?{openLibrary:M}:{},confirm:P,paint:{active:()=>te.on,brush:()=>te.brush,toggle:()=>{te.on=!te.on,ae(),fe()},setBrush:e=>{te.brush=e,fe()}}}),ce(u.working.dimension??`2d`),a(`#hints`).hidden=(u.working.dimension??`2d`)===`3d`,a(`#hints-3d`).hidden=(u.working.dimension??`2d`)!==`3d`,j.setSelection(u.selection,u.extra),ae();let e=u.pendingLivePatch;if(u.pendingLivePatch=null,!j.playing)if(e&&j.patchProp(u.working,e.path,e.key,e.value))g.hidden=!0;else{let e=j.apply(u.working);g.hidden=e===null,e!==null&&D(e)}p.disabled=!u.dirty||!u.working.root,p.title=u.working.root?``:`Add a root node before saving`,m.disabled=!u.canUndo,u.dirty!==de&&(de=u.dirty,hR.change(u.dirty))};u.onChange(fe),u.validator=e=>j.validate(e),u.onError=D;let pe=(e,t,n,r)=>{let i=u.nodeAt(e);i&&u.mutate(()=>{i.props||={},n===r?(delete i.props[t],Object.keys(i.props).length===0&&delete i.props):i.props[t]=n},{path:e,key:t,value:n})},me=(e,t,n,r)=>{let i=u.nodeAt(e);i&&u.mutate(()=>{i.props||={},JSON.stringify(n)===JSON.stringify(r)?(delete i.props[t],Object.keys(i.props).length===0&&delete i.props):i.props[t]=n},{path:e,key:t,value:n})},he=async(e,n,r)=>{j.playing&&j.stop();let i=await t.loadScene(e);w=e,S=n,C=r,T=!0;let s=e??n;a(`#file-chip`).hidden=!s,a(`#file-path`).textContent=s??``,a(`#file-chip`).title=`input: ${n}\noutput: ${r}`,y.hidden=!0,O(),IU(),u.reset(i),o.mode===`project`&&n&&hR.open(n,r)},ge=UH({list:b,search:a(`#picker-search`),count:a(`#picker-count`),path:a(`#picker-path`)},{entries:async()=>t.scenes?await t.scenes():[],current:()=>w,open:e=>_e(e.rel,e.abs)}),_e=(e,t)=>{let n=()=>{he(e,t,t).catch(e=>D(e instanceof Error?e.message:String(e)))};if(!u.dirty||!u.canUndo){n();return}P(`'${w??`This scene`}' has unsaved changes. Opening '${e}' discards them.`,`discard & open`,n,p.hidden?void 0:{label:`save & open`,run:()=>{Te().then(e=>{e&&n()})}})},ve=async()=>{y.hidden=!1,await ge.refresh()},ye=()=>{y.hidden=!0};if(a(`#picker-close`).addEventListener(`click`,ye),y.addEventListener(`pointerdown`,e=>{e.target===y&&ye()}),a(`#picker-create`).addEventListener(`click`,()=>{(async()=>{let e=a(`#picker-path`),n=(e.value.trim()||e.placeholder).trim();if(n)try{if(!t.createScene)return;let e=await t.createScene(n.endsWith(`.scene.json`)?n:`${n}.scene.json`);await he(e.rel,e.abs,e.abs)}catch(e){D(e instanceof Error?e.message:String(e))}})()}),o.mode===`project`&&t.scenes&&(x.hidden=!1,x.addEventListener(`click`,()=>void ve())),o.mode===`project`&&o.hasScene)await he(void 0,``,``);else if(o.mode===`project`&&t.scenes){let e=await t.scenes(),n=e.length===1?e[0]:void 0;n?await he(n.rel,n.abs,n.abs):await ve()}else await he(void 0,o.input,o.output);a(`#add-btn`).addEventListener(`click`,()=>{let e=u.selection??[],t=v.value,n=u.insertNode({name:t,type:t},e);n&&u.select(n)});let be=a(`#generate`);lB(u),a(`#generate-btn`).addEventListener(`click`,()=>sB(u));let xe=a(`#confirm`),N=e=>{if(u.selection===null&&e.length===0){D(`The scene itself cannot be deleted — it IS the file.`);return}if(e.length===0){let e=u.working.root;if(!e)return;let t=EW(e);P(`This deletes the ROOT '${String(e.name??``)}'${t>0?` AND its ${t} descendant node${t===1?``:`s`}`:``} — the scene goes empty, and the next node you add becomes the new root.`,`delete root`,()=>u.deleteRoot());return}let t=e[0]?.slice(0,-1)??[],n=u.findRemovalReferences(e);if(n.length===0){let n=e.reduce((e,t)=>{let n=u.nodeAt(t);return e+(n?EW(n):0)},0);if(n>0){P(`This deletes ${e.length>1?`${e.length} nodes`:`'${String(u.nodeAt(e[0]??[])?.name??``)}'`} AND ${n} descendant node${n===1?``:`s`}.`,`delete ${e.length+n} nodes`,()=>{u.removeNodes(e)&&u.select(t)});return}u.removeNodes(e)&&u.select(t);return}a(`#confirm-text`).textContent=`${n.length} reference${n.length>1?`s`:``} still point at the node(s) you are deleting. Unlink them and delete, or cancel.`;let r=a(`#confirm-list`);r.textContent=``;for(let e of n){let t=document.createElement(`div`);t.textContent=`${e.kind===`uid`?`◆ uid`:e.kind===`prop`?`→ node path`:`⇄ connection`} ${e.where}`,r.appendChild(t)}a(`#confirm-title`).textContent=`still referenced`,a(`#confirm-delete`).textContent=`unlink & delete`,xe.hidden=!1,Se={selections:e,parentOfFirst:t}},Se=null,Ce=null,we=null;function P(e,t,n,r){a(`#confirm-title`).textContent=`are you sure?`,a(`#confirm-text`).textContent=e,a(`#confirm-list`).textContent=``,a(`#confirm-delete`).textContent=t;let i=a(`#confirm-alt`);i.hidden=r===void 0,r&&(i.textContent=r.label),we=r?.run??null,Ce=n,xe.hidden=!1}async function Te(){try{return await t.saveScene?.(u.working,w),u.markSaved(),hR.save(S,C,u.working),!0}catch(e){return D(e instanceof Error?e.message:String(e)),!1}}function F(){xe.hidden=!0,Se=null,Ce=null,we=null,a(`#confirm-alt`).hidden=!0}a(`#confirm-alt`).addEventListener(`click`,()=>{let e=we;F(),e?.()}),a(`#confirm-close`).addEventListener(`click`,F),a(`#confirm-cancel`).addEventListener(`click`,F),xe.addEventListener(`pointerdown`,e=>{e.target===xe&&F()}),a(`#confirm-delete`).addEventListener(`click`,()=>{if(Ce){Ce(),F();return}Se&&u.removeNodesUnlinking(Se.selections)&&u.select(Se.parentOfFirst),F()}),DU(N),OU(e=>{ee(`${jL({en:`Rename: repaired ${e.length} reference${e.length===1?``:`s`}`,ko:`이름 변경: 참조 ${e.length}건 수정`})} — ${e.map(e=>e.where).join(`, `)}`)}),a(`#asset-add-btn`).addEventListener(`click`,e=>{e.stopPropagation(),u.startAddingAsset()}),a(`#group-add-btn`).addEventListener(`click`,e=>{e.stopPropagation(),u.startAddingGroup()});for(let e of document.querySelectorAll(`.section-toggle`)){let t=e.dataset.section??``,n=document.querySelector(`[data-body="${t}"]`),r=`incanto-editor-section-${t}`,i=t=>{e.classList.toggle(`collapsed`,t),n&&(n.hidden=t),localStorage.setItem(r,t?`1`:``)};i(localStorage.getItem(r)===`1`),e.addEventListener(`click`,()=>i(!e.classList.contains(`collapsed`)))}a(`#delete-btn`).addEventListener(`click`,()=>{N(u.allSelections().filter(e=>e.length>0))});let I=()=>{g.hidden=!0,j.play(u.working).then(e=>{e&&D(e)})};if(h.addEventListener(`click`,()=>{if(j.playing){j.stop(),fe();return}if(!e.onPlay){I();return}i.querySelector(`.play-menu`)?.remove();let t=document.createElement(`div`);t.className=`context-menu floating play-menu`;let r=[[`preview`,`▶ preview here`,e.playHints?.preview??`simulate in the editor · scripts stripped`],[`debug`,`⤢ run as the game`,e.playHints?.debug??`this page becomes the game, with the debug overlay`]];for(let[n,i,a]of r){let r=document.createElement(`button`);r.type=`button`,r.className=`menu-item play-menu-item`;let o=document.createElement(`span`);o.textContent=i;let s=document.createElement(`span`);s.className=`play-menu-hint`,s.textContent=a,r.append(o,s),r.addEventListener(`click`,()=>{t.remove(),n===`preview`?I():e.onPlay?.(n,u.working)}),t.appendChild(r)}i.appendChild(t);let a=h.getBoundingClientRect(),o=t.getBoundingClientRect().width;t.style.left=`${Math.min(Math.max(8,a.right-o),window.innerWidth-o-8)}px`,t.style.top=`${a.bottom+6}px`;let s=e=>{e.type===`keydown`&&e.key!==`Escape`||e.type!==`keydown`&&(t.contains(e.target)||e.target===h)||(t.remove(),document.removeEventListener(`pointerdown`,s,!0),document.removeEventListener(`keydown`,s,!0))};setTimeout(()=>{document.addEventListener(`pointerdown`,s,!0),document.addEventListener(`keydown`,s,!0)},0),n.push(()=>{document.removeEventListener(`pointerdown`,s,!0),document.removeEventListener(`keydown`,s,!0)})}),e.onExit){let t=document.createElement(`button`);t.type=`button`,t.className=`ghost`,t.id=`exit-btn`,t.title=`Back to the game`,t.textContent=`✕ exit`,h.parentElement?.insertBefore(t,h),t.addEventListener(`click`,()=>void e.onExit?.())}for(let e of[`move`,`rotate`,`scale`])a(`#tool-${e}`).addEventListener(`click`,()=>j.setMode(e));j.setMode(`move`);let L=a(`#tool-colliders`),Ee=`incanto-editor-show-colliders`,De=e=>{j.showColliders=e,L.classList.toggle(`active`,e),localStorage.setItem(Ee,e?``:`0`)};De(localStorage.getItem(Ee)!==`0`),L.addEventListener(`click`,()=>De(!j.showColliders));let Oe=a(`#hints-dock`),ke=`incanto-editor-hints-open`;Oe.classList.toggle(`open`,localStorage.getItem(ke)===`1`),a(`#hints-toggle`).addEventListener(`click`,()=>{let e=Oe.classList.toggle(`open`);localStorage.setItem(ke,e?`1`:``)}),a(`#fit-btn`).addEventListener(`click`,()=>j.zoomToFit()),EU(()=>j.zoomToFit()),a(`#gameview-btn`).addEventListener(`click`,()=>j.gameView()),t.saveScene||(p.hidden=!0),p.addEventListener(`click`,()=>{Te()}),m.addEventListener(`click`,()=>u.undo());let Ae=e=>{if(e.key===`Escape`&&j.cancelActiveDrag(),e.key===`Escape`&&!g.hidden&&a(`#docs`).hidden&&xe.hidden&&be.hidden&&y.hidden&&!j.playing){O();return}if(e.key===`Escape`&&!a(`#docs`).hidden){CR();return}if(e.key===`Escape`&&!xe.hidden){F();return}if(e.key===`Escape`&&!be.hidden){cB();return}if(e.key===`Escape`&&!y.hidden){ye();return}if(e.key===`Escape`&&j.playing){j.stop(),fe();return}if(j.playing)return;let t=e.target.matches(`input, textarea, select`);(e.metaKey||e.ctrlKey)&&e.key===`z`?(e.preventDefault(),u.undo()):(e.metaKey||e.ctrlKey)&&e.key===`s`?(e.preventDefault(),p.disabled||p.click()):!t&&e.code===`KeyF`?j.zoomToFit():!t&&(e.code===`Digit0`||e.code===`Numpad0`)?j.gameView():!t&&e.code===`KeyW`?j.setMode(`move`):!t&&e.code===`KeyE`?j.setMode(`rotate`):!t&&e.code===`KeyR`&&j.setMode(`scale`)};return window.addEventListener(`keydown`,Ae),n.push(()=>window.removeEventListener(`keydown`,Ae)),fe(),e.camera&&j.setEditCamera(e.camera.position,e.camera.target),hR.ready(S,C,o.version),{working:()=>u.working,camera:()=>j.editCamera(),showError:D,dispose(){j.dispose();for(let e of document.querySelectorAll(`.context-menu, .balloon`))e.remove();for(let e of n.splice(0).reverse())e()}}}function EW(e){let t=0;for(let n of e.children??[])t+=1+EW(n);return t}function DW(e,t){let n=e.working.assets;return n?Object.entries(n).filter(([,e])=>e?.type===t).map(([e])=>`$${e}`):[]}function OW(e,t){let n=e.working.assets;return n?Object.entries(n).filter(([,e])=>!t||e?.type!==void 0&&t.includes(e.type)).map(([e])=>`$${e}`):[]}function kW(e,t,n){let r=e.working.assets??{};for(let[e,t]of Object.entries(r))if(t?.url===n.url)return`$${e}`;let i=t;for(let e=2;i in r;e++)i=`${t}-${e}`;return e.mutate(()=>{e.working.assets||(e.working.assets={}),e.working.assets[i]=n}),`$${i}`}var AW=null,jW=null;function MW(){return jW||(jW=document.createElement(`canvas`),jW.style.cssText=`position:fixed; inset:0; width:100%; height:100%; display:block;`,document.body.appendChild(jW)),jW.style.visibility=``,jW}async function NW(e,t){return AW=await TW({api:ue,...e?{camera:e}:{},onPlay:(e,t)=>{e===`debug`&&PW(t)},playHints:{debug:`this page becomes the game — needs a scene with no project behaviors`},...t?{onExit:()=>(AW?.dispose(),AW=null,MW(),t())}:{}}),AW}async function PW(e){let t=e.dimension??`2d`;AW?.dispose(),AW=null;let n=async e=>{jW&&(jW.style.visibility=`hidden`),await NW(e.camera,e.exit)};try{if(t===`3d`){let{createGame3D:t}=await Vg(async()=>{let{createGame3D:e}=await Promise.resolve().then(()=>dL);return{createGame3D:e}},void 0,import.meta.url);await t({canvas:MW(),scene:e,debug:!0,editor:{open:n}})}else{let{createGame2D:t}=await Vg(async()=>{let{createGame2D:e}=await Promise.resolve().then(()=>tS);return{createGame2D:e}},void 0,import.meta.url);await t({canvas:MW(),scene:e,debug:!0,editor:{open:n}})}}catch(e){jW&&(jW.style.visibility=`hidden`),(await NW()).showError(`${e instanceof Error?e.message:String(e)}\n\nRunning as the game needs your project's behaviors, which live in your app, not in this page. Start your own dev server with debug enabled and use the ☰ debug menu's "✎ edit this scene" — the switch works both ways from there, with every behavior loaded.`)}}NW().catch(e=>{let t=document.createElement(`div`);t.id=`error-banner`,t.style.cssText=`position:fixed;inset:0 0 auto 0;z-index:99;padding:10px 14px;background:#5b1a24;color:#ffd9df;font:13px ui-monospace,monospace`,t.textContent=e instanceof Error?e.message:String(e),document.body.appendChild(t)});export{R as i,Vg as n,dt as r,Fb as t};
|