@threepipe/webgi-plugins 0.6.4 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/CHANGELOG.md +99 -0
  2. package/LICENSE +133 -16
  3. package/README.md +29 -26
  4. package/THIRD_PARTY_NOTICES.md +243 -0
  5. package/dist/dependencies.txt +1 -1
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +3907 -18
  8. package/dist/index.js.map +1 -1
  9. package/dist/index.mjs +3824 -18
  10. package/dist/index.mjs.map +1 -1
  11. package/dist/passes/BilateralFilterPass.d.ts +1 -1
  12. package/dist/passes/BilateralFilterPass.d.ts.map +1 -1
  13. package/dist/plugins/buffer/VelocityBufferPlugin.d.ts.map +1 -1
  14. package/dist/plugins/extras/AdvancedGroundPlugin.d.ts +4 -3
  15. package/dist/plugins/extras/AdvancedGroundPlugin.d.ts.map +1 -1
  16. package/dist/plugins/extras/AnisotropyPlugin.d.ts +5 -4
  17. package/dist/plugins/extras/AnisotropyPlugin.d.ts.map +1 -1
  18. package/dist/plugins/extras/WatchHandsPlugin.d.ts +1 -1
  19. package/dist/plugins/extras/WatchHandsPlugin.d.ts.map +1 -1
  20. package/dist/plugins/index.d.ts +23 -23
  21. package/dist/plugins/postprocessing/BloomPlugin.d.ts.map +1 -1
  22. package/dist/plugins/postprocessing/DepthOfFieldPlugin.d.ts.map +1 -1
  23. package/dist/plugins/postprocessing/OutlinePlugin.d.ts +1 -1
  24. package/dist/plugins/postprocessing/OutlinePlugin.d.ts.map +1 -1
  25. package/dist/plugins/postprocessing/SSContactShadowsPlugin.d.ts.map +1 -1
  26. package/dist/plugins/postprocessing/SSGIPlugin.d.ts +3 -2
  27. package/dist/plugins/postprocessing/SSGIPlugin.d.ts.map +1 -1
  28. package/dist/plugins/postprocessing/SSReflectionPlugin.d.ts +1 -1
  29. package/dist/plugins/postprocessing/SSReflectionPlugin.d.ts.map +1 -1
  30. package/dist/plugins/postprocessing/TemporalAAPlugin.d.ts.map +1 -1
  31. package/dist/utils/FSShadowMaterial.d.ts.map +1 -1
  32. package/dist/utils/RandomizedDirectionalLight.d.ts.map +1 -1
  33. package/dist/utils/Reflector2.d.ts +4 -4
  34. package/dist/utils/Reflector2.d.ts.map +1 -1
  35. package/dist/utils/ShadowMapBaker.d.ts +1 -1
  36. package/dist/utils/ShadowMapBaker.d.ts.map +1 -1
  37. package/docs/.nojekyll +1 -0
  38. package/docs/assets/hierarchy.js +1 -0
  39. package/docs/assets/highlight.css +22 -0
  40. package/docs/assets/icons.js +18 -0
  41. package/docs/assets/icons.svg +1 -0
  42. package/docs/assets/main.js +60 -0
  43. package/docs/assets/navigation.js +1 -0
  44. package/docs/assets/search.js +1 -0
  45. package/docs/assets/style.css +1648 -0
  46. package/docs/classes/AdvancedGroundPlugin.html +736 -0
  47. package/docs/classes/AnisotropyPlugin.html +432 -0
  48. package/docs/classes/BloomPlugin.html +466 -0
  49. package/docs/classes/BloomPluginPass.html +323 -0
  50. package/docs/classes/DepthOfFieldPlugin.html +493 -0
  51. package/docs/classes/DepthOfFieldPluginPass.html +340 -0
  52. package/docs/classes/OutlinePlugin.html +696 -0
  53. package/docs/classes/OutlineRenderPass.html +252 -0
  54. package/docs/classes/SSContactShadowsPlugin.html +421 -0
  55. package/docs/classes/SSGIPlugin.html +488 -0
  56. package/docs/classes/SSGIPluginPass.html +404 -0
  57. package/docs/classes/SSReflectionPlugin.html +495 -0
  58. package/docs/classes/SSReflectionPluginPass.html +410 -0
  59. package/docs/classes/SSVelocityMaterial.html +110 -0
  60. package/docs/classes/TemporalAAPlugin.html +447 -0
  61. package/docs/classes/TemporalAAPluginPass.html +337 -0
  62. package/docs/classes/VelocityBufferPlugin.html +480 -0
  63. package/docs/classes/WatchHandsPlugin.html +443 -0
  64. package/docs/hierarchy.html +28 -0
  65. package/docs/index.html +38 -0
  66. package/docs/types/OutlinePluginPass.html +32 -0
  67. package/docs/types/OutlinePluginTarget.html +32 -0
  68. package/docs/types/SSGIPluginTarget.html +32 -0
  69. package/docs/types/SSReflectionPluginTarget.html +32 -0
  70. package/docs/types/VelocityBufferPluginPass.html +32 -0
  71. package/docs/types/VelocityBufferPluginTarget.html +32 -0
  72. package/docs/variables/anisotropyGLTFExtension.html +43 -0
  73. package/docs/variables/webgiPlugins.html +32 -0
  74. package/package.json +23 -22
  75. package/src/global.d.ts +27 -0
  76. package/src/index.ts +1 -0
  77. package/src/passes/BilateralFilterPass.ts +62 -0
  78. package/src/passes/shaders/ssaoBilateral.glsl +89 -0
  79. package/src/plugins/buffer/VelocityBufferPlugin.ts +270 -0
  80. package/src/plugins/buffer/shaders/VelocityBufferPlugin.mat.frag.glsl +46 -0
  81. package/src/plugins/buffer/shaders/VelocityBufferPlugin.mat.vert.glsl +51 -0
  82. package/src/plugins/buffer/shaders/VelocityBufferPlugin.unpack.glsl +8 -0
  83. package/src/plugins/extras/AdvancedGroundPlugin.ts +385 -0
  84. package/src/plugins/extras/AnisotropyPlugin.ts +519 -0
  85. package/src/plugins/extras/WatchHandsPlugin.ts +156 -0
  86. package/src/plugins/extras/shaders/anisotropyBsdf.glsl +64 -0
  87. package/src/plugins/extras/shaders/anisotropyTBN.glsl +35 -0
  88. package/src/plugins/index.ts +38 -0
  89. package/src/plugins/postprocessing/BloomPlugin.ts +377 -0
  90. package/src/plugins/postprocessing/DepthOfFieldPlugin.ts +470 -0
  91. package/src/plugins/postprocessing/OutlinePlugin.ts +476 -0
  92. package/src/plugins/postprocessing/SSContactShadowsPlugin.ts +374 -0
  93. package/src/plugins/postprocessing/SSGIPlugin.ts +597 -0
  94. package/src/plugins/postprocessing/SSReflectionPlugin.ts +563 -0
  95. package/src/plugins/postprocessing/TemporalAAPlugin.ts +301 -0
  96. package/src/plugins/postprocessing/shaders/dofBlurBox.glsl +46 -0
  97. package/src/plugins/postprocessing/shaders/dofCombine.glsl +68 -0
  98. package/src/plugins/postprocessing/shaders/dofComputeCoC.glsl +21 -0
  99. package/src/plugins/postprocessing/shaders/dofExpandCoC.glsl +56 -0
  100. package/src/plugins/postprocessing/shaders/dofPoissonBox.glsl +90 -0
  101. package/src/plugins/postprocessing/shaders/giPatch.glsl +53 -0
  102. package/src/plugins/postprocessing/shaders/hdrBloom.glsl +101 -0
  103. package/src/plugins/postprocessing/shaders/outline.glsl +60 -0
  104. package/src/plugins/postprocessing/shaders/outlineDepthFrag.glsl +22 -0
  105. package/src/plugins/postprocessing/shaders/outlineDepthVert.glsl +26 -0
  106. package/src/plugins/postprocessing/shaders/poissonDiskSamples.glsl +19 -0
  107. package/src/plugins/postprocessing/shaders/samplePointHelpers.glsl +3 -0
  108. package/src/plugins/postprocessing/shaders/ssrPatch.glsl +145 -0
  109. package/src/plugins/postprocessing/shaders/ssreflectionMain.glsl +69 -0
  110. package/src/plugins/postprocessing/shaders/ssrt.glsl +118 -0
  111. package/src/utils/FSShadowMaterial.ts +65 -0
  112. package/src/utils/RandomizedDirectionalLight.ts +288 -0
  113. package/src/utils/Reflector2.ts +309 -0
  114. package/src/utils/ShadowMapBaker.ts +527 -0
  115. package/src/utils/shaders/computeScreenSpaceVelocity.glsl +16 -0
  116. package/src/utils/shaders/getWorldPositionFromViewZ.glsl +9 -0
  117. package/src/utils/shaders/poissonDiskSamples.glsl +19 -0
  118. package/src/utils/shaders/reflectorSample.glsl +54 -0
  119. package/src/utils/shaders/seperableBlurShaderMasked.glsl +28 -0
  120. package/src/utils/shaders/seperableShadowBlur.glsl +21 -0
  121. package/src/utils/shaders/ssreflection.glsl +141 -0
  122. package/src/utils/shaders/ssrtao.glsl +275 -0
  123. package/src/utils/shaders/temporalaa.glsl +233 -0
  124. package/src/utils/shaders.ts +24 -0
  125. package/tsconfig.json +40 -44
  126. package/dist/version.d.ts +0 -2
  127. package/dist/version.d.ts.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,4 +1,960 @@
1
- var e,t;import{RenderManager as r,PipelinePassPlugin as i,GBufferPlugin as a,ProgressivePlugin as s,generateUiConfig as n,uiToggle as o,uiConfig as l,ExtendedShaderPass as c,Vector2 as d,Matrix4 as u,CopyShader as h,getOrCall as p,serialize as f,uniform as m,uiVector as g,matDefineBool as v,UnsignedByteType as _,shaderReplaceString as y,LinearSRGBColorSpace as x,GBufferRenderPass as S,Color as b,ShaderMaterial as w,NoBlending as T,Matrix3 as D,DoubleSide as P,uiImage as M,uiFolderContainer as E,uiConfigMaterialExtension as C,updateBit as R,Vector4 as A,HalfFloatType as U,AdditiveBlending as L,uiSlider as O,onChange as B,onChange2 as N,Vector3 as F,PickingPlugin as k,now as I,FrameFadePlugin as z,shaderUtils as V,ExtendedShaderMaterial as j,RGBAFormat as G,NearestFilter as H,bindToValue as W,AViewerPluginSync as Y,updateMaterialDefines as X,glsl as K,BaseGroundPlugin as q,matDefine as Z,SSAAPlugin as J,getTexelDecoding as $,AScreenPassExtensionPlugin as Q,animateTarget as ee,RenderPass as te,uiColor as re,makeSamplerUi as ie,SRGBColorSpace as ae,Mesh2 as se,Plane as ne,PerspectiveCamera as oe,MathUtils as le,DirectionalLight2 as ce,copyObject3DUserData as de,Serialization as ue,ThreeSerialization as he,ShadowMaterial as pe,SimpleEventDispatcher as fe,BasicShadowMap as me,ShaderMaterial2 as ge,NoColorSpace as ve,Layers as _e,LinearFilter as ye,LinearMipmapLinearFilter as xe,PCFShadowMap as Se,PCFSoftShadowMap as be,VSMShadowMap as we,uiDropdown as Te,uiInput as De,uiButton as Pe}from"threepipe";const Me={computeScreenSpaceVelocity:"uniform mat4 lastProjectionViewMatrix;uniform mat4 currentProjectionViewMatrix;vec2 computeScreenSpaceVelocity(const in vec3 worldPosition){vec4 currentPositionClip=currentProjectionViewMatrix*vec4(worldPosition,1.0);vec4 prevPositionClip=lastProjectionViewMatrix*vec4(worldPosition,1.0);vec2 currentPositionNDC=currentPositionClip.xy/currentPositionClip.w;vec2 prevPositionNDC=prevPositionClip.xy/prevPositionClip.w;if(prevPositionNDC.x>=1.0||prevPositionNDC.x<=-1.0||prevPositionNDC.x>=1.0||prevPositionNDC.y<=-1.0){return vec2(0.0);}return 0.5*(currentPositionNDC-prevPositionNDC);}",getWorldPositionFromViewZ:"uniform mat4 inverseViewMatrix;vec3 getWorldPositionFromViewZ(const in vec2 uv,const in float viewDepth){vec2 uv_=2.*uv-1.;float xe=-(uv_.x+projection[2][0])*viewDepth/projection[0][0];float ye=-(uv_.y+projection[2][1])*viewDepth/projection[1][1];return(inverseViewMatrix*vec4(xe,ye,viewDepth,1.)).xyz;}",temporalAA:"#include <common>\n#include <gbuffer_unpack>\n#ifdef HAS_VELOCITY_BUFFER\n#pragma <velocity_unpack>\n#else\n#define HAS_VELOCITY_BUFFER 0\n#endif\n#include <cameraHelpers>\nvarying vec2 vUv;uniform vec2 previousRTSize;uniform vec2 jitterSample;uniform vec2 feedBack;uniform bool firstFrame;vec3 find_closest_fragment_3x3(const in vec2 uv){const vec3 offset=vec3(-1.0,1.0,0.0);vec2 texelSize=1.0/previousRTSize;vec3 dtr=vec3(1,1,getDepth(uv+offset.yy*texelSize));vec3 dtc=vec3(0,1,getDepth(uv+offset.zy*texelSize));vec3 dtl=vec3(-1,1,getDepth(uv+offset.xy*texelSize));vec3 dml=vec3(-1,0,getDepth(uv+offset.xz*texelSize));vec3 dmc=vec3(0,0,getDepth(uv));vec3 dmr=vec3(1,0,getDepth(uv+offset.yz*texelSize));vec3 dbl=vec3(-1,-1,getDepth(uv+offset.xx*texelSize));vec3 dbc=vec3(0,-1,getDepth(uv+offset.zx*texelSize));vec3 dbr=vec3(1,-1,getDepth(uv+offset.yx*texelSize));vec3 dmin=dtl;if(dmin.z>dtc.z)dmin=dtc;if(dmin.z>dtr.z)dmin=dtr;if(dmin.z>dml.z)dmin=dml;if(dmin.z>dmc.z)dmin=dmc;if(dmin.z>dmr.z)dmin=dmr;if(dmin.z>dbl.z)dmin=dbl;if(dmin.z>dbc.z)dmin=dbc;if(dmin.z>dbr.z)dmin=dbr;return vec3(uv+texelSize.xy*dmin.xy,dmin.z);}vec3 find_closest_fragment_5tap(const in vec2 uv){vec2 texelSize=1.0/previousRTSize;vec2 offset=vec2(1.0,-1.0);vec3 dtl=vec3(-1,1,getDepth(uv+offset.yx*texelSize));vec3 dtr=vec3(1,1,getDepth(uv+offset.xx*texelSize));vec3 dmc=vec3(0,0,getDepth(uv));vec3 dbl=vec3(-1,-1,getDepth(uv+offset.yy*texelSize));vec3 dbr=vec3(1,-1,getDepth(uv+offset.xy*texelSize));vec3 dmin=dtl;if(dmin.z>dtr.z)dmin=dtr;if(dmin.z>dmc.z)dmin=dmc;if(dmin.z>dbl.z)dmin=dbl;if(dmin.z>dbr.z)dmin=dbr;return vec3(uv+dmin.xy*texelSize,dmin.z);}vec4 clip_aabb(const in vec4 aabb_min,const in vec4 aabb_max,vec4 p){const float FLT_EPS=1e-8;vec4 p_clip=0.5*(aabb_max+aabb_min);vec4 e_clip=0.5*(aabb_max-aabb_min)+FLT_EPS;vec4 v_clip=p-p_clip;vec4 v_unit=abs(v_clip/e_clip);float ma_unit=max(v_unit.x,max(v_unit.y,v_unit.z));if(ma_unit>1.0)return p_clip+v_clip/ma_unit;else return p;}\n#if HAS_VELOCITY_BUFFER == 0 || defined(DEBUG_VELOCITY)\n#include <computeScreenSpaceVelocity>\n#include <getWorldPositionFromViewZ>\n#endif\nvec4 currentRTTexelToLinear1(vec4 a){if(isinf(a.x)||isinf(a.y)||isinf(a.z)||isinf(a.w)){return vec4(1.);}return currentRTTexelToLinear(a);}vec4 computeTAA(const in vec2 uv,const in vec2 screenSpaceVelocity,const in float feedbackScale){vec2 uvUnJitter=uv;vec4 currentColor=currentRTTexelToLinear(texture2D(currentRT,uvUnJitter));vec4 previousColor=previousRTTexelToLinear(texture2D(previousRT,uv-screenSpaceVelocity));const vec3 offset=vec3(1.,-1.,0.);vec2 texelSize=1./previousRTSize;float texelSpeed=length(screenSpaceVelocity);vec4 tl=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.yx*texelSize));vec4 tc=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.zx*texelSize));vec4 tr=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.xx*texelSize));vec4 ml=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.yz*texelSize));vec4 mc=currentColor;vec4 mr=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.xz*texelSize));vec4 bl=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.yy*texelSize));vec4 bc=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.zy*texelSize));vec4 br=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.xy*texelSize));vec4 corners=2.0*(tr+bl+br+tl)-2.0*mc;mc+=(mc-(corners*0.166667))*2.718282*0.3;mc=max(vec4(0.0),mc);vec4 min5=min(tc,min(ml,min(mc,min(mr,bc))));vec4 max5=max(tc,max(ml,max(mc,max(mr,bc))));vec4 cmin=min(min5,min(tl,min(tr,min(bl,br))));vec4 cmax=max(min5,max(tl,max(tr,max(bl,br))));;cmin=0.5*(cmin+min5);cmax=0.5*(cmax+max5);previousColor=clip_aabb(cmin,cmax,previousColor);float lum0=luminance(currentColor.rgb);float lum1=luminance(previousColor.rgb);float unbiased_diff=abs(lum0-lum1)/max(lum0,max(lum1,0.2));float unbiased_weight=1.0-unbiased_diff;float unbiased_weight_sqr=unbiased_weight*unbiased_weight;float k_feedback=mix(feedBack.x,feedBack.y,unbiased_weight_sqr);return mix(currentColor,previousColor,clamp(k_feedback*feedbackScale,0.,1.));}void main(){\n#if HAS_VELOCITY_BUFFER == 0\n#if QUALITY == 1\nvec3 c_frag=find_closest_fragment_3x3(vUv);\n#else\nvec3 c_frag=find_closest_fragment_5tap(vUv);\n#endif\n#else\nvec3 c_frag=vec3(vUv,0.);\n#endif\nbool bg=firstFrame;\n#if BACKGROUND_TAA\nfloat d=c_frag.z;float edgef=min(1.,max(0.,1.-(d*100.-99.)));\n#else\nbg=bg||c_frag.z>0.999;\n#endif\nif(bg){gl_FragColor=currentRTTexelToLinear1(texture2D(currentRT,vUv));}else{\n#if HAS_VELOCITY_BUFFER == 0\nfloat sampleViewZ=mix(-cameraNearFar.x,-cameraNearFar.y,c_frag.z);vec3 worldPosition=getWorldPositionFromViewZ(c_frag.xy,sampleViewZ);vec2 screenSpaceVelocity=computeScreenSpaceVelocity(worldPosition);\n#else\nvec2 screenSpaceVelocity=getVelocity(c_frag.xy);\n#endif\n#if BACKGROUND_TAA\ngl_FragColor=computeTAA(vUv,screenSpaceVelocity*edgef,edgef);\n#else\ngl_FragColor=computeTAA(vUv,screenSpaceVelocity,1.);\n#endif\n}\n#include <colorspace_fragment>\n#ifdef DEBUG_VELOCITY\nfloat sampleViewZ=mix(-cameraNearFar.x,-cameraNearFar.y,c_frag.z);vec3 worldPosition=getWorldPositionFromViewZ(c_frag.xy,sampleViewZ);vec2 screenSpaceVelocity=computeScreenSpaceVelocity(worldPosition);gl_FragColor=vec4(10.*length(screenSpaceVelocity),0.,0.,1.);\n#endif\n}",ssReflection:"uniform float currentFrameCount;\n#ifndef D_frameCount\n#define D_frameCount\nuniform float frameCount;\n#endif\nuniform float objectRadius;uniform float radius;uniform float tolerance;uniform float ssrRoughnessFactor;uniform bool autoRadius;\n#ifndef D_sceneBoundingRadius\n#define D_sceneBoundingRadius\nuniform float sceneBoundingRadius;\n#endif\n#if SSREFL_ENABLED == 2\nuniform float ssrSplitX;\n#endif\n#ifdef HAS_VELOCITY_BUFFER\n#pragma <velocity_unpack>\n#else\n#define HAS_VELOCITY_BUFFER 0\n#endif\n#if HAS_VELOCITY_BUFFER == 0\n#include <computeScreenSpaceVelocity>\n#include <getWorldPositionFromViewZ>\n#endif\nvec3 ComputeReflectionL(vec3 N,vec2 E,vec3 V,float rough){float rough4=rough*rough*rough*rough;float phi=2.0*PI*E.x;float cos_theta=pow(max(E.y,0.000001),rough4/(2.0-rough4));float sin_theta=sqrt(max(0.,1.0-cos_theta*cos_theta));vec3 half_vec=vec3(sin_theta*cos(phi),sin_theta*sin(phi),cos_theta);vec3 tangentX=normalize(cross(abs(N.z)<0.999 ? vec3(0.0,0.0,1.0): vec3(1.0,0.0,0.0),N));vec3 tangentY=cross(N,tangentX);half_vec=half_vec.x*tangentX+half_vec.y*tangentY+half_vec.z*N;vec3 ray_dir=(2.0*dot(V,half_vec))*half_vec-V;return ray_dir;}vec2 GetRandomE(float seed){vec2 rand_e;rand_e.x=interleavedGradientNoise(gl_FragCoord.xy,frameCount*34.+seed);rand_e.y=fract(rand_e.x*38.65435);rand_e.y=mix(rand_e.y,1.0,0.7);return rand_e;}vec4 calculateSSR(in float seed,in vec3 screenPos,in vec3 normal,in float radiusFactor,in float roughness){vec3 viewPos=screenToView3(screenPos.xy,screenPos.z);normal=normalize(normal);vec2 E=GetRandomE(seed);vec3 L=ComputeReflectionL(normal,E,-normalize(viewPos),roughness*ssrRoughnessFactor);L=normalize(L);float cameraDist=length(cameraPositionWorld);float rayLen=objectRadius*sceneBoundingRadius;rayLen=autoRadius ?min(max(mix(max(0.0,(cameraDist+rayLen)+viewPos.z),max(0.0,-viewPos.z-max(0.0,cameraDist-rayLen)),L.z*0.5+0.5),rayLen*0.1),rayLen*5.):rayLen;rayLen*=radiusFactor;float r=interleavedGradientNoise(gl_FragCoord.xy,frameCount+seed);rayLen=max(rayLen,0.001);int steps=SSR_STEP_COUNT/(currentFrameCount<float(SSR_LOW_QUALITY_FRAMES)? 2 : 1);vec3 state=vec3(0.,(r+0.5)/float(steps),2.);viewPos+=normal*max(-0.0001*viewPos.z,0.001);vec3 screenHitP=traceRay(viewPos,L*rayLen,tolerance*rayLen,state,steps);if(state.z<0.99){if(currentFrameCount<1.){\n#if HAS_VELOCITY_BUFFER == 0\nvec3 worldPosition=getWorldPositionFromViewZ(screenHitP.xy,screenHitP.z);vec2 screenSpaceVelocity=computeScreenSpaceVelocity(worldPosition);\n#else\nvec2 screenSpaceVelocity=getVelocity(screenHitP.xy);\n#endif\nscreenHitP.xy-=screenSpaceVelocity;}vec3 hitColor=(tLastFrameTexelToLinear(texture2D(tLastFrame,screenHitP.xy))).rgb;float ssrWeight=1.;return vec4(hitColor*ssrWeight,1.);}return vec4(0.);}",calculateGI:"uniform float currentFrameCount;uniform float intensity;uniform float objectRadius;uniform float rayCount;uniform float power;uniform float bias;uniform float falloff;uniform float tolerance;uniform bool autoRadius;uniform vec2 screenSize;\n#ifndef D_sceneBoundingRadius\n#define D_sceneBoundingRadius\nuniform float sceneBoundingRadius;\n#endif\n#ifdef HAS_VELOCITY_BUFFER\n#pragma <velocity_unpack>\n#else\n#define HAS_VELOCITY_BUFFER 0\n#endif\n#if HAS_VELOCITY_BUFFER == 0\n#include <computeScreenSpaceVelocity>\n#include <getWorldPositionFromViewZ>\n#endif\nvec3 ComputeUniformL(vec3 N,vec2 E){vec3 L;L.xy=E;L.z=interleavedGradientNoise(gl_FragCoord.xy,currentFrameCount*5.);L=L*2.-1.;return L;}vec2 GetRandomE(float seed){vec2 rand_e;rand_e.x=random3(vec3(gl_FragCoord.xy,currentFrameCount+seed));rand_e.y=random3(vec3(gl_FragCoord.yx,rand_e.x+(currentFrameCount)*7.));return rand_e;}float saturate2(float v,float mx){return max(0.,min(mx,v));}vec4 calculateGI(in float seed,in vec3 screenPos,in vec3 normal,in float radiusFactor){vec3 viewPos=screenToView3(screenPos.xy,screenPos.z);normal=normalize(normal);vec2 E=GetRandomE(seed);vec3 L=ComputeUniformL(normal,E);L=normalize(L);L*=sign(dot(L,normal));float cameraDist=length(cameraPositionWorld);float rayLen=objectRadius*sceneBoundingRadius;rayLen=autoRadius ?min(max(mix(max(0.0,(cameraDist+rayLen)+viewPos.z),max(0.0,-viewPos.z-max(0.0,cameraDist-rayLen)),L.z*0.5+0.5),rayLen*0.1),rayLen*5.):rayLen;rayLen*=radiusFactor;float r=interleavedGradientNoise(gl_FragCoord.xy,currentFrameCount*14.+seed)+0.05;rayLen=max(rayLen,0.001);vec3 state=vec3(1.,(r+0.5)/float(RTAO_STEP_COUNT),2.);viewPos+=normal*max(-0.01*viewPos.z,0.001);vec3 screenHitP=traceRay(viewPos,L*rayLen,tolerance*rayLen,state,RTAO_STEP_COUNT);vec3 viewHitP=screenToView3(screenHitP.xy,screenHitP.z);vec3 LRes=viewHitP-viewPos;if(state.z>1.)LRes=vec3(9999999.);float dist=length(LRes)*falloff;float EPS=0.01;float zBias=(viewPos.z)*bias;float ao=(max(dot(normal,L)+zBias,0.))/(dist*dist+EPS);\n#if defined(SSGI_ENABLED) && SSGI_ENABLED > 0\nif(currentFrameCount<1.){\n#if HAS_VELOCITY_BUFFER == 0\nvec3 worldPosition=getWorldPositionFromViewZ(screenHitP.xy,screenHitP.z);vec2 screenSpaceVelocity=computeScreenSpaceVelocity(worldPosition);\n#else\nvec2 screenSpaceVelocity=getVelocity(screenHitP.xy);\n#endif\nscreenHitP.xy-=screenSpaceVelocity;}vec3 hitColor=tLastFrameTexelToLinear(texture2D(tLastFrame,screenHitP.xy)).rgb;vec3 hitNormal=getViewNormal(screenHitP.xy);float giWeight=1.;giWeight=saturate2(giWeight/(dist+EPS),1.);giWeight*=saturate2((dot(normal,L)),1.0);giWeight*=saturate2((dot(hitNormal,-L)),1.0);return vec4(hitColor*giWeight,ao);\n#endif\nreturn vec4(0,0,0,ao);}float normpdf(in float x,in float sigma){return exp(-0.5*x*x/(sigma*sigma));}vec4 getLastThis(sampler2D tex,float depth,vec3 normal){vec2 direction=vec2(1,1);vec4 color=clamp(tLastThisTexelToLinear(texture2D(tex,vUv.xy)),0.,5.);return color;}void main(){float depth;vec3 normal;getDepthNormal(vUv,depth,normal);if(depth>0.99){discard;gl_FragColor=getLastThis(tLastThis,depth,normal);return;}float viewZ=depthToViewZ(depth);vec3 screenPos=vec3(vUv.x,vUv.y,viewZ);vec4 gi=vec4(0.);gi+=calculateGI(8.,screenPos,normal,1.);if(rayCount>1.5)gi=max(gi,calculateGI(2.,screenPos,normal,0.4));if(rayCount>2.5)gi=max(gi,calculateGI(3.,screenPos,normal,1.5));if(rayCount>3.5)gi=max(gi,calculateGI(1.,screenPos,normal,0.6));if(rayCount>4.5)gi=max(gi,calculateGI(3.,screenPos,normal,1.));gi.a=min(1.,gi.a);gi.a=max(0.,gi.a);gi.rgb=min(vec3(3.),gi.rgb);gi.rgb=max(vec3(0.),gi.rgb);if(currentFrameCount<3.){gl_FragColor=gi;return;}gl_FragColor=(texture2D(tLastThis,vUv));gl_FragColor=((gi+(gl_FragColor)*currentFrameCount)/(currentFrameCount+1.));}",__inited:!1};function Ee(){return Me.__inited||(Me.__inited=!0,Object.assign(r.ShaderChunk,Me)),Me}var Ce=Object.defineProperty,Re=Object.getOwnPropertyDescriptor,Ae=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?Re(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&Ce(t,r,s),s};const Ue=class extends i{constructor(e=!0){super(),this.passId="taa",this._stableNoise=!0,this._gbufferUnpackExtension=void 0,this._gbufferUnpackExtensionChanged=()=>{if(!this._pass||!this._viewer)throw new Error("TemporalAAPlugin: pass/viewer not created yet");const e=this._viewer.renderManager.gbufferUnpackExtension;this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this._pass.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension?this._pass.material.registerMaterialExtensions([this._gbufferUnpackExtension]):this._viewer.console.warn("TemporalAAPlugin: GBuffer unpack extension removed"))},this.dependencies=[a,s],this.uiConfig={type:"folder",label:"TemporalAA Plugin",onChange:this.setDirty.bind(this),children:[...n(this)||[]]},this.enabled=e,this.setDirty=this.setDirty.bind(this)}get stableNoise(){return this._viewer?.renderManager.stableNoise??this._stableNoise}set stableNoise(e){this._viewer&&(this._viewer.renderManager.stableNoise=e),this._stableNoise=e}_createPass(){if(!this._viewer)throw new Error("TemporalAAPlugin: viewer not set");if(!this._viewer.renderManager.gbufferTarget||!this._viewer.renderManager.gbufferUnpackExtension)throw new Error("TemporalAAPlugin: GBuffer target not created. GBufferPlugin is required.");const e=!!this._viewer.renderManager.msaa;return new Oe(this.passId,()=>this._viewer?.getPlugin(s)?.target,e)}onAdded(e){super.onAdded(e),this._gbufferUnpackExtensionChanged(),e.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),e.renderManager.addEventListener("resize",this._pass.onSizeUpdate)}onRemove(e){e.renderManager.removeEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),e.renderManager.removeEventListener("resize",this._pass.onSizeUpdate),super.onRemove(e)}_beforeRender(e,t,r){if(!super._beforeRender(e,t,r))return!1;const i=this.pass,a=this._viewer;if(!i||!a)return!1;const n=r.frameCount;if(i.taaEnabled=n<=1&&e.renderCamera===e.mainCamera,!i.taaEnabled)return!1;const o=t;return!!o&&(o.updateMatrixWorld(!0),o.updateShaderProperties(i.material),i.updateCameraProperties(o),i.target=a.getPlugin(s).target,!0)}};Ue.PluginType="TAA",Ue.OldPluginType="TemporalAAPlugin";let Le=Ue;Ae([o("Stable Noise (Total frame count)")],Le.prototype,"stableNoise",1),Ae([l(void 0,{unwrapContents:!0})],Le.prototype,"_pass",2);class Oe extends c{constructor(e,t,r=!1){super({vertexShader:h.vertexShader,fragmentShader:Ee().temporalAA,uniforms:{currentRT:{value:null},previousRT:{value:null},previousRTSize:{value:new d},cameraNearFar:{value:new d},lastProjectionViewMatrix:{value:new u},currentProjectionViewMatrix:{value:new u},projection:{value:new u},inverseViewMatrix:{value:new u},jitterSample:{value:new d},firstFrame:{value:!0}},defines:{QUALITY:1,UNJITTER:0,BACKGROUND_TAA:r?1:0}},"currentRT","previousRT"),this.before=["progressive"],this.after=[],this.required=["render","progressive"],this.taaEnabled=!0,this.feedBack=new d(.88,.97),this.debugVelocity=!1,this.uiConfig={type:"folder",label:"Temporal AA Pass",onChange:this.setDirty,children:[{type:"checkbox",label:"Enabled",property:[this,"enabled"],onChange:()=>this.onSizeUpdate()},...n(this)?.filter(e=>e&&"Enabled"!==e.label)||[]]},this.passId=e,this.onSizeUpdate=this.onSizeUpdate.bind(this),this.target=t,this.clear=!1,this.needsSwap=!0}render(e,t,r,i,a){this.taaEnabled&&this.enabled?(this.needsSwap=!0,this.uniforms.previousRT.value=p(this.target)?.texture??null,super.render(e,t,r,i,a),this.uniforms.lastProjectionViewMatrix.value.copy(this.uniforms.currentProjectionViewMatrix.value),this.uniforms.firstFrame.value=!1):this.needsSwap=!1}updateCameraProperties(e){e&&(this.uniforms.currentProjectionViewMatrix.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this.uniforms.inverseViewMatrix.value.copy(e.matrixWorld))}onSizeUpdate(){this.uniforms.firstFrame.value=!0,this.setDirty()}setSize(e,t){super.setSize(e,t),this.onSizeUpdate()}}Ae([f(),m(),g("Feedback",void 0,1e-4)],Oe.prototype,"feedBack",2),Ae([o(),v("DEBUG_VELOCITY",void 0,!1,void 0,!0)],Oe.prototype,"debugVelocity",2);var Be=Object.defineProperty,Ne=Object.getOwnPropertyDescriptor,Fe=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?Ne(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&Be(t,r,s),s};let ke=class extends i{constructor(e=_,t=!0,r=!0){super(),this.passId="velocityBuffer",this.material=new Ie,this.unpackExtension={shaderExtender:e=>{this.isDisabled()||(e.fragmentShader=y(e.fragmentShader,"#pragma <velocity_unpack>","\n#if defined(HAS_VELOCITY_BUFFER)\nuniform sampler2D tVelocity;vec2 getVelocity(const in vec2 uv){vec2 screenSpaceVelocity=texture2D(tVelocity,uv).xy*2.0-1.0;return sign(screenSpaceVelocity)*pow(abs(screenSpaceVelocity),vec2(4.));}\n#endif\n\n"))},computeCacheKey:()=>this.isDisabled()?"":"vb",extraUniforms:{tVelocity:()=>({value:this.isDisabled()?null:this.target?.texture})},extraDefines:{HAS_VELOCITY_BUFFER:()=>!this.isDisabled()&&this.target?.texture?1:void 0},priority:100,isCompatible:()=>!0},this.enabled=t,this.bufferType=e,this._attachToTaa=r}_createTarget(e=!0){this._viewer&&(e&&this._disposeTarget(),this.target||(this.target=this._viewer.renderManager.createTarget({depthBuffer:!0,samples:0,type:this.bufferType,generateMipmaps:!1,colorSpace:x})),this.texture=this.target.texture,this.texture.name="velocityBuffer",this._pass&&(this._pass.target=this.target))}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0)}_createPass(){if(this._createTarget(!0),!this.target)throw new Error("VelocityBufferPlugin: target not created");this.material.userData.isGBufferMaterial=!0;const e=this._viewer,t=new class extends S{constructor(){super(...arguments),this._firstCall=!0}render(t,r,i,a,s){if(e.renderManager.frameCount>0)return;if(!this.enabled||!this.camera)return;const n=this.overrideMaterial;n.uniforms.currentProjectionViewMatrix.value.copy(this.camera.projectionMatrix).multiply(this.camera.matrixWorldInverse),this._firstCall&&(n.uniforms.lastProjectionViewMatrix.value.copy(n.uniforms.currentProjectionViewMatrix.value),this._firstCall=!1),super.render(t,r,i,a,s),n.uniforms.lastProjectionViewMatrix.value.copy(n.uniforms.currentProjectionViewMatrix.value)}}(this.passId,this.target,this.material,new b(.5,.5,.5),1),r=t.preprocessMaterial;return t.preprocessMaterial=e=>r(e,e.userData[ke.PluginType]?.disabled),t.before=["render"],t.after=[],t.required=["render"],t}onAdded(e){super.onAdded(e),e.forPlugin(Le,e=>{this._attachToTaa&&e.pass?.material.registerMaterialExtensions([this.unpackExtension])},e=>{e.pass?.material?.unregisterMaterialExtensions([this.unpackExtension])},this)}onRemove(e){return this._disposeTarget(),super.onRemove(e)}setDirty(){super.setDirty(),this.unpackExtension.setDirty?.()}_beforeRender(e,t,r){if(!super._beforeRender(e,t,r))return!1;const i=this.pass;return!!i&&(!(r.frameCount>0)&&(i.scene=e,i.camera=t,t.updateShaderProperties(i.overrideMaterial),!0))}};ke.PluginType="VelocityBuffer",ke.OldPluginType="VelocityBufferPlugin",Fe([M("Velocity Buffer",{readOnly:!0})],ke.prototype,"texture",2),ke=Fe([E("Velocity Buffer Plugin (for TAA)")],ke);class Ie extends w{constructor(){super({vertexShader:"#ifdef USE_ALPHAMAP\n#define USE_UV\n#endif\n#include <uv_pars_vertex>\n#include <batching_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec3 vWorldPosition;varying vec3 vWorldPositionPrevious;uniform mat4 modelMatrixPrevious;void main(){\n#include <uv_vertex>\n#include <batching_vertex>\n#include <skinbase_vertex>\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <skinning_vertex>\n#include <displacementmap_vertex>\nvec4 mvPosition=vec4(transformed,1.0);\n#ifdef USE_INSTANCING\nmvPosition=instanceMatrix*mvPosition;\n#endif\nvWorldPosition=(modelMatrix*mvPosition).xyz;vWorldPositionPrevious=(modelMatrixPrevious*mvPosition).xyz;mvPosition=modelViewMatrix*mvPosition;gl_Position=projectionMatrix*mvPosition;\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\n}",fragmentShader:"varying vec3 vWorldPosition;varying vec3 vWorldPositionPrevious;uniform mat4 currentProjectionViewMatrix;uniform mat4 lastProjectionViewMatrix;vec2 computeScreenSpaceVelocity2(){vec4 currentPositionClip=currentProjectionViewMatrix*vec4(vWorldPosition,1.0);vec4 prevPositionClip=lastProjectionViewMatrix*vec4(vWorldPositionPrevious,1.0);vec2 currentPositionNDC=currentPositionClip.xy/currentPositionClip.w;vec2 prevPositionNDC=prevPositionClip.xy/prevPositionClip.w;if(prevPositionNDC.x>=1.0||prevPositionNDC.x<=-1.0||prevPositionNDC.x>=1.0||prevPositionNDC.y<=-1.0){return vec2(0.0);}return 0.5*(currentPositionNDC-prevPositionNDC);}void main(){vec2 velocity=clamp(computeScreenSpaceVelocity2(),-1.0,1.0);velocity=sign(velocity)*pow(abs(velocity),vec2(1./4.));velocity=velocity*0.5+0.5;gl_FragColor=vec4(velocity.x,velocity.y,1.,1.);}",uniforms:{cameraNearFar:{value:new d(.1,1e3)},alphaMap:{value:null},alphaTest:{value:null},alphaMapTransform:{value:/* @__PURE__ */new D},currentProjectionViewMatrix:{value:new u},lastProjectionViewMatrix:{value:new u}},blending:T}),this.extraUniformsToUpload={modelMatrixPrevious:{value:(new u).identity()}},this._previousWorldMatrices={}}onBeforeRender(e,t,r,i,a,s){super.onBeforeRender(e,t,r,i,a,s);const n=this._previousWorldMatrices[a.uuid];this.extraUniformsToUpload.modelMatrixPrevious.value.copy(n??a.matrixWorld),n?n.copy(a.matrixWorld):this._previousWorldMatrices[a.uuid]=a.matrixWorld.clone();let o=a.material;Array.isArray(o)&&(o=o[0]),this.uniforms.alphaMap.value=o?.alphaMap??null,this.uniforms.alphaTest.value=!o||!o.alphaTest||o.alphaTest<1e-7?.001:o.alphaTest;let l=this.uniforms.alphaMap.value?1:void 0;l!==this.defines.USE_ALPHAMAP&&(void 0===l?delete this.defines.USE_ALPHAMAP:this.defines.USE_ALPHAMAP=l,this.needsUpdate=!0),l=o?.userData.ALPHA_I_RGBA_PACKING?1:void 0,l!==this.defines.ALPHA_I_RGBA_PACKING&&(void 0===l?delete this.defines.ALPHA_I_RGBA_PACKING:this.defines.ALPHA_I_RGBA_PACKING=l,this.needsUpdate=!0),this.side=o?.side??P}}var ze=Object.defineProperty,Ve=Object.getOwnPropertyDescriptor,je=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?Ve(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&ze(t,r,s),s};const Ge=(e=class extends i{constructor(t=!0){super(),this.passId="bloom",this.materialExtension=C(this._getUiConfig.bind(this),e.PluginType),this.dependencies=[a],this._onPluginAdd=e=>{if(e.plugin?.constructor?.PluginType!==a.PluginType)return;const t=e.plugin;t.registerGBufferUpdater(this.constructor.PluginType,this.updateGBufferFlags.bind(this)),this._pass?.material.registerMaterialExtensions([t.unpackExtension]),this._viewer?.removeEventListener("addPlugin",this._onPluginAdd)},this.uiConfig={type:"folder",label:"Bloom Plugin",onChange:this.setDirty.bind(this),children:[...n(this)||[]]},this.enabled=t}_createPass(){return new We(this.passId,Math.min(8,this._viewer?.renderManager.maxHDRIntensity||8))}onAdded(e){super.onAdded(e);const t=e.getPlugin(a);t?(t.registerGBufferUpdater(this.constructor.PluginType,this.updateGBufferFlags.bind(this)),this._pass.material.registerMaterialExtensions([t.unpackExtension])):e.addEventListener("addPlugin",this._onPluginAdd),e.materialManager.registerMaterialExtension(this.materialExtension)}onRemove(e){e.removeEventListener("addPlugin",this._onPluginAdd);const t=e.getPlugin(a);t?.unregisterGBufferUpdater(this.constructor.PluginType),t&&this._pass?.material.unregisterMaterialExtensions([t.unpackExtension]),e.materialManager.unregisterMaterialExtension(this.materialExtension),super.onRemove(e)}updateGBufferFlags(t,r){if(!r.material||!r.material.userData)return;const i=!1===r.material.userData[e.PluginType]?.enable||r.material.userData.pluginsDisabled?0:1;t.w=R(t.w,2,i)}static AddBloomData(t,r,i=!0){const a=t?.userData;if(!a)return null;a[e.PluginType]||(a[e.PluginType]={});const s=a[e.PluginType];return s.enable=!0,r&&Object.assign(s,r),i&&t.setDirty&&t.setDirty(),s}_getUiConfig(t){const r={type:"folder",label:"Bloom",children:[{type:"checkbox",label:"Enabled",get value(){return t.userData[e.PluginType]?.enable??!0},set value(i){let a=t.userData[e.PluginType];i!==a?.enable&&(a||(a=e.AddBloomData(t,void 0,!1)),a.enable=i,t.setDirty(),r.uiRefresh?.(!0,"postFrame"))},onChange:this.setDirty}]};return r}},e.PluginType="Bloom",e.OldPluginType="BloomPlugin",e);je([l(void 0,{unwrapContents:!0})],Ge.prototype,"_pass",2);let He=Ge,We=class extends c{constructor(e,t=16){super({vertexShader:h.vertexShader,defines:{PASS_STEP:1,MAX_INTENSITY:Math.min(t,16)},uniforms:{tSource:{value:null},tDiffuse:{value:null},opacity:{value:1},tDiffuseSize:{value:new d},weight:{value:1}},fragmentShader:"#include <packing>\nuniform float intensity;uniform float opacity;uniform vec2 tDiffuseSize;varying vec2 vUv;uniform float weight;\n#if PASS_STEP == 0\nuniform vec4 prefilter;vec4 Prefilter(vec4 c){\n#ifdef HAS_GBUFFER\n#if !BACKGROUND_BLOOM\nif(getDepth(vUv)>0.999){return vec4(0.0);}\n#endif\n#endif\nfloat brightness=max(c.r,max(c.g,c.b));float soft=brightness+prefilter.x*(prefilter.y-1.);soft=clamp(soft,0.,prefilter.z);soft=soft*soft*prefilter.w;float contribution=max(soft,brightness-prefilter.x);contribution/=max(brightness,0.001);return vec4(c.rgb*contribution,c.a);}\n#endif\nvec4 Sample(vec2 uv){return min(vec4(MAX_INTENSITY,MAX_INTENSITY,MAX_INTENSITY,1.),tDiffuseTexelToLinear(texture2D(tDiffuse,uv)));}vec4 SampleBox(vec2 uv,float delta){vec4 o=vec2(-delta,delta).xxyy/tDiffuseSize.xyxy;vec4 s=Sample(uv+o.xy)+Sample(uv+o.zy)+Sample(uv+o.xw)+Sample(uv+o.zw);return s*0.25;}int getBloomBit(in int number){\n#ifdef WebGL2Context\nreturn(number/4)% 2;\n#else\nreturn int(mod(floor(float(number)/4.),2.));\n#endif\n}void main(){\n#if PASS_STEP == 0\n#ifdef GBUFFER_HAS_FLAGS\nint doBloom=getBloomBit(getGBufferFlags(vUv).a);\n#else\nint doBloom=1;\n#endif\ngl_FragColor=float(doBloom)*weight*Prefilter(SampleBox(vUv,1.));gl_FragColor.a=1.;\n#elif PASS_STEP == 1\ngl_FragColor=weight*(SampleBox(vUv,1.));gl_FragColor.a=1.;\n#elif PASS_STEP == 2\ngl_FragColor=(SampleBox(vUv,0.5));gl_FragColor.a=1.;\n#elif PASS_STEP == 3\nvec4 texel=tSourceTexelToLinear(texture2D(tSource,vUv));vec4 bloom=intensity*SampleBox(vUv,0.5).rgba;float brightness=max(bloom.r,max(bloom.g,bloom.b));texel.rgb+=bloom.rgb;texel.a=min(1.,texel.a+brightness);gl_FragColor=texel;\n#elif PASS_STEP == 4\nvec4 texel=vec4(0.);texel.rgb+=intensity*SampleBox(vUv,0.5).rgb;texel.a=1.;gl_FragColor=texel;\n#endif\n#include <colorspace_fragment>\n}"},"tDiffuse","tSource"),this.uiConfig=void 0,this.before=["screen"],this.after=["render","progressive"],this.required=["render"],this.prefilter=new A(2,.5,0,0),this.threshold=2,this.softThreshold=.5,this.intensity=.2,this.backgroundBloom=!1,this.bloomIterations=4,this._currentIterations=0,this.radius=.6,this.power=1,this.bloomDebug=!1,this._weights=[],this.passId=e,this._updateWeights=this._updateWeights.bind(this),this._thresholdsUpdated=this._thresholdsUpdated.bind(this),this._updateWeights(),this._thresholdsUpdated(),this.clear=!0}_thresholdsUpdated(){this.prefilter.x=this.threshold,this.prefilter.y=this.softThreshold,this.prefilter.z=2*this.prefilter.x*this.prefilter.y,this.prefilter.w=this.uniforms?.prefilter?.125/(this.uniforms.prefilter.value.z+1e-5):0}render(e,t,r,i,a){const s=e.renderManager;this.material.defines.PASS_STEP=0,this.clear=!0,this.needsSwap=!1;const n=r;if(!n)return void console.warn("BloomPluginPass: No source to read from");this.needsSwap=!0;let o=.5,l=n.width*o,c=n.height*o;const d=[];let u=s.getTempTarget({sizeMultiplier:1,type:U});d.push(u);let h=n;this.material.needsUpdate=!0,this.material.uniforms.weight.value=this._weights[0],super.render(e,u,h,i,a),h=u;const p=this._currentIterations;let f=1;const m=Math.max(2,this.bloomIterations);for(;f<m&&(l/=2,c/=2,o/=2,!(c<2||l<2));f++){u=s.getTempTarget({sizeMultiplier:o,type:U}),d.push(u),this.material.defines.PASS_STEP=1;let t=this._weights[f];t=0!==this._weights[f-1]?this._weights[f]/this._weights[f-1]:this._weights[f],this.material.uniforms.weight.value=t,this.material.needsUpdate=!0,super.render(e,u,h,i,a),h=u,this._currentIterations=f+1}p!==this._currentIterations&&this._updateWeights(!1),this.clear=!1;const g=e.autoClear;for(e.autoClear=!1,f-=2;f>=0;f--)u=d[f],d[f]=void 0,this.material.defines.PASS_STEP=2,this.material.transparent=!0,this.material.blending=L,this.material.needsUpdate=!0,e.autoClear=!1,super.render(e,u,h,i,a),this.material.blending=T,s.releaseTempTarget(h),h=u;this.clear=!0,e.autoClear=g,e.autoClear=!0,this.bloomDebug?(this.material.defines.PASS_STEP=4,this.material.needsUpdate=!0,super.render(e,t,h,i,a)):(this.uniforms.tSource.value=n.texture,this.material.defines.PASS_STEP=3,this.material.needsUpdate=!0,super.render(e,t,h,i,a),this.uniforms.tSource.value=null),s.releaseTempTarget(h)}_updateWeights(e=!0){if(!this._weights)return;const t=Math.max(Math.min(this.radius,1),0),r=Math.max(2,this._currentIterations||this.bloomIterations),i=1/(r-1);for(let a=0;a<r;a++){let e=a*i+.1,r=1.2-e;e=Math.pow(e,this.power),r=Math.pow(r,this.power),this._weights[a]=r*(1-t)+e*t}!1!==e&&this.setDirty()}};je([m()],We.prototype,"prefilter",2),je([O("Threshold",[0,2]),B(We.prototype._thresholdsUpdated),f()],We.prototype,"threshold",2),je([O("Soft Threshold",[0,1]),B(We.prototype._thresholdsUpdated),f()],We.prototype,"softThreshold",2),je([O("Intensity",[0,3]),f(),m()],We.prototype,"intensity",2),je([o("Background Bloom"),f(),v("BACKGROUND_BLOOM")],We.prototype,"backgroundBloom",2),je([O("Iterations",[2,7],1),N(We.prototype._updateWeights),f()],We.prototype,"bloomIterations",2),je([O("Radius",[0,1],.01),N(We.prototype._updateWeights),f()],We.prototype,"radius",2),je([O("Power",[.2,10],.01),N(We.prototype._updateWeights),f()],We.prototype,"power",2),je([o("Debug")],We.prototype,"bloomDebug",2),We=je([E("Bloom Pass")],We);var Ye=Object.defineProperty,Xe=Object.getOwnPropertyDescriptor,Ke=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?Xe(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&Ye(t,r,s),s};const qe=class extends i{constructor(e=!0,t=!1){super(),this.passId="depthOfField",this.enableEdit=!1,this._focalPointHit=new F(0,0,0),this.crossFadeTime=200,this._focalPointHitTime=0,this.dependencies=[a],this._onPluginAdd=e=>{const t=e.plugin;if(t){if(t.constructor?.PluginType===a.PluginType){const e=t;this._pass?.material.registerMaterialExtensions([e.unpackExtension]),this._pass?.computeCocMaterial.registerMaterialExtensions([e.unpackExtension]),this._pass?.expandCocMaterial.registerMaterialExtensions([e.unpackExtension])}if(t.constructor?.PluginType===k.PluginType){t.addEventListener("hitObject",this._onObjectHit)}}},this._onPluginRemove=e=>{const t=e.plugin;if(t){if(t.constructor?.PluginType===a.PluginType){const t=e.plugin;this._pass?.material.unregisterMaterialExtensions([t.unpackExtension]),this._pass?.computeCocMaterial.unregisterMaterialExtensions([t.unpackExtension]),this._pass?.expandCocMaterial.unregisterMaterialExtensions([t.unpackExtension])}if(t.constructor?.PluginType===k.PluginType){e.plugin.removeEventListener("hitObject",this._onObjectHit)}}},this.uiConfig={type:"folder",label:"DepthOfField",onChange:this.setDirty.bind(this),children:[...n(this)||[],()=>this._pass?.uiConfig]},this._tempVec=new F,this.enabled=e,this.enableEdit=t,this._onObjectHit=this._onObjectHit.bind(this),this.setDirty=this.setDirty.bind(this)}get _frameFadeTime(){return 2.5*this.crossFadeTime}setFocalPoint(e,t=!0,r=!1){this._focalPointHit.copy(e),t&&this._viewer?.getPlugin("FrameFadePlugin")?.startTransition(this._frameFadeTime),r&&(this._focalPointHitTime=I()),this.setDirty()}getFocalPoint(){return this._focalPointHit}_onObjectHit(e){this._pass&&e.intersects.intersect&&!this.isDisabled()&&this.enableEdit&&(this._focalPointHit.copy(e.intersects.intersect.point),this._focalPointHitTime=e.time,e.intersects.selectedObject=null,this._viewer?.getPlugin(z)?.startTransition(this._frameFadeTime),this.setDirty())}_createPass(){return new $e(this.passId)}onAdded(e){super.onAdded(e),e.addEventListener("addPlugin",this._onPluginAdd),e.addEventListener("removePlugin",this._onPluginRemove),this._onPluginAdd({plugin:e.getPlugin(a)}),this._onPluginAdd({plugin:e.getPlugin(k)})}onRemove(e){e.removeEventListener("addPlugin",this._onPluginAdd),e.removeEventListener("removePlugin",this._onPluginRemove),this._onPluginRemove({plugin:e.getPlugin(a)}),this._onPluginRemove({plugin:e.getPlugin(k)}),super.onRemove(e)}_beforeRender(e,t,r){if(!super._beforeRender(e,t,r))return!1;const i=this.pass;if(!i)return!1;i.dofBlurMaterial.uniforms.frameCount&&r?.updateShaderProperties(i.dofBlurMaterial);const a=t;if(!a)return!1;a.updateMatrixWorld(!0),a.updateShaderProperties(i.material),a.getWorldPosition(this._tempVec),this._tempVec.subVectors(this._focalPointHit,this._tempVec),i.focalDepthRange.x=this._tempVec.length(),i.focalDepthRange.x*=a.getWorldDirection(new F).dot(this._tempVec.normalize());let s=(I()-this._focalPointHitTime)/this.crossFadeTime;if(s=1-Math.min(1,Math.max(0,s)),Math.abs(s-i.crossAlpha)>.01&&(i.crossAlpha=s,this.setDirty()),s>0){const e=this._tempVec.copy(this._focalPointHit).project(a).addScalar(1).divideScalar(2);i.crossCenter.set(e.x,e.y),i.computeCocMaterial.uniformsNeedUpdate=!0,i.expandCocMaterial.uniformsNeedUpdate=!0}return!0}};qe.PluginType="DepthOfField",qe.OldPluginType="DepthOfFieldPlugin";let Ze=qe;Ke([f(),o()],Ze.prototype,"enableEdit",2),Ke([f("focalPoint")],Ze.prototype,"_focalPointHit",2),Ke([f()],Ze.prototype,"crossFadeTime",2);const Je=new j({uniforms:{colorTexture:{value:null},colorTextureSize:{value:new d},direction:{value:new d},frameCount:{value:0},blurRadius:{value:16}},vertexShader:V.defaultVertex,fragmentShader:"vec2 poisson_disk_samples[16];void setPds(){poisson_disk_samples[0]=vec2(-0.399691779231,0.728591545584);poisson_disk_samples[1]=vec2(-0.48622557676,-0.84016533712);poisson_disk_samples[2]=vec2(0.770309468987,-0.24906070432);poisson_disk_samples[3]=vec2(0.556596796154,0.820359876432);poisson_disk_samples[4]=vec2(-0.933902004071,0.0600539051593);poisson_disk_samples[5]=vec2(0.330144964342,0.207477293384);poisson_disk_samples[6]=vec2(0.289013230975,-0.686749271417);poisson_disk_samples[7]=vec2(-0.0832470893559,-0.187351643125);poisson_disk_samples[8]=vec2(-0.296314525615,0.254474834305);poisson_disk_samples[9]=vec2(-0.850977666059,0.484642744689);poisson_disk_samples[10]=vec2(0.829287915319,0.2345063545);poisson_disk_samples[11]=vec2(-0.773042143899,-0.543741521254);poisson_disk_samples[12]=vec2(0.0561133030864,0.928419742597);poisson_disk_samples[13]=vec2(-0.205799249508,-0.562072714492);poisson_disk_samples[14]=vec2(-0.526991665882,-0.193690188118);poisson_disk_samples[15]=vec2(-0.051789270667,-0.935374050821);}\n#include <randomHelpers>\n#include <common>\nvarying vec2 vUv;uniform vec2 colorTextureSize;uniform float blurRadius;\n#ifndef D_frameCount\n#define D_frameCount\nuniform float frameCount;\n#endif\nvec4 CircularBlur(){vec4 color=colorTextureTexelToLinear(texture2D(colorTexture,vUv));\n#ifdef DOF_MODE\nfloat blurDist=blurRadius*(2.*color.a-1.);\n#else\nfloat blurDist=blurRadius*color.a;\n#endif\nfloat rnd=PI2*random3(vec3(vUv,frameCount*0.1));float costheta=cos(rnd);float sintheta=sin(rnd);vec4 rotationMatrix=vec4(costheta,-sintheta,sintheta,costheta);vec3 colorSum=vec3(0.0);float weightSum=0.001;vec2 ofs;vec4 sampleColor;setPds();\n#pragma unroll_loop_start\nfor(int i=0;i<16;i++){ofs=poisson_disk_samples[UNROLLED_LOOP_INDEX];ofs=vec2(dot(ofs,rotationMatrix.xy),dot(ofs,rotationMatrix.zw));sampleColor=colorTextureTexelToLinear(texture2D(colorTexture,vUv+blurDist*ofs/colorTextureSize.xy));\n#ifdef DOF_MODE\nsampleColor.a=abs(sampleColor.a*2.0-1.0);sampleColor.a*=sampleColor.a*sampleColor.a;\n#endif\ncolorSum+=sampleColor.rgb*sampleColor.a;weightSum+=sampleColor.a;}\n#pragma unroll_loop_end\ncolorSum/=weightSum;return vec4(min(vec3(72.),max(vec3(0.),colorSum)),1.0);}void main(){gl_FragColor=CircularBlur();\n#include <colorspace_fragment>\n}",defines:{DOF_MODE:1}},["colorTexture"]);let $e=class extends c{constructor(e){super({uniforms:{colorTexture:{value:null},blurTexture:{value:null},cocTexture:{value:null},cocTextureSize:{value:new d},cameraNearFar:{value:new d}},vertexShader:V.defaultVertex,fragmentShader:"#include <common>\n#include <packing>\nvarying vec2 vUv;uniform vec2 cocTextureSize;uniform vec2 nearFarBlurScale;uniform vec2 cameraNearFar;uniform vec2 focalDepthRange;uniform vec2 crossCenter;uniform float crossRadius;uniform float crossAlpha;uniform vec3 crossColor;float smoothBoundary(float d,float smooothFactor){smooothFactor*=0.5;float value=smoothstep(-smooothFactor,smooothFactor,d);return value;}float circle(vec2 p,float r){return min((length(p)-r),-(length(p)-r-0.01));}float computeCoc(){float depth=getDepth(vUv);if(depth>1.0-0.01)return max(nearFarBlurScale.x,nearFarBlurScale.y);depth=mix(cameraNearFar.x,cameraNearFar.y,depth);float coc=(depth-focalDepthRange.x)/focalDepthRange.y;coc=clamp(coc,-1.,1.);return(coc>0.0 ? coc*nearFarBlurScale.y : coc*nearFarBlurScale.x);}void main(){vec4 blur=blurTextureTexelToLinear(texture2D(blurTexture,vUv));float scale=0.5;blur+=blurTextureTexelToLinear(texture2D(blurTexture,vUv+scale*vec2(1.0,1.0)/cocTextureSize));blur+=blurTextureTexelToLinear(texture2D(blurTexture,vUv+scale*vec2(-1.0,1.0)/cocTextureSize));blur+=blurTextureTexelToLinear(texture2D(blurTexture,vUv+scale*vec2(-1.0,-1.0)/cocTextureSize));blur+=blurTextureTexelToLinear(texture2D(blurTexture,vUv+scale*vec2(1.0,-1.0)/cocTextureSize));blur/=5.0;vec2 uvNearest=(floor(vUv*cocTextureSize)+0.5)/cocTextureSize;float coc=abs(min(2.*cocTextureTexelToLinear(texture2D(cocTexture,uvNearest)).a-1.,computeCoc()));float cocLower=0.005;float cocHigher=0.3;vec4 outColor=vec4(mix(colorTextureTexelToLinear(texture2D(colorTexture,vUv)).rgb,blur.rgb,smoothstep(cocLower,cocHigher,coc)),1.0);vec2 d=vUv-crossCenter;if(length(d)>crossRadius+0.05){float dist=circle(d,crossRadius);gl_FragColor=outColor;}else{d.x*=cocTextureSize.x/cocTextureSize.y;float dist=circle(d,crossRadius);dist=smoothBoundary(dist,2.*fwidth(dist));vec4 color=outColor;vec3 dofCircleColor=mix(crossColor,color.rgb,1.-crossAlpha);gl_FragColor=vec4(mix(color.rgb,dofCircleColor,dist),color.a);}\n#include <colorspace_fragment>\n}"},"colorTexture","cocTexture","blurTexture"),this.uiConfig=void 0,this.before=["progressive","screen"],this.after=["render"],this.required=["render"],this.dofBlurMaterial=Je,this.nearFarBlurScale=new d(.25,.25),this.focalDepthRange=new d(.5,1.5),this.crossCenter=new d(.5,.5),this.crossRadius=.04,this.crossAlpha=1,this.crossColor=new b(16750848),this.passId=e,this.computeCocMaterial=new j({uniforms:{colorTexture:{value:null},cameraNearFar:this.uniforms.cameraNearFar,nearFarBlurScale:this.uniforms.nearFarBlurScale,focalDepthRange:this.uniforms.focalDepthRange},vertexShader:V.defaultVertex,fragmentShader:"#include <common>\n#include <packing>\nvarying vec2 vUv;uniform vec2 nearFarBlurScale;uniform vec2 cameraNearFar;uniform vec2 focalDepthRange;float computeCoc(){float depth=getDepth(vUv);if(depth==1.0)return max(nearFarBlurScale.x,nearFarBlurScale.y);depth=mix(cameraNearFar.x,cameraNearFar.y,depth);float coc=(depth-focalDepthRange.x)/focalDepthRange.y;coc=clamp(coc,-1.,1.);return(coc>0.0 ? coc*nearFarBlurScale.y : coc*nearFarBlurScale.x);}void main(){gl_FragColor=vec4(colorTextureTexelToLinear(texture2D(colorTexture,vUv)).rgb,0.5*computeCoc()+0.5);\n#include <colorspace_fragment>\n}"},["colorTexture"]),this.expandCocMaterial=new j({uniforms:{colorTexture:{value:null},colorTextureSize:{value:new d},direction:{value:new d},nearFarBlurScale:this.uniforms.nearFarBlurScale},vertexShader:V.defaultVertex,fragmentShader:"#include <common>\n#include <gbuffer_unpack>\nvarying vec2 vUv;uniform vec2 colorTextureSize;uniform vec2 direction;uniform vec2 nearFarBlurScale;const float MAXIMUM_BLUR_SIZE=4.0;float expandNear(const in vec2 offset,const in bool isBackground){float coc=0.0;vec2 sampleOffsets=MAXIMUM_BLUR_SIZE*offset/5.0;float coc0=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv)).a-1.;float coc1=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-5.0*sampleOffsets)).a-1.;float coc2=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-4.0*sampleOffsets)).a-1.;float coc3=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-3.0*sampleOffsets)).a-1.;float coc4=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-2.0*sampleOffsets)).a-1.;float coc5=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-1.0*sampleOffsets)).a-1.;float coc6=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+1.0*sampleOffsets)).a-1.;float coc7=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+2.0*sampleOffsets)).a-1.;float coc8=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+3.0*sampleOffsets)).a-1.;float coc9=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+4.0*sampleOffsets)).a-1.;float coc10=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+5.0*sampleOffsets)).a-1.;if(isBackground){coc=abs(coc0)*0.095474+(abs(coc1)+abs(coc10))*0.084264+(abs(coc2)+abs(coc9))*0.088139+(abs(coc3)+abs(coc8))*0.091276+(abs(coc4)+abs(coc7))*0.093585+(abs(coc5)+abs(coc6))*0.094998;}else{coc=min(coc0,0.0);coc=min(coc1*0.3,coc);coc=min(coc2*0.5,coc);coc=min(coc3*0.75,coc);coc=min(coc4*0.8,coc);coc=min(coc5*0.95,coc);coc=min(coc6*0.95,coc);coc=min(coc7*0.8,coc);coc=min(coc8*0.75,coc);coc=min(coc9*0.5,coc);coc=min(coc10*0.3,coc);if(abs(coc0)>abs(coc))coc=coc0;}return coc;}void main(){vec2 offset=2.*direction/colorTextureSize;bool isBackground=getDepth(vUv)>1.0-0.001;float coc=expandNear(offset,isBackground);gl_FragColor=vec4(colorTextureTexelToLinear(texture2D(colorTexture,vUv)).rgb,0.5*coc+0.5);\n#include <colorspace_fragment>\n}"},["colorTexture"])}render(e,t,r,i,a){if(!this.enabled)return;if(!r)return void console.error("DepthOfFieldPluginPass: No readBuffer");const s=e.renderManager,n={minFilter:H,magFilter:H,type:U,colorSpace:x,sizeMultiplier:.5,format:G,depthBuffer:!1,generateMipmaps:!1},o=s.getTempTarget(n),l=s.getTempTarget(n);if(this.computeCocMaterial.uniforms.colorTexture.value=r.texture,s.blit(o,{material:this.computeCocMaterial}),this.expandCocMaterial.uniforms.colorTexture.value=o.texture,this.expandCocMaterial.uniforms.direction.value.set(1,0),s.blit(l,{material:this.expandCocMaterial}),this.expandCocMaterial.uniforms.colorTexture.value=l.texture,this.expandCocMaterial.uniforms.direction.value.set(0,1),s.blit(o,{material:this.expandCocMaterial}),this.dofBlurMaterial.uniforms.frameCount)this.dofBlurMaterial.uniforms.colorTexture.value=o.texture,s.blit(l,{material:this.dofBlurMaterial});else{const e=s.getTempTarget(n);this.dofBlurMaterial.uniforms.cocTexture.value=o.texture,this.dofBlurMaterial.uniforms.colorTexture.value=o.texture,this.dofBlurMaterial.uniforms.direction.value.set(1,0),s.blit(e,{material:this.dofBlurMaterial}),this.dofBlurMaterial.uniforms.colorTexture.value=e.texture,this.dofBlurMaterial.uniforms.direction.value.set(0,1),s.blit(l,{material:this.dofBlurMaterial}),s.releaseTempTarget(e)}this.material.uniforms.blurTexture.value=l.texture,this.material.uniforms.cocTexture.value=o.texture,super.render(e,t,r,i,a),s.releaseTempTarget(o),s.releaseTempTarget(l)}};Ke([W({obj:"focalDepthRange",key:"y"}),O("Depth Range",[.25,3])],$e.prototype,"depthRange",2),Ke([W({obj:"nearFarBlurScale",key:"x"}),O("Near Blur Scale",[0,1])],$e.prototype,"nearBlurScale",2),Ke([W({obj:"nearFarBlurScale",key:"y"}),O("Far Blur Scale",[0,1])],$e.prototype,"farBlurScale",2),Ke([f(),m()],$e.prototype,"nearFarBlurScale",2),Ke([f(),m()],$e.prototype,"focalDepthRange",2),Ke([m()],$e.prototype,"crossCenter",2),Ke([m()],$e.prototype,"crossRadius",2),Ke([m()],$e.prototype,"crossAlpha",2),Ke([m()],$e.prototype,"crossColor",2),$e=Ke([E("DepthOfField Pass")],$e);const Qe="#ifndef SSRT_PARS_SNIP\n#define SSRT_PARS_SNIP\n#define pow2(a) a*a\nfloat getDepth2(const in vec2 uv,const in float lod){float viewDepth=getDepth(uv);return depthToViewZ(viewDepth);}\n#define LOD_DEPTH 1.0\n#define LOD_COLOR 5.0\nvoid _traceRay(in vec4 ray_origin,in vec4 ray_dir,in float tolerance,inout vec3 state,in int loopMax,in float iStepCount){vec4 sample_uv;float d,hit;float dLod=0.;\n#pragma unroll_loop_start\nfor(int i=0;i<8;i++){if(UNROLLED_LOOP_INDEX<loopMax){sample_uv=ray_origin+ray_dir*state.y;d=getDepth2(sample_uv.xy,dLod);d=sample_uv.z/sample_uv.w-d;if(abs(d+tolerance)<tolerance){hit=clamp(state.x/(state.x-d),0.,1.)-1.;hit=(state.y+hit*iStepCount);state.z=min(state.z,hit);}state.x=d;state.y+=1.*iStepCount;}}\n#pragma unroll_loop_end\n}vec3 traceRay(in vec3 ray_origin_view,in vec3 ray_dir_view,in float tolerance,inout vec3 state,in int _STEP_COUNT){vec4 sample_uv;vec4 ray_origin=viewToScreen3(ray_origin_view);vec3 ray_end_view=ray_origin_view+ray_dir_view;vec4 ray_dir=viewToScreen3(ray_end_view);vec2 clamp_end=clamp(ray_dir.xy,vec2(0.),vec2(1.));vec2 correction=abs(ray_dir.xy-clamp_end);correction=(step(0.01,correction)*correction/(abs(clamp_end-ray_origin.xy)+0.01))+1.;correction.x=1./min(max(correction.y,correction.x),10.);ray_dir=ray_dir-ray_origin;ray_dir.xyw*=correction.x;float iStepCount=1./float(_STEP_COUNT);tolerance*=0.125;_traceRay(ray_origin,ray_dir,tolerance,state,_STEP_COUNT,iStepCount);if(_STEP_COUNT>8&&state.z>0.98)_traceRay(ray_origin,ray_dir,tolerance,state,_STEP_COUNT-8,iStepCount);if(_STEP_COUNT>15&&state.z>0.98)_traceRay(ray_origin,ray_dir,tolerance,state,_STEP_COUNT-16,iStepCount);if(_STEP_COUNT>23&&state.z>0.98)_traceRay(ray_origin,ray_dir,tolerance,state,_STEP_COUNT-16,iStepCount);sample_uv=ray_origin+ray_dir*state.z;sample_uv.z/=sample_uv.w;state.z=state.z<0.999 ? state.z : 9999999.;return sample_uv.xyz;}/**for ray clippinga=ray_originb=ray_endc=clamp(b)x=c.y-a.yy=b.y-c.y(c.y-a.y)/(b.y-c.y)=m/(l-m)m/(l-m)=km=kl-kmm=kl/(1+k)((c-a)/(b-c))/(1+(c-a)/(b-c))x/(y*(1+x/y))x/(y+x)1/(y/x+1)x/(y+yx)1/(y/x+y)ray scale=k/(1+k)1/(1/k+1)=1/((b-c)/(c-a)+1)**/\n#endif\n";var et=Object.defineProperty,tt=Object.getOwnPropertyDescriptor,rt=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?tt(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&et(t,r,s),s};const it=r.ShaderChunk;let at=class extends Y{constructor(e=!0){super(),this.enabled=!0,this._uniforms={sscsRadius:{value:.03},sscsIntensity:{value:1},sscsTolerance:{value:1.5},frameCount:{value:0},projection:{value:new u},cameraPositionWorld:{value:new F},cameraNearFar:{value:new d(.1,1e3)},sceneBoundingRadius:{value:0}},this.radius=.015,this.intensity=1,this.tolerance=1.5,this._defines={PERSPECTIVE_CAMERA:1},this.onlySSCSDebug=!1,this.stepCount=2,this.dependencies=[a],this.materialExtension={uuid:at.PluginType,priority:5,shaderExtender:(e,t,r)=>{if(!e.defines.SSCS_ENABLED)return;const i=K`
1
+ /**
2
+ * @license
3
+ * @threepipe/webgi-plugins v0.8.0
4
+ * Copyright 2023-2026 repalash <palash@shaders.app> (https://repalash.com)
5
+ * webgi Free Forever License, see LICENSE
6
+ * See ./dependencies.txt for any bundled third-party dependencies and licenses.
7
+ */
8
+ import { AScreenPassExtensionPlugin, AViewerPluginSync, AdditiveBlending, BaseGroundPlugin, BasicShadowMap, Color, CopyShader, DirectionalLight2, DoubleSide, ExtendedShaderMaterial, ExtendedShaderPass, FrameFadePlugin, GBufferPlugin, GBufferRenderPass, HalfFloatType, Layers, LinearFilter, LinearMipmapLinearFilter, LinearSRGBColorSpace, MathUtils, Matrix3, Matrix4, Mesh2, NearestFilter, NoBlending, NoColorSpace, PCFShadowMap, PCFSoftShadowMap, PerspectiveCamera, PickingPlugin, PipelinePassPlugin, Plane, ProgressivePlugin, RGBAFormat, RenderManager, RenderPass, SRGBColorSpace, SSAAPlugin, Serialization, ShaderMaterial, ShaderMaterial2, ShadowMaterial, SimpleEventDispatcher, ThreeSerialization, UnsignedByteType, VSMShadowMap, Vector2, Vector3, Vector4, animateTarget, bindToValue, copyObject3DUserData, generateUiConfig, getOrCall, getTexelDecoding, glsl, makeSamplerUi, matDefine, matDefineBool, now, onChange, onChange2, serialize, shaderReplaceString, shaderUtils, uiButton, uiColor, uiConfig, uiConfigMaterialExtension, uiDropdown, uiFolderContainer, uiImage, uiInput, uiSlider, uiToggle, uiVector, uniform, updateBit, updateMaterialDefines } from "threepipe";
9
+ // src/plugins/buffer/shaders/VelocityBufferPlugin.unpack.glsl
10
+ var VelocityBufferPlugin_unpack_default = "#if defined(HAS_VELOCITY_BUFFER)\nuniform sampler2D tVelocity;vec2 getVelocity(const in vec2 uv){vec2 screenSpaceVelocity=texture2D(tVelocity,uv).xy*2.0-1.0;return sign(screenSpaceVelocity)*pow(abs(screenSpaceVelocity),vec2(4.));}\n#endif\n";
11
+ // src/plugins/buffer/shaders/VelocityBufferPlugin.mat.vert.glsl
12
+ var VelocityBufferPlugin_mat_vert_default = "#ifdef USE_ALPHAMAP\n#define USE_UV\n#endif\n#include <uv_pars_vertex>\n#include <batching_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec3 vWorldPosition;varying vec3 vWorldPositionPrevious;uniform mat4 modelMatrixPrevious;void main(){\n#include <uv_vertex>\n#include <batching_vertex>\n#include <skinbase_vertex>\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <skinning_vertex>\n#include <displacementmap_vertex>\nvec4 mvPosition=vec4(transformed,1.0);\n#ifdef USE_INSTANCING\nmvPosition=instanceMatrix*mvPosition;\n#endif\nvWorldPosition=(modelMatrix*mvPosition).xyz;vWorldPositionPrevious=(modelMatrixPrevious*mvPosition).xyz;mvPosition=modelViewMatrix*mvPosition;gl_Position=projectionMatrix*mvPosition;\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\n}";
13
+ // src/plugins/buffer/shaders/VelocityBufferPlugin.mat.frag.glsl
14
+ var VelocityBufferPlugin_mat_frag_default = "#ifdef USE_ALPHAMAP\n#define USE_UV\n#include <packing>\nuniform sampler2D alphaMap;uniform float alphaTest;\n#endif\n#include <uv_pars_fragment>\nvarying vec3 vWorldPosition;varying vec3 vWorldPositionPrevious;uniform mat4 currentProjectionViewMatrix;uniform mat4 lastProjectionViewMatrix;vec2 computeScreenSpaceVelocity2(){vec4 currentPositionClip=currentProjectionViewMatrix*vec4(vWorldPosition,1.0);vec4 prevPositionClip=lastProjectionViewMatrix*vec4(vWorldPositionPrevious,1.0);vec2 currentPositionNDC=currentPositionClip.xy/currentPositionClip.w;vec2 prevPositionNDC=prevPositionClip.xy/prevPositionClip.w;if(prevPositionNDC.x>=1.0||prevPositionNDC.x<=-1.0||prevPositionNDC.x>=1.0||prevPositionNDC.y<=-1.0){return vec2(0.0);}return 0.5*(currentPositionNDC-prevPositionNDC);}void main(){\n#ifdef USE_ALPHAMAP\nfloat alphaMapValue=\n#ifdef ALPHA_I_RGBA_PACKING\n1.-unpackRGBAToDepth(texture2D(alphaMap,vAlphaMapUv));\n#else\ntexture2D(alphaMap,vAlphaMapUv).g;\n#endif\nif(alphaMapValue<alphaTest)discard;\n#endif\nvec2 velocity=clamp(computeScreenSpaceVelocity2(),-1.0,1.0);velocity=sign(velocity)*pow(abs(velocity),vec2(1./4.));velocity=velocity*0.5+0.5;gl_FragColor=vec4(velocity.x,velocity.y,1.,1.);}";
15
+ // src/utils/shaders.ts
16
+ var shadersUtils2 = {
17
+ computeScreenSpaceVelocity: "uniform mat4 lastProjectionViewMatrix;uniform mat4 currentProjectionViewMatrix;vec2 computeScreenSpaceVelocity(const in vec3 worldPosition){vec4 currentPositionClip=currentProjectionViewMatrix*vec4(worldPosition,1.0);vec4 prevPositionClip=lastProjectionViewMatrix*vec4(worldPosition,1.0);vec2 currentPositionNDC=currentPositionClip.xy/currentPositionClip.w;vec2 prevPositionNDC=prevPositionClip.xy/prevPositionClip.w;if(prevPositionNDC.x>=1.0||prevPositionNDC.x<=-1.0||prevPositionNDC.x>=1.0||prevPositionNDC.y<=-1.0){return vec2(0.0);}return 0.5*(currentPositionNDC-prevPositionNDC);}",
18
+ getWorldPositionFromViewZ: "uniform mat4 inverseViewMatrix;vec3 getWorldPositionFromViewZ(const in vec2 uv,const in float viewDepth){vec2 uv_=2.*uv-1.;float xe=-(uv_.x+projection[2][0])*viewDepth/projection[0][0];float ye=-(uv_.y+projection[2][1])*viewDepth/projection[1][1];return(inverseViewMatrix*vec4(xe,ye,viewDepth,1.)).xyz;}",
19
+ temporalAA: "#include <common>\n#include <gbuffer_unpack>\n#ifdef HAS_VELOCITY_BUFFER\n#pragma <velocity_unpack>\n#else\n#define HAS_VELOCITY_BUFFER 0\n#endif\n#include <cameraHelpers>\nvarying vec2 vUv;uniform vec2 previousRTSize;uniform vec2 jitterSample;uniform vec2 feedBack;uniform bool firstFrame;vec3 find_closest_fragment_3x3(const in vec2 uv){const vec3 offset=vec3(-1.0,1.0,0.0);vec2 texelSize=1.0/previousRTSize;vec3 dtr=vec3(1,1,getDepth(uv+offset.yy*texelSize));vec3 dtc=vec3(0,1,getDepth(uv+offset.zy*texelSize));vec3 dtl=vec3(-1,1,getDepth(uv+offset.xy*texelSize));vec3 dml=vec3(-1,0,getDepth(uv+offset.xz*texelSize));vec3 dmc=vec3(0,0,getDepth(uv));vec3 dmr=vec3(1,0,getDepth(uv+offset.yz*texelSize));vec3 dbl=vec3(-1,-1,getDepth(uv+offset.xx*texelSize));vec3 dbc=vec3(0,-1,getDepth(uv+offset.zx*texelSize));vec3 dbr=vec3(1,-1,getDepth(uv+offset.yx*texelSize));vec3 dmin=dtl;if(dmin.z>dtc.z)dmin=dtc;if(dmin.z>dtr.z)dmin=dtr;if(dmin.z>dml.z)dmin=dml;if(dmin.z>dmc.z)dmin=dmc;if(dmin.z>dmr.z)dmin=dmr;if(dmin.z>dbl.z)dmin=dbl;if(dmin.z>dbc.z)dmin=dbc;if(dmin.z>dbr.z)dmin=dbr;return vec3(uv+texelSize.xy*dmin.xy,dmin.z);}vec3 find_closest_fragment_5tap(const in vec2 uv){vec2 texelSize=1.0/previousRTSize;vec2 offset=vec2(1.0,-1.0);vec3 dtl=vec3(-1,1,getDepth(uv+offset.yx*texelSize));vec3 dtr=vec3(1,1,getDepth(uv+offset.xx*texelSize));vec3 dmc=vec3(0,0,getDepth(uv));vec3 dbl=vec3(-1,-1,getDepth(uv+offset.yy*texelSize));vec3 dbr=vec3(1,-1,getDepth(uv+offset.xy*texelSize));vec3 dmin=dtl;if(dmin.z>dtr.z)dmin=dtr;if(dmin.z>dmc.z)dmin=dmc;if(dmin.z>dbl.z)dmin=dbl;if(dmin.z>dbr.z)dmin=dbr;return vec3(uv+dmin.xy*texelSize,dmin.z);}vec4 clip_aabb(const in vec4 aabb_min,const in vec4 aabb_max,vec4 p){const float FLT_EPS=1e-8;vec4 p_clip=0.5*(aabb_max+aabb_min);vec4 e_clip=0.5*(aabb_max-aabb_min)+FLT_EPS;vec4 v_clip=p-p_clip;vec4 v_unit=abs(v_clip/e_clip);float ma_unit=max(v_unit.x,max(v_unit.y,v_unit.z));if(ma_unit>1.0)return p_clip+v_clip/ma_unit;else return p;}\n#if HAS_VELOCITY_BUFFER == 0 || defined(DEBUG_VELOCITY)\n#include <computeScreenSpaceVelocity>\n#include <getWorldPositionFromViewZ>\n#endif\nvec4 currentRTTexelToLinear1(vec4 a){if(isinf(a.x)||isinf(a.y)||isinf(a.z)||isinf(a.w)){return vec4(1.);}return currentRTTexelToLinear(a);}vec4 computeTAA(const in vec2 uv,const in vec2 screenSpaceVelocity,const in float feedbackScale){vec2 uvUnJitter=uv;vec4 currentColor=currentRTTexelToLinear(texture2D(currentRT,uvUnJitter));vec4 previousColor=previousRTTexelToLinear(texture2D(previousRT,uv-screenSpaceVelocity));const vec3 offset=vec3(1.,-1.,0.);vec2 texelSize=1./previousRTSize;float texelSpeed=length(screenSpaceVelocity);vec4 tl=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.yx*texelSize));vec4 tc=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.zx*texelSize));vec4 tr=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.xx*texelSize));vec4 ml=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.yz*texelSize));vec4 mc=currentColor;vec4 mr=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.xz*texelSize));vec4 bl=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.yy*texelSize));vec4 bc=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.zy*texelSize));vec4 br=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.xy*texelSize));mc=max(vec4(0.0),mc+0.2718*(4.0*mc-(tl+tr+bl+br)));vec4 min5=min(tc,min(ml,min(mc,min(mr,bc))));vec4 max5=max(tc,max(ml,max(mc,max(mr,bc))));vec4 cmin=min(min5,min(tl,min(tr,min(bl,br))));vec4 cmax=max(min5,max(tl,max(tr,max(bl,br))));;cmin=0.5*(cmin+min5);cmax=0.5*(cmax+max5);previousColor=clip_aabb(cmin,cmax,previousColor);float lum0=luminance(currentColor.rgb);float lum1=luminance(previousColor.rgb);float unbiased_diff=abs(lum0-lum1)/max(lum0,max(lum1,0.2));float unbiased_weight=1.0-unbiased_diff;float unbiased_weight_sqr=unbiased_weight*unbiased_weight;float k_feedback=mix(feedBack.x,feedBack.y,unbiased_weight_sqr);return mix(currentColor,previousColor,clamp(k_feedback*feedbackScale,0.,1.));}void main(){\n#if HAS_VELOCITY_BUFFER == 0\n#if QUALITY == 1\nvec3 c_frag=find_closest_fragment_3x3(vUv);\n#else\nvec3 c_frag=find_closest_fragment_5tap(vUv);\n#endif\n#else\nvec3 c_frag=vec3(vUv,0.);\n#endif\nbool bg=firstFrame;\n#if BACKGROUND_TAA\nfloat d=c_frag.z;float edgef=min(1.,max(0.,1.-(d*100.-99.)));\n#else\nbg=bg||c_frag.z>0.999;\n#endif\nif(bg){gl_FragColor=currentRTTexelToLinear1(texture2D(currentRT,vUv));}else{\n#if HAS_VELOCITY_BUFFER == 0\nfloat sampleViewZ=mix(-cameraNearFar.x,-cameraNearFar.y,c_frag.z);vec3 worldPosition=getWorldPositionFromViewZ(c_frag.xy,sampleViewZ);vec2 screenSpaceVelocity=computeScreenSpaceVelocity(worldPosition);\n#else\nvec2 screenSpaceVelocity=getVelocity(c_frag.xy);\n#endif\n#if BACKGROUND_TAA\ngl_FragColor=computeTAA(vUv,screenSpaceVelocity*edgef,edgef);\n#else\ngl_FragColor=computeTAA(vUv,screenSpaceVelocity,1.);\n#endif\n}\n#include <colorspace_fragment>\n#ifdef DEBUG_VELOCITY\nfloat sampleViewZ=mix(-cameraNearFar.x,-cameraNearFar.y,c_frag.z);vec3 worldPosition=getWorldPositionFromViewZ(c_frag.xy,sampleViewZ);vec2 screenSpaceVelocity=computeScreenSpaceVelocity(worldPosition);gl_FragColor=vec4(10.*length(screenSpaceVelocity),0.,0.,1.);\n#endif\n}",
20
+ ssReflection: "uniform float currentFrameCount;\n#ifndef D_frameCount\n#define D_frameCount\nuniform float frameCount;\n#endif\nuniform float objectRadius;uniform float radius;uniform float tolerance;uniform float ssrRoughnessFactor;uniform bool autoRadius;\n#ifndef D_sceneBoundingRadius\n#define D_sceneBoundingRadius\nuniform float sceneBoundingRadius;\n#endif\n#if SSREFL_ENABLED == 2\nuniform float ssrSplitX;\n#endif\n#ifdef HAS_VELOCITY_BUFFER\n#pragma <velocity_unpack>\n#else\n#define HAS_VELOCITY_BUFFER 0\n#endif\n#if HAS_VELOCITY_BUFFER == 0\n#include <computeScreenSpaceVelocity>\n#include <getWorldPositionFromViewZ>\n#endif\nvec3 ComputeReflectionL(vec3 N,vec2 E,vec3 V,float rough){float rough4=rough*rough*rough*rough;float phi=2.0*PI*E.x;float cos_theta=pow(max(E.y,0.000001),rough4/(2.0-rough4));float sin_theta=sqrt(max(0.,1.0-cos_theta*cos_theta));vec3 half_vec=vec3(sin_theta*cos(phi),sin_theta*sin(phi),cos_theta);vec3 tangentX=normalize(cross(abs(N.z)<0.999 ? vec3(0.0,0.0,1.0): vec3(1.0,0.0,0.0),N));vec3 tangentY=cross(N,tangentX);half_vec=half_vec.x*tangentX+half_vec.y*tangentY+half_vec.z*N;vec3 ray_dir=(2.0*dot(V,half_vec))*half_vec-V;return ray_dir;}vec2 GetRandomE(float seed){vec2 rand_e;rand_e.x=interleavedGradientNoise(gl_FragCoord.xy,frameCount*34.+seed);rand_e.y=fract(rand_e.x*38.65435);rand_e.y=mix(rand_e.y,1.0,0.7);return rand_e;}vec4 calculateSSR(in float seed,in vec3 screenPos,in vec3 normal,in float radiusFactor,in float roughness){vec3 viewPos=screenToView3(screenPos.xy,screenPos.z);normal=normalize(normal);vec2 E=GetRandomE(seed);vec3 L=ComputeReflectionL(normal,E,-normalize(viewPos),roughness*ssrRoughnessFactor);L=normalize(L);float cameraDist=length(cameraPositionWorld);float rayLen=objectRadius*sceneBoundingRadius;rayLen=autoRadius ?min(max(mix(max(0.0,(cameraDist+rayLen)+viewPos.z),max(0.0,-viewPos.z-max(0.0,cameraDist-rayLen)),L.z*0.5+0.5),rayLen*0.1),rayLen*5.):rayLen;rayLen*=radiusFactor;float r=interleavedGradientNoise(gl_FragCoord.xy,frameCount+seed);rayLen=max(rayLen,0.001);int steps=SSR_STEP_COUNT/(currentFrameCount<float(SSR_LOW_QUALITY_FRAMES)? 2 : 1);vec3 state=vec3(0.,(r+0.5)/float(steps),2.);viewPos+=normal*max(-0.0001*viewPos.z,0.001);vec3 screenHitP=traceRay(viewPos,L*rayLen,tolerance*rayLen,state,steps);if(state.z<0.99){if(currentFrameCount<1.){\n#if HAS_VELOCITY_BUFFER == 0\nvec3 worldPosition=getWorldPositionFromViewZ(screenHitP.xy,screenHitP.z);vec2 screenSpaceVelocity=computeScreenSpaceVelocity(worldPosition);\n#else\nvec2 screenSpaceVelocity=getVelocity(screenHitP.xy);\n#endif\nscreenHitP.xy-=screenSpaceVelocity;}vec3 hitColor=(tLastFrameTexelToLinear(texture2D(tLastFrame,screenHitP.xy))).rgb;float ssrWeight=1.;return vec4(hitColor*ssrWeight,1.);}return vec4(0.);}",
21
+ calculateGI: "uniform float currentFrameCount;uniform float intensity;uniform float objectRadius;uniform float rayCount;uniform float power;uniform float bias;uniform float falloff;uniform float tolerance;uniform bool autoRadius;uniform vec2 screenSize;\n#ifndef D_sceneBoundingRadius\n#define D_sceneBoundingRadius\nuniform float sceneBoundingRadius;\n#endif\n#ifdef HAS_VELOCITY_BUFFER\n#pragma <velocity_unpack>\n#else\n#define HAS_VELOCITY_BUFFER 0\n#endif\n#if HAS_VELOCITY_BUFFER == 0\n#include <computeScreenSpaceVelocity>\n#include <getWorldPositionFromViewZ>\n#endif\nvec3 ComputeUniformL(vec3 N,vec2 E){vec3 L;L.xy=E;L.z=interleavedGradientNoise(gl_FragCoord.xy,currentFrameCount*5.);L=L*2.-1.;return L;}vec2 GetRandomE(float seed){vec2 rand_e;rand_e.x=random3(vec3(gl_FragCoord.xy,currentFrameCount+seed));rand_e.y=random3(vec3(gl_FragCoord.yx,rand_e.x+(currentFrameCount)*7.));return rand_e;}float saturate2(float v,float mx){return max(0.,min(mx,v));}vec4 calculateGI(in float seed,in vec3 screenPos,in vec3 normal,in float radiusFactor){vec3 viewPos=screenToView3(screenPos.xy,screenPos.z);normal=normalize(normal);vec2 E=GetRandomE(seed);vec3 L=ComputeUniformL(normal,E);L=normalize(L);L*=sign(dot(L,normal));float cameraDist=length(cameraPositionWorld);float rayLen=objectRadius*sceneBoundingRadius;rayLen=autoRadius ?min(max(mix(max(0.0,(cameraDist+rayLen)+viewPos.z),max(0.0,-viewPos.z-max(0.0,cameraDist-rayLen)),L.z*0.5+0.5),rayLen*0.1),rayLen*5.):rayLen;rayLen*=radiusFactor;float r=interleavedGradientNoise(gl_FragCoord.xy,currentFrameCount*14.+seed)+0.05;rayLen=max(rayLen,0.001);vec3 state=vec3(1.,(r+0.5)/float(RTAO_STEP_COUNT),2.);viewPos+=normal*max(-0.01*viewPos.z,0.001);vec3 screenHitP=traceRay(viewPos,L*rayLen,tolerance*rayLen,state,RTAO_STEP_COUNT);vec3 viewHitP=screenToView3(screenHitP.xy,screenHitP.z);vec3 LRes=viewHitP-viewPos;if(state.z>1.)LRes=vec3(9999999.);float dist=length(LRes)*falloff;float EPS=0.01;float zBias=(viewPos.z)*bias;float ao=(max(dot(normal,L)+zBias,0.))/(dist*dist+EPS);\n#if defined(SSGI_ENABLED) && SSGI_ENABLED > 0\nif(currentFrameCount<1.){\n#if HAS_VELOCITY_BUFFER == 0\nvec3 worldPosition=getWorldPositionFromViewZ(screenHitP.xy,screenHitP.z);vec2 screenSpaceVelocity=computeScreenSpaceVelocity(worldPosition);\n#else\nvec2 screenSpaceVelocity=getVelocity(screenHitP.xy);\n#endif\nscreenHitP.xy-=screenSpaceVelocity;}vec3 hitColor=tLastFrameTexelToLinear(texture2D(tLastFrame,screenHitP.xy)).rgb;vec3 hitNormal=getViewNormal(screenHitP.xy);float giWeight=1.;giWeight=saturate2(giWeight/(dist+EPS),1.);giWeight*=saturate2((dot(normal,L)),1.0);giWeight*=saturate2((dot(hitNormal,-L)),1.0);return vec4(hitColor*giWeight,ao);\n#endif\nreturn vec4(0,0,0,ao);}float normpdf(in float x,in float sigma){return exp(-0.5*x*x/(sigma*sigma));}vec4 getLastThis(sampler2D tex,float depth,vec3 normal){vec2 direction=vec2(1,1);vec4 color=clamp(tLastThisTexelToLinear(texture2D(tex,vUv.xy)),0.,5.);return color;}void main(){float depth;vec3 normal;getDepthNormal(vUv,depth,normal);if(depth>0.99){discard;gl_FragColor=getLastThis(tLastThis,depth,normal);return;}float viewZ=depthToViewZ(depth);vec3 screenPos=vec3(vUv.x,vUv.y,viewZ);vec4 gi=vec4(0.);gi+=calculateGI(8.,screenPos,normal,1.);if(rayCount>1.5)gi=max(gi,calculateGI(2.,screenPos,normal,0.4));if(rayCount>2.5)gi=max(gi,calculateGI(3.,screenPos,normal,1.5));if(rayCount>3.5)gi=max(gi,calculateGI(1.,screenPos,normal,0.6));if(rayCount>4.5)gi=max(gi,calculateGI(3.,screenPos,normal,1.));gi.a=min(1.,gi.a);gi.a=max(0.,gi.a);gi.rgb=min(vec3(3.),gi.rgb);gi.rgb=max(vec3(0.),gi.rgb);if(currentFrameCount<3.){gl_FragColor=gi;return;}gl_FragColor=(texture2D(tLastThis,vUv));gl_FragColor=((gi+(gl_FragColor)*currentFrameCount)/(currentFrameCount+1.));}",
22
+ ["__inited"]: false
23
+ };
24
+ function getShaders() {
25
+ if (!shadersUtils2.__inited) {
26
+ shadersUtils2.__inited = true;
27
+ Object.assign(RenderManager.ShaderChunk, shadersUtils2);
28
+ }
29
+ return shadersUtils2;
30
+ }
31
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/decorate.js
32
+ function __decorate(decorators, target, key, desc) {
33
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
34
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
35
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
36
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
37
+ }
38
+ // src/plugins/postprocessing/TemporalAAPlugin.ts
39
+ var passId$4 = "taa";
40
+ /**
41
+ * Temporal Anti-Aliasing Plugin
42
+ *
43
+ * This plugin uses a temporal anti-aliasing pass to smooth out the final image when the camera or some mesh is moving
44
+ * @category Plugins
45
+ */
46
+ var TemporalAAPlugin = class extends PipelinePassPlugin {
47
+ static {
48
+ this.PluginType = "TAA";
49
+ }
50
+ static {
51
+ this.OldPluginType = "TemporalAAPlugin";
52
+ }
53
+ constructor(enabled = true) {
54
+ super();
55
+ this.passId = passId$4;
56
+ this._stableNoise = true;
57
+ this._gbufferUnpackExtension = void 0;
58
+ this._gbufferUnpackExtensionChanged = () => {
59
+ if (!this._pass || !this._viewer) throw new Error("TemporalAAPlugin: pass/viewer not created yet");
60
+ const newExtension = this._viewer.renderManager.gbufferUnpackExtension;
61
+ if (this._gbufferUnpackExtension === newExtension) return;
62
+ if (this._gbufferUnpackExtension) this._pass.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]);
63
+ this._gbufferUnpackExtension = newExtension;
64
+ if (this._gbufferUnpackExtension) this._pass.material.registerMaterialExtensions([this._gbufferUnpackExtension]);
65
+ else this._viewer.console.warn("TemporalAAPlugin: GBuffer unpack extension removed");
66
+ };
67
+ this.dependencies = [GBufferPlugin, ProgressivePlugin];
68
+ this.uiConfig = {
69
+ type: "folder",
70
+ label: "TemporalAA Plugin",
71
+ onChange: this.setDirty.bind(this),
72
+ children: [...generateUiConfig(this) || []]
73
+ };
74
+ this.enabled = enabled;
75
+ this.setDirty = this.setDirty.bind(this);
76
+ }
77
+ /**
78
+ * Same as BaseRenderer.stableNoise Use total frame count, if this is set to true, then frameCount won't be reset when the viewer is set to dirty.
79
+ * Which will generate different random numbers for each frame during postprocessing steps. With TAA set properly, this will give a smoother result.
80
+ */
81
+ get stableNoise() {
82
+ return this._viewer?.renderManager.stableNoise ?? this._stableNoise;
83
+ }
84
+ set stableNoise(v) {
85
+ if (this._viewer) this._viewer.renderManager.stableNoise = v;
86
+ this._stableNoise = v;
87
+ }
88
+ _createPass() {
89
+ if (!this._viewer) throw new Error("TemporalAAPlugin: viewer not set");
90
+ if (!this._viewer.renderManager.gbufferTarget || !this._viewer.renderManager.gbufferUnpackExtension) throw new Error("TemporalAAPlugin: GBuffer target not created. GBufferPlugin is required.");
91
+ const applyOnBackground = !!this._viewer.renderManager.msaa;
92
+ return new TemporalAAPluginPass(this.passId, () => this._viewer?.getPlugin(ProgressivePlugin)?.target, applyOnBackground);
93
+ }
94
+ onAdded(viewer) {
95
+ super.onAdded(viewer);
96
+ this._gbufferUnpackExtensionChanged();
97
+ viewer.renderManager.addEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
98
+ viewer.renderManager.addEventListener("resize", this._pass.onSizeUpdate);
99
+ }
100
+ onRemove(viewer) {
101
+ viewer.renderManager.removeEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
102
+ viewer.renderManager.removeEventListener("resize", this._pass.onSizeUpdate);
103
+ super.onRemove(viewer);
104
+ }
105
+ _beforeRender(scene, camera, renderManager) {
106
+ if (!super._beforeRender(scene, camera, renderManager)) return false;
107
+ const pass = this.pass;
108
+ const v = this._viewer;
109
+ if (!pass || !v) return false;
110
+ pass.taaEnabled = renderManager.frameCount <= 1 && scene.renderCamera === scene.mainCamera;
111
+ if (!pass.taaEnabled) return false;
112
+ const cam = camera;
113
+ if (!cam) return false;
114
+ cam.updateMatrixWorld(true);
115
+ cam.updateShaderProperties(pass.material);
116
+ pass.updateCameraProperties(cam);
117
+ pass.target = v.getPlugin(ProgressivePlugin).target;
118
+ return true;
119
+ }
120
+ };
121
+ __decorate([uiToggle("Stable Noise (Total frame count)")], TemporalAAPlugin.prototype, "stableNoise", null);
122
+ __decorate([uiConfig(void 0, { unwrapContents: true })], TemporalAAPlugin.prototype, "_pass", void 0);
123
+ var TemporalAAPluginPass = class extends ExtendedShaderPass {
124
+ constructor(pid, target, applyOnBackground = false) {
125
+ super({
126
+ vertexShader: CopyShader.vertexShader,
127
+ fragmentShader: getShaders().temporalAA,
128
+ uniforms: {
129
+ currentRT: { value: null },
130
+ previousRT: { value: null },
131
+ previousRTSize: { value: new Vector2() },
132
+ cameraNearFar: { value: new Vector2() },
133
+ lastProjectionViewMatrix: { value: new Matrix4() },
134
+ currentProjectionViewMatrix: { value: new Matrix4() },
135
+ projection: { value: new Matrix4() },
136
+ inverseViewMatrix: { value: new Matrix4() },
137
+ jitterSample: { value: new Vector2() },
138
+ firstFrame: { value: true }
139
+ },
140
+ defines: {
141
+ ["QUALITY"]: 1,
142
+ ["UNJITTER"]: 0,
143
+ ["BACKGROUND_TAA"]: applyOnBackground ? 1 : 0
144
+ }
145
+ }, "currentRT", "previousRT");
146
+ this.before = ["progressive"];
147
+ this.after = [];
148
+ this.required = ["render", "progressive"];
149
+ this.taaEnabled = true;
150
+ this.feedBack = new Vector2(.88, .97);
151
+ this.debugVelocity = false;
152
+ this.uiConfig = {
153
+ type: "folder",
154
+ label: "Temporal AA Pass",
155
+ onChange: this.setDirty,
156
+ children: [{
157
+ type: "checkbox",
158
+ label: "Enabled",
159
+ property: [this, "enabled"],
160
+ onChange: () => this.onSizeUpdate()
161
+ }, ...generateUiConfig(this)?.filter((c) => c && c.label !== "Enabled") || []]
162
+ };
163
+ this.passId = pid;
164
+ this.onSizeUpdate = this.onSizeUpdate.bind(this);
165
+ this.target = target;
166
+ this.clear = false;
167
+ this.needsSwap = true;
168
+ }
169
+ render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) {
170
+ if (!this.taaEnabled || !this.enabled) {
171
+ this.needsSwap = false;
172
+ return;
173
+ }
174
+ this.needsSwap = true;
175
+ this.uniforms.previousRT.value = getOrCall(this.target)?.texture ?? null;
176
+ super.render(renderer, writeBuffer, readBuffer, deltaTime, maskActive);
177
+ this.uniforms.lastProjectionViewMatrix.value.copy(this.uniforms.currentProjectionViewMatrix.value);
178
+ this.uniforms.firstFrame.value = false;
179
+ }
180
+ updateCameraProperties(camera) {
181
+ if (!camera) return;
182
+ this.uniforms.currentProjectionViewMatrix.value.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
183
+ this.uniforms.inverseViewMatrix.value.copy(camera.matrixWorld);
184
+ }
185
+ onSizeUpdate() {
186
+ this.uniforms.firstFrame.value = true;
187
+ this.setDirty();
188
+ }
189
+ setSize(width, height) {
190
+ super.setSize(width, height);
191
+ this.onSizeUpdate();
192
+ }
193
+ };
194
+ __decorate([
195
+ serialize(),
196
+ uniform(),
197
+ uiVector("Feedback", void 0, 1e-4)
198
+ ], TemporalAAPluginPass.prototype, "feedBack", void 0);
199
+ __decorate([uiToggle(), matDefineBool("DEBUG_VELOCITY", void 0, false, void 0, true)], TemporalAAPluginPass.prototype, "debugVelocity", void 0);
200
+ // src/plugins/buffer/VelocityBufferPlugin.ts
201
+ var _VelocityBufferPlugin;
202
+ var VelocityBufferPlugin = class VelocityBufferPlugin extends PipelinePassPlugin {
203
+ static {
204
+ _VelocityBufferPlugin = this;
205
+ }
206
+ static {
207
+ this.PluginType = "VelocityBuffer";
208
+ }
209
+ static {
210
+ this.OldPluginType = "VelocityBufferPlugin";
211
+ }
212
+ _createTarget(recreate = true) {
213
+ if (!this._viewer) return;
214
+ if (recreate) this._disposeTarget();
215
+ if (!this.target) this.target = this._viewer.renderManager.createTarget({
216
+ depthBuffer: true,
217
+ samples: 0,
218
+ type: this.bufferType,
219
+ generateMipmaps: false,
220
+ colorSpace: LinearSRGBColorSpace
221
+ });
222
+ this.texture = this.target.texture;
223
+ this.texture.name = "velocityBuffer";
224
+ if (this._pass) this._pass.target = this.target;
225
+ }
226
+ _disposeTarget() {
227
+ if (!this._viewer) return;
228
+ if (this.target) {
229
+ this._viewer.renderManager.disposeTarget(this.target);
230
+ this.target = void 0;
231
+ }
232
+ this.texture = void 0;
233
+ }
234
+ _createPass() {
235
+ this._createTarget(true);
236
+ if (!this.target) throw new Error("VelocityBufferPlugin: target not created");
237
+ this.material.userData.isGBufferMaterial = true;
238
+ const v = this._viewer;
239
+ const pass = new class extends GBufferRenderPass {
240
+ constructor(..._args) {
241
+ super(..._args);
242
+ this._firstCall = true;
243
+ }
244
+ render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) {
245
+ if (v.renderManager.frameCount > 0) return;
246
+ if (!this.enabled || !this.camera) return;
247
+ const mat = this.overrideMaterial;
248
+ mat.uniforms.currentProjectionViewMatrix.value.copy(this.camera.projectionMatrix).multiply(this.camera.matrixWorldInverse);
249
+ if (this._firstCall) {
250
+ mat.uniforms.lastProjectionViewMatrix.value.copy(mat.uniforms.currentProjectionViewMatrix.value);
251
+ this._firstCall = false;
252
+ }
253
+ super.render(renderer, writeBuffer, readBuffer, deltaTime, maskActive);
254
+ mat.uniforms.lastProjectionViewMatrix.value.copy(mat.uniforms.currentProjectionViewMatrix.value);
255
+ }
256
+ }(this.passId, this.target, this.material, new Color(.5, .5, .5), 1);
257
+ const preprocessMaterial = pass.preprocessMaterial;
258
+ pass.preprocessMaterial = (m) => {
259
+ const disabled = m.userData[_VelocityBufferPlugin.PluginType]?.disabled;
260
+ return preprocessMaterial(m, disabled === void 0 ? void 0 : !disabled);
261
+ };
262
+ pass.before = ["render"];
263
+ pass.after = [];
264
+ pass.required = ["render"];
265
+ return pass;
266
+ }
267
+ constructor(bufferType = UnsignedByteType, enabled = true, _attachToTaa = true) {
268
+ super();
269
+ this.passId = "velocityBuffer";
270
+ this.material = new SSVelocityMaterial();
271
+ this.unpackExtension = {
272
+ shaderExtender: (shader) => {
273
+ if (this.isDisabled()) return;
274
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#pragma <velocity_unpack>", "\n" + VelocityBufferPlugin_unpack_default + "\n");
275
+ },
276
+ computeCacheKey: () => this.isDisabled() ? "" : "vb",
277
+ extraUniforms: { tVelocity: () => ({ value: !this.isDisabled() ? this.target?.texture : null }) },
278
+ extraDefines: { ["HAS_VELOCITY_BUFFER"]: () => !this.isDisabled() && this.target?.texture ? 1 : void 0 },
279
+ priority: 100,
280
+ isCompatible: () => true
281
+ };
282
+ this.enabled = enabled;
283
+ this.bufferType = bufferType;
284
+ this._attachToTaa = _attachToTaa;
285
+ }
286
+ onAdded(viewer) {
287
+ super.onAdded(viewer);
288
+ viewer.forPlugin(TemporalAAPlugin, (taa) => {
289
+ this._attachToTaa && taa.pass?.material.registerMaterialExtensions([this.unpackExtension]);
290
+ }, (taa) => {
291
+ taa.pass?.material?.unregisterMaterialExtensions([this.unpackExtension]);
292
+ }, this);
293
+ }
294
+ onRemove(viewer) {
295
+ this._disposeTarget();
296
+ return super.onRemove(viewer);
297
+ }
298
+ setDirty() {
299
+ super.setDirty();
300
+ this.unpackExtension.setDirty?.();
301
+ }
302
+ _beforeRender(scene, camera, renderManager) {
303
+ if (!super._beforeRender(scene, camera, renderManager)) return false;
304
+ const pass = this.pass;
305
+ if (!pass) return false;
306
+ if (renderManager.frameCount > 0) return false;
307
+ pass.scene = scene;
308
+ pass.camera = camera;
309
+ camera.updateShaderProperties(pass.overrideMaterial);
310
+ return true;
311
+ }
312
+ };
313
+ __decorate([uiImage("Velocity Buffer", { readOnly: true })], VelocityBufferPlugin.prototype, "texture", void 0);
314
+ VelocityBufferPlugin = _VelocityBufferPlugin = __decorate([uiFolderContainer("Velocity Buffer Plugin (for TAA)")], VelocityBufferPlugin);
315
+ var SSVelocityMaterial = class extends ShaderMaterial {
316
+ constructor() {
317
+ super({
318
+ vertexShader: VelocityBufferPlugin_mat_vert_default,
319
+ fragmentShader: VelocityBufferPlugin_mat_frag_default,
320
+ uniforms: {
321
+ cameraNearFar: { value: new Vector2(.1, 1e3) },
322
+ alphaMap: { value: null },
323
+ alphaTest: { value: null },
324
+ alphaMapTransform: { value: /* @__PURE__*/ new Matrix3() },
325
+ currentProjectionViewMatrix: { value: new Matrix4() },
326
+ lastProjectionViewMatrix: { value: new Matrix4() }
327
+ },
328
+ blending: NoBlending
329
+ });
330
+ this.extraUniformsToUpload = { modelMatrixPrevious: { value: new Matrix4().identity() } };
331
+ this._previousWorldMatrices = {};
332
+ }
333
+ onBeforeRender(_r, _s, _c, _geometry, object, group) {
334
+ super.onBeforeRender(_r, _s, _c, _geometry, object, group);
335
+ const prevMatrix = this._previousWorldMatrices[object.uuid];
336
+ this.extraUniformsToUpload.modelMatrixPrevious.value.copy(prevMatrix ?? object.matrixWorld);
337
+ if (prevMatrix) prevMatrix.copy(object.matrixWorld);
338
+ else this._previousWorldMatrices[object.uuid] = object.matrixWorld.clone();
339
+ let mat = object.material;
340
+ if (Array.isArray(mat)) mat = mat[0];
341
+ this.uniforms.alphaMap.value = mat?.alphaMap ?? null;
342
+ this.uniforms.alphaTest.value = !mat || !mat.alphaTest || mat.alphaTest < 1e-7 ? .001 : mat.alphaTest;
343
+ let x = this.uniforms.alphaMap.value ? 1 : void 0;
344
+ if (x !== this.defines.USE_ALPHAMAP) {
345
+ if (x === void 0) {
346
+ delete this.defines.USE_ALPHAMAP;
347
+ delete this.defines.ALPHAMAP_UV;
348
+ } else {
349
+ this.defines.USE_ALPHAMAP = x;
350
+ this.defines.ALPHAMAP_UV = "uv";
351
+ }
352
+ this.needsUpdate = true;
353
+ }
354
+ const alphaMap = this.uniforms.alphaMap.value;
355
+ if (alphaMap) {
356
+ if (alphaMap.matrixAutoUpdate) alphaMap.updateMatrix();
357
+ this.uniforms.alphaMapTransform.value.copy(alphaMap.matrix);
358
+ }
359
+ x = mat?.userData.ALPHA_I_RGBA_PACKING ? 1 : void 0;
360
+ if (x !== this.defines.ALPHA_I_RGBA_PACKING) {
361
+ if (x === void 0) delete this.defines.ALPHA_I_RGBA_PACKING;
362
+ else this.defines.ALPHA_I_RGBA_PACKING = x;
363
+ this.needsUpdate = true;
364
+ }
365
+ this.side = mat?.side ?? DoubleSide;
366
+ }
367
+ };
368
+ // src/plugins/postprocessing/shaders/hdrBloom.glsl
369
+ var hdrBloom_default = "#include <packing>\nuniform float intensity;uniform float opacity;uniform vec2 tDiffuseSize;varying vec2 vUv;uniform float weight;\n#if PASS_STEP == 0\nuniform vec4 prefilter;vec4 Prefilter(vec4 c){\n#ifdef HAS_GBUFFER\n#if !BACKGROUND_BLOOM\nif(getDepth(vUv)>0.999){return vec4(0.0);}\n#endif\n#endif\nfloat brightness=max(c.r,max(c.g,c.b));float soft=brightness+prefilter.x*(prefilter.y-1.);soft=clamp(soft,0.,prefilter.z);soft=soft*soft*prefilter.w;float contribution=max(soft,brightness-prefilter.x);contribution/=max(brightness,0.001);return vec4(c.rgb*contribution,c.a);}\n#endif\nvec4 Sample(vec2 uv){return min(vec4(MAX_INTENSITY,MAX_INTENSITY,MAX_INTENSITY,1.),tDiffuseTexelToLinear(texture2D(tDiffuse,uv)));}vec4 SampleBox(vec2 uv,float delta){vec4 o=vec2(-delta,delta).xxyy/tDiffuseSize.xyxy;vec4 s=Sample(uv+o.xy)+Sample(uv+o.zy)+Sample(uv+o.xw)+Sample(uv+o.zw);return s*0.25;}int getBloomBit(in int number){\n#ifdef WebGL2Context\nreturn(number/4)% 2;\n#else\nreturn int(mod(floor(float(number)/4.),2.));\n#endif\n}void main(){\n#if PASS_STEP == 0\n#ifdef GBUFFER_HAS_FLAGS\nint doBloom=getBloomBit(getGBufferFlags(vUv).a);\n#else\nint doBloom=1;\n#endif\ngl_FragColor=float(doBloom)*weight*Prefilter(SampleBox(vUv,1.));gl_FragColor.a=1.;\n#elif PASS_STEP == 1\ngl_FragColor=weight*(SampleBox(vUv,1.));gl_FragColor.a=1.;\n#elif PASS_STEP == 2\ngl_FragColor=(SampleBox(vUv,0.5));gl_FragColor.a=1.;\n#elif PASS_STEP == 3\nvec4 texel=tSourceTexelToLinear(texture2D(tSource,vUv));vec4 bloom=intensity*SampleBox(vUv,0.5).rgba;float brightness=max(bloom.r,max(bloom.g,bloom.b));texel.rgb+=bloom.rgb;texel.a=min(1.,texel.a+brightness);gl_FragColor=texel;\n#elif PASS_STEP == 4\nvec4 texel=vec4(0.);texel.rgb+=intensity*SampleBox(vUv,0.5).rgb;texel.a=1.;gl_FragColor=texel;\n#endif\n#include <colorspace_fragment>\n}";
370
+ // src/plugins/postprocessing/BloomPlugin.ts
371
+ var passId$3 = "bloom";
372
+ /**
373
+ * Bloom Plugin
374
+ *
375
+ * Adds HDR Bloom post-processing effect to the scene
376
+ * @category Plugins
377
+ */
378
+ var BloomPlugin = class BloomPlugin extends PipelinePassPlugin {
379
+ static {
380
+ this.PluginType = "Bloom";
381
+ }
382
+ static {
383
+ this.OldPluginType = "BloomPlugin";
384
+ }
385
+ _createPass() {
386
+ return new BloomPluginPass(this.passId, Math.min(8, this._viewer?.renderManager.maxHDRIntensity || 8));
387
+ }
388
+ constructor(enabled = true) {
389
+ super();
390
+ this.passId = passId$3;
391
+ this.materialExtension = uiConfigMaterialExtension(this._getUiConfig.bind(this), BloomPlugin.PluginType);
392
+ this.dependencies = [GBufferPlugin];
393
+ this._onPluginAdd = (e) => {
394
+ if (e.plugin?.constructor?.PluginType !== GBufferPlugin.PluginType) return;
395
+ const gbuffer = e.plugin;
396
+ gbuffer.registerGBufferUpdater(this.constructor.PluginType, this.updateGBufferFlags.bind(this));
397
+ this._pass?.material.registerMaterialExtensions([gbuffer.unpackExtension]);
398
+ this._viewer?.removeEventListener("addPlugin", this._onPluginAdd);
399
+ };
400
+ this.uiConfig = {
401
+ type: "folder",
402
+ label: "Bloom Plugin",
403
+ onChange: this.setDirty.bind(this),
404
+ children: [...generateUiConfig(this) || []]
405
+ };
406
+ this.enabled = enabled;
407
+ }
408
+ onAdded(viewer) {
409
+ super.onAdded(viewer);
410
+ const gbuffer = viewer.getPlugin(GBufferPlugin);
411
+ if (gbuffer) {
412
+ gbuffer.registerGBufferUpdater(this.constructor.PluginType, this.updateGBufferFlags.bind(this));
413
+ this._pass.material.registerMaterialExtensions([gbuffer.unpackExtension]);
414
+ } else viewer.addEventListener("addPlugin", this._onPluginAdd);
415
+ viewer.materialManager.registerMaterialExtension(this.materialExtension);
416
+ }
417
+ onRemove(viewer) {
418
+ viewer.removeEventListener("addPlugin", this._onPluginAdd);
419
+ const gbuffer = viewer.getPlugin(GBufferPlugin);
420
+ gbuffer?.unregisterGBufferUpdater(this.constructor.PluginType);
421
+ gbuffer && this._pass?.material.unregisterMaterialExtensions([gbuffer.unpackExtension]);
422
+ viewer.materialManager.unregisterMaterialExtension(this.materialExtension);
423
+ super.onRemove(viewer);
424
+ }
425
+ updateGBufferFlags(data, c) {
426
+ if (!c.material || !c.material.userData) return;
427
+ const x = c.material.userData[BloomPlugin.PluginType]?.enable === false || c.material.userData.pluginsDisabled ? 0 : 1;
428
+ data.w = updateBit(data.w, 2, x);
429
+ }
430
+ static AddBloomData(material, params, setDirty = true) {
431
+ const ud = material?.userData;
432
+ if (!ud) return null;
433
+ if (!ud[BloomPlugin.PluginType]) ud[BloomPlugin.PluginType] = {};
434
+ const data = ud[BloomPlugin.PluginType];
435
+ data.enable = true;
436
+ params && Object.assign(data, params);
437
+ if (setDirty && material.setDirty) material.setDirty();
438
+ return data;
439
+ }
440
+ /**
441
+ * This uiConfig is added to each material by extension
442
+ * @param material
443
+ * @private
444
+ */
445
+ _getUiConfig(material) {
446
+ const config = {
447
+ type: "folder",
448
+ label: "Bloom",
449
+ children: [{
450
+ type: "checkbox",
451
+ label: "Enabled",
452
+ get value() {
453
+ return material.userData[BloomPlugin.PluginType]?.enable ?? true;
454
+ },
455
+ set value(v) {
456
+ let data = material.userData[BloomPlugin.PluginType];
457
+ if (v === data?.enable) return;
458
+ if (!data) data = BloomPlugin.AddBloomData(material, void 0, false);
459
+ data.enable = v;
460
+ material.setDirty();
461
+ config.uiRefresh?.(true, "postFrame");
462
+ },
463
+ onChange: this.setDirty
464
+ }]
465
+ };
466
+ return config;
467
+ }
468
+ };
469
+ __decorate([uiConfig(void 0, { unwrapContents: true })], BloomPlugin.prototype, "_pass", void 0);
470
+ var BloomPluginPass = class BloomPluginPass extends ExtendedShaderPass {
471
+ constructor(pid, maxIntensity = 16) {
472
+ super({
473
+ vertexShader: CopyShader.vertexShader,
474
+ defines: {
475
+ ["PASS_STEP"]: 1,
476
+ ["MAX_INTENSITY"]: Math.min(maxIntensity, 16)
477
+ },
478
+ uniforms: {
479
+ tSource: { value: null },
480
+ tDiffuse: { value: null },
481
+ opacity: { value: 1 },
482
+ tDiffuseSize: { value: new Vector2() },
483
+ weight: { value: 1 }
484
+ },
485
+ fragmentShader: hdrBloom_default
486
+ }, "tDiffuse", "tSource");
487
+ this.uiConfig = void 0;
488
+ this.before = ["screen"];
489
+ this.after = ["render", "progressive"];
490
+ this.required = ["render"];
491
+ this.prefilter = new Vector4(2, .5, 0, 0);
492
+ this.threshold = 2;
493
+ this.softThreshold = .5;
494
+ this.intensity = .2;
495
+ this.backgroundBloom = false;
496
+ this.bloomIterations = 4;
497
+ this._currentIterations = 0;
498
+ this.radius = .6;
499
+ this.power = 1;
500
+ this.bloomDebug = false;
501
+ this._weights = [];
502
+ this.passId = pid;
503
+ this._updateWeights = this._updateWeights.bind(this);
504
+ this._thresholdsUpdated = this._thresholdsUpdated.bind(this);
505
+ this._updateWeights();
506
+ this._thresholdsUpdated();
507
+ this.clear = true;
508
+ }
509
+ _thresholdsUpdated() {
510
+ this.prefilter.x = this.threshold;
511
+ this.prefilter.y = this.softThreshold;
512
+ this.prefilter.z = 2 * this.prefilter.x * this.prefilter.y;
513
+ this.prefilter.w = this.uniforms?.prefilter ? .125 / (this.uniforms.prefilter.value.z + 1e-5) : 0;
514
+ this.setDirty();
515
+ }
516
+ render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) {
517
+ const renderManager = renderer.renderManager;
518
+ this.material.defines.PASS_STEP = 0;
519
+ this.clear = true;
520
+ this.needsSwap = false;
521
+ const source = readBuffer;
522
+ if (!source) {
523
+ console.warn("BloomPluginPass: No source to read from");
524
+ return;
525
+ }
526
+ this.needsSwap = true;
527
+ let sizeMultiplier = .5;
528
+ let width = source.width * sizeMultiplier;
529
+ let height = source.height * sizeMultiplier;
530
+ const textures = [];
531
+ let currentDestination = renderManager.getTempTarget({
532
+ sizeMultiplier: 1,
533
+ type: HalfFloatType
534
+ });
535
+ textures.push(currentDestination);
536
+ let currentSource = source;
537
+ this.material.needsUpdate = true;
538
+ this.material.uniforms.weight.value = this._weights[0];
539
+ super.render(renderer, currentDestination, currentSource, deltaTime, maskActive);
540
+ currentSource = currentDestination;
541
+ const ci = this._currentIterations;
542
+ let i = 1;
543
+ const iter = Math.max(2, this.bloomIterations);
544
+ for (; i < iter; i++) {
545
+ width /= 2;
546
+ height /= 2;
547
+ sizeMultiplier /= 2;
548
+ if (height < 2 || width < 2) break;
549
+ currentDestination = renderManager.getTempTarget({
550
+ sizeMultiplier,
551
+ type: HalfFloatType
552
+ });
553
+ textures.push(currentDestination);
554
+ this.material.defines.PASS_STEP = 1;
555
+ let modifiedWeight = this._weights[i];
556
+ modifiedWeight = this._weights[i - 1] !== 0 ? this._weights[i] / this._weights[i - 1] : this._weights[i];
557
+ this.material.uniforms.weight.value = modifiedWeight;
558
+ this.material.needsUpdate = true;
559
+ super.render(renderer, currentDestination, currentSource, deltaTime, maskActive);
560
+ currentSource = currentDestination;
561
+ this._currentIterations = i + 1;
562
+ }
563
+ if (ci !== this._currentIterations) this._updateWeights(false);
564
+ this.clear = false;
565
+ const oldAutoClear = renderer.autoClear;
566
+ renderer.autoClear = false;
567
+ for (i -= 2; i >= 0; i--) {
568
+ currentDestination = textures[i];
569
+ textures[i] = void 0;
570
+ this.material.defines.PASS_STEP = 2;
571
+ this.material.transparent = true;
572
+ this.material.blending = AdditiveBlending;
573
+ this.material.needsUpdate = true;
574
+ renderer.autoClear = false;
575
+ super.render(renderer, currentDestination, currentSource, deltaTime, maskActive);
576
+ this.material.blending = NoBlending;
577
+ renderManager.releaseTempTarget(currentSource);
578
+ currentSource = currentDestination;
579
+ }
580
+ this.clear = true;
581
+ renderer.autoClear = oldAutoClear;
582
+ renderer.autoClear = true;
583
+ if (this.bloomDebug) {
584
+ this.material.defines.PASS_STEP = 4;
585
+ this.material.needsUpdate = true;
586
+ super.render(renderer, writeBuffer, currentSource, deltaTime, maskActive);
587
+ } else {
588
+ this.uniforms.tSource.value = source.texture;
589
+ this.material.defines.PASS_STEP = 3;
590
+ this.material.needsUpdate = true;
591
+ super.render(renderer, writeBuffer, currentSource, deltaTime, maskActive);
592
+ this.uniforms.tSource.value = null;
593
+ }
594
+ renderManager.releaseTempTarget(currentSource);
595
+ }
596
+ _updateWeights(setDirty = true) {
597
+ if (!this._weights) return;
598
+ const radius = Math.max(Math.min(this.radius, 1), 0);
599
+ const iter = Math.max(2, this._currentIterations || this.bloomIterations);
600
+ const delta = 1 / (iter - 1);
601
+ for (let i = 0; i < iter; i++) {
602
+ let f = i * delta + .1;
603
+ let oneMinusF = 1.2 - f;
604
+ f = Math.pow(f, this.power);
605
+ oneMinusF = Math.pow(oneMinusF, this.power);
606
+ this._weights[i] = oneMinusF * (1 - radius) + f * radius;
607
+ }
608
+ if (setDirty !== false) this.setDirty();
609
+ }
610
+ };
611
+ __decorate([uniform()], BloomPluginPass.prototype, "prefilter", void 0);
612
+ __decorate([
613
+ uiSlider("Threshold", [0, 2]),
614
+ onChange(BloomPluginPass.prototype._thresholdsUpdated),
615
+ serialize()
616
+ ], BloomPluginPass.prototype, "threshold", void 0);
617
+ __decorate([
618
+ uiSlider("Soft Threshold", [0, 1]),
619
+ onChange(BloomPluginPass.prototype._thresholdsUpdated),
620
+ serialize()
621
+ ], BloomPluginPass.prototype, "softThreshold", void 0);
622
+ __decorate([
623
+ uiSlider("Intensity", [0, 3]),
624
+ serialize(),
625
+ uniform({ onChange: BloomPluginPass.prototype.setDirty })
626
+ ], BloomPluginPass.prototype, "intensity", void 0);
627
+ __decorate([
628
+ uiToggle("Background Bloom"),
629
+ serialize(),
630
+ matDefineBool("BACKGROUND_BLOOM", void 0, void 0, BloomPluginPass.prototype.setDirty)
631
+ ], BloomPluginPass.prototype, "backgroundBloom", void 0);
632
+ __decorate([
633
+ uiSlider("Iterations", [2, 7], 1),
634
+ onChange2(BloomPluginPass.prototype._updateWeights),
635
+ serialize()
636
+ ], BloomPluginPass.prototype, "bloomIterations", void 0);
637
+ __decorate([
638
+ uiSlider("Radius", [0, 1], .01),
639
+ onChange2(BloomPluginPass.prototype._updateWeights),
640
+ serialize()
641
+ ], BloomPluginPass.prototype, "radius", void 0);
642
+ __decorate([
643
+ uiSlider("Power", [.2, 10], .01),
644
+ onChange2(BloomPluginPass.prototype._updateWeights),
645
+ serialize()
646
+ ], BloomPluginPass.prototype, "power", void 0);
647
+ __decorate([uiToggle("Debug"), onChange2(BloomPluginPass.prototype.setDirty)], BloomPluginPass.prototype, "bloomDebug", void 0);
648
+ BloomPluginPass = __decorate([uiFolderContainer("Bloom Pass")], BloomPluginPass);
649
+ // src/plugins/postprocessing/shaders/dofCombine.glsl
650
+ var dofCombine_default = "#include <common>\n#include <packing>\nvarying vec2 vUv;uniform vec2 cocTextureSize;uniform vec2 nearFarBlurScale;uniform vec2 cameraNearFar;uniform vec2 focalDepthRange;uniform vec2 crossCenter;uniform float crossRadius;uniform float crossAlpha;uniform vec3 crossColor;float smoothBoundary(float d,float smooothFactor){smooothFactor*=0.5;float value=smoothstep(-smooothFactor,smooothFactor,d);return value;}float circle(vec2 p,float r){return min((length(p)-r),-(length(p)-r-0.01));}float computeCoc(){float depth=getDepth(vUv);if(depth>1.0-0.01)return max(nearFarBlurScale.x,nearFarBlurScale.y);depth=mix(cameraNearFar.x,cameraNearFar.y,depth);float coc=(depth-focalDepthRange.x)/focalDepthRange.y;coc=clamp(coc,-1.,1.);return(coc>0.0 ? coc*nearFarBlurScale.y : coc*nearFarBlurScale.x);}void main(){vec4 blur=blurTextureTexelToLinear(texture2D(blurTexture,vUv));float scale=0.5;blur+=blurTextureTexelToLinear(texture2D(blurTexture,vUv+scale*vec2(1.0,1.0)/cocTextureSize));blur+=blurTextureTexelToLinear(texture2D(blurTexture,vUv+scale*vec2(-1.0,1.0)/cocTextureSize));blur+=blurTextureTexelToLinear(texture2D(blurTexture,vUv+scale*vec2(-1.0,-1.0)/cocTextureSize));blur+=blurTextureTexelToLinear(texture2D(blurTexture,vUv+scale*vec2(1.0,-1.0)/cocTextureSize));blur/=5.0;vec2 uvNearest=(floor(vUv*cocTextureSize)+0.5)/cocTextureSize;float coc=abs(min(2.*cocTextureTexelToLinear(texture2D(cocTexture,uvNearest)).a-1.,computeCoc()));float cocLower=0.005;float cocHigher=0.3;vec4 outColor=vec4(mix(colorTextureTexelToLinear(texture2D(colorTexture,vUv)).rgb,blur.rgb,smoothstep(cocLower,cocHigher,coc)),1.0);vec2 d=vUv-crossCenter;if(length(d)>crossRadius+0.05){float dist=circle(d,crossRadius);gl_FragColor=outColor;}else{d.x*=cocTextureSize.x/cocTextureSize.y;float dist=circle(d,crossRadius);dist=smoothBoundary(dist,2.*fwidth(dist));vec4 color=outColor;vec3 dofCircleColor=mix(crossColor,color.rgb,1.-crossAlpha);gl_FragColor=vec4(mix(color.rgb,dofCircleColor,dist),color.a);}\n#include <colorspace_fragment>\n}";
651
+ // src/plugins/postprocessing/shaders/dofPoissonBox.glsl
652
+ var dofPoissonBox_default = "#include <randomHelpers>\n#include <common>\nvarying vec2 vUv;uniform vec2 colorTextureSize;uniform float blurRadius;\n#ifndef D_frameCount\n#define D_frameCount\nuniform float frameCount;\n#endif\nvec4 CircularBlur(){vec4 color=colorTextureTexelToLinear(texture2D(colorTexture,vUv));\n#ifdef DOF_MODE\nfloat blurDist=blurRadius*(2.*color.a-1.);\n#else\nfloat blurDist=blurRadius*color.a;\n#endif\nfloat rnd=PI2*random3(vec3(vUv,frameCount*0.1));float costheta=cos(rnd);float sintheta=sin(rnd);vec4 rotationMatrix=vec4(costheta,-sintheta,sintheta,costheta);vec3 colorSum=vec3(0.0);float weightSum=0.001;vec2 ofs;vec4 sampleColor;setPds();\n#pragma unroll_loop_start\nfor(int i=0;i<16;i++){ofs=poisson_disk_samples[UNROLLED_LOOP_INDEX];ofs=vec2(dot(ofs,rotationMatrix.xy),dot(ofs,rotationMatrix.zw));sampleColor=colorTextureTexelToLinear(texture2D(colorTexture,vUv+blurDist*ofs/colorTextureSize.xy));\n#ifdef DOF_MODE\nsampleColor.a=abs(sampleColor.a*2.0-1.0);sampleColor.a*=sampleColor.a*sampleColor.a;\n#endif\ncolorSum+=sampleColor.rgb*sampleColor.a;weightSum+=sampleColor.a;}\n#pragma unroll_loop_end\ncolorSum/=weightSum;return vec4(min(vec3(72.),max(vec3(0.),colorSum)),1.0);}void main(){gl_FragColor=CircularBlur();\n#include <colorspace_fragment>\n}";
653
+ // src/plugins/postprocessing/shaders/poissonDiskSamples.glsl
654
+ var poissonDiskSamples_default$1 = "vec2 poisson_disk_samples[16];void setPds(){poisson_disk_samples[0]=vec2(-0.399691779231,0.728591545584);poisson_disk_samples[1]=vec2(-0.48622557676,-0.84016533712);poisson_disk_samples[2]=vec2(0.770309468987,-0.24906070432);poisson_disk_samples[3]=vec2(0.556596796154,0.820359876432);poisson_disk_samples[4]=vec2(-0.933902004071,0.0600539051593);poisson_disk_samples[5]=vec2(0.330144964342,0.207477293384);poisson_disk_samples[6]=vec2(0.289013230975,-0.686749271417);poisson_disk_samples[7]=vec2(-0.0832470893559,-0.187351643125);poisson_disk_samples[8]=vec2(-0.296314525615,0.254474834305);poisson_disk_samples[9]=vec2(-0.850977666059,0.484642744689);poisson_disk_samples[10]=vec2(0.829287915319,0.2345063545);poisson_disk_samples[11]=vec2(-0.773042143899,-0.543741521254);poisson_disk_samples[12]=vec2(0.0561133030864,0.928419742597);poisson_disk_samples[13]=vec2(-0.205799249508,-0.562072714492);poisson_disk_samples[14]=vec2(-0.526991665882,-0.193690188118);poisson_disk_samples[15]=vec2(-0.051789270667,-0.935374050821);}";
655
+ // src/plugins/postprocessing/shaders/dofComputeCoC.glsl
656
+ var dofComputeCoC_default = "#include <common>\n#include <packing>\nvarying vec2 vUv;uniform vec2 nearFarBlurScale;uniform vec2 cameraNearFar;uniform vec2 focalDepthRange;float computeCoc(){float depth=getDepth(vUv);if(depth==1.0)return max(nearFarBlurScale.x,nearFarBlurScale.y);depth=mix(cameraNearFar.x,cameraNearFar.y,depth);float coc=(depth-focalDepthRange.x)/focalDepthRange.y;coc=clamp(coc,-1.,1.);return(coc>0.0 ? coc*nearFarBlurScale.y : coc*nearFarBlurScale.x);}void main(){gl_FragColor=vec4(colorTextureTexelToLinear(texture2D(colorTexture,vUv)).rgb,0.5*computeCoc()+0.5);\n#include <colorspace_fragment>\n}";
657
+ // src/plugins/postprocessing/shaders/dofExpandCoC.glsl
658
+ var dofExpandCoC_default = "#include <common>\n#include <gbuffer_unpack>\nvarying vec2 vUv;uniform vec2 colorTextureSize;uniform vec2 direction;uniform vec2 nearFarBlurScale;const float MAXIMUM_BLUR_SIZE=4.0;float expandNear(const in vec2 offset,const in bool isBackground){float coc=0.0;vec2 sampleOffsets=MAXIMUM_BLUR_SIZE*offset/5.0;float coc0=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv)).a-1.;float coc1=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-5.0*sampleOffsets)).a-1.;float coc2=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-4.0*sampleOffsets)).a-1.;float coc3=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-3.0*sampleOffsets)).a-1.;float coc4=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-2.0*sampleOffsets)).a-1.;float coc5=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-1.0*sampleOffsets)).a-1.;float coc6=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+1.0*sampleOffsets)).a-1.;float coc7=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+2.0*sampleOffsets)).a-1.;float coc8=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+3.0*sampleOffsets)).a-1.;float coc9=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+4.0*sampleOffsets)).a-1.;float coc10=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+5.0*sampleOffsets)).a-1.;if(isBackground){coc=abs(coc0)*0.095474+(abs(coc1)+abs(coc10))*0.084264+(abs(coc2)+abs(coc9))*0.088139+(abs(coc3)+abs(coc8))*0.091276+(abs(coc4)+abs(coc7))*0.093585+(abs(coc5)+abs(coc6))*0.094998;}else{coc=min(coc0,0.0);coc=min(coc1*0.3,coc);coc=min(coc2*0.5,coc);coc=min(coc3*0.75,coc);coc=min(coc4*0.8,coc);coc=min(coc5*0.95,coc);coc=min(coc6*0.95,coc);coc=min(coc7*0.8,coc);coc=min(coc8*0.75,coc);coc=min(coc9*0.5,coc);coc=min(coc10*0.3,coc);if(abs(coc0)>abs(coc))coc=coc0;}return coc;}void main(){vec2 offset=2.*direction/colorTextureSize;bool isBackground=getDepth(vUv)>1.0-0.001;float coc=expandNear(offset,isBackground);gl_FragColor=vec4(colorTextureTexelToLinear(texture2D(colorTexture,vUv)).rgb,0.5*coc+0.5);\n#include <colorspace_fragment>\n}";
659
+ // src/plugins/postprocessing/DepthOfFieldPlugin.ts
660
+ var passId$2 = "depthOfField";
661
+ /**
662
+ * Depth Of Field Plugin
663
+ *
664
+ * Adds a depth of field effect with configurable focal point.
665
+ * @category Plugins
666
+ */
667
+ var DepthOfFieldPlugin = class extends PipelinePassPlugin {
668
+ static {
669
+ this.PluginType = "DepthOfField";
670
+ }
671
+ static {
672
+ this.OldPluginType = "DepthOfFieldPlugin";
673
+ }
674
+ get _frameFadeTime() {
675
+ return this.crossFadeTime * 2.5;
676
+ }
677
+ constructor(enabled = true, enableEdit = false) {
678
+ super();
679
+ this.passId = passId$2;
680
+ this.enableEdit = false;
681
+ this._focalPointHit = new Vector3(0, 0, 0);
682
+ this.crossFadeTime = 200;
683
+ this._focalPointHitTime = 0;
684
+ this.dependencies = [GBufferPlugin];
685
+ this._onPluginAdd = (e) => {
686
+ const plugin = e.plugin;
687
+ if (!plugin) return;
688
+ if (plugin.constructor?.PluginType === GBufferPlugin.PluginType) {
689
+ const gbuffer = plugin;
690
+ this._pass?.material.registerMaterialExtensions([gbuffer.unpackExtension]);
691
+ this._pass?.computeCocMaterial.registerMaterialExtensions([gbuffer.unpackExtension]);
692
+ this._pass?.expandCocMaterial.registerMaterialExtensions([gbuffer.unpackExtension]);
693
+ }
694
+ if (plugin.constructor?.PluginType === PickingPlugin.PluginType) plugin.addEventListener("hitObject", this._onObjectHit);
695
+ };
696
+ this._onPluginRemove = (e) => {
697
+ const plugin = e.plugin;
698
+ if (!plugin) return;
699
+ if (plugin.constructor?.PluginType === GBufferPlugin.PluginType) {
700
+ const gbuffer = e.plugin;
701
+ this._pass?.material.unregisterMaterialExtensions([gbuffer.unpackExtension]);
702
+ this._pass?.computeCocMaterial.unregisterMaterialExtensions([gbuffer.unpackExtension]);
703
+ this._pass?.expandCocMaterial.unregisterMaterialExtensions([gbuffer.unpackExtension]);
704
+ }
705
+ if (plugin.constructor?.PluginType === PickingPlugin.PluginType) e.plugin.removeEventListener("hitObject", this._onObjectHit);
706
+ };
707
+ this.uiConfig = {
708
+ type: "folder",
709
+ label: "DepthOfField",
710
+ onChange: this.setDirty.bind(this),
711
+ children: [...generateUiConfig(this) || [], () => this._pass?.uiConfig]
712
+ };
713
+ this._tempVec = new Vector3();
714
+ this.enabled = enabled;
715
+ this.enableEdit = enableEdit;
716
+ this._onObjectHit = this._onObjectHit.bind(this);
717
+ this.setDirty = this.setDirty.bind(this);
718
+ }
719
+ setFocalPoint(p, fade = true, showGizmo = false) {
720
+ this._focalPointHit.copy(p);
721
+ if (fade) this._viewer?.getPlugin("FrameFadePlugin")?.startTransition(this._frameFadeTime);
722
+ if (showGizmo) this._focalPointHitTime = now();
723
+ this.setDirty();
724
+ }
725
+ getFocalPoint() {
726
+ return this._focalPointHit;
727
+ }
728
+ _onObjectHit(e) {
729
+ if (!this._pass || !e.intersects.intersect || this.isDisabled() || !this.enableEdit) return;
730
+ this._focalPointHit.copy(e.intersects.intersect.point);
731
+ this._focalPointHitTime = e.time;
732
+ e.intersects.selectedObject = null;
733
+ this._viewer?.getPlugin(FrameFadePlugin)?.startTransition(this._frameFadeTime);
734
+ this.setDirty();
735
+ }
736
+ _createPass() {
737
+ return new DepthOfFieldPluginPass(this.passId);
738
+ }
739
+ onAdded(viewer) {
740
+ super.onAdded(viewer);
741
+ viewer.addEventListener("addPlugin", this._onPluginAdd);
742
+ viewer.addEventListener("removePlugin", this._onPluginRemove);
743
+ this._onPluginAdd({ plugin: viewer.getPlugin(GBufferPlugin) });
744
+ this._onPluginAdd({ plugin: viewer.getPlugin(PickingPlugin) });
745
+ }
746
+ onRemove(viewer) {
747
+ viewer.removeEventListener("addPlugin", this._onPluginAdd);
748
+ viewer.removeEventListener("removePlugin", this._onPluginRemove);
749
+ this._onPluginRemove({ plugin: viewer.getPlugin(GBufferPlugin) });
750
+ this._onPluginRemove({ plugin: viewer.getPlugin(PickingPlugin) });
751
+ super.onRemove(viewer);
752
+ }
753
+ _beforeRender(scene, camera, renderManager) {
754
+ if (!super._beforeRender(scene, camera, renderManager)) return false;
755
+ const pass = this.pass;
756
+ if (!pass) return false;
757
+ if (pass.dofBlurMaterial.uniforms.frameCount) renderManager?.updateShaderProperties(pass.dofBlurMaterial);
758
+ const cam = camera;
759
+ if (!cam) return false;
760
+ cam.updateMatrixWorld(true);
761
+ cam.updateShaderProperties(pass.material);
762
+ cam.getWorldPosition(this._tempVec);
763
+ this._tempVec.subVectors(this._focalPointHit, this._tempVec);
764
+ pass.focalDepthRange.x = this._tempVec.length();
765
+ pass.focalDepthRange.x *= cam.getWorldDirection(new Vector3()).dot(this._tempVec.normalize());
766
+ let crossAlpha = (now() - this._focalPointHitTime) / this.crossFadeTime;
767
+ crossAlpha = 1 - Math.min(1, Math.max(0, crossAlpha));
768
+ if (Math.abs(crossAlpha - pass.crossAlpha) > .01) {
769
+ pass.crossAlpha = crossAlpha;
770
+ this.setDirty();
771
+ }
772
+ if (crossAlpha > 0) {
773
+ const projectedPoint = this._tempVec.copy(this._focalPointHit).project(cam).addScalar(1).divideScalar(2);
774
+ pass.crossCenter.set(projectedPoint.x, projectedPoint.y);
775
+ pass.computeCocMaterial.uniformsNeedUpdate = true;
776
+ pass.expandCocMaterial.uniformsNeedUpdate = true;
777
+ }
778
+ return true;
779
+ }
780
+ };
781
+ __decorate([serialize(), uiToggle()], DepthOfFieldPlugin.prototype, "enableEdit", void 0);
782
+ __decorate([serialize("focalPoint")], DepthOfFieldPlugin.prototype, "_focalPointHit", void 0);
783
+ __decorate([serialize()], DepthOfFieldPlugin.prototype, "crossFadeTime", void 0);
784
+ var dofBlurMaterialPoisson = new ExtendedShaderMaterial({
785
+ uniforms: {
786
+ colorTexture: { value: null },
787
+ colorTextureSize: { value: new Vector2() },
788
+ direction: { value: new Vector2() },
789
+ frameCount: { value: 0 },
790
+ blurRadius: { value: 16 }
791
+ },
792
+ vertexShader: shaderUtils.defaultVertex,
793
+ fragmentShader: poissonDiskSamples_default$1 + "\n" + dofPoissonBox_default,
794
+ defines: { ["DOF_MODE"]: 1 }
795
+ }, ["colorTexture"]);
796
+ var DepthOfFieldPluginPass = class DepthOfFieldPluginPass extends ExtendedShaderPass {
797
+ constructor(pid) {
798
+ super({
799
+ uniforms: {
800
+ colorTexture: { value: null },
801
+ blurTexture: { value: null },
802
+ cocTexture: { value: null },
803
+ cocTextureSize: { value: new Vector2() },
804
+ cameraNearFar: { value: new Vector2() }
805
+ },
806
+ vertexShader: shaderUtils.defaultVertex,
807
+ fragmentShader: dofCombine_default
808
+ }, "colorTexture", "cocTexture", "blurTexture");
809
+ this.uiConfig = void 0;
810
+ this.before = ["progressive", "screen"];
811
+ this.after = ["render"];
812
+ this.required = ["render"];
813
+ this.dofBlurMaterial = dofBlurMaterialPoisson;
814
+ this.nearFarBlurScale = new Vector2(.25, .25);
815
+ this.focalDepthRange = new Vector2(.5, 1.5);
816
+ this.crossCenter = new Vector2(.5, .5);
817
+ this.crossRadius = .04;
818
+ this.crossAlpha = 1;
819
+ this.crossColor = new Color(16750848);
820
+ this.passId = pid;
821
+ this.computeCocMaterial = new ExtendedShaderMaterial({
822
+ uniforms: {
823
+ colorTexture: { value: null },
824
+ cameraNearFar: this.uniforms.cameraNearFar,
825
+ nearFarBlurScale: this.uniforms.nearFarBlurScale,
826
+ focalDepthRange: this.uniforms.focalDepthRange
827
+ },
828
+ vertexShader: shaderUtils.defaultVertex,
829
+ fragmentShader: dofComputeCoC_default
830
+ }, ["colorTexture"]);
831
+ this.expandCocMaterial = new ExtendedShaderMaterial({
832
+ uniforms: {
833
+ colorTexture: { value: null },
834
+ colorTextureSize: { value: new Vector2() },
835
+ direction: { value: new Vector2() },
836
+ nearFarBlurScale: this.uniforms.nearFarBlurScale
837
+ },
838
+ vertexShader: shaderUtils.defaultVertex,
839
+ fragmentShader: dofExpandCoC_default
840
+ }, ["colorTexture"]);
841
+ }
842
+ render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) {
843
+ if (!this.enabled) return;
844
+ if (!readBuffer) {
845
+ console.error("DepthOfFieldPluginPass: No readBuffer");
846
+ return;
847
+ }
848
+ const renderManager = renderer.renderManager;
849
+ const halfPars = {
850
+ minFilter: NearestFilter,
851
+ magFilter: NearestFilter,
852
+ type: HalfFloatType,
853
+ colorSpace: LinearSRGBColorSpace,
854
+ sizeMultiplier: .5,
855
+ format: RGBAFormat,
856
+ depthBuffer: false,
857
+ generateMipmaps: false
858
+ };
859
+ const cocRt = renderManager.getTempTarget(halfPars);
860
+ const renderTargetBlurTemp = renderManager.getTempTarget(halfPars);
861
+ this.computeCocMaterial.uniforms.colorTexture.value = readBuffer.texture;
862
+ renderManager.blit(cocRt, { material: this.computeCocMaterial });
863
+ this.expandCocMaterial.uniforms.colorTexture.value = cocRt.texture;
864
+ this.expandCocMaterial.uniforms.direction.value.set(1, 0);
865
+ renderManager.blit(renderTargetBlurTemp, { material: this.expandCocMaterial });
866
+ this.expandCocMaterial.uniforms.colorTexture.value = renderTargetBlurTemp.texture;
867
+ this.expandCocMaterial.uniforms.direction.value.set(0, 1);
868
+ renderManager.blit(cocRt, { material: this.expandCocMaterial });
869
+ if (this.dofBlurMaterial.uniforms.frameCount) {
870
+ this.dofBlurMaterial.uniforms.colorTexture.value = cocRt.texture;
871
+ renderManager.blit(renderTargetBlurTemp, { material: this.dofBlurMaterial });
872
+ } else {
873
+ const renderTargetBlurTemp2 = renderManager.getTempTarget(halfPars);
874
+ this.dofBlurMaterial.uniforms.cocTexture.value = cocRt.texture;
875
+ this.dofBlurMaterial.uniforms.colorTexture.value = cocRt.texture;
876
+ this.dofBlurMaterial.uniforms.direction.value.set(1, 0);
877
+ renderManager.blit(renderTargetBlurTemp2, { material: this.dofBlurMaterial });
878
+ this.dofBlurMaterial.uniforms.colorTexture.value = renderTargetBlurTemp2.texture;
879
+ this.dofBlurMaterial.uniforms.direction.value.set(0, 1);
880
+ renderManager.blit(renderTargetBlurTemp, { material: this.dofBlurMaterial });
881
+ renderManager.releaseTempTarget(renderTargetBlurTemp2);
882
+ }
883
+ this.material.uniforms.blurTexture.value = renderTargetBlurTemp.texture;
884
+ this.material.uniforms.cocTexture.value = cocRt.texture;
885
+ super.render(renderer, writeBuffer, readBuffer, deltaTime, maskActive);
886
+ renderManager.releaseTempTarget(cocRt);
887
+ renderManager.releaseTempTarget(renderTargetBlurTemp);
888
+ }
889
+ };
890
+ __decorate([bindToValue({
891
+ obj: "focalDepthRange",
892
+ key: "y",
893
+ onChange: "setDirty"
894
+ }), uiSlider("Depth Range", [.25, 3])], DepthOfFieldPluginPass.prototype, "depthRange", void 0);
895
+ __decorate([bindToValue({
896
+ obj: "nearFarBlurScale",
897
+ key: "x",
898
+ onChange: "setDirty"
899
+ }), uiSlider("Near Blur Scale", [0, 1])], DepthOfFieldPluginPass.prototype, "nearBlurScale", void 0);
900
+ __decorate([bindToValue({
901
+ obj: "nearFarBlurScale",
902
+ key: "y",
903
+ onChange: "setDirty"
904
+ }), uiSlider("Far Blur Scale", [0, 1])], DepthOfFieldPluginPass.prototype, "farBlurScale", void 0);
905
+ __decorate([serialize(), uniform()], DepthOfFieldPluginPass.prototype, "nearFarBlurScale", void 0);
906
+ __decorate([serialize(), uniform()], DepthOfFieldPluginPass.prototype, "focalDepthRange", void 0);
907
+ __decorate([uniform()], DepthOfFieldPluginPass.prototype, "crossCenter", void 0);
908
+ __decorate([uniform()], DepthOfFieldPluginPass.prototype, "crossRadius", void 0);
909
+ __decorate([uniform()], DepthOfFieldPluginPass.prototype, "crossAlpha", void 0);
910
+ __decorate([uniform()], DepthOfFieldPluginPass.prototype, "crossColor", void 0);
911
+ DepthOfFieldPluginPass = __decorate([uiFolderContainer("DepthOfField Pass")], DepthOfFieldPluginPass);
912
+ // src/plugins/postprocessing/shaders/ssrt.glsl
913
+ var ssrt_default = "#ifndef SSRT_PARS_SNIP\n#define SSRT_PARS_SNIP\n#define pow2(a) a*a\nfloat getDepth2(const in vec2 uv,const in float lod){float viewDepth=getDepth(uv);return depthToViewZ(viewDepth);}\n#define LOD_DEPTH 1.0\n#define LOD_COLOR 5.0\nvoid _traceRay(in vec4 ray_origin,in vec4 ray_dir,in float tolerance,inout vec3 state,in int loopMax,in float iStepCount){vec4 sample_uv;float d,hit;float dLod=0.;\n#pragma unroll_loop_start\nfor(int i=0;i<8;i++){if(UNROLLED_LOOP_INDEX<loopMax){sample_uv=ray_origin+ray_dir*state.y;d=getDepth2(sample_uv.xy,dLod);d=sample_uv.z/sample_uv.w-d;if(abs(d+tolerance)<tolerance){hit=clamp(state.x/(state.x-d),0.,1.)-1.;hit=(state.y+hit*iStepCount);state.z=min(state.z,hit);}state.x=d;state.y+=1.*iStepCount;}}\n#pragma unroll_loop_end\n}vec3 traceRay(in vec3 ray_origin_view,in vec3 ray_dir_view,in float tolerance,inout vec3 state,in int _STEP_COUNT){vec4 sample_uv;vec4 ray_origin=viewToScreen3(ray_origin_view);vec3 ray_end_view=ray_origin_view+ray_dir_view;vec4 ray_dir=viewToScreen3(ray_end_view);vec2 clamp_end=clamp(ray_dir.xy,vec2(0.),vec2(1.));vec2 correction=abs(ray_dir.xy-clamp_end);correction=(step(0.01,correction)*correction/(abs(clamp_end-ray_origin.xy)+0.01))+1.;correction.x=1./min(max(correction.y,correction.x),10.);ray_dir=ray_dir-ray_origin;ray_dir.xyw*=correction.x;float iStepCount=1./float(_STEP_COUNT);tolerance*=0.125;_traceRay(ray_origin,ray_dir,tolerance,state,_STEP_COUNT,iStepCount);if(_STEP_COUNT>8&&state.z>0.98)_traceRay(ray_origin,ray_dir,tolerance,state,_STEP_COUNT-8,iStepCount);if(_STEP_COUNT>15&&state.z>0.98)_traceRay(ray_origin,ray_dir,tolerance,state,_STEP_COUNT-16,iStepCount);if(_STEP_COUNT>23&&state.z>0.98)_traceRay(ray_origin,ray_dir,tolerance,state,_STEP_COUNT-16,iStepCount);sample_uv=ray_origin+ray_dir*state.z;sample_uv.z/=sample_uv.w;state.z=state.z<0.999 ? state.z : 9999999.;return sample_uv.xyz;}/**for ray clippinga=ray_originb=ray_endc=clamp(b)x=c.y-a.yy=b.y-c.y(c.y-a.y)/(b.y-c.y)=m/(l-m)m/(l-m)=km=kl-kmm=kl/(1+k)((c-a)/(b-c))/(1+(c-a)/(b-c))x/(y*(1+x/y))x/(y+x)1/(y/x+1)x/(y+yx)1/(y/x+y)ray scale=k/(1+k)1/(1/k+1)=1/((b-c)/(c-a)+1)**/\n#endif\n";
914
+ // src/plugins/postprocessing/SSContactShadowsPlugin.ts
915
+ var _SSContactShadowsPlugin;
916
+ var ShaderChunk$2 = RenderManager.ShaderChunk;
917
+ var SSContactShadowsPlugin = class SSContactShadowsPlugin extends AViewerPluginSync {
918
+ static {
919
+ _SSContactShadowsPlugin = this;
920
+ }
921
+ static {
922
+ this.PluginType = "SSContactShadows";
923
+ }
924
+ static {
925
+ this.OldPluginType = "SSContactShadowsPlugin";
926
+ }
927
+ setDirty() {
928
+ this.materialExtension?.setDirty?.();
929
+ this._viewer?.setDirty();
930
+ }
931
+ constructor(enabled = true) {
932
+ super();
933
+ this.enabled = true;
934
+ this._uniforms = {
935
+ sscsRadius: { value: .03 },
936
+ sscsIntensity: { value: 1 },
937
+ sscsTolerance: { value: 1.5 },
938
+ frameCount: { value: 0 },
939
+ projection: { value: new Matrix4() },
940
+ cameraPositionWorld: { value: new Vector3() },
941
+ cameraNearFar: { value: new Vector2(.1, 1e3) },
942
+ sceneBoundingRadius: { value: 0 }
943
+ };
944
+ this.radius = .015;
945
+ this.intensity = 1;
946
+ this.tolerance = 1.5;
947
+ this._defines = { ["PERSPECTIVE_CAMERA"]: 1 };
948
+ this.onlySSCSDebug = false;
949
+ this.stepCount = 2;
950
+ this.dependencies = [GBufferPlugin];
951
+ this.materialExtension = {
952
+ uuid: _SSContactShadowsPlugin.PluginType,
953
+ priority: 5,
954
+ shaderExtender: (shader, _material, _renderer) => {
955
+ if (!shader.defines.SSCS_ENABLED) return;
956
+ const rsS = "float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {";
957
+ const lsS = glsl`
2
958
  #ifndef D_sceneBoundingRadius
3
959
  #define D_sceneBoundingRadius
4
960
  uniform float sceneBoundingRadius;
@@ -19,7 +975,368 @@ var e,t;import{RenderManager as r,PipelinePassPlugin as i,GBufferPlugin as a,Pro
19
975
  #if defined(SSCS_DEBUG) && SSCS_DEBUG > 0
20
976
  return state.z;
21
977
  #endif
22
- `,a=`\n#if SSCS_ENABLED\n\n uniform float sscsIntensity;\n uniform float sscsRadius;\n uniform float sscsTolerance;\n\n #define THREE_PACKING_INCLUDED // by threejs\n #include <cameraHelpers>\n #include <randomHelpers>\n ${Qe}\n \n#endif\n `+y(it.shadowmap_pars_fragment,"float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {",`${i}\n`).replace("return mix( 1.0, shadow, shadowIntensity );","return mix( 1.0, min(shadow, state.z), shadowIntensity );");e.fragmentShader=y(e.fragmentShader,"#include <shadowmap_pars_fragment>",a),e.fragmentShader=e.fragmentShader.replace("#include <lights_fragment_begin>",it.lights_fragment_begin),e.fragmentShader=y(e.fragmentShader,"directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;","directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ], directLight.direction ) : 1.0;"),e.fragmentShader=y(e.fragmentShader,"directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;","directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ], directLight.direction ) : 1.0;"),this._gbufferUnpackExtension?.shaderExtender?.(e,t,r)},onObjectRender:(e,t,r)=>{const i=!this.enabled||!1===r.userData.screenSpaceRendering||t.userData?.pluginsDisabled||t.userData?.sscsDisabled?0:1;X({...this._defines,SSCS_ENABLED:i},t)},extraUniforms:{...this._uniforms},extraDefines:{},computeCacheKey:e=>this.isDisabled()?"0":"1",isCompatible:e=>e.isPhysicalMaterial,updaters:()=>[this._viewer?.getPlugin(s),this._viewer?.scene.renderCamera,this._viewer?.renderManager,this._viewer?.scene]},this._gbufferUnpackExtension=void 0,this._gbufferUnpackExtensionChanged=()=>{if(!this._viewer)throw new Error("SSContactShadowPlugin: pass/viewer not created yet");const e=this._viewer.renderManager.gbufferUnpackExtension;this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this.setGBufferUnpackExtension(void 0),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension?this.setGBufferUnpackExtension(this._gbufferUnpackExtension):this._viewer.console.warn("SSContactShadowPlugin: GBuffer unpack extension removed"))},this.enabled=e}setDirty(){this.materialExtension?.setDirty?.(),this._viewer?.setDirty()}onAdded(e){super.onAdded(e),e.assetManager.materials.registerMaterialExtension(this.materialExtension),e.getPlugin(q)&&(e.getPlugin(q).material.userData.sscsDisabled=!1),this._gbufferUnpackExtensionChanged(),e.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.renderManager.removeEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),super.onRemove(e)}setGBufferUnpackExtension(e){this._gbufferUnpackExtension=e,this._gbufferUnpackExtension&&(Object.assign(this.materialExtension.extraUniforms,this._gbufferUnpackExtension.extraUniforms),Object.assign(this.materialExtension.extraDefines,this._gbufferUnpackExtension.extraDefines))}};at.PluginType="SSContactShadows",at.OldPluginType="SSContactShadowsPlugin",rt([o("Enabled"),f(),B(at.prototype.setDirty)],at.prototype,"enabled",2),rt([m({propKey:"sscsRadius",onChange:at.prototype.setDirty}),O("Radius",[1e-4,.1],1e-4),f()],at.prototype,"radius",2),rt([m({propKey:"sscsIntensity",onChange:at.prototype.setDirty}),O("Intensity",[1e-4,1],1e-4),f()],at.prototype,"intensity",2),rt([m({propKey:"sscsTolerance",onChange:at.prototype.setDirty}),O("Tolerance",[.1,5]),f()],at.prototype,"tolerance",2),rt([Z("SSCS_DEBUG",void 0,!0,at.prototype.setDirty),o("Debug only SSCS"),f()],at.prototype,"onlySSCSDebug",2),rt([Z("SSCS_STEP_COUNT",void 0,!0,at.prototype.setDirty),O("Step count",[1,8],1),f()],at.prototype,"stepCount",2),at=rt([E("SS Contact Shadows")],at);const st="#define PI 3.141592653589793\nmat3 GetTangentBasis(vec3 TangentZ){vec3 up=vec3(0.0,0.0,1.0);vec3 TangentX=normalize(cross(dot(TangentZ,up)<0.8 ? up : vec3(1.0,0.0,0.0),TangentZ));vec3 TangentY=cross(TangentZ,TangentX);return mat3(TangentX,TangentY,TangentZ);}vec4 CosineSampleHemisphere(vec2 E){float Phi=2.*PI*E.x;float CosTheta=sqrt(E.y);float SinTheta=sqrt(1.-CosTheta*CosTheta);vec3 H;H.x=SinTheta*cos(Phi);H.y=SinTheta*sin(Phi);H.z=CosTheta;float PDF=CosTheta*(1.0/PI);return vec4(H,PDF);}vec4 UniformSampleHemisphere(vec2 E){float Phi=2.*PI*E.x;float CosTheta=E.y;float SinTheta=sqrt(1.-CosTheta*CosTheta);vec3 H;H.x=SinTheta*cos(Phi);H.y=SinTheta*sin(Phi);H.z=CosTheta;float PDF=1.0/(2.*PI);return vec4(H,PDF);}vec2 UniformSampleDiskConcentric(vec2 E){vec2 p=2.*E-1.;float Radius;float Phi;if(abs(p.x)>abs(p.y)){Radius=p.x;Phi=(PI/4.)*(p.y/p.x);}else{Radius=p.y;Phi=(PI/2.)-(PI/4.)*(p.x/p.y);}return vec2(Radius*cos(Phi),Radius*sin(Phi));}vec2 UniformSampleDiskConcentricApprox(vec2 E){vec2 sf=E*sqrt(2.0)-sqrt(0.5);vec2 sq=sf*sf;float root=sqrt(2.0*max(sq.x,sq.y)-min(sq.x,sq.y));if(sq.x>sq.y){sf.x=sf.x>0. ? root :-root;}else{sf.y=sf.y>0. ? root :-root;}return sf;}";var nt=Object.defineProperty,ot=Object.getOwnPropertyDescriptor,lt=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?ot(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&nt(t,r,s),s};let ct=class extends i{constructor(e=!0,t=_,r=1,i=!0){super(),this.inlineShaderRayTrace=e,this.passId="ssrefl",this.dependencies=[a,J],this._gbufferUnpackExtension=void 0,this._gbufferUnpackExtensionChanged=()=>{if(!this._pass||!this._viewer)throw new Error("SSReflectionPlugin: pass/viewer not created yet");const e=this._viewer.renderManager.gbufferUnpackExtension;this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this._pass.setGBufferUnpackExtension(void 0),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension?this._pass.setGBufferUnpackExtension(this._gbufferUnpackExtension):this._viewer.console.warn("SSReflectionPlugin: GBuffer unpack extension removed"))},this._viewerListeners={preRender:()=>{if(!this._viewer||this.isDisabled())return;if(!this._pass)return;const e=this._viewer.scene.renderCamera;this._pass.uniforms.currentProjectionViewMatrix.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._pass.uniforms.inverseViewMatrix.value.copy(e.matrixWorld)},postRender:()=>{this._viewer&&!this.isDisabled()&&this._pass&&this._pass.uniforms.lastProjectionViewMatrix.value.copy(this._pass.uniforms.currentProjectionViewMatrix.value)}},this.enabled=i,this.bufferType=t,this.sizeMultiplier=r}_createTarget(e=!0){this._viewer&&(e&&this._disposeTarget(),this.inlineShaderRayTrace||(this.target||(this.target=this._viewer.renderManager.createTarget({depthBuffer:!1,type:this.bufferType,sizeMultiplier:this.sizeMultiplier})),this.texture=this.target.texture,this.texture.name="ssreflBuffer"))}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0)}_createPass(){if(!this._viewer)throw new Error("SSReflectionPlugin: viewer not set");if(!this._viewer.renderManager.gbufferTarget||!this._viewer.renderManager.gbufferUnpackExtension)throw new Error("SSReflectionPlugin: GBuffer target not created. GBufferPlugin is required.");return this._createTarget(!0),new dt(this.passId,()=>this.target,this.inlineShaderRayTrace)}onAdded(e){super.onAdded(e),(e.getPlugin("Ground")||e.getPlugin("BaseGroundPlugin"))&&console.warn("GroundPlugin must be added after SSReflectionPlugin"),this._gbufferUnpackExtensionChanged(),e.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),e.forPlugin(ke,e=>{this._pass?.material.registerMaterialExtensions([e.unpackExtension])},e=>{this._pass?.material?.unregisterMaterialExtensions([e.unpackExtension])},this)}onRemove(e){return this._disposeTarget(),e.renderManager.removeEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),super.onRemove(e)}_beforeRender(e,t,r){if(!this._viewer)return!1;const i=super._beforeRender(e,t,r);if(!i)return i;const a=this._viewer.getPlugin(s);return this._pass?.updateShaderProperties([a]),i}get ssrTarget(){return console.warn("SSReflectionPlugin: ssrTarget is deprecated, use target instead"),this.target}fromJSON(e,t){return e.passes?.ssr&&((e={...e}).pass=e.passes.ssr,delete e.passes,void 0!==e.pass.enabled&&(e.enabled=e.pass.enabled)),super.fromJSON(e,t)}};ct.PluginType="SSReflectionPlugin",ct.OldPluginType="SSReflection",lt([M("SSReflection Buffer",{readOnly:!0,hideOnEmpty:!0})],ct.prototype,"texture",2),lt([l(void 0,{unwrapContents:!0})],ct.prototype,"_pass",2),ct=lt([E("SSReflection Plugin")],ct);let dt=class extends c{constructor(e,t,r=!0){super({defines:{SSR_STEP_COUNT:16,SSR_RAY_COUNT:4,SSR_RAY_BLEND_MAX:0,SSR_LOW_QUALITY_FRAMES:0,SSR_INLINE:r?"1":"0",SSR_MASK_FRONT_RAYS:!0,PERSPECTIVE_CAMERA:1},uniforms:{tLastThis:{value:null},tLastFrame:{value:null},screenSize:{value:new d(0,0)},currentFrameCount:{value:0},frameCount:{value:0},cameraNearFar:{value:new d(.1,1e3)},cameraPositionWorld:{value:new F},projection:{value:new u},opacity:{value:1},intensity:{value:0},boost:{value:new F(0,0,0)},objectRadius:{value:0},autoRadius:{value:!1},power:{value:0},maskFrontFactor:{value:-.1},tolerance:{value:0},ssrRoughnessFactor:{value:1},sceneBoundingRadius:{value:0},currentProjectionViewMatrix:{value:new u},lastProjectionViewMatrix:{value:new u},inverseViewMatrix:{value:new u},ssrSplitX:{value:.5}},vertexShader:V.defaultVertex,fragmentShader:`\nvarying vec2 vUv;\n\n// for gbuffer\n#include <packing>\n#define THREE_PACKING_INCLUDED\n#include <cameraHelpers>\n#include <randomHelpers>\n${st}\n\n${Qe}\n\n${Ee().ssReflection}\n\nvoid main(){vec4 texel=tDiffuseTexelToLinear(texture2D(tDiffuse,vUv));vec4 lastAO=tLastThisTexelToLinear(texture2D(tLastThis,vUv));float depth;vec3 normal;getDepthNormal(vUv,depth,normal);if(depth>=0.999){discard;}float viewZ=depthToViewZ(depth);vec3 screenPos=vec3(vUv.x,vUv.y,viewZ);vec3 viewPos=screenToView3(screenPos.xy,screenPos.z);viewPos.z=viewZ/viewPos.z;vec4 ao=vec4(0.);ao+=calculateSSR(8.,screenPos,normal,1.,0.1);ao.rgb=min(vec3(3.),ao.rgb);ao.rgb=max(vec3(0.),ao.rgb);if(currentFrameCount<2.){gl_FragColor=ao;return;}if(ao.a<0.01){gl_FragColor.rgb=lastAO.rgb;gl_FragColor.a=(((lastAO.a)*currentFrameCount)/(currentFrameCount+1.));}else{gl_FragColor=((ao+(lastAO)*currentFrameCount)/(currentFrameCount+1.));}\n#include <colorspace_fragment>\n}\n `},"tDiffuse","tLastThis","tLastFrame"),this.target=t,this.inlineShaderRayTrace=r,this.before=["render"],this.after=["gbuffer","depth"],this.required=["render","progressive"],this.intensity=1,this.boost=new F(1,1,1),this.objectRadius=1,this.autoRadius=!0,this.power=1.1,this.tolerance=.5,this.roughnessFactor=1,this.stepCount=16,this.rayCount=1,this.rayBlendMax=!1,this.lowQualityFrames=0,this.maskFrontRays=!0,this.maskFrontFactor=-.2,this.split=0,this.materialExtension={extraUniforms:{tSSReflMap:()=>({value:p(this.target)?.texture??null}),ssrPower:this.material.uniforms.power,ssrIntensity:this.material.uniforms.intensity,ssrMaskFrontFactor:this.material.uniforms.maskFrontFactor,ssrBoost:this.material.uniforms.boost},extraDefines:{SSR_STEP_COUNT:()=>this.material.defines.SSR_STEP_COUNT,SSR_RAY_COUNT:()=>this.material.defines.SSR_RAY_COUNT,SSR_RAY_BLEND_MAX:()=>this.material.defines.SSR_RAY_BLEND_MAX,SSR_LOW_QUALITY_FRAMES:()=>this.material.defines.SSR_LOW_QUALITY_FRAMES,SSR_INLINE:()=>this.material.defines.SSR_INLINE,SSR_MASK_FRONT_RAYS:()=>this.material.defines.SSR_MASK_FRONT_RAYS,PERSPECTIVE_CAMERA:()=>this.material.defines.PERSPECTIVE_CAMERA},shaderExtender:(e,t,r)=>{if(!e.defines?.SSREFL_ENABLED)return;e.fragmentShader=y(e.fragmentShader,"#glMarker beforeModulation","\n \n \n#if defined(SSREFL_ENABLED) && SSREFL_ENABLED > 0\nvec3 screenPos=viewToScreen(geometryPosition);\n#if SSREFL_ENABLED == 2\nif(screenPos.x>ssrSplitX){\n#endif\nvec4 ssrColor=vec4(0,0,0,0);float alphaModifier=1.0-clamp(material.roughness*.3,0.,1.);alphaModifier*=ssrIntensity;\n#if defined(SSR_MASK_FRONT_RAYS) && SSR_MASK_FRONT_RAYS > 0\nalphaModifier*=clamp(-4.0*dot(geometryViewDir,normal)+(4.0+ssrMaskFrontFactor),0.0,1.0);\n#endif\n#ifdef USE_TRANSMISSION\nalphaModifier*=1.-transmission;\n#endif\nfloat vignette=1.;if(true){float fadeStrength=0.1;float dist=max(0.,min(min(1.-screenPos.x,1.-screenPos.y),min(screenPos.x,screenPos.y)));float fade=dist*dist/(fadeStrength+0.001);fade=clamp(fade,0.0,1.0);fade=pow(fade,0.3);vignette=fade;}alphaModifier*=vignette;vec3 specularColor=EnvironmentBRDF(geometryNormal,geometryViewDir,material.specularColor.rgb,material.specularF90,material.roughness);if(length(specularColor.rgb)*alphaModifier>0.01&&roughnessFactor<0.9){\n#if defined(SSR_INLINE) && SSR_INLINE > 0\nvec3 scPos=vec3(screenPos.xy,geometryPosition.z);vec4 scol=vec4(0,0,0,0);\n#pragma unroll_loop_start\nfor(int i=0;i<8;i++){if(SSR_RAY_COUNT>UNROLLED_LOOP_INDEX){scol=calculateSSR(float(UNROLLED_LOOP_INDEX),scPos,geometryNormal,UNROLLED_LOOP_INDEX%3==0?1.:UNROLLED_LOOP_INDEX%3==1?0.5:1.5,material.roughness);\n#ifdef SSR_RAY_BLEND_MAX\nssrColor=max(ssrColor,scol);\n#else\nssrColor+=scol;\n#endif\n}}\n#pragma unroll_loop_end\n#ifndef SSR_RAY_BLEND_MAX\nssrColor*=ssrColor.a>0.001 ? 1.0/ssrColor.a : 1.0;\n#endif\n#else\nssrColor=tSSReflMapTexelToLinear(texture2D(tSSReflMap,screenPos.xy));\n#endif\n}ssrColor.rgb*=ssrBoost;ssrColor.a*=alphaModifier;ssrColor.rgb=pow(max(vec3(0.),ssrColor.rgb),vec3(ssrPower));ssrColor.a=min(ssrColor.a,1.0);\n#if defined(SSR_NON_PHYSICAL) && SSR_NON_PHYSICAL > 0\ndiffuseColor.a=max(ssrColor.a,diffuseColor.a*diffuseColor.a);reflectedLight.indirectSpecular=mix(reflectedLight.indirectSpecular,saturate(diffuseColor.rgb*ssrColor.rgb),1.0);reflectedLight.indirectDiffuse=diffuseColor.rgb*(1.0-ssrColor.a);reflectedLight.directDiffuse=vec3(0.0);reflectedLight.directSpecular=vec3(0.0);\n#else\nreflectedLight.indirectSpecular=mix(reflectedLight.indirectSpecular,(specularColor.rgb*ssrColor.rgb),ssrColor.a);\n#endif\n#if SSREFL_ENABLED == 2\n}\n#endif\n#endif\n\n \n // reflectedLight.directDiffuse = vec3(0.);\n // reflectedLight.indirectDiffuse = vec3(0.);\n // reflectedLight.directSpecular = vec3(0.);\n // reflectedLight.indirectSpecular = vec3(0.);\n \n ",{prepend:!0}),this._gbufferUnpackExtension?.shaderExtender?.(e,t,r)},onObjectRender:(e,t,r)=>{let i=!this.enabled||!1===r.userData.screenSpaceRendering||t.userData?.pluginsDisabled||t.userData?.ssreflDisabled?0:this.split>0?2:1;t.defines.SSREFL_ENABLED!==i&&(t.defines.SSREFL_ENABLED=i,t.needsUpdate=!0),i=t.userData?.ssreflNonPhysical?1:0,t.defines.SSR_NON_PHYSICAL!==i&&(t.defines.SSR_NON_PHYSICAL=i,t.needsUpdate=!0)},parsFragmentSnippet:()=>K`
978
+ `;
979
+ const shadowChunk = `
980
+ #if SSCS_ENABLED
981
+
982
+ uniform float sscsIntensity;
983
+ uniform float sscsRadius;
984
+ uniform float sscsTolerance;
985
+
986
+ #define THREE_PACKING_INCLUDED // by threejs
987
+ #include <cameraHelpers>
988
+ #include <randomHelpers>
989
+ ${ssrt_default}
990
+
991
+ #endif
992
+ ` + shaderReplaceString(ShaderChunk$2.shadowmap_pars_fragment, rsS, `${lsS}\n`).replace("return mix( 1.0, shadow, shadowIntensity );", "return mix( 1.0, min(shadow, state.z), shadowIntensity );");
993
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#include <shadowmap_pars_fragment>", shadowChunk);
994
+ shader.fragmentShader = shader.fragmentShader.replace("#include <lights_fragment_begin>", ShaderChunk$2.lights_fragment_begin);
995
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;", "directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ], directLight.direction ) : 1.0;");
996
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;", "directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ], directLight.direction ) : 1.0;");
997
+ this._gbufferUnpackExtension?.shaderExtender?.(shader, _material, _renderer);
998
+ },
999
+ onObjectRender: (_, material, renderer) => {
1000
+ const enabled = this.enabled && renderer.userData.screenSpaceRendering !== false && !material.userData?.pluginsDisabled && !material.userData?.sscsDisabled ? 1 : 0;
1001
+ updateMaterialDefines({
1002
+ ...this._defines,
1003
+ ["SSCS_ENABLED"]: enabled
1004
+ }, material);
1005
+ },
1006
+ extraUniforms: { ...this._uniforms },
1007
+ extraDefines: {},
1008
+ computeCacheKey: (_) => {
1009
+ return this.isDisabled() ? "0" : "1";
1010
+ },
1011
+ isCompatible: (material1) => {
1012
+ return material1.isPhysicalMaterial;
1013
+ },
1014
+ updaters: () => [
1015
+ this._viewer?.getPlugin(ProgressivePlugin),
1016
+ this._viewer?.scene.renderCamera,
1017
+ this._viewer?.renderManager,
1018
+ this._viewer?.scene
1019
+ ]
1020
+ };
1021
+ this._gbufferUnpackExtension = void 0;
1022
+ this._gbufferUnpackExtensionChanged = () => {
1023
+ if (!this._viewer) throw new Error("SSContactShadowPlugin: pass/viewer not created yet");
1024
+ const newExtension = this._viewer.renderManager.gbufferUnpackExtension;
1025
+ if (this._gbufferUnpackExtension === newExtension) return;
1026
+ if (this._gbufferUnpackExtension) this.setGBufferUnpackExtension(void 0);
1027
+ this._gbufferUnpackExtension = newExtension;
1028
+ if (this._gbufferUnpackExtension) this.setGBufferUnpackExtension(this._gbufferUnpackExtension);
1029
+ else this._viewer.console.warn("SSContactShadowPlugin: GBuffer unpack extension removed");
1030
+ };
1031
+ this.enabled = enabled;
1032
+ }
1033
+ onAdded(v) {
1034
+ super.onAdded(v);
1035
+ v.assetManager.materials.registerMaterialExtension(this.materialExtension);
1036
+ if (v.getPlugin(BaseGroundPlugin)) v.getPlugin(BaseGroundPlugin).material.userData.sscsDisabled = false;
1037
+ this._gbufferUnpackExtensionChanged();
1038
+ v.renderManager.addEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
1039
+ }
1040
+ onRemove(v) {
1041
+ v.assetManager.materials?.unregisterMaterialExtension(this.materialExtension);
1042
+ v.renderManager.removeEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
1043
+ return super.onRemove(v);
1044
+ }
1045
+ setGBufferUnpackExtension(extension) {
1046
+ this._gbufferUnpackExtension = extension;
1047
+ if (!this._gbufferUnpackExtension) return;
1048
+ Object.assign(this.materialExtension.extraUniforms, this._gbufferUnpackExtension.extraUniforms);
1049
+ Object.assign(this.materialExtension.extraDefines, this._gbufferUnpackExtension.extraDefines);
1050
+ }
1051
+ };
1052
+ __decorate([
1053
+ uiToggle("Enabled"),
1054
+ serialize(),
1055
+ onChange(SSContactShadowsPlugin.prototype.setDirty)
1056
+ ], SSContactShadowsPlugin.prototype, "enabled", void 0);
1057
+ __decorate([
1058
+ uniform({
1059
+ propKey: "sscsRadius",
1060
+ onChange: SSContactShadowsPlugin.prototype.setDirty
1061
+ }),
1062
+ uiSlider("Radius", [1e-4, .1], 1e-4),
1063
+ serialize()
1064
+ ], SSContactShadowsPlugin.prototype, "radius", void 0);
1065
+ __decorate([
1066
+ uniform({
1067
+ propKey: "sscsIntensity",
1068
+ onChange: SSContactShadowsPlugin.prototype.setDirty
1069
+ }),
1070
+ uiSlider("Intensity", [1e-4, 1], 1e-4),
1071
+ serialize()
1072
+ ], SSContactShadowsPlugin.prototype, "intensity", void 0);
1073
+ __decorate([
1074
+ uniform({
1075
+ propKey: "sscsTolerance",
1076
+ onChange: SSContactShadowsPlugin.prototype.setDirty
1077
+ }),
1078
+ uiSlider("Tolerance", [.1, 5]),
1079
+ serialize()
1080
+ ], SSContactShadowsPlugin.prototype, "tolerance", void 0);
1081
+ __decorate([
1082
+ matDefine("SSCS_DEBUG", void 0, true, SSContactShadowsPlugin.prototype.setDirty),
1083
+ uiToggle("Debug only SSCS"),
1084
+ serialize()
1085
+ ], SSContactShadowsPlugin.prototype, "onlySSCSDebug", void 0);
1086
+ __decorate([
1087
+ matDefine("SSCS_STEP_COUNT", void 0, true, SSContactShadowsPlugin.prototype.setDirty),
1088
+ uiSlider("Step count", [1, 8], 1),
1089
+ serialize()
1090
+ ], SSContactShadowsPlugin.prototype, "stepCount", void 0);
1091
+ SSContactShadowsPlugin = _SSContactShadowsPlugin = __decorate([uiFolderContainer("SS Contact Shadows")], SSContactShadowsPlugin);
1092
+ /**
1093
+ * SSContactShadows Materials Extension
1094
+ *
1095
+ * Specification: https://webgi.xyz/docs/gltf-extensions/WEBGI_materials_clearcoat_tint.html
1096
+ */
1097
+ // src/plugins/postprocessing/shaders/samplePointHelpers.glsl
1098
+ var samplePointHelpers_default = "\n#define PI 3.141592653589793\n";
1099
+ // src/plugins/postprocessing/shaders/ssrPatch.glsl
1100
+ var ssrPatch_default = "\n#if defined(SSREFL_ENABLED) && SSREFL_ENABLED > 0\nvec3 screenPos=viewToScreen(geometryPosition);\n#if SSREFL_ENABLED == 2\nif(screenPos.x>ssrSplitX){\n#endif\nvec4 ssrColor=vec4(0,0,0,0);float alphaModifier=1.0-clamp(material.roughness*.3,0.,1.);alphaModifier*=ssrIntensity;\n#if defined(SSR_MASK_FRONT_RAYS) && SSR_MASK_FRONT_RAYS > 0\nalphaModifier*=clamp(-4.0*dot(geometryViewDir,normal)+(4.0+ssrMaskFrontFactor),0.0,1.0);\n#endif\n#ifdef USE_TRANSMISSION\nalphaModifier*=1.-transmission;\n#endif\nfloat vignette=1.;if(true){float fadeStrength=0.1;float dist=max(0.,min(min(1.-screenPos.x,1.-screenPos.y),min(screenPos.x,screenPos.y)));float fade=dist*dist/(fadeStrength+0.001);fade=clamp(fade,0.0,1.0);fade=pow(fade,0.3);vignette=fade;}alphaModifier*=vignette;vec3 specularColor=EnvironmentBRDF(geometryNormal,geometryViewDir,material.specularColor.rgb,material.specularF90,material.roughness);if(length(specularColor.rgb)*alphaModifier>0.01&&roughnessFactor<0.9){\n#if defined(SSR_INLINE) && SSR_INLINE > 0\nvec3 scPos=vec3(screenPos.xy,geometryPosition.z);vec4 scol=vec4(0,0,0,0);\n#pragma unroll_loop_start\nfor(int i=0;i<8;i++){if(SSR_RAY_COUNT>UNROLLED_LOOP_INDEX){scol=calculateSSR(float(UNROLLED_LOOP_INDEX),scPos,geometryNormal,UNROLLED_LOOP_INDEX%3==0?1.:UNROLLED_LOOP_INDEX%3==1?0.5:1.5,material.roughness);\n#ifdef SSR_RAY_BLEND_MAX\nssrColor=max(ssrColor,scol);\n#else\nssrColor+=scol;\n#endif\n}}\n#pragma unroll_loop_end\n#ifndef SSR_RAY_BLEND_MAX\nssrColor*=ssrColor.a>0.001 ? 1.0/ssrColor.a : 1.0;\n#endif\n#else\nssrColor=tSSReflMapTexelToLinear(texture2D(tSSReflMap,screenPos.xy));\n#endif\n}ssrColor.rgb*=ssrBoost;ssrColor.a*=alphaModifier;ssrColor.rgb=pow(max(vec3(0.),ssrColor.rgb),vec3(ssrPower));ssrColor.a=min(ssrColor.a,1.0);\n#if defined(SSR_NON_PHYSICAL) && SSR_NON_PHYSICAL > 0\ndiffuseColor.a=max(ssrColor.a,diffuseColor.a*diffuseColor.a);reflectedLight.indirectSpecular=mix(reflectedLight.indirectSpecular,saturate(diffuseColor.rgb*ssrColor.rgb),1.0);reflectedLight.indirectDiffuse=diffuseColor.rgb*(1.0-ssrColor.a);reflectedLight.directDiffuse=vec3(0.0);reflectedLight.directSpecular=vec3(0.0);\n#else\nreflectedLight.indirectSpecular=mix(reflectedLight.indirectSpecular,(specularColor.rgb*ssrColor.rgb),ssrColor.a);\n#endif\n#if SSREFL_ENABLED == 2\n}\n#endif\n#endif\n";
1101
+ // src/plugins/postprocessing/shaders/ssreflectionMain.glsl
1102
+ var ssreflectionMain_default = "void main(){vec4 texel=tDiffuseTexelToLinear(texture2D(tDiffuse,vUv));vec4 lastAO=tLastThisTexelToLinear(texture2D(tLastThis,vUv));float depth;vec3 normal;getDepthNormal(vUv,depth,normal);if(depth>=0.999){discard;}float viewZ=depthToViewZ(depth);vec3 screenPos=vec3(vUv.x,vUv.y,viewZ);vec3 viewPos=screenToView3(screenPos.xy,screenPos.z);viewPos.z=viewZ/viewPos.z;vec4 ao=vec4(0.);ao+=calculateSSR(8.,screenPos,normal,1.,0.1);ao.rgb=min(vec3(3.),ao.rgb);ao.rgb=max(vec3(0.),ao.rgb);if(currentFrameCount<2.){gl_FragColor=ao;return;}if(ao.a<0.01){gl_FragColor.rgb=lastAO.rgb;gl_FragColor.a=(((lastAO.a)*currentFrameCount)/(currentFrameCount+1.));}else{gl_FragColor=((ao+(lastAO)*currentFrameCount)/(currentFrameCount+1.));}\n#include <colorspace_fragment>\n}";
1103
+ // src/plugins/postprocessing/SSReflectionPlugin.ts
1104
+ var passId$1 = "ssrefl";
1105
+ var SSReflectionPlugin = class SSReflectionPlugin extends PipelinePassPlugin {
1106
+ static {
1107
+ this.PluginType = "SSReflectionPlugin";
1108
+ }
1109
+ static {
1110
+ this.OldPluginType = "SSReflection";
1111
+ }
1112
+ constructor(inlineShaderRayTrace = true, bufferType = UnsignedByteType, sizeMultiplier = 1, enabled = true) {
1113
+ super();
1114
+ this.inlineShaderRayTrace = inlineShaderRayTrace;
1115
+ this.passId = passId$1;
1116
+ this.dependencies = [GBufferPlugin, SSAAPlugin];
1117
+ this._gbufferUnpackExtension = void 0;
1118
+ this._gbufferUnpackExtensionChanged = () => {
1119
+ if (!this._pass || !this._viewer) throw new Error("SSReflectionPlugin: pass/viewer not created yet");
1120
+ const newExtension = this._viewer.renderManager.gbufferUnpackExtension;
1121
+ if (this._gbufferUnpackExtension === newExtension) return;
1122
+ if (this._gbufferUnpackExtension) this._pass.setGBufferUnpackExtension(void 0);
1123
+ this._gbufferUnpackExtension = newExtension;
1124
+ if (this._gbufferUnpackExtension) this._pass.setGBufferUnpackExtension(this._gbufferUnpackExtension);
1125
+ else this._viewer.console.warn("SSReflectionPlugin: GBuffer unpack extension removed");
1126
+ };
1127
+ this._viewerListeners = {
1128
+ preRender: () => {
1129
+ if (!this._viewer || this.isDisabled()) return;
1130
+ if (!this._pass) return;
1131
+ const renderCamera = this._viewer.scene.renderCamera;
1132
+ this._pass.uniforms.currentProjectionViewMatrix.value.multiplyMatrices(renderCamera.projectionMatrix, renderCamera.matrixWorldInverse);
1133
+ this._pass.uniforms.inverseViewMatrix.value.copy(renderCamera.matrixWorld);
1134
+ },
1135
+ postRender: () => {
1136
+ if (!this._viewer || this.isDisabled()) return;
1137
+ if (!this._pass) return;
1138
+ this._pass.uniforms.lastProjectionViewMatrix.value.copy(this._pass.uniforms.currentProjectionViewMatrix.value);
1139
+ }
1140
+ };
1141
+ this.enabled = enabled;
1142
+ this.bufferType = bufferType;
1143
+ this.sizeMultiplier = sizeMultiplier;
1144
+ }
1145
+ _createTarget(recreate = true) {
1146
+ if (!this._viewer) return;
1147
+ if (recreate) this._disposeTarget();
1148
+ if (this.inlineShaderRayTrace) return;
1149
+ if (!this.target) this.target = this._viewer.renderManager.createTarget({
1150
+ depthBuffer: false,
1151
+ type: this.bufferType,
1152
+ sizeMultiplier: this.sizeMultiplier
1153
+ });
1154
+ this.texture = this.target.texture;
1155
+ this.texture.name = "ssreflBuffer";
1156
+ }
1157
+ _disposeTarget() {
1158
+ if (!this._viewer) return;
1159
+ if (this.target) {
1160
+ this._viewer.renderManager.disposeTarget(this.target);
1161
+ this.target = void 0;
1162
+ }
1163
+ this.texture = void 0;
1164
+ }
1165
+ _createPass() {
1166
+ if (!this._viewer) throw new Error("SSReflectionPlugin: viewer not set");
1167
+ if (!this._viewer.renderManager.gbufferTarget || !this._viewer.renderManager.gbufferUnpackExtension) throw new Error("SSReflectionPlugin: GBuffer target not created. GBufferPlugin is required.");
1168
+ this._createTarget(true);
1169
+ return new SSReflectionPluginPass(this.passId, () => this.target, this.inlineShaderRayTrace);
1170
+ }
1171
+ onAdded(viewer) {
1172
+ super.onAdded(viewer);
1173
+ if (viewer.getPlugin("Ground") || viewer.getPlugin("BaseGroundPlugin")) console.warn("GroundPlugin must be added after SSReflectionPlugin");
1174
+ this._gbufferUnpackExtensionChanged();
1175
+ viewer.renderManager.addEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
1176
+ viewer.forPlugin(VelocityBufferPlugin, (vbp) => {
1177
+ this._pass?.material.registerMaterialExtensions([vbp.unpackExtension]);
1178
+ }, (vbp) => {
1179
+ this._pass?.material?.unregisterMaterialExtensions([vbp.unpackExtension]);
1180
+ }, this);
1181
+ }
1182
+ onRemove(viewer) {
1183
+ this._disposeTarget();
1184
+ viewer.renderManager.removeEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
1185
+ return super.onRemove(viewer);
1186
+ }
1187
+ _beforeRender(_, _1, _2) {
1188
+ if (!this._viewer) return false;
1189
+ const e = super._beforeRender(_, _1, _2);
1190
+ if (!e) return e;
1191
+ const progressive = this._viewer.getPlugin(ProgressivePlugin);
1192
+ this._pass?.updateShaderProperties([progressive]);
1193
+ return e;
1194
+ }
1195
+ /**
1196
+ * @deprecated use {@link target} instead
1197
+ */
1198
+ get ssrTarget() {
1199
+ console.warn("SSReflectionPlugin: ssrTarget is deprecated, use target instead");
1200
+ return this.target;
1201
+ }
1202
+ fromJSON(data, meta) {
1203
+ if (data.passes?.ssr) {
1204
+ data = { ...data };
1205
+ data.pass = data.passes.ssr;
1206
+ delete data.passes;
1207
+ if (data.pass.enabled !== void 0) data.enabled = data.pass.enabled;
1208
+ }
1209
+ return super.fromJSON(data, meta);
1210
+ }
1211
+ };
1212
+ __decorate([uiImage("SSReflection Buffer", {
1213
+ readOnly: true,
1214
+ hideOnEmpty: true
1215
+ })], SSReflectionPlugin.prototype, "texture", void 0);
1216
+ __decorate([uiConfig(void 0, { unwrapContents: true })], SSReflectionPlugin.prototype, "_pass", void 0);
1217
+ SSReflectionPlugin = __decorate([uiFolderContainer("SSReflection Plugin")], SSReflectionPlugin);
1218
+ var SSReflectionPluginPass = class SSReflectionPluginPass extends ExtendedShaderPass {
1219
+ setDirty() {
1220
+ this.materialExtension?.setDirty?.();
1221
+ super.setDirty();
1222
+ }
1223
+ constructor(pid, target, inlineShaderRayTrace = true) {
1224
+ super({
1225
+ defines: {
1226
+ ["SSR_STEP_COUNT"]: 16,
1227
+ ["SSR_RAY_COUNT"]: 4,
1228
+ ["SSR_RAY_BLEND_MAX"]: 0,
1229
+ ["SSR_LOW_QUALITY_FRAMES"]: 0,
1230
+ ["SSR_INLINE"]: inlineShaderRayTrace ? "1" : "0",
1231
+ ["SSR_MASK_FRONT_RAYS"]: true,
1232
+ ["PERSPECTIVE_CAMERA"]: 1
1233
+ },
1234
+ uniforms: {
1235
+ tLastThis: { value: null },
1236
+ tLastFrame: { value: null },
1237
+ screenSize: { value: new Vector2(0, 0) },
1238
+ currentFrameCount: { value: 0 },
1239
+ frameCount: { value: 0 },
1240
+ cameraNearFar: { value: new Vector2(.1, 1e3) },
1241
+ cameraPositionWorld: { value: new Vector3() },
1242
+ projection: { value: new Matrix4() },
1243
+ opacity: { value: 1 },
1244
+ intensity: { value: 0 },
1245
+ boost: { value: new Vector3(0, 0, 0) },
1246
+ objectRadius: { value: 0 },
1247
+ autoRadius: { value: false },
1248
+ power: { value: 0 },
1249
+ maskFrontFactor: { value: -.1 },
1250
+ tolerance: { value: 0 },
1251
+ ssrRoughnessFactor: { value: 1 },
1252
+ sceneBoundingRadius: { value: 0 },
1253
+ currentProjectionViewMatrix: { value: new Matrix4() },
1254
+ lastProjectionViewMatrix: { value: new Matrix4() },
1255
+ inverseViewMatrix: { value: new Matrix4() },
1256
+ ssrSplitX: { value: .5 }
1257
+ },
1258
+ vertexShader: shaderUtils.defaultVertex,
1259
+ fragmentShader: `
1260
+ varying vec2 vUv;
1261
+
1262
+ // for gbuffer
1263
+ #include <packing>
1264
+ #define THREE_PACKING_INCLUDED
1265
+ #include <cameraHelpers>
1266
+ #include <randomHelpers>
1267
+ ${samplePointHelpers_default}
1268
+
1269
+ ${ssrt_default}
1270
+
1271
+ ${getShaders().ssReflection}
1272
+
1273
+ ${ssreflectionMain_default}
1274
+ `
1275
+ }, "tDiffuse", "tLastThis", "tLastFrame");
1276
+ this.target = target;
1277
+ this.inlineShaderRayTrace = inlineShaderRayTrace;
1278
+ this.before = ["render"];
1279
+ this.after = ["gbuffer", "depth"];
1280
+ this.required = ["render", "progressive"];
1281
+ this.intensity = 1;
1282
+ this.boost = new Vector3(1, 1, 1);
1283
+ this.objectRadius = 1;
1284
+ this.autoRadius = true;
1285
+ this.power = 1.1;
1286
+ this.tolerance = .5;
1287
+ this.roughnessFactor = 1;
1288
+ this.stepCount = 16;
1289
+ this.rayCount = 1;
1290
+ this.rayBlendMax = false;
1291
+ this.lowQualityFrames = 0;
1292
+ this.maskFrontRays = true;
1293
+ this.maskFrontFactor = -.2;
1294
+ this.split = 0;
1295
+ this.materialExtension = {
1296
+ extraUniforms: {
1297
+ tSSReflMap: () => ({ value: getOrCall(this.target)?.texture ?? null }),
1298
+ ssrPower: this.material.uniforms.power,
1299
+ ssrIntensity: this.material.uniforms.intensity,
1300
+ ssrMaskFrontFactor: this.material.uniforms.maskFrontFactor,
1301
+ ssrBoost: this.material.uniforms.boost
1302
+ },
1303
+ extraDefines: {
1304
+ ["SSR_STEP_COUNT"]: () => this.material.defines.SSR_STEP_COUNT,
1305
+ ["SSR_RAY_COUNT"]: () => this.material.defines.SSR_RAY_COUNT,
1306
+ ["SSR_RAY_BLEND_MAX"]: () => this.material.defines.SSR_RAY_BLEND_MAX,
1307
+ ["SSR_LOW_QUALITY_FRAMES"]: () => this.material.defines.SSR_LOW_QUALITY_FRAMES,
1308
+ ["SSR_INLINE"]: () => this.material.defines.SSR_INLINE,
1309
+ ["SSR_MASK_FRONT_RAYS"]: () => this.material.defines.SSR_MASK_FRONT_RAYS,
1310
+ ["PERSPECTIVE_CAMERA"]: () => this.material.defines.PERSPECTIVE_CAMERA
1311
+ },
1312
+ shaderExtender: (shader, _material, _renderer) => {
1313
+ if (!shader.defines?.SSREFL_ENABLED) return;
1314
+ const ls = `
1315
+
1316
+ ${ssrPatch_default}
1317
+
1318
+ // reflectedLight.directDiffuse = vec3(0.);
1319
+ // reflectedLight.indirectDiffuse = vec3(0.);
1320
+ // reflectedLight.directSpecular = vec3(0.);
1321
+ // reflectedLight.indirectSpecular = vec3(0.);
1322
+
1323
+ `;
1324
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#glMarker beforeModulation", ls, { prepend: true });
1325
+ this._gbufferUnpackExtension?.shaderExtender?.(shader, _material, _renderer);
1326
+ },
1327
+ onObjectRender: (_object, material, renderer) => {
1328
+ let x = this.enabled && renderer.userData.screenSpaceRendering !== false && !material.userData?.pluginsDisabled && !material.userData?.ssreflDisabled ? this.split > 0 ? 2 : 1 : 0;
1329
+ if (material.defines.SSREFL_ENABLED !== x) {
1330
+ material.defines.SSREFL_ENABLED = x;
1331
+ material.needsUpdate = true;
1332
+ }
1333
+ x = material.userData?.ssreflNonPhysical ? 1 : 0;
1334
+ if (material.defines.SSR_NON_PHYSICAL !== x) {
1335
+ material.defines.SSR_NON_PHYSICAL = x;
1336
+ material.needsUpdate = true;
1337
+ }
1338
+ },
1339
+ parsFragmentSnippet: () => glsl`
23
1340
  #if defined(SSREFL_ENABLED) && SSREFL_ENABLED > 0
24
1341
  uniform float ssrPower;
25
1342
  uniform float ssrIntensity;
@@ -27,14 +1344,765 @@ var e,t;import{RenderManager as r,PipelinePassPlugin as i,GBufferPlugin as a,Pro
27
1344
  uniform vec3 ssrBoost;
28
1345
  uniform sampler2D tSSReflMap;
29
1346
  uniform sampler2D tLastFrame;
30
- ${$("tSSReflMap",p(this.target)?.texture.colorSpace)}
31
- ${$("tLastFrame",this.material.uniforms.tLastFrame.value?.colorSpace)}
32
- ${this.inlineShaderRayTrace?`\n#define THREE_PACKING_INCLUDED // by threejs\n#include <cameraHelpers>\n#include <randomHelpers>\n${st}\n${Qe}\n${Ee().ssReflection}\n `:""}
1347
+ ${getTexelDecoding("tSSReflMap", getOrCall(this.target)?.texture.colorSpace)}
1348
+ ${getTexelDecoding("tLastFrame", this.material.uniforms.tLastFrame.value?.colorSpace)}
1349
+ ${!this.inlineShaderRayTrace ? "" : `
1350
+ #define THREE_PACKING_INCLUDED // by threejs
1351
+ #include <cameraHelpers>
1352
+ #include <randomHelpers>
1353
+ ${samplePointHelpers_default}
1354
+ ${ssrt_default}
1355
+ ${getShaders().ssReflection}
1356
+ `}
33
1357
  #include <simpleCameraHelpers>
34
1358
  #endif
35
- `,computeCacheKey:()=>(this.enabled?"1":"0")+p(this.target)?.texture?.colorSpace+Object.values(this.material.defines).map(e=>e+"").join(","),uuid:ct.PluginType,...C(this._getUiConfig.bind(this),ct.PluginType),isCompatible:e=>e.isPhysicalMaterial},this.passId=e,this.needsSwap=!1,this.clear=!0,r&&Object.assign(this.materialExtension.extraUniforms,{tNormalDepth:this.material.uniforms.tNormalDepth,tLastFrame:this.material.uniforms.tLastFrame,objectRadius:this.material.uniforms.objectRadius,autoRadius:this.material.uniforms.autoRadius,tolerance:this.material.uniforms.tolerance,ssrRoughnessFactor:this.material.uniforms.ssrRoughnessFactor,frameCount:this.material.uniforms.frameCount,currentFrameCount:this.material.uniforms.currentFrameCount,projection:this.material.uniforms.projection,cameraPositionWorld:this.material.uniforms.cameraPositionWorld,cameraNearFar:this.material.uniforms.cameraNearFar,sceneBoundingRadius:this.material.uniforms.sceneBoundingRadius,currentProjectionViewMatrix:this.material.uniforms.currentProjectionViewMatrix,lastProjectionViewMatrix:this.material.uniforms.lastProjectionViewMatrix,inverseViewMatrix:this.material.uniforms.inverseViewMatrix,ssrSplitX:this.material.uniforms.ssrSplitX})}setDirty(){this.materialExtension?.setDirty?.(),super.setDirty()}render(e,t,r,i,a){if(!this.enabled)return;if(this.inlineShaderRayTrace)return void(this.needsSwap=!1);const s=p(this.target);s?(this.material.defines.HAS_GBUFFER||console.warn("SSReflectionPluginPass: DepthNormalBuffer required for ssrefl"),e.renderManager.blit(t,{source:s.texture}),this.uniforms.tLastThis.value=t.texture,super.render(e,s,r,i,a),this.needsSwap=!1):console.warn("SSReflectionPluginPass: target not defined. It must be set when inlineShaderRayTrace is false")}beforeRender(e,t,r){this.enabled&&this.updateShaderProperties([e,t,r])}_getUiConfig(e){return{type:"folder",label:"SSReflection",children:[{type:"checkbox",label:"Enabled",get value(){return!e.userData.ssreflDisabled},set value(t){t!==!e.userData.ssreflDisabled&&(e.userData.ssreflDisabled=!t,e.setDirty())},onChange:this.setDirty},{type:"checkbox",label:"Non Physical",get value(){return e.userData.ssreflNonPhysical??!1},set value(t){t!==(e.userData.ssreflNonPhysical??!1)&&(e.userData.ssreflNonPhysical=t,e.setDirty())},onChange:this.setDirty}]}}set uniformsNeedUpdate(e){this.material.uniformsNeedUpdate=e,this.setDirty()}setGBufferUnpackExtension(e){this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension&&this.material.registerMaterialExtensions([this._gbufferUnpackExtension]),this._gbufferUnpackExtension&&(Object.assign(this.materialExtension.extraUniforms,this._gbufferUnpackExtension.extraUniforms),Object.assign(this.materialExtension.extraDefines,this._gbufferUnpackExtension.extraDefines)))}};lt([O("Intensity",[0,4]),f(),m()],dt.prototype,"intensity",2),lt([g("Boost"),f(),m()],dt.prototype,"boost",2),lt([O("Object Radius",[.01,2]),f(),m()],dt.prototype,"objectRadius",2),lt([o("Auto radius"),f(),m()],dt.prototype,"autoRadius",2),lt([O("Power",[0,3]),f(),m()],dt.prototype,"power",2),lt([O("Tolerance",[.1,5]),f(),m()],dt.prototype,"tolerance",2),lt([O("Roughness Factor",[.1,1.25]),f(),m({propKey:"ssrRoughnessFactor"})],dt.prototype,"roughnessFactor",2),lt([O("Step count",[1,32],1,{tags:["performance"]}),f(),Z("SSR_STEP_COUNT",void 0,void 0,dt.prototype.setDirty)],dt.prototype,"stepCount",2),lt([O("Ray count",[1,8],1,{tags:["performance"]}),f(),Z("SSR_RAY_COUNT",void 0,void 0,dt.prototype.setDirty)],dt.prototype,"rayCount",2),lt([o("Ray Blend MAX"),f(),v("SSR_RAY_BLEND_MAX",void 0,void 0,dt.prototype.setDirty,!0)],dt.prototype,"rayBlendMax",2),lt([O("Low Quality Frames",[0,4],1),f(),Z("SSR_LOW_QUALITY_FRAMES",void 0,void 0,dt.prototype.setDirty)],dt.prototype,"lowQualityFrames",2),lt([o("Ignore front rays"),f(),v("SSR_MASK_FRONT_RAYS",void 0,void 0,dt.prototype.setDirty)],dt.prototype,"maskFrontRays",2),lt([O("Mask front rays factor",[-1,1],.01,e=>({hidden:()=>!e.maskFrontRays})),f(),m()],dt.prototype,"maskFrontFactor",2),lt([O("Split",[0,1],.01,{tags:["debug"]}),f(),m({propKey:"ssrSplitX",onChange:dt.prototype.setDirty})],dt.prototype,"split",2),dt=lt([E("SSReflection Pass")],dt);var ut=Object.defineProperty,ht=Object.getOwnPropertyDescriptor,pt=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?ht(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&ut(t,r,s),s};let ft=class extends Q{constructor(e=!0,t=_){super(),this.passId="outline",this.extraUniforms={outlineIntensity:{value:1},outlineThickness:{value:2},highlightTransparency:{value:1},outlineColor:{value:new b(15305317)},enableHighlight:{value:!0},dpr:{value:1},outlineBuffer:{value:null},tDiffuseSize:{value:new d(1024,1024)}},this.extraDefines={DEBUG_OUTLINE:"0"},this.priority=-101,this.enableHighlight=!1,this.enableDynamicSelection=!0,this.intensity=2,this.highlightTransparency=.84,this.color=new b(15305317),this.thickness=2,this.debugOutline=!1,this.highlightSelectedMaterials=!1,this.highlightMaterialSameNames=!1,this.transparency=0,this.parsFragmentSnippet=()=>this.isDisabled()?"":K`
36
- ${"uniform sampler2D outlineBuffer;uniform vec2 tDiffuseSize;uniform vec3 outlineColor;uniform float outlineThickness;uniform float outlineIntensity;uniform float highlightTransparency;uniform bool enableHighlight;uniform float dpr;float isSelected(vec2 uv){return 1.-texture2D(outlineBuffer,uv).b;}vec4 outline(in vec4 color){vec2 invSize=1.0/tDiffuseSize;\n#if DEBUG_OUTLINE > 0\ncolor=vec4(0.,0.,0.,1.);\n#endif\nvec3 finalColor=color.rgb;float c=isSelected(vUv);if(c>0.){vec4 uvOffset=1.5*dpr*outlineThickness*vec4(1.0,0.0,-1.0,1.0)*vec4(invSize,invSize);float c1=isSelected(vUv+uvOffset.xy);float c2=isSelected(vUv-uvOffset.xy);float c3=isSelected(vUv+uvOffset.yw);float c4=isSelected(vUv-uvOffset.yw);float diff1=(c1-c2)*0.5;float diff2=(c3-c4)*0.5;float d=length(vec2(diff1,diff2));vec4 highlightColor=enableHighlight ? vec4(c*outlineColor,(1.-highlightTransparency)*c): vec4(0.);vec4 edgeColor=vec4(outlineColor,1.)*vec4(d);float gbufferDepth=getDepth(vUv);float outlineDepth=unpack16(texture2D(outlineBuffer,vUv).xy);outlineDepth*=outlineDepth;outlineDepth-=0.005;if(gbufferDepth<outlineDepth){highlightColor.rgb=highlightColor.rgb*0.3;edgeColor.rgb=edgeColor.rgb*0.5;}vec4 outColor=edgeColor+highlightColor*(1.-d);finalColor=mix(color.rgb,outlineIntensity*outColor.rgb,outColor.a);}else{finalColor.rgb=color.rgb;}return vec4(finalColor.rgb,color.a);}"}
37
- `,this._shaderPatch="diffuseColor = outline(diffuseColor);",this.dependencies=[k,a],this._pickingWidgetDisabled=!1,this.material=new w({uniforms:{cameraNearFar:{value:new d(.1,100)}},vertexShader:"#ifdef USE_ALPHAMAP\n#define USE_UV\n#endif\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec3 vViewPosition;void main(){\n#include <skinbase_vertex>\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <skinning_vertex>\n#include <displacementmap_vertex>\n#include <project_vertex>\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\nvViewPosition=-mvPosition.xyz;}",fragmentShader:"uniform vec2 cameraNearFar;varying vec3 vViewPosition;vec2 pack16(float value){float sMax=65535.0;int v=int(clamp(value,0.0,1.0)*sMax+0.5);int digit0=v/256;int digit1=v-digit0*256;return vec2(float(digit0)/255.0,float(digit1)/255.0);}float linstep(float edge0,float edge1,float value){return clamp((value-edge0)/(edge1-edge0),0.0,1.0);}void main(){float linearZ=linstep(-cameraNearFar.x,-cameraNearFar.y,-vViewPosition.z);vec2 packedZ=pack16(pow(max(0.,linearZ),0.5));gl_FragColor=vec4(packedZ.x,packedZ.y,0.,0.);}",side:P}),this._getSelectedObject=()=>{if(!this._viewer)return null;const e=this._viewer.getPlugin(k);if(this.highlightSelectedMaterials){const t=e?.getSelectedObject()?.material||null;if(this.highlightMaterialSameNames&&t){const e=Array.isArray(t)?t.map(e=>e.name):[t.name],r=/* @__PURE__ */new Set;for(const t of e){const e=this._viewer?.assetManager?.materials?.findMaterialsByName(t);e?.forEach(e=>r.add(e))}return[...r]}return t}const t=e?e.getSelectedObjects?e.getSelectedObjects():[e.getSelectedObject()||null]:null;return t&&t.length>0?1===t.length?t[0]:t:null},this._viewerListeners={preRender:()=>{!this.isDisabled()&&this._viewer&&(this.extraUniforms.dpr.value=2*this._viewer.renderManager.renderScale)}},this.mouseInOutAnimationEnabled=!0,this._state="in",this.enabled=e,this.bufferType=t}setDirty(){if(super.setDirty(),!this._viewer)return;const e=this._viewer.getPlugin(k);let t=!this.isDisabled();if(t){const r=e?.getSelectedObject();"string"==typeof r?.type&&r?.type?.includes("Line")&&(t=!1)}e&&(t&&e.widgetEnabled?(e.widgetEnabled=!1,this._pickingWidgetDisabled=!0):!t&&this._pickingWidgetDisabled&&(e.widgetEnabled=!0,this._pickingWidgetDisabled=!1)),this._viewer.setDirty()}onAdded(e){super.onAdded(e),this.setDirty(),this._pass=this._createPass(),this._pass.onDirty?.push(e.setDirty),e.renderManager.registerPass(this._pass);const t=e.getPlugin(k);t?.addEventListener("selectedObjectChanged",()=>{!this._animationCallBack&&this&&(t?.getSelectedObject()?this.enableDynamicSelection?(this.transparency=1,this._animationCallBack=this._startTransparencyAnimation(1,this.highlightTransparency,400)):this.transparency=this.highlightTransparency:this.transparency=1)}),document.addEventListener("mousemove",r=>{if(!this)return;if(!this.mouseInOutAnimationEnabled)return;if(!this.enableHighlight)return;const i=t?.getSelectedObject();i&&this.enableDynamicSelection?r.target!==e.canvas?this._animationCallBack||"in"!==this._state||(this._animationCallBack=this._startTransparencyAnimation(this.highlightTransparency,1,600),this._state="out"):this._animationCallBack||"out"!==this._state||(this._animationCallBack=this._startTransparencyAnimation(1,this.highlightTransparency,600),this._state="in"):this.transparency=i?this.highlightTransparency:1})}onRemove(e){return this._disposeTarget(),this._pass&&(e.renderManager.unregisterPass(this._pass),this._pass.dispose&&this._pass.dispose()),this._pass=void 0,super.onRemove(e)}_createTarget(e=!0){this._viewer&&(e&&this._disposeTarget(),this.target||(this.target=this._viewer.renderManager.createTarget({sizeMultiplier:1,type:this.bufferType})),this.texture=this.target.texture,this.texture.name="normalBuffer")}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0)}_createPass(){if(this._createTarget(!0),!this.target)throw new Error("OutlinePlugin: target not created");this.material.userData.isOutlinePluginMaterial=!0;return new mt(this.passId,this._getSelectedObject,()=>this.target,this.material)}async _startTransparencyAnimation(e,t,r){return ee(this,"transparency",{from:e,to:t,duration:r,onComplete:()=>{this._animationCallBack=void 0}})}get outlineIntensity(){return console.warn("OutlinePlugin.outlineIntensity is deprecated, use OutlinePlugin.intensity instead"),this.intensity}set outlineIntensity(e){console.warn("OutlinePlugin.outlineIntensity is deprecated, use OutlinePlugin.intensity instead"),this.intensity=e}get outlineColor(){return console.warn("OutlinePlugin.outlineColor is deprecated, use OutlinePlugin.intensity instead"),this.intensity}set outlineColor(e){console.warn("OutlinePlugin.outlineColor is deprecated, use OutlinePlugin.intensity instead"),this.intensity=e}};ft.PluginType="OutlinePlugin",ft.OldPluginType="Outline",pt([B(ft.prototype.setDirty),o("Enable"),f()],ft.prototype,"enabled",2),pt([o("Highlight"),m({propKey:"enableHighlight"}),f()],ft.prototype,"enableHighlight",2),pt([B(ft.prototype.setDirty),o("DynamicSelection"),f()],ft.prototype,"enableDynamicSelection",2),pt([O("Intensity",[0,4],.001),m({propKey:"outlineIntensity"}),f("outlineIntensity")],ft.prototype,"intensity",2),pt([B(ft.prototype.setDirty),O("Transparency",[0,1],.01),f()],ft.prototype,"highlightTransparency",2),pt([re("Color"),m({propKey:"outlineColor"}),f("outlineColor")],ft.prototype,"color",2),pt([O("Thickness",[0,10],.01),m({propKey:"outlineThickness"}),f("outlineThickness")],ft.prototype,"thickness",2),pt([o("Debug"),v("DEBUG_OUTLINE",void 0,!0)],ft.prototype,"debugOutline",2),pt([B(ft.prototype.setDirty),o("Highlight Selected Materials")],ft.prototype,"highlightSelectedMaterials",2),pt([B(ft.prototype.setDirty),o("Highlight Materials (same name)")],ft.prototype,"highlightMaterialSameNames",2),pt([m({propKey:"highlightTransparency"})],ft.prototype,"transparency",2),pt([m({propKey:"outlineBuffer"}),M("Outline Buffer",{readOnly:!0})],ft.prototype,"texture",2),ft=pt([E("Selection Outline")],ft);let mt=class extends te{constructor(e,t,r,i){super(void 0,void 0,i,new b(1,1,1),1),this.passId=e,this._getSelectedObjectOrMaterial=t,this.target=r,this.isOutlineRenderPass=!0,this.enabled=!0,this.before=["render"],this.after=["gbuffer"],this.required=["render","gbuffer"],this.onDirty=[]}render(e,t,r,i,a){if(!this.scene||!this.camera||!this.enabled)return;const s=e.getRenderTarget(),n=e.getActiveCubeFace(),o=e.getActiveMipmapLevel(),l=this._getSelectedObjectOrMaterial();if(l)this._renderSelectedObject(e,l,t||null,i,a);else{e.setRenderTarget(p(this.target)||null);const t=new b;e.getClearColor(t),e.setClearColor(new b(16777215)),e.clear(!0,!0),e.setClearColor(t)}e.setRenderTarget(s,n,o)}_renderSelectedObject(e,t,r,i,a){if(!this.camera||!t)return;const s=(Array.isArray(t)?t:[t]).flatMap(e=>e?.isTexture?[...e.appliedObjects?.values()||[]]:e).flatMap(e=>e?.isMaterial||e?.isBufferGeometry?[...e.appliedMeshes?.values()||[]]:e);for(const l of s)l&&l.traverse(e=>{e.layers.enable(6)});const n=this.camera.layers.mask;this.camera.layers.set(6);const o=e.userData;o||console.error("threejs is not patched?"),o.transmissionRenderTarget=r,e.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!0,transparentRender:!0,transmissionRender:!0,mainRenderPass:!1},()=>super.render(e,r,p(this.target),i,a)),o.transmissionRenderTarget=void 0,s.forEach(e=>e.traverse(e=>{e.layers.disable(6)})),this.camera.layers.mask=n}dispose(){this.onDirty=[],this.scene=void 0,this.camera=void 0,super.dispose?.()}setDirty(){this.onDirty.forEach(e=>e())}beforeRender(e,t,r){this.scene=e,this.camera=t,t.updateShaderProperties(this.overrideMaterial)}};pt([o("Enabled")],mt.prototype,"enabled",2),mt=pt([E(e=>e.passId+" Render Pass")],mt);var gt=Object.defineProperty,vt=(e,t,r,i)=>{for(var a,s=void 0,n=e.length-1;n>=0;n--)(a=e[n])&&(s=a(t,r,s)||s);return s&&gt(t,r,s),s};class _t extends c{constructor(e,t="rgba"){super({vertexShader:h.vertexShader,fragmentShader:"\n// for gbuffer\n#include <packing>\n#define THREE_PACKING_INCLUDED\nuniform vec2 tDiffuseSize;uniform vec2 bilDirection;varying vec2 vUv;uniform bool smoothEnabled;uniform float edgeSharpness;vec4 bilaterialAO(){vec4 color=clamp((texture2D(tDiffuse,vUv.xy)).B_SRC_ACCESSOR,0.,5.);if(!smoothEnabled)return color;float depth;vec3 normal;getDepthNormal(vUv.xy,depth,normal);float gaussianWeights[4];gaussianWeights[0]=0.153170;gaussianWeights[1]=0.144893;gaussianWeights[2]=0.122649;gaussianWeights[3]=0.092902;float Z=gaussianWeights[0]+0.03;vec4 final_colour=Z*color;vec2 nuv;vec4 cc;float dp;vec3 nor;vec2 direction=bilDirection/tDiffuseSize.xy;\n#pragma unroll_loop_start\nfor(int i=0;i<6;i++){direction*=-1.;nuv=vUv+2.*direction*float(UNROLLED_LOOP_INDEX/2+1);getDepthNormal(nuv,dp,nor);if(dp<0.999){float normalCloseness=dot(normal,nor);normalCloseness*=normalCloseness;float normalError=(1.0-normalCloseness)*8.;float normalWeight=max((1.0-normalError*edgeSharpness),0.00);float depthWeight=max(0.0,1.0-edgeSharpness*4000.*abs(depth-dp));float kernelWeight=gaussianWeights[UNROLLED_LOOP_INDEX/2]+0.03;float bilateralWeight=kernelWeight*depthWeight*normalWeight;Z+=bilateralWeight;cc=clamp((texture2D(tDiffuse,nuv)).B_SRC_ACCESSOR,0.,5.);final_colour+=bilateralWeight*cc;}}\n#pragma unroll_loop_end\nfinal_colour/=Z;return final_colour;}void main(){vec4 ao=clamp(bilaterialAO(),vec4(0.),vec4(1.));gl_FragColor=ao;}",uniforms:{bilDirection:{value:new d(1,0)},tDiffuse:{value:null},tDiffuseSize:{value:new d}},defines:{B_SRC_ACCESSOR:t}},"tDiffuse"),this.target=e,this.smoothEnabled=!0,this.edgeSharpness=.1,this.clear=!1,this.needsSwap=!1}render(e,t,r,i,a){if(!this.enabled)return;const s=p(this.target);s&&(this.uniforms.bilDirection.value.set(1,0),this.uniforms.tDiffuse.value=s.texture,this.uniforms.tDiffuseSize.value.set(this.uniforms.tDiffuse.value?.image.width||0,this.uniforms.tDiffuse.value?.image.height||0),super.render(e,t,s,i,a),this.uniforms.bilDirection.value.set(0,1),this.uniforms.tDiffuse.value=t.texture,this.uniforms.tDiffuseSize.value.set(this.uniforms.tDiffuse.value?.image.width||0,this.uniforms.tDiffuse.value?.image.height||0),super.render(e,s,t,i,a))}}vt([f(),m()],_t.prototype,"smoothEnabled"),vt([f(),m()],_t.prototype,"edgeSharpness");var yt=Object.defineProperty,xt=Object.getOwnPropertyDescriptor,St=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?xt(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&yt(t,r,s),s};let bt=class extends i{constructor(e=_,t=1,r=!0){super(),this.passId="ssrtgi",this.dependencies=[a,J],this._gbufferUnpackExtension=void 0,this._gbufferUnpackExtensionChanged=()=>{if(!this._pass||!this._viewer)throw new Error("SSGIPlugin: pass/viewer not created yet");const e=this._viewer.renderManager.gbufferUnpackExtension;this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this._pass.setGBufferUnpackExtension(void 0),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension?this._pass.setGBufferUnpackExtension(this._gbufferUnpackExtension):this._viewer.console.warn("SSGIPlugin: GBuffer unpack extension removed"))},this.enabled=r,this.bufferType=e,this.sizeMultiplier=t}_createTarget(e=!0){this._viewer&&(e&&this._disposeTarget(),this.target||(this.target=this._viewer.renderManager.createTarget({depthBuffer:!1,type:this.bufferType,sizeMultiplier:this.sizeMultiplier})),this.texture=this.target.texture,this.texture.name="ssgiBuffer")}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0)}_createPass(){if(!this._viewer)throw new Error("SSGIPlugin: viewer not set");if(!this._viewer.renderManager.gbufferTarget||!this._viewer.renderManager.gbufferUnpackExtension)throw new Error("SSGIPlugin: GBuffer target not created. GBufferPlugin is required.");return this._createTarget(!0),new wt(this.passId,()=>this.target)}onAdded(e){super.onAdded(e),(e.getPlugin("Ground")||e.getPlugin("BaseGroundPlugin"))&&console.warn("GroundPlugin must be added after SSGIPlugin"),this._gbufferUnpackExtensionChanged(),e.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),e.forPlugin(ke,e=>{this._pass?.material.registerMaterialExtensions([e.unpackExtension])},e=>{this._pass?.material?.unregisterMaterialExtensions([e.unpackExtension])},this)}onRemove(e){return this._disposeTarget(),e.renderManager.removeEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),super.onRemove(e)}fromJSON(e,t){return e.passes?.ssrtgi&&((e={...e}).pass=e.passes.ssrtgi,delete e.passes,void 0!==e.pass.enabled&&(e.enabled=e.pass.enabled)),super.fromJSON(e,t)}_beforeRender(e,t,r){if(!this._viewer)return!1;const i=super._beforeRender(e,t,r);if(i){const e=this._viewer?.getPlugin("SSAOPlugin");e&&!e.isDisabled()&&e.disable(bt.PluginType)}if(!i)return i;const a=this._viewer.getPlugin(s);return this._pass?.updateShaderProperties([a]),i}get rtgiTarget(){return console.warn("SSGIPlugin: rtgiTarget is deprecated, use target instead"),this.target}};bt.PluginType="SSGIPlugin",bt.OldPluginType="SSGI",St([M("SSGI Buffer",{readOnly:!0})],bt.prototype,"texture",2),St([l(void 0,{unwrapContents:!0})],bt.prototype,"_pass",2),bt=St([E("SSGI Plugin")],bt);let wt=class extends c{constructor(e,t,r=!0){super({defines:{RTAO_STEP_COUNT:16,PERSPECTIVE_CAMERA:1},uniforms:{tLastThis:{value:null},tLastFrame:{value:null},screenSize:{value:new d(0,0)},currentFrameCount:{value:0},frameCount:{value:0},cameraNearFar:{value:new d(.1,1e3)},cameraPositionWorld:{value:new F},projection:{value:new u},opacity:{value:1},intensity:{value:0},objectRadius:{value:0},autoRadius:{value:!r},rayCount:{value:.1},bias:{value:.015},falloff:{value:.7},power:{value:1.1},tolerance:{value:0},sceneBoundingRadius:{value:0},currentProjectionViewMatrix:{value:new u},lastProjectionViewMatrix:{value:new u},inverseViewMatrix:{value:new u},ssrtaoSplitX:{value:.5}},vertexShader:V.defaultVertex,fragmentShader:`\nvarying vec2 vUv;\n\n// for gbuffer\n#include <packing>\n#define THREE_PACKING_INCLUDED\n#include <cameraHelpers>\n#include <randomHelpers>\n${st}\n\n${Qe}\n\n${Ee().calculateGI}\n `},"tDiffuse","tLastThis","tLastFrame"),this.target=t,this.before=["render"],this.after=["gbuffer","depth"],this.required=["render","progressive"],this.giEnabled=!0,this.intensity=2,this.power=1.1,this.autoRadius=!0,this.objectRadius=1,this.tolerance=1,this.bias=.001,this.falloff=.7,this.rayCount=4,this.stepCount=8,this.smoothEnabled=!0,this.renderWithCamera=!0,this.split=0,this.materialExtension={extraUniforms:{tSSGIMap:()=>({value:p(this.target)?.texture??null}),ssaoPower:this.material.uniforms.power,ssgiIntensity:this.material.uniforms.intensity,ssrtaoSplitX:this.material.uniforms.ssrtaoSplitX},extraDefines:{SSGI_ENABLED:()=>this.material.defines.SSGI_ENABLED},shaderExtender:(e,t,r)=>{if(!e.defines?.SSRTAO_ENABLED)return;e.fragmentShader=y(e.fragmentShader,"vec3 totalDiffuse =","\n \n \n#if defined(SSRTAO_ENABLED) && SSRTAO_ENABLED > 0\nvec3 screenPos_gi=viewToScreen(vViewPosition.xyz);\n#if SSRTAO_ENABLED == 2\nif(screenPos_gi.x>ssrtaoSplitX){\n#endif\nvec4 ssgi=tSSGIMapTexelToLinear(texture2D(tSSGIMap,screenPos_gi.xy));float ambientOcclusion=1.-ssgi.a;ambientOcclusion=max(0.,ambientOcclusion);ambientOcclusion=pow(ambientOcclusion,ssaoPower);ambientOcclusion=min(1.,ambientOcclusion);reflectedLight.indirectDiffuse*=ambientOcclusion;\n#if defined(SSGI_ENABLED) && SSGI_ENABLED > 0\nvec3 ssgiColor=ssgi.rgb*ssgiIntensity;reflectedLight.indirectDiffuse+=ssgiColor*(material.diffuseColor.rgb);\n#endif\n#if defined( USE_ENVMAP )\nfloat dotNV=saturate(dot(geometryNormal,geometryViewDir));float specularOcclusion=saturate(pow(dotNV+ambientOcclusion,exp2(-16.0*material.roughness-1.0))-1.0+ambientOcclusion);reflectedLight.indirectSpecular*=specularOcclusion;\n#if defined(SSGI_ENABLED) && SSGI_ENABLED > 0\n#if !defined(SSR_ENABLED) || SSR_ENABLED < 1\nreflectedLight.indirectSpecular+=ssgiColor*material.specularColor;\n#endif\n#endif\n#endif\n#if SSRTAO_ENABLED == 2\n}\n#endif\n#endif\n\n \n#if defined(SSGI_ENABLED) && SSGI_ENABLED > 0\n // reflectedLight.directDiffuse = vec3(0.);\n // reflectedLight.indirectDiffuse = vec3(0.);\n // reflectedLight.directSpecular = vec3(0.);\n // reflectedLight.indirectSpecular = vec3(0.);\n#endif \n ",{prepend:!0}),e.fragmentShader=y(e.fragmentShader,"#include <aomap_fragment>","")},onObjectRender:(e,t,r)=>{let i=!this.enabled||!(this.renderWithCamera||r.renderManager.frameCount>1)||!1===r.userData.screenSpaceRendering||t.userData?.pluginsDisabled||t.userData?.ssrtaoDisabled||t.userData?.ssaoDisabled?0:this.split>0?2:1;t.defines.SSRTAO_ENABLED!==i&&(t.defines.SSRTAO_ENABLED=i,t.needsUpdate=!0)},parsFragmentSnippet:e=>K`
1359
+ `,
1360
+ computeCacheKey: () => {
1361
+ return (this.enabled ? "1" : "0") + getOrCall(this.target)?.texture?.colorSpace + Object.values(this.material.defines).map((v) => v + "").join(",");
1362
+ },
1363
+ uuid: SSReflectionPlugin.PluginType,
1364
+ ...uiConfigMaterialExtension(this._getUiConfig.bind(this), SSReflectionPlugin.PluginType),
1365
+ isCompatible: (material) => {
1366
+ return material.isPhysicalMaterial;
1367
+ }
1368
+ };
1369
+ this.passId = pid;
1370
+ this.needsSwap = false;
1371
+ this.clear = true;
1372
+ if (inlineShaderRayTrace) Object.assign(this.materialExtension.extraUniforms, {
1373
+ tNormalDepth: this.material.uniforms.tNormalDepth,
1374
+ tLastFrame: this.material.uniforms.tLastFrame,
1375
+ objectRadius: this.material.uniforms.objectRadius,
1376
+ autoRadius: this.material.uniforms.autoRadius,
1377
+ tolerance: this.material.uniforms.tolerance,
1378
+ ssrRoughnessFactor: this.material.uniforms.ssrRoughnessFactor,
1379
+ frameCount: this.material.uniforms.frameCount,
1380
+ currentFrameCount: this.material.uniforms.currentFrameCount,
1381
+ projection: this.material.uniforms.projection,
1382
+ cameraPositionWorld: this.material.uniforms.cameraPositionWorld,
1383
+ cameraNearFar: this.material.uniforms.cameraNearFar,
1384
+ sceneBoundingRadius: this.material.uniforms.sceneBoundingRadius,
1385
+ currentProjectionViewMatrix: this.material.uniforms.currentProjectionViewMatrix,
1386
+ lastProjectionViewMatrix: this.material.uniforms.lastProjectionViewMatrix,
1387
+ inverseViewMatrix: this.material.uniforms.inverseViewMatrix,
1388
+ ssrSplitX: this.material.uniforms.ssrSplitX
1389
+ });
1390
+ }
1391
+ render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) {
1392
+ if (!this.enabled) return;
1393
+ if (this.inlineShaderRayTrace) {
1394
+ this.needsSwap = false;
1395
+ return;
1396
+ }
1397
+ const target = getOrCall(this.target);
1398
+ if (!target) {
1399
+ console.warn("SSReflectionPluginPass: target not defined. It must be set when inlineShaderRayTrace is false");
1400
+ return;
1401
+ }
1402
+ if (!this.material.defines.HAS_GBUFFER) console.warn("SSReflectionPluginPass: DepthNormalBuffer required for ssrefl");
1403
+ renderer.renderManager.blit(writeBuffer, { source: target.texture });
1404
+ this.uniforms.tLastThis.value = writeBuffer.texture;
1405
+ super.render(renderer, target, readBuffer, deltaTime, maskActive);
1406
+ this.needsSwap = false;
1407
+ }
1408
+ beforeRender(scene, camera, renderManager) {
1409
+ if (!this.enabled) return;
1410
+ this.updateShaderProperties([
1411
+ scene,
1412
+ camera,
1413
+ renderManager
1414
+ ]);
1415
+ }
1416
+ /**
1417
+ * Returns a uiConfig to toggle SSReflection on a material.
1418
+ * This uiConfig is added to each material by extension
1419
+ * @param material
1420
+ * @private
1421
+ */
1422
+ _getUiConfig(material) {
1423
+ return {
1424
+ type: "folder",
1425
+ label: "SSReflection",
1426
+ children: [{
1427
+ type: "checkbox",
1428
+ label: "Enabled",
1429
+ get value() {
1430
+ return !(material.userData.ssreflDisabled ?? false);
1431
+ },
1432
+ set value(v) {
1433
+ if (v === !(material.userData.ssreflDisabled ?? false)) return;
1434
+ material.userData.ssreflDisabled = !v;
1435
+ material.setDirty();
1436
+ },
1437
+ onChange: this.setDirty
1438
+ }, {
1439
+ type: "checkbox",
1440
+ label: "Non Physical",
1441
+ get value() {
1442
+ return material.userData.ssreflNonPhysical ?? false;
1443
+ },
1444
+ set value(v) {
1445
+ if (v === (material.userData.ssreflNonPhysical ?? false)) return;
1446
+ material.userData.ssreflNonPhysical = v;
1447
+ material.setDirty();
1448
+ },
1449
+ onChange: this.setDirty
1450
+ }]
1451
+ };
1452
+ }
1453
+ set uniformsNeedUpdate(value) {
1454
+ this.material.uniformsNeedUpdate = value;
1455
+ this.setDirty();
1456
+ }
1457
+ setGBufferUnpackExtension(extension) {
1458
+ if (this._gbufferUnpackExtension === extension) return;
1459
+ if (this._gbufferUnpackExtension) this.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]);
1460
+ this._gbufferUnpackExtension = extension;
1461
+ if (this._gbufferUnpackExtension) this.material.registerMaterialExtensions([this._gbufferUnpackExtension]);
1462
+ if (!this._gbufferUnpackExtension) return;
1463
+ Object.assign(this.materialExtension.extraUniforms, this._gbufferUnpackExtension.extraUniforms);
1464
+ Object.assign(this.materialExtension.extraDefines, this._gbufferUnpackExtension.extraDefines);
1465
+ }
1466
+ };
1467
+ __decorate([
1468
+ uiSlider("Intensity", [0, 4]),
1469
+ serialize(),
1470
+ uniform()
1471
+ ], SSReflectionPluginPass.prototype, "intensity", void 0);
1472
+ __decorate([
1473
+ uiVector("Boost"),
1474
+ serialize(),
1475
+ uniform()
1476
+ ], SSReflectionPluginPass.prototype, "boost", void 0);
1477
+ __decorate([
1478
+ uiSlider("Object Radius", [.01, 2]),
1479
+ serialize(),
1480
+ uniform()
1481
+ ], SSReflectionPluginPass.prototype, "objectRadius", void 0);
1482
+ __decorate([
1483
+ uiToggle("Auto radius"),
1484
+ serialize(),
1485
+ uniform()
1486
+ ], SSReflectionPluginPass.prototype, "autoRadius", void 0);
1487
+ __decorate([
1488
+ uiSlider("Power", [0, 3]),
1489
+ serialize(),
1490
+ uniform()
1491
+ ], SSReflectionPluginPass.prototype, "power", void 0);
1492
+ __decorate([
1493
+ uiSlider("Tolerance", [.1, 5]),
1494
+ serialize(),
1495
+ uniform()
1496
+ ], SSReflectionPluginPass.prototype, "tolerance", void 0);
1497
+ __decorate([
1498
+ uiSlider("Roughness Factor", [.1, 1.25]),
1499
+ serialize(),
1500
+ uniform({ propKey: "ssrRoughnessFactor" })
1501
+ ], SSReflectionPluginPass.prototype, "roughnessFactor", void 0);
1502
+ __decorate([
1503
+ uiSlider("Step count", [1, 32], 1, { tags: ["performance"] }),
1504
+ serialize(),
1505
+ matDefine("SSR_STEP_COUNT", void 0, void 0, SSReflectionPluginPass.prototype.setDirty)
1506
+ ], SSReflectionPluginPass.prototype, "stepCount", void 0);
1507
+ __decorate([
1508
+ uiSlider("Ray count", [1, 8], 1, { tags: ["performance"] }),
1509
+ serialize(),
1510
+ matDefine("SSR_RAY_COUNT", void 0, void 0, SSReflectionPluginPass.prototype.setDirty)
1511
+ ], SSReflectionPluginPass.prototype, "rayCount", void 0);
1512
+ __decorate([
1513
+ uiToggle("Ray Blend MAX"),
1514
+ serialize(),
1515
+ matDefineBool("SSR_RAY_BLEND_MAX", void 0, void 0, SSReflectionPluginPass.prototype.setDirty, true)
1516
+ ], SSReflectionPluginPass.prototype, "rayBlendMax", void 0);
1517
+ __decorate([
1518
+ uiSlider("Low Quality Frames", [0, 4], 1),
1519
+ serialize(),
1520
+ matDefine("SSR_LOW_QUALITY_FRAMES", void 0, void 0, SSReflectionPluginPass.prototype.setDirty)
1521
+ ], SSReflectionPluginPass.prototype, "lowQualityFrames", void 0);
1522
+ __decorate([
1523
+ uiToggle("Ignore front rays"),
1524
+ serialize(),
1525
+ matDefineBool("SSR_MASK_FRONT_RAYS", void 0, void 0, SSReflectionPluginPass.prototype.setDirty)
1526
+ ], SSReflectionPluginPass.prototype, "maskFrontRays", void 0);
1527
+ __decorate([
1528
+ uiSlider("Mask front rays factor", [-1, 1], .01, (that) => ({ hidden: () => !that.maskFrontRays })),
1529
+ serialize(),
1530
+ uniform()
1531
+ ], SSReflectionPluginPass.prototype, "maskFrontFactor", void 0);
1532
+ __decorate([
1533
+ uiSlider("Split", [0, 1], .01, { tags: ["debug"] }),
1534
+ serialize(),
1535
+ uniform({
1536
+ propKey: "ssrSplitX",
1537
+ onChange: SSReflectionPluginPass.prototype.setDirty
1538
+ })
1539
+ ], SSReflectionPluginPass.prototype, "split", void 0);
1540
+ SSReflectionPluginPass = __decorate([uiFolderContainer("SSReflection Pass")], SSReflectionPluginPass);
1541
+ // src/plugins/postprocessing/shaders/outline.glsl
1542
+ var outline_default = "uniform sampler2D outlineBuffer;uniform vec2 tDiffuseSize;uniform vec3 outlineColor;uniform float outlineThickness;uniform float outlineIntensity;uniform float highlightTransparency;uniform bool enableHighlight;uniform float dpr;float isSelected(vec2 uv){return 1.-texture2D(outlineBuffer,uv).b;}vec4 outline(in vec4 color){vec2 invSize=1.0/tDiffuseSize;\n#if DEBUG_OUTLINE > 0\ncolor=vec4(0.,0.,0.,1.);\n#endif\nvec3 finalColor=color.rgb;float c=isSelected(vUv);if(c>0.){vec4 uvOffset=1.5*dpr*outlineThickness*vec4(1.0,0.0,-1.0,1.0)*vec4(invSize,invSize);float c1=isSelected(vUv+uvOffset.xy);float c2=isSelected(vUv-uvOffset.xy);float c3=isSelected(vUv+uvOffset.yw);float c4=isSelected(vUv-uvOffset.yw);float diff1=(c1-c2)*0.5;float diff2=(c3-c4)*0.5;float d=length(vec2(diff1,diff2));vec4 highlightColor=enableHighlight ? vec4(c*outlineColor,(1.-highlightTransparency)*c): vec4(0.);vec4 edgeColor=vec4(outlineColor,1.)*vec4(d);float gbufferDepth=getDepth(vUv);float outlineDepth=unpack16(texture2D(outlineBuffer,vUv).xy);outlineDepth*=outlineDepth;outlineDepth-=0.005;if(gbufferDepth<outlineDepth){highlightColor.rgb=highlightColor.rgb*0.3;edgeColor.rgb=edgeColor.rgb*0.5;}vec4 outColor=edgeColor+highlightColor*(1.-d);finalColor=mix(color.rgb,outlineIntensity*outColor.rgb,outColor.a);}else{finalColor.rgb=color.rgb;}return vec4(finalColor.rgb,color.a);}";
1543
+ // src/plugins/postprocessing/shaders/outlineDepthVert.glsl
1544
+ var outlineDepthVert_default = "#ifdef USE_ALPHAMAP\n#define USE_UV\n#endif\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec3 vViewPosition;void main(){\n#include <skinbase_vertex>\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <skinning_vertex>\n#include <displacementmap_vertex>\n#include <project_vertex>\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\nvViewPosition=-mvPosition.xyz;}";
1545
+ // src/plugins/postprocessing/shaders/outlineDepthFrag.glsl
1546
+ var outlineDepthFrag_default = "uniform vec2 cameraNearFar;varying vec3 vViewPosition;vec2 pack16(float value){float sMax=65535.0;int v=int(clamp(value,0.0,1.0)*sMax+0.5);int digit0=v/256;int digit1=v-digit0*256;return vec2(float(digit0)/255.0,float(digit1)/255.0);}float linstep(float edge0,float edge1,float value){return clamp((value-edge0)/(edge1-edge0),0.0,1.0);}void main(){float linearZ=linstep(-cameraNearFar.x,-cameraNearFar.y,-vViewPosition.z);vec2 packedZ=pack16(pow(max(0.,linearZ),0.5));gl_FragColor=vec4(packedZ.x,packedZ.y,0.,0.);}";
1547
+ // src/plugins/postprocessing/OutlinePlugin.ts
1548
+ var OutlinePlugin = class OutlinePlugin extends AScreenPassExtensionPlugin {
1549
+ static {
1550
+ this.PluginType = "OutlinePlugin";
1551
+ }
1552
+ static {
1553
+ this.OldPluginType = "Outline";
1554
+ }
1555
+ constructor(enabled = true, bufferType = UnsignedByteType) {
1556
+ super();
1557
+ this.passId = "outline";
1558
+ this.extraUniforms = {
1559
+ outlineIntensity: { value: 1 },
1560
+ outlineThickness: { value: 2 },
1561
+ highlightTransparency: { value: 1 },
1562
+ outlineColor: { value: new Color(15305317) },
1563
+ enableHighlight: { value: true },
1564
+ dpr: { value: 1 },
1565
+ outlineBuffer: { value: null },
1566
+ tDiffuseSize: { value: new Vector2(1024, 1024) }
1567
+ };
1568
+ this.extraDefines = { ["DEBUG_OUTLINE"]: "0" };
1569
+ this.priority = -101;
1570
+ this.enableHighlight = false;
1571
+ this.enableDynamicSelection = true;
1572
+ this.intensity = 2;
1573
+ this.highlightTransparency = .84;
1574
+ this.color = new Color(15305317);
1575
+ this.thickness = 2;
1576
+ this.debugOutline = false;
1577
+ this.highlightSelectedMaterials = false;
1578
+ this.highlightMaterialSameNames = false;
1579
+ this.transparency = 0;
1580
+ this.parsFragmentSnippet = () => {
1581
+ if (this.isDisabled()) return "";
1582
+ return glsl`
1583
+ ${outline_default}
1584
+ `;
1585
+ };
1586
+ this._shaderPatch = "diffuseColor = outline(diffuseColor);";
1587
+ this.dependencies = [PickingPlugin, GBufferPlugin];
1588
+ this._pickingWidgetDisabled = false;
1589
+ this.material = new ShaderMaterial({
1590
+ uniforms: { "cameraNearFar": { value: new Vector2(.1, 100) } },
1591
+ vertexShader: outlineDepthVert_default,
1592
+ fragmentShader: outlineDepthFrag_default,
1593
+ side: DoubleSide
1594
+ });
1595
+ this._getSelectedObject = () => {
1596
+ if (!this._viewer) return null;
1597
+ const picking = this._viewer.getPlugin(PickingPlugin);
1598
+ if (this.highlightSelectedMaterials) {
1599
+ const mat = picking?.getSelectedObject()?.material || null;
1600
+ if (this.highlightMaterialSameNames && mat) {
1601
+ const names = Array.isArray(mat) ? mat.map((m) => m.name) : [mat.name];
1602
+ const mats = /* @__PURE__ */ new Set();
1603
+ for (const name of names) (this._viewer?.assetManager?.materials?.findMaterialsByName(name))?.forEach((m) => mats.add(m));
1604
+ return [...mats];
1605
+ }
1606
+ return mat;
1607
+ }
1608
+ const objects = picking ? picking.getSelectedObjects ? picking.getSelectedObjects() : [picking.getSelectedObject() || null] : null;
1609
+ return objects && objects.length > 0 ? objects.length === 1 ? objects[0] : objects : null;
1610
+ };
1611
+ this._viewerListeners = { preRender: () => {
1612
+ if (this.isDisabled() || !this._viewer) return;
1613
+ this.extraUniforms.dpr.value = this._viewer.renderManager.renderScale * 2;
1614
+ } };
1615
+ this.mouseInOutAnimationEnabled = true;
1616
+ this._state = "in";
1617
+ this.enabled = enabled;
1618
+ this.bufferType = bufferType;
1619
+ }
1620
+ setDirty() {
1621
+ super.setDirty();
1622
+ if (!this._viewer) return;
1623
+ const picking = this._viewer.getPlugin(PickingPlugin);
1624
+ let enabled = !this.isDisabled();
1625
+ if (enabled) {
1626
+ const selected = picking?.getSelectedObject();
1627
+ if (typeof selected?.type === "string" && selected?.type?.includes("Line")) enabled = false;
1628
+ }
1629
+ if (picking) {
1630
+ if (enabled && picking.widgetEnabled) {
1631
+ picking.widgetEnabled = false;
1632
+ this._pickingWidgetDisabled = true;
1633
+ } else if (!enabled && this._pickingWidgetDisabled) {
1634
+ picking.widgetEnabled = true;
1635
+ this._pickingWidgetDisabled = false;
1636
+ }
1637
+ }
1638
+ this._viewer.setDirty();
1639
+ }
1640
+ onAdded(viewer) {
1641
+ super.onAdded(viewer);
1642
+ this.setDirty();
1643
+ this._pass = this._createPass();
1644
+ this._pass.onDirty?.push(viewer.setDirty);
1645
+ viewer.renderManager.registerPass(this._pass);
1646
+ const pickingPlugin = viewer.getPlugin(PickingPlugin);
1647
+ pickingPlugin?.addEventListener("selectedObjectChanged", () => {
1648
+ if (!this._animationCallBack && this) {
1649
+ if (pickingPlugin?.getSelectedObject()) {
1650
+ if (this.enableDynamicSelection) {
1651
+ this.transparency = 1;
1652
+ this._animationCallBack = this._startTransparencyAnimation(1, this.highlightTransparency, 400);
1653
+ } else this.transparency = this.highlightTransparency;
1654
+ } else this.transparency = 1;
1655
+ }
1656
+ });
1657
+ document.addEventListener("mousemove", (e) => {
1658
+ if (!this) return;
1659
+ if (!this.mouseInOutAnimationEnabled) return;
1660
+ if (!this.enableHighlight) return;
1661
+ const selectedObject = pickingPlugin?.getSelectedObject();
1662
+ if (selectedObject && this.enableDynamicSelection) {
1663
+ if (e.target !== viewer.canvas) {
1664
+ if (!this._animationCallBack && this._state === "in") {
1665
+ this._animationCallBack = this._startTransparencyAnimation(this.highlightTransparency, 1, 600);
1666
+ this._state = "out";
1667
+ }
1668
+ } else if (!this._animationCallBack && this._state === "out") {
1669
+ this._animationCallBack = this._startTransparencyAnimation(1, this.highlightTransparency, 600);
1670
+ this._state = "in";
1671
+ }
1672
+ } else this.transparency = selectedObject ? this.highlightTransparency : 1;
1673
+ });
1674
+ }
1675
+ onRemove(viewer) {
1676
+ this._disposeTarget();
1677
+ if (this._pass) {
1678
+ viewer.renderManager.unregisterPass(this._pass);
1679
+ if (this._pass.dispose) this._pass.dispose();
1680
+ }
1681
+ this._pass = void 0;
1682
+ return super.onRemove(viewer);
1683
+ }
1684
+ _createTarget(recreate = true) {
1685
+ if (!this._viewer) return;
1686
+ if (recreate) this._disposeTarget();
1687
+ if (!this.target) this.target = this._viewer.renderManager.createTarget({
1688
+ sizeMultiplier: 1,
1689
+ type: this.bufferType
1690
+ });
1691
+ this.texture = this.target.texture;
1692
+ this.texture.name = "normalBuffer";
1693
+ }
1694
+ _disposeTarget() {
1695
+ if (!this._viewer) return;
1696
+ if (this.target) {
1697
+ this._viewer.renderManager.disposeTarget(this.target);
1698
+ this.target = void 0;
1699
+ }
1700
+ this.texture = void 0;
1701
+ }
1702
+ _createPass() {
1703
+ this._createTarget(true);
1704
+ if (!this.target) throw new Error("OutlinePlugin: target not created");
1705
+ this.material.userData.isOutlinePluginMaterial = true;
1706
+ return new OutlineRenderPass(this.passId, this._getSelectedObject, () => this.target, this.material);
1707
+ }
1708
+ async _startTransparencyAnimation(from, to, duration) {
1709
+ return animateTarget(this, "transparency", {
1710
+ from,
1711
+ to,
1712
+ duration,
1713
+ onComplete: () => {
1714
+ this._animationCallBack = void 0;
1715
+ }
1716
+ });
1717
+ }
1718
+ get outlineIntensity() {
1719
+ console.warn("OutlinePlugin.outlineIntensity is deprecated, use OutlinePlugin.intensity instead");
1720
+ return this.intensity;
1721
+ }
1722
+ set outlineIntensity(v) {
1723
+ console.warn("OutlinePlugin.outlineIntensity is deprecated, use OutlinePlugin.intensity instead");
1724
+ this.intensity = v;
1725
+ }
1726
+ get outlineColor() {
1727
+ console.warn("OutlinePlugin.outlineColor is deprecated, use OutlinePlugin.intensity instead");
1728
+ return this.intensity;
1729
+ }
1730
+ set outlineColor(v) {
1731
+ console.warn("OutlinePlugin.outlineColor is deprecated, use OutlinePlugin.intensity instead");
1732
+ this.intensity = v;
1733
+ }
1734
+ };
1735
+ __decorate([
1736
+ onChange(OutlinePlugin.prototype.setDirty),
1737
+ uiToggle("Enable"),
1738
+ serialize()
1739
+ ], OutlinePlugin.prototype, "enabled", void 0);
1740
+ __decorate([
1741
+ uiToggle("Highlight"),
1742
+ uniform({ propKey: "enableHighlight" }),
1743
+ serialize()
1744
+ ], OutlinePlugin.prototype, "enableHighlight", void 0);
1745
+ __decorate([
1746
+ onChange(OutlinePlugin.prototype.setDirty),
1747
+ uiToggle("DynamicSelection"),
1748
+ serialize()
1749
+ ], OutlinePlugin.prototype, "enableDynamicSelection", void 0);
1750
+ __decorate([
1751
+ uiSlider("Intensity", [0, 4], .001),
1752
+ uniform({ propKey: "outlineIntensity" }),
1753
+ serialize("outlineIntensity")
1754
+ ], OutlinePlugin.prototype, "intensity", void 0);
1755
+ __decorate([
1756
+ onChange(OutlinePlugin.prototype.setDirty),
1757
+ uiSlider("Transparency", [0, 1], .01),
1758
+ serialize()
1759
+ ], OutlinePlugin.prototype, "highlightTransparency", void 0);
1760
+ __decorate([
1761
+ uiColor("Color"),
1762
+ uniform({ propKey: "outlineColor" }),
1763
+ serialize("outlineColor")
1764
+ ], OutlinePlugin.prototype, "color", void 0);
1765
+ __decorate([
1766
+ uiSlider("Thickness", [0, 10], .01),
1767
+ uniform({ propKey: "outlineThickness" }),
1768
+ serialize("outlineThickness")
1769
+ ], OutlinePlugin.prototype, "thickness", void 0);
1770
+ __decorate([uiToggle("Debug"), matDefineBool("DEBUG_OUTLINE", void 0, true)], OutlinePlugin.prototype, "debugOutline", void 0);
1771
+ __decorate([onChange(OutlinePlugin.prototype.setDirty), uiToggle("Highlight Selected Materials")], OutlinePlugin.prototype, "highlightSelectedMaterials", void 0);
1772
+ __decorate([onChange(OutlinePlugin.prototype.setDirty), uiToggle("Highlight Materials (same name)")], OutlinePlugin.prototype, "highlightMaterialSameNames", void 0);
1773
+ __decorate([uniform({ propKey: "highlightTransparency" })], OutlinePlugin.prototype, "transparency", void 0);
1774
+ __decorate([uniform({ propKey: "outlineBuffer" }), uiImage("Outline Buffer", { readOnly: true })], OutlinePlugin.prototype, "texture", void 0);
1775
+ OutlinePlugin = __decorate([uiFolderContainer("Selection Outline")], OutlinePlugin);
1776
+ var OutlineRenderPass = class OutlineRenderPass extends RenderPass {
1777
+ constructor(passId, _getSelectedObjectOrMaterial, target, overrideMaterial) {
1778
+ super(void 0, void 0, overrideMaterial, new Color(1, 1, 1), 1);
1779
+ this.passId = passId;
1780
+ this._getSelectedObjectOrMaterial = _getSelectedObjectOrMaterial;
1781
+ this.target = target;
1782
+ this.isOutlineRenderPass = true;
1783
+ this.enabled = true;
1784
+ this.before = ["render"];
1785
+ this.after = ["gbuffer"];
1786
+ this.required = ["render", "gbuffer"];
1787
+ this.onDirty = [];
1788
+ }
1789
+ /**
1790
+ * Renders to {@link target}
1791
+ * @param renderer
1792
+ * @param writeBuffer - this is ignored? or used as transmissionRenderTarget?
1793
+ * @param _1 - this is ignored
1794
+ * @param deltaTime
1795
+ * @param maskActive
1796
+ */
1797
+ render(renderer, writeBuffer, _1, deltaTime, maskActive) {
1798
+ if (!this.scene || !this.camera || !this.enabled) return;
1799
+ const t = renderer.getRenderTarget();
1800
+ const activeCubeFace = renderer.getActiveCubeFace();
1801
+ const activeMipLevel = renderer.getActiveMipmapLevel();
1802
+ const selectedObject = this._getSelectedObjectOrMaterial();
1803
+ if (selectedObject) this._renderSelectedObject(renderer, selectedObject, writeBuffer || null, deltaTime, maskActive);
1804
+ else {
1805
+ renderer.setRenderTarget(getOrCall(this.target) || null);
1806
+ const color = new Color();
1807
+ renderer.getClearColor(color);
1808
+ renderer.setClearColor(new Color(16777215));
1809
+ renderer.clear(true, true);
1810
+ renderer.setClearColor(color);
1811
+ }
1812
+ renderer.setRenderTarget(t, activeCubeFace, activeMipLevel);
1813
+ }
1814
+ _renderSelectedObject(renderer, selectedObject, writeBuffer, deltaTime, maskActive) {
1815
+ if (!this.camera || !selectedObject) return;
1816
+ const selectionLayer = 6;
1817
+ const objs = (Array.isArray(selectedObject) ? selectedObject : [selectedObject]).flatMap((o) => o?.isTexture ? [...o.appliedObjects?.values() || []] : o).flatMap((o) => o?.isMaterial ? [...o.appliedMeshes?.values() || []] : o?.isBufferGeometry ? [...o.appliedMeshes?.values() || []] : o);
1818
+ for (const o1 of objs) o1 && o1.traverse((o) => {
1819
+ o.layers.enable(selectionLayer);
1820
+ });
1821
+ const mask = this.camera.layers.mask;
1822
+ this.camera.layers.set(selectionLayer);
1823
+ const ud = renderer.userData;
1824
+ if (!ud) console.error("threejs is not patched?");
1825
+ ud.transmissionRenderTarget = writeBuffer;
1826
+ renderer.renderWithModes({
1827
+ shadowMapRender: false,
1828
+ backgroundRender: false,
1829
+ opaqueRender: true,
1830
+ transparentRender: true,
1831
+ transmissionRender: true,
1832
+ mainRenderPass: false
1833
+ }, () => super.render(renderer, writeBuffer, getOrCall(this.target), deltaTime, maskActive));
1834
+ ud.transmissionRenderTarget = void 0;
1835
+ objs.forEach((o1) => o1.traverse((o) => {
1836
+ o.layers.disable(selectionLayer);
1837
+ }));
1838
+ this.camera.layers.mask = mask;
1839
+ }
1840
+ dispose() {
1841
+ this.onDirty = [];
1842
+ this.scene = void 0;
1843
+ this.camera = void 0;
1844
+ super.dispose?.();
1845
+ }
1846
+ setDirty() {
1847
+ this.onDirty.forEach((v) => v());
1848
+ }
1849
+ beforeRender(scene, camera, _) {
1850
+ this.scene = scene;
1851
+ this.camera = camera;
1852
+ camera.updateShaderProperties(this.overrideMaterial);
1853
+ }
1854
+ };
1855
+ __decorate([uiToggle("Enabled")], OutlineRenderPass.prototype, "enabled", void 0);
1856
+ OutlineRenderPass = __decorate([uiFolderContainer((c) => c.passId + " Render Pass")], OutlineRenderPass);
1857
+ // src/plugins/postprocessing/shaders/giPatch.glsl
1858
+ var giPatch_default = "\n#if defined(SSRTAO_ENABLED) && SSRTAO_ENABLED > 0\nvec3 screenPos_gi=viewToScreen(vViewPosition.xyz);\n#if SSRTAO_ENABLED == 2\nif(screenPos_gi.x>ssrtaoSplitX){\n#endif\nvec4 ssgi=tSSGIMapTexelToLinear(texture2D(tSSGIMap,screenPos_gi.xy));float ambientOcclusion=1.-ssgi.a;ambientOcclusion=max(0.,ambientOcclusion);ambientOcclusion=pow(ambientOcclusion,ssaoPower);ambientOcclusion=min(1.,ambientOcclusion);reflectedLight.indirectDiffuse*=ambientOcclusion;\n#if defined(SSGI_ENABLED) && SSGI_ENABLED > 0\nvec3 ssgiColor=ssgi.rgb*ssgiIntensity;reflectedLight.indirectDiffuse+=ssgiColor*(material.diffuseColor.rgb);\n#endif\n#if defined( USE_ENVMAP )\nfloat dotNV=saturate(dot(geometryNormal,geometryViewDir));float specularOcclusion=saturate(pow(dotNV+ambientOcclusion,exp2(-16.0*material.roughness-1.0))-1.0+ambientOcclusion);reflectedLight.indirectSpecular*=specularOcclusion;\n#if defined(SSGI_ENABLED) && SSGI_ENABLED > 0\n#if !defined(SSR_ENABLED) || SSR_ENABLED < 1\nreflectedLight.indirectSpecular+=ssgiColor*material.specularColor;\n#endif\n#endif\n#endif\n#if SSRTAO_ENABLED == 2\n}\n#endif\n#endif\n";
1859
+ // src/passes/shaders/ssaoBilateral.glsl
1860
+ var ssaoBilateral_default = "uniform vec2 tDiffuseSize;uniform vec2 bilDirection;varying vec2 vUv;uniform bool smoothEnabled;uniform float edgeSharpness;vec4 bilaterialAO(){vec4 color=clamp((texture2D(tDiffuse,vUv.xy)).B_SRC_ACCESSOR,0.,5.);if(!smoothEnabled)return color;float depth;vec3 normal;getDepthNormal(vUv.xy,depth,normal);float gaussianWeights[4];gaussianWeights[0]=0.153170;gaussianWeights[1]=0.144893;gaussianWeights[2]=0.122649;gaussianWeights[3]=0.092902;float Z=gaussianWeights[0]+0.03;vec4 final_colour=Z*color;vec2 nuv;vec4 cc;float dp;vec3 nor;vec2 direction=bilDirection/tDiffuseSize.xy;\n#pragma unroll_loop_start\nfor(int i=0;i<6;i++){direction*=-1.;nuv=vUv+2.*direction*float(UNROLLED_LOOP_INDEX/2+1);getDepthNormal(nuv,dp,nor);if(dp<0.999){float normalCloseness=dot(normal,nor);normalCloseness*=normalCloseness;float normalError=(1.0-normalCloseness)*8.;float normalWeight=max((1.0-normalError*edgeSharpness),0.00);float depthWeight=max(0.0,1.0-edgeSharpness*4000.*abs(depth-dp));float kernelWeight=gaussianWeights[UNROLLED_LOOP_INDEX/2]+0.03;float bilateralWeight=kernelWeight*depthWeight*normalWeight;Z+=bilateralWeight;cc=clamp((texture2D(tDiffuse,nuv)).B_SRC_ACCESSOR,0.,5.);final_colour+=bilateralWeight*cc;}}\n#pragma unroll_loop_end\nfinal_colour/=Z;return final_colour;}void main(){vec4 ao=clamp(bilaterialAO(),vec4(0.),vec4(1.));gl_FragColor=ao;}";
1861
+ // src/passes/BilateralFilterPass.ts
1862
+ var BilateralFilterPass = class extends ExtendedShaderPass {
1863
+ constructor(target, sourceAccessor = "rgba") {
1864
+ super({
1865
+ vertexShader: CopyShader.vertexShader,
1866
+ fragmentShader: `
1867
+ // for gbuffer
1868
+ #include <packing>
1869
+ #define THREE_PACKING_INCLUDED
1870
+ ` + ssaoBilateral_default,
1871
+ uniforms: {
1872
+ bilDirection: { value: new Vector2(1, 0) },
1873
+ tDiffuse: { value: null },
1874
+ tDiffuseSize: { value: new Vector2() }
1875
+ },
1876
+ defines: { ["B_SRC_ACCESSOR"]: sourceAccessor }
1877
+ }, "tDiffuse");
1878
+ this.target = target;
1879
+ this.smoothEnabled = true;
1880
+ this.edgeSharpness = .1;
1881
+ this.clear = false;
1882
+ this.needsSwap = false;
1883
+ }
1884
+ render(renderer, writeBuffer, _readBuffer, deltaTime, maskActive) {
1885
+ if (!this.enabled) return;
1886
+ const target = getOrCall(this.target);
1887
+ if (!target) return;
1888
+ this.uniforms.bilDirection.value.set(1, 0);
1889
+ this.uniforms.tDiffuse.value = target.texture;
1890
+ this.uniforms.tDiffuseSize.value.set(this.uniforms.tDiffuse.value?.image.width || 0, this.uniforms.tDiffuse.value?.image.height || 0);
1891
+ super.render(renderer, writeBuffer, target, deltaTime, maskActive);
1892
+ this.uniforms.bilDirection.value.set(0, 1);
1893
+ this.uniforms.tDiffuse.value = writeBuffer.texture;
1894
+ this.uniforms.tDiffuseSize.value.set(this.uniforms.tDiffuse.value?.image.width || 0, this.uniforms.tDiffuse.value?.image.height || 0);
1895
+ super.render(renderer, target, writeBuffer, deltaTime, maskActive);
1896
+ }
1897
+ };
1898
+ __decorate([serialize(), uniform()], BilateralFilterPass.prototype, "smoothEnabled", void 0);
1899
+ __decorate([serialize(), uniform()], BilateralFilterPass.prototype, "edgeSharpness", void 0);
1900
+ // src/plugins/postprocessing/SSGIPlugin.ts
1901
+ var _SSGIPlugin;
1902
+ var passId = "ssrtgi";
1903
+ var SSGIPlugin = class SSGIPlugin extends PipelinePassPlugin {
1904
+ static {
1905
+ _SSGIPlugin = this;
1906
+ }
1907
+ static {
1908
+ this.PluginType = "SSGIPlugin";
1909
+ }
1910
+ static {
1911
+ this.OldPluginType = "SSGI";
1912
+ }
1913
+ constructor(bufferType = UnsignedByteType, sizeMultiplier = 1, enabled = true) {
1914
+ super();
1915
+ this.passId = passId;
1916
+ this.dependencies = [GBufferPlugin, SSAAPlugin];
1917
+ this._gbufferUnpackExtension = void 0;
1918
+ this._gbufferUnpackExtensionChanged = () => {
1919
+ if (!this._pass || !this._viewer) throw new Error("SSGIPlugin: pass/viewer not created yet");
1920
+ const newExtension = this._viewer.renderManager.gbufferUnpackExtension;
1921
+ if (this._gbufferUnpackExtension === newExtension) return;
1922
+ if (this._gbufferUnpackExtension) this._pass.setGBufferUnpackExtension(void 0);
1923
+ this._gbufferUnpackExtension = newExtension;
1924
+ if (this._gbufferUnpackExtension) this._pass.setGBufferUnpackExtension(this._gbufferUnpackExtension);
1925
+ else this._viewer.console.warn("SSGIPlugin: GBuffer unpack extension removed");
1926
+ };
1927
+ this._releaseSsao = () => {
1928
+ if (this.isDisabled()) this._viewer?.getPlugin("SSAOPlugin")?.enable(_SSGIPlugin.PluginType);
1929
+ };
1930
+ this.enabled = enabled;
1931
+ this.bufferType = bufferType;
1932
+ this.sizeMultiplier = sizeMultiplier;
1933
+ }
1934
+ _createTarget(recreate = true) {
1935
+ if (!this._viewer) return;
1936
+ if (recreate) this._disposeTarget();
1937
+ if (!this.target) this.target = this._viewer.renderManager.createTarget({
1938
+ depthBuffer: false,
1939
+ type: this.bufferType,
1940
+ sizeMultiplier: this.sizeMultiplier
1941
+ });
1942
+ this.texture = this.target.texture;
1943
+ this.texture.name = "ssgiBuffer";
1944
+ }
1945
+ _disposeTarget() {
1946
+ if (!this._viewer) return;
1947
+ if (this.target) {
1948
+ this._viewer.renderManager.disposeTarget(this.target);
1949
+ this.target = void 0;
1950
+ }
1951
+ this.texture = void 0;
1952
+ }
1953
+ _createPass() {
1954
+ if (!this._viewer) throw new Error("SSGIPlugin: viewer not set");
1955
+ if (!this._viewer.renderManager.gbufferTarget || !this._viewer.renderManager.gbufferUnpackExtension) throw new Error("SSGIPlugin: GBuffer target not created. GBufferPlugin is required.");
1956
+ this._createTarget(true);
1957
+ return new SSGIPluginPass(this.passId, () => this.target);
1958
+ }
1959
+ onAdded(viewer) {
1960
+ super.onAdded(viewer);
1961
+ if (viewer.getPlugin("Ground") || viewer.getPlugin("BaseGroundPlugin")) console.warn("GroundPlugin must be added after SSGIPlugin");
1962
+ this._gbufferUnpackExtensionChanged();
1963
+ viewer.renderManager.addEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
1964
+ viewer.addEventListener("preFrame", this._releaseSsao);
1965
+ viewer.forPlugin(VelocityBufferPlugin, (vbp) => {
1966
+ this._pass?.material.registerMaterialExtensions([vbp.unpackExtension]);
1967
+ }, (vbp) => {
1968
+ this._pass?.material?.unregisterMaterialExtensions([vbp.unpackExtension]);
1969
+ }, this);
1970
+ }
1971
+ onRemove(viewer) {
1972
+ this._disposeTarget();
1973
+ viewer.renderManager.removeEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
1974
+ viewer.removeEventListener("preFrame", this._releaseSsao);
1975
+ viewer.getPlugin("SSAOPlugin")?.enable(_SSGIPlugin.PluginType);
1976
+ return super.onRemove(viewer);
1977
+ }
1978
+ fromJSON(data, meta) {
1979
+ if (data.passes?.ssrtgi) {
1980
+ data = { ...data };
1981
+ data.pass = data.passes.ssrtgi;
1982
+ delete data.passes;
1983
+ if (data.pass.enabled !== void 0) data.enabled = data.pass.enabled;
1984
+ }
1985
+ return super.fromJSON(data, meta);
1986
+ }
1987
+ _beforeRender(_, _1, _2) {
1988
+ if (!this._viewer) return false;
1989
+ const e = super._beforeRender(_, _1, _2);
1990
+ if (e) {
1991
+ const ssao = this._viewer?.getPlugin("SSAOPlugin");
1992
+ if (ssao && !ssao.isDisabled()) ssao.disable(_SSGIPlugin.PluginType);
1993
+ }
1994
+ if (!e) return e;
1995
+ const progressive = this._viewer.getPlugin(ProgressivePlugin);
1996
+ this._pass?.updateShaderProperties([progressive]);
1997
+ return e;
1998
+ }
1999
+ /**
2000
+ * @deprecated use {@link target} instead
2001
+ */
2002
+ get rtgiTarget() {
2003
+ console.warn("SSGIPlugin: rtgiTarget is deprecated, use target instead");
2004
+ return this.target;
2005
+ }
2006
+ };
2007
+ __decorate([uiImage("SSGI Buffer", { readOnly: true })], SSGIPlugin.prototype, "texture", void 0);
2008
+ __decorate([uiConfig(void 0, { unwrapContents: true })], SSGIPlugin.prototype, "_pass", void 0);
2009
+ SSGIPlugin = _SSGIPlugin = __decorate([uiFolderContainer("SSGI Plugin")], SSGIPlugin);
2010
+ var SSGIPluginPass = class SSGIPluginPass extends ExtendedShaderPass {
2011
+ constructor(pid, target, giEnabled = true) {
2012
+ super({
2013
+ defines: {
2014
+ ["RTAO_STEP_COUNT"]: 16,
2015
+ ["PERSPECTIVE_CAMERA"]: 1
2016
+ },
2017
+ uniforms: {
2018
+ tLastThis: { value: null },
2019
+ tLastFrame: { value: null },
2020
+ screenSize: { value: new Vector2(0, 0) },
2021
+ currentFrameCount: { value: 0 },
2022
+ frameCount: { value: 0 },
2023
+ cameraNearFar: { value: new Vector2(.1, 1e3) },
2024
+ cameraPositionWorld: { value: new Vector3() },
2025
+ projection: { value: new Matrix4() },
2026
+ opacity: { value: 1 },
2027
+ intensity: { value: 0 },
2028
+ objectRadius: { value: 0 },
2029
+ autoRadius: { value: giEnabled ? false : true },
2030
+ rayCount: { value: .1 },
2031
+ bias: { value: .015 },
2032
+ falloff: { value: .7 },
2033
+ power: { value: 1.1 },
2034
+ tolerance: { value: 0 },
2035
+ sceneBoundingRadius: { value: 0 },
2036
+ currentProjectionViewMatrix: { value: new Matrix4() },
2037
+ lastProjectionViewMatrix: { value: new Matrix4() },
2038
+ inverseViewMatrix: { value: new Matrix4() },
2039
+ ssrtaoSplitX: { value: .5 }
2040
+ },
2041
+ vertexShader: shaderUtils.defaultVertex,
2042
+ fragmentShader: `
2043
+ varying vec2 vUv;
2044
+
2045
+ // for gbuffer
2046
+ #include <packing>
2047
+ #define THREE_PACKING_INCLUDED
2048
+ #include <cameraHelpers>
2049
+ #include <randomHelpers>
2050
+ ${samplePointHelpers_default}
2051
+
2052
+ ${ssrt_default}
2053
+
2054
+ ${getShaders().calculateGI}
2055
+ `
2056
+ }, "tDiffuse", "tLastThis", "tLastFrame");
2057
+ this.target = target;
2058
+ this.before = ["render"];
2059
+ this.after = ["gbuffer", "depth"];
2060
+ this.required = ["render", "progressive"];
2061
+ this.giEnabled = true;
2062
+ this.intensity = 2;
2063
+ this.power = 1.1;
2064
+ this.autoRadius = true;
2065
+ this.objectRadius = 1;
2066
+ this.tolerance = 1;
2067
+ this.bias = .001;
2068
+ this.falloff = .7;
2069
+ this.rayCount = 4;
2070
+ this.stepCount = 8;
2071
+ this.smoothEnabled = true;
2072
+ this.renderWithCamera = true;
2073
+ this.split = 0;
2074
+ this.materialExtension = {
2075
+ extraUniforms: {
2076
+ tSSGIMap: () => ({ value: getOrCall(this.target)?.texture ?? null }),
2077
+ ssaoPower: this.material.uniforms.power,
2078
+ ssgiIntensity: this.material.uniforms.intensity,
2079
+ ssrtaoSplitX: this.material.uniforms.ssrtaoSplitX
2080
+ },
2081
+ extraDefines: { ["SSGI_ENABLED"]: () => this.material.defines.SSGI_ENABLED },
2082
+ shaderExtender: (shader, _material, _renderer) => {
2083
+ if (!shader.defines?.SSRTAO_ENABLED) return;
2084
+ const ls = `
2085
+
2086
+ ${giPatch_default}
2087
+
2088
+ #if defined(SSGI_ENABLED) && SSGI_ENABLED > 0
2089
+ // reflectedLight.directDiffuse = vec3(0.);
2090
+ // reflectedLight.indirectDiffuse = vec3(0.);
2091
+ // reflectedLight.directSpecular = vec3(0.);
2092
+ // reflectedLight.indirectSpecular = vec3(0.);
2093
+ #endif
2094
+ `;
2095
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "vec3 totalDiffuse =", ls, { prepend: true });
2096
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#include <aomap_fragment>", "");
2097
+ },
2098
+ onObjectRender: (_object, material, renderer) => {
2099
+ let x = this.enabled && (this.renderWithCamera || renderer.renderManager.frameCount > 1) && renderer.userData.screenSpaceRendering !== false && !material.userData?.pluginsDisabled && !material.userData?.ssgiDisabled && !material.userData?.ssrtaoDisabled && !material.userData?.ssaoDisabled ? this.split > 0 ? 2 : 1 : 0;
2100
+ if (material.defines.SSRTAO_ENABLED !== x) {
2101
+ material.defines.SSRTAO_ENABLED = x;
2102
+ material.needsUpdate = true;
2103
+ }
2104
+ },
2105
+ parsFragmentSnippet: (_renderer) => glsl`
38
2106
  #if defined(SSRTAO_ENABLED) && SSRTAO_ENABLED > 0
39
2107
  uniform float ssaoPower;
40
2108
  uniform float ssgiIntensity;
@@ -42,23 +2110,976 @@ var e,t;import{RenderManager as r,PipelinePassPlugin as i,GBufferPlugin as a,Pro
42
2110
  #if defined(SSRTAO_ENABLED) && SSRTAO_ENABLED == 2
43
2111
  uniform float ssrtaoSplitX;
44
2112
  #endif
45
- ${$("tSSGIMap",p(this.target)?.texture.colorSpace)}
2113
+ ${getTexelDecoding("tSSGIMap", getOrCall(this.target)?.texture.colorSpace)}
46
2114
  ${""}
47
2115
  #include <simpleCameraHelpers>
48
2116
  #endif
49
- `,computeCacheKey:()=>{const e=p(this.target)?.texture;return(this.enabled?"1":"0")+e?.colorSpace+e?.uuid+Object.values(this.material.defines).map(e=>e+"").join(",")},uuid:bt.PluginType,...C(this._getUiConfig.bind(this),bt.PluginType),isCompatible:e=>e.isPhysicalMaterial},this.passId=e,this.needsSwap=!0,this.clear=!0,this.giEnabled=r,this.bilateralPass=new _t(this.target,"rgba")}render(e,t,r,i,a){if(!this.enabled)return;if(this.needsSwap=!1,!this.renderWithCamera&&e.renderManager.frameCount<2)return;const s=p(this.target);s?(e.renderManager.blit(t,{source:s.texture}),this.material.defines.HAS_GBUFFER||console.warn("SSGIPluginPass: DepthNormalBuffer required for ssrtao/ssgi"),this.uniforms.tLastThis.value=t.texture,super.render(e,s,r,i,a),this.smoothEnabled&&this.bilateralPass.render(e,t,r,i,a),this.uniforms.lastProjectionViewMatrix.value.copy(this.uniforms.currentProjectionViewMatrix.value)):console.warn("SSGIPluginPass: target not defined.")}beforeRender(e,t,r){this.enabled&&(this.updateShaderProperties([e,t,r]),this.uniforms.currentProjectionViewMatrix.value.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this.uniforms.inverseViewMatrix.value.copy(t.matrixWorld))}_getUiConfig(e){return{type:"folder",label:"SSGI",children:[{type:"checkbox",label:"Enabled",get value(){return!e.userData.ssgiDisabled},set value(t){t!==!e.userData.ssgiDisabled&&(e.userData.ssgiDisabled=!t,e.setDirty())},onChange:this.setDirty}]}}set uniformsNeedUpdate(e){this.material.uniformsNeedUpdate=e,this.setDirty()}setGBufferUnpackExtension(e){this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&(this.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]),this.bilateralPass.material.unregisterMaterialExtensions([this._gbufferUnpackExtension])),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension&&(this.material.registerMaterialExtensions([this._gbufferUnpackExtension]),this.bilateralPass.material.registerMaterialExtensions([this._gbufferUnpackExtension])),this._gbufferUnpackExtension)}setDirty(){this.materialExtension?.setDirty?.(),super.setDirty()}};St([f()],wt.prototype,"bilateralPass",2),St([o("GI Enabled"),f(),v("SSGI_ENABLED",void 0,void 0,wt.prototype.setDirty,!1)],wt.prototype,"giEnabled",2),St([O("Intensity",[0,4]),f(),m()],wt.prototype,"intensity",2),St([O("Power",[0,3]),f(),m()],wt.prototype,"power",2),St([o("Auto radius"),f(),m()],wt.prototype,"autoRadius",2),St([O("Object Radius",[.01,10]),f(),m()],wt.prototype,"objectRadius",2),St([O("Tolerance",[.1,5]),f(),m()],wt.prototype,"tolerance",2),St([O("Bias",[-.3,.3]),f(),m()],wt.prototype,"bias",2),St([O("Falloff",[1e-4,4]),f(),m()],wt.prototype,"falloff",2),St([O("Ray Count",[1,5],1,{tags:["performance"]}),f(),m()],wt.prototype,"rayCount",2),St([O("Step count",[1,16],1,{tags:["performance"]}),f(),Z("RTAO_STEP_COUNT",void 0,void 0,wt.prototype.setDirty)],wt.prototype,"stepCount",2),St([o("Smooth Enabled"),f()],wt.prototype,"smoothEnabled",2),St([o("Render with Camera")],wt.prototype,"renderWithCamera",2),St([O("Split",[0,1],.01,{tags:["debug"]}),f(),m({propKey:"ssrtaoSplitX",onChange:wt.prototype.setDirty})],wt.prototype,"split",2),wt=St([E("SSGI Pass")],wt);var Tt=Object.defineProperty,Dt=Object.getOwnPropertyDescriptor,Pt=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?Dt(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&Tt(t,r,s),s};const Mt=r.ShaderChunk;let Et=class extends Y{constructor(){super(),this.enabled=!0,this._defines={},this._uniforms={anisotropyFactor:{value:1},anisotropyNoise:{value:1},anisotropyDirection:{value:1},anisotropyDirectionMap:{value:null},anisotropy2MapUvTransform:{value:new D},frameCount:{value:0}},this.materialExtension={uuid:Et.PluginType,priority:10,shaderExtender:(e,t,r)=>{if(this.isDisabled()||!t?.userData._isAnisotropic)return;const i=t.userData?._anisotropyDirectionMap,a=K`
2117
+ `,
2118
+ computeCacheKey: () => {
2119
+ const tex = getOrCall(this.target)?.texture;
2120
+ return (this.enabled ? "1" : "0") + tex?.colorSpace + tex?.uuid + Object.values(this.material.defines).map((v) => v + "").join(",");
2121
+ },
2122
+ uuid: SSGIPlugin.PluginType,
2123
+ ...uiConfigMaterialExtension(this._getUiConfig.bind(this), SSGIPlugin.PluginType),
2124
+ isCompatible: (material) => {
2125
+ return material.isPhysicalMaterial;
2126
+ }
2127
+ };
2128
+ this.passId = pid;
2129
+ this.needsSwap = true;
2130
+ this.clear = true;
2131
+ this.giEnabled = giEnabled;
2132
+ this.bilateralPass = new BilateralFilterPass(this.target, "rgba");
2133
+ }
2134
+ render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) {
2135
+ if (!this.enabled) return;
2136
+ this.needsSwap = false;
2137
+ if (!this.renderWithCamera && renderer.renderManager.frameCount < 2) return;
2138
+ const target = getOrCall(this.target);
2139
+ if (!target) {
2140
+ console.warn("SSGIPluginPass: target not defined.");
2141
+ return;
2142
+ }
2143
+ renderer.renderManager.blit(writeBuffer, { source: target.texture });
2144
+ if (!this.material.defines.HAS_GBUFFER) console.warn("SSGIPluginPass: DepthNormalBuffer required for ssrtao/ssgi");
2145
+ this.uniforms.tLastThis.value = writeBuffer.texture;
2146
+ super.render(renderer, target, readBuffer, deltaTime, maskActive);
2147
+ if (this.smoothEnabled) this.bilateralPass.render(renderer, writeBuffer, readBuffer, deltaTime, maskActive);
2148
+ this.uniforms.lastProjectionViewMatrix.value.copy(this.uniforms.currentProjectionViewMatrix.value);
2149
+ }
2150
+ beforeRender(scene, camera, renderManager) {
2151
+ if (!this.enabled) return;
2152
+ this.updateShaderProperties([
2153
+ scene,
2154
+ camera,
2155
+ renderManager
2156
+ ]);
2157
+ this.uniforms.currentProjectionViewMatrix.value.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
2158
+ this.uniforms.inverseViewMatrix.value.copy(camera.matrixWorld);
2159
+ }
2160
+ /**
2161
+ * Returns a uiConfig to toggle SSGI on a material.
2162
+ * This uiConfig is added to each material by extension
2163
+ * @param material
2164
+ * @private
2165
+ */
2166
+ _getUiConfig(material) {
2167
+ return {
2168
+ type: "folder",
2169
+ label: "SSGI",
2170
+ children: [{
2171
+ type: "checkbox",
2172
+ label: "Enabled",
2173
+ get value() {
2174
+ return !(material.userData.ssgiDisabled ?? false);
2175
+ },
2176
+ set value(v) {
2177
+ if (v === !(material.userData.ssgiDisabled ?? false)) return;
2178
+ material.userData.ssgiDisabled = !v;
2179
+ material.setDirty();
2180
+ },
2181
+ onChange: this.setDirty
2182
+ }]
2183
+ };
2184
+ }
2185
+ set uniformsNeedUpdate(value) {
2186
+ this.material.uniformsNeedUpdate = value;
2187
+ this.setDirty();
2188
+ }
2189
+ setGBufferUnpackExtension(extension) {
2190
+ if (this._gbufferUnpackExtension === extension) return;
2191
+ if (this._gbufferUnpackExtension) {
2192
+ this.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]);
2193
+ this.bilateralPass.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]);
2194
+ }
2195
+ this._gbufferUnpackExtension = extension;
2196
+ if (this._gbufferUnpackExtension) {
2197
+ this.material.registerMaterialExtensions([this._gbufferUnpackExtension]);
2198
+ this.bilateralPass.material.registerMaterialExtensions([this._gbufferUnpackExtension]);
2199
+ }
2200
+ if (!this._gbufferUnpackExtension) return;
2201
+ }
2202
+ setDirty() {
2203
+ this.materialExtension?.setDirty?.();
2204
+ super.setDirty();
2205
+ }
2206
+ };
2207
+ __decorate([serialize()], SSGIPluginPass.prototype, "bilateralPass", void 0);
2208
+ __decorate([
2209
+ uiToggle("GI Enabled"),
2210
+ serialize(),
2211
+ matDefineBool("SSGI_ENABLED", void 0, void 0, SSGIPluginPass.prototype.setDirty, false)
2212
+ ], SSGIPluginPass.prototype, "giEnabled", void 0);
2213
+ __decorate([
2214
+ uiSlider("Intensity", [0, 4]),
2215
+ serialize(),
2216
+ uniform()
2217
+ ], SSGIPluginPass.prototype, "intensity", void 0);
2218
+ __decorate([
2219
+ uiSlider("Power", [0, 3]),
2220
+ serialize(),
2221
+ uniform()
2222
+ ], SSGIPluginPass.prototype, "power", void 0);
2223
+ __decorate([
2224
+ uiToggle("Auto radius"),
2225
+ serialize(),
2226
+ uniform()
2227
+ ], SSGIPluginPass.prototype, "autoRadius", void 0);
2228
+ __decorate([
2229
+ uiSlider("Object Radius", [.01, 10]),
2230
+ serialize(),
2231
+ uniform()
2232
+ ], SSGIPluginPass.prototype, "objectRadius", void 0);
2233
+ __decorate([
2234
+ uiSlider("Tolerance", [.1, 5]),
2235
+ serialize(),
2236
+ uniform()
2237
+ ], SSGIPluginPass.prototype, "tolerance", void 0);
2238
+ __decorate([
2239
+ uiSlider("Bias", [-.3, .3]),
2240
+ serialize(),
2241
+ uniform()
2242
+ ], SSGIPluginPass.prototype, "bias", void 0);
2243
+ __decorate([
2244
+ uiSlider("Falloff", [1e-4, 4]),
2245
+ serialize(),
2246
+ uniform()
2247
+ ], SSGIPluginPass.prototype, "falloff", void 0);
2248
+ __decorate([
2249
+ uiSlider("Ray Count", [1, 5], 1, { tags: ["performance"] }),
2250
+ serialize(),
2251
+ uniform()
2252
+ ], SSGIPluginPass.prototype, "rayCount", void 0);
2253
+ __decorate([
2254
+ uiSlider("Step count", [1, 16], 1, { tags: ["performance"] }),
2255
+ serialize(),
2256
+ matDefine("RTAO_STEP_COUNT", void 0, void 0, SSGIPluginPass.prototype.setDirty)
2257
+ ], SSGIPluginPass.prototype, "stepCount", void 0);
2258
+ __decorate([uiToggle("Smooth Enabled"), serialize()], SSGIPluginPass.prototype, "smoothEnabled", void 0);
2259
+ __decorate([uiToggle("Render with Camera")], SSGIPluginPass.prototype, "renderWithCamera", void 0);
2260
+ __decorate([
2261
+ uiSlider("Split", [0, 1], .01, { tags: ["debug"] }),
2262
+ serialize(),
2263
+ uniform({
2264
+ propKey: "ssrtaoSplitX",
2265
+ onChange: SSGIPluginPass.prototype.setDirty
2266
+ })
2267
+ ], SSGIPluginPass.prototype, "split", void 0);
2268
+ SSGIPluginPass = __decorate([uiFolderContainer("SSGI Pass")], SSGIPluginPass);
2269
+ // src/plugins/extras/shaders/anisotropyBsdf.glsl
2270
+ var anisotropyBsdf_default = "uniform float anisotropyFactor;uniform float anisotropyNoise;\n#if ANISOTROPY_TEX_MODE == 0\nuniform float anisotropyDirection;\n#else\nuniform sampler2D anisotropyDirectionMap;varying vec2 vAnisotropy2MapUv;\n#endif\nconst float MIN_ROUGHNESS=0.05;vec3 indirectAnisotropyBentNormal(const in vec3 normal,const in vec3 viewDir,const in float roughness,const in vec3 anisotropicT,const in vec3 anisotropicB){vec3 aDirection=anisotropyFactor>=0.0 ? anisotropicB : anisotropicT;vec3 aTangent=cross(aDirection,viewDir);vec3 aNormal=cross(aTangent,aDirection);float bendFactor=abs(anisotropyFactor)*saturate(5.0*max(roughness,MIN_ROUGHNESS));return normalize(mix(normal,aNormal,bendFactor));}vec3 BRDF_GGX_Anisotropy(const in vec3 lightDir,const in vec3 viewDir,const in vec3 normal,const in vec3 f0,const in float f90,const in float roughness,const in vec3 anisotropicT,const in vec3 anisotropicB){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));float dotTV=dot(anisotropicT,viewDir);float dotBV=dot(anisotropicB,viewDir);float dotTL=dot(anisotropicT,lightDir);float dotBL=dot(anisotropicB,lightDir);float dotTH=dot(anisotropicT,halfDir);float dotBH=dot(anisotropicB,halfDir);float aspect=sqrt(1.0-min(1.-MIN_ROUGHNESS,abs(anisotropyFactor)*0.9));if(anisotropyFactor>0.0)aspect=1.0/aspect;float at=roughness*aspect;float ab=roughness/aspect;vec3 F=F_Schlick(f0,f90,dotVH);float V=V_GGX_SmithCorrelated_Anisotropic(at,ab,dotTV,dotBV,dotTL,dotBL,dotNV,dotNL);float D=D_GGX_Anisotropic(at,ab,dotTH,dotBH,dotNH);return F*(V*D);}";
2271
+ // src/plugins/extras/shaders/anisotropyTBN.glsl
2272
+ var anisotropyTBN_default = "float rnd=(random2(vUv.xy,frameCount)-0.5)*anisotropyNoise*material.roughness;\n#if ANISOTROPY_TEX_MODE < 2\n#if ANISOTROPY_TEX_MODE == 0\nfloat rot=saturate(anisotropyDirection);\n#else\nfloat rot=(anisotropyDirectionMapTexelToLinear(texture2D(anisotropyDirectionMap,vAnisotropy2MapUv)).r);\n#endif\nrot=rot*2.*PI+rnd;vec2 rot2=vec2(sin(rot),cos(rot));\n#else\nvec2 rot2=(anisotropyDirectionMapTexelToLinear(texture2D(anisotropyDirectionMap,vAnisotropy2MapUv)).rg*2.-1.)+vec2(rnd,rnd);rot2=normalize(rot2);const float anisoSpecMultiplier=0.25;float matSpecAniso=(length(material.specularColor.rgb))*2.*PI;rot2=mix(rot2,vec2(sin(matSpecAniso),cos(matSpecAniso)),anisoSpecMultiplier);rot2=normalize(rot2);\n#endif\nvec3 anisotropicT=(tbn[0]*rot2.x+tbn[1]*rot2.y);anisotropicT=normalize(anisotropicT-normal*dot(anisotropicT,normal));vec3 anisotropicB=normalize(cross(normal,anisotropicT));";
2273
+ // src/plugins/extras/AnisotropyPlugin.ts
2274
+ var _AnisotropyPlugin;
2275
+ var ShaderChunk$1 = RenderManager.ShaderChunk;
2276
+ var AnisotropyPlugin = class AnisotropyPlugin extends AViewerPluginSync {
2277
+ static {
2278
+ _AnisotropyPlugin = this;
2279
+ }
2280
+ static {
2281
+ this.PluginType = "AnisotropyPlugin";
2282
+ }
2283
+ enableAnisotropy(material, map, factor, noise, directionMode) {
2284
+ const ud = material?.userData;
2285
+ if (!ud) return false;
2286
+ if (ud._isAnisotropic === void 0) {
2287
+ const meshes = material.appliedMeshes;
2288
+ let possible = true;
2289
+ if (meshes) for (const { geometry } of meshes) {
2290
+ if (geometry && (!geometry.attributes.position || !geometry.attributes.normal || !geometry.attributes.uv)) possible = false;
2291
+ if (possible && geometry && !geometry.attributes.tangent) geometry.computeTangents();
2292
+ }
2293
+ if (!possible) return false;
2294
+ }
2295
+ ud._isAnisotropic = true;
2296
+ ud._anisotropyFactor = factor ?? ud._anisotropyFactor ?? 1;
2297
+ ud._anisotropyNoise = noise ?? ud._anisotropyNoise ?? 0;
2298
+ ud._anisotropyDirection = ud._anisotropyDirection ?? 1;
2299
+ ud._anisotropyDirectionMode = directionMode ?? ud._anisotropyDirectionMode ?? "DIRECTION";
2300
+ ud._anisotropyDirectionMap = map ?? ud._anisotropyDirectionMap ?? null;
2301
+ if (material.setDirty) material.setDirty();
2302
+ return true;
2303
+ }
2304
+ tryComputeTangents(m, mats) {
2305
+ if (m.geometry && !m.geometry.attributes.tangent) {
2306
+ let possible = true;
2307
+ if (!m.geometry.index || !m.geometry.attributes.position || !m.geometry.attributes.normal || !m.geometry.attributes.uv) possible = false;
2308
+ if (possible) m.geometry.computeTangents();
2309
+ else mats.map((m1) => {
2310
+ if (m1?.userData?._isAnisotropic) m1.userData._isAnisotropic = false;
2311
+ });
2312
+ }
2313
+ }
2314
+ constructor() {
2315
+ super();
2316
+ this.enabled = true;
2317
+ this._defines = {};
2318
+ this._uniforms = {
2319
+ anisotropyFactor: { value: 1 },
2320
+ anisotropyNoise: { value: 1 },
2321
+ anisotropyDirection: { value: 1 },
2322
+ anisotropyDirectionMap: { value: null },
2323
+ anisotropy2MapUvTransform: { value: new Matrix3() },
2324
+ frameCount: { value: 0 }
2325
+ };
2326
+ this.materialExtension = {
2327
+ uuid: _AnisotropyPlugin.PluginType,
2328
+ priority: 10,
2329
+ shaderExtender: (shader, material, _renderer) => {
2330
+ if (this.isDisabled() || !material?.userData._isAnisotropic) return;
2331
+ const rotMap = material.userData?._anisotropyDirectionMap;
2332
+ const bsdfs = glsl`
50
2333
  //#if ANISOTROPY_ENABLED
51
2334
  #include <randomHelpers>
52
2335
  #ifndef D_frameCount
53
2336
  #define D_frameCount
54
2337
  uniform float frameCount;
55
2338
  #endif
56
- ${i?$("anisotropyDirectionMap",i?.colorSpace):""}\n
57
- `;e.fragmentShader=y(e.fragmentShader,"#include <common>",a,{append:!0}),e.fragmentShader=e.fragmentShader.replace("#include <lights_fragment_begin>",Mt.lights_fragment_begin),e.fragmentShader=y(y(e.fragmentShader,"IncidentLight directLight;","float rnd=(random2(vUv.xy,frameCount)-0.5)*anisotropyNoise*material.roughness;\n#if ANISOTROPY_TEX_MODE < 2\n#if ANISOTROPY_TEX_MODE == 0\nfloat rot=saturate(anisotropyDirection);\n#else\nfloat rot=(anisotropyDirectionMapTexelToLinear(texture2D(anisotropyDirectionMap,vAnisotropy2MapUv)).r);\n#endif\nrot=rot*2.*PI+rnd;vec2 rot2=vec2(sin(rot),cos(rot));\n#else\nvec2 rot2=(anisotropyDirectionMapTexelToLinear(texture2D(anisotropyDirectionMap,vAnisotropy2MapUv)).rg*2.-1.)+vec2(rnd,rnd);rot2=normalize(rot2);const float anisoSpecMultiplier=0.25;float matSpecAniso=(length(material.specularColor.rgb))*2.*PI;rot2=mix(rot2,vec2(sin(matSpecAniso),cos(matSpecAniso)),anisoSpecMultiplier);rot2=normalize(rot2);\n#endif\nvec3 anisotropicT=(tbn[0]*rot2.x+tbn[1]*rot2.y);anisotropicT=normalize(anisotropicT-normal*dot(anisotropicT,normal));vec3 anisotropicB=normalize(cross(normal,anisotropicT));",{prepend:!0}),"RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight )","RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight, anisotropicT, anisotropicB )",{replaceAll:!0});let s=y(Mt.lights_physical_pars_fragment,"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 ) {","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, const in vec3 anisotropicT, const in vec3 anisotropicB ) {");s=y(s,"vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {","uniform float anisotropyFactor;uniform float anisotropyNoise;\n#if ANISOTROPY_TEX_MODE == 0\nuniform float anisotropyDirection;\n#else\nuniform sampler2D anisotropyDirectionMap;varying vec2 vAnisotropy2MapUv;\n#endif\nconst float MIN_ROUGHNESS=0.05;vec3 indirectAnisotropyBentNormal(const in vec3 normal,const in vec3 viewDir,const in float roughness,const in vec3 anisotropicT,const in vec3 anisotropicB){vec3 aDirection=anisotropyFactor>=0.0 ? anisotropicB : anisotropicT;vec3 aTangent=cross(aDirection,viewDir);vec3 aNormal=cross(aTangent,aDirection);float bendFactor=abs(anisotropyFactor)*saturate(5.0*max(roughness,MIN_ROUGHNESS));return normalize(mix(normal,aNormal,bendFactor));}vec3 BRDF_GGX_Anisotropy(const in vec3 lightDir,const in vec3 viewDir,const in vec3 normal,const in vec3 f0,const in float f90,const in float roughness,const in vec3 anisotropicT,const in vec3 anisotropicB){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));float dotTV=dot(anisotropicT,viewDir);float dotBV=dot(anisotropicB,viewDir);float dotTL=dot(anisotropicT,lightDir);float dotBL=dot(anisotropicB,lightDir);float dotTH=dot(anisotropicT,halfDir);float dotBH=dot(anisotropicB,halfDir);float aspect=sqrt(1.0-min(1.-MIN_ROUGHNESS,abs(anisotropyFactor)*0.9));if(anisotropyFactor>0.0)aspect=1.0/aspect;float at=roughness*aspect;float ab=roughness/aspect;vec3 F=F_Schlick(f0,f90,dotVH);float V=V_GGX_SmithCorrelated_Anisotropic(at,ab,dotTV,dotBV,dotTL,dotBL,dotNV,dotNL);float D=D_GGX_Anisotropic(at,ab,dotTH,dotBH,dotNH);return F*(V*D);}\n",{prepend:!0}),s=y(s,"BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material )","BRDF_GGX_Anisotropy( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularF90, material.roughness, anisotropicT, anisotropicB )"),e.fragmentShader=y(e.fragmentShader,"#include <lights_physical_pars_fragment>",s),e.fragmentShader=y(e.fragmentShader,"#include <normal_fragment_begin>",Mt.normal_fragment_begin),e.fragmentShader=y(e.fragmentShader,"#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )","#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) || defined( USE_TANGENT )");let n=K`
2339
+ ${rotMap ? getTexelDecoding("anisotropyDirectionMap", rotMap?.colorSpace) : ""}\n
2340
+ `;
2341
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#include <common>", bsdfs, { append: true });
2342
+ shader.fragmentShader = shader.fragmentShader.replace("#include <lights_fragment_begin>", ShaderChunk$1.lights_fragment_begin);
2343
+ shader.fragmentShader = shaderReplaceString(shaderReplaceString(shader.fragmentShader, "IncidentLight directLight;", anisotropyTBN_default, { prepend: true }), "RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight )", "RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight, anisotropicT, anisotropicB )", { replaceAll: true });
2344
+ let lights_physical_pars_fragment = shaderReplaceString(ShaderChunk$1.lights_physical_pars_fragment, "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 ) {", "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, const in vec3 anisotropicT, const in vec3 anisotropicB ) {");
2345
+ lights_physical_pars_fragment = shaderReplaceString(lights_physical_pars_fragment, "vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {", anisotropyBsdf_default + "\n", { prepend: true });
2346
+ lights_physical_pars_fragment = shaderReplaceString(lights_physical_pars_fragment, "BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material )", "BRDF_GGX_Anisotropy( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularF90, material.roughness, anisotropicT, anisotropicB )");
2347
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#include <lights_physical_pars_fragment>", lights_physical_pars_fragment);
2348
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#include <normal_fragment_begin>", ShaderChunk$1.normal_fragment_begin);
2349
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )", "#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) || defined( USE_TANGENT )");
2350
+ let lights_fragment_maps = glsl`
58
2351
  #if defined( USE_ENVMAP )
59
2352
  vec3 anisotropyBentNormal = indirectAnisotropyBentNormal(geometryNormal, geometryViewDir, material.roughness, anisotropicT, anisotropicB);
60
2353
  #endif
61
- `+Mt.lights_fragment_maps;n=y(n,"getIBLIrradiance( geometryNormal )","getIBLIrradiance( anisotropyBentNormal )"),n=y(n,"getIBLRadiance( geometryViewDir, geometryNormal, material.roughness )","getIBLRadiance( geometryViewDir, anisotropyBentNormal, material.roughness )"),e.fragmentShader=y(e.fragmentShader,"#include <lights_fragment_maps>",n),e.vertexShader=y(e.vertexShader,"#include <uv_pars_vertex>","\n#if defined(ANISOTROPY_ENABLED) && ANISOTROPY_ENABLED > 0\n varying vec2 vAnisotropy2MapUv;\n uniform mat3 anisotropy2MapUvTransform;\n#endif\n ",{prepend:!0}),e.vertexShader=y(e.vertexShader,"#include <uv_vertex>","\n#if defined(ANISOTROPY_ENABLED) && ANISOTROPY_ENABLED > 0\n vAnisotropy2MapUv = ( anisotropy2MapUvTransform * vec3( uv, 1 ) ).xy;\n#endif\n ",{prepend:!0}),e.defines||(e.defines={}),e.defines.USE_ANISOTROPY_BRDF="",e.defines.USE_UV="",e.vertexTangents=!0},onObjectRender:(e,t)=>{const r=t.userData;if(!r?._isAnisotropic)return;if(!e.isMesh||!e.geometry)return;e.geometry.attributes.tangent||this._viewer?.console.error("AnisotropyPlugin - No tangents on the geometry, cannot use anisotropy. Make sure the tangents are computed before rendering the model. The model will render as black.",e),this._uniforms.anisotropyFactor.value=r._anisotropyFactor??1,this._uniforms.anisotropyNoise.value=r._anisotropyNoise??0,this._uniforms.anisotropyDirection.value=r._anisotropyDirection??1;const i=r._anisotropyDirectionMap?.isTexture?r._anisotropyDirectionMap:null;this._uniforms.anisotropyDirectionMap.value=i,i&&(i.updateMatrix(),this._uniforms.anisotropy2MapUvTransform.value.copy(i.matrix)),X({...this._defines,ANISOTROPY_ENABLED:+this.enabled,ANISOTROPY_TEX_MODE:i?"DIRECTION"===r._anisotropyDirectionMode?2:"ROTATION"===r._anisotropyDirectionMode?1:0:0},t)},extraUniforms:{},computeCacheKey:e=>(this.enabled?"1":"0")+(e.userData?._isAnisotropic?"1":"0")+e.userData?._anisotropyDirectionMap?.uuid,isCompatible:e=>e.isPhysicalMaterial,updaters:()=>[this._viewer?.renderManager],getUiConfig:e=>{const t=this._viewer,r=this.enableAnisotropy.bind(this),i=e.userData,a={type:"folder",label:"Anisotropy",onChange:e=>{e.config&&this.setDirty()},children:[{type:"checkbox",label:"Enabled",get value(){return i._isAnisotropic||!1},set value(s){s!==i._isAnisotropic&&(s?r(e)||t.dialog.alert("AnisotropyPlugin - One or more geometries cannot be made anisotropic."):(i._isAnisotropic=!1,e.setDirty&&e.setDirty()),a.uiRefresh?.(!0,"postFrame"))}},{type:"slider",label:"Factor",bounds:[-2,2],hidden:()=>!i._isAnisotropic,property:[i,"_anisotropyFactor"]},{type:"slider",label:"Noise",bounds:[0,2],hidden:()=>!i._isAnisotropic,property:[i,"_anisotropyNoise"]},{type:"dropdown",label:"Mode",hidden:()=>!i._isAnisotropic,property:[i,"_anisotropyDirectionMode"],children:["CONSTANT","ROTATION","DIRECTION"].map(e=>({label:e})),onChange:()=>{e.setDirty&&e.setDirty(),a.uiRefresh?.(!0,"postFrame")}},{type:"slider",label:"Direction",bounds:[0,5],hidden:()=>"CONSTANT"===i._anisotropyDirectionMode||!i._isAnisotropic,property:[i,"_anisotropicDirection"]},{type:"image",label:"Texture",hidden:()=>!i._isAnisotropic||"CONSTANT"===i._anisotropyDirectionMode,property:[i,"_anisotropyDirectionMap"],onChange:()=>{e.setDirty&&e.setDirty()}},ie(i,"_anisotropyDirectionMap","Sampler",()=>!i._isAnisotropic||"CONSTANT"===i._anisotropyDirectionMode,()=>e.setDirty&&e.setDirty())]};return a},onMaterialUpdate:e=>{e.userData?._isAnisotropic&&e.userData.__appliedMeshes?.forEach(t=>this.tryComputeTangents(t,[e]))},onRegister:e=>{e.userData?._isAnisotropic&&e.userData.__appliedMeshes?.forEach(t=>this.tryComputeTangents(t,[e]))},onAddToMesh:e=>{if(!e.isMesh)return;const t=e,r=Array.isArray(t.material)?t.material:[t.material];r.find(e=>e?.userData?._isAnisotropic)&&this.tryComputeTangents(t,r)}},this.setDirty=()=>{this.materialExtension.setDirty?.(),this._viewer?.setDirty()},Object.assign(this.materialExtension.extraUniforms,this._uniforms)}enableAnisotropy(e,t,r,i,a){const s=e?.userData;if(!s)return!1;if(void 0===s._isAnisotropic){const t=e.appliedMeshes;let r=!0;if(t)for(const{geometry:e}of t)!e||e.attributes.position&&e.attributes.normal&&e.attributes.uv||(r=!1),r&&e&&!e.attributes.tangent&&e.computeTangents();if(!r)return!1}return s._isAnisotropic=!0,s._anisotropyFactor=r??s._anisotropyFactor??1,s._anisotropyNoise=i??s._anisotropyNoise??0,s._anisotropyDirection=s._anisotropyDirection??1,s._anisotropyDirectionMode=a??s._anisotropyDirectionMode??"DIRECTION",s._anisotropyDirectionMap=t??s._anisotropyDirectionMap??null,e.setDirty&&e.setDirty(),!0}tryComputeTangents(e,t){if(e.geometry&&!e.geometry.attributes.tangent){let r=!0;e.geometry.index&&e.geometry.attributes.position&&e.geometry.attributes.normal&&e.geometry.attributes.uv||(r=!1),r?e.geometry.computeTangents():t.map(e=>{e?.userData?._isAnisotropic&&(e.userData._isAnisotropic=!1)})}}onAdded(e){super.onAdded(e),e.assetManager.materials.registerMaterialExtension(this.materialExtension),e.assetManager.registerGltfExtension(Rt)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(Rt.name),super.onRemove(e)}makeAnisotropic(e){return this.enableAnisotropy(e)}};Et.PluginType="AnisotropyPlugin",Et.ANISOTROPY_GLTF_EXTENSION="WEBGI_materials_anisotropy",Pt([o("Enabled",e=>({onChange:e.setDirty})),f()],Et.prototype,"enabled",2),Et=Pt([E("Anisotropy (MatExt)")],Et);class Ct{constructor(e){this.parser=e,this.name=Rt.name}async extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const a=[],s=i.extensions[this.name];t.userData||(t.userData={}),t.userData._isAnisotropic=!0,t.userData._anisotropyFactor=s.anisotropyFactor??0,t.userData._anisotropyNoise=s.anisotropyNoiseFactor??s.anisotropyNoise??0;let{anisotropyDirectionMode:n,anisotropyDirection:o}=s;return n||(n=s.anisotropyTextureMode),o||(o=s.anisotropyRotation),t.userData._anisotropyDirectionMode=n&&"number"==typeof o?.index?n:"CONSTANT","ROTATION"===n||"DIRECTION"===n?a.push(r.assignTexture(t.userData,"_anisotropyDirectionMap",o).then(e=>{e.colorSpace=ae})):t.userData._anisotropyDirection=o??0,Promise.all(a)}afterRoot(e){return e.scene?.traverse(e=>{const t=e.material?.userData?._isAnisotropic;if(!t)return;const r=e.geometry;r.attributes.tangent||(r.computeTangents(),r.attributes.tangent.needsUpdate=!0)}),null}}const Rt={name:"WEBGI_materials_anisotropy",import:e=>new Ct(e),export:e=>({writeMaterial:(t,r)=>{if(!t.isMeshStandardMaterial||!t.userData._isAnisotropic)return;if((t.userData._anisotropyFactor||0)<.001)return;r.extensions=r.extensions||{};const i={};if(i.anisotropyFactor=t.userData._anisotropyFactor||1,i.anisotropyNoiseFactor=t.userData._anisotropyNoise||0,i.anisotropyDirectionMode=t.userData._anisotropyDirectionMode||"CONSTANT",e.checkEmptyMap(t.userData._anisotropyDirectionMap)&&"CONSTANT"!==i.anisotropyDirectionMode){const r={index:e.processTexture(t.userData._anisotropyDirectionMap)};e.applyTextureTransform(r,t.userData._anisotropyDirectionMap),i.anisotropyDirection=r}else i.anisotropyDirectionMode="CONSTANT",i.anisotropyDirection=t.userData._anisotropyDirection||0;r.extensions[Rt.name]=i,e.extensionsUsed[Rt.name]=!0}}),textures:{anisotropyDirection:"RGB"}};var At=Object.defineProperty,Ut=(e,t,r,i)=>{for(var a,s=void 0,n=e.length-1;n>=0;n--)(a=e[n])&&(s=a(t,r,s)||s);return s&&At(t,r,s),s};const Lt=class extends se{constructor(e,t,r=0,i){super(e,i),this.type="Reflector",this.isReflector2=!0,this.enabled=!0,this.reflectorModePhysical=!0,this.reflectionTargetNeedsUpdate=!0,this.transparentReflectionBackground=!0,this.materialExtension={extraUniforms:{tRefDiffuse:{value:null},tRefDiffuseSize:{value:new d},refTextureMatrix:{value:new u},frameCount:{value:0},sceneBoundingRadius:{value:0}},extraDefines:{USE_UV:""},updaters:[],shaderExtender:(e,t,r)=>{if(this.enabled){e.vertexShader=y(e.vertexShader,"void main() {","void main() {\nvRefUv = refTextureMatrix * vec4( position, 1.0 );");const t="#glMarker beforeModulation";e.fragmentShader=y(e.fragmentShader,t,"\n if(roughnessFactor < 0.95) {\n float d = 0.;//textureProj(tRefDepth, vRefUv).r;\n // d = min(2., max(0., (d-0.06) * ((7./3.-ior)) * sceneBoundingRadius));\n vec4 refBaseColor = getReflectionColor(material.roughness, material.roughness * d);\n // refBaseColor.rgb = vec3(refBaseColor.a);\n // refBaseColor.a *= 1.0 - clamp(material.roughness * .3, 0., 1.);\n "+(this.reflectorModePhysical?"\n #if !defined(SSR_ENABLED) || SSR_ENABLED < 1 \n vec3 specularColor = EnvironmentBRDF(geometryNormal, geometryViewDir, material.specularColor.rgb, material.specularF90, material.roughness);\n #endif\n reflectedLight.indirectSpecular = mix(vec3(reflectedLight.indirectSpecular), saturate(specularColor.rgb * refBaseColor.rgb), refBaseColor.a);\n ":"\n reflectedLight.indirectSpecular = saturate(diffuseColor.rgb * refBaseColor.rgb);\n diffuseColor.a *= refBaseColor.a;\n ")+"}\n"+t)}},parsVertexSnippet:()=>this.enabled?"\n\t\tuniform mat4 refTextureMatrix;\n\t\tvarying vec4 vRefUv;\n":"",parsFragmentSnippet:()=>this.enabled?"vec2 poisson_disk_samples[16];void setPds(){poisson_disk_samples[0]=vec2(-0.399691779231,0.728591545584);poisson_disk_samples[1]=vec2(-0.48622557676,-0.84016533712);poisson_disk_samples[2]=vec2(0.770309468987,-0.24906070432);poisson_disk_samples[3]=vec2(0.556596796154,0.820359876432);poisson_disk_samples[4]=vec2(-0.933902004071,0.0600539051593);poisson_disk_samples[5]=vec2(0.330144964342,0.207477293384);poisson_disk_samples[6]=vec2(0.289013230975,-0.686749271417);poisson_disk_samples[7]=vec2(-0.0832470893559,-0.187351643125);poisson_disk_samples[8]=vec2(-0.296314525615,0.254474834305);poisson_disk_samples[9]=vec2(-0.850977666059,0.484642744689);poisson_disk_samples[10]=vec2(0.829287915319,0.2345063545);poisson_disk_samples[11]=vec2(-0.773042143899,-0.543741521254);poisson_disk_samples[12]=vec2(0.0561133030864,0.928419742597);poisson_disk_samples[13]=vec2(-0.205799249508,-0.562072714492);poisson_disk_samples[14]=vec2(-0.526991665882,-0.193690188118);poisson_disk_samples[15]=vec2(-0.051789270667,-0.935374050821);}\n\n#include <randomHelpers>\n#ifndef D_sceneBoundingRadius\n#define D_sceneBoundingRadius\nuniform float sceneBoundingRadius;\n#endif\n#ifndef D_frameCount\n#define D_frameCount\nuniform float frameCount;\n#endif\nvarying vec4 vRefUv;uniform sampler2D tRefDiffuse;uniform vec2 tRefDiffuseSize;float getSpecularMIPLevel(const in float roughness,const in float maxMIPLevel){float sigma=PI*roughness*roughness/(1.0+roughness);float desiredMIPLevel=maxMIPLevel+log2(sigma);return clamp(desiredMIPLevel,0.0,maxMIPLevel);}vec4 getReflectionColor(const in float roughness,const in float depthModifier){float mip=getSpecularMIPLevel(roughness+depthModifier,4.0);vec4 color=texture2D(tRefDiffuse,vRefUv.xy/vRefUv.w,mip);float blurDist=saturate(2.0/(1.+pow(abs(vViewPosition.z),0.25)))*roughness*64.*color.a;float rnd=PI2*interleavedGradientNoise(vUv.xy,frameCount);vec4 rotationMatrix=vec4(cos(rnd),-sin(rnd),0.,0.);rotationMatrix.z=-rotationMatrix.y;rotationMatrix.w=rotationMatrix.x;vec3 colorSum=color.rgb*color.a;float weightSum=0.001+color.a;vec2 ofs;setPds();\n#pragma unroll_loop_start\nfor(int i=0;i<16;i++){ofs=poisson_disk_samples[UNROLLED_LOOP_INDEX];ofs=vec2(dot(ofs,rotationMatrix.xy),dot(ofs,rotationMatrix.zw));ofs=vRefUv.xy+vRefUv.w*blurDist*ofs/tRefDiffuseSize.xy;color=texture2D(tRefDiffuse,ofs/vRefUv.w,mip);colorSum+=color.rgb*color.a;weightSum+=color.a;}\n#pragma unroll_loop_end\nreturn vec4(colorSum/weightSum,1.0);}":"",computeCacheKey:e=>this.enabled+" "+e.transparent+" "+this.reflectorModePhysical+" ",onObjectRender:(e,t)=>{t.userData.__lastTransparent!==t.transparent&&(t.needsUpdate=!0,t.userData.__lastTransparent=t.transparent)},isCompatible:e=>e.isPhysicalMaterial,setDirty:()=>this.materialExtension.__setDirty?.()},this._renderTarget=t;const a=new ne,s=new F,n=new F,o=new F,l=new u,c=new F(0,0,-1),h=new A,p=new F,f=new F,m=new A,g=new u,v=new oe;this.onBeforeRender=(e,t,i)=>{if(!this.enabled||!e.userData.mainRenderPass)return;if(!this.reflectionTargetNeedsUpdate)return;const d=this._getRenderTarget();if(!d)return void console.warn("Reflector2: No render target set.");const u=i.view?Object.assign({},i.view):null;if(u&&i.clearViewOffset&&i.clearViewOffset(),n.setFromMatrixPosition(this.matrixWorld),o.setFromMatrixPosition(i.matrixWorld),l.extractRotation(this.matrixWorld),s.set(0,0,1),s.applyMatrix4(l),p.subVectors(n,o),p.dot(s)>0)return;p.reflect(s).negate(),p.add(n),l.extractRotation(i.matrixWorld),c.set(0,0,-1),c.applyMatrix4(l),c.add(o),f.subVectors(n,c),f.reflect(s).negate(),f.add(n),v.position.copy(p),v.up.set(0,1,0),v.up.applyMatrix4(l),v.up.reflect(s),v.lookAt(f),v.far=2,v.near=0,v.updateMatrixWorld(),v.projectionMatrix.copy(i.projectionMatrix),g.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),g.multiply(v.projectionMatrix),g.multiply(v.matrixWorldInverse),g.multiply(this.matrixWorld),a.setFromNormalAndCoplanarPoint(s,n),a.applyMatrix4(v.matrixWorldInverse),h.set(a.normal.x,a.normal.y,a.normal.z,a.constant);const _=v.projectionMatrix;m.x=(Math.sign(h.x)+_.elements[8])/_.elements[0],m.y=(Math.sign(h.y)+_.elements[9])/_.elements[5],m.z=-1,m.w=(1+_.elements[10])/_.elements[14],h.multiplyScalar(2/h.dot(m)),_.elements[2]=h.x,_.elements[6]=h.y,_.elements[10]=h.z+1-r,_.elements[14]=h.w,this.visible=!1;const y=e.getRenderTarget(),x=e.xr.enabled,S=e.shadowMap.autoUpdate;e.xr.enabled=!1,e.shadowMap.autoUpdate=!1,e.setRenderTarget(d),e.state.buffers.depth.setMask(!0),!1===e.autoClear&&e.clear();const b=t.background;this.transparentReflectionBackground&&(t.background=null);const w=!this.transparentReflectionBackground;b?.isTexture&&w&&(b.userData||(b.userData={}),b.userData.flipX=!b.userData.flipX),e.renderWithModes({shadowMapRender:!1,backgroundRender:w,opaqueRender:!0,transparentRender:!0,transmissionRender:!1,screenSpaceRendering:!1},()=>e.render(t,v)),b?.isTexture&&w&&(b.userData.flipX=!b.userData.flipX||void 0),this.transparentReflectionBackground&&(t.background=b),e.xr.enabled=x,e.shadowMap.autoUpdate=S,e.setRenderTarget(y),u?.enabled&&i.setViewOffset&&i.setViewOffset(u.fullWidth,u.fullHeight,u.offsetX,u.offsetY,u.width,u.height);const T=i.viewport;void 0!==T&&e.state.viewport(T),this.visible=!0,this.reflectionTargetNeedsUpdate=!1},this.textureMatrix=g,this.materialExtension.extraUniforms.refTextureMatrix.value=g}_getRenderTarget(){const e=p(this._renderTarget);return e&&(!e.texture.generateMipmaps||le.isPowerOfTwo(e.texture.image.width)&&le.isPowerOfTwo(e.texture.image.height)||(e.texture.generateMipmaps=!1),this.materialExtension.extraUniforms.tRefDiffuse.value=e.texture,this.materialExtension.extraUniforms.tRefDiffuseSize.value.set(e.width,e.height)),e}_updateExtension(){this.transparentReflectionBackground=this.reflectorModePhysical,this.materialExtension?.setDirty?.()}getRenderTarget(){return this._renderTarget}};Ut([B(Lt.prototype._updateExtension)],Lt.prototype,"enabled"),Ut([B(Lt.prototype._updateExtension)],Lt.prototype,"reflectorModePhysical");let Ot=Lt;Ot.prototype.isReflector=!0;class Bt{static _xfnv1a(e){let t=2166136261;for(let r=0;r<e.length;r++)t=Math.imul(t^e.charCodeAt(r),16777619);return()=>(t+=t<<13,t^=t>>>7,t+=t<<3,t^=t>>>17,(t+=t<<5)>>>0)}}class Nt extends Bt{constructor(e){super(),Object.defineProperty(this,"a",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.a=Nt._xfnv1a(e)()}next(){let e=this.a+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}class Ft extends Bt{constructor(e){super(),Object.defineProperty(this,"a",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"b",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"c",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"d",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const t=Ft._xfnv1a(e);this.a=t(),this.b=t(),this.c=t(),this.d=t()}next(){this.a>>>=0,this.b>>>=0,this.c>>>=0,this.d>>>=0;let e=this.a+this.b|0;return this.a=this.b^this.b>>>9,this.b=this.c+(this.c<<3)|0,this.c=this.c<<21|this.c>>>11,this.d=this.d+1|0,e=e+this.d|0,this.c=this.c+e|0,(e>>>0)/4294967296}}class kt extends Bt{constructor(e){super(),Object.defineProperty(this,"a",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"b",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"c",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"d",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const t=kt._xfnv1a(e);this.a=t(),this.b=t(),this.c=t(),this.d=t()}next(){const e=this.b<<9;let t=5*this.b;return t=9*(t<<7|t>>>25),this.c^=this.a,this.d^=this.b,this.b^=this.c,this.a^=this.d,this.c^=e,this.d=this.d<<11|this.d>>>21,(t>>>0)/4294967296}}var It,zt;(zt=It||(It={})).sfc32="sfc32",zt.mulberry32="mulberry32",zt.xoshiro128ss="xoshiro128ss";class Vt{constructor(e,t=It.sfc32){Object.defineProperty(this,"str",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"prng",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.str=e,this.prng=t,this.generator=this._initializeGenerator()}next(){return this.generator.next()}_initializeGenerator(){if(/* @__PURE__ */(e=>null===e)(e=this.str)||/* @__PURE__ */(e=>void 0===e)(e))return this.wrap();var e;switch(this.prng){case"sfc32":return new Ft(this.str);case"mulberry32":return new Nt(this.str);case"xoshiro128ss":return new kt(this.str);default:return this.wrap()}}wrap(){return{next:()=>Math.random()}}}var jt=Object.defineProperty,Gt=(e,t,r,i)=>{for(var a,s=void 0,n=e.length-1;n>=0;n--)(a=e[n])&&(s=a(t,r,s)||s);return s&&jt(t,r,s),s};class Ht extends ce{constructor(e,t,r,i){super(e,t),this._shadowParams={enabled:!0,radius:2,width:1024,height:1024,bias:-.001,normalBias:0,near:1.5,far:4,frustumSize:4},this._randomParams={focus:1,spread:.01,distanceScale:50,minDistanceScale:new F(10,10,10),normalDirection:new F(.01,.98,.01).normalize(),direction:new F(-.9,.5,-1)},this.isRandomizedDirectionalLight=!0,this.shadowParams=r??{},this.randomParams=i??{},this.updateShadowParams=this.updateShadowParams.bind(this)}get shadowParams(){return this._shadowParams}set shadowParams(e){Object.keys(e).forEach(t=>void 0===e[t]&&delete e[t]),this._shadowParams={...this._shadowParams,...e},this.updateShadowParams()}get randomParams(){return this._randomParams}set randomParams(e){Object.keys(e).forEach(t=>void 0===e[t]&&delete e[t]),Object.assign(this._randomParams,e)}updateShadowParams(){this.castShadow=this._shadowParams.enabled,this.shadow.mapSize.x=this._shadowParams.width,this.shadow.mapSize.y=this._shadowParams.height,this.shadow.bias=this._shadowParams.bias,this.shadow.normalBias=this._shadowParams.normalBias,this.refreshShadowCamNearFar(),this.shadow.radius=this._shadowParams.radius,this.shadow.camera.right=this._shadowParams.frustumSize/2,this.shadow.camera.left=-this._shadowParams.frustumSize/2,this.shadow.camera.top=this._shadowParams.frustumSize/2,this.shadow.camera.bottom=-this._shadowParams.frustumSize/2,this.shadow.camera.updateProjectionMatrix(),this.matrixWorldNeedsUpdate=!0}randomizePosition(e,t=null,r=null){const i=new Vt(e.toString()),a=new d(i.next()*Math.PI*2,Math.asin(2*i.next()-1));let s=new F(Math.cos(a.x)*Math.cos(a.y),Math.sin(a.y),Math.sin(a.x)*Math.cos(a.y));const n=new d;for(let o=0;o<5;o++){n.set(i.next(),i.next()),s=Wt(n,this._randomParams.normalDirection,.4),i.next()<Math.sqrt(t??this._randomParams.focus)&&(n.set(i.next(),i.next()),s=Wt(n,this._randomParams.direction,Math.pow((r??this._randomParams.spread)/2,2)));const e=s.dot(this._randomParams.normalDirection);if(e>0&&e<.4)break}s.normalize(),s.multiplyScalar(this._randomParams.distanceScale),this.position.set(0,0,0),this.target.position.copy(s.normalize().negate()),this.target.updateMatrixWorld(),this.refreshShadowCamNearFar(),this.updateMatrixWorld()}refreshShadowCamNearFar(){const e=(new F).subVectors(this.target.position,this.shadow.camera.position).length();this.shadow.camera.near=e-this._shadowParams.near*this._shadowParams.frustumSize/2,this.shadow.camera.far=e+this._shadowParams.far*this._shadowParams.frustumSize/2}dispose(){}toJSON(e,t=!1){const{userData:r,children:i}=this;this.userData={},this.children=[];const a=super.toJSON(e),s=de({},r);return a.userData=ue.Serialize(s),this.userData=r,this.children=i,a.type="DirectionalLight2",a.target=this.target.position.toArray(),{...a,...he.Serialize(this,e,!0)}}fromJSON(e,t,r=!1){if("DirectionalLight2"!==e.type)return null;const i=e.target,a=e.object;return e.target&&(this.target.position.fromArray(e.target),this.target.updateMatrixWorld(),delete e.target),e.object&&delete e.object,he.Deserialize(e,this,t,!0),i&&(e.target=i),a&&(void 0!==a.color&&this.color.set(a.color),void 0!==a.intensity&&(this.intensity=a.intensity),e.object=a),this.updateShadowParams(),this}}function Wt(e,t,r){t=t.clone().normalize();const i=new F(0,-t.z,t.y).normalize(),a=(new F).crossVectors(t,i).normalize(),s=e;s.x=2*s.x*Math.PI,s.y=1-s.y*r;const n=Math.sqrt(1-s.y*s.y);return i.multiplyScalar(Math.cos(s.x)*n).add(a.multiplyScalar(Math.sin(s.x)*n)).add(t.multiplyScalar(s.y))}Gt([f("shadowParams")],Ht.prototype,"_shadowParams"),Gt([f("randomParams")],Ht.prototype,"_randomParams");var Yt=Object.defineProperty;class Xt extends pe{constructor(){super(...arguments),this.typeSlug="fsShadow",this.assetType="material",this._uniforms={},this.lastFrameTexture=null}get materialObject(){return this}onBeforeCompile(e,t){e.vertexShader=e.vertexShader.replace("#include <project_vertex>","\n#include <project_vertex>\ngl_Position = vec4(uv*2.-1., 0, 1.); \n "),e.vertexShader=e.vertexShader.replace("void main() {","\nvarying vec2 vUv;\nvoid main() {\n vUv = uv;\n "),e.fragmentShader=e.fragmentShader.replace("void main() {","\nvarying vec2 vUv;\nuniform sampler2D tLastThis;\nvoid main() {\n "),e.fragmentShader=e.fragmentShader.replace("gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );",K`
2354
+ ` + ShaderChunk$1.lights_fragment_maps;
2355
+ lights_fragment_maps = shaderReplaceString(lights_fragment_maps, "getIBLIrradiance( geometryNormal )", "getIBLIrradiance( anisotropyBentNormal )");
2356
+ lights_fragment_maps = shaderReplaceString(lights_fragment_maps, "getIBLRadiance( geometryViewDir, geometryNormal, material.roughness )", "getIBLRadiance( geometryViewDir, anisotropyBentNormal, material.roughness )");
2357
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#include <lights_fragment_maps>", lights_fragment_maps);
2358
+ shader.vertexShader = shaderReplaceString(shader.vertexShader, "#include <uv_pars_vertex>", `
2359
+ #if defined(ANISOTROPY_ENABLED) && ANISOTROPY_ENABLED > 0
2360
+ varying vec2 vAnisotropy2MapUv;
2361
+ uniform mat3 anisotropy2MapUvTransform;
2362
+ #endif
2363
+ `, { prepend: true });
2364
+ shader.vertexShader = shaderReplaceString(shader.vertexShader, "#include <uv_vertex>", `
2365
+ #if defined(ANISOTROPY_ENABLED) && ANISOTROPY_ENABLED > 0
2366
+ vAnisotropy2MapUv = ( anisotropy2MapUvTransform * vec3( uv, 1 ) ).xy;
2367
+ #endif
2368
+ `, { prepend: true });
2369
+ if (!shader.defines) shader.defines = {};
2370
+ shader.defines.USE_ANISOTROPY_BRDF = "";
2371
+ shader.defines.USE_UV = "";
2372
+ shader.vertexTangents = true;
2373
+ },
2374
+ onObjectRender: (object, material) => {
2375
+ const userData = material.userData;
2376
+ if (!userData?._isAnisotropic) return;
2377
+ if (!object.isMesh || !object.geometry) return;
2378
+ if (!object.geometry.attributes.tangent) this._viewer?.console.error("AnisotropyPlugin - No tangents on the geometry, cannot use anisotropy. Make sure the tangents are computed before rendering the model. The model will render as black.", object);
2379
+ this._uniforms.anisotropyFactor.value = userData._anisotropyFactor ?? 1;
2380
+ this._uniforms.anisotropyNoise.value = userData._anisotropyNoise ?? 0;
2381
+ this._uniforms.anisotropyDirection.value = userData._anisotropyDirection ?? 1;
2382
+ const tex = userData._anisotropyDirectionMap?.isTexture ? userData._anisotropyDirectionMap : null;
2383
+ this._uniforms.anisotropyDirectionMap.value = tex;
2384
+ if (tex) {
2385
+ tex.updateMatrix();
2386
+ this._uniforms.anisotropy2MapUvTransform.value.copy(tex.matrix);
2387
+ }
2388
+ updateMaterialDefines({
2389
+ ...this._defines,
2390
+ ["ANISOTROPY_ENABLED"]: +this.enabled,
2391
+ ["ANISOTROPY_TEX_MODE"]: !tex ? 0 : userData._anisotropyDirectionMode === "DIRECTION" ? 2 : userData._anisotropyDirectionMode === "ROTATION" ? 1 : 0
2392
+ }, material);
2393
+ },
2394
+ extraUniforms: {},
2395
+ computeCacheKey: (material1) => {
2396
+ return (this.enabled ? "1" : "0") + (material1.userData?._isAnisotropic ? "1" : "0") + material1.userData?._anisotropyDirectionMap?.uuid;
2397
+ },
2398
+ isCompatible: (material1) => material1.isPhysicalMaterial,
2399
+ updaters: () => [this._viewer?.renderManager],
2400
+ getUiConfig: (material) => {
2401
+ const viewer = this._viewer;
2402
+ const enableAnisotropy = this.enableAnisotropy.bind(this);
2403
+ const state = material.userData;
2404
+ const config = {
2405
+ type: "folder",
2406
+ label: "Anisotropy",
2407
+ onChange: (ev) => {
2408
+ if (!ev.config) return;
2409
+ this.setDirty();
2410
+ },
2411
+ children: [
2412
+ {
2413
+ type: "checkbox",
2414
+ label: "Enabled",
2415
+ get value() {
2416
+ return state._isAnisotropic || false;
2417
+ },
2418
+ set value(v) {
2419
+ if (v === state._isAnisotropic) return;
2420
+ if (v) {
2421
+ if (!enableAnisotropy(material)) viewer.dialog.alert("AnisotropyPlugin - One or more geometries cannot be made anisotropic.");
2422
+ } else {
2423
+ state._isAnisotropic = false;
2424
+ if (material.setDirty) material.setDirty();
2425
+ }
2426
+ config.uiRefresh?.(true, "postFrame");
2427
+ }
2428
+ },
2429
+ {
2430
+ type: "slider",
2431
+ label: "Factor",
2432
+ bounds: [-2, 2],
2433
+ hidden: () => !state._isAnisotropic,
2434
+ property: [state, "_anisotropyFactor"]
2435
+ },
2436
+ {
2437
+ type: "slider",
2438
+ label: "Noise",
2439
+ bounds: [0, 2],
2440
+ hidden: () => !state._isAnisotropic,
2441
+ property: [state, "_anisotropyNoise"]
2442
+ },
2443
+ {
2444
+ type: "dropdown",
2445
+ label: "Mode",
2446
+ hidden: () => !state._isAnisotropic,
2447
+ property: [state, "_anisotropyDirectionMode"],
2448
+ children: [
2449
+ "CONSTANT",
2450
+ "ROTATION",
2451
+ "DIRECTION"
2452
+ ].map((value) => ({ label: value })),
2453
+ onChange: () => {
2454
+ if (material.setDirty) material.setDirty();
2455
+ config.uiRefresh?.(true, "postFrame");
2456
+ }
2457
+ },
2458
+ {
2459
+ type: "slider",
2460
+ label: "Direction",
2461
+ bounds: [0, 5],
2462
+ hidden: () => state._anisotropyDirectionMode === "CONSTANT" || !state._isAnisotropic,
2463
+ property: [state, "_anisotropicDirection"]
2464
+ },
2465
+ {
2466
+ type: "image",
2467
+ label: "Texture",
2468
+ hidden: () => !state._isAnisotropic || state._anisotropyDirectionMode === "CONSTANT",
2469
+ property: [state, "_anisotropyDirectionMap"],
2470
+ onChange: () => {
2471
+ if (material.setDirty) material.setDirty();
2472
+ }
2473
+ },
2474
+ makeSamplerUi(state, "_anisotropyDirectionMap", "Sampler", () => !state._isAnisotropic || state._anisotropyDirectionMode === "CONSTANT", () => material.setDirty && material.setDirty())
2475
+ ]
2476
+ };
2477
+ return config;
2478
+ },
2479
+ onMaterialUpdate: (material) => {
2480
+ if (!material.userData?._isAnisotropic) return;
2481
+ material.userData.__appliedMeshes?.forEach((m) => this.tryComputeTangents(m, [material]));
2482
+ },
2483
+ onRegister: (material) => {
2484
+ if (!material.userData?._isAnisotropic) return;
2485
+ material.userData.__appliedMeshes?.forEach((m) => this.tryComputeTangents(m, [material]));
2486
+ },
2487
+ onAddToMesh: (mesh) => {
2488
+ if (!mesh.isMesh) return;
2489
+ const m = mesh;
2490
+ const mats = Array.isArray(m.material) ? m.material : [m.material];
2491
+ if (!mats.find((m1) => m1?.userData?._isAnisotropic)) return;
2492
+ this.tryComputeTangents(m, mats);
2493
+ }
2494
+ };
2495
+ this.setDirty = () => {
2496
+ this.materialExtension.setDirty?.();
2497
+ this._viewer?.setDirty();
2498
+ };
2499
+ Object.assign(this.materialExtension.extraUniforms, this._uniforms);
2500
+ }
2501
+ onAdded(v) {
2502
+ super.onAdded(v);
2503
+ v.assetManager.materials.registerMaterialExtension(this.materialExtension);
2504
+ v.assetManager.registerGltfExtension(anisotropyGLTFExtension);
2505
+ }
2506
+ onRemove(v) {
2507
+ v.assetManager.materials?.unregisterMaterialExtension(this.materialExtension);
2508
+ v.assetManager.unregisterGltfExtension(anisotropyGLTFExtension.name);
2509
+ return super.onRemove(v);
2510
+ }
2511
+ static {
2512
+ this.ANISOTROPY_GLTF_EXTENSION = "WEBGI_materials_anisotropy";
2513
+ }
2514
+ /**
2515
+ * @deprecated - use {@link enableAnisotropy} instead
2516
+ * @param material
2517
+ */
2518
+ makeAnisotropic(material) {
2519
+ return this.enableAnisotropy(material);
2520
+ }
2521
+ };
2522
+ __decorate([uiToggle("Enabled", (that) => ({ onChange: that.setDirty })), serialize()], AnisotropyPlugin.prototype, "enabled", void 0);
2523
+ AnisotropyPlugin = _AnisotropyPlugin = __decorate([uiFolderContainer("Anisotropy (MatExt)")], AnisotropyPlugin);
2524
+ /**
2525
+ * Anisotropy Materials Extension
2526
+ *
2527
+ * Specification: https://webgi.xyz/docs/gltf-extensions/WEBGI_materials_anisotropy.html
2528
+ */
2529
+ var GLTFMaterialsAnisotropyExtensionImport = class {
2530
+ constructor(parser) {
2531
+ this.parser = parser;
2532
+ this.name = anisotropyGLTFExtension.name;
2533
+ }
2534
+ async extendMaterialParams(materialIndex, materialParams) {
2535
+ const parser = this.parser;
2536
+ const materialDef = parser.json.materials[materialIndex];
2537
+ if (!materialDef.extensions || !materialDef.extensions[this.name]) return Promise.resolve();
2538
+ const pending = [];
2539
+ const extension = materialDef.extensions[this.name];
2540
+ if (!materialParams.userData) materialParams.userData = {};
2541
+ materialParams.userData._isAnisotropic = true;
2542
+ materialParams.userData._anisotropyFactor = extension.anisotropyFactor ?? 0;
2543
+ materialParams.userData._anisotropyNoise = extension.anisotropyNoiseFactor ?? extension.anisotropyNoise ?? 0;
2544
+ let { anisotropyDirectionMode, anisotropyDirection } = extension;
2545
+ if (!anisotropyDirectionMode) anisotropyDirectionMode = extension.anisotropyTextureMode;
2546
+ if (!anisotropyDirection) anisotropyDirection = extension.anisotropyRotation;
2547
+ materialParams.userData._anisotropyDirectionMode = anisotropyDirectionMode && typeof anisotropyDirection?.index === "number" ? anisotropyDirectionMode : "CONSTANT";
2548
+ if (anisotropyDirectionMode === "ROTATION" || anisotropyDirectionMode === "DIRECTION") pending.push(parser.assignTexture(materialParams.userData, "_anisotropyDirectionMap", anisotropyDirection).then((t) => {
2549
+ t.colorSpace = SRGBColorSpace;
2550
+ }));
2551
+ else materialParams.userData._anisotropyDirection = anisotropyDirection ?? 0;
2552
+ return Promise.all(pending);
2553
+ }
2554
+ afterRoot(result) {
2555
+ result.scene?.traverse((object) => {
2556
+ if (!object.material?.userData?._isAnisotropic) return;
2557
+ const geom = object.geometry;
2558
+ if (!geom.attributes.tangent) {
2559
+ geom.computeTangents();
2560
+ geom.attributes.tangent.needsUpdate = true;
2561
+ }
2562
+ });
2563
+ return null;
2564
+ }
2565
+ };
2566
+ var glTFMaterialsAnisotropyExtensionExport = (w) => ({ writeMaterial: (material, materialDef) => {
2567
+ if (!material.isMeshStandardMaterial || !material.userData._isAnisotropic) return;
2568
+ if ((material.userData._anisotropyFactor || 0) < .001) return;
2569
+ materialDef.extensions = materialDef.extensions || {};
2570
+ const extensionDef = {};
2571
+ extensionDef.anisotropyFactor = material.userData._anisotropyFactor || 1;
2572
+ extensionDef.anisotropyNoiseFactor = material.userData._anisotropyNoise || 0;
2573
+ extensionDef.anisotropyDirectionMode = material.userData._anisotropyDirectionMode || "CONSTANT";
2574
+ if (w.checkEmptyMap(material.userData._anisotropyDirectionMap) && extensionDef.anisotropyDirectionMode !== "CONSTANT") {
2575
+ const anisotropyDirectionMapDef = { index: w.processTexture(material.userData._anisotropyDirectionMap) };
2576
+ w.applyTextureTransform(anisotropyDirectionMapDef, material.userData._anisotropyDirectionMap);
2577
+ extensionDef.anisotropyDirection = anisotropyDirectionMapDef;
2578
+ } else {
2579
+ extensionDef.anisotropyDirectionMode = "CONSTANT";
2580
+ extensionDef.anisotropyDirection = material.userData._anisotropyDirection || 0;
2581
+ }
2582
+ materialDef.extensions[anisotropyGLTFExtension.name] = extensionDef;
2583
+ w.extensionsUsed[anisotropyGLTFExtension.name] = true;
2584
+ } });
2585
+ var anisotropyGLTFExtension = {
2586
+ name: "WEBGI_materials_anisotropy",
2587
+ import: (p) => new GLTFMaterialsAnisotropyExtensionImport(p),
2588
+ export: glTFMaterialsAnisotropyExtensionExport,
2589
+ textures: { anisotropyDirection: "RGB" }
2590
+ };
2591
+ // src/utils/shaders/poissonDiskSamples.glsl
2592
+ var poissonDiskSamples_default = "vec2 poisson_disk_samples[16];void setPds(){poisson_disk_samples[0]=vec2(-0.399691779231,0.728591545584);poisson_disk_samples[1]=vec2(-0.48622557676,-0.84016533712);poisson_disk_samples[2]=vec2(0.770309468987,-0.24906070432);poisson_disk_samples[3]=vec2(0.556596796154,0.820359876432);poisson_disk_samples[4]=vec2(-0.933902004071,0.0600539051593);poisson_disk_samples[5]=vec2(0.330144964342,0.207477293384);poisson_disk_samples[6]=vec2(0.289013230975,-0.686749271417);poisson_disk_samples[7]=vec2(-0.0832470893559,-0.187351643125);poisson_disk_samples[8]=vec2(-0.296314525615,0.254474834305);poisson_disk_samples[9]=vec2(-0.850977666059,0.484642744689);poisson_disk_samples[10]=vec2(0.829287915319,0.2345063545);poisson_disk_samples[11]=vec2(-0.773042143899,-0.543741521254);poisson_disk_samples[12]=vec2(0.0561133030864,0.928419742597);poisson_disk_samples[13]=vec2(-0.205799249508,-0.562072714492);poisson_disk_samples[14]=vec2(-0.526991665882,-0.193690188118);poisson_disk_samples[15]=vec2(-0.051789270667,-0.935374050821);}";
2593
+ // src/utils/shaders/reflectorSample.glsl
2594
+ var reflectorSample_default = "\n#include <randomHelpers>\n#ifndef D_sceneBoundingRadius\n#define D_sceneBoundingRadius\nuniform float sceneBoundingRadius;\n#endif\n#ifndef D_frameCount\n#define D_frameCount\nuniform float frameCount;\n#endif\nvarying vec4 vRefUv;uniform sampler2D tRefDiffuse;uniform vec2 tRefDiffuseSize;float getSpecularMIPLevel(const in float roughness,const in float maxMIPLevel){float sigma=PI*roughness*roughness/(1.0+roughness);float desiredMIPLevel=maxMIPLevel+log2(sigma);return clamp(desiredMIPLevel,0.0,maxMIPLevel);}vec4 getReflectionColor(const in float roughness,const in float depthModifier){float mip=getSpecularMIPLevel(roughness+depthModifier,4.0);vec4 color=texture2D(tRefDiffuse,vRefUv.xy/vRefUv.w,mip);float blurDist=saturate(2.0/(1.+pow(abs(vViewPosition.z),0.25)))*roughness*64.*color.a;float rnd=PI2*interleavedGradientNoise(vUv.xy,frameCount);vec4 rotationMatrix=vec4(cos(rnd),-sin(rnd),0.,0.);rotationMatrix.z=-rotationMatrix.y;rotationMatrix.w=rotationMatrix.x;vec3 colorSum=color.rgb*color.a;float weightSum=0.001+color.a;vec2 ofs;setPds();\n#pragma unroll_loop_start\nfor(int i=0;i<16;i++){ofs=poisson_disk_samples[UNROLLED_LOOP_INDEX];ofs=vec2(dot(ofs,rotationMatrix.xy),dot(ofs,rotationMatrix.zw));ofs=vRefUv.xy+vRefUv.w*blurDist*ofs/tRefDiffuseSize.xy;color=texture2D(tRefDiffuse,ofs/vRefUv.w,mip);colorSum+=color.rgb*color.a;weightSum+=color.a;}\n#pragma unroll_loop_end\nreturn vec4(colorSum/weightSum,1.0);}";
2595
+ // src/utils/Reflector2.ts
2596
+ var Reflector2 = class extends Mesh2 {
2597
+ _getRenderTarget() {
2598
+ const target = getOrCall(this._renderTarget);
2599
+ if (target) {
2600
+ if (target.texture.generateMipmaps && (!MathUtils.isPowerOfTwo(target.texture.image.width) || !MathUtils.isPowerOfTwo(target.texture.image.height))) target.texture.generateMipmaps = false;
2601
+ this.materialExtension.extraUniforms.tRefDiffuse.value = target.texture;
2602
+ this.materialExtension.extraUniforms.tRefDiffuseSize.value.set(target.width, target.height);
2603
+ }
2604
+ return target;
2605
+ }
2606
+ _updateExtension() {
2607
+ this.transparentReflectionBackground = this.reflectorModePhysical;
2608
+ this.materialExtension?.setDirty?.();
2609
+ }
2610
+ constructor(geometry, renderTarget, clipBias = 0, material) {
2611
+ super(geometry, material);
2612
+ this.type = "Reflector";
2613
+ this.isReflector2 = true;
2614
+ this.enabled = true;
2615
+ this.reflectorModePhysical = true;
2616
+ this.reflectionTargetNeedsUpdate = true;
2617
+ this.transparentReflectionBackground = true;
2618
+ this.materialExtension = {
2619
+ extraUniforms: {
2620
+ tRefDiffuse: { value: null },
2621
+ tRefDiffuseSize: { value: new Vector2() },
2622
+ refTextureMatrix: { value: new Matrix4() },
2623
+ frameCount: { value: 0 },
2624
+ sceneBoundingRadius: { value: 0 }
2625
+ },
2626
+ extraDefines: { USE_UV: "" },
2627
+ updaters: [],
2628
+ shaderExtender: (shader, _material, _renderer) => {
2629
+ if (this.enabled) {
2630
+ shader.vertexShader = shaderReplaceString(shader.vertexShader, "void main() {", "void main() {\nvRefUv = refTextureMatrix * vec4( position, 1.0 );");
2631
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#glMarker beforeModulation", `
2632
+ if(roughnessFactor < 0.95) {
2633
+ float d = 0.;//textureProj(tRefDepth, vRefUv).r;
2634
+ // d = min(2., max(0., (d-0.06) * ((7./3.-ior)) * sceneBoundingRadius));
2635
+ vec4 refBaseColor = getReflectionColor(material.roughness, material.roughness * d);
2636
+ // refBaseColor.rgb = vec3(refBaseColor.a);
2637
+ // refBaseColor.a *= 1.0 - clamp(material.roughness * .3, 0., 1.);
2638
+ ` + (this.reflectorModePhysical ? `
2639
+ #if !defined(SSR_ENABLED) || SSR_ENABLED < 1
2640
+ vec3 specularColor = EnvironmentBRDF(geometryNormal, geometryViewDir, material.specularColor.rgb, material.specularF90, material.roughness);
2641
+ #endif
2642
+ reflectedLight.indirectSpecular = mix(vec3(reflectedLight.indirectSpecular), saturate(specularColor.rgb * refBaseColor.rgb), refBaseColor.a);
2643
+ ` : `
2644
+ reflectedLight.indirectSpecular = saturate(diffuseColor.rgb * refBaseColor.rgb);
2645
+ diffuseColor.a *= refBaseColor.a;
2646
+ `) + "}\n#glMarker beforeModulation");
2647
+ }
2648
+ },
2649
+ parsVertexSnippet: () => !this.enabled ? "" : `
2650
+ uniform mat4 refTextureMatrix;
2651
+ varying vec4 vRefUv;
2652
+ `,
2653
+ parsFragmentSnippet: () => this.enabled ? poissonDiskSamples_default + "\n" + reflectorSample_default : "",
2654
+ computeCacheKey: (material) => {
2655
+ return this.enabled + " " + material.transparent + " " + this.reflectorModePhysical + " ";
2656
+ },
2657
+ onObjectRender: (_object, material) => {
2658
+ if (material.userData.__lastTransparent !== material.transparent) {
2659
+ material.needsUpdate = true;
2660
+ material.userData.__lastTransparent = material.transparent;
2661
+ }
2662
+ },
2663
+ isCompatible: (material) => {
2664
+ return material.isPhysicalMaterial;
2665
+ },
2666
+ setDirty: () => this.materialExtension.__setDirty?.()
2667
+ };
2668
+ this._renderTarget = renderTarget;
2669
+ const reflectorPlane = new Plane();
2670
+ const normal = new Vector3();
2671
+ const reflectorWorldPosition = new Vector3();
2672
+ const cameraWorldPosition = new Vector3();
2673
+ const rotationMatrix = new Matrix4();
2674
+ const lookAtPosition = new Vector3(0, 0, -1);
2675
+ const clipPlane = new Vector4();
2676
+ const view = new Vector3();
2677
+ const target = new Vector3();
2678
+ const q = new Vector4();
2679
+ const textureMatrix = new Matrix4();
2680
+ const virtualCamera = new PerspectiveCamera();
2681
+ this.onBeforeRender = (renderer, scene, camera) => {
2682
+ if (!this.enabled || !renderer.userData.mainRenderPass) return;
2683
+ if (!this.reflectionTargetNeedsUpdate) return;
2684
+ const thisRenderTarget = this._getRenderTarget();
2685
+ if (!thisRenderTarget) {
2686
+ console.warn("Reflector2: No render target set.");
2687
+ return;
2688
+ }
2689
+ const viewOffset = camera.view ? Object.assign({}, camera.view) : null;
2690
+ viewOffset && camera.clearViewOffset && camera.clearViewOffset();
2691
+ reflectorWorldPosition.setFromMatrixPosition(this.matrixWorld);
2692
+ cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
2693
+ rotationMatrix.extractRotation(this.matrixWorld);
2694
+ normal.set(0, 0, 1);
2695
+ normal.applyMatrix4(rotationMatrix);
2696
+ view.subVectors(reflectorWorldPosition, cameraWorldPosition);
2697
+ if (view.dot(normal) > 0) return;
2698
+ view.reflect(normal).negate();
2699
+ view.add(reflectorWorldPosition);
2700
+ rotationMatrix.extractRotation(camera.matrixWorld);
2701
+ lookAtPosition.set(0, 0, -1);
2702
+ lookAtPosition.applyMatrix4(rotationMatrix);
2703
+ lookAtPosition.add(cameraWorldPosition);
2704
+ target.subVectors(reflectorWorldPosition, lookAtPosition);
2705
+ target.reflect(normal).negate();
2706
+ target.add(reflectorWorldPosition);
2707
+ virtualCamera.position.copy(view);
2708
+ virtualCamera.up.set(0, 1, 0);
2709
+ virtualCamera.up.applyMatrix4(rotationMatrix);
2710
+ virtualCamera.up.reflect(normal);
2711
+ virtualCamera.lookAt(target);
2712
+ virtualCamera.far = 2;
2713
+ virtualCamera.near = 0;
2714
+ virtualCamera.updateMatrixWorld();
2715
+ virtualCamera.projectionMatrix.copy(camera.projectionMatrix);
2716
+ textureMatrix.set(.5, 0, 0, .5, 0, .5, 0, .5, 0, 0, .5, .5, 0, 0, 0, 1);
2717
+ textureMatrix.multiply(virtualCamera.projectionMatrix);
2718
+ textureMatrix.multiply(virtualCamera.matrixWorldInverse);
2719
+ textureMatrix.multiply(this.matrixWorld);
2720
+ reflectorPlane.setFromNormalAndCoplanarPoint(normal, reflectorWorldPosition);
2721
+ reflectorPlane.applyMatrix4(virtualCamera.matrixWorldInverse);
2722
+ clipPlane.set(reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant);
2723
+ const projectionMatrix = virtualCamera.projectionMatrix;
2724
+ q.x = (Math.sign(clipPlane.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0];
2725
+ q.y = (Math.sign(clipPlane.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5];
2726
+ q.z = -1;
2727
+ q.w = (1 + projectionMatrix.elements[10]) / projectionMatrix.elements[14];
2728
+ clipPlane.multiplyScalar(2 / clipPlane.dot(q));
2729
+ projectionMatrix.elements[2] = clipPlane.x;
2730
+ projectionMatrix.elements[6] = clipPlane.y;
2731
+ projectionMatrix.elements[10] = clipPlane.z + 1 - clipBias;
2732
+ projectionMatrix.elements[14] = clipPlane.w;
2733
+ this.visible = false;
2734
+ const currentRenderTarget = renderer.getRenderTarget();
2735
+ const currentXrEnabled = renderer.xr.enabled;
2736
+ const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
2737
+ renderer.xr.enabled = false;
2738
+ renderer.shadowMap.autoUpdate = false;
2739
+ renderer.setRenderTarget(thisRenderTarget);
2740
+ renderer.state.buffers.depth.setMask(true);
2741
+ if (renderer.autoClear === false) renderer.clear();
2742
+ const sceneBackground = scene.background;
2743
+ if (this.transparentReflectionBackground) scene.background = null;
2744
+ const renderBackground = !this.transparentReflectionBackground;
2745
+ if (sceneBackground?.isTexture && renderBackground) {
2746
+ if (!sceneBackground.userData) sceneBackground.userData = {};
2747
+ sceneBackground.userData.flipX = !sceneBackground.userData.flipX;
2748
+ }
2749
+ renderer.renderWithModes({
2750
+ shadowMapRender: false,
2751
+ backgroundRender: renderBackground,
2752
+ opaqueRender: true,
2753
+ transparentRender: true,
2754
+ transmissionRender: false,
2755
+ screenSpaceRendering: false
2756
+ }, () => renderer.render(scene, virtualCamera));
2757
+ if (sceneBackground?.isTexture && renderBackground) sceneBackground.userData.flipX = !sceneBackground.userData.flipX || void 0;
2758
+ if (this.transparentReflectionBackground) scene.background = sceneBackground;
2759
+ renderer.xr.enabled = currentXrEnabled;
2760
+ renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
2761
+ renderer.setRenderTarget(currentRenderTarget);
2762
+ if (viewOffset?.enabled && camera.setViewOffset) camera.setViewOffset(viewOffset.fullWidth, viewOffset.fullHeight, viewOffset.offsetX, viewOffset.offsetY, viewOffset.width, viewOffset.height);
2763
+ const viewport = camera.viewport;
2764
+ if (viewport !== void 0) renderer.state.viewport(viewport);
2765
+ this.visible = true;
2766
+ this.reflectionTargetNeedsUpdate = false;
2767
+ };
2768
+ this.textureMatrix = textureMatrix;
2769
+ this.materialExtension.extraUniforms.refTextureMatrix.value = textureMatrix;
2770
+ }
2771
+ getRenderTarget() {
2772
+ return this._renderTarget;
2773
+ }
2774
+ };
2775
+ __decorate([onChange(Reflector2.prototype._updateExtension)], Reflector2.prototype, "enabled", void 0);
2776
+ __decorate([onChange(Reflector2.prototype._updateExtension)], Reflector2.prototype, "reflectorModePhysical", void 0);
2777
+ Reflector2.prototype.isReflector = true;
2778
+ // ../../node_modules/rand-seed/dist/es/index.js
2779
+ var e = class {
2780
+ static _xfnv1a(e) {
2781
+ let t = 2166136261;
2782
+ for (let i = 0; i < e.length; i++) t = Math.imul(t ^ e.charCodeAt(i), 16777619);
2783
+ return () => (t += t << 13, t ^= t >>> 7, t += t << 3, t ^= t >>> 17, (t += t << 5) >>> 0);
2784
+ }
2785
+ };
2786
+ var t = class t extends e {
2787
+ constructor(e) {
2788
+ super(), Object.defineProperty(this, "a", {
2789
+ enumerable: !0,
2790
+ configurable: !0,
2791
+ writable: !0,
2792
+ value: void 0
2793
+ }), this.a = t._xfnv1a(e)();
2794
+ }
2795
+ next() {
2796
+ let e = this.a += 1831565813;
2797
+ return e = Math.imul(e ^ e >>> 15, 1 | e), e ^= e + Math.imul(e ^ e >>> 7, 61 | e), ((e ^ e >>> 14) >>> 0) / 4294967296;
2798
+ }
2799
+ };
2800
+ var i = class i extends e {
2801
+ constructor(e) {
2802
+ super(), Object.defineProperty(this, "a", {
2803
+ enumerable: !0,
2804
+ configurable: !0,
2805
+ writable: !0,
2806
+ value: void 0
2807
+ }), Object.defineProperty(this, "b", {
2808
+ enumerable: !0,
2809
+ configurable: !0,
2810
+ writable: !0,
2811
+ value: void 0
2812
+ }), Object.defineProperty(this, "c", {
2813
+ enumerable: !0,
2814
+ configurable: !0,
2815
+ writable: !0,
2816
+ value: void 0
2817
+ }), Object.defineProperty(this, "d", {
2818
+ enumerable: !0,
2819
+ configurable: !0,
2820
+ writable: !0,
2821
+ value: void 0
2822
+ });
2823
+ const t = i._xfnv1a(e);
2824
+ this.a = t(), this.b = t(), this.c = t(), this.d = t();
2825
+ }
2826
+ next() {
2827
+ this.a >>>= 0, this.b >>>= 0, this.c >>>= 0, this.d >>>= 0;
2828
+ let e = this.a + this.b | 0;
2829
+ return this.a = this.b ^ this.b >>> 9, this.b = this.c + (this.c << 3) | 0, this.c = this.c << 21 | this.c >>> 11, this.d = this.d + 1 | 0, e = e + this.d | 0, this.c = this.c + e | 0, (e >>> 0) / 4294967296;
2830
+ }
2831
+ };
2832
+ var r = class r extends e {
2833
+ constructor(e) {
2834
+ super(), Object.defineProperty(this, "a", {
2835
+ enumerable: !0,
2836
+ configurable: !0,
2837
+ writable: !0,
2838
+ value: void 0
2839
+ }), Object.defineProperty(this, "b", {
2840
+ enumerable: !0,
2841
+ configurable: !0,
2842
+ writable: !0,
2843
+ value: void 0
2844
+ }), Object.defineProperty(this, "c", {
2845
+ enumerable: !0,
2846
+ configurable: !0,
2847
+ writable: !0,
2848
+ value: void 0
2849
+ }), Object.defineProperty(this, "d", {
2850
+ enumerable: !0,
2851
+ configurable: !0,
2852
+ writable: !0,
2853
+ value: void 0
2854
+ });
2855
+ const t = r._xfnv1a(e);
2856
+ this.a = t(), this.b = t(), this.c = t(), this.d = t();
2857
+ }
2858
+ next() {
2859
+ const e = this.b << 9;
2860
+ let t = 5 * this.b;
2861
+ return t = 9 * (t << 7 | t >>> 25), this.c ^= this.a, this.d ^= this.b, this.b ^= this.c, this.a ^= this.d, this.c ^= e, this.d = this.d << 11 | this.d >>> 21, (t >>> 0) / 4294967296;
2862
+ }
2863
+ };
2864
+ var s;
2865
+ (function(e) {
2866
+ e.sfc32 = "sfc32", e.mulberry32 = "mulberry32", e.xoshiro128ss = "xoshiro128ss";
2867
+ })(s || (s = {}));
2868
+ var a = class {
2869
+ constructor(e, t = s.sfc32) {
2870
+ Object.defineProperty(this, "str", {
2871
+ enumerable: !0,
2872
+ configurable: !0,
2873
+ writable: !0,
2874
+ value: void 0
2875
+ }), Object.defineProperty(this, "prng", {
2876
+ enumerable: !0,
2877
+ configurable: !0,
2878
+ writable: !0,
2879
+ value: void 0
2880
+ }), Object.defineProperty(this, "generator", {
2881
+ enumerable: !0,
2882
+ configurable: !0,
2883
+ writable: !0,
2884
+ value: void 0
2885
+ }), this.str = e, this.prng = t, this.generator = this._initializeGenerator();
2886
+ }
2887
+ next() {
2888
+ return this.generator.next();
2889
+ }
2890
+ _initializeGenerator() {
2891
+ if (((e) => null === e)(e = this.str) || ((e) => void 0 === e)(e)) return this.wrap();
2892
+ var e;
2893
+ switch (this.prng) {
2894
+ case "sfc32": return new i(this.str);
2895
+ case "mulberry32": return new t(this.str);
2896
+ case "xoshiro128ss": return new r(this.str);
2897
+ default: return this.wrap();
2898
+ }
2899
+ }
2900
+ wrap() {
2901
+ return { next: () => Math.random() };
2902
+ }
2903
+ };
2904
+ // src/utils/RandomizedDirectionalLight.ts
2905
+ var RandomizedDirectionalLight = class extends DirectionalLight2 {
2906
+ constructor(color, intensity, shadow, random) {
2907
+ super(color, intensity);
2908
+ this._shadowParams = {
2909
+ enabled: true,
2910
+ radius: 2,
2911
+ width: 1024,
2912
+ height: 1024,
2913
+ bias: -.001,
2914
+ normalBias: 0,
2915
+ near: 1.5,
2916
+ far: 4,
2917
+ frustumSize: 4
2918
+ };
2919
+ this._randomParams = {
2920
+ focus: 1,
2921
+ spread: .01,
2922
+ distanceScale: 50,
2923
+ minDistanceScale: new Vector3(10, 10, 10),
2924
+ normalDirection: new Vector3(.01, .98, .01).normalize(),
2925
+ direction: new Vector3(-.9, .5, -1)
2926
+ };
2927
+ this.isRandomizedDirectionalLight = true;
2928
+ this.shadowParams = shadow ?? {};
2929
+ this.randomParams = random ?? {};
2930
+ this.updateShadowParams = this.updateShadowParams.bind(this);
2931
+ }
2932
+ /**
2933
+ * call setter to change. or call updateShadowParams after changing
2934
+ */
2935
+ get shadowParams() {
2936
+ return this._shadowParams;
2937
+ }
2938
+ set shadowParams(value) {
2939
+ Object.keys(value).forEach((key) => value[key] === void 0 && delete value[key]);
2940
+ this._shadowParams = {
2941
+ ...this._shadowParams,
2942
+ ...value
2943
+ };
2944
+ this.updateShadowParams();
2945
+ }
2946
+ get randomParams() {
2947
+ return this._randomParams;
2948
+ }
2949
+ set randomParams(value) {
2950
+ Object.keys(value).forEach((key) => value[key] === void 0 && delete value[key]);
2951
+ Object.assign(this._randomParams, value);
2952
+ }
2953
+ updateShadowParams() {
2954
+ this.castShadow = this._shadowParams.enabled;
2955
+ this.shadow.mapSize.x = this._shadowParams.width;
2956
+ this.shadow.mapSize.y = this._shadowParams.height;
2957
+ this.shadow.bias = this._shadowParams.bias;
2958
+ this.shadow.normalBias = this._shadowParams.normalBias;
2959
+ this.refreshShadowCamNearFar();
2960
+ this.shadow.radius = this._shadowParams.radius;
2961
+ this.shadow.camera.right = this._shadowParams.frustumSize / 2;
2962
+ this.shadow.camera.left = -this._shadowParams.frustumSize / 2;
2963
+ this.shadow.camera.top = this._shadowParams.frustumSize / 2;
2964
+ this.shadow.camera.bottom = -this._shadowParams.frustumSize / 2;
2965
+ this.shadow.camera.updateProjectionMatrix();
2966
+ this.matrixWorldNeedsUpdate = true;
2967
+ }
2968
+ randomizePosition(seed, focus = null, spread = null) {
2969
+ const rand = new a(seed.toString());
2970
+ const rnd = new Vector2(rand.next() * Math.PI * 2, Math.asin(rand.next() * 2 - 1));
2971
+ let dir = new Vector3(Math.cos(rnd.x) * Math.cos(rnd.y), Math.sin(rnd.y), Math.sin(rnd.x) * Math.cos(rnd.y));
2972
+ /**
2973
+ * @type {string}
2974
+ */
2975
+ const v2 = new Vector2();
2976
+ for (let kk = 0; kk < 5; kk++) {
2977
+ v2.set(rand.next(), rand.next());
2978
+ dir = getSample(v2, this._randomParams.normalDirection, .4);
2979
+ if (rand.next() < Math.sqrt(focus ?? this._randomParams.focus)) {
2980
+ v2.set(rand.next(), rand.next());
2981
+ dir = getSample(v2, this._randomParams.direction, Math.pow((spread ?? this._randomParams.spread) / 2, 2));
2982
+ }
2983
+ const cd = dir.dot(this._randomParams.normalDirection);
2984
+ if (cd > 0 && cd < .4) break;
2985
+ }
2986
+ dir.normalize();
2987
+ dir.multiplyScalar(this._randomParams.distanceScale);
2988
+ this.position.set(0, 0, 0);
2989
+ this.target.position.copy(dir.normalize().negate());
2990
+ this.target.updateMatrixWorld();
2991
+ this.refreshShadowCamNearFar();
2992
+ this.updateMatrixWorld();
2993
+ }
2994
+ refreshShadowCamNearFar() {
2995
+ const dist = new Vector3().subVectors(this.target.position, this.shadow.camera.position).length();
2996
+ this.shadow.camera.near = dist - this._shadowParams.near * this._shadowParams.frustumSize / 2;
2997
+ this.shadow.camera.far = dist + this._shadowParams.far * this._shadowParams.frustumSize / 2;
2998
+ }
2999
+ dispose() {
3000
+ super.dispose();
3001
+ }
3002
+ toJSON(meta, _internal = false) {
3003
+ const { userData, children } = this;
3004
+ this.userData = {};
3005
+ this.children = [];
3006
+ const data = super.toJSON(meta);
3007
+ const copiedData = copyObject3DUserData({}, userData);
3008
+ data.userData = Serialization.Serialize(copiedData);
3009
+ this.userData = userData;
3010
+ this.children = children;
3011
+ data.type = "DirectionalLight2";
3012
+ data.target = this.target.position.toArray();
3013
+ return {
3014
+ ...data,
3015
+ ...ThreeSerialization.Serialize(this, meta, true)
3016
+ };
3017
+ }
3018
+ fromJSON(data, meta, _internal = false) {
3019
+ if (data.type !== "DirectionalLight2") return null;
3020
+ const target = data.target;
3021
+ const object = data.object;
3022
+ if (data.target) {
3023
+ this.target.position.fromArray(data.target);
3024
+ this.target.updateMatrixWorld();
3025
+ delete data.target;
3026
+ }
3027
+ if (data.object) delete data.object;
3028
+ ThreeSerialization.Deserialize(data, this, meta, true);
3029
+ if (target) data.target = target;
3030
+ if (object) {
3031
+ if (object.color !== void 0) this.color.set(object.color);
3032
+ if (object.intensity !== void 0) this.intensity = object.intensity;
3033
+ data.object = object;
3034
+ }
3035
+ this.updateShadowParams();
3036
+ return this;
3037
+ }
3038
+ };
3039
+ __decorate([serialize("shadowParams")], RandomizedDirectionalLight.prototype, "_shadowParams", void 0);
3040
+ __decorate([serialize("randomParams")], RandomizedDirectionalLight.prototype, "_randomParams", void 0);
3041
+ /**
3042
+ * Random direction, uniformly distributed over the cone around `dir` in which cos(angle to dir)
3043
+ * is between 1 - extent and 1: phi = 2 pi u, cos(theta) = 1 - v extent, with (u, v) = rand in [0, 1).
3044
+ * Basis: b1 = (0, -dir.z, dir.y) and b2 = dir x b1, both zero when dir is along x.
3045
+ */
3046
+ function getSample(rand, dir, extent) {
3047
+ const w = dir.clone().normalize();
3048
+ const b1 = new Vector3(0, -w.z, w.y).normalize();
3049
+ const b2 = new Vector3().crossVectors(w, b1).normalize();
3050
+ const phi = rand.x * 2 * Math.PI;
3051
+ const cosTheta = 1 - rand.y * extent;
3052
+ const sinTheta = Math.sqrt(1 - cosTheta * cosTheta);
3053
+ return b1.multiplyScalar(Math.cos(phi) * sinTheta).add(b2.multiplyScalar(Math.sin(phi) * sinTheta)).add(w.multiplyScalar(cosTheta));
3054
+ }
3055
+ // src/utils/FSShadowMaterial.ts
3056
+ var FSShadowMaterial = class extends ShadowMaterial {
3057
+ constructor(..._args) {
3058
+ super(..._args);
3059
+ this.typeSlug = "fsShadow";
3060
+ this.assetType = "material";
3061
+ this._uniforms = {};
3062
+ this.lastFrameTexture = null;
3063
+ }
3064
+ get materialObject() {
3065
+ return this;
3066
+ }
3067
+ onBeforeCompile(shader, renderer) {
3068
+ shader.vertexShader = shader.vertexShader.replace("#include <project_vertex>", `
3069
+ #include <project_vertex>
3070
+ gl_Position = vec4(uv*2.-1., 0, 1.);
3071
+ `);
3072
+ shader.vertexShader = shader.vertexShader.replace("void main() {", `
3073
+ varying vec2 vUv;
3074
+ void main() {
3075
+ vUv = uv;
3076
+ `);
3077
+ shader.fragmentShader = shader.fragmentShader.replace("void main() {", `
3078
+ varying vec2 vUv;
3079
+ uniform sampler2D tLastThis;
3080
+ void main() {
3081
+ `);
3082
+ shader.fragmentShader = shader.fragmentShader.replace("gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );", glsl`
62
3083
  float shadow = getShadowMask();
63
3084
 
64
3085
  //shift the color by dither_shift
@@ -68,9 +3089,78 @@ float last = unpackRGBAToDepth(texture2D(tLastThis, vUv));
68
3089
  gl_FragColor = packDepthToRGBA(mix(last, shadow, opacity));
69
3090
  //if not useMovingAverage:
70
3091
  //gl_FragColor = packDepthToRGBA(shadow * opacity + last);
71
- `),Object.assign(e.uniforms,this._uniforms),super.onBeforeCompile(e,t)}customProgramCacheKey(){return super.customProgramCacheKey()}toJSON(){throw new Error("Method not supported for this material.")}fromJSON(){throw new Error("Method not supported for this material.")}copyProps(){throw new Error("Method not supported for this material.")}setDirty(e){this.needsUpdate=!0,this.dispatchEvent({...e,type:"materialUpdate"})}}((e,t,r)=>{for(var i,a=void 0,s=e.length-1;s>=0;s--)(i=e[s])&&(a=i(t,r,a)||a);a&&Yt(t,r,a)})([m({propKey:"tLastThis"})],Xt.prototype,"lastFrameTexture");var Kt=Object.defineProperty,qt=(e,t,r,i)=>{for(var a,s=void 0,n=e.length-1;n>=0;n--)(a=e[n])&&(s=a(t,r,s)||s);return s&&Kt(t,r,s),s};const Zt=r.ShaderChunk,Jt=class extends fe{constructor(e){super(),this.enabled=!0,this._lightLayer=5,this._frameNumber=0,this.maxFrameNumber=400,this.smoothShadow=!1,this.shadowMapType=me,this.groundMapMode="aoMap",this.alphaVignette=!0,this.alphaVignetteAxis="xy",this.shadowAutoUpdate=!0,this._bakeCounter=0,this.maxBakeCount=1/0,this.materialExtension={parsFragmentSnippet:(e,t)=>K`
3092
+ `);
3093
+ Object.assign(shader.uniforms, this._uniforms);
3094
+ super.onBeforeCompile(shader, renderer);
3095
+ }
3096
+ customProgramCacheKey() {
3097
+ return super.customProgramCacheKey();
3098
+ }
3099
+ toJSON() {
3100
+ throw new Error("Method not supported for this material.");
3101
+ }
3102
+ fromJSON() {
3103
+ throw new Error("Method not supported for this material.");
3104
+ }
3105
+ copyProps() {
3106
+ throw new Error("Method not supported for this material.");
3107
+ }
3108
+ setDirty(options) {
3109
+ this.needsUpdate = true;
3110
+ this.dispatchEvent({
3111
+ ...options,
3112
+ type: "materialUpdate"
3113
+ });
3114
+ }
3115
+ };
3116
+ __decorate([uniform({ propKey: "tLastThis" })], FSShadowMaterial.prototype, "lastFrameTexture", void 0);
3117
+ // src/utils/shaders/seperableShadowBlur.glsl
3118
+ var seperableShadowBlur_default = "#include <packing>\nuniform sampler2D colorTexture;uniform vec2 size;uniform vec2 direction;uniform float step;varying vec2 vUv;void main(){float sum=0.0;vec2 uvDelta=step*direction/size;sum+=unpackRGBAToDepth(texture2D(colorTexture,vUv-1.*uvDelta))*0.3333;sum+=unpackRGBAToDepth(texture2D(colorTexture,vec2(vUv.x,vUv.y)))*0.3333;sum+=unpackRGBAToDepth(texture2D(colorTexture,vUv+1.*uvDelta))*0.3333;gl_FragColor=packDepthToRGBA(sum);}";
3119
+ // src/utils/ShadowMapBaker.ts
3120
+ var ShaderChunk = RenderManager.ShaderChunk;
3121
+ var ShadowMapBaker = class extends SimpleEventDispatcher {
3122
+ get attachedMesh() {
3123
+ return this._attachedMesh;
3124
+ }
3125
+ set attachedMesh(value) {
3126
+ if (this._attachedMesh !== value) {
3127
+ this._attachedMesh && this.cleanupMaterial();
3128
+ this._attachedMesh = value;
3129
+ this._attachedMesh && this._updateMaterial();
3130
+ }
3131
+ }
3132
+ get target() {
3133
+ return this._target;
3134
+ }
3135
+ get light() {
3136
+ return this._light;
3137
+ }
3138
+ constructor(viewer) {
3139
+ super();
3140
+ this.enabled = true;
3141
+ this._lightLayer = 5;
3142
+ this._frameNumber = 0;
3143
+ this.maxFrameNumber = 400;
3144
+ this.smoothShadow = false;
3145
+ this.shadowMapType = BasicShadowMap;
3146
+ this.groundMapMode = "aoMap";
3147
+ this.alphaVignette = true;
3148
+ this.alphaVignetteAxis = "xy";
3149
+ this.shadowAutoUpdate = true;
3150
+ this._bakeCounter = 0;
3151
+ this.maxBakeCount = Infinity;
3152
+ this.materialExtension = {
3153
+ parsFragmentSnippet: (_renderer, _material) => {
3154
+ return glsl`
72
3155
  uniform float transitionOpacity;
73
- `,extraUniforms:{transitionOpacity:{value:1}},shaderExtender:(e,t,r)=>{"aoMap"===this.groundMapMode?e.fragmentShader=y(e.fragmentShader,"#include <aomap_fragment>",y(Zt.aomap_fragment,"float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;","float ambientOcclusion = ( mix(1., unpackRGBAToDepth(texture2D( aoMap, vAoMapUv ) ), transitionOpacity) - 1.0) * aoMapIntensity + 1.0;")):"map"===this.groundMapMode?e.fragmentShader=y(e.fragmentShader,"#include <map_fragment>",y(Zt.map_fragment,"diffuseColor *= sampledDiffuseColor","float groundShadow = mix(1., unpackRGBAToDepth(sampledDiffuseColor), transitionOpacity); diffuseColor.rgb *= groundShadow; diffuseColor.a *= max(0., 1.-groundShadow) * transitionOpacity;")):"alphaMap"===this.groundMapMode&&(e.fragmentShader=y(e.fragmentShader,"#include <alphamap_fragment>",y(Zt.alphamap_fragment,"texture2D( alphaMap, vAlphaMapUv ).g","1. - unpackRGBAToDepth( texture2D( alphaMap, vAlphaMapUv ) )",{replaceAll:!0}))),e.fragmentShader=y(e.fragmentShader,"#include <opaque_fragment>",K`#include <opaque_fragment>
3156
+ `;
3157
+ },
3158
+ extraUniforms: { transitionOpacity: { value: 1 } },
3159
+ shaderExtender: (shader, _material, renderer) => {
3160
+ if (this.groundMapMode === "aoMap") shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#include <aomap_fragment>", shaderReplaceString(ShaderChunk.aomap_fragment, "float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;", "float ambientOcclusion = ( mix(1., unpackRGBAToDepth(texture2D( aoMap, vAoMapUv ) ), transitionOpacity) - 1.0) * aoMapIntensity + 1.0;"));
3161
+ else if (this.groundMapMode === "map") shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#include <map_fragment>", shaderReplaceString(ShaderChunk.map_fragment, "diffuseColor *= sampledDiffuseColor", "float groundShadow = mix(1., unpackRGBAToDepth(sampledDiffuseColor), transitionOpacity); diffuseColor.rgb *= groundShadow; diffuseColor.a *= max(0., 1.-groundShadow) * transitionOpacity;"));
3162
+ else if (this.groundMapMode === "alphaMap") shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#include <alphamap_fragment>", shaderReplaceString(ShaderChunk.alphamap_fragment, "texture2D( alphaMap, vAlphaMapUv ).g", "1. - unpackRGBAToDepth( texture2D( alphaMap, vAlphaMapUv ) )", { replaceAll: true }));
3163
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#include <opaque_fragment>", glsl`#include <opaque_fragment>
74
3164
  #ifndef OPAQUE
75
3165
  #ifdef USE_AOMAP
76
3166
  #if NUM_DIR_LIGHT_SHADOWS > 0
@@ -85,7 +3175,10 @@ gl_FragColor = packDepthToRGBA(mix(last, shadow, opacity));
85
3175
  gl_FragColor.a *= max(t, 0.);
86
3176
  #endif
87
3177
  #endif
88
- `),this.alphaVignette&&r.capabilities.isWebGL2&&(e.defines.USE_UV="",e.fragmentShader=y(e.fragmentShader,"#include <opaque_fragment>",K`#include <opaque_fragment>
3178
+ `);
3179
+ if (this.alphaVignette && renderer.capabilities.isWebGL2) {
3180
+ shader.defines.USE_UV = "";
3181
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#include <opaque_fragment>", glsl`#include <opaque_fragment>
89
3182
  #ifndef OPAQUE
90
3183
  float weight = 0.;
91
3184
  #ifdef USE_UV // why are we checking for this? this is always supposed to be true
@@ -102,5 +3195,718 @@ gl_FragColor = packDepthToRGBA(mix(last, shadow, opacity));
102
3195
  gl_FragColor = saturate(gl_FragColor);
103
3196
  //gl_FragColor.a = 0.5;
104
3197
  #endif
105
- `))},computeCacheKey:()=>this.groundMapMode+"."+this.alphaVignette+"."+this.alphaVignetteAxis,onObjectRender:(e,t)=>{t.userData.gMapMode!==this.groundMapMode&&(t.userData.gMapMode=this.groundMapMode,t.needsUpdate=!0)},isCompatible:e=>e.isPhysicalMaterial},this._viewer=e;const t=new Ht(16777215,10,{near:1.5,far:20,bias:0,frustumSize:4,width:1024,height:1024,enabled:!0,radius:10,normalBias:0},{direction:new F(.2,1,.2).normalize(),spread:.9,focus:1,distanceScale:20,minDistanceScale:new F(10,10,10),normalDirection:new F(0,1,0)});t.shadow.camera.updateProjectionMatrix(),t.layers.disableAll(),t.layers.set(this._lightLayer),this._light=t,e.scene.addObject(this._light,{addToRoot:!0}),this._shadowMat=new Xt({color:"#ffffff",toneMapped:!1,depthWrite:!1,depthTest:!1,premultipliedAlpha:!1,opacity:1,transparent:!1,blending:T}),this._shadowBlurMat=new ge({uniforms:{colorTexture:{value:null},step:{value:.1},size:{value:new d(.5,.5)},direction:{value:new d(.5,.5)}},vertexShader:V.defaultVertex,fragmentShader:"#include <packing>\nuniform sampler2D colorTexture;uniform vec2 size;uniform vec2 direction;uniform float step;varying vec2 vUv;void main(){float sum=0.0;vec2 uvDelta=step*direction/size;sum+=unpackRGBAToDepth(texture2D(colorTexture,vUv-1.*uvDelta))*0.3333;sum+=unpackRGBAToDepth(texture2D(colorTexture,vec2(vUv.x,vUv.y)))*0.3333;sum+=unpackRGBAToDepth(texture2D(colorTexture,vUv+1.*uvDelta))*0.3333;gl_FragColor=packDepthToRGBA(sum);}"})}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh!==e&&(this._attachedMesh&&this.cleanupMaterial(),this._attachedMesh=e,this._attachedMesh&&this._updateMaterial())}get target(){return this._target}get light(){return this._light}dispose(){this._shadowMat.dispose(),this._target=void 0,this.reset()}cleanupMaterial(){this._updateMaterial(!0)}_groundMapModeChanged(){this._attachedMesh&&(this.cleanupMaterial(),this._updateMaterial(),"alphaMap"===this.groundMapMode?this._attachedMesh.material.transparent=!0:this._attachedMesh.material.transparent=!1),this.reset()}_alphaVignetteChanged(){this.materialExtension?.setDirty?.(),this._viewer?.setDirty()}fromJSON(e,t,r=!1){return r?(he.Deserialize(e,this,t,!0),this.reset(),this):he.Deserialize(e,this,t,!1)}reset(){this._frameNumber=0}get frameNumber(){return this._frameNumber}autoUpdateShadow(){return!!this.shadowAutoUpdate&&(!(this._bakeCounter>=this.maxBakeCount)&&(!!this.updateShadow()&&(this._frameNumber===this.maxFrameNumber?this.dispatchEvent({type:"shadowBaked",bakeCount:++this._bakeCounter}):this._frameNumber>0&&this._frameNumber<this.maxFrameNumber&&this.dispatchEvent({type:"shadowBaking",progress:this._frameNumber/this.maxFrameNumber,bakeCount:this._bakeCounter}),!0)))}updateShadow(){if(!this.enabled)return!1;const e=this._attachedMesh;if(!e)return!1;if(++this._frameNumber>this.maxFrameNumber)return!1;const t=1024;this._target||(this._target=this._viewer.renderManager.createTarget({type:_,depthBuffer:!1,size:new d(t,t),sizeMultiplier:void 0,colorSpace:ve,format:G})),this._frameNumber<3?this._light.randomizePosition(0,1,0):this._light.randomizePosition(this._frameNumber),e.castShadow=!1;const r=this._viewer.renderManager.renderer,i=r.shadowMap,a=i.type,s=i.needsUpdate,n=i.autoUpdate;i.type=this.shadowMapType,i.needsUpdate=!0,i.autoUpdate=!1;const o=this._viewer.scene,l=new _e;l.disableAll(),o.traverse(e=>{e.isLight&&e!==this._light&&(e.userData.__gp_layers=e.layers,e.layers=l)});const c=o.mainCamera;if(c.layers.mask&1<<this._lightLayer)throw"Camera can render pseudo directional light, check layers";c.layers.enable(this._lightLayer),e.layers.disable(this._lightLayer),r.renderWithModes({shadowMapRender:!0,backgroundRender:!1,sceneRender:!1},()=>r.render(o,o.mainCamera)),c.layers.disable(this._lightLayer);const u=c.layers.mask;c.layers.set(this._lightLayer),e.layers.enable(this._lightLayer);const h=this._viewer.renderManager.getTempTarget({type:_,depthBuffer:!1,size:new d(t,t),colorSpace:ve,format:G}),p=h.texture,f=p.colorSpace;p.colorSpace=ve,this._viewer.renderManager.blit(h,{clear:!0,source:this._target.texture});{const t=e.material,i=e.frustumCulled,a=r.getRenderTarget(),s=r.getActiveCubeFace(),n=r.getActiveMipmapLevel();e.material=this._shadowMat,e.frustumCulled=!1,r.setRenderTarget(this._target),this._shadowMat.opacity=Math.max(1/this.maxFrameNumber,1/this._frameNumber),this._shadowMat.lastFrameTexture=h.texture,this._shadowMat.needsUpdate=!0,r.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!0,transparentRender:!1,transmissionRender:!1},()=>r.render(o,o.mainCamera)),r.setRenderTarget(a,s,n),e.frustumCulled=i,e.material=t,this.smoothShadow&&this._applySmoothFilter(this._target,h)}return h.texture.colorSpace=f,this._viewer.renderManager.releaseTempTarget(h),e.layers.disable(this._lightLayer),c.layers.mask=u,o.modelObject.traverse(e=>{e.isLight&&e!==this._light.lightObject&&(e.layers=e.userData.__gp_layers,delete e.userData.__gp_layers)}),i.type=a,i.needsUpdate=s,i.autoUpdate=n,e.castShadow=!0,(this._frameNumber<3||this._frameNumber>Math.min(100,this.maxFrameNumber)&&this._frameNumber%4==0)&&(this._updateMaterial(),e.material.setDirty()),!0}_updateMaterial(e=!1){this._attachedMesh&&(e?(this._attachedMesh.material.alphaMap===this._target?.texture&&(this._attachedMesh.material.alphaMap=null),this._attachedMesh.material.aoMap===this._target?.texture&&(this._attachedMesh.material.aoMap=null),this._attachedMesh.material.map===this._target?.texture&&(this._attachedMesh.material.map=null)):this._target&&("alphaMap"===this.groundMapMode&&(this._attachedMesh.material.alphaMap=this._target.texture),"aoMap"===this.groundMapMode&&(this._attachedMesh.material.aoMap=this._target.texture),"map"===this.groundMapMode&&(this._attachedMesh.material.map=this._target.texture)),this._attachedMesh.material&&(this._attachedMesh.material.userData.ALPHA_I_RGBA_PACKING=!e&&"alphaMap"===this.groundMapMode,this._attachedMesh.material.alphaTest=e||"alphaMap"!==this.groundMapMode?0:.01,this._attachedMesh.material.needsUpdate=!0))}_applySmoothFilter(e,t){this._shadowBlurMat.uniforms.colorTexture.value=e.texture,this._shadowBlurMat.uniforms.direction.value.set(1,0),this._shadowBlurMat.uniforms.size.value.set(e.width,e.height),this._viewer.renderManager.blit(t,{material:this._shadowBlurMat}),this._shadowBlurMat.uniforms.colorTexture.value=t.texture,this._shadowBlurMat.uniforms.direction.value.set(0,1),this._shadowBlurMat.uniforms.size.value.set(t.width,t.height),this._viewer.renderManager.blit(e,{material:this._shadowBlurMat})}};qt([f("randomizedLight")],Jt.prototype,"_light"),qt([B(Jt.prototype.reset),f()],Jt.prototype,"maxFrameNumber"),qt([B(Jt.prototype.reset),f()],Jt.prototype,"smoothShadow"),qt([f(),B(Jt.prototype.reset)],Jt.prototype,"shadowMapType"),qt([B(Jt.prototype._groundMapModeChanged),f()],Jt.prototype,"groundMapMode"),qt([f(),B(Jt.prototype._alphaVignetteChanged)],Jt.prototype,"alphaVignette"),qt([f(),B(Jt.prototype._alphaVignetteChanged)],Jt.prototype,"alphaVignetteAxis"),qt([f()],Jt.prototype,"maxBakeCount");let $t=Jt;var Qt=Object.defineProperty,er=(e,t,r,i)=>{for(var a,s=void 0,n=e.length-1;n>=0;n--)(a=e[n])&&(s=a(t,r,s)||s);return s&&Qt(t,r,s),s};const tr=((t=class extends q{constructor(){super(),this.bakedShadows=!0,this.groundReflection=!1,this.physicalReflections=!1,this.autoFrustumSize=!0,this.autoBakeShadows=!0,this.autoResetShadows=()=>{this.autoBakeShadows&&this._shadowBaker?.reset()},this._onSceneUpdate=this._onSceneUpdate.bind(this);const e=n(this),t=e.find(e=>"function"==typeof e);this.uiConfig={label:"Ground",type:"folder",children:[...e.filter(e=>e!==t),...this._extraUiConfig(),t]}}get shadowBaker(){return this._shadowBaker}_refresh3(){this.refresh()}bakeShadows(){this._shadowBaker?.reset()}_createMesh(e){if(e)throw new Error("AdvancedGroundPlugin - mesh should not be provided");const t=new Ot(this._geometry,()=>this._viewer?.renderManager.createTarget({type:_,format:G,colorSpace:ve,size:{width:1024,height:1024},generateMipmaps:!0,depthBuffer:!0,minFilter:xe,magFilter:ye}),0,this._createMaterial()),r=t.onBeforeRender;return t.onBeforeRender=(...e)=>{let i=this._viewer?.getPluginByType("SSReflectionPlugin");i&&i.isDisabled()&&(i=void 0),i&&i.disable(t.uuid,!1),r(...e),i&&i.enable(t.uuid,!1)},t}onAdded(e){super.onAdded(e)}_postFrame(){super._postFrame(),this._viewer&&this.enabled&&this._shadowBaker&&this.bakedShadows&&this._shadowBaker.autoUpdateShadow()}_preRender(){super._preRender(),this._viewer&&(this._mesh.reflectionTargetNeedsUpdate=this._viewer.renderManager.frameCount<1)}onRemove(e){return super.onRemove(e)}_removeMaterial(){if(this._material){if(this._shadowBaker&&this._material.groundMatExtension&&(this._material.unregisterMaterialExtensions?.([this._shadowBaker.materialExtension]),delete this._material.groundMatExtension),this._material.reflectorMatExtension){const e=this._mesh.materialExtension;e||this._viewer?.console.warn("AdavancedGroundPlugin: unable to find the extension to unregister"),this._material.unregisterMaterialExtensions?.([e]),delete this._material.reflectorMatExtension}super._removeMaterial()}}_onSceneUpdate(e){super._onSceneUpdate(e),"widget"===e?.object?.assetType||e?.object?.userData?.isWidgetRoot||!1!==e.geometryChanged&&this.autoResetShadows()}refresh(){if(this._viewer){if(!this.isDisabled()){this.bakedShadows&&!this._shadowBaker?(this._shadowBaker=new $t(this._viewer),this._shadowBaker.attachedMesh=this._mesh):!this.bakedShadows&&this._shadowBaker&&(this._shadowBaker.reset(),this._shadowBaker.cleanupMaterial());const e=this._mesh;e.isReflector2&&(e.enabled=this.groundReflection,e.reflectorModePhysical=this.physicalReflections)}super.refresh()}}_refreshTransform(){if(!super._refreshTransform())return!1;if(this.autoFrustumSize){const e=this.shadowBaker;if(e){const t=this.size/2;t!==e.light.shadowParams.frustumSize&&(e.light.shadowParams.frustumSize=t,e.light.updateShadowParams(),e.reset())}}return!0}fromJSON(e,t){return super.fromJSON(e,t)?(void 0===e.autoFrustumSize&&(this.autoFrustumSize=!1),this):null}_refreshMaterial(){if(!this._viewer)return!1;if(super._refreshMaterial(),this._material){if(this.groundReflection&&this._mesh.isReflector2&&!this._material.reflectorMatExtension){const e=this._mesh.materialExtension;e.updaters=[this._viewer.scene,this._viewer.renderManager],this._material.registerMaterialExtensions?.([e]),this._material.reflectorMatExtension=!0}this.bakedShadows&&this._shadowBaker&&!this._material.groundMatExtension&&(this._material.registerMaterialExtensions?.([this._shadowBaker.materialExtension]),this._material.groundMatExtension=!0),this._material.userData.ssreflDisabled=this.groundReflection,this._material.userData.ssreflNonPhysical=!this.physicalReflections,this._material.userData.ssaoDisabled=!0,this._material.userData.sscsDisabled=!0,this._viewer.setDirty(this)}}_extraUiConfig(){return[{label:"Shadow Frames",type:"input",hidden:()=>!this._shadowBaker,stepSize:1,bounds:[1,1e3],property:()=>[this._shadowBaker,"maxFrameNumber"]},{label:"Alpha Vignette",type:"checkbox",hidden:()=>!this._material||(this._material.transmission||0)<1e-4&&!this._material.transparent,property:()=>[this._shadowBaker,"alphaVignette"],limitedUi:!0,onChange:()=>this.uiConfig?.uiRefresh?.(!0,"postFrame")},{label:"Alpha Vignette Axis",type:"dropdown",hidden:()=>!this._shadowBaker?.alphaVignette||!this._material||(this._material.transmission||0)<1e-4&&!this._material.transparent,property:()=>[this._shadowBaker,"alphaVignetteAxis"],children:["x","y","xy"].map(e=>({label:e,value:e})),limitedUi:!0},{label:"Shadow type",type:"dropdown",hidden:()=>!this._shadowBaker,property:()=>[this._shadowBaker,"groundMapMode"],children:[{label:"aoMap"},{label:"map"},{label:"alphaMap"}],limitedUi:!0},{label:"Smooth Shadow",type:"checkbox",property:()=>[this._shadowBaker,"smoothShadow"]},{label:"Baked shadow type",type:"dropdown",children:[["Basic",me],["PCF",Se],["PCFSoft",be],["VSM",we]].map(e=>({label:e[0].toString(),value:e[1]})),property:()=>[this._shadowBaker,"shadowMapType"]},{type:"folder",label:"Randomized Light",hidden:()=>!this._shadowBaker,limitedUi:!0,children:[{type:"color",label:"Color",property:()=>[this._shadowBaker?.light,"color"]},{type:"slider",bounds:[0,1],property:()=>[this._shadowBaker?.light?.randomParams,"focus"],onChange:this.autoResetShadows},{type:"slider",bounds:[0,1],property:()=>[this._shadowBaker?.light?.randomParams,"spread"],onChange:this.autoResetShadows,limitedUi:!0},{type:"slider",bounds:[.01,60],property:()=>[this._shadowBaker?.light?.randomParams,"distanceScale"],onChange:[this._shadowBaker?.light?.updateShadowParams,this.autoResetShadows]},{type:"vec3",bounds:[-1,1],property:()=>[this._shadowBaker?.light?.randomParams,"direction"],onChange:this.autoResetShadows,limitedUi:!0},{type:"vec3",bounds:[-1,1],property:()=>[this._shadowBaker?.light?.randomParams,"normalDirection"],onChange:this.autoResetShadows,limitedUi:!0},{type:"slider",bounds:[.01,10],property:()=>[this._shadowBaker?.light?.shadowParams,"radius"],onChange:[this._shadowBaker?.light?.updateShadowParams,this.autoResetShadows]},{type:"input",property:()=>[this._shadowBaker?.light?.shadowParams,"frustumSize"],hidden:()=>this.autoFrustumSize,onChange:[this._shadowBaker?.light?.updateShadowParams,this.autoResetShadows]},{type:"slider",bounds:[-.1,.1],property:()=>[this._shadowBaker?.light?.shadowParams,"bias"],onChange:[this._shadowBaker?.light?.updateShadowParams,this.autoResetShadows]}]}]}}).PluginType="AdvancedGroundPlugin",t);er([B(tr.prototype._refresh3),o("Baked Shadows"),f()],tr.prototype,"bakedShadows"),er([B(tr.prototype._refresh3),o("Planar Reflections"),f()],tr.prototype,"groundReflection"),er([B(tr.prototype._refresh3),o("Physical Reflections"),f()],tr.prototype,"physicalReflections"),er([B(tr.prototype._refresh3),o("Auto Shadow Frustum Size"),f()],tr.prototype,"autoFrustumSize"),er([f("shadowBaker")],tr.prototype,"_shadowBaker"),er([W({key:"groundReflection"})],tr.prototype,"planarReflections");let rr=tr;var ir=Object.defineProperty,ar=Object.getOwnPropertyDescriptor,sr=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?ar(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&ir(t,r,s),s};let nr=class extends Y{constructor(){super(...arguments),this.enabled=!0,this.dependencies=[],this.axis="y",this.invertAxis=!1,this.analog=!0,this.hourOffset=0,this.minuteOffset=0,this.secondOffset=0,this.hour=".*hour.*",this.minute=".*minute.*",this.second=".*second.*",this.regex=!0,this.hands=[],this._lastEnabled=!0,this._preFrame=()=>{if(!this.enabled){if(this._lastEnabled){if(this._lastEnabled=!1,!this.hands.length)return;for(const e of this.hands)e.object.rotation.fromArray(e.object.userData.initRotation),e.object.updateMatrixWorld();this._viewer?.renderManager.resetShadows(),this._viewer?.setDirty()}return}if(this._lastEnabled=!0,!this.hands.length)return;const e=this._viewer?.getPlugin("ProgressivePlugin")?.postFrameConvergedRecordingDelta();if(0===e)return;const t=/* @__PURE__ */new Date,r=this.invertAxis?-1:1,i=r*(t.getSeconds()+(this.analog?t.getMilliseconds()/1e3:0)-this.secondOffset)*(2*Math.PI)/60,a=r*(t.getMinutes()-this.minuteOffset)*(2*Math.PI)/60+i/60,s=r*(t.getHours()-this.hourOffset)*(2*Math.PI)/12+a/12;if(this.hands.find(e=>"second"===e.type&&Math.abs(i-e.object.rotation[this.axis])>.001)){for(const e of this.hands)"second"===e.type&&(e.object.rotation[this.axis]=i),"minute"===e.type&&(e.object.rotation[this.axis]=a),"hour"===e.type&&(e.object.rotation[this.axis]=s);this._viewer?.renderManager.resetShadows(),this._viewer?.setDirty()}},this._addSceneObject=async e=>{e.object&&this.refresh()}}onAdded(e){super.onAdded(e),e.scene.addEventListener("addSceneObject",this._addSceneObject),e.addEventListener("preFrame",this._preFrame)}onRemove(e){e.scene.removeEventListener("addSceneObject",this._addSceneObject),e.removeEventListener("preFrame",this._preFrame),super.onRemove(e)}refresh(){this.hands=[],this._viewer?.scene.modelRoot.traverse(e=>{let t=!1;e.traverseAncestors(e=>{t||this.hands.find(t=>t.object===e)&&(t=!0)}),t||(e.name.match(this.regex?new RegExp(this.hour):this.hour)&&(e.userData.initRotation||(e.userData.initRotation=e.rotation.toArray()),this.hands.push({type:"hour",object:e})),e.name.match(this.regex?new RegExp(this.minute):this.minute)&&(e.userData.initRotation||(e.userData.initRotation=e.rotation.toArray()),this.hands.push({type:"minute",object:e})),e.name.match(this.regex?new RegExp(this.second):this.second)&&(e.userData.initRotation||(e.userData.initRotation=e.rotation.toArray()),this.hands.push({type:"second",object:e})))})}};nr.PluginType="WatchHandsPlugin",sr([o(),f()],nr.prototype,"enabled",2),sr([Te(void 0,["x","y","z"].map(e=>({label:e}))),f()],nr.prototype,"axis",2),sr([o(),f()],nr.prototype,"invertAxis",2),sr([o(),f()],nr.prototype,"analog",2),sr([O(void 0,[0,12],.001),f()],nr.prototype,"hourOffset",2),sr([O(void 0,[0,60],.001),f()],nr.prototype,"minuteOffset",2),sr([O(void 0,[0,60],.001),f()],nr.prototype,"secondOffset",2),sr([De(),f()],nr.prototype,"hour",2),sr([De(),f()],nr.prototype,"minute",2),sr([De(),f()],nr.prototype,"second",2),sr([o(),B("refresh"),f()],nr.prototype,"regex",2),sr([Pe()],nr.prototype,"refresh",1),nr=sr([E("Watch Hands Time")],nr);const or=[Le,ke,He,ct,at,Ze,ft,bt,Et,rr,nr];export{rr as AdvancedGroundPlugin,Et as AnisotropyPlugin,He as BloomPlugin,We as BloomPluginPass,Ze as DepthOfFieldPlugin,$e as DepthOfFieldPluginPass,ft as OutlinePlugin,mt as OutlineRenderPass,at as SSContactShadowsPlugin,bt as SSGIPlugin,wt as SSGIPluginPass,ct as SSReflectionPlugin,dt as SSReflectionPluginPass,Ie as SSVelocityMaterial,Le as TemporalAAPlugin,Oe as TemporalAAPluginPass,ke as VelocityBufferPlugin,nr as WatchHandsPlugin,Rt as anisotropyGLTFExtension,or as webgiPlugins};
106
- //# sourceMappingURL=index.mjs.map
3198
+ `);
3199
+ }
3200
+ },
3201
+ computeCacheKey: () => {
3202
+ return this.groundMapMode + "." + this.alphaVignette + "." + this.alphaVignetteAxis;
3203
+ },
3204
+ onObjectRender: (_object, material) => {
3205
+ if (material.userData.gMapMode !== this.groundMapMode) {
3206
+ material.userData.gMapMode = this.groundMapMode;
3207
+ material.needsUpdate = true;
3208
+ }
3209
+ },
3210
+ isCompatible: (material) => {
3211
+ return material.isPhysicalMaterial;
3212
+ }
3213
+ };
3214
+ this._viewer = viewer;
3215
+ const light = new RandomizedDirectionalLight(16777215, 10, {
3216
+ near: 1.5,
3217
+ far: 20,
3218
+ bias: 0,
3219
+ frustumSize: 4,
3220
+ width: 1024,
3221
+ height: 1024,
3222
+ enabled: true,
3223
+ radius: 10,
3224
+ normalBias: 0
3225
+ }, {
3226
+ direction: new Vector3(.2, 1, .2).normalize(),
3227
+ spread: .9,
3228
+ focus: 1,
3229
+ distanceScale: 20,
3230
+ minDistanceScale: new Vector3(10, 10, 10),
3231
+ normalDirection: new Vector3(0, 1, 0)
3232
+ });
3233
+ light.shadow.camera.updateProjectionMatrix();
3234
+ light.layers.disableAll();
3235
+ light.layers.set(this._lightLayer);
3236
+ this._light = light;
3237
+ viewer.scene.addObject(this._light, { addToRoot: true });
3238
+ this._shadowMat = new FSShadowMaterial({
3239
+ color: "#ffffff",
3240
+ toneMapped: false,
3241
+ depthWrite: false,
3242
+ depthTest: false,
3243
+ premultipliedAlpha: false,
3244
+ opacity: 1,
3245
+ transparent: false,
3246
+ blending: NoBlending
3247
+ });
3248
+ this._shadowBlurMat = new ShaderMaterial2({
3249
+ uniforms: {
3250
+ "colorTexture": { value: null },
3251
+ "step": { value: .1 },
3252
+ "size": { value: new Vector2(.5, .5) },
3253
+ "direction": { value: new Vector2(.5, .5) }
3254
+ },
3255
+ vertexShader: shaderUtils.defaultVertex,
3256
+ fragmentShader: seperableShadowBlur_default
3257
+ });
3258
+ }
3259
+ dispose() {
3260
+ this._shadowMat.dispose();
3261
+ this._shadowBlurMat.dispose();
3262
+ if (this._target) this._viewer.renderManager.disposeTarget(this._target);
3263
+ this._target = void 0;
3264
+ this._light.dispose();
3265
+ this.reset();
3266
+ }
3267
+ cleanupMaterial() {
3268
+ this._updateMaterial(true);
3269
+ }
3270
+ _groundMapModeChanged() {
3271
+ if (this._attachedMesh) {
3272
+ this.cleanupMaterial();
3273
+ this._updateMaterial();
3274
+ if (this.groundMapMode === "alphaMap") this._attachedMesh.material.transparent = true;
3275
+ else this._attachedMesh.material.transparent = false;
3276
+ }
3277
+ this.reset();
3278
+ }
3279
+ _alphaVignetteChanged() {
3280
+ this.materialExtension?.setDirty?.();
3281
+ this._viewer?.setDirty();
3282
+ }
3283
+ fromJSON(data, meta, _internal = false) {
3284
+ if (!_internal) return ThreeSerialization.Deserialize(data, this, meta, false);
3285
+ else {
3286
+ ThreeSerialization.Deserialize(data, this, meta, true);
3287
+ this.reset();
3288
+ }
3289
+ return this;
3290
+ }
3291
+ reset() {
3292
+ this._frameNumber = 0;
3293
+ }
3294
+ get frameNumber() {
3295
+ return this._frameNumber;
3296
+ }
3297
+ autoUpdateShadow() {
3298
+ if (this.shadowAutoUpdate) {
3299
+ if (this._bakeCounter >= this.maxBakeCount) return false;
3300
+ if (!this.updateShadow()) return false;
3301
+ if (this._frameNumber === this.maxFrameNumber) this.dispatchEvent({
3302
+ type: "shadowBaked",
3303
+ bakeCount: ++this._bakeCounter
3304
+ });
3305
+ else if (this._frameNumber > 0 && this._frameNumber < this.maxFrameNumber) this.dispatchEvent({
3306
+ type: "shadowBaking",
3307
+ progress: this._frameNumber / this.maxFrameNumber,
3308
+ bakeCount: this._bakeCounter
3309
+ });
3310
+ return true;
3311
+ }
3312
+ return false;
3313
+ }
3314
+ updateShadow() {
3315
+ if (!this.enabled) return false;
3316
+ const mesh = this._attachedMesh;
3317
+ if (!mesh) return false;
3318
+ if (++this._frameNumber > this.maxFrameNumber) return false;
3319
+ const customSize = 1024;
3320
+ if (!this._target) this._target = this._viewer.renderManager.createTarget({
3321
+ type: UnsignedByteType,
3322
+ depthBuffer: false,
3323
+ size: new Vector2(customSize, customSize),
3324
+ sizeMultiplier: void 0,
3325
+ colorSpace: NoColorSpace,
3326
+ format: RGBAFormat
3327
+ });
3328
+ if (this._frameNumber < 3) this._light.randomizePosition(0, 1, 0);
3329
+ else this._light.randomizePosition(this._frameNumber);
3330
+ mesh.castShadow = false;
3331
+ const renderer = this._viewer.renderManager.renderer;
3332
+ const shadowMap = renderer.shadowMap;
3333
+ const shadowMapType = shadowMap.type;
3334
+ const shadowMapNeedsUpdate = shadowMap.needsUpdate;
3335
+ const shadowMapAutoUpdate = shadowMap.autoUpdate;
3336
+ shadowMap.type = this.shadowMapType;
3337
+ shadowMap.needsUpdate = true;
3338
+ shadowMap.autoUpdate = false;
3339
+ const scene = this._viewer.scene;
3340
+ const sceneLightLayer = new Layers();
3341
+ sceneLightLayer.disableAll();
3342
+ scene.traverse((o) => {
3343
+ if (o.isLight && o !== this._light) {
3344
+ o.userData.__gp_layers = o.layers;
3345
+ o.layers = sceneLightLayer;
3346
+ }
3347
+ });
3348
+ const cam = scene.mainCamera;
3349
+ if ((cam.layers.mask & 1 << this._lightLayer) !== 0) throw "Camera can render pseudo directional light, check layers";
3350
+ cam.layers.enable(this._lightLayer);
3351
+ mesh.layers.disable(this._lightLayer);
3352
+ renderer.renderWithModes({
3353
+ shadowMapRender: true,
3354
+ backgroundRender: false,
3355
+ sceneRender: false
3356
+ }, () => renderer.render(scene, scene.mainCamera));
3357
+ cam.layers.disable(this._lightLayer);
3358
+ const camLayers = cam.layers.mask;
3359
+ cam.layers.set(this._lightLayer);
3360
+ mesh.layers.enable(this._lightLayer);
3361
+ const lastThisTarget = this._viewer.renderManager.getTempTarget({
3362
+ type: UnsignedByteType,
3363
+ depthBuffer: false,
3364
+ size: new Vector2(customSize, customSize),
3365
+ colorSpace: NoColorSpace,
3366
+ format: RGBAFormat
3367
+ });
3368
+ const texture = lastThisTarget.texture;
3369
+ const lastThisTargetColorSpace = texture.colorSpace;
3370
+ texture.colorSpace = NoColorSpace;
3371
+ this._viewer.renderManager.blit(lastThisTarget, {
3372
+ clear: true,
3373
+ source: this._target.texture
3374
+ });
3375
+ {
3376
+ const currentMaterial = mesh.material;
3377
+ const currentFrustumCulled = mesh.frustumCulled;
3378
+ const currentRt = renderer.getRenderTarget();
3379
+ const activeCubeFace = renderer.getActiveCubeFace();
3380
+ const activeMipLevel = renderer.getActiveMipmapLevel();
3381
+ mesh.material = this._shadowMat;
3382
+ mesh.frustumCulled = false;
3383
+ renderer.setRenderTarget(this._target);
3384
+ this._shadowMat.opacity = Math.max(1 / this.maxFrameNumber, 1 / this._frameNumber);
3385
+ this._shadowMat.lastFrameTexture = lastThisTarget.texture;
3386
+ this._shadowMat.needsUpdate = true;
3387
+ renderer.renderWithModes({
3388
+ shadowMapRender: false,
3389
+ backgroundRender: false,
3390
+ opaqueRender: true,
3391
+ transparentRender: false,
3392
+ transmissionRender: false
3393
+ }, () => renderer.render(scene, scene.mainCamera));
3394
+ renderer.setRenderTarget(currentRt, activeCubeFace, activeMipLevel);
3395
+ mesh.frustumCulled = currentFrustumCulled;
3396
+ mesh.material = currentMaterial;
3397
+ if (this.smoothShadow) this._applySmoothFilter(this._target, lastThisTarget);
3398
+ }
3399
+ lastThisTarget.texture.colorSpace = lastThisTargetColorSpace;
3400
+ this._viewer.renderManager.releaseTempTarget(lastThisTarget);
3401
+ mesh.layers.disable(this._lightLayer);
3402
+ cam.layers.mask = camLayers;
3403
+ scene.modelObject.traverse((o) => {
3404
+ if (o.isLight && o !== this._light.lightObject) {
3405
+ o.layers = o.userData.__gp_layers;
3406
+ delete o.userData.__gp_layers;
3407
+ }
3408
+ });
3409
+ shadowMap.type = shadowMapType;
3410
+ shadowMap.needsUpdate = shadowMapNeedsUpdate;
3411
+ shadowMap.autoUpdate = shadowMapAutoUpdate;
3412
+ mesh.castShadow = true;
3413
+ if (this._frameNumber < 3 || this._frameNumber > Math.min(100, this.maxFrameNumber) && this._frameNumber % 4 === 0) {
3414
+ this._updateMaterial();
3415
+ mesh.material.setDirty();
3416
+ }
3417
+ return true;
3418
+ }
3419
+ _updateMaterial(isNull = false) {
3420
+ if (!this._attachedMesh) return;
3421
+ if (isNull) {
3422
+ if (this._attachedMesh.material.alphaMap === this._target?.texture) this._attachedMesh.material.alphaMap = null;
3423
+ if (this._attachedMesh.material.aoMap === this._target?.texture) this._attachedMesh.material.aoMap = null;
3424
+ if (this._attachedMesh.material.map === this._target?.texture) this._attachedMesh.material.map = null;
3425
+ } else if (this._target) {
3426
+ if (this.groundMapMode === "alphaMap") this._attachedMesh.material.alphaMap = this._target.texture;
3427
+ if (this.groundMapMode === "aoMap") this._attachedMesh.material.aoMap = this._target.texture;
3428
+ if (this.groundMapMode === "map") this._attachedMesh.material.map = this._target.texture;
3429
+ }
3430
+ if (this._attachedMesh.material) {
3431
+ this._attachedMesh.material.userData.ALPHA_I_RGBA_PACKING = !isNull && this.groundMapMode === "alphaMap";
3432
+ this._attachedMesh.material.alphaTest = !isNull && this.groundMapMode === "alphaMap" ? .01 : 0;
3433
+ this._attachedMesh.material.needsUpdate = true;
3434
+ }
3435
+ }
3436
+ _applySmoothFilter(shadowReadBuffer, shadowWriteBuffer) {
3437
+ this._shadowBlurMat.uniforms.colorTexture.value = shadowReadBuffer.texture;
3438
+ this._shadowBlurMat.uniforms.direction.value.set(1, 0);
3439
+ this._shadowBlurMat.uniforms.size.value.set(shadowReadBuffer.width, shadowReadBuffer.height);
3440
+ this._viewer.renderManager.blit(shadowWriteBuffer, { material: this._shadowBlurMat });
3441
+ this._shadowBlurMat.uniforms.colorTexture.value = shadowWriteBuffer.texture;
3442
+ this._shadowBlurMat.uniforms.direction.value.set(0, 1);
3443
+ this._shadowBlurMat.uniforms.size.value.set(shadowWriteBuffer.width, shadowWriteBuffer.height);
3444
+ this._viewer.renderManager.blit(shadowReadBuffer, { material: this._shadowBlurMat });
3445
+ }
3446
+ };
3447
+ __decorate([serialize("randomizedLight")], ShadowMapBaker.prototype, "_light", void 0);
3448
+ __decorate([onChange(ShadowMapBaker.prototype.reset), serialize()], ShadowMapBaker.prototype, "maxFrameNumber", void 0);
3449
+ __decorate([onChange(ShadowMapBaker.prototype.reset), serialize()], ShadowMapBaker.prototype, "smoothShadow", void 0);
3450
+ __decorate([serialize(), onChange(ShadowMapBaker.prototype.reset)], ShadowMapBaker.prototype, "shadowMapType", void 0);
3451
+ __decorate([onChange(ShadowMapBaker.prototype._groundMapModeChanged), serialize()], ShadowMapBaker.prototype, "groundMapMode", void 0);
3452
+ __decorate([serialize(), onChange(ShadowMapBaker.prototype._alphaVignetteChanged)], ShadowMapBaker.prototype, "alphaVignette", void 0);
3453
+ __decorate([serialize(), onChange(ShadowMapBaker.prototype._alphaVignetteChanged)], ShadowMapBaker.prototype, "alphaVignetteAxis", void 0);
3454
+ __decorate([serialize()], ShadowMapBaker.prototype, "maxBakeCount", void 0);
3455
+ // src/plugins/extras/AdvancedGroundPlugin.ts
3456
+ var AdvancedGroundPlugin = class extends BaseGroundPlugin {
3457
+ static {
3458
+ this.PluginType = "AdvancedGroundPlugin";
3459
+ }
3460
+ get shadowBaker() {
3461
+ return this._shadowBaker;
3462
+ }
3463
+ _refresh3() {
3464
+ this.refresh();
3465
+ }
3466
+ /**
3467
+ * bake shadows manually, to be used with {@see autoBakeShadows} set to false
3468
+ */
3469
+ bakeShadows() {
3470
+ this._shadowBaker?.reset();
3471
+ }
3472
+ constructor() {
3473
+ super();
3474
+ this.bakedShadows = true;
3475
+ this.groundReflection = false;
3476
+ this.physicalReflections = false;
3477
+ this.autoFrustumSize = true;
3478
+ this.autoBakeShadows = true;
3479
+ this.autoResetShadows = () => {
3480
+ if (this.autoBakeShadows) this._shadowBaker?.reset();
3481
+ };
3482
+ this._onSceneUpdate = this._onSceneUpdate.bind(this);
3483
+ const generatedUi = generateUiConfig(this);
3484
+ const matUI = generatedUi.find((f) => typeof f === "function");
3485
+ this.uiConfig = {
3486
+ label: "Ground",
3487
+ type: "folder",
3488
+ children: [
3489
+ ...generatedUi.filter((f) => f !== matUI),
3490
+ ...this._extraUiConfig(),
3491
+ matUI
3492
+ ]
3493
+ };
3494
+ }
3495
+ _createMesh(mesh) {
3496
+ if (mesh) throw new Error("AdvancedGroundPlugin - mesh should not be provided");
3497
+ const reflector = new Reflector2(this._geometry, () => this._reflectionTarget ??= this._viewer?.renderManager.createTarget({
3498
+ type: UnsignedByteType,
3499
+ format: RGBAFormat,
3500
+ colorSpace: NoColorSpace,
3501
+ size: {
3502
+ width: 1024,
3503
+ height: 1024
3504
+ },
3505
+ generateMipmaps: true,
3506
+ depthBuffer: true,
3507
+ minFilter: LinearMipmapLinearFilter,
3508
+ magFilter: LinearFilter
3509
+ }), 0, this._createMaterial());
3510
+ const superOnBeforeRender = reflector.onBeforeRender;
3511
+ reflector.onBeforeRender = (...params) => {
3512
+ let ssr = this._viewer?.getPluginByType("SSReflectionPlugin");
3513
+ if (ssr && ssr.isDisabled()) ssr = void 0;
3514
+ if (ssr) ssr.disable(reflector.uuid, false);
3515
+ superOnBeforeRender(...params);
3516
+ if (ssr) ssr.enable(reflector.uuid, false);
3517
+ };
3518
+ return reflector;
3519
+ }
3520
+ onAdded(viewer) {
3521
+ super.onAdded(viewer);
3522
+ }
3523
+ _postFrame() {
3524
+ super._postFrame();
3525
+ if (!this._viewer) return;
3526
+ if (!this.enabled) return;
3527
+ if (this._shadowBaker && this.bakedShadows) this._shadowBaker.autoUpdateShadow();
3528
+ }
3529
+ _preRender() {
3530
+ super._preRender();
3531
+ if (!this._viewer) return;
3532
+ this._mesh.reflectionTargetNeedsUpdate = this._viewer.renderManager.frameCount < 1;
3533
+ }
3534
+ onRemove(viewer) {
3535
+ if (this._reflectionTarget) {
3536
+ viewer.renderManager.disposeTarget(this._reflectionTarget);
3537
+ this._reflectionTarget = void 0;
3538
+ }
3539
+ super.onRemove(viewer);
3540
+ this._shadowBaker?.dispose();
3541
+ this._shadowBaker = void 0;
3542
+ }
3543
+ _removeMaterial() {
3544
+ if (!this._material) return;
3545
+ if (this._shadowBaker && this._material.groundMatExtension) {
3546
+ this._material.unregisterMaterialExtensions?.([this._shadowBaker.materialExtension]);
3547
+ delete this._material.groundMatExtension;
3548
+ }
3549
+ if (this._material.reflectorMatExtension) {
3550
+ const ext = this._mesh.materialExtension;
3551
+ if (!ext) this._viewer?.console.warn("AdavancedGroundPlugin: unable to find the extension to unregister");
3552
+ this._material.unregisterMaterialExtensions?.([ext]);
3553
+ delete this._material.reflectorMatExtension;
3554
+ }
3555
+ super._removeMaterial();
3556
+ }
3557
+ _onSceneUpdate(event) {
3558
+ super._onSceneUpdate(event);
3559
+ if (event?.object?.assetType === "widget" || event?.object?.userData?.isWidgetRoot) return;
3560
+ if (event.geometryChanged === false) return;
3561
+ this.autoResetShadows();
3562
+ }
3563
+ refresh() {
3564
+ if (!this._viewer) return;
3565
+ if (!this.isDisabled()) {
3566
+ if (this.bakedShadows && !this._shadowBaker) {
3567
+ this._shadowBaker = new ShadowMapBaker(this._viewer);
3568
+ this._shadowBaker.attachedMesh = this._mesh;
3569
+ } else if (!this.bakedShadows && this._shadowBaker) {
3570
+ this._shadowBaker.reset();
3571
+ this._shadowBaker.cleanupMaterial();
3572
+ }
3573
+ const ref = this._mesh;
3574
+ if (ref.isReflector2) {
3575
+ ref.enabled = this.groundReflection;
3576
+ ref.reflectorModePhysical = this.physicalReflections;
3577
+ }
3578
+ }
3579
+ super.refresh();
3580
+ }
3581
+ _refreshTransform() {
3582
+ if (!super._refreshTransform()) return false;
3583
+ if (this.autoFrustumSize) {
3584
+ const baker = this.shadowBaker;
3585
+ if (baker) {
3586
+ const fs = this.size / 2;
3587
+ if (fs !== baker.light.shadowParams.frustumSize) {
3588
+ baker.light.shadowParams.frustumSize = fs;
3589
+ baker.light.updateShadowParams();
3590
+ baker.reset();
3591
+ }
3592
+ }
3593
+ }
3594
+ return true;
3595
+ }
3596
+ fromJSON(data, meta) {
3597
+ if (!super.fromJSON(data, meta)) return null;
3598
+ if (data.autoFrustumSize === void 0) this.autoFrustumSize = false;
3599
+ return this;
3600
+ }
3601
+ _refreshMaterial() {
3602
+ if (!this._viewer) return false;
3603
+ super._refreshMaterial();
3604
+ if (!this._material) return;
3605
+ if (this.groundReflection && this._mesh.isReflector2 && !this._material.reflectorMatExtension) {
3606
+ const ext = this._mesh.materialExtension;
3607
+ ext.updaters = [this._viewer.scene, this._viewer.renderManager];
3608
+ this._material.registerMaterialExtensions?.([ext]);
3609
+ this._material.reflectorMatExtension = true;
3610
+ }
3611
+ if (this.bakedShadows && this._shadowBaker && !this._material.groundMatExtension) {
3612
+ this._material.registerMaterialExtensions?.([this._shadowBaker.materialExtension]);
3613
+ this._material.groundMatExtension = true;
3614
+ }
3615
+ this._material.userData.ssreflDisabled = this.groundReflection;
3616
+ this._material.userData.ssreflNonPhysical = !this.physicalReflections;
3617
+ this._material.userData.ssaoDisabled = true;
3618
+ this._material.userData.sscsDisabled = true;
3619
+ this._viewer.setDirty(this);
3620
+ }
3621
+ _extraUiConfig() {
3622
+ return [
3623
+ {
3624
+ label: "Shadow Frames",
3625
+ type: "input",
3626
+ hidden: () => !this._shadowBaker,
3627
+ stepSize: 1,
3628
+ bounds: [1, 1e3],
3629
+ property: () => [this._shadowBaker, "maxFrameNumber"]
3630
+ },
3631
+ {
3632
+ label: "Alpha Vignette",
3633
+ type: "checkbox",
3634
+ hidden: () => !this._material || (this._material.transmission || 0) < 1e-4 && !this._material.transparent,
3635
+ property: () => [this._shadowBaker, "alphaVignette"],
3636
+ limitedUi: true,
3637
+ onChange: () => this.uiConfig?.uiRefresh?.(true, "postFrame")
3638
+ },
3639
+ {
3640
+ label: "Alpha Vignette Axis",
3641
+ type: "dropdown",
3642
+ hidden: () => !this._shadowBaker?.alphaVignette || !this._material || (this._material.transmission || 0) < 1e-4 && !this._material.transparent,
3643
+ property: () => [this._shadowBaker, "alphaVignetteAxis"],
3644
+ children: [
3645
+ "x",
3646
+ "y",
3647
+ "xy"
3648
+ ].map((v) => ({
3649
+ label: v,
3650
+ value: v
3651
+ })),
3652
+ limitedUi: true
3653
+ },
3654
+ {
3655
+ label: "Shadow type",
3656
+ type: "dropdown",
3657
+ hidden: () => !this._shadowBaker,
3658
+ property: () => [this._shadowBaker, "groundMapMode"],
3659
+ children: [
3660
+ { label: "aoMap" },
3661
+ { label: "map" },
3662
+ { label: "alphaMap" }
3663
+ ],
3664
+ limitedUi: true
3665
+ },
3666
+ {
3667
+ label: "Smooth Shadow",
3668
+ type: "checkbox",
3669
+ property: () => [this._shadowBaker, "smoothShadow"]
3670
+ },
3671
+ {
3672
+ label: "Baked shadow type",
3673
+ type: "dropdown",
3674
+ children: [
3675
+ ["Basic", BasicShadowMap],
3676
+ ["PCF", PCFShadowMap],
3677
+ ["PCFSoft", PCFSoftShadowMap],
3678
+ ["VSM", VSMShadowMap]
3679
+ ].map((v) => ({
3680
+ label: v[0].toString(),
3681
+ value: v[1]
3682
+ })),
3683
+ property: () => [this._shadowBaker, "shadowMapType"]
3684
+ },
3685
+ {
3686
+ type: "folder",
3687
+ label: "Randomized Light",
3688
+ hidden: () => !this._shadowBaker,
3689
+ limitedUi: true,
3690
+ children: [
3691
+ {
3692
+ type: "color",
3693
+ label: "Color",
3694
+ property: () => [this._shadowBaker?.light, "color"]
3695
+ },
3696
+ {
3697
+ type: "slider",
3698
+ bounds: [0, 1],
3699
+ property: () => [this._shadowBaker?.light?.randomParams, "focus"],
3700
+ onChange: this.autoResetShadows
3701
+ },
3702
+ {
3703
+ type: "slider",
3704
+ bounds: [0, 1],
3705
+ property: () => [this._shadowBaker?.light?.randomParams, "spread"],
3706
+ onChange: this.autoResetShadows,
3707
+ limitedUi: true
3708
+ },
3709
+ {
3710
+ type: "slider",
3711
+ bounds: [.01, 60],
3712
+ property: () => [this._shadowBaker?.light?.randomParams, "distanceScale"],
3713
+ onChange: [this._shadowBaker?.light?.updateShadowParams, this.autoResetShadows]
3714
+ },
3715
+ {
3716
+ type: "vec3",
3717
+ bounds: [-1, 1],
3718
+ property: () => [this._shadowBaker?.light?.randomParams, "direction"],
3719
+ onChange: this.autoResetShadows,
3720
+ limitedUi: true
3721
+ },
3722
+ {
3723
+ type: "vec3",
3724
+ bounds: [-1, 1],
3725
+ property: () => [this._shadowBaker?.light?.randomParams, "normalDirection"],
3726
+ onChange: this.autoResetShadows,
3727
+ limitedUi: true
3728
+ },
3729
+ {
3730
+ type: "slider",
3731
+ bounds: [.01, 10],
3732
+ property: () => [this._shadowBaker?.light?.shadowParams, "radius"],
3733
+ onChange: [this._shadowBaker?.light?.updateShadowParams, this.autoResetShadows]
3734
+ },
3735
+ {
3736
+ type: "input",
3737
+ property: () => [this._shadowBaker?.light?.shadowParams, "frustumSize"],
3738
+ hidden: () => this.autoFrustumSize,
3739
+ onChange: [this._shadowBaker?.light?.updateShadowParams, this.autoResetShadows]
3740
+ },
3741
+ {
3742
+ type: "slider",
3743
+ bounds: [-.1, .1],
3744
+ property: () => [this._shadowBaker?.light?.shadowParams, "bias"],
3745
+ onChange: [this._shadowBaker?.light?.updateShadowParams, this.autoResetShadows]
3746
+ }
3747
+ ]
3748
+ }
3749
+ ];
3750
+ }
3751
+ };
3752
+ __decorate([
3753
+ onChange(AdvancedGroundPlugin.prototype._refresh3),
3754
+ uiToggle("Baked Shadows"),
3755
+ serialize()
3756
+ ], AdvancedGroundPlugin.prototype, "bakedShadows", void 0);
3757
+ __decorate([
3758
+ onChange(AdvancedGroundPlugin.prototype._refresh3),
3759
+ uiToggle("Planar Reflections"),
3760
+ serialize()
3761
+ ], AdvancedGroundPlugin.prototype, "groundReflection", void 0);
3762
+ __decorate([
3763
+ onChange(AdvancedGroundPlugin.prototype._refresh3),
3764
+ uiToggle("Physical Reflections"),
3765
+ serialize()
3766
+ ], AdvancedGroundPlugin.prototype, "physicalReflections", void 0);
3767
+ __decorate([
3768
+ onChange(AdvancedGroundPlugin.prototype._refresh3),
3769
+ uiToggle("Auto Shadow Frustum Size"),
3770
+ serialize()
3771
+ ], AdvancedGroundPlugin.prototype, "autoFrustumSize", void 0);
3772
+ __decorate([serialize("shadowBaker")], AdvancedGroundPlugin.prototype, "_shadowBaker", void 0);
3773
+ __decorate([bindToValue({ key: "groundReflection" })], AdvancedGroundPlugin.prototype, "planarReflections", void 0);
3774
+ // src/plugins/extras/WatchHandsPlugin.ts
3775
+ var WatchHandsPlugin = class WatchHandsPlugin extends AViewerPluginSync {
3776
+ constructor(..._args) {
3777
+ super(..._args);
3778
+ this.enabled = true;
3779
+ this.dependencies = [];
3780
+ this.axis = "y";
3781
+ this.invertAxis = false;
3782
+ this.analog = true;
3783
+ this.hourOffset = 0;
3784
+ this.minuteOffset = 0;
3785
+ this.secondOffset = 0;
3786
+ this.hour = ".*hour.*";
3787
+ this.minute = ".*minute.*";
3788
+ this.second = ".*second.*";
3789
+ this.regex = true;
3790
+ this.hands = [];
3791
+ this._lastEnabled = true;
3792
+ this._preFrame = () => {
3793
+ if (!this.enabled) {
3794
+ if (this._lastEnabled) {
3795
+ this._lastEnabled = false;
3796
+ if (!this.hands.length) return;
3797
+ for (const h of this.hands) {
3798
+ h.object.rotation.fromArray(h.object.userData.initRotation);
3799
+ h.object.updateMatrixWorld();
3800
+ }
3801
+ this._viewer?.renderManager.resetShadows();
3802
+ this._viewer?.setDirty();
3803
+ }
3804
+ return;
3805
+ }
3806
+ this._lastEnabled = true;
3807
+ if (!this.hands.length) return;
3808
+ if (this._viewer?.getPlugin("ProgressivePlugin")?.postFrameConvergedRecordingDelta() === 0) return;
3809
+ const time = /* @__PURE__ */ new Date();
3810
+ const invert = this.invertAxis ? -1 : 1;
3811
+ const secondHandRotation = invert * (time.getSeconds() + (this.analog ? time.getMilliseconds() / 1e3 : 0) - this.secondOffset) * (Math.PI * 2) / 60;
3812
+ const minuteHandRotation = invert * (time.getMinutes() - this.minuteOffset) * (Math.PI * 2) / 60 + secondHandRotation / 60;
3813
+ const targetRotation = {
3814
+ second: secondHandRotation,
3815
+ minute: minuteHandRotation,
3816
+ hour: invert * (time.getHours() - this.hourOffset) * (Math.PI * 2) / 12 + minuteHandRotation / 12
3817
+ };
3818
+ if (this.hands.some((h) => Math.abs(targetRotation[h.type] - h.object.rotation[this.axis]) > .001)) {
3819
+ for (const hand of this.hands) hand.object.rotation[this.axis] = targetRotation[hand.type];
3820
+ this._viewer?.renderManager.resetShadows();
3821
+ this._viewer?.setDirty();
3822
+ }
3823
+ };
3824
+ this._addSceneObject = async (e) => {
3825
+ if (!e.object) return;
3826
+ this.refresh();
3827
+ };
3828
+ }
3829
+ static {
3830
+ this.PluginType = "WatchHandsPlugin";
3831
+ }
3832
+ onAdded(viewer) {
3833
+ super.onAdded(viewer);
3834
+ viewer.scene.addEventListener("addSceneObject", this._addSceneObject);
3835
+ viewer.addEventListener("preFrame", this._preFrame);
3836
+ }
3837
+ onRemove(viewer) {
3838
+ viewer.scene.removeEventListener("addSceneObject", this._addSceneObject);
3839
+ viewer.removeEventListener("preFrame", this._preFrame);
3840
+ super.onRemove(viewer);
3841
+ }
3842
+ refresh() {
3843
+ this.hands = [];
3844
+ this._viewer?.scene.modelRoot.traverse((o) => {
3845
+ let isChild = false;
3846
+ o.traverseAncestors((oa) => {
3847
+ if (isChild) return;
3848
+ if (this.hands.find((h) => h.object === oa)) isChild = true;
3849
+ });
3850
+ if (isChild) return;
3851
+ if (o.name.match(this.regex ? new RegExp(this.hour) : this.hour)) {
3852
+ if (!o.userData.initRotation) o.userData.initRotation = o.rotation.toArray();
3853
+ this.hands.push({
3854
+ type: "hour",
3855
+ object: o
3856
+ });
3857
+ }
3858
+ if (o.name.match(this.regex ? new RegExp(this.minute) : this.minute)) {
3859
+ if (!o.userData.initRotation) o.userData.initRotation = o.rotation.toArray();
3860
+ this.hands.push({
3861
+ type: "minute",
3862
+ object: o
3863
+ });
3864
+ }
3865
+ if (o.name.match(this.regex ? new RegExp(this.second) : this.second)) {
3866
+ if (!o.userData.initRotation) o.userData.initRotation = o.rotation.toArray();
3867
+ this.hands.push({
3868
+ type: "second",
3869
+ object: o
3870
+ });
3871
+ }
3872
+ });
3873
+ }
3874
+ };
3875
+ __decorate([uiToggle(), serialize()], WatchHandsPlugin.prototype, "enabled", void 0);
3876
+ __decorate([uiDropdown(void 0, [
3877
+ "x",
3878
+ "y",
3879
+ "z"
3880
+ ].map((label) => ({ label }))), serialize()], WatchHandsPlugin.prototype, "axis", void 0);
3881
+ __decorate([uiToggle(), serialize()], WatchHandsPlugin.prototype, "invertAxis", void 0);
3882
+ __decorate([uiToggle(), serialize()], WatchHandsPlugin.prototype, "analog", void 0);
3883
+ __decorate([uiSlider(void 0, [0, 12], .001), serialize()], WatchHandsPlugin.prototype, "hourOffset", void 0);
3884
+ __decorate([uiSlider(void 0, [0, 60], .001), serialize()], WatchHandsPlugin.prototype, "minuteOffset", void 0);
3885
+ __decorate([uiSlider(void 0, [0, 60], .001), serialize()], WatchHandsPlugin.prototype, "secondOffset", void 0);
3886
+ __decorate([uiInput(), serialize()], WatchHandsPlugin.prototype, "hour", void 0);
3887
+ __decorate([uiInput(), serialize()], WatchHandsPlugin.prototype, "minute", void 0);
3888
+ __decorate([uiInput(), serialize()], WatchHandsPlugin.prototype, "second", void 0);
3889
+ __decorate([
3890
+ uiToggle(),
3891
+ onChange("refresh"),
3892
+ serialize()
3893
+ ], WatchHandsPlugin.prototype, "regex", void 0);
3894
+ __decorate([uiButton()], WatchHandsPlugin.prototype, "refresh", null);
3895
+ WatchHandsPlugin = __decorate([uiFolderContainer("Watch Hands Time")], WatchHandsPlugin);
3896
+ // src/plugins/index.ts
3897
+ var webgiPlugins = [
3898
+ TemporalAAPlugin,
3899
+ VelocityBufferPlugin,
3900
+ BloomPlugin,
3901
+ SSReflectionPlugin,
3902
+ SSContactShadowsPlugin,
3903
+ DepthOfFieldPlugin,
3904
+ OutlinePlugin,
3905
+ SSGIPlugin,
3906
+ AnisotropyPlugin,
3907
+ AdvancedGroundPlugin,
3908
+ WatchHandsPlugin
3909
+ ];
3910
+ export { AdvancedGroundPlugin, AnisotropyPlugin, BloomPlugin, BloomPluginPass, DepthOfFieldPlugin, DepthOfFieldPluginPass, OutlinePlugin, OutlineRenderPass, SSContactShadowsPlugin, SSGIPlugin, SSGIPluginPass, SSReflectionPlugin, SSReflectionPluginPass, SSVelocityMaterial, TemporalAAPlugin, TemporalAAPluginPass, VelocityBufferPlugin, WatchHandsPlugin, anisotropyGLTFExtension, webgiPlugins };
3911
+
3912
+ //# sourceMappingURL=index.mjs.map