roamwright 0.61.6 → 0.61.8

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,102 @@
1
+ import * as THREE from 'three';
2
+ import {
3
+ GeometryBuilder,
4
+ buildHaystacks,
5
+ buildStonePile,
6
+ createUnitShapes,
7
+ drystoneStone,
8
+ layRoads,
9
+ meshSprings,
10
+ meshStreamBanks,
11
+ mulberry32,
12
+ planDrystoneWall,
13
+ planSprings,
14
+ planStreamBanks,
15
+ } from 'roamwright';
16
+ import { instancedMesh } from 'roamwright/geometry/instances.js';
17
+ import { SRGB2LIN } from 'roamwright/math/color.js';
18
+ import { lerp } from 'roamwright/math/scalar.js';
19
+
20
+ // Roads, river springhead and stoned banks, drystone field enclosure, haystacks and stone pile for examples/land.js.
21
+ export function buildLandFeatures({ worldGroup, land, waters, groundExact, sea, shoreZ, tones, seed, fbm, vnoise }) {
22
+ const roadColor = (tone, mul) => ({ r: SRGB2LIN[tone[0]] * mul, g: SRGB2LIN[tone[1]] * mul, b: SRGB2LIN[tone[2]] * mul });
23
+ const roadSoil = roadColor(tones.debris, 0.72),
24
+ roadVerge = roadColor(tones.grass, 0.9);
25
+ layRoads({
26
+ roads: land.roads.map(r => ({ pts: r.pts, w: r.w, crown: 0.15, fadeStart: 20, fadeEnd: 20 })),
27
+ parent: worldGroup,
28
+ ground: groundExact,
29
+ soil: () => roadSoil,
30
+ verge: () => roadVerge,
31
+ material: () => new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.96, transparent: true }),
32
+ });
33
+
34
+ const shapes = createUnitShapes(fbm);
35
+ const [river] = waters.channels;
36
+ const riverPts = river.line.filter(([, z]) => z <= shoreZ + 10);
37
+ const bed = Float32Array.from(riverPts, ([x, z]) => groundExact(x, z) - 0.4);
38
+ const level = Float32Array.from(riverPts, (_, i) => Math.max(river.level(i / Math.max(1, river.n - 1)), sea + 0.06));
39
+ const plans = planStreamBanks({
40
+ rivers: [{ fine: riverPts, bed, level, w: river.width }],
41
+ waterLevel: sea,
42
+ ground: groundExact,
43
+ random: mulberry32(seed * 41),
44
+ });
45
+ meshStreamBanks({
46
+ plans,
47
+ stone: { geometry: shapes.rock, material: new THREE.MeshStandardMaterial({ roughness: 0.92 }) },
48
+ log: { geometry: shapes.cyl, material: new THREE.MeshStandardMaterial({ roughness: 0.95 }) },
49
+ parent: worldGroup,
50
+ });
51
+ meshSprings({
52
+ plans: planSprings({
53
+ rivers: [{ fine: riverPts, level, w: river.width }],
54
+ ground: groundExact,
55
+ noise: vnoise,
56
+ random: mulberry32(seed * 47),
57
+ }),
58
+ parent: worldGroup,
59
+ crag: () => shapes.rock,
60
+ });
61
+
62
+ const wallRng = mulberry32(seed * 53);
63
+ const wallCorners = [
64
+ [168, 62],
65
+ [224, 66],
66
+ [220, 118],
67
+ [164, 114],
68
+ ];
69
+ const stones = [],
70
+ tintsOut = [];
71
+ for (let i = 0; i < wallCorners.length; i++) {
72
+ const a = wallCorners[i],
73
+ b = wallCorners[(i + 1) % wallCorners.length];
74
+ const segs = Math.max(1, Math.round(Math.hypot(b[0] - a[0], b[1] - a[1]) / 6));
75
+ for (let s = 0; s < segs; s++) {
76
+ if (i === 0 && s === Math.floor(segs / 2)) continue; // gateway facing the road
77
+ const p0 = [lerp(a[0], b[0], s / segs), lerp(a[1], b[1], s / segs)];
78
+ const p1 = [lerp(a[0], b[0], (s + 1) / segs), lerp(a[1], b[1], (s + 1) / segs)];
79
+ const planned = planDrystoneWall(p0, p1, 0.95, wallRng, { ground: groundExact });
80
+ stones.push(...planned.stones);
81
+ tintsOut.push(...planned.tints);
82
+ }
83
+ }
84
+ const wallMesh = instancedMesh(drystoneStone(vnoise), new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.94 }), {
85
+ matrices: new Float32Array(stones),
86
+ colours: new Float32Array(tintsOut),
87
+ });
88
+ wallMesh.castShadow = wallMesh.receiveShadow = true;
89
+ worldGroup.add(wallMesh);
90
+
91
+ const placeProp = (build, x, z, roughness) => {
92
+ const gb = new GeometryBuilder();
93
+ build(gb);
94
+ const mesh = gb.mesh(new THREE.MeshStandardMaterial({ vertexColors: true, roughness }), worldGroup);
95
+ if (mesh) {
96
+ mesh.position.set(x, groundExact(x, z), z);
97
+ mesh.updateMatrix();
98
+ }
99
+ };
100
+ placeProp(gb => buildHaystacks(gb, mulberry32(seed * 59), { noise: vnoise, box: shapes.box }), 186, 86, 0.96);
101
+ placeProp(gb => buildStonePile(gb, mulberry32(seed * 61), { rock: shapes.rock }), 196, 80, 0.92);
102
+ }
@@ -37,8 +37,8 @@
37
37
  <div class="caption">
38
38
  <h1>A baked land</h1>
39
39
  <p id="status">
40
- One height sheet baked row by row: coast, eroded hills, river with stoned banks, lake, draped earth road, drystone field walls,
41
- cliff-faced tel, quarry and port pad.
40
+ One height sheet baked row by row: coast, eroded hills, river springhead and stoned banks, lake, draped earth road, drystone
41
+ enclosure with haystacks and stone pile, cliff-faced tel, quarry and port pad.
42
42
  </p>
43
43
  </div>
44
44
  <div class="tools">
package/examples/land.js CHANGED
@@ -12,17 +12,10 @@ import {
12
12
  createRenderContext,
13
13
  createSimpleWater,
14
14
  createTownGround,
15
- createUnitShapes,
16
- drystoneStone,
17
15
  landEdgeGrid,
18
- layRoads,
19
- meshStreamBanks,
20
16
  mulberry32,
21
- planDrystoneWall,
22
- planStreamBanks,
23
17
  } from 'roamwright';
24
18
  import { erodeHeightfield } from 'roamwright/geometry/erosion.js';
25
- import { instancedMesh } from 'roamwright/geometry/instances.js';
26
19
  import { createClearings, createRainRule } from 'roamwright/geometry/land-clearings.js';
27
20
  import { createSandRidges } from 'roamwright/geometry/land-dunes.js';
28
21
  import { landEdgeArrays } from 'roamwright/geometry/land-edge.js';
@@ -34,6 +27,7 @@ import { lerp, sstep } from 'roamwright/math/scalar.js';
34
27
  import { partsGeometry } from 'roamwright/geometry/foliage.js';
35
28
  import { createPlantTints } from 'roamwright/geometry/plant-tints.js';
36
29
  import { createTrees } from 'roamwright/geometry/plant-trees.js';
30
+ import { buildLandFeatures } from './land-features.js';
37
31
  import { readSeed } from './stage.js';
38
32
 
39
33
  const seed = readSeed(7);
@@ -369,71 +363,7 @@ const groundExact = (x, z) => {
369
363
  return fx + fz <= 1 ? h00 + (h10 - h00) * fx + (h01 - h00) * fz : h11 + (h01 - h11) * (1 - fx) + (h10 - h11) * (1 - fz);
370
364
  };
371
365
 
