@threenative/terrain 0.1.11 → 0.1.13

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 (218) hide show
  1. package/README.md +1 -0
  2. package/dist/bake-DJ5cxg0C.d.ts +82 -0
  3. package/dist/editor/index.d.ts +4 -4
  4. package/dist/editor/index.js +1 -1
  5. package/dist/editor/server.d.ts +2 -2
  6. package/dist/editor/worker.d.ts +1 -1
  7. package/dist/editor/worker.js +1 -1
  8. package/dist/export.d.ts +1 -1
  9. package/dist/index.d.ts +51 -222
  10. package/dist/index.js +111 -2
  11. package/dist/kit-world.d.ts +107 -0
  12. package/dist/kit-world.js +5134 -0
  13. package/dist/kit.d.ts +21 -4
  14. package/dist/kit.js +19 -4
  15. package/dist/mcp/cook-child.js +9 -6
  16. package/dist/mcp/server.js +14 -4
  17. package/dist/prop-package-Dwz0EWoB.d.ts +141 -0
  18. package/dist/{server-B5RdvEAC.d.ts → server-LnFwY8sr.d.ts} +1 -1
  19. package/dist/starter.d.ts +1141 -6
  20. package/dist/starter.js +1999 -17
  21. package/dist/{terrain-CAEaW0mQ.d.ts → terrain-DYCyAOCJ.d.ts} +1 -1
  22. package/dist/three.d.ts +1 -1
  23. package/dist/{types-BpH00qsx.d.ts → types-kpI0C4hW.d.ts} +1 -1
  24. package/dist/{world-package-B8QgHjAQ.d.ts → world-package-DqJC3-Nn.d.ts} +2 -2
  25. package/docs/authoring/new-environment.md +97 -0
  26. package/package.json +8 -8
  27. package/starter/alpine/README.md +22 -14
  28. package/starter/alpine/bake.mjs +14 -1
  29. package/starter/alpine/biome.data.json +187 -25
  30. package/starter/alpine/heightmap.r16 +0 -0
  31. package/starter/alpine/playerRig.ts +89 -0
  32. package/starter/alpine/recipe.json +169 -15
  33. package/starter/alpine/render/bakedFile.ts +17 -0
  34. package/starter/alpine/render/benchmark.ts +77 -0
  35. package/starter/alpine/render/biomeData.ts +14 -0
  36. package/starter/alpine/render/biomes.ts +687 -0
  37. package/starter/alpine/render/ground/cover.ts +565 -0
  38. package/starter/alpine/render/ground/horizon.ts +219 -0
  39. package/starter/alpine/render/ground/palette.d.ts +1 -0
  40. package/starter/alpine/render/ground/palette.js +11 -0
  41. package/starter/alpine/render/ground/scatter.ts +104 -0
  42. package/starter/alpine/render/ground/terrain.ts +1860 -0
  43. package/starter/alpine/render/kitAssets.ts +28 -0
  44. package/starter/alpine/render/loading.ts +354 -0
  45. package/starter/alpine/render/lookKnobs.ts +37 -0
  46. package/starter/alpine/render/orbitCamera.ts +155 -0
  47. package/starter/alpine/render/props/farForest.ts +94 -0
  48. package/starter/alpine/render/props/pack.ts +1114 -0
  49. package/starter/alpine/render/props/prepared.ts +225 -0
  50. package/starter/alpine/render/props/propMaterials.ts +1239 -0
  51. package/starter/alpine/render/props/propProgress.ts +2 -0
  52. package/starter/alpine/render/props/propWorld.ts +105 -0
  53. package/starter/alpine/render/props/props.ts +633 -0
  54. package/starter/alpine/render/props/spruce.ts +440 -0
  55. package/starter/alpine/render/sky/atmosphere.ts +329 -0
  56. package/starter/alpine/render/sky/sky.ts +382 -0
  57. package/starter/alpine/render/texturePreparation.ts +135 -0
  58. package/starter/alpine/render/water/river.ts +1132 -0
  59. package/starter/alpine/render/worldNames.ts +6 -0
  60. package/starter/alpine/scene.ts +715 -0
  61. package/starter/alpine/sceneProps.ts +561 -0
  62. package/starter/alpine/sceneState.ts +33 -0
  63. package/starter/alpine/world/terrainAssets.ts +145 -0
  64. package/starter/alpine/world/walkBand.ts +47 -0
  65. package/starter/alpine/world/water.ts +74 -0
  66. package/starter/alpine/worlds.ts +13 -0
  67. package/starter/coastal/README.md +26 -27
  68. package/starter/coastal/assets.json +10 -0
  69. package/starter/coastal/bake.mjs +14 -1
  70. package/starter/coastal/biome.data.json +18 -3
  71. package/starter/coastal/playerRig.ts +89 -0
  72. package/starter/coastal/recipe.json +220 -18
  73. package/starter/coastal/render/bakedFile.ts +17 -0
  74. package/starter/coastal/render/benchmark.ts +81 -0
  75. package/starter/coastal/render/biomeData.ts +14 -0
  76. package/starter/coastal/render/biomes.ts +678 -0
  77. package/starter/coastal/render/ground/cover.ts +565 -0
  78. package/starter/coastal/render/ground/horizon.ts +219 -0
  79. package/starter/coastal/render/ground/palette.d.ts +1 -0
  80. package/starter/coastal/render/ground/palette.js +11 -0
  81. package/starter/coastal/render/ground/scatter.ts +104 -0
  82. package/starter/coastal/render/ground/terrain.ts +1829 -0
  83. package/starter/coastal/render/kitAssets.ts +28 -0
  84. package/starter/coastal/render/loading.ts +354 -0
  85. package/starter/coastal/render/lookKnobs.ts +37 -0
  86. package/starter/coastal/render/orbitCamera.ts +155 -0
  87. package/starter/coastal/render/props/farForest.ts +94 -0
  88. package/starter/coastal/render/props/pack.ts +1109 -0
  89. package/starter/coastal/render/props/prepared.ts +225 -0
  90. package/starter/coastal/render/props/propMaterials.ts +1239 -0
  91. package/starter/coastal/render/props/propProgress.ts +2 -0
  92. package/starter/coastal/render/props/propWorld.ts +105 -0
  93. package/starter/coastal/render/props/props.ts +633 -0
  94. package/starter/coastal/render/props/spruce.ts +440 -0
  95. package/starter/coastal/render/sky/atmosphere.ts +329 -0
  96. package/starter/coastal/render/sky/sky.ts +382 -0
  97. package/starter/coastal/render/texturePreparation.ts +135 -0
  98. package/starter/coastal/render/water/ocean.ts +284 -0
  99. package/starter/coastal/render/water/river.ts +1132 -0
  100. package/starter/coastal/render/worldNames.ts +6 -0
  101. package/starter/coastal/scene.ts +740 -0
  102. package/starter/coastal/sceneProps.ts +559 -0
  103. package/starter/coastal/sceneState.ts +33 -0
  104. package/starter/coastal/world/terrainAssets.ts +151 -0
  105. package/starter/coastal/world/walkBand.ts +47 -0
  106. package/starter/coastal/world/water.ts +74 -0
  107. package/starter/coastal/worlds.ts +13 -0
  108. package/starter/desert/README.md +51 -25
  109. package/starter/desert/bake-flora.mjs +142 -0
  110. package/starter/desert/bake-rocks.mjs +291 -0
  111. package/starter/desert/bake.mjs +14 -1
  112. package/starter/desert/biome.data.json +24 -12
  113. package/starter/desert/playerRig.ts +89 -0
  114. package/starter/desert/recipe.json +63 -16
  115. package/starter/desert/render/bakedFile.ts +17 -0
  116. package/starter/desert/render/benchmark.ts +79 -0
  117. package/starter/desert/render/biomeData.ts +14 -0
  118. package/starter/desert/render/biomes.ts +660 -0
  119. package/starter/desert/render/ground/cover.ts +565 -0
  120. package/starter/desert/render/ground/debris.ts +136 -0
  121. package/starter/desert/render/ground/horizon.ts +219 -0
  122. package/starter/desert/render/ground/palette.d.ts +1 -0
  123. package/starter/desert/render/ground/palette.js +11 -0
  124. package/starter/desert/render/ground/scatter.ts +104 -0
  125. package/starter/desert/render/ground/terrain.ts +1854 -0
  126. package/starter/desert/render/kitAssets.ts +28 -0
  127. package/starter/desert/render/loading.ts +354 -0
  128. package/starter/desert/render/lookKnobs.ts +37 -0
  129. package/starter/desert/render/orbitCamera.ts +155 -0
  130. package/starter/desert/render/props/farForest.ts +96 -0
  131. package/starter/desert/render/props/formations.ts +630 -0
  132. package/starter/desert/render/props/pack.ts +1195 -0
  133. package/starter/desert/render/props/prepared.ts +225 -0
  134. package/starter/desert/render/props/propMaterials.ts +1255 -0
  135. package/starter/desert/render/props/propProgress.ts +2 -0
  136. package/starter/desert/render/props/propWorld.ts +105 -0
  137. package/starter/desert/render/props/props.ts +624 -0
  138. package/starter/desert/render/props/spruce.ts +440 -0
  139. package/starter/desert/render/sand.ts +581 -0
  140. package/starter/desert/render/sky/atmosphere.ts +329 -0
  141. package/starter/desert/render/sky/sky.ts +382 -0
  142. package/starter/desert/render/texturePreparation.ts +135 -0
  143. package/starter/desert/render/water/river.ts +1132 -0
  144. package/starter/desert/render/worldNames.ts +6 -0
  145. package/starter/desert/scene.ts +748 -0
  146. package/starter/desert/sceneProps.ts +562 -0
  147. package/starter/desert/sceneState.ts +33 -0
  148. package/starter/desert/world/terrainAssets.ts +162 -0
  149. package/starter/desert/world/walkBand.ts +47 -0
  150. package/starter/desert/world/water.ts +74 -0
  151. package/starter/desert/worlds.ts +13 -0
  152. package/starter/forest/README.md +8 -5
  153. package/starter/forest/bake.mjs +21 -413
  154. package/starter/forest/playerRig.ts +37 -171
  155. package/starter/forest/recipe.json +237 -47
  156. package/starter/forest/render/biomes.ts +2 -1
  157. package/starter/forest/render/ground/horizon.ts +4 -302
  158. package/starter/forest/render/ground/terrain.ts +14 -32
  159. package/starter/forest/render/kitAssets.ts +3 -2
  160. package/starter/forest/render/props/farForest.ts +2 -1
  161. package/starter/forest/render/props/pack.ts +4 -2
  162. package/starter/forest/render/props/prepared.ts +2 -1
  163. package/starter/forest/render/props/propProgress.ts +1 -11
  164. package/starter/forest/render/props/propWorld.ts +48 -662
  165. package/starter/forest/render/props/props.ts +64 -248
  166. package/starter/forest/render/sky/sky.ts +2 -1
  167. package/starter/forest/render/worldNames.ts +6 -2
  168. package/starter/forest/scene.ts +34 -25
  169. package/starter/forest/sceneProps.ts +2 -2
  170. package/starter/forest/sceneState.ts +5 -4
  171. package/starter/forest/surface.json +2 -2
  172. package/starter/forest/worlds.ts +3 -2
  173. package/starter/tundra/README.md +35 -16
  174. package/starter/tundra/bake.mjs +14 -1
  175. package/starter/tundra/biome.data.json +6 -6
  176. package/starter/tundra/playerRig.ts +89 -0
  177. package/starter/tundra/recipe.json +111 -110
  178. package/starter/tundra/render/bakedFile.ts +17 -0
  179. package/starter/tundra/render/benchmark.ts +79 -0
  180. package/starter/tundra/render/biomeData.ts +14 -0
  181. package/starter/tundra/render/biomes.ts +714 -0
  182. package/starter/tundra/render/ground/cover.ts +565 -0
  183. package/starter/tundra/render/ground/horizon.ts +219 -0
  184. package/starter/tundra/render/ground/palette.d.ts +1 -0
  185. package/starter/tundra/render/ground/palette.js +11 -0
  186. package/starter/tundra/render/ground/scatter.ts +104 -0
  187. package/starter/tundra/render/ground/terrain.ts +1874 -0
  188. package/starter/tundra/render/kitAssets.ts +28 -0
  189. package/starter/tundra/render/loading.ts +354 -0
  190. package/starter/tundra/render/lookKnobs.ts +37 -0
  191. package/starter/tundra/render/orbitCamera.ts +155 -0
  192. package/starter/tundra/render/props/farForest.ts +96 -0
  193. package/starter/tundra/render/props/pack.ts +1088 -0
  194. package/starter/tundra/render/props/prepared.ts +225 -0
  195. package/starter/tundra/render/props/propMaterials.ts +1247 -0
  196. package/starter/tundra/render/props/propProgress.ts +2 -0
  197. package/starter/tundra/render/props/propWorld.ts +105 -0
  198. package/starter/tundra/render/props/props.ts +624 -0
  199. package/starter/tundra/render/props/spruce.ts +440 -0
  200. package/starter/tundra/render/sky/atmosphere.ts +329 -0
  201. package/starter/tundra/render/sky/sky.ts +382 -0
  202. package/starter/tundra/render/texturePreparation.ts +135 -0
  203. package/starter/tundra/render/water/river.ts +1132 -0
  204. package/starter/tundra/render/worldNames.ts +6 -0
  205. package/starter/tundra/scene.ts +715 -0
  206. package/starter/tundra/sceneProps.ts +559 -0
  207. package/starter/tundra/sceneState.ts +33 -0
  208. package/starter/tundra/world/terrainAssets.ts +159 -0
  209. package/starter/tundra/world/walkBand.ts +47 -0
  210. package/starter/tundra/world/water.ts +74 -0
  211. package/starter/tundra/worlds.ts +13 -0
  212. package/starter-assets.json +4 -4
  213. package/starter-credits.json +613 -10
  214. package/starter/forest/diagnostics.ts +0 -1020
  215. package/starter/forest/render/sky/skyVisibility.ts +0 -121
  216. package/starter/forest/spawnGate.ts +0 -183
  217. package/starter/forest/viewStatistics.ts +0 -47
  218. package/starter/forest/world/streamedGround.ts +0 -139
