roamwright 0.61.25 → 0.61.27

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.
package/README.md CHANGED
@@ -30,7 +30,7 @@ npm resolves the Three.js peer in a new project. Roamwright targets Three.js **0
30
30
 
31
31
  ## Examples
32
32
 
33
- Browse all twenty-two examples on the [live showcase](https://enestaylan.github.io/roamwright/).
33
+ Browse all twenty-three examples on the [live showcase](https://enestaylan.github.io/roamwright/).
34
34
 
35
35
  | Live example | What the example shows | Source |
36
36
  | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
@@ -56,6 +56,7 @@ Browse all twenty-two examples on the [live showcase](https://enestaylan.github.
56
56
  | [World map and wayfinding](https://enestaylan.github.io/roamwright/examples/world-map.html?seed=42) | Shaded atlas relief, baked terrain sheets, collision-free lettering, interactive pan/zoom/tap and a live compass strip. | [world-map.js](examples/world-map.js) |
57
57
  | [Scenes](https://enestaylan.github.io/roamwright/examples/scenes.html?seed=42) | Melee duels with blade trails, flying bolts, energy beams, props, instanced scene markers and automated camera cuts. | [scenes.js](examples/scenes.js) |
58
58
  | [Title backdrop](https://enestaylan.github.io/roamwright/examples/title-backdrop.html?seed=42) | Procedural 2D parallax mountain ranges, snow lines, sunlit cumulus banks and freeze-on-load canvas handoff. | [title-backdrop.js](examples/title-backdrop.js) |
59
+ | [Troop formations](https://enestaylan.github.io/roamwright/examples/troops.html?seed=42) | Staggered infantry ranks, carried standards, mounted lancers, ox-drawn wagons, cattle herd and ballistic volleys. | [troops.js](examples/troops.js) |
59
60
 
60
61
  ### Run locally
61
62
 
@@ -0,0 +1,56 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <meta name="theme-color" content="#1e2a26" />
7
+ <title>Troop formations · Roamwright</title>
8
+ <link rel="stylesheet" href="./showcase.css" />
9
+ <script type="importmap">
10
+ {
11
+ "imports": {
12
+ "three": "../node_modules/three/build/three.module.js",
13
+ "three/addons/": "../node_modules/three/examples/jsm/",
14
+ "roamwright": "../index.js",
15
+ "roamwright/": "../"
16
+ }
17
+ }
18
+ </script>
19
+ </head>
20
+ <body>
21
+ <canvas
22
+ tabindex="0"
23
+ aria-label="Opposing infantry formations with carried standards, mounted lancers, ox-drawn wagons, cattle herd, and arcing volleys on a sunlit plain"
24
+ ></canvas>
25
+ <header>
26
+ <a class="back" href="../index.html"><span aria-hidden="true">←</span> Roamwright</a>
27
+ <div class="meta">
28
+ <a class="source" href="https://github.com/enestaylan/roamwright/blob/main/examples/troops.js">Source</a>
29
+ <form method="get">
30
+ <label for="seed">Seed</label>
31
+ <input id="seed" name="seed" type="number" step="1" min="-2147483648" max="2147483647" value="42" required />
32
+ <button type="submit" title="Rebuild formations with this seed" aria-label="Rebuild formations with this seed">→</button>
33
+ </form>
34
+ </div>
35
+ </header>
36
+ <footer>
37
+ <div class="caption">
38
+ <h1>Troop formations</h1>
39
+ <p>Staggered infantry lines, carried standards, mounted lancers, ox-drawn supply wagons, cattle herd, and ballistic volleys.</p>
40
+ </div>
41
+ <div class="tools">
42
+ <div class="views" role="group" aria-label="Camera viewpoint">
43
+ <button type="button" data-view="line" aria-pressed="true">Line</button>
44
+ <button type="button" data-view="cavalry" aria-pressed="false">Cavalry</button>
45
+ <button type="button" data-view="train" aria-pressed="false">Supply train</button>
46
+ <button type="button" data-view="overview" aria-pressed="false">Overview</button>
47
+ </div>
48
+ <button type="button" class="action" id="march">March</button>
49
+ <button type="button" class="action" id="fight">Engage</button>
50
+ <button type="button" class="action" id="fall">Volley fall</button>
51
+ <button type="button" class="action" id="reset">Reset</button>
52
+ </div>
53
+ </footer>
54
+ <script type="module" src="./troops.js"></script>
55
+ </body>
56
+ </html>
@@ -0,0 +1,309 @@
1
+ import * as THREE from 'three';
2
+ import {
3
+ createCrowdSystem,
4
+ createDaylightSky,
5
+ createHouseKit,
6
+ createHouseKitMaterials,
7
+ createHouseKitMeshes,
8
+ createOrbitCamera,
9
+ createSpaces,
10
+ createTroopDirector,
11
+ createTroopMounts,
12
+ createTroopStandards,
13
+ scatterTrees,
14
+ scatterTussocks,
15
+ } from 'roamwright';
16
+ import { createHeightfieldMesh } from 'roamwright/geometry/heightfield.js';
17
+ import { createProps } from 'roamwright/geometry/props.js';
18
+ import { sstep } from 'roamwright/math/scalar.js';
19
+ import { createVehicleTrains } from 'roamwright/rendering/vehicle-train.js';
20
+ import { initExample } from './stage.js';
21
+
22
+ const {
23
+ canvas,
24
+ renderer,
25
+ camera,
26
+ scene,
27
+ worldGroup,
28
+ seed,
29
+ random: rng,
30
+ noise,
31
+ hash,
32
+ shapes,
33
+ } = initExample({
34
+ fallbackSeed: 42,
35
+ fov: 38,
36
+ });
37
+
38
+ // Gentle sunlit meadow plain ringed by rolling highland ridges so formations read clearly.
39
+ function groundHeight(x, z) {
40
+ const r = Math.hypot(x, z);
41
+ const rim = sstep(46, 150, r);
42
+ const ridge = rim * (14 * noise.fbm(x * 0.0085, z * 0.0085, 4, 29) + 5 * noise.ridged(x * 0.006, z * 0.006, 3, 17));
43
+ return 0.22 * Math.sin(x * 0.035 + seed * 0.1) * Math.cos(z * 0.03) + ridge;
44
+ }
45
+
46
+ const meadowCol = new THREE.Color(0x7c8652),
47
+ dryGrassCol = new THREE.Color(0x9a8f63),
48
+ trackCol = new THREE.Color(0xa69473);
49
+ const terrain = createHeightfieldMesh({
50
+ size: 420,
51
+ segs: 136,
52
+ heightAt: groundHeight,
53
+ colorAt: (x, y, z, up, out) => {
54
+ const f = noise.fbm(x * 0.038, z * 0.038, 3, 11);
55
+ const onTrack = 1 - sstep(4.5, 11, Math.abs(z + 17));
56
+ out.copy(meadowCol).lerp(dryGrassCol, f);
57
+ out.lerp(trackCol, onTrack * 0.65);
58
+ out.multiplyScalar(0.88 + 0.22 * noise.vnoise(x * 0.15, z * 0.15, 7));
59
+ },
60
+ });
61
+ worldGroup.add(terrain);
62
+
63
+ // Trees and tussocks framing the distant ridge while keeping the parade plain clear.
64
+ const { material: leafMat } = scatterTrees({
65
+ parent: worldGroup,
66
+ noise,
67
+ hash,
68
+ seed,
69
+ random: rng,
70
+ groundAt: groundHeight,
71
+ attempts: 150,
72
+ maxPerSpecies: 48,
73
+ species: ['broadleaf', 'conifer'],
74
+ scaleRange: [0.85, 0.65],
75
+ sink: 0.15,
76
+ sample: () => {
77
+ const angle = rng() * Math.PI * 2;
78
+ const dist = 42 + rng() * 95;
79
+ const tx = Math.cos(angle) * dist;
80
+ const tz = Math.sin(angle) * dist;
81
+ return Math.abs(tz + 17) < 12 ? null : [tx, tz];
82
+ },
83
+ });
84
+
85
+ scatterTussocks({
86
+ parent: worldGroup,
87
+ seed: seed * 17,
88
+ random: rng,
89
+ groundAt: groundHeight,
90
+ count: 85,
91
+ attempts: 130,
92
+ scaleRange: [0.8, 0.55],
93
+ material: leafMat,
94
+ sample: () => {
95
+ const tx = (rng() - 0.5) * 120;
96
+ const tz = (rng() - 0.5) * 100;
97
+ return Math.hypot(tx, tz) < 22 ? null : [tx, tz];
98
+ },
99
+ });
100
+
101
+ // Kits for standards, supply wagons, and crowd batches.
102
+ const houseKit = createHouseKit({ shapes });
103
+ const props = createProps({ houseKit, shapes, vnoise: noise.vnoise, hash, horse: () => {} });
104
+ const kitMeshes = createHouseKitMeshes({ materials: createHouseKitMaterials({ doubleSide: true }) });
105
+ const { makeVehicles } = createVehicleTrains({
106
+ kitNew: houseKit.kitNew,
107
+ kitAt: houseKit.kitAt,
108
+ kitInstanced: kitMeshes.kitInstanced,
109
+ propCart: props.propCart,
110
+ propWagon: props.propWagon,
111
+ propWheel: props.propWheel,
112
+ });
113
+
114
+ const { lightDir } = createDaylightSky({
115
+ scene,
116
+ renderer,
117
+ noise,
118
+ sky: { sunDir: [0.64, 0.36, 0.68] },
119
+ sunPosition: [58, 48, 62],
120
+ shadowRadius: 72,
121
+ shadowFar: 220,
122
+ fogColor: 0xd4dfd9,
123
+ fogDensity: 0.002,
124
+ });
125
+
126
+ const spaceKit = createSpaces({ id: 'plain', ground: groundHeight });
127
+ const crowdSystem = createCrowdSystem({ scene: worldGroup, groundAt: groundHeight, spaceKit, camera, renderer });
128
+
129
+ let elapsed = 0;
130
+ let frame = 0;
131
+ const updater = crowdSystem.createUpdater({
132
+ getTime: () => elapsed,
133
+ getFrame: () => frame,
134
+ getLightDir: () => lightDir,
135
+ shadowRange: 72,
136
+ shadowFar: 220,
137
+ });
138
+
139
+ const STANDARDS = {
140
+ crimson: [0x762626, 0xd9c28c],
141
+ cobalt: [0x26486c, 0xd8d2c0],
142
+ };
143
+
144
+ const troopMounts = createTroopMounts({ camera, makeVehicles });
145
+ const troopStandards = createTroopStandards({
146
+ kitNew: houseKit.kitNew,
147
+ kitAt: houseKit.kitAt,
148
+ kitInstanced: kitMeshes.kitInstanced,
149
+ propStandard: props.propStandard,
150
+ getFrame: () => frame,
151
+ standardOf: id => STANDARDS[id] || null,
152
+ });
153
+
154
+ const director = createTroopDirector({
155
+ seed,
156
+ camera,
157
+ getTime: () => elapsed,
158
+ addCrowd: (list, tones, cx, cz, near, kind, _bodyId, spaceId) => crowdSystem.addCrowd(list, tones, cx, cz, near, kind, null, spaceId),
159
+ standardOf: id => STANDARDS[id] || null,
160
+ makeMounts: troopMounts.makeMounts,
161
+ makeHerd: troopMounts.makeHerd,
162
+ makeWagons: troopMounts.makeWagons,
163
+ makeStandards: troopStandards.makeStandards,
164
+ });
165
+
166
+ const plainSpace = { id: 'plain', group: worldGroup, ground: groundHeight };
167
+ const tickHost = director.raiseHost(
168
+ plainSpace,
169
+ 'field',
170
+ [
171
+ {
172
+ originX: 0,
173
+ originZ: 0,
174
+ troops: {
175
+ crimsonFoot: {
176
+ body: 'crimson',
177
+ kind: 'trooper',
178
+ tones: [0x762626, 0x622222, 0x5c362c],
179
+ n: 36,
180
+ wide: 9,
181
+ gap: [1.15, 1.3],
182
+ loose: 0.22,
183
+ at: [-9, 0],
184
+ face: [20, 0],
185
+ },
186
+ crimsonBows: {
187
+ body: 'crimson',
188
+ kind: 'guard',
189
+ tones: [0x6e3a2c, 0x583226],
190
+ n: 16,
191
+ wide: 8,
192
+ gap: [1.2, 1.3],
193
+ loose: 0.25,
194
+ at: [-17, 1],
195
+ face: [20, 1],
196
+ },
197
+ cobaltFoot: {
198
+ body: 'cobalt',
199
+ kind: 'raider',
200
+ tones: [0x2a4a6e, 0x38587a, 0x4b5b6b],
201
+ n: 36,
202
+ wide: 9,
203
+ gap: [1.15, 1.3],
204
+ loose: 0.28,
205
+ at: [8, -1],
206
+ face: [-20, -1],
207
+ },
208
+ cobaltLancers: {
209
+ body: 'cobalt',
210
+ kind: 'plain',
211
+ tones: [0x2a4a6e, 0x3b5878, 0x606c7a],
212
+ n: 9,
213
+ wide: 3,
214
+ gap: [2.2, 3.0],
215
+ loose: 0.2,
216
+ mounted: true,
217
+ lance: true,
218
+ at: [7.5, 8.5],
219
+ face: [-20, 6],
220
+ },
221
+ wagons: {
222
+ beast: 'wagon',
223
+ tones: [0x8a6a4a, 0xa89878, 0x5a4636],
224
+ n: 2,
225
+ wide: 1,
226
+ gap: [4.5, 11],
227
+ loose: 0.08,
228
+ at: [-2, -16],
229
+ face: [40, -16],
230
+ },
231
+ herd: {
232
+ beast: 'cattle',
233
+ tones: [0x8a6a4a, 0xa89878, 0x5a4636, 0xc8b89a],
234
+ n: 10,
235
+ wide: 5,
236
+ gap: [1.8, 2.2],
237
+ loose: 0.4,
238
+ at: [11, -16],
239
+ face: [40, -16],
240
+ },
241
+ },
242
+ },
243
+ ],
244
+ 400,
245
+ );
246
+
247
+ crowdSystem.build();
248
+
249
+ const views = {
250
+ line: { eye: [-1, 7.6, 28], target: [0.5, 1.9, -1] },
251
+ cavalry: { eye: [-2, 4.6, 19], target: [7, 1.8, 8] },
252
+ train: { eye: [-16, 5.8, -3], target: [-1, 1.6, -16] },
253
+ overview: { eye: [0, 38, 56], target: [0, 1, -2] },
254
+ };
255
+
256
+ const rig = createOrbitCamera({
257
+ camera,
258
+ canvas,
259
+ renderer,
260
+ scene,
261
+ views,
262
+ initialView: 'line',
263
+ groundAt: groundHeight,
264
+ minClearance: 1.2,
265
+ minDistance: 6,
266
+ maxDistance: 170,
267
+ onDraw: () => {},
268
+ });
269
+
270
+ const anchor = { x: 0, z: 0 };
271
+ const fireCue = (verb, targets, ...args) => director.cue('field', [elapsed, 'cue', 'field', verb, targets, ...args], anchor);
272
+
273
+ document.querySelector('#march').addEventListener('click', () => {
274
+ fireCue('go', 'crimsonFoot', -5, 0, 5, 20, 0);
275
+ fireCue('go', 'cobaltFoot', 5, 0, 5, -20, 0);
276
+ fireCue('go', 'cobaltLancers', 4, 8, 4.5, -20, 4);
277
+ fireCue('go', 'wagons', 8, -17, 10, 40, -17);
278
+ fireCue('go', 'herd', 24, -18, 10, 40, -18);
279
+ });
280
+ document.querySelector('#fight').addEventListener('click', () => {
281
+ fireCue('fight', ['crimsonFoot', 'cobaltFoot', 'cobaltLancers'], 1.25);
282
+ });
283
+ document.querySelector('#fall').addEventListener('click', () => {
284
+ fireCue('fall', ['crimsonFoot', 'cobaltFoot'], 0.35, 3);
285
+ });
286
+ document.querySelector('#reset').addEventListener('click', () => {
287
+ director.resetAll();
288
+ });
289
+
290
+ // Start with a brief opening advance so the first frames show active ranks, lancers, and rolling wagons.
291
+ fireCue('go', 'crimsonFoot', -5, 0, 6, 20, 0);
292
+ fireCue('go', 'cobaltFoot', 5, -1, 6, -20, -1);
293
+ fireCue('go', 'cobaltLancers', 3.5, 7.5, 6, -20, 5);
294
+ fireCue('go', 'wagons', 4, -16, 12, 40, -16);
295
+ fireCue('go', 'herd', 17, -16, 12, 40, -16);
296
+
297
+ const clock = new THREE.Timer();
298
+ function draw() {
299
+ clock.update();
300
+ const dt = Math.min(clock.getDelta(), 0.1);
301
+ elapsed += dt;
302
+ frame++;
303
+ rig.clampCamera();
304
+ tickHost(dt);
305
+ updater.updateCrowds();
306
+ renderer.render(scene, camera);
307
+ requestAnimationFrame(draw);
308
+ }
309
+ draw();
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Pure impact-crater height-profile function: ragged bowl depression with a thrown-subsoil lip.
3
+ * Zero Three.js dependencies so terrain-height workers can import it without pulling Three.js.
4
+ * @module
5
+ */
6
+
7
+ import { createNoise } from '../math/noise.js';
8
+
9
+ let fallbackVnoise = null;
10
+ const defaultVnoise = () => (fallbackVnoise ??= createNoise().vnoise);
11
+
12
+ /**
13
+ * Compute the height offset (in metres) of an impact crater's ragged bowl and thrown-earth lip at
14
+ * local offset `(dx, dz)` from the crater centre. Negative inside the bowl (down to `-crater.deep`),
15
+ * rising cleanly along the rim near radius `crater.r * 1.06`.
16
+ *
17
+ * @param {{ x: number, z: number, r: number, deep: number }} crater - Crater centre (`x, z`), radius `r` and depth `deep` in metres.
18
+ * @param {number} dx - Offset east from crater centre in metres.
19
+ * @param {number} dz - Offset south from crater centre in metres.
20
+ * @param {(x: number, z: number, salt?: number) => number} [vnoise] - Seeded value noise in `[0, 1)`.
21
+ * @returns {number} Vertical height displacement in metres.
22
+ */
23
+ export function craterDip(crater, dx, dz, vnoise = defaultVnoise()) {
24
+ const d = Math.hypot(dx, dz) || 1e-3;
25
+ const t = d / (crater.r * (0.86 + 0.28 * vnoise((dx / d) * 1.6 + crater.x, (dz / d) * 1.6 + crater.z, 381)));
26
+ return (t < 1 ? -crater.deep * (1 - t * t) : 0) + crater.deep * 0.42 * Math.exp(-(((t - 1.06) / 0.3) ** 2));
27
+ }
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Ground-drape patch geometry and loose surface debris scatter: draped elliptical discs conforming
3
+ * to any height field with feathered ragged edges, trodden rim banking, per-vertex surface look
4
+ * attributes (`aLook`), scattered cobbles/pebbles and droppings, and faceted pebble geometry.
5
+ * Worker-safe.
6
+ * @module
7
+ */
8
+
9
+ import * as THREE from 'three';
10
+ import { createNoise } from '../math/noise.js';
11
+ import { mulberry32 } from '../math/random.js';
12
+ import { TAU, clamp, sstep } from '../math/scalar.js';
13
+
14
+ let fallbackFbm = null;
15
+ const defaultFbm = () => (fallbackFbm ??= createNoise().fbm);
16
+
17
+ /**
18
+ * Surface kind codes written into the `aLook.x` vertex attribute for `rendering/ground-drape.js`.
19
+ */
20
+ export const GROUND_PATCH_KINDS = Object.freeze({
21
+ trodden: 0,
22
+ cracked: 1,
23
+ stain: 2,
24
+ litter: 3,
25
+ });
26
+
27
+ /**
28
+ * Default feathering, mottling, rim-banking, rutting and loose-stone scatter settings for
29
+ * {@link drapeGroundPatch} and {@link scatterPatchBits}.
30
+ */
31
+ export const GROUND_PATCH_DEFAULTS = Object.freeze({
32
+ /** Fraction of patch radius out to which the patch remains full thickness. */
33
+ fadeFrom: 0.6,
34
+ /** Rim-fade noise modulation amplitude so patch edges break up organically. */
35
+ raggedFade: 0.25,
36
+ /** Vertex-colour mottling amplitude. */
37
+ mottle: 0.2,
38
+ /** Spatial frequency (cycles/m) of vertex-colour mottling noise. */
39
+ mottleGrain: 0.16,
40
+ /** Fractional radius where a trodden patch's kicked-up bank peaks. */
41
+ bankPeak: 0.66,
42
+ /** Fractional radius half-width of the trodden rim bank. */
43
+ bankWidth: 0.42,
44
+ /** Bank height in metres per metre of the patch's lesser radius. */
45
+ bankRise: 0.009,
46
+ /** Maximum rim-bank height in metres. */
47
+ bankMost: 0.22,
48
+ /** Minimum length-to-width ratio above which a trodden patch carries wheel ruts. */
49
+ rutsFrom: 1.8,
50
+ /** Square metres of trodden ground per scattered loose stone. */
51
+ stoneArea: 7,
52
+ /** Square metres of trodden ground per scattered beast dropping cluster. */
53
+ dungArea: 45,
54
+ /** Maximum scattered stones per patch (droppings cap at one quarter of this). */
55
+ bitsMost: 1400,
56
+ /** Stones generated between async `breathe()` yields. */
57
+ stonesABreath: 600,
58
+ /** Default sRGB stone colours for scattered pebbles and cobbles. */
59
+ stoneHues: Object.freeze([0x9a8c76, 0x857a68, 0xb0a28a, 0x6f6557, 0xa89478]),
60
+ /** Default sRGB colours for scattered animal droppings. */
61
+ dungHues: Object.freeze([0x4a3a26, 0x3e3424, 0x55462c, 0x4b4430]),
62
+ });
63
+
64
+ /**
65
+ * Create an empty ground-patch vertex/index/bit accumulator consumed by {@link drapeGroundPatch} and
66
+ * meshed by `rendering/ground-drape.js`.
67
+ *
68
+ * @returns {{ pos: number[], colours: number[], looks: number[], index: number[], bits: number[] }}
69
+ */
70
+ export function createGroundPatchData() {
71
+ return {
72
+ pos: [],
73
+ colours: [],
74
+ looks: [],
75
+ index: [],
76
+ bits: [],
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Build a faceted, noise-displaced pebble `BufferGeometry` with unit white vertex colours so
82
+ * instanced stones inherit per-instance colours cleanly on vertex-coloured rock materials.
83
+ *
84
+ * @param {(x: number, z: number, octaves?: number, salt?: number) => number} [fbm] - Fractal noise in `[0, 1)`.
85
+ * @returns {THREE.BufferGeometry}
86
+ */
87
+ export function buildDrapePebbleGeometry(fbm = defaultFbm()) {
88
+ const g = new THREE.IcosahedronGeometry(0.5, 0);
89
+ const a = g.attributes.position.array;
90
+ for (let i = 0; i < a.length; i += 3) {
91
+ const l = Math.hypot(a[i], a[i + 1], a[i + 2]);
92
+ const r = (0.5 * (0.7 + 0.6 * fbm((a[i] / l) * 1.9 + 7, (a[i + 2] / l) * 1.9 + (a[i + 1] / l) * 1.4, 2, 311))) / l;
93
+ a[i] *= r;
94
+ a[i + 1] *= r * 0.7;
95
+ a[i + 2] *= r;
96
+ }
97
+ g.computeVertexNormals();
98
+ g.setAttribute('color', new THREE.Float32BufferAttribute(new Float32Array(a.length).fill(1), 3));
99
+ return g;
100
+ }
101
+
102
+ /**
103
+ * Scatter kicked-loose stones and beast droppings onto a trodden ground patch around `(x, z)` in
104
+ * local frame `at`, appending packed 8-number tuples `[wx, wy, wz, size, height, turn, tilt, hex]`
105
+ * to `patches.bits`. Optionally yields via `breathe` every `cfg.stonesABreath` stones.
106
+ *
107
+ * @param {{ bits: number[] }} patches - Target patch data accumulator.
108
+ * @param {{ x0: number, z0: number, Y: (x: number, z: number) => number }} at - Local origin and ground height sampler.
109
+ * @param {() => number} rng - Dedicated repeatable PRNG stream in `[0, 1)`.
110
+ * @param {number} x - Patch centre local X in metres.
111
+ * @param {number} z - Patch centre local Z in metres.
112
+ * @param {number} rx - Patch semi-axis along X in metres.
113
+ * @param {number} rz - Patch semi-axis along Z in metres.
114
+ * @param {(() => Promise<void>) | null} [breathe=null] - Optional async frame-yield callback.
115
+ * @param {typeof GROUND_PATCH_DEFAULTS} [cfg=GROUND_PATCH_DEFAULTS] - Scatter tuning parameters.
116
+ */
117
+ export async function scatterPatchBits(patches, at, rng, x, z, rx, rz, breathe = null, cfg = GROUND_PATCH_DEFAULTS) {
118
+ const area = Math.PI * rx * rz;
119
+ const stones = Math.min(cfg.bitsMost, Math.round(area / cfg.stoneArea));
120
+ const dung = Math.min(cfg.bitsMost / 4, Math.round(area / cfg.dungArea));
121
+ const put = (px, pz, s, h, sink, col) =>
122
+ patches.bits.push(at.x0 + px, at.Y(px, pz) - sink, at.z0 + pz, s, h, rng() * TAU, (rng() - 0.5) * 0.5, col);
123
+ const inside = () => {
124
+ const a = rng() * TAU;
125
+ const d = Math.sqrt(rng()) * 0.85;
126
+ return [x + Math.cos(a) * rx * d, z + Math.sin(a) * rz * d];
127
+ };
128
+ for (let i = 0; i < stones; i++) {
129
+ const [px, pz] = inside();
130
+ const s = rng() < 0.12 ? 0.22 + rng() * 0.25 : 0.06 + rng() * 0.12;
131
+ put(px, pz, s, s, -s * 0.08, cfg.stoneHues[(rng() * cfg.stoneHues.length) | 0]);
132
+ if (breathe && i % cfg.stonesABreath === cfg.stonesABreath - 1) await breathe();
133
+ }
134
+ for (let i = 0; i < dung; i++) {
135
+ const [px, pz] = inside();
136
+ const col = cfg.dungHues[(rng() * cfg.dungHues.length) | 0];
137
+ if (rng() < 0.6) {
138
+ const balls = 3 + ((rng() * 4) | 0);
139
+ for (let k = 0; k < balls; k++) {
140
+ put(px + (rng() - 0.5) * 0.22, pz + (rng() - 0.5) * 0.22, 0.07 + rng() * 0.03, 0.06, -0.012, col);
141
+ }
142
+ } else {
143
+ put(px, pz, 0.22 + rng() * 0.12, 0.05, -0.006, col);
144
+ }
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Append one draped elliptical ground patch conforming to `at.Y(x, z)` into `patches`, with a
150
+ * ragged feathered rim, mottled linear vertex colours, per-vertex `aLook` surface parameters, and
151
+ * optional scattered loose stones and droppings for large `'trodden'` patches.
152
+ *
153
+ * @param {{ pos: number[], colours: number[], looks: number[], index: number[], bits: number[] }} patches - Accumulator from {@link createGroundPatchData}.
154
+ * @param {{ x0: number, z0: number, Y: (x: number, z: number) => number }} at - Local origin and ground height sampler.
155
+ * @param {() => number} rng - Repeatable PRNG in `[0, 1)`.
156
+ * @param {number} x - Patch centre local X in metres.
157
+ * @param {number} z - Patch centre local Z in metres.
158
+ * @param {number} rx - Patch semi-axis along X in metres.
159
+ * @param {number} rz - Patch semi-axis along Z in metres.
160
+ * @param {readonly [number, number, number]} col - Base linear RGB colour `[r, g, b]`.
161
+ * @param {object} [options]
162
+ * @param {number} [options.lift=0.04] - Vertical lift above the terrain surface in metres.
163
+ * @param {number} [options.rag=0.12] - Rim radial irregularity share.
164
+ * @param {'trodden' | 'cracked' | 'stain' | 'litter'} [options.kind='trodden'] - Patch surface kind.
165
+ * @param {(() => Promise<void>) | null} [options.breathe=null] - Optional async frame-yield callback.
166
+ * @param {(x: number, z: number, octaves?: number, salt?: number) => number} [options.fbm] - Fractal noise in `[0, 1)`.
167
+ * @param {Partial<typeof GROUND_PATCH_DEFAULTS>} [options.shape] - Overrides to {@link GROUND_PATCH_DEFAULTS}.
168
+ */
169
+ export async function drapeGroundPatch(patches, at, rng, x, z, rx, rz, col, options = {}) {
170
+ const { lift = 0.04, rag = 0.12, kind = 'trodden', breathe = null, fbm = defaultFbm() } = options;
171
+ const cfg = options.shape ? { ...GROUND_PATCH_DEFAULTS, ...options.shape } : GROUND_PATCH_DEFAULTS;
172
+ const trodden = kind === 'trodden';
173
+ const rings = Math.max(trodden ? 8 : 5, Math.ceil(Math.max(rx, rz) / 3.5));
174
+ const segs = Math.max(30, Math.ceil((Math.max(rx, rz) * TAU) / 5));
175
+ const { pos, colours, looks, index } = patches;
176
+ const first = pos.length / 3;
177
+ const edge = Array.from({ length: segs }, () => 1 + (rng() - 0.5) * 2 * rag);
178
+ const seed = Math.floor(rng() * 1e4);
179
+ // Dedicated stream so internal debris scattering never shifts the caller's layout RNG.
180
+ const own = mulberry32(seed + 7);
181
+ const long = Math.max(rx, rz) / Math.min(rx, rz);
182
+ const ruts = trodden ? clamp((long - cfg.rutsFrom) / 1.5, 0, 1) : 0;
183
+ const bearing = long > cfg.rutsFrom ? (rx >= rz ? 0 : Math.PI / 2) : own() * Math.PI;
184
+ const bank = trodden ? Math.min(cfg.bankMost, cfg.bankRise * Math.min(rx, rz)) : 0;
185
+ const code = GROUND_PATCH_KINDS[kind];
186
+ const vertex = (px, pz, y, out) => {
187
+ const wx = at.x0 + px;
188
+ const wz = at.z0 + pz;
189
+ const grain = 2 * fbm(wx * cfg.mottleGrain, wz * cfg.mottleGrain, 3, seed) - 1;
190
+ const mottle = 1 + cfg.mottle * grain;
191
+ const thick = out >= 1 ? 0 : sstep(1, cfg.fadeFrom, out + cfg.raggedFade * grain);
192
+ const rise = bank * Math.max(0, 1 - ((out - cfg.bankPeak) / cfg.bankWidth) ** 2) ** 2;
193
+ pos.push(wx, y + rise, wz);
194
+ colours.push(col[0] * mottle, col[1] * mottle, col[2] * mottle, thick);
195
+ looks.push(code, Math.min(out, 1), ruts, bearing);
196
+ };
197
+ vertex(x, z, at.Y(x, z) + lift, 0);
198
+ for (let r = 1; r <= rings; r++) {
199
+ for (let k = 0; k < segs; k++) {
200
+ const a = (k / segs) * TAU;
201
+ const d = (r / rings) * (r === rings ? edge[k] : 1);
202
+ const px = x + Math.cos(a) * rx * d;
203
+ const pz = z + Math.sin(a) * rz * d;
204
+ vertex(px, pz, at.Y(px, pz) + lift * (r === rings ? 0.3 : 1), r / rings);
205
+ }
206
+ }
207
+ for (let k = 0; k < segs; k++) {
208
+ const n = (k + 1) % segs;
209
+ index.push(first, first + 1 + n, first + 1 + k);
210
+ for (let r = 1; r < rings; r++) {
211
+ const a = first + 1 + (r - 1) * segs;
212
+ const b = a + segs;
213
+ index.push(a + k, a + n, b + k, a + n, b + n, b + k);
214
+ }
215
+ }
216
+ if (trodden && Math.min(rx, rz) > 3) {
217
+ if (breathe) await breathe();
218
+ await scatterPatchBits(patches, at, own, x, z, rx, rz, breathe, cfg);
219
+ }
220
+ }