372
- // Earth road ribbon draped along the banked road across the river ford.
373
- const roadColor = (tone, mul) => ({ r: SRGB2LIN[tone[0]] * mul, g: SRGB2LIN[tone[1]] * mul, b: SRGB2LIN[tone[2]] * mul });
374
- const roadSoil = roadColor(TONE.debris, 0.72),
375
- roadVerge = roadColor(TONE.grass, 0.9);
376
- layRoads({
377
- roads: land.roads.map(r => ({ pts: r.pts, w: r.w, crown: 0.15, fadeStart: 20, fadeEnd: 20 })),
378
- parent: worldGroup,
379
- ground: groundExact,
380
- soil: () => roadSoil,
381
- verge: () => roadVerge,
382
- material: () => new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.96, transparent: true }),
383
- });
384
-
385
- // Stream bank boulders, shingle bars and driftwood along the river channel.
386
- {
387
- const [river] = waters.channels;
388
- const riverPts = river.line.filter(([, z]) => z <= SHORE_Z + 10);
389
- const bed = Float32Array.from(riverPts, ([x, z]) => groundExact(x, z) - 0.4);
390
- const level = Float32Array.from(riverPts, (_, i) => Math.max(river.level(i / Math.max(1, river.n - 1)), SEA + 0.06));
391
- const plans = planStreamBanks({
392
- rivers: [{ fine: riverPts, bed, level, w: river.width }],
393
- waterLevel: SEA,
394
- ground: groundExact,
395
- random: mulberry32(seed * 41),
396
- });
397
- const shapes = createUnitShapes(fbm);
398
- meshStreamBanks({
399
- plans,
400
- stone: { geometry: shapes.rock, material: new THREE.MeshStandardMaterial({ roughness: 0.92 }) },
401
- log: { geometry: shapes.cyl, material: new THREE.MeshStandardMaterial({ roughness: 0.95 }) },
402
- parent: worldGroup,
403
- });
404
- }
405
-
406
- // Drystone field enclosure beside the road east of the river ford.
407
- {
408
- const wallRng = mulberry32(seed * 53);
409
- const wallCorners = [
410
- [168, 62],
411
- [224, 66],
412
- [220, 118],
413
- [164, 114],
414
- ];
415
- const stones = [],
416
- tintsOut = [];
417
- for (let i = 0; i < wallCorners.length; i++) {
418
- const a = wallCorners[i],
419
- b = wallCorners[(i + 1) % wallCorners.length];
420
- const segs = Math.max(1, Math.round(Math.hypot(b[0] - a[0], b[1] - a[1]) / 6));
421
- for (let s = 0; s < segs; s++) {
422
- if (i === 0 && s === Math.floor(segs / 2)) continue; // gateway facing the road
423
- const p0 = [lerp(a[0], b[0], s / segs), lerp(a[1], b[1], s / segs)];
424
- const p1 = [lerp(a[0], b[0], (s + 1) / segs), lerp(a[1], b[1], (s + 1) / segs)];
425
- const planned = planDrystoneWall(p0, p1, 0.95, wallRng, { ground: groundExact });
426
- stones.push(...planned.stones);
427
- tintsOut.push(...planned.tints);
428
- }
429
- }
430
- const wallMesh = instancedMesh(drystoneStone(vnoise), new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.94 }), {
431
- matrices: new Float32Array(stones),
432
- colours: new Float32Array(tintsOut),
433
- });
434
- wallMesh.castShadow = wallMesh.receiveShadow = true;
435
- worldGroup.add(wallMesh);
436
- }
366
+ buildLandFeatures({ worldGroup, land, waters, groundExact, sea: SEA, shoreZ: SHORE_Z, tones: TONE, seed, fbm, vnoise });
437
367
 
