roamwright 0.61.17 → 0.61.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -30,7 +30,7 @@ npm resolves the Three.js peer in a new project. Roamwright targets Three.js **0
30
30
 
31
31
  ## Examples
32
32
 
33
- Browse all twenty-one examples on the [live showcase](https://enestaylan.github.io/roamwright/).
33
+ Browse all twenty examples on the [live showcase](https://enestaylan.github.io/roamwright/).
34
34
 
35
35
  | Live example | What the example shows | Source |
36
36
  | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
@@ -53,7 +53,6 @@ Browse all twenty-one examples on the [live showcase](https://enestaylan.github.
53
53
  | [A baked land](https://enestaylan.github.io/roamwright/examples/land.html?seed=7) | One height sheet baked row by row with erosion, coast, river ford, banked road, cliff-faced tel, quarry and upland mere. | [land.js](examples/land.js) |
54
54
  | [Island](https://enestaylan.github.io/roamwright/examples/island.html?seed=42) | Fractal terrain shapes a coastline, sandy coves, weathered boulders and coastal pines in turquoise shallows. | [island.js](examples/island.js) |
55
55
  | [Pacing and measuring](https://enestaylan.github.io/roamwright/examples/pacing.html?seed=42) | Device-aware presets, ground render order, frame-pacing watch and a live performance box over a coastal valley. | [pacing.js](examples/pacing.js) |
56
- | [Ruins, rocks & paved roads](https://enestaylan.github.io/roamwright/examples/ruins.html?seed=42) | Hilltop ruins, buried-town mounds, bedded outcrops, a paved arch highway with cedar avenue and a flagstone plaza. | [ruins.js](examples/ruins.js) |
57
56
  | [World map and wayfinding](https://enestaylan.github.io/roamwright/examples/world-map.html?seed=42) | Shaded atlas relief, baked terrain sheets, collision-free lettering, interactive pan/zoom/tap and a live compass strip. | [world-map.js](examples/world-map.js) |
58
57
 
59
58
  ### Run locally
@@ -1,10 +1,19 @@
1
1
  import * as THREE from 'three';
2
2
  import {
3
+ FLOWER_KINDS,
3
4
  GeometryBuilder,
5
+ buildBarnDoors,
4
6
  buildHaystacks,
5
7
  buildStonePile,
8
+ createCragLibrary,
9
+ createFigureAssembler,
10
+ createFigureBuilder,
11
+ createLivestockCache,
12
+ createPloughTeam,
13
+ createTuftMaterial,
6
14
  createUnitShapes,
7
15
  drystoneStone,
16
+ geometryOf,
8
17
  layRoads,
9
18
  meshSprings,
10
19
  meshStreamBanks,
@@ -12,13 +21,16 @@ import {
12
21
  planDrystoneWall,
13
22
  planSprings,
14
23
  planStreamBanks,
24
+ tuftGeometry,
15
25
  } from 'roamwright';
16
- import { instancedMesh } from 'roamwright/geometry/instances.js';
26
+ import { instanceArrays, instancedMesh, putInstance } from 'roamwright/geometry/instances.js';
27
+ import { C, TRS } from 'roamwright/geometry/primitives.js';
17
28
  import { SRGB2LIN } from 'roamwright/math/color.js';
18
- import { lerp } from 'roamwright/math/scalar.js';
29
+ import { lerp, TAU } from 'roamwright/math/scalar.js';
19
30
 
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 }) {
31
+ // Roads, river springhead, stoned banks, crag boulders, drystone farmstead with barn doors, haystacks, stone pile,
32
+ // oxen plough team with ploughman, and flowering meadow tufts for examples/land.js.
33
+ export function buildLandFeatures({ worldGroup, camera, land, waters, groundExact, sea, shoreZ, tones, seed, fbm, vnoise }) {
22
34
  const roadColor = (tone, mul) => ({ r: SRGB2LIN[tone[0]] * mul, g: SRGB2LIN[tone[1]] * mul, b: SRGB2LIN[tone[2]] * mul });
23
35
  const roadSoil = roadColor(tones.debris, 0.72),
24
36
  roadVerge = roadColor(tones.grass, 0.9);
@@ -32,6 +44,7 @@ export function buildLandFeatures({ worldGroup, land, waters, groundExact, sea,
32
44
  });
33
45
 
34
46
  const shapes = createUnitShapes(fbm);
47
+ const crags = createCragLibrary({ fbm, vnoise });
35
48
  const [river] = waters.channels;
36
49
  const riverPts = river.line.filter(([, z]) => z <= shoreZ + 10);
37
50
  const bed = Float32Array.from(riverPts, ([x, z]) => groundExact(x, z) - 0.4);
@@ -44,7 +57,7 @@ export function buildLandFeatures({ worldGroup, land, waters, groundExact, sea,
44
57
  });
45
58
  meshStreamBanks({
46
59
  plans,
47
- stone: { geometry: shapes.rock, material: new THREE.MeshStandardMaterial({ roughness: 0.92 }) },
60
+ stone: { geometry: crags.fallenStone(1, seed * 11), material: new THREE.MeshStandardMaterial({ roughness: 0.92 }) },
48
61
  log: { geometry: shapes.cyl, material: new THREE.MeshStandardMaterial({ roughness: 0.95 }) },
49
62
  parent: worldGroup,
50
63
  });
@@ -56,7 +69,7 @@ export function buildLandFeatures({ worldGroup, land, waters, groundExact, sea,
56
69
  random: mulberry32(seed * 47),
57
70
  }),
58
71
  parent: worldGroup,
59
- crag: () => shapes.rock,
72
+ crag: fineness => crags.crag(fineness),
60
73
  });
61
74
 
62
75
  const wallRng = mulberry32(seed * 53);
@@ -88,15 +101,123 @@ export function buildLandFeatures({ worldGroup, land, waters, groundExact, sea,
88
101
  wallMesh.castShadow = wallMesh.receiveShadow = true;
89
102
  worldGroup.add(wallMesh);
90
103
 
91
- const placeProp = (build, x, z, roughness) => {
104
+ const placeProp = (build, x, z, roughness, yaw = 0) => {
92
105
  const gb = new GeometryBuilder();
93
106
  build(gb);
94
107
  const mesh = gb.mesh(new THREE.MeshStandardMaterial({ vertexColors: true, roughness }), worldGroup);
95
108
  if (mesh) {
96
109
  mesh.position.set(x, groundExact(x, z), z);
110
+ mesh.rotation.y = yaw;
97
111
  mesh.updateMatrix();
98
112
  }
99
113
  };
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);
114
+ placeProp(gb => buildHaystacks(gb, mulberry32(seed * 59), { noise: vnoise, box: shapes.box }), 196, 84, 0.96);
115
+ placeProp(gb => buildStonePile(gb, mulberry32(seed * 61), { rock: shapes.rock }), 206, 78, 0.92);
116
+
117
+ // Weatherboarded timber barn with Roamwright's braced double barn doors facing the yard.
118
+ const barnRng = mulberry32(seed * 67);
119
+ placeProp(
120
+ gb => {
121
+ const w = 8.4,
122
+ d = 5.9,
123
+ h = 3.9,
124
+ rise = 2.0;
125
+ const wallCol = C(0x7c674c, 0.08, barnRng);
126
+ const roofCol = C(0x6e4a38, 0.1, barnRng);
127
+ gb.box(0, -0.5, 0, w, h + 0.5, d, wallCol);
128
+ // Gable end triangles built with triangular prisms along the ridge.
129
+ const slope = Math.hypot(d * 0.5 + 0.45, rise);
130
+ const pitch = Math.atan2(rise, d * 0.5 + 0.45);
131
+ for (const s of [-1, 1]) {
132
+ // Pitched timber roof deck with overhanging eaves and ridge overlap.
133
+ gb.box(0, h + rise * 0.5 - 0.08, s * (d * 0.25 + 0.12), w + 0.7, 0.24, slope, roofCol, 0, s * pitch);
134
+ // Stepped timber courses filling each gable peak cleanly behind the eaves.
135
+ for (let k = 0; k < 5; k++) {
136
+ const f = (k + 0.5) / 5;
137
+ gb.box(s * (w * 0.5 - 0.18), h + f * rise, 0, 0.36, rise / 5 + 0.04, d * (1 - f), wallCol);
138
+ }
139
+ }
140
+ gb.box(0, h + rise + 0.04, 0, w + 0.76, 0.22, 0.28, C(0x523628, 0.08, barnRng));
141
+ buildBarnDoors(gb, barnRng, { depth: d, box: shapes.box });
142
+ },
143
+ 181,
144
+ 80,
145
+ 0.93,
146
+ 0.22,
147
+ );
148
+
149
+ // Yoked oxen plough team with a posed ploughman working the open strip inside the farmstead.
150
+ const figureKit = createFigureBuilder();
151
+ const figMat = () => new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.88, side: THREE.DoubleSide });
152
+ const { assembleFigure } = createFigureAssembler({ material: figMat, holds: figureKit.kit.holds });
153
+ const buildFigure = (look, figSeed) => {
154
+ const far = figureKit.buildBody(look, figSeed, 1);
155
+ return assembleFigure(look, 'human', { ...far, geo: geometryOf(far.parts) }, null);
156
+ };
157
+ const livestock = createLivestockCache();
158
+ const team = createPloughTeam({
159
+ oxen: livestock.cattleGeometry(false, false, 'ox'),
160
+ random: mulberry32(seed * 71),
161
+ camera: null,
162
+ seenDistance: 0,
163
+ buildFigure,
164
+ shapes,
165
+ layer: null,
166
+ });
167
+ const px = 198,
168
+ pz = 102;
169
+ team.position.set(px, groundExact(px, pz), pz);
170
+ team.rotation.set(0, -0.45, 0, 'YXZ');
171
+ worldGroup.add(team);
172
+
173
+ // Flowering meadow tufts (poppies, daisies, buttercups, grain ears) swaying in the wind around the farmstead.
174
+ const tuftRng = mulberry32(seed * 79);
175
+ const tuftGeo = tuftGeometry({ seed: seed * 37 + 5 });
176
+ const uTime = { value: 0 };
177
+ const uCam = { value: new THREE.Vector3(px, groundExact(px, pz), pz) };
178
+ const uR = { value: 90 };
179
+ const tuftMat = createTuftMaterial(uCam, uR, false, {
180
+ uTime,
181
+ uSunLight: { value: 1 },
182
+ uWind: { value: new THREE.Vector3(1.1, 0, 0.4) },
183
+ });
184
+ const flowerKinds = [0, 0, 0, FLOWER_KINDS.poppy, FLOWER_KINDS.daisy, FLOWER_KINDS.buttercup, FLOWER_KINDS.ear];
185
+ const tuftCount = 320;
186
+ const tuftArr = instanceArrays(tuftCount);
187
+ const flowerAttr = new Float32Array(tuftCount);
188
+ let placed = 0;
189
+ for (let i = 0; i < tuftCount; i++) {
190
+ const tx = 166 + tuftRng() * 54;
191
+ const tz = 68 + tuftRng() * 48;
192
+ if (Math.hypot(tx - 181, tz - 80) < 7.5 || Math.hypot(tx - px, tz - pz) < 4.5) continue;
193
+ const ty = groundExact(tx, tz) - 0.03;
194
+ const wide = 0.6 + tuftRng() * 0.45;
195
+ const tall = wide * (0.75 + tuftRng() * 0.55);
196
+ const kind = flowerKinds[(tuftRng() * flowerKinds.length) | 0];
197
+ putInstance(
198
+ tuftArr,
199
+ placed,
200
+ TRS(tx, ty, tz, wide, tall, wide, tuftRng() * TAU),
201
+ 0.16 + tuftRng() * 0.08,
202
+ 0.24 + tuftRng() * 0.1,
203
+ 0.07 + tuftRng() * 0.04,
204
+ );
205
+ flowerAttr[placed] = kind ? kind * 4 + 1 + (i % 3) : 0;
206
+ placed++;
207
+ }
208
+ tuftGeo.setAttribute('aFlower', new THREE.InstancedBufferAttribute(flowerAttr.subarray(0, placed), 1));
209
+ const tufts = instancedMesh(tuftGeo, tuftMat, {
210
+ matrices: tuftArr.matrices.subarray(0, placed * 16),
211
+ colours: tuftArr.colours.subarray(0, placed * 3),
212
+ });
213
+ tufts.receiveShadow = true;
214
+ tufts.frustumCulled = false;
215
+ worldGroup.add(tufts);
216
+
217
+ return {
218
+ update(elapsed) {
219
+ uTime.value = elapsed;
220
+ if (camera) uCam.value.copy(camera.position);
221
+ },
222
+ };
102
223
  }
@@ -38,12 +38,13 @@
38
38
  <h1>A baked land</h1>
39
39
  <p id="status">
40
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.
41
+ farmstead with braced barn doors, haystacks, plough team and flowering tufts, cliff-faced tel, quarry and port pad.
42
42
  </p>
43
43
  </div>
44
44
  <div class="tools">
45
45
  <div class="views" role="group" aria-label="Camera viewpoint">
46
46
  <button type="button" data-view="coast" aria-pressed="true">Coast &amp; tel</button>
47
+ <button type="button" data-view="farmstead" aria-pressed="false">Farmstead</button>
47
48
  <button type="button" data-view="ford" aria-pressed="false">River ford</button>
48
49
  <button type="button" data-view="quarry" aria-pressed="false">Quarry &amp; mere</button>
49
50
  <button type="button" data-view="port" aria-pressed="false">Port pad</button>
package/examples/land.js CHANGED
@@ -363,7 +363,19 @@ const groundExact = (x, z) => {
363
363
  return fx + fz <= 1 ? h00 + (h10 - h00) * fx + (h01 - h00) * fz : h11 + (h01 - h11) * (1 - fx) + (h10 - h11) * (1 - fz);
364
364
  };
365
365
 
366
- buildLandFeatures({ worldGroup, land, waters, groundExact, sea: SEA, shoreZ: SHORE_Z, tones: TONE, seed, fbm, vnoise });
366
+ const features = buildLandFeatures({
367
+ worldGroup,
368
+ camera,
369
+ land,
370
+ waters,
371
+ groundExact,
372
+ sea: SEA,
373
+ shoreZ: SHORE_Z,
374
+ tones: TONE,
375
+ seed,
376
+ fbm,
377
+ vnoise,
378
+ });
367
379
 
368
380
  createDaylightSky({
369
381
  scene,
@@ -384,6 +396,7 @@ status.textContent = `${STRIDE} × ${STRIDE} points (${sheet.spacing} m step): c
384
396
 
385
397
  const views = {
386
398
  coast: { eye: [365, 138, 440], target: [35, 8, -35] },
399
+ farmstead: { eye: [215, 17, 124], target: [190, 9, 88] },
387
400
  ford: { eye: [228, 36, 152], target: [148, 8, 56] },
388
401
  quarry: { eye: [-180, 125, -45], target: [-420, 14, -220] },
389
402
  port: { eye: [-55, 78, 560], target: [-230, 5, 360] },
@@ -412,7 +425,9 @@ rig.controls.update();
412
425
  const clock = new THREE.Timer();
413
426
  renderer.setAnimationLoop(() => {
414
427
  clock.update();
415
- waterTime.value = clock.getElapsed();
428
+ const elapsed = clock.getElapsed();
429
+ waterTime.value = elapsed;
430
+ features.update(elapsed);
416
431
  rig.clampCamera();
417
432
  renderer.render(scene, camera);
418
433
  });
@@ -40,6 +40,29 @@ export const FARM_STONE_PILE = Object.freeze({
40
40
  colorJitter: 0.24,
41
41
  });
42
42
 
43
+ /**
44
+ * Default plank count, framing dimensions (in metres) and weathered timber sRGB colours for braced
45
+ * double barn doors built by {@link buildBarnDoors}.
46
+ */
47
+ export const FARM_BARN_DOORS = Object.freeze({
48
+ planks: 14,
49
+ plankStep: 0.22,
50
+ plankWidth: 0.215,
51
+ plankHeight: 2.7,
52
+ plankThickness: 0.13,
53
+ plankColor: 0x68523b,
54
+ plankJitter: 0.23,
55
+ frameColor: 0x5b4936,
56
+ jambOffset: 1.6,
57
+ jambWidth: 0.23,
58
+ jambHeight: 3,
59
+ lintelWidth: 3.42,
60
+ lintelHeight: 0.21,
61
+ lintelDepth: 0.24,
62
+ braceThickness: 0.1,
63
+ zOutset: 0.19,
64
+ });
65
+
43
66
  /**
44
67
  * Build one or more tall farmyard haystacks (by default a pair side by side) with weathered, bulging straw bodies and loose
45
68
  * projecting straw wisps into a geometry builder.
@@ -105,3 +128,39 @@ export function buildStonePile(builder, random = Math.random, options = {}) {
105
128
  );
106
129
  }
107
130
  }
131
+
132
+ /**
133
+ * Build a pair of vertical-planked, diagonally braced double barn doors framed by heavy jamb posts
134
+ * and a lintel into a wood geometry builder.
135
+ *
136
+ * @param {Pick<import('./builder.js').GB, 'box' | 'add'>} builder - Destination wood geometry builder.
137
+ * @param {() => number} [random=Math.random] - Repeatable random stream in `[0, 1)`.
138
+ * @param {object} [options]
139
+ * @param {number} [options.depth=5.9] - Barn depth in metres used to position the door face when `z` is omitted.
140
+ * @param {number} [options.z] - Explicit local Z position of the door plane in metres (overrides `depth * 0.5 + shape.zOutset`).
141
+ * @param {import('three').BufferGeometry} [options.box] - Unit box geometry for diagonal timber braces (defaults to `primitives.box`).
142
+ * @param {Partial<typeof FARM_BARN_DOORS>} [options.shape] - Overrides for {@link FARM_BARN_DOORS}.
143
+ */
144
+ export function buildBarnDoors(builder, random = Math.random, options = {}) {
145
+ const cfg = options.shape ? { ...FARM_BARN_DOORS, ...options.shape } : FARM_BARN_DOORS;
146
+ const braceBox = options.box ?? box;
147
+ const doorZ = options.z ?? (options.depth ?? 5.9) * 0.5 + cfg.zOutset;
148
+ const timber = C(cfg.frameColor);
149
+ const half = (cfg.planks - 1) * 0.5;
150
+ for (let j = 0; j < cfg.planks; j++) {
151
+ builder.box(
152
+ (j - half) * cfg.plankStep,
153
+ 0.02 + (j % 3) * 0.015,
154
+ doorZ,
155
+ cfg.plankWidth,
156
+ cfg.plankHeight,
157
+ cfg.plankThickness,
158
+ C(cfg.plankColor, cfg.plankJitter, random),
159
+ );
160
+ }
161
+ for (const sign of [-1, 1]) {
162
+ builder.box(sign * cfg.jambOffset, -0.12, doorZ, cfg.jambWidth, cfg.jambHeight, cfg.jambWidth, timber);
163
+ stick(builder, [sign * 0.16, 0.28, doorZ + 0.075], [sign * 1.43, 2.38, doorZ + 0.075], cfg.braceThickness, timber, braceBox);
164
+ }
165
+ builder.box(0, cfg.plankHeight, doorZ, cfg.lintelWidth, cfg.lintelHeight, cfg.lintelDepth, timber);
166
+ }
@@ -57,3 +57,150 @@ export function extendFieldBorders(
57
57
  }
58
58
  }
59
59
  }
60
+
61
+ /**
62
+ * Bit layout of the compact 1-byte-per-texel farmland map produced by {@link packFieldBits}.
63
+ */
64
+ export const FIELD_BITS = Object.freeze({
65
+ /** Farm track bit (wheel-rut strength above threshold). */
66
+ track: 1,
67
+ /** Standing crop bit (coverage above threshold). */
68
+ crop: 2,
69
+ /** Worked-season bit (lot work byte above threshold). */
70
+ worked: 4,
71
+ /** Bit shift of the quantized parcel use index (`0..6`). */
72
+ useShift: 3,
73
+ });
74
+
75
+ /** Default sentinel distance in metres where no trail or dry wash is nearby. */
76
+ export const NO_PATH_DISTANCE = 99;
77
+
78
+ /**
79
+ * Pack RGBA field and lot rasters into a single byte per texel holding track, crop, worked flags
80
+ * and quantized parcel use so the full RGBA arrays can be released after startup.
81
+ *
82
+ * @param {object} fields - Field raster container `{ data, lots, width, height }`.
83
+ * @param {Uint8Array | Uint8ClampedArray} fields.data - RGBA field raster.
84
+ * @param {Uint8Array | Uint8ClampedArray} fields.lots - RGBA lot-work raster.
85
+ * @param {number} fields.width - Raster width in texels.
86
+ * @param {number} fields.height - Raster height in texels.
87
+ * @param {object} [options]
88
+ * @param {number} [options.trackThreshold=45] - Blue-channel threshold for farm tracks.
89
+ * @param {number} [options.cropThreshold=100] - Alpha-channel threshold for standing crops.
90
+ * @param {number} [options.workedThreshold=127] - Lot blue-channel threshold for worked parcels.
91
+ * @param {number} [options.useStep=42] - Quantization divisor for the green parcel-use byte.
92
+ * @returns {Uint8Array}
93
+ */
94
+ export function packFieldBits(fields, options = {}) {
95
+ const { data, lots, width, height } = fields;
96
+ const trackThreshold = options.trackThreshold ?? 45;
97
+ const cropThreshold = options.cropThreshold ?? 100;
98
+ const workedThreshold = options.workedThreshold ?? 127;
99
+ const useStep = options.useStep ?? 42;
100
+ const count = width * height;
101
+ const bits = new Uint8Array(count);
102
+ for (let p = 0; p < count; p++) {
103
+ const k = p * 4;
104
+ bits[p] =
105
+ (data[k + 2] > trackThreshold ? FIELD_BITS.track : 0) |
106
+ (data[k + 3] > cropThreshold ? FIELD_BITS.crop : 0) |
107
+ (lots[k + 2] > workedThreshold ? FIELD_BITS.worked : 0) |
108
+ (Math.round(data[k + 1] / useStep) << FIELD_BITS.useShift);
109
+ }
110
+ return bits;
111
+ }
112
+
113
+ /**
114
+ * Crop full-map plain cover, trail-distance and wash-distance grids down to the tight bounding box
115
+ * of active cells so large empty areas cost no memory.
116
+ *
117
+ * @param {object} options
118
+ * @param {number} options.stride - Grid width and height in cells.
119
+ * @param {Uint8Array | Uint8ClampedArray} options.cover - Interleaved 2-channel plain cover grid (channel 0 is bunch grass).
120
+ * @param {Float32Array} options.track - Distance to nearest herd trail per cell in metres.
121
+ * @param {Float32Array} options.wash - Distance to nearest dry wash per cell in metres.
122
+ * @param {number} [options.noPath=NO_PATH_DISTANCE] - Sentinel distance for cells with no nearby path.
123
+ * @returns {{ i0: number, j0: number, w: number, h: number, bunch: Uint8Array, track: Float32Array, wash: Float32Array }}
124
+ */
125
+ export function packSparsePlain({ stride, cover, track, wash, noPath = NO_PATH_DISTANCE }) {
126
+ let i0 = stride;
127
+ let i1 = -1;
128
+ let j0 = stride;
129
+ let j1 = -1;
130
+ for (let j = 0; j < stride; j++) {
131
+ for (let i = 0; i < stride; i++) {
132
+ const k = j * stride + i;
133
+ if (!cover[k * 2] && track[k] === noPath && wash[k] === noPath) continue;
134
+ i0 = Math.min(i0, i);
135
+ i1 = Math.max(i1, i);
136
+ j0 = Math.min(j0, j);
137
+ j1 = Math.max(j1, j);
138
+ }
139
+ }
140
+ const w = Math.max(0, i1 - i0 + 1);
141
+ const h = Math.max(0, j1 - j0 + 1);
142
+ const out = { i0, j0, w, h, bunch: new Uint8Array(w * h), track: new Float32Array(w * h), wash: new Float32Array(w * h) };
143
+ for (let j = 0; j < h; j++) {
144
+ for (let i = 0; i < w; i++) {
145
+ const k = (j0 + j) * stride + i0 + i;
146
+ const c = j * w + i;
147
+ out.bunch[c] = cover[k * 2];
148
+ out.track[c] = track[k];
149
+ out.wash[c] = wash[k];
150
+ }
151
+ }
152
+ return out;
153
+ }
154
+
155
+ /**
156
+ * Create a compact runtime cache for grass placement queries over packed farmland bits and a
157
+ * cropped sparse plain/trail/wash rectangle.
158
+ *
159
+ * @param {object} options
160
+ * @param {number} options.stride - Terrain height-grid width in cells.
161
+ * @param {(x: number, z: number) => number} options.fieldPixel - Maps world `(x, z)` to RGBA byte offset in the field map, or `< 0` outside.
162
+ * @param {number} [options.noPath=NO_PATH_DISTANCE] - Sentinel distance returned outside the cropped plain rectangle.
163
+ * @returns {{
164
+ * keep: (input: { fields: { data: Uint8Array | Uint8ClampedArray, lots: Uint8Array | Uint8ClampedArray, width: number, height: number }, cover: Uint8Array | Uint8ClampedArray, track: Float32Array, wash: Float32Array }) => void,
165
+ * fieldSpot: (x: number, z: number) => number,
166
+ * plainAt: (cellIndex: number, out: number[]) => number[],
167
+ * clear: () => void,
168
+ * }}
169
+ */
170
+ export function createFieldCoverCache({ stride, fieldPixel, noPath = NO_PATH_DISTANCE }) {
171
+ let fieldBits = null;
172
+ let plain = null;
173
+ return {
174
+ keep({ fields, cover, track, wash }) {
175
+ fieldBits = packFieldBits(fields);
176
+ plain = packSparsePlain({ stride, cover, track, wash, noPath });
177
+ },
178
+ fieldSpot(x, z) {
179
+ const k = fieldPixel(x, z);
180
+ return k < 0 || !fieldBits ? 0 : fieldBits[k >> 2];
181
+ },
182
+ plainAt(k, out) {
183
+ if (!plain) {
184
+ out[0] = 0;
185
+ out[1] = out[2] = noPath;
186
+ return out;
187
+ }
188
+ const i = (k % stride) - plain.i0;
189
+ const j = ((k / stride) | 0) - plain.j0;
190
+ if (i < 0 || j < 0 || i >= plain.w || j >= plain.h) {
191
+ out[0] = 0;
192
+ out[1] = out[2] = noPath;
193
+ } else {
194
+ const c = j * plain.w + i;
195
+ out[0] = plain.bunch[c];
196
+ out[1] = plain.track[c];
197
+ out[2] = plain.wash[c];
198
+ }
199
+ return out;
200
+ },
201
+ clear() {
202
+ fieldBits = null;
203
+ plain = null;
204
+ },
205
+ };
206
+ }
@@ -75,6 +75,46 @@ class Copies {
75
75
 
76
76
  export { Copies, instanceArrays, instancedMesh, instancedTwin, putInstance };
77
77
 
78
+ /**
79
+ * Round-robin instanced batch builder over an array of variant geometries: distributes added
80
+ * `(matrix, [r, g, b])` instances evenly across `shapes`, then emits one static `THREE.InstancedMesh`
81
+ * per non-empty variant into a scene or group.
82
+ *
83
+ * @param {THREE.BufferGeometry[]} shapes - Variant geometries (each copied through `geometryView` on build).
84
+ * @param {number} maxInstances - Maximum total capacity allocated per shape bucket.
85
+ * @returns {{
86
+ * put: (matrix: THREE.Matrix4, rgb: readonly [number, number, number]) => void,
87
+ * addTo: (group: THREE.Object3D, material: THREE.Material, options?: { castShadow?: boolean, receiveShadow?: boolean }) => THREE.InstancedMesh[],
88
+ * }}
89
+ */
90
+ export function createShapeBatches(shapes, maxInstances) {
91
+ const batches = shapes.map(() => ({ copies: instanceArrays(maxInstances), count: 0 }));
92
+ let turn = 0;
93
+ return {
94
+ put(matrix, [r, g, b]) {
95
+ const batch = batches[turn++ % batches.length];
96
+ putInstance(batch.copies, batch.count++, matrix, r, g, b);
97
+ },
98
+ addTo(group, material, { castShadow = false, receiveShadow = true } = {}) {
99
+ const meshes = [];
100
+ batches.forEach(({ copies, count }, i) => {
101
+ if (!count) return;
102
+ const mesh = instancedMesh(geometryView(shapes[i]), material, {
103
+ matrices: copies.matrices.subarray(0, count * 16),
104
+ colours: copies.colours.subarray(0, count * 3),
105
+ });
106
+ mesh.castShadow = castShadow;
107
+ mesh.receiveShadow = receiveShadow;
108
+ mesh.matrixAutoUpdate = false;
109
+ mesh.computeBoundingSphere();
110
+ if (group) group.add(mesh);
111
+ meshes.push(mesh);
112
+ });
113
+ return meshes;
114
+ },
115
+ };
116
+ }
117
+
78
118
  // Partition static world-space transforms and their colors into independently cullable
79
119
  // cells. A single cell keeps its original arrays; order within every cell is stable.
80
120
  export function partitionInstances(arrays, cellSize) {
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Pure geometry builder and flower/seed-head look tables for instanced grass tufts: fifteen tapered
3
+ * blades, the last three carrying collapsed petal slots opened on the GPU by `rendering/plant-tuft.js`.
4
+ * Worker-safe.
5
+ * @module
6
+ */
7
+
8
+ import * as THREE from 'three';
9
+ import { mulberry32 } from '../math/random.js';
10
+ import { TAU } from '../math/scalar.js';
11
+
12
+ /**
13
+ * Default tuft blade, stem and petal slot counts for {@link tuftGeometry}.
14
+ */
15
+ export const TUFT_SHAPE = Object.freeze({
16
+ /** Total blades in one grass tuft. */
17
+ blades: 15,
18
+ /** Trailing blades that can rise as flower or seed-head stems. */
19
+ stems: 3,
20
+ /** Petal slots attached to each stem tip (unused slots fold to zero). */
21
+ petals: 6,
22
+ /** Fractional distance along a petal where it reaches full width. */
23
+ sideT: 0.42,
24
+ /** Tallest blade height in tuft-local metres (`0.26..0.82`). */
25
+ tallest: 0.82,
26
+ });
27
+
28
+ /**
29
+ * Built-in flower and seed-head indices matching the order of {@link DEFAULT_FLOWER_LOOKS} (1-based; 0 is plain grass).
30
+ */
31
+ export const FLOWER_KINDS = Object.freeze({
32
+ poppy: 1,
33
+ cornflower: 2,
34
+ daisy: 3,
35
+ buttercup: 4,
36
+ yarrow: 5,
37
+ tansy: 6,
38
+ seeds: 7,
39
+ ear: 8,
40
+ });
41
+
42
+ const look = (stem, over, r, cup, wide, petals, spread, nod, heart, tip) =>
43
+ Object.freeze({ stem, over, r, cup, wide, petals, spread, nod, heart: Object.freeze(heart), tip: Object.freeze(tip) });
44
+
45
+ /**
46
+ * Default flower and grain-ear descriptors (metres, radians, linear RGB heart/tip colours) indexed by
47
+ * `FLOWER_KINDS[name] - 1`.
48
+ */
49
+ export const DEFAULT_FLOWER_LOOKS = Object.freeze([
50
+ // Field poppy: four broad scarlet petals cupped round a dark heart, nodding on a tall stem.
51
+ look(0.5, 1.12, 0.052, 0.7, 0.95, 4, 0, 0.35, [0.02, 0.012, 0.01], [0.6, 0.03, 0.015]),
52
+ // Cornflower: ragged blue flower head standing in grain.
53
+ look(0.55, 1.1, 0.03, 0.4, 0.42, 6, 0, 0.15, [0.07, 0.05, 0.2], [0.1, 0.2, 0.72]),
54
+ // Ox-eye daisy: flat white rays around a yellow centre.
55
+ look(0.32, 1.06, 0.032, 0.06, 0.36, 6, 0, 0.1, [0.78, 0.5, 0.03], [0.86, 0.86, 0.8]),
56
+ // Buttercup: small glossy yellow cup of damp ground.
57
+ look(0.36, 1.02, 0.021, 0.85, 0.9, 5, 0, 0.2, [0.62, 0.42, 0.01], [0.86, 0.68, 0.03]),
58
+ // Yarrow: flat-topped spray of off-white florets for dry plains.
59
+ look(0.4, 1.08, 0.046, 0.12, 0.62, 6, 0, 0.08, [0.5, 0.5, 0.42], [0.8, 0.78, 0.7]),
60
+ // Tansy: flat spray of golden buttons along damp margins and field edges.
61
+ look(0.45, 1.1, 0.04, 0.15, 0.62, 6, 0, 0.08, [0.45, 0.3, 0.02], [0.76, 0.56, 0.03]),
62
+ // Dry grass seed head: buff spikelets climbing a stalk over the tuft.
63
+ look(0, 1.24, 0.055, 1.2, 0.3, 6, 0.04, 0.5, [0.27, 0.22, 0.12], [0.48, 0.42, 0.27]),
64
+ // Ripe barley or wheat ear: close upright golden ear heavy enough to nod.
65
+ look(0, 1.12, 0.06, 1.38, 0.34, 6, 0.028, 0.42, [0.3, 0.2, 0.06], [0.5, 0.36, 0.12]),
66
+ ]);
67
+
68
+ /**
69
+ * Build a grass tuft `BufferGeometry` with `position`, `normal`, `aStem` and `aPetal` attributes.
70
+ * Each blade has a tapered base and bent tip (five vertices); trailing stem blades carry collapsed
71
+ * petal quads opened by the flowering tuft vertex shader (`rendering/plant-tuft.js`).
72
+ *
73
+ * @param {object} [options]
74
+ * @param {() => number} [options.random] - Deterministic PRNG in `[0, 1)` (defaults to `mulberry32(seed)`).
75
+ * @param {number} [options.seed=5] - Seed used when `random` is omitted.
76
+ * @param {Partial<typeof TUFT_SHAPE>} [options.shape] - Overrides to {@link TUFT_SHAPE}.
77
+ * @returns {THREE.BufferGeometry}
78
+ */
79
+ export function tuftGeometry(options = {}) {
80
+ const cfg = options.shape ? { ...TUFT_SHAPE, ...options.shape } : TUFT_SHAPE;
81
+ const rng = options.random ?? mulberry32(options.seed ?? 5);
82
+ const pos = [];
83
+ const stem = [];
84
+ const petal = [];
85
+ const index = [];
86
+ const corner = (x, y, z, s, h, cx, cz, p = 0, t = 0, side = 0, head = 0) => {
87
+ pos.push(x, y, z);
88
+ stem.push(s, h, cx, cz);
89
+ petal.push(p, t, side, head);
90
+ return pos.length / 3 - 1;
91
+ };
92
+ for (let b = 0; b < cfg.blades; b++) {
93
+ const a = rng() * TAU;
94
+ const r = Math.sqrt(rng()) * 0.63;
95
+ const x = Math.cos(a) * r;
96
+ const z = Math.sin(a) * r;
97
+ const h = 0.26 + rng() * 0.56;
98
+ const w = 0.016 + rng() * 0.021;
99
+ const la = rng() * TAU;
100
+ const lean = 0.08 + rng() * 0.26;
101
+ const dx = Math.cos(la);
102
+ const dz = Math.sin(la);
103
+ const mx = x + dx * lean * 0.32;
104
+ const mz = z + dz * lean * 0.32;
105
+ const mh = h * 0.58;
106
+ const w2 = w * 0.6;
107
+ const s = b >= cfg.blades - cfg.stems ? b - (cfg.blades - cfg.stems) + 1 : 0;
108
+ const tx = x + dx * lean;
109
+ const tz = z + dz * lean;
110
+ const i0 = corner(x - dz * w, 0, z + dx * w, s, h, x, z);
111
+ const i1 = corner(x + dz * w, 0, z - dx * w, s, h, x, z);
112
+ const i2 = corner(mx + dz * w2, mh, mz - dx * w2, s, h, mx, mz);
113
+ const i3 = corner(mx - dz * w2, mh, mz + dx * w2, s, h, mx, mz);
114
+ const i4 = corner(tx, h, tz, s, h, tx, tz);
115
+ index.push(i0, i1, i2, i0, i2, i3, i3, i2, i4);
116
+ if (!s) continue;
117
+ for (let p = 0; p < cfg.petals; p++) {
118
+ const foot = corner(tx, h, tz, s, h, x, z, p, 0, 0, 1);
119
+ const left = corner(tx, h, tz, s, h, x, z, p, cfg.sideT, -1, 1);
120
+ const right = corner(tx, h, tz, s, h, x, z, p, cfg.sideT, 1, 1);
121
+ const end = corner(tx, h, tz, s, h, x, z, p, 1, 0, 1);
122
+ index.push(foot, left, end, foot, end, right);
123
+ }
124
+ }
125
+ const g = new THREE.BufferGeometry();
126
+ g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
127
+ g.setAttribute(
128
+ 'normal',
129
+ new THREE.Float32BufferAttribute(
130
+ new Float32Array(pos.length).map((_, i) => (i % 3 === 1 ? 1 : 0)),
131
+ 3,
132
+ ),
133
+ );
134
+ g.setAttribute('aStem', new THREE.Float32BufferAttribute(stem, 4));
135
+ g.setAttribute('aPetal', new THREE.Float32BufferAttribute(petal, 4));
136
+ g.setIndex(index);
137
+ return g;
138
+ }