roamwright 0.61.25 → 0.61.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -101,3 +101,106 @@ export function planScatterInstances({
101
101
  total,
102
102
  };
103
103
  }
104
+
105
+ /**
106
+ * Default grid tiling, LOD transition, scale, lean, tint and trunk collider settings for
107
+ * {@link planTreeGrove} and `scatterTreeGrove`.
108
+ */
109
+ export const TREE_GROVE = Object.freeze({
110
+ /** Grid square edge length in metres used to batch neighbouring trees into one LOD stand. */
111
+ squareSize: 80,
112
+ /** Distance in metres at which each tiled stand switches from near to far geometry. */
113
+ nearDistance: 340,
114
+ /** Vertical sink below the sampled ground surface in metres. */
115
+ sink: 0.15,
116
+ /** Uniform tree scale `[minScale, scaleSpan]`. */
117
+ scaleRange: Object.freeze([0.8, 0.55]),
118
+ /** Maximum trunk pitch lean span in radians (`[-leanSpan/2, +leanSpan/2]`). */
119
+ leanSpan: 0.06,
120
+ /** Greyscale tint multiplier `[minShade, shadeSpan]`. */
121
+ shadeRange: Object.freeze([0.82, 0.3]),
122
+ /** Trunk circle-collider radius per unit scale in metres. */
123
+ colliderRadius: 0.6,
124
+ /** Default number of tree variants built when no prebuilt models are supplied. */
125
+ variants: 3,
126
+ });
127
+
128
+ /**
129
+ * Plan a wood or grove of trees over a rectangle `[x - rx, x + rx] × [z - rz, z + rz]` in a local
130
+ * frame anchored at `origin`, skipping points where `clear(px, pz)` is truthy, binning accepted
131
+ * trees into `squareSize`-metre tiles and recording circle trunk colliders. Worker-safe.
132
+ *
133
+ * @param {object} [options]
134
+ * @param {{ x: number, z: number }} [options.origin={ x: 0, z: 0 }] - Local frame world origin in metres.
135
+ * @param {(x: number, z: number) => number} [options.ground] - Local ground elevation sampler `(px, pz) => y` in metres.
136
+ * @param {() => number} [options.random] - Deterministic PRNG in `[0, 1)`.
137
+ * @param {number} [options.x=0] - Grove centre local X in metres.
138
+ * @param {number} [options.z=0] - Grove centre local Z in metres.
139
+ * @param {number} [options.rx=40] - Grove half-width along X in metres.
140
+ * @param {number} [options.rz=40] - Grove half-depth along Z in metres.
141
+ * @param {number} [options.count=40] - Candidate tree positions to sample.
142
+ * @param {(px: number, pz: number) => boolean} [options.clear] - Exclusion predicate in local coordinates.
143
+ * @param {number} [options.squareSize=TREE_GROVE.squareSize] - Tile square edge length in metres.
144
+ * @param {number} [options.sink=TREE_GROVE.sink] - Vertical sink below `ground(px, pz)` in metres.
145
+ * @param {readonly [number, number]} [options.scaleRange=TREE_GROVE.scaleRange] - Scale `[min, span]`.
146
+ * @param {number} [options.leanSpan=TREE_GROVE.leanSpan] - Trunk lean span in radians.
147
+ * @param {readonly [number, number]} [options.shadeRange=TREE_GROVE.shadeRange] - Greyscale shade `[min, span]`.
148
+ * @param {number} [options.colliderRadius=TREE_GROVE.colliderRadius] - Trunk collider radius per unit scale in metres.
149
+ * @returns {{
150
+ * squares: Array<{ key: number, mid: [number, number, number], trees: Array<[number, number, number, number, number, number, number]> }>,
151
+ * solids: Array<{ x: number, z: number, r: number }>,
152
+ * total: number,
153
+ * }}
154
+ */
155
+ export function planTreeGrove({
156
+ origin = { x: 0, z: 0 },
157
+ ground = () => 0,
158
+ random = mulberry32(1),
159
+ x = 0,
160
+ z = 0,
161
+ rx = 40,
162
+ rz = 40,
163
+ count = 40,
164
+ clear = () => false,
165
+ squareSize = TREE_GROVE.squareSize,
166
+ sink = TREE_GROVE.sink,
167
+ scaleRange = TREE_GROVE.scaleRange,
168
+ leanSpan = TREE_GROVE.leanSpan,
169
+ shadeRange = TREE_GROVE.shadeRange,
170
+ colliderRadius = TREE_GROVE.colliderRadius,
171
+ } = {}) {
172
+ const buckets = new Map();
173
+ const solids = [];
174
+ let total = 0;
175
+ for (let i = 0; i < count; i++) {
176
+ const px = x + (random() * 2 - 1) * rx;
177
+ const pz = z + (random() * 2 - 1) * rz;
178
+ if (clear(px, pz)) continue;
179
+ const size = scaleRange[0] + random() * scaleRange[1];
180
+ const key = Math.floor(px / squareSize) * 1e4 + Math.floor(pz / squareSize);
181
+ let trees = buckets.get(key);
182
+ if (!trees) {
183
+ trees = [];
184
+ buckets.set(key, trees);
185
+ }
186
+ const wx = origin.x + px;
187
+ const wz = origin.z + pz;
188
+ trees.push([
189
+ wx,
190
+ ground(px, pz) - sink,
191
+ wz,
192
+ size,
193
+ random() * TAU,
194
+ (random() - 0.5) * leanSpan,
195
+ shadeRange[0] + random() * shadeRange[1],
196
+ ]);
197
+ solids.push({ x: wx, z: wz, r: colliderRadius * size });
198
+ total++;
199
+ }
200
+ const squares = [];
201
+ for (const [key, trees] of buckets) {
202
+ const mid = trees.reduce((m, t) => [m[0] + t[0] / trees.length, m[1] + t[1] / trees.length, m[2] + t[2] / trees.length], [0, 0, 0]);
203
+ squares.push({ key, mid, trees });
204
+ }
205
+ return { squares, solids, total };
206
+ }
package/index.js CHANGED
@@ -70,7 +70,7 @@ export { MESA_CLIFF, buildMesaCliff } from './geometry/strata-mesa.js';
70
70
  export { HILL_RUIN, buildHillRuin } from './geometry/ruins-hill.js';
