@threenative/terrain 0.1.9 → 0.1.12

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 (243) hide show
  1. package/README.md +40 -59
  2. package/THIRD_PARTY_NOTICES.md +2 -1
  3. package/dist/bake-DJ5cxg0C.d.ts +82 -0
  4. package/dist/editor/index.d.ts +4 -4
  5. package/dist/editor/index.js +130 -128
  6. package/dist/editor/server.d.ts +2 -2
  7. package/dist/editor/server.js +38 -35
  8. package/dist/editor/worker.d.ts +1 -1
  9. package/dist/editor/worker.js +101 -101
  10. package/dist/export.d.ts +1 -1
  11. package/dist/index.d.ts +156 -273
  12. package/dist/index.js +562 -378
  13. package/dist/kit-world.d.ts +107 -0
  14. package/dist/kit-world.js +5134 -0
  15. package/dist/kit.d.ts +21 -4
  16. package/dist/kit.js +337 -223
  17. package/dist/mcp/cook-child.js +1963 -1543
  18. package/dist/mcp/server.js +716 -429
  19. package/dist/prop-package-Dwz0EWoB.d.ts +141 -0
  20. package/dist/{server-B5RdvEAC.d.ts → server-LnFwY8sr.d.ts} +1 -1
  21. package/dist/starter.d.ts +1142 -7
  22. package/dist/starter.js +2102 -120
  23. package/dist/{terrain-CAEaW0mQ.d.ts → terrain-DYCyAOCJ.d.ts} +1 -1
  24. package/dist/three.d.ts +1 -1
  25. package/dist/three.js +1 -1
  26. package/dist/{types-BpH00qsx.d.ts → types-kpI0C4hW.d.ts} +1 -1
  27. package/dist/{world-package-B8QgHjAQ.d.ts → world-package-DqJC3-Nn.d.ts} +2 -2
  28. package/docs/authoring/editor.md +73 -0
  29. package/docs/authoring/new-environment.md +97 -0
  30. package/docs/authoring/recipes.md +97 -0
  31. package/docs/authoring/world-export.md +66 -0
  32. package/package.json +24 -8
  33. package/starter/alpine/README.md +22 -12
  34. package/starter/alpine/bake.mjs +14 -1
  35. package/starter/alpine/biome.data.json +187 -25
  36. package/starter/alpine/heightmap.r16 +0 -0
  37. package/starter/alpine/playerRig.ts +89 -0
  38. package/starter/alpine/recipe.json +169 -15
  39. package/starter/alpine/render/bakedFile.ts +17 -0
  40. package/starter/alpine/render/benchmark.ts +77 -0
  41. package/starter/alpine/render/biomeData.ts +14 -0
  42. package/starter/alpine/render/biomes.ts +687 -0
  43. package/starter/alpine/render/ground/cover.ts +565 -0
  44. package/starter/alpine/render/ground/horizon.ts +219 -0
  45. package/starter/alpine/render/ground/palette.d.ts +1 -0
  46. package/starter/alpine/render/ground/palette.js +11 -0
  47. package/starter/alpine/render/ground/scatter.ts +104 -0
  48. package/starter/alpine/render/ground/terrain.ts +1860 -0
  49. package/starter/alpine/render/kitAssets.ts +28 -0
  50. package/starter/alpine/render/loading.ts +354 -0
  51. package/starter/alpine/render/lookKnobs.ts +37 -0
  52. package/starter/alpine/render/orbitCamera.ts +155 -0
  53. package/starter/alpine/render/props/farForest.ts +94 -0
  54. package/starter/alpine/render/props/pack.ts +1114 -0
  55. package/starter/alpine/render/props/prepared.ts +225 -0
  56. package/starter/alpine/render/props/propMaterials.ts +1239 -0
  57. package/starter/alpine/render/props/propProgress.ts +2 -0
  58. package/starter/alpine/render/props/propWorld.ts +105 -0
  59. package/starter/alpine/render/props/props.ts +633 -0
  60. package/starter/alpine/render/props/spruce.ts +440 -0
  61. package/starter/alpine/render/sky/atmosphere.ts +329 -0
  62. package/starter/alpine/render/sky/sky.ts +382 -0
  63. package/starter/alpine/render/texturePreparation.ts +135 -0
  64. package/starter/alpine/render/water/river.ts +1132 -0
  65. package/starter/alpine/render/worldNames.ts +6 -0
  66. package/starter/alpine/scene.ts +715 -0
  67. package/starter/alpine/sceneProps.ts +561 -0
  68. package/starter/alpine/sceneState.ts +33 -0
  69. package/starter/alpine/world/terrainAssets.ts +145 -0
  70. package/starter/alpine/world/walkBand.ts +47 -0
  71. package/starter/alpine/world/water.ts +74 -0
  72. package/starter/alpine/worlds.ts +13 -0
  73. package/starter/arbor/wind.ts +84 -0
  74. package/starter/coastal/README.md +26 -25
  75. package/starter/coastal/assets.json +10 -0
  76. package/starter/coastal/bake.mjs +14 -1
  77. package/starter/coastal/biome.data.json +18 -3
  78. package/starter/coastal/playerRig.ts +89 -0
  79. package/starter/coastal/recipe.json +220 -18
  80. package/starter/coastal/render/bakedFile.ts +17 -0
  81. package/starter/coastal/render/benchmark.ts +81 -0
  82. package/starter/coastal/render/biomeData.ts +14 -0
  83. package/starter/coastal/render/biomes.ts +678 -0
  84. package/starter/coastal/render/ground/cover.ts +565 -0
  85. package/starter/coastal/render/ground/horizon.ts +219 -0
  86. package/starter/coastal/render/ground/palette.d.ts +1 -0
  87. package/starter/coastal/render/ground/palette.js +11 -0
  88. package/starter/coastal/render/ground/scatter.ts +104 -0
  89. package/starter/coastal/render/ground/terrain.ts +1829 -0
  90. package/starter/coastal/render/kitAssets.ts +28 -0
  91. package/starter/coastal/render/loading.ts +354 -0
  92. package/starter/coastal/render/lookKnobs.ts +37 -0
  93. package/starter/coastal/render/orbitCamera.ts +155 -0
  94. package/starter/coastal/render/props/farForest.ts +94 -0
  95. package/starter/coastal/render/props/pack.ts +1109 -0
  96. package/starter/coastal/render/props/prepared.ts +225 -0
  97. package/starter/coastal/render/props/propMaterials.ts +1239 -0
  98. package/starter/coastal/render/props/propProgress.ts +2 -0
  99. package/starter/coastal/render/props/propWorld.ts +105 -0
  100. package/starter/coastal/render/props/props.ts +633 -0
  101. package/starter/coastal/render/props/spruce.ts +440 -0
  102. package/starter/coastal/render/sky/atmosphere.ts +329 -0
  103. package/starter/coastal/render/sky/sky.ts +382 -0
  104. package/starter/coastal/render/texturePreparation.ts +135 -0
  105. package/starter/coastal/render/water/ocean.ts +284 -0
  106. package/starter/coastal/render/water/river.ts +1132 -0
  107. package/starter/coastal/render/worldNames.ts +6 -0
  108. package/starter/coastal/scene.ts +740 -0
  109. package/starter/coastal/sceneProps.ts +559 -0
  110. package/starter/coastal/sceneState.ts +33 -0
  111. package/starter/coastal/world/terrainAssets.ts +151 -0
  112. package/starter/coastal/world/walkBand.ts +47 -0
  113. package/starter/coastal/world/water.ts +74 -0
  114. package/starter/coastal/worlds.ts +13 -0
  115. package/starter/desert/README.md +51 -23
  116. package/starter/desert/bake-flora.mjs +142 -0
  117. package/starter/desert/bake-rocks.mjs +291 -0
  118. package/starter/desert/bake.mjs +14 -1
  119. package/starter/desert/biome.data.json +24 -12
  120. package/starter/desert/playerRig.ts +89 -0
  121. package/starter/desert/recipe.json +63 -16
  122. package/starter/desert/render/bakedFile.ts +17 -0
  123. package/starter/desert/render/benchmark.ts +79 -0
  124. package/starter/desert/render/biomeData.ts +14 -0
  125. package/starter/desert/render/biomes.ts +660 -0
  126. package/starter/desert/render/ground/cover.ts +565 -0
  127. package/starter/desert/render/ground/debris.ts +136 -0
  128. package/starter/desert/render/ground/horizon.ts +219 -0
  129. package/starter/desert/render/ground/palette.d.ts +1 -0
  130. package/starter/desert/render/ground/palette.js +11 -0
  131. package/starter/desert/render/ground/scatter.ts +104 -0
  132. package/starter/desert/render/ground/terrain.ts +1854 -0
  133. package/starter/desert/render/kitAssets.ts +28 -0
  134. package/starter/desert/render/loading.ts +354 -0
  135. package/starter/desert/render/lookKnobs.ts +37 -0
  136. package/starter/desert/render/orbitCamera.ts +155 -0
  137. package/starter/desert/render/props/farForest.ts +96 -0
  138. package/starter/desert/render/props/formations.ts +630 -0
  139. package/starter/desert/render/props/pack.ts +1195 -0
  140. package/starter/desert/render/props/prepared.ts +225 -0
  141. package/starter/desert/render/props/propMaterials.ts +1255 -0
  142. package/starter/desert/render/props/propProgress.ts +2 -0
  143. package/starter/desert/render/props/propWorld.ts +105 -0
  144. package/starter/desert/render/props/props.ts +624 -0
  145. package/starter/desert/render/props/spruce.ts +440 -0
  146. package/starter/desert/render/sand.ts +581 -0
  147. package/starter/desert/render/sky/atmosphere.ts +329 -0
  148. package/starter/desert/render/sky/sky.ts +382 -0
  149. package/starter/desert/render/texturePreparation.ts +135 -0
  150. package/starter/desert/render/water/river.ts +1132 -0
  151. package/starter/desert/render/worldNames.ts +6 -0
  152. package/starter/desert/scene.ts +748 -0
  153. package/starter/desert/sceneProps.ts +562 -0
  154. package/starter/desert/sceneState.ts +33 -0
  155. package/starter/desert/world/terrainAssets.ts +162 -0
  156. package/starter/desert/world/walkBand.ts +47 -0
  157. package/starter/desert/world/water.ts +74 -0
  158. package/starter/desert/worlds.ts +13 -0
  159. package/starter/forest/README.md +59 -116
  160. package/starter/forest/assets.json +14 -14
  161. package/starter/forest/bake.mjs +26 -4
  162. package/starter/forest/playerRig.ts +89 -0
  163. package/starter/forest/recipe.json +233 -43
  164. package/starter/forest/render/bakedFile.ts +17 -0
  165. package/starter/forest/render/benchmark.ts +77 -0
  166. package/starter/forest/render/biomeData.ts +14 -0
  167. package/starter/forest/render/biomes.ts +637 -0
  168. package/starter/forest/render/ground/cover.ts +565 -0
  169. package/starter/forest/render/ground/horizon.ts +219 -0
  170. package/starter/forest/render/ground/palette.d.ts +1 -0
  171. package/starter/forest/render/ground/palette.js +11 -0
  172. package/starter/forest/render/ground/scatter.ts +104 -0
  173. package/starter/forest/render/ground/terrain.ts +1796 -0
  174. package/starter/forest/render/kitAssets.ts +28 -0
  175. package/starter/forest/render/loading.ts +354 -0
  176. package/starter/forest/render/lookKnobs.ts +37 -0
  177. package/starter/forest/render/orbitCamera.ts +155 -0
  178. package/starter/forest/render/props/farForest.ts +94 -0
  179. package/starter/forest/render/props/pack.ts +1078 -0
  180. package/starter/forest/render/props/prepared.ts +226 -0
  181. package/starter/forest/render/props/propMaterials.ts +1247 -0
  182. package/starter/forest/render/props/propProgress.ts +2 -0
  183. package/starter/forest/render/props/propWorld.ts +105 -0
  184. package/starter/forest/render/props/props.ts +624 -0
  185. package/starter/forest/render/props/spruce.ts +440 -0
  186. package/starter/forest/render/sky/atmosphere.ts +329 -0
  187. package/starter/forest/render/sky/sky.ts +382 -0
  188. package/starter/forest/render/texturePreparation.ts +135 -0
  189. package/starter/forest/render/water/river.ts +1132 -0
  190. package/starter/forest/render/worldNames.ts +6 -0
  191. package/starter/forest/scene.ts +715 -0
  192. package/starter/forest/sceneProps.ts +559 -0
  193. package/starter/forest/sceneState.ts +33 -0
  194. package/starter/forest/surface.json +2 -2
  195. package/starter/forest/world/terrainAssets.ts +158 -0
  196. package/starter/forest/world/walkBand.ts +47 -0
  197. package/starter/forest/world/water.ts +74 -0
  198. package/starter/forest/worlds.ts +13 -0
  199. package/starter/tundra/README.md +35 -14
  200. package/starter/tundra/bake.mjs +14 -1
  201. package/starter/tundra/biome.data.json +6 -6
  202. package/starter/tundra/playerRig.ts +89 -0
  203. package/starter/tundra/recipe.json +111 -110
  204. package/starter/tundra/render/bakedFile.ts +17 -0
  205. package/starter/tundra/render/benchmark.ts +79 -0
  206. package/starter/tundra/render/biomeData.ts +14 -0
  207. package/starter/tundra/render/biomes.ts +714 -0
  208. package/starter/tundra/render/ground/cover.ts +565 -0
  209. package/starter/tundra/render/ground/horizon.ts +219 -0
  210. package/starter/tundra/render/ground/palette.d.ts +1 -0
  211. package/starter/tundra/render/ground/palette.js +11 -0
  212. package/starter/tundra/render/ground/scatter.ts +104 -0
  213. package/starter/tundra/render/ground/terrain.ts +1874 -0
  214. package/starter/tundra/render/kitAssets.ts +28 -0
  215. package/starter/tundra/render/loading.ts +354 -0
  216. package/starter/tundra/render/lookKnobs.ts +37 -0
  217. package/starter/tundra/render/orbitCamera.ts +155 -0
  218. package/starter/tundra/render/props/farForest.ts +96 -0
  219. package/starter/tundra/render/props/pack.ts +1088 -0
  220. package/starter/tundra/render/props/prepared.ts +225 -0
  221. package/starter/tundra/render/props/propMaterials.ts +1247 -0
  222. package/starter/tundra/render/props/propProgress.ts +2 -0
  223. package/starter/tundra/render/props/propWorld.ts +105 -0
  224. package/starter/tundra/render/props/props.ts +624 -0
  225. package/starter/tundra/render/props/spruce.ts +440 -0
  226. package/starter/tundra/render/sky/atmosphere.ts +329 -0
  227. package/starter/tundra/render/sky/sky.ts +382 -0
  228. package/starter/tundra/render/texturePreparation.ts +135 -0
  229. package/starter/tundra/render/water/river.ts +1132 -0
  230. package/starter/tundra/render/worldNames.ts +6 -0
  231. package/starter/tundra/scene.ts +715 -0
  232. package/starter/tundra/sceneProps.ts +559 -0
  233. package/starter/tundra/sceneState.ts +33 -0
  234. package/starter/tundra/world/terrainAssets.ts +159 -0
  235. package/starter/tundra/world/walkBand.ts +47 -0
  236. package/starter/tundra/world/water.ts +74 -0
  237. package/starter/tundra/worlds.ts +13 -0
  238. package/starter-assets.json +4 -4
  239. package/starter-credits.json +901 -15
  240. package/AGENT_GUIDE.md +0 -209
  241. package/starter/forest/sky.ts +0 -38
  242. package/starter/forest/water.ts +0 -257
  243. package/starter/forest/world.ts +0 -182
