roamwright 0.61.24 → 0.61.26

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.
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Draped ground-patch material and mesh binder: compiles the procedural surface shader for trodden
3
+ * earth (scuffs, hoof/foot prints, wandering wheel ruts, flat dung), dried cracked clay plates,
4
+ * pooled stains and forest-floor leaf/needle litter, and meshes gathered patches together with
5
+ * instanced loose stones and droppings.
6
+ * @module
7
+ */
8
+
9
+ import * as THREE from 'three';
10
+ import { buildDrapePebbleGeometry, createGroundPatchData, drapeGroundPatch } from '../geometry/ground-drape.js';
11
+ import { TRS as defaultTransform } from '../geometry/primitives.js';
12
+ import { createNoise } from '../math/noise.js';
13
+ import { crustGLSL as CRUST_GLSL } from './crust.js';
14
+ import { defaultGrainTexture } from './paved-ground.js';
15
+ import { terrainReliefGLSL } from './terrain-rock.js';
16
+
17
+ const DEFAULT_GROUND_BUMP = 'normal = terrainReliefNormal(vViewPosition, normal, gTH, 7.0, vec2(8.0, 46.0));';
18
+
19
+ let fallbackFbm = null;
20
+ const defaultFbm = () => (fallbackFbm ??= createNoise().fbm);
21
+
22
+ /**
23
+ * Fragment shader snippet injected into `#include <color_fragment>` by {@link createGroundDrapeMaterial}
24
+ * to evaluate rim breakup, mottling, trodden scuffs/prints/ruts, drying crust cracks, liquid stains
25
+ * and fallen needle litter.
26
+ */
27
+ export const GROUND_DRAPE_FRAGMENT = /* glsl */ `
28
+ float pKind = vLook.x, pOut = vLook.y, pRuts = vLook.z;
29
+ float trod = 1.0 - step(0.5, pKind), dry = step(0.5, pKind) - step(1.5, pKind), soak = step(1.5, pKind) - step(2.5, pKind), leaf = step(2.5, pKind);
30
+ vec2 p = vWP.xz, ax = vec2(cos(vLook.w), sin(vLook.w)), across = vec2(-ax.y, ax.x);
31
+ float px = length(fwidth(p)); // metres a pixel spans here
32
+ float g0 = grainN(p * 0.59 + 0.21), g1 = grainN(p / 9.0), g2 = grainN(p * 0.0187 + 0.37), g3 = grainN(p * 0.0026 + 0.11);
33
+ float fineSeen = 1.0 - smoothstep(0.02, 0.06, px), midSeen = 1.0 - smoothstep(0.06, 0.25, px);
34
+ // the rim: thinned out in clumps that follow the ground's own grain, so it breaks up into the land instead of ending on a line
35
+ float clump = 0.4 * g2 + 0.3 * grainN(p * 0.11 + 0.53) + 0.2 * g1 + 0.1 * mix(0.5, g0, fineSeen);
36
+ diffuseColor.a = smoothstep(clump * 0.75, clump * 0.75 + 0.2 + px * 0.3, diffuseColor.a);
37
+ // colour that varies inside a patch at three scales: paces, a stride, a hand
38
+ diffuseColor.rgb *= (0.86 + 0.28 * g2) * (0.93 + 0.14 * g3) * mix(1.0, 0.84 + 0.32 * g0, fineSeen * (1.0 - 0.6 * soak));
39
+ gTH = (g0 * fineSeen * 0.5 + g1 * 0.3) * (1.0 - soak);
40
+ if (trod > 0.5) {
41
+ float inner = 1.0 - smoothstep(0.45, 0.8, pOut), bank = smoothstep(0.42, 0.62, pOut) * (1.0 - smoothstep(0.78, 0.95, pOut));
42
+ diffuseColor.rgb *= mix(1.06, 0.92, inner) + 0.05 * bank; // packed dark where the feet went, loose and paler where it was kicked up
43
+ // scuffs: streaks dragged across the ground along the way the column went, and some across it
44
+ float sA = grainN(vec2(dot(p, ax) * 0.045, dot(p, across) * 0.8) + 0.13), sB = grainN(vec2(dot(p, across) * 0.06, dot(p, ax) * 0.7) + 0.61);
45
+ float scuff = (smoothstep(0.62, 0.85, sA) + 0.6 * smoothstep(0.66, 0.9, sB)) * midSeen;
46
+ diffuseColor.rgb *= 1.0 - 0.12 * scuff * inner + 0.05 * scuff * (1.0 - inner);
47
+ gTH -= scuff * 0.25;
48
+ // hoof and foot prints, thick where the press was and few at its edges: two scatters on grids that share no lines, each
49
+ // print a crescent hollow of its own size and heading with its front wall pushed up
50
+ float press = inner * smoothstep(0.25, 0.75, grainN(p * 0.061 + 0.29) * 0.7 + 0.3 * g1);
51
+ vec2 pr = printAt(p, 0.47, 0.0, press) + printAt(p * mat2(0.8, 0.6, -0.6, 0.8), 0.61, 31.0, press * 0.7);
52
+ float printSeen = 1.0 - smoothstep(0.025, 0.07, px);
53
+ diffuseColor.rgb *= 1.0 - (0.15 * pr.x - 0.05 * pr.y) * printSeen;
54
+ gTH += (pr.y * 0.45 - pr.x * 0.8) * printSeen;
55
+ // wheel ruts along a track: pairs an axle apart, wandering, each pair fading in and out along its length
56
+ if (pRuts > 0.01) {
57
+ float alongM = dot(p, ax), acrossM = dot(p, across) + (grainN(vec2(alongM * 0.004, 0.31)) - 0.5) * 3.0;
58
+ float lane = floor(acrossM / 5.3), inLane = acrossM - lane * 5.3;
59
+ float shown = smoothstep(0.35, 0.6, grainN(vec2(alongM * 0.007, lane * 0.37 + 0.2))) * pRuts * inner;
60
+ float w = 0.16 + px * 0.6, rut = (1.0 - smoothstep(w * 0.4, w, abs(inLane - 1.6))) + (1.0 - smoothstep(w * 0.4, w, abs(inLane - 3.3)));
61
+ float ridge = (1.0 - smoothstep(0.0, 0.5, abs(inLane - 2.45))) * 0.4;
62
+ rut *= shown * (1.0 - smoothstep(0.12, 0.4, px));
63
+ diffuseColor.rgb *= 1.0 - 0.2 * rut + 0.04 * ridge * shown;
64
+ gTH += (ridge * shown * 0.3 - rut * 1.1) * midSeen;
65
+ }
66
+ // droppings trodden flat into the dust, darker spots a hand across
67
+ vec2 dq = p / 1.9, dc = floor(dq); vec2 dp = cellPoint(dc + 17.0);
68
+ float dung = (1.0 - smoothstep(0.05, 0.09, length(fract(dq) - 0.3 - 0.4 * dp))) * step(dp.x, 0.12) * inner * midSeen;
69
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.2, 0.16, 0.1), dung * 0.6);
70
+ }
71
+ if (dry > 0.5) { // a crust dried into plates, their edges curled up and paler
72
+ vec3 cr = crustCracks(p * 0.8, (vec2(g1, grainN(p / 9.0 + 0.5)) - 0.5) * 1.6 + (g0 - 0.5) * 0.4);
73
+ float fine = grainN(p * 3.1 + 0.7) * fineSeen;
74
+ diffuseColor.rgb *= 1.0 - 0.3 * cr.x - 0.14 * cr.z + 0.08 * cr.y - 0.05 * fine;
75
+ gTH += cr.y * 0.6 - cr.x * 1.2 - cr.z * 0.5;
76
+ }
77
+ if (soak > 0.5) { // soaked in: darkest where it pooled, in blots, flecked past its edge
78
+ diffuseColor.rgb *= mix(1.12, 0.82, smoothstep(0.3, 0.9, diffuseColor.a * (0.6 + 0.6 * g1)));
79
+ pRough = -0.25 * diffuseColor.a * (1.0 - pOut);
80
+ }
81
+ if (leaf > 0.5) { // fallen needles and twigs, every way, rust and grey on the dark mould
82
+ vec2 q = p / 0.16, ci = floor(q), cf = fract(q); vec2 pick = cellPoint(ci + 41.0);
83
+ vec2 dir = vec2(cos(pick.x * 6.2832), sin(pick.x * 6.2832)), o = cf - 0.5;
84
+ float t = clamp(dot(o, dir), -0.42, 0.42), needle = 1.0 - smoothstep(0.03, 0.07, length(o - dir * t));
85
+ needle *= step(0.25, pick.y) * (1.0 - smoothstep(0.012, 0.03, px));
86
+ diffuseColor.rgb = mix(diffuseColor.rgb, mix(vec3(0.42, 0.27, 0.15), vec3(0.36, 0.33, 0.27), pick.y), needle * 0.7);
87
+ gTH += needle * 0.4;
88
+ }`;
89
+
90
+ /**
91
+ * Create the transparent, polygon-offset `MeshStandardMaterial` used to render draped ground
92
+ * patches. Accepts optional world cloud-shadow, terrain-relief, weather and sky-occlusion hooks.
93
+ *
94
+ * @param {object} [options]
95
+ * @param {THREE.Texture | (() => THREE.Texture)} [options.grainTexture] - Ground detail grain texture or lazy getter.
96
+ * @param {{ value: number }} [options.uDamp] - Shared rain dampness uniform (`0..1`).
97
+ * @param {Record<string, { value: unknown }>} [options.cloudUniforms] - Extra cloud-shadow uniforms merged on compile.
98
+ * @param {string} [options.cloudShadePars=''] - GLSL declarations for `cloudShade(vec2)` when used by `groundWeather`.
99
+ * @param {string} [options.groundBumpPars=terrainReliefGLSL] - GLSL declarations for relief normal perturbation.
100
+ * @param {string} [options.groundBump] - GLSL snippet injected into `#include <normal_fragment_maps>`.
101
+ * @param {string} [options.groundWeather=''] - GLSL snippet injected into `#include <emissivemap_fragment>`.
102
+ * @param {((shader: object) => void) | null} [options.patchShader=null] - Optional post-patch hook (e.g. sky occlusion).
103
+ * @param {string} [options.cacheKey='ground-patch'] - `customProgramCacheKey` value.
104
+ * @param {number} [options.roughness=0.95] - Base surface roughness.
105
+ * @returns {THREE.MeshStandardMaterial}
106
+ */
107
+ export function createGroundDrapeMaterial(options = {}) {
108
+ const {
109
+ grainTexture = defaultGrainTexture,
110
+ uDamp = { value: 0 },
111
+ cloudUniforms = {},
112
+ cloudShadePars = '',
113
+ groundBumpPars = terrainReliefGLSL,
114
+ groundBump = DEFAULT_GROUND_BUMP,
115
+ groundWeather = '',
116
+ patchShader = null,
117
+ cacheKey = 'ground-patch',
118
+ roughness = 0.95,
119
+ } = options;
120
+ const mat = new THREE.MeshStandardMaterial({
121
+ vertexColors: true,
122
+ transparent: true,
123
+ depthWrite: false,
124
+ roughness,
125
+ polygonOffset: true,
126
+ polygonOffsetFactor: -2,
127
+ polygonOffsetUnits: -2,
128
+ });
129
+ mat.onBeforeCompile = sh => {
130
+ const grain = typeof grainTexture === 'function' ? grainTexture() : grainTexture;
131
+ Object.assign(sh.uniforms, { uGrain: { value: grain }, uDamp, ...cloudUniforms });
132
+ sh.vertexShader = sh.vertexShader
133
+ .replace('#include <common>', '#include <common>\nattribute vec4 aLook; varying vec4 vLook; varying vec3 vWP;')
134
+ .replace('#include <begin_vertex>', '#include <begin_vertex>\nvLook = aLook; vWP = (modelMatrix * vec4(position, 1.0)).xyz;');
135
+ sh.fragmentShader = sh.fragmentShader
136
+ .replace(
137
+ '#include <common>',
138
+ `/* glsl */
139
+ #include <common>
140
+ ${cloudShadePars}
141
+ ${groundBumpPars}
142
+ uniform sampler2D uGrain; uniform float uDamp; varying vec4 vLook; varying vec3 vWP;
143
+ float gTH = 0.0, pRough = 0.0;
144
+ ${CRUST_GLSL}
145
+ // A print at most one to a cell, size metres across, where the cell's draw is under press: (how deep its hollow, how high its front wall).
146
+ vec2 printAt(vec2 p, float size, float salt, float press) {
147
+ vec2 q = p / size, ci = floor(q), cf = fract(q), pick = cellPoint(ci + salt), more = cellPoint(ci + salt + 113.0);
148
+ if (more.x > press) return vec2(0.0);
149
+ float turn = pick.x * 6.2832, big = 0.75 + 0.5 * more.y;
150
+ vec2 d = (cf - 0.3 - 0.4 * pick) / big; d = vec2(d.x * cos(turn) - d.y * sin(turn), d.x * sin(turn) + d.y * cos(turn)); d.y *= 0.85 + 0.3 * pick.y;
151
+ float r = length(d), front = smoothstep(-0.04, 0.1, d.y);
152
+ return vec2((1.0 - smoothstep(0.08, 0.14, r)) * (0.55 + 0.45 * front), smoothstep(0.1, 0.15, r) * (1.0 - smoothstep(0.15, 0.22, r)) * front);
153
+ }
154
+ const float GRAIN_MID = 0.73; // the grain map reads 0.62 to 0.84 between its tenth and ninetieth parts: grainN spreads that over 0 to 1
155
+ #define grainN(q) clamp((texture2D(uGrain, q).r - GRAIN_MID) * 4.0 + 0.5, 0.0, 1.0)`,
156
+ )
157
+ .replace('#include <color_fragment>', '#include <color_fragment>\n' + GROUND_DRAPE_FRAGMENT)
158
+ .replace(
159
+ '#include <roughnessmap_fragment>',
160
+ '#include <roughnessmap_fragment>\nroughnessFactor = clamp(roughnessFactor + pRough, 0.3, 1.0);',
161
+ )
162
+ .replace('#include <normal_fragment_maps>', '#include <normal_fragment_maps>\n' + groundBump)
163
+ .replace('#include <emissivemap_fragment>', '#include <emissivemap_fragment>\n' + groundWeather);
164
+ patchShader?.(sh);
165
+ };
166
+ mat.customProgramCacheKey = () => cacheKey;
167
+ return mat;
168
+ }
169
+
170
+ /**
171
+ * Create a world-bound ground-drape toolkit that lazily builds its shared patch material and pebble
172
+ * geometry on first mesh upload, gathers multiple draped patches into one mesh, and renders loose
173
+ * stones and droppings in a companion `InstancedMesh` ordered right after the patches.
174
+ *
175
+ * @param {object} [options]
176
+ * @param {(x: number, z: number, octaves?: number, salt?: number) => number} [options.fbm] - Fractal noise in `[0, 1)`.
177
+ * @param {THREE.Texture | (() => THREE.Texture)} [options.grainTexture] - Ground detail grain texture or lazy getter.
178
+ * @param {{ value: number }} [options.uDamp] - Shared rain dampness uniform.
179
+ * @param {Record<string, { value: unknown }>} [options.cloudUniforms] - Cloud-shadow uniforms.
180
+ * @param {string} [options.cloudShadePars] - Cloud-shadow GLSL declarations.
181
+ * @param {string} [options.groundBumpPars] - Terrain-relief GLSL declarations.
182
+ * @param {string} [options.groundBump] - Terrain-relief normal snippet.
183
+ * @param {string} [options.groundWeather] - Cloud/wetness fragment snippet.
184
+ * @param {((shader: object) => void) | null} [options.patchShader] - Optional shader post-patch hook.
185
+ * @param {(() => THREE.Material) | null} [options.bitsMaterial] - Factory for the transparent stone/dropping material ordered over patches.
186
+ * @param {Function} [options.transform] - Transform matrix helper (`TRS`).
187
+ * @param {string} [options.cacheKey='ground-patch'] - Shader program cache key.
188
+ * @param {Partial<typeof import('../geometry/ground-drape.js').GROUND_PATCH_DEFAULTS>} [options.shape] - Overrides to `GROUND_PATCH_DEFAULTS`.
189
+ * @returns {{
190
+ * groundPatches: () => { pos: number[], colours: number[], looks: number[], index: number[], bits: number[], mesh: (parent: THREE.Object3D) => void },
191
+ * drape: (patches: object, at: object, rng: () => number, x: number, z: number, rx: number, rz: number, col: readonly [number, number, number], lift?: number, rag?: number, kind?: 'trodden' | 'cracked' | 'stain' | 'litter', breathe?: (() => Promise<void>) | null) => Promise<void>,
192
+ * patchSurface: () => THREE.MeshStandardMaterial,
193
+ * pebbleGeometry: () => THREE.BufferGeometry,
194
+ * }}
195
+ */
196
+ export function createGroundDrape(options = {}) {
197
+ const { fbm = defaultFbm(), bitsMaterial = null, transform = defaultTransform, shape } = options;
198
+ let patchMat = null;
199
+ let pebble = null;
200
+
201
+ function patchSurface() {
202
+ return (patchMat ??= createGroundDrapeMaterial(options));
203
+ }
204
+
205
+ function pebbleGeometry() {
206
+ return (pebble ??= buildDrapePebbleGeometry(fbm));
207
+ }
208
+
209
+ function layBits(bits, parent) {
210
+ const n = bits.length / 8;
211
+ const mat = bitsMaterial ? bitsMaterial() : new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.94, transparent: true });
212
+ const stones = new THREE.InstancedMesh(pebbleGeometry(), mat, n);
213
+ const hue = new THREE.Color();
214
+ for (let i = 0; i < n; i++) {
215
+ const o = i * 8;
216
+ stones.setMatrixAt(
217
+ i,
218
+ transform(
219
+ bits[o],
220
+ bits[o + 1],
221
+ bits[o + 2],
222
+ bits[o + 3],
223
+ bits[o + 4],
224
+ bits[o + 3] * 0.85,
225
+ bits[o + 5],
226
+ bits[o + 6],
227
+ bits[o + 6] * 0.5,
228
+ ),
229
+ );
230
+ stones.setColorAt(i, hue.setHex(bits[o + 7]));
231
+ }
232
+ stones.castShadow = stones.receiveShadow = true;
233
+ stones.matrixAutoUpdate = false;
234
+ stones.renderOrder = 3;
235
+ stones.computeBoundingSphere();
236
+ parent.add(stones);
237
+ }
238
+
239
+ function groundPatches() {
240
+ const data = createGroundPatchData();
241
+ return {
242
+ ...data,
243
+ mesh(parent) {
244
+ if (!data.index.length) return;
245
+ const geo = new THREE.BufferGeometry();
246
+ geo.setAttribute('position', new THREE.Float32BufferAttribute(data.pos, 3));
247
+ geo.setAttribute('color', new THREE.Float32BufferAttribute(data.colours, 4));
248
+ geo.setAttribute('aLook', new THREE.Float32BufferAttribute(data.looks, 4));
249
+ geo.setIndex(data.index);
250
+ geo.computeVertexNormals();
251
+ geo.computeBoundingSphere();
252
+ const mesh = new THREE.Mesh(geo, patchSurface());
253
+ mesh.receiveShadow = true;
254
+ mesh.renderOrder = 2;
255
+ mesh.matrixAutoUpdate = false;
256
+ parent.add(mesh);
257
+ if (data.bits.length) layBits(data.bits, parent);
258
+ },
259
+ };
260
+ }
261
+
262
+ function drape(patches, at, rng, x, z, rx, rz, col, lift = 0.04, rag = 0.12, kind = 'trodden', breathe = null) {
263
+ return drapeGroundPatch(patches, at, rng, x, z, rx, rz, col, { lift, rag, kind, breathe, fbm, shape });
264
+ }
265
+
266
+ return { groundPatches, drape, patchSurface, pebbleGeometry };
267
+ }
@@ -128,7 +128,13 @@ const WET_SHEEN = `/* glsl */
128
128
  }`;
