@zephyr3d/scene 0.9.26 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (506) hide show
  1. package/README.md +60 -27
  2. package/dist/animation/animation_bank.js +634 -0
  3. package/dist/animation/animation_bank.js.map +1 -0
  4. package/dist/animation/animation_bank_gpu.js +256 -0
  5. package/dist/animation/animation_bank_gpu.js.map +1 -0
  6. package/dist/animation/animationset.js +146 -30
  7. package/dist/animation/animationset.js.map +1 -1
  8. package/dist/animation/cloth/gpu_cloth_component.js +406 -0
  9. package/dist/animation/cloth/gpu_cloth_component.js.map +1 -0
  10. package/dist/animation/cloth/gpu_cloth_system.js +332 -202
  11. package/dist/animation/cloth/gpu_cloth_system.js.map +1 -1
  12. package/dist/animation/gpu_animation_driver.js +289 -0
  13. package/dist/animation/gpu_animation_driver.js.map +1 -0
  14. package/dist/animation/joint_dynamics/collision.js +112 -1
  15. package/dist/animation/joint_dynamics/collision.js.map +1 -1
  16. package/dist/animation/joint_dynamics/controller.js +6 -0
  17. package/dist/animation/joint_dynamics/controller.js.map +1 -1
  18. package/dist/animation/joint_dynamics/joint_dynamics_system.js +11 -0
  19. package/dist/animation/joint_dynamics/joint_dynamics_system.js.map +1 -1
  20. package/dist/animation/joint_dynamics/solver.js +50 -12
  21. package/dist/animation/joint_dynamics/solver.js.map +1 -1
  22. package/dist/animation/joint_dynamics/types.js.map +1 -1
  23. package/dist/animation/skeleton.js +300 -56
  24. package/dist/animation/skeleton.js.map +1 -1
  25. package/dist/animation/skin_palette_atlas.js +252 -0
  26. package/dist/animation/skin_palette_atlas.js.map +1 -0
  27. package/dist/animation/spring/multi_chain_spring_system.js +298 -38
  28. package/dist/animation/spring/multi_chain_spring_system.js.map +1 -1
  29. package/dist/animation/spring/spring_chain.js +2 -0
  30. package/dist/animation/spring/spring_chain.js.map +1 -1
  31. package/dist/animation/spring/spring_collider.js +159 -21
  32. package/dist/animation/spring/spring_collider.js.map +1 -1
  33. package/dist/animation/spring/spring_particle.js +1 -0
  34. package/dist/animation/spring/spring_particle.js.map +1 -1
  35. package/dist/animation/spring/spring_solver.js +173 -0
  36. package/dist/animation/spring/spring_solver.js.map +1 -0
  37. package/dist/animation/spring/spring_system.js +249 -24
  38. package/dist/animation/spring/spring_system.js.map +1 -1
  39. package/dist/animation/spring_modifier.js +32 -1
  40. package/dist/animation/spring_modifier.js.map +1 -1
  41. package/dist/app/app.js +26 -0
  42. package/dist/app/app.js.map +1 -1
  43. package/dist/app/engine.js +86 -15
  44. package/dist/app/engine.js.map +1 -1
  45. package/dist/app/gamepad.js +191 -0
  46. package/dist/app/gamepad.js.map +1 -0
  47. package/dist/app/inputactions.js +271 -0
  48. package/dist/app/inputactions.js.map +1 -0
  49. package/dist/app/inputmgr.js +331 -22
  50. package/dist/app/inputmgr.js.map +1 -1
  51. package/dist/app/loading.js +138 -0
  52. package/dist/app/loading.js.map +1 -0
  53. package/dist/app/pipelinecache.js +209 -0
  54. package/dist/app/pipelinecache.js.map +1 -0
  55. package/dist/app/runtimescript.js +25 -0
  56. package/dist/app/runtimescript.js.map +1 -1
  57. package/dist/app/scriptingsystem.js +54 -0
  58. package/dist/app/scriptingsystem.js.map +1 -1
  59. package/dist/app/scriptregistry.js +7 -2
  60. package/dist/app/scriptregistry.js.map +1 -1
  61. package/dist/asset/asset_manifest.js +59 -0
  62. package/dist/asset/asset_manifest.js.map +1 -0
  63. package/dist/asset/asset_preload.js +258 -0
  64. package/dist/asset/asset_preload.js.map +1 -0
  65. package/dist/asset/assetmanager.js +117 -65
  66. package/dist/asset/assetmanager.js.map +1 -1
  67. package/dist/asset/loaders/ktx2/basis/LICENSE +201 -0
  68. package/dist/asset/loaders/ktx2/basis/basis_transcoder.js +2 -0
  69. package/dist/asset/loaders/ktx2/basis/basis_transcoder.wasm +0 -0
  70. package/dist/asset/loaders/ktx2/basis_location.js +17 -0
  71. package/dist/asset/loaders/ktx2/basis_location.js.map +1 -0
  72. package/dist/asset/loaders/ktx2/ktx2_loader.js +88 -0
  73. package/dist/asset/loaders/ktx2/ktx2_loader.js.map +1 -0
  74. package/dist/asset/loaders/ktx2/ktx2_targets.js +118 -0
  75. package/dist/asset/loaders/ktx2/ktx2_targets.js.map +1 -0
  76. package/dist/asset/loaders/ktx2/transcoder_pool.js +259 -0
  77. package/dist/asset/loaders/ktx2/transcoder_pool.js.map +1 -0
  78. package/dist/asset/mesh_lod_builder.js +104 -0
  79. package/dist/asset/mesh_lod_builder.js.map +1 -0
  80. package/dist/asset/mesh_settings.js +111 -0
  81. package/dist/asset/mesh_settings.js.map +1 -0
  82. package/dist/asset/meshopt_decoder.js +18 -0
  83. package/dist/asset/meshopt_decoder.js.map +1 -0
  84. package/dist/asset/meshopt_simplifier.js +26 -0
  85. package/dist/asset/meshopt_simplifier.js.map +1 -0
  86. package/dist/asset/model.js +177 -3
  87. package/dist/asset/model.js.map +1 -1
  88. package/dist/asset/texture_settings.js +231 -0
  89. package/dist/asset/texture_settings.js.map +1 -0
  90. package/dist/asset/zmsh_binary.js +131 -0
  91. package/dist/asset/zmsh_binary.js.map +1 -0
  92. package/dist/asset/zsdf_binary.js +111 -0
  93. package/dist/asset/zsdf_binary.js.map +1 -0
  94. package/dist/blitter/bilateralblur.js +1 -2
  95. package/dist/blitter/bilateralblur.js.map +1 -1
  96. package/dist/blitter/gaussianblur.js +1 -6
  97. package/dist/blitter/gaussianblur.js.map +1 -1
  98. package/dist/camera/base.js +31 -10
  99. package/dist/camera/base.js.map +1 -1
  100. package/dist/camera/camera.js +178 -200
  101. package/dist/camera/camera.js.map +1 -1
  102. package/dist/camera/follow.js +342 -0
  103. package/dist/camera/follow.js.map +1 -0
  104. package/dist/camera/fps.js +9 -7
  105. package/dist/camera/fps.js.map +1 -1
  106. package/dist/camera/orbit.js +46 -19
  107. package/dist/camera/orbit.js.map +1 -1
  108. package/dist/index.d.ts +30475 -19865
  109. package/dist/index.js +67 -12
  110. package/dist/index.js.map +1 -1
  111. package/dist/material/blinn.js +3 -0
  112. package/dist/material/blinn.js.map +1 -1
  113. package/dist/material/eye.js +1 -1
  114. package/dist/material/eye.js.map +1 -1
  115. package/dist/material/hair.js +2 -3
  116. package/dist/material/hair.js.map +1 -1
  117. package/dist/material/hairstrand.js +235 -235
  118. package/dist/material/hairstrand.js.map +1 -1
  119. package/dist/material/lambert.js +4 -1
  120. package/dist/material/lambert.js.map +1 -1
  121. package/dist/material/material.js +362 -300
  122. package/dist/material/material.js.map +1 -1
  123. package/dist/material/meshmaterial.js +118 -45
  124. package/dist/material/meshmaterial.js.map +1 -1
  125. package/dist/material/mixins/lightmodel/blinnphong.js +1 -1
  126. package/dist/material/mixins/lightmodel/blinnphong.js.map +1 -1
  127. package/dist/material/mixins/lightmodel/lambert.js +1 -1
  128. package/dist/material/mixins/lightmodel/lambert.js.map +1 -1
  129. package/dist/material/mixins/lightmodel/pbrblueprintmixin.js +34 -61
  130. package/dist/material/mixins/lightmodel/pbrblueprintmixin.js.map +1 -1
  131. package/dist/material/mixins/lightmodel/pbrmetallicroughness.js +16 -2
  132. package/dist/material/mixins/lightmodel/pbrmetallicroughness.js.map +1 -1
  133. package/dist/material/mixins/lightmodel/pbrspecularglossness.js +2 -1
  134. package/dist/material/mixins/lightmodel/pbrspecularglossness.js.map +1 -1
  135. package/dist/material/mixins/lit.js +223 -83
  136. package/dist/material/mixins/lit.js.map +1 -1
  137. package/dist/material/mixins/pbr/common.js +31 -206
  138. package/dist/material/mixins/pbr/common.js.map +1 -1
  139. package/dist/material/mtoon.js +1 -1
  140. package/dist/material/mtoon.js.map +1 -1
  141. package/dist/material/pbrmr.js +3 -0
  142. package/dist/material/pbrmr.js.map +1 -1
  143. package/dist/material/pbrsg.js +3 -0
  144. package/dist/material/pbrsg.js.map +1 -1
  145. package/dist/material/sdf_debug.js +78 -0
  146. package/dist/material/sdf_debug.js.map +1 -0
  147. package/dist/material/shader/helper.js +733 -190
  148. package/dist/material/shader/helper.js.map +1 -1
  149. package/dist/material/shader/terrain_blend.js +204 -43
  150. package/dist/material/shader/terrain_blend.js.map +1 -1
  151. package/dist/material/skin.js +331 -297
  152. package/dist/material/skin.js.map +1 -1
  153. package/dist/material/skinprofile.js +1058 -0
  154. package/dist/material/skinprofile.js.map +1 -0
  155. package/dist/material/sss.js +353 -0
  156. package/dist/material/sss.js.map +1 -0
  157. package/dist/material/sss_kernel.js +265 -0
  158. package/dist/material/sss_kernel.js.map +1 -0
  159. package/dist/material/sssprofile.js +879 -0
  160. package/dist/material/sssprofile.js.map +1 -0
  161. package/dist/material/subsurfaceprofile.js +4 -8
  162. package/dist/material/subsurfaceprofile.js.map +1 -1
  163. package/dist/material/terrain-cm.js +464 -188
  164. package/dist/material/terrain-cm.js.map +1 -1
  165. package/dist/material/unlit.js +3 -0
  166. package/dist/material/unlit.js.map +1 -1
  167. package/dist/material/water.js +2009 -201
  168. package/dist/material/water.js.map +1 -1
  169. package/dist/node_modules/meshoptimizer/LICENSE +21 -0
  170. package/dist/node_modules/meshoptimizer/meshopt_decoder.js +197 -0
  171. package/dist/node_modules/meshoptimizer/meshopt_decoder.js.map +1 -0
  172. package/dist/node_modules/meshoptimizer/meshopt_simplifier.js +677 -0
  173. package/dist/node_modules/meshoptimizer/meshopt_simplifier.js.map +1 -0
  174. package/dist/physics/character.js +226 -0
  175. package/dist/physics/character.js.map +1 -0
  176. package/dist/physics/collider.js +209 -0
  177. package/dist/physics/collider.js.map +1 -0
  178. package/dist/physics/events.js +79 -0
  179. package/dist/physics/events.js.map +1 -0
  180. package/dist/physics/joint.js +272 -0
  181. package/dist/physics/joint.js.map +1 -0
  182. package/dist/physics/node_physics.js +234 -0
  183. package/dist/physics/node_physics.js.map +1 -0
  184. package/dist/physics/part.js +91 -0
  185. package/dist/physics/part.js.map +1 -0
  186. package/dist/physics/rigid_body.js +379 -0
  187. package/dist/physics/rigid_body.js.map +1 -0
  188. package/dist/physics/vehicle.js +335 -0
  189. package/dist/physics/vehicle.js.map +1 -0
  190. package/dist/physics/world.js +25 -0
  191. package/dist/physics/world.js.map +1 -0
  192. package/dist/posteffect/bloom.js +49 -14
  193. package/dist/posteffect/bloom.js.map +1 -1
  194. package/dist/posteffect/motionblur.js +668 -63
  195. package/dist/posteffect/motionblur.js.map +1 -1
  196. package/dist/posteffect/posteffect.js +12 -1
  197. package/dist/posteffect/posteffect.js.map +1 -1
  198. package/dist/posteffect/postsss.js +572 -0
  199. package/dist/posteffect/postsss.js.map +1 -0
  200. package/dist/posteffect/sao.js +48 -50
  201. package/dist/posteffect/sao.js.map +1 -1
  202. package/dist/posteffect/skinsss.js +605 -355
  203. package/dist/posteffect/skinsss.js.map +1 -1
  204. package/dist/posteffect/ssgi.js +91 -162
  205. package/dist/posteffect/ssgi.js.map +1 -1
  206. package/dist/posteffect/ssr.js +3 -11
  207. package/dist/posteffect/ssr.js.map +1 -1
  208. package/dist/posteffect/sss.js +34 -15
  209. package/dist/posteffect/sss.js.map +1 -1
  210. package/dist/posteffect/taa.js +1 -0
  211. package/dist/posteffect/taa.js.map +1 -1
  212. package/dist/render/abuffer_oit.js +40 -39
  213. package/dist/render/abuffer_oit.js.map +1 -1
  214. package/dist/render/clipmap.js +328 -62
  215. package/dist/render/clipmap.js.map +1 -1
  216. package/dist/render/cluster_light.js +958 -224
  217. package/dist/render/cluster_light.js.map +1 -1
  218. package/dist/render/cull_visitor.js +26 -5
  219. package/dist/render/cull_visitor.js.map +1 -1
  220. package/dist/render/debug_views.js +37 -0
  221. package/dist/render/debug_views.js.map +1 -0
  222. package/dist/render/depthpass.js +5 -1
  223. package/dist/render/depthpass.js.map +1 -1
  224. package/dist/render/drawable_mixin.js +53 -6
  225. package/dist/render/drawable_mixin.js.map +1 -1
  226. package/dist/render/dualdepthpeeling_oit.js +53 -53
  227. package/dist/render/dualdepthpeeling_oit.js.map +1 -1
  228. package/dist/render/envlight.js +196 -113
  229. package/dist/render/envlight.js.map +1 -1
  230. package/dist/render/fbm_wavegenerator.js +8 -13
  231. package/dist/render/fbm_wavegenerator.js.map +1 -1
  232. package/dist/render/fft_wavegenerator.js +268 -136
  233. package/dist/render/fft_wavegenerator.js.map +1 -1
  234. package/dist/render/gerstner_wavegenerator.js +113 -28
  235. package/dist/render/gerstner_wavegenerator.js.map +1 -1
  236. package/dist/render/gi/probe_volume.js +1334 -0
  237. package/dist/render/gi/probe_volume.js.map +1 -0
  238. package/dist/render/gi/scene_gi.js +282 -0
  239. package/dist/render/gi/scene_gi.js.map +1 -0
  240. package/dist/render/gi/voxel_atlas.js +198 -0
  241. package/dist/render/gi/voxel_atlas.js.map +1 -0
  242. package/dist/render/gi/voxel_lighting.js +652 -0
  243. package/dist/render/gi/voxel_lighting.js.map +1 -0
  244. package/dist/render/gi/voxel_scene.js +642 -0
  245. package/dist/render/gi/voxel_scene.js.map +1 -0
  246. package/dist/render/gi/voxelize_pass.js +223 -0
  247. package/dist/render/gi/voxelize_pass.js.map +1 -0
  248. package/dist/render/globalbindgroup_allocator.js +3 -2
  249. package/dist/render/globalbindgroup_allocator.js.map +1 -1
  250. package/dist/render/gpu_picking.js +9 -36
  251. package/dist/render/gpu_picking.js.map +1 -1
  252. package/dist/render/hzb.js +80 -22
  253. package/dist/render/hzb.js.map +1 -1
  254. package/dist/render/instance_culling.js +499 -0
  255. package/dist/render/instance_culling.js.map +1 -0
  256. package/dist/render/lightpass.js +23 -9
  257. package/dist/render/lightpass.js.map +1 -1
  258. package/dist/render/lod.js +46 -0
  259. package/dist/render/lod.js.map +1 -0
  260. package/dist/render/oit.js +11 -11
  261. package/dist/render/oit.js.map +1 -1
  262. package/dist/render/primitive.js +301 -9
  263. package/dist/render/primitive.js.map +1 -1
  264. package/dist/render/primitive_readback.js +209 -0
  265. package/dist/render/primitive_readback.js.map +1 -0
  266. package/dist/render/render_queue.js +198 -11
  267. package/dist/render/render_queue.js.map +1 -1
  268. package/dist/render/renderer.js +14 -7
  269. package/dist/render/renderer.js.map +1 -1
  270. package/dist/render/rendergraph/blackboard.js +15 -1
  271. package/dist/render/rendergraph/blackboard.js.map +1 -1
  272. package/dist/render/rendergraph/executor.js +136 -0
  273. package/dist/render/rendergraph/executor.js.map +1 -1
  274. package/dist/render/rendergraph/forward_plus_builder.js +585 -59
  275. package/dist/render/rendergraph/forward_plus_builder.js.map +1 -1
  276. package/dist/render/rendergraph/frame_resource_requirements.js +1 -0
  277. package/dist/render/rendergraph/frame_resource_requirements.js.map +1 -1
  278. package/dist/render/rendergraph/history_resources.js +8 -1
  279. package/dist/render/rendergraph/history_resources.js.map +1 -1
  280. package/dist/render/rendergraph/scene_render_context.js +31 -2
  281. package/dist/render/rendergraph/scene_render_context.js.map +1 -1
  282. package/dist/render/rendergraph/types.js.map +1 -1
  283. package/dist/render/renderpass.js +28 -5
  284. package/dist/render/renderpass.js.map +1 -1
  285. package/dist/render/sdf/box_allocator.js +98 -0
  286. package/dist/render/sdf/box_allocator.js.map +1 -0
  287. package/dist/render/sdf/global_sdf.js +865 -0
  288. package/dist/render/sdf/global_sdf.js.map +1 -0
  289. package/dist/render/sdf/scene_sdf.js +562 -0
  290. package/dist/render/sdf/scene_sdf.js.map +1 -0
  291. package/dist/render/sdf/sdf_atlas.js +227 -0
  292. package/dist/render/sdf/sdf_atlas.js.map +1 -0
  293. package/dist/render/sdf/sdf_programs.js +42 -0
  294. package/dist/render/sdf/sdf_programs.js.map +1 -0
  295. package/dist/render/sdf/sdf_view.js +199 -0
  296. package/dist/render/sdf/sdf_view.js.map +1 -0
  297. package/dist/render/sdf/waterline.js +610 -0
  298. package/dist/render/sdf/waterline.js.map +1 -0
  299. package/dist/render/shadow_mask_pass.js +142 -25
  300. package/dist/render/shadow_mask_pass.js.map +1 -1
  301. package/dist/render/shore_wave_generator.js +1193 -0
  302. package/dist/render/shore_wave_generator.js.map +1 -0
  303. package/dist/render/sky.js +516 -86
  304. package/dist/render/sky.js.map +1 -1
  305. package/dist/render/transmission_thickness_pass.js +477 -0
  306. package/dist/render/transmission_thickness_pass.js.map +1 -0
  307. package/dist/render/underwater.js +524 -0
  308. package/dist/render/underwater.js.map +1 -0
  309. package/dist/render/virtualtexture/virtual_texture.js +1214 -0
  310. package/dist/render/virtualtexture/virtual_texture.js.map +1 -0
  311. package/dist/render/volumetric_cloud/cloud_common.js +472 -0
  312. package/dist/render/volumetric_cloud/cloud_common.js.map +1 -0
  313. package/dist/render/volumetric_cloud/cloud_noise.js +189 -0
  314. package/dist/render/volumetric_cloud/cloud_noise.js.map +1 -0
  315. package/dist/render/volumetric_cloud/debug_view.js +131 -0
  316. package/dist/render/volumetric_cloud/debug_view.js.map +1 -0
  317. package/dist/render/volumetric_cloud/resources.js +380 -0
  318. package/dist/render/volumetric_cloud/resources.js.map +1 -0
  319. package/dist/render/volumetric_cloud/sky_cache.js +380 -0
  320. package/dist/render/volumetric_cloud/sky_cache.js.map +1 -0
  321. package/dist/render/volumetric_cloud/volumetric_cloud.js +318 -0
  322. package/dist/render/volumetric_cloud/volumetric_cloud.js.map +1 -0
  323. package/dist/render/water_caustics.js +1195 -0
  324. package/dist/render/water_caustics.js.map +1 -0
  325. package/dist/render/water_foam.js +627 -0
  326. package/dist/render/water_foam.js.map +1 -0
  327. package/dist/render/water_interaction.js +1795 -0
  328. package/dist/render/water_interaction.js.map +1 -0
  329. package/dist/render/weightedblended_oit.js +36 -36
  330. package/dist/render/weightedblended_oit.js.map +1 -1
  331. package/dist/scene/basesprite.js +9 -4
  332. package/dist/scene/basesprite.js.map +1 -1
  333. package/dist/scene/batchgroup.js +108 -12
  334. package/dist/scene/batchgroup.js.map +1 -1
  335. package/dist/scene/environment.js +28 -7
  336. package/dist/scene/environment.js.map +1 -1
  337. package/dist/scene/foliage.js +1020 -0
  338. package/dist/scene/foliage.js.map +1 -0
  339. package/dist/scene/foliage_buckets.js +147 -0
  340. package/dist/scene/foliage_buckets.js.map +1 -0
  341. package/dist/scene/foliage_mask.js +358 -0
  342. package/dist/scene/foliage_mask.js.map +1 -0
  343. package/dist/scene/hair.js +15 -4
  344. package/dist/scene/hair.js.map +1 -1
  345. package/dist/scene/light.js +179 -13
  346. package/dist/scene/light.js.map +1 -1
  347. package/dist/scene/mesh.js +327 -45
  348. package/dist/scene/mesh.js.map +1 -1
  349. package/dist/scene/meshdrawable.js +6 -0
  350. package/dist/scene/meshdrawable.js.map +1 -1
  351. package/dist/scene/msdftext.js +9 -3
  352. package/dist/scene/msdftext.js.map +1 -1
  353. package/dist/scene/msdftextsprite.js +9 -3
  354. package/dist/scene/msdftextsprite.js.map +1 -1
  355. package/dist/scene/particlesys.js +8 -2
  356. package/dist/scene/particlesys.js.map +1 -1
  357. package/dist/scene/physics_settings.js +157 -0
  358. package/dist/scene/physics_settings.js.map +1 -0
  359. package/dist/scene/scene.js +190 -44
  360. package/dist/scene/scene.js.map +1 -1
  361. package/dist/scene/scene_node.js +147 -6
  362. package/dist/scene/scene_node.js.map +1 -1
  363. package/dist/scene/terrain-cm/bladegrassmaterial.js +735 -0
  364. package/dist/scene/terrain-cm/bladegrassmaterial.js.map +1 -0
  365. package/dist/scene/terrain-cm/grass.js +881 -42
  366. package/dist/scene/terrain-cm/grass.js.map +1 -1
  367. package/dist/scene/terrain-cm/grass_gpu.js +929 -0
  368. package/dist/scene/terrain-cm/grass_gpu.js.map +1 -0
  369. package/dist/scene/terrain-cm/grassmaterial.js +180 -9
  370. package/dist/scene/terrain-cm/grassmaterial.js.map +1 -1
  371. package/dist/scene/terrain-cm/terrain-cm.js +465 -36
  372. package/dist/scene/terrain-cm/terrain-cm.js.map +1 -1
  373. package/dist/scene/terrain-cm/terrain_gi_albedo.js +257 -0
  374. package/dist/scene/terrain-cm/terrain_gi_albedo.js.map +1 -0
  375. package/dist/scene/terrain-cm/terrain_rvt.js +395 -0
  376. package/dist/scene/terrain-cm/terrain_rvt.js.map +1 -0
  377. package/dist/scene/update_queue.js +54 -0
  378. package/dist/scene/update_queue.js.map +1 -0
  379. package/dist/scene/water.js +997 -96
  380. package/dist/scene/water.js.map +1 -1
  381. package/dist/scene/water_surface_sampler.js +324 -0
  382. package/dist/scene/water_surface_sampler.js.map +1 -0
  383. package/dist/scene/wind.js +317 -0
  384. package/dist/scene/wind.js.map +1 -0
  385. package/dist/shaders/atmosphere.js +388 -166
  386. package/dist/shaders/atmosphere.js.map +1 -1
  387. package/dist/shaders/fog.js +100 -32
  388. package/dist/shaders/fog.js.map +1 -1
  389. package/dist/shaders/gi.js +365 -0
  390. package/dist/shaders/gi.js.map +1 -0
  391. package/dist/shaders/ltc_rect.js +202 -0
  392. package/dist/shaders/ltc_rect.js.map +1 -0
  393. package/dist/shaders/misc.js +1 -10
  394. package/dist/shaders/misc.js.map +1 -1
  395. package/dist/shaders/noise.js +5 -1
  396. package/dist/shaders/noise.js.map +1 -1
  397. package/dist/shaders/probes.js +309 -0
  398. package/dist/shaders/probes.js.map +1 -0
  399. package/dist/shaders/sdf.js +537 -0
  400. package/dist/shaders/sdf.js.map +1 -0
  401. package/dist/shaders/shadow.js +104 -70
  402. package/dist/shaders/shadow.js.map +1 -1
  403. package/dist/shaders/skin_brdf.js +243 -0
  404. package/dist/shaders/skin_brdf.js.map +1 -0
  405. package/dist/shaders/ssr.js +6 -159
  406. package/dist/shaders/ssr.js.map +1 -1
  407. package/dist/shaders/temporal.js +38 -27
  408. package/dist/shaders/temporal.js.map +1 -1
  409. package/dist/shaders/water.js +40 -87
  410. package/dist/shaders/water.js.map +1 -1
  411. package/dist/shaders/water_medium.js +42 -0
  412. package/dist/shaders/water_medium.js.map +1 -0
  413. package/dist/shadow/dom.js +110 -19
  414. package/dist/shadow/dom.js.map +1 -1
  415. package/dist/shadow/esm.js +3 -3
  416. package/dist/shadow/esm.js.map +1 -1
  417. package/dist/shadow/pcf_opt.js +15 -48
  418. package/dist/shadow/pcf_opt.js.map +1 -1
  419. package/dist/shadow/pcf_pd.js +15 -53
  420. package/dist/shadow/pcf_pd.js.map +1 -1
  421. package/dist/shadow/pcss.js +34 -9
  422. package/dist/shadow/pcss.js.map +1 -1
  423. package/dist/shadow/shadow_impl.js +3 -8
  424. package/dist/shadow/shadow_impl.js.map +1 -1
  425. package/dist/shadow/shadow_region.js +87 -49
  426. package/dist/shadow/shadow_region.js.map +1 -1
  427. package/dist/shadow/shadowmapper.js +93 -53
  428. package/dist/shadow/shadowmapper.js.map +1 -1
  429. package/dist/shadow/ssm.js +18 -72
  430. package/dist/shadow/ssm.js.map +1 -1
  431. package/dist/shadow/vsm.js +3 -3
  432. package/dist/shadow/vsm.js.map +1 -1
  433. package/dist/shapes/shape.js +44 -1
  434. package/dist/shapes/shape.js.map +1 -1
  435. package/dist/utility/buoyancy.js +287 -0
  436. package/dist/utility/buoyancy.js.map +1 -0
  437. package/dist/utility/physical.js +10 -1
  438. package/dist/utility/physical.js.map +1 -1
  439. package/dist/utility/pmrem.js +17 -43
  440. package/dist/utility/pmrem.js.map +1 -1
  441. package/dist/utility/sdf/bake.js +435 -0
  442. package/dist/utility/sdf/bake.js.map +1 -0
  443. package/dist/utility/sdf/bvh.js +576 -0
  444. package/dist/utility/sdf/bvh.js.map +1 -0
  445. package/dist/utility/serialization/manager.js +36 -6
  446. package/dist/utility/serialization/manager.js.map +1 -1
  447. package/dist/utility/serialization/scene/animation.js +77 -7
  448. package/dist/utility/serialization/scene/animation.js.map +1 -1
  449. package/dist/utility/serialization/scene/batch.js +11 -4
  450. package/dist/utility/serialization/scene/batch.js.map +1 -1
  451. package/dist/utility/serialization/scene/camera.js +140 -279
  452. package/dist/utility/serialization/scene/camera.js.map +1 -1
  453. package/dist/utility/serialization/scene/cloth.js +25 -0
  454. package/dist/utility/serialization/scene/cloth.js.map +1 -0
  455. package/dist/utility/serialization/scene/common.js +14 -6
  456. package/dist/utility/serialization/scene/common.js.map +1 -1
  457. package/dist/utility/serialization/scene/foliage.js +821 -0
  458. package/dist/utility/serialization/scene/foliage.js.map +1 -0
  459. package/dist/utility/serialization/scene/hair.js +11 -4
  460. package/dist/utility/serialization/scene/hair.js.map +1 -1
  461. package/dist/utility/serialization/scene/light.js +115 -7
  462. package/dist/utility/serialization/scene/light.js.map +1 -1
  463. package/dist/utility/serialization/scene/material.js +388 -220
  464. package/dist/utility/serialization/scene/material.js.map +1 -1
  465. package/dist/utility/serialization/scene/mesh.js +69 -4
  466. package/dist/utility/serialization/scene/mesh.js.map +1 -1
  467. package/dist/utility/serialization/scene/node.js +140 -5
  468. package/dist/utility/serialization/scene/node.js.map +1 -1
  469. package/dist/utility/serialization/scene/node_physics.js +1318 -0
  470. package/dist/utility/serialization/scene/node_physics.js.map +1 -0
  471. package/dist/utility/serialization/scene/particle.js +11 -4
  472. package/dist/utility/serialization/scene/particle.js.map +1 -1
  473. package/dist/utility/serialization/scene/physics.js +120 -0
  474. package/dist/utility/serialization/scene/physics.js.map +1 -0
  475. package/dist/utility/serialization/scene/primitive.js +124 -10
  476. package/dist/utility/serialization/scene/primitive.js.map +1 -1
  477. package/dist/utility/serialization/scene/scene.js +1687 -51
  478. package/dist/utility/serialization/scene/scene.js.map +1 -1
  479. package/dist/utility/serialization/scene/sprite.js +11 -4
  480. package/dist/utility/serialization/scene/sprite.js.map +1 -1
  481. package/dist/utility/serialization/scene/terrain.js +163 -33
  482. package/dist/utility/serialization/scene/terrain.js.map +1 -1
  483. package/dist/utility/serialization/scene/text.js +11 -4
  484. package/dist/utility/serialization/scene/text.js.map +1 -1
  485. package/dist/utility/serialization/scene/water.js +2473 -114
  486. package/dist/utility/serialization/scene/water.js.map +1 -1
  487. package/dist/utility/serialization/types.js.map +1 -1
  488. package/dist/utility/shprojector.js +97 -109
  489. package/dist/utility/shprojector.js.map +1 -1
  490. package/dist/utility/textures/foam.js +170 -0
  491. package/dist/utility/textures/foam.js.map +1 -0
  492. package/dist/utility/textures/ggxlut.js +17 -43
  493. package/dist/utility/textures/ggxlut.js.map +1 -1
  494. package/dist/utility/textures/ltcdata.js +4 -4
  495. package/dist/utility/textures/ltcdata.js.map +1 -1
  496. package/dist/utility/textures/ltclut.js +16 -6
  497. package/dist/utility/textures/ltclut.js.map +1 -1
  498. package/dist/utility/unsupported.js +24 -0
  499. package/dist/utility/unsupported.js.map +1 -0
  500. package/dist/values.js +13 -1
  501. package/dist/values.js.map +1 -1
  502. package/package.json +25 -12
  503. package/src/asset/loaders/ktx2/basis/LICENSE +201 -0
  504. package/src/asset/loaders/ktx2/basis/basis_transcoder.js +2 -0
  505. package/src/asset/loaders/ktx2/basis/basis_transcoder.wasm +0 -0
  506. package/src/asset/meshoptimizer/LICENSE +21 -0
