@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,1114 @@
1
+ import {
2
+ type IAssetLoader,
3
+ baseGeometryOf,
4
+ lodChainOf,
5
+ normaliseToMetres,
6
+ thinCards,
7
+ } from "@threenative/core";
8
+
9
+ import {
10
+ type IMeshSection,
11
+ bakedNoise,
12
+ instanceRandom,
13
+ meshSections,
14
+ repairZeroNormals,
15
+ sectionGeometry,
16
+ } from "@threenative/core/world";
17
+ import {
18
+ Box3,
19
+ BufferAttribute,
20
+ type BufferGeometry,
21
+ DataTexture,
22
+ DataUtils,
23
+ DoubleSide,
24
+ EquirectangularReflectionMapping,
25
+ FrontSide,
26
+ type Group,
27
+ LinearFilter,
28
+ type Material,
29
+ type Mesh,
30
+ type MeshStandardMaterial,
31
+ RedFormat,
32
+ RepeatWrapping,
33
+ type Texture,
34
+ Vector3,
35
+ } from "three";
36
+ import { HDRLoader } from "three/addons/loaders/HDRLoader.js";
37
+ import {
38
+ attribute,
39
+ cameraProjectionMatrix,
40
+ cameraViewMatrix,
41
+ dFdx,
42
+ dFdy,
43
+ dot,
44
+ float,
45
+ length,
46
+ log2,
47
+ max,
48
+ mix,
49
+ normalMap,
50
+ normalViewGeometry,
51
+ normalWorldGeometry,
52
+ positionGeometry,
53
+ positionLocal,
54
+ positionView,
55
+ positionWorld,
56
+ sin,
57
+ smoothstep,
58
+ texture,
59
+ time,
60
+ uniform,
61
+ uv,
62
+ vec2,
63
+ vec3,
64
+ vec4,
65
+ } from "three/tsl";
66
+ import { MeshPhysicalNodeMaterial, type Node } from "three/webgpu";
67
+ import { GROUND_MAPS, ROCKFACE_MAPS } from "../../world/terrainAssets.js";
68
+ import { biomeSpec } from "../biomeData.js";
69
+ import {
70
+ BIOMES,
71
+ type IBiome,
72
+ type IWorldBiome,
73
+ type WorldName,
74
+ alpineRockAlbedo,
75
+ alpineRockColor,
76
+ alpineSnowCover,
77
+ biomeWeights,
78
+ desertRockColor,
79
+ measureBiome,
80
+ } from "../biomes.js";
81
+ import { LOOK } from "../lookKnobs.js";
82
+ import { WORLD } from "../worldNames.js";
83
+ import {
84
+ type IPropGround,
85
+ createRockGround,
86
+ lightNeedles,
87
+ skyEnvironment,
88
+ } from "./propMaterials.js";
89
+ import type { IPropPart, PropRole } from "./props.js";
90
+
91
+ export interface IPackSpecies {
92
+ readonly asset: string;
93
+ readonly variant: number;
94
+ readonly path: string;
95
+ readonly metres: number;
96
+ readonly level?: number;
97
+ }
98
+ /** Independent same-asset probes; omitted fields keep the current forest appearance. */
99
+ export interface ICanopyComparison {
100
+ /** Forest crown normals; other worlds already retain their imported geometry normals. */
101
+ readonly normals?: "radial" | "authored";
102
+ readonly specular?: "disabled" | "standard";
103
+ }
104
+ /** Fail closed so a labelled comparison cannot silently capture the current appearance. */
105
+ export function canopyComparison(
106
+ normals: string | null,
107
+ specular: string | null,
108
+ ): ICanopyComparison {
109
+ if (normals !== null && normals !== "radial" && normals !== "authored")
110
+ throw new Error(`Unsupported canopyNormals '${normals}'`);
111
+ if (specular !== null && specular !== "disabled" && specular !== "standard")
112
+ throw new Error(`Unsupported canopySpecular '${specular}'`);
113
+ return { normals: normals ?? "authored", specular: specular ?? "disabled" };
114
+ }
115
+ /**
116
+ * The alpine stand: Arbor Norway spruce and black spruce, grown by the bake's `world.arbor` rows in `recipe.json` (the conifer
117
+ * bake-off winner), at five heights (metres, crown top). Near the treeline at 1900-2000 m a Norway
118
+ * spruce stands 10-17 m. Each variant is a near GLB (lod 1) and a mid GLB (lod 2).
119
+ */
120
+ const STAND: readonly (readonly [string, number])[] = [
121
+ ["alpine_flora/spruce-a", 14],
122
+ ["alpine_flora/spruce-b", 16],
123
+ ["alpine_flora/blackspruce-a", 10],
124
+ ["alpine_flora/spruce-c", 12],
125
+ ["alpine_flora/blackspruce-b", 11],
126
+ ];
127
+ const species: IPackSpecies[] = [];
128
+ STAND.forEach(([tree, metres], variant) => {
129
+ species.push({ asset: "spruce", variant, path: `${tree}-near.glb`, metres });
130
+ species.push({ asset: "spruce", variant, path: `${tree}-mid.glb`, metres, level: 1 });
131
+ });
132
+ for (const [asset, heights] of Object.entries({
133
+ sapling: [1.1, 2.1, 3.0, 1.6],
134
+ grass: [0.3, 0.55, 0.75, 0.45],
135
+ /** The meadow's dense base layer (`meadowCover`): Open World Demo field grass and a low mat. */
136
+ meadow: [0.42, 0.3],
137
+ scrub: [0.085, 0.065, 0.018],
138
+ poppy: [0.38, 0.5, 0.42, 0.4],
139
+ bloom: [0.35, 0.5, 0.4, 0.45],
140
+ fern: [0.7, 0.6, 0.85],
141
+ bush: [0.9, 0.55],
142
+ litter: [0.42, 0.55],
143
+ boulder: [2.1, 5.2, 2.5],
144
+ riverrock: [0.8],
145
+ scree: [5.8],
146
+ cliff: [18],
147
+ /** Fallen wood (`cover.understorey.deadfall`): its scans are `POLYHAVEN_FLOOR.deadfall`. */
148
+ deadfall: [3.1, 4.0, 1.6, 1.1],
149
+ mountain: [24, 24],
150
+ })) {
151
+ heights.forEach((metres, variant) =>
152
+ species.push({ asset, variant, metres, path: `${asset}/${variant}` }),
153
+ );
154
+ }
155
+ // The alpine species the forest pack does not know: the stand's Arbor conifers for the two the box names,
156
+ // field grass for its tundra cover, shrubs for fireweed and blueberry, and scanned boulders for its
157
+ // erratics. Metres are each scan's own size, as the pack's other rows are.
158
+ for (const row of [
159
+ {
160
+ asset: "scotspine",
161
+ metres: 11,
162
+ paths: ["alpine_flora/spruce-c-near.glb", "alpine_flora/spruce-a-near.glb"],
163
+ },
164
+ {
165
+ asset: "blackspruce",
166
+ metres: 8,
167
+ paths: ["alpine_flora/blackspruce-a-near.glb", "alpine_flora/blackspruce-b-near.glb"],
168
+ },
169
+ { asset: "tundragrass", metres: 0.35, paths: ["grass_medium/tuft.glb", "grass_medium/mat.glb"] },
170
+ { asset: "tussock", metres: 0.5, paths: ["grass_medium/field.glb", "grass_medium/reed.glb"] },
171
+ { asset: "fireweed", metres: 0.6, paths: ["shrub_02/shrub_02_c.glb", "shrub_02/shrub_02_d.glb"] },
172
+ {
173
+ asset: "blueberry",
174
+ metres: 0.35,
175
+ paths: ["shrub_02/shrub_02_b.glb", "shrub_02/shrub_02_a.glb"],
176
+ },
177
+ { asset: "rock", metres: 1.5, paths: ["rocks/rock01-near.glb", "rocks/rock04-near.glb"] },
178
+ ] as const)
179
+ row.paths.forEach((path, variant) =>
180
+ species.push({ asset: row.asset, variant, path, metres: row.metres }),
181
+ );
182
+ /**
183
+ * The forest floor's Poly Haven CC0 scans (`packages/terrain/starter-assets`), as [GLB, metres] per
184
+ * variant: dead trunks, a stump and an upturned root plate for the deadfall, dry branches for the
185
+ * litter, weeds and moss for the ground mounds, shrubs and a nettle where the spruce saplings stood,
186
+ * celandine, dandelion and periwinkle where the meadow flowers stood, and the kit's own fern
187
+ * (owner, 2026-11-14: "not enough ground/debris/trunks vegetation on the floor"). Metres are each scan's own size, near enough.
188
+ */
189
+ const POLYHAVEN_FLOOR: Record<string, readonly (readonly [string, number])[]> = {
190
+ deadfall: [
191
+ ["dead_tree_trunk/dead_tree_trunk.glb", 3.1],
192
+ // dead_tree_trunk_02 is not drawn: it was scanned propped on a branch, so it floats on flat ground.
193
+ ["dead_tree_trunk/dead_tree_trunk.glb", 4.0],
194
+ ["tree_stump_01/tree_stump_01.glb", 1.6],
195
+ // root_cluster_01 is not drawn: its 4.1 x 2.7 m root plate cut through trunks and lay on slopes as a slab.
196
+ ["tree_stump_01/tree_stump_01.glb", 1.1],
197
+ ],
198
+ litter: [
199
+ ["dry_branches_medium_01/dry_branches_medium_01_a.glb", 0.34],
200
+ ["dry_branches_medium_01/dry_branches_medium_01_b.glb", 0.14],
201
+ ],
202
+ scrub: [
203
+ ["weed_plant_02/weed_plant_02_a.glb", 0.07],
204
+ ["weed_plant_02/weed_plant_02_b.glb", 0.07],
205
+ ["moss_01/moss_01_tall_b.glb", 0.04],
206
+ ],
207
+ bush: [
208
+ ["shrub_02/shrub_02_d.glb", 1.2],
209
+ ["shrub_04/shrub_04.glb", 0.3],
210
+ ],
211
+ sapling: [
212
+ ["shrub_02/shrub_02_a.glb", 1.7],
213
+ ["shrub_02/shrub_02_b.glb", 1.5],
214
+ ["shrub_02/shrub_02_c.glb", 1.3],
215
+ ["nettle_plant/nettle_plant_tall_a.glb", 0.5],
216
+ ],
217
+ poppy: [
218
+ ["celandine_01/celandine_01_a.glb", 0.25],
219
+ ["celandine_01/celandine_01_b.glb", 0.2],
220
+ ["dandelion_01/dandelion_01_a.glb", 0.22],
221
+ ["celandine_01/celandine_01_e.glb", 0.18],
222
+ ],
223
+ bloom: [
224
+ ["periwinkle_plant/periwinkle_plant_02.glb", 0.4],
225
+ ["dandelion_01/dandelion_01_b.glb", 0.16],
226
+ ["celandine_01/celandine_01_d.glb", 0.2],
227
+ ["periwinkle_plant/periwinkle_plant_05.glb", 0.22],
228
+ ],
229
+ // Stone: the kit's Poly Haven `boulder_01` (its authored LOD1, LOD2 where it is scaled past a
230
+ // boulder or seen small), by its longest side.
231
+ boulder: [
232
+ ["boulder_01/boulder-near.glb", 2.1],
233
+ ["boulder_01/boulder-mid.glb", 5.2],
234
+ ["boulder_01/boulder-near.glb", 2.5],
235
+ ],
236
+ riverrock: [["boulder_01/boulder-mid.glb", 0.8]],
237
+ scree: [["boulder_01/boulder-mid.glb", 5.8]],
238
+ cliff: [["boulder_01/boulder-near.glb", 18]],
239
+ mountain: [
240
+ ["boulder_01/boulder-near.glb", 24],
241
+ ["boulder_01/boulder-near.glb", 24],
242
+ ],
243
+ fern: [
244
+ ["fern_02/fern-a.glb", 0.55],
245
+ ["fern_02/fern-b.glb", 0.5],
246
+ ["fern_02/fern-a.glb", 0.75],
247
+ ],
248
+ };
249
+ /**
250
+ * The grass: Poly Haven CC0 grass_medium_01/02 baked to crossed cards on one atlas
251
+ * (`scripts/prep/prep-polyhaven-grass.py`), as [GLB, metres tall] per variant at the licensed
252
+ * rows' heights: a field patch for the field grass, tufts and a reed for the Grass Library tufts, and
253
+ * a low clump for the mat.
254
+ */
255
+ const POLYHAVEN_GRASS: Record<string, readonly (readonly [string, number])[]> = {
256
+ grass: [
257
+ ["grass_medium/field.glb", 0.3],
258
+ ["grass_medium/tuft.glb", 0.55],
259
+ ["grass_medium/reed.glb", 0.75],
260
+ ["grass_medium/tuft.glb", 0.45],
261
+ ],
262
+ meadow: [
263
+ ["grass_medium/field.glb", 0.42],
264
+ ["grass_medium/mat.glb", 0.3],
265
+ ],
266
+ };
267
+ /** The species drawn as stone: they stand on their lowest point and take a hull collider. */
268
+ export const STONE = new Set(["boulder", "riverrock", "scree", "cliff", "mountain"]);
269
+ /** Meadow Flowers species: photographed petals kept, stems lifted, no foliage tint. */
270
+ const FLOWERS = new Set(["poppy", "bloom"]);
271
+ /** Needle-card triangles one far spruce draws past LOD_BANDS.far (its middle level draws 0.8-4.7k). */
272
+ const FAR_NEEDLE_TRIANGLES = 1500;
273
+
274
+ // Per tree, not per draw slot: WorldCells repacks instances as the player walks.
275
+ const phase = instanceRandom().mul(6.2831);
276
+ const gust = sin(time.mul(0.1).add(phase));
277
+
278
+ /** What one imported section is, before any appearance decision: its art and its niche. */
279
+ interface ISurfaceContext {
280
+ readonly source: MeshStandardMaterial;
281
+ readonly asset: string;
282
+ readonly world: WorldName;
283
+ readonly look: IBiome;
284
+ readonly biome?: IWorldBiome;
285
+ readonly stone: boolean;
286
+ readonly cutout: boolean;
287
+ readonly canopy: boolean;
288
+ readonly fieldGrass: boolean;
289
+ readonly otherBiome: boolean;
290
+ }
291
+
292
+ /** Imported foliage draws as imported: its albedo, its normal map, its own cutoff, both faces. */
293
+ /**
294
+ * Imported normal maps whose green channel is DirectX (Unreal) rather than glTF's OpenGL, measured
295
+ * per material by a curl test on the staged maps (2026-10-08). Every other imported map is OpenGL.
296
+ */
297
+ const DIRECTX_NORMALS =
298
+ /^(branch|MI_LargePlainsBoulder002|MI_Large_VolcanicRock_002|ScotsPine_01_.*)$/u;
299
+
300
+ /**
301
+ * GLTFLoader flips `normalScale.y` for a mesh without tangents, which none of the cooked meshes
302
+ * carry; a rebuilt material that copies only `normalMap` loses that flip and lights every relief
303
+ * from the mirrored side. Keep it, and undo it for the DirectX-authored maps.
304
+ */
305
+ function copyNormalScale(material: MeshPhysicalNodeMaterial, source: MeshStandardMaterial): void {
306
+ material.normalScale.copy(source.normalScale);
307
+ if (DIRECTX_NORMALS.test(source.name)) material.normalScale.y *= -1;
308
+ }
309
+
310
+ function importedFoliage(
311
+ material: MeshPhysicalNodeMaterial,
312
+ source: MeshStandardMaterial,
313
+ map: Texture,
314
+ ): void {
315
+ const sampled = texture(map, uv());
316
+ map.anisotropy = 8;
317
+ material.normalMap = source.normalMap;
318
+ copyNormalScale(material, source);
319
+ material.roughness = 0.92;
320
+ // The Kite field grass is authored dark for Unreal's exposure (Wildwood lifts such packs ~3x); drawn raw
321
+ // it read as a blue-black carpet.
322
+ material.colorNode = sampled.rgb.mul(source.name === "open-world-demo" ? 3 : 1);
323
+ material.alphaTest = source.alphaTest;
324
+ material.alphaTestNode = float(source.alphaTest);
325
+ material.opacityNode = sampled.a;
326
+ material.side = DoubleSide;
327
+ material.shadowSide = DoubleSide;
328
+ }
329
+
330
+ /**
331
+ * Moss, snow and the upward-face mask a stone section wears over its own albedo.
332
+ *
333
+ * Alpine keeps the heightfield's upward-face mask across mesh seams; tundra uses its ground rule.
334
+ */
335
+ function stoneSurface(
336
+ material: MeshPhysicalNodeMaterial,
337
+ context: ISurfaceContext,
338
+ snowMap?: Texture,
339
+ ): void {
340
+ const { source, look } = context;
341
+ if (look.stoneFrontFace) material.shadowSide = FrontSide;
342
+ // An alpine look's erratics are the massif's limestone: the red-brown scan pulled to its grey.
343
+ if (look.alpinePasture) {
344
+ const albedo = material.colorNode as Node<"vec3">;
345
+ const grey = vec3(dot(albedo, vec3(0.2126, 0.7152, 0.0722))).mul(vec3(...look.stoneTint));
346
+ material.colorNode = mix(albedo, grey.mul(2), look.stoneGrey);
347
+ }
348
+ const growth = smoothstep(-0.15, 0.3, bakedNoise(positionWorld.mul(2.1)));
349
+ const moss = normalWorldGeometry.y.max(0).mul(growth).mul(look.stoneMoss);
350
+ material.colorNode = mix(material.colorNode as Node<"vec3">, vec3(...look.stoneMossTint), moss);
351
+ if (!look.stoneSnow) return;
352
+ const biome = context.biome;
353
+ if (!biome) throw new RangeError("Stone snow requires measured terrain elevations");
354
+ const snow = look.crestRock
355
+ ? smoothstep(0.12, 0.82, alpineSnowCover(biome))
356
+ : (biomeWeights(biome, float(1).sub(normalWorldGeometry.y), float(0), growth)
357
+ .snow as Node<"float">);
358
+ material.colorNode = mix(
359
+ material.colorNode as Node<"vec3">,
360
+ look.crestRock
361
+ ? (snowMap ? texture(snowMap, positionWorld.xz.div(12)).rgb : vec3(0.82, 0.86, 0.9)).mul(
362
+ vec3(...biome.snowTint),
363
+ )
364
+ : vec3(...look.stoneSnowTint),
365
+ snow,
366
+ );
367
+ material.roughnessNode = mix(0.96, 0.82, snow);
368
+ if (source.normalMap)
369
+ material.normalNode = normalMap(texture(source.normalMap), vec2(mix(1, 0.2, snow)));
370
+ }
371
+
372
+ /** Needle pixels nearer the lens than this are cut, in metres. */
373
+ const CANOPY_NEAR = 1.2;
374
+ /** Bark is cut only at the lens: a limb sliced further out shows a hollow, sawn end. */
375
+ const BARK_NEAR = 0.4;
376
+ /** Radius of the sight line kept clear of tree pixels from the lens to the hero, in metres. */
377
+ const SIGHT_RADIUS = 1.2;
378
+
379
+ /**
380
+ * The hero the orbit camera aims at, in world space. `game.ts` writes `aim` each frame and sets
381
+ * `radius` to {@link SIGHT_RADIUS} while the player view is live, 0 for the fixed views.
382
+ */
383
+ export const sightLine = { aim: uniform(new Vector3()), radius: uniform(0) };
384
+ /** The waterline rocks stand in the river bed. */
385
+ export const RIVER_BED = true;
386
+ export { SIGHT_RADIUS };
387
+
388
+ /**
389
+ * The orbit camera swings through crowns: a branch a metre from the lens fills the screen, and a
390
+ * stand between the lens and the hero hides the hero. Needles near the lens, and on the line from
391
+ * the lens to the hero, are eroded, as a third-person camera fades the occluders of its character
392
+ * (UE's CameraDepthFade into the opacity mask). The fade scales the needle alpha before the 4x MSAA
393
+ * alpha-to-coverage test, so cards thin from their tips inward over a metre: a hard cut drew a
394
+ * sharp circle, and slicing branches with it drew their hollow ends as rings round the hero.
395
+ * Bark takes only a short cut at the lens (a sliced limb reads hollow); branches stay whole.
396
+ * An orthographic view (P[3][3] = 1) is a shadow page or the impostor baker, so it keeps the tree.
397
+ */
398
+ export function nearCameraFade(material: MeshPhysicalNodeMaterial, needles: boolean): void {
399
+ const ortho = cameraProjectionMatrix.mul(vec4(0, 0, 0, 1)).w.greaterThan(0.5);
400
+ if (!needles) {
401
+ material.maskNode = ortho.or(length(positionView).greaterThanEqual(BARK_NEAR));
402
+ return;
403
+ }
404
+ const aim = cameraViewMatrix.mul(vec4(sightLine.aim, 1)).xyz;
405
+ const along = dot(positionView, aim).div(dot(aim, aim).max(1e-4));
406
+ const off = length(positionView.sub(aim.mul(along.clamp(0, 1))));
407
+ // 1 keeps the needle; radius 0 (a fixed view) keeps every needle off the line.
408
+ const sight = smoothstep(0.8, 1.7, off.div(sightLine.radius.max(1e-3))).max(
409
+ smoothstep(0.9, 1.05, along),
410
+ );
411
+ const lens = smoothstep(CANOPY_NEAR * 0.5, CANOPY_NEAR * 1.5, length(positionView));
412
+ const keep = sight.min(lens).max(ortho.select(float(1), float(0)));
413
+ material.opacityNode = ((material.opacityNode as Node<"float"> | null) ?? float(1)).mul(keep);
414
+ }
415
+
416
+ /** The coverage, interior depth and normal a cut-out section is drawn with. */
417
+ function cutoutSurface(
418
+ material: MeshPhysicalNodeMaterial,
419
+ context: ISurfaceContext,
420
+ sampled: Node<"vec4">,
421
+ ): void {
422
+ const { source, asset, look, canopy, otherBiome } = context;
423
+ // Shadow overrides and VirtualShadowNode classify cutouts by this scalar, not the node.
424
+ material.alphaTest = source.alphaTest;
425
+ // The scene pass is 4x MSAA: coverage from alpha smooths card edges that a hard test speckles.
426
+ material.alphaToCoverage = true;
427
+ material.side = DoubleSide;
428
+ material.shadowSide = DoubleSide;
429
+ if (canopy) {
430
+ const inner = attribute<"float">("inner", "float");
431
+ const shape = look.canopyLinearInner ? inner : inner.pow(2);
432
+ material.colorNode = (material.colorNode as Node<"vec3">).mul(
433
+ mix(look.canopyInnerShade, 1, shape),
434
+ );
435
+ material.aoNode = mix(look.canopyAmbientOcclusion[0], look.canopyAmbientOcclusion[1], shape);
436
+ // The bent crown normal is the geometry's own (radial, from `addRadialCoverage`); the imported
437
+ // normal map perturbs that same geometry normal. Installing the bare geometry normal as
438
+ // `normalNode` replaced the normal node and discarded the map, so the crown shaded as one flat
439
+ // card. The custom path only fills in where the art carries no map — an imported surface sets
440
+ // `normalMap` and leaves the node to Three, which also applies the texture's own packing.
441
+ if (look.crownGeometryNormals && !source.normalMap) material.normalNode = normalViewGeometry;
442
+ } else if (FLOWERS.has(asset)) {
443
+ // Keep the photographed red petals; lift only the nearly black stems/seed pods.
444
+ const dark = smoothstep(0.045, 0.008, sampled.r.max(sampled.g).max(sampled.b));
445
+ material.colorNode = mix(
446
+ material.colorNode as Node<"vec3">,
447
+ vec3(0.028, 0.055, 0.009),
448
+ dark.mul(0.75),
449
+ );
450
+ material.emissiveNode = (material.colorNode as Node<"vec3">).mul(0.045);
451
+ } else if (source.normalMap && !look.mats) {
452
+ // Ground foliage keeps photographed relief around its bent, upward leaf normal.
453
+ const relief = texture(source.normalMap, uv()).xy.mul(2).sub(1).mul(0.45);
454
+ material.normalNode = vec3(relief.x, 1, relief.y)
455
+ .normalize()
456
+ .transformDirection(cameraViewMatrix);
457
+ }
458
+ const image = source.map?.image as { width?: number; height?: number } | undefined;
459
+ const size = vec2(image?.width ?? 2048, image?.height ?? 2048);
460
+ const mip = max(
461
+ log2(max(length(dFdx(uv()).mul(size)), length(dFdy(uv()).mul(size))).max(1)),
462
+ float(0),
463
+ );
464
+ // Low tundra mats must reject blurred photographic background in alpha mips.
465
+ material.alphaTestNode =
466
+ look.mats && !canopy
467
+ ? float(0.5)
468
+ : float(look.authoredAlphaTest ? source.alphaTest : 0.42).div(float(1).add(mip.mul(0.25)));
469
+ material.opacityNode = sampled.a;
470
+ material.maskShadowNode = sampled.a.greaterThan(material.alphaTestNode as Node<"float">);
471
+ // Keep the authored scalar for cutout classification and impostor capture.
472
+ material.userData.tnImpostorAlphaTest = source.alphaTest;
473
+ if (canopy) {
474
+ lightNeedles(material, material.aoNode as Node<"float">);
475
+ if (!otherBiome) material.emissiveNode = (material.emissiveNode as Node<"vec3">).mul(0.18);
476
+ if (look.canopyEmissiveScale !== null && material.emissiveNode)
477
+ material.emissiveNode = (material.emissiveNode as Node<"vec3">).mul(look.canopyEmissiveScale);
478
+ } else if (!FLOWERS.has(asset))
479
+ material.emissiveNode = (material.colorNode as Node<"vec3">).mul(0.025);
480
+ }
481
+
482
+ /** Imported albedo graded per niche, then stone, cutout and coverage. */
483
+ function tintedFoliage(
484
+ material: MeshPhysicalNodeMaterial,
485
+ context: ISurfaceContext,
486
+ snowMap?: Texture,
487
+ ): void {
488
+ const { source, asset, look, stone, cutout, canopy, fieldGrass, otherBiome } = context;
489
+ const map = source.map as Texture;
490
+ map.anisotropy = 8;
491
+ const sampled = texture(map, uv());
492
+ // Cooked albedo is already sRGB (KTX2 DFD transfer=2); never apply a second decode or lift.
493
+ const tint =
494
+ cutout && canopy
495
+ ? look.canopyTint
496
+ : cutout && !FLOWERS.has(asset)
497
+ ? look.bladeTint
498
+ : FLOWERS.has(asset)
499
+ ? ([1, 1, 0.85] as const)
500
+ : canopy && source.name === "branch"
501
+ ? ([0.26, 0.21, 0.15] as const)
502
+ : ([1, 1, 1] as const);
503
+
504
+ material.colorNode = sampled.rgb.mul(vec3(...tint));
505
+ if (!otherBiome && canopy && !cutout)
506
+ // A limb is photographed pale and smooth: lit by the low sun it drew as a tan tube beside the
507
+ // dark trunk it grows from, so it takes about half the trunk's value.
508
+ material.colorNode = sampled.rgb.mul(
509
+ source.name === "branch"
510
+ ? vec3(0.11, 0.1, 0.085).mul(LOOK.limb)
511
+ : vec3(0.2, 0.18, 0.15).mul(LOOK.bark),
512
+ );
513
+ if (!otherBiome && (asset === "grass" || asset === "meadow" || asset === "scrub")) {
514
+ const tip = smoothstep(0.008, asset === "scrub" ? 0.065 : 0.34, positionGeometry.y);
515
+ const dry = smoothstep(0.65, 0.92, sin(phase).mul(0.5).add(0.5));
516
+ const dune = look.shoreGround ? smoothstep(7.5, 2.2, positionWorld.y) : float(0);
517
+ const green = mix(vec3(0.32, 0.48, 0.18), vec3(0.84, 0.92, 0.46), tip);
518
+ const straw = mix(vec3(0.4, 0.29, 0.12), vec3(1.18, 0.94, 0.48), tip);
519
+ const grain = dot(sampled.rgb, vec3(0.2126, 0.7152, 0.0722));
520
+ material.colorNode = mix(sampled.rgb.mul(green), straw.mul(grain), dry.max(dune));
521
+ if (fieldGrass)
522
+ material.colorNode = mix(vec3(0.06, 0.1, 0.025), vec3(0.2, 0.31, 0.065), tip).mul(
523
+ grain.mul(24).clamp(0.4, 1.4),
524
+ );
525
+ material.aoNode = mix(fieldGrass ? 0.55 : 0.35, 0.95, tip);
526
+ }
527
+ if (otherBiome && stone) material.colorNode = sampled.rgb.mul(vec3(...look.stoneSectionTint));
528
+ if (look.mesaRock && stone) material.colorNode = desertRockColor(sampled.rgb);
529
+ if (look.crestRock && stone) material.colorNode = alpineRockColor(alpineRockAlbedo(map));
530
+ if (otherBiome && cutout && !canopy)
531
+ material.colorNode = sampled.rgb.mul(vec3(...look.cutoutTint));
532
+ if (look.strawBlades && asset === "grass")
533
+ material.colorNode = vec3(1.28, 0.94, 0.52).mul(dot(sampled.rgb, vec3(0.2126, 0.7152, 0.0722)));
534
+ if (look.mats && cutout && !canopy) {
535
+ const root = smoothstep(0.015, 0.14, positionGeometry.y);
536
+ material.colorNode = mix(vec3(0.025, 0.035, 0.013), material.colorNode, root);
537
+ material.aoNode = mix(0.15, 0.8, root);
538
+ }
539
+ if (stone) stoneSurface(material, context, snowMap);
540
+ if (cutout) cutoutSurface(material, context, sampled);
541
+ }
542
+
543
+ /** The wind a non-stone section bends with, per instance, from the geometry's own `sway` weights. */
544
+ function applyWind(material: MeshPhysicalNodeMaterial, context: ISurfaceContext): void {
545
+ if (context.stone) return;
546
+ const bend = gust.mul(positionGeometry.y.max(0).pow(1.5)).mul(windStiffness(context.asset));
547
+ const offset = vec3(
548
+ positionLocal.x.add(bend),
549
+ positionLocal.y,
550
+ positionLocal.z.add(bend.mul(0.55)),
551
+ );
552
+ material.positionNode = offset;
553
+ // Cached shadow pages cast the rest pose, so a page refresh redraws the same shadow (see propMaterials sway).
554
+ material.castShadowPositionNode = positionLocal;
555
+ }
556
+
557
+ function windStiffness(asset: string): number {
558
+ return asset === "spruce" ? 0.008 : 0.025;
559
+ }
560
+
561
+ /**
562
+ * engine-override: the farthest applyWind moves a vertex of this section, its top bent by a full gust
563
+ * along (1, 0, 0.55). The owned engine grows each instance's shadow box by it, so a virtual shadow page
564
+ * draws only the trees that can reach it instead of the whole forest.
565
+ */
566
+ function declareWindReach(
567
+ material: MeshPhysicalNodeMaterial,
568
+ asset: string,
569
+ geometry: BufferGeometry,
570
+ ): void {
571
+ geometry.computeBoundingBox();
572
+ const top = Math.max(0, geometry.boundingBox?.max.y ?? 0);
573
+ const reach = top ** 1.5 * windStiffness(asset) * Math.hypot(1, 0.55);
574
+ const swaying = material as MeshPhysicalNodeMaterial & { maxPositionOffset?: number };
575
+ swaying.maxPositionOffset = Math.max(swaying.maxPositionOffset ?? 0, reach);
576
+ }
577
+
578
+ function surface(
579
+ source: MeshStandardMaterial,
580
+ asset: string,
581
+ world: WorldName,
582
+ snowMap?: Texture,
583
+ skyLight?: Texture,
584
+ comparison?: ICanopyComparison,
585
+ biome?: IWorldBiome,
586
+ canopyCover?: Node<"float">,
587
+ ): MeshPhysicalNodeMaterial {
588
+ const stone = STONE.has(asset);
589
+ const cutout = !stone && source.alphaTest > 0;
590
+ const canopy = asset === "spruce" || asset === "sapling";
591
+ const fieldGrass = (asset === "grass" || asset === "meadow") && source.name === "open-world-demo";
592
+ const look = BIOMES[world];
593
+ const otherBiome = !look.lawnGround;
594
+ const context: ISurfaceContext = {
595
+ source,
596
+ asset,
597
+ world,
598
+ look,
599
+ biome,
600
+ stone,
601
+ cutout,
602
+ canopy,
603
+ fieldGrass,
604
+ otherBiome,
605
+ };
606
+ const material = new MeshPhysicalNodeMaterial({
607
+ map: source.map,
608
+ color: source.color,
609
+ normalMap: source.normalMap,
610
+ roughness: stone ? 0.96 : 1,
611
+ specularIntensity: canopy
612
+ ? comparison?.specular === "standard"
613
+ ? 1
614
+ : 0
615
+ : look.mats && cutout
616
+ ? 0
617
+ : cutout
618
+ ? 0.02
619
+ : 0.3,
620
+ metalness: 0,
621
+ });
622
+ copyNormalScale(material, source);
623
+ if (!otherBiome && canopy && !cutout) material.normalMap = source.normalMap;
624
+ // Forest needle crowns need their authored interior shading and filtered alpha coverage.
625
+ // A plain imported PBR card erased canopy depth at the same geometry and camera.
626
+ if (cutout && source.map && !(look.woodCanopy && canopy)) {
627
+ importedFoliage(material, source, source.map);
628
+ if (look.woodCanopy && (asset === "grass" || asset === "meadow")) {
629
+ // One photograph per species reads as astroturf: each clump takes its own value about 1 and
630
+ // a green-to-dry hue from its instance hash, and its root sinks into the soil's shade.
631
+ const clump = sin(phase.mul(3.7)).mul(0.5).add(0.5);
632
+ const shade = mix(vec3(0.62, 0.86, 0.5), vec3(0.98, 0.96, 0.52), clump.mul(clump));
633
+ // Drifts metres across: a meadow is darker in its damp patches and paler on its dry ones.
634
+ const drift = mix(0.78, 1.08, smoothstep(-0.4, 0.4, bakedNoise(positionWorld.mul(0.11))));
635
+ // Part of a meadow has gone to seed: straw patches tens of metres across break the one green,
636
+ // on a slower field than the drift so the two do not line up.
637
+ const straw = smoothstep(
638
+ 0.2,
639
+ 0.6,
640
+ bakedNoise(
641
+ vec3(positionWorld.x, 0, positionWorld.z)
642
+ .mul(0.027)
643
+ .add(vec3(31, 0, 17)),
644
+ ),
645
+ );
646
+ const seeded = mix(vec3(1, 1, 1), vec3(1.32, 1.08, 0.6), straw.mul(0.6));
647
+ // A blade is dark where it leaves the thatch and brightest at its tip.
648
+ // A tuft stands three times as tall as the field grass, so the same 0.32 m ramp left nearly
649
+ // all of it at full value above a field that sits inside its own root shade: its ramp runs
650
+ // the tuft's own height.
651
+ const root = mix(0.34, 1, smoothstep(0.0, fieldGrass ? 0.32 : 0.8, positionGeometry.y));
652
+ // The tall tufts are photographed far paler than the field grass they stand in: bring them
653
+ // to the same sward so a tuft reads as taller grass, not as a lit paper cut-out.
654
+ const sward = fieldGrass ? vec3(1, 1, 1) : vec3(0.5, 0.62, 0.4);
655
+ material.colorNode = (material.colorNode as Node<"vec3">)
656
+ .mul(shade)
657
+ .mul(drift)
658
+ .mul(root)
659
+ .mul(sward)
660
+ .mul(seeded);
661
+ material.aoNode = mix(0.5, 1, smoothstep(0.0, 0.25, positionGeometry.y));
662
+ // A blade card stands upright, so its own normal faces the horizon and half the cards face
663
+ // away from the sun: those drew black beside sunlit ones. A meadow shades as the ground it
664
+ // grows from, so every blade takes the up normal and the sun's shadow still falls across it.
665
+ material.normalNode = vec3(0, 1, 0).transformDirection(cameraViewMatrix);
666
+ }
667
+ if (look.woodCanopy && asset === "fern") {
668
+ // A frond drew lime beside the sward it grows in: it takes a deeper green, each plant its own
669
+ // value, and the heart of the plant sinks into the shade of its own fronds.
670
+ const each = mix(0.85, 1.08, sin(phase.mul(2.3)).mul(0.5).add(0.5));
671
+ const heart = mix(0.5, 1, smoothstep(0.0, 0.4, positionGeometry.y));
672
+ material.colorNode = (material.colorNode as Node<"vec3">)
673
+ .mul(vec3(0.5, 0.66, 0.38))
674
+ .mul(each)
675
+ .mul(heart);
676
+ material.aoNode = mix(0.5, 1, smoothstep(0.0, 0.3, positionGeometry.y));
677
+ }
678
+ if (look.woodCanopy && FLOWERS.has(asset)) {
679
+ // A flower model carries its own leaves, photographed pale mint: beside the sward they drew
680
+ // as white paper rosettes (paint-by-species capture, 2026-11-09). The green texels take the
681
+ // sward's green and sink at the plant's heart; a petal, redder than it is green, keeps its
682
+ // photograph.
683
+ const sampled = material.colorNode as Node<"vec3">;
684
+ const leaf = smoothstep(0.0, 0.06, sampled.g.sub(sampled.r));
685
+ const heart = mix(0.45, 1, smoothstep(0.0, 0.3, positionGeometry.y));
686
+ material.colorNode = mix(sampled, sampled.mul(vec3(0.5, 0.66, 0.4)).mul(heart), leaf);
687
+ }
688
+ if (look.swardTint && !FLOWERS.has(asset))
689
+ material.colorNode = (material.colorNode as Node<"vec3">).mul(LOOK.sward);
690
+ if (look.woodCanopy) {
691
+ // Blades and fronds a cell thick pass the sun through; without it a meadow seen against the
692
+ // sun is lit almost only by the sky. Same shadowed term as the needles, without their fill.
693
+ // Roots and the gaps between blades stay dark; the upper blade carries the glow.
694
+ lightNeedles(material, smoothstep(0.02, 0.4, positionGeometry.y), 0.4);
695
+ material.emissiveNode = null;
696
+ }
697
+ } else if (source.map) tintedFoliage(material, context, snowMap);
698
+ // River rock lies on the waterline, and wet stone is darker and glossier: water fills the pores
699
+ // (albedo about halves) and films the surface (roughness falls). `?riverbed=off`: dry, as before.
700
+ if (asset === "riverrock" && RIVER_BED && material.colorNode) {
701
+ material.colorNode = (material.colorNode as Node<"vec3">).mul(0.45);
702
+ material.roughness = 0.32;
703
+ }
704
+ applyWind(material, context);
705
+ if (canopy) nearCameraFade(material, cutout);
706
+ // Image-based sky light, as Wildwood lights the same Fab packs (Kloofendal at 1.8 × 0.629).
707
+ // Without it a shaded needle card gets only the hemisphere fill and falls to one flat dark value.
708
+ // Per material, not `scene.environment`: the ground is tuned to the fill alone and cannot opt out.
709
+ if (skyLight && !stone) skyEnvironment(material, skyLight);
710
+ // At full sky light a forest crown is ~85% lit by sky and emissive, so it shows no sun side.
711
+ if (skyLight && look.woodCanopy && canopy) material.envMapIntensity = 0.35;
712
+ // A plant under the crowns sees the sky through a few gaps: its ambient and sky-image light fall
713
+ // to the row's share where the baked canopy closes over it, and the sun's own light is untouched,
714
+ // so a sunlit meadow keeps its full sky and a fern in deep shade stops glowing.
715
+ if (canopyCover && look.understoreySkyLight !== undefined && !canopy && !stone)
716
+ material.aoNode = ((material.aoNode as Node<"float"> | null) ?? float(1)).mul(
717
+ mix(float(1), LOOK.plantShade, smoothstep(0.05, 0.6, canopyCover)),
718
+ );
719
+ return material;
720
+ }
721
+
722
+ /**
723
+ * The photograph's sun disc (peak luminance ~72,559, 81° from the scene sun) gave the meadow 44% of
724
+ * its light from a second, unshadowed key light. The scene's own sun is the key; the image keeps only
725
+ * its sky, so every texel is capped at a luminance of 30.
726
+ */
727
+ const SKY_LUMINANCE_CAP = 30;
728
+ function clampSkySun(sky: Texture): void {
729
+ const image = sky.image as { data: Uint16Array | Float32Array; width: number; height: number };
730
+ const data = image.data;
731
+ const half = data instanceof Uint16Array;
732
+ const read = (i: number) =>
733
+ half ? DataUtils.fromHalfFloat(data[i] as number) : (data[i] as number);
734
+ const write = (i: number, v: number) => {
735
+ data[i] = half ? DataUtils.toHalfFloat(v) : v;
736
+ };
737
+ const channels = data.length / (image.width * image.height);
738
+ for (let i = 0; i < data.length; i += channels) {
739
+ const r = read(i);
740
+ const g = read(i + 1);
741
+ const b = read(i + 2);
742
+ const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
743
+ if (luminance <= SKY_LUMINANCE_CAP) continue;
744
+ const scale = SKY_LUMINANCE_CAP / luminance;
745
+ write(i, r * scale);
746
+ write(i + 1, g * scale);
747
+ write(i + 2, b * scale);
748
+ }
749
+ }
750
+
751
+ /**
752
+ * The sky's diffuse light as two colours: the cosine-weighted mean radiance of the upper hemisphere
753
+ * (what a level surface receives) and of the lower one (the bounce a surface facing down receives).
754
+ * A rough surface shows little more of image-based light than this, and two colours cost no sampler.
755
+ */
756
+ export function skyIrradiance(sky: Texture): {
757
+ up: [number, number, number];
758
+ down: [number, number, number];
759
+ } {
760
+ const image = sky.image as { data: Uint16Array | Float32Array; width: number; height: number };
761
+ const data = image.data;
762
+ const half = data instanceof Uint16Array;
763
+ const read = (i: number) =>
764
+ half ? DataUtils.fromHalfFloat(data[i] as number) : (data[i] as number);
765
+ const channels = data.length / (image.width * image.height);
766
+ const up = [0, 0, 0];
767
+ const down = [0, 0, 0];
768
+ let upWeight = 0;
769
+ let downWeight = 0;
770
+ for (let row = 0; row < image.height; row += 2) {
771
+ // Equirectangular rows run from the zenith (row 0) to the nadir.
772
+ const theta = ((row + 0.5) / image.height) * Math.PI;
773
+ const y = Math.cos(theta);
774
+ const solid = Math.sin(theta);
775
+ for (let column = 0; column < image.width; column += 2) {
776
+ const i = (row * image.width + column) * channels;
777
+ const weight = Math.abs(y) * solid;
778
+ const target = y >= 0 ? up : down;
779
+ target[0] = (target[0] ?? 0) + read(i) * weight;
780
+ target[1] = (target[1] ?? 0) + read(i + 1) * weight;
781
+ target[2] = (target[2] ?? 0) + read(i + 2) * weight;
782
+ if (y >= 0) upWeight += weight;
783
+ else downWeight += weight;
784
+ }
785
+ }
786
+ const mean = (c: number[], w: number): [number, number, number] => [
787
+ (c[0] ?? 0) / (w || 1),
788
+ (c[1] ?? 0) / (w || 1),
789
+ (c[2] ?? 0) / (w || 1),
790
+ ];
791
+ return { up: mean(up, upWeight), down: mean(down, downWeight) };
792
+ }
793
+
794
+ let skyLight: Promise<Texture | undefined> | undefined;
795
+ /** The CC0 sky photograph, loaded once; absent locally, vegetation keeps the fill alone. */
796
+ export function loadSkyLight(assets: IAssetLoader): Promise<Texture | undefined> {
797
+ skyLight ??= assets
798
+ .resolve("hdri/kloofendal_48d_partly_cloudy_2k.hdr")
799
+ .then(async ([url]) => {
800
+ if (!url) return undefined;
801
+ const sky = await new HDRLoader().loadAsync(url);
802
+ sky.mapping = EquirectangularReflectionMapping;
803
+ clampSkySun(sky);
804
+ return sky;
805
+ })
806
+ .catch(() => undefined);
807
+ return skyLight;
808
+ }
809
+
810
+ /** Per-world reshape for one asset, applied on top of the shared whole-model scale. */
811
+ const WORLD_ASSET_SCALES: Record<string, Record<string, readonly [number, number, number]>> = {
812
+ tundra: { grass: [1.35, 1, 1.35], bush: [0.18, 1, 0.18], scrub: [1.1, 2, 1.1] },
813
+ coastal: { grass: [0.55, 1.35, 0.55] },
814
+ forest: { poppy: [1, 1.4, 1] },
815
+ };
816
+ /** A reshape every world applies to one asset. */
817
+ const ASSET_SCALES: Record<string, readonly [number, number, number]> = {
818
+ spruce: [1.12, 1, 1.12],
819
+ };
820
+
821
+ /** Every step is a diagonal scale, so the order the reshapes run in cannot change the result. */
822
+ function scaleGeometry(
823
+ geometry: BufferGeometry,
824
+ asset: string,
825
+ world: WorldName,
826
+ size: Vector3,
827
+ ): void {
828
+ const look = BIOMES[world];
829
+ const worldScale = WORLD_ASSET_SCALES[world]?.[asset];
830
+ if (worldScale) geometry.scale(worldScale[0], worldScale[1], worldScale[2]);
831
+ const assetScale = ASSET_SCALES[asset];
832
+ if (assetScale) geometry.scale(assetScale[0], assetScale[1], assetScale[2]);
833
+ // Alpine peaks are pinned to a 24 m longest axis after their mountain reshape.
834
+ if (look.pinnedCrags && asset === "mountain") {
835
+ geometry.scale(0.65, 1.45, 1.8);
836
+ const longest = Math.max(size.x * 0.65, size.y * 1.45, size.z * 1.8);
837
+ geometry.scale(24 / longest, 24 / longest, 24 / longest);
838
+ }
839
+ }
840
+
841
+ /** Radial coverage per height band: tips see sky, needles near the trunk do not. */
842
+ function addRadialCoverage(
843
+ geometry: BufferGeometry,
844
+ metres: number,
845
+ world: WorldName,
846
+ comparison?: ICanopyComparison,
847
+ ): void {
848
+ const positions = geometry.getAttribute("position");
849
+ const radii = new Float32Array(16);
850
+ const band = (i: number) =>
851
+ Math.min(15, Math.max(0, Math.floor((positions.getY(i) / metres) * 16)));
852
+ for (let i = 0; i < positions.count; i++)
853
+ radii[band(i)] = Math.max(
854
+ radii[band(i)] ?? 0,
855
+ Math.hypot(positions.getX(i), positions.getZ(i)),
856
+ );
857
+ const inner = Float32Array.from({ length: positions.count }, (_, i) =>
858
+ Math.min(
859
+ 1,
860
+ Math.hypot(positions.getX(i), positions.getZ(i)) / Math.max(0.1, radii[band(i)] ?? 0),
861
+ ),
862
+ );
863
+ geometry.setAttribute("inner", new BufferAttribute(inner, 1));
864
+ if (!BIOMES[world].crownGeometryNormals || comparison?.normals !== "radial") return;
865
+ // Keep synthetic crown normals as an explicit same-asset probe; the authored normals and normal
866
+ // map preserve needle lighting by default. Only this owned clone changes, never the cached asset.
867
+ const crownNormals = new Float32Array(positions.count * 3);
868
+ const direction = new Vector3();
869
+ for (let i = 0; i < positions.count; i++) {
870
+ direction
871
+ .set(positions.getX(i), Math.max(0.1, radii[band(i)] ?? 0) * 0.45, positions.getZ(i))
872
+ .normalize();
873
+ direction.toArray(crownNormals, i * 3);
874
+ }
875
+ geometry.setAttribute("normal", new BufferAttribute(crownNormals, 3));
876
+ }
877
+
878
+ /** One whole-model base and scale for all sections: scaling each part separately detached crowns. */
879
+ /**
880
+ * The model height a prop's base stands on. A starter-assets `.glb` is a Poly Haven scan whose origin
881
+ * is the ground it was scanned on, so a branch or root below y = 0 stays buried.
882
+ */
883
+ export function standingBase(box: Box3, path: string): number {
884
+ return path.endsWith(".glb") ? Math.max(box.min.y, 0) : box.min.y;
885
+ }
886
+
887
+ function prepareGeometry(
888
+ mesh: Mesh,
889
+ one: IPackSpecies,
890
+ world: WorldName,
891
+ stone: boolean,
892
+ box: Box3,
893
+ size: Vector3,
894
+ section: IMeshSection,
895
+ ): BufferGeometry {
896
+ // `spruce_full_03_low` ships zero normals; the repair runs after the reshape so they fit it.
897
+ const geometry = sectionGeometry(mesh, box, section, {
898
+ centreXZ: stone && BIOMES[world].lawnGround,
899
+ });
900
+ scaleGeometry(geometry, one.asset, world, size);
901
+ repairZeroNormals(geometry);
902
+ return geometry;
903
+ }
904
+
905
+ /**
906
+ * The species one world draws, read from its biome file: every cell row whose asset the file names,
907
+ * then the rocks of the west-coast scans it names, then a mat plain's own small bush.
908
+ *
909
+ * The file says which species live in the biome; this pack says what art each one is drawn with.
910
+ */
911
+ export function speciesFor(world: WorldName): IPackSpecies[] {
912
+ const look = BIOMES[world];
913
+ const held = new Set(biomeSpec(world).species);
914
+ // A mat plain grows one small scrub, not the temperate thicket pair.
915
+ const rows = look.scrubBush ? species.filter((one) => one.asset !== "bush") : species;
916
+ const selected = rows.filter((one) => held.has(one.asset));
917
+ if (look.scrubBush && held.has("bush"))
918
+ selected.push({ asset: "bush", variant: 0, path: "scrub/0", metres: 0.45 });
919
+ return selected.map((one) => {
920
+ const grass = look.lawnGround ? POLYHAVEN_GRASS[one.asset]?.[one.variant] : undefined;
921
+ const scan = grass ?? (look.lawnGround ? POLYHAVEN_FLOOR[one.asset]?.[one.variant] : undefined);
922
+ return scan ? { ...one, path: scan[0], metres: scan[1] } : one;
923
+ });
924
+ }
925
+
926
+ /** The baked crown weight, 0 in the open and about 1 under a closed stand, at a world position. */
927
+ function canopyCoverNode(ground: IPropGround, canopy: Float32Array): Node<"float"> {
928
+ const map = new DataTexture(
929
+ Uint8Array.from(canopy, (weight) => Math.round(Math.min(1, Math.max(0, weight)) * 255)),
930
+ ground.resolution,
931
+ ground.resolution,
932
+ RedFormat,
933
+ );
934
+ map.minFilter = LinearFilter;
935
+ map.magFilter = LinearFilter;
936
+ map.needsUpdate = true;
937
+ const at = positionWorld.xz
938
+ .div(float(ground.size))
939
+ .add(0.5)
940
+ .mul((ground.resolution - 1) / ground.resolution)
941
+ .add(0.5 / ground.resolution);
942
+ return texture(map, at).r;
943
+ }
944
+
945
+ export interface IPackProps {
946
+ readonly parts: Map<string, IPropPart[]>;
947
+ readonly dispose: () => void;
948
+ }
949
+ export async function loadPack(
950
+ assets?: IAssetLoader,
951
+ world: WorldName = WORLD,
952
+ ground?: IPropGround,
953
+ comparison?: ICanopyComparison,
954
+ biome?: IWorldBiome,
955
+ /** The baked crown weight per ground vertex (`scatter.canopy`), row-major like the heights. */
956
+ canopy?: Float32Array,
957
+ ): Promise<IPackProps> {
958
+ const measured = biome ?? (ground ? measureBiome(BIOMES[world], ground.heights) : undefined);
959
+ const look = BIOMES[world];
960
+ if (!measured && look.stoneSnow)
961
+ throw new RangeError("Stone snow requires measured terrain elevations");
962
+ const parts = new Map<string, IPropPart[]>();
963
+ const built: { geometry: BufferGeometry; material: Material }[] = [];
964
+ const selected = speciesFor(world);
965
+ const canopyCover = ground && canopy ? canopyCoverNode(ground, canopy) : undefined;
966
+ const rockface =
967
+ look.crestRock && assets
968
+ ? await Promise.all(
969
+ [ROCKFACE_MAPS.diffuse, ROCKFACE_MAPS.normal, GROUND_MAPS.snow.diffuse].map(
970
+ (path, index) =>
971
+ path
972
+ ? assets
973
+ .texture(path, { data: index === 1, wrap: RepeatWrapping })
974
+ .catch(() => undefined)
975
+ : undefined,
976
+ ),
977
+ )
978
+ : [];
979
+ const rockGround = await createRockGround(assets, ground, measured);
980
+ const sky = assets ? await loadSkyLight(assets) : undefined;
981
+ const loaded = await Promise.all(
982
+ selected.map(async (one) => {
983
+ // A species with no scan keeps its procedural part (`buildPropVariants`).
984
+ if (!assets || !one.path.endsWith(".glb")) return undefined;
985
+ try {
986
+ // The pack copies vertices, so the streamed coarse companion would never upgrade.
987
+ return await assets.model<{ scene?: Group }>(one.path, { whole: true });
988
+ } catch {
989
+ return undefined;
990
+ }
991
+ }),
992
+ );
993
+ loaded.forEach((gltf, index) => {
994
+ const one = selected[index];
995
+ const root = gltf?.scene;
996
+ if (!root || !one) return;
997
+ normaliseToMetres(root, {
998
+ metres: one.metres,
999
+ axis: STONE.has(one.asset) || one.asset === "deadfall" ? "longest" : "height",
1000
+ });
1001
+ const box = new Box3().setFromObject(root); // engine-override: center baked geometry after unit normalization
1002
+ const size = box.getSize(new Vector3());
1003
+ box.min.y = standingBase(box, one.path);
1004
+ const stone = STONE.has(one.asset);
1005
+ const entry = parts.get(`${one.asset}:${one.variant}`) ?? [];
1006
+ const horizon = new Map<IPropPart, BufferGeometry>();
1007
+ root.traverse((object) => {
1008
+ const mesh = object as Mesh;
1009
+ if (!mesh.isMesh) return;
1010
+ for (const section of meshSections(mesh)) {
1011
+ if (!section.material) continue;
1012
+ let source = section.material as MeshStandardMaterial;
1013
+ if (look.crestRock && stone && rockface[0]) {
1014
+ source = source.clone();
1015
+ source.map = rockface[0];
1016
+ source.normalMap = rockface[1] ?? null;
1017
+ }
1018
+ // The reduced Kite GLB keeps UVs but carries no textures. Reuse the matching near surface;
1019
+ // skipping those parts kept all 3,200 trees at full detail, even in the aerial view.
1020
+ const role: PropRole = stone ? "stone" : source.alphaTest > 0 ? "pine" : "bark";
1021
+ const inherited =
1022
+ one.asset === "spruce" && one.level
1023
+ ? entry.find((part) => (part.level ?? 0) === 0 && part.role === role)?.material
1024
+ : undefined;
1025
+ if (!source.map && one.level && !(inherited instanceof MeshPhysicalNodeMaterial)) continue;
1026
+ const geometry = prepareGeometry(mesh, one, world, stone, box, size, section);
1027
+ if (source.alphaTest > 0 && (one.asset === "spruce" || one.asset === "sapling"))
1028
+ addRadialCoverage(geometry, one.metres, world, comparison);
1029
+ const material =
1030
+ inherited instanceof MeshPhysicalNodeMaterial
1031
+ ? inherited
1032
+ : surface(
1033
+ source,
1034
+ one.asset,
1035
+ world,
1036
+ rockface[2],
1037
+ sky,
1038
+ comparison,
1039
+ measured,
1040
+ canopyCover,
1041
+ );
1042
+ if (stone) rockGround?.apply(material);
1043
+ else declareWindReach(material, one.asset, geometry);
1044
+ if (source !== section.material) source.dispose();
1045
+ built.push({ geometry, material });
1046
+ const part = { geometry, material, role, level: one.level ?? 0, variant: one.variant };
1047
+ entry.push(part);
1048
+ const rung =
1049
+ one.asset === "spruce" && one.level === 1 && source.alphaTest === 0 && !section.group
1050
+ ? lodChainOf(baseGeometryOf(mesh))?.levels.at(-1)?.index
1051
+ : undefined;
1052
+ if (rung) {
1053
+ const reduced = geometry.clone().setIndex(rung.clone());
1054
+ built.push({ geometry: reduced, material });
1055
+ horizon.set(part, reduced);
1056
+ }
1057
+ }
1058
+ });
1059
+ // Past LOD_BANDS.far the far spruce draws its cook's terminal rung (TN_discrete_lod) of the opaque
1060
+ // trunk and branch meshes, which stayed full detail at every distance: 7-17k of each tree's
1061
+ // 12-21k far triangles. Needle cards, which no simplifier can reduce, keep FAR_NEEDLE_TRIANGLES
1062
+ // of their cards at the same total area: in a stand, 8.7 M far card triangles cost 5 ms of GPU.
1063
+ if (horizon.size > 0)
1064
+ for (const part of entry.filter((candidate) => candidate.level === 1)) {
1065
+ let geometry = horizon.get(part) ?? part.geometry;
1066
+ if (part.role === "pine" && geometry.index) {
1067
+ // A multi-material section draws a range of a shared index: its own triangles set the share.
1068
+ const { start, count } = geometry.drawRange;
1069
+ const drawn = (Math.min(geometry.index.count, start + count) - start) / 3;
1070
+ geometry = thinCards(geometry, Math.min(1, FAR_NEEDLE_TRIANGLES / drawn));
1071
+ if (geometry !== part.geometry && part.material)
1072
+ built.push({ geometry, material: part.material });
1073
+ }
1074
+ entry.push({ ...part, geometry, level: 2 });
1075
+ }
1076
+ // The meadow mat reaches 220 m from the eye, where a mat is a few pixels: past LOD_BANDS.mid it
1077
+ // keeps a third of its blades and past far a tenth, each grown to hold the mat's area. UE grass
1078
+ // steps down its static mesh's own LODs the same way (UE 5.8.3:
1079
+ // Engine/Source/Runtime/Landscape/Classes/LandscapeGrassType.h:59-79, cull distances and MinLOD).
1080
+ // The field grass and the ferns step down the same way at their own nearer `LOD_STEPS`, where a
1081
+ // tuft is still a dozen pixels tall: they keep half their blades, then a quarter.
1082
+ const thinned =
1083
+ one.asset === "meadow"
1084
+ ? ([
1085
+ [1, 0.35],
1086
+ [2, 0.12],
1087
+ ] as const)
1088
+ : one.asset === "grass" || one.asset === "fern"
1089
+ ? ([
1090
+ [1, 0.5],
1091
+ [2, 0.25],
1092
+ ] as const)
1093
+ : undefined;
1094
+ if (thinned)
1095
+ for (const part of entry.filter((candidate) => (candidate.level ?? 0) === 0))
1096
+ for (const [level, keep] of thinned) {
1097
+ if (!part.geometry.index || part.geometry.groups.length > 0 || !part.material) continue;
1098
+ const geometry = thinCards(part.geometry, keep);
1099
+ built.push({ geometry, material: part.material });
1100
+ entry.push({ ...part, geometry, level });
1101
+ }
1102
+ if (entry.some((part) => (part.level ?? 0) === 0))
1103
+ parts.set(`${one.asset}:${one.variant}`, entry);
1104
+ });
1105
+ return {
1106
+ parts,
1107
+ dispose: () => {
1108
+ rockGround?.dispose();
1109
+ for (const one of built) one.geometry.dispose();
1110
+ for (const material of new Set(built.map((one) => one.material))) material.dispose();
1111
+ parts.clear();
1112
+ },
1113
+ };
1114
+ }