71
71
  export { MOUND_RUINS, buildMoundRuins, buildMoundSherds, buildMoundWalls, createMoundRuins } from './geometry/ruins-mound.js';
72
72
  export { MOUND_RUINS_LOD, raiseMoundRuins, registerMoundRuins } from './rendering/ruins-mound.js';
73
- export { RUBBLE_HEAP, RUBBLE_SCATTER, buildRubbleHeap, scatterRubble } from './geometry/ruins-rubble.js';
73
+ export { RUBBLE_HEAP, RUBBLE_SCATTER, buildRubbleHeap, createRubbleStone, scatterRubble } from './geometry/ruins-rubble.js';
74
74
  export { RUIN_WALL, buildRuinWall, coursedWall, tumbleBlock } from './geometry/ruins-walls.js';
75
75
  export {
76
76
  ASHLAR_COURSE,
@@ -91,7 +91,16 @@ export {
91
91
  createLightPoolTexture,
92
92
  } from './rendering/ruins-fittings.js';
93
93
  export { DEFAULT_SCORCH_PALETTE, addEmberSkin, buildBreachFan, buildRubbleMound } from './geometry/ruins-breach.js';
94
- export { CRATER_PALETTE, buildCraterBowl, buildFallenBoulder } from './geometry/ruins-crater.js';
94
+ export { CRATER_PALETTE, buildCraterBowl, buildFallenBoulder, craterDip } from './geometry/ruins-crater.js';
95
+ export {
96
+ GROUND_PATCH_DEFAULTS,
97
+ GROUND_PATCH_KINDS,
98
+ buildDrapePebbleGeometry,
99
+ createGroundPatchData,
100
+ drapeGroundPatch,
101
+ scatterPatchBits,
102
+ } from './geometry/ground-drape.js';
103
+ export { GROUND_DRAPE_FRAGMENT, createGroundDrape, createGroundDrapeMaterial } from './rendering/ground-drape.js';
95
104
  export { createShapeBatches } from './geometry/instances.js';
96
105
  export { planStreamBanks } from './geometry/stream-banks.js';
97
106
  export { meshStreamBanks } from './rendering/stream-banks.js';
@@ -118,7 +127,15 @@ export { PAVED_GROUND_LIMITS, createPavedGroundMaterial } from './rendering/pave
118
127
  export { createRoadTraffic, ROAD_TRAFFIC } from './motion/road-traffic.js';
119
128
  export { createFieldSurvey, FIELD_SURVEY, FIELD_USE } from './geometry/field-survey.js';
120
129
  export { FIELD_BITS, NO_PATH_DISTANCE, createFieldCoverCache, packFieldBits, packSparsePlain } from './geometry/field-map.js';
121
- export { DEFAULT_FLOWER_LOOKS, FLOWER_KINDS, TUFT_SHAPE, tuftGeometry } from './geometry/plant-tuft.js';
130
+ export {
131
+ DEFAULT_DRIFT_SCALE,
132
+ DEFAULT_FLOWER_DRIFTS,
133
+ DEFAULT_FLOWER_LOOKS,
134
+ FLOWER_KINDS,
135
+ TUFT_SHAPE,
136
+ createFlowerDrift,
137
+ tuftGeometry,
138
+ } from './geometry/plant-tuft.js';
122
139
  export { TUFT_SHADER, createGrassTuft, createTuftMaterial } from './rendering/plant-tuft.js';
123
140
  export { LAND_TRAILS, LAND_TRAIL_MARKS, boundsOverlap, createLandTrails, rasterizeTrailMarks } from './geometry/land-trails.js';
124
141
  export { createTrailMarks, trailMarksGLSL } from './rendering/land-trail-surface.js';
@@ -127,8 +144,8 @@ export { DEFAULT_CROP_STANDS, FARM_CROPS, createCropPlacer } from './geometry/fa
127
144
  export { createIrrigatedFieldSurface, IRRIGATED_FIELD_KIND, IRRIGATED_FIELD_SURFACE } from './rendering/irrigated-field-surface.js';
128
145
  export { DRYSTONE_WALL, FIELD_STONE, drystoneStone, planDrystoneWall } from './geometry/drystone-wall.js';
129
146
  export { DEFAULT_FENCE_STYLE, addFenceRing, buildFenceRing } from './geometry/timber-fence.js';
130
- export { planScatterInstances } from './geometry/scatter-instances.js';
131
- export { scatterInstances, scatterTrees, scatterTussocks } from './rendering/scatter-instances.js';
147
+ export { TREE_GROVE, planScatterInstances, planTreeGrove } from './geometry/scatter-instances.js';
148
+ export { scatterInstances, scatterTreeGrove, scatterTrees, scatterTussocks } from './rendering/scatter-instances.js';
132
149
  export { FARM_BOUNDARIES, planFieldBoundaries } from './geometry/farm-boundaries.js';
133
150
  export { meshFarmCells, scatterFarmLots } from './rendering/farm-cells.js';
134
151
  export { DEFAULT_LIVESTOCK_CASTS, createLivestockCache } from './rendering/farm-livestock.js';
@@ -200,6 +217,7 @@ export { TERRACE_DEFAULTS, createTerraceFrame, planTerrace, wallAt } from './geo
200
217
  export { createTerraceWall } from './geometry/fort-terrace-wall.js';
201
218
  export { createTerraceGates } from './geometry/fort-terrace-gates.js';
202
219
  export { createRoomKit } from './geometry/room-kit.js';
220
+ export { HALL_OLD_STONE_TONE, HALL_STONE_TONE, HALL_WALL_THICKNESS, createStoneHalls } from './geometry/room-halls.js';
203
221
  export { createRoomMaterials } from './rendering/room-materials.js';
204
222
  export { finishRoom } from './rendering/room-space.js';
205
223
 
@@ -301,6 +319,7 @@ export { createSoundscape } from './runtime/soundscape.js';
301
319
  export { createStrideFoley } from './runtime/foley-strides.js';
302
320
  export { createScriptFoley } from './runtime/foley-script.js';
303
321
  export { createPool } from './runtime/pool.js';
322
+ export { createBreather, createLazySets, createSetFrame } from './runtime/lazy-sets.js';
304
323
  export { describeDevice, readDevice } from './runtime/device.js';
305
324
  export { choosePostPipeline, createDeviceQuality, groundRenderOrder, resolveDevicePresets } from './runtime/device-quality.js';
306
325
  export { LEVELS, createQualityStore } from './runtime/quality-store.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roamwright",
3
- "version": "0.61.25",
3
+ "version": "0.61.26",
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,267 @@
1
+ /**
2
+ * Draped ground-patch material and mesh binder: compiles the procedural surface shader for trodden
3
+ * earth (scuffs, hoof/foot prints, wandering wheel ruts, flat dung), dried cracked clay plates,
4
+ * pooled stains and forest-floor leaf/needle litter, and meshes gathered patches together with
5
+ * instanced loose stones and droppings.
6
+ * @module
7
+ */
8
+
9
+ import * as THREE from 'three';
10
+ import { buildDrapePebbleGeometry, createGroundPatchData, drapeGroundPatch } from '../geometry/ground-drape.js';
11
+ import { TRS as defaultTransform } from '../geometry/primitives.js';
12
+ import { createNoise } from '../math/noise.js';
13
+ import { crustGLSL as CRUST_GLSL } from './crust.js';
14
+ import { defaultGrainTexture } from './paved-ground.js';
15
+ import { terrainReliefGLSL } from './terrain-rock.js';
16
+
17
+ const DEFAULT_GROUND_BUMP = 'normal = terrainReliefNormal(vViewPosition, normal, gTH, 7.0, vec2(8.0, 46.0));';
18
+
19
+ let fallbackFbm = null;
20
+ const defaultFbm = () => (fallbackFbm ??= createNoise().fbm);
21
+
22
+ /**
23
+ * Fragment shader snippet injected into `#include <color_fragment>` by {@link createGroundDrapeMaterial}
24
+ * to evaluate rim breakup, mottling, trodden scuffs/prints/ruts, drying crust cracks, liquid stains
25
+ * and fallen needle litter.
26
+ */
27
+ export const GROUND_DRAPE_FRAGMENT = /* glsl */ `
28
+ float pKind = vLook.x, pOut = vLook.y, pRuts = vLook.z;
29
+ float trod = 1.0 - step(0.5, pKind), dry = step(0.5, pKind) - step(1.5, pKind), soak = step(1.5, pKind) - step(2.5, pKind), leaf = step(2.5, pKind);
30
+ vec2 p = vWP.xz, ax = vec2(cos(vLook.w), sin(vLook.w)), across = vec2(-ax.y, ax.x);
31
+ float px = length(fwidth(p)); // metres a pixel spans here
32
+ float g0 = grainN(p * 0.59 + 0.21), g1 = grainN(p / 9.0), g2 = grainN(p * 0.0187 + 0.37), g3 = grainN(p * 0.0026 + 0.11);
33
+ float fineSeen = 1.0 - smoothstep(0.02, 0.06, px), midSeen = 1.0 - smoothstep(0.06, 0.25, px);
34
+ // the rim: thinned out in clumps that follow the ground's own grain, so it breaks up into the land instead of ending on a line
35
+ float clump = 0.4 * g2 + 0.3 * grainN(p * 0.11 + 0.53) + 0.2 * g1 + 0.1 * mix(0.5, g0, fineSeen);
36
+ diffuseColor.a = smoothstep(clump * 0.75, clump * 0.75 + 0.2 + px * 0.3, diffuseColor.a);
37
+ // colour that varies inside a patch at three scales: paces, a stride, a hand
38
+ diffuseColor.rgb *= (0.86 + 0.28 * g2) * (0.93 + 0.14 * g3) * mix(1.0, 0.84 + 0.32 * g0, fineSeen * (1.0 - 0.6 * soak));
39
+ gTH = (g0 * fineSeen * 0.5 + g1 * 0.3) * (1.0 - soak);
40
+ if (trod > 0.5) {
41
+ float inner = 1.0 - smoothstep(0.45, 0.8, pOut), bank = smoothstep(0.42, 0.62, pOut) * (1.0 - smoothstep(0.78, 0.95, pOut));
42
+ diffuseColor.rgb *= mix(1.06, 0.92, inner) + 0.05 * bank; // packed dark where the feet went, loose and paler where it was kicked up
43
+ // scuffs: streaks dragged across the ground along the way the column went, and some across it
44
+ float sA = grainN(vec2(dot(p, ax) * 0.045, dot(p, across) * 0.8) + 0.13), sB = grainN(vec2(dot(p, across) * 0.06, dot(p, ax) * 0.7) + 0.61);
45
+ float scuff = (smoothstep(0.62, 0.85, sA) + 0.6 * smoothstep(0.66, 0.9, sB)) * midSeen;
46
+ diffuseColor.rgb *= 1.0 - 0.12 * scuff * inner + 0.05 * scuff * (1.0 - inner);
47
+ gTH -= scuff * 0.25;
48
+ // hoof and foot prints, thick where the press was and few at its edges: two scatters on grids that share no lines, each
49
+ // print a crescent hollow of its own size and heading with its front wall pushed up
50
+ float press = inner * smoothstep(0.25, 0.75, grainN(p * 0.061 + 0.29) * 0.7 + 0.3 * g1);
51
+ vec2 pr = printAt(p, 0.47, 0.0, press) + printAt(p * mat2(0.8, 0.6, -0.6, 0.8), 0.61, 31.0, press * 0.7);
52
+ float printSeen = 1.0 - smoothstep(0.025, 0.07, px);
53
+ diffuseColor.rgb *= 1.0 - (0.15 * pr.x - 0.05 * pr.y) * printSeen;
54
+ gTH += (pr.y * 0.45 - pr.x * 0.8) * printSeen;
55
+ // wheel ruts along a track: pairs an axle apart, wandering, each pair fading in and out along its length
56
+ if (pRuts > 0.01) {
57
+ float alongM = dot(p, ax), acrossM = dot(p, across) + (grainN(vec2(alongM * 0.004, 0.31)) - 0.5) * 3.0;
58
+ float lane = floor(acrossM / 5.3), inLane = acrossM - lane * 5.3;
59
+ float shown = smoothstep(0.35, 0.6, grainN(vec2(alongM * 0.007, lane * 0.37 + 0.2))) * pRuts * inner;
60
+ float w = 0.16 + px * 0.6, rut = (1.0 - smoothstep(w * 0.4, w, abs(inLane - 1.6))) + (1.0 - smoothstep(w * 0.4, w, abs(inLane - 3.3)));
61
+ float ridge = (1.0 - smoothstep(0.0, 0.5, abs(inLane - 2.45))) * 0.4;
62
+ rut *= shown * (1.0 - smoothstep(0.12, 0.4, px));
63
+ diffuseColor.rgb *= 1.0 - 0.2 * rut + 0.04 * ridge * shown;
64
+ gTH += (ridge * shown * 0.3 - rut * 1.1) * midSeen;
65
+ }
66
+ // droppings trodden flat into the dust, darker spots a hand across
67
+ vec2 dq = p / 1.9, dc = floor(dq); vec2 dp = cellPoint(dc + 17.0);
68
+ float dung = (1.0 - smoothstep(0.05, 0.09, length(fract(dq) - 0.3 - 0.4 * dp))) * step(dp.x, 0.12) * inner * midSeen;
69
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.2, 0.16, 0.1), dung * 0.6);
70
+ }
71
+ if (dry > 0.5) { // a crust dried into plates, their edges curled up and paler
72
+ vec3 cr = crustCracks(p * 0.8, (vec2(g1, grainN(p / 9.0 + 0.5)) - 0.5) * 1.6 + (g0 - 0.5) * 0.4);
73
+ float fine = grainN(p * 3.1 + 0.7) * fineSeen;
74
+ diffuseColor.rgb *= 1.0 - 0.3 * cr.x - 0.14 * cr.z + 0.08 * cr.y - 0.05 * fine;
75
+ gTH += cr.y * 0.6 - cr.x * 1.2 - cr.z * 0.5;
76
+ }
77
+ if (soak > 0.5) { // soaked in: darkest where it pooled, in blots, flecked past its edge
78
+ diffuseColor.rgb *= mix(1.12, 0.82, smoothstep(0.3, 0.9, diffuseColor.a * (0.6 + 0.6 * g1)));
79
+ pRough = -0.25 * diffuseColor.a * (1.0 - pOut);
80
+ }
81
+ if (leaf > 0.5) { // fallen needles and twigs, every way, rust and grey on the dark mould
82
+ vec2 q = p / 0.16, ci = floor(q), cf = fract(q); vec2 pick = cellPoint(ci + 41.0);
83
+ vec2 dir = vec2(cos(pick.x * 6.2832), sin(pick.x * 6.2832)), o = cf - 0.5;
84
+ float t = clamp(dot(o, dir), -0.42, 0.42), needle = 1.0 - smoothstep(0.03, 0.07, length(o - dir * t));
85
+ needle *= step(0.25, pick.y) * (1.0 - smoothstep(0.012, 0.03, px));
86
+ diffuseColor.rgb = mix(diffuseColor.rgb, mix(vec3(0.42, 0.27, 0.15), vec3(0.36, 0.33, 0.27), pick.y), needle * 0.7);
87
+ gTH += needle * 0.4;
88
+ }`;
89
+
90
+ /**
91
+ * Create the transparent, polygon-offset `MeshStandardMaterial` used to render draped ground
92
+ * patches. Accepts optional world cloud-shadow, terrain-relief, weather and sky-occlusion hooks.
93
+ *
94
+ * @param {object} [options]
95
+ * @param {THREE.Texture | (() => THREE.Texture)} [options.grainTexture] - Ground detail grain texture or lazy getter.
96
+ * @param {{ value: number }} [options.uDamp] - Shared rain dampness uniform (`0..1`).
97
+ * @param {Record<string, { value: unknown }>} [options.cloudUniforms] - Extra cloud-shadow uniforms merged on compile.
98
+ * @param {string} [options.cloudShadePars=''] - GLSL declarations for `cloudShade(vec2)` when used by `groundWeather`.
99
+ * @param {string} [options.groundBumpPars=terrainReliefGLSL] - GLSL declarations for relief normal perturbation.
100
+ * @param {string} [options.groundBump] - GLSL snippet injected into `#include <normal_fragment_maps>`.
101
+ * @param {string} [options.groundWeather=''] - GLSL snippet injected into `#include <emissivemap_fragment>`.
102
+ * @param {((shader: object) => void) | null} [options.patchShader=null] - Optional post-patch hook (e.g. sky occlusion).
103
+ * @param {string} [options.cacheKey='ground-patch'] - `customProgramCacheKey` value.
104
+ * @param {number} [options.roughness=0.95] - Base surface roughness.
105
+ * @returns {THREE.MeshStandardMaterial}
106
+ */
107
+ export function createGroundDrapeMaterial(options = {}) {
108
+ const {
109
+ grainTexture = defaultGrainTexture,
110
+ uDamp = { value: 0 },
111
+ cloudUniforms = {},
112
+ cloudShadePars = '',
113
+ groundBumpPars = terrainReliefGLSL,
114
+ groundBump = DEFAULT_GROUND_BUMP,
115
+ groundWeather = '',
116
+ patchShader = null,
117
+ cacheKey = 'ground-patch',
118
+ roughness = 0.95,
119
+ } = options;
120
+ const mat = new THREE.MeshStandardMaterial({
121
+ vertexColors: true,
122
+ transparent: true,
123
+ depthWrite: false,
124
+ roughness,
125
+ polygonOffset: true,
126
+ polygonOffsetFactor: -2,
127
+ polygonOffsetUnits: -2,
128
+ });
129
+ mat.onBeforeCompile = sh => {
130
+ const grain = typeof grainTexture === 'function' ? grainTexture() : grainTexture;
131
+ Object.assign(sh.uniforms, { uGrain: { value: grain }, uDamp, ...cloudUniforms });
132
+ sh.vertexShader = sh.vertexShader
133
+ .replace('#include <common>', '#include <common>\nattribute vec4 aLook; varying vec4 vLook; varying vec3 vWP;')
134
+ .replace('#include <begin_vertex>', '#include <begin_vertex>\nvLook = aLook; vWP = (modelMatrix * vec4(position, 1.0)).xyz;');
135
+ sh.fragmentShader = sh.fragmentShader
136
+ .replace(
137
+ '#include <common>',
138
+ `/* glsl */
139
+ #include <common>
140
+ ${cloudShadePars}
141
+ ${groundBumpPars}
142
+ uniform sampler2D uGrain; uniform float uDamp; varying vec4 vLook; varying vec3 vWP;
143
+ float gTH = 0.0, pRough = 0.0;
144
+ ${CRUST_GLSL}
145
+ // A print at most one to a cell, size metres across, where the cell's draw is under press: (how deep its hollow, how high its front wall).
146
+ vec2 printAt(vec2 p, float size, float salt, float press) {
147
+ vec2 q = p / size, ci = floor(q), cf = fract(q), pick = cellPoint(ci + salt), more = cellPoint(ci + salt + 113.0);
148
+ if (more.x > press) return vec2(0.0);
149
+ float turn = pick.x * 6.2832, big = 0.75 + 0.5 * more.y;
150
+ vec2 d = (cf - 0.3 - 0.4 * pick) / big; d = vec2(d.x * cos(turn) - d.y * sin(turn), d.x * sin(turn) + d.y * cos(turn)); d.y *= 0.85 + 0.3 * pick.y;
151
+ float r = length(d), front = smoothstep(-0.04, 0.1, d.y);
152
+ return vec2((1.0 - smoothstep(0.08, 0.14, r)) * (0.55 + 0.45 * front), smoothstep(0.1, 0.15, r) * (1.0 - smoothstep(0.15, 0.22, r)) * front);
153
+ }
154
+ const float GRAIN_MID = 0.73; // the grain map reads 0.62 to 0.84 between its tenth and ninetieth parts: grainN spreads that over 0 to 1
155
+ #define grainN(q) clamp((texture2D(uGrain, q).r - GRAIN_MID) * 4.0 + 0.5, 0.0, 1.0)`,
156
+ )
157
+ .replace('#include <color_fragment>', '#include <color_fragment>\n' + GROUND_DRAPE_FRAGMENT)
158
+ .replace(
159
+ '#include <roughnessmap_fragment>',
160
+ '#include <roughnessmap_fragment>\nroughnessFactor = clamp(roughnessFactor + pRough, 0.3, 1.0);',
161
+ )
162
+ .replace('#include <normal_fragment_maps>', '#include <normal_fragment_maps>\n' + groundBump)
163
+ .replace('#include <emissivemap_fragment>', '#include <emissivemap_fragment>\n' + groundWeather);
164
+ patchShader?.(sh);
165
+ };
166
+ mat.customProgramCacheKey = () => cacheKey;
167
+ return mat;
168
+ }
169
+
170
+ /**
171
+ * Create a world-bound ground-drape toolkit that lazily builds its shared patch material and pebble
172
+ * geometry on first mesh upload, gathers multiple draped patches into one mesh, and renders loose
173
+ * stones and droppings in a companion `InstancedMesh` ordered right after the patches.
174
+ *
175
+ * @param {object} [options]
176
+ * @param {(x: number, z: number, octaves?: number, salt?: number) => number} [options.fbm] - Fractal noise in `[0, 1)`.
177
+ * @param {THREE.Texture | (() => THREE.Texture)} [options.grainTexture] - Ground detail grain texture or lazy getter.
178
+ * @param {{ value: number }} [options.uDamp] - Shared rain dampness uniform.
179
+ * @param {Record<string, { value: unknown }>} [options.cloudUniforms] - Cloud-shadow uniforms.
180
+ * @param {string} [options.cloudShadePars] - Cloud-shadow GLSL declarations.
181
+ * @param {string} [options.groundBumpPars] - Terrain-relief GLSL declarations.
182
+ * @param {string} [options.groundBump] - Terrain-relief normal snippet.
183
+ * @param {string} [options.groundWeather] - Cloud/wetness fragment snippet.
184
+ * @param {((shader: object) => void) | null} [options.patchShader] - Optional shader post-patch hook.
185
+ * @param {(() => THREE.Material) | null} [options.bitsMaterial] - Factory for the transparent stone/dropping material ordered over patches.
186
+ * @param {Function} [options.transform] - Transform matrix helper (`TRS`).
187
+ * @param {string} [options.cacheKey='ground-patch'] - Shader program cache key.
188
+ * @param {Partial<typeof import('../geometry/ground-drape.js').GROUND_PATCH_DEFAULTS>} [options.shape] - Overrides to `GROUND_PATCH_DEFAULTS`.
189
+ * @returns {{
190
+ * groundPatches: () => { pos: number[], colours: number[], looks: number[], index: number[], bits: number[], mesh: (parent: THREE.Object3D) => void },
191
+ * drape: (patches: object, at: object, rng: () => number, x: number, z: number, rx: number, rz: number, col: readonly [number, number, number], lift?: number, rag?: number, kind?: 'trodden' | 'cracked' | 'stain' | 'litter', breathe?: (() => Promise<void>) | null) => Promise<void>,
192
+ * patchSurface: () => THREE.MeshStandardMaterial,
193
+ * pebbleGeometry: () => THREE.BufferGeometry,
194
+ * }}
195
+ */
196
+ export function createGroundDrape(options = {}) {
197
+ const { fbm = defaultFbm(), bitsMaterial = null, transform = defaultTransform, shape } = options;
198
+ let patchMat = null;
199
+ let pebble = null;
200
+
201
+ function patchSurface() {
202
+ return (patchMat ??= createGroundDrapeMaterial(options));
203
+ }
204
+
205
+ function pebbleGeometry() {
206
+ return (pebble ??= buildDrapePebbleGeometry(fbm));
207
+ }
208
+
209
+ function layBits(bits, parent) {
210
+ const n = bits.length / 8;
211
+ const mat = bitsMaterial ? bitsMaterial() : new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.94, transparent: true });
212
+ const stones = new THREE.InstancedMesh(pebbleGeometry(), mat, n);
213
+ const hue = new THREE.Color();
214
+ for (let i = 0; i < n; i++) {
215
+ const o = i * 8;
216
+ stones.setMatrixAt(
217
+ i,
218
+ transform(
219
+ bits[o],
220
+ bits[o + 1],
221
+ bits[o + 2],
222
+ bits[o + 3],
223
+ bits[o + 4],
224
+ bits[o + 3] * 0.85,
225
+ bits[o + 5],
226
+ bits[o + 6],
227
+ bits[o + 6] * 0.5,
228
+ ),
229
+ );
230
+ stones.setColorAt(i, hue.setHex(bits[o + 7]));
231
+ }
232
+ stones.castShadow = stones.receiveShadow = true;
233
+ stones.matrixAutoUpdate = false;
234
+ stones.renderOrder = 3;
235
+ stones.computeBoundingSphere();
236
+ parent.add(stones);
237
+ }
238
+
239
+ function groundPatches() {
240
+ const data = createGroundPatchData();
241
+ return {
242
+ ...data,
243
+ mesh(parent) {
244
+ if (!data.index.length) return;
245
+ const geo = new THREE.BufferGeometry();
246
+ geo.setAttribute('position', new THREE.Float32BufferAttribute(data.pos, 3));
247
+ geo.setAttribute('color', new THREE.Float32BufferAttribute(data.colours, 4));
248
+ geo.setAttribute('aLook', new THREE.Float32BufferAttribute(data.looks, 4));
249
+ geo.setIndex(data.index);
250
+ geo.computeVertexNormals();
251
+ geo.computeBoundingSphere();
252
+ const mesh = new THREE.Mesh(geo, patchSurface());
253
+ mesh.receiveShadow = true;
254
+ mesh.renderOrder = 2;
255
+ mesh.matrixAutoUpdate = false;
256
+ parent.add(mesh);
257
+ if (data.bits.length) layBits(data.bits, parent);
258
+ },
259
+ };
260
+ }
261
+
262
+ function drape(patches, at, rng, x, z, rx, rz, col, lift = 0.04, rag = 0.12, kind = 'trodden', breathe = null) {
263
+ return drapeGroundPatch(patches, at, rng, x, z, rx, rz, col, { lift, rag, kind, breathe, fbm, shape });
264
+ }
265
+
266
+ return { groundPatches, drape, patchSurface, pebbleGeometry };
267
+ }
@@ -128,7 +128,13 @@ const WET_SHEEN = `/* glsl */
128
128
  }`;