@@ -1,91 +1,379 @@
1
1
  import { applyMaterialMixins, MeshMaterial } from './meshmaterial.js';
2
- import { MaterialVaryingFlags } from '../values.js';
2
+ import { InteractiveWaveGenerator } from '../render/water_interaction.js';
3
+ import { ShoreWaveGenerator } from '../render/shore_wave_generator.js';
4
+ import { WaterFoamField, FoamFieldWaveGenerator, WaveFoamSource } from '../render/water_foam.js';
5
+ import { MaterialVaryingFlags, LIGHT_TYPE_RECT, LIGHT_TYPE_DIRECTIONAL } from '../values.js';
3
6
  import { ShaderHelper } from './shader/helper.js';
4
- import { Interpolator, DWeakRef, Vector4, DRef, Vector3 } from '@zephyr3d/base';
7
+ import { Vector4, Vector3, DRef } from '@zephyr3d/base';
5
8
  import { screenSpaceRayTracing_HiZ, screenSpaceRayTracing_Linear2D } from '../shaders/ssr.js';
6
9
  import { fetchSampler } from '../utility/misc.js';
10
+ import { PHYSICAL_BAKE_EXPOSURE } from '../utility/physical.js';
7
11
  import { mixinLight } from './mixins/lit.js';
8
12
  import { fresnelSchlick, distributionGGX, visGGX } from '../shaders/pbr.js';
9
- import { getDevice } from '../app/api.js';
13
+ import { waterScatterPhase } from '../shaders/water_medium.js';
14
+ import { evaluateLTCRectLightTerms } from '../shaders/ltc_rect.js';
15
+ import { getLTCMatLUT, getLTCAmpLUT } from '../utility/textures/ltclut.js';
16
+ import { sampleFoamTexture, foamTexelSize, getDefaultFoamTexture } from '../utility/textures/foam.js';
17
+ import { RenderGraphExecutor } from '../render/rendergraph/executor.js';
10
18
 