@@ -0,0 +1,1247 @@
1
+ import type { IAssetLoader } from "@threenative/core";
2
+ // The surfaces the starter props draw with, and the wind that moves them.
3
+ //
4
+ // All of it is appearance and all of it is this game's: which CC0 map goes on the bark, how the
5
+ // rock is projected onto three axes, how hard the wind pushes and how fast it cycles. ThreeNative
6
+ // supplies the instancing, the lighting and the alpha test's discard; nothing here is a preset the
7
+ // engine chose.
8
+ //
9
+ // Two decisions are worth stating because they are the ones a screenshot proves or refuses:
10
+ //
11
+ // 1. Foliage is alpha-tested, never blended. A cutout writes depth and casts a real shadow; a
12
+ // blended card sorts against every other card in the crown and the tree turns to soup the
13
+ // moment two branches cross on screen.
14
+ // 2. The wind is a vertex-stage displacement weighted by the baked `sway` attribute, so a branch
15
+ // card and the trunk it hangs from move as one and the base of the tree never moves at all.
16
+ import { bakedNoise } from "@threenative/core/world";
17
+ import {
18
+ Color,
19
+ DataTexture,
20
+ DataUtils,
21
+ DoubleSide,
22
+ FrontSide,
23
+ HalfFloatType,
24
+ LinearFilter,
25
+ LinearMipmapLinearFilter,
26
+ type Material,
27
+ RedFormat,
28
+ RepeatWrapping,
29
+ type Texture,
30
+ Vector3,
31
+ } from "three";
32
+ import {
33
+ abs,
34
+ attribute,
35
+ bumpMap,
36
+ cameraPosition,
37
+ cameraProjectionMatrix,
38
+ color,
39
+ dFdx,
40
+ dFdy,
41
+ dot,
42
+ element,
43
+ float,
44
+ length,
45
+ log2,
46
+ max,
47
+ mix,
48
+ normalMap,
49
+ normalViewGeometry,
50
+ normalWorld,
51
+ normalWorldGeometry,
52
+ normalize,
53
+ positionLocal,
54
+ positionView,
55
+ positionWorld,
56
+ pow,
57
+ renderGroup,
58
+ rotateUV,
59
+ sign,
60
+ smoothstep,
61
+ texture,
62
+ transformNormalToView,
63
+ uniform,
64
+ uv,
65
+ vec2,
66
+ vec3,
67
+ vec4,
68
+ } from "three/tsl";
69
+ import type { Node } from "three/webgpu";
70
+ import { MeshStandardNodeMaterial } from "three/webgpu";
71
+ import {
72
+ DRY_STONE_MAPS,
73
+ FERN_MAPS,
74
+ FIR_MAPS,
75
+ GROUND_MAPS,
76
+ type ISurfaceMaps,
77
+ NEEDLE_ATLAS,
78
+ NEEDLE_SURFACE,
79
+ PROP_MAPS,
80
+ ROCKFACE_MAPS,
81
+ SOIL_MAP,
82
+ } from "../../world/terrainAssets.js";
83
+ import {
84
+ BIOMES,
85
+ type IWorldBiome,
86
+ alpineRockAlbedo,
87
+ alpineRockColor,
88
+ alpineSnowCover,
89
+ biomeWeights,
90
+ } from "../biomes.js";
91
+ import {
92
+ groundLayer,
93
+ groundTurf,
94
+ stoneAlbedo,
95
+ stoneColor,
96
+ stoneRelief,
97
+ tiledUV,
98
+ } from "../ground/terrain.js";
99
+ import type { IPropMaterials } from "./props.js";
100
+
101
+ /** How much a mip level shrinks a needle card's alpha; see {@link mipCompensatedCutoff}. */
102
+ const MIP_ALPHA_SCALE = 0.25;
103
+
104
+ /** The wind, in metres and seconds. Its direction is world space. */
105
+ export const WIND = {
106
+ direction: [0.82, 0.57] as const,
107
+ /** Peak displacement at a full sway weight, in metres. A boulder does not move. */
108
+ amplitude: { bark: 0.05, crown: 0.34, grass: 0.14, petal: 0.2, stem: 0.16, stone: 0 },
109
+ /** Cycles per second. A tree in a stiff breeze is around one cycle every two seconds. */
110
+ rate: 0.42,
111
+ } as const;
112
+
113
+ /**
114
+ * Sun through a needle card, in this game's units.
115
+ *
116
+ * A spruce needle is one cell thick and translucent, and the light that comes *through* it is most
117
+ * of what a canopy is lit by — a backlit spruce is bright at its edges and near-black underneath,
118
+ * which is exactly the failure the judges described. Two terms buy it, and neither needs a second
119
+ * light or a custom BRDF:
120
+ *
121
+ * - a wrapped diffuse, `N·L` remapped from -1..1 onto 0..1, which lights the faces turned away
122
+ * from the sun at a fraction of the ones turned towards it. The knob is how much of the wrap;
123
+ * a needle wraps almost all the way, a leaf halfway.
124
+ * - a backlight through the card, strongest where the eye is looking along the sun's direction
125
+ * through the foliage. That is the silver rim on a backlit branch, and it is what separates a
126
+ * crown from a green cutout.
127
+ *
128
+ * Both read the sun as a *world-space direction towards it*, which is the same vector the sky rig
129
+ * puts on its own uniforms, so the `L` key moves the translucency with everything else.
130
+ */
131
+ const CANOPY = {
132
+ /** How far past the terminator a needle is still lit, 0..1. Nearly a leaf, nearly not a card. */
133
+ wrap: 0.55,
134
+ /** The lit-through share, and how tightly it is aimed at the eye. */
135
+ backlight: { strength: 0.5, focus: 5 },
136
+ /** The colour of the light coming through a needle: yellow-green, because that is what a leaf is
137
+ * transmitting and not because it is a constant anybody chose. */
138
+ tint: 0xa8d05a,
139
+ /** The floor no needle falls below, in linear albedo. Judged at 0.14: dark, never near-black. */
140
+ floor: 0.14,
141
+ } as const;
142
+
143
+ /** The sun as a world-space direction towards it, written by `src/render/sky/sky.ts`. */
144
+ const sunDirection = uniform(new Vector3(-180, 240, 120).normalize()).setGroup(
145
+ renderGroup,
146
+ ) as unknown as Node<"vec3">;
147
+
148
+ /**
149
+ * Point the shared canopy uniform at the sun. One call, from the rig that owns the sun.
150
+ *
151
+ * A module-level uniform rather than a parameter, because the fog, the cloud deck and the canopy
152
+ * light all need the same sun and passing one through every builder would be three ways to get it
153
+ * subtly out of step.
154
+ */
155
+ export function setCanopySun(direction: Vector3): void {
156
+ (sunDirection as unknown as { value: Vector3 }).value.copy(direction).normalize();
157
+ }
158
+
159
+ /**
160
+ * A copy of a tree material for crowns the sun's shadow does not reach: the far forest, which casts
161
+ * none, and the square's own trees past the shadow window (`shadowReach`, where `sky.ts` fades the
162
+ * shadow out). In a closed stand each tree stands in its neighbours' shade, more of it the lower the
163
+ * sun: with no shadow drawn, far trees measured 3 to 4 times brighter and yellower than near ones at
164
+ * a 20 degree sun. The copy takes the stand's mean shade as a tint that fades out as the sun climbs;
165
+ * with a `shadowReach` it takes the tint only past that window.
166
+ */
167
+ export function standShaded(
168
+ source: Material,
169
+ shade: readonly [number, number, number],
170
+ shadowReach?: number,
171
+ ): Material {
172
+ const shaded = source.clone() as MeshStandardNodeMaterial;
173
+ const stand = mix(vec3(...shade), vec3(1), sunDirection.y.clamp(0, 1).pow(2));
174
+ const tint =
175
+ shadowReach === undefined
176
+ ? stand
177
+ : mix(
178
+ vec3(1),
179
+ stand,
180
+ // An orthographic view has no eye distance. The engine bakes a tree's impostor through
181
+ // one, and the impostor draws only past the window, so that view takes the far value.
182
+ smoothstep(shadowReach * 0.65, shadowReach * 0.8, positionView.length()).max(
183
+ (element(cameraProjectionMatrix as never, 3) as Node<"vec4">).w,
184
+ ),
185
+ );
186
+ if (shaded.colorNode) shaded.colorNode = (shaded.colorNode as Node<"vec3">).mul(tint);
187
+ if (shaded.emissiveNode) shaded.emissiveNode = (shaded.emissiveNode as Node<"vec3">).mul(tint);
188
+ return shaded;
189
+ }
190
+
191
+ /**
192
+ * The wrapped two-sided translucency of a needle card, as an emissive node.
193
+ *
194
+ * Emissive rather than a light contribution, and that is not a cheat: a card has no thickness to
195
+ * integrate through, so any "transmission" here is an artistic term, and adding it after the standard
196
+ * shading keeps the standard shading's own shadow, its hemisphere fill and its tone curve intact.
197
+ */
198
+ function canopyTranslucency(amount: number, tint: number = CANOPY.tint): Node<"vec3"> {
199
+ // The eye's direction, away from the camera towards the fragment.
200
+ const toEye = cameraPosition.sub(positionWorld).normalize();
201
+ // `normalWorld` on a double-sided card points whichever way the geometry was wound, so a card seen
202
+ // from behind would be lit from its own interior. The wrap is remapped through the sign of the
203
+ // facing, which is the whole of the two-sided half of this effect: the back of a crown catches
204
+ // the light that came through it.
205
+ const facing = normalWorld.dot(sunDirection).abs();
206
+ // Wrapped diffuse: -1..1 becomes 0..1, lifted so a needle facing away is still lit a little.
207
+ const wrapped = facing.add(CANOPY.wrap).div(float(1).add(CANOPY.wrap));
208
+ // Backlight: the sun is behind the card and behind the eye, so light is travelling towards the
209
+ // camera through the needles. Raised to a power because the effect is a rim, not a wash.
210
+ const back = pow(toEye.dot(sunDirection).clamp(0, 1), float(CANOPY.backlight.focus));
211
+ return color(new Color(tint)).mul(
212
+ wrapped.mul(amount).add(back.mul(CANOPY.backlight.strength).mul(amount)),
213
+ );
214
+ }
215
+
216
+ /** Thin-needle transmission follows the sun and cannot light a buried or shadowed card. */
217
+ export function lightNeedles(
218
+ material: MeshStandardNodeMaterial,
219
+ occlusion: Node<"float">,
220
+ translucency = 0.55,
221
+ ): void {
222
+ if (!material.colorNode) return;
223
+ const backlit = cameraPosition
224
+ .sub(positionWorld)
225
+ .normalize()
226
+ .negate()
227
+ .dot(sunDirection)
228
+ .clamp(0, 1)
229
+ .pow(3);
230
+ const albedo = (material.colorNode as Node<"vec4">).rgb;
231
+ // Green light scattered by neighbouring needles; the crown's occlusion retains dark interiors.
232
+ const glow = albedo.mul(vec3(0.12, 0.8, 0.06)).mul(occlusion);
233
+ material.emissiveNode = glow;
234
+ const through = albedo.mul(backlit.mul(translucency)).mul(smoothstep(0.16, 0.5, occlusion));
235
+ // engine-override: the owned engine has no setupLightingModel hook, so the same transmission node
236
+ // goes into the emissive instead of the sun's direct term: same albedo scale, same occlusion gate,
237
+ // and it misses the sun's shadow. Two Sided Foliage (PRD-643) is not a stand-in: its transmittance
238
+ // is one uniform colour, neither albedo-scaled nor gated by the card's facing, so it lifted this
239
+ // forest's canopy by 2x over three at the overview pose (canopy 90/108/66 with it, 51/70/55 with the
240
+ // term cleared, three 45/62/52).
241
+ if (typeof material.setupLightingModel !== "function") {
242
+ material.emissiveNode = glow.add(through);
243
+ return;
244
+ }
245
+ // Add transmission where Three has already applied the sun's shadow to its light colour.
246
+ // Reading the raw virtual-shadow node again in emissive broke forest→coast material bindings.
247
+ const setup = material.setupLightingModel.bind(material);
248
+ material.setupLightingModel = () => {
249
+ const model = setup();
250
+ const direct = model.direct.bind(model);
251
+ model.direct = (input, builder) => {
252
+ direct(input, builder);
253
+ (input.reflectedLight.directDiffuse as unknown as Node<"vec3">).addAssign(
254
+ through.mul(input.lightColor as unknown as Node<"vec3">),
255
+ );
256
+ };
257
+ return model;
258
+ };
259
+ }
260
+
261
+ /** Alpha cutoff for every cutout surface. Half coverage: a needle card is mostly empty. */
262
+ const CUTOUT = 0.42;
263
+
264
+ /**
265
+ * Metres one tile of each mapped prop surface spans. Bark plates are a hand wide; rock is metres.
266
+ *
267
+ * A size of a pattern rather than a fact about a file, which is why it stays here and the paths do
268
+ * not: replacing the bark map with one of a different resolution changes nothing about how big a
269
+ * bark plate is.
270
+ */
271
+ const TILE = { bark: 1.6, stone: 1.4 } as const;
272
+
273
+ /**
274
+ * The prepared pine's own cutoff, which is a seventh of the shared one.
275
+ *
276
+ * Not a fudge and not a preference: it is what the pine's atlas measures. A Scots pine spray is
277
+ * 116 atlas cells of needles drawn thin, and `scripts/prep/prep-fab-pines.py` measures what that means
278
+ * by area-averaging the crown's own front view — 11.8% of the crown's silhouette carries needle at
279
+ * all, and the 99th percentile of a texel's alpha is 0.22. A cutout at 0.42 therefore discards the
280
+ * crown almost entirely the moment the card is minified, because a mip of a 12%-dense cell averages
281
+ * to about 0.12 however deep it is. The generated needle atlas and Poly Haven's twig atlas are both
282
+ * far denser per cell and keep the shared cutoff; this one gets the number its own texture implies.
283
+ */
284
+
285
+ /**
286
+ * The prepared pine's own map, cut from the licensed Fab atlas by
287
+ * `scripts/prep/prep-fab-pines.py` into this example's gitignored `local-assets/prepared/`.
288
+ *
289
+ * One texture, and the absence of the other two is a decision rather than a saving. A needle spray
290
+ * is a flat card: the relief in a pine is the four thousand cards of the prepared crown pointing
291
+ * every which way, not a normal map, and binding this atlas as one — or deriving a height field
292
+ * from its own alpha, which is the same mistake with more steps — would emboss a flat card into
293
+ * something corrugated. So the pine gets the atlas's colour and its alpha, the shared waxy
294
+ * roughness, and the same wrapped two-sided canopy light every other crown gets.
295
+ */
296
+
297
+ /** Load one starter map, or nothing. A prop still draws without it, on its own colours. */
298
+ async function map(assets: IAssetLoader | undefined, path: string, data: boolean, repeat = false) {
299
+ if (assets === undefined) return undefined;
300
+ const found = await assets
301
+ .texture(path, { data, ...(repeat ? { wrap: RepeatWrapping } : {}) })
302
+ .catch(() => undefined);
303
+ if (found === undefined) return undefined;
304
+ // Cutout maps need mips and an anisotropy filter: a needle card sampled without them shimmers at
305
+ // a grazing angle, which is exactly the angle a meadow is viewed from.
306
+ found.minFilter = LinearMipmapLinearFilter;
307
+ found.magFilter = LinearFilter;
308
+ found.anisotropy = 8;
309
+ found.needsUpdate = true;
310
+ return found;
311
+ }
312
+
313
+ async function surfaceMaps(assets: IAssetLoader | undefined, set: ISurfaceMaps) {
314
+ if (assets === undefined) return {};
315
+ const [diffuse, normal, roughness] = await Promise.all([
316
+ map(assets, set.diffuse, false),
317
+ map(assets, set.normal, true),
318
+ map(assets, set.roughness, true),
319
+ ]);
320
+ return { diffuse, normal, roughness };
321
+ }
322
+
323
+ /**
324
+ * The wind's displacement, as a TSL node.
325
+ *
326
+ * The envelope is the baked `sway` weight, so a branch card and the trunk behind it move together
327
+ * and nothing at the base of the tree moves at all. The phase carries a per-position term so a stand
328
+ * of trees does not sway as one rigid block: the phase difference between two trunks twelve metres
329
+ * apart is more than half a cycle at this rate, which is what a real gust does.
330
+ */
331
+ function windOffset(clock: Node<"float">, amplitude: number) {
332
+ const weight = attribute<"float">("sway", "float");
333
+ const wave = clock
334
+ .mul(WIND.rate * Math.PI * 2)
335
+ .add(positionWorld.x.mul(0.31))
336
+ .add(positionWorld.z.mul(0.24))
337
+ .sin()
338
+ .mul(amplitude)
339
+ .mul(weight);
340
+ // A second, slower term at a different spatial frequency: one sine is a pendulum, and a forest
341
+ // that only pendulums reads as a row of metronomes.
342
+ const gust = clock
343
+ .mul(WIND.rate * 0.37 * Math.PI * 2)
344
+ .add(positionWorld.x.mul(0.07))
345
+ .add(positionWorld.z.mul(0.11))
346
+ .sin()
347
+ .mul(amplitude * 0.55)
348
+ .mul(weight);
349
+ return vec3(WIND.direction[0], 0, WIND.direction[1]).mul(wave.add(gust));
350
+ }
351
+
352
+ /**
353
+ * Attach the wind to a material's vertex stage; the shadow pass reads the rest pose instead. Virtual
354
+ * shadow pages are cached, so a cast that moved with the wind froze the frame its page last drew and
355
+ * then snapped every nearby tree's shadow when walking re-rendered that page.
356
+ */
357
+ function sway(base: MeshStandardNodeMaterial, clock: Node<"float">, amplitude: number) {
358
+ const offset = windOffset(clock, amplitude);
359
+ base.positionNode = positionLocal.add(offset);
360
+ base.castShadowPositionNode = positionLocal;
361
+ // engine-override: the farthest windOffset moves a vertex (both sines at a full weight along a unit
362
+ // direction). The owned engine grows each tree's shadow box by it and culls the trees per shadow page.
363
+ (base as MeshStandardNodeMaterial & { maxPositionOffset?: number }).maxPositionOffset =
364
+ amplitude * 1.55;
365
+ }
366
+
367
+ /**
368
+ * Triplanar albedo and relief for the boulders, from one set of mossy-rock maps.
369
+ *
370
+ * Projected on all three axes rather than wrapped in UV, because a boulder is displaced noise with
371
+ * no sensible unwrap: a single planar projection smears the top of a round rock into stripes. Each
372
+ * axis owns a different pair of world axes and the three are recombined by the surface's own blend
373
+ * weights, which is what `src/render/ground/terrain.ts` already does for its cliff layer.
374
+ */
375
+ /**
376
+ * Where a prop meets the ground, and what the ground there is made of.
377
+ *
378
+ * A boulder or a trunk that changes material in one clean line where it enters the terrain reads as
379
+ * an object placed on a heightfield — the "stuck on" look. Real ground climbs the base of what sits in
380
+ * it: soil and litter banked against a rock, dirt around a root flare. So a prop surface reads the
381
+ * baked heights under itself and, over the bottom of its height above that ground, fades into the
382
+ * forest floor's own map and turns its normal toward the ground's.
383
+ */
384
+ export interface IPropGround {
385
+ readonly heights: readonly number[];
386
+ readonly resolution: number;
387
+ readonly size: number;
388
+ }
389
+
390
+ /** How far up a prop the ground climbs, in metres, and how far the soil map repeats. */
391
+ const GROUND_BLEND = { reach: 0.7, soilTile: 3.4 } as const;
392
+
393
+ /** The ground's height under a fragment, from the same baked heights the terrain was built from. */
394
+ function groundHeight(ground: IPropGround): {
395
+ node: Node<"float">;
396
+ normal: Node<"vec3">;
397
+ texture: DataTexture;
398
+ } {
399
+ const heights = new DataTexture(
400
+ Uint16Array.from(ground.heights, DataUtils.toHalfFloat),
401
+ ground.resolution,
402
+ ground.resolution,
403
+ RedFormat,
404
+ HalfFloatType,
405
+ );
406
+ heights.minFilter = LinearFilter;
407
+ heights.magFilter = LinearFilter;
408
+ heights.needsUpdate = true;
409
+ const at = positionWorld.xz
410
+ .div(float(ground.size))
411
+ .add(0.5)
412
+ .mul((ground.resolution - 1) / ground.resolution)
413
+ .add(0.5 / ground.resolution);
414
+ const texel = 1 / ground.resolution;
415
+ const step = ground.size / (ground.resolution - 1);
416
+ // Match Heightfield's two drawn triangles; bilinear interpolation floats above a saddle.
417
+ const grid = positionWorld.xz
418
+ .div(ground.size)
419
+ .add(0.5)
420
+ .mul(ground.resolution - 1)
421
+ .clamp(0, ground.resolution - 1.00001);
422
+ const fraction = grid.fract();
423
+ const cell = grid.floor().add(0.5).div(ground.resolution);
424
+ const a = texture(heights, cell).r;
425
+ const b = texture(heights, cell.add(vec2(texel, 0))).r;
426
+ const c = texture(heights, cell.add(vec2(0, texel))).r;
427
+ const d = texture(heights, cell.add(vec2(texel))).r;
428
+ const lower = a.add(b.sub(a).mul(fraction.x)).add(c.sub(a).mul(fraction.y));
429
+ const upper = d.add(c.sub(d).mul(fraction.x.oneMinus())).add(b.sub(d).mul(fraction.y.oneMinus()));
430
+ const height = fraction.x.add(fraction.y).lessThanEqual(1).select(lower, upper);
431
+ const dx = texture(heights, at.add(vec2(texel, 0))).r.sub(
432
+ texture(heights, at.sub(vec2(texel, 0))).r,
433
+ );
434
+ const dz = texture(heights, at.add(vec2(0, texel))).r.sub(
435
+ texture(heights, at.sub(vec2(0, texel))).r,
436
+ );
437
+ return {
438
+ node: height,
439
+ normal: normalize(vec3(dx.negate(), step * 2, dz.negate())),
440
+ texture: heights,
441
+ };
442
+ }
443
+
444
+ /**
445
+ * The share of a fragment that is ground rather than prop, 0..1: one at the contact, none a
446
+ * `GROUND_BLEND.reach` above it, with a noisy edge so the soil line wanders instead of being a level.
447
+ */
448
+ function groundShare(height: Node<"float"> | undefined): Node<"float"> {
449
+ if (height === undefined) return float(0);
450
+ const wander = bakedNoise(positionWorld.mul(1.7)).mul(0.18);
451
+ const above = positionWorld.y.sub(height).add(wander);
452
+ return float(1).sub(smoothstep(float(0.02), float(GROUND_BLEND.reach), above));
453
+ }
454
+
455
+ /** Blend a surface's colour and normal into the forest floor by `share`. */
456
+ function intoGround(
457
+ material: MeshStandardNodeMaterial,
458
+ colour: Node<"vec3">,
459
+ share: Node<"float">,
460
+ soil: Texture | undefined,
461
+ bendNormal = true,
462
+ ): void {
463
+ if (soil === undefined) return;
464
+ const floor = texture(soil, positionWorld.xz.div(float(GROUND_BLEND.soilTile))).rgb.mul(0.85);
465
+ material.colorNode = mix(colour, floor, share.mul(0.92));
466
+ // A surface lit through `normalMap` keeps it: a set normalNode would replace the map outright.
467
+ if (!bendNormal) return;
468
+ const lit = material.normalNode ?? transformNormalToView(normalWorld);
469
+ material.normalNode = normalize(
470
+ mix(lit as Node<"vec3">, transformNormalToView(vec3(0, 1, 0)), share.mul(0.75)),
471
+ );
472
+ }
473
+
474
+ /** The landscape's floor maps continue up stone, measured above the actual baked ground. */
475
+ export async function createRockGround(
476
+ assets?: IAssetLoader,
477
+ ground?: IPropGround,
478
+ biome?: IWorldBiome,
479
+ ) {
480
+ const look = biome ?? BIOMES.forest;
481
+ // Beach stones keep their dry surface: the temperate contact band paints grass onto sand.
482
+ if (!ground || !look.stoneGroundBand) return undefined;
483
+ const under = groundHeight(ground);
484
+ const paths = biome?.maps ?? GROUND_MAPS;
485
+ const rockPaths = look.contactRockface ? ROCKFACE_MAPS : paths.rock;
486
+ const [grass, relief, rock, rockNormal, snow] = await Promise.all([
487
+ map(assets, paths.grass.diffuse, false),
488
+ paths.grass.normal ? map(assets, paths.grass.normal, true) : undefined,
489
+ map(assets, rockPaths.diffuse, false).then(
490
+ (found) => found ?? map(assets, paths.rock.diffuse, false),
491
+ ),
492
+ rockPaths.normal
493
+ ? map(assets, rockPaths.normal, true).then(
494
+ (found) =>
495
+ found ?? (paths.rock.normal ? map(assets, paths.rock.normal, true) : undefined),
496
+ )
497
+ : undefined,
498
+ look.crestRock ? map(assets, paths.snow.diffuse, false) : undefined,
499
+ ]);
500
+ return {
501
+ apply(material: MeshStandardNodeMaterial): void {
502
+ if (!grass || !material.colorNode) return;
503
+ // World-space distance across the side gives a half-metre, noise-broken contact falloff.
504
+ const radial = positionWorld.y.sub(under.node).div(length(normalWorldGeometry.xz).max(0.25));
505
+ const share = float(1).sub(
506
+ smoothstep(0, 0.5, radial.add(bakedNoise(positionWorld.mul(1.7)).mul(0.12))),
507
+ );
508
+ const floor = groundTurf(groundLayer(grass, "grass").rgb, biome);
509
+ const slope = smoothstep(0.17, 0.33, under.normal.y.oneMinus());
510
+ const soil = share;
511
+ let contact = rock
512
+ ? mix(floor, stoneColor(stoneAlbedo(rock, biome, under.normal), biome), slope)
513
+ : floor;
514
+ if (snow && biome) {
515
+ const cover =
516
+ biomeWeights(
517
+ biome,
518
+ float(1).sub(under.normal.y),
519
+ float(0),
520
+ bakedNoise(positionWorld.mul(0.05)),
521
+ ).snow ?? float(0);
522
+ contact = mix(contact, groundLayer(snow, "snow").rgb.mul(vec3(...biome.snowTint)), cover);
523
+ }
524
+ material.colorNode = mix(material.colorNode as Node<"vec3">, contact, soil);
525
+ material.aoNode = ((material.aoNode as Node<"float"> | null) ?? float(1)).mul(
526
+ mix(1, 0.86, share),
527
+ );
528
+ const lit =
529
+ material.normalNode ??
530
+ (material.normalMap
531
+ ? normalMap(texture(material.normalMap))
532
+ : transformNormalToView(normalWorldGeometry));
533
+ const tilt = relief
534
+ ? rotateUV(texture(relief, tiledUV("grass")).xy.mul(2).sub(1), float(-0.38), vec2(0)).mul(
535
+ 0.22,
536
+ )
537
+ : vec2(0);
538
+ const groundTilt = rockNormal
539
+ ? mix(
540
+ vec3(tilt.x, 0, tilt.y),
541
+ stoneRelief(rockNormal, biome, under.normal).mul(0.52),
542
+ slope,
543
+ )
544
+ : vec3(tilt.x, 0, tilt.y);
545
+ const tangent = groundTilt.sub(under.normal.mul(dot(under.normal, groundTilt)));
546
+ const normal = normalize(under.normal.add(tangent));
547
+ material.normalNode = normalize(
548
+ mix(lit as Node<"vec3">, transformNormalToView(normal), soil.mul(0.82)),
549
+ );
550
+ material.roughnessNode = mix(
551
+ (material.roughnessNode as Node<"float"> | null) ?? float(material.roughness),
552
+ 0.94,
553
+ soil,
554
+ );
555
+ },
556
+ dispose(): void {
557
+ for (const source of [under.texture, grass, relief, rock, rockNormal, snow])
558
+ source?.dispose();
559
+ },
560
+ };
561
+ }
562
+
563
+ function stoneSurface(maps: { diffuse?: Texture; normal?: Texture; arm?: Texture }) {
564
+ const material = new MeshStandardNodeMaterial({ metalness: 0, roughness: 0.93, side: FrontSide });
565
+ const tile = float(TILE.stone);
566
+ const detail = float(1).sub(smoothstep(25, 90, length(cameraPosition.sub(positionWorld))));
567
+ const geometryNormal = normalWorldGeometry;
568
+ const axis = abs(geometryNormal).pow(4);
569
+ const share = axis.div(axis.x.add(axis.y).add(axis.z));
570
+ const xUV = positionWorld.zy.div(tile);
571
+ const yUV = positionWorld.xz.div(tile);
572
+ const zUV = positionWorld.xy.div(tile);
573
+ if (maps.diffuse === undefined) material.colorNode = vec3(0.42, 0.43, 0.38);
574
+ else {
575
+ material.colorNode = share.x
576
+ .mul(texture(maps.diffuse, xUV).rgb)
577
+ .add(share.y.mul(texture(maps.diffuse, yUV).rgb))
578
+ .add(share.z.mul(texture(maps.diffuse, zUV).rgb));
579
+ }
580
+ if (maps.normal !== undefined) {
581
+ // GL maps encode +Y in green. Match each tangent component to its colour projection.
582
+ const x = texture(maps.normal, xUV).xy.mul(2).sub(1);
583
+ const y = texture(maps.normal, yUV).xy.mul(2).sub(1);
584
+ const z = texture(maps.normal, zUV).xy.mul(2).sub(1);
585
+ const relief = share.x
586
+ .mul(vec3(0, x.y, x.x.mul(sign(geometryNormal.x))))
587
+ .add(share.y.mul(vec3(y.x, 0, y.y)))
588
+ .add(share.z.mul(vec3(z.x.mul(sign(geometryNormal.z)), z.y, 0)))
589
+ .mul(maps.arm ? 0.45 : 0.7)
590
+ .mul(detail);
591
+ const tangent = relief.sub(geometryNormal.mul(dot(geometryNormal, relief)));
592
+ material.normalNode = transformNormalToView(normalize(geometryNormal.add(tangent)));
593
+ }
594
+ if (maps.arm) {
595
+ // One dominant-axis ARM tap shares roughness/AO; broad data needs no three-way blend.
596
+ const plane = axis.x
597
+ .greaterThan(axis.y)
598
+ .and(axis.x.greaterThan(axis.z))
599
+ .select(xUV, axis.y.greaterThan(axis.z).select(yUV, zUV));
600
+ const arm = texture(maps.arm, plane);
601
+ material.roughnessNode = arm.g.mul(0.2).add(0.8);
602
+ material.aoNode = arm.r.max(0.65);
603
+ }
604
+ return material;
605
+ }
606
+
607
+ /**
608
+ * How much of a card one pixel covers, read from the card's own UV derivatives.
609
+ *
610
+ * Two answers, because a card is a rectangle and a pixel is a square, and the two axes of a card seen
611
+ * from a meadow are rarely the same length. `worst` is the deeper of the two levels: that is the
612
+ * right question for a cutoff, because a card compressed along one axis still has to keep its
613
+ * needles. `area` is the geometric mean, which is how many texels the pixel really lands on, and the
614
+ * only honest answer to how far away the tree is — a card seen edge-on covers a sliver of the screen
615
+ * however far away it is, and a sliver does not need to be a solid mass.
616
+ *
617
+ * The atlas is generated at 1024x1024 by `scripts/prep/make-needle-atlas.mjs`, and the chain is read from
618
+ * the texture's own dimensions so a regenerated atlas at another size still measures itself.
619
+ */
620
+ function mipLevels(atlas: Texture): { area: Node<"float">; worst: Node<"float"> } {
621
+ const image = atlas.image as { width?: number; height?: number } | undefined;
622
+ const size = vec2(image?.width ?? 1024, image?.height ?? 1024);
623
+ const x = length(dFdx(uv()).mul(size));
624
+ const y = length(dFdy(uv()).mul(size));
625
+ const level = (texels: Node<"float">): Node<"float"> =>
626
+ max(log2(max(texels, float(1))), float(0));
627
+ return { area: level(x.mul(y).sqrt()), worst: level(max(x, y)) };
628
+ }
629
+
630
+ /**
631
+ * The alpha cutoff as a node, falling with the mip level the fragment is really sampling.
632
+ *
633
+ * Ben Golus's compensation: the deeper the mip the smaller the effective cutoff, because a deeper mip
634
+ * is a coarser question about the same texel rather than a stricter one. A needle card forty metres
635
+ * away is sampled from mip three or four, where its alpha has averaged down towards 0.2, and a
636
+ * `discard` at 0.42 throws the needles away and leaves a forest of bare trunks.
637
+ *
638
+ * `cutoff` is the surface's own base value rather than one constant for every cutout in the game,
639
+ * because how much of a card is needle is a property of the card and not of the shader: the
640
+ * generated atlas and Poly Haven's twig atlas are dense enough for half coverage, and the pine's
641
+ * sprays and the baked far card are not.
642
+ */
643
+ function mipCompensatedCutoff(mip: Node<"float">, cutoff: number) {
644
+ // Golus's compensation in its cutoff form: divide the cutoff by the mip's alpha scale.
645
+ const scale = float(1).add(mip.mul(MIP_ALPHA_SCALE));
646
+ return float(cutoff).div(scale) as unknown as Node<"float">;
647
+ }
648
+
649
+ /**
650
+ * How far a cutout has become a solid mass instead of a spray of separate needles, 0..1.
651
+ *
652
+ * Lowering the cutoff alone is half a fix, and the half that is left produces the failure this exists
653
+ * to remove: a crown that is a lace of surviving specks. A needle card is mostly empty, so its mip
654
+ * average is a low number everywhere, and what clears a threshold there is chosen by noise — which is
655
+ * stipple, not foliage, and it is worst exactly where a tree is smallest on screen.
656
+ *
657
+ * Coverage is not a constant, though. A card sampled from a deep mip *is* a distant tree, and a
658
+ * distant tree is a mass, not a spray of needles: the mip average of a card is the fraction of the
659
+ * card that card covers, and the further off it is the less that fraction matters. So the alpha
660
+ * ramps towards solid as the footprint grows, and the cutoff ramp above keeps the fringe crisp where
661
+ * the fringe is still readable. The two together are the distance LOD in the shader: needles under
662
+ * thirty metres, mass past a hundred and fifty, and a crown that gains density all the way between.
663
+ *
664
+ * The ramp starts where a card's cell is about eight texels across on screen, which is the point
665
+ * where separate needles stop being resolvable and start being texture. Start it earlier and the
666
+ * near trees stop being trees: the cards fill in, and a spruce becomes a stack of solid leaves.
667
+ */
668
+ const SOLID = { from: 3, to: 5.5 } as const;
669
+
670
+ /**
671
+ * How a needle surface is graded and cut, per species.
672
+ *
673
+ * Every field is a property of the atlas rather than of the shader, which is why they are parameters
674
+ * and not constants: how much of a card is needle, how dark its darkest texel is, how far it has to
675
+ * travel before it is a mass rather than a spray, and whether the species is a yellow-green spruce or
676
+ * a blue-green pine are all questions about the texture in hand.
677
+ */
678
+ interface INeedleLook {
679
+ /** The alpha a texel is cut at, before mip compensation. */
680
+ readonly cutout: number;
681
+ /** The linear albedo the darkest texel is lifted to, as a share towards its own peak. */
682
+ readonly floor: number;
683
+ /** The mip range over which the crown gains density and becomes a mass. */
684
+ readonly ramp: { from: number; to: number };
685
+ /** A per-channel grade on the sampled needle colour. */
686
+ readonly tint: readonly [number, number, number];
687
+ /** The colour of the tree's new growth at the tips, against {@link TIP_ROOT} at its base. */
688
+ readonly tip: readonly [number, number, number];
689
+ /** How much light comes *through* the card. */
690
+ readonly light: number;
691
+ /**
692
+ * Light the cards with the normals their geometry carries — the crown's outward direction, from
693
+ * `spruce.ts` — on both faces, and darken by the `inner` attribute toward the trunk. A crown lit
694
+ * this way shades as one volume instead of as a stack of separately lit paddles.
695
+ */
696
+ readonly bent?: boolean;
697
+ /** How dark a bent crown's trunk end is against its tips, 0..1 (`inner` 0 against 1). */
698
+ readonly interior?: number;
699
+ }
700
+
701
+ /** The shared grade: new growth is lighter than the shaded interior, and both ends stay honest. */
702
+ const TIP_ROOT = [0.9, 1.0, 0.86] as const;
703
+ const TIP_TIP = [1.28, 1.34, 1.12] as const;
704
+
705
+ /**
706
+ * How the pine's own atlas is graded, cut and lit, and every number in it is measured rather than
707
+ * chosen.
708
+ *
709
+ * `cutout` 0.11, not the shared 0.42: a Scots pine spray is needles drawn thin, and
710
+ * `scripts/prep/prep-fab-pines.py` area-averages the crown's front view to find out what that costs — 12%
711
+ * of the crown's silhouette carries needle at all, and a texel's 99th percentile alpha is 0.22. A
712
+ * discard at 0.42 erases the crown the moment its cards are minified, because a mip of a 12%-dense
713
+ * cell averages to about 0.12 however deep it is.
714
+ *
715
+ * `floor` 0.05, against a shared 0.14 and an atlas whose needles peak at 0.106: the shared value
716
+ * takes a one-in-three lift on an average pine needle and up to five on a dark one, compressing the
717
+ * whole crown into one flat band.
718
+ *
719
+ * `tint` is the correction for what the atlas actually is. Its needles measure a linear
720
+ * 0.106 red against 0.026 blue — four times as much red as blue, which is olive, not green — because
721
+ * the crown samples the atlas's brown and dying cells as well as its green ones. A pine is blue-green
722
+ * against a spruce's yellow-green, and this is where the game says so: red and blue pulled down and
723
+ * green left alone turns the atlas's olive into the species' green without touching a texel.
724
+ *
725
+ * `tip` is the shared spruce grade pulled back, because the shared one is a 28 to 34 per cent push
726
+ * towards yellow at the top of the tree and this crown is *all* top of the tree.
727
+ */
728
+ const PINE_LOOK: INeedleLook = {
729
+ cutout: 0.11,
730
+ floor: 0.05,
731
+ light: 0.07,
732
+ ramp: SOLID,
733
+ tint: [0.72, 0.94, 0.78],
734
+ tip: [1.04, 1.1, 1.0],
735
+ };
736
+
737
+ /**
738
+ * The far card's cutoff, and how fast it becomes solid.
739
+ *
740
+ * A cross-card impostor is not a cutout. It is a crown that was area-averaged into a picture, and
741
+ * its alpha is a *coverage* — twelve per cent of the crown, spread thin — so a discard at any
742
+ * pine-like value erases the tree it is standing in for. The card's own margins are exactly zero, so
743
+ * the threshold can sit very low and still cut them, and the ramp is pulled forward to where a card
744
+ * of this size is already a mass: that is the whole reason the far band is eight triangles.
745
+ */
746
+ const IMPOSTOR = { cutoff: 0.02, from: 0.2, to: 2.4 } as const;
747
+
748
+ /**
749
+ * One alpha-tested needle surface, built from whichever atlas it is handed.
750
+ *
751
+ * The same shader for both crowns in the starter, because they are the same decision about light:
752
+ * a needle card is one cell thick, so a wrapped diffuse and a backlight through the card are most
753
+ * of what makes a canopy read as lit rather than as a green cutout. What differs is where the
754
+ * atlas came from — the generated one carries its relief and its occlusion in two files of its
755
+ * own, and Poly Haven's carries a real normal map and a packed arms map — so the relief and the
756
+ * occlusion are read from whichever pair it is given.
757
+ */
758
+ function needleMaterial(
759
+ atlas: Texture | undefined,
760
+ relief: Texture | undefined,
761
+ arms: Texture | undefined,
762
+ seconds: Node<"float">,
763
+ look: Partial<INeedleLook> = {},
764
+ ): MeshStandardNodeMaterial {
765
+ const {
766
+ cutout = CUTOUT,
767
+ floor = CANOPY.floor,
768
+ ramp = SOLID,
769
+ tint,
770
+ tip,
771
+ light = 0.1,
772
+ bent = false,
773
+ interior = 0.3,
774
+ } = look;
775
+ const material = new MeshStandardNodeMaterial({
776
+ metalness: 0,
777
+ // Double-sided: the far side of a spruce from across a meadow is mostly the backs of its
778
+ // cards, and a single-sided crown shows its own absence there.
779
+ side: DoubleSide,
780
+ });
781
+ material.alphaTest = cutout;
782
+ material.alphaToCoverage = true;
783
+ if (atlas === undefined) {
784
+ material.colorNode = vec3(0.09, 0.24, 0.11);
785
+ // A needle is waxy, not varnished, and rougher than the bark below it on purpose.
786
+ material.roughness = 0.96;
787
+ sway(material, seconds, WIND.amplitude.crown);
788
+ lightNeedles(material, bent ? attribute<"float">("inner", "float") : float(1));
789
+ return material;
790
+ }
791
+ const mip = mipLevels(atlas);
792
+ const card = texture(atlas);
793
+ const solid = smoothstep(float(ramp.from), float(ramp.to), mip.area);
794
+ material.map = atlas;
795
+ material.alphaTestNode = mipCompensatedCutoff(mip.worst, cutout);
796
+ // The card's own occlusion: how much sky a texel buried in the spray can see. This is the
797
+ // "near-black undersides" fix as a *texture* rather than as a colour lift — the interior of a
798
+ // spray is darker than its fringe because its neighbours are in the way, which is a fact about
799
+ // the geometry of the needles rather than a constant.
800
+ const occlusion =
801
+ arms !== undefined ? texture(arms).r : relief === undefined ? float(1) : texture(relief).b;
802
+ // New growth at the tips is lighter than the shaded interior: the same gradient the grass has,
803
+ // driven by the sway weight, which is a share of the tree's own height. Both ends stay under 1 —
804
+ // a tint above white is not a lighter needle, it is a blown highlight.
805
+ const needle = card.rgb
806
+ .mul(
807
+ mix(
808
+ vec3(...TIP_ROOT),
809
+ vec3(...(tip ?? TIP_TIP)),
810
+ smoothstep(float(0.15), float(0.95), attribute<"float">("sway", "float")),
811
+ ),
812
+ )
813
+ .mul(occlusion)
814
+ // The fringe of a cut texel is the atlas's empty colour bleeding in through the filter, which is
815
+ // pale: dark it toward the needle so a spray's edge is a needle tip rather than a white hairline.
816
+ .mul(mix(float(0.45), float(1), smoothstep(float(cutout * 0.6), float(0.92), card.a)))
817
+ // Deep inside the crown a needle sees little sky: the trunk end of a branch is the dark of a
818
+ // spruce, and its tips are where the light is.
819
+ .mul(bent ? mix(float(interior), float(1), attribute<"float">("inner", "float")) : float(1))
820
+ .mul(tint ? vec3(...tint) : vec3(1));
821
+ // The floor. Nothing in a canopy is black: a needle in the shade is lit by the needles around it
822
+ // and by the ground under the tree, so the shaded half of a crown has to keep a floor or it goes
823
+ // to ink against the sky. It is a *scale* towards the colour's own peak, not a per-channel
824
+ // maximum: a floor applied per channel lifts a dark needle's blue and red along with its green,
825
+ // and the darkest texels come out grey.
826
+ //
827
+ // And it is the floor of *this* atlas, which is why it is a parameter. The lift is
828
+ // `floor / peak`, so an absolute floor is only neutral for an atlas whose needles peak just above
829
+ // it: the generated atlas peaks at 0.167 linear and the shared 0.14 floor barely touches it,
830
+ // while the pine's peak at 0.106 takes a one-in-three lift on its average texel and up to five on
831
+ // its darkest, which compresses the whole crown into one flat pale band. Measured from each
832
+ // atlas, not guessed.
833
+ const peak = needle.r.max(needle.g).max(needle.b).max(float(0.0001));
834
+ const lifted = needle.mul(float(floor).div(peak).max(float(1)));
835
+ // The ramp fills in the needle that has already survived the test, and never the gap beside it.
836
+ //
837
+ // `mix(card.a, 1, solid)` on its own is wrong in a way that only shows up once a surface uses the
838
+ // ramp early: it raises a *transparent* texel towards solid, and it does so before the discard
839
+ // runs, so every distant tree becomes an opaque slab of its own colour standing in the meadow.
840
+ // Gating the fill on the texel already being above the cutoff keeps the intent — a crown that
841
+ // gains density with distance — and loses only the part that was never foliage.
842
+ const filled = mix(
843
+ card.a,
844
+ float(1),
845
+ solid.mul(smoothstep(float(cutout), float(cutout).mul(8), card.a)),
846
+ );
847
+ material.colorNode = vec4(lifted, filled);
848
+ if (relief !== undefined) {
849
+ // Poly Haven's twig atlas carries a real tangent-space normal, so it goes in as one; the
850
+ // generated atlas carries a height field instead, and `bumpMap` turns that into relief.
851
+ if (arms === undefined) material.normalNode = bumpMap(texture(relief), float(0.55));
852
+ else material.normalMap = relief;
853
+ }
854
+ // The bent crown normal is the geometry's own (see `spruce.ts`), unflipped on the back face. The
855
+ // relief bump above perturbs that same geometry normal, so volume and relief are one node and
856
+ // the map survives. Replacing the node with the bare geometry normal after the fact discarded
857
+ // the relief — a crown of flat cards — so it is only the fallback for a crown whose art carries
858
+ // no relief at all, and never overwrites a map the art did carry.
859
+ if (bent && material.normalNode === null && material.normalMap === null)
860
+ material.normalNode = normalViewGeometry;
861
+ if (arms !== undefined) material.roughnessNode = texture(arms).g.mul(0.35).add(0.6);
862
+ else material.roughness = 0.96;
863
+ // And the light coming *through* the card, which the standard shading cannot produce.
864
+ lightNeedles(
865
+ material,
866
+ occlusion.mul(bent ? attribute<"float">("inner", "float") : float(1)),
867
+ light * 5.5,
868
+ );
869
+ sway(material, seconds, WIND.amplitude.crown);
870
+ return material;
871
+ }
872
+
873
+ /**
874
+ * Bracken: each card one photographed frond, cut by the atlas's own alpha.
875
+ *
876
+ * The same cut as the needles — Golus's mip compensation, so a frond at forty metres keeps its
877
+ * leaflets instead of eroding to a stalk — and the same thin backlight a leaf one cell thick has. The
878
+ * vertex colour is only the clump's own root shade; the green is the photograph's.
879
+ */
880
+ function frondMaterial(
881
+ diffuse: Texture | undefined,
882
+ alpha: Texture | undefined,
883
+ seconds: Node<"float">,
884
+ ): MeshStandardNodeMaterial {
885
+ const material = new MeshStandardNodeMaterial({
886
+ metalness: 0,
887
+ roughness: 0.85,
888
+ side: DoubleSide,
889
+ });
890
+ if (diffuse === undefined || alpha === undefined) {
891
+ material.colorNode = vec3(0.08, 0.2, 0.06);
892
+ } else {
893
+ const shade = attribute<"vec3">("color", "vec3");
894
+ material.alphaTest = 0.4;
895
+ material.alphaToCoverage = true;
896
+ material.alphaTestNode = mipCompensatedCutoff(mipLevels(alpha).worst, 0.4);
897
+ // A touch cooler and darker than the scan: under a spruce a fern is in the canopy's shade.
898
+ material.colorNode = vec4(
899
+ texture(diffuse)
900
+ .rgb.mul(shade)
901
+ .mul(vec3(0.82, 0.92, 0.78)),
902
+ texture(alpha).r,
903
+ );
904
+ material.emissiveNode = canopyTranslucency(0.06);
905
+ }
906
+ sway(material, seconds, WIND.amplitude.grass);
907
+ return material;
908
+ }
909
+
910
+ /** The colour a poppy is at the far edge of a meadow, where its petal is a handful of texels. */
911
+ const POPPY_RED = 0xd41f16;
912
+
913
+ /** What a petal transmits: the sun through one cell of pigment, which is red and not green. */
914
+ const PETAL_RED_TINT = 0xd8523a;
915
+
916
+ /** Every prop surface, plus the one uniform the wind reads. */
917
+ export interface IPropSurfaces {
918
+ readonly advance: (elapsed: number) => void;
919
+ /**
920
+ * The live textures an imported image can replace, by `<surface>.<channel>`. The same texture
921
+ * objects the materials sample, so a swap changes what they draw and adds no sampler.
922
+ */
923
+ readonly inputs: Record<string, Texture | undefined>;
924
+ readonly dispose: () => void;
925
+ readonly materials: IPropMaterials;
926
+ }
927
+
928
+ /**
929
+ * Give a cutout surface the image-based light its silhouette needs.
930
+ *
931
+ * A cutout PBR material with no environment anywhere in the scene is what the engine prints
932
+ * `TN_UNLIT_FOLIAGE` for: a needle card and its back face fall on one flat hemisphere value and
933
+ * the crown reads as a painted board. The imported pack carries this per material because the
934
+ * scene's own environment was reverted (it washed the ground white); the procedural starter draws
935
+ * its own surfaces, so it has to carry the same light. One helper, so the two paths cannot drift.
936
+ */
937
+ export function skyEnvironment(material: MeshStandardNodeMaterial, sky: Texture): void {
938
+ material.envMap = sky;
939
+ material.envMapIntensity = 1.13;
940
+ }
941
+
942
+ /**
943
+ * Build every prop surface, loading the starter maps in the background.
944
+ *
945
+ * A map that never arrives leaves the prop drawn on its own colours rather than missing: the trunk is
946
+ * still a trunk and the needles are still needles, which is the difference between a host with no
947
+ * asset server and a broken scene.
948
+ */
949
+ export async function createPropSurfaces(
950
+ assets?: IAssetLoader,
951
+ ground?: IPropGround,
952
+ biome?: IWorldBiome,
953
+ skyLight?: Texture,
954
+ ): Promise<IPropSurfaces> {
955
+ const seconds = uniform(0).setGroup(renderGroup) as unknown as Node<"float">;
956
+ const under = ground === undefined ? undefined : groundHeight(ground);
957
+ const [fernDiffuse, fernAlpha] = await Promise.all([
958
+ map(assets, FERN_MAPS.diffuse, false),
959
+ map(assets, FERN_MAPS.alpha, true),
960
+ ]);
961
+ const soil = await map(
962
+ assets,
963
+ biome !== undefined && !biome.lawnGround ? biome.maps.grass.diffuse : SOIL_MAP,
964
+ false,
965
+ );
966
+ const [bark, stone, atlas, relief] = await Promise.all([
967
+ surfaceMaps(assets, PROP_MAPS.bark),
968
+ (async () => {
969
+ const set = biome?.dryStones
970
+ ? DRY_STONE_MAPS
971
+ : biome?.crestRock
972
+ ? {
973
+ diffuse: biome.maps.rock.diffuse,
974
+ normal: biome.maps.rock.normal ?? PROP_MAPS.stone.normal,
975
+ }
976
+ : biome?.mossGround
977
+ ? {
978
+ diffuse: "lichen_rock/lichen_rock_diff_512.jpg",
979
+ normal: "lichen_rock/lichen_rock_nor_gl_512.jpg",
980
+ }
981
+ : PROP_MAPS.stone;
982
+ const [diffuse, normal, arm] = await Promise.all([
983
+ map(assets, set.diffuse, false, true),
984
+ map(assets, set.normal, true, true),
985
+ biome?.dryStones ? map(assets, DRY_STONE_MAPS.arm, true, true) : undefined,
986
+ ]);
987
+ return { diffuse, normal, arm };
988
+ })(),
989
+ map(assets, NEEDLE_ATLAS, false),
990
+ map(assets, NEEDLE_SURFACE, true),
991
+ ]);
992
+ const rockSnow =
993
+ biome?.stoneSnow === true ? await map(assets, biome.maps.snow.diffuse, false) : undefined;
994
+ const textures: Texture[] = [
995
+ ...(rockSnow ? [rockSnow] : []),
996
+ ...(under ? [under.texture] : []),
997
+ ...(soil ? [soil] : []),
998
+ ...[fernDiffuse, fernAlpha].filter((found): found is Texture => found !== undefined),
999
+ bark.diffuse,
1000
+ bark.normal,
1001
+ bark.roughness,
1002
+ stone.diffuse,
1003
+ stone.normal,
1004
+ stone.arm,
1005
+ atlas,
1006
+ relief,
1007
+ ].filter((found): found is Texture => found !== undefined);
1008
+
1009
+ const barkMaterial = new MeshStandardNodeMaterial({ metalness: 0, roughness: 0.95 });
1010
+ if (bark.diffuse === undefined) barkMaterial.colorNode = vec3(0.26, 0.15, 0.11);
1011
+ else {
1012
+ barkMaterial.map = bark.diffuse;
1013
+ // Bark Brown 02 is a dark, damp-looking bark, and a spruce trunk spends most of its visible
1014
+ // length inside its own crown's shadow: untinted it renders as a black pole with a silhouette.
1015
+ // The lift is warm and well under 2, which keeps the plates legible without turning the trunk
1016
+ // into a highlight.
1017
+ // A set colorNode replaces `map`, so the lift multiplies the sampled bark instead of standing in for it.
1018
+ // Warmer than the texture: with the crown lifted off the trunk (`SPRUCE.standBareTrunk`) the
1019
+ // trunk is most of what a stand shows below eye level, and the Fab spruce's trunks read
1020
+ // orange-brown: a shaded Fab trunk at `meadow-close` is sRGB (92, 72, 58), where the old lift
1021
+ // (1.85, 1.7, 1.55) left a near-black pole (34, 37, 35); this one reads (58, 53, 42).
1022
+ barkMaterial.colorNode = texture(bark.diffuse).rgb.mul(vec3(5.2, 3.7, 2.6));
1023
+ // The root flare dies into the soil instead of meeting it at a clean bark line.
1024
+ intoGround(
1025
+ barkMaterial,
1026
+ barkMaterial.colorNode as Node<"vec3">,
1027
+ groundShare(under?.node),
1028
+ soil,
1029
+ false,
1030
+ );
1031
+ }
1032
+ if (bark.normal !== undefined) barkMaterial.normalMap = bark.normal;
1033
+ if (bark.roughness !== undefined) barkMaterial.roughnessMap = bark.roughness;
1034
+ sway(barkMaterial, seconds, WIND.amplitude.bark);
1035
+
1036
+ // A Norway spruce is a dark blue-green, not the atlas's yellow-olive: the grade pulls red and blue down
1037
+ // and keeps green, and the higher cut lets the fringe of each spray break up into needles instead of
1038
+ // closing into a smooth-edged paddle.
1039
+ const crownMaterial = needleMaterial(atlas, relief, undefined, seconds, {
1040
+ bent: true,
1041
+ cutout: 0.52,
1042
+ // Low, because the floor is a lift *to* this level: at the shared 0.14 every needle darker than it
1043
+ // comes out exactly 0.14, and a crown whose texels all share one brightness is a flat paddle with
1044
+ // the needle detail scaled away.
1045
+ floor: 0.004,
1046
+ // Half the shared glow: with the crown lit as a volume its sun side already faces the light, and
1047
+ // the full translucency on top of that washed the near trees out to pale grey-green.
1048
+ light: 0.05,
1049
+ // Matched to the Fab spruce at `meadow-close` (PRD-870, 2026-11-10), tree band, sky dropped: the
1050
+ // middle tenth went from sRGB (65, 88, 66) to (56, 69, 63) against Fab's (47, 55, 44), the
1051
+ // darkest from (43, 61, 52) to (38, 49, 47) against (22, 30, 28). The floor 0.03 lifted every
1052
+ // texel of this grade to one value, which is what made the crown a flat paddle; the rest of the
1053
+ // gap is the mist and sky fill both arms share (a black crown still reads (63, 63, 68) at the
1054
+ // overview), not the needle.
1055
+ tint: [0.3, 0.36, 0.26],
1056
+ tip: [1.4, 1.25, 0.8],
1057
+ interior: 0.05,
1058
+ });
1059
+ const firMaps = await Promise.all([
1060
+ map(assets, FIR_MAPS.surface, false),
1061
+ map(assets, FIR_MAPS.normal, true),
1062
+ map(assets, FIR_MAPS.arms, true),
1063
+ ]);
1064
+ textures.push(...firMaps.filter((found): found is Texture => found !== undefined));
1065
+ // The prepared fir cuts against its own atlas, so it needs its own instance of the same
1066
+ // surface: two atlases are two textures, and a shared material could only sample one of them.
1067
+ const needlesMaterial = needleMaterial(firMaps[0], firMaps[1], firMaps[2], seconds);
1068
+
1069
+ sway(needlesMaterial, seconds, WIND.amplitude.crown);
1070
+
1071
+ // The procedural pine and the card that stands in for it past the last band, on no atlas: the
1072
+ // forest's own trees are the scanned broadleaf, and these only dress the procedural fallback.
1073
+ const pineMaterial = needleMaterial(undefined, undefined, undefined, seconds, PINE_LOOK);
1074
+ // The far card is the same crown seen from far enough away to be a mass, so it is the same shader
1075
+ // with the ramp pulled forward: at the distances it draws at, a pine is not a spray of needles.
1076
+ const impostorMaterial = needleMaterial(undefined, undefined, undefined, seconds, {
1077
+ ...PINE_LOOK,
1078
+ cutout: IMPOSTOR.cutoff,
1079
+ ramp: { from: IMPOSTOR.from, to: IMPOSTOR.to },
1080
+ });
1081
+
1082
+ const grassMaterial = new MeshStandardNodeMaterial({
1083
+ metalness: 0,
1084
+ roughness: 0.93,
1085
+ side: DoubleSide,
1086
+ vertexColors: true,
1087
+ });
1088
+ // Sun through a blade. A grass blade is one cell thick and translucent, and the light that comes
1089
+ // through the top half of it is most of what a meadow looks lit by — the vertex colour already
1090
+ // grades every blade from a dark root to a bright tip, so the tip's share of that light is a
1091
+ // channel away, and no second texture is spent on it.
1092
+ const blade = attribute<"vec3">("color", "vec3");
1093
+ grassMaterial.emissiveNode = canopyTranslucency(0.16).mul(blade.g.mul(2.2).min(float(1)));
1094
+ sway(grassMaterial, seconds, WIND.amplitude.grass);
1095
+
1096
+ const stemMaterial = new MeshStandardNodeMaterial({
1097
+ metalness: 0,
1098
+ roughness: 0.9,
1099
+ side: DoubleSide,
1100
+ vertexColors: true,
1101
+ });
1102
+ // A poppy's stem and its leaves are as translucent as its petals, and a patch whose stems are
1103
+ // black rods under red flowers reads as wires with beads on them.
1104
+ stemMaterial.emissiveNode = canopyTranslucency(0.1);
1105
+ sway(stemMaterial, seconds, WIND.amplitude.stem);
1106
+
1107
+ const petalMaterial = new MeshStandardNodeMaterial({
1108
+ metalness: 0,
1109
+ roughness: 0.74,
1110
+ side: DoubleSide,
1111
+ });
1112
+ petalMaterial.alphaTest = CUTOUT;
1113
+ petalMaterial.alphaToCoverage = true;
1114
+ if (atlas === undefined) petalMaterial.colorNode = vec3(0.72, 0.09, 0.08);
1115
+ else {
1116
+ // A poppy is five centimetres across: at any distance past twenty metres its petal is a handful
1117
+ // of texels, and a cutout that keeps only the texels which happen to clear the threshold is a
1118
+ // grey smudge where a red one should be. The same coverage ramp the crown uses is what makes a
1119
+ // patch of poppies read as red at the far edge of a meadow.
1120
+ const mip = mipLevels(atlas);
1121
+ const petal = texture(atlas);
1122
+ const solid = smoothstep(float(SOLID.from), float(SOLID.to), mip.area);
1123
+ petalMaterial.map = atlas;
1124
+ petalMaterial.alphaTestNode = mipCompensatedCutoff(mip.worst, CUTOUT);
1125
+ // The colour goes with the coverage: a petal cell is mostly empty, so its mip average is a dark
1126
+ // red, and a patch of poppies that goes solid at sixty metres would go black with it. The
1127
+ // sampled colour is faded into the red the game wants at that distance instead.
1128
+ petalMaterial.colorNode = vec4(
1129
+ mix(petal.rgb, color(POPPY_RED), solid),
1130
+ mix(petal.a, float(1), solid),
1131
+ );
1132
+ // A poppy petal is the most translucent thing in a meadow and the most saturated, and it is the
1133
+ // one surface whose colour has to survive the tone curve: lit by the fill alone, a dark red
1134
+ // petal takes the sky's blue and a patch of poppies goes violet, which is what the first capture
1135
+ // of this lane showed. Light comes *through* a petal, so it is emissive, and by exactly as much
1136
+ // as the distance fade asks for.
1137
+ // A poppy petal is the most translucent thing in a meadow, so it gets the same two-sided
1138
+ // wrap the canopy does — at a higher share, because a petal is one cell of pigment thin — with
1139
+ // the distance fade still folded in, so a patch stays red rather than violet at the far edge.
1140
+ petalMaterial.emissiveNode = canopyTranslucency(0.09, PETAL_RED_TINT).add(
1141
+ color(POPPY_RED).mul(float(0.1).add(solid.mul(0.34))),
1142
+ );
1143
+ }
1144
+ sway(petalMaterial, seconds, WIND.amplitude.petal);
1145
+
1146
+ const stoneMaterial = stoneSurface(stone);
1147
+ // Cast the sun-facing surface: back-face depth leaves a lit strip at the sand intersection.
1148
+ if (biome?.stoneFrontFace) stoneMaterial.shadowSide = FrontSide;
1149
+ if (biome?.propStoneTint && stoneMaterial.colorNode)
1150
+ stoneMaterial.colorNode = (
1151
+ stone.diffuse ? (stoneMaterial.colorNode as Node<"vec3">) : vec3(0.4, 0.35, 0.3)
1152
+ ).mul(vec3(...biome.propStoneTint));
1153
+ if (biome?.propStoneTint && stoneMaterial.colorNode) {
1154
+ const albedo = stoneMaterial.colorNode as Node<"vec3">;
1155
+ const far = smoothstep(45, 140, length(cameraPosition.sub(positionWorld)));
1156
+ const luminance = dot(albedo, vec3(0.2126, 0.7152, 0.0722));
1157
+ const ceiling = dot(vec3(...biome.distantStone), vec3(0.2126, 0.7152, 0.0722));
1158
+ stoneMaterial.colorNode = albedo.mul(
1159
+ mix(1, ceiling.div(luminance.max(ceiling).max(0.0001)), far),
1160
+ );
1161
+ }
1162
+ const rockGround = await createRockGround(assets, ground, biome);
1163
+ const materials: IPropMaterials = {
1164
+ bark: barkMaterial,
1165
+ crown: crownMaterial,
1166
+ fern: frondMaterial(fernDiffuse, fernAlpha, seconds),
1167
+ grass: grassMaterial,
1168
+ impostor: impostorMaterial,
1169
+ needles: needlesMaterial,
1170
+ petal: petalMaterial,
1171
+ pine: pineMaterial,
1172
+ stem: stemMaterial,
1173
+ stone: stoneMaterial,
1174
+ };
1175
+ if (biome !== undefined && !biome.lawnGround) {
1176
+ // colorNode already consumes blade colour; Three must not multiply it a second time.
1177
+ grassMaterial.vertexColors = false;
1178
+ grassMaterial.colorNode = blade.mul(vec3(...biome.propGrassTint));
1179
+ grassMaterial.emissiveNode = vec3(0);
1180
+ if (!biome.propStoneTint && stoneMaterial.colorNode)
1181
+ stoneMaterial.colorNode = (stoneMaterial.colorNode as Node<"vec3">).mul(
1182
+ vec3(...biome.stoneTint),
1183
+ );
1184
+ }
1185
+ if (biome?.crestRock) {
1186
+ const rock = stone.diffuse ? alpineRockAlbedo(stone.diffuse) : vec3(0.42, 0.43, 0.38);
1187
+ const snow = rockSnow ? texture(rockSnow, positionWorld.xz.div(12)).rgb : vec3(0.82, 0.86, 0.9);
1188
+ stoneMaterial.colorNode = mix(
1189
+ alpineRockColor(rock),
1190
+ snow.mul(vec3(...biome.snowTint)),
1191
+ smoothstep(0.12, 0.82, alpineSnowCover(biome)),
1192
+ );
1193
+ }
1194
+ if (biome?.mossGround) {
1195
+ stoneMaterial.colorNode = (stoneMaterial.colorNode as Node<"vec3">).mul(1.35);
1196
+ const cover =
1197
+ biomeWeights(
1198
+ biome,
1199
+ float(1).sub(normalWorldGeometry.y),
1200
+ float(0),
1201
+ bakedNoise(positionWorld.mul(0.05)),
1202
+ ).snow ?? float(0);
1203
+ const snow = rockSnow ? texture(rockSnow, positionWorld.xz.div(12)).rgb : vec3(0.82, 0.86, 0.9);
1204
+ const side = stoneMaterial.colorNode as Node<"vec3">;
1205
+ stoneMaterial.emissiveNode = side.mul(0.18).mul(float(1).sub(cover));
1206
+ stoneMaterial.colorNode = mix(side, snow.mul(vec3(...biome.snowTint)), cover);
1207
+ stoneMaterial.normalNode = normalize(
1208
+ mix(
1209
+ (stoneMaterial.normalNode as Node<"vec3"> | null) ??
1210
+ transformNormalToView(normalWorldGeometry),
1211
+ transformNormalToView(normalWorldGeometry),
1212
+ cover,
1213
+ ),
1214
+ );
1215
+ if (skyLight) skyEnvironment(stoneMaterial, skyLight);
1216
+ }
1217
+ // Albedo-coloured ground bounce keeps unlit beach faces legible without another texture tap.
1218
+ if (biome?.propStoneTint && stoneMaterial.colorNode)
1219
+ stoneMaterial.emissiveNode = (stoneMaterial.colorNode as Node<"vec3">).mul(0.07);
1220
+ rockGround?.apply(stoneMaterial);
1221
+ // The alpha-cut, double-sided surfaces: a needle card, a frond, a petal. Without an image-based
1222
+ // light each is a flat paddle, which is the paperboard the engine warns about at scene entry.
1223
+ if (skyLight)
1224
+ for (const role of ["crown", "needles", "pine", "impostor", "fern", "petal"] as const)
1225
+ skyEnvironment(materials[role] as MeshStandardNodeMaterial, skyLight);
1226
+ let disposed = false;
1227
+ return {
1228
+ inputs: {
1229
+ "bark.albedo": bark.diffuse,
1230
+ "bark.normal": bark.normal,
1231
+ "bark.roughness": bark.roughness,
1232
+ "stone.albedo": stone.diffuse,
1233
+ "stone.normal": stone.normal,
1234
+ },
1235
+ advance: (elapsed: number) => {
1236
+ (seconds as unknown as { value: number }).value = elapsed;
1237
+ },
1238
+ dispose: () => {
1239
+ if (disposed) return;
1240
+ disposed = true;
1241
+ for (const material of Object.values(materials) as Material[]) material.dispose();
1242
+ for (const texture of textures) texture.dispose();
1243
+ rockGround?.dispose();
1244
+ },
1245
+ materials,
1246
+ };
1247
+ }