129
129
 
130
130
  let fallbackGrain = null;
131
- function defaultGrainTexture() {
131
+ /**
132
+ * Return the shared default repeating ground-grain `DataTexture` (warm greyscale in sRGB) used by
133
+ * procedural ground materials when a caller does not supply its own grain texture.
134
+ *
135
+ * @returns {THREE.DataTexture}
136
+ */
137
+ export function defaultGrainTexture() {
132
138
  if (fallbackGrain) return fallbackGrain;
133
139
  const size = 256;
134
140
  const { groundGrain } = createSurfaceTextures({ noise: createNoise(41), hash2: createHash(41) });
@@ -8,10 +8,11 @@ import * as THREE from 'three';
8
8
  import { createNoise } from '../math/noise.js';
9
9
  import { createHash, mulberry32 } from '../math/random.js';
10
10
  import { partsGeometry } from '../geometry/foliage.js';
11
+ import { TRS as defaultTransform } from '../geometry/primitives.js';
11
12
  import { createPlantTints } from '../geometry/plant-tints.js';
12
13
  import { createTrees } from '../geometry/plant-trees.js';
13
14
  import { PLAIN_GRASS, tussockGeometry } from '../geometry/plant-tussock.js';
14
- import { planScatterInstances } from '../geometry/scatter-instances.js';
15
+ import { TREE_GROVE, planScatterInstances, planTreeGrove } from '../geometry/scatter-instances.js';
15
16
 
16
17
  const DEFAULT_ROUGHNESS = 0.88;
17
18
  const DEFAULT_TREE_SPECIES = Object.freeze(['broadleaf', 'conifer', 'cedar']);
@@ -256,3 +257,152 @@ export function scatterTussocks({
256
257
  },
257
258
  };
258
259
  }
260
+
261
+ /**
262
+ * Build a tiled two-LOD grove of trees (such as upland cedars) using {@link planTreeGrove}. Each
263
+ * `squareSize`-metre grid tile selects one `{ near, far }` model variant so neighbouring stands
264
+ * differ, wraps its instanced near and far meshes in a `THREE.LOD` positioned at the tile centroid,
265
+ * and appends trunk circle colliders to `solid` when provided.
266
+ *
267
+ * @param {object} [options]
268
+ * @param {THREE.Object3D | null} [options.parent=null] - Scene or group receiving the tiled `THREE.LOD` stands.
269
+ * @param {Array<{ near: THREE.BufferGeometry, far: THREE.BufferGeometry }> | null} [options.models=null] - Prebuilt variant geometries; defaults to `variants` cedars from `createTrees`.
270
+ * @param {THREE.Material | null} [options.material=null] - Shared foliage material (defaults to double-sided vertex-coloured `MeshStandardMaterial`).
271
+ * @param {number} [options.roughness=0.88] - Roughness for the default foliage material.
272
+ * @param {number} [options.seed=0] - World seed for default cedar variants when `models` is omitted.
273
+ * @param {{ fbm: Function, vnoise: Function }} [options.noise] - Seeded noise for default cedar variants.
274
+ * @param {Function} [options.hash] - Seeded integer hash for default cedar variants.
275
+ * @param {number} [options.variants=TREE_GROVE.variants] - Number of default cedar variants to build when `models` is omitted.
276
+ * @param {{ x: number, z: number }} [options.origin={ x: 0, z: 0 }] - Local frame world origin in metres.
277
+ * @param {(x: number, z: number) => number} [options.ground] - Local ground elevation sampler `(px, pz) => y` in metres.
278
+ * @param {() => number} [options.random] - Deterministic PRNG in `[0, 1)`.
279
+ * @param {number} [options.x=0] - Grove centre local X in metres.
280
+ * @param {number} [options.z=0] - Grove centre local Z in metres.
281
+ * @param {number} [options.rx=40] - Grove half-width along X in metres.
282
+ * @param {number} [options.rz=40] - Grove half-depth along Z in metres.
283
+ * @param {number} [options.count=40] - Candidate tree positions to sample.
284
+ * @param {(px: number, pz: number) => boolean} [options.clear] - Exclusion predicate in local coordinates.
285
+ * @param {Array<{ x: number, z: number, r: number }> | null} [options.solid=null] - Optional array receiving trunk circle colliders.
286
+ * @param {number} [options.squareSize=TREE_GROVE.squareSize] - Tile square edge length in metres.
287
+ * @param {number} [options.nearDistance=TREE_GROVE.nearDistance] - Distance in metres where far geometry replaces near geometry.
288
+ * @param {number} [options.sink=TREE_GROVE.sink] - Vertical sink below `ground(px, pz)` in metres.
289
+ * @param {readonly [number, number]} [options.scaleRange=TREE_GROVE.scaleRange] - Uniform scale `[min, span]`.
290
+ * @param {number} [options.leanSpan=TREE_GROVE.leanSpan] - Trunk lean span in radians.
291
+ * @param {readonly [number, number]} [options.shadeRange=TREE_GROVE.shadeRange] - Greyscale shade `[min, span]`.
292
+ * @param {number} [options.colliderRadius=TREE_GROVE.colliderRadius] - Trunk collider radius per unit scale in metres.
293
+ * @param {boolean} [options.castShadow=true] - Whether instanced stands cast shadows.
294
+ * @param {boolean} [options.receiveShadow=true] - Whether instanced stands receive shadows.
295
+ * @param {Function} [options.transform] - Transform matrix helper (`TRS`).
296
+ * @returns {{ lods: THREE.LOD[], material: THREE.Material, solids: Array<{ x: number, z: number, r: number }>, total: number, dispose: () => void }}
297
+ */
298
+ export function scatterTreeGrove({
299
+ parent = null,
300
+ models = null,
301
+ material = null,
302
+ roughness = DEFAULT_ROUGHNESS,
303
+ seed = 0,
304
+ noise = null,
305
+ hash = null,
306
+ variants = TREE_GROVE.variants,
307
+ origin = { x: 0, z: 0 },
308
+ ground = () => 0,
309
+ random = mulberry32(seed || 1),
310
+ x = 0,
311
+ z = 0,
312
+ rx = 40,
313
+ rz = 40,
314
+ count = 40,
315
+ clear = () => false,
316
+ solid = null,
317
+ squareSize = TREE_GROVE.squareSize,
318
+ nearDistance = TREE_GROVE.nearDistance,
319
+ sink = TREE_GROVE.sink,
320
+ scaleRange = TREE_GROVE.scaleRange,
321
+ leanSpan = TREE_GROVE.leanSpan,
322
+ shadeRange = TREE_GROVE.shadeRange,
323
+ colliderRadius = TREE_GROVE.colliderRadius,
324
+ castShadow = true,
325
+ receiveShadow = true,
326
+ transform = defaultTransform,
327
+ } = {}) {
328
+ const ownsMaterial = !material;
329
+ const leaves = material ?? createDefaultFoliageMaterial(roughness);
330
+ const ownsModels = !models;
331
+ const resolvedModels =
332
+ models ??
333
+ (() => {
334
+ const n = noise ?? createNoise(seed);
335
+ const h = hash ?? createHash(seed);
336
+ const tints = createPlantTints({ fbm: n.fbm, vnoise: n.vnoise, hash: h });
337
+ const treeKit = createTrees({ hash: h, ...tints, seed });
338
+ return Array.from({ length: variants }, (_, i) => {
339
+ const shape = treeKit.cedar(i);
340
+ return { near: partsGeometry(shape.near), far: partsGeometry(shape.far) };
341
+ });
342
+ })();
343
+
344
+ const plan = planTreeGrove({
345
+ origin,
346
+ ground,
347
+ random,
348
+ x,
349
+ z,
350
+ rx,
351
+ rz,
352
+ count,
353
+ clear,
354
+ squareSize,
355
+ sink,
356
+ scaleRange,
357
+ leanSpan,
358
+ shadeRange,
359
+ colliderRadius,
360
+ });
361
+ if (solid) for (let i = 0; i < plan.solids.length; i++) solid.push(plan.solids[i]);
362
+
363
+ const tone = new THREE.Color();
364
+ const lods = [];
365
+ for (const { key, mid, trees } of plan.squares) {
366
+ const model = resolvedModels[Math.abs(key) % resolvedModels.length];
367
+ const wood = new THREE.LOD();
368
+ const near = new THREE.InstancedMesh(model.near, leaves, trees.length);
369
+ const far = new THREE.InstancedMesh(model.far, leaves, trees.length);
370
+ for (let i = 0; i < trees.length; i++) {
371
+ const [tx, ty, tz, size, turn, lean, shade] = trees[i];
372
+ const m = transform(tx - mid[0], ty - mid[1], tz - mid[2], size, size, size, turn, lean, lean * 0.6);
373
+ tone.setScalar(shade);
374
+ near.setMatrixAt(i, m);
375
+ near.setColorAt(i, tone);
376
+ far.setMatrixAt(i, m);
377
+ far.setColorAt(i, tone);
378
+ }
379
+ near.castShadow = castShadow;
380
+ near.receiveShadow = receiveShadow;
381
+ far.castShadow = castShadow;
382
+ far.receiveShadow = receiveShadow;
383
+ near.computeBoundingSphere();
384
+ far.computeBoundingSphere();
385
+ wood.position.set(mid[0], mid[1], mid[2]);
386
+ wood.addLevel(near, 0);
387
+ wood.addLevel(far, nearDistance);
388
+ if (parent) parent.add(wood);
389
+ lods.push(wood);
390
+ }
391
+
392
+ return {
393
+ lods,
394
+ material: leaves,
395
+ solids: plan.solids,
396
+ total: plan.total,
397
+ dispose() {
398
+ for (const wood of lods) wood.removeFromParent();
399
+ if (ownsMaterial) leaves.dispose();
400
+ if (ownsModels) {
401
+ for (const model of resolvedModels) {
402
+ model.near.dispose();
403
+ model.far.dispose();
404
+ }
405
+ }
406
+ },
407
+ };
408
+ }