129
129
 
130
130
  let fallbackGrain = null;
131
- function defaultGrainTexture() {
131
+ /**
132
+ * Return the shared default repeating ground-grain `DataTexture` (warm greyscale in sRGB) used by
133
+ * procedural ground materials when a caller does not supply its own grain texture.
134
+ *
135
+ * @returns {THREE.DataTexture}
136
+ */
137
+ export function defaultGrainTexture() {
132
138
  if (fallbackGrain) return fallbackGrain;
133
139
  const size = 256;
134
140
  const { groundGrain } = createSurfaceTextures({ noise: createNoise(41), hash2: createHash(41) });
@@ -8,10 +8,11 @@ import * as THREE from 'three';
8
8
  import { createNoise } from '../math/noise.js';
9
9
  import { createHash, mulberry32 } from '../math/random.js';
10
10
  import { partsGeometry } from '../geometry/foliage.js';
11
+ import { TRS as defaultTransform } from '../geometry/primitives.js';
11
12
  import { createPlantTints } from '../geometry/plant-tints.js';
12
13
  import { createTrees } from '../geometry/plant-trees.js';
13
14
  import { PLAIN_GRASS, tussockGeometry } from '../geometry/plant-tussock.js';
14
- import { planScatterInstances } from '../geometry/scatter-instances.js';
15
+ import { TREE_GROVE, planScatterInstances, planTreeGrove } from '../geometry/scatter-instances.js';
15
16
 
16
17
  const DEFAULT_ROUGHNESS = 0.88;
17
18
  const DEFAULT_TREE_SPECIES = Object.freeze(['broadleaf', 'conifer', 'cedar']);
@@ -256,3 +257,152 @@ export function scatterTussocks({
256
257
  },
257
258
  };
258
259
  }
260
+
261
+ /**
262
+ * Build a tiled two-LOD grove of trees (such as upland cedars) using {@link planTreeGrove}. Each
263
+ * `squareSize`-metre grid tile selects one `{ near, far }` model variant so neighbouring stands
264
+ * differ, wraps its instanced near and far meshes in a `THREE.LOD` positioned at the tile centroid,
265
+ * and appends trunk circle colliders to `solid` when provided.
266
+ *
267
+ * @param {object} [options]
268
+ * @param {THREE.Object3D | null} [options.parent=null] - Scene or group receiving the tiled `THREE.LOD` stands.
269
+ * @param {Array<{ near: THREE.BufferGeometry, far: THREE.BufferGeometry }> | null} [options.models=null] - Prebuilt variant geometries; defaults to `variants` cedars from `createTrees`.
270
+ * @param {THREE.Material | null} [options.material=null] - Shared foliage material (defaults to double-sided vertex-coloured `MeshStandardMaterial`).
271
+ * @param {number} [options.roughness=0.88] - Roughness for the default foliage material.
272
+ * @param {number} [options.seed=0] - World seed for default cedar variants when `models` is omitted.
273
+ * @param {{ fbm: Function, vnoise: Function }} [options.noise] - Seeded noise for default cedar variants.
274
+ * @param {Function} [options.hash] - Seeded integer hash for default cedar variants.
275
+ * @param {number} [options.variants=TREE_GROVE.variants] - Number of default cedar variants to build when `models` is omitted.
276
+ * @param {{ x: number, z: number }} [options.origin={ x: 0, z: 0 }] - Local frame world origin in metres.
277
+ * @param {(x: number, z: number) => number} [options.ground] - Local ground elevation sampler `(px, pz) => y` in metres.
278
+ * @param {() => number} [options.random] - Deterministic PRNG in `[0, 1)`.
279
+ * @param {number} [options.x=0] - Grove centre local X in metres.
280
+ * @param {number} [options.z=0] - Grove centre local Z in metres.
281
+ * @param {number} [options.rx=40] - Grove half-width along X in metres.
282
+ * @param {number} [options.rz=40] - Grove half-depth along Z in metres.
283
+ * @param {number} [options.count=40] - Candidate tree positions to sample.
284
+ * @param {(px: number, pz: number) => boolean} [options.clear] - Exclusion predicate in local coordinates.
285
+ * @param {Array<{ x: number, z: number, r: number }> | null} [options.solid=null] - Optional array receiving trunk circle colliders.
286
+ * @param {number} [options.squareSize=TREE_GROVE.squareSize] - Tile square edge length in metres.
287
+ * @param {number} [options.nearDistance=TREE_GROVE.nearDistance] - Distance in metres where far geometry replaces near geometry.
288
+ * @param {number} [options.sink=TREE_GROVE.sink] - Vertical sink below `ground(px, pz)` in metres.
289
+ * @param {readonly [number, number]} [options.scaleRange=TREE_GROVE.scaleRange] - Uniform scale `[min, span]`.
290
+ * @param {number} [options.leanSpan=TREE_GROVE.leanSpan] - Trunk lean span in radians.
291
+ * @param {readonly [number, number]} [options.shadeRange=TREE_GROVE.shadeRange] - Greyscale shade `[min, span]`.
292
+ * @param {number} [options.colliderRadius=TREE_GROVE.colliderRadius] - Trunk collider radius per unit scale in metres.
293
+ * @param {boolean} [options.castShadow=true] - Whether instanced stands cast shadows.
294
+ * @param {boolean} [options.receiveShadow=true] - Whether instanced stands receive shadows.
295
+ * @param {Function} [options.transform] - Transform matrix helper (`TRS`).
296
+ * @returns {{ lods: THREE.LOD[], material: THREE.Material, solids: Array<{ x: number, z: number, r: number }>, total: number, dispose: () => void }}
297
+ */
298
+ export function scatterTreeGrove({
299
+ parent = null,
300
+ models = null,
301
+ material = null,
302
+ roughness = DEFAULT_ROUGHNESS,
303
+ seed = 0,
304
+ noise = null,
305
+ hash = null,
306
+ variants = TREE_GROVE.variants,
307
+ origin = { x: 0, z: 0 },
308
+ ground = () => 0,
309
+ random = mulberry32(seed || 1),
310
+ x = 0,
311
+ z = 0,
312
+ rx = 40,
313
+ rz = 40,
314
+ count = 40,
315
+ clear = () => false,
316
+ solid = null,
317
+ squareSize = TREE_GROVE.squareSize,
318
+ nearDistance = TREE_GROVE.nearDistance,
319
+ sink = TREE_GROVE.sink,
320
+ scaleRange = TREE_GROVE.scaleRange,
321
+ leanSpan = TREE_GROVE.leanSpan,
322
+ shadeRange = TREE_GROVE.shadeRange,
323
+ colliderRadius = TREE_GROVE.colliderRadius,
324
+ castShadow = true,
325
+ receiveShadow = true,
326
+ transform = defaultTransform,
327
+ } = {}) {
328
+ const ownsMaterial = !material;
329
+ const leaves = material ?? createDefaultFoliageMaterial(roughness);
330
+ const ownsModels = !models;
331
+ const resolvedModels =
332
+ models ??
333
+ (() => {
334
+ const n = noise ?? createNoise(seed);
335
+ const h = hash ?? createHash(seed);
336
+ const tints = createPlantTints({ fbm: n.fbm, vnoise: n.vnoise, hash: h });
337
+ const treeKit = createTrees({ hash: h, ...tints, seed });
338
+ return Array.from({ length: variants }, (_, i) => {
339
+ const shape = treeKit.cedar(i);
340
+ return { near: partsGeometry(shape.near), far: partsGeometry(shape.far) };
341
+ });
342
+ })();
343
+
344
+ const plan = planTreeGrove({
345
+ origin,
346
+ ground,
347
+ random,
348
+ x,
349
+ z,
350
+ rx,
351
+ rz,
352
+ count,
353
+ clear,
354
+ squareSize,
355
+ sink,
356
+ scaleRange,
357
+ leanSpan,
358
+ shadeRange,
359
+ colliderRadius,
360
+ });
361
+ if (solid) for (let i = 0; i < plan.solids.length; i++) solid.push(plan.solids[i]);
362
+
363
+ const tone = new THREE.Color();
364
+ const lods = [];
365
+ for (const { key, mid, trees } of plan.squares) {
366
+ const model = resolvedModels[Math.abs(key) % resolvedModels.length];
367
+ const wood = new THREE.LOD();
368
+ const near = new THREE.InstancedMesh(model.near, leaves, trees.length);
369
+ const far = new THREE.InstancedMesh(model.far, leaves, trees.length);
370
+ for (let i = 0; i < trees.length; i++) {
371
+ const [tx, ty, tz, size, turn, lean, shade] = trees[i];
372
+ const m = transform(tx - mid[0], ty - mid[1], tz - mid[2], size, size, size, turn, lean, lean * 0.6);
373
+ tone.setScalar(shade);
374
+ near.setMatrixAt(i, m);
375
+ near.setColorAt(i, tone);
376
+ far.setMatrixAt(i, m);
377
+ far.setColorAt(i, tone);
378
+ }
379
+ near.castShadow = castShadow;
380
+ near.receiveShadow = receiveShadow;
381
+ far.castShadow = castShadow;
382
+ far.receiveShadow = receiveShadow;
383
+ near.computeBoundingSphere();
384
+ far.computeBoundingSphere();
385
+ wood.position.set(mid[0], mid[1], mid[2]);
386
+ wood.addLevel(near, 0);
387
+ wood.addLevel(far, nearDistance);
388
+ if (parent) parent.add(wood);
389
+ lods.push(wood);
390
+ }
391
+
392
+ return {
393
+ lods,
394
+ material: leaves,
395
+ solids: plan.solids,
396
+ total: plan.total,
397
+ dispose() {
398
+ for (const wood of lods) wood.removeFromParent();
399
+ if (ownsMaterial) leaves.dispose();
400
+ if (ownsModels) {
401
+ for (const model of resolvedModels) {
402
+ model.near.dispose();
403
+ model.far.dispose();
404
+ }
405
+ }
406
+ },
407
+ };
408
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Scene flash controller: short-lived exposure pulse, glare/bloom boost, and optional world-space
3
+ * point-light spill for scripted impacts, lightning, or sudden shadow dips.
4
+ * @module
5
+ */
6
+
7
+ import { Color } from 'three';
8
+
9
+ /**
10
+ * Creates a scripted exposure, bloom-boost, and light-spill flash controller.
11
+ *
12
+ * Bright tints lift renderer and post-composite exposure, raise the glare/bloom cap, and emit a
13
+ * transient light spill above `subject`. Very dark tints (below `darkThreshold`) briefly pull
14
+ * exposure down as a shadow dip without emitting light or bloom.
15
+ *
16
+ * @param {object} options
17
+ * @param {{ toneMappingExposure: number }} options.renderer Renderer whose `toneMappingExposure` is pulsed.
18
+ * @param {{ value: number } | (() => { value: number } | null | undefined) | null} [options.exposureUniform=null]
19
+ * Final post-processing pass exposure uniform, or a getter returning it when post-processing may toggle at run time.
20
+ * @param {(boost: number) => void} [options.setBloomBoost] Callback receiving the active glare/bloom cap boost.
21
+ * @param {(x: number, y: number, z: number, rgb: [number, number, number], intensity: number, seconds: number) => void} [options.onLightSpill]
22
+ * Optional callback emitting a transient world point light above `subject`.
23
+ * @param {number} [options.subjectOffsetY=1.15] Metres above `subject.y` where the light spill originates.
24
+ * @param {number} [options.spillThreshold=0.01] Minimum linear RGB peak required to emit a point-light spill.
25
+ * @param {number} [options.spillIntensityScale=6] Multiplier applied to `sqrt(peak)` for the light spill intensity.
26
+ * @param {number} [options.darkThreshold=0.02] Peak luminance below which a cue acts as a dark shadow dip.
27
+ * @param {number} [options.darkLift=-0.18] Fractional exposure change at the peak of a dark shadow dip.
28
+ * @param {number} [options.brightLiftScale=0.1] Fractional exposure lift multiplier applied to `sqrt(peak)` for bright flashes.
29
+ * @param {number} [options.bloomBoostScale=28] Bloom-cap boost multiplier applied to `sqrt(peak)` for bright flashes.
30
+ * @param {number} [options.minDuration=0.01] Minimum flash duration in seconds.
31
+ * @returns {{ trigger: (tint: import('three').ColorRepresentation, seconds: number, subject?: { x: number, y: number, z: number }) => void,
32
+ * update: (dt: number) => void, clear: () => void }}
33
+ */
34
+ export function createSceneFlash({
35
+ renderer,
36
+ exposureUniform = null,
37
+ setBloomBoost = () => {},
38
+ onLightSpill = null,
39
+ subjectOffsetY = 1.15,
40
+ spillThreshold = 0.01,
41
+ spillIntensityScale = 6,
42
+ darkThreshold = 0.02,
43
+ darkLift = -0.18,
44
+ brightLiftScale = 0.1,
45
+ bloomBoostScale = 28,
46
+ minDuration = 0.01,
47
+ }) {
48
+ const color = new Color();
49
+ const isUniformGetter = typeof exposureUniform === 'function';
50
+ let remaining = 0;
51
+ let duration = 0;
52
+ let lift = 0;
53
+ let glareBoost = 0;
54
+ let baseExposure = 1;
55
+ let baseComposite = 1;
56
+
57
+ function resolveUniform() {
58
+ return isUniformGetter ? exposureUniform() : exposureUniform;
59
+ }
60
+
61
+ function setPulse(strength) {
62
+ renderer.toneMappingExposure = baseExposure * (1 + lift * strength);
63
+ const uniform = resolveUniform();
64
+ if (uniform) uniform.value = baseComposite * (1 + lift * strength);
65
+ setBloomBoost(glareBoost * strength);
66
+ }
67
+
68
+ function clear() {
69
+ if (remaining > 0) setPulse(0);
70
+ setBloomBoost(0);
71
+ remaining = 0;
72
+ }
73
+
74
+ function trigger(tint, seconds, subject) {
75
+ clear();
76
+ color.set(tint);
77
+ const peak = Math.max(color.r, color.g, color.b);
78
+ if (peak > spillThreshold && onLightSpill && subject) {
79
+ // Allocate a small RGB tuple per cue rather than reusing a scratch array, because light budgets retain it across frames.
80
+ onLightSpill(
81
+ subject.x,
82
+ subject.y + subjectOffsetY,
83
+ subject.z,
84
+ [color.r / peak, color.g / peak, color.b / peak],
85
+ spillIntensityScale * Math.sqrt(peak),
86
+ seconds,
87
+ );
88
+ }
89
+ baseExposure = renderer.toneMappingExposure;
90
+ const uniform = resolveUniform();
91
+ baseComposite = uniform ? uniform.value : 1;
92
+ lift = peak < darkThreshold ? darkLift : brightLiftScale * Math.sqrt(peak);
93
+ glareBoost = peak < darkThreshold ? 0 : bloomBoostScale * Math.sqrt(peak);
94
+ remaining = duration = Math.max(minDuration, seconds);
95
+ setPulse(1);
96
+ }
97
+
98
+ function update(dt) {
99
+ if (remaining <= 0) return;
100
+ remaining = Math.max(0, remaining - dt);
101
+ setPulse((remaining / duration) ** 2);
102
+ }
103
+
104
+ return { trigger, update, clear };
105
+ }