@@ -0,0 +1,1132 @@
1
+ // The Temperate water: the lake in the basin and the stream the bake carved down to it.
2
+ //
3
+ // Ported from Wildwood's `src/render/water/water.ts` (`createWater`), which is where the model below comes
4
+ // from — the wind-gated wave field, the graded slope gain, the Beer-Lambert body, the shore dissolve
5
+ // and the Snell's window. Wildwood's pond.ts dresses that same surface with rocks and reeds, so
6
+ // nothing of it is ported: what makes still water read as water is the model, not the dressing.
7
+ //
8
+ // Three things here are this game's rather than Wildwood's:
9
+ //
10
+ // - **The depth is baked, and it is real.** Neither basin nor bed moves, so every vertex carries the
11
+ // metres of water standing on it, out of the same `heightAt` the terrain mesh and the collider
12
+ // read. That is what puts the shoreline on the ground's own contour instead of on a drawn circle,
13
+ // what makes the margin dissolve instead of ending on a triangle, and what keeps the shallows
14
+ // legible at a grazing angle, where a screen-space depth read has nothing to say.
15
+ // - **The lake keeps a real planar mirror.** The basin is level, so unlike the stream it can have
16
+ // one, and the mirror is what carries the far bank upside down — the one thing that makes still
17
+ // water read as water. It draws layer 0 only, which is why the water sits on `WATER_LAYER`: a
18
+ // water surface inside the mirrored pass samples a single-sampled depth target and fails WebGPU
19
+ // validation, taking the frame down with it.
20
+ // - **The forest stream has no mirror.** It falls fifteen metres over its length, so a planar
21
+ // reflection would be right at one bend and wrong everywhere else; the banks and the sky come back
22
+ // by a reflected-ray march over the frame (`traceReflection`), over an analytic sky where the ray
23
+ // leaves the screen. Tundra channels share the kettle ponds' existing mirrors, blended by
24
+ // elevation, so the stream and pond meet without a reflection-colour seam.
25
+ //
26
+ // Nothing here decides a colour for the engine: `WaterSurface3D` measures metres and hands back the
27
+ // frame beneath the surface and the world mirrored in it, and every number under LOOK below is this
28
+ // game's. One rule worth carrying: **`new Color(hex)` already converts sRGB to linear**, because
29
+ // three enables `ColorManagement` by default — calling `convertSRGBToLinear()` on top of it darkens
30
+ // every palette colour by a factor between three and thirteen, and the shader then reads as "wants
31
+ // turning up" rather than as broken.
32
+ import { WaterSurface3D, WaveField } from "@threenative/core";
33
+ import {
34
+ type Heightfield,
35
+ lakeReach,
36
+ lakeSurfaceGeometry,
37
+ riverRibbonGeometry,
38
+ } from "@threenative/core/world";
39
+ import { BufferAttribute, Color, DoubleSide, Mesh } from "three";
40
+ import { mergeGeometries } from "three/addons/utils/BufferGeometryUtils.js";
41
+ import {
42
+ attribute,
43
+ cameraFar,
44
+ cameraNear,
45
+ cameraPosition,
46
+ cameraProjectionMatrix,
47
+ cameraViewMatrix,
48
+ clamp,
49
+ color,
50
+ dFdx,
51
+ dFdy,
52
+ dot,
53
+ exp,
54
+ float,
55
+ linearDepth,
56
+ max,
57
+ min,
58
+ mix,
59
+ mx_noise_float,
60
+ normalize,
61
+ positionLocal,
62
+ positionWorld,
63
+ pow,
64
+ smoothstep,
65
+ step,
66
+ uniform,
67
+ vec2,
68
+ vec3,
69
+ vec4,
70
+ viewportDepthTexture,
71
+ viewportSharedTexture,
72
+ } from "three/tsl";
73
+ import type { Node } from "three/webgpu";
74
+ import { MeshBasicNodeMaterial } from "three/webgpu";
75
+ import { SUN, SUN_VECTOR } from "../sky/sky.js";
76
+
77
+ /** One river as the bake records it: the smoothed spline and the width of its water. */
78
+ export interface IBakedRiver {
79
+ readonly id: string;
80
+ readonly points: readonly (readonly number[])[];
81
+ readonly width: number;
82
+ }
83
+
84
+ /**
85
+ * The layer water draws on, and the only one the lake's mirror leaves out.
86
+ *
87
+ * Water reads the frame's depth to know how deep it is, and inside the mirror pass that depth is the
88
+ * mirror's own single-sampled target: drawing a water surface into the mirror fails WebGPU validation
89
+ * and takes the frame down with it. Water in a lake's reflection is the lake itself anyway.
90
+ */
91
+ export const WATER_LAYER = 1;
92
+ /** What the water mirror redraws: the ground and its distant ring, not every tree and blade again. */
93
+ export const REFLECTED_LAYER = 3;
94
+
95
+ /**
96
+ * Metres a second the forest stream flows. Unreal leaves it to the level's `WaterVelocityScalar`
97
+ * spline curve, defaulting to 128 cm/s (UE 5.8.3:
98
+ * Engine/Plugins/Experimental/Water/Source/Runtime/Public/WaterSplineMetadata.h:40), which is a
99
+ * river at its steepest; a lowland forest stream this size runs slower, so 0.9 m/s. The surface
100
+ * ripples advect at it and `waterCurrentAt` carries a swimmer with it, so what is drawn and what
101
+ * pushes the player are the same flow.
102
+ */
103
+ export const RIVER_FLOW_MPS = 0.9;
104
+
105
+ /** The stream's shape. The surface's geometry is core's `riverRibbonGeometry`, at the reach `WaterBodies` floods. */
106
+ const RIVER = {
107
+ /** Metres of water over the deepest point of the bed. The bank rises out of it on its own. */
108
+ fill: 1.1,
109
+ /**
110
+ * Stations over which the fill tapers to nothing at each end of the path, so the surface meets the
111
+ * ground it is over instead of stopping in a wall of water. See `surfaceHeights`.
112
+ */
113
+ taper: 9,
114
+ /**
115
+ * Vertices across the surface. The shore dissolve is a ramp in metres of depth, so the column
116
+ * spacing is what decides how wide the wet margin reads: at thirteen the ramp fitted inside one
117
+ * quad and the bank cut the surface like a blade.
118
+ */
119
+ across: 25,
120
+ /** The wind patches on moving water: how big one is, how fast it crosses, and which way. */
121
+ patch: { metres: 9, drift: 1.4, wind: [0.86, 0.51] as const },
122
+ /**
123
+ * The ripple scales: feature size across the current in metres, how much longer each is along it,
124
+ * the share of `RIVER_FLOW_MPS` it drifts downstream at, and the slope it adds. The shares average
125
+ * one, so the surface moves at the flow the player is carried at, and their spread keeps the
126
+ * scales sliding over each other instead of scrolling as one sheet. The old gains summed to slopes of one to
127
+ * four, a 45-75 degree chop that read as crumpled plastic. Each scale fades out once one pixel
128
+ * covers a fifth of it; see `footprint` in `createRivers`.
129
+ */
130
+ ripples: [
131
+ { metres: 2.4, stretch: 1.7, flow: 0.8, slope: 0.09 },
132
+ { metres: 0.85, stretch: 1.5, flow: 1, slope: 0.08 },
133
+ { metres: 0.3, stretch: 1.3, flow: 1.2, slope: 0.06 },
134
+ ],
135
+ } as const;
136
+
137
+ /**
138
+ * The reflected-ray march: steps, the first step in metres, how much each step grows, and the edge
139
+ * fade. Geometric steps resolve the bank a metre off and still reach the far shore. 14 steps reach
140
+ * 0.45 * (1.3^14 - 1) / 0.3 = 58 m. Past that, a direction read takes over; see `traceReflection`.
141
+ */
142
+ const TRACE = { steps: 14, first: 0.45, growth: 1.3 } as const;
143
+
144
+ /**
145
+ * How far past a basin's measured waterline a lake's water reaches, so the real shore stands inside
146
+ * it. The drawn surface and the swim footprint both size themselves at it.
147
+ */
148
+ export const LAKE_REACH = 1.12;
149
+
150
+ /** The lake's shape, and how its mirror is taken. Every number here is this game's. */
151
+ const LAKE = {
152
+ /**
153
+ * Mirror pixels as a share of the frame's, how often it redraws, and the layer mask it draws. Half
154
+ * the frame's pixels, as Unreal's planar reflection takes by default (UE 5.8.3:
155
+ * Engine/Source/Runtime/Engine/Private/Components/SceneCaptureComponent.cpp:1136,
156
+ * `ScreenPercentage = 50`): the mirror draws the full ground material, and at full size it cost a
157
+ * third of the overview's ground time for a reflection the ripples scatter anyway.
158
+ */
159
+ mirror: { resolutionScale: 0.5, refreshInterval: 2, layers: 1 << REFLECTED_LAYER },
160
+ /** Rings and spokes in the disc the basin is meshed as. */
161
+ rings: 44,
162
+ spokes: 88,
163
+ /** How far past the measured waterline the mesh reaches, so the real shore is inside it. */
164
+ reach: LAKE_REACH,
165
+ /** How the ring spacing grows outwards. Above 1 packs vertices into the near water. */
166
+ packing: 1.7,
167
+ } as const;
168
+
169
+ /**
170
+ * Extinction per metre, per channel, in the renderer's linear space.
171
+ *
172
+ * Red dies first and blue survives, which is why fresh water over a green bed reads teal. Roughly
173
+ * two and a half times distilled water: this basin carries the meadow in it — leaf tannin, silt, grass
174
+ * — and a lake you can see four metres into reads as a swimming pool. The Temperate basin is 1.3 m at
175
+ * its deepest, so this is a grade across a hand's depth rather than a wall of colour.
176
+ */
177
+ const EXTINCTION: readonly [number, number, number] = [1.6, 0.65, 0.42];
178
+
179
+ /** Metres of water past which the bed stops contributing. The basin bottoms out near 1.3 m. */
180
+ const OPAQUE_DEPTH = 1.2;
181
+
182
+ /** Deepest reading the baked attribute carries. Past the basin's own depth, so nothing saturates. */
183
+ const MAX_BAKED_DEPTH = 1.6;
184
+
185
+ /**
186
+ * Peak ripple slope close to the camera, and far from it.
187
+ *
188
+ * The wave field's honest peak slope is about 5°, which is right for sheltered water and far too
189
+ * small to see once it is the only thing bending a reflection. The physical argument for grading it
190
+ * is that one distant pixel covers many ripples and shows their average: near water gets chop you can
191
+ * see, water past seventy metres is a mirror.
192
+ */
193
+ const SLOPE_GAIN_NEAR = 1.4;
194
+ const SLOPE_GAIN_FAR = 0.65;
195
+ const SLOPE_FADE_NEAR = 10;
196
+ const SLOPE_FADE_FAR = 72;
197
+
198
+ /** Where the short ripples start and finish fading, in metres from the camera. */
199
+ const DETAIL_NEAR = 12;
200
+ const DETAIL_FAR = 44;
201
+
202
+ /**
203
+ * How much of the surface slope the reflection sees, as a share of what the glint sees.
204
+ *
205
+ * Two readings of one surface wanting two amounts of it: a glint is a peak-finder and wants every
206
+ * steep facet, a reflection is an average over the pixel's footprint and shreds into oil-slick
207
+ * crumple when fed the unfiltered slope.
208
+ */
209
+ const REFLECT_SLOPE_SHARE = 0.55;
210
+
211
+ /** The wind patches: their size, their drift, and how calm the calm is (zero would read as ice). */
212
+ const PATCH_METRES = 21;
213
+ const PATCH_DRIFT = 0.7;
214
+ const PATCH_CALM = 0.45;
215
+
216
+ /**
217
+ * How far a screen-space read may slide, in fractions of the frame, looking straight down and at a
218
+ * grazing angle. Grazing fragments slide further, because that is what a longer path through a
219
+ * tilted surface does. Beyond this the reflection stops being a reflection and becomes a smear of
220
+ * whatever happened to be in those pixels.
221
+ */
222
+ const REFRACTION_NEAR = 0.004;
223
+ const REFRACTION_FAR = 0.026;
224
+
225
+ /** How far the reflection smears, in fractions of the screen, at the near and far ends. */
226
+ const REFLECT_BLUR_NEAR = 0.0012;
227
+ const REFLECT_BLUR_FAR = 0.003;
228
+ /** How much narrower the smear is across the screen than down it. */
229
+ const REFLECT_BLUR_ASPECT = 0.5;
230
+
231
+ /** The floor under Schlick: still water seen straight down is not perfectly clear. */
232
+ const SKY_FLOOR = 0.045;
233
+
234
+ /** The analytic sky's gain, to sit at the drawn sky's radiance where the two meet at a frame edge. */
235
+ const SKY_GAIN = 0.65;
236
+
237
+ /**
238
+ * Haze on a reflected far read: clear for the first metres, as the post's aerial perspective is
239
+ * (`atmosphere.ts`, 150 m), then an exponential toward the horizon colour.
240
+ */
241
+ const HAZE_CLEAR = 150;
242
+ const HAZE_METRES = 1600;
243
+
244
+ /**
245
+ * GGX roughness of the capillary ripple below every drawn wave, and of a far lake whose waves the
246
+ * pixel averages: Unreal's water material ships a roughness of 0.1 for that reason.
247
+ */
248
+ const ROUGHNESS_NEAR = 0.04;
249
+ const ROUGHNESS_FAR = 0.13;
250
+ /** Peak glint per unit of sun irradiance: a facet can be bright, not a white spark that blooms. */
251
+ const GLINT_CAP = 3;
252
+
253
+ /** Where the ripple may start, in metres of depth. Water at the gravel is glass. */
254
+ const RIPPLE_DEPTH = 0.35;
255
+
256
+ /** The wet band at the margin, in metres of depth: the surface fades out across it. */
257
+ const SHORE_FADE = 0.42;
258
+
259
+ /** How far the mirrored bed smears under the surface, in fractions of the screen. */
260
+ const UNDER_BLUR = 0.004;
261
+
262
+ /** The cosine band the Snell's-window edge is blended over. Water's critical angle is 48.6°. */
263
+ const SNELL_INNER = 0.6;
264
+ const SNELL_OUTER = 0.79;
265
+
266
+ /** This game's water body: silt at the margin, cold green in the middle, moss in the sun path. */
267
+ const TINT = {
268
+ silt: 0x789f98,
269
+ shallow: 0.08,
270
+ deep: 0x1f3833,
271
+ deepGain: 0.26,
272
+ /** Sunlight scattered back out of the shallows. */
273
+ glow: 0x75a99b,
274
+ /** Foam and white water. */
275
+ foam: 0xe8efe8,
276
+ /** The sky the stream reflects: the horizon haze, and the zenith above it. */
277
+ skyHorizon: 0xd2e0ec,
278
+ skyZenith: 0x86acd2,
279
+ /**
280
+ * What stands on both banks of a stream in spruce wood. A reflected ray leaving the surface at two
281
+ * degrees does not reach the sky at all — it hits a trunk — and without this floor the stream is a
282
+ * strip of chrome wherever the eye is low enough for the fresnel to close.
283
+ */
284
+ bank: 0x627660,
285
+ bankGain: 0.8,
286
+ } as const;
287
+
288
+ /**
289
+ * A linear-space vec3 node from a colour, so the shader math is in the renderer's space.
290
+ *
291
+ * The palette is authored in sRGB, which is what a person picks colours in; every number below is
292
+ * multiplied and exponentiated, so it has to be linear or the absorption curve is applied to a
293
+ * gamma-encoded quantity and the shallows come out chalky. `new Color(hex)` has already made that
294
+ * conversion — see the file header.
295
+ */
296
+ function linear(value: number | Color, gain = 1): Node<"vec3"> {
297
+ const tint = typeof value === "number" ? new Color(value) : value;
298
+ return vec3(tint.r * gain, tint.g * gain, tint.b * gain);
299
+ }
300
+
301
+ /**
302
+ * The lake's ripple: eight waves, no two of them commensurate, under one slow domain warp.
303
+ *
304
+ * 11.3, 7.1, 4.7, 3.1, 1.9, 1.3, 0.79 and 0.53 metres. Ratios near, but never at, small whole numbers
305
+ * is the whole point: wavelengths at 8/4/2/1 reline up every eight metres and draw visible corduroy.
306
+ * The warp bends the domain the waves are measured in, so crests curve and wander instead of running
307
+ * as a sum of straight lines. Amplitudes are tiny because this is sheltered water — they set the
308
+ * *normal*, which is what the light reads.
309
+ */
310
+ const RIPPLE = new WaveField({
311
+ waves: [
312
+ { amplitude: 0.021, direction: [0.94, 0.35], wavelength: 11.3, speed: 0.78 },
313
+ { amplitude: 0.014, direction: [-0.42, 0.91], wavelength: 7.1, speed: 0.61, phase: 1.7 },
314
+ { amplitude: 0.009, direction: [0.71, -0.7], wavelength: 4.7, speed: 0.52, phase: 2.4 },
315
+ { amplitude: 0.006, direction: [-0.87, -0.49], wavelength: 3.1, speed: 0.44, phase: 0.8 },
316
+ {
317
+ amplitude: 0.0035,
318
+ detail: true,
319
+ direction: [0.29, 0.96],
320
+ wavelength: 1.9,
321
+ speed: 0.37,
322
+ phase: 3.9,
323
+ },
324
+ {
325
+ amplitude: 0.0022,
326
+ detail: true,
327
+ direction: [-0.66, 0.75],
328
+ wavelength: 1.3,
329
+ speed: 0.31,
330
+ phase: 5.2,
331
+ },
332
+ {
333
+ amplitude: 0.0013,
334
+ detail: true,
335
+ direction: [0.98, -0.19],
336
+ wavelength: 0.79,
337
+ speed: 0.26,
338
+ phase: 1.1,
339
+ },
340
+ {
341
+ amplitude: 0.0008,
342
+ detail: true,
343
+ direction: [-0.12, -0.99],
344
+ wavelength: 0.53,
345
+ speed: 0.21,
346
+ phase: 4.4,
347
+ },
348
+ ],
349
+ domainWarp: [
350
+ { direction: [0.8, 0.6], displacement: [0.55, -0.38], wavelength: 23, speed: 0.13, phase: 0.6 },
351
+ ],
352
+ });
353
+
354
+ export interface IRiverWater {
355
+ readonly mesh: Mesh;
356
+ /** Lake mirror sampling, shared with joining streams without another reflection pass. */
357
+ readonly reflectionAt?: (offset: Node<"vec2">) => Node<"vec3">;
358
+ /** The water's clock, in seconds; the scene advances it so the playtest's time is the water's. */
359
+ advance(elapsed: number): void;
360
+ dispose(): void;
361
+ }
362
+
363
+ /**
364
+ * Everything a fragment of water is made of, whatever it is water in.
365
+ *
366
+ * One composite for both surfaces, so the stream and the lake cannot drift apart: they are the same
367
+ * body of water with a different surface normal over them, and the difference a player can see
368
+ * between a river and a lake is the ripple and the mirror, not the colour of what comes up through it.
369
+ */
370
+ interface IWaterShading {
371
+ /** World normal, already graded by distance, wind patch and depth. */
372
+ readonly normal: Node<"vec3">;
373
+ /** Baked metres of water standing on this vertex. */
374
+ readonly depthM: Node<"float">;
375
+ /** The frame beneath the surface, offset by the normal. */
376
+ readonly bed: Node<"vec3">;
377
+ /** The world mirrored in this surface: the mirror target for the lake, the sky for the stream. */
378
+ readonly reflected: Node<"vec3">;
379
+ /**
380
+ * GGX roughness of the sun's lobe: a floor for the capillary ripple no normal draws, plus the
381
+ * slope of every ripple too fine for the pixel. A far pixel averages many facets, so its glint
382
+ * spreads into a glitter path instead of aliasing into separate white sparks.
383
+ */
384
+ readonly roughness: Node<"float">;
385
+ /** What this water absorbs and scatters back. The lake's own when omitted. */
386
+ readonly body?: IWaterBody;
387
+ }
388
+
389
+ /** A water body's colour: extinction per metre (linear RGB), and its scatter, shallow and deep. */
390
+ interface IWaterBody {
391
+ readonly extinction: readonly [number, number, number];
392
+ readonly shallow: number;
393
+ readonly shallowGain: number;
394
+ readonly deep: number;
395
+ readonly deepGain: number;
396
+ }
397
+
398
+ const LAKE_BODY: IWaterBody = {
399
+ extinction: EXTINCTION,
400
+ shallow: TINT.silt,
401
+ shallowGain: TINT.shallow,
402
+ deep: TINT.deep,
403
+ deepGain: TINT.deepGain,
404
+ };
405
+
406
+ /**
407
+ * The forest stream's body: clear over the gravel, green-brown where it deepens. Leaf tannin takes
408
+ * blue first and red second, so a metre of it reads olive rather than the lake's teal.
409
+ */
410
+ const STREAM_BODY: IWaterBody = {
411
+ extinction: [0.85, 0.55, 1.25],
412
+ shallow: 0x9a9468,
413
+ shallowGain: 0.07,
414
+ deep: 0x34401f,
415
+ deepGain: 0.3,
416
+ };
417
+
418
+ /** The composite: what comes up through the surface, what sits on it, and the sun's glint. */
419
+ function compositeWater(surface: IWaterShading): Node<"vec3"> {
420
+ const { normal, depthM, bed, reflected, roughness } = surface;
421
+ const water = surface.body ?? LAKE_BODY;
422
+ const view = normalize(cameraPosition.sub(positionWorld));
423
+ const facing = clamp(dot(normal, view), float(0), float(1));
424
+ // Schlick at water's 1.333 index: F0 is 0.02, which is why still water at your feet is nearly
425
+ // clear and the same water at the far bank is a mirror.
426
+ const fresnel = float(0.02).add(pow(float(1).sub(facing), 5).mul(0.98));
427
+
428
+ // How far light travels through this water to reach the eye: straight down it is the baked depth,
429
+ // at a grazing angle it is far further, which is the whole reason water is clear at your feet and
430
+ // opaque at the far bank. The floor on `facing` keeps a horizon fragment asking for a kilometre.
431
+ const path = min(depthM.div(max(facing, float(0.12))), float(MAX_BAKED_DEPTH * 1.6));
432
+ const tint = exp(
433
+ vec3(-water.extinction[0], -water.extinction[1], -water.extinction[2]).mul(path),
434
+ );
435
+
436
+ // Caustics: the same analytic normal that bends the reflection focuses the sun onto the bed, so the
437
+ // bright cells are where the surface happens to point at it, drifting with the ripple causing them.
438
+ // Killed with depth, because a caustic is a shallow-water phenomenon and the bed at two metres is
439
+ // in shade.
440
+ const focus = pow(clamp(dot(normal, SUN_VECTOR), float(0), float(1)), 34);
441
+ const caustic = focus.mul(1.7).mul(float(1).sub(smoothstep(float(0.15), float(1.9), depthM)));
442
+
443
+ // What the water body itself scatters back: silt at the margin, the lake's own green in the middle.
444
+ // The gains are small because these are radiances, not albedos: a fraction of what the bank returns.
445
+ const shallowBody = linear(water.shallow, water.shallowGain).mul(vec3(1.06, 1, 0.74));
446
+ const deepBody = linear(water.deep, water.deepGain);
447
+ const body = mix(shallowBody, deepBody, smoothstep(float(0.1), float(2.4), depthM));
448
+
449
+ const submerged = bed
450
+ .mul(tint)
451
+ .mul(float(1).add(caustic))
452
+ .add(body.mul(float(1).sub(tint)));
453
+
454
+ // Subsurface scatter: the green-gold glow of shallow water with the sun behind it — light that went
455
+ // in, bounced around in the silt and came back out rather than reflecting off the top.
456
+ const towardSun = clamp(dot(view.negate(), SUN_VECTOR), float(0), float(1));
457
+ const glow = pow(towardSun, 2.5)
458
+ .mul(float(1).sub(smoothstep(float(0.2), float(1.8), depthM)))
459
+ .mul(0.26);
460
+ const underwater = submerged.add(
461
+ linear(TINT.glow, 0.35)
462
+ .mul(vec3(1.3, 1.15, 0.6))
463
+ .mul(glow),
464
+ );
465
+
466
+ const skyWeight = min(float(SKY_FLOOR).add(fresnel.mul(float(1 - SKY_FLOOR))), float(1));
467
+ const composited = mix(underwater, reflected, skyWeight);
468
+
469
+ // The sun off the same normal, as GGX with Schlick's fresnel and the Kelemen visibility term: lit
470
+ // by the sun's own irradiance, so its brightness agrees with the ground it shines on. The cap
471
+ // keeps a single facet from blooming into a hard white spark.
472
+ const halfway = normalize(view.add(SUN_VECTOR));
473
+ const nh = clamp(dot(normal, halfway), float(0), float(1));
474
+ const a2 = roughness.mul(roughness);
475
+ const lobe = nh.mul(nh).mul(a2.sub(1)).add(1);
476
+ const vh = clamp(dot(view, halfway), float(0.05), float(1));
477
+ const sunFresnel = float(0.02).add(pow(float(1).sub(vh), 5).mul(0.98));
478
+ const glint = a2
479
+ .div(lobe.mul(lobe).mul(Math.PI))
480
+ .mul(sunFresnel)
481
+ .mul(clamp(dot(normal, SUN_VECTOR), float(0), float(1)))
482
+ .div(vh.mul(vh).mul(4));
483
+ return composited.add(linear(SUN.colour, SUN.intensity).mul(min(glint, float(GLINT_CAP))));
484
+ }
485
+
486
+ /**
487
+ * How much ripple the wind is touching here, 0..1.
488
+ *
489
+ * Two octaves of gradient noise in world metres, drifting downwind and evolving slowly in place.
490
+ * Noise rather than another wave sum, because a sum of sines used as a mask carries the corduroy the
491
+ * waves themselves exist to avoid.
492
+ */
493
+ function windPatch(
494
+ here: Node<"vec2">,
495
+ time: Node<"float">,
496
+ metres: number,
497
+ drift: number,
498
+ wind: readonly [number, number],
499
+ ): Node<"float"> {
500
+ const uv = here.mul(1 / metres).sub(vec2(wind[0], wind[1]).mul(time.mul(drift / metres)));
501
+ const coarse = mx_noise_float(vec3(uv.x, uv.y, time.mul(0.021)));
502
+ const fine = mx_noise_float(
503
+ vec3(uv.x.mul(2.7).add(11.3), uv.y.mul(2.7).sub(4.1), time.mul(0.048)),
504
+ );
505
+ return smoothstep(float(-0.12), float(0.34), coarse.add(fine.mul(0.34)));
506
+ }
507
+
508
+ /** The slope gain: near and far, damped in the calm patches and in the last hand's depth of water. */
509
+ function slopeGain(
510
+ eyeDistance: Node<"float">,
511
+ patch: Node<"float">,
512
+ depthM: Node<"float">,
513
+ ): Node<"float"> {
514
+ return mix(
515
+ float(SLOPE_GAIN_NEAR),
516
+ float(SLOPE_GAIN_FAR),
517
+ smoothstep(float(SLOPE_FADE_NEAR), float(SLOPE_FADE_FAR), eyeDistance),
518
+ )
519
+ .mul(mix(float(PATCH_CALM), float(1), patch))
520
+ .mul(smoothstep(float(0), float(RIPPLE_DEPTH), depthM));
521
+ }
522
+
523
+ /** The shore: the surface dissolves into the wet margin instead of ending on a triangle. */
524
+ function shoreFade(depthM: Node<"float">): Node<"float"> {
525
+ return smoothstep(float(0), float(SHORE_FADE), depthM);
526
+ }
527
+
528
+ /** The analytic sky along a reflected ray, at the frame's radiance, for rays off the screen. */
529
+ function skyAlong(bounced: Node<"vec3">): Node<"vec3"> {
530
+ return mix(
531
+ color(TINT.skyHorizon),
532
+ color(TINT.skyZenith),
533
+ clamp(bounced.y, float(0), float(1)),
534
+ ).mul(SKY_GAIN);
535
+ }
536
+
537
+ /**
538
+ * The frame reflected along `direction` from this fragment, over `fallback` where the frame cannot
539
+ * say: what a planar mirror cannot give a stream that falls along its length, and what the lake's
540
+ * ground-only mirror leaves out, the spruces on the far bank.
541
+ *
542
+ * Unreal's single-layer water takes the scene's own screen-space reflections (UE 5.8.3:
543
+ * Engine/Source/Runtime/Renderer/Private/SingleLayerWaterRendering.cpp:69), marched in 16 steps at
544
+ * the default quality (Engine/Shaders/Private/SSRT/SSRTReflections.usf:203) and faded over the outer
545
+ * fifth of the screen (Engine/Shaders/Private/SSRT/SSRTRayCast.ush:674-680). Here the steps grow in
546
+ * metres instead (`TRACE`). Past the last step the ray's own direction is read off the screen: sky, a
547
+ * mountain or a stand of trees far enough away that the parallax a march corrects is under a pixel.
548
+ */
549
+ function traceReflection(direction: Node<"vec3">, fallback: Node<"vec3">): Node<"vec3"> {
550
+ const span = cameraFar.sub(cameraNear);
551
+ const sceneMetres = (uv: Node<"vec2">): Node<"float"> =>
552
+ linearDepth(viewportDepthTexture(clamp(uv, vec2(0.001, 0.001), vec2(0.999, 0.999))))
553
+ .mul(span)
554
+ .add(cameraNear);
555
+ const screen = (clip: Node<"vec4">): { ndc: Node<"vec2">; uv: Node<"vec2"> } => {
556
+ const ndc = clip.xy.div(max(clip.w, float(0.0001)));
557
+ // Clip space has +1 at the top and the frame samples with 0 there; see the mirrored bed below.
558
+ return { ndc, uv: vec2(ndc.x.mul(0.5).add(0.5), ndc.y.mul(-0.5).add(0.5)) };
559
+ };
560
+ const inside = (ndc: Node<"vec2">): Node<"float"> =>
561
+ step(max(ndc.x.abs(), ndc.y.abs()), float(1));
562
+ const vignette = (ndc: Node<"vec2">): Node<"float"> => {
563
+ const edge = clamp(ndc.abs().mul(5).sub(4), vec2(0, 0), vec2(1, 1));
564
+ return clamp(float(1).sub(dot(edge, edge)), float(0), float(1));
565
+ };
566
+
567
+ let found: Node<"float"> = float(0);
568
+ let hitUv: Node<"vec2"> = vec2(0.5, 0.5);
569
+ let hitNdc: Node<"vec2"> = vec2(0, 0);
570
+ let stride: number = TRACE.first;
571
+ let reached = 0;
572
+ for (let index = 0; index < TRACE.steps; index += 1) {
573
+ reached += stride;
574
+ const point = positionWorld.add(direction.mul(reached));
575
+ const clip = cameraProjectionMatrix.mul(
576
+ cameraViewMatrix.mul(vec4(point.x, point.y, point.z, 1)),
577
+ );
578
+ const { ndc, uv } = screen(clip);
579
+ // `clip.w` is the point's metres in front of the eye, the same measure as the frame's depth.
580
+ const behind = clip.w.sub(sceneMetres(uv));
581
+ const hit = step(float(0), behind)
582
+ .mul(step(behind, float(stride * 1.6 + 0.25)))
583
+ .mul(inside(ndc))
584
+ .mul(step(float(0.05), clip.w));
585
+ const take = hit.mul(float(1).sub(found));
586
+ hitUv = mix(hitUv, uv, take);
587
+ hitNdc = mix(hitNdc, ndc, take);
588
+ found = found.add(take);
589
+ stride *= TRACE.growth;
590
+ }
591
+ const away = cameraProjectionMatrix.mul(
592
+ cameraViewMatrix.mul(vec4(direction.x, direction.y, direction.z, 0)),
593
+ );
594
+ const far = screen(away);
595
+ // A direction off the side of the frame reads its edge column (sky, the tree line) and fades out
596
+ // half a frame further; only the top and bottom take Unreal's vignette, so no seam crosses the water.
597
+ const farUv = vec2(clamp(far.uv.x, float(0.001), float(0.999)), far.uv.y);
598
+ const farMetres = sceneMetres(farUv);
599
+ const farWeight = step(float(0.02), away.w)
600
+ .mul(step(far.ndc.y.abs(), float(1)))
601
+ .mul(float(1).sub(smoothstep(float(1), float(1.5), far.ndc.x.abs())))
602
+ .mul(step(float(reached), farMetres))
603
+ .mul(vignette(vec2(0, far.ndc.y)));
604
+ // The haze is a post pass over the frame's depth, so a far read comes back clear and the water's
605
+ // own depth hazes it by the eye's leg only. The reflected leg is put back here, in the sky's
606
+ // horizon colour; the sky itself (depth at the far plane) takes none.
607
+ const hazed = float(1)
608
+ .sub(exp(farMetres.sub(HAZE_CLEAR).max(0).div(-HAZE_METRES)))
609
+ .mul(step(farMetres, cameraFar.mul(0.999)));
610
+ const distant = mix(
611
+ fallback,
612
+ mix(
613
+ viewportSharedTexture(farUv).rgb as unknown as Node<"vec3">,
614
+ color(TINT.skyHorizon).mul(SKY_GAIN),
615
+ hazed,
616
+ ),
617
+ farWeight,
618
+ );
619
+ return mix(
620
+ distant,
621
+ viewportSharedTexture(hitUv).rgb as unknown as Node<"vec3">,
622
+ found.mul(vignette(hitNdc)),
623
+ );
624
+ }
625
+
626
+ /**
627
+ * The stream's surface height along the path: a fill over the bed, never running uphill.
628
+ *
629
+ * The fill tapers to nothing at both ends of the recorded path. A stream's ends are where it comes
630
+ * out of the hillside and where it goes into standing water, and a ribbon that stops at full depth
631
+ * ends in a wall of water a metre high: the bake's last station sits two metres above the lake it
632
+ * drains into, and the flat cap across the channel that leaves is the hard straight edge the bank
633
+ * appears to be cut by. Tapered, the surface meets the ground it is over and the end dissolves.
634
+ */
635
+ export function surfaceHeights(
636
+ field: Heightfield,
637
+ points: readonly (readonly number[])[],
638
+ ): number[] {
639
+ const last = points.length - 1;
640
+ const raw = points.map(([x = 0, , z = 0], k) => {
641
+ const fromEnd = Math.min(k, last - k) / RIVER.taper;
642
+ return field.heightAt(x, z) + RIVER.fill * Math.max(0, Math.min(1, fromEnd));
643
+ });
644
+ // Downhill only, then a short moving average, then downhill again: the bed has erosion noise in
645
+ // it and a surface that copies that noise steps up and down like a staircase.
646
+ for (let k = 1; k < raw.length; k += 1) raw[k] = Math.min(raw[k] as number, raw[k - 1] as number);
647
+ const smooth = raw.map((_, k) => {
648
+ let sum = 0;
649
+ let n = 0;
650
+ for (let j = Math.max(0, k - 3); j <= Math.min(raw.length - 1, k + 3); j += 1) {
651
+ sum += raw[j] as number;
652
+ n += 1;
653
+ }
654
+ return sum / n;
655
+ });
656
+ for (let k = 1; k < smooth.length; k += 1)
657
+ smooth[k] = Math.min(smooth[k] as number, smooth[k - 1] as number);
658
+ return smooth;
659
+ }
660
+
661
+ /**
662
+ * A ribbon along one river: positions, the downstream heading at every vertex, and the metres of
663
+ * water standing on it.
664
+ *
665
+ * The baked depth is the point. Taken off the ground under each vertex rather than read off the
666
+ * screen, it puts the shoreline where the ground crosses the surface, the foam where the water is
667
+ * thin, and the margin's dissolve over its last thirty centimetres — which is what a screen-space
668
+ * thickness cannot do on a hillside crossing a flat plane, and reads as the bank cutting the ribbon
669
+ * like a blade.
670
+ */
671
+
672
+ /**
673
+ * Draw every baked river as one surface, or nothing when the world has none.
674
+ *
675
+ * A river stands on its bed's measured footprint: the baked spline's own heights across 2.5 widths,
676
+ * which is where the player swims and where the bake's own shore is.
677
+ */
678
+ export function createRivers(
679
+ rivers: readonly IBakedRiver[],
680
+ field: Heightfield,
681
+ lakeReflection?: (offset: Node<"vec2">) => Node<"vec3">,
682
+ ): IRiverWater | undefined {
683
+ if (rivers.length === 0) return undefined;
684
+ const geometry = riverRibbonGeometry(rivers, field, {
685
+ columns: RIVER.across,
686
+ maxDepth: MAX_BAKED_DEPTH,
687
+ });
688
+
689
+ const surface = new WaterSurface3D({ level: 0, maxThickness: MAX_BAKED_DEPTH * 2 });
690
+ const time = uniform(0);
691
+ const depthM = attribute<"float">("metres", "float");
692
+ const heading = normalize(attribute<"vec2">("flow", "vec2"));
693
+ const here = vec2(positionWorld.x, positionWorld.z);
694
+ // Metres down the centreline and metres across it, baked per vertex. These were once
695
+ // `dot(world xz, heading)`: 180 m from the origin, a 3 degree turn between two stations moved
696
+ // that frame by 9 m, so one metre of water read 3-6 m of noise and the ripples fanned out from
697
+ // the bends in radial streaks (stations 50-70 measured d(side)/ds = -1.4 to -5.9).
698
+ const flowUv = attribute<"vec2">("flowUv", "vec2");
699
+ const along = flowUv.x;
700
+ const side = flowUv.y;
701
+ // The long axis of the ellipse one pixel covers on the water, in metres. At a grazing angle it is
702
+ // metres long even near the eye, and a ripple finer than that aliases into streaks: each scale
703
+ // fades out between a pixel covering an eighth and nearly half of it, as a mip chain would.
704
+ const footprint = max(dFdx(flowUv).length(), dFdy(flowUv).length());
705
+ const octaves = RIVER.ripples.map((wave) => ({
706
+ ...wave,
707
+ weight: float(1).sub(
708
+ smoothstep(float(wave.metres * 0.12), float(wave.metres * 0.45), footprint),
709
+ ),
710
+ }));
711
+
712
+ // Ripples are noise drawn longer along the current and slid downstream at the river's own flow
713
+ // speed, the same `RIVER_FLOW_MPS` the player is carried at, so the water they see moves with the
714
+ // water that moves them. The height sums them in metres, and the normal is its gradient by finite
715
+ // difference in the current's own frame, rotated back into the world's by the baked heading.
716
+ const height = (a: Node<"float">, b: Node<"float">): Node<"float"> => {
717
+ let sum: Node<"float"> = float(0);
718
+ for (const wave of octaves) {
719
+ const length = wave.metres * wave.stretch;
720
+ const octave = mx_noise_float(
721
+ vec3(
722
+ a.sub(time.mul(RIVER_FLOW_MPS * wave.flow)).div(length),
723
+ b.div(wave.metres),
724
+ time.mul(0.11),
725
+ ),
726
+ );
727
+ sum = sum.add(octave.mul(wave.weight.mul(wave.slope * wave.metres)));
728
+ }
729
+ return sum;
730
+ };
731
+ const h0 = height(along, side);
732
+ const delta = 0.03;
733
+ const dAlong = height(along.add(delta), side).sub(h0).div(delta);
734
+ const dSide = height(along, side.add(delta)).sub(h0).div(delta);
735
+ const patch = windPatch(here, time, RIVER.patch.metres, RIVER.patch.drift, RIVER.patch.wind);
736
+ const gain = mix(float(PATCH_CALM), float(1), patch).mul(
737
+ smoothstep(float(0), float(RIPPLE_DEPTH), depthM),
738
+ );
739
+ const alongSlope = dAlong.mul(gain).negate();
740
+ const sideSlope = dSide.mul(gain).negate();
741
+ const normal = normalize(
742
+ vec3(
743
+ heading.x.mul(alongSlope).sub(heading.y.mul(sideSlope)),
744
+ float(1),
745
+ heading.y.mul(alongSlope).add(heading.x.mul(sideSlope)),
746
+ ),
747
+ );
748
+
749
+ // The normal's horizontal part is the screen offset, in fractions of the frame. Grazing fragments
750
+ // slide further, because that is what a longer path through a tilted surface does — and the offset
751
+ // is taken to zero at the margin, or the dry bank smears out across the water in front of it.
752
+ const view = normalize(cameraPosition.sub(positionWorld));
753
+ const facing = clamp(dot(normal, view), float(0), float(1));
754
+ const slide = mix(float(REFRACTION_NEAR), float(REFRACTION_FAR), float(1).sub(facing));
755
+ const offset = vec2(normal.x, normal.z)
756
+ .mul(slide)
757
+ .mul(smoothstep(float(0), float(0.4), depthM));
758
+ const bed = surface.refractionAt(offset);
759
+
760
+ // The stream falls along its length, so no one planar mirror fits it: the banks and the sky come
761
+ // back by a reflected-ray march over the frame, with an analytic sky on a floor of the wood that
762
+ // stands on both banks (`TINT.bank`) wherever the ray leaves the screen.
763
+ const bounced = view.negate().reflect(normal);
764
+ const sky = mix(
765
+ linear(TINT.bank, TINT.bankGain * SKY_GAIN),
766
+ skyAlong(bounced),
767
+ // A low reflected ray hits the wooded bank. Blend its average green radiance into sky
768
+ // over a broad angle; a hard dark cutoff makes moving facets flicker as black blobs.
769
+ smoothstep(float(0.08), float(0.5), bounced.y),
770
+ );
771
+ const reflected = traceReflection(bounced, lakeReflection ? lakeReflection(offset) : sky);
772
+ // The slope the faded scales would have drawn, as GGX roughness (alpha = sqrt(2) sigma).
773
+ const unresolved = octaves.reduce<Node<"float">>(
774
+ (sum, wave) =>
775
+ sum.add(
776
+ float(1)
777
+ .sub(wave.weight)
778
+ .mul(2 * wave.slope * wave.slope),
779
+ ),
780
+ float(ROUGHNESS_NEAR * ROUGHNESS_NEAR),
781
+ );
782
+ const shaded = compositeWater({
783
+ normal,
784
+ depthM,
785
+ bed,
786
+ reflected,
787
+ roughness: unresolved.sqrt(),
788
+ // A channel between kettle ponds takes the ponds' own water, so the two meet without a seam.
789
+ body: lakeReflection ? LAKE_BODY : STREAM_BODY,
790
+ });
791
+
792
+ // White water where the current runs over a shallow bed, and a few streaks in the channel. Broken
793
+ // rather than ruled: the shallows only whiten where the churn is high, so the edge reads as water
794
+ // catching on the gravel in patches rather than a white line painted along the bank.
795
+ const churn = mx_noise_float(
796
+ vec3(along.mul(1.3).sub(time.mul(2.2)), side.mul(1.9), time.mul(0.5)),
797
+ )
798
+ .mul(0.5)
799
+ .add(0.5);
800
+ const shallows = float(1).sub(smoothstep(float(0.03), float(0.18).add(churn.mul(0.24)), depthM));
801
+ const bank = shallows.mul(smoothstep(float(0.65), float(0.9), churn)).mul(0.12);
802
+ // The height as a share of its peak, so the streak threshold reads on the same -1..1 as the noise.
803
+ const peak = RIVER.ripples.reduce((sum, wave) => sum + wave.slope * wave.metres, 0);
804
+ const streak = smoothstep(float(0.78), float(0.92), h0.div(peak).mul(0.5).add(0.5)).mul(0.035);
805
+ const foam = max(bank, streak.mul(smoothstep(float(0), float(OPAQUE_DEPTH), depthM)));
806
+
807
+ const material = new MeshBasicNodeMaterial({
808
+ transparent: true,
809
+ depthWrite: false,
810
+ });
811
+ // The composite already contains lit refraction, reflected sky and one sun glint, as on the lake.
812
+ material.colorNode = mix(shaded, linear(TINT.foam, 0.65), foam);
813
+ // The last hand's depth of water dissolves into the gravel instead of the bank cutting the surface
814
+ // like a blade.
815
+ material.opacityNode = shoreFade(depthM);
816
+
817
+ const mesh = new Mesh(geometry, material);
818
+ mesh.layers.set(WATER_LAYER);
819
+ mesh.name = "river-surface";
820
+ mesh.receiveShadow = true;
821
+ return {
822
+ mesh,
823
+ advance(elapsed) {
824
+ time.value = elapsed;
825
+ },
826
+ dispose() {
827
+ surface.dispose();
828
+ geometry.dispose();
829
+ material.dispose();
830
+ },
831
+ };
832
+ }
833
+
834
+ /** One lake as the bake records it: where its flood fill was seeded, how far it may reach, its level. */
835
+ export interface IBakedLake {
836
+ readonly id: string;
837
+ readonly at: readonly number[];
838
+ readonly radius: number;
839
+ readonly level: number;
840
+ }
841
+
842
+ /**
843
+ * Draw the baked lake as one surface: Wildwood's water, over this basin's own depth.
844
+ *
845
+ * The mesh is a disc whose rings pack towards the middle, because this basin is not round: it is a
846
+ * compact bowl with one flooded arm running east a hundred metres, and a square grid big enough to
847
+ * hold the arm would spend four hundred thousand vertices on dry hillside. Only cells with water in
848
+ * at least one corner get triangles — that is what keeps the surface from showing as a sheet hovering
849
+ * over the meadow, and what leaves the shoreline on the ground's own contour.
850
+ *
851
+ * A lake stands inside its own footprint too: the waterline the bake measured, capped at the radius
852
+ * the biome file names.
853
+ */
854
+ export function createLakes(
855
+ lakes: readonly IBakedLake[],
856
+ field: Heightfield,
857
+ ): IRiverWater | undefined {
858
+ const lake = lakes[0];
859
+ if (lake === undefined) return undefined;
860
+ if (lakes.length > 1) {
861
+ const ponds = lakes.map((one) => createLakes([one], field)).filter((one) => one !== undefined);
862
+ if (ponds.length === 0) return undefined;
863
+ const geometry = mergeGeometries(
864
+ ponds.map((one) => one.mesh.geometry),
865
+ true,
866
+ );
867
+ if (!geometry) {
868
+ for (const pond of ponds) pond.dispose();
869
+ throw new Error("Lake geometries have incompatible attributes");
870
+ }
871
+ const mesh = new Mesh(
872
+ geometry,
873
+ ponds.flatMap((one) => one.mesh.material),
874
+ );
875
+ const mirrors = ponds.map((pond) => {
876
+ if (!pond.reflectionAt) throw new Error("A kettle pond has no mirror sampler");
877
+ return {
878
+ sample: pond.reflectionAt,
879
+ level: pond.mesh.geometry.getAttribute("position").getY(0),
880
+ };
881
+ });
882
+ mesh.layers.set(WATER_LAYER);
883
+ mesh.name = "lake-surfaces";
884
+ mesh.renderOrder = 2;
885
+ return {
886
+ mesh,
887
+ reflectionAt(offset) {
888
+ const weighted = mirrors.map((mirror) => ({
889
+ ...mirror,
890
+ weight: float(1).div(positionWorld.y.sub(mirror.level).abs().add(0.1)),
891
+ }));
892
+ const total = weighted.reduce<Node<"float">>(
893
+ (sum, mirror) => sum.add(mirror.weight),
894
+ float(0),
895
+ );
896
+ return weighted.reduce<Node<"vec3">>(
897
+ (sum, mirror) => sum.add(mirror.sample(offset).mul(mirror.weight.div(total))),
898
+ vec3(0),
899
+ );
900
+ },
901
+ advance(elapsed) {
902
+ for (const pond of ponds) pond.advance(elapsed);
903
+ },
904
+ dispose() {
905
+ geometry.dispose();
906
+ for (const pond of ponds) pond.dispose();
907
+ },
908
+ };
909
+ }
910
+ const [cx = 0, cz = 0] = lake.at;
911
+ const footprint = { ...lake, margin: LAKE.reach };
912
+ // The material fades the rim out at the same reach the geometry stops at.
913
+ const reach = lakeReach(field, footprint);
914
+ const geometry = lakeSurfaceGeometry(footprint, field, {
915
+ maxDepth: MAX_BAKED_DEPTH,
916
+ packing: LAKE.packing,
917
+ rings: LAKE.rings,
918
+ spokes: LAKE.spokes,
919
+ });
920
+ if (geometry === undefined) return undefined;
921
+ // The ripple's share of the depth, this game's look: full past OPAQUE_DEPTH, none on the shore.
922
+ const metres = geometry.getAttribute("metres");
923
+ const waveDepths = new Float32Array(metres.count);
924
+ for (let index = 0; index < metres.count; index += 1)
925
+ waveDepths[index] = Math.min(1, metres.getX(index) / OPAQUE_DEPTH);
926
+ geometry.setAttribute("waveDepth", new BufferAttribute(waveDepths, 1));
927
+
928
+ const surface = new WaterSurface3D({
929
+ level: lake.level,
930
+ maxThickness: MAX_BAKED_DEPTH * 2,
931
+ // Everything but water: the camera sees layer 0 and WATER_LAYER, the mirror only layer 0.
932
+ reflection: { ...LAKE.mirror },
933
+ });
934
+ const time = uniform(0);
935
+ const waveDepth = attribute<"float">("waveDepth", "float");
936
+ const depthM = attribute<"float">("metres", "float");
937
+ const here = vec2(positionWorld.x, positionWorld.z);
938
+ const eyeDistance = here.sub(vec2(cameraPosition.x, cameraPosition.z)).length();
939
+
940
+ const patch = windPatch(here, time, PATCH_METRES, PATCH_DRIFT, [0.62, -0.78]);
941
+ // One evaluation of the field per fragment: no texture, no stripe term, no screen-space anything.
942
+ // The short waves are gated by both distance and the wind patch, and the whole horizontal part is
943
+ // graded by distance, because a far pixel covers many ripples and shows their average.
944
+ const detailFade = float(1)
945
+ .sub(smoothstep(float(DETAIL_NEAR), float(DETAIL_FAR), eyeDistance))
946
+ .mul(patch);
947
+ const raw = RIPPLE.normalNode({ fade: detailFade, point: here, time });
948
+ const gain = slopeGain(eyeDistance, patch, depthM);
949
+ const normal = normalize(vec3(raw.x.mul(gain), raw.y, raw.z.mul(gain)));
950
+ // The same surface read with less of its slope, for the mirror alone; the glint and the caustics
951
+ // keep the sharp one.
952
+ const reflectGain = gain.mul(REFLECT_SLOPE_SHARE);
953
+ const reflectNormal = normalize(vec3(raw.x.mul(reflectGain), raw.y, raw.z.mul(reflectGain)));
954
+
955
+ // Vertices ride the four long waves only. The short ones are shorter than this grid's rings, so
956
+ // displacing by them would alias into a stair pattern the normal above already draws for free.
957
+ const material = new MeshBasicNodeMaterial({
958
+ // Writing depth, which for a transparent surface wants a reason: the passes that read depth and
959
+ // normals under every water pixel would otherwise find the lake bed at a grazing angle, where its
960
+ // triangle rows are a few pixels apart and its depth derivative is enormous.
961
+ depthWrite: true,
962
+ // Both sides: the basin is shallow but the walker wades in, so the camera goes under this
963
+ // surface and has to find something drawn there. See the Snell's window branch below.
964
+ side: DoubleSide,
965
+ transparent: true,
966
+ // One draw for both sides: the camera is on one side of a near-flat sheet at a time. three's
967
+ // default draws a transparent double-sided material twice, flipping `side` between the draws,
968
+ // and on the streamed ground that flip rebuilt this pipeline 58 times in one turn (PRD-790).
969
+ forceSinglePass: true,
970
+ });
971
+ material.positionNode = vec3(
972
+ positionLocal.x,
973
+ positionLocal.y.add(RIPPLE.heightNode({ fade: float(0), time }).mul(waveDepth)),
974
+ positionLocal.z,
975
+ );
976
+
977
+ const view = normalize(cameraPosition.sub(positionWorld));
978
+ const facing = clamp(dot(normal, view), float(0), float(1));
979
+ const slide = mix(float(REFRACTION_NEAR), float(REFRACTION_FAR), float(1).sub(facing));
980
+ const offset = vec2(normal.x, normal.z)
981
+ .mul(slide)
982
+ .mul(smoothstep(float(0), float(0.4), depthM));
983
+ const bed = surface.refractionAt(offset);
984
+ // A vertical smear, because that is the shape a rippled reflection has: the surface tilts about a
985
+ // horizontal axis far more often than it tilts toward you, so the smear is taller than it is wide
986
+ // and it grows with distance. Five taps on that ellipse; the radius shrinks where the lake is
987
+ // glass, so a calm patch takes the bank sharp and a ruffled one dissolves it.
988
+ const blur = mix(
989
+ float(REFLECT_BLUR_NEAR),
990
+ float(REFLECT_BLUR_FAR),
991
+ smoothstep(float(8), float(60), eyeDistance),
992
+ ).mul(mix(float(0.25), float(1), patch));
993
+ const tap = (dx: number, dy: number): Node<"vec3"> =>
994
+ surface.reflectionAt(
995
+ vec2(
996
+ offset.x.add(blur.mul(float(dx * REFLECT_BLUR_ASPECT))),
997
+ offset.y.add(blur.mul(float(dy))),
998
+ ),
999
+ ) as unknown as Node<"vec3">;
1000
+ const mirror = tap(0, 0)
1001
+ .mul(0.36)
1002
+ .add(tap(0, 1).mul(0.16))
1003
+ .add(tap(0, -1).mul(0.16))
1004
+ .add(tap(1.3, 0.5).mul(0.16))
1005
+ .add(tap(-1.3, -0.5).mul(0.16)) as Node<"vec3">;
1006
+ // The mirror draws the ground only, and nothing where the sky is. The spruces on the far bank and
1007
+ // the sky come from the frame; a steep ray that leaves the screen finds the analytic sky, a low
1008
+ // one the mirrored ground.
1009
+ const bounced = normalize(cameraPosition.sub(positionWorld)).negate().reflect(reflectNormal);
1010
+ const reflected = traceReflection(
1011
+ bounced,
1012
+ mix(mirror, skyAlong(bounced), smoothstep(float(0.12), float(0.4), bounced.y)),
1013
+ );
1014
+ const shaded = compositeWater({
1015
+ normal,
1016
+ depthM,
1017
+ bed,
1018
+ reflected,
1019
+ roughness: mix(
1020
+ float(ROUGHNESS_NEAR),
1021
+ float(ROUGHNESS_FAR),
1022
+ smoothstep(float(DETAIL_NEAR), float(SLOPE_FADE_FAR * 2), eyeDistance),
1023
+ ).mul(mix(float(0.7), float(1), patch)),
1024
+ });
1025
+
1026
+ // ---- and what the surface is from underneath ----------------------------------------------
1027
+ //
1028
+ // Nothing about the composite above survives being looked at from below: the fresnel is measured
1029
+ // against a ray leaving the water, the refraction reads a bed that is behind the camera, and the
1030
+ // mirror aims at a bank the ray cannot reach. Seen from under, the surface is two things either
1031
+ // side of the critical angle: look up steeply and the whole sky refracts into a 97° cone, which is
1032
+ // the only thing down here that is not dark; look up shallowly and it is a *total* mirror of the
1033
+ // bed below. The ripple moves the boundary, which is why a real window has a ragged edge.
1034
+ //
1035
+ // This is the wading case, and the wading case is the one that matters: across the whole wadeable
1036
+ // margin the eye sits under the surface with the bed a metre or two beneath it, so the view the
1037
+ // player actually gets is a surface an arm's length overhead mirroring a bed they can almost touch —
1038
+ // and a constant colour cannot be that however well the constant is chosen. It photographs as a
1039
+ // flat slab with a razor edge against the bed.
1040
+ const upward = normalize(positionWorld.sub(cameraPosition));
1041
+ const throughSurface = clamp(dot(upward, normal), float(0), float(1));
1042
+ const window = smoothstep(float(SNELL_INNER), float(SNELL_OUTER), throughSurface);
1043
+ // The mirrored bed, aimed down at a plane rather than out at a ring. The plane is not estimated:
1044
+ // `depthM` is baked off the same `heightAt` the collider walks on, so the intersection is one divide.
1045
+ const mirrored = upward.reflect(normal);
1046
+ const dive = max(mirrored.y.negate(), float(0.06));
1047
+ const toBed = min(depthM.div(dive), float(90));
1048
+ const bedHit = positionWorld.add(mirrored.mul(toBed));
1049
+ const bedClip = cameraProjectionMatrix.mul(
1050
+ cameraViewMatrix.mul(vec4(bedHit.x, bedHit.y, bedHit.z, 1)),
1051
+ );
1052
+ const bedNdc = bedClip.xy.div(max(bedClip.w, float(0.0001)));
1053
+ // Clip space puts +1 at the top of the frame and `viewportSharedTexture` samples with 0 there, so
1054
+ // the y is negated: written the obvious way every mirrored read comes back about the middle of the
1055
+ // screen, which for a ceiling means it reads the sky instead of the bed.
1056
+ const bedUv = vec2(bedNdc.x.mul(0.5).add(0.5), bedNdc.y.mul(-0.5).add(0.5));
1057
+ const bedInFrame = smoothstep(float(0), float(0.02), bedUv.x)
1058
+ .mul(smoothstep(float(1), float(0.98), bedUv.x))
1059
+ .mul(smoothstep(float(0), float(0.02), bedUv.y))
1060
+ .mul(smoothstep(float(1), float(0.98), bedUv.y))
1061
+ .mul(step(float(0.001), bedClip.w));
1062
+ const underTap = (dx: number, dy: number): Node<"vec3"> =>
1063
+ viewportSharedTexture(
1064
+ vec2(
1065
+ clamp(bedUv.x.add(float(dx * UNDER_BLUR)), float(0.002), float(0.998)),
1066
+ clamp(bedUv.y.add(float(dy * UNDER_BLUR)), float(0.002), float(0.998)),
1067
+ ),
1068
+ ).rgb as unknown as Node<"vec3">;
1069
+ const mirroredBed = underTap(0, 0)
1070
+ .mul(0.5)
1071
+ .add(underTap(0.9, 0.5).mul(0.25))
1072
+ .add(underTap(-0.9, -0.5).mul(0.25)) as Node<"vec3">;
1073
+ // Both legs of that path are under water, so Beer-Lambert applies to the whole of it: down to the
1074
+ // bed and back to the eye. This is what turns the ceiling from a slab into something with depth in
1075
+ // it — bright where the water is thin, the water's own colour by the far side of the frame.
1076
+ const underPath = min(toBed.add(positionWorld.sub(cameraPosition).length()), float(40));
1077
+ const underTint = exp(vec3(-EXTINCTION[0], -EXTINCTION[1], -EXTINCTION[2]).mul(underPath));
1078
+ const ceiling = linear(TINT.deep, 0.35)
1079
+ .add(linear(TINT.silt, 0.22))
1080
+ .mul(mix(float(0.5), float(1.4), throughSurface));
1081
+ const mirrorBelow = mirroredBed
1082
+ .mul(bedInFrame)
1083
+ .mul(underTint)
1084
+ .add(ceiling.mul(float(1).sub(underTint.mul(bedInFrame))));
1085
+ // The sky as it arrives after a metre or two of water: the horizon band, drained of red the way
1086
+ // everything under water is.
1087
+ const skyThrough = mix(
1088
+ color(TINT.skyHorizon),
1089
+ color(TINT.skyZenith),
1090
+ clamp(upward.y, float(0), float(1)),
1091
+ )
1092
+ .mul(vec3(0.55, 0.92, 1))
1093
+ .mul(1.35);
1094
+ const sunDisc = pow(clamp(dot(upward, SUN_VECTOR), float(0), float(1)), 90)
1095
+ .mul(window)
1096
+ .mul(2.2);
1097
+ const below = mix(mirrorBelow, skyThrough, window).add(linear(SUN.colour, 0.65).mul(sunDisc));
1098
+
1099
+ // Which of the two the camera is looking at, on its own height. Uniform across the draw, so both
1100
+ // sides costing a multiply is the whole price of not writing two materials. A ten-centimetre blend
1101
+ // rather than a step, because the walker crosses this line on foot and a hard flip is a one-frame
1102
+ // pop in the middle of walking into a lake.
1103
+ const eyeIsAbove = smoothstep(
1104
+ float(lake.level - 0.05),
1105
+ float(lake.level + 0.05),
1106
+ cameraPosition.y,
1107
+ );
1108
+ material.colorNode = mix(below, shaded, eyeIsAbove);
1109
+ // From underneath there is no shore to dissolve into and the ceiling is opaque.
1110
+ const opacity = mix(float(1), shoreFade(depthM), eyeIsAbove);
1111
+ // The surface fades out at the footprint it was drawn to, so its rim is not a cut edge.
1112
+ const edge = positionWorld.xz.sub(vec2(cx, cz)).length();
1113
+ material.opacityNode = opacity.mul(float(1).sub(smoothstep(reach * 0.82, reach, edge)));
1114
+
1115
+ const mesh = new Mesh(geometry, material);
1116
+ mesh.layers.set(WATER_LAYER);
1117
+ mesh.name = "lake-surface";
1118
+ // Drawn after the opaque valley, and after the scatter, so the shore blends over both.
1119
+ mesh.renderOrder = 2;
1120
+ return {
1121
+ mesh,
1122
+ reflectionAt: (offset) => surface.reflectionAt(offset) as unknown as Node<"vec3">,
1123
+ advance(elapsed) {
1124
+ time.value = elapsed;
1125
+ },
1126
+ dispose() {
1127
+ surface.dispose();
1128
+ geometry.dispose();
1129
+ material.dispose();
1130
+ },
1131
+ };
1132
+ }