19
+ /** Label/value pairs for {@link WaterDebugOutput}, for editor enumerations. */ const WATER_DEBUG_OUTPUTS = [
20
+ {
21
+ label: 'None',
22
+ value: 'none'
23
+ },
24
+ {
25
+ label: 'Normal',
26
+ value: 'normal'
27
+ },
28
+ {
29
+ label: 'Foam',
30
+ value: 'foam'
31
+ },
32
+ {
33
+ label: 'Water depth',
34
+ value: 'waterDepth'
35
+ },
36
+ {
37
+ label: 'Fresnel',
38
+ value: 'fresnel'
39
+ },
40
+ {
41
+ label: 'Reflection',
42
+ value: 'reflection'
43
+ },
44
+ {
45
+ label: 'Refraction',
46
+ value: 'refraction'
47
+ },
48
+ {
49
+ label: 'Absorption',
50
+ value: 'absorption'
51
+ },
52
+ {
53
+ label: 'Scattering',
54
+ value: 'scattering'
55
+ },
56
+ {
57
+ label: 'Sun scattering',
58
+ value: 'sunScattering'
59
+ },
60
+ {
61
+ label: 'Shadow',
62
+ value: 'shadow'
63
+ },
64
+ {
65
+ label: 'Subsurface',
66
+ value: 'subsurface'
67
+ },
68
+ {
69
+ label: 'Subsurface thickness',
70
+ value: 'subsurfaceThickness'
71
+ },
72
+ {
73
+ label: 'Specular',
74
+ value: 'specular'
75
+ },
76
+ {
77
+ label: 'Depth',
78
+ value: 'depth'
79
+ },
80
+ {
81
+ label: 'Interaction',
82
+ value: 'interaction'
83
+ },
84
+ {
85
+ label: 'Foam field',
86
+ value: 'foamField'
87
+ },
88
+ {
89
+ label: 'Shore regions (geometry)',
90
+ value: 'shoreRegions'
91
+ },
92
+ {
93
+ label: 'Shore field levels',
94
+ value: 'shoreLevels'
95
+ },
96
+ {
97
+ label: 'Swash handover (RGB)',
98
+ value: 'swashHandover'
99
+ },
100
+ {
101
+ label: 'Swash foam sources (RGB)',
102
+ value: 'swashFoamSources'
103
+ },
104
+ {
105
+ label: 'Swash foam cuts (RGB)',
106
+ value: 'swashFoamCuts'
107
+ },
108
+ {
109
+ label: 'Swash visibility (RGB)',
110
+ value: 'swashVisibility'
111
+ },
112
+ {
113
+ label: 'Swash ground support (RGB)',
114
+ value: 'swashGroundSupport'
115
+ }
116
+ ];
117
+ /** Fresnel reflectance of water at normal incidence, n = 1.333. */ const WATER_F0 = 0.02;
118
+ /** Specular roughness with the waves resolved. */ const WATER_BASE_ROUGHNESS = 0.04;
119
+ /** Specular roughness once distance has flattened the wave normals. */ const WATER_DISTANT_ROUGHNESS = 0.35;
120
+ /**
121
+ * Slope variance of a wind-driven sea for the mean Fresnel of the slopes
122
+ * distance flattens out of the normals, from the clean-surface fit of Cox &
123
+ * Munk, "Measurement of the roughness of the sea surface from photographs of
124
+ * the sun's glitter" (JOSA 44(11), 1954): upwind sigma_u^2 = 3.16e-3 U and
125
+ * crosswind sigma_c^2 = 0.003 + 1.92e-3 U, U the wind speed in m/s.
126
+ */ const COX_MUNK_UPWIND = 3.16e-3;
127
+ const COX_MUNK_CROSSWIND_BASE = 0.003;
128
+ const COX_MUNK_CROSSWIND = 1.92e-3;
129
+ /**
130
+ * Roughness over which the sky reflection hands over from the sharp baked sky
131
+ * to the environment's GGX-prefiltered radiance map, as Crest picks its
132
+ * reflection mip by roughness.
133
+ */ const SKY_PREFILTER_START = 0.06;
134
+ const SKY_PREFILTER_FULL = 0.15;
135
+ /** Wrap of the foam's diffuse lighting, `(N.L + w) / (1 + w)`. At 0 a lee slope is unlit. */ const FOAM_LIGHT_WRAP = 0.5;
136
+ /**
137
+ * Share of the edge fade width over which the foam on a thin sheet fades: the
138
+ * foam outlasts the water it floats on, down to the last centimetre or so.
139
+ */ const FOAM_EDGE_FADE_SHARE = 0.2;
140
+ /** Index of refraction of water. Must match the caustics pass. */ const WATER_IOR = 1.333;
141
+ const AIR_TO_WATER_ETA = 1 / WATER_IOR;
142
+ const WATER_TO_AIR_ETA = WATER_IOR;
143
+ /** Cap on the refracted path, as a multiple of the straight-line distance. */ const REFRACT_MAX_PATH_RATIO = 4;
144
+ /** Steps of the refracted-ray march over {@link REFRACT_MAX_PATH_RATIO}. */ const REFRACT_MARCH_STEPS = 24;
145
+ /** Depth tolerance, in meters, for a march step to count as a hit. */ const REFRACT_MARCH_THICKNESS = 0.05;
146
+ /**
147
+ * Fraction of the far plane an infinite surface is pulled in to. Must stay
148
+ * below 1: the cleared depth value is tested for by equality.
149
+ */ const INFINITE_DEPTH_PULLIN = 0.99;
150
+ /** Minimum reflection y for the sky bake lookup; its lower hemisphere is black. */ const HORIZON_REFLECT_BIAS = 0.08;
151
+ /** UV width of the band the refraction offset fades over at the screen border. */ const REFRACT_EDGE_FADE = 0.06;
152
+ /** Normalized depth at or above which the scene behind the water is sky. */ const SCENE_SKY_DEPTH01 = 0.999;
153
+ /** Medium path, in meters, through water with only sky behind it: deep enough to absorb everything. */ const SKY_MEDIUM_PATH = 1e4;
154
+ /** Floor on the subsurface term's sun-alignment factor. */ const SSS_SUN_ALIGN_FLOOR = 0.15;
155
+ /** Floor on the subsurface term's grazing-view factor. */ const SSS_GRAZING_FLOOR = 0.1;
156
+ /** Softplus width of the crest gate, as a fraction of the crest height. */ const SSS_HEIGHT_SOFTNESS = 0.6;
157
+ /** Least crest height the gate is worked out over, in metres. See {@link WaterMaterial.subsurfaceCrestHeight}. */ const SSS_CREST_HEIGHT_MIN = 0.05;
158
+ /** Floor on the crest gate's path length. */ const SSS_CREST_PATH_FLOOR = 0.2;
159
+ /** Extinction multiplier of the crest gate over a unit path. */ const SSS_ABSORPTION_SCALE = 3;
160
+ /**
161
+ * Mean cosine of one scattering event. Real sea water is near 0.9, at which
162
+ * almost nothing returns to a camera looking down.
163
+ */ const DEFAULT_SCATTER_ANISOTROPY = 0.7;
164
+ /** Floor on the refracted sun ray's descent; only reached by a sun below the horizon. */ const MIN_SUN_SLOPE = 0.05;
165
+ /** Refraction blur per meter of path from geometry alone, in mip widths. */ const REFRACT_BLUR_GEOMETRIC = 0.02;
166
+ /** Maps the scattering coefficient (1/m) onto refraction blur mip widths per meter. */ const REFRACT_BLUR_DENSITY = 1.5;
167
+ /** Cap on the refraction blur LOD. */ const REFRACT_BLUR_MAX_LOD = 6;
168
+ /**
169
+ * The foam's look follows Crest's OceanFoam.hlsl (Wave Harmonic, MIT): a
170
+ * white foam layer cut from the foam texture by the foam density with a
171
+ * feathered black point, lit through a normal taken from the slope of that
172
+ * cut over a step of a quarter texel per metre of view depth, with a narrow
173
+ * glint; and beneath it bubbles, the same texture blurred three mips and
174
+ * shifted by parallax as if under the surface, tinted and lit by the sky.
175
+ * The texture drifts at FOAM_DRIFT metres per second along x and z, Crest's
176
+ * time / 10.
177
+ */ const FOAM_DRIFT = 0.1;
178
+ const FOAM_BUBBLE_MIP_SCALE = 8;
179
+ const FOAM_SPECULAR_POWER = 293;
180
+ const FOAM_SPECULAR_BOOST = 0.15;
11
181
  class WaterMaterial extends applyMaterialMixins(MeshMaterial, mixinLight) {
12
- static _absorptionGrad = new Interpolator('linear', 'vec3', new Float32Array([
13
- 0,
14
- 0.082,
15
- 0.318,
16
- 0.665,
17
- 1
18
- ]), new Float32Array([
19
- 1,
20
- 1,
21
- 1,
22
- 0.22,
23
- 0.87,
24
- 0.87,
25
- 0,
26
- 0.47,
27
- 0.49,
28
- 0,
29
- 0.275,
30
- 0.44,
31
- 0,
32
- 0,
33
- 0
34
- ]));
35
- static _scatterGrad = new Interpolator('linear', 'vec3', new Float32Array([
36
- 0,
37
- 0.15,
38
- 0.42,
39
- 1
40
- ]), new Float32Array([
41
- 0,
42
- 0,
43
- 0,
44
- 0.08,
45
- 0.41,
46
- 0.34,
47
- 0.13,
48
- 0.4,
49
- 0.45,
50
- 0.21,
51
- 0.5,
52
- 0.6
53
- ]));
54
- static _defaultScatterRampTexture = new DWeakRef();
55
- static _defaultAbsorptionRampTexture = new DWeakRef();
182
+ static FEATURE_REFRACTION_MODE = this.defineFeature();
183
+ static FEATURE_INFINITE = this.defineFeature();
184
+ static FEATURE_DEBUG_OUTPUT = this.defineFeature();
56
185
  static _waveUpdateState = new WeakMap();
186
+ static _interactionUpdateState = new WeakMap();
57
187
  _region;
58
- _displace;
59
- _depthMulti;
60
- _refractionStrength;
61
- _scatterRampTexture;
62
- _absorptionRampTexture;
188
+ _refractionScale;
189
+ _reflectionStrength;
63
190
  _waveGenerator;
64
- _waveVersion;
191
+ _interaction;
192
+ /**
193
+ * The generator the shaders and every other consumer of the surface use: the
194
+ * base generator wrapped with the interaction field while one is attached,
195
+ * the base generator itself otherwise.
196
+ */ _effectiveWaveGenerator;
197
+ /** Settings of the shore waves, shared by reference with their generator. */ _shoreWaves = {
198
+ height: 0,
199
+ wavelength: 8,
200
+ period: 6,
201
+ zone: 20,
202
+ sharpness: 0.7,
203
+ lean: 0.5,
204
+ irregularity: 0.6,
205
+ waveFoamStrength: 1,
206
+ waveFoamCoverage: 0.55,
207
+ shorelineFoamMaxDepth: 0.65,
208
+ shorelineFoamStrength: 2,
209
+ wallFoamStrength: 1,
210
+ wallFoamMinSpeed: 0.2,
211
+ wallFoamMaxSpeed: 1.5,
212
+ wallFoamDrift: 0.3,
213
+ surfFoamDuration: 1.5,
214
+ foamSettleDepth: 0.02,
215
+ foamDriftDepth: 0.3,
216
+ settledFoamFade: 0.25
217
+ };
218
+ /** The shore wave layer of the effective generator, while the waves are on. */ _shoreWaveGenerator = null;
219
+ /** Foam with memory, carried by the water; kept across rebuilds of the generators. */ _foamField = new WaterFoamField();
220
+ /** The foam field layered over the base generator, innermost in the effective generator. */ _foamFieldGenerator = null;
221
+ /**
222
+ * The interaction layer of the effective generator while a field is attached,
223
+ * wherever it sits in the chain (the shore waves wrap it when they are on).
224
+ */ _interactiveWaveGenerator = null;
225
+ /** What feeds the foam field: the shore waves while they are on, else the open water. */ _foamSource = null;
226
+ /** Frame the foam field was last stepped in. */ _foamFrameId = -1;
227
+ /** Frame of the last update. */ _frameId = 0;
228
+ _edgeFadeWidth = 0.05;
229
+ /**
230
+ * Thickness in metres over which a thin sheet of water fades in from the
231
+ * ground under it, so swash running up the sand shows the sand through it.
232
+ * 0 disables it.
233
+ */ get edgeFadeWidth() {
234
+ return this._edgeFadeWidth;
235
+ }
236
+ set edgeFadeWidth(val) {
237
+ val = Math.max(0, val);
238
+ if (val !== this._edgeFadeWidth) {
239
+ this._edgeFadeWidth = val;
240
+ this.uniformChanged();
241
+ }
242
+ }
243
+ /** Seconds of water clock at the last update, for the shore waves. */ _waveClock = 0;
244
+ /** Wave uniform version last written, per bind group. */ _waveVersionByBindGroup;
65
245
  _clipmapInfo;
66
246
  _clipmapGridInfo;
247
+ _skirtDistance;
67
248
  _ssrParams;
249
+ /** (wind direction x, z, Cox-Munk upwind slope variance, crosswind slope variance) */ _unresolvedSlope;
250
+ /** sigma_a, 1/m, per RGB channel. */ _absorption;
251
+ /** sigma_s, 1/m, per RGB channel. */ _scattering;
252
+ /** sigma_t = sigma_a + sigma_s. */ _extinction;
253
+ /** sigma_s / sigma_t. */ _scatterAlbedo;
254
+ _absorptionScale;
255
+ _scatteringScale;
256
+ _causticsEnabled;
257
+ _causticsIntensity;
258
+ _causticsDepth;
259
+ _causticsRange;
260
+ _causticsFadeDistance;
261
+ _causticsWarp;
262
+ _causticsMinDepth;
263
+ _causticsSceneDepth;
264
+ _causticsDefocus;
265
+ _causticsResolution;
266
+ _causticsPhotonResolution;
267
+ _causticsBlurPasses;
268
+ _causticsTemporalStrength;
269
+ _underwaterEnabled;
270
+ _underwaterAmbientIntensity;
271
+ _underwaterGodRays;
272
+ _underwaterGodRayIntensity;
273
+ _underwaterGodRaySteps;
274
+ _underwaterGodRayShadow;
275
+ _underwaterHysteresis;
276
+ _subsurfaceIntensity;
277
+ _subsurfaceCrestHeight;
278
+ _subsurfaceTint;
279
+ _subsurfaceParams;
280
+ _sunScatteringIntensity;
281
+ _scatterAnisotropy;
282
+ _sunScatterParams;
283
+ _refractionBlur;
284
+ _cheapRefractionDepth;
285
+ _foamAmount;
286
+ _foamFalloff;
287
+ _foamColor;
288
+ _foamParams;
289
+ _foamFeather;
290
+ _foamNormalStrength;
291
+ _foamBubbleColor;
292
+ _foamBubbleCoverage;
293
+ _foamBubbleDepth;
294
+ _foamLookParams;
295
+ _foamTexture;
296
+ _foamTextureSize = 4;
68
297
  constructor(){
69
298
  super();
70
299
  this._region = new Vector4(-99999, -99999, 99999, 99999);
300
+ this._absorption = new Vector3(1.0, 0.25, 0.15);
301
+ this._scattering = new Vector3(0.05, 0.12, 0.18);
302
+ this._extinction = new Vector3();
303
+ this._scatterAlbedo = new Vector3();
304
+ this._absorptionScale = 1;
305
+ this._scatteringScale = 1;
306
+ this._updateMediumCoefficients();
71
307
  this._clipmapInfo = new Vector4();
72
308
  this._clipmapGridInfo = new Vector4();
309
+ this._skirtDistance = 0;
73
310
  this._waveGenerator = new DRef();
74
- this._waveVersion = -1;
311
+ this._interaction = new DRef();
312
+ this._effectiveWaveGenerator = null;
313
+ this._waveVersionByBindGroup = new WeakMap();
75
314
  this._ssrParams = new Vector4(1000, 160, 0.5, 2);
76
- this._scatterRampTexture = new DRef();
77
- this._absorptionRampTexture = new DRef();
78
- this._displace = 16;
79
- this._depthMulti = 0.1;
80
- this._refractionStrength = 0;
315
+ this._unresolvedSlope = new Vector4();
316
+ this._refractionScale = 1;
317
+ this._reflectionStrength = 1;
318
+ this._causticsEnabled = true;
319
+ this._causticsIntensity = 1;
320
+ this._causticsDepth = 4;
321
+ this._causticsRange = 60;
322
+ this._causticsFadeDistance = 0;
323
+ this._causticsWarp = 1.5;
324
+ this._causticsMinDepth = 0.15;
325
+ this._causticsSceneDepth = true;
326
+ this._causticsDefocus = 0.12;
327
+ this._causticsResolution = 1024;
328
+ this._causticsPhotonResolution = 0;
329
+ this._causticsBlurPasses = 2;
330
+ this._causticsTemporalStrength = 0.85;
331
+ this._underwaterEnabled = true;
332
+ this._underwaterAmbientIntensity = 1;
333
+ this._underwaterGodRays = true;
334
+ this._underwaterGodRayIntensity = 1;
335
+ this._underwaterGodRaySteps = 24;
336
+ this._underwaterGodRayShadow = false;
337
+ this._underwaterHysteresis = 0.05;
338
+ this._subsurfaceIntensity = 0.5;
339
+ this._subsurfaceCrestHeight = 1.5;
340
+ this._subsurfaceTint = new Vector3(0.86, 0.98, 0.71);
341
+ this._subsurfaceParams = new Vector4();
342
+ this._sunScatteringIntensity = 1;
343
+ this._scatterAnisotropy = DEFAULT_SCATTER_ANISOTROPY;
344
+ this._sunScatterParams = new Vector4();
345
+ this._refractionBlur = 1;
346
+ this._cheapRefractionDepth = 1;
347
+ this._foamAmount = 1;
348
+ this._foamFalloff = 1.5;
349
+ this._foamColor = new Vector3(0.92, 0.95, 0.97);
350
+ this._foamParams = new Vector4();
351
+ // Crest's defaults
352
+ this._foamFeather = 0.4;
353
+ this._foamNormalStrength = 3.5;
354
+ this._foamBubbleColor = new Vector3(0.64, 0.83, 0.82);
355
+ this._foamBubbleCoverage = 1.68;
356
+ this._foamBubbleDepth = 0.14;
357
+ this._foamLookParams = new Vector4();
358
+ this._foamTexture = new DRef();
81
359
  this.cullMode = 'none';
82
- //this.TAADisabled = true;
360
+ this.useFeature(WaterMaterial.FEATURE_REFRACTION_MODE, 'march');
361
+ this.useFeature(WaterMaterial.FEATURE_INFINITE, false);
362
+ this.useFeature(WaterMaterial.FEATURE_DEBUG_OUTPUT, 'none');
83
363
  }
84
364
  /** {@inheritDoc Material.onDispose} */ onDispose() {
85
365
  super.onDispose();
86
366
  this._waveGenerator.dispose();
87
- this._scatterRampTexture.dispose();
88
- this._absorptionRampTexture.dispose();
367
+ this._interaction.dispose();
368
+ this._shoreWaveGenerator?.dispose();
369
+ this._shoreWaveGenerator = null;
370
+ this._foamFieldGenerator?.dispose();
371
+ this._foamFieldGenerator = null;
372
+ this._foamSource = null;
373
+ this._interactiveWaveGenerator = null;
374
+ this._foamField.dispose();
375
+ this._effectiveWaveGenerator = null;
376
+ this._foamTexture.dispose();
89
377
  }
90
378
  /** @internal */ get region() {
91
379
  return this._region;
@@ -96,60 +384,520 @@ class WaterMaterial extends applyMaterialMixins(MeshMaterial, mixinLight) {
96
384
  this.uniformChanged();
97
385
  }
98
386
  }
99
- get waveGenerator() {
100
- return this._waveGenerator.get();
387
+ /**
388
+ * The wave generator the surface is evaluated with.
389
+ *
390
+ * While an {@link interaction} is attached this is a wrapper that layers the
391
+ * interaction field over {@link baseWaveGenerator}; every consumer of the
392
+ * surface (the shaders, the surface-point query, the caustics) goes through
393
+ * it and sees one displaced surface. Setting it sets the base generator.
394
+ */ get waveGenerator() {
395
+ return this._effectiveWaveGenerator;
101
396
  }
102
397
  set waveGenerator(waveGenerator) {
103
398
  if (this._waveGenerator.get() !== waveGenerator) {
104
399
  this._waveGenerator.set(waveGenerator);
105
- this._waveVersion = -1;
106
- this.optionChanged(true);
400
+ this._rebuildEffectiveWaveGenerator();
401
+ }
402
+ }
403
+ /** The generator supplying the ambient surface, without any interaction field. */ get baseWaveGenerator() {
404
+ return this._waveGenerator.get();
405
+ }
406
+ /**
407
+ * Dynamic height field layered over the surface, or null for none. See
408
+ * {@link WaterInteraction}.
409
+ *
410
+ * Ignored, with the base generator used on its own, on a device that cannot
411
+ * host the field.
412
+ */ get interaction() {
413
+ return this._interaction.get();
414
+ }
415
+ set interaction(val) {
416
+ if (this._interaction.get() !== val) {
417
+ this._interaction.set(val);
418
+ this._rebuildEffectiveWaveGenerator();
419
+ }
420
+ }
421
+ /** @internal */ _rebuildEffectiveWaveGenerator() {
422
+ const base = this._waveGenerator.get();
423
+ const interaction = this._interaction.get();
424
+ this._shoreWaveGenerator?.dispose();
425
+ this._shoreWaveGenerator = null;
426
+ this._foamFieldGenerator?.dispose();
427
+ this._foamFieldGenerator = null;
428
+ this._foamSource = null;
429
+ // A field left behind must not hold on to the generators disposed here
430
+ this._interactiveWaveGenerator?.interaction.setAmbientSurface(null);
431
+ this._interactiveWaveGenerator = null;
432
+ let effective = null;
433
+ if (base) {
434
+ // Innermost the foam field, whose foam the shore waves and the
435
+ // interaction field compose theirs over
436
+ const that = this;
437
+ this._foamFieldGenerator = new FoamFieldWaveGenerator(base, this._foamField, {
438
+ getFoamTexture: ()=>that.foamTexture,
439
+ getFoamTextureSize: ()=>that._foamTextureSize
440
+ });
441
+ effective = this._foamFieldGenerator;
442
+ this._foamSource = new WaveFoamSource(base, this._foamField);
443
+ }
444
+ if (effective && this._shoreWaves.height > 0) {
445
+ this._shoreWaveGenerator = new ShoreWaveGenerator(effective, this._shoreWaves, this._foamSource);
446
+ this._foamFieldGenerator.flowSource = this._shoreWaveGenerator;
447
+ this._foamSource = this._shoreWaveGenerator;
448
+ effective = this._shoreWaveGenerator;
449
+ }
450
+ // Outermost the interaction field: its ripples ride the shore waves rather
451
+ // than being faded with the open water's chop near the shore, and a query
452
+ // of the surface without the disturbers finds it on top to rebuild
453
+ if (effective && interaction && interaction.isOk()) {
454
+ // The field reads the surface beneath it under each disturber, so a hull
455
+ // riding the waves is measured against the water it floats on
456
+ interaction.setAmbientSurface(effective);
457
+ effective = new InteractiveWaveGenerator(effective, interaction);
458
+ this._interactiveWaveGenerator = effective;
459
+ interaction.ensureResources();
460
+ }
461
+ this._effectiveWaveGenerator = effective;
462
+ // Bind groups are pooled; a stale version must not suppress the upload.
463
+ this._waveVersionByBindGroup = new WeakMap();
464
+ this.optionChanged(true);
465
+ }
466
+ /** How the refracted view sample is located. Defaults to `march`. Compile-time feature. */ get refractionMode() {
467
+ return this.featureUsed(WaterMaterial.FEATURE_REFRACTION_MODE) ?? 'march';
468
+ }
469
+ set refractionMode(val) {
470
+ if (val !== this.refractionMode) {
471
+ this.useFeature(WaterMaterial.FEATURE_REFRACTION_MODE, val);
107
472
  }
108
473
  }
109
- get scatterRampTexture() {
110
- const tex = this._getScatterRampTexture(getDevice());
111
- return tex === WaterMaterial._defaultScatterRampTexture.get() ? null : tex;
474
+ /**
475
+ * Which intermediate shading term to display instead of the final colour.
476
+ * Defaults to `none`. See {@link WaterDebugOutput}.
477
+ */ get debugOutput() {
478
+ return this.featureUsed(WaterMaterial.FEATURE_DEBUG_OUTPUT) ?? 'none';
112
479
  }
113
- set scatterRampTexture(tex) {
114
- if (tex !== this.scatterRampTexture) {
115
- this._scatterRampTexture.set(tex);
480
+ set debugOutput(val) {
481
+ if (val !== this.debugOutput) {
482
+ this.useFeature(WaterMaterial.FEATURE_DEBUG_OUTPUT, val);
483
+ }
484
+ }
485
+ /**
486
+ * Whether the surface reaches the horizon rather than ending at {@link region}.
487
+ * Off by default. The clipmap's outermost ring becomes a horizon skirt.
488
+ */ get infinite() {
489
+ return this.featureUsed(WaterMaterial.FEATURE_INFINITE) ?? false;
490
+ }
491
+ set infinite(val) {
492
+ if (!!val !== this.infinite) {
493
+ this.useFeature(WaterMaterial.FEATURE_INFINITE, !!val);
494
+ }
495
+ }
496
+ /** Absorption coefficient sigma_a in 1/m, per RGB channel. */ get absorption() {
497
+ return this._absorption;
498
+ }
499
+ set absorption(val) {
500
+ if (!val.equalsTo(this._absorption)) {
501
+ this._absorption.set(val);
502
+ this._updateMediumCoefficients();
116
503
  this.uniformChanged();
117
504
  }
118
505
  }
119
- get absorptionRampTexture() {
120
- const tex = this._getAbsorptionRampTexture(getDevice());
121
- return tex === WaterMaterial._defaultAbsorptionRampTexture.get() ? null : tex;
506
+ /** Scale for the absorption coefficient. */ get absorptionScale() {
507
+ return this._absorptionScale;
122
508
  }
123
- set absorptionRampTexture(tex) {
124
- if (tex !== this.absorptionRampTexture) {
125
- this._absorptionRampTexture.set(tex);
509
+ set absorptionScale(val) {
510
+ if (val !== this._absorptionScale) {
511
+ this._absorptionScale = val;
512
+ this._updateMediumCoefficients();
126
513
  this.uniformChanged();
127
514
  }
128
515
  }
129
- get depthMulti() {
130
- return this._depthMulti;
516
+ /** Scattering coefficient sigma_s in 1/m, per RGB channel. */ get scattering() {
517
+ return this._scattering;
131
518
  }
132
- set depthMulti(val) {
133
- if (val !== this._depthMulti) {
134
- this._depthMulti = val;
519
+ set scattering(val) {
520
+ if (!val.equalsTo(this._scattering)) {
521
+ this._scattering.set(val);
522
+ this._updateMediumCoefficients();
135
523
  this.uniformChanged();
136
524
  }
137
525
  }
138
- get displace() {
139
- return this._displace;
526
+ /** Scale for the scattering coefficient. */ get scatteringScale() {
527
+ return this._scatteringScale;
140
528
  }
141
- set displace(val) {
142
- if (val !== this._displace) {
143
- this._displace = val;
529
+ set scatteringScale(val) {
530
+ if (val !== this._scatteringScale) {
531
+ this._scatteringScale = val;
532
+ this._updateMediumCoefficients();
144
533
  this.uniformChanged();
145
534
  }
146
535
  }
147
- get refractionStrength() {
148
- return this._refractionStrength;
536
+ /** sigma_t = sigma_a + sigma_s in 1/m. Shared with the caustics pass. Do not mutate. */ get extinction() {
537
+ return this._extinction;
538
+ }
539
+ /** Single-scattering albedo sigma_s / sigma_t. Do not mutate. */ get scatterAlbedo() {
540
+ return this._scatterAlbedo;
541
+ }
542
+ /**
543
+ * Whether a camera inside this body of water sees the medium applied to the
544
+ * whole scene. Uses the same coefficients as the surface shading.
545
+ */ get underwaterEnabled() {
546
+ return this._underwaterEnabled;
547
+ }
548
+ set underwaterEnabled(val) {
549
+ this._underwaterEnabled = !!val;
550
+ }
551
+ /** Scale on the downwelling sky radiance lighting the column from inside, 1 for physical. */ get underwaterAmbientIntensity() {
552
+ return this._underwaterAmbientIntensity;
553
+ }
554
+ set underwaterAmbientIntensity(val) {
555
+ this._underwaterAmbientIntensity = Math.max(0, val);
556
+ }
557
+ /**
558
+ * Whether sunlight shafts are marched through the water column. Reads the
559
+ * caustic map, so it is off wherever that is unavailable.
560
+ */ get underwaterGodRays() {
561
+ return this._underwaterGodRays;
562
+ }
563
+ set underwaterGodRays(val) {
564
+ this._underwaterGodRays = !!val;
565
+ }
566
+ /** Strength of the light shafts, 1 for the value the medium implies. */ get underwaterGodRayIntensity() {
567
+ return this._underwaterGodRayIntensity;
568
+ }
569
+ set underwaterGodRayIntensity(val) {
570
+ this._underwaterGodRayIntensity = Math.max(0, val);
571
+ }
572
+ /** Samples per view ray for the light shafts. Dithered; below about 8 reads as noise. */ get underwaterGodRaySteps() {
573
+ return this._underwaterGodRaySteps;
574
+ }
575
+ set underwaterGodRaySteps(val) {
576
+ this._underwaterGodRaySteps = Math.max(1, Math.floor(val));
577
+ }
578
+ /**
579
+ * Whether geometry in the water breaks the light shafts. Off by default; one
580
+ * shadow map lookup per march step, roughly doubling the shafts' cost.
581
+ */ get underwaterGodRayShadow() {
582
+ return this._underwaterGodRayShadow;
149
583
  }
150
- set refractionStrength(val) {
151
- if (val !== this._refractionStrength) {
152
- this._refractionStrength = val;
584
+ set underwaterGodRayShadow(val) {
585
+ this._underwaterGodRayShadow = !!val;
586
+ }
587
+ /**
588
+ * Half-width in meters of the dead band the submerged test uses around the
589
+ * rest plane, so a camera at water level does not flip state every frame.
590
+ */ get underwaterHysteresis() {
591
+ return this._underwaterHysteresis;
592
+ }
593
+ set underwaterHysteresis(val) {
594
+ this._underwaterHysteresis = Math.max(0, val);
595
+ }
596
+ /**
597
+ * Whether this water projects caustics onto the geometry below it. Requires a
598
+ * shadow-casting directional light.
599
+ */ get causticsEnabled() {
600
+ return this._causticsEnabled;
601
+ }
602
+ set causticsEnabled(val) {
603
+ this._causticsEnabled = !!val;
604
+ }
605
+ /** Strength of the caustic contrast. 0 leaves the light unmodulated. */ get causticsIntensity() {
606
+ return this._causticsIntensity;
607
+ }
608
+ set causticsIntensity(val) {
609
+ this._causticsIntensity = val;
610
+ }
611
+ /** Depth in meters below the surface where the caustics are in focus. */ get causticsDepth() {
612
+ return this._causticsDepth;
613
+ }
614
+ set causticsDepth(val) {
615
+ this._causticsDepth = Math.max(0.01, val);
616
+ }
617
+ /** Furthest distance in meters from the camera the caustic map reaches. */ get causticsRange() {
618
+ return this._causticsRange;
619
+ }
620
+ set causticsRange(val) {
621
+ this._causticsRange = Math.max(1, val);
622
+ }
623
+ /**
624
+ * Width in meters of the fade band at the edge of the caustic map, or 0 to
625
+ * derive it from {@link causticsRange}. Capped at 90% of the range.
626
+ */ get causticsFadeDistance() {
627
+ return this._causticsFadeDistance;
628
+ }
629
+ set causticsFadeDistance(val) {
630
+ this._causticsFadeDistance = Math.max(0, val);
631
+ }
632
+ /**
633
+ * Whether photons land on the scene (via the sun's shadow cascade) instead of
634
+ * on a plane at {@link causticsDepth}. On by default.
635
+ */ get causticsSceneDepth() {
636
+ return this._causticsSceneDepth;
637
+ }
638
+ set causticsSceneDepth(val) {
639
+ this._causticsSceneDepth = !!val;
640
+ }
641
+ /**
642
+ * How strongly caustic map texels are concentrated near the camera, 0 for
643
+ * uniform. Density is `1 + warp` times uniform at the centre and
644
+ * `1 / (1 + warp)` at the border. Ignored while the map fits the water.
645
+ */ get causticsWarp() {
646
+ return this._causticsWarp;
647
+ }
648
+ set causticsWarp(val) {
649
+ this._causticsWarp = Math.max(0, Math.min(8, val));
650
+ }
651
+ /**
652
+ * Water depth in metres below which no caustics show, faded in over half
653
+ * of it either side; 0 shows them right up to the water's edge.
654
+ */ get causticsMinDepth() {
655
+ return this._causticsMinDepth;
656
+ }
657
+ set causticsMinDepth(val) {
658
+ this._causticsMinDepth = Math.max(0, val);
659
+ }
660
+ /** Caustic contrast falloff per meter away from {@link causticsDepth}. */ get causticsDefocus() {
661
+ return this._causticsDefocus;
662
+ }
663
+ set causticsDefocus(val) {
664
+ this._causticsDefocus = Math.max(0, val);
665
+ }
666
+ /** Edge length of the square caustic map. */ get causticsResolution() {
667
+ return this._causticsResolution;
668
+ }
669
+ set causticsResolution(val) {
670
+ this._causticsResolution = Math.max(16, Math.min(2048, val | 0));
671
+ }
672
+ /** Edge length of the photon grid, or 0 to size it from the map. Cost is quadratic. */ get causticsPhotonResolution() {
673
+ return this._causticsPhotonResolution;
674
+ }
675
+ set causticsPhotonResolution(val) {
676
+ const n = val | 0;
677
+ this._causticsPhotonResolution = n <= 0 ? 0 : Math.max(16, Math.min(4096, n));
678
+ }
679
+ /** Number of 2x2 blur iterations on the caustic map. Rounded up to even. */ get causticsBlurPasses() {
680
+ return this._causticsBlurPasses;
681
+ }
682
+ set causticsBlurPasses(val) {
683
+ const clamped = Math.max(0, Math.min(4, val | 0));
684
+ this._causticsBlurPasses = clamped + (clamped & 1);
685
+ }
686
+ /** Weight of the previous frame's caustic map in the current one, 0 to disable. */ get causticsTemporalStrength() {
687
+ return this._causticsTemporalStrength;
688
+ }
689
+ set causticsTemporalStrength(val) {
690
+ this._causticsTemporalStrength = Math.max(0, Math.min(0.95, val));
691
+ }
692
+ /**
693
+ * Strength of the glow of a backlit wave crest, 0 to disable. Authored, not
694
+ * scaled by the light's intensity; {@link subsurfaceTint} supplies the hue.
695
+ */ get subsurfaceIntensity() {
696
+ return this._subsurfaceIntensity;
697
+ }
698
+ set subsurfaceIntensity(val) {
699
+ if (val !== this._subsurfaceIntensity) {
700
+ this._subsurfaceIntensity = Math.max(0, val);
701
+ this.uniformChanged();
702
+ }
703
+ }
704
+ /**
705
+ * Height above the still-water level, in meters, over which the lit wall of
706
+ * a crest thins by a factor of `e`. Lower for a calm sea, higher so only the
707
+ * tallest crests glow.
708
+ */ get subsurfaceCrestHeight() {
709
+ return this._subsurfaceCrestHeight;
710
+ }
711
+ set subsurfaceCrestHeight(val) {
712
+ // The gate softens over SSS_HEIGHT_SOFTNESS of this; too small a height
713
+ // makes it a hard step at the still-water level.
714
+ const clamped = Math.max(SSS_CREST_HEIGHT_MIN, val);
715
+ if (clamped !== this._subsurfaceCrestHeight) {
716
+ this._subsurfaceCrestHeight = clamped;
717
+ this.uniformChanged();
718
+ }
719
+ }
720
+ /** Colour of the crest glow, before the crest gate tints it with the medium's extinction. */ get subsurfaceTint() {
721
+ return this._subsurfaceTint;
722
+ }
723
+ set subsurfaceTint(val) {
724
+ if (!val.equalsTo(this._subsurfaceTint)) {
725
+ this._subsurfaceTint.set(val);
726
+ this.uniformChanged();
727
+ }
728
+ }
729
+ /**
730
+ * Strength of the sunlight scattered out of the water column towards the eye,
731
+ * 1 for the physical value. 0 disables the term.
732
+ */ get sunScatteringIntensity() {
733
+ return this._sunScatteringIntensity;
734
+ }
735
+ set sunScatteringIntensity(val) {
736
+ const clamped = Math.max(0, val);
737
+ if (clamped !== this._sunScatteringIntensity) {
738
+ this._sunScatteringIntensity = clamped;
739
+ this.uniformChanged();
740
+ }
741
+ }
742
+ /**
743
+ * Fixed depth in meters the `offset` refraction mode steps along the refracted
744
+ * ray. Ignored by `march`. Deliberately not the scene distance, which would
745
+ * double submerged objects across their silhouette.
746
+ */ get cheapRefractionDepth() {
747
+ return this._cheapRefractionDepth;
748
+ }
749
+ set cheapRefractionDepth(val) {
750
+ const clamped = Math.max(0, val);
751
+ if (clamped !== this._cheapRefractionDepth) {
752
+ this._cheapRefractionDepth = clamped;
753
+ this.uniformChanged();
754
+ }
755
+ }
756
+ /** Scale on the medium's refraction blur. 0 is sharp, 1 is what the medium implies. */ get refractionBlur() {
757
+ return this._refractionBlur;
758
+ }
759
+ set refractionBlur(val) {
760
+ const clamped = Math.max(0, val);
761
+ if (clamped !== this._refractionBlur) {
762
+ this._refractionBlur = clamped;
763
+ this.uniformChanged();
764
+ }
765
+ }
766
+ /** Mean cosine of a single scattering event, in `[0, 0.95]`. 0 is isotropic. */ get scatterAnisotropy() {
767
+ return this._scatterAnisotropy;
768
+ }
769
+ set scatterAnisotropy(val) {
770
+ const clamped = Math.max(0, Math.min(0.95, val));
771
+ if (clamped !== this._scatterAnisotropy) {
772
+ this._scatterAnisotropy = clamped;
773
+ this.uniformChanged();
774
+ }
775
+ }
776
+ /** Scale from the generator's fold measure to foam coverage, 0 to disable. */ get foamAmount() {
777
+ return this._foamAmount;
778
+ }
779
+ set foamAmount(val) {
780
+ if (val !== this._foamAmount) {
781
+ this._foamAmount = Math.max(0, val);
782
+ this.uniformChanged();
783
+ }
784
+ }
785
+ /** Power applied to foam coverage before scaling. Above 1 restricts foam to broken crests. */ get foamFalloff() {
786
+ return this._foamFalloff;
787
+ }
788
+ set foamFalloff(val) {
789
+ if (val !== this._foamFalloff) {
790
+ this._foamFalloff = Math.max(0.01, val);
791
+ this.uniformChanged();
792
+ }
793
+ }
794
+ /** Diffuse albedo of the foam. */ get foamColor() {
795
+ return this._foamColor;
796
+ }
797
+ set foamColor(val) {
798
+ if (!val.equalsTo(this._foamColor)) {
799
+ this._foamColor.set(val);
800
+ this.uniformChanged();
801
+ }
802
+ }
803
+ /**
804
+ * How gradually the white foam fades out at its edges, from a crisp cut
805
+ * (near 0) to a soft blend into the bubbles beneath (1).
806
+ */ get foamFeather() {
807
+ return this._foamFeather;
808
+ }
809
+ set foamFeather(val) {
810
+ const clamped = Math.min(Math.max(val, 0.001), 1);
811
+ if (clamped !== this._foamFeather) {
812
+ this._foamFeather = clamped;
813
+ this.uniformChanged();
814
+ }
815
+ }
816
+ /** How much the white foam is lit as a lumpy relief rather than a flat sheet, 0 for flat. */ get foamNormalStrength() {
817
+ return this._foamNormalStrength;
818
+ }
819
+ set foamNormalStrength(val) {
820
+ const clamped = Math.max(0, val);
821
+ if (clamped !== this._foamNormalStrength) {
822
+ this._foamNormalStrength = clamped;
823
+ this.uniformChanged();
824
+ }
825
+ }
826
+ /** Tint of the bubbles under the white foam, lit by the sky. */ get foamBubbleColor() {
827
+ return this._foamBubbleColor;
828
+ }
829
+ set foamBubbleColor(val) {
830
+ if (!val.equalsTo(this._foamBubbleColor)) {
831
+ this._foamBubbleColor.set(val);
832
+ this.uniformChanged();
833
+ }
834
+ }
835
+ /** How far the bubbles spread around the white foam and how strongly they show, 0 for none. */ get foamBubbleCoverage() {
836
+ return this._foamBubbleCoverage;
837
+ }
838
+ set foamBubbleCoverage(val) {
839
+ const clamped = Math.max(0, val);
840
+ if (clamped !== this._foamBubbleCoverage) {
841
+ this._foamBubbleCoverage = clamped;
842
+ this.uniformChanged();
843
+ }
844
+ }
845
+ /**
846
+ * Texture the foam is cut from, its value in the red channel: the foam
847
+ * density uncovers it from its brightest parts down, so bright clumps show
848
+ * first and dark holes last. Null for the built-in bubble pattern (see
849
+ * getDefaultFoamTexture), which reads as a texture of one's own would.
850
+ * Tiles every {@link foamTextureSize} metres.
851
+ */ get foamTexture() {
852
+ return this._foamTexture.get() ?? null;
853
+ }
854
+ set foamTexture(tex) {
855
+ if (tex !== this.foamTexture) {
856
+ this._foamTexture.set(tex);
857
+ this.uniformChanged();
858
+ }
859
+ }
860
+ /** Metres of water one repeat of the {@link foamTexture} covers. */ get foamTextureSize() {
861
+ return this._foamTextureSize;
862
+ }
863
+ set foamTextureSize(val) {
864
+ const clamped = Math.max(0.01, val);
865
+ if (clamped !== this._foamTextureSize) {
866
+ this._foamTextureSize = clamped;
867
+ this.uniformChanged();
868
+ }
869
+ }
870
+ /** How deep under the surface the bubbles seem to float, in metres; they shift against the foam as the view moves. */ get foamBubbleDepth() {
871
+ return this._foamBubbleDepth;
872
+ }
873
+ set foamBubbleDepth(val) {
874
+ const clamped = Math.max(0, val);
875
+ if (clamped !== this._foamBubbleDepth) {
876
+ this._foamBubbleDepth = clamped;
877
+ this.uniformChanged();
878
+ }
879
+ }
880
+ /** @internal */ _updateMediumCoefficients() {
881
+ this._extinction.setXYZ(this._absorption.x * this._absorptionScale + this._scattering.x * this._scatteringScale, this._absorption.y * this._absorptionScale + this._scattering.y * this._scatteringScale, this._absorption.z * this._absorptionScale + this._scattering.z * this._scatteringScale);
882
+ this._scatterAlbedo.setXYZ(this._extinction.x > 0 ? this._scattering.x * this._scatteringScale / this._extinction.x : 0, this._extinction.y > 0 ? this._scattering.y * this._scatteringScale / this._extinction.y : 0, this._extinction.z > 0 ? this._scattering.z * this._scatteringScale / this._extinction.z : 0);
883
+ }
884
+ /** Artistic scale on the refracted view offset. 1 is physical, 0 disables it. */ get refractionScale() {
885
+ return this._refractionScale;
886
+ }
887
+ set refractionScale(val) {
888
+ const clamped = Math.max(0, val);
889
+ if (clamped !== this._refractionScale) {
890
+ this._refractionScale = clamped;
891
+ this.uniformChanged();
892
+ }
893
+ }
894
+ /** Scale on the Fresnel reflectance, 1 for physical. Scales F0 too, so 0 kills specular. */ get reflectionStrength() {
895
+ return this._reflectionStrength;
896
+ }
897
+ set reflectionStrength(val) {
898
+ const clamped = Math.max(0, Math.min(1, val));
899
+ if (clamped !== this._reflectionStrength) {
900
+ this._reflectionStrength = clamped;
153
901
  this.uniformChanged();
154
902
  }
155
903
  }
@@ -166,9 +914,18 @@ class WaterMaterial extends applyMaterialMixins(MeshMaterial, mixinLight) {
166
914
  this._clipmapInfo.setXYZW(rotation, scale, offsetX, offsetY);
167
915
  this.uniformChanged();
168
916
  }
169
- setClipmapGridInfo(gridScale, gridOffsetX, gridOffsetY) {
170
- if (this._clipmapGridInfo.x !== gridScale || this._clipmapGridInfo.y !== gridOffsetX || this._clipmapGridInfo.z !== gridOffsetY) {
171
- this._clipmapGridInfo.setXYZW(gridScale, gridOffsetX, gridOffsetY, 0);
917
+ /**
918
+ * @param tileResolution - Cells along a clipmap tile, for the spacing of the
919
+ * mesh vertices the wave generator band-limits to; 0 for no limit.
920
+ */ setClipmapGridInfo(gridScale, gridOffsetX, gridOffsetY, tileResolution = 0) {
921
+ if (this._clipmapGridInfo.x !== gridScale || this._clipmapGridInfo.y !== gridOffsetX || this._clipmapGridInfo.z !== gridOffsetY || this._clipmapGridInfo.w !== tileResolution) {
922
+ this._clipmapGridInfo.setXYZW(gridScale, gridOffsetX, gridOffsetY, tileResolution);
923
+ this.uniformChanged();
924
+ }
925
+ }
926
+ /** Distance from the camera to the horizon skirt's outer edge. Only read while {@link infinite}. */ setSkirtDistance(distance) {
927
+ if (this._skirtDistance !== distance) {
928
+ this._skirtDistance = distance;
172
929
  this.uniformChanged();
173
930
  }
174
931
  }
@@ -178,6 +935,14 @@ class WaterMaterial extends applyMaterialMixins(MeshMaterial, mixinLight) {
178
935
  supportLighting() {
179
936
  return true;
180
937
  }
938
+ /**
939
+ * {@inheritDoc IMixinLight.receivesWaterCaustics}
940
+ *
941
+ * Always false: the submersion test would read a water fragment as submerged
942
+ * wherever the surface up-sun of it rides a crest.
943
+ */ receivesWaterCaustics() {
944
+ return false;
945
+ }
181
946
  vertexShader(scope) {
182
947
  super.vertexShader(scope);
183
948
  const pb = scope.$builder;
@@ -185,81 +950,618 @@ class WaterMaterial extends applyMaterialMixins(MeshMaterial, mixinLight) {
185
950
  scope.$inputs.position = pb.vec3().attrib('position');
186
951
  scope.$inputs.clipmapInfo = pb.vec4().attrib('texCoord0');
187
952
  scope.clipmapGridInfo = pb.vec4().uniform(2);
953
+ if (this.infinite) {
954
+ scope.skirtDistance = pb.float().uniform(2);
955
+ }
188
956
  scope.$l.s = pb.sin(scope.$inputs.clipmapInfo.x);
189
957
  scope.$l.c = pb.cos(scope.$inputs.clipmapInfo.x);
190
958
  scope.$l.scale2 = pb.mul(scope.$inputs.clipmapInfo.y, scope.clipmapGridInfo.x);
191
959
  scope.$l.clipmapMatrix = pb.mat4(pb.mul(scope.c, scope.scale2), pb.mul(scope.s, scope.scale2), 0, 0, pb.neg(pb.mul(scope.s, scope.scale2)), pb.mul(scope.c, scope.scale2), 0, 0, 0, 0, 1, 0, pb.sub(pb.mul(scope.$inputs.clipmapInfo.z, scope.clipmapGridInfo.x), scope.clipmapGridInfo.y), pb.sub(pb.mul(scope.$inputs.clipmapInfo.w, scope.clipmapGridInfo.x), scope.clipmapGridInfo.z), 0, 1);
192
960
  scope.$l.clipmapPos = pb.mul(scope.clipmapMatrix, pb.vec4(scope.$inputs.position, 1)).xy;
193
- //scope.$l.level = pb.mul(ShaderHelper.getWorldMatrix(scope), pb.vec4(0, 0, 0, 1)).y;
194
- scope.clipmapWorldPos = pb.mul(ShaderHelper.getWorldMatrix(scope), pb.vec4(scope.clipmapPos.x, 0, scope.clipmapPos.y, 1)).xyz; // pb.vec3(scope.clipmapPos.x, scope.level, scope.clipmapPos.y);
961
+ scope.clipmapWorldPos = pb.mul(ShaderHelper.getWorldMatrix(scope), pb.vec4(scope.clipmapPos.x, 0, scope.clipmapPos.y, 1)).xyz;
195
962
  scope.worldNormal = pb.vec3(0, 1, 0);
196
963
  scope.worldPos = scope.clipmapWorldPos;
197
- this.waveGenerator?.calcVertexPositionAndNormal(scope, scope.clipmapWorldPos, scope.worldPos, scope.worldNormal);
964
+ // Mesh vertex spacing: clipmap level L spans Chebyshev distances T 2^L to
965
+ // 2T 2^L cells with cells 2^L across, so distance / T bounds it. Taken from
966
+ // the distance, not the level, so both sides of a seam agree.
967
+ scope.$l.camOffset = pb.abs(pb.sub(scope.clipmapWorldPos.xz, ShaderHelper.getCameraPosition(scope).xz));
968
+ scope.$l.vertexSpacing = pb.mul(pb.max(scope.clipmapGridInfo.x, pb.div(pb.max(scope.camOffset.x, scope.camOffset.y), pb.max(scope.clipmapGridInfo.w, 1))), pb.step(0.5, scope.clipmapGridInfo.w));
969
+ if (this.infinite) {
970
+ const that = this;
971
+ // position.z is 1 on the skirt ring's outer edge, 0 everywhere else.
972
+ scope.$l.skirt = pb.step(0.5, scope.$inputs.position.z);
973
+ scope.$if(pb.greaterThan(scope.skirt, 0), function() {
974
+ // Pushed radially out from the camera, undisplaced, at the still-water level.
975
+ this.$l.camXZ = ShaderHelper.getCameraPosition(this).xz;
976
+ this.$l.outDir = pb.normalize(pb.sub(this.clipmapWorldPos.xz, this.camXZ));
977
+ this.$l.outXZ = pb.add(this.camXZ, pb.mul(this.outDir, this.skirtDistance));
978
+ this.worldPos = pb.vec3(this.outXZ.x, this.clipmapWorldPos.y, this.outXZ.y);
979
+ }).$else(function() {
980
+ that.waveGenerator?.calcVertexPositionAndNormal(this, this.clipmapWorldPos, this.worldPos, this.worldNormal, this.vertexSpacing);
981
+ });
982
+ scope.$outputs.skirt = scope.skirt;
983
+ } else {
984
+ this.waveGenerator?.calcVertexPositionAndNormal(scope, scope.clipmapWorldPos, scope.worldPos, scope.worldNormal, scope.vertexSpacing);
985
+ }
198
986
  scope.$outputs.worldPos = scope.worldPos;
199
987
  scope.$outputs.clipmapPos = scope.clipmapWorldPos;
200
988
  scope.$outputs.worldNormal = scope.worldNormal;
201
- ShaderHelper.setClipSpacePosition(scope, pb.mul(ShaderHelper.getViewProjectionMatrix(scope), pb.vec4(scope.$outputs.worldPos, 1)));
202
- ShaderHelper.resolveMotionVector(scope, scope.$outputs.worldPos, scope.$outputs.worldPos);
989
+ if (this.infinite) {
990
+ // Vertices past the far plane are pulled in along their own view ray:
991
+ // screen position is unchanged, only the written depth moves. Shading
992
+ // keeps the true world position.
993
+ scope.$l.camPos = ShaderHelper.getCameraPosition(scope).xyz;
994
+ scope.$l.viewVec = pb.sub(scope.$outputs.worldPos, scope.camPos);
995
+ scope.$l.viewDist = pb.max(pb.length(scope.viewVec), 1e-6);
996
+ scope.$l.maxDist = pb.mul(ShaderHelper.getCameraParams(scope).y, INFINITE_DEPTH_PULLIN);
997
+ scope.$l.pullIn = pb.min(pb.div(scope.maxDist, scope.viewDist), 1);
998
+ scope.$l.projPos = pb.add(scope.camPos, pb.mul(scope.viewVec, scope.pullIn));
999
+ ShaderHelper.setClipSpacePosition(scope, pb.mul(ShaderHelper.getViewProjectionMatrix(scope), pb.vec4(scope.projPos, 1)));
1000
+ } else {
1001
+ ShaderHelper.setClipSpacePosition(scope, pb.mul(ShaderHelper.getViewProjectionMatrix(scope), pb.vec4(scope.$outputs.worldPos, 1)));
1002
+ }
1003
+ const gen = this.waveGenerator;
1004
+ if (gen?.calcPrevVertexPosition && ShaderHelper.getPrevUnjitteredViewProjectionMatrix(scope)) {
1005
+ scope.$l.prevWorldPos = pb.vec3();
1006
+ gen.calcPrevVertexPosition(scope, scope.clipmapWorldPos, scope.prevWorldPos, scope.vertexSpacing);
1007
+ if (this.infinite) {
1008
+ // The skirt does not move
1009
+ scope.prevWorldPos = pb.mix(scope.prevWorldPos, scope.$outputs.worldPos, scope.skirt);
1010
+ }
1011
+ ShaderHelper.resolveMotionVector(scope, scope.$outputs.worldPos, scope.prevWorldPos);
1012
+ } else {
1013
+ ShaderHelper.resolveMotionVector(scope, scope.$outputs.worldPos, scope.$outputs.worldPos);
1014
+ }
203
1015
  }
204
1016
  fragmentShader(scope) {
205
1017
  super.fragmentShader(scope);
206
1018
  const pb = scope.$builder;
207
1019
  this.waveGenerator?.setupUniforms(scope, 2);
208
- scope.region = pb.vec4().uniform(2);
1020
+ if (!this.infinite) {
1021
+ scope.region = pb.vec4().uniform(2);
1022
+ }
209
1023
  if (this.needFragmentColor()) {
210
- scope.displace = pb.float().uniform(2);
211
- scope.depthMulti = pb.float().uniform(2);
212
- scope.refractionStrength = pb.float().uniform(2);
1024
+ scope.refractionScale = pb.float().uniform(2);
1025
+ if (this.refractionMode === 'offset') {
1026
+ scope.cheapRefractionDepth = pb.float().uniform(2);
1027
+ }
1028
+ scope.reflectionStrength = pb.float().uniform(2);
1029
+ // (wind direction x, z, upwind slope variance, crosswind slope variance)
1030
+ scope.unresolvedSlope = pb.vec4().uniform(2);
1031
+ // Sky bake to the live pre-exposed space, as the visible sky is drawn
1032
+ scope.skyReflectScale = pb.float().uniform(2);
213
1033
  scope.ssrParams = pb.vec4().uniform(2);
214
- scope.scatterRampTex = pb.tex2D().uniform(2);
215
- scope.absorptionRampTex = pb.tex2D().uniform(2);
1034
+ // Eye vs. rest plane from the CPU submersion test: 1 above, -1 below,
1035
+ // 0 unknown (compare in the shader).
1036
+ scope.eyeSide = pb.float().uniform(2);
1037
+ // (intensity, crest absorption height in m, 0, 0)
1038
+ scope.subsurfaceParams = pb.vec4().uniform(2);
1039
+ scope.subsurfaceTint = pb.vec3().uniform(2);
1040
+ // (coverage scale, coverage falloff, 0, 0)
1041
+ scope.foamShadingParams = pb.vec4().uniform(2);
1042
+ scope.foamColor = pb.vec3().uniform(2);
1043
+ // (white foam feather, foam normal strength, bubble coverage, bubble depth in m)
1044
+ scope.foamLookParams = pb.vec4().uniform(2);
1045
+ scope.foamBubbleColor = pb.vec3().uniform(2);
1046
+ scope.foamTex = pb.tex2D().uniform(2);
1047
+ // uv of the foam texture per metre
1048
+ scope.foamUVScale = pb.float().uniform(2);
1049
+ // Thickness in metres a sheet of water fades in over, 0 for none
1050
+ scope.edgeFadeWidth = pb.float().uniform(2);
1051
+ // (intensity, anisotropy, 0, 0)
1052
+ scope.sunScatterParams = pb.vec4().uniform(2);
1053
+ // Mip widths per meter of path; one scalar LOD for all three channels.
1054
+ scope.refractBlurDensity = pb.float().uniform(2);
1055
+ scope.mediumAlbedo = pb.vec3().uniform(2);
1056
+ scope.mediumExtinction = pb.vec3().uniform(2);
1057
+ // Rect light specular (evaluateLTCRectLightTerms).
1058
+ scope.zLTCMatLut = pb.tex2D().uniform(2);
1059
+ scope.zLTCAmpLut = pb.tex2D().uniform(2);
1060
+ }
1061
+ if (!this.infinite) {
1062
+ scope.$l.discardable = pb.or(pb.any(pb.lessThan(scope.$inputs.worldPos.xz, scope.region.xy)), pb.any(pb.greaterThan(scope.$inputs.worldPos.xz, scope.region.zw)));
1063
+ scope.$if(scope.discardable, function() {
1064
+ pb.discard();
1065
+ });
1066
+ }
1067
+ if (this.debugOutput === 'shoreRegions' || this.debugOutput === 'shoreLevels') {
1068
+ // Show the actual displaced carrier in every pass. Wet-edge discard and
1069
+ // ground-depth projection would otherwise conceal its geometry or create
1070
+ // an apparent boundary unrelated to rasterized mesh coverage.
1071
+ if (this.needFragmentColor()) {
1072
+ if (this.debugOutput === 'shoreLevels') {
1073
+ scope.$l.outColor = pb.vec4(this._shoreWaveGenerator ? this._shoreWaveGenerator.calcDebugLevels(scope, scope.$inputs.clipmapPos.xz) : pb.vec3(0.1), 1);
1074
+ } else {
1075
+ scope.$l.shoreRegion = this._shoreWaveGenerator ? this._shoreWaveGenerator.calcDebugRegion(scope, scope.$inputs.clipmapPos.xz) : pb.vec3(0, 0, 1);
1076
+ scope.$l.shoreColor = scope.$choice(pb.greaterThan(scope.shoreRegion.y, 0.5), scope.$choice(pb.greaterThan(scope.shoreRegion.z, 1e-3), pb.vec3(1, 0.3, 0.02), pb.vec3(0.85, 0.02, 0.8)), pb.vec3(0, 0.85, 1));
1077
+ scope.$l.outColor = pb.vec4(pb.mix(pb.vec3(0.02, 0.12, 0.9), scope.shoreColor, scope.shoreRegion.x), 1);
1078
+ }
1079
+ if (this.drawContext.materialFlags & (MaterialVaryingFlags.SCENE_STORE_ROUGHNESS | MaterialVaryingFlags.SCENE_STORE_NORMAL)) {
1080
+ this.outputFragmentColor(scope, scope.$inputs.worldPos, scope.outColor, pb.vec4(0), scope.outColor);
1081
+ } else {
1082
+ this.outputFragmentColor(scope, scope.$inputs.worldPos, scope.outColor);
1083
+ }
1084
+ } else {
1085
+ this.outputFragmentColor(scope, scope.$inputs.worldPos, null);
1086
+ }
1087
+ return;
216
1088
  }
217
- scope.$l.discardable = pb.or(pb.any(pb.lessThan(scope.$inputs.worldPos.xz, scope.region.xy)), pb.any(pb.greaterThan(scope.$inputs.worldPos.xz, scope.region.zw)));
218
- scope.$if(scope.discardable, function() {
219
- pb.discard();
220
- });
221
1089
  if (this.needFragmentColor()) {
222
- scope.$l.normal = this.waveGenerator ? this.waveGenerator.calcFragmentNormalAndFoam(scope, scope.$inputs.clipmapPos.xz, scope.$inputs.worldNormal) : pb.vec4(scope.$inputs.worldNormal, 0);
223
- scope.$l.outColor = pb.vec4(this.waterShading(scope, scope.$inputs.worldPos, scope.normal.xyz, scope.normal.w), 1);
1090
+ // Screen derivatives of the undisplaced position, taken here in uniform
1091
+ // control flow; the foam textures are sampled with them under branches.
1092
+ scope.$l.restXZGrad = pb.vec4(pb.dpdx(scope.$inputs.clipmapPos.xz), pb.dpdy(scope.$inputs.clipmapPos.xz));
1093
+ // The foam texture here, drifting; a generator carrying foam of its own
1094
+ // blends in where its foam is
1095
+ scope.$l.foamSample = sampleFoamTexture(scope, scope.foamTex, pb.mul(pb.add(scope.$inputs.clipmapPos.xz, pb.vec2(pb.mul(ShaderHelper.getElapsedTime(scope), FOAM_DRIFT))), scope.foamUVScale), scope.restXZGrad, scope.foamUVScale);
1096
+ scope.$l.normal = this.waveGenerator ? this.waveGenerator.calcFragmentNormalAndFoam(scope, scope.$inputs.clipmapPos.xz, scope.$inputs.worldNormal, scope.foamSample, this.waveGenerator.calcUnresolvedSlopeVariance ? scope.restXZGrad : undefined) : pb.vec4(scope.$inputs.worldNormal, 0);
1097
+ if (this.infinite) {
1098
+ // Flat and foamless on the skirt: waves evaluated at kilometres per
1099
+ // pixel alias into speckle.
1100
+ scope.normal = pb.mix(scope.normal, pb.vec4(0, 1, 0, 0), scope.$inputs.skirt);
1101
+ }
1102
+ // Vertical wave displacement, interpolated from the vertices. Zero on the skirt.
1103
+ scope.$l.crestHeight = pb.sub(scope.$inputs.worldPos.y, scope.$inputs.clipmapPos.y);
1104
+ const surfaceCoverage = this.waveGenerator?.calcSurfaceCoverage;
1105
+ scope.$l.surfaceCoverage = surfaceCoverage ? surfaceCoverage.call(this.waveGenerator, scope, scope.$inputs.clipmapPos.xz) : pb.float(1);
1106
+ const sheetThickness = this.waveGenerator?.calcSheetThickness;
1107
+ scope.$l.sheetThickness = sheetThickness ? sheetThickness.call(this.waveGenerator, scope, scope.$inputs.clipmapPos.xz) : pb.float(-1);
1108
+ if (this._shoreWaveGenerator) {
1109
+ // Near the shore the foam is at least the near-shore density, joining
1110
+ // the breaking waves' foam to the beach's (see nearShore).
1111
+ scope.normal.w = this._shoreWaveGenerator.calcNearShoreFoam(scope, scope.$inputs.clipmapPos.xz, scope.normal.w);
1112
+ }
1113
+ // Reconstruct the opaque surface before the swash's discard. Deposited
1114
+ // foam is projected onto this ground, independently of the raised mesh.
1115
+ scope.$l.scenePos = ShaderHelper.samplePositionFromDepth(scope, ShaderHelper.getLinearDepthTexture(scope), pb.div(scope.$builtins.fragCoord.xy, ShaderHelper.getRenderSize(scope)), ShaderHelper.getJitteredInvVPMatrix(scope), ShaderHelper.getCameraParams(scope).xy);
1116
+ scope.$l.groundFoamDensity = pb.float(0);
1117
+ scope.$l.groundFoamSample = pb.vec3(0);
1118
+ scope.$l.groundFoamWeight = pb.float(0);
1119
+ scope.$l.groundNormal = pb.vec3(0, 1, 0);
1120
+ if (this.debugOutput === 'swashVisibility') {
1121
+ scope.$l.visibilityDepthFail = pb.float(0);
1122
+ }
1123
+ if (this.debugOutput === 'swashGroundSupport') {
1124
+ scope.$l.groundFieldCoverage = pb.float(0);
1125
+ scope.$l.groundWetCoverage = pb.float(0);
1126
+ } else if (this.debugOutput === 'swashHandover') {
1127
+ scope.$l.groundWetCoverage = pb.float(0);
1128
+ } else if (this.debugOutput === 'swashFoamSources') {
1129
+ scope.$l.groundFieldDensity = pb.float(0);
1130
+ scope.$l.groundSurfDensity = pb.float(0);
1131
+ }
1132
+ if (this._shoreWaveGenerator && this._foamFieldGenerator) {
1133
+ // Derivatives precede all coverage branches; pattern coordinates stay
1134
+ // fixed to the sand even while the water and camera move.
1135
+ scope.$l.groundGrad = pb.vec4(pb.dpdx(scope.scenePos.xz), pb.dpdy(scope.scenePos.xz));
1136
+ scope.$l.groundCross = pb.cross(pb.dpdx(scope.scenePos.xyz), pb.dpdy(scope.scenePos.xyz));
1137
+ scope.groundNormal = pb.normalize(pb.add(pb.mul(scope.groundCross, pb.sign(scope.groundCross.y)), pb.vec3(0, 1e-8, 0)));
1138
+ scope.$l.groundMask = this._shoreWaveGenerator.calcFoamGroundMask(scope, scope.scenePos.xyz);
1139
+ const field = this._foamField;
1140
+ const shore = this._shoreWaveGenerator;
1141
+ const debugOutput = this.debugOutput;
1142
+ scope.$if(pb.and(pb.lessThan(scope.scenePos.w, SCENE_SKY_DEPTH01), pb.greaterThan(scope.groundMask, 0)), function() {
1143
+ // The field's foam at the actual ground position: on a thin sheet and
1144
+ // on the sand it drained from alike, the field holding it there
1145
+ // (FOAM_SETTLE of the shore waves)
1146
+ this.$l.groundMobile = field.sample(this, this.scenePos.xz);
1147
+ this.$l.groundWet = shore.calcSurfaceCoverage(this, this.scenePos.xz);
1148
+ this.$l.groundThickness = shore.calcSheetThickness(this, this.scenePos.xz);
1149
+ // Coverage and handover describe the same carrier point. Using the
1150
+ // ground point's thickness here leaves a gap at grazing angles:
1151
+ // the carrier can be dry while its projected ground is still wet.
1152
+ this.$l.groundHandoverThickness = this.$choice(pb.greaterThanEqual(this.sheetThickness, 0), this.sheetThickness, this.groundThickness);
1153
+ if (debugOutput === 'swashGroundSupport') {
1154
+ this.groundWetCoverage = this.groundWet;
1155
+ this.groundFieldCoverage = this.groundMobile.y;
1156
+ } else if (debugOutput === 'swashHandover') {
1157
+ this.groundWetCoverage = this.groundWet;
1158
+ } else if (debugOutput === 'swashFoamSources') {
1159
+ this.groundFieldDensity = this.groundMobile.x;
1160
+ this.groundSurfDensity = pb.mul(shore.calcNearShoreFoam(this, this.scenePos.xz, pb.float(0)), this.groundWet);
1161
+ }
1162
+ this.groundFoamWeight = pb.mul(this.groundMask, this.groundMobile.y, // Unknown thickness must retain the water surface. In particular,
1163
+ // a valid sand bed outside the shore-wave zone is not a dry sheet.
1164
+ this.$choice(pb.greaterThanEqual(this.groundHandoverThickness, 0), pb.sub(1, pb.smoothStep(0.01, 0.06, this.groundHandoverThickness)), pb.float(0)));
1165
+ // The surf's foam only where the sheet now is; the field's wherever it holds it
1166
+ this.groundFoamDensity = pb.clamp(pb.max(this.groundMobile.x, pb.mul(shore.calcNearShoreFoam(this, this.scenePos.xz, pb.float(0)), this.groundWet)), 0, 1);
1167
+ this.$if(pb.greaterThan(this.groundFoamDensity, 1e-3), function() {
1168
+ // The water's foam pattern at the ground: it stands still near
1169
+ // the shore (see nearShore), so the beach's foam and the water's
1170
+ // are one pattern through the handover.
1171
+ this.groundFoamSample = WaterFoamField.flowPattern(this, this.ffFoamTex, this.ffFoamUVScale, this.ffClock.x, this.scenePos.xz, this.groundGrad, shore.calcFoamFlow(this, this.scenePos.xz, this.ffDrift));
1172
+ });
1173
+ });
1174
+ // The thin-film foam and its depth use the same ground transition.
1175
+ // Otherwise a wet carrier can still clip the projected foam against
1176
+ // the terrain right where the two layers meet.
1177
+ scope.$builtins.fragDepth = pb.mix(scope.$builtins.fragCoord.z, ShaderHelper.linearNormalizedToNonLinearDepth(scope, pb.max(pb.sub(scope.scenePos.w, pb.div(0.001, ShaderHelper.getCameraParams(scope).y)), 0), ShaderHelper.getCameraParams(scope).xy), scope.$choice(pb.lessThanEqual(scope.surfaceCoverage, 1e-3), pb.float(1), scope.groundFoamWeight));
1178
+ }
1179
+ const revealSwash = this.debugOutput === 'foamField' || this.debugOutput === 'swashVisibility' || this.debugOutput === 'swashGroundSupport';
1180
+ if (revealSwash && this._shoreWaveGenerator && this._foamFieldGenerator) {
1181
+ if (this.debugOutput === 'swashVisibility') {
1182
+ scope.visibilityDepthFail = scope.$choice(pb.greaterThan(pb.mul(pb.sub(ShaderHelper.nonLinearDepthToLinearNormalized(scope, scope.$builtins.fragDepth), scope.scenePos.w), ShaderHelper.getCameraParams(scope).y), 0.0001), pb.float(1), pb.float(0));
1183
+ }
1184
+ scope.$if(pb.and(pb.lessThan(scope.scenePos.w, SCENE_SKY_DEPTH01), pb.greaterThan(scope.groundMask, 0)), function() {
1185
+ this.$builtins.fragDepth = ShaderHelper.linearNormalizedToNonLinearDepth(this, pb.max(pb.sub(this.scenePos.w, pb.div(0.001, ShaderHelper.getCameraParams(this).y)), 0), ShaderHelper.getCameraParams(this).xy);
1186
+ });
1187
+ }
1188
+ scope.$l.swashDiscard = pb.and(pb.lessThanEqual(scope.surfaceCoverage, 1e-3), pb.lessThanEqual(pb.mul(scope.groundFoamDensity, scope.groundFoamWeight), 1e-3));
1189
+ // Past the wet edge, only the foam actually left on the ground draws.
1190
+ if (surfaceCoverage && !revealSwash) {
1191
+ scope.$if(scope.swashDiscard, function() {
1192
+ pb.discard();
1193
+ });
1194
+ }
1195
+ if (this.debugOutput === 'swashGroundSupport') {
1196
+ scope.$l.outColor = pb.vec4(this._shoreWaveGenerator && this._foamFieldGenerator ? scope.groundMask : pb.float(0), scope.groundFieldCoverage, scope.groundWetCoverage, 1);
1197
+ } else if (this.debugOutput === 'swashVisibility') {
1198
+ scope.$l.outColor = pb.vec4(scope.$choice(scope.swashDiscard, pb.float(1), pb.float(0)), scope.visibilityDepthFail, scope.groundFoamDensity, 1);
1199
+ } else if (this.debugOutput === 'swashHandover') {
1200
+ scope.$l.outColor = pb.vec4(scope.surfaceCoverage, scope.groundWetCoverage, scope.groundFoamWeight, 1);
1201
+ } else if (this.debugOutput === 'swashFoamSources') {
1202
+ scope.$l.outColor = pb.vec4(scope.normal.w, scope.groundFieldDensity, scope.groundSurfDensity, 1);
1203
+ } else if (this.debugOutput === 'interaction') {
1204
+ // The field on its own, grey at rest, scaled so its amplitude clamp
1205
+ // reaches black and white; dimmed outside the window so its reach shows.
1206
+ if (this._interactiveWaveGenerator) {
1207
+ const interaction = this._interactiveWaveGenerator.interaction;
1208
+ scope.$l.wiDebugHeight = pb.div(interaction.sampleHeight(scope, scope.$inputs.clipmapPos.xz), scope.wiParams2.y);
1209
+ scope.$l.wiDebugMask = pb.mix(pb.float(0.55), pb.float(1), interaction.windowMask(scope, scope.$inputs.clipmapPos.xz));
1210
+ } else {
1211
+ scope.$l.wiDebugHeight = pb.float(0);
1212
+ scope.$l.wiDebugMask = pb.float(1);
1213
+ }
1214
+ scope.$l.outColor = pb.vec4(pb.vec3(pb.mul(pb.add(0.5, pb.mul(scope.wiDebugHeight, 0.5)), scope.wiDebugMask)), 1);
1215
+ } else if (this.debugOutput === 'foamField') {
1216
+ // The field's density; mid grey off the field, where coverage is 0
1217
+ if (this._foamFieldGenerator) {
1218
+ scope.$l.ffDebug = this._foamField.sample(scope, scope.$inputs.clipmapPos.xz);
1219
+ } else {
1220
+ scope.$l.ffDebug = pb.vec3(0);
1221
+ }
1222
+ scope.$l.outColor = pb.vec4(pb.vec3(pb.mix(pb.float(0.5), pb.max(scope.ffDebug.x, scope.ffDebug.z), scope.ffDebug.y)), 1);
1223
+ } else {
1224
+ // The foam field's wall foam layer, see FOAM_WALL
1225
+ scope.$l.wallFoam = this._foamFieldGenerator ? pb.mul(this._foamField.sample(scope, scope.$inputs.clipmapPos.xz).z, this.infinite ? pb.sub(1, scope.$inputs.skirt) : pb.float(1)) : pb.float(0);
1226
+ scope.$l.outColor = pb.vec4(this.waterShading(scope, scope.$inputs.worldPos, scope.normal.xyz, scope.normal.w, scope.crestHeight, scope.$inputs.clipmapPos.xz, scope.restXZGrad, scope.foamSample, scope.surfaceCoverage, scope.sheetThickness, scope.wallFoam, scope.scenePos, scope.groundFoamDensity, scope.groundFoamSample, scope.groundNormal, scope.groundFoamWeight), 1);
1227
+ }
224
1228
  if (this.drawContext.materialFlags & (MaterialVaryingFlags.SCENE_STORE_ROUGHNESS | MaterialVaryingFlags.SCENE_STORE_NORMAL)) {
225
- scope.$l.outRoughness = pb.vec4(1, 1, 1, 0);
1229
+ scope.$l.outRoughness = pb.vec4(pb.vec3(this.waterRoughness(scope, scope.$inputs.worldPos, scope.restXZGrad)), 0);
226
1230
  this.outputFragmentColor(scope, scope.$inputs.worldPos, scope.outColor, scope.outRoughness, scope.outColor);
227
1231
  } else {
228
1232
  this.outputFragmentColor(scope, scope.$inputs.worldPos, scope.outColor);
229
1233
  }
230
1234
  } else {
1235
+ // The support mesh over dry sand is only a carrier for the colour pass.
1236
+ // It must not replace terrain depth or its motion vectors in other passes.
1237
+ const coverage = this.waveGenerator?.calcSurfaceCoverage;
1238
+ if (coverage) {
1239
+ scope.$l.surfaceCoverage = coverage.call(this.waveGenerator, scope, scope.$inputs.clipmapPos.xz);
1240
+ scope.$if(pb.lessThanEqual(scope.surfaceCoverage, 1e-3), function() {
1241
+ pb.discard();
1242
+ });
1243
+ }
231
1244
  this.outputFragmentColor(scope, scope.$inputs.worldPos, null);
232
1245
  }
233
1246
  }
234
- waterShading(scope, worldPos, worldNormal, foamFactor) {
1247
+ /**
1248
+ * Covariance (x, z, xz) of the wave slopes the shading normal no longer shows
1249
+ * at this pixel, or null when the wave generator cannot tell.
1250
+ */ unresolvedSlopeVariance(scope, restXZGrad) {
1251
+ const gen = this.waveGenerator;
1252
+ return gen?.calcUnresolvedSlopeVariance ? gen.calcUnresolvedSlopeVariance(scope, restXZGrad) : null;
1253
+ }
1254
+ /**
1255
+ * Specular roughness at a world position. The slopes too fine for the pixel
1256
+ * leave the normal and are handed to the lobe, GGX alpha^2 taking their
1257
+ * variance (Beckmann m^2 = 2 sigma^2 per axis). Without the generator's
1258
+ * account of them, distance flattens the normals and the lobe widens with it.
1259
+ * Also written to the scene roughness buffer.
1260
+ */ waterRoughness(scope, worldPos, restXZGrad) {
1261
+ const pb = scope.$builder;
1262
+ const that = this;
1263
+ pb.func('waterRoughness', [
1264
+ pb.vec3('worldPos'),
1265
+ pb.vec4('restXZGrad')
1266
+ ], function() {
1267
+ const slopeVar = that.unresolvedSlopeVariance(this, this.restXZGrad);
1268
+ if (slopeVar) {
1269
+ this.$l.slopeVar = slopeVar;
1270
+ this.$l.alpha2 = pb.add(WATER_BASE_ROUGHNESS ** 4, pb.max(pb.add(this.slopeVar.x, this.slopeVar.y), 0));
1271
+ this.$return(pb.sqrt(pb.sqrt(this.alpha2)));
1272
+ } else {
1273
+ this.$l.dist = pb.length(pb.sub(this.worldPos, ShaderHelper.getCameraPosition(this)));
1274
+ this.$l.normalScale = pb.clamp(pb.div(100, this.dist), 0, 1);
1275
+ this.$return(pb.mix(WATER_DISTANT_ROUGHNESS, WATER_BASE_ROUGHNESS, this.normalScale));
1276
+ }
1277
+ });
1278
+ return scope.waterRoughness(worldPos, restXZGrad);
1279
+ }
1280
+ /**
1281
+ * Where to sample the scene behind the water, and the medium path length to it.
1282
+ *
1283
+ * Refracts the view ray by Snell's law and marches it against the scene depth.
1284
+ * Depth-convention independent: projection only reads `clip.xy / clip.w` and
1285
+ * all depth comparisons are in view space.
1286
+ *
1287
+ * @param scope - Current shader scope
1288
+ * @param worldPos - Surface point being shaded
1289
+ * @param normal - Wave normal at that point, pointing up out of the water
1290
+ * @param eyeVecNorm - Normalized direction from the camera to the surface
1291
+ * @param screenUV - Screen UV of the surface point
1292
+ * @param surfaceViewZ - View-space z of the surface point
1293
+ * @param straightDepth01 - Normalized linear depth of the scene behind it
1294
+ * @param straightWorldPos - Unrefracted scene world position behind the surface
1295
+ * @param straightDist - Straight-line distance from the surface to that scene
1296
+ * @param underwater - Whether the eye is below the surface
1297
+ * @returns `vec3(uv, pathLength)` - where to sample, and the medium path in meters,
1298
+ * {@link BOTTOMLESS_PATH} with only sky behind the surface
1299
+ */ waterRefraction(scope, worldPos, normal, eyeVecNorm, screenUV, surfaceViewZ, straightDepth01, straightWorldPos, straightDist, underwater) {
1300
+ const pb = scope.$builder;
1301
+ const march = this.refractionMode === 'march';
1302
+ // Only ever used as a difference of two UVs, so TAA jitter and clip-space Y
1303
+ // orientation cancel. Inverse of ShaderHelper.samplePositionFromDepth's mapping.
1304
+ pb.func('waterRefractProjectUV', [
1305
+ pb.vec3('worldPos')
1306
+ ], function() {
1307
+ this.$l.h = pb.mul(ShaderHelper.getViewProjectionMatrix(this), pb.vec4(this.worldPos, 1));
1308
+ this.$return(pb.add(pb.mul(pb.div(this.h.xy, pb.max(this.h.w, 1e-6)), 0.5), pb.vec2(0.5)));
1309
+ });
1310
+ // Sample UV for a refracted ray ending at `hitPos`, faded to the straight
1311
+ // sample at the screen border.
1312
+ pb.func('waterRefractUV', [
1313
+ pb.vec2('screenUV'),
1314
+ pb.vec2('uvBase'),
1315
+ pb.vec3('hitPos'),
1316
+ pb.float('scale')
1317
+ ], function() {
1318
+ this.$l.uv = pb.add(this.screenUV, pb.mul(pb.sub(this.waterRefractProjectUV(this.hitPos), this.uvBase), this.scale));
1319
+ this.$l.edge = pb.min(pb.min(this.uv.x, pb.sub(1, this.uv.x)), pb.min(this.uv.y, pb.sub(1, this.uv.y)));
1320
+ this.$return(pb.mix(this.screenUV, this.uv, pb.clamp(pb.div(this.edge, REFRACT_EDGE_FADE), 0, 1)));
1321
+ });
1322
+ // Declared only in `march` mode: a dead function still forces the depth
1323
+ // texture and projection matrices into the bind group.
1324
+ if (march) {
1325
+ // Returns (uv, rayViewZ - sceneViewZ) at `t` meters along the ray.
1326
+ // Positive: ray still in front of the scene. Negative: passed through it.
1327
+ pb.func('waterRefractStep', [
1328
+ pb.vec3('worldPos'),
1329
+ pb.vec3('refractDir'),
1330
+ pb.vec2('screenUV'),
1331
+ pb.vec2('uvBase'),
1332
+ pb.float('rayViewZ'),
1333
+ pb.float('cameraFar'),
1334
+ pb.float('t')
1335
+ ], function() {
1336
+ this.$l.uv = this.waterRefractUV(this.screenUV, this.uvBase, pb.add(this.worldPos, pb.mul(this.refractDir, this.t)), this.refractionScale);
1337
+ this.$l.linearDepth = ShaderHelper.sampleLinearDepth(this, ShaderHelper.getLinearDepthTexture(this), this.uv, 0);
1338
+ this.$l.sceneViewZ = pb.mul(pb.neg(this.linearDepth), this.cameraFar);
1339
+ this.$return(pb.vec3(this.uv, pb.sub(this.rayViewZ, this.sceneViewZ)));
1340
+ });
1341
+ // First crossing of the refracted ray with the depth buffer. A hit is a
1342
+ // step inside the thickness band or a sign change of the gap; an object
1343
+ // poking out of the water is negative from the first step and never hits.
1344
+ pb.func('waterRefractMarch', [
1345
+ pb.vec3('worldPos'),
1346
+ pb.vec3('refractDir'),
1347
+ pb.vec2('screenUV'),
1348
+ pb.vec2('uvBase'),
1349
+ pb.float('surfaceViewZ'),
1350
+ pb.float('refractStepZ'),
1351
+ pb.float('cameraFar'),
1352
+ pb.float('maxPath'),
1353
+ pb.float('basePath')
1354
+ ], function() {
1355
+ this.$l.step = pb.div(pb.sub(this.maxPath, 0.05), pb.float(REFRACT_MARCH_STEPS));
1356
+ this.$l.tPrev = pb.float(0.05);
1357
+ this.$l.gapPrev = pb.float(1);
1358
+ this.$l.hitUV = this.screenUV;
1359
+ this.$l.hitPath = this.basePath;
1360
+ this.$for(pb.float('i'), 0, REFRACT_MARCH_STEPS, function() {
1361
+ this.$l.t = pb.add(this.tPrev, this.step);
1362
+ this.$l.rayViewZ = pb.add(this.surfaceViewZ, pb.mul(this.refractStepZ, this.t));
1363
+ this.$l.s = this.waterRefractStep(this.worldPos, this.refractDir, this.screenUV, this.uvBase, this.rayViewZ, this.cameraFar, this.t);
1364
+ this.$l.gap = this.s.z;
1365
+ this.$if(pb.or(pb.lessThan(pb.abs(this.gap), REFRACT_MARCH_THICKNESS), pb.lessThan(pb.mul(this.gapPrev, this.gap), 0)), function() {
1366
+ // Interpolate to the exact crossing.
1367
+ this.$l.k = pb.div(this.gapPrev, pb.sub(this.gapPrev, this.gap));
1368
+ this.hitUV = this.s.xy;
1369
+ this.hitPath = pb.mix(this.tPrev, this.t, this.k);
1370
+ this.$break();
1371
+ }).$else(function() {
1372
+ this.tPrev = this.t;
1373
+ this.gapPrev = this.gap;
1374
+ });
1375
+ });
1376
+ this.$return(pb.vec3(this.hitUV, this.hitPath));
1377
+ });
1378
+ }
1379
+ pb.func('waterRefraction', [
1380
+ pb.vec3('worldPos'),
1381
+ pb.vec3('normal'),
1382
+ pb.vec3('eyeVecNorm'),
1383
+ pb.vec2('screenUV'),
1384
+ pb.float('surfaceViewZ'),
1385
+ pb.float('straightDepth01'),
1386
+ pb.vec3('straightWorldPos'),
1387
+ pb.float('straightDist'),
1388
+ pb.bool('underwater')
1389
+ ], function() {
1390
+ this.$l.faceNormal = this.$choice(this.underwater, pb.neg(this.normal), this.normal);
1391
+ this.$l.eta = this.$choice(this.underwater, pb.float(WATER_TO_AIR_ETA), pb.float(AIR_TO_WATER_ETA));
1392
+ this.$l.uvBase = this.waterRefractProjectUV(this.worldPos);
1393
+ // Sky behind the water has no bottom. Its point lies on the far plane,
1394
+ // so the straight distance falls to 0 where the surface crosses that
1395
+ // plane and the water there would show the sky unabsorbed.
1396
+ this.$if(pb.greaterThanEqual(this.straightDepth01, SCENE_SKY_DEPTH01), function() {
1397
+ this.$return(pb.vec3(this.screenUV, SKY_MEDIUM_PATH));
1398
+ });
1399
+ this.$l.waterCrossDir = pb.normalize(pb.sub(this.straightWorldPos, this.worldPos));
1400
+ // refractDir = view line + (refract by wave normal - refract by flat
1401
+ // normal), so calm water samples exactly the straight hit. The flat
1402
+ // normal carries the same facing flip so the two cancel from either side.
1403
+ this.$l.refractWave = pb.refract(this.eyeVecNorm, this.faceNormal, this.eta);
1404
+ this.$l.refractFlatNormal = pb.vec3(0, pb.sign(this.faceNormal.y), 0);
1405
+ this.$l.refractFlat = pb.refract(this.eyeVecNorm, this.refractFlatNormal, this.eta);
1406
+ // Total internal reflection makes refract return zero.
1407
+ this.$l.refractDir = pb.add(this.waterCrossDir, pb.sub(this.refractWave, this.refractFlat));
1408
+ this.$if(pb.lessThan(pb.length(pb.sub(this.refractWave, this.refractFlat)), 1e-4), function() {
1409
+ this.refractDir = this.waterCrossDir;
1410
+ });
1411
+ this.$if(pb.lessThan(pb.dot(this.refractDir, this.refractDir), 1e-6), function() {
1412
+ this.refractDir = this.waterCrossDir;
1413
+ });
1414
+ this.refractDir = pb.normalize(this.refractDir);
1415
+ this.$l.refractUV = this.screenUV;
1416
+ this.$l.refractPath = this.straightDist;
1417
+ if (!march) {
1418
+ // Fixed step, not the scene distance: that jumps across silhouettes
1419
+ // and paints a second copy of the object.
1420
+ this.refractUV = this.waterRefractUV(this.screenUV, this.uvBase, pb.add(this.worldPos, pb.mul(this.refractDir, this.cheapRefractionDepth)), this.refractionScale);
1421
+ this.$return(pb.vec3(this.refractUV, this.refractPath));
1422
+ } else {
1423
+ this.$l.refractDirView = pb.mul(ShaderHelper.getViewMatrix(this), pb.vec4(this.refractDir, 0)).xyz;
1424
+ this.$l.refractStepZ = pb.min(this.refractDirView.z, -1e-4);
1425
+ this.$l.maxPath = pb.mul(this.straightDist, REFRACT_MAX_PATH_RATIO);
1426
+ this.$l.marchResult = this.waterRefractMarch(this.worldPos, this.refractDir, this.screenUV, this.uvBase, this.surfaceViewZ, this.refractStepZ, ShaderHelper.getCameraParams(this).y, this.maxPath, this.straightDist);
1427
+ this.refractUV = this.marchResult.xy;
1428
+ this.refractPath = pb.clamp(this.marchResult.z, 0, this.maxPath);
1429
+ // A finite scene point above the surface at the refracted UV is an
1430
+ // object poking through: fall back to the straight sample.
1431
+ this.$l.sceneHit = ShaderHelper.samplePositionFromDepth(this, ShaderHelper.getLinearDepthTexture(this), this.refractUV, ShaderHelper.getJitteredInvVPMatrix(this), ShaderHelper.getCameraParams(this).xy);
1432
+ this.$if(pb.and(pb.lessThan(this.sceneHit.w, 0.999), pb.greaterThan(this.sceneHit.y, this.worldPos.y)), function() {
1433
+ this.refractUV = this.screenUV;
1434
+ this.refractPath = this.straightDist;
1435
+ });
1436
+ this.$return(pb.vec3(this.refractUV, this.refractPath));
1437
+ }
1438
+ });
1439
+ return scope.waterRefraction(worldPos, normal, eyeVecNorm, screenUV, surfaceViewZ, straightDepth01, straightWorldPos, straightDist, underwater);
1440
+ }
1441
+ /**
1442
+ * Sunlight scattered out of the water column towards the eye. Closed-form
1443
+ * single scattering in a homogeneous medium.
1444
+ *
1445
+ * With `t` the distance along the refracted view ray, `d` its length in the
1446
+ * water, `vy`/`sy` the descent rates of the view and sun rays, and
1447
+ * `r = vy / sy`:
1448
+ *
1449
+ * ```
1450
+ * S = integral(0..d) sigma_s * p * E * exp(-sigma_t * t * (1 + r)) dt
1451
+ * = albedo * p * E * (1 - exp(-sigma_t * (1 + r) * d)) / (1 + r)
1452
+ * ```
1453
+ *
1454
+ * No `NoL` factor: that geometry is already in `r`. Only the entry Fresnel is
1455
+ * applied; the exit transmission is applied once by the caller. Assumes the
1456
+ * eye is above the surface.
1457
+ *
1458
+ * @param scope - Current shader scope.
1459
+ * @param lightEnergy - Sun irradiance perpendicular to the beam, after shadowing.
1460
+ * @param lightDir - Unit vector from the surface towards the light.
1461
+ * @param eyeVecNorm - Unit vector from the camera towards the surface.
1462
+ * @param NoL - Cosine of the sun's incidence on the wave normal.
1463
+ * @param depth - Refracted path length through the medium, in meters.
1464
+ * @returns Radiance scattered towards the eye, before the exit Fresnel.
1465
+ */ waterSunScattering(scope, lightEnergy, lightDir, eyeVecNorm, NoL, depth, foam) {
1466
+ const pb = scope.$builder;
1467
+ pb.func('waterSunScattering', [
1468
+ pb.vec3('lightEnergy'),
1469
+ pb.vec3('lightDir'),
1470
+ pb.vec3('eyeVecNorm'),
1471
+ pb.float('NoL'),
1472
+ pb.float('depth'),
1473
+ pb.float('foam')
1474
+ ], function() {
1475
+ this.$l.up = pb.vec3(0, 1, 0);
1476
+ // Directions inside the water. The sun travels opposite to `lightDir`.
1477
+ this.$l.Lw = pb.refract(pb.neg(this.lightDir), this.up, AIR_TO_WATER_ETA);
1478
+ this.$l.Vw = pb.refract(this.eyeVecNorm, this.up, AIR_TO_WATER_ETA);
1479
+ this.$l.sy = pb.max(pb.neg(this.Lw.y), MIN_SUN_SLOPE);
1480
+ this.$l.vy = pb.max(pb.neg(this.Vw.y), 1e-3);
1481
+ this.$l.r = pb.div(this.vy, this.sy);
1482
+ this.$l.rr = pb.add(1, this.r);
1483
+ this.$l.cosTheta = pb.neg(pb.dot(this.Lw, this.Vw));
1484
+ this.$l.hg = waterScatterPhase(this, this.cosTheta, this.sunScatterParams.y);
1485
+ // Blend towards isotropic with optical thickness (multiple scattering).
1486
+ // Luminance-weighted: the phase is wavelength independent.
1487
+ this.$l.lumWeights = pb.vec3(0.2126, 0.7152, 0.0722);
1488
+ this.$l.extLum = pb.dot(this.mediumExtinction, this.lumWeights);
1489
+ this.$l.albedoLum = pb.dot(this.mediumAlbedo, this.lumWeights);
1490
+ this.$l.thickness = pb.mul(this.albedoLum, pb.sub(1, pb.exp(pb.neg(pb.mul(this.extLum, this.depth)))));
1491
+ this.$l.phase = pb.mix(this.hg, 1 / (4 * Math.PI), pb.smoothStep(0, 0.5, pb.clamp(this.thickness, 0, 1)));
1492
+ this.$l.k = pb.mul(this.mediumExtinction, this.rr);
1493
+ this.$l.integral = pb.div(pb.sub(pb.vec3(1), pb.exp(pb.neg(pb.mul(this.k, this.depth)))), this.rr);
1494
+ // Entry Fresnel. Zero at NoL <= 0, where the subsurface term takes over.
1495
+ // Foam is a mass of bubbles, not a mirror, so it blends towards full
1496
+ // transmission.
1497
+ this.$l.entry = pb.sub(1, pb.add(WATER_F0, pb.mul(1 - WATER_F0, pb.pow(pb.sub(1, this.NoL), 5))));
1498
+ this.$l.entry = pb.mix(this.entry, pb.float(1), this.foam);
1499
+ this.$return(pb.mul(this.mediumAlbedo, this.lightEnergy, this.integral, pb.mul(this.phase, this.entry, this.sunScatterParams.x)));
1500
+ });
1501
+ return scope.waterSunScattering(lightEnergy, lightDir, eyeVecNorm, NoL, depth, foam);
1502
+ }
1503
+ waterShading(scope, worldPos, worldNormal, foamFactor, crestHeight, restXZ, restXZGrad, foamSample, coverage, sheetThickness, wallFoam, scenePos, groundFoamDensity, groundFoamSample, groundNormal, groundFoamWeight) {
235
1504
  const pb = scope.$builder;
236
1505
  const that = this;
1506
+ const debugOutput = this.debugOutput;
1507
+ const hasGroundFoam = !!(this._shoreWaveGenerator && this._foamFieldGenerator);
1508
+ // The environment's prefiltered radiance, for the distant sky reflection
1509
+ const envLight = this.needCalculateEnvLight() ? this.drawContext.env?.light.envLight ?? null : null;
1510
+ // Transmittance over `depth` meters of path.
237
1511
  pb.func('getAbsorption', [
238
1512
  pb.float('depth')
239
1513
  ], function() {
240
- this.$l.c = pb.textureSampleLevel(this.absorptionRampTex, pb.vec2(pb.mul(this.depth, this.depthMulti), 0.5), 0).rgb;
241
- this.$return(pb.mul(this.c, this.c));
1514
+ this.$return(pb.exp(pb.neg(pb.mul(this.mediumExtinction, this.depth))));
242
1515
  });
1516
+ // Fraction of incident irradiance scattered back over `depth` meters of path.
243
1517
  pb.func('getScattering', [
244
1518
  pb.float('depth')
245
1519
  ], function() {
246
- this.$l.c = pb.textureSampleLevel(this.scatterRampTex, pb.vec2(pb.mul(this.depth, this.depthMulti), 0.5), 0).rgb;
247
- this.$return(pb.mul(this.c, this.c));
1520
+ this.$return(pb.mul(this.mediumAlbedo, pb.sub(pb.vec3(1), pb.exp(pb.neg(pb.mul(this.mediumExtinction, this.depth))))));
1521
+ });
1522
+ // Mean Fresnel over a Gaussian distribution of unresolved slopes of standard
1523
+ // deviation `sigmaV` along the view direction, Bruneton, Neyret & Holzschuch,
1524
+ // "Real-time Realistic Ocean Lighting using Seamless Transitions from Geometry
1525
+ // to BRDF" (Eurographics 2010), as their ocean demo fits it:
1526
+ // (1 - cos)^(5 exp(-2.69 sigma)) / (1 + 22.7 sigma^1.5), Schlick at sigma = 0.
1527
+ pb.func('meanFresnel', [
1528
+ pb.float('cosThetaV'),
1529
+ pb.float('sigmaV')
1530
+ ], function() {
1531
+ this.$return(pb.div(pb.pow(pb.sub(1, this.cosThetaV), pb.mul(5, pb.exp(pb.mul(-2.69, this.sigmaV)))), pb.add(1, pb.mul(22.7, pb.pow(this.sigmaV, 1.5)))));
248
1532
  });
249
1533
  pb.func('fresnel', [
250
1534
  pb.vec3('normal'),
251
- pb.vec3('eyeVec')
1535
+ pb.vec3('eyeVec'),
1536
+ pb.bool('underwater'),
1537
+ pb.float('sigmaV')
252
1538
  ], function() {
253
- this.$return(pb.clamp(pb.sub(pb.pow(pb.sub(1, pb.dot(this.normal, this.eyeVec)), 5), this.refractionStrength), 0, 1));
1539
+ // abs, not clamp: a folded crest flips the sign inside one wave, and a
1540
+ // clamp would drop to F0 exactly at the most grazing geometry.
1541
+ this.$l.NoV = pb.clamp(pb.abs(pb.dot(this.normal, this.eyeVec)), 0, 1);
1542
+ this.$if(this.underwater, function() {
1543
+ this.$l.sinT2 = pb.mul(WATER_TO_AIR_ETA * WATER_TO_AIR_ETA, pb.sub(1, pb.mul(this.NoV, this.NoV)));
1544
+ // Total internal reflection outside the Snell window. Not scaled by
1545
+ // reflectionStrength: there is no transmitted ray to reveal.
1546
+ this.$l.f = pb.float(1);
1547
+ this.$if(pb.lessThan(this.sinT2, 1), function() {
1548
+ // Schlick takes the cosine on the less dense side. F0 is symmetric.
1549
+ this.$l.cosT = pb.sqrt(pb.max(pb.sub(1, this.sinT2), 0));
1550
+ this.f = pb.clamp(pb.mul(pb.add(WATER_F0, pb.mul(1 - WATER_F0, pb.pow(pb.sub(1, this.cosT), 5))), this.reflectionStrength), 0, 1);
1551
+ });
1552
+ this.$return(this.f);
1553
+ });
1554
+ this.$l.f = pb.add(WATER_F0, pb.mul(1 - WATER_F0, this.meanFresnel(this.NoV, this.sigmaV)));
1555
+ this.$return(pb.clamp(pb.mul(this.f, this.reflectionStrength), 0, 1));
254
1556
  });
255
1557
  pb.func('lightSpecular', [
256
1558
  pb.vec3('lightDir'),
257
1559
  pb.vec3('eyeVecNorm'),
258
1560
  pb.vec3('normal'),
259
- pb.vec3('lightColor')
1561
+ pb.vec3('lightColor'),
1562
+ pb.float('roughness')
260
1563
  ], function() {
261
- this.$l.roughness = pb.float(0.04);
262
- this.$l.f0 = pb.vec3(0.02);
1564
+ this.$l.f0 = pb.vec3(WATER_F0);
263
1565
  this.$l.f90 = pb.vec3(1);
264
1566
  this.$l.L = this.lightDir;
265
1567
  this.$l.V = pb.neg(this.eyeVecNorm);
@@ -278,142 +1580,648 @@ class WaterMaterial extends applyMaterialMixins(MeshMaterial, mixinLight) {
278
1580
  });
279
1581
  this.$return(this.specular);
280
1582
  });
1583
+ // White foam revealed from a foam texture sample (value, slopes along x
1584
+ // and z) by a density, Crest's feathered black point; as (white foam, its
1585
+ // slope along x, along z).
1586
+ pb.func('waterWhiteFoam', [
1587
+ pb.float('density'),
1588
+ pb.vec3('tex'),
1589
+ pb.float('feather')
1590
+ ], function() {
1591
+ this.$l.t = pb.clamp(pb.div(pb.sub(this.tex.x, pb.sub(1, pb.clamp(this.density, 0, 1))), this.feather), 0, 1);
1592
+ this.$return(pb.vec3(pb.mul(this.t, this.t, pb.sub(3, pb.mul(this.t, 2))), pb.mul(this.tex.yz, pb.div(pb.mul(6, this.t, pb.sub(1, this.t)), this.feather))));
1593
+ });
281
1594
  pb.func('waterShading', [
282
1595
  pb.vec3('worldPos'),
283
1596
  pb.vec3('worldNormal'),
284
- pb.float('foamFactor')
1597
+ pb.float('foamFactor'),
1598
+ pb.float('crestHeight'),
1599
+ pb.vec2('restXZ'),
1600
+ pb.vec4('restXZGrad'),
1601
+ pb.vec3('foamSample'),
1602
+ pb.float('coverage'),
1603
+ pb.float('sheetThickness'),
1604
+ pb.float('wallFoam'),
1605
+ pb.vec4('scenePos'),
1606
+ pb.float('groundFoamDensity'),
1607
+ pb.vec3('groundFoamSample'),
1608
+ pb.vec3('groundNormal'),
1609
+ pb.float('groundFoamWeight')
285
1610
  ], function() {
286
1611
  this.$l.screenUV = pb.div(pb.vec2(this.$builtins.fragCoord.xy), ShaderHelper.getRenderSize(this));
287
1612
  this.$l.dist = pb.length(pb.sub(this.worldPos, ShaderHelper.getCameraPosition(this)));
288
- this.$l.normalScale = pb.clamp(pb.div(100, this.dist), 0, 1);
289
- this.$l.normal = pb.normalize(pb.mul(this.worldNormal, pb.vec3(this.normalScale, 1, this.normalScale)));
290
- this.$l.displacedTexCoord = pb.add(this.screenUV, pb.mul(this.normal.xz, this.displace));
291
- this.$l.wPos = ShaderHelper.samplePositionFromDepth(this, ShaderHelper.getLinearDepthTexture(this), this.screenUV, ShaderHelper.getInvViewProjectionMatrix(this), ShaderHelper.getCameraParams(this).xy);
1613
+ const slopeVar = that.unresolvedSlopeVariance(this, this.restXZGrad);
1614
+ if (slopeVar) {
1615
+ // The generator has already faded the slopes too fine for the pixel
1616
+ this.$l.slopeVar = slopeVar;
1617
+ this.$l.normal = pb.normalize(this.worldNormal);
1618
+ } else {
1619
+ this.$l.normalScale = pb.clamp(pb.div(100, this.dist), 0, 1);
1620
+ this.$l.normal = pb.normalize(pb.mul(this.worldNormal, pb.vec3(this.normalScale, 1, this.normalScale)));
1621
+ }
1622
+ this.$l.roughness = that.waterRoughness(this, this.worldPos, this.restXZGrad);
1623
+ this.$l.wPos = this.scenePos;
292
1624
  this.$l.eyeVec = pb.sub(this.worldPos.xyz, ShaderHelper.getCameraPosition(this));
293
1625
  this.$l.eyeVecNorm = pb.normalize(this.eyeVec);
1626
+ // Mirror-term normal, turned towards the eye on a folded underside.
1627
+ // Flipped on the cosine, not on `frontFacing`, which is discontinuous
1628
+ // along the fold's triangle edge. `eyeVecNorm` points camera -> surface,
1629
+ // so the flip case is the positive dot.
1630
+ this.$l.shadingNormal = this.$choice(pb.greaterThan(pb.dot(this.normal, this.eyeVecNorm), 0), pb.neg(this.normal), this.normal);
1631
+ // Diffuse-term normal, from the unflipped wave normal (the eye-facing
1632
+ // flip would point it into the lower hemisphere on any steep back
1633
+ // slope), mixed towards up as normal.y falls.
1634
+ this.$l.diffuseWeight = pb.smoothStep(0, 0.5, this.normal.y);
1635
+ this.$l.diffuseNormal = pb.normalize(pb.mix(pb.vec3(0, 1, 0), this.normal, this.diffuseWeight));
1636
+ // Eye below the rest plane, not `!frontFacing`: a choppy fold (J < 0)
1637
+ // flips the winding and would read as seen from below.
1638
+ this.$l.restLevel = pb.sub(this.worldPos.y, this.crestHeight);
1639
+ this.$l.underwaterEye = pb.or(pb.lessThan(this.eyeSide, 0), pb.and(pb.equal(this.eyeSide, 0), pb.lessThan(ShaderHelper.getCameraPosition(this).y, this.restLevel)));
294
1640
  this.$l.depth = pb.length(pb.sub(this.wPos.xyz, this.worldPos));
295
1641
  this.$l.viewPos = pb.mul(ShaderHelper.getViewMatrix(this), pb.vec4(this.worldPos, 1)).xyz;
296
1642
  this.incidentVec = pb.normalize(pb.sub(this.worldPos, ShaderHelper.getCameraPosition(this)));
297
- this.reflectVecW = pb.reflect(this.incidentVec, this.normal);
1643
+ this.reflectVecW = pb.reflect(this.incidentVec, this.shadingNormal);
298
1644
  this.$l.reflectance = pb.vec3();
299
1645
  this.$l.hitInfo = pb.vec4(0);
300
- this.$if(pb.greaterThan(this.reflectVecW.y, 0), function() {
1646
+ // Trace only rays leaving the surface: up from above, down from below.
1647
+ this.$if(this.$choice(this.underwaterEye, pb.lessThan(this.reflectVecW.y, 0), pb.greaterThan(this.reflectVecW.y, 0)), function() {
301
1648
  this.reflectVec = pb.mul(ShaderHelper.getViewMatrix(this), pb.vec4(this.reflectVecW, 0)).xyz;
302
1649
  this.hitInfo = ShaderHelper.getHiZDepthTexture(this) ? screenSpaceRayTracing_HiZ(this, this.viewPos, this.reflectVec, ShaderHelper.getViewMatrix(this), ShaderHelper.getProjectionMatrix(this), ShaderHelper.getInvProjectionMatrix(this), ShaderHelper.getCameraParams(this).xy, pb.int(ShaderHelper.getHiZDepthTextureMipLevelCount(this)), this.ssrParams.y, this.ssrParams.x, this.ssrParams.z, pb.vec4(ShaderHelper.getRenderSize(this), ShaderHelper.getHiZDepthTextureSize(this)), ShaderHelper.getHiZDepthTexture(this)) : screenSpaceRayTracing_Linear2D(this, this.viewPos, this.reflectVec, ShaderHelper.getViewMatrix(this), ShaderHelper.getProjectionMatrix(this), ShaderHelper.getInvProjectionMatrix(this), ShaderHelper.getCameraParams(this).xy, this.ssrParams.x, this.ssrParams.y, this.ssrParams.z, this.ssrParams.w, pb.vec4(ShaderHelper.getRenderSize(this), ShaderHelper.getLinearDepthTextureSize(this)), ShaderHelper.getLinearDepthTexture(this));
303
1650
  });
304
- this.$l.refl = pb.reflect(pb.normalize(pb.sub(this.worldPos, ShaderHelper.getCameraPosition(this))), this.normal);
305
- this.refl.y = pb.max(this.refl.y, 0.1);
306
- this.reflectance = pb.mix(// Blended against the pre-exposed scene color, so the exposure-independent sky bake has
307
- // to be lifted into the same space.
308
- ShaderHelper.sampleBakedSkyPreExposed(this, this.refl), pb.textureSampleLevel(ShaderHelper.getSceneColorTexture(this), this.hitInfo.xy, 0).rgb, this.hitInfo.w);
309
- this.$l.refractUV = this.displacedTexCoord;
310
- this.$l.displacedPos = ShaderHelper.samplePositionFromDepth(this, ShaderHelper.getLinearDepthTexture(this), this.refractUV, ShaderHelper.getInvProjectionMatrix(this), ShaderHelper.getCameraParams(this).xy);
311
- this.$if(pb.or(pb.greaterThanEqual(this.displacedPos.w, 0.99999), pb.greaterThan(this.displacedPos.z, this.viewPos.z)), function() {
312
- this.refractUV = this.screenUV;
1651
+ this.$l.refl = pb.reflect(pb.normalize(pb.sub(this.worldPos, ShaderHelper.getCameraPosition(this))), this.shadingNormal);
1652
+ // Fallback where the trace misses. From above: the sky, with the
1653
+ // reflection y floored so grazing rays do not read the bake's black
1654
+ // lower hemisphere. From below: the medium's asymptotic colour
1655
+ // albedo * ambient, the d -> inf limit of the underwater pass.
1656
+ this.$l.reflMiss = pb.vec3();
1657
+ this.$if(this.underwaterEye, function() {
1658
+ this.$l.downwelling = ShaderHelper.sampleBakedSkyPreExposed(this, pb.vec3(0, 1, 0));
1659
+ this.reflMiss = pb.mul(this.mediumAlbedo, this.downwelling);
313
1660
  }).$else(function() {
314
- this.depth = pb.length(pb.sub(this.displacedPos.xyz, this.viewPos));
1661
+ this.refl.y = pb.max(this.refl.y, HORIZON_REFLECT_BIAS);
1662
+ this.refl = pb.normalize(this.refl);
1663
+ // The mirror image of the visible sky, at its on-screen scale: the bake
1664
+ // brought to the live exposure without the environment light's
1665
+ // strength, which dims the IBL and not the sky itself.
1666
+ this.reflMiss = pb.mul(pb.textureSampleLevel(ShaderHelper.getBakedSkyTexture(this), this.refl, 0).rgb, this.skyReflectScale);
1667
+ if (envLight?.hasRadiance()) {
1668
+ // Blurred as the distant normals are: the prefiltered radiance at
1669
+ // the surface's roughness, in the same pre-exposed space
1670
+ this.$l.skyBlur = pb.smoothStep(SKY_PREFILTER_START, SKY_PREFILTER_FULL, this.roughness);
1671
+ this.$if(pb.greaterThan(this.skyBlur, 0), function() {
1672
+ this.reflMiss = pb.mix(this.reflMiss, pb.mul(envLight.getRadiance(this, this.refl, this.roughness).rgb, this.skyReflectScale), this.skyBlur);
1673
+ });
1674
+ }
315
1675
  });
316
- this.$l.refraction = pb.textureSampleLevel(ShaderHelper.getSceneColorTexture(this), this.refractUV, 0).rgb;
317
- this.refraction = pb.mul(this.refraction, this.getAbsorption(this.depth));
318
- this.$l.fresnelTerm = this.fresnel(this.normal, pb.neg(this.eyeVecNorm));
319
- this.$l.finalColor = pb.mix(pb.mix(this.refraction, this.reflectance, this.fresnelTerm), pb.vec3(1), this.foamFactor);
1676
+ // The traced reflection blurred by roughness as Uludag's cone-traced
1677
+ // reflections blur it ("Hi-Z Screen-Space Cone-Traced Reflections",
1678
+ // GPU Pro 5, 2014): the lobe as a cone of half angle
1679
+ // acos(0.244^(1 / (n + 1))) for a Phong power n, here
1680
+ // n = 2 / alpha^2 - 2 for the GGX alpha (Walter et al., "Microfacet
1681
+ // Models for Refraction through Rough Surfaces", EGSR 2007); its
1682
+ // footprint where the ray hits the radius of the circle inscribed in
1683
+ // the isosceles triangle of the cone over the screen-space ray, in
1684
+ // pixels; and the scene colour read at the level of that radius
1685
+ this.$l.alpha = pb.mul(this.roughness, this.roughness);
1686
+ this.$l.phongPower = pb.max(pb.sub(pb.div(2, pb.max(pb.mul(this.alpha, this.alpha), 1e-6)), 2), 0);
1687
+ this.$l.coneCos = pb.pow(0.244, pb.div(1, pb.add(this.phongPower, 1)));
1688
+ this.$l.coneTan = pb.div(pb.sqrt(pb.max(pb.sub(1, pb.mul(this.coneCos, this.coneCos)), 0)), pb.max(this.coneCos, 1e-4));
1689
+ this.$l.coneBase = pb.mul(2, this.coneTan, this.hitInfo.z);
1690
+ this.$l.coneRadius = pb.div(pb.mul(this.coneBase, pb.sub(pb.sqrt(pb.add(pb.mul(this.coneBase, this.coneBase), pb.mul(4, this.hitInfo.z, this.hitInfo.z))), this.coneBase)), pb.max(pb.mul(4, this.hitInfo.z), 1e-4));
1691
+ this.$l.reflectLod = pb.clamp(pb.log2(pb.max(this.coneRadius, 1)), 0, REFRACT_BLUR_MAX_LOD);
1692
+ this.reflectance = pb.mix(this.reflMiss, pb.textureSampleLevel(ShaderHelper.getSceneColorTexture(this), this.hitInfo.xy, this.reflectLod).rgb, this.hitInfo.w);
1693
+ this.$l.refractInfo = that.waterRefraction(this, this.worldPos, this.normal, this.eyeVecNorm, this.screenUV, this.viewPos.z, this.wPos.w, this.wPos.xyz, this.depth, this.underwaterEye);
1694
+ this.$l.refractUV = this.refractInfo.xy;
1695
+ // Medium path is the refracted length, not the straight line.
1696
+ this.depth = this.refractInfo.z;
1697
+ // Zero from below: the column the eye is inside belongs to the
1698
+ // Underwater pass, and charging it twice smears the Snell window.
1699
+ this.$l.mediumPath = this.$choice(this.underwaterEye, pb.float(0), this.depth);
1700
+ // Blur LOD: log2 in path length (each mip doubles the width), driven by
1701
+ // scattering rather than extinction (absorption darkens without blurring).
1702
+ this.$l.refractBlur = pb.log2(pb.add(1, pb.mul(this.mediumPath, pb.add(REFRACT_BLUR_GEOMETRIC, this.refractBlurDensity))));
1703
+ this.$l.refraction = pb.textureSampleLevel(ShaderHelper.getSceneColorTexture(this), this.refractUV, pb.clamp(this.refractBlur, 0, REFRACT_BLUR_MAX_LOD)).rgb;
1704
+ this.$l.refractionRaw = this.refraction;
1705
+ this.$l.absorption = this.getAbsorption(this.mediumPath);
1706
+ this.refraction = pb.mul(this.refraction, this.absorption);
1707
+ this.$l.viewXZ = pb.neg(this.eyeVecNorm.xz);
1708
+ if (slopeVar) {
1709
+ // Variance of the slopes the normal no longer shows along the view
1710
+ // direction, as Bruneton's MeanFresnel takes it
1711
+ this.$l.sigmaV = pb.sqrt(pb.max(pb.div(pb.add(pb.mul(this.viewXZ.x, this.viewXZ.x, this.slopeVar.x), pb.mul(this.viewXZ.y, this.viewXZ.y, this.slopeVar.y), pb.mul(this.viewXZ.x, this.viewXZ.y, this.slopeVar.z, 2)), pb.max(pb.dot(this.viewXZ, this.viewXZ), 1e-6)), 0));
1712
+ } else {
1713
+ // Variance of the slopes the flattened normal no longer shows, (1 - k^2)
1714
+ // of the sea's for a slope scaled by k, along the view direction in wind
1715
+ // space as Bruneton's MeanFresnel takes it
1716
+ this.$l.viewWind = pb.vec2(pb.dot(this.viewXZ, this.unresolvedSlope.xy), pb.dot(this.viewXZ, pb.vec2(pb.neg(this.unresolvedSlope.y), this.unresolvedSlope.x)));
1717
+ this.$l.viewWindT = pb.div(pb.mul(this.viewWind, this.viewWind), pb.max(pb.dot(this.viewXZ, this.viewXZ), 1e-6));
1718
+ this.$l.sigmaV = pb.sqrt(pb.mul(pb.dot(this.viewWindT, this.unresolvedSlope.zw), pb.sub(1, pb.mul(this.normalScale, this.normalScale))));
1719
+ }
1720
+ this.$l.fresnelTerm = this.fresnel(this.shadingNormal, pb.neg(this.eyeVecNorm), this.underwaterEye, this.sigmaV);
1721
+ // Foam density from the wave generator: crests, wakes, breaking shore waves
1722
+ this.$l.crestDensity = pb.clamp(pb.mul(pb.pow(pb.clamp(this.foamFactor, 0, 1), this.foamShadingParams.y), this.foamShadingParams.x), 0, 1);
1723
+ this.$l.crestWhite = this.waterWhiteFoam(this.crestDensity, this.foamSample, this.foamLookParams.x);
1724
+ // Wall foam, cut from the same texture by its own density: whole against
1725
+ // the wall, fraying as it thins. Its strength scales opacity after the cut.
1726
+ this.$l.wallDensity = pb.clamp(this.wallFoam, 0, 1);
1727
+ this.$l.wallCut = this.waterWhiteFoam(this.wallDensity, this.foamSample, this.foamLookParams.x);
1728
+ this.$l.wallWhite = pb.mul(this.wallCut.x, this.foamShadingParams.z);
1729
+ // The two layers combine as independent covers.
1730
+ this.$l.foam = pb.sub(1, pb.mul(pb.sub(1, this.crestWhite.x), pb.sub(1, this.wallWhite)));
1731
+ this.$l.foamGrad = pb.add(pb.mul(this.crestWhite.yz, pb.sub(1, this.wallWhite)), pb.mul(this.wallCut.yz, this.foamShadingParams.z, pb.sub(1, this.crestWhite.x)));
1732
+ this.$l.bubbleDensity = pb.sub(1, pb.mul(pb.sub(1, this.crestDensity), pb.sub(1, pb.mul(this.wallDensity, this.foamShadingParams.z))));
1733
+ // Normal of the white foam's relief: Crest differences the cut over a
1734
+ // quarter texel per metre of view depth, which keeps the relief at a
1735
+ // distance; the slope times that step here
1736
+ this.$l.foamStep = pb.mul(this.dist, 0.25, foamTexelSize(this, this.foamTex, this.foamUVScale));
1737
+ this.$l.foamNormal = pb.normalize(pb.add(this.diffuseNormal, pb.mul(pb.vec3(pb.neg(this.foamGrad.x), 0, pb.neg(this.foamGrad.y)), this.foamLookParams.y, this.foamStep)));
1738
+ // The white foam covers the water, its mirror and what is seen through
1739
+ // it alike, as Crest lays it over the finished water colour
1740
+ // (lerp(col, whiteFoam, a)): both only on the share without foam.
1741
+ // `bodyWeight`, the exit transmission on that share, weighs the
1742
+ // refraction and every body term below.
1743
+ this.$l.waterShare = pb.sub(1, this.foam);
1744
+ this.$l.bodyWeight = pb.mul(pb.sub(1, this.fresnelTerm), this.waterShare);
1745
+ this.fresnelTerm = pb.mul(this.fresnelTerm, this.waterShare);
1746
+ this.$l.finalColor = pb.add(pb.mul(this.refraction, this.bodyWeight), pb.mul(this.reflectance, this.fresnelTerm));
1747
+ // Prefer the wave generator's own ground for the thickness of thin swash.
1748
+ this.$l.edgeThickness = this.$choice(pb.greaterThanEqual(this.sheetThickness, 0), this.sheetThickness, // Sky reconstructs to the far plane, which can lie above an infinite
1749
+ // surface. With no bottom there, keep the water and foam fully visible.
1750
+ this.$choice(pb.greaterThanEqual(this.wPos.w, SCENE_SKY_DEPTH01), pb.max(this.edgeFadeWidth, 1e-4), pb.sub(this.worldPos.y, this.wPos.y)));
1751
+ this.$l.foamFade = pb.mul(this.$choice(pb.greaterThanEqual(this.sheetThickness, 0), pb.float(1), this.$choice(pb.greaterThan(this.edgeFadeWidth, 0), pb.smoothStep(0, pb.max(pb.mul(this.edgeFadeWidth, FOAM_EDGE_FADE_SHARE), 1e-4), this.edgeThickness), pb.float(1))), this.coverage);
1752
+ // Light the foam sends back, kept apart so the edge fade below can keep
1753
+ // the foam on a sheet too thin to show the water
1754
+ this.$l.foamRadiance = pb.vec3(0);
1755
+ this.$l.groundFoamOpacity = pb.float(0);
1756
+ this.$l.groundFoamRadiance = pb.vec3(0);
1757
+ if (hasGroundFoam) {
1758
+ this.$if(pb.greaterThan(this.groundFoamDensity, 1e-3), function() {
1759
+ this.$l.groundFoamWhite = this.waterWhiteFoam(pb.clamp(pb.mul(pb.pow(this.groundFoamDensity, this.foamShadingParams.y), this.foamShadingParams.x), 0, 1), this.groundFoamSample, this.foamLookParams.x);
1760
+ this.groundFoamOpacity = this.groundFoamWhite.x;
1761
+ });
1762
+ // The carrier P can still foam while its projected ground Q is dry.
1763
+ // Keep that visible cover through the handoff; once P drains, only
1764
+ // the ground foam remains. Set opacity before lighting both covers.
1765
+ this.groundFoamOpacity = pb.max(this.groundFoamOpacity, pb.mul(this.foam, this.foamFade));
1766
+ }
1767
+ // Debug accumulators. Dead in the `none` variant.
1768
+ this.$l.dbgSubsurface = pb.vec3(0);
1769
+ this.$l.dbgSunScatter = pb.vec3(0);
1770
+ this.$l.dbgShadow = pb.vec3(1);
1771
+ this.$l.dbgSpecular = pb.vec3(0);
1772
+ // Subsurface crest gate, after Ceto: the lit wall thins with height,
1773
+ // path = max(floor, exp(-softplus(h / H))), gate = exp(-sigma_t *
1774
+ // scale * path). On the vertex displacement, not the normal tilt,
1775
+ // which is zero at the crest and carries every ripple.
1776
+ this.$l.sssT = pb.div(this.crestHeight, this.subsurfaceParams.y);
1777
+ // softplus in the overflow-safe form max(t,0) + w*log(1+exp(-|t|/w)).
1778
+ this.$l.sssRise = pb.add(pb.max(this.sssT, 0), pb.mul(SSS_HEIGHT_SOFTNESS, pb.log(pb.add(1, pb.exp(pb.div(pb.neg(pb.abs(this.sssT)), SSS_HEIGHT_SOFTNESS))))));
1779
+ this.$l.sssPath = pb.max(pb.exp(pb.neg(this.sssRise)), SSS_CREST_PATH_FLOOR);
1780
+ this.$l.sssThickness = pb.exp(pb.neg(pb.mul(this.mediumExtinction, pb.mul(this.sssPath, SSS_ABSORPTION_SCALE))));
1781
+ // For the debug views that rebuild the sun terms outside the loop.
1782
+ this.dbgLightDir = pb.vec3(0, 1, 0);
320
1783
  that.forEachLight(this, function(type, posRange, dirCutoff, colorIntensity, extra, shadow) {
321
1784
  this.$l.lightAtten = that.calculateLightAttenuation(this, type, this.worldPos, posRange, dirCutoff, extra);
322
- this.$l.lightDir = that.calculateLightDirection(this, type, this.worldPos, posRange, dirCutoff);
1785
+ this.$l.lightDir = that.calculateLightDirection(this, type, this.worldPos, posRange, dirCutoff, extra);
1786
+ this.dbgLightDir = this.lightDir;
323
1787
  this.$l.NoL = pb.clamp(pb.dot(this.normal, this.lightDir), 0, 1);
324
- this.$l.lightContrib = this.lightSpecular(this.lightDir, this.eyeVecNorm, this.normal, pb.mul(colorIntensity.rgb, colorIntensity.a, this.lightAtten));
1788
+ this.$l.NoLdiffuse = pb.clamp(pb.dot(this.diffuseNormal, this.lightDir), 0, 1);
1789
+ // From the raw cosine, so a lee slope below zero still wraps up.
1790
+ this.$l.NoLfoam = pb.clamp(pb.div(pb.add(pb.dot(this.foamNormal, this.lightDir), FOAM_LIGHT_WRAP), 1 + FOAM_LIGHT_WRAP), 0, 1);
1791
+ this.$l.lightEnergy = pb.mul(colorIntensity.rgb, colorIntensity.a, this.lightAtten);
1792
+ this.$l.specularTerm = pb.vec3(0);
1793
+ // A rect light's mirror image is the rect itself: integrate the GGX
1794
+ // lobe over it with LTC, as the PBR materials do. One direction would
1795
+ // shrink it to a point highlight on a surface this smooth.
1796
+ this.$if(pb.equal(type, LIGHT_TYPE_RECT), function() {
1797
+ this.$l.rectTerms = evaluateLTCRectLightTerms(this, this.worldPos, this.shadingNormal, pb.neg(this.eyeVecNorm), this.roughness, posRange, dirCutoff.xyz, extra.xyz);
1798
+ this.specularTerm = pb.mul(colorIntensity.rgb, colorIntensity.a, this.rectTerms.x, pb.add(pb.mul(this.rectTerms.y, WATER_F0), pb.mul(this.rectTerms.z, 1 - WATER_F0)));
1799
+ }).$else(function() {
1800
+ this.specularTerm = this.lightSpecular(this.lightDir, this.eyeVecNorm, this.shadingNormal, this.lightEnergy, this.roughness);
1801
+ });
1802
+ this.$l.lightContrib = this.specularTerm;
1803
+ // Backlit-crest subsurface, after Ceto: grazing^2 * (view ray mirrored
1804
+ // in the rest plane, against the sun)^4 * sun-above-horizon fade.
1805
+ // Both cosines are floored.
1806
+ this.$l.sssToEye = pb.neg(this.eyeVecNorm);
1807
+ this.$l.sssGrazing = pb.sub(1, pb.clamp(this.sssToEye.y, 0, 1));
1808
+ this.sssGrazing = pb.mix(SSS_GRAZING_FLOOR, 1, pb.mul(this.sssGrazing, this.sssGrazing));
1809
+ this.$l.sssMirror = pb.reflect(this.sssToEye, pb.vec3(0, 1, 0));
1810
+ this.$l.sssAlign = pb.clamp(pb.dot(pb.neg(this.sssMirror), this.lightDir), 0, 1);
1811
+ this.sssAlign = pb.mul(this.sssAlign, this.sssAlign);
1812
+ this.sssAlign = pb.mix(SSS_SUN_ALIGN_FLOOR, 1, pb.mul(this.sssAlign, this.sssAlign));
1813
+ this.$l.sssSunUp = pb.smoothStep(0, 0.1, this.lightDir.y);
1814
+ this.$l.sssFacing = pb.mul(this.sssGrazing, this.sssAlign, this.sssSunUp);
1815
+ // Scaled by the light colour as in Crest, and by 1 / pi like the other
1816
+ // diffuse terms. Directional lights only; carries `bodyWeight`.
1817
+ this.$l.subsurfaceTerm = pb.vec3(0);
1818
+ this.$if(pb.equal(type, LIGHT_TYPE_DIRECTIONAL), function() {
1819
+ this.subsurfaceTerm = pb.mul(this.subsurfaceTint, this.lightEnergy, pb.mul(this.sssFacing, this.sssThickness, this.subsurfaceParams.x, 1 / Math.PI), this.bodyWeight);
1820
+ this.lightContrib = pb.add(this.lightContrib, this.subsurfaceTerm);
1821
+ });
1822
+ // Directional only (the integral assumes a parallel beam) and from
1823
+ // above only.
1824
+ this.$l.sunScatterTerm = pb.vec3(0);
1825
+ this.$if(pb.and(pb.equal(type, LIGHT_TYPE_DIRECTIONAL), pb.not(this.underwaterEye)), function() {
1826
+ this.sunScatterTerm = pb.mul(that.waterSunScattering(this, this.lightEnergy, this.lightDir, this.eyeVecNorm, this.NoLdiffuse, this.depth, this.foam), this.bodyWeight);
1827
+ this.lightContrib = pb.add(this.lightContrib, this.sunScatterTerm);
1828
+ });
1829
+ // Foam as a matte layer, with Crest's narrow glint off its relief.
1830
+ this.$l.foamGlint = pb.mul(pb.pow(pb.max(pb.dot(pb.reflect(this.eyeVecNorm, this.foamNormal), this.lightDir), 0), FOAM_SPECULAR_POWER), FOAM_SPECULAR_BOOST);
1831
+ this.$l.foamLight = pb.mul(this.lightEnergy, this.foam, pb.add(pb.mul(this.foamColor, this.NoLfoam, 1 / Math.PI), pb.vec3(this.foamGlint)));
1832
+ this.lightContrib = pb.add(this.lightContrib, this.foamLight);
1833
+ this.$l.shadow = pb.vec3(1);
325
1834
  if (shadow) {
326
- // Water is a horizontal clipmap, so +Y is the geometric normal. The
327
- // wave normal would jitter the shadow lookup per-pixel.
328
- this.$l.shadow = pb.vec3(that.calculateShadow(this, this.worldPos, pb.vec3(0, 1, 0), this.NoL));
1835
+ // +Y, not the wave normal, which would jitter the lookup per pixel.
1836
+ this.shadow = pb.vec3(that.calculateShadow(this, this.worldPos, pb.vec3(0, 1, 0), this.NoL));
329
1837
  this.lightContrib = pb.mul(this.lightContrib, this.shadow);
330
1838
  }
1839
+ this.foamRadiance = pb.add(this.foamRadiance, pb.mul(this.foamLight, this.shadow));
1840
+ if (hasGroundFoam) {
1841
+ this.$if(pb.greaterThan(this.groundFoamOpacity, 0), function() {
1842
+ this.$l.groundNoL = pb.clamp(pb.div(pb.add(pb.dot(this.groundNormal, this.lightDir), FOAM_LIGHT_WRAP), 1 + FOAM_LIGHT_WRAP), 0, 1);
1843
+ this.$l.groundShadow = pb.vec3(1);
1844
+ if (shadow) {
1845
+ this.groundShadow = pb.vec3(that.calculateShadow(this, this.wPos.xyz, this.groundNormal, this.groundNoL));
1846
+ }
1847
+ this.groundFoamRadiance = pb.add(this.groundFoamRadiance, pb.mul(this.lightEnergy, this.foamColor, this.groundNoL, this.groundShadow, this.groundFoamOpacity, 1 / Math.PI));
1848
+ });
1849
+ }
331
1850
  this.finalColor = pb.add(this.finalColor, this.lightContrib);
1851
+ this.dbgSubsurface = pb.add(this.dbgSubsurface, pb.mul(this.subsurfaceTerm, this.shadow));
1852
+ this.dbgSunScatter = pb.add(this.dbgSunScatter, pb.mul(this.sunScatterTerm, this.shadow));
1853
+ this.dbgShadow = pb.min(this.dbgShadow, this.shadow);
1854
+ this.dbgSpecular = pb.add(this.dbgSpecular, pb.mul(this.specularTerm, this.shadow));
332
1855
  });
333
1856
  if (that.needCalculateEnvLight()) {
334
- this.$l.irradiance = that.getEnvLightIrradiance(this, this.normal);
335
- this.$l.sss = pb.mul(this.getScattering(this.depth), this.irradiance, 1 / Math.PI);
1857
+ this.$l.irradiance = that.getEnvLightIrradiance(this, this.diffuseNormal);
1858
+ // On `mediumPath`, so zero from below. The foam term is unconditional.
1859
+ this.$l.sss = pb.mul(this.getScattering(this.mediumPath), this.irradiance, this.bodyWeight, 1 / Math.PI);
336
1860
  this.finalColor = pb.add(this.finalColor, this.sss);
1861
+ this.$l.foamAmbient = pb.mul(this.irradiance, this.foamColor, this.foam, 1 / Math.PI);
1862
+ this.finalColor = pb.add(this.finalColor, this.foamAmbient);
1863
+ this.foamRadiance = pb.add(this.foamRadiance, this.foamAmbient);
1864
+ if (hasGroundFoam) {
1865
+ this.groundFoamRadiance = pb.add(this.groundFoamRadiance, pb.mul(that.getEnvLightIrradiance(this, this.groundNormal), this.foamColor, this.groundFoamOpacity, 1 / Math.PI));
1866
+ }
1867
+ // Bubbles under the white foam, part of the water body as in Crest,
1868
+ // so under the white foam and the mirror: the foam texture blurred and
1869
+ // shifted by parallax, as seen at a depth under the surface
1870
+ this.$if(pb.greaterThan(this.bubbleDensity, 0), function() {
1871
+ this.$l.toEye = pb.neg(this.eyeVecNorm);
1872
+ this.$l.bubbleShift = pb.div(pb.mul(this.toEye.xz, pb.neg(this.foamLookParams.w)), pb.max(pb.dot(this.diffuseNormal, this.toEye), 0.1));
1873
+ this.$l.bubbleTex = sampleFoamTexture(this, this.foamTex, pb.mul(pb.add(this.restXZ, this.bubbleShift, pb.vec2(pb.mul(ShaderHelper.getElapsedTime(this), FOAM_DRIFT))), this.foamUVScale), this.restXZGrad, this.foamUVScale, FOAM_BUBBLE_MIP_SCALE, false).x;
1874
+ this.finalColor = pb.add(this.finalColor, pb.mul(this.irradiance, this.foamBubbleColor, this.bubbleTex, pb.clamp(pb.mul(this.bubbleDensity, this.foamLookParams.z), 0, 1), this.bodyWeight, 1 / Math.PI));
1875
+ });
1876
+ }
1877
+ // A thin sheet fades into the scene behind it. Where the generator
1878
+ // knows the wet edge, its coverage keeps foam visible on even a
1879
+ // millimetre-thick sheet; elsewhere foam fades by the measured depth.
1880
+ this.$if(pb.not(this.underwaterEye), function() {
1881
+ this.$l.edgeFade = pb.mul(this.$choice(pb.greaterThan(this.edgeFadeWidth, 0), pb.smoothStep(0, pb.max(this.edgeFadeWidth, 1e-4), this.edgeThickness), pb.float(1)), this.coverage);
1882
+ this.$if(pb.lessThan(this.edgeFade, 1), function() {
1883
+ this.$l.behind = pb.textureSampleLevel(ShaderHelper.getSceneColorTexture(this), this.screenUV, 0).rgb;
1884
+ // finalColor = water (on the share without foam) + foam light: the
1885
+ // water fades into what is behind, under the foam
1886
+ this.finalColor = pb.add(pb.mix(pb.mul(this.behind, pb.sub(1, pb.mul(this.foam, this.foamFade))), pb.sub(this.finalColor, this.foamRadiance), this.edgeFade), pb.mul(this.foamRadiance, this.foamFade));
1887
+ });
1888
+ if (hasGroundFoam) {
1889
+ this.$if(pb.greaterThan(this.groundFoamWeight, 0), function() {
1890
+ this.$l.groundBehind = pb.textureSampleLevel(ShaderHelper.getSceneColorTexture(this), this.screenUV, 0).rgb;
1891
+ // One crossfade between complete covers. Attenuating the mobile
1892
+ // foam before overlaying ground foam applies this weight twice
1893
+ // and exposes sand in the middle even if both covers are white.
1894
+ this.$l.groundColor = pb.add(pb.mul(this.groundBehind, pb.sub(1, this.groundFoamOpacity)), this.groundFoamRadiance);
1895
+ this.finalColor = pb.mix(this.finalColor, this.groundColor, this.groundFoamWeight);
1896
+ });
1897
+ }
1898
+ });
1899
+ switch(debugOutput){
1900
+ case 'normal':
1901
+ this.$if(pb.lessThan(this.diffuseNormal.y, 0.01), function() {
1902
+ this.$return(pb.vec3(1, 0, 0));
1903
+ }).$else(function() {
1904
+ this.$return(pb.add(pb.mul(this.diffuseNormal, 0.5), pb.vec3(0.5)));
1905
+ });
1906
+ break;
1907
+ case 'foam':
1908
+ this.$return(pb.vec3(pb.mix(this.foam, this.groundFoamOpacity, this.groundFoamWeight)));
1909
+ break;
1910
+ case 'swashFoamCuts':
1911
+ this.$return(pb.vec3(this.foam, this.groundFoamOpacity, this.groundFoamWeight));
1912
+ break;
1913
+ case 'waterDepth':
1914
+ this.$return(pb.vec3(pb.mul(pb.max(pb.sub(this.worldPos.y, this.wPos.y), 0), 0.1)));
1915
+ break;
1916
+ case 'fresnel':
1917
+ this.$return(pb.vec3(this.fresnelTerm));
1918
+ break;
1919
+ case 'reflection':
1920
+ this.$return(this.reflectance);
1921
+ break;
1922
+ case 'refraction':
1923
+ this.$return(this.refractionRaw);
1924
+ break;
1925
+ case 'absorption':
1926
+ this.$return(this.absorption);
1927
+ break;
1928
+ case 'scattering':
1929
+ this.$return(this.sss);
1930
+ break;
1931
+ case 'sunScattering':
1932
+ this.$return(this.dbgSunScatter);
1933
+ break;
1934
+ case 'subsurface':
1935
+ this.$return(this.dbgSubsurface);
1936
+ break;
1937
+ case 'subsurfaceThickness':
1938
+ this.$return(pb.vec3(this.sssThickness));
1939
+ break;
1940
+ case 'shadow':
1941
+ this.$return(this.dbgShadow);
1942
+ break;
1943
+ case 'specular':
1944
+ this.$return(this.dbgSpecular);
1945
+ break;
1946
+ case 'depth':
1947
+ this.$return(pb.vec3(pb.mul(this.depth, 0.1)));
1948
+ break;
1949
+ default:
1950
+ this.$return(this.finalColor);
337
1951
  }
338
- this.$return(this.finalColor);
339
1952
  });
340
- return scope.waterShading(worldPos, worldNormal, foamFactor);
1953
+ return scope.waterShading(worldPos, worldNormal, foamFactor, crestHeight, restXZ, restXZGrad, foamSample, coverage, sheetThickness, wallFoam, scenePos, groundFoamDensity, groundFoamSample, groundNormal, groundFoamWeight);
341
1954
  }
342
1955
  applyUniforms(bindGroup, ctx, needUpdate, pass) {
343
1956
  super.applyUniforms(bindGroup, ctx, needUpdate, pass);
344
- const waveGenerator = this._waveGenerator.get();
345
- if (waveGenerator && this._waveVersion !== waveGenerator.version) {
1957
+ const waveGenerator = this._effectiveWaveGenerator;
1958
+ // Per bind group: the material owns one per pass/variant hash.
1959
+ const lastWritten = this._waveVersionByBindGroup.get(bindGroup) ?? -1;
1960
+ if (waveGenerator && lastWritten !== waveGenerator.version) {
346
1961
  waveGenerator.applyWaterBindGroup(bindGroup);
347
- this._waveVersion = waveGenerator.version;
1962
+ this._waveVersionByBindGroup.set(bindGroup, waveGenerator.version);
348
1963
  }
349
1964
  }
350
1965
  applyUniformValues(bindGroup, ctx, pass) {
351
1966
  super.applyUniformValues(bindGroup, ctx, pass);
352
1967
  bindGroup.setValue('clipmapGridInfo', this._clipmapGridInfo);
353
- bindGroup.setValue('region', this._region);
1968
+ if (this.infinite) {
1969
+ bindGroup.setValue('skirtDistance', this._skirtDistance);
1970
+ } else {
1971
+ bindGroup.setValue('region', this._region);
1972
+ }
354
1973
  if (this.needFragmentColor(ctx)) {
355
- bindGroup.setValue('displace', this._displace / ctx.renderWidth);
356
- bindGroup.setValue('depthMulti', this._depthMulti);
357
- bindGroup.setValue('refractionStrength', this._refractionStrength);
1974
+ bindGroup.setValue('refractionScale', this._refractionScale);
1975
+ if (this.refractionMode === 'offset') {
1976
+ bindGroup.setValue('cheapRefractionDepth', this._cheapRefractionDepth);
1977
+ }
1978
+ bindGroup.setValue('reflectionStrength', this._reflectionStrength);
1979
+ const wind = this._waveGenerator.get()?.wind;
1980
+ const windSpeed = wind ? Math.hypot(wind.x, wind.y) : 0;
1981
+ this._unresolvedSlope.setXYZW(windSpeed > 0 ? wind.x / windSpeed : 1, windSpeed > 0 ? wind.y / windSpeed : 0, COX_MUNK_UPWIND * windSpeed, COX_MUNK_CROSSWIND_BASE + COX_MUNK_CROSSWIND * windSpeed);
1982
+ bindGroup.setValue('unresolvedSlope', this._unresolvedSlope);
1983
+ bindGroup.setValue('skyReflectScale', ctx.scene.lightingMode === 'physical' ? ShaderHelper.getPreExposure(ctx) / PHYSICAL_BAKE_EXPOSURE : 1);
358
1984
  bindGroup.setValue('ssrParams', this._ssrParams);
359
- bindGroup.setTexture('scatterRampTex', this._getScatterRampTexture(ctx.device), fetchSampler('clamp_linear_nomip'));
360
- bindGroup.setTexture('absorptionRampTex', this._getAbsorptionRampTexture(ctx.device), fetchSampler('clamp_linear_nomip'));
1985
+ const eyeUnder = ctx.underwater;
1986
+ bindGroup.setValue('eyeSide', eyeUnder ? eyeUnder.material === this ? -1 : 0 : 1);
1987
+ this._subsurfaceParams.setXYZW(this._subsurfaceIntensity, this._subsurfaceCrestHeight, 0, 0);
1988
+ bindGroup.setValue('subsurfaceParams', this._subsurfaceParams);
1989
+ bindGroup.setValue('subsurfaceTint', this._subsurfaceTint);
1990
+ this._foamParams.setXYZW(this._foamAmount, this._foamFalloff, this._shoreWaves.height > 0 ? this._shoreWaves.wallFoamStrength : 0, 0);
1991
+ bindGroup.setValue('foamShadingParams', this._foamParams);
1992
+ bindGroup.setValue('foamColor', this._foamColor);
1993
+ this._foamLookParams.setXYZW(this._foamFeather, this._foamNormalStrength, this._foamBubbleCoverage, this._foamBubbleDepth);
1994
+ bindGroup.setValue('foamLookParams', this._foamLookParams);
1995
+ bindGroup.setValue('foamBubbleColor', this._foamBubbleColor);
1996
+ bindGroup.setTexture('foamTex', this.foamTexture ?? getDefaultFoamTexture(), fetchSampler('repeat_linear'));
1997
+ bindGroup.setValue('foamUVScale', 1 / this._foamTextureSize);
1998
+ bindGroup.setValue('edgeFadeWidth', this._edgeFadeWidth);
1999
+ bindGroup.setValue('mediumAlbedo', this._scatterAlbedo);
2000
+ bindGroup.setValue('mediumExtinction', this._extinction);
2001
+ bindGroup.setTexture('zLTCMatLut', getLTCMatLUT());
2002
+ bindGroup.setTexture('zLTCAmpLut', getLTCAmpLUT());
2003
+ this._sunScatterParams.setXYZW(this._sunScatteringIntensity, this._scatterAnisotropy, 0, 0);
2004
+ bindGroup.setValue('sunScatterParams', this._sunScatterParams);
2005
+ // Luminance-weighted scalar: one blur LOD serves all three channels.
2006
+ bindGroup.setValue('refractBlurDensity', (0.2126 * this._scattering.x + 0.7152 * this._scattering.y + 0.0722 * this._scattering.z) * this._scatteringScale * REFRACT_BLUR_DENSITY * this._refractionBlur);
361
2007
  }
362
2008
  if (this.waveGenerator) {
363
2009
  this.waveGenerator.applyWaterBindGroup(bindGroup);
364
2010
  }
365
2011
  }
366
2012
  needUpdate() {
367
- return !!this._waveGenerator.get()?.needUpdate();
2013
+ return !!this._waveGenerator.get()?.needUpdate() || !!this._interaction.get() || !!this._shoreWaveGenerator;
2014
+ }
2015
+ /**
2016
+ * Crest to trough height in metres of the waves rolling in to the shore and
2017
+ * running up the beach, 0 for none. See {@link ShoreWaveGenerator}. Needs
2018
+ * the scene signed distance field (WebGPU); without it the waves are off.
2019
+ */ get shoreWaveHeight() {
2020
+ return this._shoreWaves.height;
2021
+ }
2022
+ set shoreWaveHeight(val) {
2023
+ val = Math.max(0, val);
2024
+ const wasOn = this._shoreWaves.height > 0;
2025
+ this._shoreWaves.height = val;
2026
+ if (wasOn !== val > 0) {
2027
+ this._rebuildEffectiveWaveGenerator();
2028
+ }
2029
+ }
2030
+ /** Distance in metres between shore wave crests at the outer edge of their zone; they bunch up towards the shore. */ get shoreWaveLength() {
2031
+ return this._shoreWaves.wavelength;
2032
+ }
2033
+ set shoreWaveLength(val) {
2034
+ this._shoreWaves.wavelength = Math.max(0.5, val);
2035
+ }
2036
+ /** Seconds between successive shore waves. */ get shoreWavePeriod() {
2037
+ return this._shoreWaves.period;
2038
+ }
2039
+ set shoreWavePeriod(val) {
2040
+ this._shoreWaves.period = Math.max(0.5, val);
2041
+ }
2042
+ /** How far out from the waterline the shore waves rise, in metres. */ get shoreWaveZone() {
2043
+ return this._shoreWaves.zone;
2044
+ }
2045
+ set shoreWaveZone(val) {
2046
+ this._shoreWaves.zone = Math.max(1, val);
2047
+ }
2048
+ /** How sharp the shore wave crests become at the shore, 0 for a sine and towards 1 for a cusp. */ get shoreWaveSharpness() {
2049
+ return this._shoreWaves.sharpness;
2050
+ }
2051
+ set shoreWaveSharpness(val) {
2052
+ this._shoreWaves.sharpness = Math.min(Math.max(val, 0), 0.95);
2053
+ }
2054
+ /** How far the shore wave crests lean towards the shore there, 0 for upright, 1 for a steep front face. */ get shoreWaveLean() {
2055
+ return this._shoreWaves.lean;
2056
+ }
2057
+ set shoreWaveLean(val) {
2058
+ this._shoreWaves.lean = Math.min(Math.max(val, 0), 1);
2059
+ }
2060
+ /** How irregular the shore waves are, 0..1: 0 for parallel crests a fixed wavelength apart, higher for each wave with a period and a bend of its own. */ get shoreWaveIrregularity() {
2061
+ return this._shoreWaves.irregularity;
2062
+ }
2063
+ set shoreWaveIrregularity(val) {
2064
+ this._shoreWaves.irregularity = Math.min(Math.max(val, 0), 1);
2065
+ }
2066
+ /** How fast the foam fades, per second (Crest's Foam Fade Rate): lower leaves longer trails behind breaking waves. */ get foamFadeRate() {
2067
+ return this._foamField.fadeRate;
2068
+ }
2069
+ set foamFadeRate(val) {
2070
+ this._foamField.fadeRate = val;
2071
+ }
2072
+ /** How much foam the open water's breaking crests leave behind to drift and fade; 0 keeps foam only while a crest breaks. */ get foamTrailStrength() {
2073
+ return this._foamField.baseStrength;
2074
+ }
2075
+ set foamTrailStrength(val) {
2076
+ this._foamField.baseStrength = val;
2077
+ }
2078
+ /** Share of the wind speed the foam drifts at, about 0.03 in nature. */ get foamDrift() {
2079
+ return this._foamField.drift;
2080
+ }
2081
+ set foamDrift(val) {
2082
+ this._foamField.drift = val;
2083
+ }
2084
+ /** Side in metres of the finest square of water around the view whose foam lingers, in the most detail; coarser squares reach eight times as far, beyond which foam shows only while crests break. */ get foamFieldSize() {
2085
+ return this._foamField.size;
2086
+ }
2087
+ set foamFieldSize(val) {
2088
+ this._foamField.size = val;
2089
+ }
2090
+ /** How much foam the breaking shore waves make (Crest's Wave Foam Strength). */ get shoreWaveFoamStrength() {
2091
+ return this._shoreWaves.waveFoamStrength;
2092
+ }
2093
+ set shoreWaveFoamStrength(val) {
2094
+ this._shoreWaves.waveFoamStrength = Math.max(0, val);
2095
+ }
2096
+ /** How much of the shore waves makes foam, 0..1, higher for more (Crest's Wave Foam Coverage). */ get shoreWaveFoamCoverage() {
2097
+ return this._shoreWaves.waveFoamCoverage;
2098
+ }
2099
+ set shoreWaveFoamCoverage(val) {
2100
+ this._shoreWaves.waveFoamCoverage = Math.min(Math.max(val, 0), 1);
2101
+ }
2102
+ /** Water shallower than this many metres makes foam (Crest's Shoreline Foam Max Depth). */ get shoreWaveShallowFoamDepth() {
2103
+ return this._shoreWaves.shorelineFoamMaxDepth;
2104
+ }
2105
+ set shoreWaveShallowFoamDepth(val) {
2106
+ this._shoreWaves.shorelineFoamMaxDepth = Math.max(0.01, val);
2107
+ }
2108
+ /** How much foam shallow water makes (Crest's Shoreline Foam Strength). */ get shoreWaveShallowFoamStrength() {
2109
+ return this._shoreWaves.shorelineFoamStrength;
2110
+ }
2111
+ set shoreWaveShallowFoamStrength(val) {
2112
+ this._shoreWaves.shorelineFoamStrength = Math.max(0, val);
2113
+ }
2114
+ /** How opaque the foam is that the water makes against walls, rocks and piers standing in it, 0..1; it always rings them whole. */ get wallFoamStrength() {
2115
+ return this._shoreWaves.wallFoamStrength;
2116
+ }
2117
+ set wallFoamStrength(val) {
2118
+ this._shoreWaves.wallFoamStrength = Math.min(Math.max(val, 0), 1);
2119
+ this.uniformChanged();
2120
+ }
2121
+ /** Speed in metres per second the water has to hit a wall at before it makes any foam there. */ get wallFoamMinSpeed() {
2122
+ return this._shoreWaves.wallFoamMinSpeed;
2123
+ }
2124
+ set wallFoamMinSpeed(val) {
2125
+ this._shoreWaves.wallFoamMinSpeed = Math.max(0, val);
2126
+ }
2127
+ /** Speed in metres per second at which water hitting a wall makes the most foam. */ get wallFoamMaxSpeed() {
2128
+ return this._shoreWaves.wallFoamMaxSpeed;
2129
+ }
2130
+ set wallFoamMaxSpeed(val) {
2131
+ this._shoreWaves.wallFoamMaxSpeed = Math.max(0.01, val);
2132
+ }
2133
+ /** Speed in metres per second the foam drifts out from walls, rocks and piers at: higher for a wider ring of foam around them. */ get wallFoamDrift() {
2134
+ return this._shoreWaves.wallFoamDrift;
2135
+ }
2136
+ set wallFoamDrift(val) {
2137
+ this._shoreWaves.wallFoamDrift = Math.max(0, val);
2138
+ }
2139
+ /**
2140
+ * Seconds the foam each breaking wave brings in lasts: higher for longer
2141
+ * white trails behind the crests and foam that stays on the swash all the
2142
+ * way up the beach, lower for brief flashes of white at the crests.
2143
+ */ get surfFoamDuration() {
2144
+ return this._shoreWaves.surfFoamDuration;
2145
+ }
2146
+ set surfFoamDuration(val) {
2147
+ this._shoreWaves.surfFoamDuration = Math.max(0.05, val);
2148
+ }
2149
+ /**
2150
+ * Water depth in metres at and below which foam stops drifting and stays
2151
+ * where it is: higher to leave foam lying over a wider band of the shallows
2152
+ * and the beach, lower to let it drift until the water is almost gone.
2153
+ */ get foamSettleDepth() {
2154
+ return this._shoreWaves.foamSettleDepth;
2155
+ }
2156
+ set foamSettleDepth(val) {
2157
+ this._shoreWaves.foamSettleDepth = Math.max(0, val);
2158
+ }
2159
+ /**
2160
+ * Water depth in metres at and beyond which foam drifts freely: higher to
2161
+ * slow the foam over a wider band of shallow water, lower to keep it moving
2162
+ * until close in.
2163
+ */ get foamDriftDepth() {
2164
+ return this._shoreWaves.foamDriftDepth;
2165
+ }
2166
+ set foamDriftDepth(val) {
2167
+ this._shoreWaves.foamDriftDepth = Math.max(0, val);
2168
+ }
2169
+ /**
2170
+ * How fast foam that has settled in shallow water and on the sand fades, as
2171
+ * a share of the foam's fade: lower to leave it lying on the beach longer
2172
+ * after the wave has drained, 1 to fade it as fast as foam on open water.
2173
+ */ get settledFoamFade() {
2174
+ return this._shoreWaves.settledFoamFade;
2175
+ }
2176
+ set settledFoamFade(val) {
2177
+ this._shoreWaves.settledFoamFade = Math.min(Math.max(val, 0.01), 1);
2178
+ }
2179
+ /**
2180
+ * Hands the shore waves this frame's waterline fields: the shore field in
2181
+ * levels, null when there is none, which turns them off; and the wall field,
2182
+ * null for no foam against walls. Called by the water every frame.
2183
+ * @internal
2184
+ */ setShoreWaveFrame(shore, shoreRegions, wall, wallRegion, level) {
2185
+ this._shoreWaveGenerator?.setFrame(shore, shoreRegions, wall, wallRegion, level, this._waveClock);
2186
+ }
2187
+ /**
2188
+ * Steps the foam field around the water the view looks at, once a frame
2189
+ * however many views there are. Called by the water after
2190
+ * {@link setShoreWaveFrame}, which its sources read.
2191
+ * @param focusX - World x the field is centred on.
2192
+ * @param focusZ - World z the field is centred on.
2193
+ * @internal
2194
+ */ updateFoamField(focusX, focusZ) {
2195
+ if (!this._foamSource || this._foamFrameId === this._frameId) {
2196
+ return;
2197
+ }
2198
+ this._foamFrameId = this._frameId;
2199
+ this._foamField.stepAround(focusX, focusZ, this._waveClock, this._waveGenerator.get()?.wind ?? null, this._foamSource);
368
2200
  }
369
2201
  update(frameId, elapsed) {
2202
+ this._frameId = frameId;
2203
+ this._waveClock = elapsed;
2204
+ // The base generator and the field are stepped separately, each guarded by
2205
+ // its own per-frame mark, so a generator shared between two bodies of water
2206
+ // is still stepped once even when each body wraps it with its own field.
370
2207
  const waveGenerator = this._waveGenerator.get();
371
2208
  if (waveGenerator) {
372
2209
  const updateFrameId = WaterMaterial._waveUpdateState.get(waveGenerator);
373
2210
  if (updateFrameId !== frameId) {
374
- waveGenerator.update(elapsed);
2211
+ RenderGraphExecutor.profileScope('WaterWaves', ()=>waveGenerator.update(elapsed));
375
2212
  WaterMaterial._waveUpdateState.set(waveGenerator, frameId);
376
2213
  }
377
2214
  }
378
- }
379
- _getRampTexture(device, grad) {
380
- const width = 128;
381
- const height = 1;
382
- const texture = device.createTexture2D('rgba8unorm', width, height, {
383
- mipmapping: false
384
- });
385
- const numTexels = width * height;
386
- const data = new Uint8Array(numTexels * 4);
387
- const tmpcolor = new Vector3();
388
- for(let i = 0; i < numTexels; i++){
389
- grad.interpolate(i % width / width, tmpcolor);
390
- data[i * 4 + 0] = tmpcolor.x * 255 >> 0;
391
- data[i * 4 + 1] = tmpcolor.y * 255 >> 0;
392
- data[i * 4 + 2] = tmpcolor.z * 255 >> 0;
393
- data[i * 4 + 3] = 255;
394
- }
395
- texture.update(data, 0, 0, width, height);
396
- return texture;
397
- }
398
- _getScatterRampTexture(device) {
399
- if (!this._scatterRampTexture.get()) {
400
- if (!WaterMaterial._defaultScatterRampTexture.get()) {
401
- WaterMaterial._defaultScatterRampTexture.set(this._getRampTexture(device, WaterMaterial._scatterGrad));
402
- }
403
- this._scatterRampTexture.set(WaterMaterial._defaultScatterRampTexture.get());
404
- }
405
- return this._scatterRampTexture.get();
406
- }
407
- _getAbsorptionRampTexture(device) {
408
- if (!this._absorptionRampTexture.get()) {
409
- if (!WaterMaterial._defaultAbsorptionRampTexture.get()) {
410
- WaterMaterial._defaultAbsorptionRampTexture.set(this._getRampTexture(device, WaterMaterial._absorptionGrad));
2215
+ const interaction = this._interaction.get();
2216
+ if (interaction && this._interactiveWaveGenerator) {
2217
+ const updateFrameId = WaterMaterial._interactionUpdateState.get(interaction);
2218
+ if (updateFrameId !== frameId) {
2219
+ RenderGraphExecutor.profileScope('WaterInteraction', ()=>interaction.update(elapsed));
2220
+ WaterMaterial._interactionUpdateState.set(interaction, frameId);
411
2221
  }
412
- this._absorptionRampTexture.set(WaterMaterial._defaultAbsorptionRampTexture.get());
413
2222
  }
414
- return this._absorptionRampTexture.get();
415
2223
  }
416
2224
  }
417
2225
 
418
- export { WaterMaterial };
2226
+ export { DEFAULT_SCATTER_ANISOTROPY, REFRACT_BLUR_MAX_LOD, WATER_DEBUG_OUTPUTS, WaterMaterial };
419
2227
  //# sourceMappingURL=water.js.map