ifcurl/forgejo/custom/public/assets/viewer-deps.js

6710 lines
6.6 MiB
JavaScript
Raw Permalink Normal View History

var lMe=Object.create;var Ere=Object.defineProperty;var aMe=Object.getOwnPropertyDescriptor;var uMe=Object.getOwnPropertyNames;var cMe=Object.getPrototypeOf,dMe=Object.prototype.hasOwnProperty;var ck=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var hMe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),T$=(e,t)=>{for(var i in t)Ere(e,i,{get:t[i],enumerable:!0})},fMe=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of uMe(t))!dMe.call(e,s)&&s!==i&&Ere(e,s,{get:()=>t[s],enumerable:!(n=aMe(t,s))||n.enumerable});return e};var pMe=(e,t,i)=>(i=e!=null?lMe(cMe(e)):{},fMe(t||!e||!e.__esModule?Ere(i,"default",{value:e,enumerable:!0}):i,e));var tLe=hMe((eLe,LEe)=>{(function(e){typeof eLe=="object"&&typeof LEe<"u"?LEe.exports=e():typeof define=="function"&&define.amd?define([],e):(typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:this).JSZip=e()})(function(){return(function e(t,i,n){function s(l,a){if(!i[l]){if(!t[l]){var u=typeof ck=="function"&&ck;if(!a&&u)return u(l,!0);if(o)return o(l,!0);var h=new Error("Cannot find module '"+l+"'");throw h.code="MODULE_NOT_FOUND",h}var p=i[l]={exports:{}};t[l][0].call(p.exports,function(m){var I=t[l][1][m];return s(I||m)},p,p.exports,e,t,i,n)}return i[l].exports}for(var o=typeof ck=="function"&&ck,r=0;r<n.length;r++)s(n[r]);return s})({1:[function(e,t,i){"use strict";var n=e("./utils"),s=e("./support"),o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(r){for(var l,a,u,h,p,m,I,g=[],E=0,w=r.length,T=w,S=n.getTypeOf(r)!=="string";E<r.length;)T=w-E,u=S?(l=r[E++],a=E<w?r[E++]:0,E<w?r[E++]:0):(l=r.charCodeAt(E++),a=E<w?r.charCodeAt(E++):0,E<w?r.charCodeAt(E++):0),h=l>>2,p=(3&l)<<4|a>>4,m=1<T?(15&a)<<2|u>>6:64,I=2<T?63&u:64,g.push(o.charAt(h)+o.charAt(p)+o.charAt(m)+o.charAt(I));return g.join("")},i.decode=function(r){var l,a,u,h,p,m,I=0,g=0,E="data:";if(r.substr(0,E.length)===E)throw new Error("Invalid base64 input, it looks like a data url.");var w,T=3*(r=r.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(r.charAt(r.length-1)===o.charAt(64)&&T--,r.charAt(r.length-2)===o.charAt(64)&&T--,T%1!=0)throw new Error("Invalid base64 input, bad content length.");for(w=s.uint8array?new Uint8Array(0|T):new Array(0|T);I<r.length;)l=o.indexOf(r.charAt(I++))<<2|(h=o.indexOf(r.charAt(I++)))>>4,a=(15&h)<<4|(p=o.indexOf(r.charAt(I++)))>>2,u=(3&p)<<6|(m=o.indexOf(r.charAt(I++))),w[g++]=l,p!==64&&(w[g++]=a),m!==64&&(w[g++]=u);return w}},{"./support":30,"./utils":32}],2:[function(e,t,i){"use strict";var n=e("./external"),s=e("./stream/DataWorker"),o=e("./stream/Crc32Probe"),r=e("./stream/DataLengthProbe");function l(a,u,h,p,m){this.compressedSize=a,this.uncompressedSize=u,this.crc32=h,this.compression=p,this.compressedContent=m}l.prototype={getContentWorker:function(){var a=new s(n.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new r("data_length")),u=this;return a.on("end",function(){if(this.streamInfo.data_length!==u.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),a},getCompressedWorker:function(){return new s(n.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},l.createWorkerFrom=function(a,u,h){return a.pipe(new o).pipe(new r("uncompressedSize")).pipe(u.compressWorker(h)).pipe(new r("compressedSize")).withStreamInfo("compression",u)},t.exports=l},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,i){"use strict";var n=e("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new n("STORE compression")},uncompressWorker:function(){return new n("STORE decompression")}},i.DEFLATE=e("./flate")},{"./flate":7,"./
\0`,We+=n(Me,2),We+=x.magic,We+=n(T,2),We+=n(S,2),We+=n(pt.crc32,4),We+=n(pt.compressedSize,4),We+=n(pt.uncompressedSize,4),We+=n(W.length,2),We+=n(fe.length,2),{fileRecord:u.LOCAL_FILE_HEADER+We+W+fe,dirRecord:u.CENTRAL_FILE_HEADER+n(Ye,2)+We+n(Y.length,2)+"\0\0\0\0"+n(He,4)+n(g,4)+W+fe+Y}}var o=e("../utils"),r=e("../stream/GenericWorker"),l=e("../utf8"),a=e("../crc32"),u=e("../signature");function h(p,m,I,g){r.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=m,this.zipPlatform=I,this.encodeFileName=g,this.streamFiles=p,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(h,r),h.prototype.push=function(p){var m=p.meta.percent||0,I=this.entriesCount,g=this._sources.length;this.accumulate?this.contentBuffer.push(p):(this.bytesWritten+=p.data.length,r.prototype.push.call(this,{data:p.data,meta:{currentFile:this.currentFile,percent:I?(m+100*(I-g-1))/I:100}}))},h.prototype.openedSource=function(p){this.currentSourceOffset=this.bytesWritten,this.currentFile=p.file.name;var m=this.streamFiles&&!p.file.dir;if(m){var I=s(p,m,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:I.fileRecord,meta:{percent:0}})}else this.accumulate=!0},h.prototype.closedSource=function(p){this.accumulate=!1;var m=this.streamFiles&&!p.file.dir,I=s(p,m,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(I.dirRecord),m)this.push({data:(function(g){return u.DATA_DESCRIPTOR+n(g.crc32,4)+n(g.compressedSize,4)+n(g.uncompressedSize,4)})(p),meta:{percent:100}});else for(this.push({data:I.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},h.prototype.flush=function(){for(var p=this.bytesWritten,m=0;m<this.dirRecords.length;m++)this.push({data:this.dirRecords[m],meta:{percent:100}});var I=this.bytesWritten-p,g=(function(E,w,T,S,_){var x=o.transformTo("string",_(S));return u.CENTRAL_DIRECTORY_END+"\0\0\0\0"+n(E,2)+n(E,2)+n(w,4)+n(T,4)+n(x.length,2)+x})(this.dirRecords.length,I,p,this.zipComment,this.encodeFileName);this.push({data:g,meta:{percent:100}})},h.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},h.prototype.registerPrevious=function(p){this._sources.push(p);var m=this;return p.on("data",function(I){m.processChunk(I)}),p.on("end",function(){m.closedSource(m.previous.streamInfo),m._sources.length?m.prepareNextSource():m.end()}),p.on("error",function(I){m.error(I)}),this},h.prototype.resume=function(){return!!r.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},h.prototype.error=function(p){var m=this._sources;if(!r.prototype.error.call(this,p))return!1;for(var I=0;I<m.length;I++)try{m[I].error(p)}catch{}return!0},h.prototype.lock=function(){r.prototype.lock.call(this);for(var p=this._sources,m=0;m<p.length;m++)p[m].lock()},t.exports=h},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(e,t,i){"use strict";var n=e("../compressions"),s=e("./ZipFileWorker");i.generateWorker=function(o,r,l){var a=new s(r.streamFiles,l,r.platform,r.encodeFileName),u=0;try{o.forEach(function(h,p){u++;var m=(function(w,T){var S=w||T,_=n[S];if(!_)throw new Error(S+" is not a valid compression method !");return _})(p.options.compression,r.compression),I=p.options.compressionOptions||r.compressionOptions||{},g=p.dir,E=p.date;p._compressWorker(m,I).withStreamInfo("file",{name:h,dir:g,date:E,comment:p.comment||"",unixPermissions:p.unixPermissions,dosPermissions:p.dosPermissions}).pipe(a)}),a.entriesCount=u}catch(h){a.error(h)}return a}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(e,t,i){"use strict";function n(){if(!(this instanceof n))return new n;if(arguments.length)throw new Error("The constructor with parameters ha
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,B7e=`void main() {
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}`,Bs=class extends _u{constructor(t){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=M7e,this.fragmentShader=B7e,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,t!==void 0&&this.setValues(t)}copy(t){return super.copy(t),this.fragmentShader=t.fragmentShader,this.vertexShader=t.vertexShader,this.uniforms=uO(t.uniforms),this.uniformsGroups=P7e(t.uniformsGroups),this.defines=Object.assign({},t.defines),this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.fog=t.fog,this.lights=t.lights,this.clipping=t.clipping,this.extensions=Object.assign({},t.extensions),this.glslVersion=t.glslVersion,this.defaultAttributeValues=Object.assign({},t.defaultAttributeValues),this.index0AttributeName=t.index0AttributeName,this.uniformsNeedUpdate=t.uniformsNeedUpdate,this}toJSON(t){let i=super.toJSON(t);i.glslVersion=this.glslVersion,i.uniforms={};for(let s in this.uniforms){let r=this.uniforms[s].value;r&&r.isTexture?i.uniforms[s]={type:"t",value:r.toJSON(t).uuid}:r&&r.isColor?i.uniforms[s]={type:"c",value:r.getHex()}:r&&r.isVector2?i.uniforms[s]={type:"v2",value:r.toArray()}:r&&r.isVector3?i.uniforms[s]={type:"v3",value:r.toArray()}:r&&r.isVector4?i.uniforms[s]={type:"v4",value:r.toArray()}:r&&r.isMatrix3?i.uniforms[s]={type:"m3",value:r.toArray()}:r&&r.isMatrix4?i.uniforms[s]={type:"m4",value:r.toArray()}:i.uniforms[s]={value:r}}Object.keys(this.defines).length>0&&(i.defines=this.defines),i.vertexShader=this.vertexShader,i.fragmentShader=this.fragmentShader,i.lights=this.lights,i.clipping=this.clipping;let n={};for(let s in this.extensions)this.extensions[s]===!0&&(n[s]=!0);return Object.keys(n).length>0&&(i.extensions=n),i}},Gx=class extends Bs{constructor(t){super(t),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}},Vx=class extends _u{constructor(t){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Ei(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 Ei(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=iy,this.normalScale=new si(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 JI,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.defines={STANDARD:""},this.color.copy(t.color),this.roughness=t.roughness,this.metalness=t.metalness,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.roughnessMap=t.roughnessMap,this.metalnessMap=t.metalnessMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.envMapIntensity=t.envMapIntensity,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}},j6=class extends Vx{constructor(t){super(),this.isMeshPhysicalMaterial=!0,this.defines={
if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
#endif`,c8e=`#ifdef USE_ALPHAHASH
const float ALPHA_HASH_SCALE = 0.05;
float hash2D( vec2 value ) {
return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
}
float hash3D( vec3 value ) {
return hash2D( vec2( hash2D( value.xy ), value.z ) );
}
float getAlphaHashThreshold( vec3 position ) {
float maxDeriv = max(
length( dFdx( position.xyz ) ),
length( dFdy( position.xyz ) )
);
float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
vec2 pixScales = vec2(
exp2( floor( log2( pixScale ) ) ),
exp2( ceil( log2( pixScale ) ) )
);
vec2 alpha = vec2(
hash3D( floor( pixScales.x * position.xyz ) ),
hash3D( floor( pixScales.y * position.xyz ) )
);
float lerpFactor = fract( log2( pixScale ) );
float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
float a = min( lerpFactor, 1.0 - lerpFactor );
vec3 cases = vec3(
x * x / ( 2.0 * a * ( 1.0 - a ) ),
( x - 0.5 * a ) / ( 1.0 - a ),
1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
);
float threshold = ( x < ( 1.0 - a ) )
? ( ( x < a ) ? cases.x : cases.y )
: cases.z;
return clamp( threshold , 1.0e-6, 1.0 );
}
#endif`,d8e=`#ifdef USE_ALPHAMAP
diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
#endif`,h8e=`#ifdef USE_ALPHAMAP
uniform sampler2D alphaMap;
#endif`,f8e=`#ifdef USE_ALPHATEST
#ifdef ALPHA_TO_COVERAGE
diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
if ( diffuseColor.a == 0.0 ) discard;
#else
if ( diffuseColor.a < alphaTest ) discard;
#endif
#endif`,p8e=`#ifdef USE_ALPHATEST
uniform float alphaTest;
#endif`,m8e=`#ifdef USE_AOMAP
float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
reflectedLight.indirectDiffuse *= ambientOcclusion;
#if defined( USE_CLEARCOAT )
clearcoatSpecularIndirect *= ambientOcclusion;
#endif
#if defined( USE_SHEEN )
sheenSpecularIndirect *= ambientOcclusion;
#endif
#if defined( USE_ENVMAP ) && defined( STANDARD )
float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
#endif
#endif`,I8e=`#ifdef USE_AOMAP
uniform sampler2D aoMap;
uniform float aoMapIntensity;
#endif`,y8e=`#ifdef USE_BATCHING
#if ! defined( GL_ANGLE_multi_draw )
#define gl_DrawID _gl_DrawID
uniform int _gl_DrawID;
#endif
uniform highp sampler2D batchingTexture;
uniform highp usampler2D batchingIdTexture;
mat4 getBatchingMatrix( const in float i ) {
int size = textureSize( batchingTexture, 0 ).x;
int j = int( i ) * 4;
int x = j % size;
int y = j / size;
vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
return mat4( v1, v2, v3, v4 );
}
float getIndirectIndex( const in int i ) {
int size = textureSize( batchingIdTexture, 0 ).x;
int x = i % size;
int y = i / size;
return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );
}
#endif
#ifdef USE_BATCHING_COLOR
uniform sampler2D batchingColorTexture;
vec4 getBatchingColor( const in float i ) {
int size = textureSize( batchingColorTexture, 0 ).x;
int j = int( i );
int x = j % size;
int y = j / size;
return texelFetch( batchingColorTexture, ivec2( x, y ), 0 );
}
#endif`,g8e=`#ifdef USE_BATCHING
mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
#endif`,E8e=`vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
vPosition = vec3( position );
#endif`,T8e=`vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
vec3 objectTangent = vec3( tangent.xyz );
#endif`,w8e=`float G_BlinnPhong_Implicit( ) {
return 0.25;
}
float D_BlinnPhong( const in float shininess, const in float dotNH ) {
return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
}
vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
vec3 halfDir = normalize( lightDir + viewDir );
float dotNH = saturate( dot( normal, halfDir ) );
float dotVH = saturate( dot( viewDir, halfDir ) );
vec3 F = F_Schlick( specularColor, 1.0, dotVH );
float G = G_BlinnPhong_Implicit( );
float D = D_BlinnPhong( shininess, dotNH );
return F * ( G * D );
} // validated`,v8e=`#ifdef USE_IRIDESCENCE
const mat3 XYZ_TO_REC709 = mat3(
3.2404542, -0.9692660, 0.0556434,
-1.5371385, 1.8760108, -0.2040259,
-0.4985314, 0.0415560, 1.0572252
);
vec3 Fresnel0ToIor( vec3 fresnel0 ) {
vec3 sqrtF0 = sqrt( fresnel0 );
return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
}
vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
}
float IorToFresnel0( float transmittedIor, float incidentIor ) {
return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
}
vec3 evalSensitivity( float OPD, vec3 shift ) {
float phase = 2.0 * PI * OPD * 1.0e-9;
vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );
xyz /= 1.0685e-7;
vec3 rgb = XYZ_TO_REC709 * xyz;
return rgb;
}
vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
vec3 I;
float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
float cosTheta2Sq = 1.0 - sinTheta2Sq;
if ( cosTheta2Sq < 0.0 ) {
return vec3( 1.0 );
}
float cosTheta2 = sqrt( cosTheta2Sq );
float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
float R12 = F_Schlick( R0, 1.0, cosTheta1 );
float T121 = 1.0 - R12;
float phi12 = 0.0;
if ( iridescenceIOR < outsideIOR ) phi12 = PI;
float phi21 = PI - phi12;
vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
vec3 phi23 = vec3( 0.0 );
if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
vec3 phi = vec3( phi21 ) + phi23;
vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
vec3 r123 = sqrt( R123 );
vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
vec3 C0 = R12 + Rs;
I = C0;
vec3 Cm = Rs - T121;
for ( int m = 1; m <= 2; ++ m ) {
Cm *= r123;
vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
I += Cm * Sm;
}
return max( I, vec3( 0.0 ) );
}
#endif`,S8e=`#ifdef USE_BUMPMAP
uniform sampler2D bumpMap;
uniform float bumpScale;
vec2 dHdxy_fwd() {
vec2 dSTdx = dFdx( vBumpMapUv );
vec2 dSTdy = dFdy( vBumpMapUv );
float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
return vec2( dBx, dBy );
}
vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
vec3 vN = surf_norm;
vec3 R1 = cross( vSigmaY, vN );
vec3 R2 = cross( vN, vSigmaX );
float fDet = dot( vSigmaX, R1 ) * faceDirection;
vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
return normalize( abs( fDet ) * surf_norm - vGrad );
}
#endif`,R8e=`#if NUM_CLIPPING_PLANES > 0
vec4 plane;
#ifdef ALPHA_TO_COVERAGE
float distanceToPlane, distanceGradient;
float clipOpacity = 1.0;
#pragma unroll_loop_start
for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
plane = clippingPlanes[ i ];
distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
distanceGradient = fwidth( distanceToPlane ) / 2.0;
clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
if ( clipOpacity == 0.0 ) discard;
}
#pragma unroll_loop_end
#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
float unionClipOpacity = 1.0;
#pragma unroll_loop_start
for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
plane = clippingPlanes[ i ];
distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
distanceGradient = fwidth( distanceToPlane ) / 2.0;
unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
}
#pragma unroll_loop_end
clipOpacity *= 1.0 - unionClipOpacity;
#endif
diffuseColor.a *= clipOpacity;
if ( diffuseColor.a == 0.0 ) discard;
#else
#pragma unroll_loop_start
for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
plane = clippingPlanes[ i ];
if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
}
#pragma unroll_loop_end
#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
bool clipped = true;
#pragma unroll_loop_start
for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
plane = clippingPlanes[ i ];
clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
}
#pragma unroll_loop_end
if ( clipped ) discard;
#endif
#endif
#endif`,_8e=`#if NUM_CLIPPING_PLANES > 0
varying vec3 vClipPosition;
uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
#endif`,b8e=`#if NUM_CLIPPING_PLANES > 0
varying vec3 vClipPosition;
#endif`,A8e=`#if NUM_CLIPPING_PLANES > 0
vClipPosition = - mvPosition.xyz;
#endif`,x8e=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
diffuseColor *= vColor;
#endif`,C8e=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
varying vec4 vColor;
#endif`,D8e=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
varying vec4 vColor;
#endif`,N8e=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
vColor = vec4( 1.0 );
#endif
#ifdef USE_COLOR_ALPHA
vColor *= color;
#elif defined( USE_COLOR )
vColor.rgb *= color;
#endif
#ifdef USE_INSTANCING_COLOR
vColor.rgb *= instanceColor.rgb;
#endif
#ifdef USE_BATCHING_COLOR
vColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) );
#endif`,O8e=`#define PI 3.141592653589793
#define PI2 6.283185307179586
#define PI_HALF 1.5707963267948966
#define RECIPROCAL_PI 0.3183098861837907
#define RECIPROCAL_PI2 0.15915494309189535
#define EPSILON 1e-6
#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
#define whiteComplement( a ) ( 1.0 - saturate( a ) )
float pow2( const in float x ) { return x*x; }
vec3 pow2( const in vec3 x ) { return x*x; }
float pow3( const in float x ) { return x*x*x; }
float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
highp float rand( const in vec2 uv ) {
const highp float a = 12.9898, b = 78.233, c = 43758.5453;
highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
return fract( sin( sn ) * c );
}
#ifdef HIGH_PRECISION
float precisionSafeLength( vec3 v ) { return length( v ); }
#else
float precisionSafeLength( vec3 v ) {
float maxComponent = max3( abs( v ) );
return length( v / maxComponent ) * maxComponent;
}
#endif
struct IncidentLight {
vec3 color;
vec3 direction;
bool visible;
};
struct ReflectedLight {
vec3 directDiffuse;
vec3 directSpecular;
vec3 indirectDiffuse;
vec3 indirectSpecular;
};
#ifdef USE_ALPHAHASH
varying vec3 vPosition;
#endif
vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
}
vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
}
bool isPerspectiveMatrix( mat4 m ) {
return m[ 2 ][ 3 ] == - 1.0;
}
vec2 equirectUv( in vec3 dir ) {
float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
return vec2( u, v );
}
vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
return RECIPROCAL_PI * diffuseColor;
}
vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
}
float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
} // validated`,L8e=`#ifdef ENVMAP_TYPE_CUBE_UV
#define cubeUV_minMipLevel 4.0
#define cubeUV_minTileSize 16.0
float getFace( vec3 direction ) {
vec3 absDirection = abs( direction );
float face = - 1.0;
if ( absDirection.x > absDirection.z ) {
if ( absDirection.x > absDirection.y )
face = direction.x > 0.0 ? 0.0 : 3.0;
else
face = direction.y > 0.0 ? 1.0 : 4.0;
} else {
if ( absDirection.z > absDirection.y )
face = direction.z > 0.0 ? 2.0 : 5.0;
else
face = direction.y > 0.0 ? 1.0 : 4.0;
}
return face;
}
vec2 getUV( vec3 direction, float face ) {
vec2 uv;
if ( face == 0.0 ) {
uv = vec2( direction.z, direction.y ) / abs( direction.x );
} else if ( face == 1.0 ) {
uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
} else if ( face == 2.0 ) {
uv = vec2( - direction.x, direction.y ) / abs( direction.z );
} else if ( face == 3.0 ) {
uv = vec2( - direction.z, direction.y ) / abs( direction.x );
} else if ( face == 4.0 ) {
uv = vec2( - direction.x, direction.z ) / abs( direction.y );
} else {
uv = vec2( direction.x, direction.y ) / abs( direction.z );
}
return 0.5 * ( uv + 1.0 );
}
vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
float face = getFace( direction );
float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
mipInt = max( mipInt, cubeUV_minMipLevel );
float faceSize = exp2( mipInt );
highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
if ( face > 2.0 ) {
uv.y += faceSize;
face -= 3.0;
}
uv.x += face * faceSize;
uv.x += filterInt * 3.0 * cubeUV_minTileSize;
uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
uv.x *= CUBEUV_TEXEL_WIDTH;
uv.y *= CUBEUV_TEXEL_HEIGHT;
#ifdef texture2DGradEXT
return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
#else
return texture2D( envMap, uv ).rgb;
#endif
}
#define cubeUV_r0 1.0
#define cubeUV_m0 - 2.0
#define cubeUV_r1 0.8
#define cubeUV_m1 - 1.0
#define cubeUV_r4 0.4
#define cubeUV_m4 2.0
#define cubeUV_r5 0.305
#define cubeUV_m5 3.0
#define cubeUV_r6 0.21
#define cubeUV_m6 4.0
float roughnessToMip( float roughness ) {
float mip = 0.0;
if ( roughness >= cubeUV_r1 ) {
mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
} else if ( roughness >= cubeUV_r4 ) {
mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
} else if ( roughness >= cubeUV_r5 ) {
mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
} else if ( roughness >= cubeUV_r6 ) {
mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
} else {
mip = - 2.0 * log2( 1.16 * roughness ); }
return mip;
}
vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
float mipF = fract( mip );
float mipInt = floor( mip );
vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
if ( mipF == 0.0 ) {
return vec4( color0, 1.0 );
} else {
vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
return vec4( mix( color0, color1, mipF ), 1.0 );
}
}
#endif`,P8e=`vec3 transformedNormal = objectNormal;
#ifdef USE_TANGENT
vec3 transformedTangent = objectTangent;
#endif
#ifdef USE_BATCHING
mat3 bm = mat3( batchingMatrix );
transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
transformedNormal = bm * transformedNormal;
#ifdef USE_TANGENT
transformedTangent = bm * transformedTangent;
#endif
#endif
#ifdef USE_INSTANCING
mat3 im = mat3( instanceMatrix );
transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
transformedNormal = im * transformedNormal;
#ifdef USE_TANGENT
transformedTangent = im * transformedTangent;
#endif
#endif
transformedNormal = normalMatrix * transformedNormal;
#ifdef FLIP_SIDED
transformedNormal = - transformedNormal;
#endif
#ifdef USE_TANGENT
transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
#ifdef FLIP_SIDED
transformedTangent = - transformedTangent;
#endif
#endif`,M8e=`#ifdef USE_DISPLACEMENTMAP
uniform sampler2D displacementMap;
uniform float displacementScale;
uniform float displacementBias;
#endif`,B8e=`#ifdef USE_DISPLACEMENTMAP
transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
#endif`,F8e=`#ifdef USE_EMISSIVEMAP
vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
emissiveColor = sRGBTransferEOTF( emissiveColor );
#endif
totalEmissiveRadiance *= emissiveColor.rgb;
#endif`,U8e=`#ifdef USE_EMISSIVEMAP
uniform sampler2D emissiveMap;
#endif`,H8e="gl_FragColor = linearToOutputTexel( gl_FragColor );",G8e=`vec4 LinearTransferOETF( in vec4 value ) {
return value;
}
vec4 sRGBTransferEOTF( in vec4 value ) {
return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
}
vec4 sRGBTransferOETF( in vec4 value ) {
return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );
}`,V8e=`#ifdef USE_ENVMAP
#ifdef ENV_WORLDPOS
vec3 cameraToFrag;
if ( isOrthographic ) {
cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
} else {
cameraToFrag = normalize( vWorldPosition - cameraPosition );
}
vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
#ifdef ENVMAP_MODE_REFLECTION
vec3 reflectVec = reflect( cameraToFrag, worldNormal );
#else
vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
#endif
#else
vec3 reflectVec = vReflect;
#endif
#ifdef ENVMAP_TYPE_CUBE
vec4 envColor = textureCube( envMap, envMapRotation * reflectVec );
#ifdef ENVMAP_BLENDING_MULTIPLY
outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
#elif defined( ENVMAP_BLENDING_MIX )
outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
#elif defined( ENVMAP_BLENDING_ADD )
outgoingLight += envColor.xyz * specularStrength * reflectivity;
#endif
#endif
#endif`,k8e=`#ifdef USE_ENVMAP
uniform float envMapIntensity;
uniform mat3 envMapRotation;
#ifdef ENVMAP_TYPE_CUBE
uniform samplerCube envMap;
#else
uniform sampler2D envMap;
#endif
#endif`,z8e=`#ifdef USE_ENVMAP
uniform float reflectivity;
#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
#define ENV_WORLDPOS
#endif
#ifdef ENV_WORLDPOS
varying vec3 vWorldPosition;
uniform float refractionRatio;
#else
varying vec3 vReflect;
#endif
#endif`,W8e=`#ifdef USE_ENVMAP
#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
#define ENV_WORLDPOS
#endif
#ifdef ENV_WORLDPOS
varying vec3 vWorldPosition;
#else
varying vec3 vReflect;
uniform float refractionRatio;
#endif
#endif`,j8e=`#ifdef USE_ENVMAP
#ifdef ENV_WORLDPOS
vWorldPosition = worldPosition.xyz;
#else
vec3 cameraToVertex;
if ( isOrthographic ) {
cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
} else {
cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
}
vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
#ifdef ENVMAP_MODE_REFLECTION
vReflect = reflect( cameraToVertex, worldNormal );
#else
vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
#endif
#endif
#endif`,Y8e=`#ifdef USE_FOG
vFogDepth = - mvPosition.z;
#endif`,q8e=`#ifdef USE_FOG
varying float vFogDepth;
#endif`,$8e=`#ifdef USE_FOG
#ifdef FOG_EXP2
float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
#else
float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
#endif
gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
#endif`,Z8e=`#ifdef USE_FOG
uniform vec3 fogColor;
varying float vFogDepth;
#ifdef FOG_EXP2
uniform float fogDensity;
#else
uniform float fogNear;
uniform float fogFar;
#endif
#endif`,K8e=`#ifdef USE_GRADIENTMAP
uniform sampler2D gradientMap;
#endif
vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
float dotNL = dot( normal, lightDirection );
vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
#ifdef USE_GRADIENTMAP
return vec3( texture2D( gradientMap, coord ).r );
#else
vec2 fw = fwidth( coord ) * 0.5;
return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
#endif
}`,Q8e=`#ifdef USE_LIGHTMAP
uniform sampler2D lightMap;
uniform float lightMapIntensity;
#endif`,J8e=`LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularStrength = specularStrength;`,X8e=`varying vec3 vViewPosition;
struct LambertMaterial {
vec3 diffuseColor;
float specularStrength;
};
void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
vec3 irradiance = dotNL * directLight.color;
reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct RE_Direct_Lambert
#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,eBe=`uniform bool receiveShadow;
uniform vec3 ambientLightColor;
#if defined( USE_LIGHT_PROBES )
uniform vec3 lightProbe[ 9 ];
#endif
vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
float x = normal.x, y = normal.y, z = normal.z;
vec3 result = shCoefficients[ 0 ] * 0.886227;
result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
return result;
}
vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
return irradiance;
}
vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
vec3 irradiance = ambientLightColor;
return irradiance;
}
float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
if ( cutoffDistance > 0.0 ) {
distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
}
return distanceFalloff;
}
float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
return smoothstep( coneCosine, penumbraCosine, angleCosine );
}
#if NUM_DIR_LIGHTS > 0
struct DirectionalLight {
vec3 direction;
vec3 color;
};
uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
light.color = directionalLight.color;
light.direction = directionalLight.direction;
light.visible = true;
}
#endif
#if NUM_POINT_LIGHTS > 0
struct PointLight {
vec3 position;
vec3 color;
float distance;
float decay;
};
uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
vec3 lVector = pointLight.position - geometryPosition;
light.direction = normalize( lVector );
float lightDistance = length( lVector );
light.color = pointLight.color;
light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
light.visible = ( light.color != vec3( 0.0 ) );
}
#endif
#if NUM_SPOT_LIGHTS > 0
struct SpotLight {
vec3 position;
vec3 direction;
vec3 color;
float distance;
float decay;
float coneCos;
float penumbraCos;
};
uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
vec3 lVector = spotLight.position - geometryPosition;
light.direction = normalize( lVector );
float angleCos = dot( light.direction, spotLight.direction );
float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
if ( spotAttenuation > 0.0 ) {
float lightDistance = length( lVector );
light.color = spotLight.color * spotAttenuation;
light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
light.visible = ( light.color != vec3( 0.0 ) );
} else {
light.color = vec3( 0.0 );
light.visible = false;
}
}
#endif
#if NUM_RECT_AREA_LIGHTS > 0
struct RectAreaLight {
vec3 color;
vec3 position;
vec3 halfWidth;
vec3 halfHeight;
};
uniform sampler2D ltc_1; uniform sampler2D ltc_2;
uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
#endif
#if NUM_HEMI_LIGHTS > 0
struct HemisphereLight {
vec3 direction;
vec3 skyColor;
vec3 groundColor;
};
uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
float dotNL = dot( normal, hemiLight.direction );
float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
return irradiance;
}
#endif
#include <lightprobes_pars_fragment>`,tBe=`#ifdef USE_ENVMAP
vec3 getIBLIrradiance( const in vec3 normal ) {
#ifdef ENVMAP_TYPE_CUBE_UV
vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );
return PI * envMapColor.rgb * envMapIntensity;
#else
return vec3( 0.0 );
#endif
}
vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
#ifdef ENVMAP_TYPE_CUBE_UV
vec3 reflectVec = reflect( - viewDir, normal );
reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );
reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
return envMapColor.rgb * envMapIntensity;
#else
return vec3( 0.0 );
#endif
}
#ifdef USE_ANISOTROPY
vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
#ifdef ENVMAP_TYPE_CUBE_UV
vec3 bentNormal = cross( bitangent, viewDir );
bentNormal = normalize( cross( bentNormal, bitangent ) );
bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
return getIBLRadiance( viewDir, bentNormal, roughness );
#else
return vec3( 0.0 );
#endif
}
#endif
#endif`,iBe=`ToonMaterial material;
material.diffuseColor = diffuseColor.rgb;`,nBe=`varying vec3 vViewPosition;
struct ToonMaterial {
vec3 diffuseColor;
};
void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct RE_Direct_Toon
#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,sBe=`BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
material.specularStrength = specularStrength;`,oBe=`varying vec3 vViewPosition;
struct BlinnPhongMaterial {
vec3 diffuseColor;
vec3 specularColor;
float specularShininess;
float specularStrength;
};
void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
vec3 irradiance = dotNL * directLight.color;
reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
}
void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct RE_Direct_BlinnPhong
#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,rBe=`PhysicalMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );
material.metalness = metalnessFactor;
vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
material.roughness = min( material.roughness, 1.0 );
#ifdef IOR
material.ior = ior;
#ifdef USE_SPECULAR
float specularIntensityFactor = specularIntensity;
vec3 specularColorFactor = specularColor;
#ifdef USE_SPECULAR_COLORMAP
specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
#endif
material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
#else
float specularIntensityFactor = 1.0;
vec3 specularColorFactor = vec3( 1.0 );
material.specularF90 = 1.0;
#endif
material.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;
material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );
#else
material.specularColor = vec3( 0.04 );
material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );
material.specularF90 = 1.0;
#endif
#ifdef USE_CLEARCOAT
material.clearcoat = clearcoat;
material.clearcoatRoughness = clearcoatRoughness;
material.clearcoatF0 = vec3( 0.04 );
material.clearcoatF90 = 1.0;
#ifdef USE_CLEARCOATMAP
material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
#endif
material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
material.clearcoatRoughness += geometryRoughness;
material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
#endif
#ifdef USE_DISPERSION
material.dispersion = dispersion;
#endif
#ifdef USE_IRIDESCENCE
material.iridescence = iridescence;
material.iridescenceIOR = iridescenceIOR;
#ifdef USE_IRIDESCENCEMAP
material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
#else
material.iridescenceThickness = iridescenceThicknessMaximum;
#endif
#endif
#ifdef USE_SHEEN
material.sheenColor = sheenColor;
#ifdef USE_SHEEN_COLORMAP
material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
#endif
material.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 );
#ifdef USE_SHEEN_ROUGHNESSMAP
material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
#endif
#endif
#ifdef USE_ANISOTROPY
#ifdef USE_ANISOTROPYMAP
mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
#else
vec2 anisotropyV = anisotropyVector;
#endif
material.anisotropy = length( anisotropyV );
if( material.anisotropy == 0.0 ) {
anisotropyV = vec2( 1.0, 0.0 );
} else {
anisotropyV /= material.anisotropy;
material.anisotropy = saturate( material.anisotropy );
}
material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
#endif`,lBe=`uniform sampler2D dfgLUT;
struct PhysicalMaterial {
vec3 diffuseColor;
vec3 diffuseContribution;
vec3 specularColor;
vec3 specularColorBlended;
float roughness;
float metalness;
float specularF90;
float dispersion;
#ifdef USE_CLEARCOAT
float clearcoat;
float clearcoatRoughness;
vec3 clearcoatF0;
float clearcoatF90;
#endif
#ifdef USE_IRIDESCENCE
float iridescence;
float iridescenceIOR;
float iridescenceThickness;
vec3 iridescenceFresnel;
vec3 iridescenceF0;
vec3 iridescenceFresnelDielectric;
vec3 iridescenceFresnelMetallic;
#endif
#ifdef USE_SHEEN
vec3 sheenColor;
float sheenRoughness;
#endif
#ifdef IOR
float ior;
#endif
#ifdef USE_TRANSMISSION
float transmission;
float transmissionAlpha;
float thickness;
float attenuationDistance;
vec3 attenuationColor;
#endif
#ifdef USE_ANISOTROPY
float anisotropy;
float alphaT;
vec3 anisotropyT;
vec3 anisotropyB;
#endif
};
vec3 clearcoatSpecularDirect = vec3( 0.0 );
vec3 clearcoatSpecularIndirect = vec3( 0.0 );
vec3 sheenSpecularDirect = vec3( 0.0 );
vec3 sheenSpecularIndirect = vec3(0.0 );
vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
float x2 = x * x;
float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
}
float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
float a2 = pow2( alpha );
float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
return 0.5 / max( gv + gl, EPSILON );
}
float D_GGX( const in float alpha, const in float dotNH ) {
float a2 = pow2( alpha );
float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
return RECIPROCAL_PI * a2 / pow2( denom );
}
#ifdef USE_ANISOTROPY
float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {
float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
return 0.5 / max( gv + gl, EPSILON );
}
float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
float a2 = alphaT * alphaB;
highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
highp float v2 = dot( v, v );
float w2 = a2 / v2;
return RECIPROCAL_PI * a2 * pow2 ( w2 );
}
#endif
#ifdef USE_CLEARCOAT
vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
vec3 f0 = material.clearcoatF0;
float f90 = material.clearcoatF90;
float roughness = material.clearcoatRoughness;
float alpha = pow2( roughness );
vec3 halfDir = normalize( lightDir + viewDir );
float dotNL = saturate( dot( normal, lightDir ) );
float dotNV = saturate( dot( normal, viewDir ) );
float dotNH = saturate( dot( normal, halfDir ) );
float dotVH = saturate( dot( viewDir, halfDir ) );
vec3 F = F_Schlick( f0, f90, dotVH );
float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
float D = D_GGX( alpha, dotNH );
return F * ( V * D );
}
#endif
vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
vec3 f0 = material.specularColorBlended;
float f90 = material.specularF90;
float roughness = material.roughness;
float alpha = pow2( roughness );
vec3 halfDir = normalize( lightDir + viewDir );
float dotNL = saturate( dot( normal, lightDir ) );
float dotNV = saturate( dot( normal, viewDir ) );
float dotNH = saturate( dot( normal, halfDir ) );
float dotVH = saturate( dot( viewDir, halfDir ) );
vec3 F = F_Schlick( f0, f90, dotVH );
#ifdef USE_IRIDESCENCE
F = mix( F, material.iridescenceFresnel, material.iridescence );
#endif
#ifdef USE_ANISOTROPY
float dotTL = dot( material.anisotropyT, lightDir );
float dotTV = dot( material.anisotropyT, viewDir );
float dotTH = dot( material.anisotropyT, halfDir );
float dotBL = dot( material.anisotropyB, lightDir );
float dotBV = dot( material.anisotropyB, viewDir );
float dotBH = dot( material.anisotropyB, halfDir );
float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
#else
float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
float D = D_GGX( alpha, dotNH );
#endif
return F * ( V * D );
}
vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
const float LUT_SIZE = 64.0;
const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
const float LUT_BIAS = 0.5 / LUT_SIZE;
float dotNV = saturate( dot( N, V ) );
vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
uv = uv * LUT_SCALE + LUT_BIAS;
return uv;
}
float LTC_ClippedSphereFormFactor( const in vec3 f ) {
float l = length( f );
return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
}
vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
float x = dot( v1, v2 );
float y = abs( x );
float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
float b = 3.4175940 + ( 4.1616724 + y ) * y;
float v = a / b;
float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
return cross( v1, v2 ) * theta_sintheta;
}
vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
vec3 lightNormal = cross( v1, v2 );
if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
vec3 T1, T2;
T1 = normalize( V - N * dot( V, N ) );
T2 = - cross( N, T1 );
mat3 mat = mInv * transpose( mat3( T1, T2, N ) );
vec3 coords[ 4 ];
coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
coords[ 0 ] = normalize( coords[ 0 ] );
coords[ 1 ] = normalize( coords[ 1 ] );
coords[ 2 ] = normalize( coords[ 2 ] );
coords[ 3 ] = normalize( coords[ 3 ] );
vec3 vectorFormFactor = vec3( 0.0 );
vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
return vec3( result );
}
#if defined( USE_SHEEN )
float D_Charlie( float roughness, float dotNH ) {
float alpha = pow2( roughness );
float invAlpha = 1.0 / alpha;
float cos2h = dotNH * dotNH;
float sin2h = max( 1.0 - cos2h, 0.0078125 );
return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
}
float V_Neubelt( float dotNV, float dotNL ) {
return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
}
vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
vec3 halfDir = normalize( lightDir + viewDir );
float dotNL = saturate( dot( normal, lightDir ) );
float dotNV = saturate( dot( normal, viewDir ) );
float dotNH = saturate( dot( normal, halfDir ) );
float D = D_Charlie( sheenRoughness, dotNH );
float V = V_Neubelt( dotNV, dotNL );
return sheenColor * ( D * V );
}
#endif
float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
float dotNV = saturate( dot( normal, viewDir ) );
float r2 = roughness * roughness;
float rInv = 1.0 / ( roughness + 0.1 );
float a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;
float b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;
float DG = exp( a * dotNV + b );
return saturate( DG );
}
vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
float dotNV = saturate( dot( normal, viewDir ) );
vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;
return specularColor * fab.x + specularF90 * fab.y;
}
#ifdef USE_IRIDESCENCE
void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#else
void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#endif
float dotNV = saturate( dot( normal, viewDir ) );
vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;
#ifdef USE_IRIDESCENCE
vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
#else
vec3 Fr = specularColor;
#endif
vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
float Ess = fab.x + fab.y;
float Ems = 1.0 - Ess;
vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
singleScatter += FssEss;
multiScatter += Fms * Ems;
}
vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );
float dotNL = saturate( dot( normal, lightDir ) );
float dotNV = saturate( dot( normal, viewDir ) );
vec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg;
vec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg;
vec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y;
vec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y;
float Ess_V = dfgV.x + dfgV.y;
float Ess_L = dfgL.x + dfgL.y;
float Ems_V = 1.0 - Ess_V;
float Ems_L = 1.0 - Ess_L;
vec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619;
vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON );
float compensationFactor = Ems_V * Ems_L;
vec3 multiScatter = Fms * compensationFactor;
return singleScatter + multiScatter;
}
#if NUM_RECT_AREA_LIGHTS > 0
void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
vec3 normal = geometryNormal;
vec3 viewDir = geometryViewDir;
vec3 position = geometryPosition;
vec3 lightPos = rectAreaLight.position;
vec3 halfWidth = rectAreaLight.halfWidth;
vec3 halfHeight = rectAreaLight.halfHeight;
vec3 lightColor = rectAreaLight.color;
float roughness = material.roughness;
vec3 rectCoords[ 4 ];
rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
vec2 uv = LTC_Uv( normal, viewDir, roughness );
vec4 t1 = texture2D( ltc_1, uv );
vec4 t2 = texture2D( ltc_2, uv );
mat3 mInv = mat3(
vec3( t1.x, 0, t1.y ),
vec3( 0, 1, 0 ),
vec3( t1.z, 0, t1.w )
);
vec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y );
reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
reflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
#ifdef USE_CLEARCOAT
vec3 Ncc = geometryClearcoatNormal;
vec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness );
vec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat );
vec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat );
mat3 mInvClearcoat = mat3(
vec3( t1Clearcoat.x, 0, t1Clearcoat.y ),
vec3( 0, 1, 0 ),
vec3( t1Clearcoat.z, 0, t1Clearcoat.w )
);
vec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y;
clearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords );
#endif
}
#endif
void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
vec3 irradiance = dotNL * directLight.color;
#ifdef USE_CLEARCOAT
float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
vec3 ccIrradiance = dotNLcc * directLight.color;
clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
#endif
#ifdef USE_SHEEN
sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
float sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
float sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );
float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );
irradiance *= sheenEnergyComp;
#endif
reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );
reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );
}
void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution );
#ifdef USE_SHEEN
float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;
diffuse *= sheenEnergyComp;
#endif
reflectedLight.indirectDiffuse += diffuse;
}
void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {
#ifdef USE_CLEARCOAT
clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
#endif
#ifdef USE_SHEEN
sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI;
#endif
vec3 singleScatteringDielectric = vec3( 0.0 );
vec3 multiScatteringDielectric = vec3( 0.0 );
vec3 singleScatteringMetallic = vec3( 0.0 );
vec3 multiScatteringMetallic = vec3( 0.0 );
#ifdef USE_IRIDESCENCE
computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric );
computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic );
#else
computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric );
computeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic );
#endif
vec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );
vec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );
vec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;
vec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );
vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
vec3 indirectSpecular = radiance * singleScattering;
indirectSpecular += multiScattering * cosineWeightedIrradiance;
vec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;
#ifdef USE_SHEEN
float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;
indirectSpecular *= sheenEnergyComp;
indirectDiffuse *= sheenEnergyComp;
#endif
reflectedLight.indirectSpecular += indirectSpecular;
reflectedLight.indirectDiffuse += indirectDiffuse;
}
#define RE_Direct RE_Direct_Physical
#define RE_Direct_RectArea RE_Direct_RectArea_Physical
#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical
#define RE_IndirectSpecular RE_IndirectSpecular_Physical
float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
}`,aBe=`
vec3 geometryPosition = - vViewPosition;
vec3 geometryNormal = normal;
vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
vec3 geometryClearcoatNormal = vec3( 0.0 );
#ifdef USE_CLEARCOAT
geometryClearcoatNormal = clearcoatNormal;
#endif
#ifdef USE_IRIDESCENCE
float dotNVi = saturate( dot( normal, geometryViewDir ) );
if ( material.iridescenceThickness == 0.0 ) {
material.iridescence = 0.0;
} else {
material.iridescence = saturate( material.iridescence );
}
if ( material.iridescence > 0.0 ) {
material.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
material.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );
material.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness );
material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
}
#endif
IncidentLight directLight;
#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
PointLight pointLight;
#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
PointLightShadow pointLightShadow;
#endif
#pragma unroll_loop_start
for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
pointLight = pointLights[ i ];
getPointLightInfo( pointLight, geometryPosition, directLight );
#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )
pointLightShadow = pointLightShadows[ i ];
directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
#endif
RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
}
#pragma unroll_loop_end
#endif
#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
SpotLight spotLight;
vec4 spotColor;
vec3 spotLightCoord;
bool inSpotLightMap;
#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
SpotLightShadow spotLightShadow;
#endif
#pragma unroll_loop_start
for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
spotLight = spotLights[ i ];
getSpotLightInfo( spotLight, geometryPosition, directLight );
#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
#else
#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
#endif
#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
#endif
#undef SPOT_LIGHT_MAP_INDEX
#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
spotLightShadow = spotLightShadows[ i ];
directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
#endif
RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
}
#pragma unroll_loop_end
#endif
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
DirectionalLight directionalLight;
#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
DirectionalLightShadow directionalLightShadow;
#endif
#pragma unroll_loop_start
for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
directionalLight = directionalLights[ i ];
getDirectionalLightInfo( directionalLight, directLight );
#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
directionalLightShadow = directionalLightShadows[ i ];
directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
#endif
RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
}
#pragma unroll_loop_end
#endif
#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
RectAreaLight rectAreaLight;
#pragma unroll_loop_start
for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
rectAreaLight = rectAreaLights[ i ];
RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
}
#pragma unroll_loop_end
#endif
#if defined( RE_IndirectDiffuse )
vec3 iblIrradiance = vec3( 0.0 );
vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
#if defined( USE_LIGHT_PROBES )
irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
#endif
#if ( NUM_HEMI_LIGHTS > 0 )
#pragma unroll_loop_start
for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
}
#pragma unroll_loop_end
#endif
#ifdef USE_LIGHT_PROBES_GRID
vec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz;
vec3 probeWorldNormal = inverseTransformDirection( geometryNormal, viewMatrix );
irradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal );
#endif
#endif
#if defined( RE_IndirectSpecular )
vec3 radiance = vec3( 0.0 );
vec3 clearcoatRadiance = vec3( 0.0 );
#endif`,uBe=`#if defined( RE_IndirectDiffuse )
#ifdef USE_LIGHTMAP
vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
irradiance += lightMapIrradiance;
#endif
#if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV )
#if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG )
iblIrradiance += getIBLIrradiance( geometryNormal );
#endif
#endif
#endif
#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
#ifdef USE_ANISOTROPY
radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
#else
radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
#endif
#ifdef USE_CLEARCOAT
clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
#endif
#endif`,cBe=`#if defined( RE_IndirectDiffuse )
#if defined( LAMBERT ) || defined( PHONG )
irradiance += iblIrradiance;
#endif
RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif
#if defined( RE_IndirectSpecular )
RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif`,dBe=`#ifdef USE_LIGHT_PROBES_GRID
uniform highp sampler3D probesSH;
uniform vec3 probesMin;
uniform vec3 probesMax;
uniform vec3 probesResolution;
vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {
vec3 res = probesResolution;
vec3 gridRange = probesMax - probesMin;
vec3 resMinusOne = res - 1.0;
vec3 probeSpacing = gridRange / resMinusOne;
vec3 samplePos = worldPos + worldNormal * probeSpacing * 0.5;
vec3 uvw = clamp( ( samplePos - probesMin ) / gridRange, 0.0, 1.0 );
uvw = uvw * resMinusOne / res + 0.5 / res;
float nz = res.z;
float paddedSlices = nz + 2.0;
float atlasDepth = 7.0 * paddedSlices;
float uvZBase = uvw.z * nz + 1.0;
vec4 s0 = texture( probesSH, vec3( uvw.xy, ( uvZBase ) / atlasDepth ) );
vec4 s1 = texture( probesSH, vec3( uvw.xy, ( uvZBase + paddedSlices ) / atlasDepth ) );
vec4 s2 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 2.0 * paddedSlices ) / atlasDepth ) );
vec4 s3 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 3.0 * paddedSlices ) / atlasDepth ) );
vec4 s4 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 4.0 * paddedSlices ) / atlasDepth ) );
vec4 s5 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 5.0 * paddedSlices ) / atlasDepth ) );
vec4 s6 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 6.0 * paddedSlices ) / atlasDepth ) );
vec3 c0 = s0.xyz;
vec3 c1 = vec3( s0.w, s1.xy );
vec3 c2 = vec3( s1.zw, s2.x );
vec3 c3 = s2.yzw;
vec3 c4 = s3.xyz;
vec3 c5 = vec3( s3.w, s4.xy );
vec3 c6 = vec3( s4.zw, s5.x );
vec3 c7 = s5.yzw;
vec3 c8 = s6.xyz;
float x = worldNormal.x, y = worldNormal.y, z = worldNormal.z;
vec3 result = c0 * 0.886227;
result += c1 * 2.0 * 0.511664 * y;
result += c2 * 2.0 * 0.511664 * z;
result += c3 * 2.0 * 0.511664 * x;
result += c4 * 2.0 * 0.429043 * x * y;
result += c5 * 2.0 * 0.429043 * y * z;
result += c6 * ( 0.743125 * z * z - 0.247708 );
result += c7 * 2.0 * 0.429043 * x * z;
result += c8 * 0.429043 * ( x * x - y * y );
return max( result, vec3( 0.0 ) );
}
#endif`,hBe=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
#endif`,fBe=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
uniform float logDepthBufFC;
varying float vFragDepth;
varying float vIsPerspective;
#endif`,pBe=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
varying float vFragDepth;
varying float vIsPerspective;
#endif`,mBe=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
vFragDepth = 1.0 + gl_Position.w;
vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
#endif`,IBe=`#ifdef USE_MAP
vec4 sampledDiffuseColor = texture2D( map, vMapUv );
#ifdef DECODE_VIDEO_TEXTURE
sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
#endif
diffuseColor *= sampledDiffuseColor;
#endif`,yBe=`#ifdef USE_MAP
uniform sampler2D map;
#endif`,gBe=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
#if defined( USE_POINTS_UV )
vec2 uv = vUv;
#else
vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
#endif
#endif
#ifdef USE_MAP
diffuseColor *= texture2D( map, uv );
#endif
#ifdef USE_ALPHAMAP
diffuseColor.a *= texture2D( alphaMap, uv ).g;
#endif`,EBe=`#if defined( USE_POINTS_UV )
varying vec2 vUv;
#else
#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
uniform mat3 uvTransform;
#endif
#endif
#ifdef USE_MAP
uniform sampler2D map;
#endif
#ifdef USE_ALPHAMAP
uniform sampler2D alphaMap;
#endif`,TBe=`float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
metalnessFactor *= texelMetalness.b;
#endif`,wBe=`#ifdef USE_METALNESSMAP
uniform sampler2D metalnessMap;
#endif`,vBe=`#ifdef USE_INSTANCING_MORPH
float morphTargetInfluences[ MORPHTARGETS_COUNT ];
float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
}
#endif`,SBe=`#if defined( USE_MORPHCOLORS )
vColor *= morphTargetBaseInfluence;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
#if defined( USE_COLOR_ALPHA )
if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
#elif defined( USE_COLOR )
if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
#endif
}
#endif`,RBe=`#ifdef USE_MORPHNORMALS
objectNormal *= morphTargetBaseInfluence;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
}
#endif`,_Be=`#ifdef USE_MORPHTARGETS
#ifndef USE_INSTANCING_MORPH
uniform float morphTargetBaseInfluence;
uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
#endif
uniform sampler2DArray morphTargetsTexture;
uniform ivec2 morphTargetsTextureSize;
vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
int y = texelIndex / morphTargetsTextureSize.x;
int x = texelIndex - y * morphTargetsTextureSize.x;
ivec3 morphUV = ivec3( x, y, morphTargetIndex );
return texelFetch( morphTargetsTexture, morphUV, 0 );
}
#endif`,bBe=`#ifdef USE_MORPHTARGETS
transformed *= morphTargetBaseInfluence;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
}
#endif`,ABe=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
#ifdef FLAT_SHADED
vec3 fdx = dFdx( vViewPosition );
vec3 fdy = dFdy( vViewPosition );
vec3 normal = normalize( cross( fdx, fdy ) );
#else
vec3 normal = normalize( vNormal );
#ifdef DOUBLE_SIDED
normal *= faceDirection;
#endif
#endif
#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
#ifdef USE_TANGENT
mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
#else
mat3 tbn = getTangentFrame( - vViewPosition, normal,
#if defined( USE_NORMALMAP )
vNormalMapUv
#elif defined( USE_CLEARCOAT_NORMALMAP )
vClearcoatNormalMapUv
#else
vUv
#endif
);
#endif
#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
tbn[0] *= faceDirection;
tbn[1] *= faceDirection;
#endif
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
#ifdef USE_TANGENT
mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
#else
mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
#endif
#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
tbn2[0] *= faceDirection;
tbn2[1] *= faceDirection;
#endif
#endif
vec3 nonPerturbedNormal = normal;`,xBe=`#ifdef USE_NORMALMAP_OBJECTSPACE
normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
#ifdef FLIP_SIDED
normal = - normal;
#endif
#ifdef DOUBLE_SIDED
normal = normal * faceDirection;
#endif
normal = normalize( normalMatrix * normal );
#elif defined( USE_NORMALMAP_TANGENTSPACE )
vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
#if defined( USE_PACKED_NORMALMAP )
mapN = vec3( mapN.xy, sqrt( saturate( 1.0 - dot( mapN.xy, mapN.xy ) ) ) );
#endif
mapN.xy *= normalScale;
normal = normalize( tbn * mapN );
#elif defined( USE_BUMPMAP )
normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
#endif`,CBe=`#ifndef FLAT_SHADED
varying vec3 vNormal;
#ifdef USE_TANGENT
varying vec3 vTangent;
varying vec3 vBitangent;
#endif
#endif`,DBe=`#ifndef FLAT_SHADED
varying vec3 vNormal;
#ifdef USE_TANGENT
varying vec3 vTangent;
varying vec3 vBitangent;
#endif
#endif`,NBe=`#ifndef FLAT_SHADED
vNormal = normalize( transformedNormal );
#ifdef USE_TANGENT
vTangent = normalize( transformedTangent );
vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
#endif
#endif`,OBe=`#ifdef USE_NORMALMAP
uniform sampler2D normalMap;
uniform vec2 normalScale;
#endif
#ifdef USE_NORMALMAP_OBJECTSPACE
uniform mat3 normalMatrix;
#endif
#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
vec3 q0 = dFdx( eye_pos.xyz );
vec3 q1 = dFdy( eye_pos.xyz );
vec2 st0 = dFdx( uv.st );
vec2 st1 = dFdy( uv.st );
vec3 N = surf_norm;
vec3 q1perp = cross( q1, N );
vec3 q0perp = cross( N, q0 );
vec3 T = q1perp * st0.x + q0perp * st1.x;
vec3 B = q1perp * st0.y + q0perp * st1.y;
float det = max( dot( T, T ), dot( B, B ) );
float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
return mat3( T * scale, B * scale, N );
}
#endif`,LBe=`#ifdef USE_CLEARCOAT
vec3 clearcoatNormal = nonPerturbedNormal;
#endif`,PBe=`#ifdef USE_CLEARCOAT_NORMALMAP
vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
clearcoatMapN.xy *= clearcoatNormalScale;
clearcoatNormal = normalize( tbn2 * clearcoatMapN );
#endif`,MBe=`#ifdef USE_CLEARCOATMAP
uniform sampler2D clearcoatMap;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
uniform sampler2D clearcoatNormalMap;
uniform vec2 clearcoatNormalScale;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
uniform sampler2D clearcoatRoughnessMap;
#endif`,BBe=`#ifdef USE_IRIDESCENCEMAP
uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
uniform sampler2D iridescenceThicknessMap;
#endif`,FBe=`#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
#endif
gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,UBe=`vec3 packNormalToRGB( const in vec3 normal ) {
return normalize( normal ) * 0.5 + 0.5;
}
vec3 unpackRGBToNormal( const in vec3 rgb ) {
return 2.0 * rgb.xyz - 1.0;
}
const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;
const float Inv255 = 1. / 255.;
const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );
const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );
const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );
const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );
vec4 packDepthToRGBA( const in float v ) {
if( v <= 0.0 )
return vec4( 0., 0., 0., 0. );
if( v >= 1.0 )
return vec4( 1., 1., 1., 1. );
float vuf;
float af = modf( v * PackFactors.a, vuf );
float bf = modf( vuf * ShiftRight8, vuf );
float gf = modf( vuf * ShiftRight8, vuf );
return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );
}
vec3 packDepthToRGB( const in float v ) {
if( v <= 0.0 )
return vec3( 0., 0., 0. );
if( v >= 1.0 )
return vec3( 1., 1., 1. );
float vuf;
float bf = modf( v * PackFactors.b, vuf );
float gf = modf( vuf * ShiftRight8, vuf );
return vec3( vuf * Inv255, gf * PackUpscale, bf );
}
vec2 packDepthToRG( const in float v ) {
if( v <= 0.0 )
return vec2( 0., 0. );
if( v >= 1.0 )
return vec2( 1., 1. );
float vuf;
float gf = modf( v * 256., vuf );
return vec2( vuf * Inv255, gf );
}
float unpackRGBAToDepth( const in vec4 v ) {
return dot( v, UnpackFactors4 );
}
float unpackRGBToDepth( const in vec3 v ) {
return dot( v, UnpackFactors3 );
}
float unpackRGToDepth( const in vec2 v ) {
return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;
}
vec4 pack2HalfToRGBA( const in vec2 v ) {
vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
}
vec2 unpackRGBATo2Half( const in vec4 v ) {
return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
}
float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
return ( viewZ + near ) / ( near - far );
}
float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
#ifdef USE_REVERSED_DEPTH_BUFFER
return depth * ( far - near ) - far;
#else
return depth * ( near - far ) - near;
#endif
}
float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
}
float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
#ifdef USE_REVERSED_DEPTH_BUFFER
return ( near * far ) / ( ( near - far ) * depth - near );
#else
return ( near * far ) / ( ( far - near ) * depth - far );
#endif
}`,HBe=`#ifdef PREMULTIPLIED_ALPHA
gl_FragColor.rgb *= gl_FragColor.a;
#endif`,GBe=`vec4 mvPosition = vec4( transformed, 1.0 );
#ifdef USE_BATCHING
mvPosition = batchingMatrix * mvPosition;
#endif
#ifdef USE_INSTANCING
mvPosition = instanceMatrix * mvPosition;
#endif
mvPosition = modelViewMatrix * mvPosition;
gl_Position = projectionMatrix * mvPosition;`,VBe=`#ifdef DITHERING
gl_FragColor.rgb = dithering( gl_FragColor.rgb );
#endif`,kBe=`#ifdef DITHERING
vec3 dithering( vec3 color ) {
float grid_position = rand( gl_FragCoord.xy );
vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
return color + dither_shift_RGB;
}
#endif`,zBe=`float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
roughnessFactor *= texelRoughness.g;
#endif`,WBe=`#ifdef USE_ROUGHNESSMAP
uniform sampler2D roughnessMap;
#endif`,jBe=`#if NUM_SPOT_LIGHT_COORDS > 0
varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#if NUM_SPOT_LIGHT_MAPS > 0
uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
#endif
#ifdef USE_SHADOWMAP
#if NUM_DIR_LIGHT_SHADOWS > 0
#if defined( SHADOWMAP_TYPE_PCF )
uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
#else
uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
#endif
varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
struct DirectionalLightShadow {
float shadowIntensity;
float shadowBias;
float shadowNormalBias;
float shadowRadius;
vec2 shadowMapSize;
};
uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
#endif
#if NUM_SPOT_LIGHT_SHADOWS > 0
#if defined( SHADOWMAP_TYPE_PCF )
uniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
#else
uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
#endif
struct SpotLightShadow {
float shadowIntensity;
float shadowBias;
float shadowNormalBias;
float shadowRadius;
vec2 shadowMapSize;
};
uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
#endif
#if NUM_POINT_LIGHT_SHADOWS > 0
#if defined( SHADOWMAP_TYPE_PCF )
uniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
#elif defined( SHADOWMAP_TYPE_BASIC )
uniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
#endif
varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
struct PointLightShadow {
float shadowIntensity;
float shadowBias;
float shadowNormalBias;
float shadowRadius;
vec2 shadowMapSize;
float shadowCameraNear;
float shadowCameraFar;
};
uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
#endif
#if defined( SHADOWMAP_TYPE_PCF )
float interleavedGradientNoise( vec2 position ) {
return fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );
}
vec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {
const float goldenAngle = 2.399963229728653;
float r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );
float theta = float( sampleIndex ) * goldenAngle + phi;
return vec2( cos( theta ), sin( theta ) ) * r;
}
#endif
#if defined( SHADOWMAP_TYPE_PCF )
float getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
float shadow = 1.0;
shadowCoord.xyz /= shadowCoord.w;
shadowCoord.z += shadowBias;
bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
if ( frustumTest ) {
vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
float radius = shadowRadius * texelSize.x;
float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;
shadow = (
texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +
texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +
texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +
texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +
texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )
) * 0.2;
}
return mix( 1.0, shadow, shadowIntensity );
}
#elif defined( SHADOWMAP_TYPE_VSM )
float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
float shadow = 1.0;
shadowCoord.xyz /= shadowCoord.w;
#ifdef USE_REVERSED_DEPTH_BUFFER
shadowCoord.z -= shadowBias;
#else
shadowCoord.z += shadowBias;
#endif
bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
if ( frustumTest ) {
vec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;
float mean = distribution.x;
float variance = distribution.y * distribution.y;
#ifdef USE_REVERSED_DEPTH_BUFFER
float hard_shadow = step( mean, shadowCoord.z );
#else
float hard_shadow = step( shadowCoord.z, mean );
#endif
if ( hard_shadow == 1.0 ) {
shadow = 1.0;
} else {
variance = max( variance, 0.0000001 );
float d = shadowCoord.z - mean;
float p_max = variance / ( variance + d * d );
p_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );
shadow = max( hard_shadow, p_max );
}
}
return mix( 1.0, shadow, shadowIntensity );
}
#else
float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
float shadow = 1.0;
shadowCoord.xyz /= shadowCoord.w;
#ifdef USE_REVERSED_DEPTH_BUFFER
shadowCoord.z -= shadowBias;
#else
shadowCoord.z += shadowBias;
#endif
bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
if ( frustumTest ) {
float depth = texture2D( shadowMap, shadowCoord.xy ).r;
#ifdef USE_REVERSED_DEPTH_BUFFER
shadow = step( depth, shadowCoord.z );
#else
shadow = step( shadowCoord.z, depth );
#endif
}
return mix( 1.0, shadow, shadowIntensity );
}
#endif
#if NUM_POINT_LIGHT_SHADOWS > 0
#if defined( SHADOWMAP_TYPE_PCF )
float getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
float shadow = 1.0;
vec3 lightToPosition = shadowCoord.xyz;
vec3 bd3D = normalize( lightToPosition );
vec3 absVec = abs( lightToPosition );
float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );
if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {
#ifdef USE_REVERSED_DEPTH_BUFFER
float dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );
dp -= shadowBias;
#else
float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );
dp += shadowBias;
#endif
float texelSize = shadowRadius / shadowMapSize.x;
vec3 absDir = abs( bd3D );
vec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );
tangent = normalize( cross( bd3D, tangent ) );
vec3 bitangent = cross( bd3D, tangent );
float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;
vec2 sample0 = vogelDiskSample( 0, 5, phi );
vec2 sample1 = vogelDiskSample( 1, 5, phi );
vec2 sample2 = vogelDiskSample( 2, 5, phi );
vec2 sample3 = vogelDiskSample( 3, 5, phi );
vec2 sample4 = vogelDiskSample( 4, 5, phi );
shadow = (
texture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) +
texture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) +
texture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) +
texture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) +
texture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) )
) * 0.2;
}
return mix( 1.0, shadow, shadowIntensity );
}
#elif defined( SHADOWMAP_TYPE_BASIC )
float getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
float shadow = 1.0;
vec3 lightToPosition = shadowCoord.xyz;
vec3 absVec = abs( lightToPosition );
float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );
if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {
float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );
dp += shadowBias;
vec3 bd3D = normalize( lightToPosition );
float depth = textureCube( shadowMap, bd3D ).r;
#ifdef USE_REVERSED_DEPTH_BUFFER
depth = 1.0 - depth;
#endif
shadow = step( dp, depth );
}
return mix( 1.0, shadow, shadowIntensity );
}
#endif
#endif
#endif`,YBe=`#if NUM_SPOT_LIGHT_COORDS > 0
uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#ifdef USE_SHADOWMAP
#if NUM_DIR_LIGHT_SHADOWS > 0
uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
struct DirectionalLightShadow {
float shadowIntensity;
float shadowBias;
float shadowNormalBias;
float shadowRadius;
vec2 shadowMapSize;
};
uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
#endif
#if NUM_SPOT_LIGHT_SHADOWS > 0
struct SpotLightShadow {
float shadowIntensity;
float shadowBias;
float shadowNormalBias;
float shadowRadius;
vec2 shadowMapSize;
};
uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
#endif
#if NUM_POINT_LIGHT_SHADOWS > 0
uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
struct PointLightShadow {
float shadowIntensity;
float shadowBias;
float shadowNormalBias;
float shadowRadius;
vec2 shadowMapSize;
float shadowCameraNear;
float shadowCameraFar;
};
uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
#endif
#endif`,qBe=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
#ifdef HAS_NORMAL
vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
#else
vec3 shadowWorldNormal = vec3( 0.0 );
#endif
vec4 shadowWorldPosition;
#endif
#if defined( USE_SHADOWMAP )
#if NUM_DIR_LIGHT_SHADOWS > 0
#pragma unroll_loop_start
for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
}
#pragma unroll_loop_end
#endif
#if NUM_POINT_LIGHT_SHADOWS > 0
#pragma unroll_loop_start
for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
}
#pragma unroll_loop_end
#endif
#endif
#if NUM_SPOT_LIGHT_COORDS > 0
#pragma unroll_loop_start
for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
shadowWorldPosition = worldPosition;
#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
#endif
vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
}
#pragma unroll_loop_end
#endif`,$Be=`float getShadowMask() {
float shadow = 1.0;
#ifdef USE_SHADOWMAP
#if NUM_DIR_LIGHT_SHADOWS > 0
DirectionalLightShadow directionalLight;
#pragma unroll_loop_start
for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
directionalLight = directionalLightShadows[ i ];
shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
}
#pragma unroll_loop_end
#endif
#if NUM_SPOT_LIGHT_SHADOWS > 0
SpotLightShadow spotLight;
#pragma unroll_loop_start
for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
spotLight = spotLightShadows[ i ];
shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
}
#pragma unroll_loop_end
#endif
#if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )
PointLightShadow pointLight;
#pragma unroll_loop_start
for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
pointLight = pointLightShadows[ i ];
shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
}
#pragma unroll_loop_end
#endif
#endif
return shadow;
}`,ZBe=`#ifdef USE_SKINNING
mat4 boneMatX = getBoneMatrix( skinIndex.x );
mat4 boneMatY = getBoneMatrix( skinIndex.y );
mat4 boneMatZ = getBoneMatrix( skinIndex.z );
mat4 boneMatW = getBoneMatrix( skinIndex.w );
#endif`,KBe=`#ifdef USE_SKINNING
uniform mat4 bindMatrix;
uniform mat4 bindMatrixInverse;
uniform highp sampler2D boneTexture;
mat4 getBoneMatrix( const in float i ) {
int size = textureSize( boneTexture, 0 ).x;
int j = int( i ) * 4;
int x = j % size;
int y = j / size;
vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
return mat4( v1, v2, v3, v4 );
}
#endif`,QBe=`#ifdef USE_SKINNING
vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
vec4 skinned = vec4( 0.0 );
skinned += boneMatX * skinVertex * skinWeight.x;
skinned += boneMatY * skinVertex * skinWeight.y;
skinned += boneMatZ * skinVertex * skinWeight.z;
skinned += boneMatW * skinVertex * skinWeight.w;
transformed = ( bindMatrixInverse * skinned ).xyz;
#endif`,JBe=`#ifdef USE_SKINNING
mat4 skinMatrix = mat4( 0.0 );
skinMatrix += skinWeight.x * boneMatX;
skinMatrix += skinWeight.y * boneMatY;
skinMatrix += skinWeight.z * boneMatZ;
skinMatrix += skinWeight.w * boneMatW;
skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
#ifdef USE_TANGENT
objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
#endif
#endif`,XBe=`float specularStrength;
#ifdef USE_SPECULARMAP
vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
specularStrength = texelSpecular.r;
#else
specularStrength = 1.0;
#endif`,eFe=`#ifdef USE_SPECULARMAP
uniform sampler2D specularMap;
#endif`,tFe=`#if defined( TONE_MAPPING )
gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
#endif`,iFe=`#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
uniform float toneMappingExposure;
vec3 LinearToneMapping( vec3 color ) {
return saturate( toneMappingExposure * color );
}
vec3 ReinhardToneMapping( vec3 color ) {
color *= toneMappingExposure;
return saturate( color / ( vec3( 1.0 ) + color ) );
}
vec3 CineonToneMapping( vec3 color ) {
color *= toneMappingExposure;
color = max( vec3( 0.0 ), color - 0.004 );
return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
}
vec3 RRTAndODTFit( vec3 v ) {
vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
return a / b;
}
vec3 ACESFilmicToneMapping( vec3 color ) {
const mat3 ACESInputMat = mat3(
vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),
vec3( 0.04823, 0.01566, 0.83777 )
);
const mat3 ACESOutputMat = mat3(
vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),
vec3( -0.07367, -0.00605, 1.07602 )
);
color *= toneMappingExposure / 0.6;
color = ACESInputMat * color;
color = RRTAndODTFit( color );
color = ACESOutputMat * color;
return saturate( color );
}
const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(
vec3( 1.6605, - 0.1246, - 0.0182 ),
vec3( - 0.5876, 1.1329, - 0.1006 ),
vec3( - 0.0728, - 0.0083, 1.1187 )
);
const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(
vec3( 0.6274, 0.0691, 0.0164 ),
vec3( 0.3293, 0.9195, 0.0880 ),
vec3( 0.0433, 0.0113, 0.8956 )
);
vec3 agxDefaultContrastApprox( vec3 x ) {
vec3 x2 = x * x;
vec3 x4 = x2 * x2;
return + 15.5 * x4 * x2
- 40.14 * x4 * x
+ 31.96 * x4
- 6.868 * x2 * x
+ 0.4298 * x2
+ 0.1191 * x
- 0.00232;
}
vec3 AgXToneMapping( vec3 color ) {
const mat3 AgXInsetMatrix = mat3(
vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),
vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),
vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )
);
const mat3 AgXOutsetMatrix = mat3(
vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),
vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),
vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )
);
const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069;
color *= toneMappingExposure;
color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;
color = AgXInsetMatrix * color;
color = max( color, 1e-10 ); color = log2( color );
color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );
color = clamp( color, 0.0, 1.0 );
color = agxDefaultContrastApprox( color );
color = AgXOutsetMatrix * color;
color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );
color = LINEAR_REC2020_TO_LINEAR_SRGB * color;
color = clamp( color, 0.0, 1.0 );
return color;
}
vec3 NeutralToneMapping( vec3 color ) {
const float StartCompression = 0.8 - 0.04;
const float Desaturation = 0.15;
color *= toneMappingExposure;
float x = min( color.r, min( color.g, color.b ) );
float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
color -= offset;
float peak = max( color.r, max( color.g, color.b ) );
if ( peak < StartCompression ) return color;
float d = 1. - StartCompression;
float newPeak = 1. - d * d / ( peak + d - StartCompression );
color *= newPeak / peak;
float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
return mix( color, vec3( newPeak ), g );
}
vec3 CustomToneMapping( vec3 color ) { return color; }`,nFe=`#ifdef USE_TRANSMISSION
material.transmission = transmission;
material.transmissionAlpha = 1.0;
material.thickness = thickness;
material.attenuationDistance = attenuationDistance;
material.attenuationColor = attenuationColor;
#ifdef USE_TRANSMISSIONMAP
material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
#endif
#ifdef USE_THICKNESSMAP
material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
#endif
vec3 pos = vWorldPosition;
vec3 v = normalize( cameraPosition - pos );
vec3 n = inverseTransformDirection( normal, viewMatrix );
vec4 transmitted = getIBLVolumeRefraction(
n, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90,
pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,
material.attenuationColor, material.attenuationDistance );
material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
#endif`,sFe=`#ifdef USE_TRANSMISSION
uniform float transmission;
uniform float thickness;
uniform float attenuationDistance;
uniform vec3 attenuationColor;
#ifdef USE_TRANSMISSIONMAP
uniform sampler2D transmissionMap;
#endif
#ifdef USE_THICKNESSMAP
uniform sampler2D thicknessMap;
#endif
uniform vec2 transmissionSamplerSize;
uniform sampler2D transmissionSamplerMap;
uniform mat4 modelMatrix;
uniform mat4 projectionMatrix;
varying vec3 vWorldPosition;
float w0( float a ) {
return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
}
float w1( float a ) {
return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );
}
float w2( float a ){
return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
}
float w3( float a ) {
return ( 1.0 / 6.0 ) * ( a * a * a );
}
float g0( float a ) {
return w0( a ) + w1( a );
}
float g1( float a ) {
return w2( a ) + w3( a );
}
float h0( float a ) {
return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
}
float h1( float a ) {
return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
}
vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
uv = uv * texelSize.zw + 0.5;
vec2 iuv = floor( uv );
vec2 fuv = fract( uv );
float g0x = g0( fuv.x );
float g1x = g1( fuv.x );
float h0x = h0( fuv.x );
float h1x = h1( fuv.x );
float h0y = h0( fuv.y );
float h1y = h1( fuv.y );
vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
}
vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
vec2 fLodSizeInv = 1.0 / fLodSize;
vec2 cLodSizeInv = 1.0 / cLodSize;
vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
return mix( fSample, cSample, fract( lod ) );
}
vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
vec3 modelScale;
modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
return normalize( refractionVector ) * thickness * modelScale;
}
float applyIorToRoughness( const in float roughness, const in float ior ) {
return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
}
vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );
}
vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
if ( isinf( attenuationDistance ) ) {
return vec3( 1.0 );
} else {
vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance;
}
}
vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,
const in vec3 attenuationColor, const in float attenuationDistance ) {
vec4 transmittedLight;
vec3 transmittance;
#ifdef USE_DISPERSION
float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;
vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );
for ( int i = 0; i < 3; i ++ ) {
vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );
vec3 refractedRayExit = position + transmissionRay;
vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
vec2 refractionCoords = ndcPos.xy / ndcPos.w;
refractionCoords += 1.0;
refractionCoords /= 2.0;
vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );
transmittedLight[ i ] = transmissionSample[ i ];
transmittedLight.a += transmissionSample.a;
transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];
}
transmittedLight.a /= 3.0;
#else
vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
vec3 refractedRayExit = position + transmissionRay;
vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
vec2 refractionCoords = ndcPos.xy / ndcPos.w;
refractionCoords += 1.0;
refractionCoords /= 2.0;
transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
#endif
vec3 attenuatedColor = transmittance * transmittedLight.rgb;
vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
}
#endif`,oFe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
varying vec2 vUv;
#endif
#ifdef USE_MAP
varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
varying vec2 vNormalMapUv;
#endif
#ifdef USE_EMISSIVEMAP
varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_SPECULARMAP
varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
uniform mat3 transmissionMapTransform;
varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
uniform mat3 thicknessMapTransform;
varying vec2 vThicknessMapUv;
#endif`,rFe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
varying vec2 vUv;
#endif
#ifdef USE_MAP
uniform mat3 mapTransform;
varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
uniform mat3 alphaMapTransform;
varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
uniform mat3 lightMapTransform;
varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
uniform mat3 aoMapTransform;
varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
uniform mat3 bumpMapTransform;
varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
uniform mat3 normalMapTransform;
varying vec2 vNormalMapUv;
#endif
#ifdef USE_DISPLACEMENTMAP
uniform mat3 displacementMapTransform;
varying vec2 vDisplacementMapUv;
#endif
#ifdef USE_EMISSIVEMAP
uniform mat3 emissiveMapTransform;
varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
uniform mat3 metalnessMapTransform;
varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
uniform mat3 roughnessMapTransform;
varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
uniform mat3 anisotropyMapTransform;
varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
uniform mat3 clearcoatMapTransform;
varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
uniform mat3 clearcoatNormalMapTransform;
varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
uniform mat3 clearcoatRoughnessMapTransform;
varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
uniform mat3 sheenColorMapTransform;
varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
uniform mat3 sheenRoughnessMapTransform;
varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
uniform mat3 iridescenceMapTransform;
varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
uniform mat3 iridescenceThicknessMapTransform;
varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SPECULARMAP
uniform mat3 specularMapTransform;
varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
uniform mat3 specularColorMapTransform;
varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
uniform mat3 specularIntensityMapTransform;
varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
uniform mat3 transmissionMapTransform;
varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
uniform mat3 thicknessMapTransform;
varying vec2 vThicknessMapUv;
#endif`,lFe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
vUv = vec3( uv, 1 ).xy;
#endif
#ifdef USE_MAP
vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ALPHAMAP
vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_LIGHTMAP
vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_AOMAP
vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_BUMPMAP
vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_NORMALMAP
vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_DISPLACEMENTMAP
vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_EMISSIVEMAP
vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_METALNESSMAP
vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ROUGHNESSMAP
vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ANISOTROPYMAP
vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOATMAP
vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCEMAP
vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_COLORMAP
vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULARMAP
vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_COLORMAP
vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_TRANSMISSIONMAP
vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_THICKNESSMAP
vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
#endif`,aFe=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
vec4 worldPosition = vec4( transformed, 1.0 );
#ifdef USE_BATCHING
worldPosition = batchingMatrix * worldPosition;
#endif
#ifdef USE_INSTANCING
worldPosition = instanceMatrix * worldPosition;
#endif
worldPosition = modelMatrix * worldPosition;
#endif`,uFe=`varying vec2 vUv;
uniform mat3 uvTransform;
void main() {
vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
gl_Position = vec4( position.xy, 1.0, 1.0 );
}`,cFe=`uniform sampler2D t2D;
uniform float backgroundIntensity;
varying vec2 vUv;
void main() {
vec4 texColor = texture2D( t2D, vUv );
#ifdef DECODE_VIDEO_TEXTURE
texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );
#endif
texColor.rgb *= backgroundIntensity;
gl_FragColor = texColor;
#include <tonemapping_fragment>
#include <colorspace_fragment>
}`,dFe=`varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
gl_Position.z = gl_Position.w;
}`,hFe=`#ifdef ENVMAP_TYPE_CUBE
uniform samplerCube envMap;
#elif defined( ENVMAP_TYPE_CUBE_UV )
uniform sampler2D envMap;
#endif
uniform float backgroundBlurriness;
uniform float backgroundIntensity;
uniform mat3 backgroundRotation;
varying vec3 vWorldDirection;
#include <cube_uv_reflection_fragment>
void main() {
#ifdef ENVMAP_TYPE_CUBE
vec4 texColor = textureCube( envMap, backgroundRotation * vWorldDirection );
#elif defined( ENVMAP_TYPE_CUBE_UV )
vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );
#else
vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
#endif
texColor.rgb *= backgroundIntensity;
gl_FragColor = texColor;
#include <tonemapping_fragment>
#include <colorspace_fragment>
}`,fFe=`varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
gl_Position.z = gl_Position.w;
}`,pFe=`uniform samplerCube tCube;
uniform float tFlip;
uniform float opacity;
varying vec3 vWorldDirection;
void main() {
vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
gl_FragColor = texColor;
gl_FragColor.a *= opacity;
#include <tonemapping_fragment>
#include <colorspace_fragment>
}`,mFe=`#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
varying vec2 vHighPrecisionZW;
void main() {
#include <uv_vertex>
#include <batching_vertex>
#include <skinbase_vertex>
#include <morphinstance_vertex>
#ifdef USE_DISPLACEMENTMAP
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinnormal_vertex>
#endif
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
vHighPrecisionZW = gl_Position.zw;
}`,IFe=`#if DEPTH_PACKING == 3200
uniform float opacity;
#endif
#include <common>
#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
varying vec2 vHighPrecisionZW;
void main() {
vec4 diffuseColor = vec4( 1.0 );
#include <clipping_planes_fragment>
#if DEPTH_PACKING == 3200
diffuseColor.a = opacity;
#endif
#include <map_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <logdepthbuf_fragment>
#ifdef USE_REVERSED_DEPTH_BUFFER
float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];
#else
float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;
#endif
#if DEPTH_PACKING == 3200
gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
#elif DEPTH_PACKING == 3201
gl_FragColor = packDepthToRGBA( fragCoordZ );
#elif DEPTH_PACKING == 3202
gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );
#elif DEPTH_PACKING == 3203
gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );
#endif
}`,yFe=`#define DISTANCE
varying vec3 vWorldPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <batching_vertex>
#include <skinbase_vertex>
#include <morphinstance_vertex>
#ifdef USE_DISPLACEMENTMAP
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinnormal_vertex>
#endif
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <worldpos_vertex>
#include <clipping_planes_vertex>
vWorldPosition = worldPosition.xyz;
}`,gFe=`#define DISTANCE
uniform vec3 referencePosition;
uniform float nearDistance;
uniform float farDistance;
varying vec3 vWorldPosition;
#include <common>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <clipping_planes_pars_fragment>
void main () {
vec4 diffuseColor = vec4( 1.0 );
#include <clipping_planes_fragment>
#include <map_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
float dist = length( vWorldPosition - referencePosition );
dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
dist = saturate( dist );
gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 );
}`,EFe=`varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
}`,TFe=`uniform sampler2D tEquirect;
varying vec3 vWorldDirection;
#include <common>
void main() {
vec3 direction = normalize( vWorldDirection );
vec2 sampleUV = equirectUv( direction );
gl_FragColor = texture2D( tEquirect, sampleUV );
#include <tonemapping_fragment>
#include <colorspace_fragment>
}`,wFe=`uniform float scale;
attribute float lineDistance;
varying float vLineDistance;
#include <common>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
vLineDistance = scale * lineDistance;
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <fog_vertex>
}`,vFe=`uniform vec3 diffuse;
uniform float opacity;
uniform float dashSize;
uniform float totalSize;
varying float vLineDistance;
#include <common>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
if ( mod( vLineDistance, totalSize ) > dashSize ) {
discard;
}
vec3 outgoingLight = vec3( 0.0 );
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
outgoingLight = diffuseColor.rgb;
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
}`,SFe=`#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#endif
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <worldpos_vertex>
#include <envmap_vertex>
#include <fog_vertex>
}`,RFe=`uniform vec3 diffuse;
uniform float opacity;
#ifndef FLAT_SHADED
varying vec3 vNormal;
#endif
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <specularmap_fragment>
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
#ifdef USE_LIGHTMAP
vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
#else
reflectedLight.indirectDiffuse += vec3( 1.0 );
#endif
#include <aomap_fragment>
reflectedLight.indirectDiffuse *= diffuseColor.rgb;
vec3 outgoingLight = reflectedLight.indirectDiffuse;
#include <envmap_fragment>
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,_Fe=`#define LAMBERT
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
vViewPosition = - mvPosition.xyz;
#include <worldpos_vertex>
#include <envmap_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
}`,bFe=`#define LAMBERT
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <envmap_physical_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_lambert_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
vec3 totalEmissiveRadiance = emissive;
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <specularmap_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
#include <emissivemap_fragment>
#include <lights_lambert_fragment>
#include <lights_fragment_begin>
#include <lights_fragment_maps>
#include <lights_fragment_end>
#include <aomap_fragment>
vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
#include <envmap_fragment>
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,AFe=`#define MATCAP
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <displacementmap_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <fog_vertex>
vViewPosition = - mvPosition.xyz;
}`,xFe=`#define MATCAP
uniform vec3 diffuse;
uniform float opacity;
uniform sampler2D matcap;
varying vec3 vViewPosition;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
vec3 viewDir = normalize( vViewPosition );
vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
vec3 y = cross( viewDir, x );
vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
#ifdef USE_MATCAP
vec4 matcapColor = texture2D( matcap, uv );
#else
vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
#endif
vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,CFe=`#define NORMAL
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
varying vec3 vViewPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphinstance_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
vViewPosition = - mvPosition.xyz;
#endif
}`,DFe=`#define NORMAL
uniform float opacity;
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
varying vec3 vViewPosition;
#endif
#include <uv_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );
#include <clipping_planes_fragment>
#include <logdepthbuf_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
gl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a );
#ifdef OPAQUE
gl_FragColor.a = 1.0;
#endif
}`,NFe=`#define PHONG
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphinstance_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
vViewPosition = - mvPosition.xyz;
#include <worldpos_vertex>
#include <envmap_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
}`,OFe=`#define PHONG
uniform vec3 diffuse;
uniform vec3 emissive;
uniform vec3 specular;
uniform float shininess;
uniform float opacity;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <envmap_physical_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_phong_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
vec3 totalEmissiveRadiance = emissive;
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <specularmap_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
#include <emissivemap_fragment>
#include <lights_phong_fragment>
#include <lights_fragment_begin>
#include <lights_fragment_maps>
#include <lights_fragment_end>
#include <aomap_fragment>
vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
#include <envmap_fragment>
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,LFe=`#define STANDARD
varying vec3 vViewPosition;
#ifdef USE_TRANSMISSION
varying vec3 vWorldPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
vViewPosition = - mvPosition.xyz;
#include <worldpos_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
#ifdef USE_TRANSMISSION
vWorldPosition = worldPosition.xyz;
#endif
}`,PFe=`#define STANDARD
#ifdef PHYSICAL
#define IOR
#define USE_SPECULAR
#endif
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float roughness;
uniform float metalness;
uniform float opacity;
#ifdef IOR
uniform float ior;
#endif
#ifdef USE_SPECULAR
uniform float specularIntensity;
uniform vec3 specularColor;
#ifdef USE_SPECULAR_COLORMAP
uniform sampler2D specularColorMap;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
uniform sampler2D specularIntensityMap;
#endif
#endif
#ifdef USE_CLEARCOAT
uniform float clearcoat;
uniform float clearcoatRoughness;
#endif
#ifdef USE_DISPERSION
uniform float dispersion;
#endif
#ifdef USE_IRIDESCENCE
uniform float iridescence;
uniform float iridescenceIOR;
uniform float iridescenceThicknessMinimum;
uniform float iridescenceThicknessMaximum;
#endif
#ifdef USE_SHEEN
uniform vec3 sheenColor;
uniform float sheenRoughness;
#ifdef USE_SHEEN_COLORMAP
uniform sampler2D sheenColorMap;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
uniform sampler2D sheenRoughnessMap;
#endif
#endif
#ifdef USE_ANISOTROPY
uniform vec2 anisotropyVector;
#ifdef USE_ANISOTROPYMAP
uniform sampler2D anisotropyMap;
#endif
#endif
varying vec3 vViewPosition;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <iridescence_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_physical_pars_fragment>
#include <fog_pars_fragment>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_physical_pars_fragment>
#include <transmission_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <clearcoat_pars_fragment>
#include <iridescence_pars_fragment>
#include <roughnessmap_pars_fragment>
#include <metalnessmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
vec3 totalEmissiveRadiance = emissive;
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <roughnessmap_fragment>
#include <metalnessmap_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
#include <clearcoat_normal_fragment_begin>
#include <clearcoat_normal_fragment_maps>
#include <emissivemap_fragment>
#include <lights_physical_fragment>
#include <lights_fragment_begin>
#include <lights_fragment_maps>
#include <lights_fragment_end>
#include <aomap_fragment>
vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
#include <transmission_fragment>
vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
#ifdef USE_SHEEN
outgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect;
#endif
#ifdef USE_CLEARCOAT
float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
#endif
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,MFe=`#define TOON
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
vViewPosition = - mvPosition.xyz;
#include <worldpos_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
}`,BFe=`#define TOON
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <gradientmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_toon_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
vec3 totalEmissiveRadiance = emissive;
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <color_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
#include <emissivemap_fragment>
#include <lights_toon_fragment>
#include <lights_fragment_begin>
#include <lights_fragment_maps>
#include <lights_fragment_end>
#include <aomap_fragment>
vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
}`,FFe=`uniform float size;
uniform float scale;
#include <common>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
#ifdef USE_POINTS_UV
varying vec2 vUv;
uniform mat3 uvTransform;
#endif
void main() {
#ifdef USE_POINTS_UV
vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
#endif
#include <color_vertex>
#include <morphinstance_vertex>
#include <morphcolor_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <project_vertex>
gl_PointSize = size;
#ifdef USE_SIZEATTENUATION
bool isPerspective = isPerspectiveMatrix( projectionMatrix );
if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
#endif
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <worldpos_vertex>
#include <fog_vertex>
}`,UFe=`uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <color_pars_fragment>
#include <map_particle_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
vec3 outgoingLight = vec3( 0.0 );
#include <logdepthbuf_fragment>
#include <map_particle_fragment>
#include <color_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
outgoingLight = diffuseColor.rgb;
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
}`,HFe=`#include <common>
#include <batching_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <shadowmap_pars_vertex>
void main() {
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphinstance_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <worldpos_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
}`,GFe=`uniform vec3 color;
uniform float opacity;
#include <common>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <logdepthbuf_pars_fragment>
#include <shadowmap_pars_fragment>
#include <shadowmask_pars_fragment>
void main() {
#include <logdepthbuf_fragment>
gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
}`,VFe=`uniform float rotation;
uniform vec2 center;
#include <common>
#include <uv_pars_vertex>
#include <fog_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
#include <uv_vertex>
vec4 mvPosition = modelViewMatrix[ 3 ];
vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );
#ifndef USE_SIZEATTENUATION
bool isPerspective = isPerspectiveMatrix( projectionMatrix );
if ( isPerspective ) scale *= - mvPosition.z;
#endif
vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
vec2 rotatedPosition;
rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
mvPosition.xy += rotatedPosition;
gl_Position = projectionMatrix * mvPosition;
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <fog_vertex>
}`,kFe=`uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
vec4 diffuseColor = vec4( diffuse, opacity );
#include <clipping_planes_fragment>
vec3 outgoingLight = vec3( 0.0 );
#include <logdepthbuf_fragment>
#include <map_fragment>
#include <alphamap_fragment>
#include <alphatest_fragment>
#include <alphahash_fragment>
outgoingLight = diffuseColor.rgb;
#include <opaque_fragment>
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
}`,mo={alphahash_fragment:u8e,alphahash_pars_fragment:c8e,alphamap_fragment:d8e,alphamap_pars_fragment:h8e,alphatest_fragment:f8e,alphatest_pars_fragment:p8e,aomap_fragment:m8e,aomap_pars_fragment:I8e,batching_pars_vertex:y8e,batching_vertex:g8e,begin_vertex:E8e,beginnormal_vertex:T8e,bsdfs:w8e,iridescence_fragment:v8e,bumpmap_pars_fragment:S8e,clipping_planes_fragment:R8e,clipping_planes_pars_fragment:_8e,clipping_planes_pars_vertex:b8e,clipping_planes_vertex:A8e,color_fragment:x8e,color_pars_fragment:C8e,color_pars_vertex:D8e,color_vertex:N8e,common:O8e,cube_uv_reflection_fragment:L8e,defaultnormal_vertex:P8e,displacementmap_pars_vertex:M8e,displacementmap_vertex:B8e,emissivemap_fragment:F8e,emissivemap_pars_fragment:U8e,colorspace_fragment:H8e,colorspace_pars_fragment:G8e,envmap_fragment:V8e,envmap_common_pars_fragment:k8e,envmap_pars_fragment:z8e,envmap_pars_vertex:W8e,envmap_physical_pars_fragment:tBe,envmap_vertex:j8e,fog_vertex:Y8e,fog_pars_vertex:q8e,fog_fragment:$8e,fog_pars_fragment:Z8e,gradientmap_pars_fragment:K8e,lightmap_pars_fragment:Q8e,lights_lambert_fragment:J8e,lights_lambert_pars_fragment:X8e,lights_pars_begin:eBe,lights_toon_fragment:iBe,lights_toon_pars_fragment:nBe,lights_phong_fragment:sBe,lights_phong_pars_fragment:oBe,lights_physical_fragment:rBe,lights_physical_pars_fragment:lBe,lights_fragment_begin:aBe,lights_fragment_maps:uBe,lights_fragment_end:cBe,lightprobes_pars_fragment:dBe,logdepthbuf_fragment:hBe,logdepthbuf_pars_fragment:fBe,logdepthbuf_pars_vertex:pBe,logdepthbuf_vertex:mBe,map_fragment:IBe,map_pars_fragment:yBe,map_particle_fragment:gBe,map_particle_pars_fragment:EBe,metalnessmap_fragment:TBe,metalnessmap_pars_fragment:wBe,morphinstance_vertex:vBe,morphcolor_vertex:SBe,morphnormal_vertex:RBe,morphtarget_pars_vertex:_Be,morphtarget_vertex:bBe,normal_fragment_begin:ABe,normal_fragment_maps:xBe,normal_pars_fragment:CBe,normal_pars_vertex:DBe,normal_vertex:NBe,normalmap_pars_fragment:OBe,clearcoat_normal_fragment_begin:LBe,clearcoat_normal_fragment_maps:PBe,clearcoat_pars_fragment:MBe,iridescence_pars_fragment:BBe,opaque_fragment:FBe,packing:UBe,premultiplied_alpha_fragment:HBe,project_vertex:GBe,dithering_fragment:VBe,dithering_pars_fragment:kBe,roughnessmap_fragment:zBe,roughnessmap_pars_fragment:WBe,shadowmap_pars_fragment:jBe,shadowmap_pars_vertex:YBe,shadowmap_vertex:qBe,shadowmask_pars_fragment:$Be,skinbase_vertex:ZBe,skinning_pars_vertex:KBe,skinning_vertex:QBe,skinnormal_vertex:JBe,specularmap_fragment:XBe,specularmap_pars_fragment:eFe,tonemapping_fragment:tFe,tonemapping_pars_fragment:iFe,transmission_fragment:nFe,transmission_pars_fragment:sFe,uv_pars_fragment:oFe,uv_pars_vertex:rFe,uv_vertex:lFe,worldpos_vertex:aFe,background_vert:uFe,background_frag:cFe,backgroundCube_vert:dFe,backgroundCube_frag:hFe,cube_vert:fFe,cube_frag:pFe,depth_vert:mFe,depth_frag:IFe,distance_vert:yFe,distance_frag:gFe,equirect_vert:EFe,equirect_frag:TFe,linedashed_vert:wFe,linedashed_frag:vFe,meshbasic_vert:SFe,meshbasic_frag:RFe,meshlambert_vert:_Fe,meshlambert_frag:bFe,meshmatcap_vert:AFe,meshmatcap_frag:xFe,meshnormal_vert:CFe,meshnormal_frag:DFe,meshphong_vert:NFe,meshphong_frag:OFe,meshphysical_vert:LFe,meshphysical_frag:PFe,meshtoon_vert:MFe,meshtoon_frag:BFe,points_vert:FFe,points_frag:UFe,shadow_vert:HFe,shadow_frag:GFe,sprite_vert:VFe,sprite_frag:kFe},yn={common:{diffuse:{value:new Ei(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new us},alphaMap:{value:null},alphaMapTransform:{value:new us},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new us}},envmap:{envMap:{value:null},envMapRotation:{value:new us},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new us}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new us}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new us},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new us},normalScale:{value:n
precision highp float;
precision highp int;
varying vec3 vOutputDirection;
uniform sampler2D envMap;
uniform float roughness;
uniform float mipInt;
#define ENVMAP_TYPE_CUBE_UV
#include <cube_uv_reflection_fragment>
#define PI 3.14159265359
// Van der Corput radical inverse
float radicalInverse_VdC(uint bits) {
bits = (bits << 16u) | (bits >> 16u);
bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
return float(bits) * 2.3283064365386963e-10; // / 0x100000000
}
// Hammersley sequence
vec2 hammersley(uint i, uint N) {
return vec2(float(i) / float(N), radicalInverse_VdC(i));
}
// GGX VNDF importance sampling (Eric Heitz 2018)
// "Sampling the GGX Distribution of Visible Normals"
// https://jcgt.org/published/0007/04/01/
vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {
float alpha = roughness * roughness;
// Section 4.1: Orthonormal basis
vec3 T1 = vec3(1.0, 0.0, 0.0);
vec3 T2 = cross(V, T1);
// Section 4.2: Parameterization of projected area
float r = sqrt(Xi.x);
float phi = 2.0 * PI * Xi.y;
float t1 = r * cos(phi);
float t2 = r * sin(phi);
float s = 0.5 * (1.0 + V.z);
t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;
// Section 4.3: Reprojection onto hemisphere
vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V;
// Section 3.4: Transform back to ellipsoid configuration
return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));
}
void main() {
vec3 N = normalize(vOutputDirection);
vec3 V = N; // Assume view direction equals normal for pre-filtering
vec3 prefilteredColor = vec3(0.0);
float totalWeight = 0.0;
// For very low roughness, just sample the environment directly
if (roughness < 0.001) {
gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);
return;
}
// Tangent space basis for VNDF sampling
vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
vec3 tangent = normalize(cross(up, N));
vec3 bitangent = cross(N, tangent);
for(uint i = 0u; i < uint(GGX_SAMPLES); i++) {
vec2 Xi = hammersley(i, uint(GGX_SAMPLES));
// For PMREM, V = N, so in tangent space V is always (0, 0, 1)
vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);
// Transform H back to world space
vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);
vec3 L = normalize(2.0 * dot(V, H) * H - V);
float NdotL = max(dot(N, L), 0.0);
if(NdotL > 0.0) {
// Sample environment at fixed mip level
// VNDF importance sampling handles the distribution filtering
vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);
// Weight by NdotL for the split-sum approximation
// VNDF PDF naturally accounts for the visible microfacet distribution
prefilteredColor += sampleColor * NdotL;
totalWeight += NdotL;
}
}
if (totalWeight > 0.0) {
prefilteredColor = prefilteredColor / totalWeight;
}
gl_FragColor = vec4(prefilteredColor, 1.0);
}
`,blending:jo,depthTest:!1,depthWrite:!1})}function XFe(e,t,i){let n=new Float32Array(cO),s=new ne(0,1,0);return new Bs({name:"SphericalGaussianBlur",defines:{n:cO,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/i,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:_K(),fragmentShader:`
precision mediump float;
precision mediump int;
varying vec3 vOutputDirection;
uniform sampler2D envMap;
uniform int samples;
uniform float weights[ n ];
uniform bool latitudinal;
uniform float dTheta;
uniform float mipInt;
uniform vec3 poleAxis;
#define ENVMAP_TYPE_CUBE_UV
#include <cube_uv_reflection_fragment>
vec3 getSample( float theta, vec3 axis ) {
float cosTheta = cos( theta );
// Rodrigues' axis-angle rotation
vec3 sampleDirection = vOutputDirection * cosTheta
+ cross( axis, vOutputDirection ) * sin( theta )
+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
return bilinearCubeUV( envMap, sampleDirection, mipInt );
}
void main() {
vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
}
axis = normalize( axis );
gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
for ( int i = 1; i < n; i++ ) {
if ( i >= samples ) {
break;
}
float theta = dTheta * float( i );
gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
}
}
`,blending:jo,depthTest:!1,depthWrite:!1})}function Awe(){return new Bs({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:_K(),fragmentShader:`
precision mediump float;
precision mediump int;
varying vec3 vOutputDirection;
uniform sampler2D envMap;
#include <common>
void main() {
vec3 outputDirection = normalize( vOutputDirection );
vec2 uv = equirectUv( outputDirection );
gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
}
`,blending:jo,depthTest:!1,depthWrite:!1})}function xwe(){return new Bs({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:_K(),fragmentShader:`
precision mediump float;
precision mediump int;
uniform float flipEnvMap;
varying vec3 vOutputDirection;
uniform samplerCube envMap;
void main() {
gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
}
`,blending:jo,depthTest:!1,depthWrite:!1})}function _K(){return`
precision mediump float;
precision mediump int;
attribute float faceIndex;
varying vec3 vOutputDirection;
// RH coordinate system; PMREM face-indexing convention
vec3 getDirection( vec2 uv, float face ) {
uv = 2.0 * uv - 1.0;
vec3 direction = vec3( uv, 1.0 );
if ( face == 0.0 ) {
direction = direction.zyx; // ( 1, v, u ) pos x
} else if ( face == 1.0 ) {
direction = direction.xzy;
direction.xz *= -1.0; // ( -u, 1, -v ) pos y
} else if ( face == 2.0 ) {
direction.x *= -1.0; // ( -u, v, 1 ) pos z
} else if ( face == 3.0 ) {
direction = direction.zyx;
direction.xz *= -1.0; // ( -1, v, -u ) neg x
} else if ( face == 4.0 ) {
direction = direction.xzy;
direction.xy *= -1.0; // ( -u, -1, v ) neg y
} else if ( face == 5.0 ) {
direction.z *= -1.0; // ( u, v, -1 ) neg z
}
return direction;
}
void main() {
vOutputDirection = getDirection( uv, faceIndex );
gl_Position = vec4( position, 1.0 );
}
`}var Nz=class extends bo{constructor(t=1,i={}){super(t,t,i),this.isWebGLCubeRenderTarget=!0;let n={width:t,height:t,depth:1},s=[n,n,n,n,n,n];this.texture=new jy(s),this._setTextureOptions(i),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(t,i){this.texture.type=i.type,this.texture.colorSpace=i.colorSpace,this.texture.generateMipmaps=i.generateMipmaps,this.texture.minFilter=i.minFilter,this.texture.magFilter=i.magFilter;let n={uniforms:{tEquirect:{value:null}},vertexShader:`
varying vec3 vWorldDirection;
vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
}
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
}
`,fragmentShader:`
uniform sampler2D tEquirect;
varying vec3 vWorldDirection;
#include <common>
void main() {
vec3 direction = normalize( vWorldDirection );
vec2 sampleUV = equirectUv( direction );
gl_FragColor = texture2D( tEquirect, sampleUV );
}
`},s=new Gr(5,5,5),o=new Bs({name:"CubemapFromEquirect",uniforms:uO(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:wo,blending:jo});o.uniforms.tEquirect.value=i;let r=new ci(s,o),l=i.minFilter;return i.minFilter===$d&&(i.minFilter=Ds),new eO(1,10,this).update(t,r),i.minFilter=l,r.geometry.dispose(),r.material.dispose(),this}clear(t,i=!0,n=!0,s=!0){let o=t.getRenderTarget();for(let r=0;r<6;r++)t.setRenderTarget(this,r),t.clear(i,n,s);t.setRenderTarget(o)}};function eUe(e){let t=new WeakMap,i=new WeakMap,n=null;function s(m,I=!1){return m==null?null:I?r(m):o(m)}function o(m){if(m&&m.isTexture){let I=m.mapping;if(I===Fv||I===Uv)if(t.has(m)){let g=t.get(m).texture;return l(g,m.mapping)}else{let g=m.image;if(g&&g.height>0){let E=new Nz(g.height);return E.fromEquirectangularTexture(e,m),t.set(m,E),m.addEventListener("dispose",u),l(E.texture,m.mapping)}else return null}}return m}function r(m){if(m&&m.isTexture){let I=m.mapping,g=I===Fv||I===Uv,E=I===vp||I===ty;if(g||E){let w=i.get(m),T=w!==void 0?w.texture.pmremVersion:0;if(m.isRenderTargetTexture&&m.pmremVersion!==T)return n===null&&(n=new Dz(e)),w=g?n.fromEquirectangular(m,w):n.fromCubemap(m,w),w.texture.pmremVersion=m.pmremVersion,i.set(m,w),w.texture;if(w!==void 0)return w.texture;{let S=m.image;return g&&S&&S.height>0||E&&S&&a(S)?(n===null&&(n=new Dz(e)),w=g?n.fromEquirectangular(m):n.fromCubemap(m),w.texture.pmremVersion=m.pmremVersion,i.set(m,w),m.addEventListener("dispose",h),w.texture):null}}}return m}function l(m,I){return I===Fv?m.mapping=vp:I===Uv&&(m.mapping=ty),m}function a(m){let I=0,g=6;for(let E=0;E<g;E++)m[E]!==void 0&&I++;return I===g}function u(m){let I=m.target;I.removeEventListener("dispose",u);let g=t.get(I);g!==void 0&&(t.delete(I),g.dispose())}function h(m){let I=m.target;I.removeEventListener("dispose",h);let g=i.get(I);g!==void 0&&(i.delete(I),g.dispose())}function p(){t=new WeakMap,i=new WeakMap,n!==null&&(n.dispose(),n=null)}return{get:s,dispose:p}}function tUe(e){let t={};function i(n){if(t[n]!==void 0)return t[n];let s=e.getExtension(n);return t[n]=s,s}return{has:function(n){return i(n)!==null},init:function(){i("EXT_color_buffer_float"),i("WEBGL_clip_cull_distance"),i("OES_texture_float_linear"),i("EXT_color_buffer_half_float"),i("WEBGL_multisampled_render_to_texture"),i("WEBGL_render_shared_exponent")},get:function(n){let s=i(n);return s===null&&yr("WebGLRenderer: "+n+" extension not supported."),s}}}function iUe(e,t,i,n){let s={},o=new WeakMap;function r(p){let m=p.target;m.index!==null&&t.remove(m.index);for(let g in m.attributes)t.remove(m.attributes[g]);m.removeEventListener("dispose",r),delete s[m.id];let I=o.get(m);I&&(t.remove(I),o.delete(m)),n.releaseStatesOfGeometry(m),m.isInstancedBufferGeometry===!0&&delete m._maxInstanceCount,i.memory.geometries--}function l(p,m){return s[m.id]===!0||(m.addEventListener("dispose",r),s[m.id]=!0,i.memory.geometries++),m}function a(p){let m=p.attributes;for(let I in m)t.update(m[I],e.ARRAY_BUFFER)}function u(p){let m=[],I=p.index,g=p.attributes.position,E=0;if(g===void 0)return;if(I!==null){let S=I.array;E=I.version;for(let _=0,x=S.length;_<x;_+=3){let M=S[_+0],W=S[_+1],G=S[_+2];m.push(M,W,W,G,G,M)}}else{let S=g.array;E=g.version;for(let _=0,x=S.length/3-1;_<x;_+=3){let M=_+0,W=_+1,G=_+2;m.push(M,W,W,G,G,M)}}let w=new(g.count>=65535?Fx:Bx)(m,1);w.version=E;let T=o.get(p);T&&t.remove(T),o.set(p,w)}function h(p){let m=o.get(p);if(m){let I=p.index;I!==null&&m.version<I.version&&u(p)}else u(p);return o.get(p)}return{get:l,update:a,getWireframeAttribute:h}}function nUe(e,t,i){let n;function s(p){n=p}let o,r;function l(p){o=p.type,r=p.bytesPerElement}function a(p,m){e.drawElements(n,m,o,p*r),i.update(m,n,1)}function u(p,m,I){I!==0&&(e.drawElementsInstanced(n,m,o,p*r,I),i.update(m,n,I))}function h(p,m,I){if(I===0)return;t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,m,0,o,p,0,I);let E=0;for(let w=0;w<I;w++)E+=m[w];i.update(E,n,1)}this.setMode=s,this.setIndex=l,this.render=a,this.renderInstances=u,this.renderMultiDraw=h}function sUe(e){let t={geometries:0,textures:0},i={fra
precision highp float;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
attribute vec3 position;
attribute vec2 uv;
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,fragmentShader:`
precision highp float;
uniform sampler2D tDiffuse;
varying vec2 vUv;
#include <tonemapping_pars_fragment>
#include <colorspace_pars_fragment>
void main() {
gl_FragColor = texture2D( tDiffuse, vUv );
#ifdef LINEAR_TONE_MAPPING
gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );
#elif defined( REINHARD_TONE_MAPPING )
gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );
#elif defined( CINEON_TONE_MAPPING )
gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );
#elif defined( ACES_FILMIC_TONE_MAPPING )
gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );
#elif defined( AGX_TONE_MAPPING )
gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );
#elif defined( NEUTRAL_TONE_MAPPING )
gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );
#elif defined( CUSTOM_TONE_MAPPING )
gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );
#endif
#ifdef SRGB_TRANSFER
gl_FragColor = sRGBTransferOETF( gl_FragColor );
#endif
}`,depthTest:!1,depthWrite:!1}),u=new ci(l,a),h=new gr(-1,1,1,-1,0,1),p=null,m=null,I=!1,g,E=null,w=[],T=!1;this.setSize=function(S,_){o.setSize(S,_),r.setSize(S,_);for(let x=0;x<w.length;x++){let M=w[x];M.setSize&&M.setSize(S,_)}},this.setEffects=function(S){w=S,T=w.length>0&&w[0].isRenderPass===!0;let _=o.width,x=o.height;for(let M=0;M<w.length;M++){let W=w[M];W.setSize&&W.setSize(_,x)}},this.begin=function(S,_){if(I||S.toneMapping===_d&&w.length===0)return!1;if(E=_,_!==null){let x=_.width,M=_.height;(o.width!==x||o.height!==M)&&this.setSize(x,M)}return T===!1&&S.setRenderTarget(o),g=S.toneMapping,S.toneMapping=_d,!0},this.hasRenderPass=function(){return T},this.end=function(S,_){S.toneMapping=g,I=!0;let x=o,M=r;for(let W=0;W<w.length;W++){let G=w[W];if(G.enabled!==!1&&(G.render(S,M,x,_),G.needsSwap!==!1)){let $=x;x=M,M=$}}if(p!==S.outputColorSpace||m!==S.toneMapping){p=S.outputColorSpace,m=S.toneMapping,a.defines={},Kn.getTransfer(p)===Sn&&(a.defines.SRGB_TRANSFER="");let W=lUe[m];W&&(a.defines[W]=""),a.needsUpdate=!0}a.uniforms.tDiffuse.value=x.texture,S.setRenderTarget(E),S.render(u,h),E=null,I=!1},this.isCompositing=function(){return I},this.dispose=function(){o.depthTexture&&o.depthTexture.dispose(),o.dispose(),r.dispose(),l.dispose(),a.dispose()}}var $we=new Ur,Hle=new rl(1,1),Zwe=new LR,Kwe=new L6,Qwe=new jy,Cwe=[],Dwe=[],Nwe=new Float32Array(16),Owe=new Float32Array(9),Lwe=new Float32Array(4);function H8(e,t,i){let n=e[0];if(n<=0||n>0)return e;let s=t*i,o=Cwe[s];if(o===void 0&&(o=new Float32Array(s),Cwe[s]=o),t!==0){n.toArray(o,0);for(let r=1,l=0;r!==t;++r)l+=i,e[r].toArray(o,l)}return o}function Kd(e,t){if(e.length!==t.length)return!1;for(let i=0,n=e.length;i<n;i++)if(e[i]!==t[i])return!1;return!0}function Qd(e,t){for(let i=0,n=t.length;i<n;i++)e[i]=t[i]}function bK(e,t){let i=Dwe[t];i===void 0&&(i=new Int32Array(t),Dwe[t]=i);for(let n=0;n!==t;++n)i[n]=e.allocateTextureUnit();return i}function uUe(e,t){let i=this.cache;i[0]!==t&&(e.uniform1f(this.addr,t),i[0]=t)}function cUe(e,t){let i=this.cache;if(t.x!==void 0)(i[0]!==t.x||i[1]!==t.y)&&(e.uniform2f(this.addr,t.x,t.y),i[0]=t.x,i[1]=t.y);else{if(Kd(i,t))return;e.uniform2fv(this.addr,t),Qd(i,t)}}function dUe(e,t){let i=this.cache;if(t.x!==void 0)(i[0]!==t.x||i[1]!==t.y||i[2]!==t.z)&&(e.uniform3f(this.addr,t.x,t.y,t.z),i[0]=t.x,i[1]=t.y,i[2]=t.z);else if(t.r!==void 0)(i[0]!==t.r||i[1]!==t.g||i[2]!==t.b)&&(e.uniform3f(this.addr,t.r,t.g,t.b),i[0]=t.r,i[1]=t.g,i[2]=t.b);else{if(Kd(i,t))return;e.uniform3fv(this.addr,t),Qd(i,t)}}function hUe(e,t){let i=this.cache;if(t.x!==void 0)(i[0]!==t.x||i[1]!==t.y||i[2]!==t.z||i[3]!==t.w)&&(e.uniform4f(this.addr,t.x,t.y,t.z,t.w),i[0]=t.x,i[1]=t.y,i[2]=t.z,i[3]=t.w);else{if(Kd(i,t))return;e.uniform4fv(this.addr,t),Qd(i,t)}}function fUe(e,t){let i=this.cache,n=t.elements;if(n===void 0){if(Kd(i,t))return;e.uniformMatrix2fv(this.addr,!1,t),Qd(i,t)}else{if(Kd(i,n))return;Lwe.set(n),e.uniformMatrix2fv(this.addr,!1,Lwe),Qd(i,n)}}function pUe(e,t){let i=this.cache,n=t.elements;if(n===void 0){if(Kd(i,t))return;e.uniformMatrix3fv(this.addr,!1,t),Qd(i,t)}else{if(Kd(i,n))return;Owe.set(n),e.uniformMatrix3fv(this.addr,!1,Owe),Qd(i,n)}}function mUe(e,t){let i=this.cache,n=t.elements;if(n===void 0){if(Kd(i,t))return;e.uniformMatrix4fv(this.addr,!1,t),Qd(i,t)}else{if(Kd(i,n))return;Nwe.set(n),e.uniformMatrix4fv(this.addr,!1,Nwe),Qd(i,n)}}function IUe(e,t){let i=this.cache;i[0]!==t&&(e.uniform1i(this.addr,t),i[0]=t)}function yUe(e,t){let i=this.cache;if(t.x!==void 0)(i[0]!==t.x||i[1]!==t.y)&&(e.uniform2i(this.addr,t.x,t.y),i[0]=t.x,i[1]=t.y);else{if(Kd(i,t))return;e.uniform2iv(this.addr,t),Qd(i,t)}}function gUe(e,t){let i=this.cache;if(t.x!==void 0)(i[0]!==t.x||i[1]!==t.y||i[2]!==t.z)&&(e.uniform3i(this.addr,t.x,t.y,t.z),i[0]=t.x,i[1]=t.y,i[2]=t.z);else{if(Kd(i,t))return;e.uniform3iv(this.addr,t),Qd(i,t)}}function EUe(e,t){let i=this.cache;if(t.x!==void 0)(i[0]!==t.x||i[1]!==t.y||i[2]!==t.z||i[3]!==t.w)&&(e.uniform4i(this.addr,t.x,t.y,t.z,t.w),i[0]=t.x,i[1]=t.y,i[2]=t.z,i[3]=t.w);else{if(Kd(i,t))return;e.uniform4iv(this.addr,t),Qd(i,t)}}func
`),n=[],s=Math.max(t-6,0),o=Math.min(t+6,i.length);for(let r=s;r<o;r++){let l=r+1;n.push(`${l===t?">":" "} ${l}: ${i[r]}`)}return n.join(`
`)}var Bwe=new us;function XUe(e){Kn._getMatrix(Bwe,Kn.workingColorSpace,e);let t=`mat3( ${Bwe.elements.map(i=>i.toFixed(4))} )`;switch(Kn.getTransfer(e)){case NR:return[t,"LinearTransferOETF"];case Sn:return[t,"sRGBTransferOETF"];default:return yi("WebGLProgram: Unsupported color space: ",e),[t,"LinearTransferOETF"]}}function Fwe(e,t,i){let n=e.getShaderParameter(t,e.COMPILE_STATUS),o=(e.getShaderInfoLog(t)||"").trim();if(n&&o==="")return"";let r=/ERROR: 0:(\d+)/.exec(o);if(r){let l=parseInt(r[1]);return i.toUpperCase()+`
`+o+`
`+JUe(e.getShaderSource(t),l)}else return o}function e9e(e,t){let i=XUe(t);return[`vec4 ${e}( vec4 value ) {`,` return ${i[1]}( vec4( value.rgb * ${i[0]}, value.a ) );`,"}"].join(`
`)}var t9e={[Qx]:"Linear",[Jx]:"Reinhard",[Xx]:"Cineon",[eC]:"ACESFilmic",[tC]:"AgX",[iC]:"Neutral",[D8]:"Custom"};function i9e(e,t){let i=t9e[t];return i===void 0?(yi("WebGLProgram: Unsupported toneMapping:",t),"vec3 "+e+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+e+"( vec3 color ) { return "+i+"ToneMapping( color ); }"}var RK=new ne;function n9e(){Kn.getLuminanceCoefficients(RK);let e=RK.x.toFixed(4),t=RK.y.toFixed(4),i=RK.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${e}, ${t}, ${i} );`," return dot( weights, rgb );","}"].join(`
`)}function s9e(e){return[e.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",e.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Cz).join(`
`)}function o9e(e){let t=[];for(let i in e){let n=e[i];n!==!1&&t.push("#define "+i+" "+n)}return t.join(`
`)}function r9e(e,t){let i={},n=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let s=0;s<n;s++){let o=e.getActiveAttrib(t,s),r=o.name,l=1;o.type===e.FLOAT_MAT2&&(l=2),o.type===e.FLOAT_MAT3&&(l=3),o.type===e.FLOAT_MAT4&&(l=4),i[r]={type:o.type,location:e.getAttribLocation(t,r),locationSize:l}}return i}function Cz(e){return e!==""}function Uwe(e,t){let i=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,i).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 Hwe(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}var l9e=/^[ \t]*#include +<([\w\d./]+)>/gm;function zle(e){return e.replace(l9e,u9e)}var a9e=new Map;function u9e(e,t){let i=mo[t];if(i===void 0){let n=a9e.get(t);if(n!==void 0)i=mo[n],yi('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,n);else throw new Error("Can not resolve #include <"+t+">")}return zle(i)}var c9e=/#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 Gwe(e){return e.replace(c9e,d9e)}function d9e(e,t,i,n){let s="";for(let o=parseInt(t);o<parseInt(i);o++)s+=n.replace(/\[\s*i\s*\]/g,"[ "+o+" ]").replace(/UNROLLED_LOOP_INDEX/g,o);return s}function Vwe(e){let t=`precision ${e.precision} float;
precision ${e.precision} int;
precision ${e.precision} sampler2D;
precision ${e.precision} samplerCube;
precision ${e.precision} sampler3D;
precision ${e.precision} sampler2DArray;
precision ${e.precision} sampler2DShadow;
precision ${e.precision} samplerCubeShadow;
precision ${e.precision} sampler2DArrayShadow;
precision ${e.precision} isampler2D;
precision ${e.precision} isampler3D;
precision ${e.precision} isamplerCube;
precision ${e.precision} isampler2DArray;
precision ${e.precision} usampler2D;
precision ${e.precision} usampler3D;
precision ${e.precision} usamplerCube;
precision ${e.precision} usampler2DArray;
`;return e.precision==="highp"?t+=`
#define HIGH_PRECISION`:e.precision==="mediump"?t+=`
#define MEDIUM_PRECISION`:e.precision==="lowp"&&(t+=`
#define LOW_PRECISION`),t}var h9e={[zR]:"SHADOWMAP_TYPE_PCF",[qy]:"SHADOWMAP_TYPE_VSM"};function f9e(e){return h9e[e.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}var p9e={[vp]:"ENVMAP_TYPE_CUBE",[ty]:"ENVMAP_TYPE_CUBE",[iw]:"ENVMAP_TYPE_CUBE_UV"};function m9e(e){return e.envMap===!1?"ENVMAP_TYPE_CUBE":p9e[e.envMapMode]||"ENVMAP_TYPE_CUBE"}var I9e={[ty]:"ENVMAP_MODE_REFRACTION"};function y9e(e){return e.envMap===!1?"ENVMAP_MODE_REFLECTION":I9e[e.envMapMode]||"ENVMAP_MODE_REFLECTION"}var g9e={[Kx]:"ENVMAP_BLENDING_MULTIPLY",[yz]:"ENVMAP_BLENDING_MIX",[gz]:"ENVMAP_BLENDING_ADD"};function E9e(e){return e.envMap===!1?"ENVMAP_BLENDING_NONE":g9e[e.combine]||"ENVMAP_BLENDING_NONE"}function T9e(e){let t=e.envMapCubeUVHeight;if(t===null)return null;let i=Math.log2(t)-2,n=1/t;return{texelWidth:1/(3*Math.max(Math.pow(2,i),112)),texelHeight:n,maxMip:i}}function w9e(e,t,i,n){let s=e.getContext(),o=i.defines,r=i.vertexShader,l=i.fragmentShader,a=f9e(i),u=m9e(i),h=y9e(i),p=E9e(i),m=T9e(i),I=s9e(i),g=o9e(o),E=s.createProgram(),w,T,S=i.glslVersion?"#version "+i.glslVersion+`
`:"";i.isRawShaderMaterial?(w=["#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,g].filter(Cz).join(`
`),w.length>0&&(w+=`
`),T=["#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,g].filter(Cz).join(`
`),T.length>0&&(T+=`
`)):(w=[Vwe(i),"#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,g,i.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",i.batching?"#define USE_BATCHING":"",i.batchingColor?"#define USE_BATCHING_COLOR":"",i.instancing?"#define USE_INSTANCING":"",i.instancingColor?"#define USE_INSTANCING_COLOR":"",i.instancingMorph?"#define USE_INSTANCING_MORPH":"",i.useFog&&i.fog?"#define USE_FOG":"",i.useFog&&i.fogExp2?"#define FOG_EXP2":"",i.map?"#define USE_MAP":"",i.envMap?"#define USE_ENVMAP":"",i.envMap?"#define "+h:"",i.lightMap?"#define USE_LIGHTMAP":"",i.aoMap?"#define USE_AOMAP":"",i.bumpMap?"#define USE_BUMPMAP":"",i.normalMap?"#define USE_NORMALMAP":"",i.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",i.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",i.displacementMap?"#define USE_DISPLACEMENTMAP":"",i.emissiveMap?"#define USE_EMISSIVEMAP":"",i.anisotropy?"#define USE_ANISOTROPY":"",i.anisotropyMap?"#define USE_ANISOTROPYMAP":"",i.clearcoatMap?"#define USE_CLEARCOATMAP":"",i.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",i.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",i.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",i.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",i.specularMap?"#define USE_SPECULARMAP":"",i.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",i.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",i.roughnessMap?"#define USE_ROUGHNESSMAP":"",i.metalnessMap?"#define USE_METALNESSMAP":"",i.alphaMap?"#define USE_ALPHAMAP":"",i.alphaHash?"#define USE_ALPHAHASH":"",i.transmission?"#define USE_TRANSMISSION":"",i.transmissionMap?"#define USE_TRANSMISSIONMAP":"",i.thicknessMap?"#define USE_THICKNESSMAP":"",i.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",i.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",i.mapUv?"#define MAP_UV "+i.mapUv:"",i.alphaMapUv?"#define ALPHAMAP_UV "+i.alphaMapUv:"",i.lightMapUv?"#define LIGHTMAP_UV "+i.lightMapUv:"",i.aoMapUv?"#define AOMAP_UV "+i.aoMapUv:"",i.emissiveMapUv?"#define EMISSIVEMAP_UV "+i.emissiveMapUv:"",i.bumpMapUv?"#define BUMPMAP_UV "+i.bumpMapUv:"",i.normalMapUv?"#define NORMALMAP_UV "+i.normalMapUv:"",i.displacementMapUv?"#define DISPLACEMENTMAP_UV "+i.displacementMapUv:"",i.metalnessMapUv?"#define METALNESSMAP_UV "+i.metalnessMapUv:"",i.roughnessMapUv?"#define ROUGHNESSMAP_UV "+i.roughnessMapUv:"",i.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+i.anisotropyMapUv:"",i.clearcoatMapUv?"#define CLEARCOATMAP_UV "+i.clearcoatMapUv:"",i.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+i.clearcoatNormalMapUv:"",i.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+i.clearcoatRoughnessMapUv:"",i.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+i.iridescenceMapUv:"",i.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+i.iridescenceThicknessMapUv:"",i.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+i.sheenColorMapUv:"",i.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+i.sheenRoughnessMapUv:"",i.specularMapUv?"#define SPECULARMAP_UV "+i.specularMapUv:"",i.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+i.specularColorMapUv:"",i.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+i.specularIntensityMapUv:"",i.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+i.transmissionMapUv:"",i.thicknessMapUv?"#define THICKNESSMAP_UV "+i.thicknessMapUv:"",i.vertexTangents&&i.flatShading===!1?"#define USE_TANGENT":"",i.vertexNormals?"#define HAS_NORMAL":"",i.vertexColors?"#define USE_COLOR":"",i.vertexAlphas?"#define USE_COLOR_ALPHA":"",i.vertexUv1s?"#define USE_UV1":"",i.vertexUv2s?"#define USE_UV2":"",i.vertexUv3s?"#define USE_UV3":"",i.pointsUvs?"#define USE_POINTS_UV":"",i.flatShading?"#define FLAT_SHADED":"",i.skinning?"#define USE_SKINNING":"",i.morphTargets?"#define USE_MORPHTARGETS":"",i.morphNormals&&i.flatShading===!1?"#define USE_MORPHNORMALS":"",i.morphColors?"#define USE_MORPHCOLORS":"",i.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+i.morphTextureStride:"",i.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+i.morphTargetsCount:""
`].filter(Cz).join(`
`),T=[Vwe(i),"#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,g,i.useFog&&i.fog?"#define USE_FOG":"",i.useFog&&i.fogExp2?"#define FOG_EXP2":"",i.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",i.map?"#define USE_MAP":"",i.matcap?"#define USE_MATCAP":"",i.envMap?"#define USE_ENVMAP":"",i.envMap?"#define "+u:"",i.envMap?"#define "+h:"",i.envMap?"#define "+p:"",m?"#define CUBEUV_TEXEL_WIDTH "+m.texelWidth:"",m?"#define CUBEUV_TEXEL_HEIGHT "+m.texelHeight:"",m?"#define CUBEUV_MAX_MIP "+m.maxMip+".0":"",i.lightMap?"#define USE_LIGHTMAP":"",i.aoMap?"#define USE_AOMAP":"",i.bumpMap?"#define USE_BUMPMAP":"",i.normalMap?"#define USE_NORMALMAP":"",i.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",i.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",i.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",i.emissiveMap?"#define USE_EMISSIVEMAP":"",i.anisotropy?"#define USE_ANISOTROPY":"",i.anisotropyMap?"#define USE_ANISOTROPYMAP":"",i.clearcoat?"#define USE_CLEARCOAT":"",i.clearcoatMap?"#define USE_CLEARCOATMAP":"",i.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",i.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",i.dispersion?"#define USE_DISPERSION":"",i.iridescence?"#define USE_IRIDESCENCE":"",i.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",i.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",i.specularMap?"#define USE_SPECULARMAP":"",i.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",i.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",i.roughnessMap?"#define USE_ROUGHNESSMAP":"",i.metalnessMap?"#define USE_METALNESSMAP":"",i.alphaMap?"#define USE_ALPHAMAP":"",i.alphaTest?"#define USE_ALPHATEST":"",i.alphaHash?"#define USE_ALPHAHASH":"",i.sheen?"#define USE_SHEEN":"",i.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",i.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",i.transmission?"#define USE_TRANSMISSION":"",i.transmissionMap?"#define USE_TRANSMISSIONMAP":"",i.thicknessMap?"#define USE_THICKNESSMAP":"",i.vertexTangents&&i.flatShading===!1?"#define USE_TANGENT":"",i.vertexColors||i.instancingColor?"#define USE_COLOR":"",i.vertexAlphas||i.batchingColor?"#define USE_COLOR_ALPHA":"",i.vertexUv1s?"#define USE_UV1":"",i.vertexUv2s?"#define USE_UV2":"",i.vertexUv3s?"#define USE_UV3":"",i.pointsUvs?"#define USE_POINTS_UV":"",i.gradientMap?"#define USE_GRADIENTMAP":"",i.flatShading?"#define FLAT_SHADED":"",i.doubleSided?"#define DOUBLE_SIDED":"",i.flipSided?"#define FLIP_SIDED":"",i.shadowMapEnabled?"#define USE_SHADOWMAP":"",i.shadowMapEnabled?"#define "+a:"",i.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",i.numLightProbes>0?"#define USE_LIGHT_PROBES":"",i.numLightProbeGrids>0?"#define USE_LIGHT_PROBES_GRID":"",i.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",i.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",i.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",i.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",i.toneMapping!==_d?"#define TONE_MAPPING":"",i.toneMapping!==_d?mo.tonemapping_pars_fragment:"",i.toneMapping!==_d?i9e("toneMapping",i.toneMapping):"",i.dithering?"#define DITHERING":"",i.opaque?"#define OPAQUE":"",mo.colorspace_pars_fragment,e9e("linearToOutputTexel",i.outputColorSpace),n9e(),i.useDepthPacking?"#define DEPTH_PACKING "+i.depthPacking:"",`
`].filter(Cz).join(`
`)),r=zle(r),r=Uwe(r,i),r=Hwe(r,i),l=zle(l),l=Uwe(l,i),l=Hwe(l,i),r=Gwe(r),l=Gwe(l),i.isRawShaderMaterial!==!0&&(S=`#version 300 es
`,w=[I,"#define attribute in","#define varying out","#define texture2D texture"].join(`
`)+`
`+w,T=["#define varying in",i.glslVersion===hC?"":"layout(location = 0) out highp vec4 pc_fragColor;",i.glslVersion===hC?"":"#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(`
`)+`
`+T);let _=S+w+r,x=S+T+l,M=Mwe(s,s.VERTEX_SHADER,_),W=Mwe(s,s.FRAGMENT_SHADER,x);s.attachShader(E,M),s.attachShader(E,W),i.index0AttributeName!==void 0?s.bindAttribLocation(E,0,i.index0AttributeName):i.morphTargets===!0&&s.bindAttribLocation(E,0,"position"),s.linkProgram(E);function G(pe){if(e.debug.checkShaderErrors){let k=s.getProgramInfoLog(E)||"",fe=s.getShaderInfoLog(M)||"",Q=s.getShaderInfoLog(W)||"",Te=k.trim(),Ve=fe.trim(),Fe=Q.trim(),pt=!0,Me=!0;if(s.getProgramParameter(E,s.LINK_STATUS)===!1)if(pt=!1,typeof e.debug.onShaderError=="function")e.debug.onShaderError(s,E,M,W);else{let He=Fwe(s,M,"vertex"),Ye=Fwe(s,W,"fragment");_i("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(E,s.VALIDATE_STATUS)+`
Material Name: `+pe.name+`
Material Type: `+pe.type+`
Program Info Log: `+Te+`
`+He+`
`+Ye)}else Te!==""?yi("WebGLProgram: Program Info Log:",Te):(Ve===""||Fe==="")&&(Me=!1);Me&&(pe.diagnostics={runnable:pt,programLog:Te,vertexShader:{log:Ve,prefix:w},fragmentShader:{log:Fe,prefix:T}})}s.deleteShader(M),s.deleteShader(W),$=new U8(s,E),Y=r9e(s,E)}let $;this.getUniforms=function(){return $===void 0&&G(this),$};let Y;this.getAttributes=function(){return Y===void 0&&G(this),Y};let se=i.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return se===!1&&(se=s.getProgramParameter(E,KUe)),se},this.destroy=function(){n.releaseStatesOfProgram(this),s.deleteProgram(E),this.program=void 0},this.type=i.shaderType,this.name=i.shaderName,this.id=QUe++,this.cacheKey=t,this.usedTimes=1,this.program=E,this.vertexShader=M,this.fragmentShader=W,this}var v9e=0,Wle=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(t){let i=t.vertexShader,n=t.fragmentShader,s=this._getShaderStage(i),o=this._getShaderStage(n),r=this._getShaderCacheForMaterial(t);return r.has(s)===!1&&(r.add(s),s.usedTimes++),r.has(o)===!1&&(r.add(o),o.usedTimes++),this}remove(t){let i=this.materialCache.get(t);for(let n of i)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(t),this}getVertexShaderID(t){return this._getShaderStage(t.vertexShader).id}getFragmentShaderID(t){return this._getShaderStage(t.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(t){let i=this.materialCache,n=i.get(t);return n===void 0&&(n=new Set,i.set(t,n)),n}_getShaderStage(t){let i=this.shaderCache,n=i.get(t);return n===void 0&&(n=new jle(t),i.set(t,n)),n}},jle=class{constructor(t){this.id=v9e++,this.code=t,this.usedTimes=0}};function S9e(e){return e===bd||e===cw||e===dw}function R9e(e,t,i,n,s,o){let r=new P6,l=new Wle,a=new Set,u=[],h=new Map,p=n.logarithmicDepthBuffer,m=n.precision,I={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 g($){return a.add($),$===0?"uv":`uv${$}`}function E($,Y,se,pe,k,fe){let Q=pe.fog,Te=k.geometry,Ve=$.isMeshStandardMaterial||$.isMeshLambertMaterial||$.isMeshPhongMaterial?pe.environment:null,Fe=$.isMeshStandardMaterial||$.isMeshLambertMaterial&&!$.envMap||$.isMeshPhongMaterial&&!$.envMap,pt=t.get($.envMap||Ve,Fe),Me=pt&&pt.mapping===iw?pt.image.height:null,He=I[$.type];$.precision!==null&&(m=n.getMaxPrecision($.precision),m!==$.precision&&yi("WebGLProgram.getParameters:",$.precision,"not supported, using",m,"instead."));let Ye=Te.morphAttributes.position||Te.morphAttributes.normal||Te.morphAttributes.color,We=Ye!==void 0?Ye.length:0,_t=0;Te.morphAttributes.position!==void 0&&(_t=1),Te.morphAttributes.normal!==void 0&&(_t=2),Te.morphAttributes.color!==void 0&&(_t=3);let xt,wt,Bt,Xt;if(He){let Yn=Rp[He];xt=Yn.vertexShader,wt=Yn.fragmentShader}else xt=$.vertexShader,wt=$.fragmentShader,l.update($),Bt=l.getVertexShaderID($),Xt=l.getFragmentShaderID($);let Dt=e.getRenderTarget(),Pt=e.state.buffers.depth.getReversed(),$t=k.isInstancedMesh===!0,Vt=k.isBatchedMesh===!0,Ue=!!$.map,Ft=!!$.matcap,ie=!!pt,Oe=!!$.aoMap,Ce=!!$.lightMap,Se=!!$.bumpMap,_e=!!$.normalMap,je=!!$.displacementMap,Be=!!$.emissiveMap,dt=!!$.metalnessMap,it=!!$.roughnessMap,Rt=$.anisotropy>0,At=$.clearcoat>0,Ht=$.dispersion>0,Xe=$.iridescence>0,Ze=$.sheen>0,Mt=$.transmission>0,ni=Rt&&!!$.anisotropyMap,gi=At&&!!$.clearcoatMap,hi=At&&!!$.clearcoatNormalMap,Di=At&&!!$.clearcoatRoughnessMap,ti=Xe&&!!$.iridescenceMap,fi=Xe&&!!$.iridescenceThicknessMap,zi=Ze&&!!$.sheenColorMap,Bi=Ze&&!!$.sheenRoughnessMap,Fi=!!$.specularMap,Mi=!!$.specularColorMap,cn=!!$.specularIntensityMap,Cn=Mt&&!!$.transmissionMap,Ji=Mt&&!!$.thicknessMap,qt=!!$.gradientMap,Hi=!!$.alphaMap,Ai=$.alphaTest>0,en=!!$.al
gl_Position = vec4( position, 1.0 );
}`,M9e=`uniform sampler2D shadow_pass;
uniform vec2 resolution;
uniform float radius;
void main() {
const float samples = float( VSM_SAMPLES );
float mean = 0.0;
float squared_mean = 0.0;
float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );
float uvStart = samples <= 1.0 ? 0.0 : - 1.0;
for ( float i = 0.0; i < samples; i ++ ) {
float uvOffset = uvStart + i * uvStride;
#ifdef HORIZONTAL_PASS
vec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg;
mean += distribution.x;
squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
#else
float depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r;
mean += depth;
squared_mean += depth * depth;
#endif
}
mean = mean / samples;
squared_mean = squared_mean / samples;
float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );
gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );
}`,B9e=[new ne(1,0,0),new ne(-1,0,0),new ne(0,1,0),new ne(0,-1,0),new ne(0,0,1),new ne(0,0,-1)],F9e=[new ne(0,-1,0),new ne(0,-1,0),new ne(0,0,1),new ne(0,0,-1),new ne(0,-1,0),new ne(0,-1,0)],jwe=new di,xz=new ne,Ule=new ne;function U9e(e,t,i){let n=new Rd,s=new si,o=new si,r=new Gn,l=new a8,a=new u8,u={},h=i.maxTextureSize,p={[Xr]:wo,[wo]:Xr,[ls]:ls},m=new Bs({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new si},radius:{value:4}},vertexShader:P9e,fragmentShader:M9e}),I=m.clone();I.defines.HORIZONTAL_PASS=1;let g=new Ni;g.setAttribute("position",new Wi(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let E=new ci(g,m),w=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=zR;let T=this.type;this.render=function(W,G,$){if(w.enabled===!1||w.autoUpdate===!1&&w.needsUpdate===!1||W.length===0)return;this.type===pz&&(yi("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=zR);let Y=e.getRenderTarget(),se=e.getActiveCubeFace(),pe=e.getActiveMipmapLevel(),k=e.state;k.setBlending(jo),k.buffers.depth.getReversed()===!0?k.buffers.color.setClear(0,0,0,0):k.buffers.color.setClear(1,1,1,1),k.buffers.depth.setTest(!0),k.setScissorTest(!1);let fe=T!==this.type;fe&&G.traverse(function(Q){Q.material&&(Array.isArray(Q.material)?Q.material.forEach(Te=>Te.needsUpdate=!0):Q.material.needsUpdate=!0)});for(let Q=0,Te=W.length;Q<Te;Q++){let Ve=W[Q],Fe=Ve.shadow;if(Fe===void 0){yi("WebGLShadowMap:",Ve,"has no shadow.");continue}if(Fe.autoUpdate===!1&&Fe.needsUpdate===!1)continue;s.copy(Fe.mapSize);let pt=Fe.getFrameExtents();s.multiply(pt),o.copy(Fe.mapSize),(s.x>h||s.y>h)&&(s.x>h&&(o.x=Math.floor(h/pt.x),s.x=o.x*pt.x,Fe.mapSize.x=o.x),s.y>h&&(o.y=Math.floor(h/pt.y),s.y=o.y*pt.y,Fe.mapSize.y=o.y));let Me=e.state.buffers.depth.getReversed();if(Fe.camera._reversedDepth=Me,Fe.map===null||fe===!0){if(Fe.map!==null&&(Fe.map.depthTexture!==null&&(Fe.map.depthTexture.dispose(),Fe.map.depthTexture=null),Fe.map.dispose()),this.type===qy){if(Ve.isPointLight){yi("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}Fe.map=new bo(s.x,s.y,{format:bd,type:Ao,minFilter:Ds,magFilter:Ds,generateMipmaps:!1}),Fe.map.texture.name=Ve.name+".shadowMap",Fe.map.depthTexture=new rl(s.x,s.y,lr),Fe.map.depthTexture.name=Ve.name+".shadowMapDepth",Fe.map.depthTexture.format=lu,Fe.map.depthTexture.compareFunction=null,Fe.map.depthTexture.minFilter=Us,Fe.map.depthTexture.magFilter=Us}else Ve.isPointLight?(Fe.map=new Nz(s.x),Fe.map.depthTexture=new U6(s.x,Ko)):(Fe.map=new bo(s.x,s.y),Fe.map.depthTexture=new rl(s.x,s.y,Ko)),Fe.map.depthTexture.name=Ve.name+".shadowMap",Fe.map.depthTexture.format=lu,this.type===zR?(Fe.map.depthTexture.compareFunction=Me?Bg:hw,Fe.map.depthTexture.minFilter=Ds,Fe.map.depthTexture.magFilter=Ds):(Fe.map.depthTexture.compareFunction=null,Fe.map.depthTexture.minFilter=Us,Fe.map.depthTexture.magFilter=Us);Fe.camera.updateProjectionMatrix()}let He=Fe.map.isWebGLCubeRenderTarget?6:1;for(let Ye=0;Ye<He;Ye++){if(Fe.map.isWebGLCubeRenderTarget)e.setRenderTarget(Fe.map,Ye),e.clear();else{Ye===0&&(e.setRenderTarget(Fe.map),e.clear());let We=Fe.getViewport(Ye);r.set(o.x*We.x,o.y*We.y,o.x*We.z,o.y*We.w),k.viewport(r)}if(Ve.isPointLight){let We=Fe.camera,_t=Fe.matrix,xt=Ve.distance||We.far;xt!==We.far&&(We.far=xt,We.updateProjectionMatrix()),xz.setFromMatrixPosition(Ve.matrixWorld),We.position.copy(xz),Ule.copy(We.position),Ule.add(B9e[Ye]),We.up.copy(F9e[Ye]),We.lookAt(Ule),We.updateMatrixWorld(),_t.makeTranslation(-xz.x,-xz.y,-xz.z),jwe.multiplyMatrices(We.projectionMatrix,We.matrixWorldInverse),Fe._frustum.setFromProjectionMatrix(jwe,We.coordinateSystem,We.reversedDepth)}else Fe.updateMatrices(Ve);n=Fe.getFrustum(),x(G,$,Fe.camera,Ve,this.type)}Fe.isPointLightShadow!==!0&&this.type===qy&&S(Fe,$),Fe.needsUpdate=!1}T=this.type,w.needsUpdate=!1,e.setRenderTarget(Y,se,pe)};function S(W,G){let $=t.update(E);m.defines.VSM_SAMPLES!==W.blurSamples&&(m.defines.VSM_SAMPLES=W.blurSamples,I.defines.VSM_SAMPLES=W.blurSamples
void main() {
gl_Position = vec4( position, 1.0 );
}`,k9e=`
uniform sampler2DArray depthColor;
uniform float depthWidth;
uniform float depthHeight;
void main() {
vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
if ( coord.x >= 1.0 ) {
gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
} else {
gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
}
}`,Yle=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,i){if(this.texture===null){let n=new t8(t.texture);(t.depthNear!==i.depthNear||t.depthFar!==i.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=n}}getMesh(t){if(this.texture!==null&&this.mesh===null){let i=t.cameras[0].viewport,n=new Bs({vertexShader:V9e,fragmentShader:k9e,uniforms:{depthColor:{value:this.texture},depthWidth:{value:i.z},depthHeight:{value:i.w}}});this.mesh=new ci(new bu(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},qle=class extends qd{constructor(t,i){super();let n=this,s=null,o=1,r=null,l="local-floor",a=1,u=null,h=null,p=null,m=null,I=null,g=null,E=typeof XRWebGLBinding<"u",w=new Yle,T={},S=i.getContextAttributes(),_=null,x=null,M=[],W=[],G=new si,$=null,Y=new Wo;Y.viewport=new Gn;let se=new Wo;se.viewport=new Gn;let pe=[Y,se],k=new tO,fe=null,Q=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Bt){let Xt=M[Bt];return Xt===void 0&&(Xt=new PR,M[Bt]=Xt),Xt.getTargetRaySpace()},this.getControllerGrip=function(Bt){let Xt=M[Bt];return Xt===void 0&&(Xt=new PR,M[Bt]=Xt),Xt.getGripSpace()},this.getHand=function(Bt){let Xt=M[Bt];return Xt===void 0&&(Xt=new PR,M[Bt]=Xt),Xt.getHandSpace()};function Te(Bt){let Xt=W.indexOf(Bt.inputSource);if(Xt===-1)return;let Dt=M[Xt];Dt!==void 0&&(Dt.update(Bt.inputSource,Bt.frame,u||r),Dt.dispatchEvent({type:Bt.type,data:Bt.inputSource}))}function Ve(){s.removeEventListener("select",Te),s.removeEventListener("selectstart",Te),s.removeEventListener("selectend",Te),s.removeEventListener("squeeze",Te),s.removeEventListener("squeezestart",Te),s.removeEventListener("squeezeend",Te),s.removeEventListener("end",Ve),s.removeEventListener("inputsourceschange",Fe);for(let Bt=0;Bt<M.length;Bt++){let Xt=W[Bt];Xt!==null&&(W[Bt]=null,M[Bt].disconnect(Xt))}fe=null,Q=null,w.reset();for(let Bt in T)delete T[Bt];t.setRenderTarget(_),I=null,m=null,p=null,s=null,x=null,wt.stop(),n.isPresenting=!1,t.setPixelRatio($),t.setSize(G.width,G.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Bt){o=Bt,n.isPresenting===!0&&yi("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Bt){l=Bt,n.isPresenting===!0&&yi("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return u||r},this.setReferenceSpace=function(Bt){u=Bt},this.getBaseLayer=function(){return m!==null?m:I},this.getBinding=function(){return p===null&&E&&(p=new XRWebGLBinding(s,i)),p},this.getFrame=function(){return g},this.getSession=function(){return s},this.setSession=async function(Bt){if(s=Bt,s!==null){if(_=t.getRenderTarget(),s.addEventListener("select",Te),s.addEventListener("selectstart",Te),s.addEventListener("selectend",Te),s.addEventListener("squeeze",Te),s.addEventListener("squeezestart",Te),s.addEventListener("squeezeend",Te),s.addEventListener("end",Ve),s.addEventListener("inputsourceschange",Fe),S.xrCompatible!==!0&&await i.makeXRCompatible(),$=t.getPixelRatio(),t.getSize(G),E&&"createProjectionLayer"in XRWebGLBinding.prototype){let Dt=null,Pt=null,$t=null;S.depth&&($t=S.stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24,Dt=S.stencil?Tc:lu,Pt=S.stencil?Zd:Ko);let Vt={colorFormat:i.RGBA8,depthFormat:$t,scaleFactor:o};p=this.getBinding(),m=p.createProjectionLayer(Vt),s.updateRenderState({layers:[m]}),t.setPixelRatio(1),t.setSize(m.textureWidth,m.textureHeight,!1),x=new bo(m.textureWidth,m.textureHeight,{format:_o,type:Vo,depthTexture:new rl(m.textureWidth,m.textureHeight,Pt,void 0,void 0,void 0,void 0,void 0,void 0,Dt),stencilBuffer:S.stencil,colorSpace:t.outputColorSpace,samples:S.antialias?4:0,resolveDepthBuffer:m.ignoreDepthValues===!1,resolveStencilBuffer:m.ignoreDepthValues===!1})}else{let Dt={antialias:S.antialias,alpha:!0,depth:S.depth,stencil:S.stencil,framebufferScaleFactor:o};I=new XRWebGLLayer(s,i,Dt),s.updateRenderState({baseLayer:I}),t.setPixelRatio(1),t.set
`)),!q)return null;ag=dT(q,!0)}return ag.shift()},op={ttys:[],init(){},shutdown(){},register(q,le){op.ttys[q]={input:[],output:[],ops:le},ht.registerDevice(q,op.stream_ops)},stream_ops:{open(q){var le=op.ttys[q.node.rdev];if(!le)throw new ht.ErrnoError(43);q.tty=le,q.seekable=!1},close(q){q.tty.ops.fsync(q.tty)},fsync(q){q.tty.ops.fsync(q.tty)},read(q,le,be,ke,st){if(!q.tty||!q.tty.ops.get_char)throw new ht.ErrnoError(60);for(var St=0,Ct=0;Ct<ke;Ct++){var Lt;try{Lt=q.tty.ops.get_char(q.tty)}catch{throw new ht.ErrnoError(29)}if(Lt===void 0&&St===0)throw new ht.ErrnoError(6);if(Lt==null)break;St++,le[be+Ct]=Lt}return St&&(q.node.atime=Date.now()),St},write(q,le,be,ke,st){if(!q.tty||!q.tty.ops.put_char)throw new ht.ErrnoError(60);try{for(var St=0;St<ke;St++)q.tty.ops.put_char(q.tty,le[be+St])}catch{throw new ht.ErrnoError(29)}return ke&&(q.node.mtime=q.node.ctime=Date.now()),St}},default_tty_ops:{get_char(q){return P3()},put_char(q,le){le===null||le===10?(_(xI(q.output)),q.output=[]):le!=0&&q.output.push(le)},fsync(q){q.output?.length>0&&(_(xI(q.output)),q.output=[])},ioctl_tcgets(q){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(q,le,be){return 0},ioctl_tiocgwinsz(q){return[24,80]}},default_tty1_ops:{put_char(q,le){le===null||le===10?(x(xI(q.output)),q.output=[]):le!=0&&q.output.push(le)},fsync(q){q.output?.length>0&&(x(xI(q.output)),q.output=[])}}},ct=q=>{Vt()},ds={ops_table:null,mount(q){return ds.createNode(null,"/",16895,0)},createNode(q,le,be,ke){if(ht.isBlkdev(be)||ht.isFIFO(be))throw new ht.ErrnoError(63);ds.ops_table||={dir:{node:{getattr:ds.node_ops.getattr,setattr:ds.node_ops.setattr,lookup:ds.node_ops.lookup,mknod:ds.node_ops.mknod,rename:ds.node_ops.rename,unlink:ds.node_ops.unlink,rmdir:ds.node_ops.rmdir,readdir:ds.node_ops.readdir,symlink:ds.node_ops.symlink},stream:{llseek:ds.stream_ops.llseek}},file:{node:{getattr:ds.node_ops.getattr,setattr:ds.node_ops.setattr},stream:{llseek:ds.stream_ops.llseek,read:ds.stream_ops.read,write:ds.stream_ops.write,mmap:ds.stream_ops.mmap,msync:ds.stream_ops.msync}},link:{node:{getattr:ds.node_ops.getattr,setattr:ds.node_ops.setattr,readlink:ds.node_ops.readlink},stream:{}},chrdev:{node:{getattr:ds.node_ops.getattr,setattr:ds.node_ops.setattr},stream:ht.chrdev_stream_ops}};var st=ht.createNode(q,le,be,ke);return ht.isDir(st.mode)?(st.node_ops=ds.ops_table.dir.node,st.stream_ops=ds.ops_table.dir.stream,st.contents={}):ht.isFile(st.mode)?(st.node_ops=ds.ops_table.file.node,st.stream_ops=ds.ops_table.file.stream,st.usedBytes=0,st.contents=null):ht.isLink(st.mode)?(st.node_ops=ds.ops_table.link.node,st.stream_ops=ds.ops_table.link.stream):ht.isChrdev(st.mode)&&(st.node_ops=ds.ops_table.chrdev.node,st.stream_ops=ds.ops_table.chrdev.stream),st.atime=st.mtime=st.ctime=Date.now(),q&&(q.contents[le]=st,q.atime=q.mtime=q.ctime=st.atime),st},getFileDataAsTypedArray(q){return q.contents?q.contents.subarray?q.contents.subarray(0,q.usedBytes):new Uint8Array(q.contents):new Uint8Array(0)},expandFileStorage(q,le){var be=q.contents?q.contents.length:0;if(!(be>=le)){var ke=1024*1024;le=Math.max(le,be*(be<ke?2:1.125)>>>0),be!=0&&(le=Math.max(le,256));var st=q.contents;q.contents=new Uint8Array(le),q.usedBytes>0&&q.contents.set(st.subarray(0,q.usedBytes),0)}},resizeFileStorage(q,le){if(q.usedBytes!=le)if(le==0)q.contents=null,q.usedBytes=0;else{var be=q.contents;q.contents=new Uint8Array(le),be&&q.contents.set(be.subarray(0,Math.min(le,q.usedBytes))),q.usedBytes=le}},node_ops:{getattr(q){var le={};return le.dev=ht.isChrdev(q.mode)?q.id:1,le.ino=q.id,le.mode=q.mode,le.nlink=1,le.uid=0,le.gid=0,le.rdev=q.rdev,ht.isDir(q.mode)?le.size=4096:ht.isFile(q.mode)?le.size=q.usedBytes:ht.isLink(q.mode)?le.size=q.link.length:le.size=0,le.atime=new Date(q.atime),le.mtime=new Date(q.mtime),le.ctime=new Date(q.ctime),le.blksize=4096,le.blocks=Math.ceil(le.size/le.blksize),le},setattr(q,le){for(let be of["mode","atime","mtime","ctime"])le[be]!=null&&(q[be]=le[be]);le.size!==void 0&&ds.resizeFileStorage(q,
We'll free it automatically in this case, but this functionality is not reliable across various environments.
Make sure to invoke .delete() manually once you're done with the instance instead.
Originally allocated`);"captureStackTrace"in Error&&Error.captureStackTrace(Gt,ai),ut.leakWarning=Gt.stack.replace(/^Error: /,""),Qr.register(de,ut,de)}return de},fl=de=>Qr.unregister(de),li(K)):(li=de=>de,K),oi=[],Xi=()=>{for(;oi.length;){var K=oi.pop();K.$$.deleteScheduled=!1,K.delete()}},mn,nn=()=>{let K=vn.prototype;Object.assign(K,{isAliasOf(De){if(!(this instanceof vn)||!(De instanceof vn))return!1;var Je=this.$$.ptrType.registeredClass,ut=this.$$.ptr;De.$$=De.$$;for(var Ot=De.$$.ptrType.registeredClass,Gt=De.$$.ptr;Je.baseClass;)ut=Je.upcast(ut),Je=Je.baseClass;for(;Ot.baseClass;)Gt=Ot.upcast(Gt),Ot=Ot.baseClass;return Je===Ot&&ut===Gt},clone(){if(this.$$.ptr||rc(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var De=li(Object.create(Object.getPrototypeOf(this),{$$:{value:Kr(this.$$)}}));return De.$$.count.value+=1,De.$$.deleteScheduled=!1,De},delete(){this.$$.ptr||rc(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&as("Object already scheduled for deletion"),fl(this),lc(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||rc(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&as("Object already scheduled for deletion"),oi.push(this),oi.length===1&&mn&&mn(Xi),this.$$.deleteScheduled=!0,this}});let de=Symbol.dispose;de&&(K[de]=K.delete)};function vn(){}var _n=(K,de)=>Object.defineProperty(de,"name",{value:K}),ts=(K,de,De)=>{if(K[de].overloadTable===void 0){var Je=K[de];K[de]=function(...ut){return K[de].overloadTable.hasOwnProperty(ut.length)||as(`Function '${De}' called with an invalid number of arguments (${ut.length}) - expects one of (${K[de].overloadTable})!`),K[de].overloadTable[ut.length].apply(this,ut)},K[de].overloadTable=[],K[de].overloadTable[Je.argCount]=Je}},is=(K,de,De)=>{r.hasOwnProperty(K)?((De===void 0||r[K].overloadTable!==void 0&&r[K].overloadTable[De]!==void 0)&&as(`Cannot register public name '${K}' twice`),ts(r,K,K),r[K].overloadTable.hasOwnProperty(De)&&as(`Cannot register multiple overloads of a function with the same number of arguments (${De})!`),r[K].overloadTable[De]=de):(r[K]=de,r[K].argCount=De)},bn=48,Zs=57,ho=K=>{G(typeof K=="string"),K=K.replace(/[^a-zA-Z0-9_]/g,"$");var de=K.charCodeAt(0);return de>=bn&&de<=Zs?`_${K}`:K};function Ks(K,de,De,Je,ut,Ot,Gt,zt){this.name=K,this.constructor=de,this.instancePrototype=De,this.rawDestructor=Je,this.baseClass=ut,this.getActualType=Ot,this.upcast=Gt,this.downcast=zt,this.pureVirtualFunctions=[]}var Cs=(K,de,De)=>{for(;de!==De;)de.upcast||as(`Expected null or instance of ${De.name}, got an instance of ${de.name}`),K=de.upcast(K),de=de.baseClass;return K};function Uo(K,de){if(de===null)return this.isReference&&as(`null is not a valid ${this.name}`),0;de.$$||as(`Cannot pass "${Br(de)}" as a ${this.name}`),de.$$.ptr||as(`Cannot pass deleted object as a pointer of type ${this.name}`);var De=de.$$.ptrType.registeredClass,Je=Cs(de.$$.ptr,De,this.registeredClass);return Je}function an(K,de){var De;if(de===null)return this.isReference&&as(`null is not a valid ${this.name}`),this.isSmartPointer?(De=this.rawConstructor(),K!==null&&K.push(this.rawDestructor,De),De):0;(!de||!de.$$)&&as(`Cannot pass "${Br(de)}" as a ${this.name}`),de.$$.ptr||as(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&de.$$.ptrType.isConst&&as(`Cannot convert argument of type ${de.$$.smartPtrType?de.$$.smartPtrType.name:de.$$.ptrType.name} to parameter type ${this.name}`);var Je=de.$$.ptrType.registeredClass;if(De=Cs(de.$$.ptr,Je,this.registeredClass),this.isSmartPointer)switch(de.$$.smartPtr===void 0&&as("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:de.$$.smartPtrType===this?De=de.$$.smartPtr:as(`Cannot convert argument of type ${de.$$.smartPtrType?de.$$.smartPtrType.name:de.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:De=de.$$.smartPtr;break;case 2:if(de.$$.smartPtrType===this)De=de.$$.smartPtr;else{var ut=de.clone();De=this.rawShare(De,Ro.toHandle
`)),!K)return null;rT=lT(K,!0)}return rT.shift()},rf={ttys:[],init(){},shutdown(){},register(K,de){rf.ttys[K]={input:[],output:[],ops:de},ct.registerDevice(K,rf.stream_ops)},stream_ops:{open(K){var de=rf.ttys[K.node.rdev];if(!de)throw new ct.ErrnoError(43);K.tty=de,K.seekable=!1},close(K){K.tty.ops.fsync(K.tty)},fsync(K){K.tty.ops.fsync(K.tty)},read(K,de,De,Je,ut){if(!K.tty||!K.tty.ops.get_char)throw new ct.ErrnoError(60);for(var Ot=0,Gt=0;Gt<Je;Gt++){var zt;try{zt=K.tty.ops.get_char(K.tty)}catch{throw new ct.ErrnoError(29)}if(zt===void 0&&Ot===0)throw new ct.ErrnoError(6);if(zt==null)break;Ot++,de[De+Gt]=zt}return Ot&&(K.node.atime=Date.now()),Ot},write(K,de,De,Je,ut){if(!K.tty||!K.tty.ops.put_char)throw new ct.ErrnoError(60);try{for(var Ot=0;Ot<Je;Ot++)K.tty.ops.put_char(K.tty,de[De+Ot])}catch{throw new ct.ErrnoError(29)}return Je&&(K.node.mtime=K.node.ctime=Date.now()),Ot}},default_tty_ops:{get_char(K){return b4()},put_char(K,de){de===null||de===10?(S(Qs(K.output)),K.output=[]):de!=0&&K.output.push(de)},fsync(K){K.output?.length>0&&(S(Qs(K.output)),K.output=[])},ioctl_tcgets(K){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(K,de,De){return 0},ioctl_tiocgwinsz(K){return[24,80]}},default_tty1_ops:{put_char(K,de){de===null||de===10?(_(Qs(K.output)),K.output=[]):de!=0&&K.output.push(de)},fsync(K){K.output?.length>0&&(_(Qs(K.output)),K.output=[])}}},O3=K=>{Oe("internal error: mmapAlloc called but `emscripten_builtin_memalign` native symbol not exported")},Fs={ops_table:null,mount(K){return Fs.createNode(null,"/",16895,0)},createNode(K,de,De,Je){if(ct.isBlkdev(De)||ct.isFIFO(De))throw new ct.ErrnoError(63);Fs.ops_table||={dir:{node:{getattr:Fs.node_ops.getattr,setattr:Fs.node_ops.setattr,lookup:Fs.node_ops.lookup,mknod:Fs.node_ops.mknod,rename:Fs.node_ops.rename,unlink:Fs.node_ops.unlink,rmdir:Fs.node_ops.rmdir,readdir:Fs.node_ops.readdir,symlink:Fs.node_ops.symlink},stream:{llseek:Fs.stream_ops.llseek}},file:{node:{getattr:Fs.node_ops.getattr,setattr:Fs.node_ops.setattr},stream:{llseek:Fs.stream_ops.llseek,read:Fs.stream_ops.read,write:Fs.stream_ops.write,mmap:Fs.stream_ops.mmap,msync:Fs.stream_ops.msync}},link:{node:{getattr:Fs.node_ops.getattr,setattr:Fs.node_ops.setattr,readlink:Fs.node_ops.readlink},stream:{}},chrdev:{node:{getattr:Fs.node_ops.getattr,setattr:Fs.node_ops.setattr},stream:ct.chrdev_stream_ops}};var ut=ct.createNode(K,de,De,Je);return ct.isDir(ut.mode)?(ut.node_ops=Fs.ops_table.dir.node,ut.stream_ops=Fs.ops_table.dir.stream,ut.contents={}):ct.isFile(ut.mode)?(ut.node_ops=Fs.ops_table.file.node,ut.stream_ops=Fs.ops_table.file.stream,ut.usedBytes=0,ut.contents=null):ct.isLink(ut.mode)?(ut.node_ops=Fs.ops_table.link.node,ut.stream_ops=Fs.ops_table.link.stream):ct.isChrdev(ut.mode)&&(ut.node_ops=Fs.ops_table.chrdev.node,ut.stream_ops=Fs.ops_table.chrdev.stream),ut.atime=ut.mtime=ut.ctime=Date.now(),K&&(K.contents[de]=ut,K.atime=K.mtime=K.ctime=ut.atime),ut},getFileDataAsTypedArray(K){return K.contents?K.contents.subarray?K.contents.subarray(0,K.usedBytes):new Uint8Array(K.contents):new Uint8Array(0)},expandFileStorage(K,de){var De=K.contents?K.contents.length:0;if(!(De>=de)){var Je=1024*1024;de=Math.max(de,De*(De<Je?2:1.125)>>>0),De!=0&&(de=Math.max(de,256));var ut=K.contents;K.contents=new Uint8Array(de),K.usedBytes>0&&K.contents.set(ut.subarray(0,K.usedBytes),0)}},resizeFileStorage(K,de){if(K.usedBytes!=de)if(de==0)K.contents=null,K.usedBytes=0;else{var De=K.contents;K.contents=new Uint8Array(de),De&&K.contents.set(De.subarray(0,Math.min(de,K.usedBytes))),K.usedBytes=de}},node_ops:{getattr(K){var de={};return de.dev=ct.isChrdev(K.mode)?K.id:1,de.ino=K.id,de.mode=K.mode,de.nlink=1,de.uid=0,de.gid=0,de.rdev=K.rdev,ct.isDir(K.mode)?de.size=4096:ct.isFile(K.mode)?de.size=K.usedBytes:ct.isLink(K.mode)?de.size=K.link.length:de.size=0,de.atime=new Date(K.atime),de.mtime=new Date(K.mtime),de.ctime=new Date(K.ctime),de.blksize=4096,de.blocks=Math.ceil(de.size/de.blksize),de},setattr(K,de){for(let De of["mode",
#include <common>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
uniform float linewidth;
uniform vec2 resolution;
attribute vec3 instanceStart;
attribute vec3 instanceEnd;
attribute vec3 instanceColorStart;
attribute vec3 instanceColorEnd;
#ifdef WORLD_UNITS
varying vec4 worldPos;
varying vec3 worldStart;
varying vec3 worldEnd;
#ifdef USE_DASH
varying vec2 vUv;
#endif
#else
varying vec2 vUv;
#endif
#ifdef USE_DASH
uniform float dashScale;
attribute float instanceDistanceStart;
attribute float instanceDistanceEnd;
varying float vLineDistance;
#endif
void trimSegment( const in vec4 start, inout vec4 end ) {
// trim end segment so it terminates between the camera plane and the near plane
// conservative estimate of the near plane
float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
float nearEstimate = - 0.5 * b / a;
float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );
end.xyz = mix( start.xyz, end.xyz, alpha );
}
void main() {
#ifdef USE_COLOR
vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;
#endif
#ifdef USE_DASH
vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
vUv = uv;
#endif
float aspect = resolution.x / resolution.y;
// camera space
vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );
#ifdef WORLD_UNITS
worldStart = start.xyz;
worldEnd = end.xyz;
#else
vUv = uv;
#endif
// special case for perspective projection, and segments that terminate either in, or behind, the camera plane
// clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
// but we need to perform ndc-space calculations in the shader, so we must address this issue directly
// perhaps there is a more elegant solution -- WestLangley
bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column
if ( perspective ) {
if ( start.z < 0.0 && end.z >= 0.0 ) {
trimSegment( start, end );
} else if ( end.z < 0.0 && start.z >= 0.0 ) {
trimSegment( end, start );
}
}
// clip space
vec4 clipStart = projectionMatrix * start;
vec4 clipEnd = projectionMatrix * end;
// ndc space
vec3 ndcStart = clipStart.xyz / clipStart.w;
vec3 ndcEnd = clipEnd.xyz / clipEnd.w;
// direction
vec2 dir = ndcEnd.xy - ndcStart.xy;
// account for clip-space aspect ratio
dir.x *= aspect;
dir = normalize( dir );
#ifdef WORLD_UNITS
vec3 worldDir = normalize( end.xyz - start.xyz );
vec3 tmpFwd = normalize( mix( start.xyz, end.xyz, 0.5 ) );
vec3 worldUp = normalize( cross( worldDir, tmpFwd ) );
vec3 worldFwd = cross( worldDir, worldUp );
worldPos = position.y < 0.5 ? start: end;
// height offset
float hw = linewidth * 0.5;
worldPos.xyz += position.x < 0.0 ? hw * worldUp : - hw * worldUp;
// don't extend the line if we're rendering dashes because we
// won't be rendering the endcaps
#ifndef USE_DASH
// cap extension
worldPos.xyz += position.y < 0.5 ? - hw * worldDir : hw * worldDir;
// add width to the box
worldPos.xyz += worldFwd * hw;
// endcaps
if ( position.y > 1.0 || position.y < 0.0 ) {
worldPos.xyz -= worldFwd * 2.0 * hw;
}
#endif
// project the worldpos
vec4 clip = projectionMatrix * worldPos;
// shift the depth of the projected points so the line
// segments overlap neatly
vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
clip.z = clipPose.z * clip.w;
#else
vec2 offset = vec2( dir.y, - dir.x );
// undo aspect ratio adjustment
dir.x /= aspect;
offset.x /= aspect;
// sign flip
if ( position.x < 0.0 ) offset *= - 1.0;
// endcaps
if ( position.y < 0.0 ) {
offset += - dir;
} else if ( position.y > 1.0 ) {
offset += dir;
}
// adjust for linewidth
offset *= linewidth;
// adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
offset /= resolution.y;
// select end
vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;
// back to clip space
offset *= clip.w;
clip.xy += offset;
#endif
gl_Position = clip;
vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <fog_vertex>
}
`,fragmentShader:`
uniform vec3 diffuse;
uniform float opacity;
uniform float linewidth;
#ifdef USE_DASH
uniform float dashOffset;
uniform float dashSize;
uniform float gapSize;
#endif
varying float vLineDistance;
#ifdef WORLD_UNITS
varying vec4 worldPos;
varying vec3 worldStart;
varying vec3 worldEnd;
#ifdef USE_DASH
varying vec2 vUv;
#endif
#else
varying vec2 vUv;
#endif
#include <common>
#include <color_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {
float mua;
float mub;
vec3 p13 = p1 - p3;
vec3 p43 = p4 - p3;
vec3 p21 = p2 - p1;
float d1343 = dot( p13, p43 );
float d4321 = dot( p43, p21 );
float d1321 = dot( p13, p21 );
float d4343 = dot( p43, p43 );
float d2121 = dot( p21, p21 );
float denom = d2121 * d4343 - d4321 * d4321;
float numer = d1343 * d4321 - d1321 * d4343;
mua = numer / denom;
mua = clamp( mua, 0.0, 1.0 );
mub = ( d1343 + d4321 * ( mua ) ) / d4343;
mub = clamp( mub, 0.0, 1.0 );
return vec2( mua, mub );
}
void main() {
float alpha = opacity;
vec4 diffuseColor = vec4( diffuse, alpha );
#include <clipping_planes_fragment>
#ifdef USE_DASH
if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX
#endif
#ifdef WORLD_UNITS
// Find the closest points on the view ray and the line segment
vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
vec3 lineDir = worldEnd - worldStart;
vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );
vec3 p1 = worldStart + lineDir * params.x;
vec3 p2 = rayEnd * params.y;
vec3 delta = p1 - p2;
float len = length( delta );
float norm = len / linewidth;
#ifndef USE_DASH
#ifdef USE_ALPHA_TO_COVERAGE
float dnorm = fwidth( norm );
alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );
#else
if ( norm > 0.5 ) {
discard;
}
#endif
#endif
#else
#ifdef USE_ALPHA_TO_COVERAGE
// artifacts appear on some hardware if a derivative is taken within a conditional
float a = vUv.x;
float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
float len2 = a * a + b * b;
float dlen = fwidth( len2 );
if ( abs( vUv.y ) > 1.0 ) {
alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );
}
#else
if ( abs( vUv.y ) > 1.0 ) {
float a = vUv.x;
float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
float len2 = a * a + b * b;
if ( len2 > 1.0 ) discard;
}
#endif
#endif
#include <logdepthbuf_fragment>
#include <color_fragment>
gl_FragColor = vec4( diffuseColor.rgb, alpha );
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
}
`};var dI=class extends Bs{constructor(t){super({type:"LineMaterial",uniforms:xu.clone(Rp.line.uniforms),vertexShader:Rp.line.vertexShader,fragmentShader:Rp.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(t)}get color(){return this.uniforms.diffuse.value}set color(t){this.uniforms.diffuse.value=t}get worldUnits(){return"WORLD_UNITS"in this.defines}set worldUnits(t){t===!0!==this.worldUnits&&(this.needsUpdate=!0),t===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(t){this.uniforms.linewidth&&(this.uniforms.linewidth.value=t)}get dashed(){return"USE_DASH"in this.defines}set dashed(t){t===!0!==this.dashed&&(this.needsUpdate=!0),t===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(t){this.uniforms.dashScale.value=t}get dashSize(){return this.uniforms.dashSize.value}set dashSize(t){this.uniforms.dashSize.value=t}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(t){this.uniforms.dashOffset.value=t}get gapSize(){return this.uniforms.gapSize.value}set gapSize(t){this.uniforms.gapSize.value=t}get opacity(){return this.uniforms.opacity.value}set opacity(t){this.uniforms&&(this.uniforms.opacity.value=t)}get resolution(){return this.uniforms.resolution.value}set resolution(t){this.uniforms.resolution.value.copy(t)}get alphaToCoverage(){return"USE_ALPHA_TO_COVERAGE"in this.defines}set alphaToCoverage(t){this.defines&&(t===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),t===!0?this.defines.USE_ALPHA_TO_COVERAGE="":delete this.defines.USE_ALPHA_TO_COVERAGE)}};var Gae=new Gn,F3e=new ne,U3e=new ne,Vf=new Gn,kf=new Gn,k2=new Gn,Vae=new ne,kae=new di,zf=new wn,H3e=new ne,UQ=new tn,HQ=new no,z2=new Gn,W2,vL;function G3e(e,t,i){return z2.set(0,0,-t,1).applyMatrix4(e.projectionMatrix),z2.multiplyScalar(1/z2.w),z2.x=vL/i.width,z2.y=vL/i.height,z2.applyMatrix4(e.projectionMatrixInverse),z2.multiplyScalar(1/z2.w),Math.abs(Math.max(z2.x,z2.y))}function Dke(e,t){let i=e.matrixWorld,n=e.geometry,s=n.attributes.instanceStart,o=n.attributes.instanceEnd,r=Math.min(n.instanceCount,s.count);for(let l=0,a=r;l<a;l++){zf.start.fromBufferAttribute(s,l),zf.end.fromBufferAttribute(o,l),zf.applyMatrix4(i);let u=new ne,h=new ne;W2.distanceSqToSegment(zf.start,zf.end,h,u),h.distanceTo(u)<vL*.5&&t.push({point:h,pointOnLine:u,distance:W2.origin.distanceTo(h),object:e,face:null,faceIndex:l,uv:null,uv1:null})}}function Nke(e,t,i){let n=t.projectionMatrix,o=e.material.resolution,r=e.matrixWorld,l=e.geometry,a=l.attributes.instanceStart,u=l.attributes.instanceEnd,h=Math.min(l.instanceCount,a.count),p=-t.near;W2.at(1,k2),k2.w=1,k2.applyMatrix4(t.matrixWorldInverse),k2.applyMatrix4(n),k2.multiplyScalar(1/k2.w),k2.x*=o.x/2,k2.y*=o.y/2,k2.z=0,Vae.copy(k2),kae.multiplyMatrices(t.matrixWorldInverse,r);for(let m=0,I=h;m<I;m++){if(Vf.fromBufferAttribute(a,m),kf.fromBufferAttribute(u,m),Vf.w=1,kf.w=1,Vf.applyMatrix4(kae),kf.applyMatrix4(kae),Vf.z>p&&kf.z>p)continue;if(Vf.z>p){let _=Vf.z-kf.z,x=(Vf.z-p)/_;Vf.lerp(kf,x)}else if(kf.z>p){let _=kf.z-Vf.z,x=(kf.z-p)/_;kf.lerp(Vf,x)}Vf.applyMatrix4(n),kf.applyMatrix4(n),Vf.multiplyScalar(1/Vf.w),kf.multiplyScalar(1/kf.w),Vf.x*=o.x/2,Vf.y*=o.y/2,kf.x*=o.x/2,kf.y*=o.y/2,zf.start.copy(Vf),zf.start.z=0,zf.end.copy(kf),zf.end.z=0;let E=zf.closestPointToPointParameter(Vae,!0);zf.at(E,H3e);let w=Ns.lerp(Vf.z,kf.z,E),T=w>=-1&&w<=1,S=Vae.distanceTo(H3e)<vL*.5;if(T&&S){zf.start.fromBufferAttribute(a,m),zf.end.fromBufferAttribute(u,m),zf.start.applyMatrix4(r),zf.end.applyMatrix4(r);let _=new ne,x=new ne;W2.distanceSqToSegment(zf.start,zf.end,x,_),i.push({point:x,pointOnLine:_,distance:W2.origin.distanceTo(x),object:e,face:null,faceIndex:m,uv:null,uv1:null})}}}var SL=class extends ci{constructor(t=new gb,i=new dI({color:Math.random()*16777215})){super(t,i),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){let t=this.geometry,i=t.attributes.instanceStart,n=t.attributes.instanceEnd,s=new Float32Array(2*i.count);for(let r=0,
#include <common>
#include <clipping_planes_pars_vertex>
attribute float itemFilter;
uniform vec2 lodSize;
attribute vec3 itemFirst;
attribute vec3 itemLast;
float lodWidth = 2.0;
void cutLodLine(const in vec4 first, inout vec4 second ) {
float projValue1 = projectionMatrix[2][2];
float projValue2 = projectionMatrix[3][2];
float approxResult = -(projValue2 / projValue1) / 2.0;
float diff1 = approxResult - first.z;
float diff2 = second.z - first.z;
float cutFilter = diff1 / diff2;
second.xyz = mix(first.xyz, second.xyz, cutFilter);
}
varying float vHighlight;
void main() {
if (itemFilter == 0.0) {
gl_Position = vec4(0,0,0,0);
return;
}
vHighlight = itemFilter > 1.5 ? 1.0 : 0.0;
vec4 rawFirst = vec4(itemFirst, 1.0);
vec4 rawLast = vec4(itemLast, 1.0);
vec4 first = modelViewMatrix * rawFirst;
vec4 last = modelViewMatrix * rawLast;
bool lodPerspective = projectionMatrix[2][3] == -1.0;
if (lodPerspective) {
bool firstCut = first.z < 0.0 && last.z >= 0.0;
bool lastCut = last.z < 0.0 && first.z >= 0.0;
if (firstCut) {
cutLodLine( first, last );
} else if (lastCut) {
cutLodLine( last, first );
}
}
vec4 firstCut = projectionMatrix * first;
vec4 lastCut = projectionMatrix * last;
vec3 firstNdc = firstCut.xyz / firstCut.w;
vec3 lastNdc = lastCut.xyz / lastCut.w;
vec2 lodOrientation = lastNdc.xy - firstNdc.xy;
float lodRatio = lodSize.x / lodSize.y;
lodOrientation.x *= lodRatio;
lodOrientation = normalize(lodOrientation);
vec2 lodDistance = vec2(lodOrientation.y, - lodOrientation.x);
lodOrientation.x /= lodRatio;
lodDistance.x /= lodRatio;
if (position.x < 0.0) {
lodDistance *= - 1.0;
}
if (position.y < 0.0) {
lodDistance += -lodOrientation;
} else if (position.y > 1.0) {
lodDistance += lodOrientation;
}
lodDistance *= lodWidth;
lodDistance /= lodSize.y;
bool isFirst = position.y < 0.5;
vec4 lodPosition = isFirst ? firstCut : lastCut;
lodDistance *= lodPosition.w;
lodPosition.xy += lodDistance;
gl_Position = lodPosition;
vec4 mvPosition = isFirst ? first : last;
#include <clipping_planes_vertex>
}
`);Ne(iF,"fragment",`
#include <common>
#include <clipping_planes_pars_fragment>
uniform vec3 lodColor;
uniform float lodOpacity;
uniform vec3 highlightColor;
uniform float highlightOpacity;
varying float vHighlight;
void main() {
#include <clipping_planes_fragment>
vec3 color = mix(lodColor, highlightColor, vHighlight);
float alpha = mix(lodOpacity, highlightOpacity, vHighlight);
gl_FragColor = vec4(color, alpha);
#include <colorspace_fragment>
}
`);var Nj=class kC{static setupLodMeshResize(t){t.onBeforeRender=i=>{i.getSize(t.material[0].lodSize)}}static setupLodAttributes(t){t.setIndex(kC.indices),t.setAttribute("position",kC.vertices)}static setLodBuffer(t,i,n){let s=t.getItemFirst(),o=t.getItemLast(),r=this.setItemFirst(t,s,i,o);({itemFirst:s,dataBuffer:r,itemLast:o}=this.resetAttributes(s,r,i,o)),this.setupFinish(n,r),t.setAttribute("itemFirst",s),t.setAttribute("itemLast",o)}static setLodVisibility(t,i){let n=this.setupItemFilter(t);this.applyVisibilityState(t,i,n),n.needsUpdate=!0}static getInterAttribute(t,i){return t.getAttribute(i)}static computeLodSphere(t){if(!t.boundingSphere)return;let i=t.getItemFirst();if(i){let n=kC.getLodMidPoint(t,i),s=kC.getLodRadius(n,i);t.boundingSphere.radius=s}}static newLodMaterialParams(t){let i={lodColor:{value:new Ei(t.color)},lodSize:{value:new si(1,1)},lodOpacity:{value:t.opacity??1},highlightColor:{value:new Ei(1,1,1)},highlightOpacity:{value:1}},n=xu.merge([yn.common,i]),s=t.transparent??!1;return{uniforms:n,transparent:s,vertexShader:iF.vertex,fragmentShader:iF.fragment}}static setLodFilter(t,i){let n=t.getItemFilter(),s=n.array;for(let o=0;o<i.position.length;++o){let r=i.position[o]/2,l=i.size[o]/2;l===4294967295?s.fill(1,r):s.fill(1,r,r+l)}n.needsUpdate=!0}static setLodHighlight(t,i){let n=t.getItemFilter(),s=n.array;for(let o=0;o<i.position.length;++o){let r=i.position[o]/2,l=i.size[o]/2;l===4294967295?s.fill(2,r):s.fill(2,r,r+l)}n.needsUpdate=!0}static getInstancedAttribute(t,i){return t.getAttribute(i)}static computeLodBox(t){if(!t.boundingBox)return;let i=t.getItemFirst();if(i){let n=i.data.array;t.boundingBox.setFromArray(n);return}t.boundingBox.makeEmpty()}static setDataBuffer(t,i,n){return t=i.data,t.array=n,t.needsUpdate=!0,t}static disposeAllData(t){delete t.attributes.itemFilter,delete t.attributes.position,t.index=null,t.dispose(),kC.setupLodAttributes(t)}static setItemFirst(t,i,n,s){let o=null;return i&&(n.length===i.data.array.length?o=this.setDataBuffer(o,i,n):(i=void 0,this.disposeAllData(t))),o}static setupFinish(t,i){t&&(i.onUploadCallback=t)}static resetAttributes(t,i,n,s){return t||(i=new Yy(n,6,1),t=new gc(i,3,0),s=new gc(i,3,3)),{itemFirst:t,dataBuffer:i,itemLast:s}}static setupItemFilter(t){let n=t.getItemFirst().count,s=t.getItemFilter();return s?s.array.fill(0):(s=new M0(new Uint8Array(n),1),t.setAttribute("itemFilter",s)),s}static applyVisibilityState(t,i,n){if(i===!0){n.array.fill(1);return}i&&this.setLodFilter(t,i)}static getLodMidPoint(t,i){let n=t.boundingSphere.center;return this.tempBox.setFromArray(i.data.array),this.tempBox.getCenter(n),n}static getLodRadius(t,i){let n=0,s=i.data.array.length;for(let o=0;o<s;o+=3){let r=i.data.array;kC.tempVec.fromArray(r,o);let l=t.distanceToSquared(kC.tempVec);n=Math.max(n,l)}return Math.sqrt(n)}};Ne(Nj,"tempVec",new ne);Ne(Nj,"tempBox",new tn);Ne(Nj,"vertices",new ln([-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0],3));Ne(Nj,"indices",new X7([0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5],1));var Kw=Nj,vJ=class extends ci{constructor(t,i){super(t,i),Ne(this,"geometry"),Ne(this,"material"),this.geometry=t,this.material=i,Kw.setupLodMeshResize(this)}},jue=class extends kR{constructor(){super(),Ne(this,"isLODGeometry",!0),Kw.setupLodAttributes(this)}isFiltered(){return!!this.getItemFilter()}computeBoundingBox(){this.boundingBox||(this.boundingBox=new tn),Kw.computeLodBox(this)}applyMatrix4(t){return this.applyTransformToBuffers(t),this.updateBounds(),this}computeBoundingSphere(){this.boundingSphere||(this.boundingSphere=new no),Kw.computeLodSphere(this)}getItemFilter(){return Kw.getInstancedAttribute(this,"itemFilter")}getItemLast(){return Kw.getInterAttribute(this,"itemLast")}getItemFirst(){return Kw.getInterAttribute(this,"itemFirst")}applyTransformToBuffers(t){this.getItemFirst().applyMatrix4(t),this.getItemLast().applyMatrix4(t)}updateBounds(){this.boundingBox&&this.computeBoundingBox(),this.boundingSphere&&this.computeBoundingSphere()}},Yue=class extends Bs{constructor(t){super(Kw.newLodMaterialParams(t)),Ne(this,"isLodMaterial",!0),Ne(thi
`).map(i=>{let n=i.match(t);if(!n)return null;let s=n[1]||n[2]||"",o=n[3].split("?")[0],r=parseInt(n[4],10),l=parseInt(n[5],10),a=o.split("/").pop();return{fn:s,file:a,line:r,column:l}}).filter(i=>i&&!lqe.some(n=>n.test(i.file)))}var $a=class{constructor(t=null){this.isStackTrace=!0,this.stack=aqe(t||new Error().stack)}getLocation(){if(this.stack.length===0)return"[Unknown location]";let t=this.stack[0],i=t.fn;return`${i?`"${i}()" at `:""}"${t.file}:${t.line}"`}getError(t){if(this.stack.length===0)return t;let i=this.stack.map(n=>{let s=`${n.file}:${n.line}:${n.column}`;return n.fn?` at ${n.fn} (${s})`:` at ${s}`}).join(`
`);return`${t}
${i}`}};function wpe(e,t=0){let i=3735928559^t,n=1103547991^t;if(Array.isArray(e))for(let s=0,o;s<e.length;s++)o=e[s],i=Math.imul(i^o,2654435761),n=Math.imul(n^o,1597334677);else for(let s=0,o;s<e.length;s++)o=e.charCodeAt(s),i=Math.imul(i^o,2654435761),n=Math.imul(n^o,1597334677);return i=Math.imul(i^i>>>16,2246822507),i^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(i^i>>>13,3266489909),4294967296*(2097151&n)+(i>>>0)}var MF=e=>wpe(e),TY=e=>wpe(e),qj=(...e)=>wpe(e),uqe=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),q2e=new WeakMap;function c4e(e){return uqe.get(e)}function pX(e){if(/[iu]?vec\d/.test(e))return e.startsWith("ivec")?Int32Array:e.startsWith("uvec")?Uint32Array:Float32Array;if(/mat\d/.test(e)||/float/.test(e))return Float32Array;if(/uint/.test(e))return Uint32Array;if(/int/.test(e))return Int32Array;throw new Error(`THREE.NodeUtils: Unsupported type: ${e}`)}function d4e(e){if(/float|int|uint/.test(e))return 1;if(/vec2/.test(e))return 2;if(/vec3/.test(e))return 3;if(/vec4/.test(e)||/mat2/.test(e))return 4;if(/mat3/.test(e))return 9;if(/mat4/.test(e))return 16;_i(`TSL: Unsupported type: ${e}`,new $a)}function cqe(e){if(/float|int|uint/.test(e))return 1;if(/vec2/.test(e))return 2;if(/vec3/.test(e))return 3;if(/vec4/.test(e)||/mat2/.test(e))return 4;if(/mat3/.test(e))return 12;if(/mat4/.test(e))return 16;_i(`TSL: Unsupported type: ${e}`,new $a)}function dqe(e){if(/float|int|uint/.test(e))return 4;if(/vec2/.test(e))return 8;if(/vec3/.test(e)||/vec4/.test(e))return 16;if(/mat2/.test(e))return 8;if(/mat3/.test(e)||/mat4/.test(e))return 16;_i(`TSL: Unsupported type: ${e}`,new $a)}function mD(e){if(e==null)return null;let t=typeof e;return e.isNode===!0?"node":t==="number"?"float":t==="boolean"?"bool":t==="string"?"string":t==="function"?"shader":e.isVector2===!0?"vec2":e.isVector3===!0?"vec3":e.isVector4===!0?"vec4":e.isMatrix2===!0?"mat2":e.isMatrix3===!0?"mat3":e.isMatrix4===!0?"mat4":e.isColor===!0?"color":e instanceof ArrayBuffer?"ArrayBuffer":null}function vpe(e,...t){let i=e?e.slice(-4):void 0;return t.length===1&&(i==="vec2"?t=[t[0],t[0]]:i==="vec3"?t=[t[0],t[0],t[0]]:i==="vec4"&&(t=[t[0],t[0],t[0],t[0]])),e==="color"?new Ei(...t):i==="vec2"?new si(...t):i==="vec3"?new ne(...t):i==="vec4"?new Gn(...t):i==="mat2"?new nO(...t):i==="mat3"?new us(...t):i==="mat4"?new di(...t):e==="bool"?t[0]||!1:e==="float"||e==="int"||e==="uint"?t[0]||0:e==="string"?t[0]||"":e==="ArrayBuffer"?fqe(t[0]):null}function h4e(e){let t=q2e.get(e);return t===void 0&&(t={},q2e.set(e,t)),t}function hqe(e){let t="",i=new Uint8Array(e);for(let n=0;n<i.length;n++)t+=String.fromCharCode(i[n]);return btoa(t)}function fqe(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0)).buffer}var jj={VERTEX:"vertex",FRAGMENT:"fragment"},ps={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},pqe={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},$f={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},f4e=["fragment","vertex"],aX=["setup","analyze","generate"],uX=[...f4e,"compute"],rP=["x","y","z","w"],mqe={analyze:"setup",generate:"analyze"},Iqe=0,Un=class e extends qd{static get type(){return"Node"}constructor(t=null){super(),this.nodeType=t,this.updateType=ps.NONE,this.updateBeforeType=ps.NONE,this.updateAfterType=ps.NONE,this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._uuid=null,this._cacheKeyVersion=0,this.id=Iqe++,this.stackTrace=null,e.captureStackTrace===!0&&(this.stackTrace=new $a)}set needsUpdate(t){t===!0&&this.version++}get uuid(){return this._uuid===null&&(this._uuid=Ns.generateUUID()),this._uuid}get type(){return this.constructor.type}onUpdate(t,i){return this.updateType=i,this.update=t.bind(this),this}onFrameUpdate(t){return this.onUpdate(t,ps.FRAME)}onRenderUpdate(t){return this.onUpdate(t,ps.RENDER)}onObjectUpdate(t){return this.onUpdate(t,ps.OBJECT)}onReference(t){return this.updateReference=t.bind
${t.tab}if ( ${p} ) {
`).addFlowTab();let I=r.build(t,n);if(I&&(u?I=h+" = "+I+";":(I="return "+I+";",a===null&&(yi("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),I="// "+I))),t.removeFlowTab().addFlowCode(t.tab+" "+I+`
`+t.tab+"}"),l!==null){t.addFlowCode(` else {
`).addFlowTab();let g=l.build(t,n);g&&(u?g=h+" = "+g+";":(g="return "+g+";",a===null&&(yi("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),g="// "+g))),t.removeFlowTab().addFlowCode(t.tab+" "+g+`
`+t.tab+`}
`)}else t.addFlowCode(`
`);return t.format(h,n,i)}},Kp=$s(nhe).setParameterLength(2,3);xi("select",Kp);var bX=class extends Un{static get type(){return"ContextNode"}constructor(t=null,i={}){super(),this.isContextNode=!0,this.node=t,this.value=i}getScope(){return this.node.getScope()}generateNodeType(t){return this.node.getNodeType(t)}getFlowContextData(){let t=[];return this.traverse(i=>{i.isContextNode===!0&&t.push(i.value)}),Object.assign({},...t)}getMemberType(t,i){return this.node.getMemberType(t,i)}analyze(t){let i=t.addContext(this.value);this.node.build(t),t.setContext(i)}setup(t){let i=t.addContext(this.value);this.node.build(t),t.setContext(i)}generate(t,i){let n=t.addContext(this.value),s=this.node.build(t,i);return t.setContext(n),s}},zb=(e=null,t={})=>{let i=e;return(i===null||i.isNode!==!0)&&(t=i||t,i=null),new bX(i,t)},wRe=e=>zb(e,{uniformFlow:!0}),Jpe=(e,t)=>zb(e,{nodeName:t});function vRe(e,t,i=null){return zb(i,{getShadow:({light:n,shadowColorNode:s})=>t===n?s.mul(e):s})}function SRe(e,t=null){return zb(t,{getAO:(i,{material:n})=>n.transparent===!0?i:i!==null?i.mul(e):e})}function RRe(e,t){return yi('TSL: "label()" has been deprecated. Use "setName()" instead.'),Jpe(e,t)}xi("context",zb);xi("label",RRe);xi("uniformFlow",wRe);xi("setName",Jpe);xi("builtinShadowContext",(e,t,i)=>vRe(t,i,e));xi("builtinAOContext",(e,t)=>SRe(t,e));var TF=class extends Un{static get type(){return"VarNode"}constructor(t,i=null,n=!1){super(),this.node=t,this.name=i,this.global=!0,this.isVarNode=!0,this.readOnly=n,this.parents=!0,this.intent=!1}setIntent(t){return this.intent=t,this}isIntent(t){return t.getDataFromNode(this).forceDeclaration===!0?!1:this.intent}getIntent(){return this.intent}getMemberType(t,i){return this.node.getMemberType(t,i)}getElementType(t){return this.node.getElementType(t)}generateNodeType(t){return this.node.getNodeType(t)}getArrayCount(t){return this.node.getArrayCount(t)}isAssign(t){return t.getDataFromNode(this).assign}build(...t){let i=t[0];if(this._hasStack(i)===!1&&i.buildStage==="setup"&&(i.context.nodeLoop||i.context.nodeBlock)){let n=!1;if(this.node.isShaderCallNodeInternal&&this.node.shaderNode.getLayout()===null&&i.fnCall&&i.fnCall.shaderNode&&i.getDataFromNode(this.node.shaderNode).hasLoop){let r=i.getDataFromNode(this);r.forceDeclaration=!0,n=!0}let s=i.getBaseStack();n?s.addToStackBefore(this):s.addToStack(this)}return this.isIntent(i)&&this.isAssign(i)!==!0?this.node.build(...t):super.build(...t)}generate(t){let{node:i,name:n,readOnly:s}=this,{renderer:o}=t,r=o.backend.isWebGPUBackend===!0,l=!1,a=!1;s&&(l=t.isDeterministic(i),a=r?s:l);let u=this.getNodeType(t);if(u=="void")return this.isIntent(t)!==!0&&_i('TSL: ".toVar()" can not be used with void type.',this.stackTrace),i.build(t);let h=t.getVectorType(u),p=i.build(t,h),m=t.getVarFromNode(this,n,h,void 0,a),I=t.getPropertyName(m),g=I;if(a)if(r)g=l?`const ${I}`:`let ${I}`;else{let E=i.getArrayCount(t);g=`const ${t.getVar(m.type,I,E)}`}return t.addLineFlowCode(`${g} = ${p}`,this),I}_hasStack(t){return t.getDataFromNode(this).stack!==void 0}},Xpe=$s(TF),_Re=(e,t=null)=>Xpe(e,t).toStack(),bRe=(e,t=null)=>Xpe(e,t,!0).toStack(),ARe=e=>Xpe(e).setIntent(!0).toStack();xi("toVar",_Re);xi("toConst",bRe);xi("toVarIntent",ARe);var she=class extends Un{static get type(){return"SubBuild"}constructor(t,i,n=null){super(n),this.node=t,this.name=i,this.isSubBuildNode=!0}generateNodeType(t){if(this.nodeType!==null)return this.nodeType;t.addSubBuild(this.name);let i=this.node.getNodeType(t);return t.removeSubBuild(),i}build(t,...i){t.addSubBuild(this.name);let n=this.node.build(t,...i);return t.removeSubBuild(),n}},eP=(e,t,i=null)=>new she(Bn(e),t,i),ohe=class extends Un{static get type(){return"VaryingNode"}constructor(t,i=null){super(),this.node=eP(t,"VERTEX"),this.name=i,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(t,i=null){return this.interpolationType=t,this.interpolationSampling=i,this}getHash(t){return this.name||super.getHash(t)}generateNodeType(t){return this.node.getNodeType(t)}setupVarying(t){let i=t.
${t.flow.code}`}}else{let o=t.getNodeProperties(this).outputComputeNode;if(o)return o.build(t,i)}}},ime=(e,t=[64])=>{(t.length===0||t.length>3)&&_i("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new $a);for(let i=0;i<t.length;i++){let n=t[i];(typeof n!="number"||n<=0||!Number.isInteger(n))&&_i(`TSL: compute() workgroupSize element at index [ ${i} ] must be a positive integer`,new $a)}for(;t.length<3;)t.push(1);return new uhe(Bn(e),t)},FRe=(e,t,i)=>{let n=ime(e,i);return typeof t=="number"?n.count=t:n.dispatchSize=t,n};xi("compute",FRe);xi("computeKernel",ime);var che=class extends Un{static get type(){return"IsolateNode"}constructor(t,i=!0){super(),this.node=t,this.parent=i,this.isIsolateNode=!0}generateNodeType(t){let i=t.getCache(),n=t.getCacheFromNode(this,this.parent);t.setCache(n);let s=this.node.getNodeType(t);return t.setCache(i),s}build(t,...i){let n=t.getCache(),s=t.getCacheFromNode(this,this.parent);t.setCache(s);let o=this.node.build(t,...i);return t.setCache(n),o}setParent(t){return this.parent=t,this}getParent(){return this.parent}},wF=e=>new che(Bn(e));function URe(e,t=!0){return yi('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),wF(e).setParent(t)}xi("cache",URe);xi("isolate",wF);var dhe=class extends Un{static get type(){return"BypassNode"}constructor(t,i){super(),this.isBypassNode=!0,this.outputNode=t,this.callNode=i}generateNodeType(t){return this.outputNode.getNodeType(t)}generate(t){let i=this.callNode.build(t,"void");return i!==""&&t.addLineFlowCode(i,this),this.outputNode.build(t)}},HRe=$s(dhe).setParameterLength(2);xi("bypass",HRe);var nme=Qt(([e,t,i,n=bt(0),s=bt(1),o=Q1(!1)])=>{let r=e.sub(t).div(i.sub(t));return RF(o)&&(r=r.clamp()),r.mul(s.sub(n)).add(n)});function GRe(e,t,i,n=bt(0),s=bt(1)){return nme(e,t,i,n,s,!0)}xi("remap",nme);xi("remapClamp",GRe);var vF=class extends Un{static get type(){return"ExpressionNode"}constructor(t="",i="void"){super(i),this.snippet=t}generate(t,i){let n=this.getNodeType(t),s=this.snippet;if(n==="void")t.addLineFlowCode(s,this);else return t.format(s,n,i)}},K1=$s(vF).setParameterLength(1,2),VRe=e=>(e?Kp(e,K1("discard")):K1("discard")).toStack(),Qqe=()=>K1("return").toStack();xi("discard",VRe);var hhe=class extends wa{static get type(){return"RenderOutputNode"}constructor(t,i,n){super("vec4"),this.colorNode=t,this._toneMapping=i,this.outputColorSpace=n,this.isRenderOutputNode=!0}setToneMapping(t){return this._toneMapping=t,this}getToneMapping(){return this._toneMapping}setup({context:t}){let i=this.colorNode||t.color,n=(this._toneMapping!==null?this._toneMapping:t.toneMapping)||_d,s=(this.outputColorSpace!==null?this.outputColorSpace:t.outputColorSpace)||Tf;return n!==_d&&(i=i.toneMapping(n)),s!==Tf&&s!==Kn.workingColorSpace&&(i=i.workingToColorSpace(s)),i}},sme=(e,t=null,i=null)=>new hhe(Bn(e),t,i);xi("renderOutput",sme);var fhe=class extends wa{static get type(){return"DebugNode"}constructor(t,i=null){super(),this.node=t,this.callback=i}generateNodeType(t){return this.node.getNodeType(t)}setup(t){return this.node.build(t)}analyze(t){return this.node.build(t)}generate(t){let i=this.callback,n=this.node.build(t);if(i!==null)i(t,n);else{let s="--- TSL debug - "+t.shaderStage+" shader ---",o="-".repeat(s.length),r="";r+="// #"+s+`#
`,r+=t.flow.code.replace(/^\t/mg,"")+`
`,r+="/* ... */ "+n+` /* ... */
`,r+="// #"+o+`#
`,Mx(r)}return n}},kRe=(e,t=null)=>new fhe(Bn(e),t).toStack();xi("debug",kRe);var CX=class extends qd{constructor(){super(),this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(t){return this._renderer=t,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}},phe=class extends Un{static get type(){return"InspectorNode"}constructor(t,i="",n=null){super(),this.node=t,this.name=i,this.callback=n,this.updateType=ps.FRAME,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(t){t.renderer.inspector.inspect(this)}generateNodeType(t){return this.node.getNodeType(t)}setup(t){let i=this.node;return t.context.inspector===!0&&this.callback!==null&&(i=this.callback(i)),t.renderer.backend.isWebGPUBackend!==!0&&t.renderer.inspector.constructor!==CX&&yr('TSL: ".toInspector()" is only available with WebGPU.'),i}};function zRe(e,t="",i=null){return e=Bn(e),e.before(new phe(e,t,i))}xi("toInspector",zRe);function Jqe(e){yi("TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)}var DX=class extends Un{static get type(){return"AttributeNode"}constructor(t,i=null){super(i),this.global=!0,this._attributeName=t}getHash(t){return this.getAttributeName(t)}generateNodeType(t){let i=this.nodeType;if(i===null){let n=this.getAttributeName(t);if(t.hasGeometryAttribute(n)){let s=t.geometry.getAttribute(n);i=t.getTypeFromAttribute(s)}else i="float"}return i}setAttributeName(t){return this._attributeName=t,this}getAttributeName(){return this._attributeName}generate(t){let i=this.getAttributeName(t),n=this.getNodeType(t);if(t.hasGeometryAttribute(i)===!0){let o=t.geometry.getAttribute(i),r=t.getTypeFromAttribute(o),l=t.getAttribute(i,r);return t.shaderStage==="vertex"?t.format(l.name,r,n):SD(this).build(t,n)}else return yi(`AttributeNode: Vertex attribute "${i}" not found on geometry.`),t.generateConst(n)}serialize(t){super.serialize(t),t.global=this.global,t._attributeName=this._attributeName}deserialize(t){super.deserialize(t),this.global=t.global,this._attributeName=t._attributeName}},Vb=(e,t=null)=>new DX(e,t),Or=(e=0)=>Vb("uv"+(e>0?e:""),"vec2"),mhe=class extends Un{static get type(){return"TextureSizeNode"}constructor(t,i=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=t,this.levelNode=i}generate(t,i){let n=this.textureNode.build(t,"property"),s=this.levelNode===null?"0":this.levelNode.build(t,"int");return t.format(`${t.getMethod("textureDimensions")}( ${n}, ${s} )`,this.getNodeType(t),i)}},gD=$s(mhe).setParameterLength(1,2),Ihe=class extends tP{static get type(){return"MaxMipLevelNode"}constructor(t){super(0),this._textureNode=t,this.updateType=ps.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){let t=this.texture,i=t.images,n=i&&i.length>0?i[0]&&i[0].image||i[0]:t.image;if(n&&n.width!==void 0){let{width:s,height:o}=n;this.value=Math.log2(Math.max(s,o))}}},ome=$s(Ihe).setParameterLength(1),NX=class extends Error{constructor(t,i=null){super(t),this.name="NodeError",this.stackTrace=i}},rme=new Ur,FE=class extends tP{static get type(){return"TextureNode"}constructor(t=rme,i=null,n=null,s=null){super(t),this.isTextureNode=!0,this.uvNode=i,this.levelNode=n,this.biasNode=s,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=ps.NONE,this.referenceNode=null,this._value=t,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(i===null)}set value(t){this.referenceNode?this.referenceNode.value=t:this._value=t}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}generateNodeType(){return this.value.isDepthTexture===!0?"float":this.value.type===Ko?"uvec4":this.value.type===Au?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return Or(this.value.channel)}updateReference
`:"")+t.tab+w+` {
`).addFlowTab()}let o=s.build(t,"void");i.returnsNode.build(t,"void"),t.removeFlowTab().addFlowCode(`
`+t.tab+o);for(let r=0,l=this.params.length-1;r<l;r++)t.addFlowCode((r===0?"":t.tab)+`}
`).removeFlowTab();t.addFlowTab()}},_r=(...e)=>new Uhe(JL(e,"int")).toStack(),G$e=()=>K1("continue").toStack(),e_e=()=>K1("break").toStack(),mde=new WeakMap,q1=new Gn,sSe=Qt(({bufferMap:e,influence:t,stride:i,width:n,depth:s,offset:o})=>{let r=Wt(MRe).mul(i).add(o),l=r.div(n),a=r.sub(l.mul(n));return fu(e,Od(a,l)).depth(s).xyz.mul(t)});function V$e(e){let t=e.morphAttributes.position!==void 0,i=e.morphAttributes.normal!==void 0,n=e.morphAttributes.color!==void 0,s=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,o=s!==void 0?s.length:0,r=mde.get(e);if(r===void 0||r.count!==o){let T=function(){E.dispose(),mde.delete(e),e.removeEventListener("dispose",T)};r!==void 0&&r.texture.dispose();let l=e.morphAttributes.position||[],a=e.morphAttributes.normal||[],u=e.morphAttributes.color||[],h=0;t===!0&&(h=1),i===!0&&(h=2),n===!0&&(h=3);let p=e.attributes.position.count*h,m=1,I=4096;p>I&&(m=Math.ceil(p/I),p=I);let g=new Float32Array(p*m*4*o),E=new LR(g,p,m,o);E.type=lr,E.needsUpdate=!0;let w=h*4;for(let S=0;S<o;S++){let _=l[S],x=a[S],M=u[S],W=p*m*4*S;for(let G=0;G<_.count;G++){let $=G*w;t===!0&&(q1.fromBufferAttribute(_,G),g[W+$+0]=q1.x,g[W+$+1]=q1.y,g[W+$+2]=q1.z,g[W+$+3]=0),i===!0&&(q1.fromBufferAttribute(x,G),g[W+$+4]=q1.x,g[W+$+5]=q1.y,g[W+$+6]=q1.z,g[W+$+7]=0),n===!0&&(q1.fromBufferAttribute(M,G),g[W+$+8]=q1.x,g[W+$+9]=q1.y,g[W+$+10]=q1.z,g[W+$+11]=M.itemSize===4?q1.w:1)}}r={count:o,texture:E,stride:h,size:new si(p,m)},mde.set(e,r),e.addEventListener("dispose",T)}return r}var Hhe=class extends Un{static get type(){return"MorphNode"}constructor(t){super("void"),this.mesh=t,this.morphBaseInfluence=kn(1),this.updateType=ps.OBJECT}setup(t){let{geometry:i}=t,n=i.morphAttributes.position!==void 0,s=i.hasAttribute("normal")&&i.morphAttributes.normal!==void 0,o=i.morphAttributes.position||i.morphAttributes.normal||i.morphAttributes.color,r=o!==void 0?o.length:0,{texture:l,stride:a,size:u}=V$e(i);n===!0&&Ea.mulAssign(this.morphBaseInfluence),s===!0&&Ey.mulAssign(this.morphBaseInfluence);let h=Wt(u.width);_r(r,({i:p})=>{let m=bt(0).toVar();this.mesh.count>1&&this.mesh.morphTexture!==null&&this.mesh.morphTexture!==void 0?m.assign(fu(this.mesh.morphTexture,Od(Wt(p).add(1),Wt(n3))).r):m.assign(cl("morphTargetInfluences","float").element(p).toVar()),Jn(m.notEqual(0),()=>{n===!0&&Ea.addAssign(sSe({bufferMap:l,influence:m,stride:a,width:h,depth:p,offset:Wt(0)})),s===!0&&Ey.addAssign(sSe({bufferMap:l,influence:m,stride:a,width:h,depth:p,offset:Wt(1)}))})})}update(){let t=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?t.value=1:t.value=1-this.mesh.morphTargetInfluences.reduce((i,n)=>i+n,0)}},t_e=$s(Hhe).setParameterLength(1),vD=class extends Un{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}},Ghe=class extends vD{static get type(){return"AONode"}constructor(t=null){super(),this.aoNode=t}setup(t){t.context.ambientOcclusion.mulAssign(this.aoNode)}},Vhe=class extends bX{static get type(){return"LightingContextNode"}constructor(t,i=null,n=null,s=null){super(t),this.lightingModel=i,this.backdropNode=n,this.backdropAlphaNode=s,this._value=null}getContext(){let{backdropNode:t,backdropAlphaNode:i}=this,n=Zt().toVar("directDiffuse"),s=Zt().toVar("directSpecular"),o=Zt().toVar("indirectDiffuse"),r=Zt().toVar("indirectSpecular"),l={directDiffuse:n,directSpecular:s,indirectDiffuse:o,indirectSpecular:r};return{radiance:Zt().toVar("radiance"),irradiance:Zt().toVar("irradiance"),iblIrradiance:Zt().toVar("iblIrradiance"),ambientOcclusion:bt(1).toVar("ambientOcclusion"),reflectedLight:l,backdrop:t,backdropAlpha:i}}setup(t){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||t.context.lightingModel,super.setup(t)}},i_e=$s(Vhe),khe=class extends vD{static get type(){return"IrradianceNode"}constructor(t){super(),this.node=t}setup(t){t.context.irradiance.addAssign(this.node)}},GL=new si,DF=class extends FE{static get type(){return"ViewportTextureNode"}constructor(t=gS,i=null,n=null){let s=null;n===null?(s=new Hx,s.minFilt
`,i==="property"?l:t.format(`${l}()`,o,i)}},V_e=(e,t=[],i="")=>{for(let o=0;o<t.length;o++){let r=t[o];typeof r=="function"&&(t[o]=r.functionNode)}let n=new ZX(e,t,i),s=(...o)=>n.call(...o);return s.functionNode=n,s},VQe=(e,t)=>V_e(e,t,"glsl"),kQe=(e,t)=>V_e(e,t,"wgsl");function Nme(e){let t,i=e.context.getViewZ;return i!==void 0&&(t=i(this)),(t||ic.z).negate()}var k_e=Qt(([e,t],i)=>{let n=Nme(i);return r3(e,t,n)}),z_e=Qt(([e],t)=>{let i=Nme(t);return e.mul(e,i,i).negate().exp().oneMinus()}),zQe=Qt(([e,t],i)=>{let n=Nme(i),o=t.sub(ES.y).max(0).toConst().mul(n).toConst();return e.mul(e,o,o).negate().exp().oneMinus()}),K0e=Qt(([e,t])=>qn(t.toFloat().mix(EF.rgb,e.toVec3()),EF.a)),kL=null,zL=null,Q0e=class extends Un{static get type(){return"RangeNode"}constructor(t=bt(),i=bt()){super(),this.minNode=t,this.maxNode=i}getVectorLength(t){let i=this.getConstNode(this.minNode),n=this.getConstNode(this.maxNode),s=t.getTypeLength(mD(i.value)),o=t.getTypeLength(mD(n.value));return s>o?s:o}generateNodeType(t){return t.object.count>1?t.getTypeFromLength(this.getVectorLength(t)):"float"}getConstNode(t){let i=null;if(t.traverse(n=>{n.isConstNode===!0&&(i=n)}),i===null)throw new NX('THREE.TSL: No "ConstNode" found in node graph.',this.stackTrace);return i}setup(t){let i=t.object,n=null;if(i.count>1){let s=this.getConstNode(this.minNode),o=this.getConstNode(this.maxNode),r=s.value,l=o.value,a=t.getTypeLength(mD(r)),u=t.getTypeLength(mD(l));kL=kL||new Gn,zL=zL||new Gn,kL.setScalar(0),zL.setScalar(0),a===1?kL.setScalar(r):r.isColor?kL.set(r.r,r.g,r.b,1):kL.set(r.x,r.y,r.z||0,r.w||0),u===1?zL.setScalar(l):l.isColor?zL.set(l.r,l.g,l.b,1):zL.set(l.x,l.y,l.z||0,l.w||0);let h=4,p=h*i.count,m=new Float32Array(p);for(let E=0;E<p;E++){let w=E%h,T=kL.getComponent(w),S=zL.getComponent(w);m[E]=Ns.lerp(T,S,Math.random())}let I=this.getNodeType(t);if(i.count*4*4<=t.getUniformBufferLimit())n=vY(m,"vec4",i.count).element(n3).convert(I);else{let E=new M0(m,4);t.geometry.setAttribute("__range"+this.id,E),n=xX(E).convert(I)}}else n=bt(0);return n}},WQe=$s(Q0e).setParameterLength(2),J0e=class extends Un{static get type(){return"ComputeBuiltinNode"}constructor(t,i){super(i),this._builtinName=t}getHash(t){return this.getBuiltinName(t)}generateNodeType(){return this.nodeType}setBuiltinName(t){return this._builtinName=t,this}getBuiltinName(){return this._builtinName}hasBuiltin(t){return t.hasBuiltin(this._builtinName)}generate(t,i){let n=this.getBuiltinName(t),s=this.getNodeType(t);return t.shaderStage==="compute"?t.format(n,s,i):(yi(`ComputeBuiltinNode: Compute built-in value ${n} can not be accessed in the ${t.shaderStage} stage`),t.generateConst(s))}serialize(t){super.serialize(t),t.global=this.global,t._builtinName=this._builtinName}deserialize(t){super.deserialize(t),this.global=t.global,this._builtinName=t._builtinName}},_Y=(e,t)=>new J0e(e,t),jQe=_Y("numWorkgroups","uvec3"),YQe=_Y("workgroupId","uvec3"),qQe=_Y("globalId","uvec3"),$Qe=_Y("localId","uvec3"),ZQe=_Y("subgroupSize","uint"),X0e=class extends Un{constructor(t){super(),this.scope=t,this.isBarrierNode=!0}setup(t){t.allowEarlyReturns=!1,t.allowGlobalVariables=!1}generate(t){let{scope:i}=this,{renderer:n}=t;n.backend.isWebGLBackend===!0?t.addFlowCode(` // ${i}Barrier
`):t.addLineFlowCode(`${i}Barrier()`,this)}},Ome=$s(X0e),KQe=()=>Ome("workgroup").toStack(),QQe=()=>Ome("storage").toStack(),JQe=()=>Ome("texture").toStack(),efe=class extends Hb{constructor(t,i){super(t,i),this.isWorkgroupInfoElementNode=!0}generate(t,i){let n,s=t.context.assign;if(n=super.generate(t),s!==!0){let o=this.getNodeType(t);n=t.format(n,o,i)}return n}},tfe=class extends Un{constructor(t,i,n=0){super(i),this.bufferType=i,this.bufferCount=n,this.isWorkgroupInfoNode=!0,this.elementType=i,this.scope=t,this.name=""}setName(t){return this.name=t,this}label(t){return yi('TSL: "label()" has been deprecated. Use "setName()" instead.',new $a),this.setName(t)}setScope(t){return this.scope=t,this}getElementType(){return this.elementType}getInputType(){return`${this.scope}Array`}element(t){return new efe(this,t)}generate(t){let i=this.name!==""?this.name:`${this.scope}Array_${this.id}`;return t.getScopedArray(i,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}},XQe=(e,t)=>new tfe("Workgroup",e,t),cd=class extends Un{static get type(){return"AtomicFunctionNode"}constructor(t,i,n){super("uint"),this.method=t,this.pointerNode=i,this.valueNode=n,this.parents=!0}getInputType(t){return this.pointerNode.getNodeType(t)}generateNodeType(t){return this.getInputType(t)}generate(t){let i=t.getNodeProperties(this),n=i.parents,s=this.method,o=this.getNodeType(t),r=this.getInputType(t),l=this.pointerNode,a=this.valueNode,u=[];u.push(`&${l.build(t,r)}`),a!==null&&u.push(a.build(t,r));let h=`${t.getMethod(s,o)}( ${u.join(", ")} )`;if(n?n.length===1&&n[0].isStackNode===!0:!1)t.addLineFlowCode(h,this);else return i.constNode===void 0&&(i.constNode=K1(h,o).toConst()),i.constNode.build(t)}};cd.ATOMIC_LOAD="atomicLoad";cd.ATOMIC_STORE="atomicStore";cd.ATOMIC_ADD="atomicAdd";cd.ATOMIC_SUB="atomicSub";cd.ATOMIC_MAX="atomicMax";cd.ATOMIC_MIN="atomicMin";cd.ATOMIC_AND="atomicAnd";cd.ATOMIC_OR="atomicOr";cd.ATOMIC_XOR="atomicXor";var eJe=$s(cd),bS=(e,t,i)=>eJe(e,t,i).toStack(),tJe=e=>bS(cd.ATOMIC_LOAD,e,null),iJe=(e,t)=>bS(cd.ATOMIC_STORE,e,t),nJe=(e,t)=>bS(cd.ATOMIC_ADD,e,t),sJe=(e,t)=>bS(cd.ATOMIC_SUB,e,t),oJe=(e,t)=>bS(cd.ATOMIC_MAX,e,t),rJe=(e,t)=>bS(cd.ATOMIC_MIN,e,t),lJe=(e,t)=>bS(cd.ATOMIC_AND,e,t),aJe=(e,t)=>bS(cd.ATOMIC_OR,e,t),uJe=(e,t)=>bS(cd.ATOMIC_XOR,e,t),xn=class e extends wa{static get type(){return"SubgroupFunctionNode"}constructor(t,i=null,n=null){super(),this.method=t,this.aNode=i,this.bNode=n}getInputType(t){let i=this.aNode?this.aNode.getNodeType(t):null,n=this.bNode?this.bNode.getNodeType(t):null,s=t.isMatrix(i)?0:t.getTypeLength(i),o=t.isMatrix(n)?0:t.getTypeLength(n);return s>o?i:n}generateNodeType(t){let i=this.method;return i===e.SUBGROUP_ELECT?"bool":i===e.SUBGROUP_BALLOT?"uvec4":this.getInputType(t)}generate(t,i){let n=this.method,s=this.getNodeType(t),o=this.getInputType(t),r=this.aNode,l=this.bNode,a=[];if(n===e.SUBGROUP_BROADCAST||n===e.SUBGROUP_SHUFFLE||n===e.QUAD_BROADCAST){let h=l.getNodeType(t);a.push(r.build(t,s),l.build(t,h==="float"?"int":s))}else n===e.SUBGROUP_SHUFFLE_XOR||n===e.SUBGROUP_SHUFFLE_DOWN||n===e.SUBGROUP_SHUFFLE_UP?a.push(r.build(t,s),l.build(t,"uint")):(r!==null&&a.push(r.build(t,o)),l!==null&&a.push(l.build(t,o)));let u=a.length===0?"()":`( ${a.join(", ")} )`;return t.format(`${t.getMethod(n,s)}${u}`,s,i)}serialize(t){super.serialize(t),t.method=this.method}deserialize(t){super.deserialize(t),this.method=t.method}};xn.SUBGROUP_ELECT="subgroupElect";xn.SUBGROUP_BALLOT="subgroupBallot";xn.SUBGROUP_ADD="subgroupAdd";xn.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd";xn.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd";xn.SUBGROUP_MUL="subgroupMul";xn.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul";xn.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul";xn.SUBGROUP_AND="subgroupAnd";xn.SUBGROUP_OR="subgroupOr";xn.SUBGROUP_XOR="subgroupXor";xn.SUBGROUP_MIN="subgroupMin";xn.SUBGROUP_MAX="subgroupMax";xn.SUBGROUP_ALL="subgroupAll";xn.SUBGROUP_ANY="subgroupAny";xn.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst";xn.QUAD_SWAP_X="quadSwapX";xn.QUAD_SWAP_Y="quadSwapY";xn.QUAD_SWAP_DIAGONAL="quadSwapDiagonal";
`),this.flow.code+=t,this)}addFlowCode(t){return this.flow.code+=t,this}addFlowTab(){return this.tab+=" ",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(t){return this.flowsData.get(t)}flowNode(t){let i=t.getNodeType(this),n=this.flowChildNode(t,i);return this.flowsData.set(t,n),n}addInclude(t){this.currentFunctionNode!==null&&this.currentFunctionNode.includes.push(t)}buildFunctionNode(t){let i=new ZX,n=this.currentFunctionNode;return this.currentFunctionNode=i,i.code=this.buildFunctionCode(t),this.currentFunctionNode=n,i}flowShaderNode(t){let i=t.layout,n={[Symbol.iterator](){let r=0,l=Object.values(this);return{next:()=>({value:l[r],done:r++>=l.length})}}};for(let r of i.inputs)n[r.name]=new zX(r.type,r.name);t.layout=null;let s=t.call(n),o=this.flowStagesNode(s,i.type);return t.layout=i,o}flowBuildStage(t,i,n=null){let s=this.getBuildStage();this.setBuildStage(i);let o=t.build(this,n);return this.setBuildStage(s),o}flowStagesNode(t,i=null){let n=this.flow,s=this.vars,o=this.declarations,r=this.cache,l=this.buildStage,a=this.stack,u={code:""};this.flow=u,this.vars={},this.declarations={},this.cache=new tY,this.stack=fX();for(let h of aX)this.setBuildStage(h),u.result=t.build(this,i);return u.vars=this.getVars(this.shaderStage),this.flow=n,this.vars=s,this.declarations=o,this.cache=r,this.stack=a,this.setBuildStage(l),u}getFunctionOperator(){return null}buildFunctionCode(){yi("Abstract function.")}flowChildNode(t,i=null){let n=this.flow,s={code:""};return this.flow=s,s.result=t.build(this,i),this.flow=n,s}flowNodeFromShaderStage(t,i,n=null,s=null){let o=this.tab,r=this.cache,l=this.shaderStage,a=this.context;this.setShaderStage(t);let u={...this.context};delete u.nodeBlock,this.cache=this.globalCache,this.tab=" ",this.context=u;let h=null;if(this.buildStage==="generate"){let p=this.flowChildNode(i,n);s!==null&&(p.code+=`${this.tab+s} = ${p.result};
`),this.flowCode[t]=this.flowCode[t]+p.code,h=p}else h=i.build(this);return this.setShaderStage(l),this.cache=r,this.tab=o,this.context=a,h}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){yi("Abstract function.")}getVaryings(){yi("Abstract function.")}getVar(t,i,n=null){return`${n!==null?this.generateArrayDeclaration(t,n):this.getType(t)} ${i}`}getVars(t,i=!1){let n=[],s=this.vars[t];if(s!==void 0)for(let o of s)n.push(`${this.getVar(o.type,o.name,o.count)};`);return n.join(i?`
`:`
`)}getUniforms(){yi("Abstract function.")}getCodes(t){let i=this.codes[t],n="";if(i!==void 0)for(let s of i)n+=s.code+`
`;return n}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(t){this.shaderStage=t}getShaderStage(){return this.shaderStage}setBuildStage(t){this.buildStage=t}getBuildStage(){return this.buildStage}buildCode(){yi("Abstract function.")}get subBuild(){return this.subBuildLayers[this.subBuildLayers.length-1]||null}addSubBuild(t){this.subBuildLayers.push(t)}removeSubBuild(){return this.subBuildLayers.pop()}getClosestSubBuild(t){let i;if(t&&t.isNode?t.isShaderCallNodeInternal?i=t.shaderNode.subBuilds:t.isStackNode?i=[t.subBuild]:i=this.getDataFromNode(t,"any").subBuilds:t instanceof Set?i=[...t]:i=t,!i)return null;let n=this.subBuildLayers;for(let s=i.length-1;s>=0;s--){let o=i[s];if(n.includes(o))return o}return null}getSubBuildOutput(t){return this.getSubBuildProperty("outputNode",t)}getSubBuildProperty(t="",i=null){let n;i!==null?n=this.getClosestSubBuild(i):n=this.subBuildFn;let s;return n?s=t?n+"_"+t:n:s=t,s}prebuild(){let{object:t,renderer:i,material:n}=this;if(i.contextNode.isContextNode===!0?this.context={...this.context,...i.contextNode.getFlowContextData()}:_i('NodeBuilder: "renderer.contextNode" must be an instance of `context()`.'),n&&n.contextNode&&(n.contextNode.isContextNode===!0?this.context={...this.context,...n.contextNode.getFlowContextData()}:_i('NodeBuilder: "material.contextNode" must be an instance of `context()`.')),n!==null){let s=i.library.fromMaterial(n);s===null&&(_i(`NodeBuilder: Material "${n.type}" is not compatible.`),s=new va),s.build(this)}else this.addFlow("compute",t)}build(){this.prebuild();for(let t of aX){this.setBuildStage(t),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(let i of uX){this.setShaderStage(i);let n=this.flowNodes[i];for(let s of n)t==="generate"?this.flowNode(s):s.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}async buildAsync(){this.prebuild();for(let t of aX){this.setBuildStage(t),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(let i of uX){this.setShaderStage(i);let n=this.flowNodes[i];for(let s of n)t==="generate"?this.flowNode(s):s.build(this);await _le()}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(t){let i=zet.get(t);return i===void 0&&(i={}),i}getNodeUniform(t,i){let n=this.getSharedDataFromNode(t),s=n.cache;if(s===void 0){if(i==="float"||i==="int"||i==="uint")s=new Efe(t);else if(i==="vec2"||i==="ivec2"||i==="uvec2")s=new Tfe(t);else if(i==="vec3"||i==="ivec3"||i==="uvec3")s=new wfe(t);else if(i==="vec4"||i==="ivec4"||i==="uvec4")s=new vfe(t);else if(i==="color")s=new Sfe(t);else if(i==="mat2")s=new Rfe(t);else if(i==="mat3")s=new _fe(t);else if(i==="mat4")s=new bfe(t);else throw new Error(`Uniform "${i}" not implemented.`);n.cache=s}return s}format(t,i,n){if(i=this.getVectorType(i),n=this.getVectorType(n),i===n||n===null||this.isReference(n))return t;let s=this.getTypeLength(i),o=this.getTypeLength(n);return s===16&&o===9?`${this.getType(n)}( ${t}[ 0 ].xyz, ${t}[ 1 ].xyz, ${t}[ 2 ].xyz )`:s===9&&o===4?`${this.getType(n)}( ${t}[ 0 ].xy, ${t}[ 1 ].xy )`:s>4||o>4||o===0?t:s===o?`${this.getType(n)}( ${t} )`:s>o?(t=n==="bool"?`all( ${t} )`:`${t}.${"xyz".slice(0,o)}`,this.format(t,this.getTypeFromLength(o,this.getComponentType(i)),n)):o===4&&s>1?`${this.getType(n)}( ${this.format(t,i,"vec3")}, 1.0 )`:s===2?`${this.getType(n)}( ${this.format(t,i,"vec2")}, 0.0 )`:(s===1&&o>1&&i!==this.getComponentType(n)&&(t=`${this.getType(this.getComponentType(n))}( ${t} )`),`${this.getType(n)}( ${t} )`)}getSignature(){return`// Three.js r${"184"} - Node System
`}needsPreviousData(){let t=this.renderer.getMRT();return t&&t.has("velocity")||h4e(this.object).useVelocity===!0}},nee=class{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(t,i){let n=t.get(i);return n===void 0&&(n={renderId:0,frameId:0},t.set(i,n)),n}updateBeforeNode(t){let i=t.getUpdateBeforeType(),n=t.updateReference(this);if(i===ps.FRAME){let s=this._getMaps(this.updateBeforeMap,n);if(s.frameId!==this.frameId){let o=s.frameId;s.frameId=this.frameId,t.updateBefore(this)===!1&&(s.frameId=o)}}else if(i===ps.RENDER){let s=this._getMaps(this.updateBeforeMap,n);if(s.renderId!==this.renderId){let o=s.renderId;s.renderId=this.renderId,t.updateBefore(this)===!1&&(s.renderId=o)}}else i===ps.OBJECT&&t.updateBefore(this)}updateAfterNode(t){let i=t.getUpdateAfterType(),n=t.updateReference(this);if(i===ps.FRAME){let s=this._getMaps(this.updateAfterMap,n);s.frameId!==this.frameId&&t.updateAfter(this)!==!1&&(s.frameId=this.frameId)}else if(i===ps.RENDER){let s=this._getMaps(this.updateAfterMap,n);s.renderId!==this.renderId&&t.updateAfter(this)!==!1&&(s.renderId=this.renderId)}else i===ps.OBJECT&&t.updateAfter(this)}updateNode(t){let i=t.getUpdateType(),n=t.updateReference(this);if(i===ps.FRAME){let s=this._getMaps(this.updateMap,n);s.frameId!==this.frameId&&t.update(this)!==!1&&(s.frameId=this.frameId)}else if(i===ps.RENDER){let s=this._getMaps(this.updateMap,n);s.renderId!==this.renderId&&t.update(this)!==!1&&(s.renderId=this.renderId)}else i===ps.OBJECT&&t.update(this)}update(){this.frameId++,this.lastTime===void 0&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}},IY=class{constructor(t,i,n=null,s="",o=!1){this.type=t,this.name=i,this.count=n,this.qualifier=s,this.isConst=o}};IY.isNodeFunctionInput=!0;var Afe=class extends kb{static get type(){return"AmbientLightNode"}constructor(t=null){super(t)}setup({context:t}){t.irradiance.addAssign(this.colorNode)}},xfe=class extends kb{static get type(){return"DirectionalLightNode"}constructor(t=null){super(t)}setupDirect(){let t=this.colorNode;return{lightDirection:Mme(this.light),lightColor:t}}},Cfe=class extends kb{static get type(){return"HemisphereLightNode"}constructor(t=null){super(t),this.lightPositionNode=Lme(t),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=kn(new Ei).setGroup(Zn)}update(t){let{light:i}=this;super.update(t),this.lightPositionNode.object3d=i,this.groundColorNode.value.copy(i.groundColor).multiplyScalar(i.intensity)}setup(t){let{colorNode:i,groundColorNode:n,lightDirectionNode:s}=this,r=bD.dot(s).mul(.5).add(.5),l=Co(n,i,r);t.context.irradiance.addAssign(l)}},yY=class extends kb{static get type(){return"SpotLightNode"}constructor(t=null){super(t),this.coneCosNode=kn(0).setGroup(Zn),this.penumbraCosNode=kn(0).setGroup(Zn),this.cutoffDistanceNode=kn(0).setGroup(Zn),this.decayExponentNode=kn(0).setGroup(Zn),this.colorNode=kn(this.color).setGroup(Zn)}update(t){super.update(t);let{light:i}=this;this.coneCosNode.value=Math.cos(i.angle),this.penumbraCosNode.value=Math.cos(i.angle*(1-i.penumbra)),this.cutoffDistanceNode.value=i.distance,this.decayExponentNode.value=i.decay}getSpotAttenuation(t,i){let{coneCosNode:n,penumbraCosNode:s}=this;return r3(n,s,i)}getLightCoord(t){let i=t.getNodeProperties(this),n=i.projectionUV;return n===void 0&&(n=W_e(this.light,t.context.positionWorld),i.projectionUV=n),n}setupDirect(t){let{colorNode:i,cutoffDistanceNode:n,decayExponentNode:s,light:o}=this,r=this.getLightVector(t),l=r.normalize(),a=l.dot(Mme(o)),u=this.getSpotAttenuation(t,a),h=r.length(),p=Fme({lightDistance:h,cutoffDistance:n,decayExponent:s}),m=i.mul(u).mul(p),I,g;return o.colorNode?(g=this.getLightCoord(t),I=o.colorNode(g)):o.map&&(g=this.getLightCoord(t),I=$o(o.map,g.xy).onRenderUpdate(()=>o.map)),I&&(m=g.mul(2).sub(1).abs().lessThan
Message: ${t.message}`;t.reason&&(i+=`
Reason: ${t.reason}`),_i(i),this._isDeviceLost=!0}_renderBundle(t,i,n){let{bundleGroup:s,camera:o,renderList:r}=t,l=this._currentRenderContext,a=this._bundles.get(s,o,l),u=this.backend.get(a),h=s.version!==u.version;if(h||u.bundleGPU===void 0){this.backend.beginBundle(l),(u.renderObjects===void 0||h)&&(u.renderObjects=[]),this._currentRenderBundle=a;let{transparentDoublePass:m,transparent:I,opaque:g}=r;this.opaque===!0&&g.length>0&&this._renderObjects(g,o,i,n),this.transparent===!0&&I.length>0&&this._renderTransparents(I,m,o,i,n),this._currentRenderBundle=null,this.backend.finishBundle(l,a),u.version=s.version}else{let{renderObjects:m}=u;for(let I=0,g=m.length;I<g;I++){let E=m[I];this._nodes.needsRefresh(E)&&(this._nodes.updateBefore(E),this._nodes.updateForRender(E),this._bindings.updateForRender(E),this._nodes.updateAfter(E))}}this.backend.addBundle(l,a)}render(t,i){if(this._initialized===!1)throw new Error('Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.');this._renderScene(t,i)}get initialized(){return this._initialized}_getFrameBufferTarget(){let{currentToneMapping:t,currentColorSpace:i}=this,n=t!==_d,s=i!==Kn.workingColorSpace;if(n===!1&&s===!1)return null;let{width:o,height:r}=this.getDrawingBufferSize(fF),{depth:l,stencil:a}=this,u=this._outputRenderTarget||this._canvasTarget,h=this._frameBufferTargets.get(u);if(h===void 0){h=new Ep(o,r,{depthBuffer:l,stencilBuffer:a,type:this._outputBufferType,format:_o,colorSpace:Kn.workingColorSpace,generateMipmaps:!1,minFilter:Ds,magFilter:Ds,samples:this.samples}),h.isPostProcessingRenderTarget=!0;let w=()=>{u.removeEventListener("dispose",w),h.dispose(),this._frameBufferTargets.delete(u)};u.addEventListener("dispose",w),this._frameBufferTargets.set(u,h)}let p=this.getOutputRenderTarget();h.depthBuffer=l,h.stencilBuffer=a,p!==null?h.setSize(p.width,p.height,p.depth):h.setSize(o,r,1);let m=this._outputRenderTarget?this._outputRenderTarget.viewport:u._viewport,I=this._outputRenderTarget?this._outputRenderTarget.scissor:u._scissor,g=this._outputRenderTarget?1:u._pixelRatio,E=this._outputRenderTarget?this._outputRenderTarget.scissorTest:u._scissorTest;return h.viewport.copy(m),h.scissor.copy(I),h.viewport.multiplyScalar(g),h.scissor.multiplyScalar(g),h.scissorTest=E,h.multiview=p!==null?p.multiview:!1,h.resolveDepthBuffer=p!==null?p.resolveDepthBuffer:!0,h._autoAllocateDepthBuffer=p!==null?p._autoAllocateDepthBuffer:!1,h}_renderScene(t,i,n=!0){if(this._isDeviceLost===!0)return;let s=n?this._getFrameBufferTarget():null,o=this._nodes.nodeFrame,r=o.renderId,l=this._currentRenderContext,a=this._currentRenderObjectFunction,u=this._handleObjectFunction;this._callDepth++;let h=t.isScene===!0?t:WSe,p=this._renderTarget||this._outputRenderTarget,m=this._activeCubeFace,I=this._activeMipmapLevel,g;if(s!==null?(g=s,this.setRenderTarget(g)):g=p,g!==null&&g.depthBuffer===!0){let Q=this._textures.get(g);Q.depthInitialized!==!0&&((this.autoClear===!1||this.autoClear===!0&&this.autoClearDepth===!1)&&this.clearDepth(),Q.depthInitialized=!0)}let E=this._renderContexts.get(g,this._mrt,this._callDepth);this._currentRenderContext=E,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,o.renderId=this.info.calls,this.backend.updateTimeStampUID(E),this.inspector.beginRender(this.backend.getTimestampUID(E),t,i,g);let w=this.xr;if(w.isPresenting===!1){let Q=!1;if(this.reversedDepthBuffer===!0&&i.reversedDepth!==!0){if(i._reversedDepth=!0,i.isArrayCamera)for(let Ve of i.cameras)Ve._reversedDepth=!0;Q=!0}let Te=this.coordinateSystem;if(i.coordinateSystem!==Te){if(i.coordinateSystem=Te,i.isArrayCamera)for(let Ve of i.cameras)Ve.coordinateSystem=Te;Q=!0}if(Q===!0&&(i.updateProjectionMatrix(),i.isArrayCamera))for(let Ve of i.cameras)Ve.updateProjectionMatrix()}t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),i.parent===null&&i.matrixWorldAutoUpdate===!0&&i.updateMatrixWorld(),w.enabled===!0&&w.isP
precision highp float;
precision highp int;
precision highp sampler2D;
precision highp sampler3D;
precision highp samplerCube;
precision highp sampler2DArray;
precision highp usampler2D;
precision highp usampler3D;
precision highp usamplerCube;
precision highp usampler2DArray;
precision highp isampler2D;
precision highp isampler3D;
precision highp isamplerCube;
precision highp isampler2DArray;
precision highp sampler2DShadow;
precision highp sampler2DArrayShadow;
precision highp samplerCubeShadow;
`,jfe=class extends iee{constructor(t,i){super(t,i,new Mfe),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(t){return t.isVideoTexture===!0&&t.colorSpace!==Tf}_include(t){let i=jSe[t];return i.build(this),this.addInclude(i),i}getMethod(t){return jSe[t]!==void 0&&this._include(t),ctt[t]||t}getBitcastMethod(t,i){return this.getMethod(`bitcast_${i}_${t}`)}getFloatPackingMethod(t){return this.getMethod(`floatpack_${t}_2x16`)}getFloatUnpackingMethod(t){return this.getMethod(`floatunpack_${t}_2x16`)}getTernary(t,i,n){return`${t} ? ${i} : ${n}`}getOutputStructName(){return""}buildFunctionCode(t){let i=t.layout,n=this.flowShaderNode(t),s=[];for(let r of i.inputs)s.push(this.getType(r.type)+" "+r.name);return`${this.getType(i.type)} ${i.name}( ${s.join(", ")} ) {
${n.vars}
${n.code}
return ${n.result};
}`}setupPBO(t){let i=t.value;if(i.pbo===void 0){let n=i.array,s=i.count*i.itemSize,{itemSize:o}=i,r=i.array.constructor.name.toLowerCase().includes("int"),l=r?ow:Gv;o===2?l=r?Vv:bd:o===3?l=r?Ez:YR:o===4&&(l=r?qR:_o);let a={Float32Array:lr,Uint8Array:Vo,Uint16Array:Ef,Uint32Array:Ko,Int8Array:nw,Int16Array:sw,Int32Array:Au,Uint8ClampedArray:Vo},u=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(s/o)))),h=Math.ceil(s/o/u);u*h*o<s&&h++;let p=u*h*o,m=new n.constructor(p);m.set(n,0),i.array=m;let I=new Ic(i.array,u,h,l,a[i.array.constructor.name]||lr);I.needsUpdate=!0,I.isPBOTexture=!0;let g=new FE(I,null,null);g.setPrecision("high"),i.pboNode=g,i.pbo=g.value,this.getUniformFromNode(i.pboNode,"texture",this.shaderStage,this.context.nodeName)}}getPropertyName(t,i=this.shaderStage){return t.isNodeUniform&&t.node.isTextureNode!==!0&&t.node.isBufferNode!==!0?t.name:super.getPropertyName(t,i)}generatePBO(t){let{node:i,indexNode:n}=t,s=i.value;if(this.renderer.backend.has(s)){let h=this.renderer.backend.get(s);h.pbo=s.pbo}let o=this.getUniformFromNode(s.pboNode,"texture",this.shaderStage,this.context.nodeName),r=this.getPropertyName(o);this.increaseUsage(n);let l=n.build(this,"uint"),a=this.getDataFromNode(t),u=a.propertyName;if(u===void 0){let h=this.getVarFromNode(t);u=this.getPropertyName(h);let p=this.getDataFromNode(i),m=p.propertySizeName;m===void 0&&(m=u+"Size",this.getVarFromNode(i,m,"uint"),this.addLineFlowCode(`${m} = uint( textureSize( ${r}, 0 ).x )`,t),p.propertySizeName=m);let{itemSize:I}=s,g="."+rP.join("").slice(0,I),E=`ivec2(${l} % ${m}, ${l} / ${m})`,w=this.generateTextureLoad(null,r,E,"0",null,null),T="vec4";s.pbo.type===Ko?T="uvec4":s.pbo.type===Au&&(T="ivec4"),this.addLineFlowCode(`${u} = ${T}(${w})${g}`,t),a.propertyName=u}return u}generateTextureLoad(t,i,n,s,o,r){s===null&&(s="0");let l;return o?r?l=`texelFetchOffset( ${i}, ivec3( ${n}, ${o} ), int( ${s} ), ${r} )`:l=`texelFetch( ${i}, ivec3( ${n}, ${o} ), int( ${s} ) )`:r?l=`texelFetchOffset( ${i}, ${n}, int( ${s} ), ${r} )`:l=`texelFetch( ${i}, ${n}, int( ${s} ) )`,t!==null&&t.isDepthTexture&&(l+=".x"),l}generateTexture(t,i,n,s,o){return s&&(n=`vec3( ${n}, ${s} )`),t.isDepthTexture?o?`textureOffset( ${i}, ${n}, ${o} ).x`:`texture( ${i}, ${n} ).x`:o?`textureOffset( ${i}, ${n}, ${o} )`:`texture( ${i}, ${n} )`}generateTextureLevel(t,i,n,s,o,r){return o&&(n=`vec3( ${n}, ${o} )`),r?`textureLodOffset( ${i}, ${n}, ${s}, ${r} )`:`textureLod( ${i}, ${n}, ${s} )`}generateTextureBias(t,i,n,s,o,r){return o&&(n=`vec3( ${n}, ${o} )`),r?`textureOffset( ${i}, ${n}, ${r}, ${s} )`:`texture( ${i}, ${n}, ${s} )`}generateTextureGrad(t,i,n,s,o,r){return o&&(n=`vec3( ${n}, ${o} )`),r?`textureGradOffset( ${i}, ${n}, ${s[0]}, ${s[1]}, ${r} )`:`textureGrad( ${i}, ${n}, ${s[0]}, ${s[1]} )`}generateTextureCompare(t,i,n,s,o,r,l=this.shaderStage){if(l==="fragment")return t.isCubeTexture?`texture( ${i}, vec4( ${n}, ${s} ) )`:o?r?`textureOffset( ${i}, vec4( ${n}, ${o}, ${s} ), ${r} )`:`texture( ${i}, vec4( ${n}, ${o}, ${s} ) )`:r?`textureOffset( ${i}, vec3( ${n}, ${s} ), ${r} )`:`texture( ${i}, vec3( ${n}, ${s} ) )`;_i(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${l} shader.`)}getUniforms(t){let i=this.uniforms[t],n=[],s={};for(let r of i){let l=null,a=!1;if(r.type==="texture"||r.type==="texture3D"){let u=r.node.value,h="";(u.isDataTexture===!0||u.isData3DTexture===!0)&&(u.type===Ko?h="u":u.type===Au&&(h="i")),r.type==="texture3D"&&u.isArrayTexture===!1?l=`${h}sampler3D ${r.name};`:u.compareFunction?u.isArrayTexture===!0?l=`sampler2DArrayShadow ${r.name};`:l=`sampler2DShadow ${r.name};`:u.isArrayTexture===!0||u.isDataArrayTexture===!0||u.isCompressedArrayTexture===!0?l=`${h}sampler2DArray ${r.name};`:l=`${h}sampler2D ${r.name};`}else if(r.type==="cubeTexture")l=`samplerCube ${r.name};`;else if(r.type==="cubeDepthTexture")r.node.value.compareFunction?l=`samplerCubeShadow ${r.name};`:l=`samplerCube ${r.name};`;else if(r.type==="buffer"){let u=r.node,h=this.getType(u.bufferType),p=u.bufferCount,m=p>0?p:"";l=`${u.name} {
${h} ${r.name}[${m}];
};
`}else{let u=r.groupNode.name;if(s[u]===void 0){let h=this.uniformGroups[u];if(h!==void 0){let p=[];for(let m of h.uniforms){let I=m.getType(),g=this.getVectorType(I),E=m.nodeUniform.node.precision,w=`${g} ${m.name};`;E!==null&&(w=YSe[E]+" "+w),p.push(" "+w)}s[u]=p}}a=!0}if(!a){let u=r.node.precision;u!==null&&(l=YSe[u]+" "+l),l="uniform "+l,n.push(l)}}let o="";for(let r in s){let l=s[r];o+=this._getGLSLUniformStruct(r,l.join(`
`))+`
`}return o+=n.join(`
`),o}getTypeFromAttribute(t){let i=super.getTypeFromAttribute(t);if(/^[iu]/.test(i)&&t.gpuType!==Au){let n=t;t.isInterleavedBufferAttribute&&(n=t.data);let s=n.array;s instanceof Uint32Array||s instanceof Int32Array||(i=i.slice(1))}return i}getAttributes(t){let i="";if(t==="vertex"||t==="compute"){let n=this.getAttributesArray(),s=0;for(let o of n)i+=`layout( location = ${s++} ) in ${o.type} ${o.name};
`}return i}getStructMembers(t){let i=[];for(let n of t.members)i.push(` ${n.type} ${n.name};`);return i.join(`
`)}getStructs(t){let i=[],n=this.structs[t],s=[];for(let o of n)if(o.output)for(let r of o.members)s.push(`layout( location = ${r.index} ) out ${r.type} ${r.name};`);else{let r="struct "+o.name+` {
`;r+=this.getStructMembers(o),r+=`
};
`,i.push(r)}return s.length===0&&s.push("layout( location = 0 ) out vec4 fragColor;"),`
`+s.join(`
`)+`
`+i.join(`
`)}getVaryings(t){let i="",n=this.varyings;if(t==="vertex"||t==="compute")for(let s of n){t==="compute"&&(s.needsInterpolation=!0);let o=this.getType(s.type);if(s.needsInterpolation)if(s.interpolationType){let r=$Se[s.interpolationType]||s.interpolationType,l=ZSe[s.interpolationSampling]||"";i+=`${r} ${l} out ${o} ${s.name};
`}else{let r=o.includes("int")||o.includes("uv")||o.includes("iv")?"flat ":"";i+=`${r}out ${o} ${s.name};
`}else i+=`${o} ${s.name};
`}else if(t==="fragment"){for(let s of n)if(s.needsInterpolation){let o=this.getType(s.type);if(s.interpolationType){let r=$Se[s.interpolationType]||s.interpolationType,l=ZSe[s.interpolationSampling]||"";i+=`${r} ${l} in ${o} ${s.name};
`}else{let r=o.includes("int")||o.includes("uv")||o.includes("iv")?"flat ":"";i+=`${r}in ${o} ${s.name};
`}}}for(let s of this.builtins[t])i+=`${s};
`;return i}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((n,s)=>n*s,1)}u`}getSubgroupSize(){_i("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){_i("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){_i("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":"nodeUniformDrawId"}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(t,i,n=this.shaderStage){let s=this.extensions[n]||(this.extensions[n]=new Map);s.has(t)===!1&&s.set(t,{name:t,behavior:i})}getExtensions(t){let i=[];if(t==="vertex"){let s=this.renderer.backend.extensions;this.object.isBatchedMesh&&s.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",t)}let n=this.extensions[t];if(n!==void 0)for(let{name:s,behavior:o}of n.values())i.push(`#extension ${s} : ${o}`);return i.join(`
`)}getClipDistance(){return"gl_ClipDistance"}isAvailable(t){let i=qSe[t];if(i===void 0){let n;switch(i=!1,t){case"float32Filterable":n="OES_texture_float_linear";break;case"clipDistance":n="WEBGL_clip_cull_distance";break}if(n!==void 0){let s=this.renderer.backend.extensions;s.has(n)&&(s.get(n),i=!0)}qSe[t]=i}return i}isFlipY(){return!0}enableHardwareClipping(t){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${t} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(t,i){this.transforms.push({varyingName:t,attributeNode:i})}getTransforms(){let t=this.transforms,i="";for(let n=0;n<t.length;n++){let s=t[n],o=this.getPropertyName(s.attributeNode);o&&(i+=`${s.varyingName} = ${o};
`)}return i}_getGLSLUniformStruct(t,i){return`
layout( std140 ) uniform ${t} {
${i}
};`}_getGLSLVertexCode(t){return`#version 300 es
${this.getSignature()}
// extensions
${t.extensions}
// precision
${KSe}
// uniforms
${t.uniforms}
// varyings
${t.varyings}
// attributes
${t.attributes}
// vars
${t.vars}
// codes
${t.codes}
void main() {
// transforms
${t.transforms}
// flow
${t.flow}
gl_PointSize = 1.0;
}
`}_getGLSLFragmentCode(t){return`#version 300 es
${this.getSignature()}
// extensions
${t.extensions}
// precision
${KSe}
// structs
${t.structs}
// uniforms
${t.uniforms}
// varyings
${t.varyings}
// vars
${t.vars}
// codes
${t.codes}
void main() {
// flow
${t.flow}
}
`}buildCode(){let t=this.material!==null?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(let i in t){let n=`// code
`;n+=this.flowCode[i];let s=this.flowNodes[i],o=s[s.length-1];for(let l of s){let a=this.getFlowData(l),u=l.name;u&&(n.length>0&&(n+=`
`),n+=` // flow -> ${u}
`),n+=`${a.code}
`,l===o&&i!=="compute"&&(n+=`// result
`,i==="vertex"?(n+="gl_Position = ",n+=`${a.result};`):i==="fragment"&&(l.outputNode.isOutputStructNode||(n+="fragColor = ",n+=`${a.result};`)))}let r=t[i];if(r.extensions=this.getExtensions(i),r.uniforms=this.getUniforms(i),r.attributes=this.getAttributes(i),r.varyings=this.getVaryings(i),r.vars=this.getVars(i,!0),r.structs=this.getStructs(i),r.codes=this.getCodes(i),r.transforms=this.getTransforms(i),r.flow=n,i==="vertex"){let l=this.renderer.backend.extensions;this.object.isBatchedMesh&&l.has("WEBGL_multi_draw")===!1&&(r.uniforms+=`
uniform uint nodeUniformDrawId;
`)}}this.material!==null?(this.vertexShader=this._getGLSLVertexCode(t.vertex),this.fragmentShader=this._getGLSLFragmentCode(t.fragment)):this.computeShader=this._getGLSLVertexCode(t.compute)}getUniformFromNode(t,i,n,s=null){let o=super.getUniformFromNode(t,i,n,s),r=this.getDataFromNode(t,n,this.globalCache),l=r.uniformGPU;if(l===void 0){let a=t.groupNode,u=a.name,h=this.getBindGroupArray(u,n);if(i==="texture")l=new LF(o.name,o.node,a),h.push(l);else if(i==="cubeTexture"||i==="cubeDepthTexture")l=new fee(o.name,o.node,a),h.push(l);else if(i==="texture3D")l=new EY(o.name,o.node,a),h.push(l);else if(i==="buffer"){o.name=`buffer${t.id}`;let p=this.getSharedDataFromNode(t),m=p.buffer;m===void 0&&(t.name=`NodeBuffer_${t.id}`,m=new cee(t,a),m.name=t.name,p.buffer=m),h.push(m),l=m}else{let p=this.uniformGroups[u];p===void 0?(p=new dee(u,a),this.uniformGroups[u]=p,h.push(p)):h.indexOf(p)===-1&&h.push(p),l=this.getNodeUniform(o,i);let m=l.name;p.uniforms.some(g=>g.name===m)||p.addUniform(l)}r.uniformGPU=l}return o}},Fde=null,pF=null,pee=class{constructor(t={}){this.parameters=Object.assign({},t),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[Zy.RENDER]:null,[Zy.COMPUTE]:null},this.trackTimestamp=t.trackTimestamp===!0}async init(t){this.renderer=t}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(t){let i=this.get(t),n=this.renderer.info.frame,s;t.isComputeNode===!0?s="c:"+this.renderer.info.compute.frameCalls:s="r:"+this.renderer.info.render.frameCalls,i.timestampUID=s+":"+t.id+":f"+n}getTimestampUID(t){return this.get(t).timestampUID}getTimestampFrames(t){let i=this.timestampQueryPool[t];return i?i.getTimestampFrames():[]}_getQueryPool(t){let i=t.startsWith("c:")?Zy.COMPUTE:Zy.RENDER;return this.timestampQueryPool[i]}getTimestamp(t){return this._getQueryPool(t).getTimestamp(t)}hasTimestamp(t){return this._getQueryPool(t).hasTimestamp(t)}isOccluded(){}async resolveTimestampsAsync(t="render"){if(!this.trackTimestamp){yr("WebGPURenderer: Timestamp tracking is disabled.");return}let i=this.timestampQueryPool[t];if(!i)return;let n=await i.resolveQueriesAsync();return this.renderer.info[t].timestamp=n,n}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getDrawingBufferSize(){return Fde=Fde||new si,this.renderer.getDrawingBufferSize(Fde)}setScissorTest(){}getClearColor(){let t=this.renderer;return pF=pF||new cY,t.getClearColor(pF),pF.getRGB(pF),pF}getDomElement(){let t=this.domElement;return t===null&&(t=this.parameters.canvas!==void 0?this.parameters.canvas:_z(),"setAttribute"in t&&t.setAttribute("data-engine",`three.js r${"184"} webgpu`),this.domElement=t),t}hasCompatibility(){return!1}initRenderTarget(){}set(t,i){this.data.set(t,i)}get(t){let i=this.data.get(t);return i===void 0&&(i={},this.data.set(t,i)),i}has(t){return this.data.has(t)}delete(t){this.data.delete(t)}deleteBindGroupData(){}dispose(){}},dtt=0,Yfe=class{constructor(t,i){this.buffers=[t.bufferGPU,i],this.type=t.type,this.bufferType=t.bufferType,this.pbo=t.pbo,this.byteLength=t.byteLength,this.bytesPerElement=t.BYTES_PER_ELEMENT,this.version=t.version,this.isInteger=t.isInteger,this.activeBufferIndex=0,this.baseId=t.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[this.activeBufferIndex^1]}switchBuffers(){this.activeBufferIndex^=1}},qfe=class{constructor(t){this.backend=t}createAttribute(t
`),s=[],o=Math.max(i-6,0),r=Math.min(i+6,n.length);for(let l=o;l<r;l++){let a=l+1;s.push(`${a===i?">":" "} ${a}: ${n[l]}`)}return s.join(`
`)}_getShaderErrors(t,i,n){let s=t.getShaderParameter(i,t.COMPILE_STATUS),r=(t.getShaderInfoLog(i)||"").trim();if(s&&r==="")return"";let l=/ERROR: 0:(\d+)/.exec(r);if(l){let a=parseInt(l[1]);return n.toUpperCase()+`
`+r+`
`+this._handleSource(t.getShaderSource(i),a)}else return r}_logProgramError(t,i,n){if(this.renderer.debug.checkShaderErrors){let s=this.gl,r=(s.getProgramInfoLog(t)||"").trim();if(s.getProgramParameter(t,s.LINK_STATUS)===!1)if(typeof this.renderer.debug.onShaderError=="function")this.renderer.debug.onShaderError(s,t,n,i);else{let l=this._getShaderErrors(s,n,"vertex"),a=this._getShaderErrors(s,i,"fragment");_i("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(t,s.VALIDATE_STATUS)+`
Program Info Log: `+r+`
`+l+`
`+a)}else r!==""&&yi("WebGLProgram: Program Info Log:",r)}}_completeCompile(t,i){let{state:n,gl:s}=this,o=this.get(i),{programGPU:r,fragmentShader:l,vertexShader:a}=o;s.getProgramParameter(r,s.LINK_STATUS)===!1&&this._logProgramError(r,l,a),n.useProgram(r);let u=t.getBindings();this._setupBindings(u,r),this.set(i,{programGPU:r,pipeline:r})}createComputePipeline(t,i){let{state:n,gl:s}=this,o={stage:"fragment",code:`#version 300 es
precision highp float;
void main() {}`};this.createProgram(o);let{computeProgram:r}=t,l=s.createProgram(),a=this.get(o).shaderGPU,u=this.get(r).shaderGPU,h=r.transforms,p=[],m=[];for(let w=0;w<h.length;w++){let T=h[w];p.push(T.varyingName),m.push(T.attributeNode)}s.attachShader(l,a),s.attachShader(l,u),s.transformFeedbackVaryings(l,p,s.SEPARATE_ATTRIBS),s.linkProgram(l),s.getProgramParameter(l,s.LINK_STATUS)===!1&&this._logProgramError(l,a,u),n.useProgram(l),this._setupBindings(i,l);let I=r.attributes,g=[],E=[];for(let w=0;w<I.length;w++){let T=I[w].node.attribute;g.push(T),this.has(T)||this.attributeUtils.createAttribute(T,s.ARRAY_BUFFER)}for(let w=0;w<m.length;w++){let T=m[w].attribute;this.has(T)||this.attributeUtils.createAttribute(T,s.ARRAY_BUFFER);let S=this.get(T);E.push(S)}this.set(t,{programGPU:l,transformBuffers:E,attributes:g})}createBindings(t,i){if(this._knownBindings.has(i)===!1){this._knownBindings.add(i);let n=0,s=0;for(let o of i){this.set(o,{textures:s,uniformBuffers:n});for(let r of o.bindings)r.isUniformBuffer&&n++,r.isSampledTexture&&s++}}this.updateBindings(t,i)}updateBindings(t){let{gl:i}=this;for(let n of t.bindings){let s=this.get(n);if(n.isUniformsGroup||n.isUniformBuffer){let o=n.buffer,{bufferGPU:r}=this.get(o);r===void 0?(r=i.createBuffer(),i.bindBuffer(i.UNIFORM_BUFFER,r),i.bufferData(i.UNIFORM_BUFFER,o.byteLength,i.DYNAMIC_DRAW),this.set(o,{bufferGPU:r})):i.bindBuffer(i.UNIFORM_BUFFER,r);let l=n.updateRanges;if(i.bindBuffer(i.UNIFORM_BUFFER,r),l.length===0)i.bufferData(i.UNIFORM_BUFFER,o,i.DYNAMIC_DRAW);else{let a=aO(o),u=a?1:o.BYTES_PER_ELEMENT;for(let h=0,p=l.length;h<p;h++){let m=l[h],I=m.start*u,g=m.count*u,E=I*(a?o.BYTES_PER_ELEMENT:1);i.bufferSubData(i.UNIFORM_BUFFER,E,o,I,g)}}s.bufferGPU=r,this.set(n,s)}else if(n.isSampledTexture){let{textureGPU:o,glTextureType:r}=this.get(n.texture);s.textureGPU=o,s.glTextureType=r,this.set(n,s)}}}updateBinding(t){let i=this.gl;if(t.isUniformsGroup||t.isUniformBuffer){let s=this.get(t).bufferGPU,o=t.buffer,r=t.updateRanges;if(i.bindBuffer(i.UNIFORM_BUFFER,s),r.length===0)i.bufferData(i.UNIFORM_BUFFER,o,i.DYNAMIC_DRAW);else{let l=aO(o),a=l?1:o.BYTES_PER_ELEMENT;for(let u=0,h=r.length;u<h;u++){let p=r[u],m=p.start*a,I=p.count*a,g=m*(l?o.BYTES_PER_ELEMENT:1);i.bufferSubData(i.UNIFORM_BUFFER,g,o,m,I)}}}}createIndexAttribute(t){let i=this.gl;this.attributeUtils.createAttribute(t,i.ELEMENT_ARRAY_BUFFER)}createAttribute(t){if(this.has(t))return;let i=this.gl;this.attributeUtils.createAttribute(t,i.ARRAY_BUFFER)}createStorageAttribute(t){if(this.has(t))return;let i=this.gl;this.attributeUtils.createAttribute(t,i.ARRAY_BUFFER)}updateAttribute(t){this.attributeUtils.updateAttribute(t)}destroyAttribute(t){this.attributeUtils.destroyAttribute(t)}hasFeature(t){let i=Object.keys(XSe).filter(s=>XSe[s]===t),n=this.extensions;for(let s=0;s<i.length;s++)if(n.has(i[s]))return!0;return!1}copyTextureToTexture(t,i,n=null,s=null,o=0,r=0){this.textureUtils.copyTextureToTexture(t,i,n,s,o,r)}copyFramebufferToTexture(t,i,n){this.textureUtils.copyFramebufferToTexture(t,i,n)}hasCompatibility(t){return t===zv.TEXTURE_COMPARE?!0:super.hasCompatibility(t)}initRenderTarget(t){let{gl:i,state:n}=this;this._setFramebuffer(t),n.bindFramebuffer(i.FRAMEBUFFER,null)}_setFramebuffer(t){let{gl:i,state:n}=this,s=null;if(t.textures!==null){let o=t.renderTarget,r=this.get(o),{samples:l,depthBuffer:a,stencilBuffer:u}=o,h=o.isCubeRenderTarget===!0,p=o.isRenderTarget3D===!0,m=o.depth>1,I=o.isXRRenderTarget===!0,g=I===!0&&o._hasExternalTextures===!0,E=r.msaaFrameBuffer,w=r.depthRenderbuffer,T=this.extensions.get("WEBGL_multisampled_render_to_texture"),S=this.extensions.get("OVR_multiview2"),_=this._useMultisampledExtension(o),x=S_e(t),M;if(h?(r.cubeFramebuffers||(r.cubeFramebuffers={}),M=r.cubeFramebuffers[x]):I&&g===!1?M=this._xrFramebuffer:(r.framebuffers||(r.framebuffers={}),M=r.framebuffers[x]),M===void 0){M=i.createFramebuffer(),n.bindFramebuffer(i.FRAMEBUFFER,M);let W=t.textures,G=[];if(h){r.cubeFramebuffers[x]=M;let{textureGPU:Y}=this.get(W[0]),se=this.renderer._activeCubeFace,pe=this.renderer._activeMipmapLevel
struct VarysStruct {
@builtin( position ) Position: vec4f,
@location( 0 ) vTex : vec2f,
@location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,
};
@group( 0 ) @binding ( 2 )
var<uniform> flipY: u32;
@vertex
fn mainVS(
@builtin( vertex_index ) vertexIndex : u32,
@builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {
var Varys : VarysStruct;
var pos = array(
vec2f( -1, -1 ),
vec2f( -1, 3 ),
vec2f( 3, -1 ),
);
let p = pos[ vertexIndex ];
let mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );
Varys.vTex = p * mult + vec2f( 0.5 );
Varys.Position = vec4f( p, 0, 1 );
Varys.vBaseArrayLayer = instanceIndex;
return Varys;
}
@group( 0 ) @binding( 0 )
var imgSampler : sampler;
@group( 0 ) @binding( 1 )
var img2d : texture_2d<f32>;
@fragment
fn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
return textureSample( img2d, imgSampler, Varys.vTex );
}
@group( 0 ) @binding( 1 )
var img2dArray : texture_2d_array<f32>;
@fragment
fn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
return textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );
}
const faceMat = array(
mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x
mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x
mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y
mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y
mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z
mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z
);
@group( 0 ) @binding( 1 )
var imgCube : texture_cube<f32>;
@fragment
fn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
return textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );
}
`;this.mipmapSampler=t.createSampler({minFilter:hS.Linear}),this.flipYSampler=t.createSampler({minFilter:hS.Nearest}),this.flipUniformBuffer=t.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),t.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),this.noFlipUniformBuffer=t.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM}),this.transferPipelines={},this.mipmapShaderModule=t.createShaderModule({label:"mipmap",code:i})}getTransferPipeline(t,i){i=i||"2d-array";let n=`${t}-${i}`,s=this.transferPipelines[n];return s===void 0&&(s=this.device.createRenderPipeline({label:`mipmap-${t}-${i}`,vertex:{module:this.mipmapShaderModule},fragment:{module:this.mipmapShaderModule,entryPoint:`main_${i.replace("-","_")}`,targets:[{format:t}]},layout:"auto"}),this.transferPipelines[n]=s),s}flipY(t,i,n=0){let s=i.format,{width:o,height:r}=i.size,l=this.device.createTexture({size:{width:o,height:r},format:s,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),a=this.getTransferPipeline(s,t.textureBindingViewDimension),u=this.getTransferPipeline(s,l.textureBindingViewDimension),h=this.device.createCommandEncoder({}),p=(m,I,g,E,w,T)=>{let S=m.getBindGroupLayout(0),_=this.device.createBindGroup({layout:S,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:I.createView({dimension:I.textureBindingViewDimension||"2d-array",baseMipLevel:0,mipLevelCount:1})},{binding:2,resource:{buffer:T?this.flipUniformBuffer:this.noFlipUniformBuffer}}]}),x=h.beginRenderPass({colorAttachments:[{view:E.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:w,arrayLayerCount:1}),loadOp:Sr.Clear,storeOp:mI.Store}]});x.setPipeline(m),x.setBindGroup(0,_),x.draw(3,1,0,g),x.end()};p(a,t,n,l,0,!1),p(u,l,0,t,n,!0),this.device.queue.submit([h.finish()]),l.destroy()}generateMipmaps(t,i=null){let n=this.get(t),s=n.layers||this._mipmapCreateBundles(t),o=i||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(o,s),i===null&&this.device.queue.submit([o.finish()]),n.layers=s}_mipmapCreateBundles(t){let i=t.textureBindingViewDimension||"2d-array",n=this.getTransferPipeline(t.format,i),s=n.getBindGroupLayout(0),o=[];for(let r=1;r<t.mipLevelCount;r++)for(let l=0;l<t.depthOrArrayLayers;l++){let a=this.device.createBindGroup({layout:s,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:t.createView({dimension:i,baseMipLevel:r-1,mipLevelCount:1})},{binding:2,resource:{buffer:this.noFlipUniformBuffer}}]}),u={colorAttachments:[{view:t.createView({dimension:"2d",baseMipLevel:r,mipLevelCount:1,baseArrayLayer:l,arrayLayerCount:1}),loadOp:Sr.Clear,storeOp:mI.Store}]},h=this.device.createRenderBundleEncoder({colorFormats:[t.format]});h.setPipeline(n),h.setBindGroup(0,a),h.draw(3,1,0,l),o.push({renderBundles:[h.finish()],passDescriptor:u})}return o}_mipmapRunBundles(t,i){let n=i.length;for(let s=0;s<n;s++){let o=i[s],r=t.beginRenderPass(o.passDescriptor);r.executeBundles(o.renderBundles),r.end()}}},ptt={[O8]:"never",[lO]:"less",[L8]:"equal",[hw]:"less-equal",[dC]:"greater",[Bg]:"greater-equal",[M8]:"always",[P8]:"not-equal"},mtt=[0,1,3,2,4,5],ope=class{constructor(t){this.backend=t,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this._samplerCache=new Map}updateSampler(t){let i=this.backend,n=t.minFilter+"-"+t.magFilter+"-"+t.wrapS+"-"+t.wrapT+"-"+(t.wrapR||"0")+"-"+t.anisotropy+"-"+(t.compareFunction||0),s=this._samplerCache.get(n);if(s===void 0){let r={addressModeU:this._convertAddressMode(t.wrapS),addressModeV:this._convertAddressMode(t.wrapT),addressModeW:this._convertAddressMode(t.wrapR),magFilter:this._convertFilterMode(t.magFilter),minFilter:this._convertFilterMode(t.minFilter),mipmapFilter:this._convertFilterMode(t.minFilter),maxAnisotropy:1};t.isDepthTexture&&t.compareFunction===null&&(r.magFilter=hS.Nearest,r.minFilter=hS.Nearest,r.mipmapFilter=hS.Nearest),r.magFilter===hS.Linear&&r.minFilter===hS.Linear&&r.mipmapFilter===hS.Linear&&(r.maxAnisotropy=t.anisotropy),t.isDepthTexture&&t.compareFunction!
fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
let res = vec2f( iRes );
let uvScaled = coord * res;
let uvWrapping = ( ( uvScaled % res ) + res ) % res;
// https://www.shadertoy.com/view/WtyXRy
let uv = uvWrapping - 0.5;
let iuv = floor( uv );
let f = fract( uv );
let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
}
`),biquadraticTextureArray:new rd(`
fn tsl_biquadraticTexture_array( map : texture_2d_array<f32>, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {
let res = vec2f( iRes );
let uvScaled = coord * res;
let uvWrapping = ( ( uvScaled % res ) + res ) % res;
// https://www.shadertoy.com/view/WtyXRy
let uv = uvWrapping - 0.5;
let iuv = floor( uv );
let f = fract( uv );
let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );
let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );
let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );
let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );
return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
}
`)},vtt={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast<f32>",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float"},fbe="";(typeof navigator<"u"&&/Firefox|Deno/g.test(navigator.userAgent))!==!0&&(fbe+=`diagnostic( off, derivative_uniformity );
`);var upe=class extends iee{constructor(t,i){super(t,i,new ape),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_generateTextureSample(t,i,n,s,o,r=this.shaderStage){return r==="fragment"?s?o?`textureSample( ${i}, ${i}_sampler, ${n}, ${s}, ${o} )`:`textureSample( ${i}, ${i}_sampler, ${n}, ${s} )`:o?`textureSample( ${i}, ${i}_sampler, ${n}, ${o} )`:`textureSample( ${i}, ${i}_sampler, ${n} )`:this.generateTextureSampleLevel(t,i,n,"0",s)}generateTextureSampleLevel(t,i,n,s,o,r){return this.isUnfilterable(t)===!1?o?r?`textureSampleLevel( ${i}, ${i}_sampler, ${n}, ${o}, ${s}, ${r} )`:`textureSampleLevel( ${i}, ${i}_sampler, ${n}, ${o}, ${s} )`:r?`textureSampleLevel( ${i}, ${i}_sampler, ${n}, ${s}, ${r} )`:`textureSampleLevel( ${i}, ${i}_sampler, ${n}, ${s} )`:this.isFilteredTexture(t)?this.generateFilteredTexture(t,i,n,r,s,o):this.generateTextureLod(t,i,n,o,r,s)}generateWrapFunction(t){let i=`tsl_coord_${l4e[t.wrapS]}S_${l4e[t.wrapT]}_${t.is3DTexture||t.isData3DTexture?"3d":"2d"}T`,n=u4e[i];if(n===void 0){let s=[],o=t.is3DTexture||t.isData3DTexture?"vec3f":"vec2f",r=`fn ${i}( coord : ${o} ) -> ${o} {
return ${o}(
`,l=(a,u)=>{a===If?(s.push(Wj.repeatWrapping_float),r+=` tsl_repeatWrapping_float( coord.${u} )`):a===mc?(s.push(Wj.clampWrapping_float),r+=` tsl_clampWrapping_float( coord.${u} )`):a===qT?(s.push(Wj.mirrorWrapping_float),r+=` tsl_mirrorWrapping_float( coord.${u} )`):(r+=` coord.${u}`,yi(`WebGPURenderer: Unsupported texture wrap type "${a}" for vertex shader.`))};l(t.wrapS,"x"),r+=`,
`,l(t.wrapT,"y"),(t.is3DTexture||t.isData3DTexture)&&(r+=`,
`,l(t.wrapR,"z")),r+=`
);
}
`,u4e[i]=n=new rd(r,s)}return n.build(this),i}generateArrayDeclaration(t,i){return`array< ${this.getType(t)}, ${i} >`}generateTextureDimension(t,i,n){let s=this.getDataFromNode(t,this.shaderStage,this.cache);s.dimensionsSnippet===void 0&&(s.dimensionsSnippet={});let o=s.dimensionsSnippet[n];if(s.dimensionsSnippet[n]===void 0){let r,l,{primarySamples:a}=this.renderer.backend.utils.getTextureSampleData(t),u=a>1;t.is3DTexture||t.isData3DTexture?l="vec3<u32>":l="vec2<u32>",u||t.isStorageTexture?r=i:r=`${i}${n?`, u32( ${n} )`:""}`,o=new TF(new vF(`textureDimensions( ${r} )`,l)),s.dimensionsSnippet[n]=o,(t.isArrayTexture||t.isDataArrayTexture||t.is3DTexture||t.isData3DTexture)&&(s.arrayLayerCount=new TF(new vF(`textureNumLayers(${i})`,"u32"))),t.isTextureCube&&(s.cubeFaceCount=new TF(new vF("6u","u32")))}return o.build(this)}generateFilteredTexture(t,i,n,s,o="0u",r){let l=this.generateWrapFunction(t),a=this.generateTextureDimension(t,i,o);return s&&(n=`${n} + vec2<f32>(${s}) / ${a}`),r?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${i}, ${l}( ${n} ), ${a}, u32( ${r} ), u32( ${o} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${i}, ${l}( ${n} ), ${a}, u32( ${o} ) )`)}generateTextureLod(t,i,n,s,o,r="0u"){if(t.isCubeTexture===!0){o&&(n=`${n} + vec3<f32>(${o})`);let I=t.isDepthTexture?"u32":"f32";return`textureSampleLevel( ${i}, ${i}_sampler, ${n}, ${I}( ${r} ) )`}let l=this.generateWrapFunction(t),a=this.generateTextureDimension(t,i,r),u=t.is3DTexture||t.isData3DTexture?"vec3":"vec2",h=u==="vec3"?"vec3<u32>( 1, 1, 1 )":"vec2<u32>( 1, 1 )";o&&(n=`${n} + ${u}<f32>(${o}) / ${u}<f32>( ${a} )`);let p=`${u}<f32>( 0 )`,m=`${u}<f32>( ${a} - ${h} )`;return n=`${u}<u32>( clamp( floor( ${l}( ${n} ) * ${u}<f32>( ${a} ) ), ${p}, ${m} ) )`,this.generateTextureLoad(t,i,n,r,s,null)}generateStorageTextureLoad(t,i,n,s,o,r){r&&(n=`${n} + ${r}`);let l;return o?l=`textureLoad( ${i}, ${n}, ${o} )`:l=`textureLoad( ${i}, ${n} )`,l}generateTextureLoad(t,i,n,s,o,r){s===null&&(s="0u"),r&&(n=`${n} + ${r}`);let l;return o?l=`textureLoad( ${i}, ${n}, ${o}, u32( ${s} ) )`:(l=`textureLoad( ${i}, ${n}, u32( ${s} ) )`,this.renderer.backend.compatibilityMode&&t.isDepthTexture&&(l+=".x")),l}generateTextureStore(t,i,n,s,o){let r;return s?r=`textureStore( ${i}, ${n}, ${s}, ${o} )`:r=`textureStore( ${i}, ${n}, ${o} )`,r}isSampleCompare(t){return t.isDepthTexture===!0&&t.compareFunction!==null&&this.renderer.hasCompatibility(zv.TEXTURE_COMPARE)}isUnfilterable(t){return this.getComponentTypeFromTexture(t)!=="float"||!this.isAvailable("float32Filterable")&&t.type===lr||this.isSampleCompare(t)===!1&&t.minFilter===Us&&t.magFilter===Us||this.renderer.backend.utils.getTextureSampleData(t).primarySamples>1}generateTexture(t,i,n,s,o,r=this.shaderStage){let l=null;return this.isUnfilterable(t)?l=this.generateTextureLod(t,i,n,s,o,"0",r):l=this._generateTextureSample(t,i,n,s,o,r),l}generateTextureGrad(t,i,n,s,o,r,l=this.shaderStage){if(l==="fragment")return o?r?`textureSampleGrad( ${i}, ${i}_sampler, ${n}, ${o}, ${s[0]}, ${s[1]}, ${r} )`:`textureSampleGrad( ${i}, ${i}_sampler, ${n}, ${o}, ${s[0]}, ${s[1]} )`:r?`textureSampleGrad( ${i}, ${i}_sampler, ${n}, ${s[0]}, ${s[1]}, ${r} )`:`textureSampleGrad( ${i}, ${i}_sampler, ${n}, ${s[0]}, ${s[1]} )`;_i(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${l} shader.`)}generateTextureCompare(t,i,n,s,o,r,l=this.shaderStage){if(l==="fragment")return t.isDepthTexture===!0&&t.isArrayTexture===!0?r?`textureSampleCompare( ${i}, ${i}_sampler, ${n}, ${o}, ${s}, ${r} )`:`textureSampleCompare( ${i}, ${i}_sampler, ${n}, ${o}, ${s} )`:r?`textureSampleCompare( ${i}, ${i}_sampler, ${n}, ${s}, ${r} )`:`textureSampleCompare( ${i}, ${i}_sampler, ${n}, ${s} )`;_i(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${l} shader.`)}generateTextureLevel(t,i,n,s,o,r){return this.isUnfilterable(t)===!1?o?r?`textureSampleLevel( ${i}, ${i}_sampler, ${n}, ${o}, ${s}, ${r} )`:`textureSampleLevel( ${i}, ${i}_sampler, ${n}, ${o}, ${s} )`:r?`textureSampleLevel( ${i}, ${i}_sampler, ${n},
${n.vars}
${n.code}
`;return n.result&&(o+=` return ${n.result};
`),o+=`
}
`,o}getInstanceIndex(){return this.shaderStage==="vertex"?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4<f32>")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(t,i=this.shaderStage){(this.directives[i]||(this.directives[i]=new Set)).add(t)}getDirectives(t){let i=[],n=this.directives[t];if(n!==void 0)for(let s of n)i.push(`enable ${s};`);return i.join(`
`)}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(t){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array<f32, ${t} >`,"vertex")}getBuiltins(t){let i=[],n=this.builtins[t];if(n!==void 0)for(let{name:s,property:o,type:r}of n.values())i.push(`@builtin( ${s} ) ${o} : ${r}`);return i.join(`,
`)}getScopedArray(t,i,n,s){return this.scopedArrays.has(t)===!1&&this.scopedArrays.set(t,{name:t,scope:i,bufferType:n,bufferCount:s}),t}getScopedArrays(t){if(t!=="compute")return;let i=[];for(let{name:n,scope:s,bufferType:o,bufferCount:r}of this.scopedArrays.values()){let l=this.getType(o);i.push(`var<${s}> ${n}: array< ${l}, ${r} >;`)}return i.join(`
`)}getAttributes(t){let i=[];if(t==="compute"&&(this.getBuiltin("global_invocation_id","globalId","vec3<u32>","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3<u32>","attribute"),this.getBuiltin("local_invocation_id","localId","vec3<u32>","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3<u32>","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",t),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),t==="vertex"||t==="compute"){let n=this.getBuiltins("attribute");n&&i.push(n);let s=this.getAttributesArray();for(let o=0,r=s.length;o<r;o++){let l=s[o],a=l.name,u=this.getType(l.type);i.push(`@location( ${o} ) ${a} : ${u}`)}}return i.join(`,
`)}getStructMembers(t){let i=[];for(let n of t.members){let s=t.output?"@location( "+n.index+" ) ":"",o=this.getType(n.type);n.atomic&&(o="atomic< "+o+" >"),i.push(` ${s+n.name} : ${o}`)}return t.output&&i.push(` ${this.getBuiltins("output")}`),i.join(`,
`)}getStructs(t){let i="",n=this.structs[t];if(n.length>0){let s=[];for(let o of n){let r=`struct ${o.name} {
`;r+=this.getStructMembers(o),r+=`
};`,s.push(r)}i=`
`+s.join(`
`)+`
`}return i}getVar(t,i,n=null,s=""){let o=`var${s} ${i} : `;return n!==null?o+=this.generateArrayDeclaration(t,n):o+=this.getType(t),o}getVars(t,i=!1){let n="";i&&(n="<private>");let s=[],o=this.vars[t];if(o!==void 0)for(let r of o)s.push(`${this.getVar(r.type,r.name,r.count,n)};`);return i?s.join(`
`):`
${s.join(`
`)}
`}getVaryings(t){let i=[];if(t==="vertex"&&this.getBuiltin("position","builtinClipSpace","vec4<f32>","vertex"),t==="vertex"||t==="fragment"){let o=this.varyings,r=this.vars[t],l=0;for(let a=0;a<o.length;a++){let u=o[a];if(u.needsInterpolation){let h=`@location( ${l++} )`;if(u.interpolationType){let p=u.interpolationSampling!==null?`, ${u.interpolationSampling} )`:" )";h+=` @interpolate( ${u.interpolationType}${p}`}else/^(int|uint|ivec|uvec)/.test(u.type)&&(h+=" @interpolate(flat, either)");i.push(`${h} ${u.name} : ${this.getType(u.type)}`)}else t==="vertex"&&r.includes(u)===!1&&r.push(u)}}let n=this.getBuiltins(t);n&&i.push(n);let s=i.join(`,
`);return t==="vertex"?this._getWGSLStruct("VaryingsStruct"," "+s):s}isCustomStruct(t){let i=t.value,n=t.node,s=(i.isBufferAttribute||i.isInstancedBufferAttribute)&&n.structTypeNode!==null,o=n.value&&n.value.array&&typeof n.value.itemSize=="number"&&n.value.array.length>n.value.itemSize;return s&&!o}getUniforms(t){let i=this.renderer.backend,n=this.uniforms[t],s=[],o=[],r=[],l={};for(let u of n){let h=u.groupNode.name,p=this.bindingsIndexes[h];if(u.type==="texture"||u.type==="cubeTexture"||u.type==="cubeDepthTexture"||u.type==="storageTexture"||u.type==="texture3D"){let m=u.node.value;(m.isCubeTexture===!0||this.isUnfilterable(m)===!1&&u.node.isStorageTextureNode!==!0)&&(this.isSampleCompare(m)?s.push(`@binding( ${p.binding++} ) @group( ${p.group} ) var ${u.name}_sampler : sampler_comparison;`):s.push(`@binding( ${p.binding++} ) @group( ${p.group} ) var ${u.name}_sampler : sampler;`));let g,E="",{primarySamples:w}=i.utils.getTextureSampleData(m);if(w>1&&(E="_multisampled"),m.isCubeTexture===!0&&m.isDepthTexture===!0)g="texture_depth_cube";else if(m.isCubeTexture===!0)g="texture_cube<f32>";else if(m.isDepthTexture===!0)i.compatibilityMode&&m.compareFunction===null?g=`texture${E}_2d<f32>`:g=`texture_depth${E}_2d${m.isArrayTexture===!0?"_array":""}`;else if(u.node.isStorageTextureNode===!0){let T=rpe(m,i.device),S=this.getStorageAccess(u.node,t),_=u.node.value.is3DTexture,x=u.node.value.isArrayTexture;g=`texture_storage_${_?"3d":`2d${x?"_array":""}`}<${T}, ${S}>`}else if(m.isArrayTexture===!0||m.isDataArrayTexture===!0||m.isCompressedArrayTexture===!0)g="texture_2d_array<f32>";else if(m.is3DTexture===!0||m.isData3DTexture===!0)g="texture_3d<f32>";else{let T=this.getComponentTypeFromTexture(m).charAt(0);g=`texture${E}_2d<${T}32>`}s.push(`@binding( ${p.binding++} ) @group( ${p.group} ) var ${u.name} : ${g};`)}else if(u.type==="buffer"||u.type==="storageBuffer"||u.type==="indirectStorageBuffer"){let m=u.node,I=this.getType(m.getNodeType(this)),g=m.bufferCount,E=g>0&&u.type==="buffer"?", "+g:"",w=m.isStorageBufferNode?`storage, ${this.getStorageAccess(m,t)}`:"uniform";if(this.isCustomStruct(u))o.push(`@binding( ${p.binding++} ) @group( ${p.group} ) var<${w}> ${u.name} : ${I};`);else{let S=` value : array< ${m.isAtomic?`atomic<${I}>`:`${I}`}${E} >`;o.push(this._getWGSLStructBinding(u.name,S,w,p.binding++,p.group))}}else{let m=u.groupNode.name;if(l[m]===void 0){let I=this.uniformGroups[m];if(I!==void 0){let g=[];for(let w of I.uniforms){let T=w.getType(),S=this.getType(this.getVectorType(T));g.push(` ${w.name} : ${S}`)}let E=this.uniformGroupsBindings[m];E===void 0&&(E={index:p.binding++,id:p.group},this.uniformGroupsBindings[m]=E),l[m]={index:E.index,id:E.id,snippets:g}}}}}for(let u in l){let h=l[u];r.push(this._getWGSLStructBinding(u,h.snippets.join(`,
`),"uniform",h.index,h.id))}return[...s,...o,...r].join(`
`)}buildCode(){let t=this.material!==null?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(let i in t){this.shaderStage=i;let n=this.allowGlobalVariables,s=t[i];s.uniforms=this.getUniforms(i),s.attributes=this.getAttributes(i),s.varyings=this.getVaryings(i),s.structs=this.getStructs(i),s.vars=this.getVars(i,n),s.codes=this.getCodes(i),s.directives=this.getDirectives(i),s.scopedArrays=this.getScopedArrays(i);let o=`// code
`;o+=this.flowCode[i];let r=this.flowNodes[i],l=r[r.length-1],a=l.outputNode,u=a!==void 0&&a.isOutputStructNode===!0;for(let h of r){let p=this.getFlowData(h),m=h.name;if(m&&(o.length>0&&(o+=`
`),o+=` // flow -> ${m}
`),o+=`${p.code}
`,h===l&&i!=="compute"){if(o+=`// result
`,i==="vertex")o+=`varyings.builtinClipSpace = ${p.result};`;else if(i==="fragment")if(u)s.returnType=a.getNodeType(this),s.structs+="var<private> output : "+s.returnType+";",o+=`return ${p.result};`;else{let I=" @location( 0 ) color: vec4<f32>",g=this.getBuiltins("output");g&&(I+=`,
`+g),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",I),s.structs+=`
var<private> output : OutputStruct;`,o+=`output.color = ${p.result};
return output;`}}}s.flow=o}if(this.shaderStage=null,this.material!==null)this.vertexShader=this._getWGSLVertexCode(t.vertex),this.fragmentShader=this._getWGSLFragmentCode(t.fragment);else{let i=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(t.compute,i)}}getMethod(t,i=null){let n;return i!==null&&(n=this._getWGSLMethod(t+"_"+i)),n===void 0&&(n=this._getWGSLMethod(t)),n||t}getBitcastMethod(t){return`bitcast<${this.getType(t)}>`}getFloatPackingMethod(t){return this.getMethod(`floatpack_${t}_2x16`)}getFloatUnpackingMethod(t){return this.getMethod(`floatunpack_${t}_2x16`)}getTernary(t,i,n){return`select( ${n}, ${i}, ${t} )`}getType(t){return wtt[t]||t}isAvailable(t){let i=a4e[t];return i===void 0&&(t==="float32Filterable"?i=this.renderer.hasFeature("float32-filterable"):t==="clipDistance"&&(i=this.renderer.hasFeature("clip-distances")),a4e[t]=i),i}_getWGSLMethod(t){return Wj[t]!==void 0&&this._include(t),vtt[t]}_include(t){let i=Wj[t];return i.build(this),this.addInclude(i),i}_getWGSLVertexCode(t){return`${this.getSignature()}
// directives
${t.directives}
// structs
${t.structs}
// uniforms
${t.uniforms}
// varyings
${t.varyings}
var<private> varyings : VaryingsStruct;
// vars
${t.vars}
// codes
${t.codes}
@vertex
fn main( ${t.attributes} ) -> VaryingsStruct {
// flow
${t.flow}
return varyings;
}
`}_getWGSLFragmentCode(t){return`${this.getSignature()}
// global
${fbe}
// structs
${t.structs}
// uniforms
${t.uniforms}
// vars
${t.vars}
// codes
${t.codes}
@fragment
fn main( ${t.varyings} ) -> ${t.returnType} {
// flow
${t.flow}
}
`}_getWGSLComputeCode(t,i){let[n,s,o]=i;return`${this.getSignature()}
// directives
${t.directives}
// system
var<private> instanceIndex : u32;
// locals
${t.scopedArrays}
// structs
${t.structs}
// uniforms
${t.uniforms}
// vars
${this.allowGlobalVariables?t.vars:""}
// codes
${t.codes}
@compute @workgroup_size( ${n}, ${s}, ${o} )
fn main( ${t.attributes} ) {
// local vars
${this.allowGlobalVariables?"":t.vars}
// system
instanceIndex = globalId.x
+ globalId.y * ( ${n} * numWorkgroups.x )
+ globalId.z * ( ${n} * numWorkgroups.x ) * ( ${s} * numWorkgroups.y );
// flow
${t.flow}
}
`}_getWGSLStruct(t,i){return`
struct ${t} {
${i}
};`}_getWGSLStructBinding(t,i,n,s=0,o=0){let r=t+"Struct";return`${this._getWGSLStruct(r,i)}
@binding( ${s} ) @group( ${o} )
var<${n}> ${t} : ${r};`}},cpe=class{constructor(t){this.backend=t}getCurrentDepthStencilFormat(t){let i;return t.depth&&(t.depthTexture!==null?i=this.getTextureFormatGPU(t.depthTexture):t.stencil?this.backend.renderer.reversedDepthBuffer===!0?i=jt.Depth32FloatStencil8:i=jt.Depth24PlusStencil8:this.backend.renderer.reversedDepthBuffer===!0?i=jt.Depth32Float:i=jt.Depth24Plus),i}getTextureFormatGPU(t){return this.backend.get(t).format}getTextureSampleData(t){let i;if(t.isFramebufferTexture)i=1;else if(t.isDepthTexture&&!t.renderTarget){let o=this.backend.renderer,r=o.getRenderTarget();i=r?r.samples:o.currentSamples}else t.renderTarget&&(i=t.renderTarget.samples);i=i||1;let n=i>1&&t.renderTarget!==null&&t.isDepthTexture!==!0&&t.isFramebufferTexture!==!0;return{samples:i,primarySamples:n?1:i,isMSAA:n}}getCurrentColorFormat(t){let i;return t.textures!==null?i=this.getTextureFormatGPU(t.textures[0]):i=this.getPreferredCanvasFormat(),i}getCurrentColorFormats(t){return t.textures!==null?t.textures.map(i=>this.getTextureFormatGPU(i)):[this.getPreferredCanvasFormat()]}getCurrentColorSpace(t){return t.textures!==null?t.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(t,i){if(t.isPoints)return rX.PointList;if(t.isLineSegments||t.isMesh&&i.wireframe===!0)return rX.LineList;if(t.isLine)return rX.LineStrip;if(t.isMesh)return rX.TriangleList}getSampleCount(t){return t>=4?4:1}getSampleCountRenderContext(t){return t.textures!==null?this.getSampleCount(t.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){let i=this.backend.parameters.outputType;if(i===void 0)return navigator.gpu.getPreferredCanvasFormat();if(i===Vo)return jt.BGRA8Unorm;if(i===Ao)return jt.RGBA16Float;throw new Error("Unsupported output buffer type.")}},pbe=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);typeof Float16Array<"u"&&pbe.set(Float16Array,["float16"]);var Stt=new Map([[M6,["float16"]]]),Rtt=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]),dpe=class{constructor(t){this.backend=t}createAttribute(t,i){let n=this._getBufferAttribute(t),s=this.backend,o=s.get(n),r=o.buffer;if(r===void 0){let l=s.device,a=n.array;if(t.normalized===!1){if(a.constructor===Int16Array||a.constructor===Int8Array)a=new Int32Array(a);else if((a.constructor===Uint16Array||a.constructor===Uint8Array)&&(a=new Uint32Array(a),i&GPUBufferUsage.INDEX))for(let p=0;p<a.length;p++)a[p]===65535&&(a[p]=4294967295)}if(n.array=a,(n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&n.itemSize===3){a=new a.constructor(n.count*4);for(let p=0;p<n.count;p++)a.set(n.array.subarray(p*3,p*3+3),p*4);n.itemSize=4,n.array=a,o._force3to4BytesAlignment=!0}let u=a.byteLength,h=u+(4-u%4)%4;r=l.createBuffer({label:n.name,size:h,usage:i,mappedAtCreation:!0}),new a.constructor(r.getMappedRange()).set(a),r.unmap(),o.buffer=r}}updateAttribute(t){let i=this._getBufferAttribute(t),n=this.backend,s=n.device,o=n.get(i),r=n.get(i).buffer,l=i.array;if(o._force3to4BytesAlignment===!0){l=new l.constructor(i.count*4);for(let u=0;u<i.count;u++)l.set(i.array.subarray(u*3,u*3+3),u*4);i.array=l}let a=i.updateRanges;if(a.length===0)s.queue.writeBuffer(r,0,l,0);else{let u=aO(l),h=u?1:l.BYTES_PER_ELEMENT;for(let p=0,m=a.length;p<m;p++){let I=a[p],g,E;if(o._force3to4BytesAlignment===!0){let T=Math.floor(I.start/3),S=Math.ceil(I.count/3);g=T*4*h,E=S*4*h}else g=I.start*h,E=I.count*h;let w=g*(u?l.BYTES_PER_ELEMENT:1);s.queue.writeBuffer(r,w,l,g,E)}i.clearUpdateRanges()}}createShaderVertexBuffers(t){let i=t.getAttributes(),n=new Map;for(let s=0;s<i.length;s++){let o=i[s],r=o.array.BYTES_PER_ELEMENT,l=this._getBufferAttribute(o),a=n.get(l);if(a===void 0){let p,m;o.isInterleavedBufferAttribute===!0?(p=o.data.stride*r,m=o.data.isInstancedInterleavedBuffer?lX.Instance:lX.Vertex):(p=o.itemSize*r
- If you're the tool creator, you can take one from https://www.uuidgenerator.net/.
- If you're using a platform tool, verify the uuid isn't misspelled or contact the tool creator.`)}};ze(dye,"_pattern",/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/);ze(dye,"_lut",["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"]);var wI=dye,VAe=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",Ptt=VAe+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Mtt="["+VAe+"]["+Ptt+"]*",Btt=new RegExp("^"+Mtt+"$");function kAe(e,t){let i=[],n=t.exec(e);for(;n;){let s=[];s.startIndex=t.lastIndex-n[0].length;let o=n.length;for(let r=0;r<o;r++)s.push(n[r]);i.push(s),n=t.exec(e)}return i}var Tie=function(e){let t=Btt.exec(e);return!(t===null||typeof t>"u")};function Ftt(e){return typeof e<"u"}var Utt={allowBooleanAttributes:!1,unpairedTags:[]};function Htt(e,t){t=Object.assign({},Utt,t);let i=[],n=!1,s=!1;e[0]==="\uFEFF"&&(e=e.substr(1));for(let o=0;o<e.length;o++)if(e[o]==="<"&&e[o+1]==="?"){if(o+=2,o=Lbe(e,o),o.err)return o}else if(e[o]==="<"){let r=o;if(o++,e[o]==="!"){o=Pbe(e,o);continue}else{let l=!1;e[o]==="/"&&(l=!0,o++);let a="";for(;o<e.length&&e[o]!==">"&&e[o]!==" "&&e[o]!==" "&&e[o]!==`
`&&e[o]!=="\r";o++)a+=e[o];if(a=a.trim(),a[a.length-1]==="/"&&(a=a.substring(0,a.length-1),o--),!qtt(a)){let p;return a.trim().length===0?p="Invalid space after '<'.":p="Tag '"+a+"' is an invalid name.",dd("InvalidTag",p,TI(e,o))}let u=ktt(e,o);if(u===!1)return dd("InvalidAttr","Attributes for '"+a+"' have open quote.",TI(e,o));let h=u.value;if(o=u.index,h[h.length-1]==="/"){let p=o-h.length;h=h.substring(0,h.length-1);let m=Mbe(h,t);if(m===!0)n=!0;else return dd(m.err.code,m.err.msg,TI(e,p+m.err.line))}else if(l)if(u.tagClosed){if(h.trim().length>0)return dd("InvalidTag","Closing tag '"+a+"' can't have attributes or invalid starting.",TI(e,r));if(i.length===0)return dd("InvalidTag","Closing tag '"+a+"' has not been opened.",TI(e,r));{let p=i.pop();if(a!==p.tagName){let m=TI(e,p.tagStartPos);return dd("InvalidTag","Expected closing tag '"+p.tagName+"' (opened in line "+m.line+", col "+m.col+") instead of closing tag '"+a+"'.",TI(e,r))}i.length==0&&(s=!0)}}else return dd("InvalidTag","Closing tag '"+a+"' doesn't have proper closing.",TI(e,o));else{let p=Mbe(h,t);if(p!==!0)return dd(p.err.code,p.err.msg,TI(e,o-h.length+p.err.line));if(s===!0)return dd("InvalidXml","Multiple possible root nodes found.",TI(e,o));t.unpairedTags.indexOf(a)!==-1||i.push({tagName:a,tagStartPos:r}),n=!0}for(o++;o<e.length;o++)if(e[o]==="<")if(e[o+1]==="!"){o++,o=Pbe(e,o);continue}else if(e[o+1]==="?"){if(o=Lbe(e,++o),o.err)return o}else break;else if(e[o]==="&"){let p=jtt(e,o);if(p==-1)return dd("InvalidChar","char '&' is not expected.",TI(e,o));o=p}else if(s===!0&&!Obe(e[o]))return dd("InvalidXml","Extra text at the end",TI(e,o));e[o]==="<"&&o--}}else{if(Obe(e[o]))continue;return dd("InvalidChar","char '"+e[o]+"' is not expected.",TI(e,o))}if(n){if(i.length==1)return dd("InvalidTag","Unclosed tag '"+i[0].tagName+"'.",TI(e,i[0].tagStartPos));if(i.length>0)return dd("InvalidXml","Invalid '"+JSON.stringify(i.map(o=>o.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return dd("InvalidXml","Start tag expected.",1);return!0}function Obe(e){return e===" "||e===" "||e===`
`||e==="\r"}function Lbe(e,t){let i=t;for(;t<e.length;t++)if(e[t]=="?"||e[t]==" "){let n=e.substr(i,t-i);if(t>5&&n==="xml")return dd("InvalidXml","XML declaration allowed only at the start of the document.",TI(e,t));if(e[t]=="?"&&e[t+1]==">"){t++;break}else continue}return t}function Pbe(e,t){if(e.length>t+5&&e[t+1]==="-"&&e[t+2]==="-"){for(t+=3;t<e.length;t++)if(e[t]==="-"&&e[t+1]==="-"&&e[t+2]===">"){t+=2;break}}else if(e.length>t+8&&e[t+1]==="D"&&e[t+2]==="O"&&e[t+3]==="C"&&e[t+4]==="T"&&e[t+5]==="Y"&&e[t+6]==="P"&&e[t+7]==="E"){let i=1;for(t+=8;t<e.length;t++)if(e[t]==="<")i++;else if(e[t]===">"&&(i--,i===0))break}else if(e.length>t+9&&e[t+1]==="["&&e[t+2]==="C"&&e[t+3]==="D"&&e[t+4]==="A"&&e[t+5]==="T"&&e[t+6]==="A"&&e[t+7]==="["){for(t+=8;t<e.length;t++)if(e[t]==="]"&&e[t+1]==="]"&&e[t+2]===">"){t+=2;break}}return t}var Gtt='"',Vtt="'";function ktt(e,t){let i="",n="",s=!1;for(;t<e.length;t++){if(e[t]===Gtt||e[t]===Vtt)n===""?n=e[t]:n!==e[t]||(n="");else if(e[t]===">"&&n===""){s=!0;break}i+=e[t]}return n!==""?!1:{value:i,index:t,tagClosed:s}}var ztt=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function Mbe(e,t){let i=kAe(e,ztt),n={};for(let s=0;s<i.length;s++){if(i[s][1].length===0)return dd("InvalidAttr","Attribute '"+i[s][2]+"' has no space in starting.",BY(i[s]));if(i[s][3]!==void 0&&i[s][4]===void 0)return dd("InvalidAttr","Attribute '"+i[s][2]+"' is without value.",BY(i[s]));if(i[s][3]===void 0&&!t.allowBooleanAttributes)return dd("InvalidAttr","boolean attribute '"+i[s][2]+"' is not allowed.",BY(i[s]));let o=i[s][2];if(!Ytt(o))return dd("InvalidAttr","Attribute '"+o+"' is an invalid name.",BY(i[s]));if(!n.hasOwnProperty(o))n[o]=1;else return dd("InvalidAttr","Attribute '"+o+"' is repeated.",BY(i[s]))}return!0}function Wtt(e,t){let i=/\d/;for(e[t]==="x"&&(t++,i=/[\da-fA-F]/);t<e.length;t++){if(e[t]===";")return t;if(!e[t].match(i))break}return-1}function jtt(e,t){if(t++,e[t]===";")return-1;if(e[t]==="#")return t++,Wtt(e,t);let i=0;for(;t<e.length;t++,i++)if(!(e[t].match(/\w/)&&i<20)){if(e[t]===";")break;return-1}return t}function dd(e,t,i){return{err:{code:e,msg:t,line:i.line||i,col:i.col}}}function Ytt(e){return Tie(e)}function qtt(e){return Tie(e)}function TI(e,t){let i=e.substring(0,t).split(/\r?\n/);return{line:i.length,col:i[i.length-1].length+1}}function BY(e){return e.startIndex+e[1].length}var $tt={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,i){return e},captureMetaData:!1};function zAe(e){return typeof e=="boolean"?{enabled:e,maxEntitySize:1e4,maxExpansionDepth:10,maxTotalExpansions:1e3,maxExpandedLength:1e5,allowedTags:null,tagFilter:null}:typeof e=="object"&&e!==null?{enabled:e.enabled!==!1,maxEntitySize:e.maxEntitySize??1e4,maxExpansionDepth:e.maxExpansionDepth??10,maxTotalExpansions:e.maxTotalExpansions??1e3,maxExpandedLength:e.maxExpandedLength??1e5,allowedTags:e.allowedTags??null,tagFilter:e.tagFilter??null}:zAe(!0)}var Ztt=function(e){let t=Object.assign({},$tt,e);return t.processEntities=zAe(t.processEntities),t},Ute;typeof Symbol!="function"?Ute="@@xmlMetadata":Ute=Symbol("XML Node Metadata");var Kb=class{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,i){t==="__proto__"&&(t="#__proto__"),this.child.push({[t]:i})}addChild(t,i){t.tagname==="__proto__"&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),i!==void 0&&(this.child[this.child.length-1][Ute]={startIndex:i})}static getMetaDataSymbol(){return Ute}},
`);let t=new Kb("!xml"),i=t,n="",s="";this.entityExpansionCount=0,this.currentExpandedLength=0;let o=new EIe(this.options.processEntities);for(let r=0;r<e.length;r++)if(e[r]==="<")if(e[r+1]==="/"){let a=TP(e,">",r,"Closing Tag is not closed."),u=e.substring(r+2,a).trim();if(this.options.removeNSPrefix){let m=u.indexOf(":");m!==-1&&(u=u.substr(m+1))}this.options.transformTagName&&(u=this.options.transformTagName(u)),i&&(n=this.saveTextToParentTag(n,i,s));let h=s.substring(s.lastIndexOf(".")+1);if(u&&this.options.unpairedTags.indexOf(u)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${u}>`);let p=0;h&&this.options.unpairedTags.indexOf(h)!==-1?(p=s.lastIndexOf(".",s.lastIndexOf(".")-1),this.tagsNodeStack.pop()):p=s.lastIndexOf("."),s=s.substring(0,p),i=this.tagsNodeStack.pop(),n="",r=a}else if(e[r+1]==="?"){let a=wIe(e,r,!1,"?>");if(!a)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,i,s),!(this.options.ignoreDeclaration&&a.tagName==="?xml"||this.options.ignorePiTags)){let u=new Kb(a.tagName);u.add(this.options.textNodeName,""),a.tagName!==a.tagExp&&a.attrExpPresent&&(u[":@"]=this.buildAttributesMap(a.tagExp,s,a.tagName)),this.addChild(i,u,s,r)}r=a.closeIndex+1}else if(e.substr(r+1,3)==="!--"){let a=TP(e,"-->",r+4,"Comment is not closed.");if(this.options.commentPropName){let u=e.substring(r+4,a-2);n=this.saveTextToParentTag(n,i,s),i.add(this.options.commentPropName,[{[this.options.textNodeName]:u}])}r=a}else if(e.substr(r+1,2)==="!D"){let a=o.readDocType(e,r);this.docTypeEntities=a.entities,r=a.i}else if(e.substr(r+1,2)==="!["){let a=TP(e,"]]>",r,"CDATA is not closed.")-2,u=e.substring(r+9,a);n=this.saveTextToParentTag(n,i,s);let h=this.parseTextData(u,i.tagname,s,!0,!1,!0,!0);h==null&&(h=""),this.options.cdataPropName?i.add(this.options.cdataPropName,[{[this.options.textNodeName]:u}]):i.add(this.options.textNodeName,h),r=a+2}else{let a=wIe(e,r,this.options.removeNSPrefix),u=a.tagName,h=a.rawTagName,p=a.tagExp,m=a.attrExpPresent,I=a.closeIndex;if(this.options.transformTagName){let w=this.options.transformTagName(u);p===u&&(p=w),u=w}i&&n&&i.tagname!=="!xml"&&(n=this.saveTextToParentTag(n,i,s,!1));let g=i;g&&this.options.unpairedTags.indexOf(g.tagname)!==-1&&(i=this.tagsNodeStack.pop(),s=s.substring(0,s.lastIndexOf("."))),u!==t.tagname&&(s+=s?"."+u:u);let E=r;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,s,u)){let w="";if(p.length>0&&p.lastIndexOf("/")===p.length-1)u[u.length-1]==="/"?(u=u.substr(0,u.length-1),s=s.substr(0,s.length-1),p=u):p=p.substr(0,p.length-1),r=a.closeIndex;else if(this.options.unpairedTags.indexOf(u)!==-1)r=a.closeIndex;else{let S=this.readStopNodeData(e,h,I+1);if(!S)throw new Error(`Unexpected end of ${h}`);r=S.i,w=S.tagContent}let T=new Kb(u);u!==p&&m&&(T[":@"]=this.buildAttributesMap(p,s,u)),w&&(w=this.parseTextData(w,u,s,!0,m,!0,!0)),s=s.substr(0,s.lastIndexOf(".")),T.add(this.options.textNodeName,w),this.addChild(i,T,s,E)}else{if(p.length>0&&p.lastIndexOf("/")===p.length-1){if(u[u.length-1]==="/"?(u=u.substr(0,u.length-1),s=s.substr(0,s.length-1),p=u):p=p.substr(0,p.length-1),this.options.transformTagName){let T=this.options.transformTagName(u);p===u&&(p=T),u=T}let w=new Kb(u);u!==p&&m&&(w[":@"]=this.buildAttributesMap(p,s,u)),this.addChild(i,w,s,E),s=s.substr(0,s.lastIndexOf("."))}else{let w=new Kb(u);this.tagsNodeStack.push(i),u!==p&&m&&(w[":@"]=this.buildAttributesMap(p,s,u)),this.addChild(i,w,s,E),i=w}n="",r=I}}else n+=e[r];return t.child};function cit(e,t,i,n){this.options.captureMetaData||(n=void 0);let s=this.options.updateTag(t.tagname,i,t[":@"]);s===!1||(typeof s=="string"&&(t.tagname=s),e.addChild(t,n))}var dit=function(e,t,i){if(e.indexOf("&")===-1)return e;let n=this.options.processEntities;if(!n.enabled||n.allowedTags&&!n.allowedTags.includes(t)||n.tagFilter&&!n.tagFilter(t,i))return e;for(let s in this.docTypeEntities){let o=this.docTypeEntities[s],r=e.match(o.regx);if(r){if(this.entityExpansionCount+=r.length,n.maxTotalExpansions&&this.entityExpansionCount>n.maxTotalExpansions)throw new Error(`Entity expansion limit ex
`;function wit(e,t){let i="";return t.format&&t.indentBy.length>0&&(i=Tit),YAe(e,t,"",i)}function YAe(e,t,i,n){let s="",o=!1;for(let r=0;r<e.length;r++){let l=e[r],a=vit(l);if(a===void 0)continue;let u="";if(i.length===0?u=a:u=`${i}.${a}`,a===t.textNodeName){let g=l[a];Sit(u,t)||(g=t.tagValueProcessor(a,g),g=qAe(g,t)),o&&(s+=n),s+=g,o=!1;continue}else if(a===t.cdataPropName){o&&(s+=n),s+=`<![CDATA[${l[a][0][t.textNodeName]}]]>`,o=!1;continue}else if(a===t.commentPropName){s+=n+`<!--${l[a][0][t.textNodeName]}-->`,o=!0;continue}else if(a[0]==="?"){let g=Fbe(l[":@"],t),E=a==="?xml"?"":n,w=l[a][0][t.textNodeName];w=w.length!==0?" "+w:"",s+=E+`<${a}${w}${g}?>`,o=!0;continue}let h=n;h!==""&&(h+=t.indentBy);let p=Fbe(l[":@"],t),m=n+`<${a}${p}`,I=YAe(l[a],t,u,h);t.unpairedTags.indexOf(a)!==-1?t.suppressUnpairedNode?s+=m+">":s+=m+"/>":(!I||I.length===0)&&t.suppressEmptyNode?s+=m+"/>":I&&I.endsWith(">")?s+=m+`>${I}${n}</${a}>`:(s+=m+">",I&&n!==""&&(I.includes("/>")||I.includes("</"))?s+=n+t.indentBy+I+n:s+=I,s+=`</${a}>`),o=!0}return s}function vit(e){let t=Object.keys(e);for(let i=0;i<t.length;i++){let n=t[i];if(e.hasOwnProperty(n)&&n!==":@")return n}}function Fbe(e,t){let i="";if(e&&!t.ignoreAttributes)for(let n in e){if(!e.hasOwnProperty(n))continue;let s=t.attributeValueProcessor(n,e[n]);s=qAe(s,t),s===!0&&t.suppressBooleanAttributes?i+=` ${n.substr(t.attributeNamePrefix.length)}`:i+=` ${n.substr(t.attributeNamePrefix.length)}="${s}"`}return i}function Sit(e,t){e=e.substr(0,e.length-t.textNodeName.length-1);let i=e.substr(e.lastIndexOf(".")+1);for(let n in t.stopNodes)if(t.stopNodes[n]===e||t.stopNodes[n]==="*."+i)return!0;return!1}function qAe(e,t){if(e&&e.length>0&&t.processEntities)for(let i=0;i<t.entities.length;i++){let n=t.entities[i];e=e.replace(n.regex,n.val)}return e}var Rit={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function GD(e){this.options=Object.assign({},Rit,e),this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=WAe(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Ait),this.processTextOrObjNode=_it,this.options.format?(this.indentate=bit,this.tagEndChar=`>
`,this.newLine=`
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}GD.prototype.build=function(e){return this.options.preserveOrder?wit(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)};GD.prototype.j2x=function(e,t,i){let n="",s="",o=i.join(".");for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r))if(typeof e[r]>"u")this.isAttribute(r)&&(s+="");else if(e[r]===null)this.isAttribute(r)||r===this.options.cdataPropName?s+="":r[0]==="?"?s+=this.indentate(t)+"<"+r+"?"+this.tagEndChar:s+=this.indentate(t)+"<"+r+"/"+this.tagEndChar;else if(e[r]instanceof Date)s+=this.buildTextValNode(e[r],r,"",t);else if(typeof e[r]!="object"){let l=this.isAttribute(r);if(l&&!this.ignoreAttributesFn(l,o))n+=this.buildAttrPairStr(l,""+e[r]);else if(!l)if(r===this.options.textNodeName){let a=this.options.tagValueProcessor(r,""+e[r]);s+=this.replaceEntitiesValue(a)}else s+=this.buildTextValNode(e[r],r,"",t)}else if(Array.isArray(e[r])){let l=e[r].length,a="",u="";for(let h=0;h<l;h++){let p=e[r][h];if(!(typeof p>"u"))if(p===null)r[0]==="?"?s+=this.indentate(t)+"<"+r+"?"+this.tagEndChar:s+=this.indentate(t)+"<"+r+"/"+this.tagEndChar;else if(typeof p=="object")if(this.options.oneListGroup){let m=this.j2x(p,t+1,i.concat(r));a+=m.val,this.options.attributesGroupName&&p.hasOwnProperty(this.options.attributesGroupName)&&(u+=m.attrStr)}else a+=this.processTextOrObjNode(p,r,t,i);else if(this.options.oneListGroup){let m=this.options.tagValueProcessor(r,p);m=this.replaceEntitiesValue(m),a+=m}else a+=this.buildTextValNode(p,r,"",t)}this.options.oneListGroup&&(a=this.buildObjectNode(a,r,u,t)),s+=a}else if(this.options.attributesGroupName&&r===this.options.attributesGroupName){let l=Object.keys(e[r]),a=l.length;for(let u=0;u<a;u++)n+=this.buildAttrPairStr(l[u],""+e[r][l[u]])}else s+=this.processTextOrObjNode(e[r],r,t,i);return{attrStr:n,val:s}};GD.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,""+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t==="true"?" "+e:" "+e+'="'+t+'"'};function _it(e,t,i,n){let s=this.j2x(e,i+1,n.concat(t));return e[this.options.textNodeName]!==void 0&&Object.keys(e).length===1?this.buildTextValNode(e[this.options.textNodeName],t,s.attrStr,i):this.buildObjectNode(s.val,t,s.attrStr,i)}GD.prototype.buildObjectNode=function(e,t,i,n){if(e==="")return t[0]==="?"?this.indentate(n)+"<"+t+i+"?"+this.tagEndChar:this.indentate(n)+"<"+t+i+this.closeTag(t)+this.tagEndChar;{let s="</"+t+this.tagEndChar,o="";return t[0]==="?"&&(o="?",s=""),(i||i==="")&&e.indexOf("<")===-1?this.indentate(n)+"<"+t+i+o+">"+e+s:this.options.commentPropName!==!1&&t===this.options.commentPropName&&o.length===0?this.indentate(n)+`<!--${e}-->`+this.newLine:this.indentate(n)+"<"+t+i+o+this.tagEndChar+e+this.indentate(n)+s}};GD.prototype.closeTag=function(e){let t="";return this.options.unpairedTags.indexOf(e)!==-1?this.options.suppressUnpairedNode||(t="/"):this.options.suppressEmptyNode?t="/":t=`></${e}`,t};GD.prototype.buildTextValNode=function(e,t,i,n){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(n)+`<![CDATA[${e}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(n)+`<!--${e}-->`+this.newLine;if(t[0]==="?")return this.indentate(n)+"<"+t+i+"?"+this.tagEndChar;{let s=this.options.tagValueProcessor(t,e);return s=this.replaceEntitiesValue(s),s===""?this.indentate(n)+"<"+t+i+this.closeTag(t)+this.tagEndChar:this.indentate(n)+"<"+t+i+">"+s+"</"+t+this.tagEndChar}};GD.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){let i=this.options.entities[t];e=e.replace(i.regex,i.val)}return e};function bit(e){return this.options.indentBy.repeat(e)}function Ait(e){return e.startsWith(this.options.attributeNamePrefix)&&e!==this.options.textNodeName?e.substr(this.attrPrefixLen):!1}var wP=class{};ze(wP,"parser",n
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
`,fragmentShader:`
layout(location = 0) out vec4 out_id;
uniform vec4 objectId;
void main() {
out_id = objectId;
}
`}),this._objectId=0,this.setValues(t)}},VIe=1e-16,Ont=new ne(0,1,0),uAe=new ne;function cAe(e){return e.delta(uAe).normalize(),Math.abs(uAe.dot(Ont))>=1-VIe}function kIe(e,t){let{start:i,end:n}=t,s=e.points,o=!1,r=!1;for(let l=0;l<3;l++){let a=s[l];if(!o&&i.distanceToSquared(a)<=VIe&&(o=!0),!r&&n.distanceToSquared(a)<=VIe&&(r=!0),o&&r)return!0}return o&&r}var LD=new wn;function dAe(e,t,i=!1,n=[]){let s=[[0,1]];for(let o=0,r=t.length;o<r;o++){let l=s[o],a=t[o];l[1]=a[0],s.push([a[1],1])}i&&([t,s]=[s,t]);for(let o=0,r=s.length;o<r;o++){let{start:l,end:a}=e;LD.start.lerpVectors(l,a,s[o][0]),LD.end.lerpVectors(l,a,s[o][1]),n.push(new Float32Array([LD.start.x,LD.start.y,LD.start.z,LD.end.x,LD.end.y,LD.end.z]))}return n}var hAe=1e-10,Lnt=new ne(0,1,0),fAe=new ne,pAe=new ne,Ete=new ne,Tte=new Zo;function*mAe(e,t=[],i={}){let{projectionDirection:n=Lnt,thresholdAngle:s=1,iterationTime:o=30}=i,l=Math.pow(10,4),a=Math.cos(Ns.DEG2RAD*s),u=e.getIndex(),h=e.getAttribute("position"),p=u?u.count:h.count,m=[0,0,0],I=["a","b","c"],g=new Array(3),E={},w=performance.now();for(let T=0;T<p;T+=3){performance.now()-w>o&&(yield,w=performance.now()),u?(m[0]=u.getX(T),m[1]=u.getX(T+1),m[2]=u.getX(T+2)):(m[0]=T,m[1]=T+1,m[2]=T+2);let{a:S,b:_,c:x}=Tte;if(S.fromBufferAttribute(h,m[0]),_.fromBufferAttribute(h,m[1]),x.fromBufferAttribute(h,m[2]),Tte.getNormal(Ete),g[0]=`${Math.round(S.x*l)},${Math.round(S.y*l)},${Math.round(S.z*l)}`,g[1]=`${Math.round(_.x*l)},${Math.round(_.y*l)},${Math.round(_.z*l)}`,g[2]=`${Math.round(x.x*l)},${Math.round(x.y*l)},${Math.round(x.z*l)}`,!(g[0]===g[1]||g[1]===g[2]||g[2]===g[0]))for(let M=0;M<3;M++){let W=(M+1)%3,G=g[M],$=g[W],Y=Tte[I[M]],se=Tte[I[W]],pe=`${G}_${$}`,k=`${$}_${G}`;if(k in E&&E[k]){let fe=E[k].normal,Q=Ete.dot(fe)<=a,Te=!1;if(n!==null){let Ve=n.dot(Ete);Ve=Math.abs(Ve)<hAe?0:Ve;let Fe=n.dot(fe);Fe=Math.abs(Fe)<hAe?0:Fe,Te=Math.sign(Ve)!==Math.sign(Fe)}if(Q||Te){let Ve=new wn;Ve.start.copy(Y),Ve.end.copy(se),t.push(Ve)}E[k]=null}else pe in E||(E[pe]={index0:m[M],index1:m[W],normal:Ete.clone()})}}for(let T in E)if(E[T]){let{index0:S,index1:_}=E[T];fAe.fromBufferAttribute(h,S),pAe.fromBufferAttribute(h,_);let x=new wn;x.start.copy(fAe),x.end.copy(pAe),t.push(x)}return t}var wte=new wn;function IAe(e,t,i,n=[]){return e.bvhcast(t,i,{intersectsTriangles:(s,o)=>{if(Mnt(s,o)||(s.needsUpdate&&s.update(),o.needsUpdate&&o.update(),Math.abs(s.plane.normal.dot(o.plane.normal))>1-1e-6))return!1;s.intersectsTriangle(o,wte,!0)&&!kIe(s,wte)&&!kIe(o,wte)&&n.push(wte.clone())}}),n}function Pnt(e,t){return e.distanceTo(t)<1e-10}function Mnt(e,t){let i=["a","b","c"],n=0;for(let s=0;s<3;s++)for(let o=0;o<3;o++){let r=e[i[s]],l=t[i[o]];Pnt(r,l)&&n++}return n>=2}function zIe(e){nxe(e);let t=[];return e.traverse(i=>{i.geometry&&i.visible&&t.push(i)}),t}var nxe=e=>{if(e===void 0)return;let t=[...e.children];for(let i of t)i===void 0?e.children.splice(e.children.indexOf(i),1):nxe(i)},vte=new di,yAe=new di,WIe=class{constructor(){this.projectionDirection=new ne(0,1,0),this.thresholdAngle=50,this.iterationTime=30}getEdges(...t){let i=this.iterationTime;this.iterationTime=1/0;let n=this.getEdgesGenerator(...t).next().value;return this.iterationTime=i,n}*getEdgesGenerator(t,i=[],n=null){let{projectionDirection:s,thresholdAngle:o,iterationTime:r}=this;if(t.isObject3D){let l=zIe(t),a=null;s&&(a=new ne);let u=performance.now();for(let h=0;h<l.length;h++){u-performance.now()>r&&(yield);let p=l[h];a&&(yAe.copy(p.matrixWorld).invert(),a.copy(s).transformDirection(yAe).normalize());let m=yield*mAe(p.geometry,[],{projectionDirection:a,thresholdAngle:o,iterationTime:r});gAe(m,p.matrixWorld);for(let I=0;I<m.length;I++)i.push(m[I]);if(n!==null)for(let I=0;I<m.length;I++)n.push(p)}return i}else return yield*mAe(t,i,{projectionDirection:s,thresholdAngle:o,iterationTime:r})}getIntersectionEdges(...t){let i=this.iterationTime;this.iterationTime=1/0;let n=this.getIntersectionEdgesGenerator(...t).next().value;return this.iterationTime=i,n}*getIntersectionEdgesGenerator(t,i=[],n=null){let{iterationTime:s}=this;if(t.isObject3D){let o=zIe(t),r=new Map
=== Projection Summary ===`),console.log(`Total time: ${e.toFixed(1)}ms
`);for(let[t,i]of Object.entries(_te)){let n=(i/e*100).toFixed(1);console.log(` ${t}: ${i.toFixed(1)}ms (${n}%)`)}if(Object.keys(jY).length>0){console.log(`
--- Stats ---`);for(let[t,i]of Object.entries(jY))console.log(` ${t}: ${i}`)}console.log("")}},c3=1e-5,bte=1e-16,Ate=1e-16;function Ynt(e){let t=new Float32Array(e.length*6);for(let i=0;i<e.length;i++){let n=e[i];t[i*6+0]=n.start.x,t[i*6+1]=n.start.y,t[i*6+2]=n.start.z,t[i*6+3]=n.end.x,t[i*6+4]=n.end.y,t[i*6+5]=n.end.z}return t}function qnt(e,t,i,n,s){e.bvhcast(t,i.matrixWorld,{intersectsRanges:(o,r,l,a)=>{n._edgeOffsets.push(o),n._edgeCounts.push(r),n._meshOffsets.push(l),n._meshCounts.push(a),n._meshIndex.push(s),n.groupCount++}})}var $nt=1e3,Znt=1e5,pIe=5,mIe=3,Knt=2e6,YY=null;async function Qnt(){return YY===null&&(YY=new PF,await YY.init()),YY}async function Jnt(e,t,i,n,s=null){let o=await Qnt();e._edgeOffsets&&(e.edgeOffsets=new Uint32Array(e._edgeOffsets),e.edgeCounts=new Uint32Array(e._edgeCounts),e.meshOffsets=new Uint32Array(e._meshOffsets),e.meshCounts=new Uint32Array(e._meshCounts),e.meshIndex=new Uint32Array(e._meshIndex),e._edgeOffsets=null,e._edgeCounts=null,e._meshOffsets=null,e._meshCounts=null,e._meshIndex=null);let r=Jp(Ynt(i.lines),"float");sr.enabled&&console.log("Number of meshes:",t.length),sr.enabled&&console.log("Group count:",e.groupCount);let l=[];{let g=0;for(;g<t.length;){let E=g,w=0;for(;E<t.length;){let T=t[E].geometry,S=T.index?T.index.count/3:T.attributes.position.count/3;if(E>g&&(E-g>=$nt||w+S>Znt))break;w+=S,E++}l.push({start:g,end:E}),g=E}}sr.enabled&&console.log(`Split ${t.length} meshes into ${l.length} batches`);let a=0,u=0,h=0,p=0,m=0;for(let g=0;g<l.length;g++){let{start:E,end:w}=l[g],T=w-E;sr.enabled&&console.log(`Processing batch ${g+1}/${l.length} (meshes ${E}-${w-1})`);let S=0,_=0,x=[];for(let Pt=E;Pt<w;Pt++){let $t=t[Pt].geometry;x.push(_/3),S+=$t.attributes.position.array.length,_+=$t.index.array.length}let M=new Float32Array(S),W=new Uint32Array(_),G=0,$=0,Y=0;for(let Pt=E;Pt<w;Pt++){let $t=t[Pt].geometry,Vt=$t.attributes.position.array,Ue=$t.index.array;M.set(Vt,G),G+=Vt.length;for(let Ft=0;Ft<Ue.length;Ft++)W[$+Ft]=Ue[Ft]+Y;$+=Ue.length,Y+=$t.attributes.position.count}let se=new Float32Array(T*16);for(let Pt=E;Pt<w;Pt++){let $t=Pt-E;se.set(t[Pt].matrixWorld.elements,$t*16)}let pe=[];for(let Pt=0;Pt<e.groupCount;Pt++){let $t=e.meshIndex[Pt];if($t>=E&&$t<w){let Vt=$t-E,Ue=x[Vt]+e.meshOffsets[Pt];pe.push({edgeOffset:e.edgeOffsets[Pt],edgeCount:e.edgeCounts[Pt],triOffset:Ue,triCount:e.meshCounts[Pt],meshIdx:Vt})}}if(pe.length===0){sr.enabled&&console.log(` Batch ${g+1}: no groups, skipping`);continue}let k=new Uint32Array(pe.length*pIe);for(let Pt=0;Pt<pe.length;Pt++){let $t=pe[Pt],Vt=Pt*pIe;k[Vt+0]=$t.edgeOffset,k[Vt+1]=$t.edgeCount,k[Vt+2]=$t.triOffset,k[Vt+3]=$t.triCount,k[Vt+4]=$t.meshIdx}let fe=0;for(let Pt=0;Pt<pe.length;Pt++)fe+=pe[Pt].edgeCount*pe[Pt].triCount;s&&(s.candidates+=fe);let Q=Math.min(Math.ceil(fe*.1),Knt),Te=Math.max(Q,1e4);sr.enabled&&console.log(` Batch ${g+1}: ${pe.length} groups, ${S/3} vertices, ${_/3} triangles, ${fe} pairs, buffer for ${Te} overlaps`);let Ve=performance.now(),Fe=Jp(M,"float"),pt=Jp(W,"uint"),Me=Jp(se,"float"),He=Jp(k,"uint"),Ye=Jp(new Uint32Array([0]),"uint").toAtomic(),We=Jp(new Float32Array(Te*mIe),"float");p+=performance.now()-Ve;let _t=performance.now(),xt=Wee(()=>{let $t=Yee.mul(pIe),Vt=He.element($t),Ue=He.element($t.add(1)),Ft=He.element($t.add(2)),ie=He.element($t.add(3)),Ce=He.element($t.add(4)).mul(16),Se=qee(Me.element(Ce),Me.element(Ce.add(1)),Me.element(Ce.add(2)),Me.element(Ce.add(3)),Me.element(Ce.add(4)),Me.element(Ce.add(5)),Me.element(Ce.add(6)),Me.element(Ce.add(7)),Me.element(Ce.add(8)),Me.element(Ce.add(9)),Me.element(Ce.add(10)),Me.element(Ce.add(11)),Me.element(Ce.add(12)),Me.element(Ce.add(13)),Me.element(Ce.add(14)),Me.element(Ce.add(15)));GF({start:VF(0),end:ie.toInt(),type:"int",condition:"<",name:"triIdx"},({triIdx:_e})=>{let Be=Ft.add(_e.toUint()).mul(3),dt=pt.element(Be),it=pt.element(Be.add(1)),Rt=pt.element(Be.add(2)),At=Bo(Fe.element(dt.mul(3)),Fe.element(dt.mul(3).add(1)),Fe.element(dt.mul(3).add(2))),Ht=Bo(Fe.element(it.mul(3)),Fe.element(it.mul(3).add(1)),Fe.element(it.mul(3).add(2))),Xe=Bo(F
varying vec3 worldPosition;
uniform float uDistance;
void main() {
vec3 pos = position.xzy * uDistance;
pos.xz += cameraPosition.xz;
worldPosition = pos;
gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
}
`,fragmentShader:`
varying vec3 worldPosition;
uniform float uZoom;
uniform float uFade;
uniform float uSize1;
uniform float uSize2;
uniform vec3 uColor;
uniform float uDistance;
float getGrid(float size) {
vec2 r = worldPosition.xz / size;
vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);
float line = min(grid.x, grid.y);
return 1.0 - min(line, 1.0);
}
void main() {
float d = 1.0 - min(distance(cameraPosition.xz, worldPosition.xz) / uDistance, 1.0);
float g1 = getGrid(uSize1);
float g2 = getGrid(uSize2);
// Ortho camera fades the grid away when zooming out
float minZoom = step(0.2, uZoom);
float zoomFactor = pow(min(uZoom, 1.), 2.) * minZoom;
gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, uFade));
gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2) * zoomFactor;
if ( gl_FragColor.a <= 0.0 ) discard;
}
`,extensions:{derivatives:!0}});this.three=new ci(l,a),this.three.frustumCulled=!1,i.scene.three.add(this.three),this.setupEvents(!0)}get visible(){return this.three.visible}set visible(t){this.three.visible=t,t?this.world.scene.three.add(this.three):this.three.removeFromParent()}get material(){return this.three.material}get fade(){return this._fade===3}set fade(t){this._fade=t?3:0,this.material.uniforms.uFade.value=this._fade}setup(t){let i={...this._defaultConfig,...t};this.config.visible=!0,this.config.color=i.color,this.config.primarySize=i.primarySize,this.config.secondarySize=i.secondarySize,this.config.distance=i.distance,this.isSetup=!0,this.onSetup.trigger()}dispose(){this.setupEvents(!1),this.components.get(iq).list.delete(this.config.uuid),this.components.get(IU).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset(),this.world=null,this.components=null}setupEvents(t){if(this.world.isDisposing||!(this.world.camera instanceof hU))return;let i=this.world.camera.controls;t?i.addEventListener("update",this.updateZoom):i.removeEventListener("update",this.updateZoom)}},Rxe=class _xe extends Ra{constructor(t){super(t),ze(this,"list",new Map),ze(this,"onDisposed",new rn),ze(this,"enabled",!0),t.add(_xe.uuid,this)}create(t){if(this.list.has(t.uuid))throw new Error("This world already has a grid!");let i=new Kte(this.components,t);return this.list.set(t.uuid,i),t.onDisposed.add(()=>{this.delete(t)}),i}delete(t){let i=this.list.get(t.uuid);i&&i.dispose(),this.list.delete(t.uuid)}dispose(){for(let[t,i]of this.list)i.dispose();this.list.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}};ze(Rxe,"uuid","d1e814d5-b81c-4452-87a2-f039375e0489");var ist=Rxe,bxe=class Axe{constructor(){ze(this,"onDisposed",new rn),ze(this,"list",new Ln),ze(this,"enabled",!1),ze(this,"_clock"),ze(this,"onInit",new rn),ze(this,"update",()=>{if(!this.enabled)return;let t=this._clock.getDelta();for(let[i,n]of this.list)n.enabled&&n.isUpdateable()&&n.update(t);requestAnimationFrame(this.update)}),this._clock=new qx,Axe.setupBVH()}add(t,i){if(this.list.has(t))throw new Error("You're trying to add a component that already exists in the components instance. Use Components.get() instead.");wI.validate(t),this.list.set(t,i)}get(t){var i;let n=t.uuid;if(!this.list.has(n)){let s=new t(this);return(i=s.isDisposeable)!=null&&i.call(s)&&s.onDisposed.add(()=>this.list.delete(n)),this.list.has(n)||this.add(n,s),s}return this.list.get(n)}init(){this.enabled=!0;for(let[t,i]of this.list.entries())i.enabled=!0;this._clock.start(),this.update(),this.onInit.trigger()}dispose(){this.enabled=!1;let t;for(let[i,n]of this.list){if(n.enabled=!1,i===ro.uuid){t=n;continue}n.isDisposeable()&&n.dispose()}t?.dispose(),this._clock.stop(),this.onDisposed.trigger()}static setupBVH(){Ni.prototype.computeBoundsTree=Ant,Ni.prototype.disposeBoundsTree=xnt,ci.prototype.raycast=aAe,Rn.prototype.raycast=aAe}};ze(bxe,"release","2.4.3");var Eye=bxe,Qte=class{constructor(t){ze(this,"enabled",!1),ze(this,"id","FirstPerson"),this.camera=t}set(t){if(this.enabled=t,t){if(this.camera.projection.current!=="Perspective"){this.camera.set("Orbit");return}this.setupFirstPersonCamera()}}setupFirstPersonCamera(){let t=this.camera.controls,i=new ne;t.distance--,t.getPosition(i),t.minDistance=1,t.maxDistance=1,t.distance=1,t.moveTo(i.x,i.y,i.z),t.truckSpeed=50,t.mouseButtons.wheel=em.ACTION.DOLLY,t.touches.two=em.ACTION.TOUCH_ZOOM_TRUCK}},Jte=class{constructor(t){ze(this,"enabled",!0),ze(this,"id","Orbit"),this.camera=t,this.activateOrbitControls()}set(t){this.enabled=t,t&&this.activateOrbitControls()}activateOrbitControls(){let t=this.camera.controls;t.minDistance=1,t.maxDistance=300;let i=new ne;t.getPosition(i);let n=i.length();t.distance=n,t.truckSpeed=2;let{rotation:s}=this.camera.three,o=new ne(0,0,-1).applyEuler(s),r=i.addScaledVector(o,n);t.moveTo(r.x,r.y,r.z)}},Xte=class{constructor(t){ze(this,"enabled",!1),ze(this,"id","Plan"),ze(this,"mouseAction1"),ze(this,"mouseAction2"),ze(this,"mouseInitialized",!1),ze(this,"defaultAzimuthSpeed"),ze(this,"defaultPolarSpe
\0`,xt+=o(Ye,2),xt+=W.magic,xt+=o(_,2),xt+=o(x,2),xt+=o(He.crc32,4),xt+=o(He.compressedSize,4),xt+=o(He.uncompressedSize,4),xt+=o($.length,2),xt+=o(Te.length,2),{fileRecord:p.LOCAL_FILE_HEADER+xt+$+Te,dirRecord:p.CENTRAL_FILE_HEADER+o(_t,2)+xt+o(pe.length,2)+"\0\0\0\0"+o(We,4)+o(w,4)+$+Te+pe}}var l=i("../utils"),a=i("../stream/GenericWorker"),u=i("../utf8"),h=i("../crc32"),p=i("../signature");function m(I,g,E,w){a.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=E,this.encodeFileName=w,this.streamFiles=I,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}l.inherits(m,a),m.prototype.push=function(I){var g=I.meta.percent||0,E=this.entriesCount,w=this._sources.length;this.accumulate?this.contentBuffer.push(I):(this.bytesWritten+=I.data.length,a.prototype.push.call(this,{data:I.data,meta:{currentFile:this.currentFile,percent:E?(g+100*(E-w-1))/E:100}}))},m.prototype.openedSource=function(I){this.currentSourceOffset=this.bytesWritten,this.currentFile=I.file.name;var g=this.streamFiles&&!I.file.dir;if(g){var E=r(I,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:E.fileRecord,meta:{percent:0}})}else this.accumulate=!0},m.prototype.closedSource=function(I){this.accumulate=!1;var g=this.streamFiles&&!I.file.dir,E=r(I,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(E.dirRecord),g)this.push({data:(function(w){return p.DATA_DESCRIPTOR+o(w.crc32,4)+o(w.compressedSize,4)+o(w.uncompressedSize,4)})(I),meta:{percent:100}});else for(this.push({data:E.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},m.prototype.flush=function(){for(var I=this.bytesWritten,g=0;g<this.dirRecords.length;g++)this.push({data:this.dirRecords[g],meta:{percent:100}});var E=this.bytesWritten-I,w=(function(T,S,_,x,M){var W=l.transformTo("string",M(x));return p.CENTRAL_DIRECTORY_END+"\0\0\0\0"+o(T,2)+o(T,2)+o(S,4)+o(_,4)+o(W.length,2)+W})(this.dirRecords.length,E,I,this.zipComment,this.encodeFileName);this.push({data:w,meta:{percent:100}})},m.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},m.prototype.registerPrevious=function(I){this._sources.push(I);var g=this;return I.on("data",function(E){g.processChunk(E)}),I.on("end",function(){g.closedSource(g.previous.streamInfo),g._sources.length?g.prepareNextSource():g.end()}),I.on("error",function(E){g.error(E)}),this},m.prototype.resume=function(){return!!a.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},m.prototype.error=function(I){var g=this._sources;if(!a.prototype.error.call(this,I))return!1;for(var E=0;E<g.length;E++)try{g[E].error(I)}catch{}return!0},m.prototype.lock=function(){a.prototype.lock.call(this);for(var I=this._sources,g=0;g<I.length;g++)I[g].lock()},n.exports=m},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(i,n,s){var o=i("../compressions"),r=i("./ZipFileWorker");s.generateWorker=function(l,a,u){var h=new r(a.streamFiles,u,a.platform,a.encodeFileName),p=0;try{l.forEach(function(m,I){p++;var g=(function(S,_){var x=S||_,M=o[x];if(!M)throw new Error(x+" is not a valid compression method !");return M})(I.options.compression,a.compression),E=I.options.compressionOptions||a.compressionOptions||{},w=I.dir,T=I.date;I._compressWorker(g,E).withStreamInfo("file",{name:m,dir:w,date:T,comment:I.comment||"",unixPermissions:I.unixPermissions,dosPermissions:I.dosPermissions}).pipe(h)}),h.entriesCount=p}catch(m){h.error(m)}return h}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(i,n,s){function o(){if(!(this instanceof o))return new o;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip
${wP.builder.build(o)}`}};ze(Cxe,"default",{title:"BCF Topic",type:"Issue",status:"Active"});var eye=Cxe,Dxe=(e,t)=>{if(t.trim()==="")return;let i=v0.xmlParser.parse(t).Extensions;if(!i)return;let{Priorities:n,TopicStatuses:s,TopicTypes:o,Users:r}=i;if(n&&n.Priority){let l=Array.isArray(n.Priority)?n.Priority:[n.Priority];for(let a of l)e.config.priorities.add(a)}if(s&&s.TopicStatus){let l=Array.isArray(s.TopicStatus)?s.TopicStatus:[s.TopicStatus];for(let a of l)e.config.statuses.add(a)}if(o&&o.TopicType){let l=Array.isArray(o.TopicType)?o.TopicType:[o.TopicType];for(let a of l)e.config.types.add(a)}if(r&&r.User){let l=Array.isArray(r.User)?r.User:[r.User];for(let a of l)e.config.users.add(a)}},tie=class extends UD{constructor(){super(...arguments),ze(this,"_config",{version:{type:"Select",options:new Set(["2.1","3"]),multiple:!1,value:""},author:{type:"Text",value:""},types:{type:"TextSet",value:new Set},statuses:{type:"TextSet",value:new Set},priorities:{type:"TextSet",value:new Set},labels:{type:"TextSet",value:new Set},stages:{type:"TextSet",value:new Set},users:{type:"TextSet",value:new Set},includeSelectionTag:{type:"Boolean",value:!1},updateExtensionsOnImport:{type:"Boolean",value:!1},strict:{type:"Boolean",value:!1},includeAllExtensionsOnExport:{type:"Boolean",value:!1},fallbackVersionOnImport:{type:"Select",multiple:!1,options:new Set(["2.1","3"]),value:""},ignoreIncompleteTopicsOnImport:{type:"Boolean",value:!1},exportCustomDataAsLabels:{type:"Boolean",value:!1}})}get version(){return this._config.version.value}set version(t){this._config.version.value=t}get author(){return this._config.author.value}set author(t){this._config.author.value=t}get types(){return this._config.types.value}set types(t){this._config.types.value=t}get statuses(){return this._config.statuses.value}set statuses(t){this._config.statuses.value=t}get priorities(){return this._config.priorities.value}set priorities(t){this._config.priorities.value=t}get labels(){return this._config.labels.value}set labels(t){this._config.labels.value=t}get stages(){return this._config.stages.value}set stages(t){this._config.stages.value=t}get users(){return this._config.users.value}set users(t){this._config.users.value=t}get includeSelectionTag(){return this._config.includeSelectionTag.value}set includeSelectionTag(t){this._config.includeSelectionTag.value=t}get updateExtensionsOnImport(){return this._config.updateExtensionsOnImport.value}set updateExtensionsOnImport(t){this._config.updateExtensionsOnImport.value=t}get strict(){return this._config.strict.value}set strict(t){this._config.strict.value=t}get includeAllExtensionsOnExport(){return this._config.includeAllExtensionsOnExport.value}set includeAllExtensionsOnExport(t){this._config.includeAllExtensionsOnExport.value=t}get fallbackVersionOnImport(){return this._config.fallbackVersionOnImport.value}set fallbackVersionOnImport(t){this._config.fallbackVersionOnImport.value=t}get ignoreIncompleteTopicsOnImport(){return this._config.ignoreIncompleteTopicsOnImport.value}set ignoreIncompleteTopicsOnImport(t){this._config.ignoreIncompleteTopicsOnImport.value=t}get exportCustomDataAsLabels(){return this._config.exportCustomDataAsLabels.value}set exportCustomDataAsLabels(t){this._config.exportCustomDataAsLabels.value=t}},Tye=class qY extends Ra{constructor(){super(...arguments),ze(this,"enabled",!1),ze(this,"_defaultConfig",{author:"jhon.doe@example.com",version:"2.1",types:new Set(["Clash","Failure","Fault","Inquiry","Issue","Remark","Request"]),statuses:new Set(["Active","In Progress","Done","In Review","Closed"]),priorities:new Set(["On hold","Minor","Normal","Major","Critical"]),labels:new Set,stages:new Set,users:new Set,includeSelectionTag:!1,updateExtensionsOnImport:!0,strict:!1,includeAllExtensionsOnExport:!0,fallbackVersionOnImport:"2.1",ignoreIncompleteTopicsOnImport:!1,exportCustomDataAsLabels:!1}),ze(this,"config",new tie(this,this.components,"BCF Topics",qY.uuid)),ze(this,"list",new Ln),ze(this,"documents",new Ln),ze(this,"onSetup",new rn),ze(this,"isSetup",!1),ze(this,"onBCFImported",new rn),ze
<Version VersionId="${this.config.version}" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/buildingSMART/BCF-XML/release_3_0/Schemas/version.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</Version>`);for(let[o,r]of this.documents.entries())r.type!=="external"&&i.file(this.config.version==="2.1"?r.fileName:`documents/${o}`,r.data);if(this.config.version==="3"){let o=[];for(let[r,l]of this.documents.entries()){let{type:a,description:u}=l;a!=="external"&&o.push(`<Document Guid="${r}">
<Filename>${l.fileName}</Filename>
${u?`<Description>${u}</Description>`:""}
</Document>`)}o.length>0&&i.file("documents.xml",`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<DocumentInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="documents.xsd">
<Documents>
${o.join(`
`)}
</Documents>
</DocumentInfo>`)}i.file("bcf.extensions",this.serializeExtensions());let n=this.components.get(LS);for(let o of t){let r=i.folder(o.guid);r.file("markup.bcf",o.serialize());for(let l of o.viewpoints){let a=n.list.get(l);if(!a)continue;let u=a.title??a.guid;r.file(`${u}.bcfv`,await a.serialize());let h=n.snapshots.get(a.snapshot);if(!h)continue;let p=h?a.snapshot:a.guid,m=n.getSnapshotExtension(a.snapshot);r.file(`${p}.${m}`,h,{binary:!0})}}return await i.generateAsync({type:"blob"})}serializeExtensions(){let t=[...this.config.types].map(l=>`<TopicType>${l}</TopicType>`).join(`
`),i=[...this.config.statuses].map(l=>`<TopicStatus>${l}</TopicStatus>`).join(`
`),n=[...this.config.priorities].map(l=>`<Priority>${l}</Priority>`).join(`
`),s=[...this.config.labels].map(l=>`<TopicLabel>${l}</TopicLabel>`).join(`
`),o=[...this.config.stages].map(l=>`<Stage>${l}</Stage>`).join(`
`),r=[...this.config.users].map(l=>`<User>${l}</User>`).join(`
`);return`
<?xml version="1.0" encoding="UTF-8"?>
<Extensions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="your-schema-location.xsd">
${t.length!==0?`<TopicTypes>
${t}
</TopicTypes>`:""}
${i.length!==0?`<TopicStatuses>
${i}
</TopicStatuses>`:""}
${n.length!==0?`<Priorities>
${n}
</Priorities>`:""}
${s.length!==0?`<TopicLabels>
${s}
</TopicLabels>`:""}
${o.length!==0?`<Stages>
${o}
</Stages>`:""}
${r.length!==0?`<Users>
${r}
</Users>`:""}
</Extensions>
`}processMarkupComment(t){let{Guid:i,Date:n,Author:s,Comment:o,Viewpoint:r}=t;if(!(i&&n&&s&&(pU||r)))return null;let l=new pU(this.components,o??"");return l.guid=i,l.date=new Date(n),l.author=s,l.viewpoint=r?.Guid,l.modifiedAuthor=t.ModifiedAuthor,l.modifiedDate=t.ModifiedDate?new Date(t.ModifiedDate):void 0,l}getMarkupComments(t,i){var n;let s;if(i==="2.1"&&(s=t.Comment),i==="3"&&(s=(n=t.Topic.Comments)==null?void 0:n.Comment),!s)return[];s=Array.isArray(s)?s:[s];let o=s.map(l=>this.processMarkupComment(l)).filter(l=>l);return Array.isArray(o)?o:[o]}getMarkupLabels(t,i){var n;let s;return i==="2.1"&&(s=t.Topic.Labels),i==="3"&&(s=(n=t.Topic.Labels)==null?void 0:n.Label),s?Array.isArray(s)?s:[s]:[]}getMarkupViewpoints(t,i){var n;let s;return i==="2.1"&&(s=t.Viewpoints),i==="3"&&(s=(n=t.Topic.Viewpoints)==null?void 0:n.ViewPoint),s?(s=Array.isArray(s)?s:[s],s):[]}getMarkupRelatedTopics(t,i){var n;let s;return i==="2.1"&&(s=t.Topic.RelatedTopic),i==="3"&&(s=(n=t.Topic.RelatedTopics)==null?void 0:n.RelatedTopic),s?(Array.isArray(s)?s:[s]).map(r=>r.Guid):[]}getMarkupDocumentReferences(t,i){var n;let s;return i==="2.1"&&(s=t.Topic.DocumentReference),i==="3"&&(s=(n=t.Topic.DocumentReferences)==null?void 0:n.DocumentReference),s?Array.isArray(s)?s:[s]:[]}async load(t){var i,n,s;let{fallbackVersionOnImport:o,ignoreIncompleteTopicsOnImport:r,updateExtensionsOnImport:l}=this.config,a=new CAe;await a.loadAsync(t);let u=Object.values(a.files),h=o,p=u.find(_=>_.name.endsWith(".version"));if(p){let _=await p.async("string"),x=qY.xmlParser.parse(_).Version.VersionId;h=String(x)}if(!(h&&(h==="2.1"||h==="3")))throw new Error(`BCFTopics: ${h} is not supported.`);let m=u.find(_=>_.name.endsWith(".extensions"));if(l&&m){let _=await m.async("string");Dxe(this,_)}let I=[],g=this.components.get(LS),E=u.filter(_=>_.name.endsWith(".bcfv"));for(let _ of E){let x=await _.async("string"),M=qY.xmlParser.parse(x).VisualizationInfo;if(!M){console.warn("Missing VisualizationInfo in Viewpoint");continue}let W={},{Guid:G,ClippingPlanes:$,Components:Y,OrthogonalCamera:se,PerspectiveCamera:pe}=M;if(G&&(W.guid=G),Y){let fe={selection:[],coloring:[],visibility:{default_visibility:!1,exceptions:[],view_setup_hints:{spaces_visible:!1,space_boundaries_visible:!1,openings_visible:!1}}};W.components=fe;let{Selection:Q,Visibility:Te}=Y;if(Q&&Q.Component){let pt=Array.isArray(Q.Component)?Q.Component:[Q.Component];fe.selection=pt.map(Me=>Me.IfcGuid?{ifc_guid:Me.IfcGuid}:null).filter(Me=>Me!==null)}if(Te&&"DefaultVisibility"in Te&&(fe.visibility.default_visibility=Te.DefaultVisibility),Te&&Te.Exceptions&&"Component"in Te.Exceptions){let{Component:pt}=Te.Exceptions,Me=Array.isArray(pt)?pt:[pt];fe.visibility.exceptions=Me.map(He=>He.IfcGuid?{ifc_guid:He.IfcGuid}:null).filter(He=>He!==null)}let Ve;h==="2.1"&&(Ve=Y.ViewSetupHints),h==="3"&&(Ve=(i=Y.Visibility)==null?void 0:i.ViewSetupHints),Ve&&("OpeningsVisible"in Ve&&(fe.visibility.view_setup_hints.openings_visible=Ve.OpeningsVisible),"SpacesVisible"in Ve&&(fe.visibility.view_setup_hints.spaces_visible=Ve.SpacesVisible),"SpaceBoundariesVisible"in Ve&&(fe.visibility.view_setup_hints.space_boundaries_visible=Ve.SpaceBoundariesVisible));let{Coloring:Fe}=Y;if(Fe&&Fe.Color){let pt=Array.isArray(Fe.Color)?Fe.Color:[Fe.Color];for(let Me of pt){let{Color:He,Component:Ye}=Me;if(!(He.length===6||He.length===8))continue;let We=He.length===6?He:He.slice(2),xt=(Array.isArray(Ye)?Ye:[Ye]).map(wt=>wt.IfcGuid?{ifc_guid:wt.IfcGuid}:null).filter(wt=>wt!==null);fe.coloring.push({color:We,components:xt})}}}if(se||pe){let fe=M.PerspectiveCamera??M.OrthogonalCamera,{CameraViewPoint:Q,CameraDirection:Te}=fe,Ve=new ne(Number(Q.X),Number(Q.Z),Number(-Q.Y)),Fe=new ne(Number(Te.X),Number(Te.Z),Number(-Te.Y)),pt={camera_view_point:{x:Ve.x,y:Ve.y,z:Ve.z},camera_direction:{x:Fe.x,y:Fe.y,z:Fe.z},aspect_ratio:"AspectRatio"in fe?fe.AspectRatio:1,camera_up_vector:{x:0,y:0,z:0}};"ViewToWorldScale"in fe&&(W.orthogonal_camera={...pt,view_to_world_scale:fe.ViewToWorldScale}),"FieldOfView"in fe&&(W.perspective_camera={...pt,field_of_view:fe.FieldOfVi
<Component IfcGuid="${m}" ${g??""} />`}}}else o=[...this.selectionComponents].map(r=>`<Component IfcGuid="${r}" />`).join(`
`);return o}createColorTags(){let t="";for(let[i,n]of this.componentColors.entries()){let s=n.map(o=>`
<Component IfcGuid="${o}" />`).join(`
`);t+=`<Color Color="${i}">
${s}
</Color>`}return t.length!==0?`<Coloring>
${t}
</Coloring>`:"<Coloring />"}toJSON(){let t=this._components.get(EP),i={guid:this.guid,components:{selection:[...this.selectionComponents].map(o=>({ifc_guid:o,authoring_tool_id:null})),coloring:[...this.componentColors].map(([o,r])=>({color:o,components:r.map(l=>({ifc_guid:l,authoring_tool_id:null}))})),visibility:{default_visibility:this.defaultVisibility,exceptions:[...this.exceptionComponents].map(o=>({ifc_guid:o,authoring_tool_id:null})),view_setup_hints:{spaces_visible:this.spacesVisible,space_boundaries_visible:this.spaceBoundariesVisible,openings_visible:this.openingsVisible}}},clipping_planes:[...this.clippingPlanes].map(o=>{let r=t.list.get(o);if(!r)return null;let l=r._controls.worldPosition??r.origin,{normal:a}=r;return{location:{x:l.x,y:-l.z,z:l.y},direction:{x:a.x,y:-a.z,z:a.y}}}).filter(o=>o!==null)};"field_of_view"in this.camera?i.perspective_camera=this.camera:i.orthogonal_camera=this.camera;let n=this._components.get(LS),s=n.snapshots.get(this.snapshot);if(s){let o=s.toString(),r=btoa(o),l=n.getSnapshotExtension(this.snapshot);i.snapshot={snapshot_type:l,snapshot_data:r}}return i}async serialize(t=this._managerVersion){let i=this._components.get(ro),n=this.position;n.applyMatrix4(i.baseCoordinationMatrix.clone().invert());let s=this.direction;s.normalize();let o=new di().makeRotationX(Math.PI/2),r=s.clone().applyMatrix4(o);r.normalize();let l=`<CameraViewPoint>
<X>${n.x}</X>
<Y>${-n.z}</Y>
<Z>${n.y}</Z>
</CameraViewPoint>`,a=`<CameraDirection>
<X>${s.x}</X>
<Y>${-s.z}</Y>
<Z>${s.y}</Z>
</CameraDirection>`,u=`<CameraUpVector>
<X>${r.x}</X>
<Y>${-r.z}</Y>
<Z>${r.y}</Z>
</CameraUpVector>`,h=`<AspectRatio>${this.camera.aspect_ratio}</AspectRatio>`,p="";"view_to_world_scale"in this.camera?p=`<OrthogonalCamera>
${l}
${a}
${u}
${h}
<ViewToWorldScale>${this.camera.view_to_world_scale}</ViewToWorldScale>
</OrthogonalCamera>`:"field_of_view"in this.camera&&(p=`<PerspectiveCamera>
${l}
${a}
${u}
${h}
<FieldOfView>${this.camera.field_of_view}</FieldOfView>
</PerspectiveCamera>`);let m=`<ViewSetupHints SpacesVisible="${this.spacesVisible??!1}" SpaceBoundariesVisible="${this.spaceBoundariesVisible??!1}" OpeningsVisible="${this.openingsVisible??!1}" />`,I=(await this.createComponentTags("selection")).trim(),g=(await this.createComponentTags("exception")).trim(),E=this.createColorTags();return`<?xml version="1.0" encoding="UTF-8"?>
<VisualizationInfo Guid="${this.guid}">
<Components>
${t==="2.1"?m:""}
${I.length!==0?`<Selection>${I}</Selection>`:""}
<Visibility DefaultVisibility="${this.defaultVisibility}">
${t==="3"?m:""}
${g.length!==0?`<Exceptions>${g}</Exceptions>`:""}
</Visibility>
${E}
</Components>
${p}
</VisualizationInfo>`}},iye=class extends UD{constructor(){super(...arguments),ze(this,"_config",{overwriteColors:{value:!1,type:"Boolean"}})}get overwriteColors(){return this._config.overwriteColors.value}set overwriteColors(t){this._config.overwriteColors.value=t}},Oxe=class nye extends Ra{constructor(t){super(t),ze(this,"enabled",!0),ze(this,"world",null),ze(this,"list",new Ln),ze(this,"snapshots",new Ln),ze(this,"isSetup",!1),ze(this,"onSetup",new rn),ze(this,"config",new iye(this,this.components,"Viewpoints",nye.uuid)),ze(this,"onDisposed",new rn),t.add(nye.uuid,this)}create(t){let i=new XY(this.components,t);return i.world=this.world,t||this.list.set(i.guid,i),i}getSnapshotExtension(t){let i="jpeg",n=this.snapshots.get(t);if(!n)return i;let s=n.subarray(0,4),o="";for(let r=0;r<s.length;r++)o+=s[r].toString(16);return o.startsWith("89504e47")&&(i="png"),o.startsWith("ffd8ffe")&&(i="jpeg"),i}setup(){}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}};ze(Oxe,"uuid","ee867824-a796-408d-8aa0-4e5962a83c66");var LS=Oxe,eq=class{constructor(t,i){ze(this,"_components"),ze(this,"_cameraOffset",10),ze(this,"_planeHelper"),ze(this,"_farPlaneHelper"),ze(this,"_cameraHelper"),ze(this,"onStateChanged",new rn),ze(this,"onUpdated",new rn),ze(this,"onDisposed",new rn),ze(this,"camera"),ze(this,"plane",new Nn),ze(this,"farPlane",new Nn),ze(this,"id",wI.create()),ze(this,"_open",!1),ze(this,"_range",Pxe.defaultRange),ze(this,"_world",null),ze(this,"_helpersVisible",!1),ze(this,"_planesEnabled",!1),this._components=t,this.camera=new fU(this._components);let{threeOrtho:n}=this.camera;if(i?.id&&(this.id=i.id),i?.normal&&i?.point){let{normal:s,point:o}=i;this.plane.setFromNormalAndCoplanarPoint(s,o)}this._cameraHelper=new Zx(n),this._planeHelper=new Bv(this.plane,50),this._farPlaneHelper=new Bv(this.farPlane,50),this.farPlaneHelperColor=new Ei("blue"),this.update()}get _planeNormalOpposite(){return this.plane.normal.clone().negate()}get _planePosition(){return this.plane.normal.clone().multiplyScalar(-this.plane.constant)}get _cameraPosition(){return this._planePosition.addScaledVector(this._planeNormalOpposite,this._cameraOffset)}set open(t){this._open=t,this.onStateChanged.trigger(["open"])}get open(){return this._open}set planeHelperColor(t){!Array.isArray(this._planeHelper.material)&&"color"in this._planeHelper.material&&this._planeHelper.material.color instanceof Ei&&(this._planeHelper.material.color=t)}set farPlaneHelperColor(t){!Array.isArray(this._farPlaneHelper.material)&&"color"in this._farPlaneHelper.material&&this._farPlaneHelper.material.color instanceof Ei&&(this._farPlaneHelper.material.color=t)}set range(t){this._range=t,this.update()}get range(){return this._range}set distance(t){this.plane.constant=t,this.update()}get distance(){return this.plane.constant}set world(t){this._world=t,this.camera.currentWorld=t,t&&(this.camera.projection.set("Orthographic"),this.camera.set("Plan"),this.camera.controls.dollySpeed=6,this.camera.controls.restThreshold=.005,this.update())}get world(){return this._world}set helpersVisible(t){if(!t){this._helpersVisible=t,this._planeHelper.removeFromParent(),this._farPlaneHelper.removeFromParent(),this._cameraHelper.removeFromParent();return}this.world&&(this._helpersVisible=t,this.world.scene.three.add(this._planeHelper,this._farPlaneHelper))}get helpersVisible(){return this._helpersVisible}set planesEnabled(t){let{world:i}=this;if(!i)return;let{renderer:n}=i;n&&(n.setPlane(t,this.plane),n.setPlane(t,this.farPlane),this._planesEnabled=t)}get planesEnabled(){return this._planesEnabled}dispose(){this.helpersVisible=!1;let t=this._components.get(IU);t.destroy(this._planeHelper),t.destroy(this._farPlaneHelper),t.destroy(this._cameraHelper),this.camera.dispose(),this.onDisposed.trigger()}update(){if(this.world){let t=this._cameraPosition,i=this._planePosition;this.camera.controls.setLookAt(t.x,t.y,t.z,i.x,i.y,i.z,!1)}this.farPlane.normal.copy(this._planeNormalOpposite),this.farPlane.constant=this.range-this.plane.constant,this.onUpdated.trigger()}flip(){this.plane.
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,fragmentShader:`
#include <packing>
varying vec2 vUv;
uniform sampler2D tDiffuse;
uniform sampler2D tDepth;
uniform float cameraNear;
uniform float cameraFar;
float readDepth( sampler2D depthSampler, vec2 coord ) {
float fragCoordZ = texture2D( depthSampler, coord ).x;
float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
}
void main() {
//vec3 diffuse = texture2D( tDiffuse, vUv ).rgb;
float depth = readDepth( tDepth, vUv );
gl_FragColor.rgb = 1.0 - vec3( depth );
gl_FragColor.a = 1.0;
}
`,uniforms:{cameraNear:{value:n.near},cameraFar:{value:n.far},tDiffuse:{value:null},tDepth:{value:null}}});let s=new bu(2,2);this._postQuad=new ci(s,this.depthMaterial),this.scene.add(this._postQuad);let o=`
addEventListener("message", (event) => {
const { buffer } = event.data;
const colors = new Set();
for (let i = 0; i < buffer.length; i += 4) {
const r = buffer[i];
colors.add(r);
}
postMessage({ colors });
});
`,r=new Blob([o],{type:"application/javascript"});this.worker=new Worker(URL.createObjectURL(r)),this.worker.addEventListener("message",this.handleWorkerMessage)}dispose(){this.enabled=!1,this.onDistanceComputed.reset(),this.worker.terminate(),this.tempRT.dispose(),this.resultRT.dispose();let t=[...this.scene.children];this.excludedObjects.clear();for(let i of t)i.removeFromParent();this._postQuad.geometry.dispose(),this._postQuad.removeFromParent(),this._buffer=null,this.onDisposed.reset()}},oye=class extends $te{constructor(){super(...arguments),ze(this,"_distanceRenderer"),ze(this,"autoBias",!0),ze(this,"_defaultShadowConfig",{cascade:1,resolution:512}),ze(this,"_lightsWithShadow",new Map),ze(this,"_isComputingShadows",!1),ze(this,"_shadowsEnabled",!0),ze(this,"_bias",0),ze(this,"recomputeShadows",t=>{if(!this._shadowsEnabled)return;if(this.autoBias&&(this.bias=-.005),t*=1.5,!this.currentWorld)throw new Error("A world needs to be assigned to the scene before computing shadows!");if(!this._lightsWithShadow.size)throw new Error("No shadows found!");let n=this.currentWorld.camera.three;if(!(n instanceof Wo)&&!(n instanceof gr))throw new Error("Invalid camera type!");let s=new ne;n.getWorldDirection(s);let o=t,r=new ne;r.copy(this.config.directionalLight.position),r.normalize();for(let[l,a]of this._lightsWithShadow){let u=this.directionalLights.get(a);if(!u)throw new Error("Light not found.");let h=new ne;h.copy(s);let p=l===this._lightsWithShadow.size-1,m=p?o/2:o*2/3;h.multiplyScalar(m),h.add(n.position);let I=o-m,g=new ne;g.copy(r),g.multiplyScalar(I),u.target.position.copy(h),u.position.copy(h),u.position.add(g),u.shadow.camera.right=I,u.shadow.camera.left=-I,u.shadow.camera.top=I,u.shadow.camera.bottom=-I,u.shadow.camera.far=I*2,u.shadow.camera.updateProjectionMatrix(),u.shadow.camera.updateMatrix(),p||(o/=3)}this._isComputingShadows=!1})}get bias(){return this._bias}set bias(t){this._bias=t;for(let[,i]of this._lightsWithShadow){let n=this.directionalLights.get(i);n&&(n.shadow.bias=t)}}get shadowsEnabled(){return this._shadowsEnabled}set shadowsEnabled(t){this._shadowsEnabled=t;for(let[,i]of this.directionalLights)i.castShadow=t}get distanceRenderer(){if(!this._distanceRenderer)throw new Error("You must set up this component before accessing the distance renderer!");return this._distanceRenderer}setup(t){super.setup(t);let i={...this._defaultConfig,...this._defaultShadowConfig,...t};if(i.cascade<=0)throw new Error("Config.shadows.cascade must be a natural number greater than 0!");if(i.cascade>1)throw new Error("Multiple shadows not supported yet!");if(!this.currentWorld)throw new Error("A world needs to be assigned to the scene before setting it up!");for(let[,n]of this.directionalLights)n.target.removeFromParent(),n.removeFromParent(),n.dispose();this.directionalLights.clear(),this._distanceRenderer||(this._distanceRenderer=new sye(this.components,this.currentWorld),this._distanceRenderer.onDistanceComputed.add(this.recomputeShadows)),this._lightsWithShadow.clear();for(let n=0;n<i.cascade;n++){let s=new Mv;s.intensity=this.config.directionalLight.intensity,s.color=this.config.directionalLight.color,s.position.copy(this.config.directionalLight.position),s.shadow.mapSize.width=i.resolution,s.shadow.mapSize.height=i.resolution,this.three.add(s,s.target),this.directionalLights.set(s.uuid,s),this._lightsWithShadow.set(n,s.uuid),s.castShadow=!0,s.shadow.bias=this._bias}}dispose(){super.dispose(),this._distanceRenderer&&this._distanceRenderer.dispose(),this._lightsWithShadow.clear()}async updateShadows(){this._isComputingShadows||!this._shadowsEnabled||(this._isComputingShadows=!0,await this.distanceRenderer.compute())}},Qb=class{constructor(t){ze(this,"cardinality","required"),ze(this,"instructions"),ze(this,"evalRequirement",(i,n,s,o)=>{let r={parameter:s,currentValue:i,requiredValue:n,pass:!1};o&&this.addCheckResult(r,o);let l=!1;if(n.type==="simple"&&(l=i===n.parameter),n.type==="enumeration"&&(l=n.parameter.includes(i)),n.type==="pattern"&&(l=new RegExp(n.parameter).test(String(i))),n.type==="length"){let{min:a,le
${t.parameter.map(o=>`<xs:enumeration value="${o}" />`).join(`
`)}
</xs:restriction>`),t.type==="pattern"&&(i=`<xs:restriction base="xs:string">
<xs:pattern value="${t.parameter}" />
</xs:restriction>`),t.type==="bounds"){let{min:s,minInclusive:o,max:r,maxInclusive:l}=t.parameter,a="";s!==void 0&&(a=`<xs:min${o?"Inclusive":"Exclusive"} value="${s}">`);let u="";r!==void 0&&(u=`<xs:max${l?"Inclusive":"Exclusive"} value="${r}">`),i=`<xs:restriction base="xs:double">
${a}
${u}
</xs:restriction>`}if(t.type==="length"){let{length:s,min:o,max:r}=t.parameter,l="";s!==void 0&&o===void 0&&r===void 0&&(l=`<xs:length value="${s}" />`);let a="";o!==void 0&&s===void 0&&(a=`<xs:minLength value="${o}" />`);let u="";r!==void 0&&s===void 0&&(u=`<xs:maxLength value="${r}" />`),i=`<xs:restriction base="xs:string">
${l}
${a}
${u}
</xs:restriction>`}return`<${e[0].toLowerCase()+e.slice(1)}>
${i}
</${e[0].toLowerCase()+e.slice(1)}>`},nie=class extends Qb{constructor(t,i){super(t),ze(this,"facetType","Attribute"),ze(this,"name"),ze(this,"value"),this.name=i}serialize(t){let i=PS("Name",this.name),n=PS("Value",this.value),s="";return t==="requirement"&&(s+=`cardinality="${this.cardinality}"`,s+=this.instructions?`instructions="${this.instructions}"`:""),`<attribute ${s}>
${i}
${n}
</attribute>`}async getEntities(){}async test(t,i,n={skipIfFails:!0}){let s=this._components.get(ro);for(let[o,r]of Object.entries(t)){let l=s.list.get(o);if(!l)continue;let a=await l.getItemsData([...r]);for(let u of a){let h=this.getItemChecks(i,o,u,n.skipIfFails);if(!h)continue;let m=Object.keys(u).filter(g=>{let E=this.evalRequirement(g,this.name,"Name");if(!E)return!1;let w=u[g];return Array.isArray(w)?!0:w===null||w.value===null?this.cardinality==="optional"||this.cardinality==="prohibited":Array.isArray(w.value)&&w.value.length===0||typeof w.value=="string"&&w.value.trim()===""?!1:E}),I=m.length>0;if(h.push({parameter:"Name",currentValue:I?m[0]:null,requiredValue:this.name,pass:this.cardinality==="prohibited"?!I:I}),this.value)if(m[0]){let g=u[m[0]];Array.isArray(g)?h.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:this.cardinality==="prohibited"}):Array.isArray(g.value)?h.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:this.cardinality==="prohibited"}):this.evalRequirement(g.value,this.value,"Value",h)}else h.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:this.cardinality==="prohibited"})}}}},sie=class extends Qb{constructor(t,i){super(t),ze(this,"facetType","Classification"),ze(this,"system"),ze(this,"value"),ze(this,"uri"),this.system=i}serialize(t){let i=PS("System",this.system),n=PS("Value",this.value),s="";return t==="requirement"&&(s+=`cardinality="${this.cardinality}"`,s+=this.uri?`uri=${this.uri}`:"",s+=this.instructions?`instructions="${this.instructions}"`:""),`<classification ${s}>
${i}
${n}
</classification>`}async getEntities(t,i){}async test(t,i){}},mU=class extends Qb{constructor(t,i){super(t),ze(this,"facetType","Entity"),ze(this,"name"),ze(this,"predefinedType"),this.name=i}serialize(t){let i=PS("Name",this.name),n=PS("Name",this.predefinedType),s="";return t==="requirement"&&(s+=`cardinality="${this.cardinality}"`,s+=this.instructions?`instructions="${this.instructions}"`:""),`<entity ${s}>
${i}
${n}
</entity>`}async getEntities(t,i){let n=this._components.get(ro),s=new Map;for(let[r,l]of n.list){if(!t.find(h=>h.test(r)))continue;let u=await l.getCategories();for(let h of u){if(!await this.evalName(h))continue;let m=s.get(r);m||(m=[],s.set(r,m)),m.push(h)}}let o={};if(await Promise.all(Array.from(s.entries()).map(async([r,l])=>{let a=n.list.get(r);if(!a)return;let u=l.map(m=>new RegExp(`^${m}$`)),h=await a.getItemsOfCategories(u),p=Object.values(h).flat();o[r]=new Set(p)})),!this.predefinedType){Jf.add(i,o);return}for(let[r,l]of Object.entries(o)){let a=n.list.get(r);if(!a)continue;let u=await a.getItemsData([...l]);for(let h of u){if(!("value"in h._localId))continue;await this.evalPredefinedType(r,h)&&Jf.append(i,r,h._localId.value)}}}async test(t,i,n){let s=this._components.get(ro);for(let[o,r]of Object.entries(t)){let l=s.list.get(o);if(!l)continue;let a=await l.getItemsData([...r]);for(let u of a){if(!("value"in u._category))continue;let h=this.getItemChecks(i,o,u,n.skipIfFails);h&&(await this.evalName(u._category.value,h),await this.evalPredefinedType(o,u,h))}}}async evalName(t,i){return this.evalRequirement(t,this.name,"Name",i)}async evalPredefinedType(t,i,n){if(!this.predefinedType||!("value"in i.PredefinedType))return null;let s=typeof this.predefinedType.parameter=="string"&&this.predefinedType.parameter==="USERDEFINED",o=i.PredefinedType.value;if(o==="USERDEFINED"&&!s){let a=Object.keys(i).find(u=>/^((?!Predefined).)*Type$/.test(u));if(a){let u=i[a];"value"in u&&(o=u.value)}else o="USERDEFINED"}if(!o){let a=this._components.get(ro).list.get(t);if(a&&"value"in i._localId){let[u]=await a.getItemsData([i._localId.value],{relations:{IsTypedBy:{attributes:!0,relations:!1}}});if(Array.isArray(u.IsTypedBy)){let h=u.IsTypedBy[0];if(h&&"value"in h.PredefinedType&&(o=h.PredefinedType.value,o==="USERDEFINED"&&!s)){let m=Object.keys(h).find(I=>/^((?!Predefined).)*Type$/.test(I));if(m){let I=h[m];"value"in I&&(o=I.value)}else o="USERDEFINED"}}}}return this.evalRequirement(o,this.predefinedType,"PredefinedType",n)}},oie=class extends Qb{constructor(t,i,n){super(t),ze(this,"facetType","Property"),ze(this,"propertySet"),ze(this,"baseName"),ze(this,"value"),ze(this,"dataType"),ze(this,"uri"),ze(this,"_unsupportedTypes",["IFCCOMPLEXPROPERTY","IFCPHYSICALCOMPLEXQUANTITY"]),this.propertySet=i,this.baseName=n}serialize(t){let i=PS("PropertySet",this.propertySet),n=PS("BaseName",this.baseName),s=PS("Value",this.value),o=this.dataType?`dataType=${this.dataType}`:"",r="";return t==="requirement"&&(r+=`cardinality="${this.cardinality}"`,r+=this.uri?`uri=${this.uri}`:"",r+=this.instructions?`instructions="${this.instructions}"`:""),`<property ${o} ${r}>
${i}
${n}
${s}
</property>`}async getEntities(t,i){let n=this._components.get(ro);for(let[s,o]of n.list){if(!t.find(h=>h.test(s)))continue;let l=await o.getItemsOfCategories([/PROPERTYSET/,/ELEMENTQUANTITY/]),a=Object.values(l).flat();if(a.length===0)continue;let u=await o.getItemsData(a,{relations:{HasProperties:{attributes:!0,relations:!1},DefinesOcurrence:{attributes:!0,relations:!1}}});for(let h of u){if(!("value"in h._localId&&"value"in h._category&&"value"in h.Name&&Array.isArray(h.DefinesOcurrence))||!this.evalRequirement(h.Name.value,this.propertySet,"PropertySet"))continue;let m;if(h._category.value==="IFCPROPERTYSET"&&(m="HasProperties"),h._category.value==="IFCELEMENTQUANTITY"&&(m="Quantities"),!m)continue;let I=h[m];if(Array.isArray(I))for(let g of I){let E=Object.keys(g),w=E.find(x=>/Name/.test(x));if(!(w&&"value"in g[w]))continue;let T=g[w];if(!("value"in T)||!this.evalRequirement(T.value,this.baseName,"BaseName"))continue;if(this.value){let x=E.find(G=>/Value/.test(G));if(!x)continue;let M=g[x];if(!("value"in M)||!this.evalRequirement(M.value,this.value,"Value"))continue}let _=h.DefinesOcurrence.map(x=>"value"in x._localId&&typeof x._localId.value=="number"?x._localId.value:null).filter(x=>x!==null);Jf.append(i,s,..._)}}}}async test(t,i,n={skipIfFails:!0}){let s=this._components.get(ro);for(let[o,r]of Object.entries(t)){let l=s.list.get(o);if(!l)continue;let a=await l.getItemsData([...r],{relations:{IsDefinedBy:{attributes:!0,relations:!0},IsTypedBy:{attributes:!0,relations:!1},HasPropertySets:{attributes:!0,relations:!0},DefinesOcurrence:{attributes:!1,relations:!1}}});for(let u of a){let h=this.getItemChecks(i,o,u,n.skipIfFails);if(!h)continue;let m=(await this.getPsets(u)).filter(I=>!("value"in I.Name)||!this.evalRequirement(I.Name.value,this.propertySet,"PropertySet")?!1:(h.push({currentValue:I.Name.value,parameter:"PropertySet",pass:!0,requiredValue:this.propertySet}),!0));if(m.length===0){h.push({currentValue:null,parameter:"PropertySet",pass:!1,requiredValue:this.propertySet});continue}for(let I of m){let g=this.getPropertyListName(I);if(!g)continue;let E=I[g];if(!Array.isArray(E)){h.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName});continue}let w=E.filter(T=>!("value"in T._category&&"value"in T.Name)||this._unsupportedTypes.includes(T._category.value)||!this.evalRequirement(T.Name.value,this.baseName,"BaseName")?!1:(h.push({currentValue:T.Name.value,parameter:"BaseName",pass:!0,requiredValue:this.baseName}),!0));if(w.length===0){h.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName});continue}for(let T of w)this.evalValue(T,h),this.evalDataType(T,h),this.evalURI()}}}}getPropertyListName(t){let i;return"value"in t._category&&(t._category.value==="IFCPROPERTYSET"&&(i="HasProperties"),t._category.value==="IFCELEMENTQUANTITY"&&(i="Quantities")),i}getValueKey(t){return Object.keys(t).find(i=>/Value/.test(i)||/Values/.test(i))}getTypePsets(t){if(!Array.isArray(t.IsTypedBy))return[];let[i]=t.IsTypedBy;return i&&Array.isArray(i.HasPropertySets)?i.HasPropertySets:[]}async getPsets(t){let i=this.getTypePsets(t);if(!Array.isArray(t.IsDefinedBy))return i;let n=[];for(let s of t.IsDefinedBy){if(!("value"in s.Name))continue;let o=s.Name.value,r=this.getPropertyListName(s);if(!(o&&r))continue;let l=i.find(a=>"value"in a.Name?a.Name.value===o:!1);if(l&&Array.isArray(l.HasProperties)&&Array.isArray(s.HasProperties))for(let a of l.HasProperties){if(!("value"in a.Name))continue;let u=a.Name.value;s.HasProperties.find(p=>"value"in p.Name?p.Name.value===u:!1)||s.HasProperties.push(a)}n.push(s)}return n}evalValue(t,i){let n=this.getValueKey(t),s=t[n];if(!("value"in s))return!1;if(this.value){if(!n)return i?.push({parameter:"Value",currentValue:null,pass:!1,requiredValue:this.value}),!1;let o=structuredClone(this.value);return s.type==="IFCLABEL"&&o.type==="simple"&&(o.parameter=String(o.parameter)),this.evalRequirement(s.value,o,"Value",i)}return n&&typeof s.value=="string"&&s.value.trim()===""?(i?.push({parameter:"Value",currentValue:"",pass:!1,requiredValue:this.value}),
${i}
</material>`}async getEntities(t,i){let n=this._components.get(ro);for(let[s,o]of n.list){if(!t.find(h=>h.test(s)))continue;let l=await o.getItemsOfCategories(this._ifcMaterialEntities),a=Object.values(l).flat();if(a.length===0)continue;let u=await o.getItemsData(a,{relations:{AssociatedTo:{attributes:!0,relations:!1},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(let h of u){if(!("value"in h._localId&&"value"in h._category&&Array.isArray(h.AssociatedTo))||!this.hasValidMaterial(h))continue;let m=h.AssociatedTo.map(I=>"value"in I._localId&&I._localId.value?I._localId.value:null).filter(I=>I!==null);Jf.append(i,s,...m)}}}async test(t,i,n={skipIfFails:!0}){let s=this._components.get(ro);for(let[o,r]of Object.entries(t)){let l=s.list.get(o);if(!l)continue;let a=await l.getItemsData([[...r][0]],{relations:{AssociatedTo:{attributes:!1,relations:!1},HasAssociations:{attributes:!0,relations:!0},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(let u of a){let h=this.getItemChecks(i,o,u,n.skipIfFails);if(h){if(!Array.isArray(u.HasAssociations)){h.push({parameter:null,currentValue:null,requiredValue:this.value,pass:!1});continue}for(let p of u.HasAssociations){if(!this._ifcMaterialEntities.some(I=>"value"in p._category?I.test(p._category.value):!1))continue;if(this.hasValidMaterial(p,h))break}}}}}hasValidMaterial(t,i){let n=!1;if("value"in t._category&&t._category.value==="IFCMATERIAL")this.evalValue(t,i)&&(n=!0);else for(let[s,o]of Object.entries(t))if(["ForLayerSet","MaterialLayers","Material","MaterialConstituents","Materials"].includes(s)&&Array.isArray(o)){for(let r of o)if("value"in r._category&&r._category.value==="IFCMATERIAL"){if(this.evalValue(r,i)){n=!0;break}}else if(this.hasValidMaterial(r)){n=!0;break}}return n}evalValue(t,i){if(!this.value)return i?.push({parameter:null,currentValue:t.Name&&"value"in t.Name?t.Name.value:null,pass:!0}),!0;if(!("value"in t._category&&t._category.value==="IFCMATERIAL"))return null;let n=!1;return t.Name&&"value"in t.Name&&(n=this.evalRequirement(t.Name.value,this.value,"Value",i)),n||(t.Category&&"value"in t.Category&&(n=this.evalRequirement(t.Category.value,this.value,"Value",i)),n)}},lie=class extends Qb{constructor(t,i){super(t),ze(this,"facetType","PartOf"),ze(this,"_entityFacet"),ze(this,"_entity"),ze(this,"relation"),ze(this,"cardinality","required"),this._entity=i,this._entityFacet=new mU(t,i.name),this._entityFacet.predefinedType=i.predefinedType}set entity(t){this._entity=t;let{name:i,predefinedType:n}=t;this._entityFacet=new mU(this._components,i),this._entityFacet.predefinedType=n}get entity(){return this._entity}serialize(){return""}async getEntities(t,i){}async test(t){}},aie=class{constructor(t,i,n){ze(this,"name"),ze(this,"ifcVersion",new Set),ze(this,"identifier",wI.create()),ze(this,"description"),ze(this,"instructions"),ze(this,"requirementsDescription"),ze(this,"applicability",new Po),ze(this,"requirements",new Po),ze(this,"components"),this.components=t,this.name=i;for(let s of n)this.ifcVersion.add(s)}set(t){let i=t,n=this;for(let o in t){if(o==="identifier")continue;let r=i[o];o in this&&(n[o]=r)}return this.components.get(Mxe).list.set(this.identifier,this),this}async test(t,i={skipIfFails:!0}){let n=new Ln;if(this.requirements.size===0)return n;let s={},o=[];for(let l of this.applicability)o.push(l.getEntities(t,s));await Promise.all(o);let r=[];for(let l of this.requirements)r.push(l.test(s,n,i));return await Promise.all(r),n}serialize(){let t=`name="${this.name}"`,i=this.identifier?`identifier="${this.identifier}"`:"",n=this.description?`description="${this.description}"`:"",s=this.instructions?`instructions="${this.instructions}"`:"";return`<specification ifcVersion="${[...this.ifcVersion].join(" ")}" ${t} ${i} ${n} ${s}>
<applicability minOccurs="1" maxOccurs="unbounded">
${[...this.applicability].map(r=>r.serialize("applicability")).join(`
`)}
</applicability>
<requirements>
${[...this.requirements].map(r=>r.serialize("requirement")).join(`
`)}
</requirements>
</specification>`}},zE=e=>{if(!e)return;let t={};if("simpleValue"in e&&(t.type="simple",t.parameter=e.simpleValue),"restriction"in e){let i=e.restriction,n=Object.keys(i);if("pattern"in i&&(t.type="pattern",t.parameter=i.pattern.value),"enumeration"in i){t.type="enumeration";let s=i.enumeration.map(({value:o})=>i.base.includes("string")?String(o):i.base.includes("integer")||i.base.includes("double")?Number(o):o);t.parameter=s}if(n.some(s=>["minInclusive","minExclusive","maxInclusive","maxExclusive"].includes(s))){t.type="bounds";let s={},o=n.find(l=>l.includes("min")),r=n.find(l=>l.includes("max"));o&&(s.minInclusive=o==="minInclusive",s.min=i[o].value),r&&(s.maxInclusive=r==="maxInclusive",s.max=i[r].value),t.parameter=s}if(n.some(s=>["minLength","length","maxLength"].includes(s))){t.type="length";let s={};i.length!==void 0&&(s.length=i.length.value),i.minLength!==void 0&&(s.min=i.minLength.value),i.maxLength!==void 0&&(s.max=i.maxLength.value),t.parameter=s}}if(t.parameter!==void 0)return t},DAe=(e,t)=>{let i=[];for(let n of t){let s=n.name,o=zE(s);if(!o)continue;let r=new mU(e,o);n.cardinality&&(r.cardinality=n.cardinality),r.predefinedType=zE(n.predefinedType),r.instructions=n.instructions,i.push(r)}return i},NAe=(e,t)=>{let i=[];for(let n of t){let s=n.name,o=zE(s);if(!o)continue;let r=new nie(e,o);n.cardinality&&(r.cardinality=n.cardinality),r.value=zE(n.value),r.instructions=n.instructions,i.push(r)}return i},OAe=(e,t)=>{let i=[];for(let n of t){let s=new rie(e);n.cardinality&&(s.cardinality=n.cardinality);let o=zE(n.value);o?.type==="enumeration"&&Array.isArray(o.parameter)&&(o.parameter=o.parameter.map(String)),s.value=o,s.uri=n.uri,s.instructions=n.instructions,i.push(s)}return i},LAe=(e,t)=>{let i=[];for(let n of t){let s=n.propertySet,o=n.baseName,r=zE(s),l=zE(o);if(!(l&&r))continue;let a=new oie(e,r,l);n.cardinality&&(a.cardinality=n.cardinality);let u=zE(n.value);a.value=u,a.dataType=n.dataType,a.uri=n.uri,a.instructions=n.instructions,i.push(a)}return i},PAe=(e,t)=>{let i=[];for(let n of t){let s=n.system,o=zE(s);if(!o)continue;let r=new sie(e,o);n.cardinality&&(r.cardinality=n.cardinality);let l=zE(n.value);l?.type==="simple"&&(l.parameter=String(l.parameter)),l?.type==="enumeration"&&Array.isArray(l.parameter)&&(l.parameter=l.parameter.map(String)),r.value=l,r.uri=n.uri,r.instructions=n.instructions,i.push(r)}return i},MAe=(e,t)=>{let i=[];for(let n of t){let s=zE(n.entity.name);if(!s)continue;let o=zE(n.entity.predefinedType),r=new lie(e,{name:s,predefinedType:o});r.relation=n.relation,n.cardinality&&(r.cardinality=n.cardinality),r.instructions=n.instructions,i.push(r)}return i},vye=class rye extends Ra{constructor(t){super(t),ze(this,"enabled",!0),ze(this,"IDSInfo"),ze(this,"list",new Ln),t.add(rye.uuid,this)}getModelIdMap(t){let i={},n={};for(let[s,o]of t){let l=[...o].filter(([,h])=>h.pass).map(([h])=>h);Jf.append(i,s,...l);let u=[...o].filter(([,h])=>!h.pass).map(([h])=>h);Jf.append(n,s,...u)}return{pass:i,fail:n}}create(t,i,n){let s=new aie(this.components,t,i);return n&&(s.identifier=n),this.list.set(s.identifier,s),s}load(t){let i=[],n=rye.xmlParser.parse(t).ids,{specifications:s,info:o}=n;if(this.IDSInfo={...o},s&&s.specification){let r=Array.isArray(s.specification)?s.specification:[s.specification];for(let l of r){let{name:a,ifcVersion:u,description:h,instructions:p,identifier:m}=l;if(!(a&&u))continue;let I=[],g=[],{applicability:E,requirements:w}=l;if(E){let{maxOccurs:_,...x}=E,M=Array.isArray(x)?x:[x];for(let W of M)for(let G in W){let $=Array.isArray(W[G])?W[G]:[W[G]];if(G==="entity"){let Y=DAe(this.components,$);I.push(...Y)}if(G==="attribute"){let Y=NAe(this.components,$);I.push(...Y)}if(G==="material"){let Y=OAe(this.components,$);I.push(...Y)}if(G==="classification"){let Y=PAe(this.components,$);I.push(...Y)}if(G==="property"){let Y=LAe(this.components,$);I.push(...Y)}if(G==="partOf"){let Y=MAe(this.components,$);I.push(...Y)}}}let T;if(w){let{maxOccurs:_,...x}=w;T=w.description;let M=Array.isArray(x)?x:[x];for(let W of M)for(let G in W){let $=Array.isArray(W[G])?W[G]:[W[G]];if(G==
<!-- Made with That Open Engine ${Eye.release} (https://github.com/thatopen/engine_components) -->
<info>
<title>${t.title}</title>
${t.copyright?`<copyright>${t.copyright}</copyright>`:""}
${t.version?`<version>${t.version}</version>`:""}
${t.description?`<description>${t.description}</description>`:""}
${t.author?`<author>${t.author}</author>`:""}
${t.date?`<date>${t.date.toISOString().split("T")[0]}</date>`:""}
${t.purpose?`<purpose>${t.purpose}</purpose>`:""}
${t.milestone?`<milestone>${t.milestone}</milestone>`:""}
</info>
<specifications>
${[...n].map(o=>o.serialize()).join(`
`)}
</specifications>
</ids>`}};ze(vye,"uuid","9f0b9f78-9b2e-481a-b766-2fbfd01f342c");ze(vye,"xmlParser",new KY({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0}));var Mxe=vye,Bxe=class Fxe extends Ra{constructor(t){super(t),ze(this,"enabled",!0),t.add(Fxe.uuid,this)}static distanceFromPointToLine(t,i,n,s=!1){let o=new wn,r=new ne;return o.set(i,n),o.closestPointToPoint(t,s,r),r.distanceTo(t)}round(t){t.x=Math.trunc(t.x*1e3)/1e3,t.y=Math.trunc(t.y*1e3)/1e3,t.z=Math.trunc(t.z*1e3)/1e3}async getVolumeFromFragments(t){return console.warn("getVolumeFromFragments is deprecated. Use getItemsVolume instead."),this.getItemsVolume(t)}async getItemsVolume(t){let i=0,n=this.components.get(ro);for(let[s,o]of Object.entries(t)){let r=n.list.get(s);r&&(i+=await r.getItemsVolume([...o]))}return i}static convertUnits(t,i,n,s=2){let o={m:1,cm:.01,mm:.001,km:1e3,m2:1,cm2:1e-4,mm2:1e-6,km2:1e6,m3:1,cm3:1e-6,mm3:1e-9,km3:1e9};if(!o[i]||!o[n])throw new Error("Invalid units provided for conversion.");if(!Number.isInteger(s)||s<0||s>5)throw new Error("Precision must be an integer between 0 and 5.");let r=o[i]/o[n],l=t*r,a=10**s;return Math.round(l*a)/a}};ze(Bxe,"uuid","267ca032-672f-4cb0-afa9-d24e904f39d6");var ast=Bxe,Sye=(e,t,i)=>{let n=new ne(-t.z,0,t.x),s=new ne(t.x+n.x,0,t.z+n.z).normalize().multiplyScalar(i/2);return[e.x+s.x,e.y,e.z+s.z,e.x-s.x,e.y,e.z-s.z]},ust=(e,t,i)=>{let n=new ne(-t.z,0,t.x),s=e.x-t.x*i+n.x*i*.4,o=e.z-t.z*i+n.z*i*.4,r=e.x-t.x*i-n.x*i*.4,l=e.z-t.z*i-n.z*i*.4;return[e.x,e.y,e.z,s,e.y,o,e.x,e.y,e.z,r,e.y,l,s,e.y,o,r,e.y,l]},Rye=(e,t,i)=>{let n=new ne(-t.z,0,t.x),s=e.x-t.x*i+n.x*i*.4,o=e.z-t.z*i+n.z*i*.4,r=e.x-t.x*i-n.x*i*.4,l=e.z-t.z*i-n.z*i*.4;return[e.x,e.y,e.z,s,e.y,o,e.x,e.y,e.z,r,e.y,l]},Uxe=()=>[],cst=(e,t,i)=>{let n=i*.4,s=12,o=[];for(let r=0;r<s;r++){let l=r/s*Math.PI*2,a=(r+1)/s*Math.PI*2;o.push(e.x+Math.cos(l)*n,e.y,e.z+Math.sin(l)*n,e.x+Math.cos(a)*n,e.y,e.z+Math.sin(a)*n)}return o},dst=(e,t,i)=>{let n=i*.4,s=16,o=[];for(let r=0;r<s;r++){let l=r/s*Math.PI*2,a=(r+1)/s*Math.PI*2;o.push(e.x,e.y,e.z,e.x+Math.cos(l)*n,e.y,e.z+Math.sin(l)*n,e.x+Math.cos(a)*n,e.y,e.z+Math.sin(a)*n)}return o},hst=(e,t,i)=>{let n=new ne(-t.z,0,t.x),s=i*.4,o=e.clone().addScaledVector(t,s).addScaledVector(n,s),r=e.clone().addScaledVector(t,s).addScaledVector(n,-s),l=e.clone().addScaledVector(t,-s).addScaledVector(n,-s),a=e.clone().addScaledVector(t,-s).addScaledVector(n,s);return[o.x,o.y,o.z,r.x,r.y,r.z,l.x,l.y,l.z,o.x,o.y,o.z,l.x,l.y,l.z,a.x,a.y,a.z]},Hxe=(e,t,i)=>{let n=new ne(-t.z,0,t.x),s=e.clone().addScaledVector(t,-i),o=s.clone().addScaledVector(n,i*.4),r=s.clone().addScaledVector(n,-i*.4);return[e.x,e.y,e.z,o.x,o.y,o.z,r.x,r.y,r.z]},uie=class extends Ln{constructor(){super()}getBySystem(t){let i=new Map;for(let[n,s]of this)s.system===t&&i.set(n,s.data);return i}},cie=class extends Ln{constructor(t){super(),ze(this,"_container"),this._container=t,this.deleteGuard=i=>i!=="0",this.set("0",{name:"0",visible:!0,material:new qs({color:0})})}create(t,i){if(!this.has(t)){let n={name:t,visible:i?.visible??!0,material:i?.material??new qs({color:0})};this.set(t,n)}return this.get(t)}setColor(t,i){let n=this.get(t);n&&(n.material.color.setHex(i),this.set(t,n))}setMaterial(t,i){let n=this.get(t);if(!n)return;let s=n.material;n.material=i,this._container.traverse(o=>{o.userData.layer===t&&(o.userData.isDimension||o.isLineSegments&&(o.material=i))}),s.dispose(),this.set(t,n)}setVisibility(t,i){let n=this.get(t);n&&(n.visible=i,this._container.traverse(s=>{s.userData.layer===t&&(s.visible=i)}),this.set(t,n))}assign(t,i){let n=this.get(i);n&&(t.userData.layer=i,n.visible||(t.visible=!1),t.isLineSegments&&(t.material=n.material))}resolveColor(t){let i=this.get(t);if(i)return i.material.color.getHex()}},nq=class $b extends rs{constructor(t){super(),ze(this,"_viewport"),ze(this,"_border"),ze(this,"_handles",[]),ze(this,"_raycaster",new Oa),ze(this,"_resizable",!1),ze(this,"_movab
`)+`
`}},Eie=class{constructor(t){ze(this,"precision",2),ze(this,"config",{trueColor:!1}),ze(this,"_viewport",null),ze(this,"_paperSlot",null),ze(this,"_annotationLayers",new Map),ze(this,"_systemExporters",new Map),this._components=t}registerSystemExporter(t,i){this._systemExporters.set(t,i)}export(t,i){let n=!!i,s=new cye,o=new Map;for(let h of t)for(let p of h.drawing.layers.values())o.has(p.name)||o.set(p.name,p);let r=[...o.values()],a=this._components.get(OS).systems.get(tq),u=a?[...a.definitions.keys()]:[];this._writeHeader(s,n),this._writeTables(s,r,u),this._writeBlocks(s,a??null),s.p(0,"SECTION").p(2,"ENTITIES"),n&&i&&this._writePaperBorders(s,i);for(let h of t){h.drawing.three.traverse(p=>{p.userData.isDimension&&p.userData.annotationUuid&&this._annotationLayers.set(p.userData.annotationUuid,p.userData.layer??"0")});for(let p of h.viewports){if(this._viewport=p.viewport??null,n&&p.viewport){let m=p.viewport,I=i.heightMm-2*i.margin;this._paperSlot={x:p.x??0,y:I-(p.y??0),mmPerUnit:1e3/m.drawingScale,vpLeft:m.left,vpTop:m.top}}else this._paperSlot=null;this._writeViewportBorder(s),this._writeRawLines(s,h.drawing),this._writeLinearAnnotations(s,h.drawing),this._writeAngleAnnotations(s,h.drawing),this._writeLeaderAnnotations(s,h.drawing),this._writeSlopeAnnotations(s,h.drawing),this._writeCalloutAnnotations(s,h.drawing),this._writeBlockInsertions(s,h.drawing),this._writeCustomSystems(s,h.drawing)}this._annotationLayers.clear()}return s.p(0,"ENDSEC"),this._writeObjects(s),s.p(0,"EOF"),this._viewport=null,this._paperSlot=null,s.build()}_writeHeader(t,i){t.p(0,"SECTION").p(2,"HEADER"),t.p(9,"$ACADVER").p(1,this.config.trueColor?"AC1018":"AC1015"),t.p(9,"$INSUNITS").p(70,i?4:6),t.p(0,"ENDSEC")}_writeTables(t,i,n){t.p(0,"SECTION").p(2,"TABLES"),t.p(0,"TABLE").p(2,"VPORT").p(70,0).p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"LTYPE").p(70,1),t.p(0,"LTYPE").p(2,"CONTINUOUS").p(70,0).p(3,"Solid line").p(72,65).p(73,0).n(40,0),t.p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"LAYER").p(70,i.length);for(let o of i){let r=Yb(o.material.color.getHex());t.p(0,"LAYER").p(2,o.name).p(70,0).p(62,r).p(6,"CONTINUOUS")}t.p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"STYLE").p(70,1),t.p(0,"STYLE").p(2,"STANDARD").p(70,0).n(40,0).n(41,1).n(50,0).p(71,0).n(42,.2).p(3,"txt").p(4,""),t.p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"VIEW").p(70,0).p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"UCS").p(70,0).p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"APPID").p(70,1),t.p(0,"APPID").p(2,"ACAD").p(70,0),t.p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"DIMSTYLE").p(70,0).p(0,"ENDTAB");let s=["*Model_Space","*Paper_Space",...n];t.p(0,"TABLE").p(2,"BLOCK_RECORD").p(70,s.length);for(let o of s)t.p(0,"BLOCK_RECORD").p(5,t.handle()).p(2,o);t.p(0,"ENDTAB"),t.p(0,"ENDSEC")}_writeBlocks(t,i){if(t.p(0,"SECTION").p(2,"BLOCKS"),this._writeBlock(t,"*Model_Space",null),this._writeBlock(t,"*Paper_Space",null),i)for(let[n,s]of i.definitions)this._writeBlock(t,n,s.lines??null);t.p(0,"ENDSEC")}_writeBlock(t,i,n){if(t.p(0,"BLOCK").p(5,t.handle()).p(8,"0").p(2,i).p(70,0).n(10,0).n(20,0).n(30,0).p(3,i).p(1,""),n){let s=this._viewport,o=this._paperSlot;this._viewport=null,this._paperSlot=null,this._writeGeoAsLines(t,n,"0"),this._viewport=s,this._paperSlot=o}t.p(0,"ENDBLK").p(5,t.handle()).p(8,"0")}_writeViewportBorder(t){if(!this._viewport)return;let i=this._viewport,n=this._tx(i.left),s=this._tx(i.right),o=this._ty(-i.bottom),r=this._ty(-i.top);this._writeRawLine(t,n,o,s,o,"0",7),this._writeRawLine(t,s,o,s,r,"0",7),this._writeRawLine(t,s,r,n,r,"0",7),this._writeRawLine(t,n,r,n,o,"0",7)}_writePaperBorders(t,i){let{margin:n,widthMm:s,heightMm:o}=i,r=s-2*n,l=o-2*n;this._writeRawLine(t,0,0,r,0,"0",7),this._writeRawLine(t,r,0,r,l,"0",7),this._writeRawLine(t,r,l,0,l,"0",7),this._writeRawLine(t,0,l,0,0,"0",7),this._writeRawLine(t,-n,-n,r+n,-n,"0",7),this._writeRawLine(t,r+n,-n,r+n,l+n,"0",7),this._writeRawLine(t,r+n,l+n,-n,l+n,"0",7),this._writeRawLine(t,-n,l+n,-n,-n,"0",7)}_writeObjects(t){t.p(0,"SECTION").p(2,"OBJECTS"),t.p(0,"DICTIONARY").p(5,t.handle()).p(330,0).p(100,"AcDbRootDictionary"),t.p(0,"ENDSEC")}_writeRawLines(t,i){i.three.traverse(n=>{var s;if(!
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,fragmentShader:`
uniform float opacity;
uniform sampler2D tDiffuse;
varying vec2 vUv;
void main() {
vec4 texel = texture2D( tDiffuse, vUv );
gl_FragColor = opacity * texel;
}`};var _0=class{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}},Cst=new gr(-1,1,1,-1,0,1),Pye=class extends Ni{constructor(){super(),this.setAttribute("position",new ln([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new ln([0,2,0,0,2,0],2))}},Dst=new Pye,sm=class{constructor(t){this._mesh=new ci(Dst,t)}dispose(){this._mesh.geometry.dispose()}render(t){t.render(this._mesh,Cst)}get material(){return this._mesh.material}set material(t){this._mesh.material=t}};var _ie=class extends _0{constructor(t,i="tDiffuse"){super(),this.textureID=i,this.uniforms=null,this.material=null,t instanceof Bs?(this.uniforms=t.uniforms,this.material=t):t&&(this.uniforms=xu.clone(t.uniforms),this.material=new Bs({name:t.name!==void 0?t.name:"unspecified",defines:Object.assign({},t.defines),uniforms:this.uniforms,vertexShader:t.vertexShader,fragmentShader:t.fragmentShader})),this._fsQuad=new sm(this.material)}render(t,i,n){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=n.texture),this._fsQuad.material=this.material,this.renderToScreen?(t.setRenderTarget(null),this._fsQuad.render(t)):(t.setRenderTarget(i),this.clear&&t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil),this._fsQuad.render(t))}dispose(){this.material.dispose(),this._fsQuad.dispose()}};var oq=class extends _0{constructor(t,i){super(),this.scene=t,this.camera=i,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(t,i,n){let s=t.getContext(),o=t.state;o.buffers.color.setMask(!1),o.buffers.depth.setMask(!1),o.buffers.color.setLocked(!0),o.buffers.depth.setLocked(!0);let r,l;this.inverse?(r=0,l=1):(r=1,l=0),o.buffers.stencil.setTest(!0),o.buffers.stencil.setOp(s.REPLACE,s.REPLACE,s.REPLACE),o.buffers.stencil.setFunc(s.ALWAYS,r,4294967295),o.buffers.stencil.setClear(l),o.buffers.stencil.setLocked(!0),t.setRenderTarget(n),this.clear&&t.clear(),t.render(this.scene,this.camera),t.setRenderTarget(i),this.clear&&t.clear(),t.render(this.scene,this.camera),o.buffers.color.setLocked(!1),o.buffers.depth.setLocked(!1),o.buffers.color.setMask(!0),o.buffers.depth.setMask(!0),o.buffers.stencil.setLocked(!1),o.buffers.stencil.setFunc(s.EQUAL,1,4294967295),o.buffers.stencil.setOp(s.KEEP,s.KEEP,s.KEEP),o.buffers.stencil.setLocked(!0)}},bie=class extends _0{constructor(){super(),this.needsSwap=!1}render(t){t.state.buffers.stencil.setLocked(!1),t.state.buffers.stencil.setTest(!1)}};var Aie=class{constructor(t,i){if(this.renderer=t,this._pixelRatio=t.getPixelRatio(),i===void 0){let n=t.getSize(new si);this._width=n.width,this._height=n.height,i=new bo(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Ao}),i.texture.name="EffectComposer.rt1"}else this._width=i.width,this._height=i.height;this.renderTarget1=i,this.renderTarget2=i.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new _ie(gU),this.copyPass.material.blending=jo,this.timer=new iO}swapBuffers(){let t=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=t}addPass(t){this.passes.push(t),t.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(t,i){this.passes.splice(i,0,t),t.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(t){let i=this.passes.indexOf(t);i!==-1&&this.passes.splice(i,1)}isLastEnabledPass(t){for(let i=t+1;i<this.passes.length;i++)if(this.passes[i].enabled)return!1;return!0}render(t){this.timer.update(),t===void 0&&(t=this.timer.getDelta());let i=this.renderer.getRenderTarget(),n=!1;for(let s=0,o=this.passes.length;s<o;s++){let r=this.passes[s];if(r.enabled!==!1){if(r.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(s),r.render(this.renderer,this.writeBuffer,this.readBuffer,t,n),r.needsSwap){if(n){let l=this.renderer.getContext(),a=this.renderer.state.buffers.stencil;a.setFunc(l.NOTEQUAL,1,4294967295),this.copyPass.r
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,fragmentShader:`
varying vec2 vUv;
uniform highp sampler2D tNormal;
uniform highp sampler2D tDepth;
uniform sampler2D tNoise;
uniform vec2 resolution;
uniform float cameraNear;
uniform float cameraFar;
uniform mat4 cameraProjectionMatrix;
uniform mat4 cameraProjectionMatrixInverse;
uniform mat4 cameraWorldMatrix;
uniform float radius;
uniform float distanceExponent;
uniform float thickness;
uniform float distanceFallOff;
uniform float scale;
#if SCENE_CLIP_BOX == 1
uniform vec3 sceneBoxMin;
uniform vec3 sceneBoxMax;
#endif
#include <common>
#include <packing>
#ifndef FRAGMENT_OUTPUT
#define FRAGMENT_OUTPUT vec4(vec3(ao), 1.)
#endif
vec3 getViewPosition( const in vec2 screenPosition, const in float depth ) {
#ifdef USE_REVERSED_DEPTH_BUFFER
vec4 clipSpacePosition = vec4( vec2( screenPosition ) * 2.0 - 1.0, depth, 1.0 );
#else
vec4 clipSpacePosition = vec4( vec3( screenPosition, depth ) * 2.0 - 1.0, 1.0 );
#endif
vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition;
return viewSpacePosition.xyz / viewSpacePosition.w;
}
float getDepth(const vec2 uv) {
return textureLod(tDepth, uv.xy, 0.0).DEPTH_SWIZZLING;
}
float fetchDepth(const ivec2 uv) {
return texelFetch(tDepth, uv.xy, 0).DEPTH_SWIZZLING;
}
float getViewZ(const in float depth) {
#if PERSPECTIVE_CAMERA == 1
return perspectiveDepthToViewZ(depth, cameraNear, cameraFar);
#else
return orthographicDepthToViewZ(depth, cameraNear, cameraFar);
#endif
}
vec3 computeNormalFromDepth(const vec2 uv) {
vec2 size = vec2(textureSize(tDepth, 0));
ivec2 p = ivec2(uv * size);
float c0 = fetchDepth(p);
float l2 = fetchDepth(p - ivec2(2, 0));
float l1 = fetchDepth(p - ivec2(1, 0));
float r1 = fetchDepth(p + ivec2(1, 0));
float r2 = fetchDepth(p + ivec2(2, 0));
float b2 = fetchDepth(p - ivec2(0, 2));
float b1 = fetchDepth(p - ivec2(0, 1));
float t1 = fetchDepth(p + ivec2(0, 1));
float t2 = fetchDepth(p + ivec2(0, 2));
float dl = abs((2.0 * l1 - l2) - c0);
float dr = abs((2.0 * r1 - r2) - c0);
float db = abs((2.0 * b1 - b2) - c0);
float dt = abs((2.0 * t1 - t2) - c0);
vec3 ce = getViewPosition(uv, c0).xyz;
vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz;
vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz;
return normalize(cross(dpdx, dpdy));
}
vec3 getViewNormal(const vec2 uv) {
#if NORMAL_VECTOR_TYPE == 2
return normalize(textureLod(tNormal, uv, 0.).rgb);
#elif NORMAL_VECTOR_TYPE == 1
return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb);
#else
return computeNormalFromDepth(uv);
#endif
}
vec3 getSceneUvAndDepth(vec3 sampleViewPos) {
vec4 sampleClipPos = cameraProjectionMatrix * vec4(sampleViewPos, 1.);
vec2 sampleUv = sampleClipPos.xy / sampleClipPos.w * 0.5 + 0.5;
float sampleSceneDepth = getDepth(sampleUv);
return vec3(sampleUv, sampleSceneDepth);
}
void main() {
float depth = getDepth(vUv.xy);
#ifdef USE_REVERSED_DEPTH_BUFFER
if (depth <= 0.0) {
discard;
return;
}
#else
if (depth >= 1.0) {
discard;
return;
}
#endif
vec3 viewPos = getViewPosition(vUv, depth);
vec3 viewNormal = getViewNormal(vUv);
float radiusToUse = radius;
float distanceFalloffToUse = thickness;
#if SCREEN_SPACE_RADIUS == 1
float radiusScale = getViewPosition(vec2(0.5 + float(SCREEN_SPACE_RADIUS_SCALE) / resolution.x, 0.0), depth).x;
radiusToUse *= radiusScale;
distanceFalloffToUse *= radiusScale;
#endif
#if SCENE_CLIP_BOX == 1
vec3 worldPos = (cameraWorldMatrix * vec4(viewPos, 1.0)).xyz;
float boxDistance = length(max(vec3(0.0), max(sceneBoxMin - worldPos, worldPos - sceneBoxMax)));
if (boxDistance > radiusToUse) {
discard;
return;
}
#endif
vec2 noiseResolution = vec2(textureSize(tNoise, 0));
vec2 noiseUv = vUv * resolution / noiseResolution;
vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0);
vec3 randomVec = noiseTexel.xyz * 2.0 - 1.0;
vec3 tangent = normalize(vec3(randomVec.xy, 0.));
vec3 bitangent = vec3(-tangent.y, tangent.x, 0.);
mat3 kernelMatrix = mat3(tangent, bitangent, vec3(0., 0., 1.));
const int DIRECTIONS = SAMPLES < 30 ? 3 : 5;
const int STEPS = (SAMPLES + DIRECTIONS - 1) / DIRECTIONS;
float ao = 0.0;
for (int i = 0; i < DIRECTIONS; ++i) {
float angle = float(i) / float(DIRECTIONS) * PI;
vec4 sampleDir = vec4(cos(angle), sin(angle), 0., 0.5 + 0.5 * noiseTexel.w);
sampleDir.xyz = normalize(kernelMatrix * sampleDir.xyz);
vec3 viewDir = normalize(-viewPos.xyz);
vec3 sliceBitangent = normalize(cross(sampleDir.xyz, viewDir));
vec3 sliceTangent = cross(sliceBitangent, viewDir);
vec3 normalInSlice = normalize(viewNormal - sliceBitangent * dot(viewNormal, sliceBitangent));
vec3 tangentToNormalInSlice = cross(normalInSlice, sliceBitangent);
vec2 cosHorizons = vec2(dot(viewDir, tangentToNormalInSlice), dot(viewDir, -tangentToNormalInSlice));
for (int j = 0; j < STEPS; ++j) {
vec3 sampleViewOffset = sampleDir.xyz * radiusToUse * sampleDir.w * pow(float(j + 1) / float(STEPS), distanceExponent);
vec3 sampleSceneUvDepth = getSceneUvAndDepth(viewPos + sampleViewOffset);
vec3 sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z);
vec3 viewDelta = sampleSceneViewPos - viewPos;
if (abs(viewDelta.z) < thickness) {
float sampleCosHorizon = dot(viewDir, normalize(viewDelta));
cosHorizons.x += max(0., (sampleCosHorizon - cosHorizons.x) * mix(1., 2. / float(j + 2), distanceFallOff));
}
sampleSceneUvDepth = getSceneUvAndDepth(viewPos - sampleViewOffset);
sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z);
viewDelta = sampleSceneViewPos - viewPos;
if (abs(viewDelta.z) < thickness) {
float sampleCosHorizon = dot(viewDir, normalize(viewDelta));
cosHorizons.y += max(0., (sampleCosHorizon - cosHorizons.y) * mix(1., 2. / float(j + 2), distanceFallOff));
}
}
vec2 sinHorizons = sqrt(1. - cosHorizons * cosHorizons);
float nx = dot(normalInSlice, sliceTangent);
float ny = dot(normalInSlice, viewDir);
float nxb = 1. / 2. * (acos(cosHorizons.y) - acos(cosHorizons.x) + sinHorizons.x * cosHorizons.x - sinHorizons.y * cosHorizons.y);
float nyb = 1. / 2. * (2. - cosHorizons.x * cosHorizons.x - cosHorizons.y * cosHorizons.y);
float occlusion = nx * nxb + ny * nyb;
ao += occlusion;
}
ao = clamp(ao / float(DIRECTIONS), 0., 1.);
#if SCENE_CLIP_BOX == 1
ao = mix(ao, 1., smoothstep(0., radiusToUse, boxDistance));
#endif
ao = pow(ao, scale);
gl_FragColor = FRAGMENT_OUTPUT;
}`},lq={name:"GTAODepthShader",defines:{PERSPECTIVE_CAMERA:1},uniforms:{tDepth:{value:null},cameraNear:{value:null},cameraFar:{value:null}},vertexShader:`
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,fragmentShader:`
uniform sampler2D tDepth;
uniform float cameraNear;
uniform float cameraFar;
varying vec2 vUv;
#include <packing>
float getLinearDepth( const in vec2 screenPosition ) {
#if PERSPECTIVE_CAMERA == 1
float fragCoordZ = texture2D( tDepth, screenPosition ).x;
float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
#else
return texture2D( tDepth, screenPosition ).x;
#endif
}
void main() {
float depth = getLinearDepth( vUv );
gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 );
}`},xie={name:"GTAOBlendShader",uniforms:{tDiffuse:{value:null},intensity:{value:1}},vertexShader:`
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,fragmentShader:`
uniform float intensity;
uniform sampler2D tDiffuse;
varying vec2 vUv;
void main() {
vec4 texel = texture2D( tDiffuse, vUv );
gl_FragColor = vec4(mix(vec3(1.), texel.rgb, intensity), texel.a);
}`};function uCe(e=5){let t=Math.floor(e)%2===0?Math.floor(e)+1:Math.floor(e),i=Nst(t),n=i.length,s=new Uint8Array(n*4);for(let r=0;r<n;++r){let l=i[r],a=2*Math.PI*l/n,u=new ne(Math.cos(a),Math.sin(a),0).normalize();s[r*4]=(u.x*.5+.5)*255,s[r*4+1]=(u.y*.5+.5)*255,s[r*4+2]=127,s[r*4+3]=255}let o=new Ic(s,t,t);return o.wrapS=If,o.wrapT=If,o.needsUpdate=!0,o}function Nst(e){let t=Math.floor(e)%2===0?Math.floor(e)+1:Math.floor(e),i=t*t,n=Array(i).fill(0),s=Math.floor(t/2),o=t-1;for(let r=1;r<=i;){if(s===-1&&o===t?(o=t-2,s=0):(o===t&&(o=0),s<0&&(s=t-1)),n[s*t+o]!==0){o-=2,s++;continue}else n[s*t+o]=r++;o++,s--}return n}var aq={name:"PoissonDenoiseShader",defines:{SAMPLES:16,SAMPLE_VECTORS:Mye(16,2,1),NORMAL_VECTOR_TYPE:1,DEPTH_VALUE_SOURCE:0},uniforms:{tDiffuse:{value:null},tNormal:{value:null},tDepth:{value:null},tNoise:{value:null},resolution:{value:new si},cameraProjectionMatrixInverse:{value:new di},lumaPhi:{value:5},depthPhi:{value:5},normalPhi:{value:5},radius:{value:4},index:{value:0}},vertexShader:`
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,fragmentShader:`
varying vec2 vUv;
uniform sampler2D tDiffuse;
uniform sampler2D tNormal;
uniform sampler2D tDepth;
uniform sampler2D tNoise;
uniform vec2 resolution;
uniform mat4 cameraProjectionMatrixInverse;
uniform float lumaPhi;
uniform float depthPhi;
uniform float normalPhi;
uniform float radius;
uniform int index;
#include <common>
#include <packing>
#ifndef SAMPLE_LUMINANCE
#define SAMPLE_LUMINANCE dot(vec3(0.2125, 0.7154, 0.0721), a)
#endif
#ifndef FRAGMENT_OUTPUT
#define FRAGMENT_OUTPUT vec4(denoised, 1.)
#endif
float getLuminance(const in vec3 a) {
return SAMPLE_LUMINANCE;
}
const vec3 poissonDisk[SAMPLES] = SAMPLE_VECTORS;
vec3 getViewPosition( const in vec2 screenPosition, const in float depth ) {
#ifdef USE_REVERSED_DEPTH_BUFFER
vec4 clipSpacePosition = vec4( vec2( screenPosition ) * 2.0 - 1.0, depth, 1.0 );
#else
vec4 clipSpacePosition = vec4( vec3( screenPosition, depth ) * 2.0 - 1.0, 1.0 );
#endif
vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition;
return viewSpacePosition.xyz / viewSpacePosition.w;
}
float getDepth(const vec2 uv) {
#if DEPTH_VALUE_SOURCE == 1
return textureLod(tDepth, uv.xy, 0.0).a;
#else
return textureLod(tDepth, uv.xy, 0.0).r;
#endif
}
float fetchDepth(const ivec2 uv) {
#if DEPTH_VALUE_SOURCE == 1
return texelFetch(tDepth, uv.xy, 0).a;
#else
return texelFetch(tDepth, uv.xy, 0).r;
#endif
}
vec3 computeNormalFromDepth(const vec2 uv) {
vec2 size = vec2(textureSize(tDepth, 0));
ivec2 p = ivec2(uv * size);
float c0 = fetchDepth(p);
float l2 = fetchDepth(p - ivec2(2, 0));
float l1 = fetchDepth(p - ivec2(1, 0));
float r1 = fetchDepth(p + ivec2(1, 0));
float r2 = fetchDepth(p + ivec2(2, 0));
float b2 = fetchDepth(p - ivec2(0, 2));
float b1 = fetchDepth(p - ivec2(0, 1));
float t1 = fetchDepth(p + ivec2(0, 1));
float t2 = fetchDepth(p + ivec2(0, 2));
float dl = abs((2.0 * l1 - l2) - c0);
float dr = abs((2.0 * r1 - r2) - c0);
float db = abs((2.0 * b1 - b2) - c0);
float dt = abs((2.0 * t1 - t2) - c0);
vec3 ce = getViewPosition(uv, c0).xyz;
vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz
: -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz;
vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz
: -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz;
return normalize(cross(dpdx, dpdy));
}
vec3 getViewNormal(const vec2 uv) {
#if NORMAL_VECTOR_TYPE == 2
return normalize(textureLod(tNormal, uv, 0.).rgb);
#elif NORMAL_VECTOR_TYPE == 1
return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb);
#else
return computeNormalFromDepth(uv);
#endif
}
void denoiseSample(in vec3 center, in vec3 viewNormal, in vec3 viewPos, in vec2 sampleUv, inout vec3 denoised, inout float totalWeight) {
vec4 sampleTexel = textureLod(tDiffuse, sampleUv, 0.0);
float sampleDepth = getDepth(sampleUv);
vec3 sampleNormal = getViewNormal(sampleUv);
vec3 neighborColor = sampleTexel.rgb;
vec3 viewPosSample = getViewPosition(sampleUv, sampleDepth);
float normalDiff = dot(viewNormal, sampleNormal);
float normalSimilarity = pow(max(normalDiff, 0.), normalPhi);
float lumaDiff = abs(getLuminance(neighborColor) - getLuminance(center));
float lumaSimilarity = max(1.0 - lumaDiff / lumaPhi, 0.0);
float depthDiff = abs(dot(viewPos - viewPosSample, viewNormal));
float depthSimilarity = max(1. - depthDiff / depthPhi, 0.);
float w = lumaSimilarity * depthSimilarity * normalSimilarity;
denoised += w * neighborColor;
totalWeight += w;
}
void main() {
float depth = getDepth(vUv.xy);
vec3 viewNormal = getViewNormal(vUv);
if (depth == 1. || dot(viewNormal, viewNormal) == 0.) {
discard;
return;
}
vec4 texel = textureLod(tDiffuse, vUv, 0.0);
vec3 center = texel.rgb;
vec3 viewPos = getViewPosition(vUv, depth);
vec2 noiseResolution = vec2(textureSize(tNoise, 0));
vec2 noiseUv = vUv * resolution / noiseResolution;
vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0);
vec2 noiseVec = vec2(sin(noiseTexel[index % 4] * 2. * PI), cos(noiseTexel[index % 4] * 2. * PI));
mat2 rotationMatrix = mat2(noiseVec.x, -noiseVec.y, noiseVec.x, noiseVec.y);
float totalWeight = 1.0;
vec3 denoised = texel.rgb;
for (int i = 0; i < SAMPLES; i++) {
vec3 sampleDir = poissonDisk[i];
vec2 offset = rotationMatrix * (sampleDir.xy * (1. + sampleDir.z * (radius - 1.)) / resolution);
vec2 sampleUv = vUv + offset;
denoiseSample(center, viewNormal, viewPos, sampleUv, denoised, totalWeight);
}
if (totalWeight > 0.) {
denoised /= totalWeight;
}
gl_FragColor = FRAGMENT_OUTPUT;
}`};function Mye(e,t,i){let n=Ost(e,t,i),s="vec3[SAMPLES](";for(let o=0;o<e;o++){let r=n[o];s+=`vec3(${r.x}, ${r.y}, ${r.z})${o<e-1?",":")"}`}return s}function Ost(e,t,i){let n=[];for(let s=0;s<e;s++){let o=2*Math.PI*t*s/e,r=Math.pow(s/(e-1),i);n.push(new ne(Math.cos(o),Math.sin(o),r))}return n}var Cie=class{constructor(t=Math){this.grad3=[[1,1,0],[-1,1,0],[1,-1,0],[-1,-1,0],[1,0,1],[-1,0,1],[1,0,-1],[-1,0,-1],[0,1,1],[0,-1,1],[0,1,-1],[0,-1,-1]],this.grad4=[[0,1,1,1],[0,1,1,-1],[0,1,-1,1],[0,1,-1,-1],[0,-1,1,1],[0,-1,1,-1],[0,-1,-1,1],[0,-1,-1,-1],[1,0,1,1],[1,0,1,-1],[1,0,-1,1],[1,0,-1,-1],[-1,0,1,1],[-1,0,1,-1],[-1,0,-1,1],[-1,0,-1,-1],[1,1,0,1],[1,1,0,-1],[1,-1,0,1],[1,-1,0,-1],[-1,1,0,1],[-1,1,0,-1],[-1,-1,0,1],[-1,-1,0,-1],[1,1,1,0],[1,1,-1,0],[1,-1,1,0],[1,-1,-1,0],[-1,1,1,0],[-1,1,-1,0],[-1,-1,1,0],[-1,-1,-1,0]],this.p=[];for(let i=0;i<256;i++)this.p[i]=Math.floor(t.random()*256);this.perm=[];for(let i=0;i<512;i++)this.perm[i]=this.p[i&255];this.simplex=[[0,1,2,3],[0,1,3,2],[0,0,0,0],[0,2,3,1],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,2,3,0],[0,2,1,3],[0,0,0,0],[0,3,1,2],[0,3,2,1],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,3,2,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,2,0,3],[0,0,0,0],[1,3,0,2],[0,0,0,0],[0,0,0,0],[0,0,0,0],[2,3,0,1],[2,3,1,0],[1,0,2,3],[1,0,3,2],[0,0,0,0],[0,0,0,0],[0,0,0,0],[2,0,3,1],[0,0,0,0],[2,1,3,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[2,0,1,3],[0,0,0,0],[0,0,0,0],[0,0,0,0],[3,0,1,2],[3,0,2,1],[0,0,0,0],[3,1,2,0],[2,1,0,3],[0,0,0,0],[0,0,0,0],[0,0,0,0],[3,1,0,2],[0,0,0,0],[3,2,0,1],[3,2,1,0]]}noise(t,i){let n,s,o,r=.5*(Math.sqrt(3)-1),l=(t+i)*r,a=Math.floor(t+l),u=Math.floor(i+l),h=(3-Math.sqrt(3))/6,p=(a+u)*h,m=a-p,I=u-p,g=t-m,E=i-I,w,T;g>E?(w=1,T=0):(w=0,T=1);let S=g-w+h,_=E-T+h,x=g-1+2*h,M=E-1+2*h,W=a&255,G=u&255,$=this.perm[W+this.perm[G]]%12,Y=this.perm[W+w+this.perm[G+T]]%12,se=this.perm[W+1+this.perm[G+1]]%12,pe=.5-g*g-E*E;pe<0?n=0:(pe*=pe,n=pe*pe*this._dot(this.grad3[$],g,E));let k=.5-S*S-_*_;k<0?s=0:(k*=k,s=k*k*this._dot(this.grad3[Y],S,_));let fe=.5-x*x-M*M;return fe<0?o=0:(fe*=fe,o=fe*fe*this._dot(this.grad3[se],x,M)),70*(n+s+o)}noise3d(t,i,n){let s,o,r,l,u=(t+i+n)*.3333333333333333,h=Math.floor(t+u),p=Math.floor(i+u),m=Math.floor(n+u),I=1/6,g=(h+p+m)*I,E=h-g,w=p-g,T=m-g,S=t-E,_=i-w,x=n-T,M,W,G,$,Y,se;S>=_?_>=x?(M=1,W=0,G=0,$=1,Y=1,se=0):S>=x?(M=1,W=0,G=0,$=1,Y=0,se=1):(M=0,W=0,G=1,$=1,Y=0,se=1):_<x?(M=0,W=0,G=1,$=0,Y=1,se=1):S<x?(M=0,W=1,G=0,$=0,Y=1,se=1):(M=0,W=1,G=0,$=1,Y=1,se=0);let pe=S-M+I,k=_-W+I,fe=x-G+I,Q=S-$+2*I,Te=_-Y+2*I,Ve=x-se+2*I,Fe=S-1+3*I,pt=_-1+3*I,Me=x-1+3*I,He=h&255,Ye=p&255,We=m&255,_t=this.perm[He+this.perm[Ye+this.perm[We]]]%12,xt=this.perm[He+M+this.perm[Ye+W+this.perm[We+G]]]%12,wt=this.perm[He+$+this.perm[Ye+Y+this.perm[We+se]]]%12,Bt=this.perm[He+1+this.perm[Ye+1+this.perm[We+1]]]%12,Xt=.6-S*S-_*_-x*x;Xt<0?s=0:(Xt*=Xt,s=Xt*Xt*this._dot3(this.grad3[_t],S,_,x));let Dt=.6-pe*pe-k*k-fe*fe;Dt<0?o=0:(Dt*=Dt,o=Dt*Dt*this._dot3(this.grad3[xt],pe,k,fe));let Pt=.6-Q*Q-Te*Te-Ve*Ve;Pt<0?r=0:(Pt*=Pt,r=Pt*Pt*this._dot3(this.grad3[wt],Q,Te,Ve));let $t=.6-Fe*Fe-pt*pt-Me*Me;return $t<0?l=0:($t*=$t,l=$t*$t*this._dot3(this.grad3[Bt],Fe,pt,Me)),32*(s+o+r+l)}noise4d(t,i,n,s){let o=this.grad4,r=this.simplex,l=this.perm,a=(Math.sqrt(5)-1)/4,u=(5-Math.sqrt(5))/20,h,p,m,I,g,E=(t+i+n+s)*a,w=Math.floor(t+E),T=Math.floor(i+E),S=Math.floor(n+E),_=Math.floor(s+E),x=(w+T+S+_)*u,M=w-x,W=T-x,G=S-x,$=_-x,Y=t-M,se=i-W,pe=n-G,k=s-$,fe=Y>se?32:0,Q=Y>pe?16:0,Te=se>pe?8:0,Ve=Y>k?4:0,Fe=se>k?2:0,pt=pe>k?1:0,Me=fe+Q+Te+Ve+Fe+pt,He=r[Me][0]>=3?1:0,Ye=r[Me][1]>=3?1:0,We=r[Me][2]>=3?1:0,_t=r[Me][3]>=3?1:0,xt=r[Me][0]>=2?1:0,wt=r[Me][1]>=2?1:0,Bt=r[Me][2]>=2?1:0,Xt=r[Me][3]>=2?1:0,Dt=r[Me][0]>=1?1:0,Pt=r[Me][1]>=1?1:0,$t=r[Me][2]>=1?1:0,Vt=r[Me][3]>=1?1:0,Ue=Y-He+u,Ft=se-Ye+u,ie=pe-We+u,Oe=k-_t+u,Ce=Y-xt+2*u,Se=se-wt+2*u,_e=pe-Bt+2*u,je=k-Xt+2*u,Be=Y-Dt+3*u,dt=se-Pt+3*u,it=pe-$t+3*u,Rt=k-Vt+3*u,At=Y-1+4*u,Ht=se-1+4*u,Xe=pe-1+4*u,Ze=k-1+4*u,Mt=w&255,ni=T&255,gi=S&255,hi=_&255,Di=l[Mt+l[ni+l[gi+l[hi]]]]%32,ti=l[Mt+He+l[ni+Ye+l[g
precision highp float;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
attribute vec3 position;
attribute vec2 uv;
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,fragmentShader:`
precision highp float;
uniform sampler2D tDiffuse;
#include <tonemapping_pars_fragment>
#include <colorspace_pars_fragment>
varying vec2 vUv;
void main() {
gl_FragColor = texture2D( tDiffuse, vUv );
// tone mapping
#ifdef LINEAR_TONE_MAPPING
gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );
#elif defined( REINHARD_TONE_MAPPING )
gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );
#elif defined( CINEON_TONE_MAPPING )
gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );
#elif defined( ACES_FILMIC_TONE_MAPPING )
gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );
#elif defined( AGX_TONE_MAPPING )
gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );
#elif defined( NEUTRAL_TONE_MAPPING )
gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );
#elif defined( CUSTOM_TONE_MAPPING )
gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );
#endif
// color space
#ifdef SRGB_TRANSFER
gl_FragColor = sRGBTransferOETF( gl_FragColor );
#endif
}`};var Die=class extends _0{constructor(){super(),this.isOutputPass=!0,this.uniforms=xu.clone(uq.uniforms),this.material=new Gx({name:uq.name,uniforms:this.uniforms,vertexShader:uq.vertexShader,fragmentShader:uq.fragmentShader}),this._fsQuad=new sm(this.material),this._outputColorSpace=null,this._toneMapping=null}render(t,i,n){this.uniforms.tDiffuse.value=n.texture,this.uniforms.toneMappingExposure.value=t.toneMappingExposure,(this._outputColorSpace!==t.outputColorSpace||this._toneMapping!==t.toneMapping)&&(this._outputColorSpace=t.outputColorSpace,this._toneMapping=t.toneMapping,this.material.defines={},Kn.getTransfer(this._outputColorSpace)===Sn&&(this.material.defines.SRGB_TRANSFER=""),this._toneMapping===Qx?this.material.defines.LINEAR_TONE_MAPPING="":this._toneMapping===Jx?this.material.defines.REINHARD_TONE_MAPPING="":this._toneMapping===Xx?this.material.defines.CINEON_TONE_MAPPING="":this._toneMapping===eC?this.material.defines.ACES_FILMIC_TONE_MAPPING="":this._toneMapping===tC?this.material.defines.AGX_TONE_MAPPING="":this._toneMapping===iC?this.material.defines.NEUTRAL_TONE_MAPPING="":this._toneMapping===D8&&(this.material.defines.CUSTOM_TONE_MAPPING=""),this.material.needsUpdate=!0),this.renderToScreen===!0?(t.setRenderTarget(null),this._fsQuad.render(t)):(t.setRenderTarget(i),this.clear&&t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil),this._fsQuad.render(t))}dispose(){this.material.dispose(),this._fsQuad.dispose()}};var cq={name:"SMAAEdgesShader",defines:{SMAA_THRESHOLD:"0.1"},uniforms:{tDiffuse:{value:null},resolution:{value:new si(1/1024,1/512)}},vertexShader:`
uniform vec2 resolution;
varying vec2 vUv;
varying vec4 vOffset[ 3 ];
void SMAAEdgeDetectionVS( vec2 texcoord ) {
vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component
vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component
vOffset[ 2 ] = texcoord.xyxy + resolution.xyxy * vec4( -2.0, 0.0, 0.0, 2.0 ); // WebGL port note: Changed sign in W component
}
void main() {
vUv = uv;
SMAAEdgeDetectionVS( vUv );
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,fragmentShader:`
uniform sampler2D tDiffuse;
varying vec2 vUv;
varying vec4 vOffset[ 3 ];
vec4 SMAAColorEdgeDetectionPS( vec2 texcoord, vec4 offset[3], sampler2D colorTex ) {
vec2 threshold = vec2( SMAA_THRESHOLD, SMAA_THRESHOLD );
// Calculate color deltas:
vec4 delta;
vec3 C = texture2D( colorTex, texcoord ).rgb;
vec3 Cleft = texture2D( colorTex, offset[0].xy ).rgb;
vec3 t = abs( C - Cleft );
delta.x = max( max( t.r, t.g ), t.b );
vec3 Ctop = texture2D( colorTex, offset[0].zw ).rgb;
t = abs( C - Ctop );
delta.y = max( max( t.r, t.g ), t.b );
// We do the usual threshold:
vec2 edges = step( threshold, delta.xy );
// Then discard if there is no edge:
if ( dot( edges, vec2( 1.0, 1.0 ) ) == 0.0 )
discard;
// Calculate right and bottom deltas:
vec3 Cright = texture2D( colorTex, offset[1].xy ).rgb;
t = abs( C - Cright );
delta.z = max( max( t.r, t.g ), t.b );
vec3 Cbottom = texture2D( colorTex, offset[1].zw ).rgb;
t = abs( C - Cbottom );
delta.w = max( max( t.r, t.g ), t.b );
// Calculate the maximum delta in the direct neighborhood:
float maxDelta = max( max( max( delta.x, delta.y ), delta.z ), delta.w );
// Calculate left-left and top-top deltas:
vec3 Cleftleft = texture2D( colorTex, offset[2].xy ).rgb;
t = abs( C - Cleftleft );
delta.z = max( max( t.r, t.g ), t.b );
vec3 Ctoptop = texture2D( colorTex, offset[2].zw ).rgb;
t = abs( C - Ctoptop );
delta.w = max( max( t.r, t.g ), t.b );
// Calculate the final maximum delta:
maxDelta = max( max( maxDelta, delta.z ), delta.w );
// Local contrast adaptation in action:
edges.xy *= step( 0.5 * maxDelta, delta.xy );
return vec4( edges, 0.0, 0.0 );
}
void main() {
gl_FragColor = SMAAColorEdgeDetectionPS( vUv, vOffset, tDiffuse );
}`},dq={name:"SMAAWeightsShader",defines:{SMAA_MAX_SEARCH_STEPS:"8",SMAA_AREATEX_MAX_DISTANCE:"16",SMAA_AREATEX_PIXEL_SIZE:"( 1.0 / vec2( 160.0, 560.0 ) )",SMAA_AREATEX_SUBTEX_SIZE:"( 1.0 / 7.0 )"},uniforms:{tDiffuse:{value:null},tArea:{value:null},tSearch:{value:null},resolution:{value:new si(1/1024,1/512)}},vertexShader:`
uniform vec2 resolution;
varying vec2 vUv;
varying vec4 vOffset[ 3 ];
varying vec2 vPixcoord;
void SMAABlendingWeightCalculationVS( vec2 texcoord ) {
vPixcoord = texcoord / resolution;
// We will use these offsets for the searches later on (see @PSEUDO_GATHER4):
vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.25, 0.125, 1.25, 0.125 ); // WebGL port note: Changed sign in Y and W components
vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.125, 0.25, -0.125, -1.25 ); // WebGL port note: Changed sign in Y and W components
// And these for the searches, they indicate the ends of the loops:
vOffset[ 2 ] = vec4( vOffset[ 0 ].xz, vOffset[ 1 ].yw ) + vec4( -2.0, 2.0, -2.0, 2.0 ) * resolution.xxyy * float( SMAA_MAX_SEARCH_STEPS );
}
void main() {
vUv = uv;
SMAABlendingWeightCalculationVS( vUv );
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,fragmentShader:`
#define SMAASampleLevelZeroOffset( tex, coord, offset ) texture2D( tex, coord + float( offset ) * resolution, 0.0 )
uniform sampler2D tDiffuse;
uniform sampler2D tArea;
uniform sampler2D tSearch;
uniform vec2 resolution;
varying vec2 vUv;
varying vec4 vOffset[3];
varying vec2 vPixcoord;
#if __VERSION__ == 100
vec2 round( vec2 x ) {
return sign( x ) * floor( abs( x ) + 0.5 );
}
#endif
float SMAASearchLength( sampler2D searchTex, vec2 e, float bias, float scale ) {
// Not required if searchTex accesses are set to point:
// float2 SEARCH_TEX_PIXEL_SIZE = 1.0 / float2(66.0, 33.0);
// e = float2(bias, 0.0) + 0.5 * SEARCH_TEX_PIXEL_SIZE +
// e * float2(scale, 1.0) * float2(64.0, 32.0) * SEARCH_TEX_PIXEL_SIZE;
e.r = bias + e.r * scale;
return 255.0 * texture2D( searchTex, e, 0.0 ).r;
}
float SMAASearchXLeft( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
/**
* @PSEUDO_GATHER4
* This texcoord has been offset by (-0.25, -0.125) in the vertex shader to
* sample between edge, thus fetching four edges in a row.
* Sampling with different offsets in each direction allows to disambiguate
* which edges are active from the four fetched ones.
*/
vec2 e = vec2( 0.0, 1.0 );
for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
e = texture2D( edgesTex, texcoord, 0.0 ).rg;
texcoord -= vec2( 2.0, 0.0 ) * resolution;
if ( ! ( texcoord.x > end && e.g > 0.8281 && e.r == 0.0 ) ) break;
}
// We correct the previous (-0.25, -0.125) offset we applied:
texcoord.x += 0.25 * resolution.x;
// The searches are bias by 1, so adjust the coords accordingly:
texcoord.x += resolution.x;
// Disambiguate the length added by the last step:
texcoord.x += 2.0 * resolution.x; // Undo last step
texcoord.x -= resolution.x * SMAASearchLength(searchTex, e, 0.0, 0.5);
return texcoord.x;
}
float SMAASearchXRight( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
vec2 e = vec2( 0.0, 1.0 );
for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
e = texture2D( edgesTex, texcoord, 0.0 ).rg;
texcoord += vec2( 2.0, 0.0 ) * resolution;
if ( ! ( texcoord.x < end && e.g > 0.8281 && e.r == 0.0 ) ) break;
}
texcoord.x -= 0.25 * resolution.x;
texcoord.x -= resolution.x;
texcoord.x -= 2.0 * resolution.x;
texcoord.x += resolution.x * SMAASearchLength( searchTex, e, 0.5, 0.5 );
return texcoord.x;
}
float SMAASearchYUp( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
vec2 e = vec2( 1.0, 0.0 );
for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
e = texture2D( edgesTex, texcoord, 0.0 ).rg;
texcoord += vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign
if ( ! ( texcoord.y > end && e.r > 0.8281 && e.g == 0.0 ) ) break;
}
texcoord.y -= 0.25 * resolution.y; // WebGL port note: Changed sign
texcoord.y -= resolution.y; // WebGL port note: Changed sign
texcoord.y -= 2.0 * resolution.y; // WebGL port note: Changed sign
texcoord.y += resolution.y * SMAASearchLength( searchTex, e.gr, 0.0, 0.5 ); // WebGL port note: Changed sign
return texcoord.y;
}
float SMAASearchYDown( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
vec2 e = vec2( 1.0, 0.0 );
for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
e = texture2D( edgesTex, texcoord, 0.0 ).rg;
texcoord -= vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign
if ( ! ( texcoord.y < end && e.r > 0.8281 && e.g == 0.0 ) ) break;
}
texcoord.y += 0.25 * resolution.y; // WebGL port note: Changed sign
texcoord.y += resolution.y; // WebGL port note: Changed sign
texcoord.y += 2.0 * resolution.y; // WebGL port note: Changed sign
texcoord.y -= resolution.y * SMAASearchLength( searchTex, e.gr, 0.5, 0.5 ); // WebGL port note: Changed sign
return texcoord.y;
}
vec2 SMAAArea( sampler2D areaTex, vec2 dist, float e1, float e2, float offset ) {
// Rounding prevents precision errors of bilinear filtering:
vec2 texcoord = float( SMAA_AREATEX_MAX_DISTANCE ) * round( 4.0 * vec2( e1, e2 ) ) + dist;
// We do a scale and bias for mapping to texel space:
texcoord = SMAA_AREATEX_PIXEL_SIZE * texcoord + ( 0.5 * SMAA_AREATEX_PIXEL_SIZE );
// Move to proper place, according to the subpixel offset:
texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset;
return texture2D( areaTex, texcoord, 0.0 ).rg;
}
vec4 SMAABlendingWeightCalculationPS( vec2 texcoord, vec2 pixcoord, vec4 offset[ 3 ], sampler2D edgesTex, sampler2D areaTex, sampler2D searchTex, ivec4 subsampleIndices ) {
vec4 weights = vec4( 0.0, 0.0, 0.0, 0.0 );
vec2 e = texture2D( edgesTex, texcoord ).rg;
if ( e.g > 0.0 ) { // Edge at north
vec2 d;
// Find the distance to the left:
vec2 coords;
coords.x = SMAASearchXLeft( edgesTex, searchTex, offset[ 0 ].xy, offset[ 2 ].x );
coords.y = offset[ 1 ].y; // offset[1].y = texcoord.y - 0.25 * resolution.y (@CROSSING_OFFSET)
d.x = coords.x;
// Now fetch the left crossing edges, two at a time using bilinear
// filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to
// discern what value each edge has:
float e1 = texture2D( edgesTex, coords, 0.0 ).r;
// Find the distance to the right:
coords.x = SMAASearchXRight( edgesTex, searchTex, offset[ 0 ].zw, offset[ 2 ].y );
d.y = coords.x;
// We want the distances to be in pixel units (doing this here allow to
// better interleave arithmetic and memory accesses):
d = d / resolution.x - pixcoord.x;
// SMAAArea below needs a sqrt, as the areas texture is compressed
// quadratically:
vec2 sqrt_d = sqrt( abs( d ) );
// Fetch the right crossing edges:
coords.y -= 1.0 * resolution.y; // WebGL port note: Added
float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 1, 0 ) ).r;
// Ok, we know how this pattern looks like, now it is time for getting
// the actual area:
weights.rg = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.y ) );
}
if ( e.r > 0.0 ) { // Edge at west
vec2 d;
// Find the distance to the top:
vec2 coords;
coords.y = SMAASearchYUp( edgesTex, searchTex, offset[ 1 ].xy, offset[ 2 ].z );
coords.x = offset[ 0 ].x; // offset[1].x = texcoord.x - 0.25 * resolution.x;
d.x = coords.y;
// Fetch the top crossing edges:
float e1 = texture2D( edgesTex, coords, 0.0 ).g;
// Find the distance to the bottom:
coords.y = SMAASearchYDown( edgesTex, searchTex, offset[ 1 ].zw, offset[ 2 ].w );
d.y = coords.y;
// We want the distances to be in pixel units:
d = d / resolution.y - pixcoord.y;
// SMAAArea below needs a sqrt, as the areas texture is compressed
// quadratically:
vec2 sqrt_d = sqrt( abs( d ) );
// Fetch the bottom crossing edges:
coords.y -= 1.0 * resolution.y; // WebGL port note: Added
float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 0, 1 ) ).g;
// Get the area for this direction:
weights.ba = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.x ) );
}
return weights;
}
void main() {
gl_FragColor = SMAABlendingWeightCalculationPS( vUv, vPixcoord, vOffset, tDiffuse, tArea, tSearch, ivec4( 0.0 ) );
}`},Nie={name:"SMAABlendShader",uniforms:{tDiffuse:{value:null},tColor:{value:null},resolution:{value:new si(1/1024,1/512)}},vertexShader:`
uniform vec2 resolution;
varying vec2 vUv;
varying vec4 vOffset[ 2 ];
void SMAANeighborhoodBlendingVS( vec2 texcoord ) {
vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component
vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component
}
void main() {
vUv = uv;
SMAANeighborhoodBlendingVS( vUv );
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,fragmentShader:`
uniform sampler2D tDiffuse;
uniform sampler2D tColor;
uniform vec2 resolution;
varying vec2 vUv;
varying vec4 vOffset[ 2 ];
vec4 SMAANeighborhoodBlendingPS( vec2 texcoord, vec4 offset[ 2 ], sampler2D colorTex, sampler2D blendTex ) {
// Fetch the blending weights for current pixel:
vec4 a;
a.xz = texture2D( blendTex, texcoord ).xz;
a.y = texture2D( blendTex, offset[ 1 ].zw ).g;
a.w = texture2D( blendTex, offset[ 1 ].xy ).a;
// Is there any blending weight with a value greater than 0.0?
if ( dot(a, vec4( 1.0, 1.0, 1.0, 1.0 )) < 1e-5 ) {
return texture2D( colorTex, texcoord, 0.0 );
} else {
// Up to 4 lines can be crossing a pixel (one through each edge). We
// favor blending by choosing the line with the maximum weight for each
// direction:
vec2 offset;
offset.x = a.a > a.b ? a.a : -a.b; // left vs. right
offset.y = a.g > a.r ? -a.g : a.r; // top vs. bottom // WebGL port note: Changed signs
// Then we go in the direction that has the maximum weight:
if ( abs( offset.x ) > abs( offset.y )) { // horizontal vs. vertical
offset.y = 0.0;
} else {
offset.x = 0.0;
}
// Fetch the opposite color and lerp by hand:
vec4 C = texture2D( colorTex, texcoord, 0.0 );
texcoord += sign( offset ) * resolution;
vec4 Cop = texture2D( colorTex, texcoord, 0.0 );
float s = abs( offset.x ) > abs( offset.y ) ? abs( offset.x ) : abs( offset.y );
// WebGL port note: Added gamma correction
C.xyz = pow(C.xyz, vec3(2.2));
Cop.xyz = pow(Cop.xyz, vec3(2.2));
vec4 mixed = mix(C, Cop, s);
mixed.xyz = pow(mixed.xyz, vec3(1.0 / 2.2));
return mixed;
}
}
void main() {
gl_FragColor = SMAANeighborhoodBlendingPS( vUv, vOffset, tColor, tDiffuse );
}`};var Oie=class extends _0{constructor(){super(),this._edgesRT=new bo(1,1,{depthBuffer:!1,type:Ao}),this._edgesRT.texture.name="SMAAPass.edges",this._weightsRT=new bo(1,1,{depthBuffer:!1,type:Ao}),this._weightsRT.texture.name="SMAAPass.weights";let t=this,i=new Image;i.src=this._getAreaTexture(),i.onload=function(){t._areaTexture.needsUpdate=!0},this._areaTexture=new Ur,this._areaTexture.name="SMAAPass.area",this._areaTexture.image=i,this._areaTexture.minFilter=Ds,this._areaTexture.generateMipmaps=!1,this._areaTexture.flipY=!1;let n=new Image;n.src=this._getSearchTexture(),n.onload=function(){t._searchTexture.needsUpdate=!0},this._searchTexture=new Ur,this._searchTexture.name="SMAAPass.search",this._searchTexture.image=n,this._searchTexture.magFilter=Us,this._searchTexture.minFilter=Us,this._searchTexture.generateMipmaps=!1,this._searchTexture.flipY=!1,this._uniformsEdges=xu.clone(cq.uniforms),this._materialEdges=new Bs({defines:Object.assign({},cq.defines),uniforms:this._uniformsEdges,vertexShader:cq.vertexShader,fragmentShader:cq.fragmentShader}),this._uniformsWeights=xu.clone(dq.uniforms),this._uniformsWeights.tDiffuse.value=this._edgesRT.texture,this._uniformsWeights.tArea.value=this._areaTexture,this._uniformsWeights.tSearch.value=this._searchTexture,this._materialWeights=new Bs({defines:Object.assign({},dq.defines),uniforms:this._uniformsWeights,vertexShader:dq.vertexShader,fragmentShader:dq.fragmentShader}),this._uniformsBlend=xu.clone(Nie.uniforms),this._uniformsBlend.tDiffuse.value=this._weightsRT.texture,this._materialBlend=new Bs({uniforms:this._uniformsBlend,vertexShader:Nie.vertexShader,fragmentShader:Nie.fragmentShader}),this._fsQuad=new sm(null)}render(t,i,n){this._uniformsEdges.tDiffuse.value=n.texture,this._fsQuad.material=this._materialEdges,t.setRenderTarget(this._edgesRT),this.clear&&t.clear(),this._fsQuad.render(t),this._fsQuad.material=this._materialWeights,t.setRenderTarget(this._weightsRT),this.clear&&t.clear(),this._fsQuad.render(t),this._uniformsBlend.tColor.value=n.texture,this._fsQuad.material=this._materialBlend,this.renderToScreen?(t.setRenderTarget(null),this._fsQuad.render(t)):(t.setRenderTarget(i),this.clear&&t.clear(),this._fsQuad.render(t))}setSize(t,i){this._edgesRT.setSize(t,i),this._weightsRT.setSize(t,i),this._materialEdges.uniforms.resolution.value.set(1/t,1/i),this._materialWeights.uniforms.resolution.value.set(1/t,1/i),this._materialBlend.uniforms.resolution.value.set(1/t,1/i)}dispose(){this._edgesRT.dispose(),this._weightsRT.dispose(),this._areaTexture.dispose(),this._searchTexture.dispose(),this._materialEdges.dispose(),this._materialWeights.dispose(),this._materialBlend.dispose(),this._fsQuad.dispose()}_getAreaTexture(){return"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAAIwCAIAAACOVPcQAACBeklEQVR42u39W4xlWXrnh/3WWvuciIzMrKxrV8/0rWbY0+SQFKcb4owIkSIFCjY9AC1BT/LYBozRi+EX+cV+8IMsYAaCwRcBwjzMiw2jAWtgwC8WR5Q8mDFHZLNHTarZGrLJJllt1W2qKrsumZWZcTvn7L3W54e1vrXX3vuciLPPORFR1XE2EomorB0nVuz//r71re/y/1eMvb4Cb3N11xV/PP/2v4UBAwJG/7H8urx6/25/Gf8O5hypMQ0EEEQwAqLfoN/Z+97f/SW+/NvcgQk4sGBJK6H7N4PFVL+K+e0N11yNfkKvwUdwdlUAXPHHL38oa15f/i/46Ih6SuMSPmLAYAwyRKn7dfMGH97jaMFBYCJUgotIC2YAdu+LyW9vvubxAP8kAL8H/koAuOKP3+q6+xGnd5kdYCeECnGIJViwGJMAkQKfDvB3WZxjLKGh8VSCCzhwEWBpMc5/kBbjawT4HnwJfhr+pPBIu7uu+OOTo9vsmtQcniMBGkKFd4jDWMSCRUpLjJYNJkM+IRzQ+PQvIeAMTrBS2LEiaiR9b/5PuT6Ap/AcfAFO4Y3dA3DFH7/VS+M8k4baEAQfMI4QfbVDDGIRg7GKaIY52qAjTAgTvGBAPGIIghOCYAUrGFNgzA7Q3QhgCwfwAnwe5vDejgG44o/fbm1C5ZlYQvQDARPAIQGxCWBM+wWl37ZQESb4gImexGMDouhGLx1Cst0Saa4b4AqO4Hk4gxo+3DHAV/nx27p3JziPM2pVgoiia5MdEzCGULprIN7gEEeQ5IQxEBBBQnxhsDb5auGmAAYcHMA9eAAz8PBol8/xij9+C4Djlim4gJjWcwZBhCBgMIIYxGAVIkH3ZtcBuLdtRFMWsPGoY9rN+HoBji9VBYdwD2ZQg4cnO7OSq/z4rU5KKdwVbFAjNojCQzTlCLPFSxtamwh2jMUcEgg2Wm/6XgErIBhBckQtGN3CzbVacERgCnfgLswhnvqf7QyAq/z4rRZm1YglYE3affGITaZsdIe2FmMIpnOCap25I6jt2kCwCW0D1uAD9sZctNGXcQIHCkINDQgc78aCr+zjtw3BU/ijdpw3zhCwcaONwBvdeS2YZKkJNJsMPf2JKEvC28RXxxI0ASJyzQCjCEQrO4Q7sFArEzjZhaFc4cdv+/JFdKULM4px0DfUBI2hIsy06BqLhGTQEVdbfAIZXYMPesq6VoCHICzUyjwInO4Y411//LYLs6TDa9wvg2CC2rElgAnpTBziThxaL22MYhzfkghz6GAs2VHbbdM91VZu1MEEpupMMwKyV
`)a=0,u-=r;else{let m=eut(p,o,a,u,i);n=="tb"?(a=0,u+=i.ascender*o):a+=m.offsetX,l.push(m.path)}}return l}function eut(e,t,i,n,s){let o=s.glyphs[e]||s.glyphs["?"];if(!o){console.error('THREE.Font: character "'+e+'" does not exists in font family '+s.familyName+".");return}let r=new y8,l,a,u,h,p,m,I,g;if(o.o){let E=o._cachedOutline||(o._cachedOutline=o.o.split(" "));for(let w=0,T=E.length;w<T;)switch(E[w++]){case"m":l=E[w++]*t+i,a=E[w++]*t+n,r.moveTo(l,a);break;case"l":l=E[w++]*t+i,a=E[w++]*t+n,r.lineTo(l,a);break;case"q":u=E[w++]*t+i,h=E[w++]*t+n,p=E[w++]*t+i,m=E[w++]*t+n,r.quadraticCurveTo(p,m,u,h);break;case"b":u=E[w++]*t+i,h=E[w++]*t+n,p=E[w++]*t+i,m=E[w++]*t+n,I=E[w++]*t+i,g=E[w++]*t+n,r.bezierCurveTo(p,m,I,g,u,h);break}}return{offsetX:o.ha*t,path:r}}var tut=Object.defineProperty,iut=(e,t,i)=>t in e?tut(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Ge=(e,t,i)=>(iut(e,typeof t!="symbol"?t+"":t,i),i);var yu={LEFT:1,RIGHT:2,MIDDLE:4},vi=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,SCREEN_PAN:4,OFFSET:8,DOLLY:16,ZOOM:32,TOUCH_ROTATE:64,TOUCH_TRUCK:128,TOUCH_SCREEN_PAN:256,TOUCH_OFFSET:512,TOUCH_DOLLY:1024,TOUCH_ZOOM:2048,TOUCH_DOLLY_TRUCK:4096,TOUCH_DOLLY_SCREEN_PAN:8192,TOUCH_DOLLY_OFFSET:16384,TOUCH_DOLLY_ROTATE:32768,TOUCH_ZOOM_TRUCK:65536,TOUCH_ZOOM_OFFSET:131072,TOUCH_ZOOM_SCREEN_PAN:262144,TOUCH_ZOOM_ROTATE:524288}),RU={NONE:0,IN:1,OUT:-1};function AP(e){return e.isPerspectiveCamera}function QD(e){return e.isOrthographicCamera}var qD=Math.PI*2,jDe=Math.PI/2,y6e=1e-5,Sq=Math.PI/180;function E3(e,t,i){return Math.max(t,Math.min(i,e))}function hl(e,t=y6e){return Math.abs(e)<t}function Pr(e,t,i=y6e){return hl(e-t,i)}function YDe(e,t){return Math.round(e/t)*t}function Rq(e){return isFinite(e)?e:e<0?-Number.MAX_VALUE:Number.MAX_VALUE}function _q(e){return Math.abs(e)<Number.MAX_VALUE?e:e*(1/0)}function Kie(e,t,i,n,s=1/0,o){n=Math.max(1e-4,n);let r=2/n,l=r*o,a=1/(1+l+.48*l*l+.235*l*l*l),u=e-t,h=t,p=s*n;u=E3(u,-p,p),t=e-u;let m=(i.value+r*u)*o;i.value=(i.value-r*m)*a;let I=t+(u+m)*a;return h-e>0==I>h&&(I=h,i.value=(I-h)/o),I}function qDe(e,t,i,n,s=1/0,o,r){n=Math.max(1e-4,n);let l=2/n,a=l*o,u=1/(1+a+.48*a*a+.235*a*a*a),h=t.x,p=t.y,m=t.z,I=e.x-h,g=e.y-p,E=e.z-m,w=h,T=p,S=m,_=s*n,x=_*_,M=I*I+g*g+E*E;if(M>x){let Te=Math.sqrt(M);I=I/Te*_,g=g/Te*_,E=E/Te*_}h=e.x-I,p=e.y-g,m=e.z-E;let W=(i.x+l*I)*o,G=(i.y+l*g)*o,$=(i.z+l*E)*o;i.x=(i.x-l*W)*u,i.y=(i.y-l*G)*u,i.z=(i.z-l*$)*u,r.x=h+(I+W)*u,r.y=p+(g+G)*u,r.z=m+(E+$)*u;let Y=w-e.x,se=T-e.y,pe=S-e.z,k=r.x-w,fe=r.y-T,Q=r.z-S;return Y*k+se*fe+pe*Q>0&&(r.x=w,r.y=T,r.z=S,i.x=(r.x-w)/o,i.y=(r.y-T)/o,i.z=(r.z-S)/o),r}function d1e(e,t){t.set(0,0),e.forEach(i=>{t.x+=i.clientX,t.y+=i.clientY}),t.x/=e.length,t.y/=e.length}function h1e(e,t){return QD(e)?(console.warn(`${t} is not supported in OrthographicCamera`),!0):!1}var F1e=class{constructor(){Ge(this,"_listeners",{})}addEventListener(t,i){let n=this._listeners;n[t]===void 0&&(n[t]=[]),n[t].indexOf(i)===-1&&n[t].push(i)}hasEventListener(t,i){let n=this._listeners;return n[t]!==void 0&&n[t].indexOf(i)!==-1}removeEventListener(t,i){let n=this._listeners[t];if(n!==void 0){let s=n.indexOf(i);s!==-1&&n.splice(s,1)}}removeAllEventListeners(t){if(!t){this._listeners={};return}Array.isArray(this._listeners[t])&&(this._listeners[t].length=0)}dispatchEvent(t){let i=this._listeners[t.type];if(i!==void 0){t.target=this;let n=i.slice(0);for(let s=0,o=n.length;s<o;s++)n[s].call(this,t)}}},nut="3.1.2",Qie=1/8,$De,sut=/Mac/.test(($De=globalThis?.navigator)==null?void 0:$De.platform),Ws,ZDe,Jie,f1e,Sy,yo,wr,_U,bq,HS,GS,xP,KDe,QDe,ng,bU,AU,JDe,p1e,XDe,m1e,I1e,Xie,_I=class e extends F1e{constructor(t,i){super(),Ge(this,"minPolarAngle",0),Ge(this,"maxPolarAngle",Math.PI),Ge(this,"minAzimuthAngle",-1/0),Ge(this,"maxAzimuthAngle",1/0),Ge(this,"minDistance",Number.EPSILON),Ge(this,"maxDistance",1/0),Ge(this,"infinityDolly",!1),Ge(this,"minZoom",.01),Ge(this,"maxZoom",1/0),Ge(this,"smoothTime",.25),Ge(this,"draggingSmoothTime",.125),Ge(this,"maxSpeed",1/0),Ge(this,"azimuthRotateSpeed",1),Ge(this,"polarRotateSpeed",1),Ge(this,"dollySpeed",1),Ge(this,"dol
- If you're the tool creator, you can take one from https://www.uuidgenerator.net/.
- If you're using a platform tool, verify the uuid isn't misspelled or contact the tool creator.`)}};Ke(TEe,"_pattern",/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/);Ke(TEe,"_lut",["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"]);var x0=TEe,E6e=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",lut=E6e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",aut="["+E6e+"]["+lut+"]*",uut=new RegExp("^"+aut+"$");function T6e(e,t){let i=[],n=t.exec(e);for(;n;){let s=[];s.startIndex=t.lastIndex-n[0].length;let o=n.length;for(let r=0;r<o;r++)s.push(n[r]);i.push(s),n=t.exec(e)}return i}var cse=function(e){let t=uut.exec(e);return!(t===null||typeof t>"u")};function cut(e){return typeof e<"u"}var dut={allowBooleanAttributes:!1,unpairedTags:[]};function hut(e,t){t=Object.assign({},dut,t);let i=[],n=!1,s=!1;e[0]==="\uFEFF"&&(e=e.substr(1));for(let o=0;o<e.length;o++)if(e[o]==="<"&&e[o+1]==="?"){if(o+=2,o=tNe(e,o),o.err)return o}else if(e[o]==="<"){let r=o;if(o++,e[o]==="!"){o=iNe(e,o);continue}else{let l=!1;e[o]==="/"&&(l=!0,o++);let a="";for(;o<e.length&&e[o]!==">"&&e[o]!==" "&&e[o]!==" "&&e[o]!==`
`&&e[o]!=="\r";o++)a+=e[o];if(a=a.trim(),a[a.length-1]==="/"&&(a=a.substring(0,a.length-1),o--),!Tut(a)){let p;return a.trim().length===0?p="Invalid space after '<'.":p="Tag '"+a+"' is an invalid name.",hd("InvalidTag",p,RI(e,o))}let u=mut(e,o);if(u===!1)return hd("InvalidAttr","Attributes for '"+a+"' have open quote.",RI(e,o));let h=u.value;if(o=u.index,h[h.length-1]==="/"){let p=o-h.length;h=h.substring(0,h.length-1);let m=nNe(h,t);if(m===!0)n=!0;else return hd(m.err.code,m.err.msg,RI(e,p+m.err.line))}else if(l)if(u.tagClosed){if(h.trim().length>0)return hd("InvalidTag","Closing tag '"+a+"' can't have attributes or invalid starting.",RI(e,r));if(i.length===0)return hd("InvalidTag","Closing tag '"+a+"' has not been opened.",RI(e,r));{let p=i.pop();if(a!==p.tagName){let m=RI(e,p.tagStartPos);return hd("InvalidTag","Expected closing tag '"+p.tagName+"' (opened in line "+m.line+", col "+m.col+") instead of closing tag '"+a+"'.",RI(e,r))}i.length==0&&(s=!0)}}else return hd("InvalidTag","Closing tag '"+a+"' doesn't have proper closing.",RI(e,o));else{let p=nNe(h,t);if(p!==!0)return hd(p.err.code,p.err.msg,RI(e,o-h.length+p.err.line));if(s===!0)return hd("InvalidXml","Multiple possible root nodes found.",RI(e,o));t.unpairedTags.indexOf(a)!==-1||i.push({tagName:a,tagStartPos:r}),n=!0}for(o++;o<e.length;o++)if(e[o]==="<")if(e[o+1]==="!"){o++,o=iNe(e,o);continue}else if(e[o+1]==="?"){if(o=tNe(e,++o),o.err)return o}else break;else if(e[o]==="&"){let p=gut(e,o);if(p==-1)return hd("InvalidChar","char '&' is not expected.",RI(e,o));o=p}else if(s===!0&&!eNe(e[o]))return hd("InvalidXml","Extra text at the end",RI(e,o));e[o]==="<"&&o--}}else{if(eNe(e[o]))continue;return hd("InvalidChar","char '"+e[o]+"' is not expected.",RI(e,o))}if(n){if(i.length==1)return hd("InvalidTag","Unclosed tag '"+i[0].tagName+"'.",RI(e,i[0].tagStartPos));if(i.length>0)return hd("InvalidXml","Invalid '"+JSON.stringify(i.map(o=>o.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return hd("InvalidXml","Start tag expected.",1);return!0}function eNe(e){return e===" "||e===" "||e===`
`||e==="\r"}function tNe(e,t){let i=t;for(;t<e.length;t++)if(e[t]=="?"||e[t]==" "){let n=e.substr(i,t-i);if(t>5&&n==="xml")return hd("InvalidXml","XML declaration allowed only at the start of the document.",RI(e,t));if(e[t]=="?"&&e[t+1]==">"){t++;break}else continue}return t}function iNe(e,t){if(e.length>t+5&&e[t+1]==="-"&&e[t+2]==="-"){for(t+=3;t<e.length;t++)if(e[t]==="-"&&e[t+1]==="-"&&e[t+2]===">"){t+=2;break}}else if(e.length>t+8&&e[t+1]==="D"&&e[t+2]==="O"&&e[t+3]==="C"&&e[t+4]==="T"&&e[t+5]==="Y"&&e[t+6]==="P"&&e[t+7]==="E"){let i=1;for(t+=8;t<e.length;t++)if(e[t]==="<")i++;else if(e[t]===">"&&(i--,i===0))break}else if(e.length>t+9&&e[t+1]==="["&&e[t+2]==="C"&&e[t+3]==="D"&&e[t+4]==="A"&&e[t+5]==="T"&&e[t+6]==="A"&&e[t+7]==="["){for(t+=8;t<e.length;t++)if(e[t]==="]"&&e[t+1]==="]"&&e[t+2]===">"){t+=2;break}}return t}var fut='"',put="'";function mut(e,t){let i="",n="",s=!1;for(;t<e.length;t++){if(e[t]===fut||e[t]===put)n===""?n=e[t]:n!==e[t]||(n="");else if(e[t]===">"&&n===""){s=!0;break}i+=e[t]}return n!==""?!1:{value:i,index:t,tagClosed:s}}var Iut=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function nNe(e,t){let i=T6e(e,Iut),n={};for(let s=0;s<i.length;s++){if(i[s][1].length===0)return hd("InvalidAttr","Attribute '"+i[s][2]+"' has no space in starting.",Aq(i[s]));if(i[s][3]!==void 0&&i[s][4]===void 0)return hd("InvalidAttr","Attribute '"+i[s][2]+"' is without value.",Aq(i[s]));if(i[s][3]===void 0&&!t.allowBooleanAttributes)return hd("InvalidAttr","boolean attribute '"+i[s][2]+"' is not allowed.",Aq(i[s]));let o=i[s][2];if(!Eut(o))return hd("InvalidAttr","Attribute '"+o+"' is an invalid name.",Aq(i[s]));if(!n.hasOwnProperty(o))n[o]=1;else return hd("InvalidAttr","Attribute '"+o+"' is repeated.",Aq(i[s]))}return!0}function yut(e,t){let i=/\d/;for(e[t]==="x"&&(t++,i=/[\da-fA-F]/);t<e.length;t++){if(e[t]===";")return t;if(!e[t].match(i))break}return-1}function gut(e,t){if(t++,e[t]===";")return-1;if(e[t]==="#")return t++,yut(e,t);let i=0;for(;t<e.length;t++,i++)if(!(e[t].match(/\w/)&&i<20)){if(e[t]===";")break;return-1}return t}function hd(e,t,i){return{err:{code:e,msg:t,line:i.line||i,col:i.col}}}function Eut(e){return cse(e)}function Tut(e){return cse(e)}function RI(e,t){let i=e.substring(0,t).split(/\r?\n/);return{line:i.length,col:i[i.length-1].length+1}}function Aq(e){return e.startIndex+e[1].length}var wut={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,i){return e},captureMetaData:!1};function w6e(e){return typeof e=="boolean"?{enabled:e,maxEntitySize:1e4,maxExpansionDepth:10,maxTotalExpansions:1e3,maxExpandedLength:1e5,allowedTags:null,tagFilter:null}:typeof e=="object"&&e!==null?{enabled:e.enabled!==!1,maxEntitySize:e.maxEntitySize??1e4,maxExpansionDepth:e.maxExpansionDepth??10,maxTotalExpansions:e.maxTotalExpansions??1e3,maxExpandedLength:e.maxExpandedLength??1e5,allowedTags:e.allowedTags??null,tagFilter:e.tagFilter??null}:w6e(!0)}var vut=function(e){let t=Object.assign({},wut,e);return t.processEntities=w6e(t.processEntities),t},Gne;typeof Symbol!="function"?Gne="@@xmlMetadata":Gne=Symbol("XML Node Metadata");var aA=class{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,i){t==="__proto__"&&(t="#__proto__"),this.child.push({[t]:i})}addChild(t,i){t.tagname==="__proto__"&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),i!==void 0&&(this.child[this.child.length-1][Gne]={startIndex:i})}static getMetaDataSymbol(){return Gne}},
`);let t=new aA("!xml"),i=t,n="",s="";this.entityExpansionCount=0,this.currentExpandedLength=0;let o=new V1e(this.options.processEntities);for(let r=0;r<e.length;r++)if(e[r]==="<")if(e[r+1]==="/"){let l=MP(e,">",r,"Closing Tag is not closed."),a=e.substring(r+2,l).trim();if(this.options.removeNSPrefix){let p=a.indexOf(":");p!==-1&&(a=a.substr(p+1))}this.options.transformTagName&&(a=this.options.transformTagName(a)),i&&(n=this.saveTextToParentTag(n,i,s));let u=s.substring(s.lastIndexOf(".")+1);if(a&&this.options.unpairedTags.indexOf(a)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${a}>`);let h=0;u&&this.options.unpairedTags.indexOf(u)!==-1?(h=s.lastIndexOf(".",s.lastIndexOf(".")-1),this.tagsNodeStack.pop()):h=s.lastIndexOf("."),s=s.substring(0,h),i=this.tagsNodeStack.pop(),n="",r=l}else if(e[r+1]==="?"){let l=z1e(e,r,!1,"?>");if(!l)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,i,s),!(this.options.ignoreDeclaration&&l.tagName==="?xml"||this.options.ignorePiTags)){let a=new aA(l.tagName);a.add(this.options.textNodeName,""),l.tagName!==l.tagExp&&l.attrExpPresent&&(a[":@"]=this.buildAttributesMap(l.tagExp,s,l.tagName)),this.addChild(i,a,s,r)}r=l.closeIndex+1}else if(e.substr(r+1,3)==="!--"){let l=MP(e,"-->",r+4,"Comment is not closed.");if(this.options.commentPropName){let a=e.substring(r+4,l-2);n=this.saveTextToParentTag(n,i,s),i.add(this.options.commentPropName,[{[this.options.textNodeName]:a}])}r=l}else if(e.substr(r+1,2)==="!D"){let l=o.readDocType(e,r);this.docTypeEntities=l.entities,r=l.i}else if(e.substr(r+1,2)==="!["){let l=MP(e,"]]>",r,"CDATA is not closed.")-2,a=e.substring(r+9,l);n=this.saveTextToParentTag(n,i,s);let u=this.parseTextData(a,i.tagname,s,!0,!1,!0,!0);u==null&&(u=""),this.options.cdataPropName?i.add(this.options.cdataPropName,[{[this.options.textNodeName]:a}]):i.add(this.options.textNodeName,u),r=l+2}else{let l=z1e(e,r,this.options.removeNSPrefix),a=l.tagName,u=l.rawTagName,h=l.tagExp,p=l.attrExpPresent,m=l.closeIndex;if(this.options.transformTagName){let E=this.options.transformTagName(a);h===a&&(h=E),a=E}i&&n&&i.tagname!=="!xml"&&(n=this.saveTextToParentTag(n,i,s,!1));let I=i;I&&this.options.unpairedTags.indexOf(I.tagname)!==-1&&(i=this.tagsNodeStack.pop(),s=s.substring(0,s.lastIndexOf("."))),a!==t.tagname&&(s+=s?"."+a:a);let g=r;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,s,a)){let E="";if(h.length>0&&h.lastIndexOf("/")===h.length-1)a[a.length-1]==="/"?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),h=a):h=h.substr(0,h.length-1),r=l.closeIndex;else if(this.options.unpairedTags.indexOf(a)!==-1)r=l.closeIndex;else{let T=this.readStopNodeData(e,u,m+1);if(!T)throw new Error(`Unexpected end of ${u}`);r=T.i,E=T.tagContent}let w=new aA(a);a!==h&&p&&(w[":@"]=this.buildAttributesMap(h,s,a)),E&&(E=this.parseTextData(E,a,s,!0,p,!0,!0)),s=s.substr(0,s.lastIndexOf(".")),w.add(this.options.textNodeName,E),this.addChild(i,w,s,g)}else{if(h.length>0&&h.lastIndexOf("/")===h.length-1){if(a[a.length-1]==="/"?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),h=a):h=h.substr(0,h.length-1),this.options.transformTagName){let w=this.options.transformTagName(a);h===a&&(h=w),a=w}let E=new aA(a);a!==h&&p&&(E[":@"]=this.buildAttributesMap(h,s,a)),this.addChild(i,E,s,g),s=s.substr(0,s.lastIndexOf("."))}else{let E=new aA(a);this.tagsNodeStack.push(i),a!==h&&p&&(E[":@"]=this.buildAttributesMap(h,s,a)),this.addChild(i,E,s,g),i=E}n="",r=m}}else n+=e[r];return t.child};function Fut(e,t,i,n){this.options.captureMetaData||(n=void 0);let s=this.options.updateTag(t.tagname,i,t[":@"]);s===!1||(typeof s=="string"&&(t.tagname=s),e.addChild(t,n))}var Uut=function(e,t,i){if(e.indexOf("&")===-1)return e;let n=this.options.processEntities;if(!n.enabled||n.allowedTags&&!n.allowedTags.includes(t)||n.tagFilter&&!n.tagFilter(t,i))return e;for(let s in this.docTypeEntities){let o=this.docTypeEntities[s],r=e.match(o.regx);if(r){if(this.entityExpansionCount+=r.length,n.maxTotalExpansions&&this.entityExpansionCount>n.maxTotalExpansions)throw new Error(`Entity expansion limit ex
`;function $ut(e,t){let i="";return t.format&&t.indentBy.length>0&&(i=qut),R6e(e,t,"",i)}function R6e(e,t,i,n){let s="",o=!1;for(let r=0;r<e.length;r++){let l=e[r],a=Zut(l);if(a===void 0)continue;let u="";if(i.length===0?u=a:u=`${i}.${a}`,a===t.textNodeName){let g=l[a];Kut(u,t)||(g=t.tagValueProcessor(a,g),g=_6e(g,t)),o&&(s+=n),s+=g,o=!1;continue}else if(a===t.cdataPropName){o&&(s+=n),s+=`<![CDATA[${l[a][0][t.textNodeName]}]]>`,o=!1;continue}else if(a===t.commentPropName){s+=n+`<!--${l[a][0][t.textNodeName]}-->`,o=!0;continue}else if(a[0]==="?"){let g=oNe(l[":@"],t),E=a==="?xml"?"":n,w=l[a][0][t.textNodeName];w=w.length!==0?" "+w:"",s+=E+`<${a}${w}${g}?>`,o=!0;continue}let h=n;h!==""&&(h+=t.indentBy);let p=oNe(l[":@"],t),m=n+`<${a}${p}`,I=R6e(l[a],t,u,h);t.unpairedTags.indexOf(a)!==-1?t.suppressUnpairedNode?s+=m+">":s+=m+"/>":(!I||I.length===0)&&t.suppressEmptyNode?s+=m+"/>":I&&I.endsWith(">")?s+=m+`>${I}${n}</${a}>`:(s+=m+">",I&&n!==""&&(I.includes("/>")||I.includes("</"))?s+=n+t.indentBy+I+n:s+=I,s+=`</${a}>`),o=!0}return s}function Zut(e){let t=Object.keys(e);for(let i=0;i<t.length;i++){let n=t[i];if(e.hasOwnProperty(n)&&n!==":@")return n}}function oNe(e,t){let i="";if(e&&!t.ignoreAttributes)for(let n in e){if(!e.hasOwnProperty(n))continue;let s=t.attributeValueProcessor(n,e[n]);s=_6e(s,t),s===!0&&t.suppressBooleanAttributes?i+=` ${n.substr(t.attributeNamePrefix.length)}`:i+=` ${n.substr(t.attributeNamePrefix.length)}="${s}"`}return i}function Kut(e,t){e=e.substr(0,e.length-t.textNodeName.length-1);let i=e.substr(e.lastIndexOf(".")+1);for(let n in t.stopNodes)if(t.stopNodes[n]===e||t.stopNodes[n]==="*."+i)return!0;return!1}function _6e(e,t){if(e&&e.length>0&&t.processEntities)for(let i=0;i<t.entities.length;i++){let n=t.entities[i];e=e.replace(n.regex,n.val)}return e}var Qut={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function oN(e){this.options=Object.assign({},Qut,e),this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=v6e(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=ect),this.processTextOrObjNode=Jut,this.options.format?(this.indentate=Xut,this.tagEndChar=`>
`,this.newLine=`
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}oN.prototype.build=function(e){return this.options.preserveOrder?$ut(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)};oN.prototype.j2x=function(e,t,i){let n="",s="",o=i.join(".");for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r))if(typeof e[r]>"u")this.isAttribute(r)&&(s+="");else if(e[r]===null)this.isAttribute(r)||r===this.options.cdataPropName?s+="":r[0]==="?"?s+=this.indentate(t)+"<"+r+"?"+this.tagEndChar:s+=this.indentate(t)+"<"+r+"/"+this.tagEndChar;else if(e[r]instanceof Date)s+=this.buildTextValNode(e[r],r,"",t);else if(typeof e[r]!="object"){let l=this.isAttribute(r);if(l&&!this.ignoreAttributesFn(l,o))n+=this.buildAttrPairStr(l,""+e[r]);else if(!l)if(r===this.options.textNodeName){let a=this.options.tagValueProcessor(r,""+e[r]);s+=this.replaceEntitiesValue(a)}else s+=this.buildTextValNode(e[r],r,"",t)}else if(Array.isArray(e[r])){let l=e[r].length,a="",u="";for(let h=0;h<l;h++){let p=e[r][h];if(!(typeof p>"u"))if(p===null)r[0]==="?"?s+=this.indentate(t)+"<"+r+"?"+this.tagEndChar:s+=this.indentate(t)+"<"+r+"/"+this.tagEndChar;else if(typeof p=="object")if(this.options.oneListGroup){let m=this.j2x(p,t+1,i.concat(r));a+=m.val,this.options.attributesGroupName&&p.hasOwnProperty(this.options.attributesGroupName)&&(u+=m.attrStr)}else a+=this.processTextOrObjNode(p,r,t,i);else if(this.options.oneListGroup){let m=this.options.tagValueProcessor(r,p);m=this.replaceEntitiesValue(m),a+=m}else a+=this.buildTextValNode(p,r,"",t)}this.options.oneListGroup&&(a=this.buildObjectNode(a,r,u,t)),s+=a}else if(this.options.attributesGroupName&&r===this.options.attributesGroupName){let l=Object.keys(e[r]),a=l.length;for(let u=0;u<a;u++)n+=this.buildAttrPairStr(l[u],""+e[r][l[u]])}else s+=this.processTextOrObjNode(e[r],r,t,i);return{attrStr:n,val:s}};oN.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,""+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t==="true"?" "+e:" "+e+'="'+t+'"'};function Jut(e,t,i,n){let s=this.j2x(e,i+1,n.concat(t));return e[this.options.textNodeName]!==void 0&&Object.keys(e).length===1?this.buildTextValNode(e[this.options.textNodeName],t,s.attrStr,i):this.buildObjectNode(s.val,t,s.attrStr,i)}oN.prototype.buildObjectNode=function(e,t,i,n){if(e==="")return t[0]==="?"?this.indentate(n)+"<"+t+i+"?"+this.tagEndChar:this.indentate(n)+"<"+t+i+this.closeTag(t)+this.tagEndChar;{let s="</"+t+this.tagEndChar,o="";return t[0]==="?"&&(o="?",s=""),(i||i==="")&&e.indexOf("<")===-1?this.indentate(n)+"<"+t+i+o+">"+e+s:this.options.commentPropName!==!1&&t===this.options.commentPropName&&o.length===0?this.indentate(n)+`<!--${e}-->`+this.newLine:this.indentate(n)+"<"+t+i+o+this.tagEndChar+e+this.indentate(n)+s}};oN.prototype.closeTag=function(e){let t="";return this.options.unpairedTags.indexOf(e)!==-1?this.options.suppressUnpairedNode||(t="/"):this.options.suppressEmptyNode?t="/":t=`></${e}`,t};oN.prototype.buildTextValNode=function(e,t,i,n){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(n)+`<![CDATA[${e}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(n)+`<!--${e}-->`+this.newLine;if(t[0]==="?")return this.indentate(n)+"<"+t+i+"?"+this.tagEndChar;{let s=this.options.tagValueProcessor(t,e);return s=this.replaceEntitiesValue(s),s===""?this.indentate(n)+"<"+t+i+this.closeTag(t)+this.tagEndChar:this.indentate(n)+"<"+t+i+">"+s+"</"+t+this.tagEndChar}};oN.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){let i=this.options.entities[t];e=e.replace(i.regex,i.val)}return e};function Xut(e){return this.options.indentBy.repeat(e)}function ect(e){return e.startsWith(this.options.attributeNamePrefix)&&e!==this.options.textNodeName?e.substr(this.attrPrefixLen):!1}var zU=class{};Ke(zU,"parser",n
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
`,fragmentShader:`
layout(location = 0) out vec4 out_id;
uniform vec4 objectId;
void main() {
out_id = objectId;
}
`}),this._objectId=0,this.setValues(t)}},age=1e-16,odt=new ne(0,1,0),NNe=new ne;function ONe(e){return e.delta(NNe).normalize(),Math.abs(NNe.dot(odt))>=1-age}function uge(e,t){let{start:i,end:n}=t,s=e.points,o=!1,r=!1;for(let l=0;l<3;l++){let a=s[l];if(!o&&i.distanceToSquared(a)<=age&&(o=!0),!r&&n.distanceToSquared(a)<=age&&(r=!0),o&&r)return!0}return o&&r}var ZD=new wn;function LNe(e,t,i=!1,n=[]){let s=[[0,1]];for(let o=0,r=t.length;o<r;o++){let l=s[o],a=t[o];l[1]=a[0],s.push([a[1],1])}i&&([t,s]=[s,t]);for(let o=0,r=s.length;o<r;o++){let{start:l,end:a}=e;ZD.start.lerpVectors(l,a,s[o][0]),ZD.end.lerpVectors(l,a,s[o][1]),n.push(new Float32Array([ZD.start.x,ZD.start.y,ZD.start.z,ZD.end.x,ZD.end.y,ZD.end.z]))}return n}var PNe=1e-10,rdt=new ne(0,1,0),MNe=new ne,BNe=new ne,yne=new ne,gne=new Zo;function*FNe(e,t=[],i={}){let{projectionDirection:n=rdt,thresholdAngle:s=1,iterationTime:o=30}=i,r=Math.pow(10,4),l=Math.cos(Ns.DEG2RAD*s),a=e.getIndex(),u=e.getAttribute("position"),h=a?a.count:u.count,p=[0,0,0],m=["a","b","c"],I=new Array(3),g={},E=performance.now();for(let w=0;w<h;w+=3){performance.now()-E>o&&(yield,E=performance.now()),a?(p[0]=a.getX(w),p[1]=a.getX(w+1),p[2]=a.getX(w+2)):(p[0]=w,p[1]=w+1,p[2]=w+2);let{a:T,b:S,c:_}=gne;if(T.fromBufferAttribute(u,p[0]),S.fromBufferAttribute(u,p[1]),_.fromBufferAttribute(u,p[2]),gne.getNormal(yne),I[0]=`${Math.round(T.x*r)},${Math.round(T.y*r)},${Math.round(T.z*r)}`,I[1]=`${Math.round(S.x*r)},${Math.round(S.y*r)},${Math.round(S.z*r)}`,I[2]=`${Math.round(_.x*r)},${Math.round(_.y*r)},${Math.round(_.z*r)}`,!(I[0]===I[1]||I[1]===I[2]||I[2]===I[0]))for(let x=0;x<3;x++){let M=(x+1)%3,W=I[x],G=I[M],$=gne[m[x]],Y=gne[m[M]],se=`${W}_${G}`,pe=`${G}_${W}`;if(pe in g&&g[pe]){let k=g[pe].normal,fe=yne.dot(k)<=l,Q=!1;if(n!==null){let Te=n.dot(yne);Te=Math.abs(Te)<PNe?0:Te;let Ve=n.dot(k);Ve=Math.abs(Ve)<PNe?0:Ve,Q=Math.sign(Te)!==Math.sign(Ve)}if(fe||Q){let Te=new wn;Te.start.copy($),Te.end.copy(Y),t.push(Te)}g[pe]=null}else se in g||(g[se]={index0:p[x],index1:p[M],normal:yne.clone()})}}for(let w in g)if(g[w]){let{index0:T,index1:S}=g[w];MNe.fromBufferAttribute(u,T),BNe.fromBufferAttribute(u,S);let _=new wn;_.start.copy(MNe),_.end.copy(BNe),t.push(_)}return t}var Ene=new wn;function UNe(e,t,i,n=[]){return e.bvhcast(t,i,{intersectsTriangles:(s,o)=>{if(adt(s,o)||(s.needsUpdate&&s.update(),o.needsUpdate&&o.update(),Math.abs(s.plane.normal.dot(o.plane.normal))>1-1e-6))return!1;s.intersectsTriangle(o,Ene,!0)&&!uge(s,Ene)&&!uge(o,Ene)&&n.push(Ene.clone())}}),n}function ldt(e,t){return e.distanceTo(t)<1e-10}function adt(e,t){let i=["a","b","c"],n=0;for(let s=0;s<3;s++)for(let o=0;o<3;o++){let r=e[i[s]],l=t[i[o]];ldt(r,l)&&n++}return n>=2}function cge(e){M6e(e);let t=[];return e.traverse(i=>{i.geometry&&i.visible&&t.push(i)}),t}var M6e=e=>{if(e===void 0)return;let t=[...e.children];for(let i of t)i===void 0?e.children.splice(e.children.indexOf(i),1):M6e(i)},Tne=new di,HNe=new di,dge=class{constructor(){this.projectionDirection=new ne(0,1,0),this.thresholdAngle=50,this.iterationTime=30}getEdges(...t){let i=this.iterationTime;this.iterationTime=1/0;let n=this.getEdgesGenerator(...t).next().value;return this.iterationTime=i,n}*getEdgesGenerator(t,i=[],n=null){let{projectionDirection:s,thresholdAngle:o,iterationTime:r}=this;if(t.isObject3D){let l=cge(t),a=null;s&&(a=new ne);let u=performance.now();for(let h=0;h<l.length;h++){u-performance.now()>r&&(yield);let p=l[h];a&&(HNe.copy(p.matrixWorld).invert(),a.copy(s).transformDirection(HNe).normalize());let m=yield*FNe(p.geometry,[],{projectionDirection:a,thresholdAngle:o,iterationTime:r});GNe(m,p.matrixWorld);for(let I=0;I<m.length;I++)i.push(m[I]);if(n!==null)for(let I=0;I<m.length;I++)n.push(p)}return i}else return yield*FNe(t,i,{projectionDirection:s,thresholdAngle:o,iterationTime:r})}getIntersectionEdges(...t){let i=this.iterationTime;this.iterationTime=1/0;let n=this.getIntersectionEdgesGenerator(...t).next().value;return this.iterationTime=i,n}*getIntersectionEdgesGenerator(t,i=[],n=null){let{iterationTime:s}=this;if(t.isObject3D){let o=cge(t),r=new Map,
=== Projection Summary ===`),console.log(`Total time: ${e.toFixed(1)}ms
`);for(let[t,i]of Object.entries(Sne)){let n=(i/e*100).toFixed(1);console.log(` ${t}: ${i.toFixed(1)}ms (${n}%)`)}if(Object.keys(Bq).length>0){console.log(`
--- Stats ---`);for(let[t,i]of Object.entries(Bq))console.log(` ${t}: ${i}`)}console.log("")}},g3=1e-5,Rne=1e-16,_ne=1e-16;function Edt(e){let t=new Float32Array(e.length*6);for(let i=0;i<e.length;i++){let n=e[i];t[i*6+0]=n.start.x,t[i*6+1]=n.start.y,t[i*6+2]=n.start.z,t[i*6+3]=n.end.x,t[i*6+4]=n.end.y,t[i*6+5]=n.end.z}return t}function Tdt(e,t,i,n,s){e.bvhcast(t,i.matrixWorld,{intersectsRanges:(o,r,l,a)=>{n._edgeOffsets.push(o),n._edgeCounts.push(r),n._meshOffsets.push(l),n._meshCounts.push(a),n._meshIndex.push(s),n.groupCount++}})}var wdt=1e3,vdt=1e5,L1e=5,P1e=3,Sdt=2e6,Uq=null;async function Rdt(){return Uq===null&&(Uq=new PF,await Uq.init()),Uq}async function _dt(e,t,i,n,s=null){let o=await Rdt();e._edgeOffsets&&(e.edgeOffsets=new Uint32Array(e._edgeOffsets),e.edgeCounts=new Uint32Array(e._edgeCounts),e.meshOffsets=new Uint32Array(e._meshOffsets),e.meshCounts=new Uint32Array(e._meshCounts),e.meshIndex=new Uint32Array(e._meshIndex),e._edgeOffsets=null,e._edgeCounts=null,e._meshOffsets=null,e._meshCounts=null,e._meshIndex=null);let r=Jp(Edt(i.lines),"float");or.enabled&&console.log("Number of meshes:",t.length),or.enabled&&console.log("Group count:",e.groupCount);let l=[];{let g=0;for(;g<t.length;){let E=g,w=0;for(;E<t.length;){let T=t[E].geometry,S=T.index?T.index.count/3:T.attributes.position.count/3;if(E>g&&(E-g>=wdt||w+S>vdt))break;w+=S,E++}l.push({start:g,end:E}),g=E}}or.enabled&&console.log(`Split ${t.length} meshes into ${l.length} batches`);let a=0,u=0,h=0,p=0,m=0;for(let g=0;g<l.length;g++){let{start:E,end:w}=l[g],T=w-E;or.enabled&&console.log(`Processing batch ${g+1}/${l.length} (meshes ${E}-${w-1})`);let S=0,_=0,x=[];for(let Pt=E;Pt<w;Pt++){let $t=t[Pt].geometry;x.push(_/3),S+=$t.attributes.position.array.length,_+=$t.index.array.length}let M=new Float32Array(S),W=new Uint32Array(_),G=0,$=0,Y=0;for(let Pt=E;Pt<w;Pt++){let $t=t[Pt].geometry,Vt=$t.attributes.position.array,Ue=$t.index.array;M.set(Vt,G),G+=Vt.length;for(let Ft=0;Ft<Ue.length;Ft++)W[$+Ft]=Ue[Ft]+Y;$+=Ue.length,Y+=$t.attributes.position.count}let se=new Float32Array(T*16);for(let Pt=E;Pt<w;Pt++){let $t=Pt-E;se.set(t[Pt].matrixWorld.elements,$t*16)}let pe=[];for(let Pt=0;Pt<e.groupCount;Pt++){let $t=e.meshIndex[Pt];if($t>=E&&$t<w){let Vt=$t-E,Ue=x[Vt]+e.meshOffsets[Pt];pe.push({edgeOffset:e.edgeOffsets[Pt],edgeCount:e.edgeCounts[Pt],triOffset:Ue,triCount:e.meshCounts[Pt],meshIdx:Vt})}}if(pe.length===0){or.enabled&&console.log(` Batch ${g+1}: no groups, skipping`);continue}let k=new Uint32Array(pe.length*L1e);for(let Pt=0;Pt<pe.length;Pt++){let $t=pe[Pt],Vt=Pt*L1e;k[Vt+0]=$t.edgeOffset,k[Vt+1]=$t.edgeCount,k[Vt+2]=$t.triOffset,k[Vt+3]=$t.triCount,k[Vt+4]=$t.meshIdx}let fe=0;for(let Pt=0;Pt<pe.length;Pt++)fe+=pe[Pt].edgeCount*pe[Pt].triCount;s&&(s.candidates+=fe);let Q=Math.min(Math.ceil(fe*.1),Sdt),Te=Math.max(Q,1e4);or.enabled&&console.log(` Batch ${g+1}: ${pe.length} groups, ${S/3} vertices, ${_/3} triangles, ${fe} pairs, buffer for ${Te} overlaps`);let Ve=performance.now(),Fe=Jp(M,"float"),pt=Jp(W,"uint"),Me=Jp(se,"float"),He=Jp(k,"uint"),Ye=Jp(new Uint32Array([0]),"uint").toAtomic(),We=Jp(new Float32Array(Te*P1e),"float");p+=performance.now()-Ve;let _t=performance.now(),xt=Wee(()=>{let Pt=Yee.mul(L1e),$t=He.element(Pt),Vt=He.element(Pt.add(1)),Ue=He.element(Pt.add(2)),Ft=He.element(Pt.add(3)),ie=He.element(Pt.add(4)).mul(16),Oe=qee(Me.element(ie),Me.element(ie.add(1)),Me.element(ie.add(2)),Me.element(ie.add(3)),Me.element(ie.add(4)),Me.element(ie.add(5)),Me.element(ie.add(6)),Me.element(ie.add(7)),Me.element(ie.add(8)),Me.element(ie.add(9)),Me.element(ie.add(10)),Me.element(ie.add(11)),Me.element(ie.add(12)),Me.element(ie.add(13)),Me.element(ie.add(14)),Me.element(ie.add(15)));GF({start:VF(0),end:Ft.toInt(),type:"int",condition:"<",name:"triIdx"},({triIdx:Ce})=>{let Se=Ue.add(Ce.toUint()).mul(3),_e=pt.element(Se),je=pt.element(Se.add(1)),Be=pt.element(Se.add(2)),dt=Bo(Fe.element(_e.mul(3)),Fe.element(_e.mul(3).add(1)),Fe.element(_e.mul(3).add(2))),it=Bo(Fe.element(je.mul(3)),Fe.element(je.mul(3).add(1)),Fe.element(je.mul(3).add(2))),Rt=Bo(F
varying vec3 worldPosition;
uniform float uDistance;
void main() {
vec3 pos = position.xzy * uDistance;
pos.xz += cameraPosition.xz;
worldPosition = pos;
gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
}
`,fragmentShader:`
varying vec3 worldPosition;
uniform float uZoom;
uniform float uFade;
uniform float uSize1;
uniform float uSize2;
uniform vec3 uColor;
uniform float uDistance;
float getGrid(float size) {
vec2 r = worldPosition.xz / size;
vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);
float line = min(grid.x, grid.y);
return 1.0 - min(line, 1.0);
}
void main() {
float d = 1.0 - min(distance(cameraPosition.xz, worldPosition.xz) / uDistance, 1.0);
float g1 = getGrid(uSize1);
float g2 = getGrid(uSize2);
// Ortho camera fades the grid away when zooming out
float minZoom = step(0.2, uZoom);
float zoomFactor = pow(min(uZoom, 1.), 2.) * minZoom;
gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, uFade));
gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2) * zoomFactor;
if ( gl_FragColor.a <= 0.0 ) discard;
}
`,extensions:{derivatives:!0}});this.three=new ci(l,a),this.three.frustumCulled=!1,i.scene.three.add(this.three),this.setupEvents(!0)}get visible(){return this.three.visible}set visible(t){this.three.visible=t,t?this.world.scene.three.add(this.three):this.three.removeFromParent()}get material(){return this.three.material}get fade(){return this._fade===3}set fade(t){this._fade=t?3:0,this.material.uniforms.uFade.value=this._fade}setup(t){let i={...this._defaultConfig,...t};this.config.visible=!0,this.config.color=i.color,this.config.primarySize=i.primarySize,this.config.secondarySize=i.secondarySize,this.config.distance=i.distance,this.isSetup=!0,this.onSetup.trigger()}dispose(){this.setupEvents(!1),this.components.get(wEe).list.delete(this.config.uuid),this.components.get(v3).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset(),this.world=null,this.components=null}setupEvents(t){if(this.world.isDisposing||!(this.world.camera instanceof qq))return;let i=this.world.camera.controls;t?i.addEventListener("update",this.updateZoom):i.removeEventListener("update",this.updateZoom)}},Odt=class J6e extends fr{constructor(t){super(t),Ke(this,"list",new Map),Ke(this,"onDisposed",new Vi),Ke(this,"enabled",!0),t.add(J6e.uuid,this)}create(t){if(this.list.has(t.uuid))throw new Error("This world already has a grid!");let i=new _ge(this.components,t);return this.list.set(t.uuid,i),t.onDisposed.add(()=>{this.delete(t)}),i}delete(t){let i=this.list.get(t.uuid);i&&i.dispose(),this.list.delete(t.uuid)}dispose(){for(let[t,i]of this.list)i.dispose();this.list.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}};Ke(Odt,"uuid","d1e814d5-b81c-4452-87a2-f039375e0489");var X6e=class eOe{constructor(){Ke(this,"onDisposed",new Vi),Ke(this,"list",new Ln),Ke(this,"enabled",!1),Ke(this,"_clock"),Ke(this,"onInit",new Vi),Ke(this,"update",()=>{if(!this.enabled)return;let t=this._clock.getDelta();for(let[i,n]of this.list)n.enabled&&n.isUpdateable()&&n.update(t);requestAnimationFrame(this.update)}),this._clock=new qx,eOe.setupBVH()}add(t,i){if(this.list.has(t))throw new Error("You're trying to add a component that already exists in the components instance. Use Components.get() instead.");x0.validate(t),this.list.set(t,i)}get(t){var i;let n=t.uuid;if(!this.list.has(n)){let s=new t(this);return(i=s.isDisposeable)!=null&&i.call(s)&&s.onDisposed.add(()=>this.list.delete(n)),this.list.has(n)||this.add(n,s),s}return this.list.get(n)}init(){this.enabled=!0;for(let[t,i]of this.list.entries())i.enabled=!0;this._clock.start(),this.update(),this.onInit.trigger()}dispose(){this.enabled=!1;let t;for(let[i,n]of this.list){if(n.enabled=!1,i===xs.uuid){t=n;continue}n.isDisposeable()&&n.dispose()}t?.dispose(),this._clock.stop(),this.onDisposed.trigger()}static setupBVH(){Ni.prototype.computeBoundsTree=edt,Ni.prototype.disposeBoundsTree=tdt,ci.prototype.raycast=DNe,Rn.prototype.raycast=DNe}};Ke(X6e,"release","2.4.3");var tOe=X6e,bge=class{constructor(t){Ke(this,"enabled",!1),Ke(this,"id","FirstPerson"),this.camera=t}set(t){if(this.enabled=t,t){if(this.camera.projection.current!=="Perspective"){this.camera.set("Orbit");return}this.setupFirstPersonCamera()}}setupFirstPersonCamera(){let t=this.camera.controls,i=new ne;t.distance--,t.getPosition(i),t.minDistance=1,t.maxDistance=1,t.distance=1,t.moveTo(i.x,i.y,i.z),t.truckSpeed=50,t.mouseButtons.wheel=_I.ACTION.DOLLY,t.touches.two=_I.ACTION.TOUCH_ZOOM_TRUCK}},Age=class{constructor(t){Ke(this,"enabled",!0),Ke(this,"id","Orbit"),this.camera=t,this.activateOrbitControls()}set(t){this.enabled=t,t&&this.activateOrbitControls()}activateOrbitControls(){let t=this.camera.controls;t.minDistance=1,t.maxDistance=300;let i=new ne;t.getPosition(i);let n=i.length();t.distance=n,t.truckSpeed=2;let{rotation:s}=this.camera.three,o=new ne(0,0,-1).applyEuler(s),r=i.addScaledVector(o,n);t.moveTo(r.x,r.y,r.z)}},xge=class{constructor(t){Ke(this,"enabled",!1),Ke(this,"id","Plan"),Ke(this,"mouseAction1"),Ke(this,"mouseAction2"),Ke(this,"mouseInitialized",!1),Ke(this,"defaultAzimuthSpeed"),Ke(this,"defaultPolarSpeed"),th
\0`,xt+=o(Ye,2),xt+=W.magic,xt+=o(_,2),xt+=o(x,2),xt+=o(He.crc32,4),xt+=o(He.compressedSize,4),xt+=o(He.uncompressedSize,4),xt+=o($.length,2),xt+=o(Te.length,2),{fileRecord:p.LOCAL_FILE_HEADER+xt+$+Te,dirRecord:p.CENTRAL_FILE_HEADER+o(_t,2)+xt+o(pe.length,2)+"\0\0\0\0"+o(We,4)+o(w,4)+$+Te+pe}}var l=i("../utils"),a=i("../stream/GenericWorker"),u=i("../utf8"),h=i("../crc32"),p=i("../signature");function m(I,g,E,w){a.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=E,this.encodeFileName=w,this.streamFiles=I,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}l.inherits(m,a),m.prototype.push=function(I){var g=I.meta.percent||0,E=this.entriesCount,w=this._sources.length;this.accumulate?this.contentBuffer.push(I):(this.bytesWritten+=I.data.length,a.prototype.push.call(this,{data:I.data,meta:{currentFile:this.currentFile,percent:E?(g+100*(E-w-1))/E:100}}))},m.prototype.openedSource=function(I){this.currentSourceOffset=this.bytesWritten,this.currentFile=I.file.name;var g=this.streamFiles&&!I.file.dir;if(g){var E=r(I,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:E.fileRecord,meta:{percent:0}})}else this.accumulate=!0},m.prototype.closedSource=function(I){this.accumulate=!1;var g=this.streamFiles&&!I.file.dir,E=r(I,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(E.dirRecord),g)this.push({data:(function(w){return p.DATA_DESCRIPTOR+o(w.crc32,4)+o(w.compressedSize,4)+o(w.uncompressedSize,4)})(I),meta:{percent:100}});else for(this.push({data:E.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},m.prototype.flush=function(){for(var I=this.bytesWritten,g=0;g<this.dirRecords.length;g++)this.push({data:this.dirRecords[g],meta:{percent:100}});var E=this.bytesWritten-I,w=(function(T,S,_,x,M){var W=l.transformTo("string",M(x));return p.CENTRAL_DIRECTORY_END+"\0\0\0\0"+o(T,2)+o(T,2)+o(S,4)+o(_,4)+o(W.length,2)+W})(this.dirRecords.length,E,I,this.zipComment,this.encodeFileName);this.push({data:w,meta:{percent:100}})},m.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},m.prototype.registerPrevious=function(I){this._sources.push(I);var g=this;return I.on("data",function(E){g.processChunk(E)}),I.on("end",function(){g.closedSource(g.previous.streamInfo),g._sources.length?g.prepareNextSource():g.end()}),I.on("error",function(E){g.error(E)}),this},m.prototype.resume=function(){return!!a.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},m.prototype.error=function(I){var g=this._sources;if(!a.prototype.error.call(this,I))return!1;for(var E=0;E<g.length;E++)try{g[E].error(I)}catch{}return!0},m.prototype.lock=function(){a.prototype.lock.call(this);for(var I=this._sources,g=0;g<I.length;g++)I[g].lock()},n.exports=m},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(i,n,s){var o=i("../compressions"),r=i("./ZipFileWorker");s.generateWorker=function(l,a,u){var h=new r(a.streamFiles,u,a.platform,a.encodeFileName),p=0;try{l.forEach(function(m,I){p++;var g=(function(S,_){var x=S||_,M=o[x];if(!M)throw new Error(x+" is not a valid compression method !");return M})(I.options.compression,a.compression),E=I.options.compressionOptions||a.compressionOptions||{},w=I.dir,T=I.date;I._compressWorker(g,E).withStreamInfo("file",{name:m,dir:w,date:T,comment:I.comment||"",unixPermissions:I.unixPermissions,dosPermissions:I.dosPermissions}).pipe(h)}),h.entriesCount=p}catch(m){h.error(m)}return h}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(i,n,s){function o(){if(!(this instanceof o))return new o;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip
${zU.builder.build(o)}`}};Ke(nOe,"default",{title:"BCF Topic",type:"Issue",status:"Active"});var JNe=nOe,Mdt=(e,t)=>{if(t.trim()==="")return;let i=tf.xmlParser.parse(t).Extensions;if(!i)return;let{Priorities:n,TopicStatuses:s,TopicTypes:o,Users:r}=i;if(n&&n.Priority){let l=Array.isArray(n.Priority)?n.Priority:[n.Priority];for(let a of l)e.config.priorities.add(a)}if(s&&s.TopicStatus){let l=Array.isArray(s.TopicStatus)?s.TopicStatus:[s.TopicStatus];for(let a of l)e.config.statuses.add(a)}if(o&&o.TopicType){let l=Array.isArray(o.TopicType)?o.TopicType:[o.TopicType];for(let a of l)e.config.types.add(a)}if(r&&r.User){let l=Array.isArray(r.User)?r.User:[r.User];for(let a of l)e.config.users.add(a)}},Dge=class extends WU{constructor(){super(...arguments),Ke(this,"_config",{version:{type:"Select",options:new Set(["2.1","3"]),multiple:!1,value:""},author:{type:"Text",value:""},types:{type:"TextSet",value:new Set},statuses:{type:"TextSet",value:new Set},priorities:{type:"TextSet",value:new Set},labels:{type:"TextSet",value:new Set},stages:{type:"TextSet",value:new Set},users:{type:"TextSet",value:new Set},includeSelectionTag:{type:"Boolean",value:!1},updateExtensionsOnImport:{type:"Boolean",value:!1},strict:{type:"Boolean",value:!1},includeAllExtensionsOnExport:{type:"Boolean",value:!1},fallbackVersionOnImport:{type:"Select",multiple:!1,options:new Set(["2.1","3"]),value:""},ignoreIncompleteTopicsOnImport:{type:"Boolean",value:!1},exportCustomDataAsLabels:{type:"Boolean",value:!1}})}get version(){return this._config.version.value}set version(t){this._config.version.value=t}get author(){return this._config.author.value}set author(t){this._config.author.value=t}get types(){return this._config.types.value}set types(t){this._config.types.value=t}get statuses(){return this._config.statuses.value}set statuses(t){this._config.statuses.value=t}get priorities(){return this._config.priorities.value}set priorities(t){this._config.priorities.value=t}get labels(){return this._config.labels.value}set labels(t){this._config.labels.value=t}get stages(){return this._config.stages.value}set stages(t){this._config.stages.value=t}get users(){return this._config.users.value}set users(t){this._config.users.value=t}get includeSelectionTag(){return this._config.includeSelectionTag.value}set includeSelectionTag(t){this._config.includeSelectionTag.value=t}get updateExtensionsOnImport(){return this._config.updateExtensionsOnImport.value}set updateExtensionsOnImport(t){this._config.updateExtensionsOnImport.value=t}get strict(){return this._config.strict.value}set strict(t){this._config.strict.value=t}get includeAllExtensionsOnExport(){return this._config.includeAllExtensionsOnExport.value}set includeAllExtensionsOnExport(t){this._config.includeAllExtensionsOnExport.value=t}get fallbackVersionOnImport(){return this._config.fallbackVersionOnImport.value}set fallbackVersionOnImport(t){this._config.fallbackVersionOnImport.value=t}get ignoreIncompleteTopicsOnImport(){return this._config.ignoreIncompleteTopicsOnImport.value}set ignoreIncompleteTopicsOnImport(t){this._config.ignoreIncompleteTopicsOnImport.value=t}get exportCustomDataAsLabels(){return this._config.exportCustomDataAsLabels.value}set exportCustomDataAsLabels(t){this._config.exportCustomDataAsLabels.value=t}},AEe=class Hq extends fr{constructor(){super(...arguments),Ke(this,"enabled",!1),Ke(this,"_defaultConfig",{author:"jhon.doe@example.com",version:"2.1",types:new Set(["Clash","Failure","Fault","Inquiry","Issue","Remark","Request"]),statuses:new Set(["Active","In Progress","Done","In Review","Closed"]),priorities:new Set(["On hold","Minor","Normal","Major","Critical"]),labels:new Set,stages:new Set,users:new Set,includeSelectionTag:!1,updateExtensionsOnImport:!0,strict:!1,includeAllExtensionsOnExport:!0,fallbackVersionOnImport:"2.1",ignoreIncompleteTopicsOnImport:!1,exportCustomDataAsLabels:!1}),Ke(this,"config",new Dge(this,this.components,"BCF Topics",Hq.uuid)),Ke(this,"list",new Ln),Ke(this,"documents",new Ln),Ke(this,"onSetup",new Vi),Ke(this,"isSetup",!1),Ke(this,"onBCFImported",new Vi),Ke
<Version VersionId="${this.config.version}" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/buildingSMART/BCF-XML/release_3_0/Schemas/version.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</Version>`);for(let[s,o]of this.documents.entries())o.type!=="external"&&i.file(this.config.version==="2.1"?o.fileName:`documents/${s}`,o.data);if(this.config.version==="3"){let s=[];for(let[o,r]of this.documents.entries()){let{type:l,description:a}=r;l!=="external"&&s.push(`<Document Guid="${o}">
<Filename>${r.fileName}</Filename>
${a?`<Description>${a}</Description>`:""}
</Document>`)}s.length>0&&i.file("documents.xml",`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<DocumentInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="documents.xsd">
<Documents>
${s.join(`
`)}
</Documents>
</DocumentInfo>`)}i.file("bcf.extensions",this.serializeExtensions());let n=this.components.get(uA);for(let s of t){let o=i.folder(s.guid);o.file("markup.bcf",s.serialize());for(let r of s.viewpoints){let l=n.list.get(r);if(!l)continue;let a=l.title??l.guid;o.file(`${a}.bcfv`,await l.serialize());let u=n.snapshots.get(l.snapshot);if(!u)continue;let h=u?l.snapshot:l.guid,p=n.getSnapshotExtension(l.snapshot);o.file(`${h}.${p}`,u,{binary:!0})}}return await i.generateAsync({type:"blob"})}serializeExtensions(){let t=[...this.config.types].map(l=>`<TopicType>${l}</TopicType>`).join(`
`),i=[...this.config.statuses].map(l=>`<TopicStatus>${l}</TopicStatus>`).join(`
`),n=[...this.config.priorities].map(l=>`<Priority>${l}</Priority>`).join(`
`),s=[...this.config.labels].map(l=>`<TopicLabel>${l}</TopicLabel>`).join(`
`),o=[...this.config.stages].map(l=>`<Stage>${l}</Stage>`).join(`
`),r=[...this.config.users].map(l=>`<User>${l}</User>`).join(`
`);return`
<?xml version="1.0" encoding="UTF-8"?>
<Extensions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="your-schema-location.xsd">
${t.length!==0?`<TopicTypes>
${t}
</TopicTypes>`:""}
${i.length!==0?`<TopicStatuses>
${i}
</TopicStatuses>`:""}
${n.length!==0?`<Priorities>
${n}
</Priorities>`:""}
${s.length!==0?`<TopicLabels>
${s}
</TopicLabels>`:""}
${o.length!==0?`<Stages>
${o}
</Stages>`:""}
${r.length!==0?`<Users>
${r}
</Users>`:""}
</Extensions>
`}processMarkupComment(t){let{Guid:i,Date:n,Author:s,Comment:o,Viewpoint:r}=t;if(!(i&&n&&s&&(Zq||r)))return null;let l=new Zq(this.components,o??"");return l.guid=i,l.date=new Date(n),l.author=s,l.viewpoint=r?.Guid,l.modifiedAuthor=t.ModifiedAuthor,l.modifiedDate=t.ModifiedDate?new Date(t.ModifiedDate):void 0,l}getMarkupComments(t,i){var n;let s;if(i==="2.1"&&(s=t.Comment),i==="3"&&(s=(n=t.Topic.Comments)==null?void 0:n.Comment),!s)return[];s=Array.isArray(s)?s:[s];let o=s.map(r=>this.processMarkupComment(r)).filter(r=>r);return Array.isArray(o)?o:[o]}getMarkupLabels(t,i){var n;let s;return i==="2.1"&&(s=t.Topic.Labels),i==="3"&&(s=(n=t.Topic.Labels)==null?void 0:n.Label),s?Array.isArray(s)?s:[s]:[]}getMarkupViewpoints(t,i){var n;let s;return i==="2.1"&&(s=t.Viewpoints),i==="3"&&(s=(n=t.Topic.Viewpoints)==null?void 0:n.ViewPoint),s?(s=Array.isArray(s)?s:[s],s):[]}getMarkupRelatedTopics(t,i){var n;let s;return i==="2.1"&&(s=t.Topic.RelatedTopic),i==="3"&&(s=(n=t.Topic.RelatedTopics)==null?void 0:n.RelatedTopic),s?(Array.isArray(s)?s:[s]).map(o=>o.Guid):[]}getMarkupDocumentReferences(t,i){var n;let s;return i==="2.1"&&(s=t.Topic.DocumentReference),i==="3"&&(s=(n=t.Topic.DocumentReferences)==null?void 0:n.DocumentReference),s?Array.isArray(s)?s:[s]:[]}async load(t){var i,n,s;let{fallbackVersionOnImport:o,ignoreIncompleteTopicsOnImport:r,updateExtensionsOnImport:l}=this.config,a=new QNe;await a.loadAsync(t);let u=Object.values(a.files),h=o,p=u.find(_=>_.name.endsWith(".version"));if(p){let _=await p.async("string"),x=Hq.xmlParser.parse(_).Version.VersionId;h=String(x)}if(!(h&&(h==="2.1"||h==="3")))throw new Error(`BCFTopics: ${h} is not supported.`);let m=u.find(_=>_.name.endsWith(".extensions"));if(l&&m){let _=await m.async("string");Mdt(this,_)}let I=[],g=this.components.get(uA),E=u.filter(_=>_.name.endsWith(".bcfv"));for(let _ of E){let x=await _.async("string"),M=Hq.xmlParser.parse(x).VisualizationInfo;if(!M){console.warn("Missing VisualizationInfo in Viewpoint");continue}let W={},{Guid:G,ClippingPlanes:$,Components:Y,OrthogonalCamera:se,PerspectiveCamera:pe}=M;if(G&&(W.guid=G),Y){let fe={selection:[],coloring:[],visibility:{default_visibility:!1,exceptions:[],view_setup_hints:{spaces_visible:!1,space_boundaries_visible:!1,openings_visible:!1}}};W.components=fe;let{Selection:Q,Visibility:Te}=Y;if(Q&&Q.Component){let pt=Array.isArray(Q.Component)?Q.Component:[Q.Component];fe.selection=pt.map(Me=>Me.IfcGuid?{ifc_guid:Me.IfcGuid}:null).filter(Me=>Me!==null)}if(Te&&"DefaultVisibility"in Te&&(fe.visibility.default_visibility=Te.DefaultVisibility),Te&&Te.Exceptions&&"Component"in Te.Exceptions){let{Component:pt}=Te.Exceptions,Me=Array.isArray(pt)?pt:[pt];fe.visibility.exceptions=Me.map(He=>He.IfcGuid?{ifc_guid:He.IfcGuid}:null).filter(He=>He!==null)}let Ve;h==="2.1"&&(Ve=Y.ViewSetupHints),h==="3"&&(Ve=(i=Y.Visibility)==null?void 0:i.ViewSetupHints),Ve&&("OpeningsVisible"in Ve&&(fe.visibility.view_setup_hints.openings_visible=Ve.OpeningsVisible),"SpacesVisible"in Ve&&(fe.visibility.view_setup_hints.spaces_visible=Ve.SpacesVisible),"SpaceBoundariesVisible"in Ve&&(fe.visibility.view_setup_hints.space_boundaries_visible=Ve.SpaceBoundariesVisible));let{Coloring:Fe}=Y;if(Fe&&Fe.Color){let pt=Array.isArray(Fe.Color)?Fe.Color:[Fe.Color];for(let Me of pt){let{Color:He,Component:Ye}=Me;if(!(He.length===6||He.length===8))continue;let We=He.length===6?He:He.slice(2),_t=(Array.isArray(Ye)?Ye:[Ye]).map(xt=>xt.IfcGuid?{ifc_guid:xt.IfcGuid}:null).filter(xt=>xt!==null);fe.coloring.push({color:We,components:_t})}}}if(se||pe){let fe=M.PerspectiveCamera??M.OrthogonalCamera,{CameraViewPoint:Q,CameraDirection:Te}=fe,Ve=new ne(Number(Q.X),Number(Q.Z),Number(-Q.Y)),Fe=new ne(Number(Te.X),Number(Te.Z),Number(-Te.Y)),pt={camera_view_point:{x:Ve.x,y:Ve.y,z:Ve.z},camera_direction:{x:Fe.x,y:Fe.y,z:Fe.z},aspect_ratio:"AspectRatio"in fe?fe.AspectRatio:1,camera_up_vector:{x:0,y:0,z:0}};"ViewToWorldScale"in fe&&(W.orthogonal_camera={...pt,view_to_world_scale:fe.ViewToWorldScale}),"FieldOfView"in fe&&(W.perspective_camera={...pt,field_of_view:fe.FieldOfVi
<Component IfcGuid="${m}" ${g??""} />`}}}else o=[...this.selectionComponents].map(r=>`<Component IfcGuid="${r}" />`).join(`
`);return o}createColorTags(){let t="";for(let[i,n]of this.componentColors.entries()){let s=n.map(o=>`
<Component IfcGuid="${o}" />`).join(`
`);t+=`<Color Color="${i}">
${s}
</Color>`}return t.length!==0?`<Coloring>
${t}
</Coloring>`:"<Coloring />"}toJSON(){let t=this._components.get(eN),i={guid:this.guid,components:{selection:[...this.selectionComponents].map(o=>({ifc_guid:o,authoring_tool_id:null})),coloring:[...this.componentColors].map(([o,r])=>({color:o,components:r.map(l=>({ifc_guid:l,authoring_tool_id:null}))})),visibility:{default_visibility:this.defaultVisibility,exceptions:[...this.exceptionComponents].map(o=>({ifc_guid:o,authoring_tool_id:null})),view_setup_hints:{spaces_visible:this.spacesVisible,space_boundaries_visible:this.spaceBoundariesVisible,openings_visible:this.openingsVisible}}},clipping_planes:[...this.clippingPlanes].map(o=>{let r=t.list.get(o);if(!r)return null;let l=r._controls.worldPosition??r.origin,{normal:a}=r;return{location:{x:l.x,y:-l.z,z:l.y},direction:{x:a.x,y:-a.z,z:a.y}}}).filter(o=>o!==null)};"field_of_view"in this.camera?i.perspective_camera=this.camera:i.orthogonal_camera=this.camera;let n=this._components.get(uA),s=n.snapshots.get(this.snapshot);if(s){let o=s.toString(),r=btoa(o),l=n.getSnapshotExtension(this.snapshot);i.snapshot={snapshot_type:l,snapshot_data:r}}return i}async serialize(t=this._managerVersion){let i=this._components.get(xs),n=this.position;n.applyMatrix4(i.baseCoordinationMatrix.clone().invert());let s=this.direction;s.normalize();let o=new di().makeRotationX(Math.PI/2),r=s.clone().applyMatrix4(o);r.normalize();let l=`<CameraViewPoint>
<X>${n.x}</X>
<Y>${-n.z}</Y>
<Z>${n.y}</Z>
</CameraViewPoint>`,a=`<CameraDirection>
<X>${s.x}</X>
<Y>${-s.z}</Y>
<Z>${s.y}</Z>
</CameraDirection>`,u=`<CameraUpVector>
<X>${r.x}</X>
<Y>${-r.z}</Y>
<Z>${r.y}</Z>
</CameraUpVector>`,h=`<AspectRatio>${this.camera.aspect_ratio}</AspectRatio>`,p="";"view_to_world_scale"in this.camera?p=`<OrthogonalCamera>
${l}
${a}
${u}
${h}
<ViewToWorldScale>${this.camera.view_to_world_scale}</ViewToWorldScale>
</OrthogonalCamera>`:"field_of_view"in this.camera&&(p=`<PerspectiveCamera>
${l}
${a}
${u}
${h}
<FieldOfView>${this.camera.field_of_view}</FieldOfView>
</PerspectiveCamera>`);let m=`<ViewSetupHints SpacesVisible="${this.spacesVisible??!1}" SpaceBoundariesVisible="${this.spaceBoundariesVisible??!1}" OpeningsVisible="${this.openingsVisible??!1}" />`,I=(await this.createComponentTags("selection")).trim(),g=(await this.createComponentTags("exception")).trim(),E=this.createColorTags();return`<?xml version="1.0" encoding="UTF-8"?>
<VisualizationInfo Guid="${this.guid}">
<Components>
${t==="2.1"?m:""}
${I.length!==0?`<Selection>${I}</Selection>`:""}
<Visibility DefaultVisibility="${this.defaultVisibility}">
${t==="3"?m:""}
${g.length!==0?`<Exceptions>${g}</Exceptions>`:""}
</Visibility>
${E}
</Components>
${p}
</VisualizationInfo>`}},Lge=class extends WU{constructor(){super(...arguments),Ke(this,"_config",{overwriteColors:{value:!1,type:"Boolean"}})}get overwriteColors(){return this._config.overwriteColors.value}set overwriteColors(t){this._config.overwriteColors.value=t}},oOe=class Pge extends fr{constructor(t){super(t),Ke(this,"enabled",!0),Ke(this,"world",null),Ke(this,"list",new Ln),Ke(this,"snapshots",new Ln),Ke(this,"isSetup",!1),Ke(this,"onSetup",new Vi),Ke(this,"config",new Lge(this,this.components,"Viewpoints",Pge.uuid)),Ke(this,"onDisposed",new Vi),t.add(Pge.uuid,this)}create(t){let i=new Yne(this.components,t);return i.world=this.world,t||this.list.set(i.guid,i),i}getSnapshotExtension(t){let i="jpeg",n=this.snapshots.get(t);if(!n)return i;let s=n.subarray(0,4),o="";for(let r=0;r<s.length;r++)o+=s[r].toString(16);return o.startsWith("89504e47")&&(i="png"),o.startsWith("ffd8ffe")&&(i="jpeg"),i}setup(){}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}};Ke(oOe,"uuid","ee867824-a796-408d-8aa0-4e5962a83c66");var uA=oOe,qne=class{constructor(t,i){Ke(this,"_components"),Ke(this,"_cameraOffset",10),Ke(this,"_planeHelper"),Ke(this,"_farPlaneHelper"),Ke(this,"_cameraHelper"),Ke(this,"onStateChanged",new Vi),Ke(this,"onUpdated",new Vi),Ke(this,"onDisposed",new Vi),Ke(this,"camera"),Ke(this,"plane",new Nn),Ke(this,"farPlane",new Nn),Ke(this,"id",x0.create()),Ke(this,"_open",!1),Ke(this,"_range",Bdt.defaultRange),Ke(this,"_world",null),Ke(this,"_helpersVisible",!1),Ke(this,"_planesEnabled",!1),this._components=t,this.camera=new $q(this._components);let{threeOrtho:n}=this.camera;if(i!=null&&i.id&&(this.id=i.id),i!=null&&i.normal&&i!=null&&i.point){let{normal:s,point:o}=i;this.plane.setFromNormalAndCoplanarPoint(s,o)}this._cameraHelper=new Zx(n),this._planeHelper=new Bv(this.plane,50),this._farPlaneHelper=new Bv(this.farPlane,50),this.farPlaneHelperColor=new Ei("blue"),this.update()}get _planeNormalOpposite(){return this.plane.normal.clone().negate()}get _planePosition(){return this.plane.normal.clone().multiplyScalar(-this.plane.constant)}get _cameraPosition(){return this._planePosition.addScaledVector(this._planeNormalOpposite,this._cameraOffset)}set open(t){this._open=t,this.onStateChanged.trigger(["open"])}get open(){return this._open}set planeHelperColor(t){!Array.isArray(this._planeHelper.material)&&"color"in this._planeHelper.material&&this._planeHelper.material.color instanceof Ei&&(this._planeHelper.material.color=t)}set farPlaneHelperColor(t){!Array.isArray(this._farPlaneHelper.material)&&"color"in this._farPlaneHelper.material&&this._farPlaneHelper.material.color instanceof Ei&&(this._farPlaneHelper.material.color=t)}set range(t){this._range=t,this.update()}get range(){return this._range}set distance(t){this.plane.constant=t,this.update()}get distance(){return this.plane.constant}set world(t){this._world=t,this.camera.currentWorld=t,t&&(this.camera.projection.set("Orthographic"),this.camera.set("Plan"),this.camera.controls.dollySpeed=6,this.camera.controls.restThreshold=.005,this.update())}get world(){return this._world}set helpersVisible(t){if(!t){this._helpersVisible=t,this._planeHelper.removeFromParent(),this._farPlaneHelper.removeFromParent(),this._cameraHelper.removeFromParent();return}this.world&&(this._helpersVisible=t,this.world.scene.three.add(this._planeHelper,this._farPlaneHelper))}get helpersVisible(){return this._helpersVisible}set planesEnabled(t){let{world:i}=this;if(!i)return;let{renderer:n}=i;n&&(n.setPlane(t,this.plane),n.setPlane(t,this.farPlane),this._planesEnabled=t)}get planesEnabled(){return this._planesEnabled}dispose(){this.helpersVisible=!1;let t=this._components.get(v3);t.destroy(this._planeHelper),t.destroy(this._farPlaneHelper),t.destroy(this._cameraHelper),this.camera.dispose(),this.onDisposed.trigger()}update(){if(this.world){let t=this._cameraPosition,i=this._planePosition;this.camera.controls.setLookAt(t.x,t.y,t.z,i.x,i.y,i.z,!1)}this.farPlane.normal.copy(this._planeNormalOpposite),this.farPlane.constant=this.range-this.plane.constant,this.onUpdated.tr
${t.parameter.map(n=>`<xs:enumeration value="${n}" />`).join(`
`)}
</xs:restriction>`),t.type==="pattern"&&(i=`<xs:restriction base="xs:string">
<xs:pattern value="${t.parameter}" />
</xs:restriction>`),t.type==="bounds"){let{min:n,minInclusive:s,max:o,maxInclusive:r}=t.parameter,l="";n!==void 0&&(l=`<xs:min${s?"Inclusive":"Exclusive"} value="${n}">`);let a="";o!==void 0&&(a=`<xs:max${r?"Inclusive":"Exclusive"} value="${o}">`),i=`<xs:restriction base="xs:double">
${l}
${a}
</xs:restriction>`}if(t.type==="length"){let{length:n,min:s,max:o}=t.parameter,r="";n!==void 0&&s===void 0&&o===void 0&&(r=`<xs:length value="${n}" />`);let l="";s!==void 0&&n===void 0&&(l=`<xs:minLength value="${s}" />`);let a="";o!==void 0&&n===void 0&&(a=`<xs:maxLength value="${o}" />`),i=`<xs:restriction base="xs:string">
${r}
${l}
${a}
</xs:restriction>`}return`<${e[0].toLowerCase()+e.slice(1)}>
${i}
</${e[0].toLowerCase()+e.slice(1)}>`},Mge=class extends nN{constructor(t,i){super(t),Ke(this,"facetType","Attribute"),Ke(this,"name"),Ke(this,"value"),this.name=i}serialize(t){let i=zS("Name",this.name),n=zS("Value",this.value),s="";return t==="requirement"&&(s+=`cardinality="${this.cardinality}"`,s+=this.instructions?`instructions="${this.instructions}"`:""),`<attribute ${s}>
${i}
${n}
</attribute>`}async getEntities(){}async test(t,i,n={skipIfFails:!0}){let s=this._components.get(xs);for(let[o,r]of Object.entries(t)){let l=s.list.get(o);if(!l)continue;let a=await l.getItemsData([...r]);for(let u of a){let h=this.getItemChecks(i,o,u,n.skipIfFails);if(!h)continue;let p=Object.keys(u).filter(I=>{let g=this.evalRequirement(I,this.name,"Name");if(!g)return!1;let E=u[I];return Array.isArray(E)?!0:E===null||E.value===null?this.cardinality==="optional"||this.cardinality==="prohibited":Array.isArray(E.value)&&E.value.length===0||typeof E.value=="string"&&E.value.trim()===""?!1:g}),m=p.length>0;if(h.push({parameter:"Name",currentValue:m?p[0]:null,requiredValue:this.name,pass:this.cardinality==="prohibited"?!m:m}),this.value)if(p[0]){let I=u[p[0]];Array.isArray(I)?h.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:this.cardinality==="prohibited"}):Array.isArray(I.value)?h.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:this.cardinality==="prohibited"}):this.evalRequirement(I.value,this.value,"Value",h)}else h.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:this.cardinality==="prohibited"})}}}},Bge=class extends nN{constructor(t,i){super(t),Ke(this,"facetType","Classification"),Ke(this,"system"),Ke(this,"value"),Ke(this,"uri"),this.system=i}serialize(t){let i=zS("System",this.system),n=zS("Value",this.value),s="";return t==="requirement"&&(s+=`cardinality="${this.cardinality}"`,s+=this.uri?`uri=${this.uri}`:"",s+=this.instructions?`instructions="${this.instructions}"`:""),`<classification ${s}>
${i}
${n}
</classification>`}async getEntities(t,i){}async test(t,i){}},Kq=class extends nN{constructor(t,i){super(t),Ke(this,"facetType","Entity"),Ke(this,"name"),Ke(this,"predefinedType"),this.name=i}serialize(t){let i=zS("Name",this.name),n=zS("Name",this.predefinedType),s="";return t==="requirement"&&(s+=`cardinality="${this.cardinality}"`,s+=this.instructions?`instructions="${this.instructions}"`:""),`<entity ${s}>
${i}
${n}
</entity>`}async getEntities(t,i){let n=this._components.get(xs),s=new Map;for(let[r,l]of n.list){if(!t.find(u=>u.test(r)))continue;let a=await l.getCategories();for(let u of a){if(!await this.evalName(u))continue;let h=s.get(r);h||(h=[],s.set(r,h)),h.push(u)}}let o={};if(await Promise.all(Array.from(s.entries()).map(async([r,l])=>{let a=n.list.get(r);if(!a)return;let u=l.map(m=>new RegExp(`^${m}$`)),h=await a.getItemsOfCategories(u),p=Object.values(h).flat();o[r]=new Set(p)})),!this.predefinedType){Mr.add(i,o);return}for(let[r,l]of Object.entries(o)){let a=n.list.get(r);if(!a)continue;let u=await a.getItemsData([...l]);for(let h of u)"value"in h._localId&&await this.evalPredefinedType(r,h)&&Mr.append(i,r,h._localId.value)}}async test(t,i,n){let s=this._components.get(xs);for(let[o,r]of Object.entries(t)){let l=s.list.get(o);if(!l)continue;let a=await l.getItemsData([...r]);for(let u of a){if(!("value"in u._category))continue;let h=this.getItemChecks(i,o,u,n.skipIfFails);h&&(await this.evalName(u._category.value,h),await this.evalPredefinedType(o,u,h))}}}async evalName(t,i){return this.evalRequirement(t,this.name,"Name",i)}async evalPredefinedType(t,i,n){if(!this.predefinedType||!("value"in i.PredefinedType))return null;let s=typeof this.predefinedType.parameter=="string"&&this.predefinedType.parameter==="USERDEFINED",o=i.PredefinedType.value;if(o==="USERDEFINED"&&!s){let r=Object.keys(i).find(l=>/^((?!Predefined).)*Type$/.test(l));if(r){let l=i[r];"value"in l&&(o=l.value)}else o="USERDEFINED"}if(!o){let r=this._components.get(xs).list.get(t);if(r&&"value"in i._localId){let[l]=await r.getItemsData([i._localId.value],{relations:{IsTypedBy:{attributes:!0,relations:!1}}});if(Array.isArray(l.IsTypedBy)){let a=l.IsTypedBy[0];if(a&&"value"in a.PredefinedType&&(o=a.PredefinedType.value,o==="USERDEFINED"&&!s)){let u=Object.keys(a).find(h=>/^((?!Predefined).)*Type$/.test(h));if(u){let h=a[u];"value"in h&&(o=h.value)}else o="USERDEFINED"}}}}return this.evalRequirement(o,this.predefinedType,"PredefinedType",n)}},Fge=class extends nN{constructor(t,i,n){super(t),Ke(this,"facetType","Property"),Ke(this,"propertySet"),Ke(this,"baseName"),Ke(this,"value"),Ke(this,"dataType"),Ke(this,"uri"),Ke(this,"_unsupportedTypes",["IFCCOMPLEXPROPERTY","IFCPHYSICALCOMPLEXQUANTITY"]),this.propertySet=i,this.baseName=n}serialize(t){let i=zS("PropertySet",this.propertySet),n=zS("BaseName",this.baseName),s=zS("Value",this.value),o=this.dataType?`dataType=${this.dataType}`:"",r="";return t==="requirement"&&(r+=`cardinality="${this.cardinality}"`,r+=this.uri?`uri=${this.uri}`:"",r+=this.instructions?`instructions="${this.instructions}"`:""),`<property ${o} ${r}>
${i}
${n}
${s}
</property>`}async getEntities(t,i){let n=this._components.get(xs);for(let[s,o]of n.list){if(!t.find(u=>u.test(s)))continue;let r=await o.getItemsOfCategories([/PROPERTYSET/,/ELEMENTQUANTITY/]),l=Object.values(r).flat();if(l.length===0)continue;let a=await o.getItemsData(l,{relations:{HasProperties:{attributes:!0,relations:!1},DefinesOcurrence:{attributes:!0,relations:!1}}});for(let u of a){if(!("value"in u._localId&&"value"in u._category&&"value"in u.Name&&Array.isArray(u.DefinesOcurrence))||!this.evalRequirement(u.Name.value,this.propertySet,"PropertySet"))continue;let h;if(u._category.value==="IFCPROPERTYSET"&&(h="HasProperties"),u._category.value==="IFCELEMENTQUANTITY"&&(h="Quantities"),!h)continue;let p=u[h];if(Array.isArray(p))for(let m of p){let I=Object.keys(m),g=I.find(T=>/Name/.test(T));if(!(g&&"value"in m[g]))continue;let E=m[g];if(!("value"in E)||!this.evalRequirement(E.value,this.baseName,"BaseName"))continue;if(this.value){let T=I.find(_=>/Value/.test(_));if(!T)continue;let S=m[T];if(!("value"in S)||!this.evalRequirement(S.value,this.value,"Value"))continue}let w=u.DefinesOcurrence.map(T=>"value"in T._localId&&typeof T._localId.value=="number"?T._localId.value:null).filter(T=>T!==null);Mr.append(i,s,...w)}}}}async test(t,i,n={skipIfFails:!0}){let s=this._components.get(xs);for(let[o,r]of Object.entries(t)){let l=s.list.get(o);if(!l)continue;let a=await l.getItemsData([...r],{relations:{IsDefinedBy:{attributes:!0,relations:!0},IsTypedBy:{attributes:!0,relations:!1},HasPropertySets:{attributes:!0,relations:!0},DefinesOcurrence:{attributes:!1,relations:!1}}});for(let u of a){let h=this.getItemChecks(i,o,u,n.skipIfFails);if(!h)continue;let p=(await this.getPsets(u)).filter(m=>!("value"in m.Name)||!this.evalRequirement(m.Name.value,this.propertySet,"PropertySet")?!1:(h.push({currentValue:m.Name.value,parameter:"PropertySet",pass:!0,requiredValue:this.propertySet}),!0));if(p.length===0){h.push({currentValue:null,parameter:"PropertySet",pass:!1,requiredValue:this.propertySet});continue}for(let m of p){let I=this.getPropertyListName(m);if(!I)continue;let g=m[I];if(!Array.isArray(g)){h.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName});continue}let E=g.filter(w=>!("value"in w._category&&"value"in w.Name)||this._unsupportedTypes.includes(w._category.value)||!this.evalRequirement(w.Name.value,this.baseName,"BaseName")?!1:(h.push({currentValue:w.Name.value,parameter:"BaseName",pass:!0,requiredValue:this.baseName}),!0));if(E.length===0){h.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName});continue}for(let w of E)this.evalValue(w,h),this.evalDataType(w,h),this.evalURI()}}}}getPropertyListName(t){let i;return"value"in t._category&&(t._category.value==="IFCPROPERTYSET"&&(i="HasProperties"),t._category.value==="IFCELEMENTQUANTITY"&&(i="Quantities")),i}getValueKey(t){return Object.keys(t).find(i=>/Value/.test(i)||/Values/.test(i))}getTypePsets(t){if(!Array.isArray(t.IsTypedBy))return[];let[i]=t.IsTypedBy;return i&&Array.isArray(i.HasPropertySets)?i.HasPropertySets:[]}async getPsets(t){let i=this.getTypePsets(t);if(!Array.isArray(t.IsDefinedBy))return i;let n=[];for(let s of t.IsDefinedBy){if(!("value"in s.Name))continue;let o=s.Name.value,r=this.getPropertyListName(s);if(!(o&&r))continue;let l=i.find(a=>"value"in a.Name?a.Name.value===o:!1);if(l&&Array.isArray(l.HasProperties)&&Array.isArray(s.HasProperties))for(let a of l.HasProperties){if(!("value"in a.Name))continue;let u=a.Name.value;s.HasProperties.find(h=>"value"in h.Name?h.Name.value===u:!1)||s.HasProperties.push(a)}n.push(s)}return n}evalValue(t,i){let n=this.getValueKey(t),s=t[n];if(!("value"in s))return!1;if(this.value){if(!n)return i?.push({parameter:"Value",currentValue:null,pass:!1,requiredValue:this.value}),!1;let o=structuredClone(this.value);return s.type==="IFCLABEL"&&o.type==="simple"&&(o.parameter=String(o.parameter)),this.evalRequirement(s.value,o,"Value",i)}return n&&typeof s.value=="string"&&s.value.trim()===""?(i?.push({parameter:"Value",currentValue:"",pass:!1,requiredValue:this.value}),
${i}
</material>`}async getEntities(t,i){let n=this._components.get(xs);for(let[s,o]of n.list){if(!t.find(u=>u.test(s)))continue;let r=await o.getItemsOfCategories(this._ifcMaterialEntities),l=Object.values(r).flat();if(l.length===0)continue;let a=await o.getItemsData(l,{relations:{AssociatedTo:{attributes:!0,relations:!1},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(let u of a){if(!("value"in u._localId&&"value"in u._category&&Array.isArray(u.AssociatedTo))||!this.hasValidMaterial(u))continue;let h=u.AssociatedTo.map(p=>"value"in p._localId&&p._localId.value?p._localId.value:null).filter(p=>p!==null);Mr.append(i,s,...h)}}}async test(t,i,n={skipIfFails:!0}){let s=this._components.get(xs);for(let[o,r]of Object.entries(t)){let l=s.list.get(o);if(!l)continue;let a=await l.getItemsData([[...r][0]],{relations:{AssociatedTo:{attributes:!1,relations:!1},HasAssociations:{attributes:!0,relations:!0},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(let u of a){let h=this.getItemChecks(i,o,u,n.skipIfFails);if(h){if(!Array.isArray(u.HasAssociations)){h.push({parameter:null,currentValue:null,requiredValue:this.value,pass:!1});continue}for(let p of u.HasAssociations)if(this._ifcMaterialEntities.some(m=>"value"in p._category?m.test(p._category.value):!1)&&this.hasValidMaterial(p,h))break}}}}hasValidMaterial(t,i){let n=!1;if("value"in t._category&&t._category.value==="IFCMATERIAL")this.evalValue(t,i)&&(n=!0);else for(let[s,o]of Object.entries(t))if(["ForLayerSet","MaterialLayers","Material","MaterialConstituents","Materials"].includes(s)&&Array.isArray(o)){for(let r of o)if("value"in r._category&&r._category.value==="IFCMATERIAL"){if(this.evalValue(r,i)){n=!0;break}}else if(this.hasValidMaterial(r)){n=!0;break}}return n}evalValue(t,i){if(!this.value)return i?.push({parameter:null,currentValue:t.Name&&"value"in t.Name?t.Name.value:null,pass:!0}),!0;if(!("value"in t._category&&t._category.value==="IFCMATERIAL"))return null;let n=!1;return t.Name&&"value"in t.Name&&(n=this.evalRequirement(t.Name.value,this.value,"Value",i)),n||(t.Category&&"value"in t.Category&&(n=this.evalRequirement(t.Category.value,this.value,"Value",i)),n)}},Hge=class extends nN{constructor(t,i){super(t),Ke(this,"facetType","PartOf"),Ke(this,"_entityFacet"),Ke(this,"_entity"),Ke(this,"relation"),Ke(this,"cardinality","required"),this._entity=i,this._entityFacet=new Kq(t,i.name),this._entityFacet.predefinedType=i.predefinedType}set entity(t){this._entity=t;let{name:i,predefinedType:n}=t;this._entityFacet=new Kq(this._components,i),this._entityFacet.predefinedType=n}get entity(){return this._entity}serialize(){return""}async getEntities(t,i){}async test(t){}},Gge=class{constructor(t,i,n){Ke(this,"name"),Ke(this,"ifcVersion",new Set),Ke(this,"identifier",x0.create()),Ke(this,"description"),Ke(this,"instructions"),Ke(this,"requirementsDescription"),Ke(this,"applicability",new Po),Ke(this,"requirements",new Po),Ke(this,"components"),this.components=t,this.name=i;for(let s of n)this.ifcVersion.add(s)}set(t){let i=t,n=this;for(let s in t){if(s==="identifier")continue;let o=i[s];s in this&&(n[s]=o)}return this.components.get(Fdt).list.set(this.identifier,this),this}async test(t,i={skipIfFails:!0}){let n=new Ln;if(this.requirements.size===0)return n;let s={},o=[];for(let l of this.applicability)o.push(l.getEntities(t,s));await Promise.all(o);let r=[];for(let l of this.requirements)r.push(l.test(s,n,i));return await Promise.all(r),n}serialize(){let t=`name="${this.name}"`,i=this.identifier?`identifier="${this.identifier}"`:"",n=this.description?`description="${this.description}"`:"",s=this.instructions?`instructions="${this.instructions}"`:"";return`<specification ifcVersion="${[...this.ifcVersion].join(" ")}" ${t} ${i} ${n} ${s}>
<applicability minOccurs="1" maxOccurs="unbounded">
${[...this.applicability].map(o=>o.serialize("applicability")).join(`
`)}
</applicability>
<requirements>
${[...this.requirements].map(o=>o.serialize("requirement")).join(`
`)}
</requirements>
</specification>`}},qE=e=>{if(!e)return;let t={};if("simpleValue"in e&&(t.type="simple",t.parameter=e.simpleValue),"restriction"in e){let i=e.restriction,n=Object.keys(i);if("pattern"in i&&(t.type="pattern",t.parameter=i.pattern.value),"enumeration"in i){t.type="enumeration";let s=i.enumeration.map(({value:o})=>i.base.includes("string")?String(o):i.base.includes("integer")||i.base.includes("double")?Number(o):o);t.parameter=s}if(n.some(s=>["minInclusive","minExclusive","maxInclusive","maxExclusive"].includes(s))){t.type="bounds";let s={},o=n.find(l=>l.includes("min")),r=n.find(l=>l.includes("max"));o&&(s.minInclusive=o==="minInclusive",s.min=i[o].value),r&&(s.maxInclusive=r==="maxInclusive",s.max=i[r].value),t.parameter=s}if(n.some(s=>["minLength","length","maxLength"].includes(s))){t.type="length";let s={};i.length!==void 0&&(s.length=i.length.value),i.minLength!==void 0&&(s.min=i.minLength.value),i.maxLength!==void 0&&(s.max=i.maxLength.value),t.parameter=s}}if(t.parameter!==void 0)return t},XNe=(e,t)=>{let i=[];for(let n of t){let s=n.name,o=qE(s);if(!o)continue;let r=new Kq(e,o);n.cardinality&&(r.cardinality=n.cardinality),r.predefinedType=qE(n.predefinedType),r.instructions=n.instructions,i.push(r)}return i},e6e=(e,t)=>{let i=[];for(let n of t){let s=n.name,o=qE(s);if(!o)continue;let r=new Mge(e,o);n.cardinality&&(r.cardinality=n.cardinality),r.value=qE(n.value),r.instructions=n.instructions,i.push(r)}return i},t6e=(e,t)=>{let i=[];for(let n of t){let s=new Uge(e);n.cardinality&&(s.cardinality=n.cardinality);let o=qE(n.value);o?.type==="enumeration"&&Array.isArray(o.parameter)&&(o.parameter=o.parameter.map(String)),s.value=o,s.uri=n.uri,s.instructions=n.instructions,i.push(s)}return i},i6e=(e,t)=>{let i=[];for(let n of t){let s=n.propertySet,o=n.baseName,r=qE(s),l=qE(o);if(!(l&&r))continue;let a=new Fge(e,r,l);n.cardinality&&(a.cardinality=n.cardinality);let u=qE(n.value);a.value=u,a.dataType=n.dataType,a.uri=n.uri,a.instructions=n.instructions,i.push(a)}return i},n6e=(e,t)=>{let i=[];for(let n of t){let s=n.system,o=qE(s);if(!o)continue;let r=new Bge(e,o);n.cardinality&&(r.cardinality=n.cardinality);let l=qE(n.value);l?.type==="simple"&&(l.parameter=String(l.parameter)),l?.type==="enumeration"&&Array.isArray(l.parameter)&&(l.parameter=l.parameter.map(String)),r.value=l,r.uri=n.uri,r.instructions=n.instructions,i.push(r)}return i},s6e=(e,t)=>{let i=[];for(let n of t){let s=qE(n.entity.name);if(!s)continue;let o=qE(n.entity.predefinedType),r=new Hge(e,{name:s,predefinedType:o});r.relation=n.relation,n.cardinality&&(r.cardinality=n.cardinality),r.instructions=n.instructions,i.push(r)}return i},CEe=class Vge extends fr{constructor(t){super(t),Ke(this,"enabled",!0),Ke(this,"IDSInfo"),Ke(this,"list",new Ln),t.add(Vge.uuid,this)}getModelIdMap(t){let i={},n={};for(let[s,o]of t){let r=[...o].filter(([,a])=>a.pass).map(([a])=>a);Mr.append(i,s,...r);let l=[...o].filter(([,a])=>!a.pass).map(([a])=>a);Mr.append(n,s,...l)}return{pass:i,fail:n}}create(t,i,n){let s=new Gge(this.components,t,i);return n&&(s.identifier=n),this.list.set(s.identifier,s),s}load(t){let i=[],n=Vge.xmlParser.parse(t).ids,{specifications:s,info:o}=n;if(this.IDSInfo={...o},s&&s.specification){let r=Array.isArray(s.specification)?s.specification:[s.specification];for(let l of r){let{name:a,ifcVersion:u,description:h,instructions:p,identifier:m}=l;if(!(a&&u))continue;let I=[],g=[],{applicability:E,requirements:w}=l;if(E){let{maxOccurs:_,...x}=E,M=Array.isArray(x)?x:[x];for(let W of M)for(let G in W){let $=Array.isArray(W[G])?W[G]:[W[G]];if(G==="entity"){let Y=XNe(this.components,$);I.push(...Y)}if(G==="attribute"){let Y=e6e(this.components,$);I.push(...Y)}if(G==="material"){let Y=t6e(this.components,$);I.push(...Y)}if(G==="classification"){let Y=n6e(this.components,$);I.push(...Y)}if(G==="property"){let Y=i6e(this.components,$);I.push(...Y)}if(G==="partOf"){let Y=s6e(this.components,$);I.push(...Y)}}}let T;if(w){let{maxOccurs:_,...x}=w;T=w.description;let M=Array.isArray(x)?x:[x];for(let W of M)for(let G in W){let $=Array.isArray(W[G])?W[G]:[W[G]];if(G==
<!-- Made with That Open Engine ${tOe.release} (https://github.com/thatopen/engine_components) -->
<info>
<title>${t.title}</title>
${t.copyright?`<copyright>${t.copyright}</copyright>`:""}
${t.version?`<version>${t.version}</version>`:""}
${t.description?`<description>${t.description}</description>`:""}
${t.author?`<author>${t.author}</author>`:""}
${t.date?`<date>${t.date.toISOString().split("T")[0]}</date>`:""}
${t.purpose?`<purpose>${t.purpose}</purpose>`:""}
${t.milestone?`<milestone>${t.milestone}</milestone>`:""}
</info>
<specifications>
${[...n].map(s=>s.serialize()).join(`
`)}
</specifications>
</ids>`}};Ke(CEe,"uuid","9f0b9f78-9b2e-481a-b766-2fbfd01f342c");Ke(CEe,"xmlParser",new Yq({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0}));var Fdt=CEe,lOe=class aOe extends fr{constructor(t){super(t),Ke(this,"enabled",!0),t.add(aOe.uuid,this)}static distanceFromPointToLine(t,i,n,s=!1){let o=new wn,r=new ne;return o.set(i,n),o.closestPointToPoint(t,s,r),r.distanceTo(t)}round(t){t.x=Math.trunc(t.x*1e3)/1e3,t.y=Math.trunc(t.y*1e3)/1e3,t.z=Math.trunc(t.z*1e3)/1e3}async getVolumeFromFragments(t){return console.warn("getVolumeFromFragments is deprecated. Use getItemsVolume instead."),this.getItemsVolume(t)}async getItemsVolume(t){let i=0,n=this.components.get(xs);for(let[s,o]of Object.entries(t)){let r=n.list.get(s);r&&(i+=await r.getItemsVolume([...o]))}return i}static convertUnits(t,i,n,s=2){let o={m:1,cm:.01,mm:.001,km:1e3,m2:1,cm2:1e-4,mm2:1e-6,km2:1e6,m3:1,cm3:1e-6,mm3:1e-9,km3:1e9};if(!o[i]||!o[n])throw new Error("Invalid units provided for conversion.");if(!Number.isInteger(s)||s<0||s>5)throw new Error("Precision must be an integer between 0 and 5.");let r=o[i]/o[n],l=t*r,a=10**s;return Math.round(l*a)/a}};Ke(lOe,"uuid","267ca032-672f-4cb0-afa9-d24e904f39d6");var YU=lOe,uOe=(e,t,i)=>{let n=new ne(-t.z,0,t.x),s=new ne(t.x+n.x,0,t.z+n.z).normalize().multiplyScalar(i/2);return[e.x+s.x,e.y,e.z+s.z,e.x-s.x,e.y,e.z-s.z]},cOe=(e,t,i)=>{let n=new ne(-t.z,0,t.x),s=e.x-t.x*i+n.x*i*.4,o=e.z-t.z*i+n.z*i*.4,r=e.x-t.x*i-n.x*i*.4,l=e.z-t.z*i-n.z*i*.4;return[e.x,e.y,e.z,s,e.y,o,e.x,e.y,e.z,r,e.y,l]},Udt=()=>[],Hdt=(e,t,i)=>{let n=new ne(-t.z,0,t.x),s=e.clone().addScaledVector(t,-i),o=s.clone().addScaledVector(n,i*.4),r=s.clone().addScaledVector(n,-i*.4);return[e.x,e.y,e.z,o.x,o.y,o.z,r.x,r.y,r.z]},kge=class extends Ln{constructor(){super()}getBySystem(t){let i=new Map;for(let[n,s]of this)s.system===t&&i.set(n,s.data);return i}},zge=class extends Ln{constructor(t){super(),Ke(this,"_container"),this._container=t,this.deleteGuard=i=>i!=="0",this.set("0",{name:"0",visible:!0,material:new qs({color:0})})}create(t,i){if(!this.has(t)){let n={name:t,visible:i?.visible??!0,material:i?.material??new qs({color:0})};this.set(t,n)}return this.get(t)}setColor(t,i){let n=this.get(t);n&&(n.material.color.setHex(i),this.set(t,n))}setMaterial(t,i){let n=this.get(t);if(!n)return;let s=n.material;n.material=i,this._container.traverse(o=>{o.userData.layer===t&&(o.userData.isDimension||o.isLineSegments&&(o.material=i))}),s.dispose(),this.set(t,n)}setVisibility(t,i){let n=this.get(t);n&&(n.visible=i,this._container.traverse(s=>{s.userData.layer===t&&(s.visible=i)}),this.set(t,n))}assign(t,i){let n=this.get(i);n&&(t.userData.layer=i,n.visible||(t.visible=!1),t.isLineSegments&&(t.material=n.material))}resolveColor(t){let i=this.get(t);if(i)return i.material.color.getHex()}},s$=class rA extends rs{constructor(t){super(),Ke(this,"_viewport"),Ke(this,"_border"),Ke(this,"_handles",[]),Ke(this,"_raycaster",new Oa),Ke(this,"_resizable",!1),Ke(this,"_movable",!1),Ke(this,"_dragHandle",null),Ke(this,"_dragConstraints",[]),Ke(this,"_hoveredHandle",null),Ke(this,"_moveDrag",null),Ke(this,"_hoveringBorder",!1),Ke(this,"_normalMat"),Ke(this,"_hoverMat"),Ke(this,"_borderMat"),this._viewport=t,this._borderMat=new qs({color:rA._BORDER_COLOR,depthTest:!1});let i=new Ni;i.setAttribute("position",new Wi(new Float32Array(24),3)),this._border=new Rn(i,this._borderMat),this._border.renderOrder=999,this._border.frustumCulled=!1,this._border.userData.isDimension=!0,this.add(this._border),this._normalMat=new ws({color:rA._BORDER_COLOR}),this._hoverMat=new ws({color:rA._BORDER_HOVER_COLOR});let n=new wm(.05,8,6);for(let s of rA._HANDLE_DEFS){let o=new ci(n,this._normalMat);o.renderOrder=1e3,o.visible=!1,o.userData.constraints=s.constraints,o.userData.isDimension=!0,this.add(o),this._handles.push(o)}this.update()}get resizable(){return this._resizable}set resizable(t){this._resizable=t;for(le
`)+`
`}},Kge=class{constructor(t){Ke(this,"precision",2),Ke(this,"config",{trueColor:!1}),Ke(this,"_viewport",null),Ke(this,"_paperSlot",null),Ke(this,"_annotationLayers",new Map),Ke(this,"_systemExporters",new Map),this._components=t}registerSystemExporter(t,i){this._systemExporters.set(t,i)}export(t,i){let n=!!i,s=new Zge,o=new Map;for(let u of t)for(let h of u.drawing.layers.values())o.has(h.name)||o.set(h.name,h);let r=[...o.values()],l=this._components.get(om).systems.get(Qq),a=l?[...l.definitions.keys()]:[];this._writeHeader(s,n),this._writeTables(s,r,a),this._writeBlocks(s,l??null),s.p(0,"SECTION").p(2,"ENTITIES"),n&&i&&this._writePaperBorders(s,i);for(let u of t){u.drawing.three.traverse(h=>{h.userData.isDimension&&h.userData.annotationUuid&&this._annotationLayers.set(h.userData.annotationUuid,h.userData.layer??"0")});for(let h of u.viewports){if(this._viewport=h.viewport??null,n&&h.viewport){let p=h.viewport,m=i.heightMm-2*i.margin;this._paperSlot={x:h.x??0,y:m-(h.y??0),mmPerUnit:1e3/p.drawingScale,vpLeft:p.left,vpTop:p.top}}else this._paperSlot=null;this._writeViewportBorder(s),this._writeRawLines(s,u.drawing),this._writeLinearAnnotations(s,u.drawing),this._writeAngleAnnotations(s,u.drawing),this._writeLeaderAnnotations(s,u.drawing),this._writeSlopeAnnotations(s,u.drawing),this._writeCalloutAnnotations(s,u.drawing),this._writeBlockInsertions(s,u.drawing),this._writeCustomSystems(s,u.drawing)}this._annotationLayers.clear()}return s.p(0,"ENDSEC"),this._writeObjects(s),s.p(0,"EOF"),this._viewport=null,this._paperSlot=null,s.build()}_writeHeader(t,i){t.p(0,"SECTION").p(2,"HEADER"),t.p(9,"$ACADVER").p(1,this.config.trueColor?"AC1018":"AC1015"),t.p(9,"$INSUNITS").p(70,i?4:6),t.p(0,"ENDSEC")}_writeTables(t,i,n){t.p(0,"SECTION").p(2,"TABLES"),t.p(0,"TABLE").p(2,"VPORT").p(70,0).p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"LTYPE").p(70,1),t.p(0,"LTYPE").p(2,"CONTINUOUS").p(70,0).p(3,"Solid line").p(72,65).p(73,0).n(40,0),t.p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"LAYER").p(70,i.length);for(let o of i){let r=sA(o.material.color.getHex());t.p(0,"LAYER").p(2,o.name).p(70,0).p(62,r).p(6,"CONTINUOUS")}t.p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"STYLE").p(70,1),t.p(0,"STYLE").p(2,"STANDARD").p(70,0).n(40,0).n(41,1).n(50,0).p(71,0).n(42,.2).p(3,"txt").p(4,""),t.p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"VIEW").p(70,0).p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"UCS").p(70,0).p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"APPID").p(70,1),t.p(0,"APPID").p(2,"ACAD").p(70,0),t.p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"DIMSTYLE").p(70,0).p(0,"ENDTAB");let s=["*Model_Space","*Paper_Space",...n];t.p(0,"TABLE").p(2,"BLOCK_RECORD").p(70,s.length);for(let o of s)t.p(0,"BLOCK_RECORD").p(5,t.handle()).p(2,o);t.p(0,"ENDTAB"),t.p(0,"ENDSEC")}_writeBlocks(t,i){if(t.p(0,"SECTION").p(2,"BLOCKS"),this._writeBlock(t,"*Model_Space",null),this._writeBlock(t,"*Paper_Space",null),i)for(let[n,s]of i.definitions)this._writeBlock(t,n,s.lines??null);t.p(0,"ENDSEC")}_writeBlock(t,i,n){if(t.p(0,"BLOCK").p(5,t.handle()).p(8,"0").p(2,i).p(70,0).n(10,0).n(20,0).n(30,0).p(3,i).p(1,""),n){let s=this._viewport,o=this._paperSlot;this._viewport=null,this._paperSlot=null,this._writeGeoAsLines(t,n,"0"),this._viewport=s,this._paperSlot=o}t.p(0,"ENDBLK").p(5,t.handle()).p(8,"0")}_writeViewportBorder(t){if(!this._viewport)return;let i=this._viewport,n=this._tx(i.left),s=this._tx(i.right),o=this._ty(-i.bottom),r=this._ty(-i.top);this._writeRawLine(t,n,o,s,o,"0",7),this._writeRawLine(t,s,o,s,r,"0",7),this._writeRawLine(t,s,r,n,r,"0",7),this._writeRawLine(t,n,r,n,o,"0",7)}_writePaperBorders(t,i){let{margin:n,widthMm:s,heightMm:o}=i,r=s-2*n,l=o-2*n;this._writeRawLine(t,0,0,r,0,"0",7),this._writeRawLine(t,r,0,r,l,"0",7),this._writeRawLine(t,r,l,0,l,"0",7),this._writeRawLine(t,0,l,0,0,"0",7),this._writeRawLine(t,-n,-n,r+n,-n,"0",7),this._writeRawLine(t,r+n,-n,r+n,l+n,"0",7),this._writeRawLine(t,r+n,l+n,-n,l+n,"0",7),this._writeRawLine(t,-n,l+n,-n,-n,"0",7)}_writeObjects(t){t.p(0,"SECTION").p(2,"OBJECTS"),t.p(0,"DICTIONARY").p(5,t.handle()).p(330,0).p(100,"AcDbRootDictionary"),t.p(0,"ENDSEC")}_writeRawLines(t,i){i.three.traverse(n=>{var s;if(!
#include <common>
#include <color_pars_vertex>
#include <clipping_planes_pars_vertex>
uniform float depthBiasStrength;
void main() {
#include <color_vertex>
vColor = color;
#include <begin_vertex>
#include <project_vertex>
// Compute priority from vertex color (using luminance)
// Higher values = higher priority = render on top
float priority = dot(color, vec3(0.299, 0.587, 0.114)); // Luminance
// Apply depth bias: subtract from z to bring higher priority faces closer
// In clip space, smaller z values are closer to camera
gl_Position.z -= priority * depthBiasStrength;
#include <clipping_planes_vertex>
}
`,fragmentShader:`
varying vec3 vColor;
#include <clipping_planes_pars_fragment>
void main() {
#include <clipping_planes_fragment>
gl_FragColor = vec4(vColor, 1.0);
}
`}),this._edgeMaterial=new Bs({uniforms:{tDiffuse:{value:null},width:{value:n}},vertexShader:`
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,fragmentShader:`
uniform sampler2D tDiffuse;
uniform float width;
varying vec2 vUv;
void main() {
vec2 texel = vec2(1.0 / float(textureSize(tDiffuse, 0).x), 1.0 / float(textureSize(tDiffuse, 0).y));
vec2 offset = texel * width;
vec4 center = texture2D(tDiffuse, vUv);
vec4 right = texture2D(tDiffuse, vUv + vec2(offset.x, 0.0));
vec4 up = texture2D(tDiffuse, vUv + vec2(0.0, offset.y));
float diff = 0.0;
diff += distance(center.rgb, right.rgb);
diff += distance(center.rgb, up.rgb);
gl_FragColor = vec4(vec3(step(0.0001, diff)), 1.0);
}
`}),this._combineMaterial=new Bs({uniforms:{tDiffuse:{value:null},tEdges:{value:null},edgeColor:{value:new Ei(8947848)}},vertexShader:`
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,fragmentShader:`
uniform sampler2D tDiffuse;
uniform sampler2D tEdges;
uniform vec3 edgeColor;
varying vec2 vUv;
void main() {
vec4 color = texture2D(tDiffuse, vUv);
vec4 edges = texture2D(tEdges, vUv);
// Combine color with edges (edges are black, so we multiply)
gl_FragColor = mix(color, vec4(edgeColor, 1.0), edges.r);
}
`}),this._fsQuad=new sm(this._edgeMaterial),this._edgeRenderTarget=new bo(1,1,{minFilter:Ds,magFilter:Ds,format:_o}),this._vertexColorRenderTarget=new bo(1,1,{minFilter:Ds,magFilter:Ds,format:_o})}get mode(){return this._mode}set mode(t){this._mode=t,this.setMaterialToMesh(!1)}get width(){return this._edgeMaterial.uniforms.width.value}set width(t){this._edgeMaterial.uniforms.width.value=t}get color(){return this._combineMaterial.uniforms.edgeColor.value}set color(t){this._combineMaterial.uniforms.edgeColor.value=t}get depthBiasStrength(){return this._depthBiasStrength}set depthBiasStrength(t){this._depthBiasStrength=t,this._overrideMaterial&&(this._overrideMaterial.uniforms.depthBiasStrength.value=t)}setSize(t,i){this._edgeRenderTarget.setSize(t,i),this._vertexColorRenderTarget.setSize(t,i)}setWidth(t){this._edgeMaterial.uniforms.width.value=t}render(t,i,n){let s=this._renderer.currentWorld,o=s.scene.three,r=s.scene.three,l=r.fog,a=r.background;if(r.fog=null,r.background=null,this._mode===0)this.setMaterialToMesh(!0),t.setRenderTarget(this._vertexColorRenderTarget),t.render(o,s.camera.three),this.setMaterialToMesh(!1);else if(this._mode===1){let u=o.overrideMaterial;o.overrideMaterial=this._overrideMaterial,t.setRenderTarget(this._vertexColorRenderTarget),t.render(o,s.camera.three),o.overrideMaterial=u}r.fog=l,r.background=a,this._edgeMaterial.uniforms.tDiffuse.value=this._vertexColorRenderTarget.texture,this._fsQuad.material=this._edgeMaterial,t.setRenderTarget(this._edgeRenderTarget),this._fsQuad.render(t),this._combineMaterial.uniforms.tDiffuse.value=n.texture,this._combineMaterial.uniforms.tEdges.value=this._edgeRenderTarget.texture,this._fsQuad.material=this._combineMaterial,this.renderToScreen?t.setRenderTarget(null):t.setRenderTarget(i),this._fsQuad.render(t)}dispose(){this._edgeMaterial.dispose(),this._combineMaterial.dispose(),this._overrideMaterial.dispose(),this._fsQuad.dispose(),this._edgeRenderTarget.dispose(),this._vertexColorRenderTarget.dispose()}setMaterialToMesh(t){if(this._fragments.initialized)for(let[,i]of this._fragments.core.models.list)for(let[,n]of i.tiles)"isLODGeometry"in n.geometry||(t?(n.userData.edgePassPreviousMaterial=n.material,n.material=this.xray?this._overrideMaterial:[this._overrideMaterial]):"edgePassPreviousMaterial"in n.userData&&(n.material=n.userData.edgePassPreviousMaterial))}},tEe=class extends _0{constructor(t,i,n){super(),Ge(this,"outlineColor",new Ei(16762880)),Ge(this,"thickness",2),Ge(this,"fillColor",new Ei(16776960)),Ge(this,"fillOpacity",.3),Ge(this,"debugShowMask",!1),Ge(this,"scene",new yc),Ge(this,"_maskTarget"),Ge(this,"_fsQuad"),Ge(this,"_world"),Ge(this,"_debugQuad",null),this._world=n,this.scene.background=new Ei(0),this._maskTarget=new bo(t,i,{minFilter:Ds,magFilter:Ds,format:_o,type:Vo}),this._fsQuad=new sm(new Bs({uniforms:{tDiffuse:{value:null},tMask:{value:null},outlineColor:{value:new Ei(65280)},thickness:{value:2},resolution:{value:new si(t,i)},fillColor:{value:new Ei(16776960)},fillOpacity:{value:.3}},vertexShader:`
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,fragmentShader:`
uniform sampler2D tDiffuse;
uniform sampler2D tMask;
uniform vec3 outlineColor;
uniform float thickness;
uniform vec2 resolution;
uniform vec3 fillColor;
uniform float fillOpacity;
varying vec2 vUv;
void main() {
float mask = texture2D(tMask, vUv).r;
float outline = 0.0;
float t = thickness;
vec2 texel = 1.0 / resolution;
for (float x = -t; x <= t; x++) {
for (float y = -t; y <= t; y++) {
vec2 offset = vec2(x, y) * texel;
float neighbor = texture2D(tMask, vUv + offset).r;
if (neighbor > 0.5) outline = 1.0;
}
}
vec4 sceneColor = texture2D(tDiffuse, vUv);
// Fill inside
if (mask > 0.5) {
sceneColor.rgb = mix(sceneColor.rgb, fillColor, fillOpacity);
}
// Only draw outline where mask is not set but neighbor is
if (outline > 0.5 && mask < 0.5) {
gl_FragColor = vec4(outlineColor, 1.0);
} else {
gl_FragColor = sceneColor;
}
}
`})),this._debugQuad=new sm(new Bs({uniforms:{tMask:{value:null}},vertexShader:`
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,fragmentShader:`
uniform sampler2D tMask;
varying vec2 vUv;
void main() {
float mask = texture2D(tMask, vUv).r;
gl_FragColor = vec4(vec3(mask), 1.0);
}
`}))}setSize(t,i){this._maskTarget.setSize(t,i),this._fsQuad.material.uniforms.resolution.value.set(t,i)}render(t,i,n){let s=this._world.camera.three,o=t.getClearColor(new Ei),r=t.getClearAlpha();if(t.setClearColor(0,0),t.setRenderTarget(this._maskTarget),t.clear(),t.render(this.scene,s),t.setClearColor(o,r),this.debugShowMask){let a=this._debugQuad.material;a.uniforms.tMask.value=this._maskTarget.texture,this.renderToScreen?t.setRenderTarget(null):t.setRenderTarget(i),this._debugQuad.render(t);return}let l=this._fsQuad.material;l.uniforms.tDiffuse.value=n.texture,l.uniforms.tMask.value=this._maskTarget.texture,l.uniforms.outlineColor.value.copy(this.outlineColor),l.uniforms.thickness.value=this.thickness,l.uniforms.fillColor.value.copy(this.fillColor),l.uniforms.fillOpacity.value=this.fillOpacity,this.renderToScreen?t.setRenderTarget(null):t.setRenderTarget(i),this._fsQuad.render(t)}dispose(){this._maskTarget.dispose(),this._fsQuad.dispose();let t=[...this.scene.children];for(let i of t)i.removeFromParent()}},iEe=class extends _0{constructor(t,i){super(),Ge(this,"materialToExclude",new ws({color:0})),Ge(this,"_excludedMaterials",new Set),Ge(this,"_originalMaterials",new Map),Ge(this,"_renderer"),Ge(this,"_world"),Ge(this,"_fsQuad"),Ge(this,"_combineMaterial"),Ge(this,"_excludedRenderTarget"),this._renderer=t,this._world=i,this._excludedRenderTarget=new bo(1,1,{minFilter:Ds,magFilter:Ds,format:_o}),this._combineMaterial=new Bs({uniforms:{tDiffuse:{value:null},tExcluded:{value:null}},vertexShader:`
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,fragmentShader:`
uniform sampler2D tDiffuse;
uniform sampler2D tExcluded;
varying vec2 vUv;
void main() {
vec4 inputColor = texture2D(tDiffuse, vUv);
vec4 excludedColor = texture2D(tExcluded, vUv);
// If excluded pixel is black (or very dark), use input color
// Otherwise, use excluded color
float excludedLuminance = (excludedColor.r + excludedColor.g + excludedColor.b) / 3.0;
float threshold = 0.01; // Adjust this threshold as needed
if (excludedLuminance < threshold) {
gl_FragColor = inputColor;
} else {
gl_FragColor = excludedColor;
}
}
`}),this._fsQuad=new sm(this._combineMaterial)}addExcludedMaterial(t){this._excludedMaterials.add(t)}removeExcludedMaterial(t){this._excludedMaterials.delete(t)}clearExcludedMaterials(){this._excludedMaterials.clear()}get excludedMaterials(){return Array.from(this._excludedMaterials)}setSize(t,i){this._excludedRenderTarget.setSize(t,i)}render(t,i,n){let s=this._world.scene.three,o=this._world.camera.three,r=t.getClearColor(new Ei),l=t.getClearAlpha();t.setClearColor(0,0),this._substituteMaterials(s),t.setRenderTarget(this._excludedRenderTarget),t.render(s,o),this._restoreMaterials(),this._combineMaterial.uniforms.tDiffuse.value=n.texture,this._combineMaterial.uniforms.tExcluded.value=this._excludedRenderTarget.texture,this.renderToScreen?t.setRenderTarget(null):t.setRenderTarget(i),this._fsQuad.render(t),t.setClearColor(r,l)}_substituteMaterials(t){if(t instanceof ci){let i=t.material;if(Array.isArray(i)){for(let n of i)if("isLodMaterial"in n)return}else if("isLodMaterial"in i)return;this._excludedMaterials.has(i)||(this._originalMaterials.set(t,i),t.material=this.materialToExclude)}for(let i of t.children)this._substituteMaterials(i)}_restoreMaterials(){for(let[t,i]of this._originalMaterials)t.material=i;this._originalMaterials.clear()}dispose(){this.materialToExclude.dispose(),this._combineMaterial.dispose(),this._fsQuad.dispose(),this._excludedRenderTarget.dispose(),this._excludedMaterials.clear(),this._originalMaterials.clear()}},nEe=class extends _0{constructor(t,i,n=null,s=null,o=null){super(),Ge(this,"scene"),Ge(this,"camera"),Ge(this,"overrideMaterial"),Ge(this,"clearColor"),Ge(this,"clearAlpha"),Ge(this,"clearDepth"),Ge(this,"needsSwap"),Ge(this,"isolatedMaterials",[]),Ge(this,"_oldClearColor"),this.scene=t,this.camera=i,this.overrideMaterial=n,this.clearColor=s,this.clearAlpha=o,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this._oldClearColor=new Ei}render(t,i,n){for(let l of this.isolatedMaterials)l.userData.wasVisibleBasePass!==void 0&&(l.visible=l.userData.wasVisibleBasePass);let s=t.autoClear;t.autoClear=!1;let o,r;this.overrideMaterial!==null&&(r=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),this.clearColor!==null&&(t.getClearColor(this._oldClearColor),t.setClearColor(this.clearColor,t.getClearAlpha())),this.clearAlpha!==null&&(o=t.getClearAlpha(),t.setClearAlpha(this.clearAlpha)),this.clearDepth===!0&&t.clearDepth(),t.setRenderTarget(this.renderToScreen?null:n),this.clear===!0&&t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil),t.render(this.scene,this.camera),this.clearColor!==null&&t.setClearColor(this._oldClearColor),this.clearAlpha!==null&&t.setClearAlpha(o),this.overrideMaterial!==null&&(this.scene.overrideMaterial=r),t.autoClear=s;for(let l of this.isolatedMaterials)l.userData.wasVisibleBasePass=l.visible,l.visible=!1}};function aht(){return new Bs({clipping:!0,uniforms:{glossExponent:{value:10},fresnelExponent:{value:6},glossFactor:{value:.2},fresnelFactor:{value:1}},vertexShader:`
varying vec3 vCameraPosition;
varying vec3 vPosition;
varying vec3 vNormal;
#include <clipping_planes_pars_vertex>
void main() {
#include <begin_vertex>
vec4 absPosition = vec4(position, 1.0);
vNormal = normal;
#ifdef USE_INSTANCING
absPosition = instanceMatrix * absPosition;
vNormal = (instanceMatrix * vec4(normal, 0.)).xyz;
#endif
absPosition = modelMatrix * absPosition;
vNormal = (normalize(modelMatrix * vec4(vNormal, 0.))).xyz;
gl_Position = projectionMatrix * viewMatrix * absPosition;
vCameraPosition = cameraPosition;
vPosition = absPosition.xyz;
#include <project_vertex>
#include <clipping_planes_vertex>
}
`,fragmentShader:`
uniform float glossExponent;
uniform float glossFactor;
uniform float fresnelExponent;
uniform float fresnelFactor;
varying vec3 vCameraPosition;
varying vec3 vPosition;
varying vec3 vNormal;
#include <clipping_planes_pars_fragment>
void main() {
#include <clipping_planes_fragment>
vec3 cameraPixelVec = normalize(vCameraPosition - vPosition);
float dotProduct = dot(vNormal, cameraPixelVec);
// Use abs() for both gloss and fresnel to handle DoubleSide materials
// On back faces, dotProduct is negative, which breaks the fresnel calculation
float absDotProduct = abs(dotProduct);
float gloss = absDotProduct;
// Use absDotProduct instead of dotProduct to prevent values > 1.0
float fresnel = pow(1.0 - absDotProduct, fresnelExponent) * fresnelFactor;
gloss = pow(gloss, glossExponent) * glossFactor;
float result = gloss + fresnel;
gl_FragColor = vec4(result, result, result, 1.);
}
`})}var tse=class extends _0{constructor(t,i){super(),Ge(this,"resolution"),Ge(this,"renderScene"),Ge(this,"renderCamera"),Ge(this,"fsQuad"),Ge(this,"glossOverrideMaterial"),Ge(this,"glossBuffer"),Ge(this,"_glossEnabled",!0),this.renderScene=i.scene.three,this.renderCamera=i.camera.three,this.resolution=new si(t.x,t.y),this.fsQuad=new sm,this.fsQuad.material=this.createGlossMaterial(),this.glossBuffer=this.newRenderTarget();let n=aht();this.glossOverrideMaterial=n}get glossEnabled(){return this._glossEnabled}set glossEnabled(t){this._glossEnabled=t;let i=this.fsQuad.material;i.uniforms.glossEnabled.value=t?1:0}get minGloss(){return this.fsQuad.material.uniforms.minGloss.value}set minGloss(t){let i=this.fsQuad.material;i.uniforms.minGloss.value=t}get maxGloss(){return this.fsQuad.material.uniforms.maxGloss.value}set maxGloss(t){let i=this.fsQuad.material;i.uniforms.maxGloss.value=t}get glossExponent(){return this.glossOverrideMaterial.uniforms.glossExponent.value}set glossExponent(t){this.glossOverrideMaterial.uniforms.glossExponent.value=t}get fresnelExponent(){return this.glossOverrideMaterial.uniforms.fresnelExponent.value}set fresnelExponent(t){this.glossOverrideMaterial.uniforms.fresnelExponent.value=t}get glossFactor(){return this.glossOverrideMaterial.uniforms.glossFactor.value}set glossFactor(t){this.glossOverrideMaterial.uniforms.glossFactor.value=t}get fresnelFactor(){return this.glossOverrideMaterial.uniforms.fresnelFactor.value}set fresnelFactor(t){this.glossOverrideMaterial.uniforms.fresnelFactor.value=t}dispose(){this.glossBuffer.dispose(),this.glossOverrideMaterial.dispose(),this.fsQuad.dispose()}setSize(t,i){this.glossBuffer.setSize(t,i),this.resolution.set(t,i),this.fsQuad.material.uniforms.screenSize.value.set(this.resolution.x,this.resolution.y,1/this.resolution.x,1/this.resolution.y)}render(t,i,n){let s=i.depthBuffer;i.depthBuffer=!1;let o=this.renderScene.overrideMaterial,r=this.renderScene.background;this.renderScene.background=null,t.setRenderTarget(this.glossBuffer),this.renderScene.overrideMaterial=this.glossOverrideMaterial,t.render(this.renderScene,this.renderCamera),this.renderScene.overrideMaterial=o,this.renderScene.background=r;let l=this.fsQuad.material;l.uniforms.glossBuffer.value=this.glossBuffer.texture,l.uniforms.sceneColorBuffer.value=n.texture,this.renderToScreen?(t.setRenderTarget(null),this.fsQuad.render(t)):(t.setRenderTarget(i),this.fsQuad.render(t)),i.depthBuffer=s}get vertexShader(){return`
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`}get fragmentShader(){return`
uniform sampler2D sceneColorBuffer;
uniform sampler2D glossBuffer;
uniform vec4 screenSize;
uniform float glossEnabled;
uniform float minGloss;
uniform float maxGloss;
varying vec2 vUv;
vec4 getValue(sampler2D buffer, int x, int y) {
return texture2D(buffer, vUv + screenSize.zw * vec2(x, y));
}
void main() {
vec4 sceneColor = getValue(sceneColorBuffer, 0, 0);
// Apply gloss effect
vec3 gloss = getValue(glossBuffer, 0, 0).xyz;
// Prevent the gloss from being zero, which would break normalize() later
gloss = max(gloss, vec3(0.001));
vec3 glossEffect = gloss * glossEnabled;
// Map glossEffect to range [minGloss, maxGloss]
// All dimensions of the glossEffect are the same, so we can use the x dimension.
float mappedGloss = minGloss + (maxGloss - minGloss) * glossEffect.x;
glossEffect = normalize(glossEffect) * mappedGloss;
vec4 glossedColor = sceneColor + vec4(glossEffect, 0.0);
// Prevent the glossed color from being darker than zero
glossedColor = max(glossedColor, vec4(0.0, 0.0, 0.0, sceneColor.a));
gl_FragColor = glossedColor;
}
`}createGlossMaterial(){return new Bs({uniforms:{sceneColorBuffer:{value:null},glossBuffer:{value:null},glossEnabled:{value:this._glossEnabled?1:0},minGloss:{value:-.12},maxGloss:{value:.8},screenSize:{value:new Gn(this.resolution.x,this.resolution.y,1/this.resolution.x,1/this.resolution.y)}},vertexShader:this.vertexShader,fragmentShader:this.fragmentShader})}newRenderTarget(){let t=new bo(this.resolution.x,this.resolution.y);return t.texture.colorSpace="srgb-linear",t.texture.format=_o,t.texture.type=Ao,t.texture.minFilter=Us,t.texture.magFilter=Us,t.texture.generateMipmaps=!1,t.stencilBuffer=!1,t}},ise=(e=>(e[e.COLOR=0]="COLOR",e[e.PEN=1]="PEN",e[e.PEN_SHADOWS=2]="PEN_SHADOWS",e[e.COLOR_PEN=3]="COLOR_PEN",e[e.COLOR_SHADOWS=4]="COLOR_SHADOWS",e[e.COLOR_PEN_SHADOWS=5]="COLOR_PEN_SHADOWS",e))(ise||{}),sEe=class{constructor(t,i){Ge(this,"invisibleMaterials",new Set),Ge(this,"composer"),Ge(this,"onStyleChanged",new Vi),Ge(this,"_enabled",!1),Ge(this,"_initialized",!1),Ge(this,"_basePass"),Ge(this,"_aoPass"),Ge(this,"_outputPass"),Ge(this,"_edgeDetectionPass"),Ge(this,"_smaaPass"),Ge(this,"_simpleOutlinePass"),Ge(this,"_excludedObjectsPass"),Ge(this,"_glossPass"),Ge(this,"_style",0),Ge(this,"_outlinesEnabled",!1),Ge(this,"_glossEnabled",!1),Ge(this,"_smaaEnabled",!1),Ge(this,"_excludedObjectsEnabled",!1),Ge(this,"_components"),Ge(this,"_renderer"),Ge(this,"_clearColor",new Ei),Ge(this,"defaultAoParameters",{radius:.25,distanceExponent:5.7,thickness:10,scale:2,samples:16,distanceFallOff:1,screenSpaceRadius:!0}),this._components=t,this._renderer=i}get basePass(){if(!this._basePass)throw new Error("Base pass not initialized");return this._basePass}get enabled(){return this._enabled}set enabled(t){if(this._enabled=t,t&&!this._initialized&&this.initialize(),!t)for(let i of this.basePass.isolatedMaterials)i.visible=!0}get aoPass(){if(!this._aoPass)throw new Error("AO pass not initialized");return this._aoPass}get outlinePass(){if(!this._simpleOutlinePass)throw new Error("Outline pass not initialized");return this._simpleOutlinePass}get edgesPass(){if(!this._edgeDetectionPass)throw new Error("Edge detection pass not initialized");return this._edgeDetectionPass}get excludedObjectsPass(){if(!this._excludedObjectsPass)throw new Error("Excluded objects pass not initialized");return this._excludedObjectsPass}get glossPass(){if(!this._glossPass)throw new Error("Gloss pass not initialized");return this._glossPass}get outlinesEnabled(){return this._outlinesEnabled}set outlinesEnabled(t){this._outlinesEnabled=t,this.style=this._style}get excludedObjectsEnabled(){return this._excludedObjectsEnabled}set excludedObjectsEnabled(t){this._excludedObjectsEnabled=t,this.style=this._style}get glossEnabled(){return this._glossEnabled}set glossEnabled(t){this._glossEnabled=t,this.style=this._style}get smaaEnabled(){return this._smaaEnabled}set smaaEnabled(t){this._smaaEnabled=t,this.style=this._style}get style(){return this._style}set style(t){this.composer&&(!this.composer||!this._basePass||!this._smaaPass||!this._outputPass||!this._aoPass||!this._edgeDetectionPass||!this._simpleOutlinePass||!this._excludedObjectsPass||!this._glossPass||(this._style===2&&this._aoPass.updateGtaoMaterial(this.defaultAoParameters),this._style=t,this.clear(),t===0&&(this.composer.addPass(this._basePass),this._glossEnabled&&this.composer.addPass(this._glossPass),this._outlinesEnabled&&this.composer.addPass(this._simpleOutlinePass),this._excludedObjectsEnabled&&this.composer.addPass(this._excludedObjectsPass),this._smaaEnabled&&this.composer.addPass(this._smaaPass),this.composer.addPass(this._outputPass)),t===1&&(this.composer.addPass(this._edgeDetectionPass),this._outlinesEnabled&&this.composer.addPass(this._simpleOutlinePass),this._excludedObjectsEnabled&&this.composer.addPass(this._excludedObjectsPass),this._smaaEnabled&&this.composer.addPass(this._smaaPass)),t===2&&(this.composer.addPass(this._basePass),this.composer.addPass(this._aoPass),this._aoPass.output=Xb.OUTPUT.AO,this.composer.addPass(this._edgeDetectionPass),this._outlinesEnabled&&this.composer.addPass(th
/*! Bundled license information:
jszip/dist/jszip.min.js:
@thatopen/components/dist/index.mjs:
(*!
JSZip v3.10.1 - A JavaScript class for generating and reading zip files
<http://stuartk.com/jszip>
(c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown.
JSZip uses the library pako released under the MIT license :
https://github.com/nodeca/pako/blob/main/LICENSE
*)
three/build/three.core.js:
three/build/three.module.js:
three/build/three.webgpu.js:
three/build/three.tsl.js:
(**
* @license
* Copyright 2010-2026 Three.js Authors
* SPDX-License-Identifier: MIT
*)
@thatopen/fragments/dist/index.mjs:
(*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) *)
camera-controls/dist/camera-controls.module.js:
(*!
* camera-controls
* https://github.com/yomotsu/camera-controls
* (c) 2017 @yomotsu
* Released under the MIT License.
*)
three/examples/jsm/libs/opentype.module.js:
(*! https://mths.be/codepointat v0.2.0 by @mathias *)
@thatopen/components-front/dist/index.js:
(*!
* camera-controls
* https://github.com/yomotsu/camera-controls
* (c) 2017 @yomotsu
* Released under the MIT License.
*)
(*!
JSZip v3.10.1 - A JavaScript class for generating and reading zip files
<http://stuartk.com/jszip>
(c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown.
JSZip uses the library pako released under the MIT license :
https://github.com/nodeca/pako/blob/main/LICENSE
*)
*/