clipoox-render 0.4.3 → 0.4.5

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 (191) hide show
  1. package/package.json +4 -3
  2. package/scripts/render-local.mjs +5160 -1446
  3. package/web/assets/FxEmbed-DbfuM8Yo.js +1 -0
  4. package/web/assets/MotionEmbed-CBQ-8Tzh.js +1 -0
  5. package/web/assets/PluginStore-OOEx0lP5.js +3 -0
  6. package/web/assets/ShotComposer-Cng515xa.js +287 -0
  7. package/web/assets/{ShotComposer-VixLbeMe.css → ShotComposer-deLi4grZ.css} +1 -1
  8. package/web/assets/TemplateEmbed-hjwM2b0o.js +2 -0
  9. package/web/assets/{TimelinePlugins-BYZ9y4m3.js → TimelinePlugins-D-NakABP.js} +4 -4
  10. package/web/assets/TimelineShotFx-D3kGhHN3.js +2 -0
  11. package/web/assets/TransitionEmbed-DR26yI3a.js +1 -0
  12. package/web/assets/{Whiteboard-BP_DvIAV.js → Whiteboard-BhxY0D0Z.js} +3 -3
  13. package/web/assets/aerial-BisYSXzG.js +2 -0
  14. package/web/assets/agentTools-CPFQeiDP.js +2 -0
  15. package/web/assets/aiInbetween-AOOM1e6p.js +2 -0
  16. package/web/assets/analyzerRun-Dtp2o7gT.js +1 -0
  17. package/web/assets/analyzerSandbox-BG_3Cea1.js +33 -0
  18. package/web/assets/api-BFN7blbw.js +3158 -0
  19. package/web/assets/auraTrack-D_gxHNVe.js +1 -0
  20. package/web/assets/breakthrough-0qFpZW-V.js +2 -0
  21. package/web/assets/{cameraPresets-CYw0OdM3.js → cameraPresets-eK3mP7qb.js} +1 -1
  22. package/web/assets/cameraTracker-BAQHuTV-.js +72 -0
  23. package/web/assets/captionLayout-CWPcbid-.js +1 -0
  24. package/web/assets/clientExport-DvpTTndR.js +1 -0
  25. package/web/assets/clientJobs-CIrYTMpn.js +2 -0
  26. package/web/assets/clientJobs-CuuUyhEy.js +1 -0
  27. package/web/assets/cutoutClean-CLYYAuXg.js +1 -0
  28. package/web/assets/depthEstimate-B7D7cGCl.js +1 -0
  29. package/web/assets/directorTools-CJD4Huqk.js +1 -0
  30. package/web/assets/distortFrames-BLt1icUb.js +2 -0
  31. package/web/assets/{distortGL-QalhICvi.js → distortGL-BA5molk-.js} +3 -3
  32. package/web/assets/draco_decoder-C32yEggz.wasm +0 -0
  33. package/web/assets/draco_decoder-Z1_iN-Ht.wasm +0 -0
  34. package/web/assets/draco_decoder-fzg4nYZr.js +34 -0
  35. package/web/assets/draco_wasm_wrapper-DxJM36Ib.js +117 -0
  36. package/web/assets/draco_wasm_wrapper-fZCQGLGb.js +116 -0
  37. package/web/assets/editTools-NKLsWZD1.js +1 -0
  38. package/web/assets/{engine-BedcnK45.js → engine-DioUF2mX.js} +1 -1
  39. package/web/assets/exportGlb-BOdI9cVS.js +2 -0
  40. package/web/assets/faceTracker-D7CbF-qX.js +1 -0
  41. package/web/assets/fightDirector-CYP8jxo8.js +1 -0
  42. package/web/assets/fightDrama-DIPcRKnc.js +2 -0
  43. package/web/assets/focusTool-vfabPqQ5.js +1 -0
  44. package/web/assets/{frameSink-DeM8xC8_.js → frameSink-DYs2gTzq.js} +3 -3
  45. package/web/assets/glTransitionSources.generated-DM5sRMX2.js +3695 -0
  46. package/web/assets/gltfLoader-U0Eebg7v.js +2 -0
  47. package/web/assets/{gpuCompose-CA3UmOl4.js → gpuCompose-DbnZuelB.js} +1 -1
  48. package/web/assets/gpuExport-CQ7ZhpsX.js +198 -0
  49. package/web/assets/handMatte-DIbMuqCu.js +1 -0
  50. package/web/assets/handTracker-DY_g5Xmg.js +2 -0
  51. package/web/assets/i18n-BJppIrtF.js +3 -0
  52. package/web/assets/index-BfrDwjDI.js +4247 -0
  53. package/web/assets/index-CKtv7gGE.js +9 -0
  54. package/web/assets/{index-D5oyVCRl.js → index-DxdDhmLR.js} +2 -2
  55. package/web/assets/layer-worker-DK67WH1a.js +5 -0
  56. package/web/assets/library-B6KsZUKq.js +1 -0
  57. package/web/assets/lottieLayer-C2YbiXhK.js +161 -0
  58. package/web/assets/{lottie_light_canvas-B-d7-ATe.js → lottie_light_canvas-DX9Wf-DS.js} +1 -1
  59. package/web/assets/main-B27kf5aL.css +1 -0
  60. package/web/assets/main-BKatDoGw.js +309 -0
  61. package/web/assets/mapBake-C-G7WpFM.js +1 -0
  62. package/web/assets/maskTrack-LMrwm5ub.js +1 -0
  63. package/web/assets/matteFixRun-B38CbeEt.js +1 -0
  64. package/web/assets/matteQuality-9X-jgJrH.js +1 -0
  65. package/web/assets/objectLocate-CKi3OTnL.js +1 -0
  66. package/web/assets/objectSegmenter-CziPuM61.js +1 -0
  67. package/web/assets/{objectTrack.worker-BlZkgpOX.js → objectTrack.worker-b7DJ-ub6.js} +196 -196
  68. package/web/assets/pathTracer-bqau16sX.js +2 -0
  69. package/web/assets/pendingMatte-CQb7jPg1.js +2 -0
  70. package/web/assets/personAi-CQntGDqK.js +2 -0
  71. package/web/assets/personHq-B1c0QVJT.js +2 -0
  72. package/web/assets/plateCamera-D7iLiNBy.js +1 -0
  73. package/web/assets/plateCameraMatch-BM88dx-a.js +2 -0
  74. package/web/assets/plateFollow-4iGUDTu1.js +2 -0
  75. package/web/assets/plateMatte-zTyuHHqh.js +2 -0
  76. package/web/assets/plugin-guide.en-DO_fHbzT.js +1 -0
  77. package/web/assets/plugin-guide.vi-CMJDxOhi.js +1 -0
  78. package/web/assets/pluginAutomation-DSg-sYLF.js +1 -0
  79. package/web/assets/poseTracker-DZl8l2qS.js +1 -0
  80. package/web/assets/productTools-B-jh8ukh.js +2 -0
  81. package/web/assets/remote-DJd9xWjn.js +963 -0
  82. package/web/assets/{rigTrack-urT3nDK0.js → rigTrack-XaMj1yaH.js} +1 -1
  83. package/web/assets/rotoMaskStore-DdpmT9C3.js +1 -0
  84. package/web/assets/{rotoMatte-C-2o3vv0.js → rotoMatte-i-cJTYmK.js} +1 -1
  85. package/web/assets/rotoscope-DqRSWmHR.js +1 -0
  86. package/web/assets/sceneTrack-Bbov7zET.js +1 -0
  87. package/web/assets/sceneTrack-DIPzBmMK.js +1 -0
  88. package/web/assets/{sceneTrack.worker-CT4uoTKn.js → sceneTrack.worker-Bav9h0pv.js} +180 -180
  89. package/web/assets/shot-worker-m-q77W9f.js +1 -0
  90. package/web/assets/{shotFxAgent-BFLkqs8v.js → shotFxAgent-DIMS7BGA.js} +2 -2
  91. package/web/assets/{skin-DY4QLaBI.js → skin-DrUzJE1u.js} +1 -1
  92. package/web/assets/{spark.module-DzziUgOj.js → spark.module-Y1SEI8Xz.js} +10 -10
  93. package/web/assets/spellDuel-DNnyQDVr.js +2 -0
  94. package/web/assets/store-GFMJzaWS.js +1 -0
  95. package/web/assets/surfaceLight-C--moyc9.js +1 -0
  96. package/web/assets/surfacePin-B4-1UqXD.js +2 -0
  97. package/web/assets/{textAnimators-DUZjhVGO.js → textAnimators-BVXTl8bU.js} +1 -1
  98. package/web/assets/{thumb-CS0ZuiGS.js → thumb-CTfDJgLp.js} +1 -1
  99. package/web/assets/timeline3d-Dn7PqmEe.js +2 -0
  100. package/web/assets/timeline3dExport-DCOr6ARB.js +1 -0
  101. package/web/assets/timelineComp-Dx_kED5V.js +1 -0
  102. package/web/assets/timelineOps-afzSo188.js +525 -0
  103. package/web/assets/timelineProps-eYgO6gs5.js +1 -0
  104. package/web/assets/timelineText-RKyRP988.js +1 -0
  105. package/web/assets/{titleArt-Drsrtfiv.js → titleArt-CUtA0C3I.js} +4 -4
  106. package/web/assets/{titleFrameBudget-CLZWaFHO.js → titleFrameBudget-X7HLSDre.js} +721 -704
  107. package/web/assets/titleFrames-aMG7HdVe.js +1 -0
  108. package/web/assets/{tool-DktQYmS6.js → tool-DpFjybaq.js} +1 -1
  109. package/web/assets/{tools-Co9aRDiT.js → tools-CeOU0p13.js} +1 -1
  110. package/web/assets/toonTools-DLmo37Z_.js +2 -0
  111. package/web/assets/trackAnchor-hAOtEhKO.js +1 -0
  112. package/web/assets/userFonts-1kuRjWOo.js +1 -0
  113. package/web/assets/{vfxAlpha-71tSN86T.js → vfxAlpha-DxS5-QwY.js} +2 -2
  114. package/web/assets/vfxBackground-CYpaQaTa.js +2 -0
  115. package/web/assets/videoExport-Cg4B2Nyh.js +1 -0
  116. package/web/assets/views-CUXyRb9x.js +1 -0
  117. package/web/assets/weaponDuel-nFECu9nk.js +1 -0
  118. package/web/assets/windowFrames-1wAkkWnv.js +1 -0
  119. package/web/layer-worker.html +3 -3
  120. package/web/shot-worker.html +41 -0
  121. package/web/assets/FxEmbed-BCmj9Q5C.js +0 -1
  122. package/web/assets/GLTFLoader-BHWu1lKg.js +0 -1
  123. package/web/assets/MotionEmbed-CEmbcq8Z.js +0 -1
  124. package/web/assets/PluginStore-C5hyahvG.js +0 -3
  125. package/web/assets/ShotComposer-0DUtMTVI.js +0 -287
  126. package/web/assets/TemplateEmbed-ANxSs7H5.js +0 -2
  127. package/web/assets/TimelineShotFx-q5PQwq-V.js +0 -2
  128. package/web/assets/TransitionEmbed-O6LInGWq.js +0 -1
  129. package/web/assets/aerial-CGLDKKtP.js +0 -2
  130. package/web/assets/agentTools-2Ghb80VH.js +0 -2
  131. package/web/assets/analyzerRun-DRgxrcJA.js +0 -1
  132. package/web/assets/analyzerSandbox-DuIVFnsk.js +0 -33
  133. package/web/assets/api-CJ8PdbfZ.js +0 -3168
  134. package/web/assets/auraTrack-DQw9sVU6.js +0 -1
  135. package/web/assets/breakthrough-BNj_iTDr.js +0 -2
  136. package/web/assets/captionLayout-DvDPTwO9.js +0 -1
  137. package/web/assets/clientExport-xhoXY6Dh.js +0 -1
  138. package/web/assets/depthEstimate-DEpeCojm.js +0 -1
  139. package/web/assets/directorTools-C5CpTmci.js +0 -1
  140. package/web/assets/distortFrames-Dia8O1NM.js +0 -2
  141. package/web/assets/editTools-CY_JrQfw.js +0 -1
  142. package/web/assets/exportEncode-QYsT9JBO.js +0 -1
  143. package/web/assets/exportGlb-TSj09XoV.js +0 -2
  144. package/web/assets/faceTracker-CnCWOwnJ.js +0 -1
  145. package/web/assets/fightDirector-DCI_FWTh.js +0 -1
  146. package/web/assets/fightDrama-Bg7uP_2Q.js +0 -2
  147. package/web/assets/gpuExport-D31azOQA.js +0 -198
  148. package/web/assets/handMatte-Dl-xVXFR.js +0 -1
  149. package/web/assets/handTracker-CplBsAFg.js +0 -2
  150. package/web/assets/layer-worker-DFuo32bk.js +0 -5
  151. package/web/assets/library-BufgA-Pl.js +0 -1
  152. package/web/assets/lottieLayer-DzbA3bHV.js +0 -158
  153. package/web/assets/main-Ca_CVxMz.css +0 -1
  154. package/web/assets/main-VVYiW8XD.js +0 -309
  155. package/web/assets/mapBake-BKOcEd0w.js +0 -1
  156. package/web/assets/maskTrack-CHGXtBRy.js +0 -1
  157. package/web/assets/matteFixRun-vgYrINet.js +0 -1
  158. package/web/assets/objectLocate-BJltm8Ob.js +0 -1
  159. package/web/assets/pendingMatte-BPyzzx4y.js +0 -2
  160. package/web/assets/personAi-gJu03SjU.js +0 -2
  161. package/web/assets/plateCamera-B2JvhjJw.js +0 -1
  162. package/web/assets/plateCameraMatch-ByB9nVQT.js +0 -2
  163. package/web/assets/plateFollow-C9S-l7RH.js +0 -2
  164. package/web/assets/plateMatte-J4qlNHnY.js +0 -2
  165. package/web/assets/plugin-guide.en-CGYh_9Su.js +0 -1
  166. package/web/assets/plugin-guide.vi-DMphSELb.js +0 -1
  167. package/web/assets/pluginAutomation-CkP3tA9r.js +0 -1
  168. package/web/assets/poseTracker-DGLbouqt.js +0 -1
  169. package/web/assets/productTools-CkaWF1bM.js +0 -2
  170. package/web/assets/remote-C7J0Tqhb.js +0 -1433
  171. package/web/assets/rotoMaskStore-DPziPKAN.js +0 -1
  172. package/web/assets/rotoscope-GvPFRUBg.js +0 -1
  173. package/web/assets/shot-worker-6dYkHPoL.js +0 -1
  174. package/web/assets/spellDuel-BD3m2ebA.js +0 -2
  175. package/web/assets/store-DW4E9xnW.js +0 -1
  176. package/web/assets/surfaceLight-aDSYU8Jg.js +0 -1
  177. package/web/assets/surfacePin-m83hCgGP.js +0 -2
  178. package/web/assets/timeline3d-DOw-CpZI.js +0 -2
  179. package/web/assets/timeline3dExport-BtYLU1pw.js +0 -1
  180. package/web/assets/timelineComp-B4GtoH2f.js +0 -1
  181. package/web/assets/timelineProps-D7MVutxu.js +0 -1
  182. package/web/assets/timelineText-BH09jfSM.js +0 -1
  183. package/web/assets/titleFrames-BI1DnLBn.js +0 -1
  184. package/web/assets/toonTools-CD9clJvN.js +0 -2
  185. package/web/assets/trackAnchor-sOjTtd3I.js +0 -1
  186. package/web/assets/userFonts-CwlKh9NR.js +0 -1
  187. package/web/assets/vfxBackground-Bq7lJvmZ.js +0 -2
  188. package/web/assets/videoExport-D4KbireJ.js +0 -1
  189. package/web/assets/views-ozVF4ABO.js +0 -1
  190. package/web/assets/weaponDuel-ZhX-tjGZ.js +0 -1
  191. package/web/assets/windowFrames-CpqX3kOM.js +0 -1
@@ -0,0 +1,4247 @@
1
+ import{Box3 as de,Matrix4 as $,BufferAttribute as te,Vector3 as C,Line3 as ge,Plane as br,Vector2 as Y,Triangle as Ye,BackSide as Tr,DoubleSide as wr,REVISION as Sr,Ray as Kr,FrontSide as oi,UnsignedIntType as lt,FloatType as G,DataTexture as Z,NearestFilter as N,IntType as qt,UnsignedByteType as ci,UnsignedShortType as Zr,ByteType as Di,ShortType as Jr,RGBAFormat as L,RGBAIntegerFormat as li,RGIntegerFormat as _r,RedIntegerFormat as en,RGFormat as Ar,RedFormat as Et,BufferGeometry as Ke,Matrix3 as tn,Vector4 as Ze,MeshBasicMaterial as rn,Mesh as nn,ShaderMaterial as Nt,NoBlending as Je,WebGLRenderTarget as Qe,PerspectiveCamera as Mr,DataUtils as K,HalfFloatType as ee,LinearFilter as oe,RepeatWrapping as we,ClampToEdgeWrapping as Se,Source as sn,Quaternion as an,DataArrayTexture as on,WebGLArrayRenderTarget as cn,Color as et,NoToneMapping as ln,NormalBlending as Ir,EquirectangularReflectionMapping as Ti,Spherical as un,LinearMipMapLinearFilter as fn,Clock as hn,Scene as dn,AdditiveBlending as mn,Camera as pn,SpotLight as gn,RectAreaLight as vn,PMREMGenerator as xn,MeshStandardMaterial as yn,TangentSpaceNormalMap as Ei}from"./three.module-Bx43vjkH.js";import{eK as De}from"./remote-DJd9xWjn.js";import"./index-CKtv7gGE.js";import"./i18n-BJppIrtF.js";import"./api-BFN7blbw.js";import"./titleFrameBudget-X7HLSDre.js";import"./gltfLoader-U0Eebg7v.js";import"./store-GFMJzaWS.js";import"./rotoMaskStore-DdpmT9C3.js";import"./sceneTrack-Bbov7zET.js";import"./timelineOps-afzSo188.js";import"./cameraTracker-BAQHuTV-.js";import"./textAnimators-BVXTl8bU.js";import"./timelineComp-Dx_kED5V.js";import"./rigTrack-XaMj1yaH.js";import"./clientJobs-CuuUyhEy.js";const Pr=0,bn=1,Rr=2,Bi=2,Gt=1.25,zi=1,j=32,O=j/4,wi=65535,Tn=wi<<16,Dt=Math.pow(2,-24),Si=Symbol("SKIP_GENERATION"),Fr={strategy:Pr,maxDepth:40,targetLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[Si]:!1};function z(n,e,t){return t.min.x=e[n],t.min.y=e[n+1],t.min.z=e[n+2],t.max.x=e[n+3],t.max.y=e[n+4],t.max.z=e[n+5],t}function ui(n){let e=-1,t=-1/0;for(let i=0;i<3;i++){const s=n[i+3]-n[i];s>t&&(t=s,e=i)}return e}function Ni(n,e,t){for(let i=0;i<3;i++){const s=e[n+2*i],a=e[n+2*i+1],r=s-a,c=s+a;r<t[i]&&(t[i]=r),c>t[i+3]&&(t[i+3]=c)}}function $t(n){const e=n[3]-n[0],t=n[4]-n[1],i=n[5]-n[2];return 2*(e*t+t*i+i*e)}function k(n,e){return e[n+15]===wi}function H(n,e){return e[n+6]}function q(n,e){return e[n+14]}function W(n){return n+O}function V(n,e){const t=e[n+6];return n+t*O}function kt(n,e){return e[n+7]}function Yt(n,e,t,i,s){let a=1/0,r=1/0,c=1/0,l=-1/0,h=-1/0,f=-1/0,u=1/0,o=1/0,m=1/0,g=-1/0,x=-1/0,d=-1/0;const b=n.offset||0;for(let p=(e-b)*6,v=(e+t-b)*6;p<v;p+=6){const y=n[p+0],T=n[p+1],A=y-T,w=y+T;A<a&&(a=A),w>l&&(l=w),y<u&&(u=y),y>g&&(g=y);const M=n[p+2],I=n[p+3],_=M-I,P=M+I;_<r&&(r=_),P>h&&(h=P),M<o&&(o=M),M>x&&(x=M);const S=n[p+4],R=n[p+5],F=S-R,D=S+R;F<c&&(c=F),D>f&&(f=D),S<m&&(m=S),S>d&&(d=S)}i[0]=a,i[1]=r,i[2]=c,i[3]=l,i[4]=h,i[5]=f,s[0]=u,s[1]=o,s[2]=m,s[3]=g,s[4]=x,s[5]=d}const he=8,_i=8,jt=new Int32Array(he),ue=new Float32Array(he*6),ze=new Float32Array(he*6),ne=new Float32Array(6),ft=new Float32Array(6),ye=new Int32Array(_i),ki=new Float32Array(_i*6);function wn(n,e,t,i){for(let s=0;s<3;s++){const a=e[n+2*s],r=e[n+2*s+1],c=a-r,l=a+r;c<t[i+s]&&(t[i+s]=c),l>t[i+s+3]&&(t[i+s+3]=l)}}function Oi(n,e){const t=n[e+3]-n[e],i=n[e+4]-n[e+1],s=n[e+5]-n[e+2];return 2*(t*i+i*s+s*t)}function Sn(n,e,t,i,s,a){let r=-1,c=0;if(a===Pr)r=ui(e),r!==-1&&(c=(e[r]+e[r+3])/2);else if(a===bn)r=ui(n),r!==-1&&(c=_n(t,i,s,r));else if(a===Rr){const l=$t(n);let h=Gt*s;const f=t.offset||0,u=(i-f)*6,o=(i+s-f)*6;for(let m=0;m<3;m++){const g=e[m],b=(e[m+3]-g)/he;if(s<_i){for(let p=0;p<s;p++){const v=u+p*6,y=t[v+2*m];let T=p;for(;T>0&&t[ye[T-1]+2*m]>y;)ye[T]=ye[T-1],T--;ye[T]=v}for(let p=0;p<3;p++)ne[p]=1/0,ne[p+3]=-1/0,ft[p]=1/0,ft[p+3]=-1/0;for(let p=s-1;p>=0;p--)Ni(ye[p],t,ft),ki.set(ft,p*6);for(let p=0;p<s-1;p++){Ni(ye[p],t,ne);const v=t[ye[p+1]+2*m];if(t[ye[p]+2*m]===v)continue;const y=p+1,T=s-y,A=$t(ne)/l,w=Oi(ki,y*6)/l,M=zi+Gt*(A*y+w*T);M<h&&(r=m,h=M,c=v)}}else{for(let y=0;y<he;y++){jt[y]=0;for(let T=0;T<3;T++)ue[y*6+T]=1/0,ue[y*6+T+3]=-1/0}for(let y=u;y<o;y+=6){let w=~~((t[y+2*m]-g)/b);w>=he&&(w=he-1),jt[w]++,wn(y,t,ue,w*6)}const p=(he-1)*6;for(let y=0;y<6;y++)ze[p+y]=ue[p+y];for(let y=he-2;y>=0;y--){const T=y*6,A=T+6;for(let w=0;w<3;w++)ze[T+w]=Math.min(ue[T+w],ze[A+w]),ze[T+w+3]=Math.max(ue[T+w+3],ze[A+w+3])}let v=0;for(let y=0;y<he-1;y++){const T=y*6,A=jt[y];if(A!==0)for(let P=0;P<3;P++)v===0?(ne[P]=ue[T+P],ne[P+3]=ue[T+P+3]):(ne[P]=Math.min(ne[P],ue[T+P]),ne[P+3]=Math.max(ne[P+3],ue[T+P+3]));v+=A;let w=0,M=0;v!==0&&(w=$t(ne)/l);const I=s-v;I!==0&&(M=Oi(ze,T+6)/l);const _=zi+Gt*(w*v+M*I);_<h&&(r=m,h=_,c=g+b+y*b)}}}}else console.warn(`BVH: Invalid build strategy value ${a} used.`);return{axis:r,pos:c}}function _n(n,e,t,i){let s=0;const a=n.offset;for(let r=e,c=e+t;r<c;r++)s+=n[(r-a)*6+i*2];return s/t}function An(n,e,t,i,s,a){let r=i,c=i+s-1;const l=a.pos,h=a.axis*2,f=t.offset||0;for(;;){for(;r<=c&&t[(r-f)*6+h]<l;)r++;for(;r<=c&&t[(c-f)*6+h]>=l;)c--;if(r<c){for(let u=0;u<e;u++){let o=n[r*e+u];n[r*e+u]=n[c*e+u],n[c*e+u]=o}for(let u=0;u<6;u++){const o=r-f,m=c-f,g=t[o*6+u];t[o*6+u]=t[m*6+u],t[m*6+u]=g}r++,c--}else return r}}const Mn=Math.pow(2,32),Ne=new Float32Array(6),ht=new Float32Array(6);function In(n,e,t,i,s,a){const{maxDepth:r,verbose:c,targetLeafSize:l,_strictLeafSize:h=1/0,strategy:f,onProgress:u,useSharedArrayBuffer:o=!1}=s,m=n.primitiveBuffer,g=n.primitiveBufferStride,x=o?SharedArrayBuffer:ArrayBuffer,d=new x(j*Math.max(1,2*Math.ceil(i)-1)),b=new Float32Array(d),p=new Uint32Array(d),v=new Uint16Array(d);let y=0,T=!1;return Yt(e,t,i,Ne,ht),M(t,i,0),d.slice(0,y*j);function A(I){u&&u((I-a.offset)/a.count)}function w(I,_,P){const S=I*2;p[I+6]=_,v[S+14]=P,v[S+15]=wi,A(_+P)}function M(I,_,P){const S=y++,R=S*O;b.set(Ne,R),!T&&P>=r&&(T=!0,c&&console.warn(`BVH: Max depth of ${r} reached when generating BVH. Consider increasing maxDepth.`));const F=_>h;if(_<=l&&!F||P>=r){w(R,I,_);return}const D=Sn(Ne,ht,e,I,_,f);let E=D.axis===-1?-1:An(m,g,e,I,_,D);if(D.axis===-1||E===I||E===I+_){if(!F){w(R,I,_);return}D.axis=Math.max(0,ui(Ne)),E=I+Math.max(1,Math.floor(_/2))}p[R+7]=D.axis;const le=E-I;Yt(e,I,le,Ne,ht),M(I,le,P+1);const me=y-S;if(me>Mn)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");p[R+6]=me;const xe=_-le;Yt(e,E,xe,Ne,ht),M(E,xe,P+1)}}function Pn(n,e){const t=n.getRootRanges(e.range),i=t[0],s=t[t.length-1],a={offset:i.offset,count:s.offset+s.count-i.offset},r=new Float32Array(6*a.count);r.offset=a.offset,n.computePrimitiveBounds(a.offset,a.count,r),n._roots=t.map(c=>In(n,r,c.offset,c.count,e,a))}class Ai{constructor(e){this._getNewPrimitive=e,this._primitives=[]}getPrimitive(){const e=this._primitives;return e.length===0?this._getNewPrimitive():e.pop()}releasePrimitive(e){this._primitives.push(e)}}class Rn{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=i=>{t&&e.push(t),t=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,e.length!==0&&this.setBuffer(e.pop())}}}const B=new Rn;let Te,Xe;const ke=[],dt=new Ai(()=>new de);function Fn(n,e,t,i,s,a){Te=dt.getPrimitive(),Xe=dt.getPrimitive(),ke.push(Te,Xe),B.setBuffer(n._roots[e]);const r=fi(0,n.geometry,t,i,s,a);B.clearBuffer(),dt.releasePrimitive(Te),dt.releasePrimitive(Xe),ke.pop(),ke.pop();const c=ke.length;return c>0&&(Xe=ke[c-1],Te=ke[c-2]),r}function fi(n,e,t,i,s=null,a=0,r=0){const{float32Array:c,uint16Array:l,uint32Array:h}=B;let f=n*2;if(k(f,l)){const o=H(n,h),m=q(f,l);return z(n,c,Te),i(o,m,!1,r,a+n/O,Te)}else{let _=function(S){const{uint16Array:R,uint32Array:F}=B;let D=S*2;for(;!k(D,R);)S=W(S),D=S*2;return H(S,F)},P=function(S){const{uint16Array:R,uint32Array:F}=B;let D=S*2;for(;!k(D,R);)S=V(S,F),D=S*2;return H(S,F)+q(D,R)};const o=W(n),m=V(n,h);let g=o,x=m,d,b,p,v;if(s&&(p=Te,v=Xe,z(g,c,p),z(x,c,v),d=s(p),b=s(v),b<d)){g=m,x=o;const S=d;d=b,b=S,p=v}p||(p=Te,z(g,c,p));const y=k(g*2,l),T=t(p,y,d,r+1,a+g/O);let A;if(T===Bi){const S=_(g),F=P(g)-S;A=i(S,F,!0,r+1,a+g/O,p)}else A=T&&fi(g,e,t,i,s,a,r+1);if(A)return!0;v=Xe,z(x,c,v);const w=k(x*2,l),M=t(v,w,b,r+1,a+x/O);let I;if(M===Bi){const S=_(x),F=P(x)-S;I=i(S,F,!0,r+1,a+x/O,v)}else I=M&&fi(x,e,t,i,s,a,r+1);return!!I}}const ut=new B.constructor,Bt=new B.constructor,be=new Ai(()=>new de),Oe=new de,Ue=new de,Xt=new de,Qt=new de;let Kt=!1;function Cn(n,e,t,i){if(Kt)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Kt=!0;const s=n._roots,a=e._roots;let r,c=0,l=0;const h=new $().copy(t).invert();for(let f=0,u=s.length;f<u;f++){ut.setBuffer(s[f]),l=0;const o=be.getPrimitive();z(0,ut.float32Array,o),o.applyMatrix4(h);for(let m=0,g=a.length;m<g&&(Bt.setBuffer(a[m]),r=ae(0,0,t,h,i,c,l,0,0,o),Bt.clearBuffer(),l+=a[m].byteLength/j,!r);m++);if(be.releasePrimitive(o),ut.clearBuffer(),c+=s[f].byteLength/j,r)break}return Kt=!1,r}function ae(n,e,t,i,s,a=0,r=0,c=0,l=0,h=null,f=!1){let u,o;f?(u=Bt,o=ut):(u=ut,o=Bt);const m=u.float32Array,g=u.uint32Array,x=u.uint16Array,d=o.float32Array,b=o.uint32Array,p=o.uint16Array,v=n*2,y=e*2,T=k(v,x),A=k(y,p);let w=!1;if(A&&T)f?w=s(H(e,b),q(e*2,p),H(n,g),q(n*2,x),l,r+e/O,c,a+n/O):w=s(H(n,g),q(n*2,x),H(e,b),q(e*2,p),c,a+n/O,l,r+e/O);else if(A){const M=be.getPrimitive();z(e,d,M),M.applyMatrix4(t);const I=W(n),_=V(n,g);z(I,m,Oe),z(_,m,Ue);const P=M.intersectsBox(Oe),S=M.intersectsBox(Ue);w=P&&ae(e,I,i,t,s,r,a,l,c+1,M,!f)||S&&ae(e,_,i,t,s,r,a,l,c+1,M,!f),be.releasePrimitive(M)}else{const M=W(e),I=V(e,b);z(M,d,Xt),z(I,d,Qt);const _=h.intersectsBox(Xt),P=h.intersectsBox(Qt);if(_&&P)w=ae(n,M,t,i,s,a,r,c,l+1,h,f)||ae(n,I,t,i,s,a,r,c,l+1,h,f);else if(_)if(T)w=ae(n,M,t,i,s,a,r,c,l+1,h,f);else{const S=be.getPrimitive();S.copy(Xt).applyMatrix4(t);const R=W(n),F=V(n,g);z(R,m,Oe),z(F,m,Ue);const D=S.intersectsBox(Oe),E=S.intersectsBox(Ue);w=D&&ae(M,R,i,t,s,r,a,l,c+1,S,!f)||E&&ae(M,F,i,t,s,r,a,l,c+1,S,!f),be.releasePrimitive(S)}else if(P)if(T)w=ae(n,I,t,i,s,a,r,c,l+1,h,f);else{const S=be.getPrimitive();S.copy(Qt).applyMatrix4(t);const R=W(n),F=V(n,g);z(R,m,Oe),z(F,m,Ue);const D=S.intersectsBox(Oe),E=S.intersectsBox(Ue);w=D&&ae(I,R,i,t,s,r,a,l,c+1,S,!f)||E&&ae(I,F,i,t,s,r,a,l,c+1,S,!f),be.releasePrimitive(S)}}return w}const Zt=new class{constructor(){let n=null,e=null,t=null,i=!1;this.root=null,this.buffer=null,this.uint32Array=null,this.uint16Array=null,this.setBVH=(a,r)=>{if(i)throw new Error("BVHTraversalHelper: cannot call setBVH during an active traversal.");this.root=r,this.buffer=n=a._roots[r],this.uint16Array=t=new Uint16Array(n),this.uint32Array=e=new Uint32Array(n)},this.reset=()=>{this.root=null,this.buffer=n=null,this.uint16Array=t=null,this.uint32Array=e=null},this.getRangeStart=a=>{let r=a*2;for(;!k(r,t);)a=W(a),r=a*2;return H(a,e)},this.getRangeEnd=a=>{let r=a*2;for(;!k(r,t);)a=V(a,e),r=a*2;return H(a,e)+q(r,t)};const s=(a,r,c)=>{const l=r*2,h=k(l,t);if(!a(c,h,r)&&!h){const u=W(r),o=V(r,e);s(a,u,c+1),s(a,o,c+1)}};this.traverseBuffer=a=>{if(i)throw new Error("BVHTraversalHelper: cannot start a traversal during an active traversal.");i=!0;try{s(a,0,0)}finally{i=!1}},this.traverse=a=>{this.traverseBuffer((r,c,l)=>{if(c){const h=l*2,f=e[l+6],u=t[h+14];return a(r,c,new Float32Array(n,l*4,6),f,u)}else{const h=kt(l,e);return a(r,c,new Float32Array(n,l*4,6),h)}})}}},Ui=new de,Le=new Float32Array(6);class Dn{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(e){e={...Fr,...e},"maxLeafSize"in e&&(console.warn('BVH: "maxLeafSize" option has been deprecated. Use "targetLeafSize", instead.'),e={...e,targetLeafSize:e.maxLeafSize}),Pn(this,e)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(e,t,i,s){let a=1/0,r=1/0,c=1/0,l=-1/0,h=-1/0,f=-1/0;for(let u=e,o=e+t;u<o;u++){this.writePrimitiveBounds(u,Le,0);const[m,g,x,d,b,p]=Le;m<a&&(a=m),d>l&&(l=d),g<r&&(r=g),b>h&&(h=b),x<c&&(c=x),p>f&&(f=p)}return i[s+0]=a,i[s+1]=r,i[s+2]=c,i[s+3]=l,i[s+4]=h,i[s+5]=f,i}computePrimitiveBounds(e,t,i){const s=i.offset||0;for(let a=e,r=e+t;a<r;a++){this.writePrimitiveBounds(a,Le,0);const[c,l,h,f,u,o]=Le,m=(c+f)/2,g=(l+u)/2,x=(h+o)/2,d=(f-c)/2,b=(u-l)/2,p=(o-h)/2,v=(a-s)*6;i[v+0]=m,i[v+1]=d+(Math.abs(m)+d)*Dt,i[v+2]=g,i[v+3]=b+(Math.abs(g)+b)*Dt,i[v+4]=x,i[v+5]=p+(Math.abs(x)+p)*Dt}return i}shiftPrimitiveOffsets(e){const t=this._indirectBuffer;if(t)for(let i=0,s=t.length;i<s;i++)t[i]+=e;else{const i=this._roots;for(let s=0;s<i.length;s++){const a=i[s],r=new Uint32Array(a),c=new Uint16Array(a),l=a.byteLength/j;for(let h=0;h<l;h++){const f=O*h,u=2*f;k(u,c)&&(r[f+6]+=e)}}}}traverse(e,t=0){Zt.setBVH(this,t),Zt.traverse(e),Zt.reset()}refit(){const e=this._roots;for(let t=0,i=e.length;t<i;t++){const s=e[t],a=new Uint32Array(s),r=new Uint16Array(s),c=new Float32Array(s),l=s.byteLength/j;for(let h=l-1;h>=0;h--){const f=h*O,u=f*2;if(k(u,r)){const m=H(f,a),g=q(u,r);this.writePrimitiveRangeBounds(m,g,Le,0),c.set(Le,f)}else{const m=W(f),g=V(f,a);for(let x=0;x<3;x++){const d=c[m+x],b=c[m+x+3],p=c[g+x],v=c[g+x+3];c[f+x]=d<p?d:p,c[f+x+3]=b>v?b:v}}}}}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(i=>{z(0,new Float32Array(i),Ui),e.union(Ui)}),e}shapecast(e){let{boundsTraverseOrder:t,intersectsBounds:i,intersectsRange:s,intersectsPrimitive:a,scratchPrimitive:r,iterate:c}=e;if(s&&a){const u=s;s=(o,m,g,x,d)=>u(o,m,g,x,d)?!0:c(o,m,this,a,g,x,r)}else s||(a?s=(u,o,m,g)=>c(u,o,this,a,m,g,r):s=(u,o,m)=>m);let l=!1,h=0;const f=this._roots;for(let u=0,o=f.length;u<o;u++){const m=f[u];if(l=Fn(this,u,i,s,t,h),l)break;h+=m.byteLength/j}return l}bvhcast(e,t,i){let{intersectsRanges:s}=i;return Cn(this,e,t,s)}}function En(){return typeof SharedArrayBuffer<"u"}function Ot(n){return n.index?n.index.count:n.attributes.position.count}function Ut(n){return Ot(n)/3}function Cr(n,e=ArrayBuffer){return n>65535?new Uint32Array(new e(4*n)):new Uint16Array(new e(2*n))}function Bn(n,e){if(!n.index){const t=n.attributes.position.count,i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=Cr(t,i);n.setIndex(new te(s,1));for(let a=0;a<t;a++)s[a]=a}}function zn(n,e,t){const i=Ot(n)/t,s=e||n.drawRange,a=s.start/t,r=(s.start+s.count)/t,c=Math.max(0,a),l=Math.min(i,r)-c;return{offset:Math.floor(c),count:Math.floor(l)}}function Nn(n,e){return n.groups.map(t=>({offset:t.start/e,count:t.count/e}))}function Li(n,e,t){const i=zn(n,e,t),s=Nn(n,t);if(!s.length)return[i];const a=[],r=i.offset,c=i.offset+i.count,l=Ot(n)/t,h=[];for(const o of s){const{offset:m,count:g}=o,x=m,d=isFinite(g)?g:l-m,b=m+d;x<c&&b>r&&(h.push({pos:Math.max(r,x),isStart:!0}),h.push({pos:Math.min(c,b),isStart:!1}))}h.sort((o,m)=>o.pos!==m.pos?o.pos-m.pos:o.type==="end"?-1:1);let f=0,u=null;for(const o of h){const m=o.pos;f!==0&&m!==u&&a.push({offset:u,count:m-u}),f+=o.isStart?1:-1,u=m}return a}function kn(n,e){const t=n[n.length-1],i=t.offset+t.count>2**16,s=n.reduce((h,f)=>h+f.count,0),a=i?4:2,r=e?new SharedArrayBuffer(s*a):new ArrayBuffer(s*a),c=i?new Uint32Array(r):new Uint16Array(r);let l=0;for(let h=0;h<n.length;h++){const{offset:f,count:u}=n[h];for(let o=0;o<u;o++)c[l+o]=f+o;l+=u}return c}class On extends Dn{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(e){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(e){}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("BVH: Only BufferGeometries are supported.");if(t.useSharedArrayBuffer&&!En())throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=e,this.resolvePrimitiveIndex=t.indirect?i=>this._indirectBuffer[i]:i=>i,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,t={...Fr,...t},t[Si]||this.init(t)}init(e){const{geometry:t,primitiveStride:i}=this;if(e.indirect){const s=Li(t,e.range,i),a=kn(s,e.useSharedArrayBuffer);this._indirectBuffer=a}else Bn(t,e);super.init(e),!t.boundingBox&&e.setBoundingBox&&(t.boundingBox=this.getBoundingBox(new de))}getRootRanges(e){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:Li(this.geometry,e,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class ve{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let i=1/0,s=-1/0;for(let a=0,r=e.length;a<r;a++){const l=e[a][t];i=l<i?l:i,s=l>s?l:s}this.min=i,this.max=s}setFromPoints(e,t){let i=1/0,s=-1/0;for(let a=0,r=t.length;a<r;a++){const c=t[a],l=e.dot(c);i=l<i?l:i,s=l>s?l:s}this.min=i,this.max=s}isSeparated(e){return this.min>e.max||e.min>this.max}}ve.prototype.setFromBox=(function(){const n=new C;return function(t,i){const s=i.min,a=i.max;let r=1/0,c=-1/0;for(let l=0;l<=1;l++)for(let h=0;h<=1;h++)for(let f=0;f<=1;f++){n.x=s.x*l+a.x*(1-l),n.y=s.y*h+a.y*(1-h),n.z=s.z*f+a.z*(1-f);const u=t.dot(n);r=Math.min(u,r),c=Math.max(u,c)}this.min=r,this.max=c}})();const Un=(function(){const n=new C,e=new C,t=new C;return function(s,a,r){const c=s.start,l=n,h=a.start,f=e;t.subVectors(c,h),n.subVectors(s.end,s.start),e.subVectors(a.end,a.start);const u=t.dot(f),o=f.dot(l),m=f.dot(f),g=t.dot(l),d=l.dot(l)*m-o*o;let b,p;d!==0?b=(u*o-g*m)/d:b=0,p=(u+b*o)/m,r.x=b,r.y=p}})(),Mi=(function(){const n=new Y,e=new C,t=new C;return function(s,a,r,c){Un(s,a,n);let l=n.x,h=n.y;if(l>=0&&l<=1&&h>=0&&h<=1){s.at(l,r),a.at(h,c);return}else if(l>=0&&l<=1){h<0?a.at(0,c):a.at(1,c),s.closestPointToPoint(c,!0,r);return}else if(h>=0&&h<=1){l<0?s.at(0,r):s.at(1,r),a.closestPointToPoint(r,!0,c);return}else{let f;l<0?f=s.start:f=s.end;let u;h<0?u=a.start:u=a.end;const o=e,m=t;if(s.closestPointToPoint(u,!0,e),a.closestPointToPoint(f,!0,t),o.distanceToSquared(u)<=m.distanceToSquared(f)){r.copy(o),c.copy(u);return}else{r.copy(f),c.copy(m);return}}}})(),Ln=(function(){const n=new C,e=new C,t=new br,i=new ge;return function(a,r){const{radius:c,center:l}=a,{a:h,b:f,c:u}=r;if(i.start=h,i.end=f,i.closestPointToPoint(l,!0,n).distanceTo(l)<=c||(i.start=h,i.end=u,i.closestPointToPoint(l,!0,n).distanceTo(l)<=c)||(i.start=f,i.end=u,i.closestPointToPoint(l,!0,n).distanceTo(l)<=c))return!0;const x=r.getPlane(t);if(Math.abs(x.distanceToPoint(l))<=c){const b=x.projectPoint(l,e);if(r.containsPoint(b))return!0}return!1}})(),Hn=["x","y","z"],pe=1e-15,Hi=pe*pe;function J(n){return Math.abs(n)<pe}class ce extends Ye{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new C),this.satBounds=new Array(4).fill().map(()=>new ve),this.points=[this.a,this.b,this.c],this.plane=new br,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new ge,this.needsUpdate=!0}intersectsSphere(e){return Ln(e,this)}update(){const e=this.a,t=this.b,i=this.c,s=this.points,a=this.satAxes,r=this.satBounds,c=a[0],l=r[0];this.getNormal(c),l.setFromPoints(c,s);const h=a[1],f=r[1];h.subVectors(e,t),f.setFromPoints(h,s);const u=a[2],o=r[2];u.subVectors(t,i),o.setFromPoints(u,s);const m=a[3],g=r[3];m.subVectors(i,e),g.setFromPoints(m,s);const x=h.length(),d=u.length(),b=m.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,x<pe?d<pe||b<pe?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(i)):d<pe?b<pe?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):b<pe&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(c,e),this.needsUpdate=!1}}ce.prototype.closestPointToSegment=(function(){const n=new C,e=new C,t=new ge;return function(s,a=null,r=null){this.needsUpdate&&this.update();const{start:c,end:l}=s,h=this.points;let f,u=1/0;const o=this.plane.distanceToPoint(c),m=this.plane.distanceToPoint(l);if(o*m<0&&this.plane.intersectLine(s,n)!==null&&this.containsPoint(n))return a&&a.copy(n),r&&r.copy(n),0;for(let g=0;g<3;g++){const x=(g+1)%3;t.start.copy(h[g]),t.end.copy(h[x]),Mi(t,s,n,e),f=n.distanceToSquared(e),f<u&&(u=f,a&&a.copy(n),r&&r.copy(e))}return this.closestPointToPoint(c,n),f=c.distanceToSquared(n),f<u&&(u=f,a&&a.copy(n),r&&r.copy(c)),this.closestPointToPoint(l,n),f=l.distanceToSquared(n),f<u&&(u=f,a&&a.copy(n),r&&r.copy(l)),Math.sqrt(u)}})();ce.prototype.intersectsTriangle=(function(){const n=new ce,e=new ve,t=new ve,i=new C,s=new C,a=new C,r=new C,c=new ge,l=new ge,h=new C,f=new Y,u=new Y;function o(v,y,T,A){const w=i;!v.isDegenerateIntoPoint&&!v.isDegenerateIntoSegment?w.copy(v.plane.normal):w.copy(y.plane.normal);const M=v.satBounds,I=v.satAxes;for(let S=1;S<4;S++){const R=M[S],F=I[S];if(e.setFromPoints(F,y.points),R.isSeparated(e)||(r.copy(w).cross(F),e.setFromPoints(r,v.points),t.setFromPoints(r,y.points),e.isSeparated(t)))return!1}const _=y.satBounds,P=y.satAxes;for(let S=1;S<4;S++){const R=_[S],F=P[S];if(e.setFromPoints(F,v.points),R.isSeparated(e)||(r.crossVectors(w,F),e.setFromPoints(r,v.points),t.setFromPoints(r,y.points),e.isSeparated(t)))return!1}return T&&(A||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),T.start.set(0,0,0),T.end.set(0,0,0)),!0}function m(v,y,T,A,w,M,I,_,P,S,R){let F=I/(I-_);S.x=A+(w-A)*F,R.start.subVectors(y,v).multiplyScalar(F).add(v),F=I/(I-P),S.y=A+(M-A)*F,R.end.subVectors(T,v).multiplyScalar(F).add(v)}function g(v,y,T,A,w,M,I,_,P,S,R){if(w>0)m(v.c,v.a,v.b,A,y,T,P,I,_,S,R);else if(M>0)m(v.b,v.a,v.c,T,y,A,_,I,P,S,R);else if(_*P>0||I!=0)m(v.a,v.b,v.c,y,T,A,I,_,P,S,R);else if(_!=0)m(v.b,v.a,v.c,T,y,A,_,I,P,S,R);else if(P!=0)m(v.c,v.a,v.b,A,y,T,P,I,_,S,R);else return!0;return!1}function x(v,y,T,A){const w=y.degenerateSegment,M=v.plane.distanceToPoint(w.start),I=v.plane.distanceToPoint(w.end);return J(M)?J(I)?o(v,y,T,A):(T&&(T.start.copy(w.start),T.end.copy(w.start)),v.containsPoint(w.start)):J(I)?(T&&(T.start.copy(w.end),T.end.copy(w.end)),v.containsPoint(w.end)):v.plane.intersectLine(w,i)!=null?(T&&(T.start.copy(i),T.end.copy(i)),v.containsPoint(i)):!1}function d(v,y,T){const A=y.a;return J(v.plane.distanceToPoint(A))&&v.containsPoint(A)?(T&&(T.start.copy(A),T.end.copy(A)),!0):!1}function b(v,y,T){const A=v.degenerateSegment,w=y.a;return A.closestPointToPoint(w,!0,i),w.distanceToSquared(i)<Hi?(T&&(T.start.copy(w),T.end.copy(w)),!0):!1}function p(v,y,T,A){if(v.isDegenerateIntoSegment)if(y.isDegenerateIntoSegment){const w=v.degenerateSegment,M=y.degenerateSegment,I=s,_=a;w.delta(I),M.delta(_);const P=i.subVectors(M.start,w.start),S=I.x*_.y-I.y*_.x;if(J(S))return!1;const R=(P.x*_.y-P.y*_.x)/S,F=-(I.x*P.y-I.y*P.x)/S;if(R<0||R>1||F<0||F>1)return!1;const D=w.start.z+I.z*R,E=M.start.z+_.z*F;return J(D-E)?(T&&(T.start.copy(w.start).addScaledVector(I,R),T.end.copy(w.start).addScaledVector(I,R)),!0):!1}else return y.isDegenerateIntoPoint?b(v,y,T):x(y,v,T,A);else{if(v.isDegenerateIntoPoint)return y.isDegenerateIntoPoint?y.a.distanceToSquared(v.a)<Hi?(T&&(T.start.copy(v.a),T.end.copy(v.a)),!0):!1:y.isDegenerateIntoSegment?b(y,v,T):d(y,v,T);if(y.isDegenerateIntoPoint)return d(v,y,T);if(y.isDegenerateIntoSegment)return x(v,y,T,A)}}return function(y,T=null,A=!1){this.needsUpdate&&this.update(),y.isExtendedTriangle?y.needsUpdate&&y.update():(n.copy(y),n.update(),y=n);const w=p(this,y,T,A);if(w!==void 0)return w;const M=this.plane,I=y.plane;let _=I.distanceToPoint(this.a),P=I.distanceToPoint(this.b),S=I.distanceToPoint(this.c);J(_)&&(_=0),J(P)&&(P=0),J(S)&&(S=0);const R=_*P,F=_*S;if(R>0&&F>0)return!1;let D=M.distanceToPoint(y.a),E=M.distanceToPoint(y.b),le=M.distanceToPoint(y.c);J(D)&&(D=0),J(E)&&(E=0),J(le)&&(le=0);const me=D*E,xe=D*le;if(me>0&&xe>0)return!1;s.copy(M.normal),a.copy(I.normal);const Ee=s.cross(a);let _e=0,Wt=Math.abs(Ee.x);const Ci=Math.abs(Ee.y);Ci>Wt&&(Wt=Ci,_e=1),Math.abs(Ee.z)>Wt&&(_e=2);const Be=Hn[_e],Gr=this.a[Be],$r=this.b[Be],Yr=this.c[Be],jr=y.a[Be],Xr=y.b[Be],Qr=y.c[Be];if(g(this,Gr,$r,Yr,R,F,_,P,S,f,c))return o(this,y,T,A);if(g(y,jr,Xr,Qr,me,xe,D,E,le,u,l))return o(this,y,T,A);if(f.y<f.x){const Vt=f.y;f.y=f.x,f.x=Vt,h.copy(c.start),c.start.copy(c.end),c.end.copy(h)}if(u.y<u.x){const Vt=u.y;u.y=u.x,u.x=Vt,h.copy(l.start),l.start.copy(l.end),l.end.copy(h)}return f.y<u.x||u.y<f.x?!1:(T&&(u.x>f.x?T.start.copy(l.start):T.start.copy(c.start),u.y<f.y?T.end.copy(l.end):T.end.copy(c.end)),!0)}})();ce.prototype.distanceToPoint=(function(){const n=new C;return function(t){return this.closestPointToPoint(t,n),t.distanceTo(n)}})();ce.prototype.distanceToTriangle=(function(){const n=new C,e=new C,t=["a","b","c"],i=new ge,s=new ge;return function(r,c=null,l=null){const h=c||l?i:null;if(this.intersectsTriangle(r,h,!0))return(c||l)&&(c&&h.getCenter(c),l&&h.getCenter(l)),0;let f=1/0;for(let u=0;u<3;u++){let o;const m=t[u],g=r[m];this.closestPointToPoint(g,n),o=g.distanceToSquared(n),o<f&&(f=o,c&&c.copy(n),l&&l.copy(g));const x=this[m];r.closestPointToPoint(x,n),o=x.distanceToSquared(n),o<f&&(f=o,c&&c.copy(x),l&&l.copy(n))}for(let u=0;u<3;u++){const o=t[u],m=t[(u+1)%3];i.set(this[o],this[m]);for(let g=0;g<3;g++){const x=t[g],d=t[(g+1)%3];s.set(r[x],r[d]),Mi(i,s,n,e);const b=n.distanceToSquared(e);b<f&&(f=b,c&&c.copy(n),l&&l.copy(e))}}return Math.sqrt(f)}})();class X{constructor(e,t,i){this.isOrientedBox=!0,this.min=new C,this.max=new C,this.matrix=new $,this.invMatrix=new $,this.points=new Array(8).fill().map(()=>new C),this.satAxes=new Array(3).fill().map(()=>new C),this.satBounds=new Array(3).fill().map(()=>new ve),this.alignedSatBounds=new Array(3).fill().map(()=>new ve),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),i&&this.matrix.copy(i)}set(e,t,i){this.min.copy(e),this.max.copy(t),this.matrix.copy(i),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}X.prototype.update=(function(){return function(){const e=this.matrix,t=this.min,i=this.max,s=this.points;for(let h=0;h<=1;h++)for(let f=0;f<=1;f++)for(let u=0;u<=1;u++){const o=1*h|2*f|4*u,m=s[o];m.x=h?i.x:t.x,m.y=f?i.y:t.y,m.z=u?i.z:t.z,m.applyMatrix4(e)}const a=this.satBounds,r=this.satAxes,c=s[0];for(let h=0;h<3;h++){const f=r[h],u=a[h],o=1<<h,m=s[o];f.subVectors(c,m),u.setFromPoints(f,s)}const l=this.alignedSatBounds;l[0].setFromPointsField(s,"x"),l[1].setFromPointsField(s,"y"),l[2].setFromPointsField(s,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})();X.prototype.intersectsBox=(function(){const n=new ve;return function(t){this.needsUpdate&&this.update();const i=t.min,s=t.max,a=this.satBounds,r=this.satAxes,c=this.alignedSatBounds;if(n.min=i.x,n.max=s.x,c[0].isSeparated(n)||(n.min=i.y,n.max=s.y,c[1].isSeparated(n))||(n.min=i.z,n.max=s.z,c[2].isSeparated(n)))return!1;for(let l=0;l<3;l++){const h=r[l],f=a[l];if(n.setFromBox(h,t),f.isSeparated(n))return!1}return!0}})();X.prototype.intersectsTriangle=(function(){const n=new ce,e=new Array(3),t=new ve,i=new ve,s=new C;return function(r){this.needsUpdate&&this.update(),r.isExtendedTriangle?r.needsUpdate&&r.update():(n.copy(r),n.update(),r=n);const c=this.satBounds,l=this.satAxes;e[0]=r.a,e[1]=r.b,e[2]=r.c;for(let o=0;o<3;o++){const m=c[o],g=l[o];if(t.setFromPoints(g,e),m.isSeparated(t))return!1}const h=r.satBounds,f=r.satAxes,u=this.points;for(let o=0;o<3;o++){const m=h[o],g=f[o];if(t.setFromPoints(g,u),m.isSeparated(t))return!1}for(let o=0;o<3;o++){const m=l[o];for(let g=0;g<4;g++){const x=f[g];if(s.crossVectors(m,x),t.setFromPoints(s,e),i.setFromPoints(s,u),t.isSeparated(i))return!1}}return!0}})();X.prototype.closestPointToPoint=(function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}})();X.prototype.distanceToPoint=(function(){const n=new C;return function(t){return this.closestPointToPoint(t,n),t.distanceTo(n)}})();X.prototype.distanceToBox=(function(){const n=["x","y","z"],e=new Array(12).fill().map(()=>new ge),t=new Array(12).fill().map(()=>new ge),i=new C,s=new C;return function(r,c=0,l=null,h=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(l||h)&&(r.getCenter(s),this.closestPointToPoint(s,i),r.closestPointToPoint(i,s),l&&l.copy(i),h&&h.copy(s)),0;const f=c*c,u=r.min,o=r.max,m=this.points;let g=1/0;for(let d=0;d<8;d++){const b=m[d];s.copy(b).clamp(u,o);const p=b.distanceToSquared(s);if(p<g&&(g=p,l&&l.copy(b),h&&h.copy(s),p<f))return Math.sqrt(p)}let x=0;for(let d=0;d<3;d++)for(let b=0;b<=1;b++)for(let p=0;p<=1;p++){const v=(d+1)%3,y=(d+2)%3,T=b<<v|p<<y,A=1<<d|b<<v|p<<y,w=m[T],M=m[A];e[x].set(w,M);const _=n[d],P=n[v],S=n[y],R=t[x],F=R.start,D=R.end;F[_]=u[_],F[P]=b?u[P]:o[P],F[S]=p?u[S]:o[S],D[_]=o[_],D[P]=b?u[P]:o[P],D[S]=p?u[S]:o[S],x++}for(let d=0;d<=1;d++)for(let b=0;b<=1;b++)for(let p=0;p<=1;p++){s.x=d?o.x:u.x,s.y=b?o.y:u.y,s.z=p?o.z:u.z,this.closestPointToPoint(s,i);const v=s.distanceToSquared(i);if(v<g&&(g=v,l&&l.copy(i),h&&h.copy(s),v<f))return Math.sqrt(v)}for(let d=0;d<12;d++){const b=e[d];for(let p=0;p<12;p++){const v=t[p];Mi(b,v,i,s);const y=i.distanceToSquared(s);if(y<g&&(g=y,l&&l.copy(i),h&&h.copy(s),y<f))return Math.sqrt(y)}}return Math.sqrt(g)}})();class Wn extends Ai{constructor(){super(()=>new ce)}}const ie=new Wn,it=new C,Jt=new C;function Vn(n,e,t={},i=0,s=1/0){const a=i*i,r=s*s;let c=1/0,l=null;if(n.shapecast({boundsTraverseOrder:f=>(it.copy(e).clamp(f.min,f.max),it.distanceToSquared(e)),intersectsBounds:(f,u,o)=>o<c&&o<r,intersectsTriangle:(f,u)=>{f.closestPointToPoint(e,it);const o=e.distanceToSquared(it);return o<c&&(Jt.copy(it),c=o,l=u),o<a}}),c===1/0)return null;const h=Math.sqrt(c);return t.point?t.point.copy(Jt):t.point=Jt.clone(),t.distance=h,t.faceIndex=l,t}const mt=parseInt(Sr)>=169,qn=parseInt(Sr)<=161,Ae=new C,Me=new C,Ie=new C,pt=new Y,gt=new Y,vt=new Y,Wi=new C,Vi=new C,qi=new C,rt=new C;function Gn(n,e,t,i,s,a,r,c){let l;if(a===Tr?l=n.intersectTriangle(i,t,e,!0,s):l=n.intersectTriangle(e,t,i,a!==wr,s),l===null)return null;const h=n.origin.distanceTo(s);return h<r||h>c?null:{distance:h,point:s.clone()}}function Gi(n,e,t,i,s,a,r,c,l,h,f){Ae.fromBufferAttribute(e,a),Me.fromBufferAttribute(e,r),Ie.fromBufferAttribute(e,c);const u=Gn(n,Ae,Me,Ie,rt,l,h,f);if(u){if(i){pt.fromBufferAttribute(i,a),gt.fromBufferAttribute(i,r),vt.fromBufferAttribute(i,c),u.uv=new Y;const m=Ye.getInterpolation(rt,Ae,Me,Ie,pt,gt,vt,u.uv);mt||(u.uv=m)}if(s){pt.fromBufferAttribute(s,a),gt.fromBufferAttribute(s,r),vt.fromBufferAttribute(s,c),u.uv1=new Y;const m=Ye.getInterpolation(rt,Ae,Me,Ie,pt,gt,vt,u.uv1);mt||(u.uv1=m),qn&&(u.uv2=u.uv1)}if(t){Wi.fromBufferAttribute(t,a),Vi.fromBufferAttribute(t,r),qi.fromBufferAttribute(t,c),u.normal=new C;const m=Ye.getInterpolation(rt,Ae,Me,Ie,Wi,Vi,qi,u.normal);u.normal.dot(n.direction)>0&&u.normal.multiplyScalar(-1),mt||(u.normal=m)}const o={a,b:r,c,normal:new C,materialIndex:0};if(Ye.getNormal(Ae,Me,Ie,o.normal),u.face=o,u.faceIndex=a,mt){const m=new C;Ye.getBarycoord(rt,Ae,Me,Ie,m),u.barycoord=m}}return u}function $i(n){return n&&n.isMaterial?n.side:n}function Lt(n,e,t,i,s,a,r){const c=i*3;let l=c+0,h=c+1,f=c+2;const{index:u,groups:o}=n;n.index&&(l=u.getX(l),h=u.getX(h),f=u.getX(f));const{position:m,normal:g,uv:x,uv1:d}=n.attributes;if(Array.isArray(e)){const b=i*3;for(let p=0,v=o.length;p<v;p++){const{start:y,count:T,materialIndex:A}=o[p];if(b>=y&&b<y+T){const w=$i(e[A]),M=Gi(t,m,g,x,d,l,h,f,w,a,r);if(M)if(M.faceIndex=i,M.face.materialIndex=A,s)s.push(M);else return M}}}else{const b=$i(e),p=Gi(t,m,g,x,d,l,h,f,b,a,r);if(p)if(p.faceIndex=i,p.face.materialIndex=0,s)s.push(p);else return p}return null}function U(n,e,t,i){const s=n.a,a=n.b,r=n.c;let c=e,l=e+1,h=e+2;t&&(c=t.getX(c),l=t.getX(l),h=t.getX(h)),s.x=i.getX(c),s.y=i.getY(c),s.z=i.getZ(c),a.x=i.getX(l),a.y=i.getY(l),a.z=i.getZ(l),r.x=i.getX(h),r.y=i.getY(h),r.z=i.getZ(h)}function $n(n,e,t,i,s,a,r,c){const{geometry:l,_indirectBuffer:h}=n;for(let f=i,u=i+s;f<u;f++)Lt(l,e,t,f,a,r,c)}function Yn(n,e,t,i,s,a,r){const{geometry:c,_indirectBuffer:l}=n;let h=1/0,f=null;for(let u=i,o=i+s;u<o;u++){let m;m=Lt(c,e,t,u,null,a,r),m&&m.distance<h&&(f=m,h=m.distance)}return f}function jn(n,e,t,i,s,a,r){const{geometry:c}=t,{index:l}=c,h=c.attributes.position;for(let f=n,u=e+n;f<u;f++){let o;if(o=f,U(r,o*3,l,h),r.needsUpdate=!0,i(r,o,s,a))return!0}return!1}function Xn(n,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=n.geometry,i=t.index?t.index.array:null,s=t.attributes.position;let a,r,c,l,h=0;const f=n._roots;for(let o=0,m=f.length;o<m;o++)a=f[o],r=new Uint32Array(a),c=new Uint16Array(a),l=new Float32Array(a),u(0,h),h+=a.byteLength;function u(o,m,g=!1){const x=o*2;if(k(x,c)){const d=H(o,r),b=q(x,c);let p=1/0,v=1/0,y=1/0,T=-1/0,A=-1/0,w=-1/0;for(let M=3*d,I=3*(d+b);M<I;M++){let _=i[M];const P=s.getX(_),S=s.getY(_),R=s.getZ(_);P<p&&(p=P),P>T&&(T=P),S<v&&(v=S),S>A&&(A=S),R<y&&(y=R),R>w&&(w=R)}return l[o+0]!==p||l[o+1]!==v||l[o+2]!==y||l[o+3]!==T||l[o+4]!==A||l[o+5]!==w?(l[o+0]=p,l[o+1]=v,l[o+2]=y,l[o+3]=T,l[o+4]=A,l[o+5]=w,!0):!1}else{const d=W(o),b=V(o,r);let p=g,v=!1,y=!1;if(e){if(!p){const _=d/O+m/j,P=b/O+m/j;v=e.has(_),y=e.has(P),p=!v&&!y}}else v=!0,y=!0;const T=p||v,A=p||y;let w=!1;T&&(w=u(d,m,p));let M=!1;A&&(M=u(b,m,p));const I=w||M;if(I)for(let _=0;_<3;_++){const P=d+_,S=b+_,R=l[P],F=l[P+3],D=l[S],E=l[S+3];l[o+_]=R<D?R:D,l[o+_+3]=F>E?F:E}return I}}}function re(n,e,t,i,s){let a,r,c,l,h,f;const u=1/t.direction.x,o=1/t.direction.y,m=1/t.direction.z,g=t.origin.x,x=t.origin.y,d=t.origin.z;let b=e[n],p=e[n+3],v=e[n+1],y=e[n+3+1],T=e[n+2],A=e[n+3+2];return u>=0?(a=(b-g)*u,r=(p-g)*u):(a=(p-g)*u,r=(b-g)*u),o>=0?(c=(v-x)*o,l=(y-x)*o):(c=(y-x)*o,l=(v-x)*o),a>l||c>r||((c>a||isNaN(a))&&(a=c),(l<r||isNaN(r))&&(r=l),m>=0?(h=(T-d)*m,f=(A-d)*m):(h=(A-d)*m,f=(T-d)*m),a>f||h>r)?!1:((h>a||a!==a)&&(a=h),(f<r||r!==r)&&(r=f),a<=s&&r>=i)}function Qn(n,e,t,i,s,a,r,c){const{geometry:l,_indirectBuffer:h}=n;for(let f=i,u=i+s;f<u;f++){let o=h?h[f]:f;Lt(l,e,t,o,a,r,c)}}function Kn(n,e,t,i,s,a,r){const{geometry:c,_indirectBuffer:l}=n;let h=1/0,f=null;for(let u=i,o=i+s;u<o;u++){let m;m=Lt(c,e,t,l?l[u]:u,null,a,r),m&&m.distance<h&&(f=m,h=m.distance)}return f}function Zn(n,e,t,i,s,a,r){const{geometry:c}=t,{index:l}=c,h=c.attributes.position;for(let f=n,u=e+n;f<u;f++){let o;if(o=t.resolveTriangleIndex(f),U(r,o*3,l,h),r.needsUpdate=!0,i(r,o,s,a))return!0}return!1}function Jn(n,e,t,i,s,a,r){B.setBuffer(n._roots[e]),re(0,B.float32Array,i,a,r)&&hi(0,n,t,i,s,a,r),B.clearBuffer()}function hi(n,e,t,i,s,a,r){const{float32Array:c,uint16Array:l,uint32Array:h}=B,f=n*2;if(k(f,l)){const o=H(n,h),m=q(f,l);$n(e,t,i,o,m,s,a,r)}else{const o=W(n);re(o,c,i,a,r)&&hi(o,e,t,i,s,a,r);const m=V(n,h);re(m,c,i,a,r)&&hi(m,e,t,i,s,a,r)}}const es=["x","y","z"];function ts(n,e,t,i,s,a){B.setBuffer(n._roots[e]);let r=null;return re(0,B.float32Array,i,s,a)&&(r=di(0,n,t,i,s,a)),B.clearBuffer(),r}function di(n,e,t,i,s,a){const{float32Array:r,uint16Array:c,uint32Array:l}=B;let h=n*2;if(k(h,c)){const u=H(n,l),o=q(h,c);return Yn(e,t,i,u,o,s,a)}else{const u=kt(n,l),o=es[u],g=i.direction[o]>=0;let x,d;g?(x=W(n),d=V(n,l)):(x=V(n,l),d=W(n));const p=re(x,r,i,s,a)?di(x,e,t,i,s,a):null;if(p){const T=p.point[o];if(g?T<=r[d+u]:T>=r[d+u+3])return p}const y=re(d,r,i,s,a)?di(d,e,t,i,s,a):null;return p&&y?p.distance<=y.distance?p:y:p||y||null}}const xt=new de,He=new ce,We=new ce,nt=new $,Yi=new X,yt=new X;function is(n,e,t,i){B.setBuffer(n._roots[e]);const s=mi(0,n,t,i);return B.clearBuffer(),s}function mi(n,e,t,i,s=null){const{float32Array:a,uint16Array:r,uint32Array:c}=B;let l=n*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),Yi.set(t.boundingBox.min,t.boundingBox.max,i),s=Yi),k(l,r)){const f=e.geometry,u=f.index,o=f.attributes.position,m=t.index,g=t.attributes.position,x=H(n,c),d=q(l,r);if(nt.copy(i).invert(),t.boundsTree)return z(n,a,yt),yt.matrix.copy(nt),yt.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:p=>yt.intersectsBox(p),intersectsTriangle:p=>{p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let v=x*3,y=(d+x)*3;v<y;v+=3)if(U(We,v,u,o),We.needsUpdate=!0,p.intersectsTriangle(We))return!0;return!1}});{const b=Ut(t);for(let p=x*3,v=(d+x)*3;p<v;p+=3){U(He,p,u,o),He.a.applyMatrix4(nt),He.b.applyMatrix4(nt),He.c.applyMatrix4(nt),He.needsUpdate=!0;for(let y=0,T=b*3;y<T;y+=3)if(U(We,y,m,g),We.needsUpdate=!0,He.intersectsTriangle(We))return!0}}}else{const f=W(n),u=V(n,c);return z(f,a,xt),!!(s.intersectsBox(xt)&&mi(f,e,t,i,s)||(z(u,a,xt),s.intersectsBox(xt)&&mi(u,e,t,i,s)))}}const bt=new $,ei=new X,st=new X,rs=new C,ns=new C,ss=new C,as=new C;function os(n,e,t,i={},s={},a=0,r=1/0){e.boundingBox||e.computeBoundingBox(),ei.set(e.boundingBox.min,e.boundingBox.max,t),ei.needsUpdate=!0;const c=n.geometry,l=c.attributes.position,h=c.index,f=e.attributes.position,u=e.index,o=ie.getPrimitive(),m=ie.getPrimitive();let g=rs,x=ns,d=null,b=null;s&&(d=ss,b=as);let p=1/0,v=null,y=null;return bt.copy(t).invert(),st.matrix.copy(bt),n.shapecast({boundsTraverseOrder:T=>ei.distanceToBox(T),intersectsBounds:(T,A,w)=>w<p&&w<r?(A&&(st.min.copy(T.min),st.max.copy(T.max),st.needsUpdate=!0),!0):!1,intersectsRange:(T,A)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:M=>st.distanceToBox(M),intersectsBounds:(M,I,_)=>_<p&&_<r,intersectsRange:(M,I)=>{for(let _=M,P=M+I;_<P;_++){U(m,3*_,u,f),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let S=T,R=T+A;S<R;S++){U(o,3*S,h,l),o.needsUpdate=!0;const F=o.distanceToTriangle(m,g,d);if(F<p&&(x.copy(g),b&&b.copy(d),p=F,v=S,y=_),F<a)return!0}}}});{const w=Ut(e);for(let M=0,I=w;M<I;M++){U(m,3*M,u,f),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let _=T,P=T+A;_<P;_++){U(o,3*_,h,l),o.needsUpdate=!0;const S=o.distanceToTriangle(m,g,d);if(S<p&&(x.copy(g),b&&b.copy(d),p=S,v=_,y=M),S<a)return!0}}}}}),ie.releasePrimitive(o),ie.releasePrimitive(m),p===1/0?null:(i.point?i.point.copy(x):i.point=x.clone(),i.distance=p,i.faceIndex=v,s&&(s.point?s.point.copy(b):s.point=b.clone(),s.point.applyMatrix4(bt),x.applyMatrix4(bt),s.distance=x.sub(s.point).length(),s.faceIndex=y),i)}function cs(n,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=n.geometry,i=t.index?t.index.array:null,s=t.attributes.position;let a,r,c,l,h=0;const f=n._roots;for(let o=0,m=f.length;o<m;o++)a=f[o],r=new Uint32Array(a),c=new Uint16Array(a),l=new Float32Array(a),u(0,h),h+=a.byteLength;function u(o,m,g=!1){const x=o*2;if(k(x,c)){const d=H(o,r),b=q(x,c);let p=1/0,v=1/0,y=1/0,T=-1/0,A=-1/0,w=-1/0;for(let M=d,I=d+b;M<I;M++){const _=3*n.resolveTriangleIndex(M);for(let P=0;P<3;P++){let S=_+P;S=i?i[S]:S;const R=s.getX(S),F=s.getY(S),D=s.getZ(S);R<p&&(p=R),R>T&&(T=R),F<v&&(v=F),F>A&&(A=F),D<y&&(y=D),D>w&&(w=D)}}return l[o+0]!==p||l[o+1]!==v||l[o+2]!==y||l[o+3]!==T||l[o+4]!==A||l[o+5]!==w?(l[o+0]=p,l[o+1]=v,l[o+2]=y,l[o+3]=T,l[o+4]=A,l[o+5]=w,!0):!1}else{const d=W(o),b=V(o,r);let p=g,v=!1,y=!1;if(e){if(!p){const _=d/O+m/j,P=b/O+m/j;v=e.has(_),y=e.has(P),p=!v&&!y}}else v=!0,y=!0;const T=p||v,A=p||y;let w=!1;T&&(w=u(d,m,p));let M=!1;A&&(M=u(b,m,p));const I=w||M;if(I)for(let _=0;_<3;_++){const P=d+_,S=b+_,R=l[P],F=l[P+3],D=l[S],E=l[S+3];l[o+_]=R<D?R:D,l[o+_+3]=F>E?F:E}return I}}}function ls(n,e,t,i,s,a,r){B.setBuffer(n._roots[e]),re(0,B.float32Array,i,a,r)&&pi(0,n,t,i,s,a,r),B.clearBuffer()}function pi(n,e,t,i,s,a,r){const{float32Array:c,uint16Array:l,uint32Array:h}=B,f=n*2;if(k(f,l)){const o=H(n,h),m=q(f,l);Qn(e,t,i,o,m,s,a,r)}else{const o=W(n);re(o,c,i,a,r)&&pi(o,e,t,i,s,a,r);const m=V(n,h);re(m,c,i,a,r)&&pi(m,e,t,i,s,a,r)}}const us=["x","y","z"];function fs(n,e,t,i,s,a){B.setBuffer(n._roots[e]);let r=null;return re(0,B.float32Array,i,s,a)&&(r=gi(0,n,t,i,s,a)),B.clearBuffer(),r}function gi(n,e,t,i,s,a){const{float32Array:r,uint16Array:c,uint32Array:l}=B;let h=n*2;if(k(h,c)){const u=H(n,l),o=q(h,c);return Kn(e,t,i,u,o,s,a)}else{const u=kt(n,l),o=us[u],g=i.direction[o]>=0;let x,d;g?(x=W(n),d=V(n,l)):(x=V(n,l),d=W(n));const p=re(x,r,i,s,a)?gi(x,e,t,i,s,a):null;if(p){const T=p.point[o];if(g?T<=r[d+u]:T>=r[d+u+3])return p}const y=re(d,r,i,s,a)?gi(d,e,t,i,s,a):null;return p&&y?p.distance<=y.distance?p:y:p||y||null}}const Tt=new de,Ve=new ce,qe=new ce,at=new $,ji=new X,wt=new X;function hs(n,e,t,i){B.setBuffer(n._roots[e]);const s=vi(0,n,t,i);return B.clearBuffer(),s}function vi(n,e,t,i,s=null){const{float32Array:a,uint16Array:r,uint32Array:c}=B;let l=n*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),ji.set(t.boundingBox.min,t.boundingBox.max,i),s=ji),k(l,r)){const f=e.geometry,u=f.index,o=f.attributes.position,m=t.index,g=t.attributes.position,x=H(n,c),d=q(l,r);if(at.copy(i).invert(),t.boundsTree)return z(n,a,wt),wt.matrix.copy(at),wt.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:p=>wt.intersectsBox(p),intersectsTriangle:p=>{p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let v=x,y=d+x;v<y;v++)if(U(qe,3*e.resolveTriangleIndex(v),u,o),qe.needsUpdate=!0,p.intersectsTriangle(qe))return!0;return!1}});{const b=Ut(t);for(let p=x,v=d+x;p<v;p++){const y=e.resolveTriangleIndex(p);U(Ve,3*y,u,o),Ve.a.applyMatrix4(at),Ve.b.applyMatrix4(at),Ve.c.applyMatrix4(at),Ve.needsUpdate=!0;for(let T=0,A=b*3;T<A;T+=3)if(U(qe,T,m,g),qe.needsUpdate=!0,Ve.intersectsTriangle(qe))return!0}}}else{const f=W(n),u=V(n,c);return z(f,a,Tt),!!(s.intersectsBox(Tt)&&vi(f,e,t,i,s)||(z(u,a,Tt),s.intersectsBox(Tt)&&vi(u,e,t,i,s)))}}const St=new $,ti=new X,ot=new X,ds=new C,ms=new C,ps=new C,gs=new C;function vs(n,e,t,i={},s={},a=0,r=1/0){e.boundingBox||e.computeBoundingBox(),ti.set(e.boundingBox.min,e.boundingBox.max,t),ti.needsUpdate=!0;const c=n.geometry,l=c.attributes.position,h=c.index,f=e.attributes.position,u=e.index,o=ie.getPrimitive(),m=ie.getPrimitive();let g=ds,x=ms,d=null,b=null;s&&(d=ps,b=gs);let p=1/0,v=null,y=null;return St.copy(t).invert(),ot.matrix.copy(St),n.shapecast({boundsTraverseOrder:T=>ti.distanceToBox(T),intersectsBounds:(T,A,w)=>w<p&&w<r?(A&&(ot.min.copy(T.min),ot.max.copy(T.max),ot.needsUpdate=!0),!0):!1,intersectsRange:(T,A)=>{if(e.boundsTree){const w=e.boundsTree;return w.shapecast({boundsTraverseOrder:M=>ot.distanceToBox(M),intersectsBounds:(M,I,_)=>_<p&&_<r,intersectsRange:(M,I)=>{for(let _=M,P=M+I;_<P;_++){const S=w.resolveTriangleIndex(_);U(m,3*S,u,f),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let R=T,F=T+A;R<F;R++){const D=n.resolveTriangleIndex(R);U(o,3*D,h,l),o.needsUpdate=!0;const E=o.distanceToTriangle(m,g,d);if(E<p&&(x.copy(g),b&&b.copy(d),p=E,v=R,y=_),E<a)return!0}}}})}else{const w=Ut(e);for(let M=0,I=w;M<I;M++){U(m,3*M,u,f),m.a.applyMatrix4(t),m.b.applyMatrix4(t),m.c.applyMatrix4(t),m.needsUpdate=!0;for(let _=T,P=T+A;_<P;_++){const S=n.resolveTriangleIndex(_);U(o,3*S,h,l),o.needsUpdate=!0;const R=o.distanceToTriangle(m,g,d);if(R<p&&(x.copy(g),b&&b.copy(d),p=R,v=_,y=M),R<a)return!0}}}}}),ie.releasePrimitive(o),ie.releasePrimitive(m),p===1/0?null:(i.point?i.point.copy(x):i.point=x.clone(),i.distance=p,i.faceIndex=v,s&&(s.point?s.point.copy(b):s.point=b.clone(),s.point.applyMatrix4(St),x.applyMatrix4(St),s.distance=x.sub(s.point).length(),s.faceIndex=y),i)}function Xi(n,e,t){return n===null?null:(n.point.applyMatrix4(e.matrixWorld),n.distance=n.point.distanceTo(t.ray.origin),n.object=e,n)}const _t=new X,At=new Kr,Qi=new C,Ki=new $,Zi=new C,ii=["getX","getY","getZ"];class zt extends On{static serialize(e,t={}){t={cloneBuffers:!0,...t};const i=e.geometry,s=e._roots,a=e._indirectBuffer,r=i.getIndex(),c={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(c.roots=s.map(l=>l.slice()),c.index=r?r.array.slice():null,c.indirectBuffer=a?a.slice():null):(c.roots=s,c.index=r?r.array:null,c.indirectBuffer=a),c}static deserialize(e,t,i={}){i={setIndex:!0,indirect:!!e.indirectBuffer,...i};const{index:s,roots:a,indirectBuffer:r}=e;e.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),l(a));const c=new zt(t,{...i,[Si]:!0});if(c._roots=a,c._indirectBuffer=r||null,i.setIndex){const h=t.getIndex();if(h===null){const f=new te(e.index,1,!1);t.setIndex(f)}else h.array!==s&&(h.array.set(s),h.needsUpdate=!0)}return c;function l(h){for(let f=0;f<h.length;f++){const u=h[f],o=new Uint32Array(u),m=new Uint16Array(u);for(let g=0,x=u.byteLength/j;g<x;g++){const d=O*g,b=2*d;k(b,m)||(o[d+6]=o[d+6]/O-g)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(e,t={}){t.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use "targetLeafSize", instead.'),t={...t,targetLeafSize:t.maxLeafTris}),super(e,t)}shiftTriangleOffsets(e){return super.shiftPrimitiveOffsets(e)}writePrimitiveBounds(e,t,i){const s=this.geometry,a=this._indirectBuffer,r=s.attributes.position,c=s.index?s.index.array:null,h=(a?a[e]:e)*3;let f=h+0,u=h+1,o=h+2;c&&(f=c[f],u=c[u],o=c[o]);for(let m=0;m<3;m++){const g=r[ii[m]](f),x=r[ii[m]](u),d=r[ii[m]](o);let b=g;x<b&&(b=x),d<b&&(b=d);let p=g;x>p&&(p=x),d>p&&(p=d),t[i+m]=b,t[i+m+3]=p}return t}computePrimitiveBounds(e,t,i){const s=this.geometry,a=this._indirectBuffer,r=s.attributes.position,c=s.index?s.index.array:null,l=r.normalized;if(e<0||t+e-i.offset>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const h=r.array,f=r.offset||0;let u=3;r.isInterleavedBufferAttribute&&(u=r.data.stride);const o=["getX","getY","getZ"],m=i.offset;for(let g=e,x=e+t;g<x;g++){const b=(a?a[g]:g)*3,p=(g-m)*6;let v=b+0,y=b+1,T=b+2;c&&(v=c[v],y=c[y],T=c[T]),l||(v=v*u+f,y=y*u+f,T=T*u+f);for(let A=0;A<3;A++){let w,M,I;l?(w=r[o[A]](v),M=r[o[A]](y),I=r[o[A]](T)):(w=h[v+A],M=h[y+A],I=h[T+A]);let _=w;M<_&&(_=M),I<_&&(_=I);let P=w;M>P&&(P=M),I>P&&(P=I);const S=(P-_)/2,R=A*2;i[p+R+0]=_+S,i[p+R+1]=S+(Math.abs(_)+S)*Dt}}return i}raycastObject3D(e,t,i=[]){const{material:s}=e;if(s===void 0)return;Ki.copy(e.matrixWorld).invert(),At.copy(t.ray).applyMatrix4(Ki),Zi.setFromMatrixScale(e.matrixWorld),Qi.copy(At.direction).multiply(Zi);const a=Qi.length(),r=t.near/a,c=t.far/a;if(t.firstHitOnly===!0){let l=this.raycastFirst(At,s,r,c);l=Xi(l,e,t),l&&i.push(l)}else{const l=this.raycast(At,s,r,c);for(let h=0,f=l.length;h<f;h++){const u=Xi(l[h],e,t);u&&i.push(u)}}return i}refit(e=null){return(this.indirect?cs:Xn)(this,e)}raycast(e,t=oi,i=0,s=1/0){const a=this._roots,r=[],c=this.indirect?ls:Jn;for(let l=0,h=a.length;l<h;l++)c(this,l,t,e,r,i,s);return r}raycastFirst(e,t=oi,i=0,s=1/0){const a=this._roots;let r=null;const c=this.indirect?fs:ts;for(let l=0,h=a.length;l<h;l++){const f=c(this,l,t,e,i,s);f!=null&&(r==null||f.distance<r.distance)&&(r=f)}return r}intersectsGeometry(e,t){let i=!1;const s=this._roots,a=this.indirect?hs:is;for(let r=0,c=s.length;r<c&&(i=a(this,r,e,t),!i);r++);return i}shapecast(e){const t=ie.getPrimitive(),i=super.shapecast({...e,intersectsPrimitive:e.intersectsTriangle,scratchPrimitive:t,iterate:this.indirect?Zn:jn});return ie.releasePrimitive(t),i}bvhcast(e,t,i){let{intersectsRanges:s,intersectsTriangles:a}=i;const r=ie.getPrimitive(),c=this.geometry.index,l=this.geometry.attributes.position,h=this.indirect?g=>{const x=this.resolveTriangleIndex(g);U(r,x*3,c,l)}:g=>{U(r,g*3,c,l)},f=ie.getPrimitive(),u=e.geometry.index,o=e.geometry.attributes.position,m=e.indirect?g=>{const x=e.resolveTriangleIndex(g);U(f,x*3,u,o)}:g=>{U(f,g*3,u,o)};if(a){if(!(e instanceof zt))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const g=(x,d,b,p,v,y,T,A)=>{for(let w=b,M=b+p;w<M;w++){m(w),f.a.applyMatrix4(t),f.b.applyMatrix4(t),f.c.applyMatrix4(t),f.needsUpdate=!0;for(let I=x,_=x+d;I<_;I++)if(h(I),r.needsUpdate=!0,a(r,f,I,w,v,y,T,A))return!0}return!1};if(s){const x=s;s=function(d,b,p,v,y,T,A,w){return x(d,b,p,v,y,T,A,w)?!0:g(d,b,p,v,y,T,A,w)}}else s=g}return super.bvhcast(e,t,{intersectsRanges:s})}intersectsBox(e,t){return _t.set(e.min,e.max,t),_t.needsUpdate=!0,this.shapecast({intersectsBounds:i=>_t.intersectsBox(i),intersectsTriangle:i=>_t.intersectsTriangle(i)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,i={},s={},a=0,r=1/0){return(this.indirect?vs:os)(this,e,t,i,s,a,r)}closestPointToPoint(e,t={},i=0,s=1/0){return Vn(this,e,t,i,s)}}function xs(n){switch(n){case 1:return"R";case 2:return"RG";case 3:return"RGBA";case 4:return"RGBA"}throw new Error}function ys(n){switch(n){case 1:return Et;case 2:return Ar;case 3:return L;case 4:return L}}function Ji(n){switch(n){case 1:return en;case 2:return _r;case 3:return li;case 4:return li}}class Dr extends Z{constructor(){super(),this.minFilter=N,this.magFilter=N,this.generateMipmaps=!1,this.overrideItemSize=null,this._forcedType=null}updateFrom(e){const t=this.overrideItemSize,i=e.itemSize,s=e.count;if(t!==null){if(i*s%t!==0)throw new Error("VertexAttributeTexture: overrideItemSize must divide evenly into buffer length.");e.itemSize=t,e.count=s*i/t}const a=e.itemSize,r=e.count,c=e.normalized,l=e.array.constructor,h=l.BYTES_PER_ELEMENT;let f=this._forcedType,u=a;if(f===null)switch(l){case Float32Array:f=G;break;case Uint8Array:case Uint16Array:case Uint32Array:f=lt;break;case Int8Array:case Int16Array:case Int32Array:f=qt;break}let o,m,g,x,d=xs(a);switch(f){case G:g=1,m=ys(a),c&&h===1?(x=l,d+="8",l===Uint8Array?o=ci:(o=Di,d+="_SNORM")):(x=Float32Array,d+="32F",o=G);break;case qt:d+=h*8+"I",g=c?Math.pow(2,l.BYTES_PER_ELEMENT*8-1):1,m=Ji(a),h===1?(x=Int8Array,o=Di):h===2?(x=Int16Array,o=Jr):(x=Int32Array,o=qt);break;case lt:d+=h*8+"UI",g=c?Math.pow(2,l.BYTES_PER_ELEMENT*8-1):1,m=Ji(a),h===1?(x=Uint8Array,o=ci):h===2?(x=Uint16Array,o=Zr):(x=Uint32Array,o=lt);break}u===3&&(m===L||m===li)&&(u=4);const b=Math.ceil(Math.sqrt(r))||1,p=u*b*b,v=new x(p),y=e.normalized;e.normalized=!1;for(let T=0;T<r;T++){const A=u*T;v[A]=e.getX(T)/g,a>=2&&(v[A+1]=e.getY(T)/g),a>=3&&(v[A+2]=e.getZ(T)/g,u===4&&(v[A+3]=1)),a>=4&&(v[A+3]=e.getW(T)/g)}e.normalized=y,this.internalFormat=d,this.format=m,this.type=o,this.image.width=b,this.image.height=b,this.image.data=v,this.needsUpdate=!0,this.dispose(),e.itemSize=i,e.count=s}}class Er extends Dr{constructor(){super(),this._forcedType=lt}}class Br extends Dr{constructor(){super(),this._forcedType=G}}class zr{constructor(){this.index=new Er,this.position=new Br,this.bvhBounds=new Z,this.bvhContents=new Z,this._cachedIndexAttr=null,this.index.overrideItemSize=3}updateFrom(e){const{geometry:t}=e;if(Ts(e,this.bvhBounds,this.bvhContents),this.position.updateFrom(t.attributes.position),e.indirect){const i=e._indirectBuffer;if(this._cachedIndexAttr===null||this._cachedIndexAttr.count!==i.length)if(t.index)this._cachedIndexAttr=t.index.clone();else{const s=Cr(Ot(t));this._cachedIndexAttr=new te(s,1,!1)}bs(t,i,this._cachedIndexAttr),this.index.updateFrom(this._cachedIndexAttr)}else this.index.updateFrom(t.index)}dispose(){const{index:e,position:t,bvhBounds:i,bvhContents:s}=this;e&&e.dispose(),t&&t.dispose(),i&&i.dispose(),s&&s.dispose()}}function bs(n,e,t){const i=t.array,s=n.index?n.index.array:null;for(let a=0,r=e.length;a<r;a++){const c=3*a,l=3*e[a];for(let h=0;h<3;h++)i[c+h]=s?s[l+h]:l+h}}function Ts(n,e,t){const i=n._roots;if(i.length!==1)throw new Error("MeshBVHUniformStruct: Multi-root BVHs not supported.");const s=i[0],a=new Uint16Array(s),r=new Uint32Array(s),c=new Float32Array(s),l=s.byteLength/j,h=2*Math.ceil(Math.sqrt(l/2)),f=new Float32Array(4*h*h),u=Math.ceil(Math.sqrt(l)),o=new Uint32Array(2*u*u);for(let m=0;m<l;m++){const g=m*j/4,x=g*2,d=g;for(let b=0;b<3;b++)f[8*m+0+b]=c[d+0+b],f[8*m+4+b]=c[d+3+b];if(k(x,a)){const b=q(x,a),p=H(g,r),v=Tn|b;o[m*2+0]=v,o[m*2+1]=p}else{const b=r[g+6],p=kt(g,r);o[m*2+0]=p,o[m*2+1]=b}}e.image.data=f,e.image.width=h,e.image.height=h,e.format=L,e.type=G,e.internalFormat="RGBA32F",e.minFilter=N,e.magFilter=N,e.generateMipmaps=!1,e.needsUpdate=!0,e.dispose(),t.image.data=o,t.image.width=u,t.image.height=u,t.format=_r,t.type=lt,t.internalFormat="RG32UI",t.minFilter=N,t.magFilter=N,t.generateMipmaps=!1,t.needsUpdate=!0,t.dispose()}const Nr=`
2
+
3
+ // A stack of uint32 indices can can store the indices for
4
+ // a perfectly balanced tree with a depth up to 31. Lower stack
5
+ // depth gets higher performance.
6
+ //
7
+ // However not all trees are balanced. Best value to set this to
8
+ // is the trees max depth.
9
+ #ifndef BVH_STACK_DEPTH
10
+ #define BVH_STACK_DEPTH 60
11
+ #endif
12
+
13
+ #ifndef INFINITY
14
+ #define INFINITY 1e20
15
+ #endif
16
+
17
+ // Utilities
18
+ uvec4 uTexelFetch1D( usampler2D tex, uint index ) {
19
+
20
+ uint width = uint( textureSize( tex, 0 ).x );
21
+ uvec2 uv;
22
+ uv.x = index % width;
23
+ uv.y = index / width;
24
+
25
+ return texelFetch( tex, ivec2( uv ), 0 );
26
+
27
+ }
28
+
29
+ ivec4 iTexelFetch1D( isampler2D tex, uint index ) {
30
+
31
+ uint width = uint( textureSize( tex, 0 ).x );
32
+ uvec2 uv;
33
+ uv.x = index % width;
34
+ uv.y = index / width;
35
+
36
+ return texelFetch( tex, ivec2( uv ), 0 );
37
+
38
+ }
39
+
40
+ vec4 texelFetch1D( sampler2D tex, uint index ) {
41
+
42
+ uint width = uint( textureSize( tex, 0 ).x );
43
+ uvec2 uv;
44
+ uv.x = index % width;
45
+ uv.y = index / width;
46
+
47
+ return texelFetch( tex, ivec2( uv ), 0 );
48
+
49
+ }
50
+
51
+ vec4 textureSampleBarycoord( sampler2D tex, vec3 barycoord, uvec3 faceIndices ) {
52
+
53
+ return
54
+ barycoord.x * texelFetch1D( tex, faceIndices.x ) +
55
+ barycoord.y * texelFetch1D( tex, faceIndices.y ) +
56
+ barycoord.z * texelFetch1D( tex, faceIndices.z );
57
+
58
+ }
59
+
60
+ void ndcToCameraRay(
61
+ vec2 coord, mat4 cameraWorld, mat4 invProjectionMatrix,
62
+ out vec3 rayOrigin, out vec3 rayDirection
63
+ ) {
64
+
65
+ // get camera look direction and near plane for camera clipping
66
+ vec4 lookDirection = cameraWorld * vec4( 0.0, 0.0, - 1.0, 0.0 );
67
+ vec4 nearVector = invProjectionMatrix * vec4( 0.0, 0.0, - 1.0, 1.0 );
68
+ float near = abs( nearVector.z / nearVector.w );
69
+
70
+ // get the camera direction and position from camera matrices
71
+ vec4 origin = cameraWorld * vec4( 0.0, 0.0, 0.0, 1.0 );
72
+ vec4 direction = invProjectionMatrix * vec4( coord, 0.5, 1.0 );
73
+ direction /= direction.w;
74
+ direction = cameraWorld * direction - origin;
75
+
76
+ // slide the origin along the ray until it sits at the near clip plane position
77
+ origin.xyz += direction.xyz * near / dot( direction, lookDirection );
78
+
79
+ rayOrigin = origin.xyz;
80
+ rayDirection = direction.xyz;
81
+
82
+ }
83
+ `,kr=`
84
+
85
+ #ifndef TRI_INTERSECT_EPSILON
86
+ #define TRI_INTERSECT_EPSILON 1e-5
87
+ #endif
88
+
89
+ // Raycasting
90
+ bool intersectsBounds( vec3 rayOrigin, vec3 rayDirection, vec3 boundsMin, vec3 boundsMax, out float dist ) {
91
+
92
+ // https://www.reddit.com/r/opengl/comments/8ntzz5/fast_glsl_ray_box_intersection/
93
+ // https://tavianator.com/2011/ray_box.html
94
+ vec3 invDir = 1.0 / rayDirection;
95
+
96
+ // find intersection distances for each plane
97
+ vec3 tMinPlane = invDir * ( boundsMin - rayOrigin );
98
+ vec3 tMaxPlane = invDir * ( boundsMax - rayOrigin );
99
+
100
+ // get the min and max distances from each intersection
101
+ vec3 tMinHit = min( tMaxPlane, tMinPlane );
102
+ vec3 tMaxHit = max( tMaxPlane, tMinPlane );
103
+
104
+ // get the furthest hit distance
105
+ vec2 t = max( tMinHit.xx, tMinHit.yz );
106
+ float t0 = max( t.x, t.y );
107
+
108
+ // get the minimum hit distance
109
+ t = min( tMaxHit.xx, tMaxHit.yz );
110
+ float t1 = min( t.x, t.y );
111
+
112
+ // set distance to 0.0 if the ray starts inside the box
113
+ dist = max( t0, 0.0 );
114
+
115
+ return t1 >= dist;
116
+
117
+ }
118
+
119
+ bool intersectsTriangle(
120
+ vec3 rayOrigin, vec3 rayDirection, vec3 a, vec3 b, vec3 c,
121
+ out vec3 barycoord, out vec3 norm, out float dist, out float side
122
+ ) {
123
+
124
+ // https://stackoverflow.com/questions/42740765/intersection-between-line-and-triangle-in-3d
125
+ vec3 edge1 = b - a;
126
+ vec3 edge2 = c - a;
127
+ norm = cross( edge1, edge2 );
128
+
129
+ float det = - dot( rayDirection, norm );
130
+ float invdet = 1.0 / det;
131
+
132
+ vec3 AO = rayOrigin - a;
133
+ vec3 DAO = cross( AO, rayDirection );
134
+
135
+ vec4 uvt;
136
+ uvt.x = dot( edge2, DAO ) * invdet;
137
+ uvt.y = - dot( edge1, DAO ) * invdet;
138
+ uvt.z = dot( AO, norm ) * invdet;
139
+ uvt.w = 1.0 - uvt.x - uvt.y;
140
+
141
+ // set the hit information
142
+ barycoord = uvt.wxy; // arranged in A, B, C order
143
+ dist = uvt.z;
144
+ side = sign( det );
145
+ norm = side * normalize( norm );
146
+
147
+ // add an epsilon to avoid misses between triangles
148
+ uvt += vec4( TRI_INTERSECT_EPSILON );
149
+
150
+ return all( greaterThanEqual( uvt, vec4( 0.0 ) ) );
151
+
152
+ }
153
+
154
+ bool intersectTriangles(
155
+ // geometry info and triangle range
156
+ sampler2D positionAttr, usampler2D indexAttr, uint offset, uint count,
157
+
158
+ // ray
159
+ vec3 rayOrigin, vec3 rayDirection,
160
+
161
+ // outputs
162
+ inout float minDistance, inout uvec4 faceIndices, inout vec3 faceNormal, inout vec3 barycoord,
163
+ inout float side, inout float dist
164
+ ) {
165
+
166
+ bool found = false;
167
+ vec3 localBarycoord, localNormal;
168
+ float localDist, localSide;
169
+ for ( uint i = offset, l = offset + count; i < l; i ++ ) {
170
+
171
+ uvec3 indices = uTexelFetch1D( indexAttr, i ).xyz;
172
+ vec3 a = texelFetch1D( positionAttr, indices.x ).rgb;
173
+ vec3 b = texelFetch1D( positionAttr, indices.y ).rgb;
174
+ vec3 c = texelFetch1D( positionAttr, indices.z ).rgb;
175
+
176
+ if (
177
+ intersectsTriangle( rayOrigin, rayDirection, a, b, c, localBarycoord, localNormal, localDist, localSide )
178
+ && localDist < minDistance
179
+ ) {
180
+
181
+ found = true;
182
+ minDistance = localDist;
183
+
184
+ faceIndices = uvec4( indices.xyz, i );
185
+ faceNormal = localNormal;
186
+
187
+ side = localSide;
188
+ barycoord = localBarycoord;
189
+ dist = localDist;
190
+
191
+ }
192
+
193
+ }
194
+
195
+ return found;
196
+
197
+ }
198
+
199
+ bool intersectsBVHNodeBounds( vec3 rayOrigin, vec3 rayDirection, sampler2D bvhBounds, uint currNodeIndex, out float dist ) {
200
+
201
+ uint cni2 = currNodeIndex * 2u;
202
+ vec3 boundsMin = texelFetch1D( bvhBounds, cni2 ).xyz;
203
+ vec3 boundsMax = texelFetch1D( bvhBounds, cni2 + 1u ).xyz;
204
+ return intersectsBounds( rayOrigin, rayDirection, boundsMin, boundsMax, dist );
205
+
206
+ }
207
+
208
+ // use a macro to hide the fact that we need to expand the struct into separate fields
209
+ #define bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist ) _bvhIntersectFirstHit( bvh.position, bvh.index, bvh.bvhBounds, bvh.bvhContents, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist )
210
+
211
+ bool _bvhIntersectFirstHit(
212
+ // bvh info
213
+ sampler2D bvh_position, usampler2D bvh_index, sampler2D bvh_bvhBounds, usampler2D bvh_bvhContents,
214
+
215
+ // ray
216
+ vec3 rayOrigin, vec3 rayDirection,
217
+
218
+ // output variables split into separate variables due to output precision
219
+ inout uvec4 faceIndices, inout vec3 faceNormal, inout vec3 barycoord,
220
+ inout float side, inout float dist
221
+ ) {
222
+
223
+ // stack needs to be twice as long as the deepest tree we expect because
224
+ // we push both the left and right child onto the stack every traversal
225
+ int pointer = 0;
226
+ uint stack[ BVH_STACK_DEPTH ];
227
+ stack[ 0 ] = 0u;
228
+
229
+ float triangleDistance = INFINITY;
230
+ bool found = false;
231
+ while ( pointer > - 1 && pointer < BVH_STACK_DEPTH ) {
232
+
233
+ uint currNodeIndex = stack[ pointer ];
234
+ pointer --;
235
+
236
+ // check if we intersect the current bounds
237
+ float boundsHitDistance;
238
+ if (
239
+ ! intersectsBVHNodeBounds( rayOrigin, rayDirection, bvh_bvhBounds, currNodeIndex, boundsHitDistance )
240
+ || boundsHitDistance > triangleDistance
241
+ ) {
242
+
243
+ continue;
244
+
245
+ }
246
+
247
+ uvec2 boundsInfo = uTexelFetch1D( bvh_bvhContents, currNodeIndex ).xy;
248
+ bool isLeaf = bool( boundsInfo.x & 0xffff0000u );
249
+
250
+ if ( isLeaf ) {
251
+
252
+ uint count = boundsInfo.x & 0x0000ffffu;
253
+ uint offset = boundsInfo.y;
254
+
255
+ found = intersectTriangles(
256
+ bvh_position, bvh_index, offset, count,
257
+ rayOrigin, rayDirection, triangleDistance,
258
+ faceIndices, faceNormal, barycoord, side, dist
259
+ ) || found;
260
+
261
+ } else {
262
+
263
+ uint leftIndex = currNodeIndex + 1u;
264
+ uint splitAxis = boundsInfo.x & 0x0000ffffu;
265
+ uint rightIndex = currNodeIndex + boundsInfo.y;
266
+
267
+ bool leftToRight = rayDirection[ splitAxis ] >= 0.0;
268
+ uint c1 = leftToRight ? leftIndex : rightIndex;
269
+ uint c2 = leftToRight ? rightIndex : leftIndex;
270
+
271
+ // set c2 in the stack so we traverse it later. We need to keep track of a pointer in
272
+ // the stack while we traverse. The second pointer added is the one that will be
273
+ // traversed first
274
+ pointer ++;
275
+ stack[ pointer ] = c2;
276
+
277
+ pointer ++;
278
+ stack[ pointer ] = c1;
279
+
280
+ }
281
+
282
+ }
283
+
284
+ return found;
285
+
286
+ }
287
+ `,Or=`
288
+ struct BVH {
289
+
290
+ usampler2D index;
291
+ sampler2D position;
292
+
293
+ sampler2D bvhBounds;
294
+ usampler2D bvhContents;
295
+
296
+ };
297
+ `;function Ur(n,e,t=0){if(n.isInterleavedBufferAttribute){const i=n.itemSize;for(let s=0,a=n.count;s<a;s++){const r=s+t;e.setX(r,n.getX(s)),i>=2&&e.setY(r,n.getY(s)),i>=3&&e.setZ(r,n.getZ(s)),i>=4&&e.setW(r,n.getW(s))}}else{const i=e.array,s=i.constructor,a=i.BYTES_PER_ELEMENT*n.itemSize*t;new s(i.buffer,a,n.array.length).set(n.array)}}function ct(n,e=null){const t=n.array.constructor,i=n.normalized,s=n.itemSize,a=e===null?n.count:e;return new te(new t(s*a),s,i)}function je(n,e){if(!n&&!e)return!0;if(!!n!=!!e)return!1;const t=n.count===e.count,i=n.normalized===e.normalized,s=n.array.constructor===e.array.constructor,a=n.itemSize===e.itemSize;return!(!t||!i||!s||!a)}function ws(n){const e=n[0].index!==null,t=new Set(Object.keys(n[0].attributes));if(!n[0].getAttribute("position"))throw new Error("StaticGeometryGenerator: position attribute is required.");for(let i=0;i<n.length;++i){const s=n[i];let a=0;if(e!==(s.index!==null))throw new Error("StaticGeometryGenerator: All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.");for(const r in s.attributes){if(!t.has(r))throw new Error('StaticGeometryGenerator: All geometries must have compatible attributes; make sure "'+r+'" attribute exists among all geometries, or in none of them.');a++}if(a!==t.size)throw new Error("StaticGeometryGenerator: All geometries must have the same number of attributes.")}}function Ss(n){let e=0;for(let t=0,i=n.length;t<i;t++)e+=n[t].getIndex().count;return e}function _s(n){let e=0;for(let t=0,i=n.length;t<i;t++)e+=n[t].getAttribute("position").count;return e}function As(n,e,t){n.index&&n.index.count!==e&&n.setIndex(null);const i=n.attributes;for(const s in i)i[s].count!==t&&n.deleteAttribute(s)}function Ms(n,e={},t=new Ke){const{useGroups:i=!1,forceUpdate:s=!1,skipAssigningAttributes:a=[],overwriteIndex:r=!0}=e;ws(n);const c=n[0].index!==null,l=c?Ss(n):-1,h=_s(n);if(As(t,l,h),i){let u=0;for(let o=0,m=n.length;o<m;o++){const g=n[o];let x;c?x=g.getIndex().count:x=g.getAttribute("position").count,t.addGroup(u,x,o),u+=x}}if(c){let u=!1;if(t.index||(t.setIndex(new te(new Uint32Array(l),1,!1)),u=!0),u||r){let o=0,m=0;const g=t.getIndex();for(let x=0,d=n.length;x<d;x++){const b=n[x],p=b.getIndex();if(!(!s&&!u&&a[x]))for(let y=0;y<p.count;++y)g.setX(o+y,p.getX(y)+m);o+=p.count,m+=b.getAttribute("position").count}}}const f=Object.keys(n[0].attributes);for(let u=0,o=f.length;u<o;u++){let m=!1;const g=f[u];if(!t.getAttribute(g)){const b=n[0].getAttribute(g);t.setAttribute(g,ct(b,h)),m=!0}let x=0;const d=t.getAttribute(g);for(let b=0,p=n.length;b<p;b++){const v=n[b],y=!s&&!m&&a[b],T=v.getAttribute(g);if(!y)if(g==="color"&&d.itemSize!==T.itemSize)for(let A=x,w=T.count;A<w;A++)T.setXYZW(A,d.getX(A),d.getY(A),d.getZ(A),1);else Ur(T,d,x);x+=T.count}}}function Is(n,e,t){const i=n.index,a=n.attributes.position.count,r=i?i.count:a;let c=n.groups;c.length===0&&(c=[{count:r,start:0,materialIndex:0}]);let l=n.getAttribute("materialIndex");if(!l||l.count!==a){let f;t.length<=255?f=new Uint8Array(a):f=new Uint16Array(a),l=new te(f,1,!1),n.deleteAttribute("materialIndex"),n.setAttribute("materialIndex",l)}const h=l.array;for(let f=0;f<c.length;f++){const u=c[f],o=u.start,m=u.count,g=Math.min(m,r-o),x=Array.isArray(e)?e[u.materialIndex]:e,d=t.indexOf(x);for(let b=0;b<g;b++){let p=o+b;i&&(p=i.getX(p)),h[p]=d}}}function Ps(n,e){if(!n.index){const t=n.attributes.position.count,i=new Array(t);for(let s=0;s<t;s++)i[s]=s;n.setIndex(i)}if(!n.attributes.normal&&e&&e.includes("normal")&&n.computeVertexNormals(),!n.attributes.uv&&e&&e.includes("uv")){const t=n.attributes.position.count;n.setAttribute("uv",new te(new Float32Array(t*2),2,!1))}if(!n.attributes.uv2&&e&&e.includes("uv2")){const t=n.attributes.position.count;n.setAttribute("uv2",new te(new Float32Array(t*2),2,!1))}if(!n.attributes.tangent&&e&&e.includes("tangent"))if(n.attributes.uv&&n.attributes.normal)n.computeTangents();else{const t=n.attributes.position.count;n.setAttribute("tangent",new te(new Float32Array(t*4),4,!1))}if(!n.attributes.color&&e&&e.includes("color")){const t=n.attributes.position.count,i=new Float32Array(t*4);i.fill(1),n.setAttribute("color",new te(i,4))}}function Ii(n){let e=0;if(n.byteLength!==0){const t=new Uint8Array(n);for(let i=0;i<n.byteLength;i++){const s=t[i];e=(e<<5)-e+s,e|=0}}return e}function er(n){let e=n.uuid;const t=Object.values(n.attributes);n.index&&(t.push(n.index),e+=`index|${n.index.version}`);const i=Object.keys(t).sort();for(const s of i){const a=t[s];e+=`${s}_${a.version}|`}return e}function tr(n){const e=n.skeleton;return e?(e.boneTexture||e.computeBoneTexture(),`${Ii(e.boneTexture.image.data.buffer)}_${e.boneTexture.uuid}`):null}class Rs{constructor(e=null){this.matrixWorld=new $,this.geometryHash=null,this.skeletonHash=null,this.primitiveCount=-1,e!==null&&this.updateFrom(e)}updateFrom(e){const t=e.geometry,i=(t.index?t.index.count:t.attributes.position.count)/3;this.matrixWorld.copy(e.matrixWorld),this.geometryHash=er(t),this.primitiveCount=i,this.skeletonHash=tr(e)}didChange(e){const t=e.geometry,i=(t.index?t.index.count:t.attributes.position.count)/3;return!(this.matrixWorld.equals(e.matrixWorld)&&this.geometryHash===er(t)&&this.skeletonHash===tr(e)&&this.primitiveCount===i)}}const Pe=new C,Re=new C,Fe=new C,ir=new Ze,Mt=new C,ri=new C,rr=new Ze,nr=new Ze,It=new $,sr=new $;function ar(n,e,t){const i=n.skeleton,s=n.geometry,a=i.bones,r=i.boneInverses;rr.fromBufferAttribute(s.attributes.skinIndex,e),nr.fromBufferAttribute(s.attributes.skinWeight,e),It.elements.fill(0);for(let c=0;c<4;c++){const l=nr.getComponent(c);if(l!==0){const h=rr.getComponent(c);sr.multiplyMatrices(a[h].matrixWorld,r[h]),Fs(It,sr,l)}}return It.multiply(n.bindMatrix).premultiply(n.bindMatrixInverse),t.transformDirection(It),t}function ni(n,e,t,i,s){Mt.set(0,0,0);for(let a=0,r=n.length;a<r;a++){const c=e[a],l=n[a];c!==0&&(ri.fromBufferAttribute(l,i),t?Mt.addScaledVector(ri,c):Mt.addScaledVector(ri.sub(s),c))}s.add(Mt)}function Fs(n,e,t){const i=n.elements,s=e.elements;for(let a=0,r=s.length;a<r;a++)i[a]+=s[a]*t}function Cs(n){const{index:e,attributes:t}=n;if(e)for(let i=0,s=e.count;i<s;i+=3){const a=e.getX(i),r=e.getX(i+2);e.setX(i,r),e.setX(i+2,a)}else for(const i in t){const s=t[i],a=s.itemSize;for(let r=0,c=s.count;r<c;r+=3)for(let l=0;l<a;l++){const h=s.getComponent(r,l),f=s.getComponent(r+2,l);s.setComponent(r,l,f),s.setComponent(r+2,l,h)}}return n}function Ds(n,e={},t=new Ke){e={applyWorldTransforms:!0,attributes:[],...e};const i=n.geometry,s=e.applyWorldTransforms,a=e.attributes.includes("normal"),r=e.attributes.includes("tangent"),c=i.attributes,l=t.attributes;for(const p in t.attributes)(!e.attributes.includes(p)||!(p in i.attributes))&&t.deleteAttribute(p);!t.index&&i.index&&(t.index=i.index.clone()),l.position||t.setAttribute("position",ct(c.position)),a&&!l.normal&&c.normal&&t.setAttribute("normal",ct(c.normal)),r&&!l.tangent&&c.tangent&&t.setAttribute("tangent",ct(c.tangent)),je(i.index,t.index),je(c.position,l.position),a&&je(c.normal,l.normal),r&&je(c.tangent,l.tangent);const h=c.position,f=a?c.normal:null,u=r?c.tangent:null,o=i.morphAttributes.position,m=i.morphAttributes.normal,g=i.morphAttributes.tangent,x=i.morphTargetsRelative,d=n.morphTargetInfluences,b=new tn;b.getNormalMatrix(n.matrixWorld),i.index&&t.index.array.set(i.index.array);for(let p=0,v=c.position.count;p<v;p++)Pe.fromBufferAttribute(h,p),f&&Re.fromBufferAttribute(f,p),u&&(ir.fromBufferAttribute(u,p),Fe.fromBufferAttribute(u,p)),d&&(o&&ni(o,d,x,p,Pe),m&&ni(m,d,x,p,Re),g&&ni(g,d,x,p,Fe)),n.isSkinnedMesh&&(n.applyBoneTransform(p,Pe),f&&ar(n,p,Re),u&&ar(n,p,Fe)),s&&Pe.applyMatrix4(n.matrixWorld),l.position.setXYZ(p,Pe.x,Pe.y,Pe.z),f&&(s&&Re.applyNormalMatrix(b),l.normal.setXYZ(p,Re.x,Re.y,Re.z)),u&&(s&&Fe.transformDirection(n.matrixWorld),l.tangent.setXYZW(p,Fe.x,Fe.y,Fe.z,ir.w));for(const p in e.attributes){const v=e.attributes[p];v==="position"||v==="tangent"||v==="normal"||!(v in c)||(l[v]||t.setAttribute(v,ct(c[v])),je(c[v],l[v]),Ur(c[v],l[v]))}return n.matrixWorld.determinant()<0&&Cs(t),t}class Es extends Ke{constructor(){super(),this.version=0,this.hash=null,this._diff=new Rs}isCompatible(e,t){const i=e.geometry;for(let s=0;s<t.length;s++){const a=t[s],r=i.attributes[a],c=this.attributes[a];if(r&&!je(r,c))return!1}return!0}updateFrom(e,t){const i=this._diff;return i.didChange(e)?(Ds(e,t,this),i.updateFrom(e),this.version++,this.hash=`${this.uuid}_${this.version}`,!0):!1}}const xi=0,Lr=1,Hr=2;function Bs(n,e){for(let t=0,i=n.length;t<i;t++)n[t].traverseVisible(a=>{a.isMesh&&e(a)})}function zs(n){const e=[];for(let t=0,i=n.length;t<i;t++){const s=n[t];Array.isArray(s.material)?e.push(...s.material):e.push(s.material)}return e}function Ns(n,e,t){if(n.length===0){e.setIndex(null);const i=e.attributes;for(const s in i)e.deleteAttribute(s);for(const s in t.attributes)e.setAttribute(t.attributes[s],new te(new Float32Array(0),4,!1))}else Ms(n,t,e);for(const i in e.attributes)e.attributes[i].needsUpdate=!0}class ks{constructor(e){this.objects=null,this.useGroups=!0,this.applyWorldTransforms=!0,this.generateMissingAttributes=!0,this.overwriteIndex=!0,this.attributes=["position","normal","color","tangent","uv","uv2"],this._intermediateGeometry=new Map,this._geometryMergeSets=new WeakMap,this._mergeOrder=[],this._dummyMesh=null,this.setObjects(e||[])}_getDummyMesh(){if(!this._dummyMesh){const e=new rn,t=new Ke;t.setAttribute("position",new te(new Float32Array(9),3)),this._dummyMesh=new nn(t,e)}return this._dummyMesh}_getMeshes(){const e=[];return Bs(this.objects,t=>{e.push(t)}),e.sort((t,i)=>t.uuid>i.uuid?1:t.uuid<i.uuid?-1:0),e.length===0&&e.push(this._getDummyMesh()),e}_updateIntermediateGeometries(){const{_intermediateGeometry:e}=this,t=this._getMeshes(),i=new Set(e.keys()),s={attributes:this.attributes,applyWorldTransforms:this.applyWorldTransforms};for(let a=0,r=t.length;a<r;a++){const c=t[a],l=c.uuid;i.delete(l);let h=e.get(l);(!h||!h.isCompatible(c,this.attributes))&&(h&&h.dispose(),h=new Es,e.set(l,h)),h.updateFrom(c,s)&&this.generateMissingAttributes&&Ps(h,this.attributes)}i.forEach(a=>{e.delete(a)})}setObjects(e){Array.isArray(e)?this.objects=[...e]:this.objects=[e]}generate(e=new Ke){const{useGroups:t,overwriteIndex:i,_intermediateGeometry:s,_geometryMergeSets:a}=this,r=this._getMeshes(),c=[],l=[],h=a.get(e)||[];this._updateIntermediateGeometries();let f=!1;r.length!==h.length&&(f=!0);for(let o=0,m=r.length;o<m;o++){const g=r[o],x=s.get(g.uuid);l.push(x);const d=h[o];!d||d.uuid!==x.uuid?(c.push(!1),f=!0):d.version!==x.version?c.push(!1):c.push(!0)}Ns(l,e,{useGroups:t,forceUpdate:f,skipAssigningAttributes:c,overwriteIndex:i}),f&&e.dispose(),a.set(e,l.map(o=>({version:o.version,uuid:o.uuid})));let u=xi;return f?u=Hr:c.includes(!1)&&(u=Lr),{changeType:u,materials:zs(r),geometry:e}}}function Os(n){const e=new Set;for(let t=0,i=n.length;t<i;t++){const s=n[t];for(const a in s){const r=s[a];r&&r.isTexture&&e.add(r)}}return Array.from(e)}function Us(n){const e=[],t=new Set;for(let s=0,a=n.length;s<a;s++)n[s].traverse(r=>{r.visible&&(r.isRectAreaLight||r.isSpotLight||r.isPointLight||r.isDirectionalLight)&&(e.push(r),r.iesMap&&t.add(r.iesMap))});const i=Array.from(t).sort((s,a)=>s.uuid<a.uuid?1:s.uuid>a.uuid?-1:0);return{lights:e,iesTextures:i}}class Pi{get initialized(){return!!this.bvh}constructor(e){this.bvhOptions={},this.attributes=["position","normal","tangent","color","uv","uv2"],this.generateBVH=!0,this.bvh=null,this.geometry=new Ke,this.staticGeometryGenerator=new ks(e),this._bvhWorker=null,this._pendingGenerate=null,this._buildAsync=!1,this._materialUuids=null}setObjects(e){this.staticGeometryGenerator.setObjects(e)}setBVHWorker(e){this._bvhWorker=e}async generateAsync(e=null){if(!this._bvhWorker)throw new Error('PathTracingSceneGenerator: "setBVHWorker" must be called before "generateAsync" can be called.');if(this.bvh instanceof Promise)return this._pendingGenerate||(this._pendingGenerate=new Promise(async()=>(await this.bvh,this._pendingGenerate=null,this.generateAsync(e)))),this._pendingGenerate;{this._buildAsync=!0;const t=this.generate(e);return this._buildAsync=!1,t.bvh=this.bvh=await t.bvh,t}}generate(e=null){const{staticGeometryGenerator:t,geometry:i,attributes:s}=this,a=t.objects;t.attributes=s,a.forEach(o=>{o.traverse(m=>{m.isSkinnedMesh&&m.skeleton&&m.skeleton.update()})});const r=t.generate(i),c=r.materials;let l=r.changeType!==xi||this._materialUuids===null||this._materialUuids.length!==length;if(!l){for(let o=0,m=c.length;o<m;o++)if(c[o].uuid!==this._materialUuids[o]){l=!0;break}}const h=Os(c),{lights:f,iesTextures:u}=Us(a);if(l&&(Is(i,c,c),this._materialUuids=c.map(o=>o.uuid)),this.generateBVH){if(this.bvh instanceof Promise)throw new Error("PathTracingSceneGenerator: BVH is already building asynchronously.");if(r.changeType===Hr){const o={strategy:Rr,maxLeafTris:1,indirect:!0,onProgress:e,...this.bvhOptions};this._buildAsync?this.bvh=this._bvhWorker.generate(i,o):this.bvh=new zt(i,o)}else r.changeType===Lr&&this.bvh.refit()}return{bvhChanged:r.changeType!==xi,bvh:this.bvh,needsMaterialIndexUpdate:l,lights:f,iesTextures:u,geometry:i,materials:c,textures:h,objects:a}}}class To extends Pi{constructor(...e){super(...e),console.warn('DynamicPathTracingSceneGenerator has been deprecated and renamed to "PathTracingSceneGenerator".')}}class wo extends Pi{constructor(...e){super(...e),console.warn('PathTracingSceneWorker has been deprecated and renamed to "PathTracingSceneGenerator".')}}class tt extends Nt{set needsUpdate(e){super.needsUpdate=!0,this.dispatchEvent({type:"recompilation"})}constructor(e){super(e);for(const t in this.uniforms)Object.defineProperty(this,t,{get(){return this.uniforms[t].value},set(i){this.uniforms[t].value=i}})}setDefine(e,t=void 0){if(t==null){if(e in this.defines)return delete this.defines[e],this.needsUpdate=!0,!0}else if(this.defines[e]!==t)return this.defines[e]=t,this.needsUpdate=!0,!0;return!1}}class Ls extends tt{constructor(e){super({blending:Je,uniforms:{target1:{value:null},target2:{value:null},opacity:{value:1}},vertexShader:`
298
+
299
+ varying vec2 vUv;
300
+
301
+ void main() {
302
+
303
+ vUv = uv;
304
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
305
+
306
+ }`,fragmentShader:`
307
+
308
+ uniform float opacity;
309
+
310
+ uniform sampler2D target1;
311
+ uniform sampler2D target2;
312
+
313
+ varying vec2 vUv;
314
+
315
+ void main() {
316
+
317
+ vec4 color1 = texture2D( target1, vUv );
318
+ vec4 color2 = texture2D( target2, vUv );
319
+
320
+ float invOpacity = 1.0 - opacity;
321
+ float totalAlpha = color1.a * invOpacity + color2.a * opacity;
322
+
323
+ if ( color1.a != 0.0 || color2.a != 0.0 ) {
324
+
325
+ gl_FragColor.rgb = color1.rgb * ( invOpacity * color1.a / totalAlpha ) + color2.rgb * ( opacity * color2.a / totalAlpha );
326
+ gl_FragColor.a = totalAlpha;
327
+
328
+ } else {
329
+
330
+ gl_FragColor = vec4( 0.0 );
331
+
332
+ }
333
+
334
+ }`}),this.setValues(e)}}function Pt(n=1){let e="uint";return n>1&&(e="uvec"+n),`
335
+ ${e} sobolReverseBits( ${e} x ) {
336
+
337
+ x = ( ( ( x & 0xaaaaaaaau ) >> 1 ) | ( ( x & 0x55555555u ) << 1 ) );
338
+ x = ( ( ( x & 0xccccccccu ) >> 2 ) | ( ( x & 0x33333333u ) << 2 ) );
339
+ x = ( ( ( x & 0xf0f0f0f0u ) >> 4 ) | ( ( x & 0x0f0f0f0fu ) << 4 ) );
340
+ x = ( ( ( x & 0xff00ff00u ) >> 8 ) | ( ( x & 0x00ff00ffu ) << 8 ) );
341
+ return ( ( x >> 16 ) | ( x << 16 ) );
342
+
343
+ }
344
+
345
+ ${e} sobolHashCombine( uint seed, ${e} v ) {
346
+
347
+ return seed ^ ( v + ${e}( ( seed << 6 ) + ( seed >> 2 ) ) );
348
+
349
+ }
350
+
351
+ ${e} sobolLaineKarrasPermutation( ${e} x, ${e} seed ) {
352
+
353
+ x += seed;
354
+ x ^= x * 0x6c50b47cu;
355
+ x ^= x * 0xb82f1e52u;
356
+ x ^= x * 0xc7afe638u;
357
+ x ^= x * 0x8d22f6e6u;
358
+ return x;
359
+
360
+ }
361
+
362
+ ${e} nestedUniformScrambleBase2( ${e} x, ${e} seed ) {
363
+
364
+ x = sobolLaineKarrasPermutation( x, seed );
365
+ x = sobolReverseBits( x );
366
+ return x;
367
+
368
+ }
369
+ `}function Rt(n=1){let e="uint",t="float",i="",s=".r",a="1u";return n>1&&(e="uvec"+n,t="vec"+n,i=n+"",n===2?(s=".rg",a="uvec2( 1u, 2u )"):n===3?(s=".rgb",a="uvec3( 1u, 2u, 3u )"):(s="",a="uvec4( 1u, 2u, 3u, 4u )")),`
370
+
371
+ ${t} sobol${i}( int effect ) {
372
+
373
+ uint seed = sobolGetSeed( sobolBounceIndex, uint( effect ) );
374
+ uint index = sobolPathIndex;
375
+
376
+ uint shuffle_seed = sobolHashCombine( seed, 0u );
377
+ uint shuffled_index = nestedUniformScrambleBase2( sobolReverseBits( index ), shuffle_seed );
378
+ ${t} sobol_pt = sobolGetTexturePoint( shuffled_index )${s};
379
+ ${e} result = ${e}( sobol_pt * 16777216.0 );
380
+
381
+ ${e} seed2 = sobolHashCombine( seed, ${a} );
382
+ result = nestedUniformScrambleBase2( result, seed2 );
383
+
384
+ return SOBOL_FACTOR * ${t}( result >> 8 );
385
+
386
+ }
387
+ `}const Wr=`
388
+
389
+ // Utils
390
+ const float SOBOL_FACTOR = 1.0 / 16777216.0;
391
+ const uint SOBOL_MAX_POINTS = 256u * 256u;
392
+
393
+ ${Pt(1)}
394
+ ${Pt(2)}
395
+ ${Pt(3)}
396
+ ${Pt(4)}
397
+
398
+ uint sobolHash( uint x ) {
399
+
400
+ // finalizer from murmurhash3
401
+ x ^= x >> 16;
402
+ x *= 0x85ebca6bu;
403
+ x ^= x >> 13;
404
+ x *= 0xc2b2ae35u;
405
+ x ^= x >> 16;
406
+ return x;
407
+
408
+ }
409
+
410
+ `,Hs=`
411
+
412
+ const uint SOBOL_DIRECTIONS_1[ 32 ] = uint[ 32 ](
413
+ 0x80000000u, 0xc0000000u, 0xa0000000u, 0xf0000000u,
414
+ 0x88000000u, 0xcc000000u, 0xaa000000u, 0xff000000u,
415
+ 0x80800000u, 0xc0c00000u, 0xa0a00000u, 0xf0f00000u,
416
+ 0x88880000u, 0xcccc0000u, 0xaaaa0000u, 0xffff0000u,
417
+ 0x80008000u, 0xc000c000u, 0xa000a000u, 0xf000f000u,
418
+ 0x88008800u, 0xcc00cc00u, 0xaa00aa00u, 0xff00ff00u,
419
+ 0x80808080u, 0xc0c0c0c0u, 0xa0a0a0a0u, 0xf0f0f0f0u,
420
+ 0x88888888u, 0xccccccccu, 0xaaaaaaaau, 0xffffffffu
421
+ );
422
+
423
+ const uint SOBOL_DIRECTIONS_2[ 32 ] = uint[ 32 ](
424
+ 0x80000000u, 0xc0000000u, 0x60000000u, 0x90000000u,
425
+ 0xe8000000u, 0x5c000000u, 0x8e000000u, 0xc5000000u,
426
+ 0x68800000u, 0x9cc00000u, 0xee600000u, 0x55900000u,
427
+ 0x80680000u, 0xc09c0000u, 0x60ee0000u, 0x90550000u,
428
+ 0xe8808000u, 0x5cc0c000u, 0x8e606000u, 0xc5909000u,
429
+ 0x6868e800u, 0x9c9c5c00u, 0xeeee8e00u, 0x5555c500u,
430
+ 0x8000e880u, 0xc0005cc0u, 0x60008e60u, 0x9000c590u,
431
+ 0xe8006868u, 0x5c009c9cu, 0x8e00eeeeu, 0xc5005555u
432
+ );
433
+
434
+ const uint SOBOL_DIRECTIONS_3[ 32 ] = uint[ 32 ](
435
+ 0x80000000u, 0xc0000000u, 0x20000000u, 0x50000000u,
436
+ 0xf8000000u, 0x74000000u, 0xa2000000u, 0x93000000u,
437
+ 0xd8800000u, 0x25400000u, 0x59e00000u, 0xe6d00000u,
438
+ 0x78080000u, 0xb40c0000u, 0x82020000u, 0xc3050000u,
439
+ 0x208f8000u, 0x51474000u, 0xfbea2000u, 0x75d93000u,
440
+ 0xa0858800u, 0x914e5400u, 0xdbe79e00u, 0x25db6d00u,
441
+ 0x58800080u, 0xe54000c0u, 0x79e00020u, 0xb6d00050u,
442
+ 0x800800f8u, 0xc00c0074u, 0x200200a2u, 0x50050093u
443
+ );
444
+
445
+ const uint SOBOL_DIRECTIONS_4[ 32 ] = uint[ 32 ](
446
+ 0x80000000u, 0x40000000u, 0x20000000u, 0xb0000000u,
447
+ 0xf8000000u, 0xdc000000u, 0x7a000000u, 0x9d000000u,
448
+ 0x5a800000u, 0x2fc00000u, 0xa1600000u, 0xf0b00000u,
449
+ 0xda880000u, 0x6fc40000u, 0x81620000u, 0x40bb0000u,
450
+ 0x22878000u, 0xb3c9c000u, 0xfb65a000u, 0xddb2d000u,
451
+ 0x78022800u, 0x9c0b3c00u, 0x5a0fb600u, 0x2d0ddb00u,
452
+ 0xa2878080u, 0xf3c9c040u, 0xdb65a020u, 0x6db2d0b0u,
453
+ 0x800228f8u, 0x400b3cdcu, 0x200fb67au, 0xb00ddb9du
454
+ );
455
+
456
+ uint getMaskedSobol( uint index, uint directions[ 32 ] ) {
457
+
458
+ uint X = 0u;
459
+ for ( int bit = 0; bit < 32; bit ++ ) {
460
+
461
+ uint mask = ( index >> bit ) & 1u;
462
+ X ^= mask * directions[ bit ];
463
+
464
+ }
465
+ return X;
466
+
467
+ }
468
+
469
+ vec4 generateSobolPoint( uint index ) {
470
+
471
+ if ( index >= SOBOL_MAX_POINTS ) {
472
+
473
+ return vec4( 0.0 );
474
+
475
+ }
476
+
477
+ // NOTE: this sobol "direction" is also available but we can't write out 5 components
478
+ // uint x = index & 0x00ffffffu;
479
+ uint x = sobolReverseBits( getMaskedSobol( index, SOBOL_DIRECTIONS_1 ) ) & 0x00ffffffu;
480
+ uint y = sobolReverseBits( getMaskedSobol( index, SOBOL_DIRECTIONS_2 ) ) & 0x00ffffffu;
481
+ uint z = sobolReverseBits( getMaskedSobol( index, SOBOL_DIRECTIONS_3 ) ) & 0x00ffffffu;
482
+ uint w = sobolReverseBits( getMaskedSobol( index, SOBOL_DIRECTIONS_4 ) ) & 0x00ffffffu;
483
+
484
+ return vec4( x, y, z, w ) * SOBOL_FACTOR;
485
+
486
+ }
487
+
488
+ `,Ws=`
489
+
490
+ // Seeds
491
+ uniform sampler2D sobolTexture;
492
+ uint sobolPixelIndex = 0u;
493
+ uint sobolPathIndex = 0u;
494
+ uint sobolBounceIndex = 0u;
495
+
496
+ uint sobolGetSeed( uint bounce, uint effect ) {
497
+
498
+ return sobolHash(
499
+ sobolHashCombine(
500
+ sobolHashCombine(
501
+ sobolHash( bounce ),
502
+ sobolPixelIndex
503
+ ),
504
+ effect
505
+ )
506
+ );
507
+
508
+ }
509
+
510
+ vec4 sobolGetTexturePoint( uint index ) {
511
+
512
+ if ( index >= SOBOL_MAX_POINTS ) {
513
+
514
+ index = index % SOBOL_MAX_POINTS;
515
+
516
+ }
517
+
518
+ uvec2 dim = uvec2( textureSize( sobolTexture, 0 ).xy );
519
+ uint y = index / dim.x;
520
+ uint x = index - y * dim.x;
521
+ vec2 uv = vec2( x, y ) / vec2( dim );
522
+ return texture( sobolTexture, uv );
523
+
524
+ }
525
+
526
+ ${Rt(1)}
527
+ ${Rt(2)}
528
+ ${Rt(3)}
529
+ ${Rt(4)}
530
+
531
+ `;class Vs extends tt{constructor(){super({blending:Je,uniforms:{resolution:{value:new Y}},vertexShader:`
532
+
533
+ varying vec2 vUv;
534
+ void main() {
535
+
536
+ vUv = uv;
537
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
538
+
539
+ }
540
+ `,fragmentShader:`
541
+
542
+ ${Wr}
543
+ ${Hs}
544
+
545
+ varying vec2 vUv;
546
+ uniform vec2 resolution;
547
+ void main() {
548
+
549
+ uint index = uint( gl_FragCoord.y ) * uint( resolution.x ) + uint( gl_FragCoord.x );
550
+ gl_FragColor = generateSobolPoint( index );
551
+
552
+ }
553
+ `})}}class qs{generate(e,t=256){const i=new Qe(t,t,{type:G,format:L,minFilter:N,magFilter:N,generateMipmaps:!1}),s=e.getRenderTarget();e.setRenderTarget(i);const a=new De(new Vs);return a.material.resolution.set(t,t),a.render(e),e.setRenderTarget(s),a.dispose(),i}}class Gs extends Mr{set bokehSize(e){this.fStop=this.getFocalLength()/e}get bokehSize(){return this.getFocalLength()/this.fStop}constructor(...e){super(...e),this.fStop=1.4,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=25,this.anamorphicRatio=1}copy(e,t){return super.copy(e,t),this.fStop=e.fStop,this.apertureBlades=e.apertureBlades,this.apertureRotation=e.apertureRotation,this.focusDistance=e.focusDistance,this.anamorphicRatio=e.anamorphicRatio,this}}class $s{constructor(){this.bokehSize=0,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=10,this.anamorphicRatio=1}updateFrom(e){e instanceof Gs?(this.bokehSize=e.bokehSize,this.apertureBlades=e.apertureBlades,this.apertureRotation=e.apertureRotation,this.focusDistance=e.focusDistance,this.anamorphicRatio=e.anamorphicRatio):(this.bokehSize=0,this.apertureRotation=0,this.apertureBlades=0,this.focusDistance=10,this.anamorphicRatio=1)}}function si(n){const e=new Uint16Array(n.length);for(let t=0,i=n.length;t<i;++t)e[t]=K.toHalfFloat(n[t]);return e}function or(n,e,t=0,i=n.length){let s=t,a=t+i-1;for(;s<a;){const r=s+a>>1;n[r]<e?s=r+1:a=r}return s-t}function Ys(n,e,t){return .2126*n+.7152*e+.0722*t}function js(n,e=ee){const t=n.clone();t.source=new sn({...t.image});const{width:i,height:s,data:a}=t.image;let r=a;if(t.type!==e){e===ee?r=new Uint16Array(a.length):r=new Float32Array(a.length);let c;a instanceof Int8Array||a instanceof Int16Array||a instanceof Int32Array?c=2**(8*a.BYTES_PER_ELEMENT-1)-1:c=2**(8*a.BYTES_PER_ELEMENT)-1;for(let l=0,h=a.length;l<h;l++){let f=a[l];t.type===ee&&(f=K.fromHalfFloat(a[l])),t.type!==G&&t.type!==ee&&(f/=c),e===ee&&(r[l]=K.toHalfFloat(f))}t.image.data=r,t.type=e}if(t.flipY){const c=r;r=r.slice();for(let l=0;l<s;l++)for(let h=0;h<i;h++){const f=s-l-1,u=4*(l*i+h),o=4*(f*i+h);r[o+0]=c[u+0],r[o+1]=c[u+1],r[o+2]=c[u+2],r[o+3]=c[u+3]}t.flipY=!1,t.image.data=r}return t}class Xs{constructor(){const e=new Z(si(new Float32Array([0,0,0,0])),1,1);e.type=ee,e.format=L,e.minFilter=oe,e.magFilter=oe,e.wrapS=we,e.wrapT=we,e.generateMipmaps=!1,e.needsUpdate=!0;const t=new Z(si(new Float32Array([0,1])),1,2);t.type=ee,t.format=Et,t.minFilter=oe,t.magFilter=oe,t.generateMipmaps=!1,t.needsUpdate=!0;const i=new Z(si(new Float32Array([0,0,1,1])),2,2);i.type=ee,i.format=Et,i.minFilter=oe,i.magFilter=oe,i.generateMipmaps=!1,i.needsUpdate=!0,this.map=e,this.marginalWeights=t,this.conditionalWeights=i,this.totalSum=0}getPixelWeight(e,t,i){return Ys(e,t,i)}dispose(){this.marginalWeights.dispose(),this.conditionalWeights.dispose(),this.map.dispose()}updateFrom(e){const t=js(e);t.wrapS=we,t.wrapT=Se;const{width:i,height:s,data:a}=t.image,r=new Float32Array(i*s),c=new Float32Array(i*s),l=new Float32Array(s),h=new Float32Array(s);let f=0,u=0;for(let d=0;d<s;d++){let b=0;for(let p=0;p<i;p++){const v=d*i+p,y=K.fromHalfFloat(a[4*v+0]),T=K.fromHalfFloat(a[4*v+1]),A=K.fromHalfFloat(a[4*v+2]),w=this.getPixelWeight(y,T,A,d,s);b+=w,f+=w,r[v]=w,c[v]=b}if(b!==0)for(let p=d*i,v=d*i+i;p<v;p++)r[p]/=b,c[p]/=b;u+=b,l[d]=b,h[d]=u}if(u!==0)for(let d=0,b=l.length;d<b;d++)l[d]/=u,h[d]/=u;const o=new Uint16Array(s),m=new Uint16Array(i*s);for(let d=0;d<s;d++){const b=(d+1)/s,p=or(h,b);o[d]=K.toHalfFloat((p+.5)/s)}for(let d=0;d<s;d++)for(let b=0;b<i;b++){const p=d*i+b,v=(b+1)/i,y=or(c,v,d*i,i);m[p]=K.toHalfFloat((y+.5)/i)}this.dispose();const{marginalWeights:g,conditionalWeights:x}=this;g.image={width:s,height:1,data:o},g.needsUpdate=!0,x.image={width:i,height:s,data:m},x.needsUpdate=!0,this.totalSum=f,this.map=t}}const ai=6,Qs=11,Ks=0,Zs=1,Js=2,ea=3,ta=4,se=new C,Q=new C,cr=new $,Ge=new an,lr=new C,fe=new C,ia=new C(0,1,0);class ra{constructor(){const e=new Z(new Float32Array(4),1,1);e.format=L,e.type=G,e.wrapS=Se,e.wrapT=Se,e.generateMipmaps=!1,e.minFilter=N,e.magFilter=N,this.tex=e,this.count=0}updateFrom(e,t=[]){const i=this.tex,s=Math.max(e.length*ai,1),a=Math.ceil(Math.sqrt(s));i.image.width!==a&&(i.dispose(),i.image.data=new Float32Array(a*a*4),i.image.width=a,i.image.height=a);const r=i.image.data;for(let l=0,h=e.length;l<h;l++){const f=e[l],u=l*ai*4;let o=0;for(let g=0;g<ai*4;g++)r[u+g]=0;f.getWorldPosition(Q),r[u+o++]=Q.x,r[u+o++]=Q.y,r[u+o++]=Q.z;let m=Ks;if(f.isRectAreaLight&&f.isCircular?m=Zs:f.isSpotLight?m=Js:f.isDirectionalLight||f.isSunLight?m=ea:f.isPointLight&&(m=ta),r[u+o++]=m,r[u+o++]=f.color.r,r[u+o++]=f.color.g,r[u+o++]=f.color.b,r[u+o++]=f.intensity,f.getWorldQuaternion(Ge),f.isRectAreaLight)se.set(f.width,0,0).applyQuaternion(Ge),r[u+o++]=se.x,r[u+o++]=se.y,r[u+o++]=se.z,o++,Q.set(0,f.height,0).applyQuaternion(Ge),r[u+o++]=Q.x,r[u+o++]=Q.y,r[u+o++]=Q.z,r[u+o++]=se.cross(Q).length()*(f.isCircular?Math.PI/4:1);else if(f.isSpotLight){const g=f.radius||0;lr.setFromMatrixPosition(f.matrixWorld),fe.setFromMatrixPosition(f.target.matrixWorld),cr.lookAt(lr,fe,ia),Ge.setFromRotationMatrix(cr),se.set(1,0,0).applyQuaternion(Ge),r[u+o++]=se.x,r[u+o++]=se.y,r[u+o++]=se.z,o++,Q.set(0,1,0).applyQuaternion(Ge),r[u+o++]=Q.x,r[u+o++]=Q.y,r[u+o++]=Q.z,r[u+o++]=Math.PI*g*g,r[u+o++]=g,r[u+o++]=f.decay,r[u+o++]=f.distance,r[u+o++]=Math.cos(f.angle),r[u+o++]=Math.cos(f.angle*(1-f.penumbra)),r[u+o++]=f.iesMap?t.indexOf(f.iesMap):-1}else if(f.isPointLight){const g=se.setFromMatrixPosition(f.matrixWorld);r[u+o++]=g.x,r[u+o++]=g.y,r[u+o++]=g.z,o++,o+=4,o+=1,r[u+o++]=f.decay,r[u+o++]=f.distance}else if(f.isDirectionalLight){const g=se.setFromMatrixPosition(f.matrixWorld),x=Q.setFromMatrixPosition(f.target.matrixWorld);fe.subVectors(g,x).normalize(),r[u+o++]=fe.x,r[u+o++]=fe.y,r[u+o++]=fe.z}else f.isSunLight&&(fe.setFromMatrixPosition(f.matrixWorld).normalize(),r[u+o++]=fe.x,r[u+o++]=fe.y,r[u+o++]=fe.z);r[u+Qs]=f.visibleToCameraRays?1:0}this.count=e.length;const c=Ii(r.buffer);return this.hash!==c?(this.hash=c,i.needsUpdate=!0,!0):!1}}function ur(n,e,t,i,s){if(e>i)throw new Error;const a=n.length/e,r=n.constructor.BYTES_PER_ELEMENT*8;let c=1;switch(n.constructor){case Uint8Array:case Uint16Array:case Uint32Array:c=2**r-1;break;case Int8Array:case Int16Array:case Int32Array:c=2**(r-1)-1;break}for(let l=0;l<a;l++){const h=4*l,f=e*l;for(let u=0;u<i;u++)t[s+h+u]=e>=u+1?n[f+u]/c:0}}class na extends on{constructor(){super(),this._textures=[],this.type=G,this.format=L,this.internalFormat="RGBA32F"}updateAttribute(e,t){const i=this._textures[e];i.updateFrom(t);const s=i.image,a=this.image;if(s.width!==a.width||s.height!==a.height)throw new Error("FloatAttributeTextureArray: Attribute must be the same dimensions when updating single layer.");const{width:r,height:c,data:l}=a,f=r*c*4*e;let u=t.itemSize;u===3&&(u=4),ur(i.image.data,u,l,4,f),this.dispose(),this.needsUpdate=!0}setAttributes(e){const t=e[0].count,i=e.length;for(let u=0,o=i;u<o;u++)if(e[u].count!==t)throw new Error("FloatAttributeTextureArray: All attributes must have the same item count.");const s=this._textures;for(;s.length<i;){const u=new Br;s.push(u)}for(;s.length>i;)s.pop();for(let u=0,o=i;u<o;u++)s[u].updateFrom(e[u]);const r=s[0].image,c=this.image;(r.width!==c.width||r.height!==c.height||r.depth!==i)&&(c.width=r.width,c.height=r.height,c.depth=i,c.data=new Float32Array(c.width*c.height*c.depth*4));const{data:l,width:h,height:f}=c;for(let u=0,o=i;u<o;u++){const m=s[u],x=h*f*4*u;let d=e[u].itemSize;d===3&&(d=4),ur(m.image.data,d,l,4,x)}this.dispose(),this.needsUpdate=!0}}class sa extends na{updateNormalAttribute(e){this.updateAttribute(0,e)}updateTangentAttribute(e){this.updateAttribute(1,e)}updateUvAttribute(e){this.updateAttribute(2,e)}updateColorAttribute(e){this.updateAttribute(3,e)}updateFrom(e,t,i,s){this.setAttributes([e,t,i,s])}}function Ri(n,e){return n.uuid<e.uuid?1:n.uuid>e.uuid?-1:0}function yi(n){return`${n.source.uuid}:${n.colorSpace}`}function aa(n){const e=new Set,t=[];for(let i=0,s=n.length;i<s;i++){const a=n[i],r=yi(a);e.has(r)||(e.add(r),t.push(a))}return t}function oa(n){const e=n.map(i=>i.iesMap||null).filter(i=>i),t=new Set(e);return Array.from(t).sort(Ri)}function ca(n){const e=new Set;for(let i=0,s=n.length;i<s;i++){const a=n[i];for(const r in a){const c=a[r];c&&c.isTexture&&e.add(c)}}const t=Array.from(e);return aa(t).sort(Ri)}function la(n){const e=[];return n.traverseVisible(t=>{(t.isRectAreaLight||t.isSpotLight||t.isPointLight||t.isDirectionalLight||t.isSunLight)&&e.push(t)}),e.sort(Ri)}const Ht=47,fr=Ht*4;class ua{constructor(){this._features={}}isUsed(e){return e in this._features}setUsed(e,t=!0){t===!1?delete this._features[e]:this._features[e]=!0}reset(){this._features={}}}class fa extends Z{constructor(){super(new Float32Array(4),1,1),this.format=L,this.type=G,this.wrapS=Se,this.wrapT=Se,this.minFilter=N,this.magFilter=N,this.generateMipmaps=!1,this.features=new ua}updateFrom(e,t){function i(g,x,d=-1){if(x in g&&g[x]){const b=yi(g[x]);return u[b]}else return d}function s(g,x,d){return x in g?g[x]:d}function a(g,x,d,b){const p=g[x]&&g[x].isTexture?g[x]:null;if(p){p.matrixAutoUpdate&&p.updateMatrix();const v=p.matrix.elements;let y=0;d[b+y++]=v[0],d[b+y++]=v[3],d[b+y++]=v[6],y++,d[b+y++]=v[1],d[b+y++]=v[4],d[b+y++]=v[7],y++}return 8}let r=0;const c=e.length*Ht,l=Math.ceil(Math.sqrt(c))||1,{image:h,features:f}=this,u={};for(let g=0,x=t.length;g<x;g++)u[yi(t[g])]=g;h.width!==l&&(this.dispose(),h.data=new Float32Array(l*l*4),h.width=l,h.height=l);const o=h.data;f.reset();for(let g=0,x=e.length;g<x;g++){const d=e[g];if(d.isFogVolumeMaterial){f.setUsed("FOG");for(let v=0;v<fr;v++)o[r+v]=0;o[r+0+0]=d.color.r,o[r+0+1]=d.color.g,o[r+0+2]=d.color.b,o[r+8+3]=s(d,"emissiveIntensity",0),o[r+12+0]=d.emissive.r,o[r+12+1]=d.emissive.g,o[r+12+2]=d.emissive.b,o[r+52+1]=d.density,o[r+52+3]=0,o[r+56+2]=4,r+=fr;continue}o[r++]=d.color.r,o[r++]=d.color.g,o[r++]=d.color.b,o[r++]=i(d,"map"),o[r++]=s(d,"metalness",0),o[r++]=i(d,"metalnessMap"),o[r++]=s(d,"roughness",0),o[r++]=i(d,"roughnessMap"),o[r++]=s(d,"ior",1.5),o[r++]=s(d,"transmission",0),o[r++]=i(d,"transmissionMap"),o[r++]=s(d,"emissiveIntensity",0),"emissive"in d?(o[r++]=d.emissive.r,o[r++]=d.emissive.g,o[r++]=d.emissive.b):(o[r++]=0,o[r++]=0,o[r++]=0),o[r++]=i(d,"emissiveMap"),o[r++]=i(d,"normalMap"),"normalScale"in d?(o[r++]=d.normalScale.x,o[r++]=d.normalScale.y):(o[r++]=1,o[r++]=1),o[r++]=s(d,"clearcoat",0),o[r++]=i(d,"clearcoatMap"),o[r++]=s(d,"clearcoatRoughness",0),o[r++]=i(d,"clearcoatRoughnessMap"),o[r++]=i(d,"clearcoatNormalMap"),"clearcoatNormalScale"in d?(o[r++]=d.clearcoatNormalScale.x,o[r++]=d.clearcoatNormalScale.y):(o[r++]=1,o[r++]=1),r++,o[r++]=s(d,"sheen",0),"sheenColor"in d?(o[r++]=d.sheenColor.r,o[r++]=d.sheenColor.g,o[r++]=d.sheenColor.b):(o[r++]=0,o[r++]=0,o[r++]=0),o[r++]=i(d,"sheenColorMap"),o[r++]=s(d,"sheenRoughness",0),o[r++]=i(d,"sheenRoughnessMap"),o[r++]=i(d,"iridescenceMap"),o[r++]=i(d,"iridescenceThicknessMap"),o[r++]=s(d,"iridescence",0),o[r++]=s(d,"iridescenceIOR",1.3);const b=s(d,"iridescenceThicknessRange",[100,400]);o[r++]=b[0],o[r++]=b[1],"specularColor"in d?(o[r++]=d.specularColor.r,o[r++]=d.specularColor.g,o[r++]=d.specularColor.b):(o[r++]=1,o[r++]=1,o[r++]=1),o[r++]=i(d,"specularColorMap"),o[r++]=s(d,"specularIntensity",1),o[r++]=i(d,"specularIntensityMap");const p=s(d,"thickness",0)===0&&s(d,"attenuationDistance",1/0)===1/0;if(o[r++]=Number(p),r++,"attenuationColor"in d?(o[r++]=d.attenuationColor.r,o[r++]=d.attenuationColor.g,o[r++]=d.attenuationColor.b):(o[r++]=1,o[r++]=1,o[r++]=1),o[r++]=s(d,"attenuationDistance",1/0),o[r++]=i(d,"alphaMap"),o[r++]=d.opacity,o[r++]=d.alphaTest,!p&&d.transmission>0)o[r++]=0;else switch(d.side){case oi:o[r++]=1;break;case Tr:o[r++]=-1;break;case wr:o[r++]=0;break}o[r++]=Number(s(d,"matte",!1)),o[r++]=Number(s(d,"castShadow",!0)),o[r++]=Number(d.vertexColors)|Number(d.flatShading)<<1,o[r++]=Number(d.transparent),r+=a(d,"map",o,r),r+=a(d,"metalnessMap",o,r),r+=a(d,"roughnessMap",o,r),r+=a(d,"transmissionMap",o,r),r+=a(d,"emissiveMap",o,r),r+=a(d,"normalMap",o,r),r+=a(d,"clearcoatMap",o,r),r+=a(d,"clearcoatNormalMap",o,r),r+=a(d,"clearcoatRoughnessMap",o,r),r+=a(d,"sheenColorMap",o,r),r+=a(d,"sheenRoughnessMap",o,r),r+=a(d,"iridescenceMap",o,r),r+=a(d,"iridescenceThicknessMap",o,r),r+=a(d,"specularColorMap",o,r),r+=a(d,"specularIntensityMap",o,r),r+=a(d,"alphaMap",o,r)}const m=Ii(o.buffer);return this.hash!==m?(this.hash=m,this.needsUpdate=!0,!0):!1}}const hr=new et;function ha(n){return n?`${n.uuid}:${n.version}`:null}function da(n,e){for(const t in e)t in n&&(n[t]=e[t])}class dr extends cn{constructor(e,t,i){const s={format:L,type:ci,minFilter:oe,magFilter:oe,wrapS:we,wrapT:we,generateMipmaps:!1,...i};super(e,t,1,s),da(this.texture,s),this.texture.setTextures=(...r)=>{this.setTextures(...r)},this.hashes=[null];const a=new De(new ma);this.fsQuad=a}setTextures(e,t,i=this.width,s=this.height){const a=e.getRenderTarget(),r=e.toneMapping,c=e.getClearAlpha();e.getClearColor(hr);const l=t.length||1;(i!==this.width||s!==this.height||this.depth!==l)&&(this.setSize(i,s,l),this.hashes=new Array(l).fill(null)),e.setClearColor(0,0),e.toneMapping=ln;const h=this.fsQuad,f=this.hashes;let u=!1;for(let o=0,m=l;o<m;o++){const g=t[o],x=ha(g);g&&(f[o]!==x||g.isWebGLRenderTarget)&&(g.matrixAutoUpdate=!1,g.matrix.identity(),h.material.map=g,e.setRenderTarget(this,o),h.render(e),g.updateMatrix(),g.matrixAutoUpdate=!0,f[o]=x,u=!0)}return h.material.map=null,e.setClearColor(hr,c),e.setRenderTarget(a),e.toneMapping=r,u}dispose(){super.dispose(),this.fsQuad.dispose()}}class ma extends Nt{get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}constructor(){super({uniforms:{map:{value:null}},vertexShader:`
554
+ varying vec2 vUv;
555
+ void main() {
556
+
557
+ vUv = uv;
558
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
559
+
560
+ }
561
+ `,fragmentShader:`
562
+ uniform sampler2D map;
563
+ varying vec2 vUv;
564
+ void main() {
565
+
566
+ gl_FragColor = texture2D( map, vUv );
567
+
568
+ }
569
+ `})}}function pa(n,e=Math.random()){for(let t=n.length-1;t>0;t--){const i=Math.floor(e()*(t+1)),s=n[t];n[t]=n[i],n[i]=s}return n}class ga{constructor(e,t,i=Math.random){const s=e**t,a=new Uint16Array(s);let r=s;for(let c=0;c<s;c++)a[c]=c;this.samples=new Float32Array(t),this.strataCount=e,this.reset=function(){for(let c=0;c<s;c++)a[c]=c;r=0},this.reshuffle=function(){r=0},this.next=function(){const{samples:c}=this;r>=a.length&&(pa(a,i),this.reshuffle());let l=a[r++];for(let h=0;h<t;h++)c[h]=(l%e+i())/e,l=Math.floor(l/e);return c}}}class va{constructor(e,t,i=Math.random){let s=0;for(const l of t)s+=l;const a=new Float32Array(s),r=[];let c=0;for(const l of t){const h=new ga(e,l,i);h.samples=new Float32Array(a.buffer,c,h.samples.length),c+=h.samples.length*4,r.push(h)}this.samples=a,this.strataCount=e,this.next=function(){for(const l of r)l.next();return a},this.reshuffle=function(){for(const l of r)l.reshuffle()},this.reset=function(){for(const l of r)l.reset()}}}class xa{constructor(e=0){this.m=2147483648,this.a=1103515245,this.c=12345,this.seed=e}nextInt(){return this.seed=(this.a*this.seed+this.c)%this.m,this.seed}nextFloat(){return this.nextInt()/(this.m-1)}}class ya extends Z{constructor(e=1,t=1,i=8){super(new Float32Array(1),1,1,L,G),this.minFilter=N,this.magFilter=N,this.strata=i,this.sampler=null,this.generator=new xa,this.stableNoise=!1,this.random=()=>this.stableNoise?this.generator.nextFloat():Math.random(),this.init(e,t,i)}init(e=this.image.height,t=this.image.width,i=this.strata){const{image:s}=this;if(s.width===t&&s.height===e&&this.sampler!==null)return;const a=new Array(e*t).fill(4),r=new va(i,a,this.random);s.width=t,s.height=e,s.data=r.samples,this.sampler=r,this.dispose(),this.next()}next(){this.sampler.next(),this.needsUpdate=!0}reset(){this.sampler.reset(),this.generator.seed=0}}function ba(n,e=Math.random){for(let t=n.length-1;t>0;t--){const i=~~((e()-1e-6)*t),s=n[t];n[t]=n[i],n[i]=s}}function Ta(n,e){n.fill(0);for(let t=0;t<e;t++)n[t]=1}class mr{constructor(e){this.count=0,this.size=-1,this.sigma=-1,this.radius=-1,this.lookupTable=null,this.score=null,this.binaryPattern=null,this.resize(e),this.setSigma(1.5)}findVoid(){const{score:e,binaryPattern:t}=this;let i=1/0,s=-1;for(let a=0,r=t.length;a<r;a++){if(t[a]!==0)continue;const c=e[a];c<i&&(i=c,s=a)}return s}findCluster(){const{score:e,binaryPattern:t}=this;let i=-1/0,s=-1;for(let a=0,r=t.length;a<r;a++){if(t[a]!==1)continue;const c=e[a];c>i&&(i=c,s=a)}return s}setSigma(e){if(e===this.sigma)return;const t=~~(Math.sqrt(20*e**2)+1),i=2*t+1,s=new Float32Array(i*i),a=e*e;for(let r=-t;r<=t;r++)for(let c=-t;c<=t;c++){const l=(t+c)*i+r+t,h=r*r+c*c;s[l]=Math.E**(-h/(2*a))}this.lookupTable=s,this.sigma=e,this.radius=t}resize(e){this.size!==e&&(this.size=e,this.score=new Float32Array(e*e),this.binaryPattern=new Uint8Array(e*e))}invert(){const{binaryPattern:e,score:t,size:i}=this;t.fill(0);for(let s=0,a=e.length;s<a;s++)if(e[s]===0){const r=~~(s/i),c=s-r*i;this.updateScore(c,r,1),e[s]=1}else e[s]=0}updateScore(e,t,i){const{size:s,score:a,lookupTable:r}=this,c=this.radius,l=2*c+1;for(let h=-c;h<=c;h++)for(let f=-c;f<=c;f++){const u=(c+f)*l+h+c,o=r[u];let m=e+h;m=m<0?s+m:m%s;let g=t+f;g=g<0?s+g:g%s;const x=g*s+m;a[x]+=i*o}}addPointIndex(e){this.binaryPattern[e]=1;const t=this.size,i=~~(e/t),s=e-i*t;this.updateScore(s,i,1),this.count++}removePointIndex(e){this.binaryPattern[e]=0;const t=this.size,i=~~(e/t),s=e-i*t;this.updateScore(s,i,-1),this.count--}copy(e){this.resize(e.size),this.score.set(e.score),this.binaryPattern.set(e.binaryPattern),this.setSigma(e.sigma),this.count=e.count}}class wa{constructor(){this.random=Math.random,this.sigma=1.5,this.size=64,this.majorityPointsRatio=.1,this.samples=new mr(1),this.savedSamples=new mr(1)}generate(){const{samples:e,savedSamples:t,sigma:i,majorityPointsRatio:s,size:a}=this;e.resize(a),e.setSigma(i);const r=Math.floor(a*a*s),c=e.binaryPattern;Ta(c,r),ba(c,this.random);for(let u=0,o=c.length;u<o;u++)c[u]===1&&e.addPointIndex(u);for(;;){const u=e.findCluster();e.removePointIndex(u);const o=e.findVoid();if(u===o){e.addPointIndex(u);break}e.addPointIndex(o)}const l=new Uint32Array(a*a);t.copy(e);let h;for(h=e.count-1;h>=0;){const u=e.findCluster();e.removePointIndex(u),l[u]=h,h--}const f=a*a;for(h=t.count;h<f/2;){const u=t.findVoid();t.addPointIndex(u),l[u]=h,h++}for(t.invert();h<f;){const u=t.findCluster();t.removePointIndex(u),l[u]=h,h++}return{data:l,maxValue:f}}}function Sa(n){return n>=3?4:n}function _a(n){switch(n){case 1:return Et;case 2:return Ar;default:return L}}class Aa extends Z{constructor(e=64,t=1){super(new Float32Array(4),1,1,L,G),this.minFilter=N,this.magFilter=N,this.size=e,this.channels=t,this.update()}update(){const e=this.channels,t=this.size,i=new wa;i.channels=e,i.size=t;const s=Sa(e),a=_a(s);(this.image.width!==t||a!==this.format)&&(this.image.width=t,this.image.height=t,this.image.data=new Float32Array(t**2*s),this.format=a,this.dispose());const r=this.image.data;for(let c=0,l=e;c<l;c++){const h=i.generate(),f=h.data,u=h.maxValue;for(let o=0,m=f.length;o<m;o++){const g=f[o]/u;r[o*s+c]=g}}this.needsUpdate=!0}}const Ma=`
570
+
571
+ struct PhysicalCamera {
572
+
573
+ float focusDistance;
574
+ float anamorphicRatio;
575
+ float bokehSize;
576
+ int apertureBlades;
577
+ float apertureRotation;
578
+
579
+ };
580
+
581
+ `,Ia=`
582
+
583
+ struct EquirectHdrInfo {
584
+
585
+ sampler2D marginalWeights;
586
+ sampler2D conditionalWeights;
587
+ sampler2D map;
588
+
589
+ float totalSum;
590
+
591
+ };
592
+
593
+ `,Pa=`
594
+
595
+ #define RECT_AREA_LIGHT_TYPE 0
596
+ #define CIRC_AREA_LIGHT_TYPE 1
597
+ #define SPOT_LIGHT_TYPE 2
598
+ #define DIR_LIGHT_TYPE 3
599
+ #define POINT_LIGHT_TYPE 4
600
+
601
+ struct LightsInfo {
602
+
603
+ sampler2D tex;
604
+ uint count;
605
+
606
+ };
607
+
608
+ struct Light {
609
+
610
+ vec3 position;
611
+ int type;
612
+
613
+ vec3 color;
614
+ float intensity;
615
+
616
+ vec3 u;
617
+ vec3 v;
618
+ float area;
619
+
620
+ // spot light fields
621
+ float radius;
622
+ float near;
623
+ float decay;
624
+ float distance;
625
+ float coneCos;
626
+ float penumbraCos;
627
+ int iesProfile;
628
+
629
+ };
630
+
631
+ Light readLightInfo( sampler2D tex, uint index ) {
632
+
633
+ uint i = index * 6u;
634
+
635
+ vec4 s0 = texelFetch1D( tex, i + 0u );
636
+ vec4 s1 = texelFetch1D( tex, i + 1u );
637
+ vec4 s2 = texelFetch1D( tex, i + 2u );
638
+ vec4 s3 = texelFetch1D( tex, i + 3u );
639
+
640
+ Light l;
641
+ l.position = s0.rgb;
642
+ l.type = int( round( s0.a ) );
643
+
644
+ l.color = s1.rgb;
645
+ l.intensity = s1.a;
646
+
647
+ l.u = s2.rgb;
648
+ l.v = s3.rgb;
649
+ l.area = s3.a;
650
+
651
+ if ( l.type == SPOT_LIGHT_TYPE || l.type == POINT_LIGHT_TYPE ) {
652
+
653
+ vec4 s4 = texelFetch1D( tex, i + 4u );
654
+ vec4 s5 = texelFetch1D( tex, i + 5u );
655
+ l.radius = s4.r;
656
+ l.decay = s4.g;
657
+ l.distance = s4.b;
658
+ l.coneCos = s4.a;
659
+
660
+ l.penumbraCos = s5.r;
661
+ l.iesProfile = int( round( s5.g ) );
662
+
663
+ } else {
664
+
665
+ l.radius = 0.0;
666
+ l.decay = 0.0;
667
+ l.distance = 0.0;
668
+
669
+ l.coneCos = 0.0;
670
+ l.penumbraCos = 0.0;
671
+ l.iesProfile = - 1;
672
+
673
+ }
674
+
675
+ return l;
676
+
677
+ }
678
+
679
+ `,Vr=`
680
+
681
+ struct Material {
682
+
683
+ vec3 color;
684
+ int map;
685
+
686
+ float metalness;
687
+ int metalnessMap;
688
+
689
+ float roughness;
690
+ int roughnessMap;
691
+
692
+ float ior;
693
+ float transmission;
694
+ int transmissionMap;
695
+
696
+ float emissiveIntensity;
697
+ vec3 emissive;
698
+ int emissiveMap;
699
+
700
+ int normalMap;
701
+ vec2 normalScale;
702
+
703
+ float clearcoat;
704
+ int clearcoatMap;
705
+ int clearcoatNormalMap;
706
+ vec2 clearcoatNormalScale;
707
+ float clearcoatRoughness;
708
+ int clearcoatRoughnessMap;
709
+
710
+ int iridescenceMap;
711
+ int iridescenceThicknessMap;
712
+ float iridescence;
713
+ float iridescenceIor;
714
+ float iridescenceThicknessMinimum;
715
+ float iridescenceThicknessMaximum;
716
+
717
+ vec3 specularColor;
718
+ int specularColorMap;
719
+
720
+ float specularIntensity;
721
+ int specularIntensityMap;
722
+ bool thinFilm;
723
+
724
+ vec3 attenuationColor;
725
+ float attenuationDistance;
726
+
727
+ int alphaMap;
728
+
729
+ bool castShadow;
730
+ float opacity;
731
+ float alphaTest;
732
+
733
+ float side;
734
+ bool matte;
735
+
736
+ float sheen;
737
+ vec3 sheenColor;
738
+ int sheenColorMap;
739
+ float sheenRoughness;
740
+ int sheenRoughnessMap;
741
+
742
+ bool vertexColors;
743
+ bool flatShading;
744
+ bool transparent;
745
+ bool fogVolume;
746
+
747
+ mat3 mapTransform;
748
+ mat3 metalnessMapTransform;
749
+ mat3 roughnessMapTransform;
750
+ mat3 transmissionMapTransform;
751
+ mat3 emissiveMapTransform;
752
+ mat3 normalMapTransform;
753
+ mat3 clearcoatMapTransform;
754
+ mat3 clearcoatNormalMapTransform;
755
+ mat3 clearcoatRoughnessMapTransform;
756
+ mat3 sheenColorMapTransform;
757
+ mat3 sheenRoughnessMapTransform;
758
+ mat3 iridescenceMapTransform;
759
+ mat3 iridescenceThicknessMapTransform;
760
+ mat3 specularColorMapTransform;
761
+ mat3 specularIntensityMapTransform;
762
+ mat3 alphaMapTransform;
763
+
764
+ };
765
+
766
+ mat3 readTextureTransform( sampler2D tex, uint index ) {
767
+
768
+ mat3 textureTransform;
769
+
770
+ vec4 row1 = texelFetch1D( tex, index );
771
+ vec4 row2 = texelFetch1D( tex, index + 1u );
772
+
773
+ textureTransform[0] = vec3(row1.r, row2.r, 0.0);
774
+ textureTransform[1] = vec3(row1.g, row2.g, 0.0);
775
+ textureTransform[2] = vec3(row1.b, row2.b, 1.0);
776
+
777
+ return textureTransform;
778
+
779
+ }
780
+
781
+ Material readMaterialInfo( sampler2D tex, uint index ) {
782
+
783
+ uint i = index * uint( MATERIAL_PIXELS );
784
+
785
+ vec4 s0 = texelFetch1D( tex, i + 0u );
786
+ vec4 s1 = texelFetch1D( tex, i + 1u );
787
+ vec4 s2 = texelFetch1D( tex, i + 2u );
788
+ vec4 s3 = texelFetch1D( tex, i + 3u );
789
+ vec4 s4 = texelFetch1D( tex, i + 4u );
790
+ vec4 s5 = texelFetch1D( tex, i + 5u );
791
+ vec4 s6 = texelFetch1D( tex, i + 6u );
792
+ vec4 s7 = texelFetch1D( tex, i + 7u );
793
+ vec4 s8 = texelFetch1D( tex, i + 8u );
794
+ vec4 s9 = texelFetch1D( tex, i + 9u );
795
+ vec4 s10 = texelFetch1D( tex, i + 10u );
796
+ vec4 s11 = texelFetch1D( tex, i + 11u );
797
+ vec4 s12 = texelFetch1D( tex, i + 12u );
798
+ vec4 s13 = texelFetch1D( tex, i + 13u );
799
+ vec4 s14 = texelFetch1D( tex, i + 14u );
800
+
801
+ Material m;
802
+ m.color = s0.rgb;
803
+ m.map = int( round( s0.a ) );
804
+
805
+ m.metalness = s1.r;
806
+ m.metalnessMap = int( round( s1.g ) );
807
+ m.roughness = s1.b;
808
+ m.roughnessMap = int( round( s1.a ) );
809
+
810
+ m.ior = s2.r;
811
+ m.transmission = s2.g;
812
+ m.transmissionMap = int( round( s2.b ) );
813
+ m.emissiveIntensity = s2.a;
814
+
815
+ m.emissive = s3.rgb;
816
+ m.emissiveMap = int( round( s3.a ) );
817
+
818
+ m.normalMap = int( round( s4.r ) );
819
+ m.normalScale = s4.gb;
820
+
821
+ m.clearcoat = s4.a;
822
+ m.clearcoatMap = int( round( s5.r ) );
823
+ m.clearcoatRoughness = s5.g;
824
+ m.clearcoatRoughnessMap = int( round( s5.b ) );
825
+ m.clearcoatNormalMap = int( round( s5.a ) );
826
+ m.clearcoatNormalScale = s6.rg;
827
+
828
+ m.sheen = s6.a;
829
+ m.sheenColor = s7.rgb;
830
+ m.sheenColorMap = int( round( s7.a ) );
831
+ m.sheenRoughness = s8.r;
832
+ m.sheenRoughnessMap = int( round( s8.g ) );
833
+
834
+ m.iridescenceMap = int( round( s8.b ) );
835
+ m.iridescenceThicknessMap = int( round( s8.a ) );
836
+ m.iridescence = s9.r;
837
+ m.iridescenceIor = s9.g;
838
+ m.iridescenceThicknessMinimum = s9.b;
839
+ m.iridescenceThicknessMaximum = s9.a;
840
+
841
+ m.specularColor = s10.rgb;
842
+ m.specularColorMap = int( round( s10.a ) );
843
+
844
+ m.specularIntensity = s11.r;
845
+ m.specularIntensityMap = int( round( s11.g ) );
846
+ m.thinFilm = bool( s11.b );
847
+
848
+ m.attenuationColor = s12.rgb;
849
+ m.attenuationDistance = s12.a;
850
+
851
+ m.alphaMap = int( round( s13.r ) );
852
+
853
+ m.opacity = s13.g;
854
+ m.alphaTest = s13.b;
855
+ m.side = s13.a;
856
+
857
+ m.matte = bool( s14.r );
858
+ m.castShadow = bool( s14.g );
859
+ m.vertexColors = bool( int( s14.b ) & 1 );
860
+ m.flatShading = bool( int( s14.b ) & 2 );
861
+ m.fogVolume = bool( int( s14.b ) & 4 );
862
+ m.transparent = bool( s14.a );
863
+
864
+ uint firstTextureTransformIdx = i + 15u;
865
+
866
+ // mat3( 1.0 ) is an identity matrix
867
+ m.mapTransform = m.map == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx );
868
+ m.metalnessMapTransform = m.metalnessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 2u );
869
+ m.roughnessMapTransform = m.roughnessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 4u );
870
+ m.transmissionMapTransform = m.transmissionMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 6u );
871
+ m.emissiveMapTransform = m.emissiveMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 8u );
872
+ m.normalMapTransform = m.normalMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 10u );
873
+ m.clearcoatMapTransform = m.clearcoatMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 12u );
874
+ m.clearcoatNormalMapTransform = m.clearcoatNormalMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 14u );
875
+ m.clearcoatRoughnessMapTransform = m.clearcoatRoughnessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 16u );
876
+ m.sheenColorMapTransform = m.sheenColorMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 18u );
877
+ m.sheenRoughnessMapTransform = m.sheenRoughnessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 20u );
878
+ m.iridescenceMapTransform = m.iridescenceMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 22u );
879
+ m.iridescenceThicknessMapTransform = m.iridescenceThicknessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 24u );
880
+ m.specularColorMapTransform = m.specularColorMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 26u );
881
+ m.specularIntensityMapTransform = m.specularIntensityMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 28u );
882
+ m.alphaMapTransform = m.alphaMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 30u );
883
+
884
+ return m;
885
+
886
+ }
887
+
888
+ `,Ra=`
889
+
890
+ struct SurfaceRecord {
891
+
892
+ // surface type
893
+ bool volumeParticle;
894
+
895
+ // geometry
896
+ vec3 faceNormal;
897
+ bool frontFace;
898
+ vec3 normal;
899
+ mat3 normalBasis;
900
+ mat3 normalInvBasis;
901
+
902
+ // cached properties
903
+ float eta;
904
+ float f0;
905
+
906
+ // material
907
+ float roughness;
908
+ float filteredRoughness;
909
+ float metalness;
910
+ vec3 color;
911
+ vec3 emission;
912
+
913
+ // transmission
914
+ float ior;
915
+ float transmission;
916
+ bool thinFilm;
917
+ vec3 attenuationColor;
918
+ float attenuationDistance;
919
+
920
+ // clearcoat
921
+ vec3 clearcoatNormal;
922
+ mat3 clearcoatBasis;
923
+ mat3 clearcoatInvBasis;
924
+ float clearcoat;
925
+ float clearcoatRoughness;
926
+ float filteredClearcoatRoughness;
927
+
928
+ // sheen
929
+ float sheen;
930
+ vec3 sheenColor;
931
+ float sheenRoughness;
932
+
933
+ // iridescence
934
+ float iridescence;
935
+ float iridescenceIor;
936
+ float iridescenceThickness;
937
+
938
+ // specular
939
+ vec3 specularColor;
940
+ float specularIntensity;
941
+ };
942
+
943
+ struct ScatterRecord {
944
+ float specularPdf;
945
+ float pdf;
946
+ vec3 direction;
947
+ vec3 color;
948
+ };
949
+
950
+ `,Fa=`
951
+
952
+ // samples the the given environment map in the given direction
953
+ vec3 sampleEquirectColor( sampler2D envMap, vec3 direction ) {
954
+
955
+ return texture2D( envMap, equirectDirectionToUv( direction ) ).rgb;
956
+
957
+ }
958
+
959
+ // gets the pdf of the given direction to sample
960
+ float equirectDirectionPdf( vec3 direction ) {
961
+
962
+ vec2 uv = equirectDirectionToUv( direction );
963
+ float theta = uv.y * PI;
964
+ float sinTheta = sin( theta );
965
+ if ( sinTheta == 0.0 ) {
966
+
967
+ return 0.0;
968
+
969
+ }
970
+
971
+ return 1.0 / ( 2.0 * PI * PI * sinTheta );
972
+
973
+ }
974
+
975
+ // samples the color given env map with CDF and returns the pdf of the direction
976
+ float sampleEquirect( vec3 direction, inout vec3 color ) {
977
+
978
+ float totalSum = envMapInfo.totalSum;
979
+ if ( totalSum == 0.0 ) {
980
+
981
+ color = vec3( 0.0 );
982
+ return 1.0;
983
+
984
+ }
985
+
986
+ vec2 uv = equirectDirectionToUv( direction );
987
+ color = texture2D( envMapInfo.map, uv ).rgb;
988
+
989
+ float lum = luminance( color );
990
+ ivec2 resolution = textureSize( envMapInfo.map, 0 );
991
+ float pdf = lum / totalSum;
992
+
993
+ return float( resolution.x * resolution.y ) * pdf * equirectDirectionPdf( direction );
994
+
995
+ }
996
+
997
+ // samples a direction of the envmap with color and retrieves pdf
998
+ float sampleEquirectProbability( vec2 r, inout vec3 color, inout vec3 direction ) {
999
+
1000
+ // sample env map cdf
1001
+ float v = texture2D( envMapInfo.marginalWeights, vec2( r.x, 0.0 ) ).x;
1002
+ float u = texture2D( envMapInfo.conditionalWeights, vec2( r.y, v ) ).x;
1003
+ vec2 uv = vec2( u, v );
1004
+
1005
+ vec3 derivedDirection = equirectUvToDirection( uv );
1006
+ direction = derivedDirection;
1007
+ color = texture2D( envMapInfo.map, uv ).rgb;
1008
+
1009
+ float totalSum = envMapInfo.totalSum;
1010
+ float lum = luminance( color );
1011
+ ivec2 resolution = textureSize( envMapInfo.map, 0 );
1012
+ float pdf = lum / totalSum;
1013
+
1014
+ return float( resolution.x * resolution.y ) * pdf * equirectDirectionPdf( direction );
1015
+
1016
+ }
1017
+ `,Ca=`
1018
+
1019
+ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
1020
+
1021
+ return smoothstep( coneCosine, penumbraCosine, angleCosine );
1022
+
1023
+ }
1024
+
1025
+ float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
1026
+
1027
+ // based upon Frostbite 3 Moving to Physically-based Rendering
1028
+ // page 32, equation 26: E[window1]
1029
+ // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
1030
+ float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), EPSILON );
1031
+
1032
+ if ( cutoffDistance > 0.0 ) {
1033
+
1034
+ distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
1035
+
1036
+ }
1037
+
1038
+ return distanceFalloff;
1039
+
1040
+ }
1041
+
1042
+ float getPhotometricAttenuation( sampler2DArray iesProfiles, int iesProfile, vec3 posToLight, vec3 lightDir, vec3 u, vec3 v ) {
1043
+
1044
+ float cosTheta = dot( posToLight, lightDir );
1045
+ float angle = acos( cosTheta ) / PI;
1046
+
1047
+ return texture2D( iesProfiles, vec3( angle, 0.0, iesProfile ) ).r;
1048
+
1049
+ }
1050
+
1051
+ struct LightRecord {
1052
+
1053
+ float dist;
1054
+ vec3 direction;
1055
+ float pdf;
1056
+ vec3 emission;
1057
+ int type;
1058
+
1059
+ };
1060
+
1061
+ bool intersectLightAtIndex( sampler2D lights, vec3 rayOrigin, vec3 rayDirection, uint l, inout LightRecord lightRec ) {
1062
+
1063
+ bool didHit = false;
1064
+ Light light = readLightInfo( lights, l );
1065
+
1066
+ vec3 u = light.u;
1067
+ vec3 v = light.v;
1068
+
1069
+ // check for backface
1070
+ vec3 normal = normalize( cross( u, v ) );
1071
+ if ( dot( normal, rayDirection ) > 0.0 ) {
1072
+
1073
+ u *= 1.0 / dot( u, u );
1074
+ v *= 1.0 / dot( v, v );
1075
+
1076
+ float dist;
1077
+
1078
+ // MIS / light intersection is not supported for punctual lights.
1079
+ if(
1080
+ ( light.type == RECT_AREA_LIGHT_TYPE && intersectsRectangle( light.position, normal, u, v, rayOrigin, rayDirection, dist ) ) ||
1081
+ ( light.type == CIRC_AREA_LIGHT_TYPE && intersectsCircle( light.position, normal, u, v, rayOrigin, rayDirection, dist ) )
1082
+ ) {
1083
+
1084
+ float cosTheta = dot( rayDirection, normal );
1085
+ didHit = true;
1086
+ lightRec.dist = dist;
1087
+ lightRec.pdf = ( dist * dist ) / ( light.area * cosTheta );
1088
+ lightRec.emission = light.color * light.intensity;
1089
+ lightRec.direction = rayDirection;
1090
+ lightRec.type = light.type;
1091
+
1092
+ }
1093
+
1094
+ }
1095
+
1096
+ return didHit;
1097
+
1098
+ }
1099
+
1100
+ LightRecord randomAreaLightSample( Light light, vec3 rayOrigin, vec2 ruv ) {
1101
+
1102
+ vec3 randomPos;
1103
+ if( light.type == RECT_AREA_LIGHT_TYPE ) {
1104
+
1105
+ // rectangular area light
1106
+ randomPos = light.position + light.u * ( ruv.x - 0.5 ) + light.v * ( ruv.y - 0.5 );
1107
+
1108
+ } else if( light.type == CIRC_AREA_LIGHT_TYPE ) {
1109
+
1110
+ // circular area light
1111
+ float r = 0.5 * sqrt( ruv.x );
1112
+ float theta = ruv.y * 2.0 * PI;
1113
+ float x = r * cos( theta );
1114
+ float y = r * sin( theta );
1115
+
1116
+ randomPos = light.position + light.u * x + light.v * y;
1117
+
1118
+ }
1119
+
1120
+ vec3 toLight = randomPos - rayOrigin;
1121
+ float lightDistSq = dot( toLight, toLight );
1122
+ float dist = sqrt( lightDistSq );
1123
+ vec3 direction = toLight / dist;
1124
+ vec3 lightNormal = normalize( cross( light.u, light.v ) );
1125
+
1126
+ LightRecord lightRec;
1127
+ lightRec.type = light.type;
1128
+ lightRec.emission = light.color * light.intensity;
1129
+ lightRec.dist = dist;
1130
+ lightRec.direction = direction;
1131
+
1132
+ // TODO: the denominator is potentially zero
1133
+ lightRec.pdf = lightDistSq / ( light.area * dot( direction, lightNormal ) );
1134
+
1135
+ return lightRec;
1136
+
1137
+ }
1138
+
1139
+ LightRecord randomSpotLightSample( Light light, sampler2DArray iesProfiles, vec3 rayOrigin, vec2 ruv ) {
1140
+
1141
+ float radius = light.radius * sqrt( ruv.x );
1142
+ float theta = ruv.y * 2.0 * PI;
1143
+ float x = radius * cos( theta );
1144
+ float y = radius * sin( theta );
1145
+
1146
+ vec3 u = light.u;
1147
+ vec3 v = light.v;
1148
+ vec3 normal = normalize( cross( u, v ) );
1149
+
1150
+ float angle = acos( light.coneCos );
1151
+ float angleTan = tan( angle );
1152
+ float startDistance = light.radius / max( angleTan, EPSILON );
1153
+
1154
+ vec3 randomPos = light.position - normal * startDistance + u * x + v * y;
1155
+ vec3 toLight = randomPos - rayOrigin;
1156
+ float lightDistSq = dot( toLight, toLight );
1157
+ float dist = sqrt( lightDistSq );
1158
+
1159
+ vec3 direction = toLight / max( dist, EPSILON );
1160
+ float cosTheta = dot( direction, normal );
1161
+
1162
+ float spotAttenuation = light.iesProfile != - 1 ?
1163
+ getPhotometricAttenuation( iesProfiles, light.iesProfile, direction, normal, u, v ) :
1164
+ getSpotAttenuation( light.coneCos, light.penumbraCos, cosTheta );
1165
+
1166
+ float distanceAttenuation = getDistanceAttenuation( dist, light.distance, light.decay );
1167
+ LightRecord lightRec;
1168
+ lightRec.type = light.type;
1169
+ lightRec.dist = dist;
1170
+ lightRec.direction = direction;
1171
+ lightRec.emission = light.color * light.intensity * distanceAttenuation * spotAttenuation;
1172
+ lightRec.pdf = 1.0;
1173
+
1174
+ return lightRec;
1175
+
1176
+ }
1177
+
1178
+ LightRecord randomLightSample( sampler2D lights, sampler2DArray iesProfiles, uint lightCount, vec3 rayOrigin, vec3 ruv ) {
1179
+
1180
+ LightRecord result;
1181
+
1182
+ // pick a random light
1183
+ uint l = uint( ruv.x * float( lightCount ) );
1184
+ Light light = readLightInfo( lights, l );
1185
+
1186
+ if ( light.type == SPOT_LIGHT_TYPE ) {
1187
+
1188
+ result = randomSpotLightSample( light, iesProfiles, rayOrigin, ruv.yz );
1189
+
1190
+ } else if ( light.type == POINT_LIGHT_TYPE ) {
1191
+
1192
+ vec3 lightRay = light.u - rayOrigin;
1193
+ float lightDist = length( lightRay );
1194
+ float cutoffDistance = light.distance;
1195
+ float distanceFalloff = 1.0 / max( pow( lightDist, light.decay ), 0.01 );
1196
+ if ( cutoffDistance > 0.0 ) {
1197
+
1198
+ distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDist / cutoffDistance ) ) );
1199
+
1200
+ }
1201
+
1202
+ LightRecord rec;
1203
+ rec.direction = normalize( lightRay );
1204
+ rec.dist = length( lightRay );
1205
+ rec.pdf = 1.0;
1206
+ rec.emission = light.color * light.intensity * distanceFalloff;
1207
+ rec.type = light.type;
1208
+ result = rec;
1209
+
1210
+ } else if ( light.type == DIR_LIGHT_TYPE ) {
1211
+
1212
+ LightRecord rec;
1213
+ rec.dist = 1e10;
1214
+ rec.direction = light.u;
1215
+ rec.pdf = 1.0;
1216
+ rec.emission = light.color * light.intensity;
1217
+ rec.type = light.type;
1218
+
1219
+ result = rec;
1220
+
1221
+ } else {
1222
+
1223
+ // sample the light
1224
+ result = randomAreaLightSample( light, rayOrigin, ruv.yz );
1225
+
1226
+ }
1227
+
1228
+ return result;
1229
+
1230
+ }
1231
+
1232
+ `,qr=`
1233
+
1234
+ vec3 sampleHemisphere( vec3 n, vec2 uv ) {
1235
+
1236
+ // https://www.rorydriscoll.com/2009/01/07/better-sampling/
1237
+ // https://graphics.pixar.com/library/OrthonormalB/paper.pdf
1238
+ float sign = n.z == 0.0 ? 1.0 : sign( n.z );
1239
+ float a = - 1.0 / ( sign + n.z );
1240
+ float b = n.x * n.y * a;
1241
+ vec3 b1 = vec3( 1.0 + sign * n.x * n.x * a, sign * b, - sign * n.x );
1242
+ vec3 b2 = vec3( b, sign + n.y * n.y * a, - n.y );
1243
+
1244
+ float r = sqrt( uv.x );
1245
+ float theta = 2.0 * PI * uv.y;
1246
+ float x = r * cos( theta );
1247
+ float y = r * sin( theta );
1248
+ return x * b1 + y * b2 + sqrt( 1.0 - uv.x ) * n;
1249
+
1250
+ }
1251
+
1252
+ vec2 sampleTriangle( vec2 a, vec2 b, vec2 c, vec2 r ) {
1253
+
1254
+ // get the edges of the triangle and the diagonal across the
1255
+ // center of the parallelogram
1256
+ vec2 e1 = a - b;
1257
+ vec2 e2 = c - b;
1258
+ vec2 diag = normalize( e1 + e2 );
1259
+
1260
+ // pick the point in the parallelogram
1261
+ if ( r.x + r.y > 1.0 ) {
1262
+
1263
+ r = vec2( 1.0 ) - r;
1264
+
1265
+ }
1266
+
1267
+ return e1 * r.x + e2 * r.y;
1268
+
1269
+ }
1270
+
1271
+ vec2 sampleCircle( vec2 uv ) {
1272
+
1273
+ float angle = 2.0 * PI * uv.x;
1274
+ float radius = sqrt( uv.y );
1275
+ return vec2( cos( angle ), sin( angle ) ) * radius;
1276
+
1277
+ }
1278
+
1279
+ vec3 sampleSphere( vec2 uv ) {
1280
+
1281
+ float u = ( uv.x - 0.5 ) * 2.0;
1282
+ float t = uv.y * PI * 2.0;
1283
+ float f = sqrt( 1.0 - u * u );
1284
+
1285
+ return vec3( f * cos( t ), f * sin( t ), u );
1286
+
1287
+ }
1288
+
1289
+ vec2 sampleRegularPolygon( int sides, vec3 uvw ) {
1290
+
1291
+ sides = max( sides, 3 );
1292
+
1293
+ vec3 r = uvw;
1294
+ float anglePerSegment = 2.0 * PI / float( sides );
1295
+ float segment = floor( float( sides ) * r.x );
1296
+
1297
+ float angle1 = anglePerSegment * segment;
1298
+ float angle2 = angle1 + anglePerSegment;
1299
+ vec2 a = vec2( sin( angle1 ), cos( angle1 ) );
1300
+ vec2 b = vec2( 0.0, 0.0 );
1301
+ vec2 c = vec2( sin( angle2 ), cos( angle2 ) );
1302
+
1303
+ return sampleTriangle( a, b, c, r.yz );
1304
+
1305
+ }
1306
+
1307
+ // samples an aperture shape with the given number of sides. 0 means circle
1308
+ vec2 sampleAperture( int blades, vec3 uvw ) {
1309
+
1310
+ return blades == 0 ?
1311
+ sampleCircle( uvw.xy ) :
1312
+ sampleRegularPolygon( blades, uvw );
1313
+
1314
+ }
1315
+
1316
+
1317
+ `,Da=`
1318
+
1319
+ bool totalInternalReflection( float cosTheta, float eta ) {
1320
+
1321
+ float sinTheta = sqrt( 1.0 - cosTheta * cosTheta );
1322
+ return eta * sinTheta > 1.0;
1323
+
1324
+ }
1325
+
1326
+ // https://google.github.io/filament/Filament.md.html#materialsystem/diffusebrdf
1327
+ float schlickFresnel( float cosine, float f0 ) {
1328
+
1329
+ return f0 + ( 1.0 - f0 ) * pow( 1.0 - cosine, 5.0 );
1330
+
1331
+ }
1332
+
1333
+ vec3 schlickFresnel( float cosine, vec3 f0 ) {
1334
+
1335
+ return f0 + ( 1.0 - f0 ) * pow( 1.0 - cosine, 5.0 );
1336
+
1337
+ }
1338
+
1339
+ vec3 schlickFresnel( float cosine, vec3 f0, vec3 f90 ) {
1340
+
1341
+ return f0 + ( f90 - f0 ) * pow( 1.0 - cosine, 5.0 );
1342
+
1343
+ }
1344
+
1345
+ float dielectricFresnel( float cosThetaI, float eta ) {
1346
+
1347
+ // https://schuttejoe.github.io/post/disneybsdf/
1348
+ float ni = eta;
1349
+ float nt = 1.0;
1350
+
1351
+ // Check for total internal reflection
1352
+ float sinThetaISq = 1.0f - cosThetaI * cosThetaI;
1353
+ float sinThetaTSq = eta * eta * sinThetaISq;
1354
+ if( sinThetaTSq >= 1.0 ) {
1355
+
1356
+ return 1.0;
1357
+
1358
+ }
1359
+
1360
+ float sinThetaT = sqrt( sinThetaTSq );
1361
+
1362
+ float cosThetaT = sqrt( max( 0.0, 1.0f - sinThetaT * sinThetaT ) );
1363
+ float rParallel = ( ( nt * cosThetaI ) - ( ni * cosThetaT ) ) / ( ( nt * cosThetaI ) + ( ni * cosThetaT ) );
1364
+ float rPerpendicular = ( ( ni * cosThetaI ) - ( nt * cosThetaT ) ) / ( ( ni * cosThetaI ) + ( nt * cosThetaT ) );
1365
+ return ( rParallel * rParallel + rPerpendicular * rPerpendicular ) / 2.0;
1366
+
1367
+ }
1368
+
1369
+ // https://raytracing.github.io/books/RayTracingInOneWeekend.html#dielectrics/schlickapproximation
1370
+ float iorRatioToF0( float eta ) {
1371
+
1372
+ return pow( ( 1.0 - eta ) / ( 1.0 + eta ), 2.0 );
1373
+
1374
+ }
1375
+
1376
+ vec3 evaluateFresnel( float cosTheta, float eta, vec3 f0, vec3 f90 ) {
1377
+
1378
+ if ( totalInternalReflection( cosTheta, eta ) ) {
1379
+
1380
+ return f90;
1381
+
1382
+ }
1383
+
1384
+ return schlickFresnel( cosTheta, f0, f90 );
1385
+
1386
+ }
1387
+
1388
+ // TODO: disney fresnel was removed and replaced with this fresnel function to better align with
1389
+ // the glTF but is causing blown out pixels. Should be revisited
1390
+ // float evaluateFresnelWeight( float cosTheta, float eta, float f0 ) {
1391
+
1392
+ // if ( totalInternalReflection( cosTheta, eta ) ) {
1393
+
1394
+ // return 1.0;
1395
+
1396
+ // }
1397
+
1398
+ // return schlickFresnel( cosTheta, f0 );
1399
+
1400
+ // }
1401
+
1402
+ // https://schuttejoe.github.io/post/disneybsdf/
1403
+ float disneyFresnel( vec3 wo, vec3 wi, vec3 wh, float f0, float eta, float metalness ) {
1404
+
1405
+ float dotHV = dot( wo, wh );
1406
+ if ( totalInternalReflection( dotHV, eta ) ) {
1407
+
1408
+ return 1.0;
1409
+
1410
+ }
1411
+
1412
+ float dotHL = dot( wi, wh );
1413
+ float dielectricFresnel = dielectricFresnel( abs( dotHV ), eta );
1414
+ float metallicFresnel = schlickFresnel( dotHL, f0 );
1415
+
1416
+ return mix( dielectricFresnel, metallicFresnel, metalness );
1417
+
1418
+ }
1419
+
1420
+ `,Ea=`
1421
+
1422
+ // Fast arccos approximation used to remove banding artifacts caused by numerical errors in acos.
1423
+ // This is a cubic Lagrange interpolating polynomial for x = [-1, -1/2, 0, 1/2, 1].
1424
+ // For more information see: https://github.com/gkjohnson/three-gpu-pathtracer/pull/171#issuecomment-1152275248
1425
+ float acosApprox( float x ) {
1426
+
1427
+ x = clamp( x, -1.0, 1.0 );
1428
+ return ( - 0.69813170079773212 * x * x - 0.87266462599716477 ) * x + 1.5707963267948966;
1429
+
1430
+ }
1431
+
1432
+ // An acos with input values bound to the range [-1, 1].
1433
+ float acosSafe( float x ) {
1434
+
1435
+ return acos( clamp( x, -1.0, 1.0 ) );
1436
+
1437
+ }
1438
+
1439
+ float saturateCos( float val ) {
1440
+
1441
+ return clamp( val, 0.001, 1.0 );
1442
+
1443
+ }
1444
+
1445
+ float square( float t ) {
1446
+
1447
+ return t * t;
1448
+
1449
+ }
1450
+
1451
+ vec2 square( vec2 t ) {
1452
+
1453
+ return t * t;
1454
+
1455
+ }
1456
+
1457
+ vec3 square( vec3 t ) {
1458
+
1459
+ return t * t;
1460
+
1461
+ }
1462
+
1463
+ vec4 square( vec4 t ) {
1464
+
1465
+ return t * t;
1466
+
1467
+ }
1468
+
1469
+ vec2 rotateVector( vec2 v, float t ) {
1470
+
1471
+ float ac = cos( t );
1472
+ float as = sin( t );
1473
+ return vec2(
1474
+ v.x * ac - v.y * as,
1475
+ v.x * as + v.y * ac
1476
+ );
1477
+
1478
+ }
1479
+
1480
+ // forms a basis with the normal vector as Z
1481
+ mat3 getBasisFromNormal( vec3 normal ) {
1482
+
1483
+ vec3 other;
1484
+ if ( abs( normal.x ) > 0.5 ) {
1485
+
1486
+ other = vec3( 0.0, 1.0, 0.0 );
1487
+
1488
+ } else {
1489
+
1490
+ other = vec3( 1.0, 0.0, 0.0 );
1491
+
1492
+ }
1493
+
1494
+ vec3 ortho = normalize( cross( normal, other ) );
1495
+ vec3 ortho2 = normalize( cross( normal, ortho ) );
1496
+ return mat3( ortho2, ortho, normal );
1497
+
1498
+ }
1499
+
1500
+ `,Ba=`
1501
+
1502
+ // Finds the point where the ray intersects the plane defined by u and v and checks if this point
1503
+ // falls in the bounds of the rectangle on that same plane.
1504
+ // Plane intersection: https://lousodrome.net/blog/light/2020/07/03/intersection-of-a-ray-and-a-plane/
1505
+ bool intersectsRectangle( vec3 center, vec3 normal, vec3 u, vec3 v, vec3 rayOrigin, vec3 rayDirection, inout float dist ) {
1506
+
1507
+ float t = dot( center - rayOrigin, normal ) / dot( rayDirection, normal );
1508
+
1509
+ if ( t > EPSILON ) {
1510
+
1511
+ vec3 p = rayOrigin + rayDirection * t;
1512
+ vec3 vi = p - center;
1513
+
1514
+ // check if p falls inside the rectangle
1515
+ float a1 = dot( u, vi );
1516
+ if ( abs( a1 ) <= 0.5 ) {
1517
+
1518
+ float a2 = dot( v, vi );
1519
+ if ( abs( a2 ) <= 0.5 ) {
1520
+
1521
+ dist = t;
1522
+ return true;
1523
+
1524
+ }
1525
+
1526
+ }
1527
+
1528
+ }
1529
+
1530
+ return false;
1531
+
1532
+ }
1533
+
1534
+ // Finds the point where the ray intersects the plane defined by u and v and checks if this point
1535
+ // falls in the bounds of the circle on that same plane. See above URL for a description of the plane intersection algorithm.
1536
+ bool intersectsCircle( vec3 position, vec3 normal, vec3 u, vec3 v, vec3 rayOrigin, vec3 rayDirection, inout float dist ) {
1537
+
1538
+ float t = dot( position - rayOrigin, normal ) / dot( rayDirection, normal );
1539
+
1540
+ if ( t > EPSILON ) {
1541
+
1542
+ vec3 hit = rayOrigin + rayDirection * t;
1543
+ vec3 vi = hit - position;
1544
+
1545
+ float a1 = dot( u, vi );
1546
+ float a2 = dot( v, vi );
1547
+
1548
+ if( length( vec2( a1, a2 ) ) <= 0.5 ) {
1549
+
1550
+ dist = t;
1551
+ return true;
1552
+
1553
+ }
1554
+
1555
+ }
1556
+
1557
+ return false;
1558
+
1559
+ }
1560
+
1561
+ `,za=`
1562
+
1563
+ // add texel fetch functions for texture arrays
1564
+ vec4 texelFetch1D( sampler2DArray tex, int layer, uint index ) {
1565
+
1566
+ uint width = uint( textureSize( tex, 0 ).x );
1567
+ uvec2 uv;
1568
+ uv.x = index % width;
1569
+ uv.y = index / width;
1570
+
1571
+ return texelFetch( tex, ivec3( uv, layer ), 0 );
1572
+
1573
+ }
1574
+
1575
+ vec4 textureSampleBarycoord( sampler2DArray tex, int layer, vec3 barycoord, uvec3 faceIndices ) {
1576
+
1577
+ return
1578
+ barycoord.x * texelFetch1D( tex, layer, faceIndices.x ) +
1579
+ barycoord.y * texelFetch1D( tex, layer, faceIndices.y ) +
1580
+ barycoord.z * texelFetch1D( tex, layer, faceIndices.z );
1581
+
1582
+ }
1583
+
1584
+ `,Fi=`
1585
+
1586
+ // TODO: possibly this should be renamed something related to material or path tracing logic
1587
+
1588
+ #ifndef RAY_OFFSET
1589
+ #define RAY_OFFSET 1e-4
1590
+ #endif
1591
+
1592
+ // adjust the hit point by the surface normal by a factor of some offset and the
1593
+ // maximum component-wise value of the current point to accommodate floating point
1594
+ // error as values increase.
1595
+ vec3 stepRayOrigin( vec3 rayOrigin, vec3 rayDirection, vec3 offset, float dist ) {
1596
+
1597
+ vec3 point = rayOrigin + rayDirection * dist;
1598
+ vec3 absPoint = abs( point );
1599
+ float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
1600
+ return point + offset * ( maxPoint + 1.0 ) * RAY_OFFSET;
1601
+
1602
+ }
1603
+
1604
+ // https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_volume/README.md#attenuation
1605
+ vec3 transmissionAttenuation( float dist, vec3 attColor, float attDist ) {
1606
+
1607
+ vec3 ot = - log( attColor ) / attDist;
1608
+ return exp( - ot * dist );
1609
+
1610
+ }
1611
+
1612
+ vec3 getHalfVector( vec3 wi, vec3 wo, float eta ) {
1613
+
1614
+ // get the half vector - assuming if the light incident vector is on the other side
1615
+ // of the that it's transmissive.
1616
+ vec3 h;
1617
+ if ( wi.z > 0.0 ) {
1618
+
1619
+ h = normalize( wi + wo );
1620
+
1621
+ } else {
1622
+
1623
+ // Scale by the ior ratio to retrieve the appropriate half vector
1624
+ // From Section 2.2 on computing the transmission half vector:
1625
+ // https://blog.selfshadow.com/publications/s2015-shading-course/burley/s2015_pbs_disney_bsdf_notes.pdf
1626
+ h = normalize( wi + wo * eta );
1627
+
1628
+ }
1629
+
1630
+ h *= sign( h.z );
1631
+ return h;
1632
+
1633
+ }
1634
+
1635
+ vec3 getHalfVector( vec3 a, vec3 b ) {
1636
+
1637
+ return normalize( a + b );
1638
+
1639
+ }
1640
+
1641
+ // The discrepancy between interpolated surface normal and geometry normal can cause issues when a ray
1642
+ // is cast that is on the top side of the geometry normal plane but below the surface normal plane. If
1643
+ // we find a ray like that we ignore it to avoid artifacts.
1644
+ // This function returns if the direction is on the same side of both planes.
1645
+ bool isDirectionValid( vec3 direction, vec3 surfaceNormal, vec3 geometryNormal ) {
1646
+
1647
+ bool aboveSurfaceNormal = dot( direction, surfaceNormal ) > 0.0;
1648
+ bool aboveGeometryNormal = dot( direction, geometryNormal ) > 0.0;
1649
+ return aboveSurfaceNormal == aboveGeometryNormal;
1650
+
1651
+ }
1652
+
1653
+ // ray sampling x and z are swapped to align with expected background view
1654
+ vec2 equirectDirectionToUv( vec3 direction ) {
1655
+
1656
+ // from Spherical.setFromCartesianCoords
1657
+ vec2 uv = vec2( atan( direction.z, direction.x ), acos( direction.y ) );
1658
+ uv /= vec2( 2.0 * PI, PI );
1659
+
1660
+ // apply adjustments to get values in range [0, 1] and y right side up
1661
+ uv.x += 0.5;
1662
+ uv.y = 1.0 - uv.y;
1663
+ return uv;
1664
+
1665
+ }
1666
+
1667
+ vec3 equirectUvToDirection( vec2 uv ) {
1668
+
1669
+ // undo above adjustments
1670
+ uv.x -= 0.5;
1671
+ uv.y = 1.0 - uv.y;
1672
+
1673
+ // from Vector3.setFromSphericalCoords
1674
+ float theta = uv.x * 2.0 * PI;
1675
+ float phi = uv.y * PI;
1676
+
1677
+ float sinPhi = sin( phi );
1678
+
1679
+ return vec3( sinPhi * cos( theta ), cos( phi ), sinPhi * sin( theta ) );
1680
+
1681
+ }
1682
+
1683
+ // power heuristic for multiple importance sampling
1684
+ float misHeuristic( float a, float b ) {
1685
+
1686
+ float aa = a * a;
1687
+ float bb = b * b;
1688
+ return aa / ( aa + bb );
1689
+
1690
+ }
1691
+
1692
+ // tentFilter from Peter Shirley's 'Realistic Ray Tracing (2nd Edition)' book, pg. 60
1693
+ // erichlof/THREE.js-PathTracing-Renderer/
1694
+ float tentFilter( float x ) {
1695
+
1696
+ return x < 0.5 ? sqrt( 2.0 * x ) - 1.0 : 1.0 - sqrt( 2.0 - ( 2.0 * x ) );
1697
+
1698
+ }
1699
+ `,bi=`
1700
+
1701
+ // https://www.shadertoy.com/view/wltcRS
1702
+ uvec4 WHITE_NOISE_SEED;
1703
+
1704
+ void rng_initialize( vec2 p, int frame ) {
1705
+
1706
+ // white noise seed
1707
+ WHITE_NOISE_SEED = uvec4( p, uint( frame ), uint( p.x ) + uint( p.y ) );
1708
+
1709
+ }
1710
+
1711
+ // https://www.pcg-random.org/
1712
+ void pcg4d( inout uvec4 v ) {
1713
+
1714
+ v = v * 1664525u + 1013904223u;
1715
+ v.x += v.y * v.w;
1716
+ v.y += v.z * v.x;
1717
+ v.z += v.x * v.y;
1718
+ v.w += v.y * v.z;
1719
+ v = v ^ ( v >> 16u );
1720
+ v.x += v.y*v.w;
1721
+ v.y += v.z*v.x;
1722
+ v.z += v.x*v.y;
1723
+ v.w += v.y*v.z;
1724
+
1725
+ }
1726
+
1727
+ // returns [ 0, 1 ]
1728
+ float pcgRand() {
1729
+
1730
+ pcg4d( WHITE_NOISE_SEED );
1731
+ return float( WHITE_NOISE_SEED.x ) / float( 0xffffffffu );
1732
+
1733
+ }
1734
+
1735
+ vec2 pcgRand2() {
1736
+
1737
+ pcg4d( WHITE_NOISE_SEED );
1738
+ return vec2( WHITE_NOISE_SEED.xy ) / float(0xffffffffu);
1739
+
1740
+ }
1741
+
1742
+ vec3 pcgRand3() {
1743
+
1744
+ pcg4d( WHITE_NOISE_SEED );
1745
+ return vec3( WHITE_NOISE_SEED.xyz ) / float( 0xffffffffu );
1746
+
1747
+ }
1748
+
1749
+ vec4 pcgRand4() {
1750
+
1751
+ pcg4d( WHITE_NOISE_SEED );
1752
+ return vec4( WHITE_NOISE_SEED ) / float( 0xffffffffu );
1753
+
1754
+ }
1755
+ `,Na=`
1756
+
1757
+ uniform sampler2D stratifiedTexture;
1758
+ uniform sampler2D stratifiedOffsetTexture;
1759
+
1760
+ uint sobolPixelIndex = 0u;
1761
+ uint sobolPathIndex = 0u;
1762
+ uint sobolBounceIndex = 0u;
1763
+ vec4 pixelSeed = vec4( 0 );
1764
+
1765
+ vec4 rand4( int v ) {
1766
+
1767
+ ivec2 uv = ivec2( v, sobolBounceIndex );
1768
+ vec4 stratifiedSample = texelFetch( stratifiedTexture, uv, 0 );
1769
+ return fract( stratifiedSample + pixelSeed.r ); // blue noise + stratified samples
1770
+
1771
+ }
1772
+
1773
+ vec3 rand3( int v ) {
1774
+
1775
+ return rand4( v ).xyz;
1776
+
1777
+ }
1778
+
1779
+ vec2 rand2( int v ) {
1780
+
1781
+ return rand4( v ).xy;
1782
+
1783
+ }
1784
+
1785
+ float rand( int v ) {
1786
+
1787
+ return rand4( v ).x;
1788
+
1789
+ }
1790
+
1791
+ void rng_initialize( vec2 screenCoord, int frame ) {
1792
+
1793
+ // tile the small noise texture across the entire screen
1794
+ ivec2 noiseSize = ivec2( textureSize( stratifiedOffsetTexture, 0 ) );
1795
+ ivec2 pixel = ivec2( screenCoord.xy ) % noiseSize;
1796
+ vec2 pixelWidth = 1.0 / vec2( noiseSize );
1797
+ vec2 uv = vec2( pixel ) * pixelWidth + pixelWidth * 0.5;
1798
+
1799
+ // note that using "texelFetch" here seems to break Android for some reason
1800
+ pixelSeed = texture( stratifiedOffsetTexture, uv );
1801
+
1802
+ }
1803
+
1804
+ `,ka=`
1805
+
1806
+ // diffuse
1807
+ float diffuseEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
1808
+
1809
+ // https://schuttejoe.github.io/post/disneybsdf/
1810
+ float fl = schlickFresnel( wi.z, 0.0 );
1811
+ float fv = schlickFresnel( wo.z, 0.0 );
1812
+
1813
+ float metalFactor = ( 1.0 - surf.metalness );
1814
+ float transFactor = ( 1.0 - surf.transmission );
1815
+ float rr = 0.5 + 2.0 * surf.roughness * fl * fl;
1816
+ float retro = rr * ( fl + fv + fl * fv * ( rr - 1.0f ) );
1817
+ float lambert = ( 1.0f - 0.5f * fl ) * ( 1.0f - 0.5f * fv );
1818
+
1819
+ // TODO: subsurface approx?
1820
+
1821
+ // float F = evaluateFresnelWeight( dot( wo, wh ), surf.eta, surf.f0 );
1822
+ float F = disneyFresnel( wo, wi, wh, surf.f0, surf.eta, surf.metalness );
1823
+ color = ( 1.0 - F ) * transFactor * metalFactor * wi.z * surf.color * ( retro + lambert ) / PI;
1824
+
1825
+ return wi.z / PI;
1826
+
1827
+ }
1828
+
1829
+ vec3 diffuseDirection( vec3 wo, SurfaceRecord surf ) {
1830
+
1831
+ vec3 lightDirection = sampleSphere( rand2( 11 ) );
1832
+ lightDirection.z += 1.0;
1833
+ lightDirection = normalize( lightDirection );
1834
+
1835
+ return lightDirection;
1836
+
1837
+ }
1838
+
1839
+ // specular
1840
+ float specularEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
1841
+
1842
+ // if roughness is set to 0 then D === NaN which results in black pixels
1843
+ float metalness = surf.metalness;
1844
+ float roughness = surf.filteredRoughness;
1845
+
1846
+ float eta = surf.eta;
1847
+ float f0 = surf.f0;
1848
+
1849
+ vec3 f0Color = mix( f0 * surf.specularColor * surf.specularIntensity, surf.color, surf.metalness );
1850
+ vec3 f90Color = vec3( mix( surf.specularIntensity, 1.0, surf.metalness ) );
1851
+ vec3 F = evaluateFresnel( dot( wo, wh ), eta, f0Color, f90Color );
1852
+
1853
+ vec3 iridescenceF = evalIridescence( 1.0, surf.iridescenceIor, dot( wi, wh ), surf.iridescenceThickness, f0Color );
1854
+ F = mix( F, iridescenceF, surf.iridescence );
1855
+
1856
+ // PDF
1857
+ // See 14.1.1 Microfacet BxDFs in https://www.pbr-book.org/
1858
+ float incidentTheta = acos( wo.z );
1859
+ float G = ggxShadowMaskG2( wi, wo, roughness );
1860
+ float D = ggxDistribution( wh, roughness );
1861
+ float G1 = ggxShadowMaskG1( incidentTheta, roughness );
1862
+ float ggxPdf = D * G1 * max( 0.0, abs( dot( wo, wh ) ) ) / abs ( wo.z );
1863
+
1864
+ color = wi.z * F * G * D / ( 4.0 * abs( wi.z * wo.z ) );
1865
+ return ggxPdf / ( 4.0 * dot( wo, wh ) );
1866
+
1867
+ }
1868
+
1869
+ vec3 specularDirection( vec3 wo, SurfaceRecord surf ) {
1870
+
1871
+ // sample ggx vndf distribution which gives a new normal
1872
+ float roughness = surf.filteredRoughness;
1873
+ vec3 halfVector = ggxDirection(
1874
+ wo,
1875
+ vec2( roughness ),
1876
+ rand2( 12 )
1877
+ );
1878
+
1879
+ // apply to new ray by reflecting off the new normal
1880
+ return - reflect( wo, halfVector );
1881
+
1882
+ }
1883
+
1884
+
1885
+ // transmission
1886
+ /*
1887
+ float transmissionEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
1888
+
1889
+ // See section 4.2 in https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf
1890
+
1891
+ float filteredRoughness = surf.filteredRoughness;
1892
+ float eta = surf.eta;
1893
+ bool frontFace = surf.frontFace;
1894
+ bool thinFilm = surf.thinFilm;
1895
+
1896
+ color = surf.transmission * surf.color;
1897
+
1898
+ float denom = pow( eta * dot( wi, wh ) + dot( wo, wh ), 2.0 );
1899
+ return ggxPDF( wo, wh, filteredRoughness ) / denom;
1900
+
1901
+ }
1902
+
1903
+ vec3 transmissionDirection( vec3 wo, SurfaceRecord surf ) {
1904
+
1905
+ float filteredRoughness = surf.filteredRoughness;
1906
+ float eta = surf.eta;
1907
+ bool frontFace = surf.frontFace;
1908
+
1909
+ // sample ggx vndf distribution which gives a new normal
1910
+ vec3 halfVector = ggxDirection(
1911
+ wo,
1912
+ vec2( filteredRoughness ),
1913
+ rand2( 13 )
1914
+ );
1915
+
1916
+ vec3 lightDirection = refract( normalize( - wo ), halfVector, eta );
1917
+ if ( surf.thinFilm ) {
1918
+
1919
+ lightDirection = - refract( normalize( - lightDirection ), - vec3( 0.0, 0.0, 1.0 ), 1.0 / eta );
1920
+
1921
+ }
1922
+
1923
+ return normalize( lightDirection );
1924
+
1925
+ }
1926
+ */
1927
+
1928
+ // TODO: This is just using a basic cosine-weighted specular distribution with an
1929
+ // incorrect PDF value at the moment. Update it to correctly use a GGX distribution
1930
+ float transmissionEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
1931
+
1932
+ color = surf.transmission * surf.color;
1933
+
1934
+ // PDF
1935
+ // float F = evaluateFresnelWeight( dot( wo, wh ), surf.eta, surf.f0 );
1936
+ // float F = disneyFresnel( wo, wi, wh, surf.f0, surf.eta, surf.metalness );
1937
+ // if ( F >= 1.0 ) {
1938
+
1939
+ // return 0.0;
1940
+
1941
+ // }
1942
+
1943
+ // return 1.0 / ( 1.0 - F );
1944
+
1945
+ // reverted to previous to transmission. The above was causing black pixels
1946
+ float eta = surf.eta;
1947
+ float f0 = surf.f0;
1948
+ float cosTheta = min( wo.z, 1.0 );
1949
+ float sinTheta = sqrt( 1.0 - cosTheta * cosTheta );
1950
+ float reflectance = schlickFresnel( cosTheta, f0 );
1951
+ bool cannotRefract = eta * sinTheta > 1.0;
1952
+ if ( cannotRefract ) {
1953
+
1954
+ return 0.0;
1955
+
1956
+ }
1957
+
1958
+ return 1.0 / ( 1.0 - reflectance );
1959
+
1960
+ }
1961
+
1962
+ vec3 transmissionDirection( vec3 wo, SurfaceRecord surf ) {
1963
+
1964
+ float roughness = surf.filteredRoughness;
1965
+ float eta = surf.eta;
1966
+ vec3 halfVector = normalize( vec3( 0.0, 0.0, 1.0 ) + sampleSphere( rand2( 13 ) ) * roughness );
1967
+ vec3 lightDirection = refract( normalize( - wo ), halfVector, eta );
1968
+
1969
+ if ( surf.thinFilm ) {
1970
+
1971
+ lightDirection = - refract( normalize( - lightDirection ), - vec3( 0.0, 0.0, 1.0 ), 1.0 / eta );
1972
+
1973
+ }
1974
+ return normalize( lightDirection );
1975
+
1976
+ }
1977
+
1978
+ // clearcoat
1979
+ float clearcoatEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
1980
+
1981
+ float ior = 1.5;
1982
+ float f0 = iorRatioToF0( ior );
1983
+ bool frontFace = surf.frontFace;
1984
+ float roughness = surf.filteredClearcoatRoughness;
1985
+
1986
+ float eta = frontFace ? 1.0 / ior : ior;
1987
+ float G = ggxShadowMaskG2( wi, wo, roughness );
1988
+ float D = ggxDistribution( wh, roughness );
1989
+ float F = schlickFresnel( dot( wi, wh ), f0 );
1990
+
1991
+ float fClearcoat = F * D * G / ( 4.0 * abs( wi.z * wo.z ) );
1992
+ color = color * ( 1.0 - surf.clearcoat * F ) + fClearcoat * surf.clearcoat * wi.z;
1993
+
1994
+ // PDF
1995
+ // See equation (27) in http://jcgt.org/published/0003/02/03/
1996
+ return ggxPDF( wo, wh, roughness ) / ( 4.0 * dot( wi, wh ) );
1997
+
1998
+ }
1999
+
2000
+ vec3 clearcoatDirection( vec3 wo, SurfaceRecord surf ) {
2001
+
2002
+ // sample ggx vndf distribution which gives a new normal
2003
+ float roughness = surf.filteredClearcoatRoughness;
2004
+ vec3 halfVector = ggxDirection(
2005
+ wo,
2006
+ vec2( roughness ),
2007
+ rand2( 14 )
2008
+ );
2009
+
2010
+ // apply to new ray by reflecting off the new normal
2011
+ return - reflect( wo, halfVector );
2012
+
2013
+ }
2014
+
2015
+ // sheen
2016
+ vec3 sheenColor( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf ) {
2017
+
2018
+ float cosThetaO = saturateCos( wo.z );
2019
+ float cosThetaI = saturateCos( wi.z );
2020
+ float cosThetaH = wh.z;
2021
+
2022
+ float D = velvetD( cosThetaH, surf.sheenRoughness );
2023
+ float G = velvetG( cosThetaO, cosThetaI, surf.sheenRoughness );
2024
+
2025
+ // See equation (1) in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
2026
+ vec3 color = surf.sheenColor;
2027
+ color *= D * G / ( 4.0 * abs( cosThetaO * cosThetaI ) );
2028
+
2029
+ return color;
2030
+
2031
+ }
2032
+
2033
+ // bsdf
2034
+ void getLobeWeights(
2035
+ vec3 wo, vec3 wi, vec3 wh, vec3 clearcoatWo, SurfaceRecord surf,
2036
+ inout float diffuseWeight, inout float specularWeight, inout float transmissionWeight, inout float clearcoatWeight
2037
+ ) {
2038
+
2039
+ float metalness = surf.metalness;
2040
+ float transmission = surf.transmission;
2041
+ // float fEstimate = evaluateFresnelWeight( dot( wo, wh ), surf.eta, surf.f0 );
2042
+ float fEstimate = disneyFresnel( wo, wi, wh, surf.f0, surf.eta, surf.metalness );
2043
+
2044
+ float transSpecularProb = mix( max( 0.25, fEstimate ), 1.0, metalness );
2045
+ float diffSpecularProb = 0.5 + 0.5 * metalness;
2046
+
2047
+ diffuseWeight = ( 1.0 - transmission ) * ( 1.0 - diffSpecularProb );
2048
+ specularWeight = transmission * transSpecularProb + ( 1.0 - transmission ) * diffSpecularProb;
2049
+ transmissionWeight = transmission * ( 1.0 - transSpecularProb );
2050
+ clearcoatWeight = surf.clearcoat * schlickFresnel( clearcoatWo.z, 0.04 );
2051
+
2052
+ float totalWeight = diffuseWeight + specularWeight + transmissionWeight + clearcoatWeight;
2053
+ diffuseWeight /= totalWeight;
2054
+ specularWeight /= totalWeight;
2055
+ transmissionWeight /= totalWeight;
2056
+ clearcoatWeight /= totalWeight;
2057
+ }
2058
+
2059
+ float bsdfEval(
2060
+ vec3 wo, vec3 clearcoatWo, vec3 wi, vec3 clearcoatWi, SurfaceRecord surf,
2061
+ float diffuseWeight, float specularWeight, float transmissionWeight, float clearcoatWeight, inout float specularPdf, inout vec3 color
2062
+ ) {
2063
+
2064
+ float metalness = surf.metalness;
2065
+ float transmission = surf.transmission;
2066
+
2067
+ float spdf = 0.0;
2068
+ float dpdf = 0.0;
2069
+ float tpdf = 0.0;
2070
+ float cpdf = 0.0;
2071
+ color = vec3( 0.0 );
2072
+
2073
+ vec3 halfVector = getHalfVector( wi, wo, surf.eta );
2074
+
2075
+ // diffuse
2076
+ if ( diffuseWeight > 0.0 && wi.z > 0.0 ) {
2077
+
2078
+ dpdf = diffuseEval( wo, wi, halfVector, surf, color );
2079
+ color *= 1.0 - surf.transmission;
2080
+
2081
+ }
2082
+
2083
+ // ggx specular
2084
+ if ( specularWeight > 0.0 && wi.z > 0.0 ) {
2085
+
2086
+ vec3 outColor;
2087
+ spdf = specularEval( wo, wi, getHalfVector( wi, wo ), surf, outColor );
2088
+ color += outColor;
2089
+
2090
+ }
2091
+
2092
+ // transmission
2093
+ if ( transmissionWeight > 0.0 && wi.z < 0.0 ) {
2094
+
2095
+ tpdf = transmissionEval( wo, wi, halfVector, surf, color );
2096
+
2097
+ }
2098
+
2099
+ // sheen
2100
+ color *= mix( 1.0, sheenAlbedoScaling( wo, wi, surf ), surf.sheen );
2101
+ color += sheenColor( wo, wi, halfVector, surf ) * surf.sheen;
2102
+
2103
+ // clearcoat
2104
+ if ( clearcoatWi.z >= 0.0 && clearcoatWeight > 0.0 ) {
2105
+
2106
+ vec3 clearcoatHalfVector = getHalfVector( clearcoatWo, clearcoatWi );
2107
+ cpdf = clearcoatEval( clearcoatWo, clearcoatWi, clearcoatHalfVector, surf, color );
2108
+
2109
+ }
2110
+
2111
+ float pdf =
2112
+ dpdf * diffuseWeight
2113
+ + spdf * specularWeight
2114
+ + tpdf * transmissionWeight
2115
+ + cpdf * clearcoatWeight;
2116
+
2117
+ // retrieve specular rays for the shadows flag
2118
+ specularPdf = spdf * specularWeight + cpdf * clearcoatWeight;
2119
+
2120
+ return pdf;
2121
+
2122
+ }
2123
+
2124
+ float bsdfResult( vec3 worldWo, vec3 worldWi, SurfaceRecord surf, inout vec3 color ) {
2125
+
2126
+ if ( surf.volumeParticle ) {
2127
+
2128
+ color = surf.color / ( 4.0 * PI );
2129
+ return 1.0 / ( 4.0 * PI );
2130
+
2131
+ }
2132
+
2133
+ vec3 wo = normalize( surf.normalInvBasis * worldWo );
2134
+ vec3 wi = normalize( surf.normalInvBasis * worldWi );
2135
+
2136
+ vec3 clearcoatWo = normalize( surf.clearcoatInvBasis * worldWo );
2137
+ vec3 clearcoatWi = normalize( surf.clearcoatInvBasis * worldWi );
2138
+
2139
+ vec3 wh = getHalfVector( wo, wi, surf.eta );
2140
+ float diffuseWeight;
2141
+ float specularWeight;
2142
+ float transmissionWeight;
2143
+ float clearcoatWeight;
2144
+ getLobeWeights( wo, wi, wh, clearcoatWo, surf, diffuseWeight, specularWeight, transmissionWeight, clearcoatWeight );
2145
+
2146
+ float specularPdf;
2147
+ return bsdfEval( wo, clearcoatWo, wi, clearcoatWi, surf, diffuseWeight, specularWeight, transmissionWeight, clearcoatWeight, specularPdf, color );
2148
+
2149
+ }
2150
+
2151
+ ScatterRecord bsdfSample( vec3 worldWo, SurfaceRecord surf ) {
2152
+
2153
+ if ( surf.volumeParticle ) {
2154
+
2155
+ ScatterRecord sampleRec;
2156
+ sampleRec.specularPdf = 0.0;
2157
+ sampleRec.pdf = 1.0 / ( 4.0 * PI );
2158
+ sampleRec.direction = sampleSphere( rand2( 16 ) );
2159
+ sampleRec.color = surf.color / ( 4.0 * PI );
2160
+ return sampleRec;
2161
+
2162
+ }
2163
+
2164
+ vec3 wo = normalize( surf.normalInvBasis * worldWo );
2165
+ vec3 clearcoatWo = normalize( surf.clearcoatInvBasis * worldWo );
2166
+ mat3 normalBasis = surf.normalBasis;
2167
+ mat3 invBasis = surf.normalInvBasis;
2168
+ mat3 clearcoatNormalBasis = surf.clearcoatBasis;
2169
+ mat3 clearcoatInvBasis = surf.clearcoatInvBasis;
2170
+
2171
+ float diffuseWeight;
2172
+ float specularWeight;
2173
+ float transmissionWeight;
2174
+ float clearcoatWeight;
2175
+ // using normal and basically-reflected ray since we don't have proper half vector here
2176
+ getLobeWeights( wo, wo, vec3( 0, 0, 1 ), clearcoatWo, surf, diffuseWeight, specularWeight, transmissionWeight, clearcoatWeight );
2177
+
2178
+ float pdf[4];
2179
+ pdf[0] = diffuseWeight;
2180
+ pdf[1] = specularWeight;
2181
+ pdf[2] = transmissionWeight;
2182
+ pdf[3] = clearcoatWeight;
2183
+
2184
+ float cdf[4];
2185
+ cdf[0] = pdf[0];
2186
+ cdf[1] = pdf[1] + cdf[0];
2187
+ cdf[2] = pdf[2] + cdf[1];
2188
+ cdf[3] = pdf[3] + cdf[2];
2189
+
2190
+ if( cdf[3] != 0.0 ) {
2191
+
2192
+ float invMaxCdf = 1.0 / cdf[3];
2193
+ cdf[0] *= invMaxCdf;
2194
+ cdf[1] *= invMaxCdf;
2195
+ cdf[2] *= invMaxCdf;
2196
+ cdf[3] *= invMaxCdf;
2197
+
2198
+ } else {
2199
+
2200
+ cdf[0] = 1.0;
2201
+ cdf[1] = 0.0;
2202
+ cdf[2] = 0.0;
2203
+ cdf[3] = 0.0;
2204
+
2205
+ }
2206
+
2207
+ vec3 wi;
2208
+ vec3 clearcoatWi;
2209
+
2210
+ float r = rand( 15 );
2211
+ if ( r <= cdf[0] ) { // diffuse
2212
+
2213
+ wi = diffuseDirection( wo, surf );
2214
+ clearcoatWi = normalize( clearcoatInvBasis * normalize( normalBasis * wi ) );
2215
+
2216
+ } else if ( r <= cdf[1] ) { // specular
2217
+
2218
+ wi = specularDirection( wo, surf );
2219
+ clearcoatWi = normalize( clearcoatInvBasis * normalize( normalBasis * wi ) );
2220
+
2221
+ } else if ( r <= cdf[2] ) { // transmission / refraction
2222
+
2223
+ wi = transmissionDirection( wo, surf );
2224
+ clearcoatWi = normalize( clearcoatInvBasis * normalize( normalBasis * wi ) );
2225
+
2226
+ } else if ( r <= cdf[3] ) { // clearcoat
2227
+
2228
+ clearcoatWi = clearcoatDirection( clearcoatWo, surf );
2229
+ wi = normalize( invBasis * normalize( clearcoatNormalBasis * clearcoatWi ) );
2230
+
2231
+ }
2232
+
2233
+ ScatterRecord result;
2234
+ result.pdf = bsdfEval( wo, clearcoatWo, wi, clearcoatWi, surf, diffuseWeight, specularWeight, transmissionWeight, clearcoatWeight, result.specularPdf, result.color );
2235
+ result.direction = normalize( surf.normalBasis * wi );
2236
+
2237
+ return result;
2238
+
2239
+ }
2240
+
2241
+ `,Oa=`
2242
+
2243
+ // returns the hit distance given the material density
2244
+ float intersectFogVolume( Material material, float u ) {
2245
+
2246
+ // https://raytracing.github.io/books/RayTracingTheNextWeek.html#volumes/constantdensitymediums
2247
+ return material.opacity == 0.0 ? INFINITY : ( - 1.0 / material.opacity ) * log( u );
2248
+
2249
+ }
2250
+
2251
+ ScatterRecord sampleFogVolume( SurfaceRecord surf, vec2 uv ) {
2252
+
2253
+ ScatterRecord sampleRec;
2254
+ sampleRec.specularPdf = 0.0;
2255
+ sampleRec.pdf = 1.0 / ( 2.0 * PI );
2256
+ sampleRec.direction = sampleSphere( uv );
2257
+ sampleRec.color = surf.color;
2258
+ return sampleRec;
2259
+
2260
+ }
2261
+
2262
+ `,Ua=`
2263
+
2264
+ // The GGX functions provide sampling and distribution information for normals as output so
2265
+ // in order to get probability of scatter direction the half vector must be computed and provided.
2266
+ // [0] https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf
2267
+ // [1] https://hal.archives-ouvertes.fr/hal-01509746/document
2268
+ // [2] http://jcgt.org/published/0007/04/01/
2269
+ // [4] http://jcgt.org/published/0003/02/03/
2270
+
2271
+ // trowbridge-reitz === GGX === GTR
2272
+
2273
+ vec3 ggxDirection( vec3 incidentDir, vec2 roughness, vec2 uv ) {
2274
+
2275
+ // TODO: try GGXVNDF implementation from reference [2], here. Needs to update ggxDistribution
2276
+ // function below, as well
2277
+
2278
+ // Implementation from reference [1]
2279
+ // stretch view
2280
+ vec3 V = normalize( vec3( roughness * incidentDir.xy, incidentDir.z ) );
2281
+
2282
+ // orthonormal basis
2283
+ vec3 T1 = ( V.z < 0.9999 ) ? normalize( cross( V, vec3( 0.0, 0.0, 1.0 ) ) ) : vec3( 1.0, 0.0, 0.0 );
2284
+ vec3 T2 = cross( T1, V );
2285
+
2286
+ // sample point with polar coordinates (r, phi)
2287
+ float a = 1.0 / ( 1.0 + V.z );
2288
+ float r = sqrt( uv.x );
2289
+ float phi = ( uv.y < a ) ? uv.y / a * PI : PI + ( uv.y - a ) / ( 1.0 - a ) * PI;
2290
+ float P1 = r * cos( phi );
2291
+ float P2 = r * sin( phi ) * ( ( uv.y < a ) ? 1.0 : V.z );
2292
+
2293
+ // compute normal
2294
+ vec3 N = P1 * T1 + P2 * T2 + V * sqrt( max( 0.0, 1.0 - P1 * P1 - P2 * P2 ) );
2295
+
2296
+ // unstretch
2297
+ N = normalize( vec3( roughness * N.xy, max( 0.0, N.z ) ) );
2298
+
2299
+ return N;
2300
+
2301
+ }
2302
+
2303
+ // Below are PDF and related functions for use in a Monte Carlo path tracer
2304
+ // as specified in Appendix B of the following paper
2305
+ // See equation (34) from reference [0]
2306
+ float ggxLamda( float theta, float roughness ) {
2307
+
2308
+ float tanTheta = tan( theta );
2309
+ float tanTheta2 = tanTheta * tanTheta;
2310
+ float alpha2 = roughness * roughness;
2311
+
2312
+ float numerator = - 1.0 + sqrt( 1.0 + alpha2 * tanTheta2 );
2313
+ return numerator / 2.0;
2314
+
2315
+ }
2316
+
2317
+ // See equation (34) from reference [0]
2318
+ float ggxShadowMaskG1( float theta, float roughness ) {
2319
+
2320
+ return 1.0 / ( 1.0 + ggxLamda( theta, roughness ) );
2321
+
2322
+ }
2323
+
2324
+ // See equation (125) from reference [4]
2325
+ float ggxShadowMaskG2( vec3 wi, vec3 wo, float roughness ) {
2326
+
2327
+ float incidentTheta = acos( wi.z );
2328
+ float scatterTheta = acos( wo.z );
2329
+ return 1.0 / ( 1.0 + ggxLamda( incidentTheta, roughness ) + ggxLamda( scatterTheta, roughness ) );
2330
+
2331
+ }
2332
+
2333
+ // See equation (33) from reference [0]
2334
+ float ggxDistribution( vec3 halfVector, float roughness ) {
2335
+
2336
+ float a2 = roughness * roughness;
2337
+ a2 = max( EPSILON, a2 );
2338
+ float cosTheta = halfVector.z;
2339
+ float cosTheta4 = pow( cosTheta, 4.0 );
2340
+
2341
+ if ( cosTheta == 0.0 ) return 0.0;
2342
+
2343
+ float theta = acosSafe( halfVector.z );
2344
+ float tanTheta = tan( theta );
2345
+ float tanTheta2 = pow( tanTheta, 2.0 );
2346
+
2347
+ float denom = PI * cosTheta4 * pow( a2 + tanTheta2, 2.0 );
2348
+ return ( a2 / denom );
2349
+
2350
+ }
2351
+
2352
+ // See equation (3) from reference [2]
2353
+ float ggxPDF( vec3 wi, vec3 halfVector, float roughness ) {
2354
+
2355
+ float incidentTheta = acos( wi.z );
2356
+ float D = ggxDistribution( halfVector, roughness );
2357
+ float G1 = ggxShadowMaskG1( incidentTheta, roughness );
2358
+
2359
+ return D * G1 * max( 0.0, dot( wi, halfVector ) ) / wi.z;
2360
+
2361
+ }
2362
+
2363
+ `,La=`
2364
+
2365
+ // XYZ to sRGB color space
2366
+ const mat3 XYZ_TO_REC709 = mat3(
2367
+ 3.2404542, -0.9692660, 0.0556434,
2368
+ -1.5371385, 1.8760108, -0.2040259,
2369
+ -0.4985314, 0.0415560, 1.0572252
2370
+ );
2371
+
2372
+ vec3 fresnel0ToIor( vec3 fresnel0 ) {
2373
+
2374
+ vec3 sqrtF0 = sqrt( fresnel0 );
2375
+ return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
2376
+
2377
+ }
2378
+
2379
+ // Conversion FO/IOR
2380
+ vec3 iorToFresnel0( vec3 transmittedIor, float incidentIor ) {
2381
+
2382
+ return square( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
2383
+
2384
+ }
2385
+
2386
+ // ior is a value between 1.0 and 3.0. 1.0 is air interface
2387
+ float iorToFresnel0( float transmittedIor, float incidentIor ) {
2388
+
2389
+ return square( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ) );
2390
+
2391
+ }
2392
+
2393
+ // Fresnel equations for dielectric/dielectric interfaces. See https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
2394
+ vec3 evalSensitivity( float OPD, vec3 shift ) {
2395
+
2396
+ float phase = 2.0 * PI * OPD * 1.0e-9;
2397
+
2398
+ vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
2399
+ vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
2400
+ vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
2401
+
2402
+ vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - square( phase ) * var );
2403
+ xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * square( phase ) );
2404
+ xyz /= 1.0685e-7;
2405
+
2406
+ vec3 srgb = XYZ_TO_REC709 * xyz;
2407
+ return srgb;
2408
+
2409
+ }
2410
+
2411
+ // See Section 4. Analytic Spectral Integration, A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence, https://hal.archives-ouvertes.fr/hal-01518344/document
2412
+ vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
2413
+
2414
+ vec3 I;
2415
+
2416
+ // Force iridescenceIor -> outsideIOR when thinFilmThickness -> 0.0
2417
+ float iridescenceIor = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
2418
+
2419
+ // Evaluate the cosTheta on the base layer (Snell law)
2420
+ float sinTheta2Sq = square( outsideIOR / iridescenceIor ) * ( 1.0 - square( cosTheta1 ) );
2421
+
2422
+ // Handle TIR:
2423
+ float cosTheta2Sq = 1.0 - sinTheta2Sq;
2424
+ if ( cosTheta2Sq < 0.0 ) {
2425
+
2426
+ return vec3( 1.0 );
2427
+
2428
+ }
2429
+
2430
+ float cosTheta2 = sqrt( cosTheta2Sq );
2431
+
2432
+ // First interface
2433
+ float R0 = iorToFresnel0( iridescenceIor, outsideIOR );
2434
+ float R12 = schlickFresnel( cosTheta1, R0 );
2435
+ float R21 = R12;
2436
+ float T121 = 1.0 - R12;
2437
+ float phi12 = 0.0;
2438
+ if ( iridescenceIor < outsideIOR ) {
2439
+
2440
+ phi12 = PI;
2441
+
2442
+ }
2443
+
2444
+ float phi21 = PI - phi12;
2445
+
2446
+ // Second interface
2447
+ vec3 baseIOR = fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); // guard against 1.0
2448
+ vec3 R1 = iorToFresnel0( baseIOR, iridescenceIor );
2449
+ vec3 R23 = schlickFresnel( cosTheta2, R1 );
2450
+ vec3 phi23 = vec3( 0.0 );
2451
+ if ( baseIOR[0] < iridescenceIor ) {
2452
+
2453
+ phi23[ 0 ] = PI;
2454
+
2455
+ }
2456
+
2457
+ if ( baseIOR[1] < iridescenceIor ) {
2458
+
2459
+ phi23[ 1 ] = PI;
2460
+
2461
+ }
2462
+
2463
+ if ( baseIOR[2] < iridescenceIor ) {
2464
+
2465
+ phi23[ 2 ] = PI;
2466
+
2467
+ }
2468
+
2469
+ // Phase shift
2470
+ float OPD = 2.0 * iridescenceIor * thinFilmThickness * cosTheta2;
2471
+ vec3 phi = vec3( phi21 ) + phi23;
2472
+
2473
+ // Compound terms
2474
+ vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
2475
+ vec3 r123 = sqrt( R123 );
2476
+ vec3 Rs = square( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
2477
+
2478
+ // Reflectance term for m = 0 (DC term amplitude)
2479
+ vec3 C0 = R12 + Rs;
2480
+ I = C0;
2481
+
2482
+ // Reflectance term for m > 0 (pairs of diracs)
2483
+ vec3 Cm = Rs - T121;
2484
+ for ( int m = 1; m <= 2; ++ m ) {
2485
+
2486
+ Cm *= r123;
2487
+ vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
2488
+ I += Cm * Sm;
2489
+
2490
+ }
2491
+
2492
+ // Since out of gamut colors might be produced, negative color values are clamped to 0.
2493
+ return max( I, vec3( 0.0 ) );
2494
+
2495
+ }
2496
+
2497
+ `,Ha=`
2498
+
2499
+ // See equation (2) in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
2500
+ float velvetD( float cosThetaH, float roughness ) {
2501
+
2502
+ float alpha = max( roughness, 0.07 );
2503
+ alpha = alpha * alpha;
2504
+
2505
+ float invAlpha = 1.0 / alpha;
2506
+
2507
+ float sqrCosThetaH = cosThetaH * cosThetaH;
2508
+ float sinThetaH = max( 1.0 - sqrCosThetaH, 0.001 );
2509
+
2510
+ return ( 2.0 + invAlpha ) * pow( sinThetaH, 0.5 * invAlpha ) / ( 2.0 * PI );
2511
+
2512
+ }
2513
+
2514
+ float velvetParamsInterpolate( int i, float oneMinusAlphaSquared ) {
2515
+
2516
+ const float p0[5] = float[5]( 25.3245, 3.32435, 0.16801, -1.27393, -4.85967 );
2517
+ const float p1[5] = float[5]( 21.5473, 3.82987, 0.19823, -1.97760, -4.32054 );
2518
+
2519
+ return mix( p1[i], p0[i], oneMinusAlphaSquared );
2520
+
2521
+ }
2522
+
2523
+ float velvetL( float x, float alpha ) {
2524
+
2525
+ float oneMinusAlpha = 1.0 - alpha;
2526
+ float oneMinusAlphaSquared = oneMinusAlpha * oneMinusAlpha;
2527
+
2528
+ float a = velvetParamsInterpolate( 0, oneMinusAlphaSquared );
2529
+ float b = velvetParamsInterpolate( 1, oneMinusAlphaSquared );
2530
+ float c = velvetParamsInterpolate( 2, oneMinusAlphaSquared );
2531
+ float d = velvetParamsInterpolate( 3, oneMinusAlphaSquared );
2532
+ float e = velvetParamsInterpolate( 4, oneMinusAlphaSquared );
2533
+
2534
+ return a / ( 1.0 + b * pow( abs( x ), c ) ) + d * x + e;
2535
+
2536
+ }
2537
+
2538
+ // See equation (3) in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
2539
+ float velvetLambda( float cosTheta, float alpha ) {
2540
+
2541
+ return abs( cosTheta ) < 0.5 ? exp( velvetL( cosTheta, alpha ) ) : exp( 2.0 * velvetL( 0.5, alpha ) - velvetL( 1.0 - cosTheta, alpha ) );
2542
+
2543
+ }
2544
+
2545
+ // See Section 3, Shadowing Term, in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
2546
+ float velvetG( float cosThetaO, float cosThetaI, float roughness ) {
2547
+
2548
+ float alpha = max( roughness, 0.07 );
2549
+ alpha = alpha * alpha;
2550
+
2551
+ return 1.0 / ( 1.0 + velvetLambda( cosThetaO, alpha ) + velvetLambda( cosThetaI, alpha ) );
2552
+
2553
+ }
2554
+
2555
+ float directionalAlbedoSheen( float cosTheta, float alpha ) {
2556
+
2557
+ cosTheta = saturate( cosTheta );
2558
+
2559
+ float c = 1.0 - cosTheta;
2560
+ float c3 = c * c * c;
2561
+
2562
+ return 0.65584461 * c3 + 1.0 / ( 4.16526551 + exp( -7.97291361 * sqrt( alpha ) + 6.33516894 ) );
2563
+
2564
+ }
2565
+
2566
+ float sheenAlbedoScaling( vec3 wo, vec3 wi, SurfaceRecord surf ) {
2567
+
2568
+ float alpha = max( surf.sheenRoughness, 0.07 );
2569
+ alpha = alpha * alpha;
2570
+
2571
+ float maxSheenColor = max( max( surf.sheenColor.r, surf.sheenColor.g ), surf.sheenColor.b );
2572
+
2573
+ float eWo = directionalAlbedoSheen( saturateCos( wo.z ), alpha );
2574
+ float eWi = directionalAlbedoSheen( saturateCos( wi.z ), alpha );
2575
+
2576
+ return min( 1.0 - maxSheenColor * eWo, 1.0 - maxSheenColor * eWi );
2577
+
2578
+ }
2579
+
2580
+ // See Section 5, Layering, in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
2581
+ float sheenAlbedoScaling( vec3 wo, SurfaceRecord surf ) {
2582
+
2583
+ float alpha = max( surf.sheenRoughness, 0.07 );
2584
+ alpha = alpha * alpha;
2585
+
2586
+ float maxSheenColor = max( max( surf.sheenColor.r, surf.sheenColor.g ), surf.sheenColor.b );
2587
+
2588
+ float eWo = directionalAlbedoSheen( saturateCos( wo.z ), alpha );
2589
+
2590
+ return 1.0 - maxSheenColor * eWo;
2591
+
2592
+ }
2593
+
2594
+ `,Wa=`
2595
+
2596
+ #ifndef FOG_CHECK_ITERATIONS
2597
+ #define FOG_CHECK_ITERATIONS 30
2598
+ #endif
2599
+
2600
+ // returns whether the given material is a fog material or not
2601
+ bool isMaterialFogVolume( sampler2D materials, uint materialIndex ) {
2602
+
2603
+ uint i = materialIndex * uint( MATERIAL_PIXELS );
2604
+ vec4 s14 = texelFetch1D( materials, i + 14u );
2605
+ return bool( int( s14.b ) & 4 );
2606
+
2607
+ }
2608
+
2609
+ // returns true if we're within the first fog volume we hit
2610
+ bool bvhIntersectFogVolumeHit(
2611
+ vec3 rayOrigin, vec3 rayDirection,
2612
+ usampler2D materialIndexAttribute, sampler2D materials,
2613
+ inout Material material
2614
+ ) {
2615
+
2616
+ material.fogVolume = false;
2617
+
2618
+ for ( int i = 0; i < FOG_CHECK_ITERATIONS; i ++ ) {
2619
+
2620
+ // find nearest hit
2621
+ uvec4 faceIndices = uvec4( 0u );
2622
+ vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
2623
+ vec3 barycoord = vec3( 0.0 );
2624
+ float side = 1.0;
2625
+ float dist = 0.0;
2626
+ bool hit = bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist );
2627
+ if ( hit ) {
2628
+
2629
+ // if it's a fog volume return whether we hit the front or back face
2630
+ uint materialIndex = uTexelFetch1D( materialIndexAttribute, faceIndices.x ).r;
2631
+ if ( isMaterialFogVolume( materials, materialIndex ) ) {
2632
+
2633
+ material = readMaterialInfo( materials, materialIndex );
2634
+ return side == - 1.0;
2635
+
2636
+ } else {
2637
+
2638
+ // move the ray forward
2639
+ rayOrigin = stepRayOrigin( rayOrigin, rayDirection, - faceNormal, dist );
2640
+
2641
+ }
2642
+
2643
+ } else {
2644
+
2645
+ return false;
2646
+
2647
+ }
2648
+
2649
+ }
2650
+
2651
+ return false;
2652
+
2653
+ }
2654
+
2655
+ `,Va=`
2656
+
2657
+ // step through multiple surface hits and accumulate color attenuation based on transmissive surfaces
2658
+ // returns true if a solid surface was hit
2659
+ bool attenuateHit(
2660
+ RenderState state,
2661
+ Ray ray, float rayDist,
2662
+ out vec3 color
2663
+ ) {
2664
+
2665
+ // store the original bounce index so we can reset it after
2666
+ uint originalBounceIndex = sobolBounceIndex;
2667
+
2668
+ int traversals = state.traversals;
2669
+ int transmissiveTraversals = state.transmissiveTraversals;
2670
+ bool isShadowRay = state.isShadowRay;
2671
+ Material fogMaterial = state.fogMaterial;
2672
+
2673
+ vec3 startPoint = ray.origin;
2674
+
2675
+ // hit results
2676
+ SurfaceHit surfaceHit;
2677
+
2678
+ color = vec3( 1.0 );
2679
+
2680
+ bool result = true;
2681
+ for ( int i = 0; i < traversals; i ++ ) {
2682
+
2683
+ sobolBounceIndex ++;
2684
+
2685
+ int hitType = traceScene( ray, fogMaterial, surfaceHit );
2686
+
2687
+ if ( hitType == FOG_HIT ) {
2688
+
2689
+ result = true;
2690
+ break;
2691
+
2692
+ } else if ( hitType == SURFACE_HIT ) {
2693
+
2694
+ float totalDist = distance( startPoint, ray.origin + ray.direction * surfaceHit.dist );
2695
+ if ( totalDist > rayDist ) {
2696
+
2697
+ result = false;
2698
+ break;
2699
+
2700
+ }
2701
+
2702
+ // TODO: attenuate the contribution based on the PDF of the resulting ray including refraction values
2703
+ // Should be able to work using the material BSDF functions which will take into account specularity, etc.
2704
+ // TODO: should we account for emissive surfaces here?
2705
+
2706
+ uint materialIndex = uTexelFetch1D( materialIndexAttribute, surfaceHit.faceIndices.x ).r;
2707
+ Material material = readMaterialInfo( materials, materialIndex );
2708
+
2709
+ // adjust the ray to the new surface
2710
+ bool isEntering = surfaceHit.side == 1.0;
2711
+ ray.origin = stepRayOrigin( ray.origin, ray.direction, - surfaceHit.faceNormal, surfaceHit.dist );
2712
+
2713
+ #if FEATURE_FOG
2714
+
2715
+ if ( material.fogVolume ) {
2716
+
2717
+ fogMaterial = material;
2718
+ fogMaterial.fogVolume = surfaceHit.side == 1.0;
2719
+ i -= sign( transmissiveTraversals );
2720
+ transmissiveTraversals --;
2721
+ continue;
2722
+
2723
+ }
2724
+
2725
+ #endif
2726
+
2727
+ if ( ! material.castShadow && isShadowRay ) {
2728
+
2729
+ continue;
2730
+
2731
+ }
2732
+
2733
+ vec2 uv = textureSampleBarycoord( attributesArray, ATTR_UV, surfaceHit.barycoord, surfaceHit.faceIndices.xyz ).xy;
2734
+ vec4 vertexColor = textureSampleBarycoord( attributesArray, ATTR_COLOR, surfaceHit.barycoord, surfaceHit.faceIndices.xyz );
2735
+
2736
+ // albedo
2737
+ vec4 albedo = vec4( material.color, material.opacity );
2738
+ if ( material.map != - 1 ) {
2739
+
2740
+ vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
2741
+ albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
2742
+
2743
+ }
2744
+
2745
+ if ( material.vertexColors ) {
2746
+
2747
+ albedo *= vertexColor;
2748
+
2749
+ }
2750
+
2751
+ // alphaMap
2752
+ if ( material.alphaMap != - 1 ) {
2753
+
2754
+ vec3 uvPrime = material.alphaMapTransform * vec3( uv, 1 );
2755
+ albedo.a *= texture2D( textures, vec3( uvPrime.xy, material.alphaMap ) ).x;
2756
+
2757
+ }
2758
+
2759
+ // transmission
2760
+ float transmission = material.transmission;
2761
+ if ( material.transmissionMap != - 1 ) {
2762
+
2763
+ vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
2764
+ transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
2765
+
2766
+ }
2767
+
2768
+ // metalness
2769
+ float metalness = material.metalness;
2770
+ if ( material.metalnessMap != - 1 ) {
2771
+
2772
+ vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
2773
+ metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
2774
+
2775
+ }
2776
+
2777
+ float alphaTest = material.alphaTest;
2778
+ bool useAlphaTest = alphaTest != 0.0;
2779
+ float transmissionFactor = ( 1.0 - metalness ) * transmission;
2780
+ if (
2781
+ transmissionFactor < rand( 9 ) && ! (
2782
+ // material sidedness
2783
+ material.side != 0.0 && surfaceHit.side == material.side
2784
+
2785
+ // alpha test
2786
+ || useAlphaTest && albedo.a < alphaTest
2787
+
2788
+ // opacity
2789
+ || material.transparent && ! useAlphaTest && albedo.a < rand( 10 )
2790
+ )
2791
+ ) {
2792
+
2793
+ result = true;
2794
+ break;
2795
+
2796
+ }
2797
+
2798
+ if ( surfaceHit.side == 1.0 && isEntering ) {
2799
+
2800
+ // only attenuate by surface color on the way in
2801
+ color *= mix( vec3( 1.0 ), albedo.rgb, transmissionFactor );
2802
+
2803
+ } else if ( surfaceHit.side == - 1.0 ) {
2804
+
2805
+ // attenuate by medium once we hit the opposite side of the model
2806
+ color *= transmissionAttenuation( surfaceHit.dist, material.attenuationColor, material.attenuationDistance );
2807
+
2808
+ }
2809
+
2810
+ bool isTransmissiveRay = dot( ray.direction, surfaceHit.faceNormal * surfaceHit.side ) < 0.0;
2811
+ if ( ( isTransmissiveRay || isEntering ) && transmissiveTraversals > 0 ) {
2812
+
2813
+ i -= sign( transmissiveTraversals );
2814
+ transmissiveTraversals --;
2815
+
2816
+ }
2817
+
2818
+ } else {
2819
+
2820
+ result = false;
2821
+ break;
2822
+
2823
+ }
2824
+
2825
+ }
2826
+
2827
+ // reset the bounce index
2828
+ sobolBounceIndex = originalBounceIndex;
2829
+ return result;
2830
+
2831
+ }
2832
+
2833
+ `,qa=`
2834
+
2835
+ vec3 ndcToRayOrigin( vec2 coord ) {
2836
+
2837
+ vec4 rayOrigin4 = cameraWorldMatrix * invProjectionMatrix * vec4( coord, - 1.0, 1.0 );
2838
+ return rayOrigin4.xyz / rayOrigin4.w;
2839
+ }
2840
+
2841
+ Ray getCameraRay() {
2842
+
2843
+ vec2 ssd = vec2( 1.0 ) / resolution;
2844
+
2845
+ // Jitter the camera ray by finding a uv coordinate at a random sample
2846
+ // around this pixel's UV coordinate for AA
2847
+ vec2 ruv = rand2( 0 );
2848
+ vec2 jitteredUv = vUv + vec2( tentFilter( ruv.x ) * ssd.x, tentFilter( ruv.y ) * ssd.y );
2849
+ Ray ray;
2850
+
2851
+ #if CAMERA_TYPE == 2
2852
+
2853
+ // Equirectangular projection
2854
+ vec4 rayDirection4 = vec4( equirectUvToDirection( jitteredUv ), 0.0 );
2855
+ vec4 rayOrigin4 = vec4( 0.0, 0.0, 0.0, 1.0 );
2856
+
2857
+ rayDirection4 = cameraWorldMatrix * rayDirection4;
2858
+ rayOrigin4 = cameraWorldMatrix * rayOrigin4;
2859
+
2860
+ ray.direction = normalize( rayDirection4.xyz );
2861
+ ray.origin = rayOrigin4.xyz / rayOrigin4.w;
2862
+
2863
+ #else
2864
+
2865
+ // get [- 1, 1] normalized device coordinates
2866
+ vec2 ndc = 2.0 * jitteredUv - vec2( 1.0 );
2867
+ ray.origin = ndcToRayOrigin( ndc );
2868
+
2869
+ #if CAMERA_TYPE == 1
2870
+
2871
+ // Orthographic projection
2872
+ ray.direction = ( cameraWorldMatrix * vec4( 0.0, 0.0, - 1.0, 0.0 ) ).xyz;
2873
+ ray.direction = normalize( ray.direction );
2874
+
2875
+ #else
2876
+
2877
+ // Perspective projection
2878
+ ray.direction = normalize( mat3( cameraWorldMatrix ) * ( invProjectionMatrix * vec4( ndc, 0.0, 1.0 ) ).xyz );
2879
+
2880
+ #endif
2881
+
2882
+ #endif
2883
+
2884
+ #if FEATURE_DOF
2885
+ {
2886
+
2887
+ // depth of field
2888
+ vec3 focalPoint = ray.origin + normalize( ray.direction ) * physicalCamera.focusDistance;
2889
+
2890
+ // get the aperture sample
2891
+ // if blades === 0 then we assume a circle
2892
+ vec3 shapeUVW= rand3( 1 );
2893
+ int blades = physicalCamera.apertureBlades;
2894
+ float anamorphicRatio = physicalCamera.anamorphicRatio;
2895
+ vec2 apertureSample = sampleAperture( blades, shapeUVW );
2896
+ apertureSample *= physicalCamera.bokehSize * 0.5 * 1e-3;
2897
+
2898
+ // rotate the aperture shape
2899
+ apertureSample =
2900
+ rotateVector( apertureSample, physicalCamera.apertureRotation ) *
2901
+ saturate( vec2( anamorphicRatio, 1.0 / anamorphicRatio ) );
2902
+
2903
+ // create the new ray
2904
+ ray.origin += ( cameraWorldMatrix * vec4( apertureSample, 0.0, 0.0 ) ).xyz;
2905
+ ray.direction = focalPoint - ray.origin;
2906
+
2907
+ }
2908
+ #endif
2909
+
2910
+ ray.direction = normalize( ray.direction );
2911
+
2912
+ return ray;
2913
+
2914
+ }
2915
+
2916
+ `,Ga=`
2917
+
2918
+ vec3 directLightContribution( vec3 worldWo, SurfaceRecord surf, RenderState state, vec3 rayOrigin ) {
2919
+
2920
+ vec3 result = vec3( 0.0 );
2921
+
2922
+ // uniformly pick a light or environment map
2923
+ if( lightsDenom != 0.0 && rand( 5 ) < float( lights.count ) / lightsDenom ) {
2924
+
2925
+ // sample a light or environment
2926
+ LightRecord lightRec = randomLightSample( lights.tex, iesProfiles, lights.count, rayOrigin, rand3( 6 ) );
2927
+
2928
+ bool isSampleBelowSurface = ! surf.volumeParticle && dot( surf.faceNormal, lightRec.direction ) < 0.0;
2929
+ if ( isSampleBelowSurface ) {
2930
+
2931
+ lightRec.pdf = 0.0;
2932
+
2933
+ }
2934
+
2935
+ // check if a ray could even reach the light area
2936
+ Ray lightRay;
2937
+ lightRay.origin = rayOrigin;
2938
+ lightRay.direction = lightRec.direction;
2939
+ vec3 attenuatedColor;
2940
+ if (
2941
+ lightRec.pdf > 0.0 &&
2942
+ isDirectionValid( lightRec.direction, surf.normal, surf.faceNormal ) &&
2943
+ ! attenuateHit( state, lightRay, lightRec.dist, attenuatedColor )
2944
+ ) {
2945
+
2946
+ // get the material pdf
2947
+ vec3 sampleColor;
2948
+ float lightMaterialPdf = bsdfResult( worldWo, lightRec.direction, surf, sampleColor );
2949
+ bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
2950
+ if ( lightMaterialPdf > 0.0 && isValidSampleColor ) {
2951
+
2952
+ // weight the direct light contribution
2953
+ float lightPdf = lightRec.pdf / lightsDenom;
2954
+ float misWeight = lightRec.type == SPOT_LIGHT_TYPE || lightRec.type == DIR_LIGHT_TYPE || lightRec.type == POINT_LIGHT_TYPE ? 1.0 : misHeuristic( lightPdf, lightMaterialPdf );
2955
+ result = attenuatedColor * lightRec.emission * state.throughputColor * sampleColor * misWeight / lightPdf;
2956
+
2957
+ }
2958
+
2959
+ }
2960
+
2961
+ } else if ( envMapInfo.totalSum != 0.0 && environmentIntensity != 0.0 ) {
2962
+
2963
+ // find a sample in the environment map to include in the contribution
2964
+ vec3 envColor, envDirection;
2965
+ float envPdf = sampleEquirectProbability( rand2( 7 ), envColor, envDirection );
2966
+ envDirection = invEnvRotation3x3 * envDirection;
2967
+
2968
+ // this env sampling is not set up for transmissive sampling and yields overly bright
2969
+ // results so we ignore the sample in this case.
2970
+ // TODO: this should be improved but how? The env samples could traverse a few layers?
2971
+ bool isSampleBelowSurface = ! surf.volumeParticle && dot( surf.faceNormal, envDirection ) < 0.0;
2972
+ if ( isSampleBelowSurface ) {
2973
+
2974
+ envPdf = 0.0;
2975
+
2976
+ }
2977
+
2978
+ // check if a ray could even reach the surface
2979
+ Ray envRay;
2980
+ envRay.origin = rayOrigin;
2981
+ envRay.direction = envDirection;
2982
+ vec3 attenuatedColor;
2983
+ if (
2984
+ envPdf > 0.0 &&
2985
+ isDirectionValid( envDirection, surf.normal, surf.faceNormal ) &&
2986
+ ! attenuateHit( state, envRay, INFINITY, attenuatedColor )
2987
+ ) {
2988
+
2989
+ // get the material pdf
2990
+ vec3 sampleColor;
2991
+ float envMaterialPdf = bsdfResult( worldWo, envDirection, surf, sampleColor );
2992
+ bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
2993
+ if ( envMaterialPdf > 0.0 && isValidSampleColor ) {
2994
+
2995
+ // weight the direct light contribution
2996
+ envPdf /= lightsDenom;
2997
+ float misWeight = misHeuristic( envPdf, envMaterialPdf );
2998
+ result = attenuatedColor * environmentIntensity * envColor * state.throughputColor * sampleColor * misWeight / envPdf;
2999
+
3000
+ }
3001
+
3002
+ }
3003
+
3004
+ }
3005
+
3006
+ // Function changed to have a single return statement to potentially help with crashes on Mac OS.
3007
+ // See issue #470
3008
+ return result;
3009
+
3010
+ }
3011
+
3012
+ `,$a=`
3013
+
3014
+ #define SKIP_SURFACE 0
3015
+ #define HIT_SURFACE 1
3016
+ int getSurfaceRecord(
3017
+ Material material, SurfaceHit surfaceHit, sampler2DArray attributesArray,
3018
+ float accumulatedRoughness,
3019
+ inout SurfaceRecord surf
3020
+ ) {
3021
+
3022
+ if ( material.fogVolume ) {
3023
+
3024
+ vec3 normal = vec3( 0, 0, 1 );
3025
+
3026
+ SurfaceRecord fogSurface;
3027
+ fogSurface.volumeParticle = true;
3028
+ fogSurface.color = material.color;
3029
+ fogSurface.emission = material.emissiveIntensity * material.emissive;
3030
+ fogSurface.normal = normal;
3031
+ fogSurface.faceNormal = normal;
3032
+ fogSurface.clearcoatNormal = normal;
3033
+
3034
+ surf = fogSurface;
3035
+ return HIT_SURFACE;
3036
+
3037
+ }
3038
+
3039
+ // uv coord for textures
3040
+ vec2 uv = textureSampleBarycoord( attributesArray, ATTR_UV, surfaceHit.barycoord, surfaceHit.faceIndices.xyz ).xy;
3041
+ vec4 vertexColor = textureSampleBarycoord( attributesArray, ATTR_COLOR, surfaceHit.barycoord, surfaceHit.faceIndices.xyz );
3042
+
3043
+ // albedo
3044
+ vec4 albedo = vec4( material.color, material.opacity );
3045
+ if ( material.map != - 1 ) {
3046
+
3047
+ vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
3048
+ albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
3049
+
3050
+ }
3051
+
3052
+ if ( material.vertexColors ) {
3053
+
3054
+ albedo *= vertexColor;
3055
+
3056
+ }
3057
+
3058
+ // alphaMap
3059
+ if ( material.alphaMap != - 1 ) {
3060
+
3061
+ vec3 uvPrime = material.alphaMapTransform * vec3( uv, 1 );
3062
+ albedo.a *= texture2D( textures, vec3( uvPrime.xy, material.alphaMap ) ).x;
3063
+
3064
+ }
3065
+
3066
+ // possibly skip this sample if it's transparent, alpha test is enabled, or we hit the wrong material side
3067
+ // and it's single sided.
3068
+ // - alpha test is disabled when it === 0
3069
+ // - the material sidedness test is complicated because we want light to pass through the back side but still
3070
+ // be able to see the front side. This boolean checks if the side we hit is the front side on the first ray
3071
+ // and we're rendering the other then we skip it. Do the opposite on subsequent bounces to get incoming light.
3072
+ float alphaTest = material.alphaTest;
3073
+ bool useAlphaTest = alphaTest != 0.0;
3074
+ if (
3075
+ // material sidedness
3076
+ material.side != 0.0 && surfaceHit.side != material.side
3077
+
3078
+ // alpha test
3079
+ || useAlphaTest && albedo.a < alphaTest
3080
+
3081
+ // opacity
3082
+ || material.transparent && ! useAlphaTest && albedo.a < rand( 3 )
3083
+ ) {
3084
+
3085
+ return SKIP_SURFACE;
3086
+
3087
+ }
3088
+
3089
+ // fetch the interpolated smooth normal
3090
+ vec3 normal = normalize( textureSampleBarycoord(
3091
+ attributesArray,
3092
+ ATTR_NORMAL,
3093
+ surfaceHit.barycoord,
3094
+ surfaceHit.faceIndices.xyz
3095
+ ).xyz );
3096
+
3097
+ // roughness
3098
+ float roughness = material.roughness;
3099
+ if ( material.roughnessMap != - 1 ) {
3100
+
3101
+ vec3 uvPrime = material.roughnessMapTransform * vec3( uv, 1 );
3102
+ roughness *= texture2D( textures, vec3( uvPrime.xy, material.roughnessMap ) ).g;
3103
+
3104
+ }
3105
+
3106
+ // metalness
3107
+ float metalness = material.metalness;
3108
+ if ( material.metalnessMap != - 1 ) {
3109
+
3110
+ vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
3111
+ metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
3112
+
3113
+ }
3114
+
3115
+ // emission
3116
+ vec3 emission = material.emissiveIntensity * material.emissive;
3117
+ if ( material.emissiveMap != - 1 ) {
3118
+
3119
+ vec3 uvPrime = material.emissiveMapTransform * vec3( uv, 1 );
3120
+ emission *= texture2D( textures, vec3( uvPrime.xy, material.emissiveMap ) ).xyz;
3121
+
3122
+ }
3123
+
3124
+ // transmission
3125
+ float transmission = material.transmission;
3126
+ if ( material.transmissionMap != - 1 ) {
3127
+
3128
+ vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
3129
+ transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
3130
+
3131
+ }
3132
+
3133
+ // normal
3134
+ if ( material.flatShading ) {
3135
+
3136
+ // if we're rendering a flat shaded object then use the face normals - the face normal
3137
+ // is provided based on the side the ray hits the mesh so flip it to align with the
3138
+ // interpolated vertex normals.
3139
+ normal = surfaceHit.faceNormal * surfaceHit.side;
3140
+
3141
+ }
3142
+
3143
+ vec3 baseNormal = normal;
3144
+ if ( material.normalMap != - 1 ) {
3145
+
3146
+ vec4 tangentSample = textureSampleBarycoord(
3147
+ attributesArray,
3148
+ ATTR_TANGENT,
3149
+ surfaceHit.barycoord,
3150
+ surfaceHit.faceIndices.xyz
3151
+ );
3152
+
3153
+ // some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
3154
+ // resulting in NaNs and slow path tracing.
3155
+ if ( length( tangentSample.xyz ) > 0.0 ) {
3156
+
3157
+ vec3 tangent = normalize( tangentSample.xyz );
3158
+ vec3 bitangent = normalize( cross( normal, tangent ) * tangentSample.w );
3159
+ mat3 vTBN = mat3( tangent, bitangent, normal );
3160
+
3161
+ vec3 uvPrime = material.normalMapTransform * vec3( uv, 1 );
3162
+ vec3 texNormal = texture2D( textures, vec3( uvPrime.xy, material.normalMap ) ).xyz * 2.0 - 1.0;
3163
+ texNormal.xy *= material.normalScale;
3164
+ normal = vTBN * texNormal;
3165
+
3166
+ }
3167
+
3168
+ }
3169
+
3170
+ normal *= surfaceHit.side;
3171
+
3172
+ // clearcoat
3173
+ float clearcoat = material.clearcoat;
3174
+ if ( material.clearcoatMap != - 1 ) {
3175
+
3176
+ vec3 uvPrime = material.clearcoatMapTransform * vec3( uv, 1 );
3177
+ clearcoat *= texture2D( textures, vec3( uvPrime.xy, material.clearcoatMap ) ).r;
3178
+
3179
+ }
3180
+
3181
+ // clearcoatRoughness
3182
+ float clearcoatRoughness = material.clearcoatRoughness;
3183
+ if ( material.clearcoatRoughnessMap != - 1 ) {
3184
+
3185
+ vec3 uvPrime = material.clearcoatRoughnessMapTransform * vec3( uv, 1 );
3186
+ clearcoatRoughness *= texture2D( textures, vec3( uvPrime.xy, material.clearcoatRoughnessMap ) ).g;
3187
+
3188
+ }
3189
+
3190
+ // clearcoatNormal
3191
+ vec3 clearcoatNormal = baseNormal;
3192
+ if ( material.clearcoatNormalMap != - 1 ) {
3193
+
3194
+ vec4 tangentSample = textureSampleBarycoord(
3195
+ attributesArray,
3196
+ ATTR_TANGENT,
3197
+ surfaceHit.barycoord,
3198
+ surfaceHit.faceIndices.xyz
3199
+ );
3200
+
3201
+ // some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
3202
+ // resulting in NaNs and slow path tracing.
3203
+ if ( length( tangentSample.xyz ) > 0.0 ) {
3204
+
3205
+ vec3 tangent = normalize( tangentSample.xyz );
3206
+ vec3 bitangent = normalize( cross( clearcoatNormal, tangent ) * tangentSample.w );
3207
+ mat3 vTBN = mat3( tangent, bitangent, clearcoatNormal );
3208
+
3209
+ vec3 uvPrime = material.clearcoatNormalMapTransform * vec3( uv, 1 );
3210
+ vec3 texNormal = texture2D( textures, vec3( uvPrime.xy, material.clearcoatNormalMap ) ).xyz * 2.0 - 1.0;
3211
+ texNormal.xy *= material.clearcoatNormalScale;
3212
+ clearcoatNormal = vTBN * texNormal;
3213
+
3214
+ }
3215
+
3216
+ }
3217
+
3218
+ clearcoatNormal *= surfaceHit.side;
3219
+
3220
+ // sheenColor
3221
+ vec3 sheenColor = material.sheenColor;
3222
+ if ( material.sheenColorMap != - 1 ) {
3223
+
3224
+ vec3 uvPrime = material.sheenColorMapTransform * vec3( uv, 1 );
3225
+ sheenColor *= texture2D( textures, vec3( uvPrime.xy, material.sheenColorMap ) ).rgb;
3226
+
3227
+ }
3228
+
3229
+ // sheenRoughness
3230
+ float sheenRoughness = material.sheenRoughness;
3231
+ if ( material.sheenRoughnessMap != - 1 ) {
3232
+
3233
+ vec3 uvPrime = material.sheenRoughnessMapTransform * vec3( uv, 1 );
3234
+ sheenRoughness *= texture2D( textures, vec3( uvPrime.xy, material.sheenRoughnessMap ) ).a;
3235
+
3236
+ }
3237
+
3238
+ // iridescence
3239
+ float iridescence = material.iridescence;
3240
+ if ( material.iridescenceMap != - 1 ) {
3241
+
3242
+ vec3 uvPrime = material.iridescenceMapTransform * vec3( uv, 1 );
3243
+ iridescence *= texture2D( textures, vec3( uvPrime.xy, material.iridescenceMap ) ).r;
3244
+
3245
+ }
3246
+
3247
+ // iridescence thickness
3248
+ float iridescenceThickness = material.iridescenceThicknessMaximum;
3249
+ if ( material.iridescenceThicknessMap != - 1 ) {
3250
+
3251
+ vec3 uvPrime = material.iridescenceThicknessMapTransform * vec3( uv, 1 );
3252
+ float iridescenceThicknessSampled = texture2D( textures, vec3( uvPrime.xy, material.iridescenceThicknessMap ) ).g;
3253
+ iridescenceThickness = mix( material.iridescenceThicknessMinimum, material.iridescenceThicknessMaximum, iridescenceThicknessSampled );
3254
+
3255
+ }
3256
+
3257
+ iridescence = iridescenceThickness == 0.0 ? 0.0 : iridescence;
3258
+
3259
+ // specular color
3260
+ vec3 specularColor = material.specularColor;
3261
+ if ( material.specularColorMap != - 1 ) {
3262
+
3263
+ vec3 uvPrime = material.specularColorMapTransform * vec3( uv, 1 );
3264
+ specularColor *= texture2D( textures, vec3( uvPrime.xy, material.specularColorMap ) ).rgb;
3265
+
3266
+ }
3267
+
3268
+ // specular intensity
3269
+ float specularIntensity = material.specularIntensity;
3270
+ if ( material.specularIntensityMap != - 1 ) {
3271
+
3272
+ vec3 uvPrime = material.specularIntensityMapTransform * vec3( uv, 1 );
3273
+ specularIntensity *= texture2D( textures, vec3( uvPrime.xy, material.specularIntensityMap ) ).a;
3274
+
3275
+ }
3276
+
3277
+ surf.volumeParticle = false;
3278
+
3279
+ surf.faceNormal = surfaceHit.faceNormal;
3280
+ surf.normal = normal;
3281
+
3282
+ surf.metalness = metalness;
3283
+ surf.color = albedo.rgb;
3284
+ surf.emission = emission;
3285
+
3286
+ surf.ior = material.ior;
3287
+ surf.transmission = transmission;
3288
+ surf.thinFilm = material.thinFilm;
3289
+ surf.attenuationColor = material.attenuationColor;
3290
+ surf.attenuationDistance = material.attenuationDistance;
3291
+
3292
+ surf.clearcoatNormal = clearcoatNormal;
3293
+ surf.clearcoat = clearcoat;
3294
+
3295
+ surf.sheen = material.sheen;
3296
+ surf.sheenColor = sheenColor;
3297
+
3298
+ surf.iridescence = iridescence;
3299
+ surf.iridescenceIor = material.iridescenceIor;
3300
+ surf.iridescenceThickness = iridescenceThickness;
3301
+
3302
+ surf.specularColor = specularColor;
3303
+ surf.specularIntensity = specularIntensity;
3304
+
3305
+ // apply perceptual roughness factor from gltf. sheen perceptual roughness is
3306
+ // applied by its brdf function
3307
+ // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#microfacet-surfaces
3308
+ surf.roughness = roughness * roughness;
3309
+ surf.clearcoatRoughness = clearcoatRoughness * clearcoatRoughness;
3310
+ surf.sheenRoughness = sheenRoughness;
3311
+
3312
+ // frontFace is used to determine transmissive properties and PDF. If no transmission is used
3313
+ // then we can just always assume this is a front face.
3314
+ surf.frontFace = surfaceHit.side == 1.0 || transmission == 0.0;
3315
+ surf.eta = material.thinFilm || surf.frontFace ? 1.0 / material.ior : material.ior;
3316
+ surf.f0 = iorRatioToF0( surf.eta );
3317
+
3318
+ // Compute the filtered roughness value to use during specular reflection computations.
3319
+ // The accumulated roughness value is scaled by a user setting and a "magic value" of 5.0.
3320
+ // If we're exiting something transmissive then scale the factor down significantly so we can retain
3321
+ // sharp internal reflections
3322
+ surf.filteredRoughness = applyFilteredGlossy( surf.roughness, accumulatedRoughness );
3323
+ surf.filteredClearcoatRoughness = applyFilteredGlossy( surf.clearcoatRoughness, accumulatedRoughness );
3324
+
3325
+ // get the normal frames
3326
+ surf.normalBasis = getBasisFromNormal( surf.normal );
3327
+ surf.normalInvBasis = inverse( surf.normalBasis );
3328
+
3329
+ surf.clearcoatBasis = getBasisFromNormal( surf.clearcoatNormal );
3330
+ surf.clearcoatInvBasis = inverse( surf.clearcoatBasis );
3331
+
3332
+ return HIT_SURFACE;
3333
+
3334
+ }
3335
+ `,Ya=`
3336
+
3337
+ struct Ray {
3338
+
3339
+ vec3 origin;
3340
+ vec3 direction;
3341
+
3342
+ };
3343
+
3344
+ struct SurfaceHit {
3345
+
3346
+ uvec4 faceIndices;
3347
+ vec3 barycoord;
3348
+ vec3 faceNormal;
3349
+ float side;
3350
+ float dist;
3351
+
3352
+ };
3353
+
3354
+ struct RenderState {
3355
+
3356
+ bool firstRay;
3357
+ bool transmissiveRay;
3358
+ bool isShadowRay;
3359
+ float accumulatedRoughness;
3360
+ int transmissiveTraversals;
3361
+ int traversals;
3362
+ uint depth;
3363
+ vec3 throughputColor;
3364
+ Material fogMaterial;
3365
+
3366
+ };
3367
+
3368
+ RenderState initRenderState() {
3369
+
3370
+ RenderState result;
3371
+ result.firstRay = true;
3372
+ result.transmissiveRay = true;
3373
+ result.isShadowRay = false;
3374
+ result.accumulatedRoughness = 0.0;
3375
+ result.transmissiveTraversals = 0;
3376
+ result.traversals = 0;
3377
+ result.throughputColor = vec3( 1.0 );
3378
+ result.depth = 0u;
3379
+ result.fogMaterial.fogVolume = false;
3380
+ return result;
3381
+
3382
+ }
3383
+
3384
+ `,ja=`
3385
+
3386
+ #define NO_HIT 0
3387
+ #define SURFACE_HIT 1
3388
+ #define LIGHT_HIT 2
3389
+ #define FOG_HIT 3
3390
+
3391
+ // Passing the global variable 'lights' into this function caused shader program errors.
3392
+ // So global variables like 'lights' and 'bvh' were moved out of the function parameters.
3393
+ // For more information, refer to: https://github.com/gkjohnson/three-gpu-pathtracer/pull/457
3394
+ int traceScene(
3395
+ Ray ray, Material fogMaterial, inout SurfaceHit surfaceHit
3396
+ ) {
3397
+
3398
+ int result = NO_HIT;
3399
+ bool hit = bvhIntersectFirstHit( bvh, ray.origin, ray.direction, surfaceHit.faceIndices, surfaceHit.faceNormal, surfaceHit.barycoord, surfaceHit.side, surfaceHit.dist );
3400
+
3401
+ #if FEATURE_FOG
3402
+
3403
+ if ( fogMaterial.fogVolume ) {
3404
+
3405
+ // offset the distance so we don't run into issues with particles on the same surface
3406
+ // as other objects
3407
+ float particleDist = intersectFogVolume( fogMaterial, rand( 1 ) );
3408
+ if ( particleDist + RAY_OFFSET < surfaceHit.dist ) {
3409
+
3410
+ surfaceHit.side = 1.0;
3411
+ surfaceHit.faceNormal = normalize( - ray.direction );
3412
+ surfaceHit.dist = particleDist;
3413
+ return FOG_HIT;
3414
+
3415
+ }
3416
+
3417
+ }
3418
+
3419
+ #endif
3420
+
3421
+ if ( hit ) {
3422
+
3423
+ result = SURFACE_HIT;
3424
+
3425
+ }
3426
+
3427
+ return result;
3428
+
3429
+ }
3430
+
3431
+ `;class Xa extends tt{onBeforeRender(){this.setDefine("FEATURE_DOF",this.physicalCamera.bokehSize===0?0:1),this.setDefine("FEATURE_BACKGROUND_MAP",this.backgroundMap?1:0),this.setDefine("FEATURE_FOG",this.materials.features.isUsed("FOG")?1:0)}constructor(e){super({transparent:!0,depthWrite:!1,defines:{FEATURE_MIS:1,FEATURE_RUSSIAN_ROULETTE:1,FEATURE_DOF:1,FEATURE_BACKGROUND_MAP:0,FEATURE_FOG:1,RANDOM_TYPE:2,CAMERA_TYPE:0,DEBUG_MODE:0,ATTR_NORMAL:0,ATTR_TANGENT:1,ATTR_UV:2,ATTR_COLOR:3,MATERIAL_PIXELS:Ht},uniforms:{resolution:{value:new Y},opacity:{value:1},bounces:{value:10},transmissiveBounces:{value:10},filterGlossyFactor:{value:0},physicalCamera:{value:new $s},cameraWorldMatrix:{value:new $},invProjectionMatrix:{value:new $},bvh:{value:new zr},attributesArray:{value:new sa},materialIndexAttribute:{value:new Er},materials:{value:new fa},textures:{value:new dr().texture},lights:{value:new ra},iesProfiles:{value:new dr(360,180,{type:ee,wrapS:Se,wrapT:Se}).texture},environmentIntensity:{value:1},environmentRotation:{value:new $},envMapInfo:{value:new Xs},backgroundBlur:{value:0},backgroundMap:{value:null},backgroundAlpha:{value:1},backgroundIntensity:{value:1},backgroundRotation:{value:new $},seed:{value:0},sobolTexture:{value:null},stratifiedTexture:{value:new ya},stratifiedOffsetTexture:{value:new Aa(64,1)}},vertexShader:`
3432
+
3433
+ varying vec2 vUv;
3434
+ void main() {
3435
+
3436
+ vec4 mvPosition = vec4( position, 1.0 );
3437
+ mvPosition = modelViewMatrix * mvPosition;
3438
+ gl_Position = projectionMatrix * mvPosition;
3439
+
3440
+ vUv = uv;
3441
+
3442
+ }
3443
+
3444
+ `,fragmentShader:`
3445
+ #define RAY_OFFSET 1e-4
3446
+ #define INFINITY 1e20
3447
+
3448
+ precision highp isampler2D;
3449
+ precision highp usampler2D;
3450
+ precision highp sampler2DArray;
3451
+ vec4 envMapTexelToLinear( vec4 a ) { return a; }
3452
+ #include <common>
3453
+
3454
+ // bvh intersection
3455
+ ${Nr}
3456
+ ${Or}
3457
+ ${kr}
3458
+
3459
+ // uniform structs
3460
+ ${Ma}
3461
+ ${Pa}
3462
+ ${Ia}
3463
+ ${Vr}
3464
+ ${Ra}
3465
+
3466
+ // random
3467
+ #if RANDOM_TYPE == 2 // Stratified List
3468
+
3469
+ ${Na}
3470
+
3471
+ #elif RANDOM_TYPE == 1 // Sobol
3472
+
3473
+ ${bi}
3474
+ ${Wr}
3475
+ ${Ws}
3476
+
3477
+ #define rand(v) sobol(v)
3478
+ #define rand2(v) sobol2(v)
3479
+ #define rand3(v) sobol3(v)
3480
+ #define rand4(v) sobol4(v)
3481
+
3482
+ #else // PCG
3483
+
3484
+ ${bi}
3485
+
3486
+ // Using the sobol functions seems to break the the compiler on MacOS
3487
+ // - specifically the "sobolReverseBits" function.
3488
+ uint sobolPixelIndex = 0u;
3489
+ uint sobolPathIndex = 0u;
3490
+ uint sobolBounceIndex = 0u;
3491
+
3492
+ #define rand(v) pcgRand()
3493
+ #define rand2(v) pcgRand2()
3494
+ #define rand3(v) pcgRand3()
3495
+ #define rand4(v) pcgRand4()
3496
+
3497
+ #endif
3498
+
3499
+ // common
3500
+ ${za}
3501
+ ${Da}
3502
+ ${Fi}
3503
+ ${Ea}
3504
+ ${Ba}
3505
+
3506
+ // environment
3507
+ uniform EquirectHdrInfo envMapInfo;
3508
+ uniform mat4 environmentRotation;
3509
+ uniform float environmentIntensity;
3510
+
3511
+ // lighting
3512
+ uniform sampler2DArray iesProfiles;
3513
+ uniform LightsInfo lights;
3514
+
3515
+ // background
3516
+ uniform float backgroundBlur;
3517
+ uniform float backgroundAlpha;
3518
+ #if FEATURE_BACKGROUND_MAP
3519
+
3520
+ uniform sampler2D backgroundMap;
3521
+ uniform mat4 backgroundRotation;
3522
+ uniform float backgroundIntensity;
3523
+
3524
+ #endif
3525
+
3526
+ // camera
3527
+ uniform mat4 cameraWorldMatrix;
3528
+ uniform mat4 invProjectionMatrix;
3529
+ #if FEATURE_DOF
3530
+
3531
+ uniform PhysicalCamera physicalCamera;
3532
+
3533
+ #endif
3534
+
3535
+ // geometry
3536
+ uniform sampler2DArray attributesArray;
3537
+ uniform usampler2D materialIndexAttribute;
3538
+ uniform sampler2D materials;
3539
+ uniform sampler2DArray textures;
3540
+ uniform BVH bvh;
3541
+
3542
+ // path tracer
3543
+ uniform int bounces;
3544
+ uniform int transmissiveBounces;
3545
+ uniform float filterGlossyFactor;
3546
+ uniform int seed;
3547
+
3548
+ // image
3549
+ uniform vec2 resolution;
3550
+ uniform float opacity;
3551
+
3552
+ varying vec2 vUv;
3553
+
3554
+ // globals
3555
+ mat3 envRotation3x3;
3556
+ mat3 invEnvRotation3x3;
3557
+ float lightsDenom;
3558
+
3559
+ // sampling
3560
+ ${qr}
3561
+ ${Fa}
3562
+ ${Ca}
3563
+
3564
+ ${Wa}
3565
+ ${Ua}
3566
+ ${Ha}
3567
+ ${La}
3568
+ ${Oa}
3569
+ ${ka}
3570
+
3571
+ float applyFilteredGlossy( float roughness, float accumulatedRoughness ) {
3572
+
3573
+ return clamp(
3574
+ max(
3575
+ roughness,
3576
+ accumulatedRoughness * filterGlossyFactor * 5.0 ),
3577
+ 0.0,
3578
+ 1.0
3579
+ );
3580
+
3581
+ }
3582
+
3583
+ vec3 sampleBackground( vec3 direction, vec2 uv ) {
3584
+
3585
+ vec3 sampleDir = sampleHemisphere( direction, uv ) * 0.5 * backgroundBlur;
3586
+
3587
+ #if FEATURE_BACKGROUND_MAP
3588
+
3589
+ sampleDir = normalize( mat3( backgroundRotation ) * direction + sampleDir );
3590
+ return backgroundIntensity * sampleEquirectColor( backgroundMap, sampleDir );
3591
+
3592
+ #else
3593
+
3594
+ sampleDir = normalize( envRotation3x3 * direction + sampleDir );
3595
+ return environmentIntensity * sampleEquirectColor( envMapInfo.map, sampleDir );
3596
+
3597
+ #endif
3598
+
3599
+ }
3600
+
3601
+ ${Ya}
3602
+ ${qa}
3603
+ ${ja}
3604
+ ${Va}
3605
+ ${Ga}
3606
+ ${$a}
3607
+
3608
+ void main() {
3609
+
3610
+ // init
3611
+ rng_initialize( gl_FragCoord.xy, seed );
3612
+ sobolPixelIndex = ( uint( gl_FragCoord.x ) << 16 ) | uint( gl_FragCoord.y );
3613
+ sobolPathIndex = uint( seed );
3614
+
3615
+ // get camera ray
3616
+ Ray ray = getCameraRay();
3617
+
3618
+ // inverse environment rotation
3619
+ envRotation3x3 = mat3( environmentRotation );
3620
+ invEnvRotation3x3 = inverse( envRotation3x3 );
3621
+ lightsDenom =
3622
+ ( environmentIntensity == 0.0 || envMapInfo.totalSum == 0.0 ) && lights.count != 0u ?
3623
+ float( lights.count ) :
3624
+ float( lights.count + 1u );
3625
+
3626
+ // final color
3627
+ gl_FragColor = vec4( 0, 0, 0, 1 );
3628
+
3629
+ // surface results
3630
+ SurfaceHit surfaceHit;
3631
+ ScatterRecord scatterRec;
3632
+
3633
+ // path tracing state
3634
+ RenderState state = initRenderState();
3635
+ state.transmissiveTraversals = transmissiveBounces;
3636
+ #if FEATURE_FOG
3637
+
3638
+ state.fogMaterial.fogVolume = bvhIntersectFogVolumeHit(
3639
+ ray.origin, - ray.direction,
3640
+ materialIndexAttribute, materials,
3641
+ state.fogMaterial
3642
+ );
3643
+
3644
+ #endif
3645
+
3646
+ for ( int i = 0; i < bounces; i ++ ) {
3647
+
3648
+ sobolBounceIndex ++;
3649
+
3650
+ state.depth ++;
3651
+ state.traversals = bounces - i;
3652
+ state.firstRay = i == 0 && state.transmissiveTraversals == transmissiveBounces;
3653
+
3654
+ int hitType = traceScene( ray, state.fogMaterial, surfaceHit );
3655
+
3656
+ // check if we intersect any lights and accumulate the light contribution
3657
+ // TODO: we can add support for light surface rendering in the else condition if we
3658
+ // add the ability to toggle visibility of the the light
3659
+ if ( ! state.firstRay && ! state.transmissiveRay ) {
3660
+
3661
+ LightRecord lightRec;
3662
+ float lightDist = hitType == NO_HIT ? INFINITY : surfaceHit.dist;
3663
+ for ( uint i = 0u; i < lights.count; i ++ ) {
3664
+
3665
+ if (
3666
+ intersectLightAtIndex( lights.tex, ray.origin, ray.direction, i, lightRec ) &&
3667
+ lightRec.dist < lightDist
3668
+ ) {
3669
+
3670
+ #if FEATURE_MIS
3671
+
3672
+ // weight the contribution
3673
+ // NOTE: Only area lights are supported for forward sampling and can be hit
3674
+ float misWeight = misHeuristic( scatterRec.pdf, lightRec.pdf / lightsDenom );
3675
+ gl_FragColor.rgb += lightRec.emission * state.throughputColor * misWeight;
3676
+
3677
+ #else
3678
+
3679
+ gl_FragColor.rgb += lightRec.emission * state.throughputColor;
3680
+
3681
+ #endif
3682
+
3683
+ }
3684
+
3685
+ }
3686
+
3687
+ }
3688
+
3689
+ if ( hitType == NO_HIT ) {
3690
+
3691
+ if ( state.firstRay || state.transmissiveRay ) {
3692
+
3693
+ gl_FragColor.rgb += sampleBackground( ray.direction, rand2( 2 ) ) * state.throughputColor;
3694
+ gl_FragColor.a = backgroundAlpha;
3695
+
3696
+ } else {
3697
+
3698
+ #if FEATURE_MIS
3699
+
3700
+ // get the PDF of the hit envmap point
3701
+ vec3 envColor;
3702
+ float envPdf = sampleEquirect( envRotation3x3 * ray.direction, envColor );
3703
+ envPdf /= lightsDenom;
3704
+
3705
+ // and weight the contribution
3706
+ float misWeight = misHeuristic( scatterRec.pdf, envPdf );
3707
+ gl_FragColor.rgb += environmentIntensity * envColor * state.throughputColor * misWeight;
3708
+
3709
+ #else
3710
+
3711
+ gl_FragColor.rgb +=
3712
+ environmentIntensity *
3713
+ sampleEquirectColor( envMapInfo.map, envRotation3x3 * ray.direction ) *
3714
+ state.throughputColor;
3715
+
3716
+ #endif
3717
+
3718
+ }
3719
+ break;
3720
+
3721
+ }
3722
+
3723
+ uint materialIndex = uTexelFetch1D( materialIndexAttribute, surfaceHit.faceIndices.x ).r;
3724
+ Material material = readMaterialInfo( materials, materialIndex );
3725
+
3726
+ #if FEATURE_FOG
3727
+
3728
+ if ( hitType == FOG_HIT ) {
3729
+
3730
+ material = state.fogMaterial;
3731
+ state.accumulatedRoughness += 0.2;
3732
+
3733
+ } else if ( material.fogVolume ) {
3734
+
3735
+ state.fogMaterial = material;
3736
+ state.fogMaterial.fogVolume = surfaceHit.side == 1.0;
3737
+
3738
+ ray.origin = stepRayOrigin( ray.origin, ray.direction, - surfaceHit.faceNormal, surfaceHit.dist );
3739
+
3740
+ i -= sign( state.transmissiveTraversals );
3741
+ state.transmissiveTraversals -= sign( state.transmissiveTraversals );
3742
+ continue;
3743
+
3744
+ }
3745
+
3746
+ #endif
3747
+
3748
+ // early out if this is a matte material
3749
+ if ( material.matte && state.firstRay ) {
3750
+
3751
+ gl_FragColor = vec4( 0.0 );
3752
+ break;
3753
+
3754
+ }
3755
+
3756
+ // if we've determined that this is a shadow ray and we've hit an item with no shadow casting
3757
+ // then skip it
3758
+ if ( ! material.castShadow && state.isShadowRay ) {
3759
+
3760
+ ray.origin = stepRayOrigin( ray.origin, ray.direction, - surfaceHit.faceNormal, surfaceHit.dist );
3761
+ continue;
3762
+
3763
+ }
3764
+
3765
+ SurfaceRecord surf;
3766
+ if (
3767
+ getSurfaceRecord(
3768
+ material, surfaceHit, attributesArray, state.accumulatedRoughness,
3769
+ surf
3770
+ ) == SKIP_SURFACE
3771
+ ) {
3772
+
3773
+ // only allow a limited number of transparency discards otherwise we could
3774
+ // crash the context with too long a loop.
3775
+ i -= sign( state.transmissiveTraversals );
3776
+ state.transmissiveTraversals -= sign( state.transmissiveTraversals );
3777
+
3778
+ ray.origin = stepRayOrigin( ray.origin, ray.direction, - surfaceHit.faceNormal, surfaceHit.dist );
3779
+ continue;
3780
+
3781
+ }
3782
+
3783
+ scatterRec = bsdfSample( - ray.direction, surf );
3784
+ state.isShadowRay = scatterRec.specularPdf < rand( 4 );
3785
+
3786
+ bool isBelowSurface = ! surf.volumeParticle && dot( scatterRec.direction, surf.faceNormal ) < 0.0;
3787
+ vec3 hitPoint = stepRayOrigin( ray.origin, ray.direction, isBelowSurface ? - surf.faceNormal : surf.faceNormal, surfaceHit.dist );
3788
+
3789
+ // next event estimation
3790
+ #if FEATURE_MIS
3791
+
3792
+ gl_FragColor.rgb += directLightContribution( - ray.direction, surf, state, hitPoint );
3793
+
3794
+ #endif
3795
+
3796
+ // accumulate a roughness value to offset diffuse, specular, diffuse rays that have high contribution
3797
+ // to a single pixel resulting in fireflies
3798
+ // TODO: handle transmissive surfaces
3799
+ if ( ! surf.volumeParticle && ! isBelowSurface ) {
3800
+
3801
+ // determine if this is a rough normal or not by checking how far off straight up it is
3802
+ vec3 halfVector = normalize( - ray.direction + scatterRec.direction );
3803
+ state.accumulatedRoughness += max(
3804
+ sin( acosApprox( dot( halfVector, surf.normal ) ) ),
3805
+ sin( acosApprox( dot( halfVector, surf.clearcoatNormal ) ) )
3806
+ );
3807
+
3808
+ state.transmissiveRay = false;
3809
+
3810
+ }
3811
+
3812
+ // accumulate emissive color
3813
+ gl_FragColor.rgb += ( surf.emission * state.throughputColor );
3814
+
3815
+ // skip the sample if our PDF or ray is impossible
3816
+ if ( scatterRec.pdf <= 0.0 || ! isDirectionValid( scatterRec.direction, surf.normal, surf.faceNormal ) ) {
3817
+
3818
+ break;
3819
+
3820
+ }
3821
+
3822
+ // if we're bouncing around the inside a transmissive material then decrement
3823
+ // perform this separate from a bounce
3824
+ bool isTransmissiveRay = ! surf.volumeParticle && dot( scatterRec.direction, surf.faceNormal * surfaceHit.side ) < 0.0;
3825
+ if ( ( isTransmissiveRay || isBelowSurface ) && state.transmissiveTraversals > 0 ) {
3826
+
3827
+ state.transmissiveTraversals --;
3828
+ i --;
3829
+
3830
+ }
3831
+
3832
+ //
3833
+
3834
+ // handle throughput color transformation
3835
+ // attenuate the throughput color by the medium color
3836
+ if ( ! surf.frontFace ) {
3837
+
3838
+ state.throughputColor *= transmissionAttenuation( surfaceHit.dist, surf.attenuationColor, surf.attenuationDistance );
3839
+
3840
+ }
3841
+
3842
+ #if FEATURE_RUSSIAN_ROULETTE
3843
+
3844
+ // russian roulette path termination
3845
+ // https://www.arnoldrenderer.com/research/physically_based_shader_design_in_arnold.pdf
3846
+ uint minBounces = 3u;
3847
+ float depthProb = float( state.depth < minBounces );
3848
+
3849
+ float rrProb = luminance( state.throughputColor * scatterRec.color / scatterRec.pdf );
3850
+ rrProb /= luminance( state.throughputColor );
3851
+ rrProb = sqrt( rrProb );
3852
+ rrProb = max( rrProb, depthProb );
3853
+ rrProb = min( rrProb, 1.0 );
3854
+ if ( rand( 8 ) > rrProb ) {
3855
+
3856
+ break;
3857
+
3858
+ }
3859
+
3860
+ // perform sample clamping here to avoid bright pixels
3861
+ state.throughputColor *= min( 1.0 / rrProb, 20.0 );
3862
+
3863
+ #endif
3864
+
3865
+ // adjust the throughput and discard and exit if we find discard the sample if there are any NaNs
3866
+ state.throughputColor *= scatterRec.color / scatterRec.pdf;
3867
+ if ( any( isnan( state.throughputColor ) ) || any( isinf( state.throughputColor ) ) ) {
3868
+
3869
+ break;
3870
+
3871
+ }
3872
+
3873
+ //
3874
+
3875
+ // prepare for next ray
3876
+ ray.direction = scatterRec.direction;
3877
+ ray.origin = hitPoint;
3878
+
3879
+ }
3880
+
3881
+ gl_FragColor.a *= opacity;
3882
+
3883
+ #if DEBUG_MODE == 1
3884
+
3885
+ // output the number of rays checked in the path and number of
3886
+ // transmissive rays encountered.
3887
+ gl_FragColor.rgb = vec3(
3888
+ float( state.depth ),
3889
+ transmissiveBounces - state.transmissiveTraversals,
3890
+ 0.0
3891
+ );
3892
+ gl_FragColor.a = 1.0;
3893
+
3894
+ #endif
3895
+
3896
+ }
3897
+
3898
+ `}),this.setValues(e)}}function*Qa(){const{_renderer:n,_fsQuad:e,_blendQuad:t,_primaryTarget:i,_blendTargets:s,_sobolTarget:a,_subframe:r,alpha:c,material:l}=this,h=new Ze,f=new Ze,u=t.material;let[o,m]=s;for(;;){c?(u.opacity=this._opacityFactor/(this.samples+1),l.blending=Je,l.opacity=1):(l.opacity=this._opacityFactor/(this.samples+1),l.blending=Ir);const[g,x,d,b]=r,p=i.width,v=i.height;l.resolution.set(p*d,v*b),l.sobolTexture=a.texture,l.stratifiedTexture.init(20,l.bounces+l.transmissiveBounces+5),l.stratifiedTexture.next(),l.seed++;const y=this.tiles.x||1,T=this.tiles.y||1,A=y*T,w=Math.ceil(p*d),M=Math.ceil(v*b),I=Math.floor(g*p),_=Math.floor(x*v),P=Math.ceil(w/y),S=Math.ceil(M/T);for(let R=0;R<T;R++)for(let F=0;F<y;F++){const D=n.getRenderTarget(),E=n.autoClear,le=n.getScissorTest();n.getScissor(h),n.getViewport(f);let me=F,xe=R;if(!this.stableTiles){const _e=this._currentTile%(y*T);me=_e%y,xe=~~(_e/y),this._currentTile=_e+1}const Ee=T-xe-1;i.scissor.set(I+me*P,_+Ee*S,Math.min(P,w-me*P),Math.min(S,M-Ee*S)),i.viewport.set(I,_,w,M),n.setRenderTarget(i),n.setScissorTest(!0),n.autoClear=!1,e.render(n),n.setViewport(f),n.setScissor(h),n.setScissorTest(le),n.setRenderTarget(D),n.autoClear=E,c&&(u.target1=o.texture,u.target2=i.texture,n.setRenderTarget(m),t.render(n),n.setRenderTarget(D)),this.samples+=1/A,F===y-1&&R===T-1&&(this.samples=Math.round(this.samples)),yield}[o,m]=[m,o]}}const pr=new et;class gr{get material(){return this._fsQuad.material}set material(e){this._fsQuad.material.removeEventListener("recompilation",this._compileFunction),e.addEventListener("recompilation",this._compileFunction),this._fsQuad.material=e}get target(){return this._alpha?this._blendTargets[1]:this._primaryTarget}set alpha(e){this._alpha!==e&&(e||(this._blendTargets[0].dispose(),this._blendTargets[1].dispose()),this._alpha=e,this.reset())}get alpha(){return this._alpha}get isCompiling(){return!!this._compilePromise}constructor(e){this.camera=null,this.tiles=new Y(3,3),this.stableNoise=!1,this.stableTiles=!0,this.samples=0,this._subframe=new Ze(0,0,1,1),this._opacityFactor=1,this._renderer=e,this._alpha=!1,this._fsQuad=new De(new Xa),this._blendQuad=new De(new Ls),this._task=null,this._currentTile=0,this._compilePromise=null,this._sobolTarget=new qs().generate(e),this._primaryTarget=new Qe(1,1,{format:L,type:G,magFilter:N,minFilter:N}),this._blendTargets=[new Qe(1,1,{format:L,type:G,magFilter:N,minFilter:N}),new Qe(1,1,{format:L,type:G,magFilter:N,minFilter:N})],this._compileFunction=()=>{const t=this.compileMaterial(this._fsQuad._mesh);t.then(()=>{this._compilePromise===t&&(this._compilePromise=null)}),this._compilePromise=t},this.material.addEventListener("recompilation",this._compileFunction)}compileMaterial(){return this._renderer.compileAsync(this._fsQuad._mesh)}setCamera(e){const{material:t}=this;t.cameraWorldMatrix.copy(e.matrixWorld),t.invProjectionMatrix.copy(e.projectionMatrixInverse),t.physicalCamera.updateFrom(e);let i=0;e.projectionMatrix.elements[15]>0&&(i=1),e.isEquirectCamera&&(i=2),t.setDefine("CAMERA_TYPE",i),this.camera=e}setSize(e,t){e=Math.ceil(e),t=Math.ceil(t),!(this._primaryTarget.width===e&&this._primaryTarget.height===t)&&(this._primaryTarget.setSize(e,t),this._blendTargets[0].setSize(e,t),this._blendTargets[1].setSize(e,t),this.reset())}getSize(e){e.x=this._primaryTarget.width,e.y=this._primaryTarget.height}dispose(){this._primaryTarget.dispose(),this._blendTargets[0].dispose(),this._blendTargets[1].dispose(),this._sobolTarget.dispose(),this._fsQuad.dispose(),this._blendQuad.dispose(),this._task=null}reset(){const{_renderer:e,_primaryTarget:t,_blendTargets:i}=this,s=e.getRenderTarget(),a=e.getClearAlpha();e.getClearColor(pr),e.setRenderTarget(t),e.setClearColor(0,0),e.clearColor(),e.setRenderTarget(i[0]),e.setClearColor(0,0),e.clearColor(),e.setRenderTarget(i[1]),e.setClearColor(0,0),e.clearColor(),e.setClearColor(pr,a),e.setRenderTarget(s),this.samples=0,this._task=null,this.material.stratifiedTexture.stableNoise=this.stableNoise,this.stableNoise&&(this.material.seed=0,this.material.stratifiedTexture.reset())}update(){this.material.onBeforeRender(),!this.isCompiling&&(this._task||(this._task=Qa.call(this)),this._task.next())}}const Ce=new Y,vr=new Y,Ft=new un,Ct=new et;class Ka extends Z{constructor(e=512,t=512){super(new Uint16Array(e*t*4),e,t,L,ee,Ti,we,Se,oe,oe),this.generationCallback=null}update(){this.dispose(),this.needsUpdate=!0;const{data:e,width:t,height:i}=this.image;for(let s=0;s<t;s++)for(let a=0;a<i;a++){vr.set(t,i),Ce.set(s/t,a/i),Ce.x-=.5,Ce.y=1-Ce.y,Ft.theta=Ce.x*2*Math.PI,Ft.phi=Ce.y*Math.PI,Ft.radius=1,this.generationCallback(Ft,Ce,vr,Ct);const c=4*(a*t+s);e[c+0]=K.toHalfFloat(Ct.r),e[c+1]=K.toHalfFloat(Ct.g),e[c+2]=K.toHalfFloat(Ct.b),e[c+3]=K.toHalfFloat(1)}}copy(e){return super.copy(e),this.generationCallback=e.generationCallback,this}}const xr=new C;class Za extends Ka{constructor(e=512){super(e,e),this.topColor=new et().set(16777215),this.bottomColor=new et().set(0),this.exponent=2,this.generationCallback=(t,i,s,a)=>{xr.setFromSpherical(t);const r=xr.y*.5+.5;a.lerpColors(this.bottomColor,this.topColor,r**this.exponent)}}copy(e){return super.copy(e),this.topColor.copy(e.topColor),this.bottomColor.copy(e.bottomColor),this}}class Ja extends Nt{get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}constructor(e){super({uniforms:{map:{value:null},opacity:{value:1}},vertexShader:`
3899
+ varying vec2 vUv;
3900
+ void main() {
3901
+
3902
+ vUv = uv;
3903
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
3904
+
3905
+ }
3906
+ `,fragmentShader:`
3907
+ uniform sampler2D map;
3908
+ uniform float opacity;
3909
+ varying vec2 vUv;
3910
+
3911
+ vec4 clampedTexelFatch( sampler2D map, ivec2 px, int lod ) {
3912
+
3913
+ vec4 res = texelFetch( map, ivec2( px.x, px.y ), 0 );
3914
+
3915
+ #if defined( TONE_MAPPING )
3916
+
3917
+ res.xyz = toneMapping( res.xyz );
3918
+
3919
+ #endif
3920
+
3921
+ return linearToOutputTexel( res );
3922
+
3923
+ }
3924
+
3925
+ void main() {
3926
+
3927
+ vec2 size = vec2( textureSize( map, 0 ) );
3928
+ vec2 pxUv = vUv * size;
3929
+ vec2 pxCurr = floor( pxUv );
3930
+ vec2 pxFrac = fract( pxUv ) - 0.5;
3931
+ vec2 pxOffset;
3932
+ pxOffset.x = pxFrac.x > 0.0 ? 1.0 : - 1.0;
3933
+ pxOffset.y = pxFrac.y > 0.0 ? 1.0 : - 1.0;
3934
+
3935
+ vec2 pxNext = clamp( pxOffset + pxCurr, vec2( 0.0 ), size - 1.0 );
3936
+ vec2 alpha = abs( pxFrac );
3937
+
3938
+ vec4 p1 = mix(
3939
+ clampedTexelFatch( map, ivec2( pxCurr.x, pxCurr.y ), 0 ),
3940
+ clampedTexelFatch( map, ivec2( pxNext.x, pxCurr.y ), 0 ),
3941
+ alpha.x
3942
+ );
3943
+
3944
+ vec4 p2 = mix(
3945
+ clampedTexelFatch( map, ivec2( pxCurr.x, pxNext.y ), 0 ),
3946
+ clampedTexelFatch( map, ivec2( pxNext.x, pxNext.y ), 0 ),
3947
+ alpha.x
3948
+ );
3949
+
3950
+ gl_FragColor = mix( p1, p2, alpha.y );
3951
+ gl_FragColor.a *= opacity;
3952
+ #include <premultiplied_alpha_fragment>
3953
+
3954
+ }
3955
+ `}),this.setValues(e)}}class eo extends Nt{constructor(){super({uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:`
3956
+ varying vec2 vUv;
3957
+ void main() {
3958
+
3959
+ vUv = uv;
3960
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
3961
+
3962
+ }`,fragmentShader:`
3963
+ #define ENVMAP_TYPE_CUBE_UV
3964
+
3965
+ uniform samplerCube envMap;
3966
+ uniform float flipEnvMap;
3967
+ varying vec2 vUv;
3968
+
3969
+ #include <common>
3970
+ #include <cube_uv_reflection_fragment>
3971
+
3972
+ ${Fi}
3973
+
3974
+ void main() {
3975
+
3976
+ vec3 rayDirection = equirectUvToDirection( vUv );
3977
+ rayDirection.x *= flipEnvMap;
3978
+ gl_FragColor = textureCube( envMap, rayDirection );
3979
+
3980
+ }`}),this.depthWrite=!1,this.depthTest=!1}}class yr{constructor(e){this._renderer=e,this._quad=new De(new eo)}generate(e,t=null,i=null){if(!e.isCubeTexture)throw new Error("CubeToEquirectMaterial: Source can only be cube textures.");const s=e.images[0],a=this._renderer,r=this._quad;t===null&&(t=4*s.height),i===null&&(i=2*s.height);const c=new Qe(t,i,{type:G,colorSpace:s.colorSpace}),l=s.height,h=Math.log2(l)-2,f=1/l,u=1/(3*Math.max(Math.pow(2,h),112));r.material.defines.CUBEUV_MAX_MIP=`${h}.0`,r.material.defines.CUBEUV_TEXEL_WIDTH=u,r.material.defines.CUBEUV_TEXEL_HEIGHT=f,r.material.uniforms.envMap.value=e,r.material.uniforms.flipEnvMap.value=e.isRenderTargetTexture?1:-1,r.material.needsUpdate=!0;const o=a.getRenderTarget(),m=a.autoClear;a.autoClear=!0,a.setRenderTarget(c),r.render(a),a.setRenderTarget(o),a.autoClear=m;const g=new Uint16Array(t*i*4),x=new Float32Array(t*i*4);a.readRenderTargetPixels(c,0,0,t,i,x),c.dispose();for(let b=0,p=x.length;b<p;b++)g[b]=K.toHalfFloat(x[b]);const d=new Z(g,t,i,L,ee);return d.minFilter=fn,d.magFilter=oe,d.wrapS=we,d.wrapT=we,d.mapping=Ti,d.needsUpdate=!0,d}dispose(){this._quad.dispose()}}function to(n){return n.extensions.get("EXT_float_blend")}const $e=new Y;class So{get multipleImportanceSampling(){return!!this._pathTracer.material.defines.FEATURE_MIS}set multipleImportanceSampling(e){this._pathTracer.material.setDefine("FEATURE_MIS",e?1:0)}get transmissiveBounces(){return this._pathTracer.material.transmissiveBounces}set transmissiveBounces(e){this._pathTracer.material.transmissiveBounces=e}get bounces(){return this._pathTracer.material.bounces}set bounces(e){this._pathTracer.material.bounces=e}get filterGlossyFactor(){return this._pathTracer.material.filterGlossyFactor}set filterGlossyFactor(e){this._pathTracer.material.filterGlossyFactor=e}get samples(){return this._pathTracer.samples}get target(){return this._pathTracer.target}get tiles(){return this._pathTracer.tiles}get stableNoise(){return this._pathTracer.stableNoise}set stableNoise(e){this._pathTracer.stableNoise=e}get isCompiling(){return!!this._pathTracer.isCompiling}constructor(e){console.warn('WebGLPathTracer: This class has been deprecated and will be removed in a future release. Use "WebGPUPathTracer" instead.'),this._renderer=e,this._generator=new Pi,this._pathTracer=new gr(e),this._queueReset=!1,this._clock=new hn,this._compilePromise=null,this._lowResPathTracer=new gr(e),this._lowResPathTracer.tiles.set(1,1),this._quad=new De(new Ja({map:null,transparent:!0,blending:Je,premultipliedAlpha:e.getContextAttributes().premultipliedAlpha})),this._materials=null,this._previousEnvironment=null,this._previousBackground=null,this._internalBackground=null,this.renderDelay=100,this.minSamples=5,this.fadeDuration=500,this.enablePathTracing=!0,this.pausePathTracing=!1,this.dynamicLowRes=!1,this.lowResScale=.25,this.renderScale=1,this.synchronizeRenderSize=!0,this.rasterizeScene=!0,this.renderToCanvas=!0,this.textureSize=new Y(1024,1024),this.rasterizeSceneCallback=(t,i)=>{this._renderer.render(t,i)},this.renderToCanvasCallback=(t,i,s)=>{const a=i.autoClear;i.autoClear=!1,s.render(i),i.autoClear=a},this.setScene(new dn,new Mr)}setBVHWorker(e){this._generator.setBVHWorker(e)}setScene(e,t,i={}){e.updateMatrixWorld(!0),t.updateMatrixWorld();const s=this._generator;if(s.setObjects(e),this._buildAsync)return s.generateAsync(i.onProgress).then(a=>this._updateFromResults(e,t,a));{const a=s.generate();return this._updateFromResults(e,t,a)}}setSceneAsync(...e){this._buildAsync=!0;const t=this.setScene(...e);return this._buildAsync=!1,t}setCamera(e){this.camera=e,this.updateCamera()}updateCamera(){const e=this.camera;e.updateMatrixWorld(),this._pathTracer.setCamera(e),this._lowResPathTracer.setCamera(e),this.reset()}updateMaterials(){const e=this._pathTracer.material,t=this._renderer,i=this._materials,s=this.textureSize,a=ca(i);e.textures.setTextures(t,a,s.x,s.y),e.materials.updateFrom(i,a),this.reset()}updateLights(){const e=this.scene,t=this._renderer,i=this._pathTracer.material,s=la(e),a=oa(s);i.lights.updateFrom(s,a),i.iesProfiles.setTextures(t,a),this.reset()}updateEnvironment(){const e=this.scene,t=this._pathTracer.material;if(this._internalBackground&&(this._internalBackground.dispose(),this._internalBackground=null),t.backgroundBlur=e.backgroundBlurriness,t.backgroundIntensity=e.backgroundIntensity??1,t.backgroundRotation.makeRotationFromEuler(e.backgroundRotation).invert(),e.background===null)t.backgroundMap=null,t.backgroundAlpha=0;else if(e.background.isColor){this._colorBackground=this._colorBackground||new Za(16);const i=this._colorBackground;i.topColor.equals(e.background)||(i.topColor.set(e.background),i.bottomColor.set(e.background),i.update()),t.backgroundMap=i,t.backgroundAlpha=1}else if(e.background.isCubeTexture){if(e.background!==this._previousBackground){const i=new yr(this._renderer).generate(e.background);this._internalBackground=i,t.backgroundMap=i,t.backgroundAlpha=1}}else t.backgroundMap=e.background,t.backgroundAlpha=1;if(t.environmentIntensity=e.environment!==null?e.environmentIntensity??1:0,t.environmentRotation.makeRotationFromEuler(e.environmentRotation).invert(),this._previousEnvironment!==e.environment&&e.environment!==null)if(e.environment.isCubeTexture){const i=new yr(this._renderer).generate(e.environment);t.envMapInfo.updateFrom(i)}else t.envMapInfo.updateFrom(e.environment);this._previousEnvironment=e.environment,this._previousBackground=e.background,this.reset()}_updateFromResults(e,t,i){const{materials:s,geometry:a,bvh:r,bvhChanged:c,needsMaterialIndexUpdate:l}=i;this._materials=s;const f=this._pathTracer.material;return c&&(f.bvh.updateFrom(r),f.attributesArray.updateFrom(a.attributes.normal,a.attributes.tangent,a.attributes.uv,a.attributes.color)),l&&f.materialIndexAttribute.updateFrom(a.attributes.materialIndex),this._previousScene=e,this.scene=e,this.camera=t,this.updateCamera(),this.updateMaterials(),this.updateEnvironment(),this.updateLights(),i}renderSample(){const e=this._lowResPathTracer,t=this._pathTracer,i=this._renderer,s=this._clock,a=this._quad;this._updateScale(),this._queueReset&&(t.reset(),e.reset(),this._queueReset=!1,a.material.opacity=0,s.start());const r=s.getDelta()*1e3,c=s.getElapsedTime()*1e3;if(!this.pausePathTracing&&this.enablePathTracing&&this.renderDelay<=c&&!this.isCompiling&&t.update(),t.alpha=t.material.backgroundAlpha!==1||!to(i),e.alpha=t.alpha,this.renderToCanvas){const l=this._renderer,h=this.minSamples;if(c>=this.renderDelay&&this.samples>=this.minSamples&&(this.fadeDuration!==0?a.material.opacity=Math.min(a.material.opacity+r/this.fadeDuration,1):a.material.opacity=1),!this.enablePathTracing||this.samples<h||a.material.opacity<1){if(this.dynamicLowRes&&!this.isCompiling){e.samples<1&&(e.material=t.material,e.update());const f=a.material.opacity;a.material.opacity=1-a.material.opacity,a.material.map=e.target.texture,a.render(l),a.material.opacity=f}(!this.dynamicLowRes&&this.rasterizeScene||this.dynamicLowRes&&this.isCompiling)&&this.rasterizeSceneCallback(this.scene,this.camera)}this.enablePathTracing&&a.material.opacity>0&&(a.material.opacity<1&&(a.material.blending=this.dynamicLowRes?mn:Ir),a.material.map=t.target.texture,this.renderToCanvasCallback(t.target,l,a),a.material.blending=Je)}}reset(){this._queueReset=!0,this._pathTracer.samples=0}dispose(){this._quad.dispose(),this._quad.material.dispose(),this._pathTracer.dispose()}_updateScale(){if(this.synchronizeRenderSize){this._renderer.getDrawingBufferSize($e);const e=Math.floor(this.renderScale*$e.x),t=Math.floor(this.renderScale*$e.y);if(this._pathTracer.getSize($e),$e.x!==e||$e.y!==t){const i=this.lowResScale;this._pathTracer.setSize(e,t),this._lowResPathTracer.setSize(Math.floor(e*i),Math.floor(t*i))}}}getRenderTime(){return this._clock.getElapsedTime()*1e3}}class _o extends pn{constructor(){super(),this.isEquirectCamera=!0}}class Ao extends gn{constructor(...e){super(...e),this.iesMap=null,this.radius=0}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this.radius=e.radius,this}}class Mo extends vn{constructor(...e){super(...e),this.isCircular=!1}copy(e,t){return super.copy(e,t),this.isCircular=e.isCircular,this}}class io extends tt{constructor(){super({uniforms:{envMap:{value:null},blur:{value:0}},vertexShader:`
3981
+
3982
+ varying vec2 vUv;
3983
+ void main() {
3984
+ vUv = uv;
3985
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
3986
+ }
3987
+
3988
+ `,fragmentShader:`
3989
+
3990
+ #include <common>
3991
+ #include <cube_uv_reflection_fragment>
3992
+
3993
+ ${Fi}
3994
+
3995
+ uniform sampler2D envMap;
3996
+ uniform float blur;
3997
+ varying vec2 vUv;
3998
+ void main() {
3999
+
4000
+ vec3 rayDirection = equirectUvToDirection( vUv );
4001
+ gl_FragColor = textureCubeUV( envMap, rayDirection, blur );
4002
+
4003
+ }
4004
+
4005
+ `})}}class Io{constructor(e){this.renderer=e,this.pmremGenerator=new xn(e),this.copyQuad=new De(new io),this.renderTarget=new Qe(1,1,{type:G,format:L})}dispose(){this.pmremGenerator.dispose(),this.copyQuad.dispose(),this.renderTarget.dispose()}generate(e,t){const{pmremGenerator:i,renderTarget:s,copyQuad:a,renderer:r}=this,c=i.fromEquirectangular(e),{width:l,height:h}=e.image;s.setSize(l,h),a.material.envMap=c.texture,a.material.blur=t;const f=r.getRenderTarget(),u=r.autoClear;r.setRenderTarget(s),r.autoClear=!0,a.render(r),r.setRenderTarget(f),r.autoClear=u;const o=new Uint16Array(l*h*4),m=new Float32Array(l*h*4);r.readRenderTargetPixels(s,0,0,l,h,m);for(let x=0,d=m.length;x<d;x++)o[x]=K.toHalfFloat(m[x]);const g=new Z(o,l,h,L,ee);return g.minFilter=e.minFilter,g.magFilter=e.magFilter,g.wrapS=e.wrapS,g.wrapT=e.wrapT,g.mapping=Ti,g.needsUpdate=!0,c.dispose(),g}}class Po extends tt{constructor(e){super({blending:Je,transparent:!1,depthWrite:!1,depthTest:!1,defines:{USE_SLIDER:0},uniforms:{sigma:{value:5},threshold:{value:.03},kSigma:{value:1},map:{value:null},opacity:{value:1}},vertexShader:`
4006
+
4007
+ varying vec2 vUv;
4008
+
4009
+ void main() {
4010
+
4011
+ vUv = uv;
4012
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
4013
+
4014
+ }
4015
+
4016
+ `,fragmentShader:`
4017
+
4018
+ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4019
+ // Copyright (c) 2018-2019 Michele Morrone
4020
+ // All rights reserved.
4021
+ //
4022
+ // https://michelemorrone.eu - https://BrutPitt.com
4023
+ //
4024
+ // me@michelemorrone.eu - brutpitt@gmail.com
4025
+ // twitter: @BrutPitt - github: BrutPitt
4026
+ //
4027
+ // https://github.com/BrutPitt/glslSmartDeNoise/
4028
+ //
4029
+ // This software is distributed under the terms of the BSD 2-Clause license
4030
+ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4031
+
4032
+ uniform sampler2D map;
4033
+
4034
+ uniform float sigma;
4035
+ uniform float threshold;
4036
+ uniform float kSigma;
4037
+ uniform float opacity;
4038
+
4039
+ varying vec2 vUv;
4040
+
4041
+ #define INV_SQRT_OF_2PI 0.39894228040143267793994605993439
4042
+ #define INV_PI 0.31830988618379067153776752674503
4043
+
4044
+ // Parameters:
4045
+ // sampler2D tex - sampler image / texture
4046
+ // vec2 uv - actual fragment coord
4047
+ // float sigma > 0 - sigma Standard Deviation
4048
+ // float kSigma >= 0 - sigma coefficient
4049
+ // kSigma * sigma --> radius of the circular kernel
4050
+ // float threshold - edge sharpening threshold
4051
+ vec4 smartDeNoise( sampler2D tex, vec2 uv, float sigma, float kSigma, float threshold ) {
4052
+
4053
+ float radius = round( kSigma * sigma );
4054
+ float radQ = radius * radius;
4055
+
4056
+ float invSigmaQx2 = 0.5 / ( sigma * sigma );
4057
+ float invSigmaQx2PI = INV_PI * invSigmaQx2;
4058
+
4059
+ float invThresholdSqx2 = 0.5 / ( threshold * threshold );
4060
+ float invThresholdSqrt2PI = INV_SQRT_OF_2PI / threshold;
4061
+
4062
+ vec4 centrPx = texture2D( tex, uv );
4063
+ centrPx.rgb *= centrPx.a;
4064
+
4065
+ float zBuff = 0.0;
4066
+ vec4 aBuff = vec4( 0.0 );
4067
+ vec2 size = vec2( textureSize( tex, 0 ) );
4068
+
4069
+ vec2 d;
4070
+ for ( d.x = - radius; d.x <= radius; d.x ++ ) {
4071
+
4072
+ float pt = sqrt( radQ - d.x * d.x );
4073
+
4074
+ for ( d.y = - pt; d.y <= pt; d.y ++ ) {
4075
+
4076
+ float blurFactor = exp( - dot( d, d ) * invSigmaQx2 ) * invSigmaQx2PI;
4077
+
4078
+ vec4 walkPx = texture2D( tex, uv + d / size );
4079
+ walkPx.rgb *= walkPx.a;
4080
+
4081
+ vec4 dC = walkPx - centrPx;
4082
+ float deltaFactor = exp( - dot( dC.rgba, dC.rgba ) * invThresholdSqx2 ) * invThresholdSqrt2PI * blurFactor;
4083
+
4084
+ zBuff += deltaFactor;
4085
+ aBuff += deltaFactor * walkPx;
4086
+
4087
+ }
4088
+
4089
+ }
4090
+
4091
+ return aBuff / zBuff;
4092
+
4093
+ }
4094
+
4095
+ void main() {
4096
+
4097
+ gl_FragColor = smartDeNoise( map, vec2( vUv.x, vUv.y ), sigma, kSigma, threshold );
4098
+ #include <tonemapping_fragment>
4099
+ #include <colorspace_fragment>
4100
+ #include <premultiplied_alpha_fragment>
4101
+
4102
+ gl_FragColor.a *= opacity;
4103
+
4104
+ }
4105
+
4106
+ `}),this.setValues(e)}}class Ro extends yn{constructor(e){super(e),this.isFogVolumeMaterial=!0,this.density=.015,this.emissive=new et,this.emissiveIntensity=0,this.opacity=.15,this.transparent=!0,this.roughness=1,this.metalness=0,this.setValues(e)}}class Fo extends tt{get normalMap(){return this.uniforms.normalMap.value}set normalMap(e){this.uniforms.normalMap.value=e,this.setDefine("USE_NORMALMAP",e?null:"")}get normalMapType(){return Ei}set normalMapType(e){if(e!==Ei)throw new Error("AmbientOcclusionMaterial: Only tangent space normal map are supported")}constructor(e){super({defines:{SAMPLES:10,MATERIAL_PIXELS:Ht},uniforms:{bvh:{value:new zr},radius:{value:1},seed:{value:0},normalMap:{value:null},normalScale:{value:new Y(1,1)}},vertexShader:`
4107
+
4108
+ varying vec3 vNorm;
4109
+ varying vec3 vPos;
4110
+
4111
+ #if defined( USE_NORMALMAP ) && defined( USE_TANGENT )
4112
+
4113
+ varying vec2 vUv;
4114
+ varying vec4 vTan;
4115
+
4116
+ #endif
4117
+
4118
+ void main() {
4119
+
4120
+ vec4 mvPosition = vec4( position, 1.0 );
4121
+ mvPosition = modelViewMatrix * mvPosition;
4122
+ gl_Position = projectionMatrix * mvPosition;
4123
+
4124
+ mat3 modelNormalMatrix = transpose( inverse( mat3( modelMatrix ) ) );
4125
+ vNorm = normalize( modelNormalMatrix * normal );
4126
+ vPos = ( modelMatrix * vec4( position, 1.0 ) ).xyz;
4127
+
4128
+ #if defined( USE_NORMALMAP ) && defined( USE_TANGENT )
4129
+
4130
+ vUv = uv;
4131
+ vTan = tangent;
4132
+
4133
+ #endif
4134
+
4135
+ }
4136
+
4137
+ `,fragmentShader:`
4138
+ #define RAY_OFFSET 1e-4
4139
+
4140
+ precision highp isampler2D;
4141
+ precision highp usampler2D;
4142
+ precision highp sampler2DArray;
4143
+ #include <common>
4144
+ #include <cube_uv_reflection_fragment>
4145
+
4146
+ // bvh
4147
+ ${Nr}
4148
+ ${Or}
4149
+ ${kr}
4150
+
4151
+ // uniform structs
4152
+ ${Vr}
4153
+
4154
+ // rand
4155
+ ${bi}
4156
+
4157
+ // common
4158
+ ${qr}
4159
+
4160
+ uniform BVH bvh;
4161
+ uniform int seed;
4162
+ uniform float radius;
4163
+
4164
+ varying vec3 vNorm;
4165
+ varying vec3 vPos;
4166
+
4167
+ #if defined(USE_NORMALMAP) && defined(USE_TANGENT)
4168
+
4169
+ uniform sampler2D normalMap;
4170
+ uniform vec2 normalScale;
4171
+ varying vec2 vUv;
4172
+ varying vec4 vTan;
4173
+
4174
+ #endif
4175
+
4176
+ void main() {
4177
+
4178
+ rng_initialize( gl_FragCoord.xy, seed );
4179
+
4180
+ // compute the flat face surface normal
4181
+ vec3 fdx = vec3( dFdx( vPos.x ), dFdx( vPos.y ), dFdx( vPos.z ) );
4182
+ vec3 fdy = vec3( dFdy( vPos.x ), dFdy( vPos.y ), dFdy( vPos.z ) );
4183
+ vec3 faceNormal = normalize( cross( fdx, fdy ) );
4184
+
4185
+ // find the max component to scale the offset to account for floating point error
4186
+ vec3 absPoint = abs( vPos );
4187
+ float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
4188
+ vec3 normal = vNorm;
4189
+
4190
+ #if defined( USE_NORMALMAP ) && defined( USE_TANGENT )
4191
+
4192
+ // some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
4193
+ // resulting in NaNs and slow path tracing.
4194
+ if ( length( vTan.xyz ) > 0.0 ) {
4195
+
4196
+ vec2 uv = vUv;
4197
+ vec3 tangent = normalize( vTan.xyz );
4198
+ vec3 bitangent = normalize( cross( normal, tangent ) * vTan.w );
4199
+ mat3 vTBN = mat3( tangent, bitangent, normal );
4200
+
4201
+ vec3 texNormal = texture2D( normalMap, uv ).xyz * 2.0 - 1.0;
4202
+ texNormal.xy *= normalScale;
4203
+ normal = vTBN * texNormal;
4204
+
4205
+ }
4206
+
4207
+ #endif
4208
+
4209
+ normal *= gl_FrontFacing ? 1.0 : - 1.0;
4210
+
4211
+ vec3 rayOrigin = vPos + faceNormal * ( maxPoint + 1.0 ) * RAY_OFFSET;
4212
+ float accumulated = 0.0;
4213
+ for ( int i = 0; i < SAMPLES; i ++ ) {
4214
+
4215
+ // sample the cosine weighted hemisphere and discard the sample if it's below
4216
+ // the geometric surface
4217
+ vec3 rayDirection = sampleHemisphere( normalize( normal ), pcgRand4().xy );
4218
+
4219
+ // check if we hit the mesh and its within the specified radius
4220
+ float side = 1.0;
4221
+ float dist = 0.0;
4222
+ vec3 barycoord = vec3( 0.0 );
4223
+ vec3 outNormal = vec3( 0.0 );
4224
+ uvec4 faceIndices = uvec4( 0u );
4225
+
4226
+ // if the ray is above the geometry surface, and it doesn't hit another surface within the specified radius then
4227
+ // we consider it lit
4228
+ if (
4229
+ dot( rayDirection, faceNormal ) > 0.0 &&
4230
+ (
4231
+ ! bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, outNormal, barycoord, side, dist ) ||
4232
+ dist >= radius
4233
+ )
4234
+ ) {
4235
+
4236
+ accumulated += 1.0;
4237
+
4238
+ }
4239
+
4240
+ }
4241
+
4242
+ gl_FragColor.rgb = vec3( accumulated / float( SAMPLES ) );
4243
+ gl_FragColor.a = 1.0;
4244
+
4245
+ }
4246
+
4247
+ `}),this.setValues(e)}}export{Fo as AmbientOcclusionMaterial,Io as BlurredEnvMapGenerator,Po as DenoiseMaterial,To as DynamicPathTracingSceneGenerator,_o as EquirectCamera,Ro as FogVolumeMaterial,Za as GradientEquirectTexture,gr as PathTracingRenderer,Pi as PathTracingSceneGenerator,wo as PathTracingSceneWorker,Gs as PhysicalCamera,Xa as PhysicalPathTracingMaterial,Ao as PhysicalSpotLight,Ka as ProceduralEquirectTexture,Mo as ShapedAreaLight,So as WebGLPathTracer};