438
368
  createDaylightSky({
439
369
  scene,
@@ -450,7 +380,7 @@ createDaylightSky({
450
380
  });
451
381
 
452
382
  const status = document.querySelector('#status');
453
- status.textContent = `${STRIDE} × ${STRIDE} points (${sheet.spacing} m step): coast, eroded hills, river with stoned banks, mere, draped earth road, drystone field walls, cliff-faced tel, quarry and port pad.`;
383
+ status.textContent = `${STRIDE} × ${STRIDE} points (${sheet.spacing} m step): coast, eroded hills, river springhead and stoned banks, mere, draped earth road, drystone enclosure with haystacks and stone pile, cliff-faced tel, quarry and port pad.`;
454
384
 
455
385
  const views = {
456
386
  coast: { eye: [365, 138, 440], target: [35, 8, -35] },
@@ -0,0 +1,142 @@
1
+ import { IRRIGATED_FIELDS } from './irrigated-fields.js';
2
+
3
+ /**
4
+ * Default ring grids and placement dimensions (in metres) for standing crop tufts over irrigated fields: three nested rings
5
+ * around the camera (close drilled plants stepping out to wider clumps), drilled row pitch, worked-ground threshold, bund
6
+ * footpath clearance, palm watering-basin clearance, tuft blade height normalization, maximum clump width, edge taper room,
7
+ * and grain-ear edge margin.
8
+ */
9
+ export const FARM_CROPS = Object.freeze({
10
+ rings: Object.freeze([
11
+ Object.freeze({ cell: 0.45, half: 20, refill: 2 }),
12
+ Object.freeze({ cell: 0.9, half: 24, refill: 4 }),
13
+ Object.freeze({ cell: 1.6, half: 25, refill: 8 }),
14
+ ]),
15
+ rows: 0.69,
16
+ worked: 0.5,
17
+ path: 0.14,
18
+ bundExtra: 0.1,
19
+ basinClear: 1.7,
20
+ sink: 0.03,
21
+ blade: 0.82,
22
+ widest: 1.3,
23
+ room: Object.freeze([0.3, 1.2]),
24
+ earRoom: 1.2,
25
+ });
26
+
27
+ /**
28
+ * Default crop stand profiles (density share, width multiplier, max height in metres, linear RGB colour, optional drilled row
29
+ * pitch in metres and grain-ear flag) for each irrigated parcel state (`crop`, `ripe`, `cut`, `old`, `garden`, `grove`,
30
+ * `verge`, `bund`). Callers supply their own table to match a world's ground palette and crops.
31
+ */
32
+ export const DEFAULT_CROP_STANDS = Object.freeze({
33
+ crop: Object.freeze({ share: 1, wide: 1.1, high: 0.62, tone: Object.freeze([0.16, 0.24, 0.08]), rows: FARM_CROPS.rows }),
34
+ ripe: Object.freeze({ share: 1, wide: 1.1, high: 0.95, tone: Object.freeze([0.42, 0.31, 0.12]), ears: true, rows: FARM_CROPS.rows }),
35
+ cut: Object.freeze({ share: 0.6, wide: 0.6, high: 0.16, tone: Object.freeze([0.34, 0.26, 0.13]), rows: FARM_CROPS.rows }),
36
+ old: Object.freeze({ share: 0.4, wide: 0.8, high: 0.3, tone: Object.freeze([0.29, 0.22, 0.11]) }),
37
+ garden: Object.freeze({ share: 0.85, wide: 0.75, high: 0.34, tone: Object.freeze([0.14, 0.22, 0.09]) }),
38
+ grove: Object.freeze({ share: 0.2, wide: 0.7, high: 0.4, tone: Object.freeze([0.15, 0.21, 0.08]) }),
39
+ verge: Object.freeze({ share: 0.75, wide: 0.9, high: 0.85, tone: Object.freeze([0.15, 0.2, 0.06]) }),
40
+ bund: Object.freeze({ share: 0.45, wide: 0.6, high: 0.3, tone: Object.freeze([0.3, 0.25, 0.13]) }),
41
+ });
42
+
43
+ /**
44
+ * Create a zero-allocation crop-tuft placer (`cropAt`) and stand resolver (`standOf`) for irrigated parcels built with
45
+ * `createIrrigatedFields`, ready to pass directly into a scatter grid or `tuftPatch`.
46
+ *
47
+ * @param {object} options
48
+ * @param {(x: number, z: number) => object} options.fieldAt - Queries the irrigated field state at `(x, z)` metres.
49
+ * @param {() => number} options.gardenBed - Evaluates the garden bed value at the last queried field point (`< bedBare` is bare/furrow).
50
+ * @param {(x: number, z: number) => number} options.ground - Terrain height sampler at `(x, z)` in metres.
51
+ * @param {typeof DEFAULT_CROP_STANDS} [options.stands=DEFAULT_CROP_STANDS] - Per-state crop stand definitions and linear RGB tones.
52
+ * @param {number} [options.ears=0] - Encoded flower/ear attribute value written to `tuft.flower` on ripe stands clear of parcel edges.
53
+ * @param {Partial<typeof IRRIGATED_FIELDS>} [options.fieldShape=IRRIGATED_FIELDS] - Parcel geometry thresholds (`bank`, `bedBare`, `bund`, `palmPitch`, `verge`).
54
+ * @param {Partial<typeof FARM_CROPS>} [options.shape] - Overrides for {@link FARM_CROPS}.
55
+ * @returns {{
56
+ * cropAt: (x: number, z: number, h1: number, h2: number, ix: number, iz: number, tuft: object, cell: number) => boolean,
57
+ * standOf: (field: object) => object | null,
58
+ * rings: readonly { cell: number, half: number, refill: number }[]
59
+ * }}
60
+ */
61
+ export function createCropPlacer({
62
+ fieldAt,
63
+ gardenBed,
64
+ ground,
65
+ stands = DEFAULT_CROP_STANDS,
66
+ ears = 0,
67
+ fieldShape = IRRIGATED_FIELDS,
68
+ shape = {},
69
+ }) {
70
+ const bank = fieldShape.bank ?? IRRIGATED_FIELDS.bank,
71
+ bedBare = fieldShape.bedBare ?? IRRIGATED_FIELDS.bedBare,
72
+ bund = fieldShape.bund ?? IRRIGATED_FIELDS.bund,
73
+ palmPitch = fieldShape.palmPitch ?? IRRIGATED_FIELDS.palmPitch,
74
+ verge = fieldShape.verge ?? IRRIGATED_FIELDS.verge;
75
+ const rings = shape.rings ?? FARM_CROPS.rings,
76
+ worked = shape.worked ?? FARM_CROPS.worked,
77
+ path = shape.path ?? FARM_CROPS.path,
78
+ bundClear = bund + (shape.bundExtra ?? FARM_CROPS.bundExtra),
79
+ basinClear = shape.basinClear ?? FARM_CROPS.basinClear,
80
+ basinClearSq = basinClear * basinClear,
81
+ sink = shape.sink ?? FARM_CROPS.sink,
82
+ blade = shape.blade ?? FARM_CROPS.blade,
83
+ widest = shape.widest ?? FARM_CROPS.widest,
84
+ room = shape.room ?? FARM_CROPS.room,
85
+ earRoom = shape.earRoom ?? FARM_CROPS.earRoom;
86
+
87
+ // What stands in a parcel worked as `field` says, at the point it was asked about: one of `stands`, or null.
88
+ function standOf(field) {
89
+ switch (field.use) {
90
+ case 'crop':
91
+ return stands.crop;
92
+ case 'ripe':
93
+ return field.work > 0 ? stands.cut : stands.ripe;
94
+ case 'stubble':
95
+ return stands.cut;
96
+ case 'tilled':
97
+ return field.work > 0 ? null : stands.old; // nothing on a turned furrow
98
+ case 'garden':
99
+ return gardenBed() < bedBare ? null : stands.garden; // nor in a bed's furrow, or a bed left bare
100
+ default: {
101
+ // A grove: keep each palm's watering basin clear.
102
+ const a = (Math.floor(field.a / palmPitch) + 0.5) * palmPitch - field.a,
103
+ b = (Math.floor(field.b / palmPitch) + 0.5) * palmPitch - field.b;
104
+ return a * a + b * b < basinClearSq ? null : stands.grove;
105
+ }
106
+ }
107
+ }
108
+
109
+ // Decide whether a crop tuft stands in a cell at (x, z) of width `cell` metres and write its transform/colour into `tuft`.
110
+ function cropAt(x, z, h1, h2, ix, iz, tuft, cell) {
111
+ const field = fieldAt(x, z);
112
+ if (field.net < worked) return false;
113
+ let stand = stands.verge;
114
+ if (field.water < verge) {
115
+ if (field.water < bank) return false; // a canal's water and its dug bank
116
+ } else if (field.edge < bundClear || field.end < bundClear) {
117
+ if (Math.min(field.edge, field.end) < path) return false;
118
+ stand = stands.bund;
119
+ } else if (field.k < worked) return false;
120
+ else stand = standOf(field);
121
+ if (!stand || h2 > stand.share) return false;
122
+ if (stand.rows && cell < stand.rows) {
123
+ // Drilled grain rows where the grid is finer than the row pitch: step across the parcel to the nearest row.
124
+ const step = Math.round(field.a / stand.rows) * stand.rows - field.a;
125
+ tuft.x = x + step * field.axes[0];
126
+ tuft.z = z + step * field.axes[1];
127
+ }
128
+ const edgeRoom = stand === stands.verge || stand === stands.bund ? widest : room[0] + room[1] * Math.min(field.edge, field.end),
129
+ wide = Math.min(widest, edgeRoom, cell * stand.wide * (0.8 + h1 * 0.4)),
130
+ shade = 0.85 + h1 * 0.35;
131
+ tuft.y = ground(tuft.x, tuft.z) - sink;
132
+ tuft.wide = wide;
133
+ tuft.tall = (stand.high * (0.88 + h1 * 0.24)) / blade;
134
+ tuft.r = stand.tone[0] * shade;
135
+ tuft.g = stand.tone[1] * shade;
136
+ tuft.b = stand.tone[2] * shade;
137
+ tuft.flower = stand.ears && Math.min(field.edge, field.end) > earRoom ? ears : 0;
138
+ return true;
139
+ }
140
+
141
+ return { cropAt, standOf, rings };
142
+ }
@@ -0,0 +1,107 @@
1
+ import { dim } from '../math/color.js';
2
+ import { createNoise } from '../math/noise.js';
3
+ import { TAU } from '../math/scalar.js';
4
+ import { C, TRS, box, createUnitShapes, stick } from './primitives.js';
5
+ import { sampleSurface } from './sampled-surface.js';
6
+
7
+ let fallbackRock = null;
8
+ const defaultRock = () => (fallbackRock ??= createUnitShapes().rock);
9
+
10
+ /**
11
+ * Default proportions, mesh resolution and straw colours (sRGB hex) for stacked farmyard haystacks built by
12
+ * {@link buildHaystacks}. Dimensions are in metres.
13
+ */
14
+ export const FARM_HAYSTACK = Object.freeze({
15
+ count: 2,
16
+ spacing: 3.05,
17
+ offsetX: -1.1,
18
+ height: Object.freeze([1.75, 0.65]),
19
+ radius: Object.freeze([1.32, 0.2]),
20
+ strawColor: 0xa89255,
21
+ strawJitter: 0.12,
22
+ strandColors: Object.freeze([0xa59157, 0xc8ad6e]),
23
+ strandJitter: 0.13,
24
+ strands: 126,
25
+ columns: 29,
26
+ rows: 18,
27
+ noiseSeed: 370,
28
+ });
29
+
30
+ /**
31
+ * Default stone count, footprint radii, diameter range (in metres) and sRGB stone colours for field-cleared stone piles built
32
+ * by {@link buildStonePile}.
33
+ */
34
+ export const FARM_STONE_PILE = Object.freeze({
35
+ count: 22,
36
+ radiusX: 1.4,
37
+ radiusZ: 1.05,
38
+ size: Object.freeze([0.3, 0.55]),
39
+ colors: Object.freeze([0x544935, 0x7d6e53]),
40
+ colorJitter: 0.24,
41
+ });
42
+
43
+ /**
44
+ * Build one or more tall farmyard haystacks (by default a pair side by side) with weathered, bulging straw bodies and loose
45
+ * projecting straw wisps into a geometry builder.
46
+ *
47
+ * @param {Pick<import('./builder.js').GB, 'raw' | 'add'>} builder - Destination geometry builder (e.g. a kit's cloth builder).
48
+ * @param {() => number} [random=Math.random] - Repeatable random stream in `[0, 1)`.
49
+ * @param {object} [options]
50
+ * @param {(x: number, z: number, seed: number) => number} [options.noise] - Seeded value noise (`createNoise().vnoise`).
51
+ * @param {import('three').BufferGeometry} [options.box] - Unit box geometry for loose straw wisps (defaults to `primitives.box`).
52
+ * @param {Partial<typeof FARM_HAYSTACK>} [options.shape] - Overrides for {@link FARM_HAYSTACK}.
53
+ */
54
+ export function buildHaystacks(builder, random = Math.random, options = {}) {
55
+ const noise = options.noise ?? createNoise().vnoise,
56
+ strandBox = options.box ?? box,
57
+ cfg = options.shape ? { ...FARM_HAYSTACK, ...options.shape } : FARM_HAYSTACK,
58
+ { count, spacing, offsetX, height, radius, strawColor, strawJitter, strandColors, strandJitter, strands, columns, rows, noiseSeed } =
59
+ cfg;
60
+ for (let i = 0; i < count; i++) {
61
+ const px = i * spacing + offsetX,
62
+ h = height[0] + random() * height[1],
63
+ wide = radius[0] + random() * radius[1];
64
+ const straw = C(strawColor, strawJitter, random);
65
+ const fibre = (u, v, offset = 0) => {
66
+ const a = u * TAU,
67
+ sn = Math.sin(a),
68
+ cs = Math.cos(a);
69
+ const profile = v < 0.45 ? 0.87 + 0.29 * Math.sin(v * 3.1) : 1.14 * ((1 - v) / 0.55) ** 0.73;
70
+ const r = wide * profile * (0.96 + 0.09 * noise(4 * cs + i * 9, 4 * sn + 7 * v, noiseSeed)) + offset;
71
+ return [px + cs * r - v * 0.21, h * v - 0.15 + 0.07 * sn * (1 - v), sn * r * 0.84 + v * 0.16];
72
+ };
73
+ sampleSurface(builder, columns, rows, fibre, (u, v) => dim(straw, (0.88 + random() * 0.22) * (0.73 + 0.29 * Math.sin(v * 1.9))));
74
+ for (let j = 0; j < strands; j++) {
75
+ const u = random(),
76
+ v = 0.04 + random() * 0.87,
77
+ strand = C(j % 3 ? strandColors[0] : strandColors[1], strandJitter, random);
78
+ stick(builder, fibre(u, v, 0.025), fibre(u + (random() - 0.56) * 0.044, v + 0.035, random() * 0.09), 0.011, strand, strandBox);
79
+ }
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Build a low mound of field-cleared stones into a geometry builder, piling stones higher toward the middle and scattering
85
+ * them wider around the base.
86
+ *
87
+ * @param {Pick<import('./builder.js').GB, 'add'>} builder - Destination geometry builder (e.g. a kit's wall/stone builder).
88
+ * @param {() => number} [random=Math.random] - Repeatable random stream in `[0, 1)`.
89
+ * @param {object} [options]
90
+ * @param {import('three').BufferGeometry} [options.rock] - Unit broken stone geometry (defaults to `createUnitShapes().rock`).
91
+ * @param {Partial<typeof FARM_STONE_PILE>} [options.shape] - Overrides for {@link FARM_STONE_PILE}.
92
+ */
93
+ export function buildStonePile(builder, random = Math.random, options = {}) {
94
+ const rock = options.rock ?? defaultRock(),
95
+ cfg = options.shape ? { ...FARM_STONE_PILE, ...options.shape } : FARM_STONE_PILE,
96
+ { count, radiusX, radiusZ, size, colors, colorJitter } = cfg;
97
+ for (let i = 0; i < count; i++) {
98
+ const a = random() * TAU,
99
+ r = Math.sqrt(random()),
100
+ d = size[0] + random() * size[1];
101
+ builder.add(
102
+ rock,
103
+ C(i % 6 ? colors[0] : colors[1], colorJitter, random),
104
+ TRS(Math.cos(a) * r * radiusX, 0.05 + (1 - r) * 0.46, Math.sin(a) * r * radiusZ, d * 1.55, d * 0.7, d, a, random(), random()),
105
+ );
106
+ }
107
+ }
@@ -1,4 +1,5 @@
1
1
  import { spacedCurve } from '../math/curve.js';
2
+ import { clamp } from '../math/scalar.js';
2
3
 
3
4
  /**
4
5
  * A plain's washes and trails, in metres: how far a herd's side trails swing away from the one they follow; the spacing of the
@@ -14,6 +15,110 @@ export const LAND_TRAILS = Object.freeze({
14
15
  far: 99, // the distance every cell starts at, beyond any radius marked
15
16
  });
16
17
 
18
+ /**
19
+ * Defaults for rasterizing fine 2-channel RG distance fields of herd trails (R) and dry washes (G), in metres:
20
+ * texel spacing (`step`), encoded distance reach per channel (`reach`), endpoint tapering length (`head`), and
21
+ * clearance margins around roads, rivers and cleared sites.
22
+ */
23
+ export const LAND_TRAIL_MARKS = Object.freeze({
24
+ step: 1.5,
25
+ reach: Object.freeze({ trail: 8, wash: 16 }),
26
+ head: Object.freeze({ trail: 30, wash: 70 }),
27
+ roadRoom: 9,
28
+ riverRoom: 15,
29
+ siteFade: 18,
30
+ });
31
+
32
+ /**
33
+ * Test whether a world-space XZ rectangle overlaps a marks bounding box `{ x0, z0, x1, z1 }`.
34
+ *
35
+ * @param {{ x0: number, z0: number, x1: number, z1: number }} bounds - Marks bounds in metres.
36
+ * @param {number} x0 - Query minimum X in metres.
37
+ * @param {number} z0 - Query minimum Z in metres.
38
+ * @param {number} x1 - Query maximum X in metres.
39
+ * @param {number} z1 - Query maximum Z in metres.
40
+ * @returns {boolean}
41
+ */
42
+ export function boundsOverlap(bounds, x0, z0, x1, z1) {
43
+ return x1 > bounds.x0 && x0 < bounds.x1 && z1 > bounds.z0 && z0 < bounds.z1;
44
+ }
45
+
46
+ /**
47
+ * Rasterize herd trails (R channel) and dry washes (G channel) into a fine 2-channel `Uint8Array` distance field over
48
+ * `bounds`, tapering each line near its ends and fading marks near roads, rivers and cleared sites. Pure arithmetic, safe for
49
+ * workers and Node tests.
50
+ *
51
+ * @param {object} options
52
+ * @param {{ trails: number[][][], washes: number[][][] }} options.paths - Sampled polylines (`[x, z]` metres).
53
+ * @param {{ x0: number, z0: number, x1: number, z1: number }} options.bounds - World-space XZ extent in metres.
54
+ * @param {(x: number, z: number) => number} [options.road] - Metres to the nearest road.
55
+ * @param {(x: number, z: number) => number} [options.river] - Metres to the nearest river.
56
+ * @param {(x: number, z: number) => number} [options.siteDistance] - Metres to the nearest cleared site.
57
+ * @param {number} [options.siteRoom=LAND_TRAILS.siteRoom] - Inner clear radius around each site, in metres.
58
+ * @param {Partial<typeof LAND_TRAIL_MARKS>} [options.shape] - Overrides for {@link LAND_TRAIL_MARKS}.
59
+ * @returns {{ data: Uint8Array, width: number, height: number, rect: [number, number, number, number] }}
60
+ */
61
+ export function rasterizeTrailMarks({ paths, bounds, road, river, siteDistance, siteRoom = LAND_TRAILS.siteRoom, shape = {} }) {
62
+ const step = shape.step ?? LAND_TRAIL_MARKS.step,
63
+ reach = shape.reach ? { ...LAND_TRAIL_MARKS.reach, ...shape.reach } : LAND_TRAIL_MARKS.reach,
64
+ head = shape.head ? { ...LAND_TRAIL_MARKS.head, ...shape.head } : LAND_TRAIL_MARKS.head,
65
+ roadRoom = shape.roadRoom ?? LAND_TRAIL_MARKS.roadRoom,
66
+ riverRoom = shape.riverRoom ?? LAND_TRAIL_MARKS.riverRoom,
67
+ siteFade = shape.siteFade ?? LAND_TRAIL_MARKS.siteFade;
68
+ const { x0, z0, x1, z1 } = bounds,
69
+ width = Math.ceil((x1 - x0) / step),
70
+ height = Math.ceil((z1 - z0) / step),
71
+ data = new Uint8Array(width * height * 2).fill(255);
72
+ // `ends`: 1 when the line thins out at its head only (a gully runs into the next), 2 at both ends.
73
+ const stamp = (path, lineReach, lineHead, ends, channel) => {
74
+ const arc = [0];
75
+ for (let s = 1; s < path.length; s++) arc.push(arc[s - 1] + Math.hypot(path[s][0] - path[s - 1][0], path[s][1] - path[s - 1][1]));
76
+ for (let s = 1; s < path.length; s++) {
77
+ const fromEnd = ends > 1 ? Math.min(arc[s], arc[arc.length - 1] - arc[s]) : arc[s],
78
+ thin = lineReach * Math.max(0, 1 - fromEnd / lineHead) * 0.6; // the line's own distance starts this far out, so it draws narrower
79
+ const [ax, az] = path[s - 1],
80
+ [bx, bz] = path[s],
81
+ dx = bx - ax,
82
+ dz = bz - az,
83
+ len2 = dx * dx + dz * dz || 1;
84
+ const i0 = Math.max(0, Math.floor((Math.min(ax, bx) - lineReach - x0) / step)),
85
+ i1 = Math.min(width - 1, Math.ceil((Math.max(ax, bx) + lineReach - x0) / step)),
86
+ j0 = Math.max(0, Math.floor((Math.min(az, bz) - lineReach - z0) / step)),
87
+ j1 = Math.min(height - 1, Math.ceil((Math.max(az, bz) + lineReach - z0) / step));
88
+ for (let j = j0; j <= j1; j++)
89
+ for (let i = i0; i <= i1; i++) {
90
+ const x = x0 + (i + 0.5) * step,
91
+ z = z0 + (j + 0.5) * step,
92
+ t = clamp(((x - ax) * dx + (z - az) * dz) / len2, 0, 1),
93
+ near = Math.round(((Math.hypot(x - ax - dx * t, z - az - dz * t) + thin) / lineReach) * 255),
94
+ k = (j * width + i) * 2 + channel;
95
+ if (near < data[k]) data[k] = near;
96
+ }
97
+ }
98
+ };
99
+ for (const path of paths.trails) stamp(path, reach.trail, head.trail, 2, 0);
100
+ for (const path of paths.washes) stamp(path, reach.wash, head.wash, 1, 1);
101
+ // A mark fades out towards a road, running water and cleared sites.
102
+ const hasRoad = typeof road === 'function',
103
+ hasRiver = typeof river === 'function',
104
+ hasSites = typeof siteDistance === 'function';
105
+ if (hasRoad || hasRiver || hasSites)
106
+ for (let j = 0; j < height; j++)
107
+ for (let i = 0; i < width; i++) {
108
+ const k = (j * width + i) * 2;
109
+ if (data[k] === 255 && data[k + 1] === 255) continue;
110
+ const x = x0 + (i + 0.5) * step,
111
+ z = z0 + (j + 0.5) * step;
112
+ const crowded =
113
+ (hasRoad ? Math.max(0, roadRoom - road(x, z)) / roadRoom : 0) +
114
+ (hasRiver ? Math.max(0, riverRoom - river(x, z)) / riverRoom : 0) +
115
+ (hasSites ? clamp((siteRoom + siteFade - siteDistance(x, z)) / siteFade, 0, 1) : 0);
116
+ data[k] = Math.min(255, data[k] + crowded * 255);
117
+ data[k + 1] = Math.min(255, data[k + 1] + crowded * 255);
118
+ }
119
+ return { data, width, height, rect: [x0, z0, 1 / (width * step), 1 / (height * step)] };
120
+ }
121
+
17
122
  /**
18
123
  * Seasonal washes and the trails of herds over a plain. The washes converge on the outflow; several livestock tracks fan out
19
124
  * inland from shallow approaches, wearing the grass before the soil itself. Each is kept as the metres from every cell of the
@@ -94,6 +199,10 @@ export function createLandTrails({ noise, stamp, shape = {} }) {
94
199
  washD = trackD = cover = null;
95
200
  }
96
201
 
202
+ function rasterizeMarks({ bounds, road, river, shape: markShape } = {}) {
203
+ return rasterizeTrailMarks({ paths, bounds, road, river, siteDistance, siteRoom: SITE_ROOM, shape: markShape });
204
+ }
205
+
97
206
  return {
98
207
  siteRoom: SITE_ROOM,
99
208
  paths,
@@ -101,6 +210,7 @@ export function createLandTrails({ noise, stamp, shape = {} }) {
101
210
  forget,
102
211
  siteDistance,
103
212
  clear,
213
+ rasterizeMarks,
104
214
  washDistance: () => washD,
105
215
  trailDistance: () => trackD,
106
216
  cover: () => cover,
@@ -0,0 +1,236 @@
1
+ import { createNoise } from '../math/noise.js';
2
+ import { lerp, sstep, TAU } from '../math/scalar.js';
3
+
4
+ /**
5
+ * The layout of a stream's springhead and its soaked surround, in metres and turns: which point downstream sets the spring's
6
+ * bearing, rock fineness thresholds, how deeply loose stones sit in the earth, what hill slope behind the pool forms a rock
7
+ * cleft rather than a ring of boulders, and the reach and spacing of the wet-ground sheet.
8
+ */
9
+ export const SPRING_HEAD = Object.freeze({
10
+ /** Point index along `river.fine` that sets the downstream direction of the spring's local frame. */
11
+ aim: 6,
12
+ /** Rocks smaller than this diameter in metres use the coarsest rock fineness (1). */
13
+ stoneUnder: 0.45,
14
+ /** Rocks larger than this diameter in metres use the finest rock fineness (3); intermediate rocks use 2. */
15
+ block: 2.4,
16
+ /** Vertical centre offset of a loose rock above the terrain, as a share of its height. */
17
+ settled: 0.1,
18
+ /** Hillside slope measurement behind the spring (`back` to `far` metres upstream); steeper than `slope` builds a cleft. */
19
+ steep: Object.freeze({ back: 10, far: 24, slope: 0.3 }),
20
+ /** Boulders ringing a gentle spring's head: arc span in turns from downstream, radial reach and size range in metres. */
21
+ ring: Object.freeze({ from: 0.2, to: 0.8, near: 2.7, far: 4.4, small: 0.9, large: 2.3 }),
22
+ /** Soaked-ground strip: upstream/downstream reach, tail fade, half-width, column step, head/tail width and lift in metres. */
23
+ wet: Object.freeze({ behind: 9, along: 46, fade: 18, half: 11.2, step: 0.8, head: 8, tail: 5.6, lift: 0.06 }),
24
+ /** Value-noise seeds for the wet patch's ragged edge and local soil shade. */
25
+ wetNoise: Object.freeze([907, 911]),
26
+ /** Default spring eye offset along the stream as a share of the stream's full width. */
27
+ eyeRatio: 0.43,
28
+ });
29
+
30
+ /**
31
+ * Default linear RGB colours for springhead rocks and soaked earth: dry stone in sun, wet stone at the waterline, the dark
32
+ * interior of a rock cleft's throat, and soaked mud around the pool.
33
+ */
34
+ export const SPRING_COLOURS = Object.freeze({
35
+ dry: Object.freeze([0.36, 0.34, 0.3]),
36
+ wet: Object.freeze([0.17, 0.17, 0.16]),
37
+ dark: Object.freeze([0.012, 0.012, 0.011]),
38
+ mud: Object.freeze([0.075, 0.064, 0.048]),
39
+ });
40
+
41
+ /**
42
+ * Compute a spring's local coordinate frame from its stream polyline and surrounding terrain: `at(along, across)` maps metres
43
+ * downstream and to the left into world `[x, z]`, `eye` is the pool centre distance downstream, `turn` is the downstream yaw in
44
+ * radians, and `steep` indicates whether the slope behind the spring rises steeply enough to form a rock cleft.
45
+ *
46
+ * @param {{ fine: number[][], w: number }} river - Stream polyline (`[x, z]` points in metres) and stream width in metres.
47
+ * @param {object} options
48
+ * @param {(x: number, z: number) => number} options.ground - Terrain height sampler in metres.
49
+ * @param {number | ((width: number) => number)} [options.eye] - Pool centre distance downstream in metres, or a function of stream width.
50
+ * @param {Partial<typeof SPRING_HEAD>} [options.shape] - Overrides for {@link SPRING_HEAD}.
51
+ * @returns {{ at: (along: number, across: number) => [number, number], eye: number, turn: number, steep: boolean }}
52
+ */
53
+ export function springFrame(river, { ground, eye, shape = {} }) {
54
+ const aim = shape.aim ?? SPRING_HEAD.aim,
55
+ eyeRatio = shape.eyeRatio ?? SPRING_HEAD.eyeRatio,
56
+ steep = shape.steep ? { ...SPRING_HEAD.steep, ...shape.steep } : SPRING_HEAD.steep;
57
+ const [x, z] = river.fine[0],
58
+ [ax, az] = river.fine[aim],
59
+ length = Math.hypot(ax - x, az - z),
60
+ dx = (ax - x) / length,
61
+ dz = (az - z) / length,
62
+ eyeOffset = typeof eye === 'function' ? eye(river.w) : (eye ?? river.w * eyeRatio),
63
+ at = (along, across) => [x + dx * along - dz * across, z + dz * along + dx * across],
64
+ behind = (ground(...at(-steep.far, 0)) - ground(...at(-steep.back, 0))) / (steep.far - steep.back);
65
+ return { at, eye: eyeOffset, turn: Math.atan2(dx, dz), steep: behind > steep.slope };
66
+ }
67
+
68
+ /**
69
+ * Plan the rock placements around one springhead: either a hillside cleft (two leaning slabs over a dark throat, chockstone,
70
+ * capstone and flanking boulders) or a boulder-ringed hollow, followed by wet stones in the pool and stones strewn along the
71
+ * wet rill. Pure arithmetic, safe for workers and Node tests.
72
+ *
73
+ * @param {ReturnType<typeof springFrame>} frame - The spring's local frame from {@link springFrame}.
74
+ * @param {object} options
75
+ * @param {(x: number, z: number) => number} options.ground - Terrain height sampler in metres.
76
+ * @param {() => number} [options.random=Math.random] - Repeatable random stream in `[0, 1)`.
77
+ * @param {Partial<typeof SPRING_HEAD>} [options.shape] - Overrides for {@link SPRING_HEAD}.
78
+ * @param {Partial<typeof SPRING_COLOURS>} [options.colours] - Overrides for {@link SPRING_COLOURS}.
79
+ * @returns {number[]} Flat rows of 13 numbers per rock: `[x, y, z, sx, sy, sz, turn, leanX, leanZ, fineness, r, g, b]`.
80
+ */
81
+ export function planSpringRocks(frame, { ground, random = Math.random, shape = {}, colours = {} }) {
82
+ const stoneUnder = shape.stoneUnder ?? SPRING_HEAD.stoneUnder,
83
+ block = shape.block ?? SPRING_HEAD.block,
84
+ settled = shape.settled ?? SPRING_HEAD.settled,
85
+ ring = shape.ring ? { ...SPRING_HEAD.ring, ...shape.ring } : SPRING_HEAD.ring,
86
+ dry = colours.dry ?? SPRING_COLOURS.dry,
87
+ wetTone = colours.wet ?? SPRING_COLOURS.wet,
88
+ dark = colours.dark ?? SPRING_COLOURS.dark;
89
+ const fineness = size => (size < stoneUnder ? 1 : size < block ? 2 : 3);
90
+ const rr = (a, b) => a + random() * (b - a);
91
+ const rocks = [];
92
+ // One rock in the spring's frame: default lean and turn draw before shape and shade to preserve seeded stream order.
93
+ const rock = (along, across, size, wet, blockShape = null, lean = [rr(-0.4, 0.4), rr(-0.4, 0.4)], lift = 0, turn = random() * TAU) => {
94
+ const [px, pz] = frame.at(along, across),
95
+ [sx, sy, sz] = blockShape ?? [1.2, rr(0.6, 0.95), rr(0.8, 1.1)],
96
+ shade = rr(0.82, 1.18),
97
+ r = wet < 0 ? dark[0] : lerp(dry[0], wetTone[0], wet) * shade,
98
+ g = wet < 0 ? dark[1] : lerp(dry[1], wetTone[1], wet) * shade,
99
+ b = wet < 0 ? dark[2] : lerp(dry[2], wetTone[2], wet) * shade,
100
+ y = ground(px, pz) + (blockShape ? lift : size * sy * settled);
101
+ rocks.push(px, y, pz, size * sx, size * sy, size * sz, turn, lean[0], lean[1], fineness(size * Math.max(sx, sy, sz)), r, g, b);
102
+ };
103
+ if (frame.steep) {
104
+ // A cleft: two slabs leaning together over a dark throat, a chockstone wedged between them and a capstone across their heads.
105
+ rock(-1.3, 1.75, 1, 0.35, [2.6, 4.9, 3.4], [-0.14, -0.19], 1.5, frame.turn + 0.12);
106
+ rock(-1.2, -1.8, 1, 0.3, [2.4, 4.4, 3.1], [-0.1, 0.21], 1.3, frame.turn - 0.1);
107
+ rock(-2.5, 0, 1, -1, [1.7, 3.6, 1.6], [0, 0], 1.1, frame.turn);
108
+ rock(-1.5, 0.05, 1.25, 0.2, [1.1, 0.9, 1.2], [0.3, 0.5], 2.9);
109
+ rock(-1.9, 0.1, 1, 0.1, [5.0, 1.5, 3.6], [-0.1, 0.07], 4.3, frame.turn + 0.2);
110
+ for (const side of [-1, 1]) {
111
+ rock(-0.4 + rr(-0.5, 0.5), side * rr(3.4, 4.2), rr(1.4, 2.0), 0.25);
112
+ rock(-2.2 + rr(-0.6, 0.6), side * rr(3.6, 4.8), rr(1.0, 1.7), 0.1);
113
+ rock(0.8 + rr(-0.4, 0.4), side * rr(2.6, 3.2), rr(0.7, 1.1), 0.6);
114
+ }
115
+ } else {
116
+ // A hollow: boulders ringing the pool's head, the largest at its back, and a second rank behind them.
117
+ const stand = 9;
118
+ for (let i = 0; i < stand; i++) {
119
+ const round = lerp(ring.from, ring.to, (i + rr(0.2, 0.8)) / stand),
120
+ back = 1 - Math.abs(round - 0.5) / 0.3,
121
+ reach = rr(ring.near, ring.far) - back * 0.4;
122
+ rock(
123
+ frame.eye + Math.cos(round * TAU) * reach,
124
+ Math.sin(round * TAU) * reach,
125
+ lerp(ring.small, ring.large, back * rr(0.55, 1)),
126
+ 0.45,
127
+ );
128
+ }
129
+ for (let i = 0; i < 6; i++) {
130
+ const round = rr(0.27, 0.73),
131
+ reach = rr(5.0, 7.2);
132
+ rock(frame.eye + Math.cos(round * TAU) * reach, Math.sin(round * TAU) * reach, rr(0.55, 1.3), 0.1);
133
+ }
134
+ }
135
+ // Stones in the pool and its outlet, wet and half sunk; then stones strewn over the wet ground and along the rill.
136
+ for (let i = 0; i < 9; i++) rock(frame.eye + rr(-1.8, 5), rr(-1.5, 1.5), rr(0.2, 0.55), 1);
137
+ for (let i = 0; i < 54; i++) {
138
+ const along = rr(-5, 30),
139
+ spread = lerp(6.5, 4.2, sstep(0, 20, along)),
140
+ across = rr(-1, 1) * spread;
141
+ rock(along, across, lerp(0.1, 0.5, random() ** 2.2), sstep(spread, 1, Math.abs(across)) * 0.8);
142
+ }
143
+ return rocks;
144
+ }
145
+
146
+ /**
147
+ * Build the vertex arrays of a spring's soaked-ground sheet: a strip draped over the terrain round the pool and down both
148
+ * sides of the rill, with RGBA vertex colours whose alpha thins out along a noise-ragged margin. Pure typed-array builder.
149
+ *
150
+ * @param {{ fine: number[][] }} river - Stream polyline (`[x, z]` points in metres).
151
+ * @param {ReturnType<typeof springFrame>} frame - The spring's local frame from {@link springFrame}.
152
+ * @param {object} options
153
+ * @param {(x: number, z: number) => number} options.drawnGround - Drawn triangle height of the terrain mesh in metres.
154
+ * @param {(x: number, z: number, seed: number) => number} [options.noise] - Seeded value noise (`createNoise().vnoise`).
155
+ * @param {Partial<typeof SPRING_HEAD>} [options.shape] - Overrides for {@link SPRING_HEAD}.
156
+ * @param {Partial<typeof SPRING_COLOURS>} [options.colours] - Overrides for {@link SPRING_COLOURS}.
157
+ * @returns {{ position: Float32Array, normal: Float32Array, color: Float32Array, index: number[] }}
158
+ */
159
+ export function springWetGround(river, frame, { drawnGround, noise = createNoise().vnoise, shape = {}, colours = {} }) {
160
+ const wet = shape.wet ? { ...SPRING_HEAD.wet, ...shape.wet } : SPRING_HEAD.wet,
161
+ wetNoise = shape.wetNoise ?? SPRING_HEAD.wetNoise,
162
+ mud = colours.mud ?? SPRING_COLOURS.mud,
163
+ pts = river.fine,
164
+ rows = [];
165
+ for (let along = -wet.behind; along < 0; along += 1.5) {
166
+ const [x, z] = frame.at(along, 0),
167
+ [lx, lz] = frame.at(along, 1);
168
+ rows.push({ along, x, z, nx: lx - x, nz: lz - z });
169
+ }
170
+ for (let i = 0, along = 0; along < wet.along && i < pts.length - 1; i++) {
171
+ const a = pts[Math.max(0, i - 1)],
172
+ b = pts[i + 1],
173
+ length = Math.hypot(b[0] - a[0], b[1] - a[1]);
174
+ rows.push({ along, x: pts[i][0], z: pts[i][1], nx: -(b[1] - a[1]) / length, nz: (b[0] - a[0]) / length });
175
+ along += Math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]);
176
+ }
177
+ const columns = Math.round((wet.half * 2) / wet.step) + 1,
178
+ position = new Float32Array(rows.length * columns * 3),
179
+ normal = new Float32Array(rows.length * columns * 3),
180
+ color = new Float32Array(rows.length * columns * 4),
181
+ index = [];
182
+ rows.forEach((row, i) => {
183
+ const reach =
184
+ row.along < 0 ? wet.head * Math.sqrt(1 - (row.along / wet.behind) ** 2) : lerp(wet.head, wet.tail, sstep(0, 16, row.along)),
185
+ ending = sstep(wet.along, wet.along - wet.fade, row.along);
186
+ for (let j = 0; j < columns; j++) {
187
+ const across = j * wet.step - wet.half,
188
+ x = row.x + row.nx * across,
189
+ z = row.z + row.nz * across,
190
+ v = i * columns + j,
191
+ ragged = reach * (0.7 + 0.6 * noise(x / 2.7, z / 2.7, wetNoise[0])),
192
+ shade = 0.75 + 0.5 * noise(x / 1.3, z / 1.3, wetNoise[1]);
193
+ position.set([x, drawnGround(x, z) + wet.lift, z], v * 3);
194
+ normal.set([0, 1, 0], v * 3);
195
+ color.set([mud[0] * shade, mud[1] * shade, mud[2] * shade, 0.94 * ending * sstep(ragged, ragged * 0.45, Math.abs(across))], v * 4);
196
+ if (i < rows.length - 1 && j < columns - 1) index.push(v, v + 1, v + columns, v + 1, v + columns + 1, v + columns);
197
+ }
198
+ });
199
+ return { position, normal, color, index };
200
+ }
201
+
202
+ /**
203
+ * Plan the springheads and soaked ground for every rising stream in `rivers` (entries carrying a `level` profile). Pure
204
+ * arithmetic, suitable for the page or a worker.
205
+ *
206
+ * @param {object} options
207
+ * @param {{ fine: number[][], w: number, level?: Float32Array | number[] }[]} options.rivers - Streams to inspect; rivers without `level` are skipped.
208
+ * @param {(x: number, z: number) => number} options.ground - Terrain height sampler in metres, for rocks and slope checks.
209
+ * @param {(x: number, z: number) => number} [options.drawnGround=options.ground] - Drawn mesh triangle height in metres, for the wet-ground sheet.
210
+ * @param {number | ((width: number) => number)} [options.eye] - Pool centre distance downstream in metres, or a function of stream width.
211
+ * @param {(x: number, z: number, seed: number) => number} [options.noise] - Seeded value noise (`createNoise().vnoise`).
212
+ * @param {() => number} [options.random=Math.random] - Repeatable random stream shared across springs in order.
213
+ * @param {Partial<typeof SPRING_HEAD>} [options.shape] - Overrides for {@link SPRING_HEAD}.
214
+ * @param {Partial<typeof SPRING_COLOURS>} [options.colours] - Overrides for {@link SPRING_COLOURS}.
215
+ * @returns {{ frame: ReturnType<typeof springFrame>, wetGround: ReturnType<typeof springWetGround>, rocks: number[] }[]}
216
+ */
217
+ export function planSprings({
218
+ rivers,
219
+ ground,
220
+ drawnGround = ground,
221
+ eye,
222
+ noise = createNoise().vnoise,
223
+ random = Math.random,
224
+ shape = {},
225
+ colours = {},
226
+ }) {
227
+ const plans = [];
228
+ for (const river of rivers) {
229
+ if (!river.level) continue;
230
+ const frame = springFrame(river, { ground, eye, shape }),
231
+ wetGround = springWetGround(river, frame, { drawnGround, noise, shape, colours }),
232
+ rocks = planSpringRocks(frame, { ground, random, shape, colours });
233
+ plans.push({ frame, wetGround, rocks });
234
+ }
235
+ return plans;
236
+ }
package/index.js CHANGED
@@ -52,13 +52,17 @@ export { planTalusStones } from './geometry/strata-talus.js';
52
52
  export { meshTalusStones } from './rendering/strata-talus.js';
53
53
  export { planStreamBanks } from './geometry/stream-banks.js';
54
54
  export { meshStreamBanks } from './rendering/stream-banks.js';
55
+ export { SPRING_COLOURS, SPRING_HEAD, planSpringRocks, planSprings, springFrame, springWetGround } from './geometry/stream-springs.js';
56
+ export { meshSprings } from './rendering/stream-springs.js';
55
57
  export { planShoreReeds } from './geometry/shore-reeds.js';
56
58
  export { roadRibbon } from './geometry/road-ribbon.js';
57
59
  export { layRoads } from './rendering/road-ribbons.js';
58
60
  export { createRoadTraffic, ROAD_TRAFFIC } from './motion/road-traffic.js';
59
61
  export { createFieldSurvey, FIELD_SURVEY, FIELD_USE } from './geometry/field-survey.js';
60
- export { createLandTrails, LAND_TRAILS } from './geometry/land-trails.js';
62
+ export { LAND_TRAILS, LAND_TRAIL_MARKS, boundsOverlap, createLandTrails, rasterizeTrailMarks } from './geometry/land-trails.js';
63
+ export { createTrailMarks, trailMarksGLSL } from './rendering/land-trail-surface.js';
61
64
  export { createIrrigatedFields, IRRIGATED_FIELDS } from './geometry/irrigated-fields.js';
65
+ export { DEFAULT_CROP_STANDS, FARM_CROPS, createCropPlacer } from './geometry/farm-crops.js';
62
66
  export { createIrrigatedFieldSurface, IRRIGATED_FIELD_KIND, IRRIGATED_FIELD_SURFACE } from './rendering/irrigated-field-surface.js';
63
67
  export { DRYSTONE_WALL, FIELD_STONE, drystoneStone, planDrystoneWall } from './geometry/drystone-wall.js';
64
68
  export { DEFAULT_FENCE_STYLE, addFenceRing, buildFenceRing } from './geometry/timber-fence.js';
@@ -70,6 +74,7 @@ export { DEFAULT_LIVESTOCK_CASTS, createLivestockCache } from './rendering/farm-
70
74
  export { DEFAULT_FARM_HERDS, FARM_LIFE, herdPlaces, parcelPlaces, planFarmLife, ploughSite } from './geometry/farm-life.js';
71
75
  export { STOOK, createStook } from './geometry/prop-stook.js';
72
76
  export { PLOUGH, ploughGear } from './geometry/prop-plough.js';
77
+ export { FARM_HAYSTACK, FARM_STONE_PILE, buildHaystacks, buildStonePile } from './geometry/farm-props.js';
73
78
 
74
79
  // ── Settlements, houses, fortifications & interiors ──────────────────────
75
80
  export { createHouseKit } from './geometry/house-kit.js';
@@ -188,7 +188,8 @@ function createFigureArms({ gestureOf, seat, blade, flier = () => false, dropInt
188
188
  }
189
189
  w.foreL = foreL;
190
190
  w.foreR = foreR;
191
- if (seated > FELT) seatedArms(a, w, a.cur[TRUNK]);
191
+ // an act has the arms it names even in the saddle or on a seat: the seat keeps only the rest
192
+ if (seated > FELT) seatedArms(a, w, a.cur[TRUNK], act ? 1 - act[HAS_LEFT] : 1, act ? 1 - act[HAS_RIGHT] : 1);
192
193
  const flatL = (held && held.r && !held.stow && (held.both || held.left)) || (held && held.flat),
193
194
  flatR = held && held.r && !held.stow && !held.left;
194
195
  let turnL = seated * onTable(a, true) * (0.42 + a.seed * 0.2) + (gesture ? gesture[LY] : 0) + recTurnL,
@@ -58,7 +58,7 @@ const FLAT = () => 0,
58
58
  * metres, table: the height of a table before it, if any }) is in the place being shown; every seat is, by default.
59
59
  * @returns {object} seatTarget(a, w, t) and kneelTarget(a, w, footGround): the pose's targets for this frame on a seat (a
60
60
  * stool, a horse: `a.mount`) or on one knee, with `a.joints` solved; groundUnderKnee(a, size): the ground under a kneeling
61
- * figure's forward foot (and into `a.y` under its knee); seatedArms(a, w, lean); onTable(a, left); kneeOf(a, left);
61
+ * figure's forward foot (and into `a.y` under its knee); seatedArms(a, w, lean, freeL, freeR) (freeL, freeR: each arm's share left to the seat, 1 by default; an act takes the rest); onTable(a, left); kneeOf(a, left);
62
62
  * freeKnees(a, thighL, thighR); conformGroundPosture(a, w, target) and groundConformState(): a
63
63
  * crawler's or a lying body's fit to the slope under it.
64
64
  */
@@ -186,15 +186,16 @@ function createFigureSeat({ ground = FLAT, seatHere = ANY_SEAT } = {}) {
186
186
  CLOSEST = 0.14; // and one nearer the shoulder than this is taken as this far
187
187
  const armIK = (forward, up) => solveTwoBone(reach, UPPER_ARM, FOREARM, forward, up, CLOSEST, (UPPER_ARM + FOREARM) * FULL_REACH);
188
188
  // A seated figure's arms reach for where its hands rest (seatTarget), as far as it is seated.
189
- function seatedArms(a, w, lean) {
189
+ function seatedArms(a, w, lean, freeL = 1, freeR = 1) {
190
190
  const joints = a.joints,
191
- seated = w.seated;
191
+ seatedL = w.seated * freeL,
192
+ seatedR = w.seated * freeR;
192
193
  let solved = armIK(joints[HAND_L_FWD], joints[HAND_L_UP]);
193
- w.armL = lerp(w.armL, -solved[0] - lean, seated);
194
- w.foreL = lerp(w.foreL, -solved[1], seated);
194
+ w.armL = lerp(w.armL, -solved[0] - lean, seatedL);
195
+ w.foreL = lerp(w.foreL, -solved[1], seatedL);
195
196
  solved = armIK(joints[HAND_R_FWD], joints[HAND_R_UP]);
196
- w.armR = lerp(w.armR, -solved[0] - lean, seated);
197
- w.foreR = lerp(w.foreR, -solved[1], seated);
197
+ w.armR = lerp(w.armR, -solved[0] - lean, seatedR);
198
+ w.foreR = lerp(w.foreR, -solved[1], seatedR);
198
199
  }
199
200
  // How far each seated forearm lies on the table (0 to 1).
200
201
  const onTable = (a, left) => a.joints[left ? TABLE_L : TABLE_R];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roamwright",
3
- "version": "0.61.6",
3
+ "version": "0.61.8",
4
4
  "description": "A procedural worldbuilding engine built on top of Three.js. Generate landscapes with rivers and changing weather, animate crowds, and explore on foot or in flight.",
5
5
  "keywords": [
6
6
  "threejs",
@@ -0,0 +1,91 @@
1
+ import * as THREE from 'three';
2
+ import { LAND_TRAIL_MARKS, boundsOverlap, rasterizeTrailMarks } from '../geometry/land-trails.js';
3
+
4
+ /**
5
+ * Build the GLSL fragment chunk that draws dry stream beds (gravel, silt bars, cut banks and close-up cobbles from channel G)
6
+ * and braided herd trails (parallel worn ruts fading cleanly with pixel footprint from channel R).
7
+ *
8
+ * Expects uniforms `uPlain` (RG distance field `sampler2D`) and `uPlainR` (`vec4(x0, z0, 1/width, 1/height)`), world position
9
+ * `vWP`, world normal `vWN`, baked mesh vertex colour `vColor`, detail grain samples `d2`, `d3`, `fleck`, `grit` (0.73..1),
10
+ * view distance `vd`, and pixel footprints `groundX`, `groundY`. Updates `diffuseColor.rgb` and surface relief `gTH`.
11
+ * Contains no screen-space derivatives so both branches can be skipped cleanly off the trails.
12
+ *
13
+ * @param {object} [options]
14
+ * @param {{ trail?: number, wash?: number }} [options.reach] - Encoded distance reach per channel in metres (defaults to `LAND_TRAIL_MARKS.reach`).
15
+ * @returns {string} GLSL fragment snippet.
16
+ */
17
+ export function trailMarksGLSL({ reach } = {}) {
18
+ const trail = reach?.trail ?? LAND_TRAIL_MARKS.reach.trail,
19
+ wash = reach?.wash ?? LAND_TRAIL_MARKS.reach.wash;
20
+ return `/* glsl */
21
+ vec2 pu = (vWP.xz - uPlainR.xy) * uPlainR.zw;
22
+ if (min(pu.x, pu.y) > 0.0 && max(pu.x, pu.y) < 1.0) {
23
+ vec2 mark = textureLod(uPlain, pu, 0.0).rg;
24
+ float level = smoothstep(0.55, 0.8, vWN.y);
25
+ vec3 baked = max(vColor.rgb, vec3(0.02));
26
+ if (mark.g < 0.995) { // a dry stream bed
27
+ float reach = smoothstep(0.76, 0.94, d3.r), swing = smoothstep(0.74, 0.96, d2.g); // from the grain samples the shader already holds: no further reads
28
+ float from = mark.g * ${wash.toFixed(1)} + (swing - 0.5) * 2.4, width = 2.0 + 3.8 * reach; // metres from the bed's middle, and its half width, which comes and goes
29
+ float bed = (1.0 - smoothstep(width - 0.6, width + 0.25, from)) * level;
30
+ float lip = (1.0 - smoothstep(0.0, 0.7, abs(from - width - 0.15))) * level; // the cut bank: a lip of bare earth and its shade
31
+ float stones = smoothstep(0.8, 0.93, fleck * 0.55 + grit * 0.45);
32
+ float bar = smoothstep(0.35, 0.75, reach * 0.5 + swing * 0.5 + (from / width - 0.5) * 0.5); // silt laid down in bars
33
+ vec3 gravel = mix(vec3(0.33, 0.275, 0.19), vec3(0.7, 0.63, 0.49), stones) * (0.8 + 0.3 * smoothstep(0.74, 0.96, d2.g));
34
+ vec3 silt = vec3(0.62, 0.52, 0.35) * (0.82 + 0.3 * smoothstep(0.74, 0.96, fleck));
35
+ // near the eye the gravel is cobbles: rounded stones a hand or two across, some pale, some dark, thinner on the silt
36
+ float close = 1.0 - smoothstep(18.0, 55.0, vd);
37
+ vec2 q = vWP.xz * 3.1 + (d3.rg - 0.86) * 6.0, cell = floor(q);
38
+ float pick = fract(sin(dot(cell, vec2(127.1, 311.7))) * 43758.5453), pick2 = fract(pick * 57.3), pick3 = fract(pick * 131.7);
39
+ vec2 in_ = fract(q) - 0.5 - (vec2(pick2, pick3) - 0.5) * 0.44; // each stone lies where it fell in its square, and is its own size and shape
40
+ float girth = (0.5 + 0.45 * pick) * 0.27;
41
+ float cobble = smoothstep(girth, girth * 0.6, length(in_ * vec2(0.8 + pick2 * 0.5, 1.2 - pick3 * 0.4))) * step(0.3 + 0.45 * bar, pick3) * close;
42
+ vec3 floor_ = mix(gravel, silt, bar);
43
+ floor_ = mix(floor_ * (1.0 - 0.25 * close), vec3(0.3, 0.27, 0.23) + 0.5 * fract(pick * 7.3) * vec3(0.95, 0.9, 0.8), cobble);
44
+ diffuseColor.rgb = mix(diffuseColor.rgb, floor_ / baked, bed * 0.94);
45
+ diffuseColor.rgb *= 1.0 - 0.4 * lip;
46
+ gTH = mix(gTH, 0.3 + stones * (1.0 - bar) * 0.22 + 0.12 * fleck + cobble * (0.45 - dot(in_, in_) * 2.0), bed);
47
+ }
48
+ if (mark.r < 0.995) { // herd trails: a path down the middle and others worn beside it, a pace apart, where the herd spreads
49
+ float spread = smoothstep(0.76, 0.94, d3.r), wander = smoothstep(0.76, 0.94, d3.g) - 0.5;
50
+ float mid = mark.r * ${trail.toFixed(1)}, from = mid + wander * 1.1 * smoothstep(0.6, 2.2, mid), lane = from / 1.3;
51
+ float lanes = (1.0 - smoothstep(0.8, 2.2 + 3.2 * spread, mid)) * level;
52
+ float seen = 1.0 - smoothstep(0.12, 0.4, (length(groundX) + length(groundY)) / 1.3);
53
+ float rut = max(1.0 - smoothstep(0.5, 0.85, mid), 1.0 - smoothstep(0.13, 0.27, abs(fract(lane + 0.5) - 0.5))) * lanes;
54
+ vec3 dust = vec3(0.27, 0.2, 0.125) * (0.8 + 0.4 * smoothstep(0.74, 0.96, fleck));
55
+ diffuseColor.rgb = mix(diffuseColor.rgb, dust / baked, mix(0.3 * lanes, rut, seen) * 0.8);
56
+ gTH -= rut * seen * 0.2;
57
+ }
58
+ }`;
59
+ }
60
+
61
+ /**
62
+ * Create a Three.js uniform holder (`tex`, `rect`), bounds overlap test (`reaches`), `DataTexture` baker (`bake`), and
63
+ * matching GLSL fragment chunk (`glsl`) for fine herd trails and dry stream beds over a region of terrain.
64
+ *
65
+ * @param {object} options
66
+ * @param {{ x0: number, z0: number, x1: number, z1: number }} options.bounds - World-space XZ extent in metres.
67
+ * @param {Partial<typeof LAND_TRAIL_MARKS>} [options.shape] - Overrides for `LAND_TRAIL_MARKS`.
68
+ * @returns {{
69
+ * uniforms: { tex: { value: THREE.DataTexture | null }, rect: { value: THREE.Vector4 } },
70
+ * reaches: (x0: number, z0: number, x1: number, z1: number) => boolean,
71
+ * bake: (inputs: { paths: { trails: number[][][], washes: number[][][] }, road?: Function, river?: Function, siteDistance?: Function, siteRoom?: number }) => THREE.DataTexture,
72
+ * glsl: string
73
+ * }}
74
+ */
75
+ export function createTrailMarks({ bounds, shape = {} }) {
76
+ const uniforms = { tex: { value: null }, rect: { value: new THREE.Vector4() } },
77
+ reaches = (x0, z0, x1, z1) => boundsOverlap(bounds, x0, z0, x1, z1),
78
+ glsl = trailMarksGLSL({ reach: shape.reach });
79
+
80
+ function bake({ paths, road, river, siteDistance, siteRoom }) {
81
+ const { data, width, height, rect } = rasterizeTrailMarks({ paths, bounds, road, river, siteDistance, siteRoom, shape });
82
+ const tex = new THREE.DataTexture(data, width, height, THREE.RGFormat);
83
+ tex.minFilter = tex.magFilter = THREE.LinearFilter;
84
+ tex.needsUpdate = true;
85
+ uniforms.tex.value = tex;
86
+ uniforms.rect.value.set(rect[0], rect[1], rect[2], rect[3]);
87
+ return tex;
88
+ }
89
+
90
+ return { uniforms, reaches, bake, glsl };
91
+ }
@@ -0,0 +1,66 @@
1
+ import * as THREE from 'three';
2
+ import { GB } from '../geometry/builder.js';
3
+ import { TRS, createUnitShapes } from '../geometry/primitives.js';
4
+
5
+ /**
6
+ * Put planned springheads and their soaked ground sheets (`planSprings`) into a scene group: for each spring, adds the
7
+ * transparent wet-ground mesh (`renderOrder` 3 by default so it lies over ground and roads and under water) and one merged
8
+ * mesh of its cleft slabs, ring boulders and strewn stones.
9
+ *
10
+ * @param {object} options
11
+ * @param {{ wetGround: { position: Float32Array, normal: Float32Array, color: Float32Array, index: number[] }, rocks: number[] }[]} options.plans - Planned springs from `planSprings`.
12
+ * @param {THREE.Object3D} options.parent - Scene or group that receives the meshes.
13
+ * @param {(fineness: number) => THREE.BufferGeometry} [options.crag] - Returns rock geometry for fineness level `1 | 2 | 3`; defaults to a unit broken stone.
14
+ * @param {THREE.Material} [options.rockMaterial] - Vertex-coloured material for springhead rocks.
15
+ * @param {THREE.Material} [options.groundMaterial] - Transparent RGBA vertex-coloured material for the soaked-ground sheet.
16
+ * @param {number} [options.renderOrder=3] - Render order applied to each wet-ground mesh.
17
+ * @returns {{ wetMeshes: THREE.Mesh[], rockMeshes: THREE.Mesh[] }} Added meshes, in spring order.
18
+ */
19
+ export function meshSprings({ plans, parent, crag, rockMaterial, groundMaterial, renderOrder = 3 }) {
20
+ let defaultRock = null;
21
+ const rockFor =
22
+ crag ??
23
+ (() => {
24
+ defaultRock ??= createUnitShapes().rock;
25
+ return defaultRock;
26
+ });
27
+ const rockMat = rockMaterial ?? new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.88 });
28
+ const groundMat =
29
+ groundMaterial ??
30
+ new THREE.MeshStandardMaterial({
31
+ vertexColors: true,
32
+ roughness: 0.5,
33
+ transparent: true,
34
+ depthWrite: false,
35
+ polygonOffset: true,
36
+ polygonOffsetFactor: -2,
37
+ polygonOffsetUnits: -2,
38
+ });
39
+ const wetMeshes = [],
40
+ rockMeshes = [];
41
+ for (const { wetGround, rocks } of plans) {
42
+ const geometry = new THREE.BufferGeometry();
43
+ geometry.setAttribute('position', new THREE.BufferAttribute(wetGround.position, 3));
44
+ geometry.setAttribute('normal', new THREE.BufferAttribute(wetGround.normal, 3));
45
+ geometry.setAttribute('color', new THREE.BufferAttribute(wetGround.color, 4));
46
+ geometry.setIndex(wetGround.index);
47
+ const wetMesh = new THREE.Mesh(geometry, groundMat);
48
+ wetMesh.receiveShadow = true;
49
+ wetMesh.renderOrder = renderOrder;
50
+ wetMesh.matrixAutoUpdate = false;
51
+ parent.add(wetMesh);
52
+ wetMeshes.push(wetMesh);
53
+
54
+ const builder = new GB();
55
+ for (let i = 0; i < rocks.length; i += 13) {
56
+ builder.add(
57
+ rockFor(rocks[i + 9]),
58
+ [rocks[i + 10], rocks[i + 11], rocks[i + 12]],
59
+ TRS(rocks[i], rocks[i + 1], rocks[i + 2], rocks[i + 3], rocks[i + 4], rocks[i + 5], rocks[i + 6], rocks[i + 7], rocks[i + 8]),
60
+ );
61
+ }
62
+ const rockMesh = builder.mesh(rockMat, parent);
63
+ if (rockMesh) rockMeshes.push(rockMesh);
64
+ }
65
+ return { wetMeshes, rockMeshes };
66
+ }