roamwright 0.57.0 → 0.59.0

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.
@@ -37,7 +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, lake, banked road, cliff-faced tel, quarry and port pad.
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.
41
42
  </p>
42
43
  </div>
43
44
  <div class="tools">
package/examples/land.js CHANGED
@@ -12,10 +12,17 @@ import {
12
12
  createRenderContext,
13
13
  createSimpleWater,
14
14
  createTownGround,
15
+ createUnitShapes,
16
+ drystoneStone,
15
17
  landEdgeGrid,
18
+ layRoads,
19
+ meshStreamBanks,
16
20
  mulberry32,
21
+ planDrystoneWall,
22
+ planStreamBanks,
17
23
  } from 'roamwright';
18
24
  import { erodeHeightfield } from 'roamwright/geometry/erosion.js';
25
+ import { instancedMesh } from 'roamwright/geometry/instances.js';
19
26
  import { createClearings, createRainRule } from 'roamwright/geometry/land-clearings.js';
20
27
  import { createSandRidges } from 'roamwright/geometry/land-dunes.js';
21
28
  import { landEdgeArrays } from 'roamwright/geometry/land-edge.js';
@@ -334,6 +341,7 @@ for (let i = 0; i < 650 && tc < 220; i++) {
334
341
  const ty = sampleSheet(tx, tz);
335
342
  if (ty < 3 || ty > 42) continue;
336
343
  if (Math.hypot(tx - 260, tz + 170) < 105 || Math.hypot(tx + 400, tz + 330) < 120 || Math.hypot(tx + 470, tz + 40) < 115) continue;
344
+ if (tx > 152 && tx < 236 && tz > 50 && tz < 130) continue; // keep the drystone field enclosure clear of trees
337
345
  if (Math.abs(tz - 50) < 28) continue;
338
346
  dummy.position.set(tx, ty - 0.2, tz);
339
347
  dummy.rotation.set(0, rng() * Math.PI * 2, 0);
@@ -345,6 +353,88 @@ trees.count = tc;
345
353
  trees.instanceMatrix.needsUpdate = true;
346
354
  worldGroup.add(trees);
347
355
 
356
+ // Exact triangle height on the baked heightfield so roads, stream stones and drystone walls sit flush on slopes.
357
+ const groundExact = (x, z) => {
358
+ const gx = Math.max(0, Math.min(STRIDE - 1.001, (x - sheet.x0) / sheet.spacing));
359
+ const gz = Math.max(0, Math.min(STRIDE - 1.001, (z - sheet.z0) / sheet.spacing));
360
+ const i = Math.floor(gx),
361
+ j = Math.floor(gz),
362
+ fx = gx - i,
363
+ fz = gz - j,
364
+ k = j * STRIDE + i;
365
+ const h00 = sheet.heights[k],
366
+ h10 = sheet.heights[k + 1],
367
+ h01 = sheet.heights[k + STRIDE],
368
+ h11 = sheet.heights[k + STRIDE + 1];
369
+ return fx + fz <= 1 ? h00 + (h10 - h00) * fx + (h01 - h00) * fz : h11 + (h01 - h11) * (1 - fx) + (h10 - h11) * (1 - fz);
370
+ };
371
+
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
+ }
437
+
348
438
  createDaylightSky({
349
439
  scene,
350
440
  renderer,
@@ -360,11 +450,11 @@ createDaylightSky({
360
450
  });
361
451
 
362
452
  const status = document.querySelector('#status');
363
- status.textContent = `${STRIDE} × ${STRIDE} points (${sheet.spacing} m step): coast, eroded hills, river, mere, banked road, cliff-faced tel, quarry and port pad.`;
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.`;
364
454
 
365
455
  const views = {
366
456
  coast: { eye: [365, 138, 440], target: [35, 8, -35] },
367
- ford: { eye: [240, 62, 165], target: [110, 6, 30] },
457
+ ford: { eye: [228, 36, 152], target: [148, 8, 56] },
368
458
  quarry: { eye: [-180, 125, -45], target: [-420, 14, -220] },
369
459
  port: { eye: [-55, 78, 560], target: [-230, 5, 360] },
370
460
  };
@@ -130,3 +130,23 @@ export function creasedSheet(
130
130
  }
131
131
  }
132
132
  }
133
+
134
+ /**
135
+ * A sheet of rock: `creasedSheet` with the edge rock keeps (a crease of 0.55, so a face turns sharply where it steepens past
136
+ * about 57 degrees) and the dust that settles on its upward-facing ledges, given as `dust` (the creased sheet's tint, from a
137
+ * slope of 0.6 up to 0.86). `columns` shapes only the cells from `from` to `to` of each row, so a sheet too large for one frame
138
+ * is shaped a band at a time; every corner is still shaded from the whole sheet.
139
+ *
140
+ * @param {object} builder - A geometry builder with `raw(x, y, z, nx, ny, nz, r, g, b)`.
141
+ * @param {number[][][]} rows - The grid's points, each `[x, y, z]` in metres.
142
+ * @param {number[][][]} tones - The grid's colours, each `[r, g, b]` in linear light.
143
+ * @param {object} [options]
144
+ * @param {boolean} [options.wrap] - The last column joins the first (a closed column).
145
+ * @param {boolean} [options.inside] - The sheet is seen from within.
146
+ * @param {number} [options.crease=0.55] - The least cosine of two faces that share a soft edge.
147
+ * @param {number[] | null} [options.dust] - The dust's linear colour, or none.
148
+ * @param {[number, number] | null} [options.columns] - The cells to shape, `[from, to)`.
149
+ */
150
+ export function rockSheet(builder, rows, tones, { wrap, inside, crease = 0.55, dust, columns } = {}) {
151
+ creasedSheet(builder, rows, tones, { wrap, inside, crease, tint: dust, slopeFrom: 0.6, slopeTo: 0.86, columns });
152
+ }
@@ -0,0 +1,143 @@
1
+ import * as THREE from 'three';
2
+ import { clamp, lerp } from '../math/scalar.js';
3
+ import { C, TRS } from './primitives.js';
4
+
5
+ /**
6
+ * A drystone wall, in metres: its courses from the footing up (where a course's middle lies as a share of the wall's height, its
7
+ * stones' length and depth, and their height as a share of the wall's; large stones at the foot, smaller ones above, the wall
8
+ * battered narrower as it rises, and on top a cope of thin stones set on edge, leaning a little each way); the one stone every
9
+ * stone is a copy of (its length and depth before it is stretched, and its height); and the box it is drawn as from afar (longer
10
+ * and taller than the wall, and its depth, with its middle set below the foot).
11
+ */
12
+ export const DRYSTONE_WALL = Object.freeze({
13
+ courses: [
14
+ { at: 0.14, len: 0.62, tall: 0.3, deep: 0.7 },
15
+ { at: 0.42, len: 0.52, tall: 0.27, deep: 0.6 },
16
+ { at: 0.66, len: 0.46, tall: 0.22, deep: 0.52 },
17
+ { at: 0.87, len: 0.24, tall: 0.3, deep: 0.44, lean: 0.12 },
18
+ ],
19
+ stone: 1.1,
20
+ tall: 0.84,
21
+ farLonger: 0.11,
22
+ farTaller: 1.08,
23
+ farDeep: 0.61,
24
+ farBeneath: 0.2,
25
+ /** How far a stone may stand off its place along the course, off its height, and be turned, as shares and radians. */
26
+ slip: 0.2,
27
+ lift: 0.04,
28
+ turn: 0.3,
29
+ tilt: 0.2,
30
+ lean: 0.3,
31
+ jitter: 0.13,
32
+ });
33
+
34
+ /** Field stone, weathered grey and buff, sRGB. */
35
+ export const FIELD_STONE = Object.freeze([0x8e8470, 0xa29680, 0x777163, 0xab9b84, 0x807d6d]);
36
+
37
+ /**
38
+ * The one stone a drystone wall is built of: an icosahedron of radius 0.56 m, roughened, flattened top and bottom and tilted a
39
+ * little into a bedded shape, with room for each copy's own colour.
40
+ *
41
+ * @param {(x: number, z: number, seed: number) => number} noise - Seeded value noise (`createNoise`), which roughens it.
42
+ * @param {number} [seed=362] - The noise's seed.
43
+ * @returns {import('three').BufferGeometry} With `position`, `normal` and a white `color` attribute.
44
+ */
45
+ export function drystoneStone(noise, seed = 362) {
46
+ const stone = new THREE.IcosahedronGeometry(0.56, 1),
47
+ points = stone.attributes.position;
48
+ for (let i = 0; i < points.count; i++) {
49
+ const x = points.getX(i),
50
+ y = points.getY(i),
51
+ z = points.getZ(i);
52
+ const r = 0.89 + 0.22 * noise(x * 19 + y * 2, z * 17, seed);
53
+ points.setXYZ(i, x * r + y * 0.12, clamp(y * r, -0.4 + 0.13 * z, 0.44 + 0.12 * x), z * r + x * 0.06);
54
+ }
55
+ stone.computeVertexNormals();
56
+ stone.setAttribute('color', new THREE.BufferAttribute(new Float32Array(points.count * 3).fill(1), 3)); // each stone's own colour is its instance's
57
+ return stone;
58
+ }
59
+
60
+ /**
61
+ * Plan a length of drystone wall from `a` to `b` of a given height: a box it is drawn as from afar, and the wall itself as
62
+ * thousands of the one stone, each turned, stretched and tinted, course by course, each course breaking the joints of the one
63
+ * below. Pure arithmetic over the caller's ground, noise and stone palette.
64
+ *
65
+ * @param {number[]} a - The wall's foot at one end, `[x, z]` in metres.
66
+ * @param {number[]} b - Its foot at the other end.
67
+ * @param {number} height - The wall's height in metres.
68
+ * @param {Function} rng - A repeatable stream.
69
+ * @param {object} readers
70
+ * @param {(x: number, z: number) => number} readers.ground - The terrain's height at a place, metres.
71
+ * @param {number[]} [readers.palette=FIELD_STONE] - The stones' colours, sRGB.
72
+ * @param {number} [readers.jitter=DRYSTONE_WALL.jitter] - How far each stone's colour may stray from its palette's.
73
+ * @param {Partial<typeof DRYSTONE_WALL>} [readers.shape] - Changes to {@link DRYSTONE_WALL}.
74
+ * @returns {{ stones: number[], tints: number[], far: { x: number, y: number, z: number, length: number, height: number, depth: number, colour: number[], yaw: number, pitch: number }, foot: { x: number, z: number, halfLength: number, halfDepth: number, yaw: number } }}
75
+ * `stones`: a matrix (16 numbers, Three.js order) to a stone; `tints`: a linear colour (3 numbers) to a stone; `far`: the box the
76
+ * wall is from afar; `foot`: what the walker collides with (a rectangle half `halfLength` by `halfDepth`, turned `yaw`).
77
+ */
78
+ export function planDrystoneWall(a, b, height, rng, { ground, palette = FIELD_STONE, jitter = DRYSTONE_WALL.jitter, shape = {} }) {
79
+ const {
80
+ courses,
81
+ stone: STONE_SIZE,
82
+ tall: STONE_TALL,
83
+ farLonger,
84
+ farTaller,
85
+ farDeep,
86
+ farBeneath,
87
+ slip,
88
+ lift,
89
+ turn,
90
+ tilt,
91
+ lean,
92
+ } = {
93
+ ...DRYSTONE_WALL,
94
+ ...shape,
95
+ };
96
+ const dx = b[0] - a[0],
97
+ dz = b[1] - a[1],
98
+ length = Math.hypot(dx, dz),
99
+ yaw = Math.atan2(-dz, dx);
100
+ const x = (a[0] + b[0]) * 0.5,
101
+ z = (a[1] + b[1]) * 0.5;
102
+ const ya = ground(...a),
103
+ yb = ground(...b),
104
+ pitch = Math.atan2(yb - ya, length);
105
+ const far = {
106
+ x,
107
+ y: (ya + yb) * 0.5 - farBeneath,
108
+ z,
109
+ length: length + farLonger,
110
+ height: height * farTaller,
111
+ depth: farDeep,
112
+ colour: C(palette[0], jitter, rng),
113
+ yaw,
114
+ pitch,
115
+ };
116
+ const stones = [],
117
+ tints = [];
118
+ for (let course = 0; course < courses.length; course++) {
119
+ const { at, len, tall, deep, lean: courseLean } = courses[course],
120
+ steps = Math.max(1, Math.round(length / len)),
121
+ span = length / steps,
122
+ stagger = course % 2 ? 0.5 : 0; // each course breaks the joints of the one below
123
+ for (let i = 0; i < steps; i++) {
124
+ const t = (((i + 0.5 + stagger) % steps) + (rng() - 0.5) * slip) / steps, // a staggered course's last stone straddles the joint at its start
125
+ px = lerp(a[0], b[0], t),
126
+ pz = lerp(a[1], b[1], t);
127
+ tints.push(...C(palette[Math.floor(rng() * palette.length)], jitter, rng));
128
+ const placed = TRS(
129
+ px,
130
+ ground(px, pz) + height * at + (rng() - 0.5) * lift,
131
+ pz,
132
+ (span / STONE_SIZE) * (1.12 + rng() * 0.16),
133
+ ((height * tall) / STONE_TALL) * (0.85 + 0.3 * rng()),
134
+ (deep / STONE_SIZE) * (0.88 + rng() * 0.24),
135
+ yaw + (rng() - 0.5) * turn,
136
+ (rng() - 0.5) * tilt + (courseLean ? (i % 2 ? courseLean : -courseLean) : 0),
137
+ (rng() - 0.5) * lean,
138
+ );
139
+ for (let e = 0; e < 16; e++) stones.push(placed.elements[e]);
140
+ }
141
+ }
142
+ return { stones, tints, far, foot: { x, z, halfLength: length * 0.51, halfDepth: 0.31, yaw } };
143
+ }
@@ -0,0 +1,158 @@
1
+ import { lerp } from '../math/scalar.js';
2
+ import { GB } from './builder.js';
3
+ import { C } from './primitives.js';
4
+ import { planDrystoneWall } from './drystone-wall.js';
5
+
6
+ /**
7
+ * What stands on a farm's parcels, in metres: the boundary a survey gave each side of a parcel (0 a ditch; 1 to 3 a hedge, 4 and 5
8
+ * a wall; 6 and above an open balk of grass) with a hedge's lengths every so far, a few missing and a few grown out to trees; the
9
+ * length of drystone wall laid at a time so it follows a boundary's bends, and the share of hedges and walls with a gap left for
10
+ * a gate; an orchard's trees along and across the rows; the cells the stones and strips are gathered into; a drain's strip (four
11
+ * points across, tapering at both ends, its wet silt and its waterlogged gravel); and the kinds a hedge length and a fruit tree
12
+ * are to the caller's cover.
13
+ */
14
+ export const FARM_BOUNDARIES = Object.freeze({
15
+ bound: { hedge: [1, 3], wall: [4, 5] },
16
+ hedge: { step: 2, size: [0.85, 1.25], gaps: 0.05, trees: 0.04 },
17
+ wallStep: 4,
18
+ gateShare: 0.45,
19
+ gateSeed: 359,
20
+ orchard: { along: 6.4, across: 6.2, shake: 0.42, kept: 0.92 },
21
+ cell: 140,
22
+ wallHeight: [0.84, 0.16],
23
+ ditch: {
24
+ across: [-1, -0.45, 0.35, 1],
25
+ width: [1.25, 0.35],
26
+ over: 0.08,
27
+ lift: 0.035,
28
+ taper: 0.22,
29
+ colours: [0x52442d, 0x73654d],
30
+ jitter: 0.14,
31
+ },
32
+ });
33
+
34
+ /**
35
+ * Plan what stands on a farm's parcels from the field map: fruit trees in the orchards and hedge lengths (with a tree now and
36
+ * then) along the hedges, each as a row for the caller's cover; drystone walls along the walled sides, with here and there a gap
37
+ * for a gate, as copies of one stone gathered into cells with the box each cell's walls are drawn as from afar; and a carved
38
+ * strip of silt and gravel along every drain. The wall the plan lays is kept for the caller to lay a farmyard's walls with, from
39
+ * the same stream. Pure arithmetic over the caller's readers.
40
+ *
41
+ * @param {object} options
42
+ * @param {object} options.fields - The survey's record (`createFieldSurvey`): its parcels with their uses and sides, and its drains.
43
+ * @param {ReturnType<import('./field-survey.js').createFieldSurvey>} options.survey - The survey, for a parcel's sides and points.
44
+ * @param {(x: number, z: number) => number} options.ground - The terrain's height at a place, metres.
45
+ * @param {(x: number, z: number) => boolean} options.valid - Whether a tree or wall may stand at a place: the caller keeps them off
46
+ * its roads, its drains, its farmyards and their tracks, and off ground it keeps clear.
47
+ * @param {(ix: number, iz: number, seed: number) => number} options.hash - Seeded coordinate hash (`createHash`), for the gates.
48
+ * @param {Function} options.random - A repeatable stream, drawn from for every tree, wall and drain.
49
+ * @param {{ hedge: number, tree: number }} [options.kinds] - What a hedge length and a fruit tree are to the caller's cover.
50
+ * @param {(foot: { x: number, z: number, halfLength: number, halfDepth: number, yaw: number }) => void} [options.collide] - Called with each wall segment's collider footprint.
51
+ * @param {number[]} [options.stonePalette] - Optional field-stone colours (sRGB) forwarded to `planDrystoneWall`.
52
+ * @param {Partial<typeof import('./drystone-wall.js').DRYSTONE_WALL>} [options.wallShape] - Optional wall overrides forwarded to `planDrystoneWall`.
53
+ * @param {Partial<typeof FARM_BOUNDARIES>} [options.shape] - Changes to {@link FARM_BOUNDARIES}.
54
+ * @returns {{ cells: Map<string, { stones: number[], tints: number[], far: import('./builder.js').GB, ditches: import('./builder.js').GB }>, trees: number[], wall: Function }}
55
+ * `cells`: by 140 m square, the stones of its walls (a matrix to a stone, and a linear colour to a stone), their far boxes as
56
+ * parts, and its drains' strips as parts; `trees`: rows `[x, z, kind, scale, shade]`, a hedge's with its heading after;
57
+ * `wall(a, b, height)`: lays a wall from `a` to `b` and returns its foot for the caller's walker to collide with.
58
+ */
59
+ export function planFieldBoundaries({
60
+ fields,
61
+ survey,
62
+ ground,
63
+ valid = () => true,
64
+ hash,
65
+ random,
66
+ kinds = { hedge: 3, tree: 4 },
67
+ collide = () => {},
68
+ stonePalette,
69
+ wallShape,
70
+ shape = {},
71
+ }) {
72
+ const {
73
+ bound: BOUND,
74
+ hedge: HEDGE,
75
+ wallStep: WALL_STEP,
76
+ gateShare: GATE_SHARE,
77
+ gateSeed: GATE_SEED,
78
+ orchard: ORCHARD,
79
+ cell: CELL,
80
+ wallHeight: WALL_HEIGHT,
81
+ ditch: DITCH,
82
+ } = { ...FARM_BOUNDARIES, ...shape };
83
+ const rng = random,
84
+ USE = survey.USE;
85
+ const cells = new Map(),
86
+ trees = [];
87
+ const batch = (x, z) => {
88
+ const key = Math.floor(x / CELL) + ':' + Math.floor(z / CELL);
89
+ if (!cells.has(key)) cells.set(key, { stones: [], tints: [], far: new GB(), ditches: new GB() });
90
+ return cells.get(key);
91
+ };
92
+ // A length of drystone wall: its far box and its stones into the cell it lies in, and its foot for the walker.
93
+ const wallOptions = { ground, ...(stonePalette ? { palette: stonePalette } : {}), ...(wallShape ? { shape: wallShape } : {}) };
94
+ function wall(a, b, height) {
95
+ const planned = planDrystoneWall(a, b, height, rng, wallOptions),
96
+ far = planned.far,
97
+ cell = batch(far.x, far.z);
98
+ cell.far.box(far.x, far.y, far.z, far.length, far.height, far.depth, far.colour, far.yaw, 0, far.pitch);
99
+ cell.stones.push(...planned.stones);
100
+ cell.tints.push(...planned.tints);
101
+ collide(planned.foot);
102
+ }
103
+
104
+ for (const parcel of fields.parcels) {
105
+ if (parcel.use === USE.orchard)
106
+ survey.points(fields, parcel, ORCHARD.along, ORCHARD.across, ORCHARD.shake, rng, (x, z, lot) => {
107
+ if (lot[1] > 0.9 && valid(x, z) && rng() < ORCHARD.kept) trees.push([x, z, kinds.tree, 0.36 + rng() * 0.18, 0.88]);
108
+ });
109
+ for (let e = 0; e < 4; e++) {
110
+ const bound = parcel.edges[e];
111
+ if (bound < BOUND.hedge[0] || bound > BOUND.wall[1]) continue;
112
+ const hedge = bound <= BOUND.hedge[1],
113
+ line = survey.boundary(parcel, e, hedge ? HEDGE.step : WALL_STEP);
114
+ const [cx, cz] = parcel.ring[e * 2],
115
+ gate = hash(e, Math.floor(cx) + 14 * Math.floor(cz), GATE_SEED) < GATE_SHARE ? Math.floor(line.length * 0.57) : -1;
116
+ for (let i = 0; i + 1 < line.length; i++) {
117
+ const a = line[i],
118
+ b = line[i + 1];
119
+ if (i === gate || !valid(...a) || !valid(...b)) continue;
120
+ if (!hedge) wall(a, b, WALL_HEIGHT[0] + rng() * WALL_HEIGHT[1]);
121
+ else if (rng() > HEDGE.gaps) {
122
+ const along = Math.atan2(-(b[1] - a[1]), b[0] - a[0]) + (rng() - 0.5) * 0.3;
123
+ trees.push([a[0], a[1], kinds.hedge, lerp(HEDGE.size[0], HEDGE.size[1], rng()), 0.8 + rng() * 0.2, along]);
124
+ if (rng() < HEDGE.trees) trees.push([a[0], a[1], kinds.tree, 0.72 + 0.48 * rng(), 0.94]);
125
+ }
126
+ }
127
+ }
128
+ }
129
+ // the drains: a carved bed with a seam of exposed silt and waterlogged gravel, four points across, tapering to nothing at both ends
130
+ for (const path of fields.ditches) {
131
+ const strip = [];
132
+ for (let i = 0; i < path.length; i++) {
133
+ const [x, z] = path[i],
134
+ a = path[Math.max(0, i - 1)],
135
+ b = path[Math.min(path.length - 1, i + 1)];
136
+ const dx = b[0] - a[0],
137
+ dz = b[1] - a[1],
138
+ d = Math.hypot(dx, dz) || 1,
139
+ taper = Math.min(1, (i + 1) * DITCH.taper, (path.length - i) * DITCH.taper);
140
+ const row = DITCH.across.map(v => {
141
+ const w = v * taper * (DITCH.width[0] + rng() * DITCH.width[1]),
142
+ px = x - (dz / d) * w,
143
+ pz = z + (dx / d) * w;
144
+ return [px, ground(px, pz) + DITCH.over + Math.abs(v) * DITCH.lift, pz];
145
+ });
146
+ if (i > 0) {
147
+ const prev = strip[i - 1],
148
+ gb = batch(x, z).ditches;
149
+ for (let j = 0; j < 3; j++) {
150
+ const color = C(DITCH.colours[j === 1 ? 0 : 1], DITCH.jitter, rng);
151
+ for (const v of [prev[j], prev[j + 1], row[j], row[j], prev[j + 1], row[j + 1]]) gb.raw(...v, 0, 1, 0, ...color);
152
+ }
153
+ }
154
+ strip.push(row);
155
+ }
156
+ }
157
+ return { cells, trees, wall };
158
+ }
@@ -0,0 +1,183 @@
1
+ import { TAU, lerp } from '../math/scalar.js';
2
+
3
+ /**
4
+ * What the season leaves on a farm's fields, in metres: how far the full shapes are drawn and beyond them the light ones; the
5
+ * side of the squares the shapes are gathered into, each one mesh; the room kept clear of a parcel's edge; a row of stooks down
6
+ * every strip of the stubble; a haycock's places on a mown meadow; a herd's candidate places a pace apart, and the share of its
7
+ * animals with their heads down; how many animals a herd has, their sizes and the room each keeps (its coats are the caller's);
8
+ * of the pastures, those grazed by cattle (sheep have the rest); and how far from the plough the oxen's shoulders stand.
9
+ */
10
+ export const FARM_LIFE = Object.freeze({
11
+ near: 95,
12
+ gather: 240,
13
+ edgeRoom: 3,
14
+ stooks: { along: 9.5, across: 7.4, shake: 1.6, near: 60, turn: 0.5, size: [0.92, 0.16] },
15
+ haycocks: { along: 8, across: 6.9, shake: 1.5, size: [0.75, 0.35] },
16
+ grazing: { step: 7, shake: 3, share: 0.7, turn: 2.4 },
17
+ herd: { count: [5, 9], size: [0.92, 1.1], room: 0.75 },
18
+ cattleShare: 0.55,
19
+ teamReach: 4,
20
+ });
21
+
22
+ /**
23
+ * The places of a parcel where the season's work has (`worked` 1) or has not (0) passed, on a grid laid along its rows.
24
+ *
25
+ * @param {ReturnType<import('./field-survey.js').createFieldSurvey>} survey - The survey.
26
+ * @param {object} fields - The survey's record, with its field map drawn.
27
+ * @param {object} parcel - The parcel.
28
+ * @param {{ along: number, across: number, shake: number }} grid - The grid's spacings and shake in metres (`step` for both).
29
+ * @param {0 | 1} worked - Whether the places are those the work has reached.
30
+ * @param {Function} rng - A repeatable stream.
31
+ * @returns {number[][]} `[x, z]` places, in metres.
32
+ */
33
+ export function parcelPlaces(survey, fields, parcel, grid, worked, rng) {
34
+ const places = [];
35
+ survey.points(fields, parcel, grid.along ?? grid.step, grid.across ?? grid.step, grid.shake, rng, (x, z, lot) => {
36
+ if (lot[1] > 0.9 && lot[2] === worked && lot[3] > FARM_LIFE.edgeRoom) places.push([x, z]);
37
+ });
38
+ return places;
39
+ }
40
+
41
+ /**
42
+ * A herd on a parcel: its numbers, sizes and coats; most graze, heading much the same way, the rest stand and look about.
43
+ *
44
+ * @param {ReturnType<import('./field-survey.js').createFieldSurvey>} survey - The survey.
45
+ * @param {object} fields - The survey's record, with its field map drawn.
46
+ * @param {object} parcel - The pasture.
47
+ * @param {{ herd: number[], size: number[], room: number, coats: number[] }} kind - The herd's least and most animals, their
48
+ * least and greatest size, the room each keeps in metres, and their coats (sRGB).
49
+ * @param {Function} rng - A repeatable stream.
50
+ * @returns {{ grazing: number[][], standing: number[][], room: number }} Each animal a site `[x, z, yaw, size, coat]`, those
51
+ * with their heads down and those standing; and the room to keep round each, for the caller's walker.
52
+ */
53
+ export function herdPlaces(survey, fields, parcel, kind, rng) {
54
+ const places = parcelPlaces(survey, fields, parcel, FARM_LIFE.grazing, 0, rng),
55
+ heading = rng() * TAU,
56
+ count = Math.min(places.length, Math.round(lerp(kind.herd[0], kind.herd[1], rng()))),
57
+ grazing = [],
58
+ standing = [];
59
+ for (let i = 0; i < count; i++) {
60
+ const [x, z] = places.splice(Math.floor(rng() * places.length), 1)[0];
61
+ const site = [
62
+ x,
63
+ z,
64
+ heading + (rng() - 0.5) * FARM_LIFE.grazing.turn,
65
+ lerp(kind.size[0], kind.size[1], rng()),
66
+ kind.coats[Math.floor(rng() * kind.coats.length)],
67
+ ];
68
+ (rng() < FARM_LIFE.grazing.share ? grazing : standing).push(site);
69
+ }
70
+ return { grazing, standing, room: kind.room };
71
+ }
72
+
73
+ /** Default livestock herd definitions when the caller does not pass its own coats or sizes. */
74
+ export const DEFAULT_FARM_HERDS = Object.freeze({
75
+ cattle: Object.freeze({
76
+ herd: [5, 9],
77
+ size: [0.92, 1.1],
78
+ room: 0.75,
79
+ coats: [0x9a6a4c, 0x80553c, 0xbfa07c, 0x54463e, 0xddd3c0, 0x7a5a44],
80
+ }),
81
+ sheep: Object.freeze({ herd: [7, 13], size: [0.9, 1.08], room: 0.45, coats: [0xd8d0c0, 0xc8bfa8, 0xb6ac96, 0x6c6256] }),
82
+ });
83
+
84
+ /**
85
+ * The partly ploughed parcel nearest a place whose next furrow lies well inside it, with where the team stands on it and the way
86
+ * it faces.
87
+ *
88
+ * @param {ReturnType<import('./field-survey.js').createFieldSurvey>} survey - The survey.
89
+ * @param {object} fields - The survey's record, with its field map drawn.
90
+ * @param {(x: number, z: number) => number} ground - The terrain's height at a place, metres.
91
+ * @param {number[]} near - The place (a town, say) the team is chosen nearest, `[x, z]`.
92
+ * @param {number} [reach=FARM_LIFE.teamReach] - Metres ahead of the plough used to sample the team's heading and slope.
93
+ * @returns {{ far: number, x: number, z: number, yaw: number, climb: number } | null} The site: its distance from `near`, where the
94
+ * plough stands, the way it faces, and the climb its oxen stand on (radians); null where no parcel is under the plough.
95
+ */
96
+ export function ploughSite(survey, fields, ground, near, reach = FARM_LIFE.teamReach) {
97
+ const USE = survey.USE,
98
+ lot = [0, 0, 0, 0],
99
+ here = [0, 0],
100
+ ahead = [0, 0];
101
+ let best = null;
102
+ for (const parcel of fields.parcels) {
103
+ if (parcel.use !== USE.plough || parcel.progress <= 0 || parcel.progress >= 1) continue;
104
+ const [c, s] = parcel.axis,
105
+ u = lerp(parcel.along[0], parcel.along[1], 0.5),
106
+ v = lerp(parcel.across[0], parcel.across[1], parcel.progress);
107
+ survey.unbend(u * c - v * s, u * s + v * c, here);
108
+ survey.unbend((u + reach) * c - v * s, (u + reach) * s + v * c, ahead);
109
+ if (!survey.lot(fields, here[0], here[1], lot) || lot[0] !== USE.plough || lot[1] < 0.9 || lot[3] < 2 * FARM_LIFE.edgeRoom) continue;
110
+ const far = Math.hypot(here[0] - near[0], here[1] - near[1]);
111
+ const climb = Math.atan2(ground(ahead[0], ahead[1]) - ground(here[0], here[1]), reach); // the team stands on the slope
112
+ if (!best || far < best.far) best = { far, x: here[0], z: here[1], yaw: Math.atan2(ahead[0] - here[0], ahead[1] - here[1]), climb };
113
+ }
114
+ return best;
115
+ }
116
+
117
+ /**
118
+ * Plan the season's life on a farm's fields from the field map: a row of stooks down every strip of the stubble, cocks of hay on
119
+ * the mown meadows, and cattle or sheep at pasture (of the pastures, `cattleShare` by cattle, the rest by sheep), all placed
120
+ * along the parcels' bent rows and stopping where their work has. The few animals and haycocks are gathered by shape and by
121
+ * square of the land, so a view over many parcels draws a handful of meshes; the many stooks stay a mesh a parcel, so only the
122
+ * parcels close by are drawn in full.
123
+ *
124
+ * @param {object} options
125
+ * @param {object} options.fields - The survey's record, with its field map drawn.
126
+ * @param {ReturnType<import('./field-survey.js').createFieldSurvey>} options.survey - The survey.
127
+ * @param {Function} options.random - A repeatable stream.
128
+ * @param {{ cattle: object, sheep: object }} [options.kinds] - The two herds' kinds, as {@link herdPlaces} takes them.
129
+ * @param {Partial<typeof FARM_LIFE>} [options.shape] - Changes to {@link FARM_LIFE}.
130
+ * @returns {{ lots: Map<string, { id: string, near: number, sites: number[][] }>, herds: { room: number, sites: number[][] }[] }}
131
+ * `lots`: in the order the shapes come, each the copies of one shape (by `id`: `stook`, `haycock`, `cattle` or `sheep` with
132
+ * `grazing` or `standing`) drawn within `near` metres in full, and their sites `[x, z, yaw, size, tint]`; `herds`: each herd's
133
+ * sites and the room to keep round each, for the caller's walker.
134
+ */
135
+ export function planFarmLife({ fields, survey, random, kinds = DEFAULT_FARM_HERDS, shape = {} }) {
136
+ const { near: NEAR, gather: GATHER, stooks: STOOKS, haycocks: HAYCOCKS, cattleShare: CATTLE_SHARE } = { ...FARM_LIFE, ...shape };
137
+ const rng = random,
138
+ USE = survey.USE,
139
+ lots = new Map(),
140
+ herds = [];
141
+ const place = (id, near, sites, group) => {
142
+ for (const site of sites) {
143
+ const key = id + ':' + (group ?? Math.floor(site[0] / GATHER) + ':' + Math.floor(site[1] / GATHER));
144
+ if (!lots.has(key)) lots.set(key, { id, near, sites: [] });
145
+ lots.get(key).sites.push(site);
146
+ }
147
+ };
148
+ fields.parcels.forEach((parcel, index) => {
149
+ if (parcel.use === USE.grain) {
150
+ const along = Math.PI / 2 - parcel.angle;
151
+ place(
152
+ 'stook',
153
+ STOOKS.near,
154
+ parcelPlaces(survey, fields, parcel, STOOKS, 1, rng).map(([x, z]) => [
155
+ x,
156
+ z,
157
+ along + (rng() - 0.5) * STOOKS.turn,
158
+ STOOKS.size[0] + rng() * STOOKS.size[1],
159
+ 0xffffff,
160
+ ]),
161
+ index,
162
+ );
163
+ }
164
+ if (parcel.use !== USE.grass) return;
165
+ place(
166
+ 'haycock',
167
+ NEAR,
168
+ parcelPlaces(survey, fields, parcel, HAYCOCKS, 1, rng).map(([x, z]) => [
169
+ x,
170
+ z,
171
+ rng() * TAU,
172
+ HAYCOCKS.size[0] + rng() * HAYCOCKS.size[1],
173
+ 0xffffff,
174
+ ]),
175
+ );
176
+ const cows = (index * 0.618) % 1 < CATTLE_SHARE,
177
+ herd = herdPlaces(survey, fields, parcel, cows ? kinds.cattle : kinds.sheep, rng);
178
+ place((cows ? 'cattle' : 'sheep') + 'grazing', NEAR, herd.grazing);
179
+ place((cows ? 'cattle' : 'sheep') + 'standing', NEAR, herd.standing);
180
+ herds.push({ room: herd.room, sites: [...herd.grazing, ...herd.standing] });
181
+ });
182
+ return { lots, herds };
183
+ }