roamwright 0.55.1 → 0.56.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.
@@ -11,7 +11,7 @@ import { between, direction, lifted, moved } from './plant-shrub.js';
11
11
  * @param {Function} o.barkTint - The kit's bark tint (`createPlantTints`).
12
12
  * @param {Function} o.crownBlob - The kit's crown lump (`createPlantTints`).
13
13
  * @param {Function} o.crownTint - The kit's foliage tint (`createPlantTints`).
14
- * @returns {{broadleaf: Function, broadleafArrays: Function}} `broadleaf(far = false)`: the tree's parts for
14
+ * @returns {{broadleaf: Function, broadleafArrays: Function}} `broadleaf()`: `{ near, far }` parts for
15
15
  * `partsGeometry`, its foot at the origin; `broadleafArrays()`: the near tree as transferable arrays (`partsArrays`).
16
16
  */
17
17
  export function createBroadleaf({ barkTint, crownBlob, crownTint }) {
@@ -214,10 +214,10 @@ export function createBroadleaf({ barkTint, crownBlob, crownTint }) {
214
214
 
215
215
  // A broadleaf: its near version, or with `far` its far one, which keeps the trunk and the boughs and gathers each bough's
216
216
  // clumps into one, a fifth of the near tree's triangles.
217
- function broadleaf(far = false) {
217
+ function buildBroadleaf(far, plan = broadleafPlan()) {
218
218
  const parts = shapeParts(),
219
219
  bark = barkTint(BROAD_BARK),
220
- { limbs, clumps, sprays } = broadleafPlan(),
220
+ { limbs, clumps, sprays } = plan,
221
221
  sides = far ? [5, 3, 0, 0] : [8, 6, 4, 3];
222
222
  for (const [from, to, foot, tip, rank] of limbs) if (sides[rank]) addLimb(parts, from, to, foot, tip, sides[rank], bark);
223
223
  const putClump = (at, size, flat, turn, hex, seed, detail) => {
@@ -261,8 +261,14 @@ export function createBroadleaf({ barkTint, crownBlob, crownTint }) {
261
261
  return parts;
262
262
  }
263
263
 
264
+ // Returns both detail levels from one shared scaffold plan, matching every other tree builder's `{ near, far }` shape.
265
+ function broadleaf() {
266
+ const plan = broadleafPlan();
267
+ return { near: buildBroadleaf(false, plan), far: buildBroadleaf(true, plan) };
268
+ }
269
+
264
270
  // The broadleaf as the arrays of its geometry (foliage.js's partsArrays), for the pool's workers to hand over: the model is
265
271
  // too large to build in one frame on a page that draws.
266
- const broadleafArrays = () => partsArrays(broadleaf());
272
+ const broadleafArrays = () => partsArrays(buildBroadleaf(false));
267
273
  return { broadleaf, broadleafArrays };
268
274
  }
@@ -1,25 +1,27 @@
1
- // Trees of the plant kit, near and, for most, far: the conifer, the burnt tree, the thorn tree, the park acacia and the cedar.
2
- // Each is a set of parts for `partsGeometry`, its foot at the origin. Worker-safe.
1
+ // Trees of the plant kit, each returning `{ near, far }` parts for `partsGeometry`, with its foot at the origin:
2
+ // the broadleaf, conifer, burnt tree, thorn tree, park acacia and cedar. Worker-safe.
3
3
  import * as THREE from 'three';
4
4
  import { lerp, TAU } from '../math/scalar.js';
5
5
  import { mulberry32 } from '../math/random.js';
6
6
  import { C, TRS } from './primitives.js';
7
7
  import { addShape, shapeParts } from './foliage.js';
8
+ import { createBroadleaf } from './plant-broadleaf.js';
8
9
 
9
10
  /**
10
11
  * The kit's trees bound to a world's hash, seed and the kit's tints.
12
+ * Every species builder returns `{ near, far }` parts suitable for `partsGeometry`.
13
+ *
11
14
  * @param {object} o
12
15
  * @param {Function} o.hash - A seeded integer hash (`createHash`), which mottles needles and char.
13
16
  * @param {Function} o.barkTint - The kit's bark tint (`createPlantTints`).
14
17
  * @param {Function} o.crownBlob - The kit's crown lump (`createPlantTints`).
15
18
  * @param {Function} o.crownTint - The kit's foliage tint (`createPlantTints`).
16
19
  * @param {number} [o.seed=0] - The world's seed: the burnt, thorn, acacia and cedar trees grow from streams counted from it.
17
- * @returns {{conifer: Function, farConifer: Function, burntTree: Function, farBurntTree: Function, thornTree: Function,
18
- * acacia: Function, cedar: Function}} `conifer()`, `farConifer()`, `burntTree()` and `farBurntTree()`: one set of
19
- * parts each (about 10, 9.5 and 5 m tall); `thornTree()`, `acacia()` and `cedar(variant = 0)`: `{ near, far }`, the cedar
20
- * about fourteen metres tall and each `variant` a tree of its own.
20
+ * @returns {{broadleaf: Function, conifer: Function, burntTree: Function, thornTree: Function, acacia: Function, cedar: Function}}
21
+ * Every tree builder returns `{ near, far }`; `cedar(variant = 0)` builds an upland cedar about fourteen metres tall where each `variant` is a tree of its own.
21
22
  */
22
23
  export function createTrees({ hash: hash2, barkTint, crownBlob, crownTint, seed = 0 }) {
24
+ const { broadleaf } = createBroadleaf({ barkTint, crownBlob, crownTint });
23
25
  const LIMB_NEAR = new THREE.CylinderGeometry(0.62, 1, 1, 7, 1, true).translate(0, 0.5, 0), // a limb of radius 1 at its foot, a metre long
24
26
  LIMB_FAR = new THREE.CylinderGeometry(0.62, 1, 1, 4, 1, true).translate(0, 0.5, 0),
25
27
  FAR_PLATE = new THREE.Vector3(1.3, 1, 1.3), // a far cedar's plates, one to a limb, stand for the near tree's three
@@ -36,7 +38,7 @@ export function createTrees({ hash: hash2, barkTint, crownBlob, crownTint, seed
36
38
  }
37
39
 
38
40
  // A conifer: a tapering trunk to the top, and whorl after whorl of separate drooping boughs, long at the base and short at the leader.
39
- function conifer() {
41
+ function nearConifer() {
40
42
  const near = shapeParts();
41
43
  const boughGeo = (() => {
42
44
  // one bough along +z: a tapered spray, thicker above than below, its tip hanging
@@ -142,7 +144,7 @@ export function createTrees({ hash: hash2, barkTint, crownBlob, crownTint, seed
142
144
  }
143
145
 
144
146
  // A burnt tree: a fire-killed trunk, bent and blackened, its top snapped off; charred limbs forking into bare twigs, some burnt back to stubs.
145
- function burntTree() {
147
+ function nearBurntTree() {
146
148
  const near = shapeParts();
147
149
  const R = mulberry32(seed + 611),
148
150
  up = new THREE.Vector3(0, 1, 0),
@@ -449,5 +451,9 @@ export function createTrees({ hash: hash2, barkTint, crownBlob, crownTint, seed
449
451
  }
450
452
  return parts;
451
453
  }
452
- return { conifer, farConifer, burntTree, farBurntTree, thornTree, acacia, cedar };
454
+
455
+ const conifer = () => ({ near: nearConifer(), far: farConifer() });
456
+ const burntTree = () => ({ near: nearBurntTree(), far: farBurntTree() });
457
+
458
+ return { broadleaf, conifer, burntTree, thornTree, acacia, cedar };
453
459
  }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Helper creating a mesh with shadow defaults, optional static-caster layer marking, and
3
+ * configurable `matrixAutoUpdate` (enabled by default so subsequent `position`/`rotation`/`scale`
4
+ * edits take effect without manual `updateMatrix()` calls).
5
+ * @module
6
+ */
7
+
8
+ import * as THREE from 'three';
9
+ import { markStill } from '../rendering/still-casters.js';
10
+
11
+ /**
12
+ * Builds a `THREE.Mesh` configured for static or repositionable world geometry, enabling shadow
13
+ * reception, optional shadow casting and static-caster registration (`markStill`).
14
+ *
15
+ * `matrixAutoUpdate` defaults to `true` so callers can position or move the returned mesh without
16
+ * remembering a manual `updateMatrix()` call; pass `{ matrixAutoUpdate: false }` to freeze the
17
+ * local matrix immediately at the origin.
18
+ *
19
+ * @param {THREE.BufferGeometry} geometry Geometry to render.
20
+ * @param {THREE.Material} material Material applied to the mesh.
21
+ * @param {boolean} [shadow=true] Whether the mesh casts shadows (and joins the static-caster layer).
22
+ * @param {object} [options]
23
+ * @param {boolean} [options.matrixAutoUpdate=true] Keep Three.js automatic local-matrix updates enabled.
24
+ * @param {boolean} [options.receiveShadow=true] Whether the mesh receives shadows.
25
+ * @returns {THREE.Mesh}
26
+ */
27
+ export function stillMesh(geometry, material, shadow = true, { matrixAutoUpdate = true, receiveShadow = true } = {}) {
28
+ const mesh = new THREE.Mesh(geometry, material);
29
+ mesh.castShadow = shadow;
30
+ mesh.receiveShadow = receiveShadow;
31
+ mesh.matrixAutoUpdate = matrixAutoUpdate;
32
+ if (!matrixAutoUpdate) mesh.updateMatrix();
33
+ if (shadow) markStill(mesh);
34
+ return mesh;
35
+ }
package/index.js CHANGED
@@ -8,6 +8,8 @@
8
8
 
9
9
  // ── Context, math & core geometry ────────────────────────────────────────
10
10
  export { RENDER_LAYERS, createRenderContext } from './rendering/context.js';
11
+ export { createDaylightSky, createSkyPanorama, createSkyTexture } from './rendering/daylight-sky.js';
12
+ export { bindKeyboardOrbit, createOrbitCamera } from './rendering/orbit-camera.js';
11
13
  export { createDayCycle, luminanceOf } from './rendering/day-cycle.js';
12
14
  export { DEFAULT_DAY_CYCLE, DEFAULT_SKY_PALETTE } from './rendering/day-cycle-defaults.js';
13
15
  export { createSurfaceMaterialFactory } from './rendering/surface-material.js';
@@ -17,6 +19,7 @@ export { createStainMaterial } from './rendering/stain-material.js';
17
19
  export { createNoise } from './math/noise.js';
18
20
  export { mulberry32 } from './math/random.js';
19
21
  export { GB as GeometryBuilder, geometryOf } from './geometry/builder.js';
22
+ export { stillMesh } from './geometry/still-mesh.js';
20
23
  export { createUnitShapes } from './geometry/primitives.js';
21
24
 
22
25
  // ── Spaces & player motion ───────────────────────────────────────────────
@@ -33,10 +36,11 @@ export { createMoundFaces } from './geometry/land-mound-faces.js';
33
36
  export { createTownGround } from './geometry/land-town-ground.js';
34
37
  export { createDryBasin } from './geometry/land-dry-basin.js';
35
38
  export { landEdgeGrid } from './geometry/land-edge.js';
39
+ export { createSimpleWater } from './rendering/water-simple.js';
36
40
 
37
41
  // ── Settlements, houses, fortifications & interiors ──────────────────────
38
42
  export { createHouseKit } from './geometry/house-kit.js';
39
- export { createHouseKitMeshes } from './rendering/house-kit-meshes.js';
43
+ export { createHouseKitMaterials, createHouseKitMeshes } from './rendering/house-kit-meshes.js';
40
44
  export { createPooledKit } from './geometry/house-kit-pool.js';
41
45
  export { createQuarterStream } from './rendering/settlement-quarter.js';
42
46
  export { createTowns } from './rendering/settlement-town.js';
@@ -136,6 +140,7 @@ export { createCrowdVisibility } from './rendering/crowd-visibility.js';
136
140
  export { createHerdRenderer, createHerdSkins } from './rendering/crowd-herd.js';
137
141
  export { createCrowdBatches } from './rendering/crowd-batches.js';
138
142
  export { createCrowdUpdater, registerCrowd } from './rendering/crowd-update.js';
143
+ export { createCrowdSystem } from './rendering/crowd-system.js';
139
144
 
140
145
  // ── Effects, audio & runtime ─────────────────────────────────────────────
141
146
  export { createFireLightWatch } from './rendering/fire-light-watch.js';
@@ -189,6 +189,7 @@ function createFigureMount({ ground = FLAT, hoofbeat = SILENT } = {}) {
189
189
  horse.yaw = a.yaw;
190
190
  mesh.position.set(horse.x, ground(horse.x, horse.z), horse.z);
191
191
  mesh.rotation.set(0, horse.yaw, 0);
192
+ mesh.updateMatrixWorld(true);
192
193
  a.beside = horse;
193
194
  }
194
195
  const ends = a.steed.H.rig.bones[BONE.crest];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roamwright",
3
- "version": "0.55.1",
3
+ "version": "0.56.0",
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,239 @@
1
+ /**
2
+ * High-level crowd system facade wiring figure assembly, instanced crowd batches, pose texture,
3
+ * herd skins and rendering, street beasts, frustum visibility, alarms, and per-frame updating
4
+ * from one call.
5
+ * @module
6
+ */
7
+
8
+ import * as THREE from 'three';
9
+ import { geometryOf } from '../geometry/builder.js';
10
+ import { farCrowdFigure } from '../geometry/crowd-far.js';
11
+ import { createCrowdLookBuilder } from '../geometry/crowd-look.js';
12
+ import { createFigureBuilder } from '../geometry/figure-body.js';
13
+ import { createCrowdAlarms } from '../motion/crowd-alarms.js';
14
+ import { createStreetBeasts } from '../motion/crowd-beasts.js';
15
+ import { createCrowdPoser } from '../motion/crowd-pose.js';
16
+ import { createCrowdBatches } from './crowd-batches.js';
17
+ import { createHerdRenderer, createHerdSkins } from './crowd-herd.js';
18
+ import { createCrowdUpdater, registerCrowd } from './crowd-update.js';
19
+ import { createCrowdVisibility } from './crowd-visibility.js';
20
+ import { createFigureAssembler } from './figure-skeleton.js';
21
+
22
+ /**
23
+ * Wires figure builders, instanced crowd batches, pose texture, herd skins, ambient street beasts,
24
+ * frustum/shadow visibility, alarms, and the per-frame crowd updater from one call.
25
+ *
26
+ * When `getTime` and `getLightDir` are supplied, the updater is created immediately and available
27
+ * through `updater`, `updateCrowds()`, and `orderLooksAround()`. Callers that create lights later
28
+ * may call `createUpdater({ getTime, getFrame, getLightDir, ... })` afterward.
29
+ *
30
+ * @param {object} config
31
+ * @param {THREE.Object3D} config.scene Scene or world group receiving instanced crowd and herd meshes.
32
+ * @param {THREE.PerspectiveCamera} config.camera Active camera for frustum culling and LOD promotion.
33
+ * @param {THREE.WebGLRenderer|null} [config.renderer=null] Optional renderer for shadow-map checks.
34
+ * @param {(x: number, z: number) => number} [config.groundAt] Ground height sampler (metres); defaults to flat `0`.
35
+ * @param {{ worldSpace: object, steer?: Function }|null} [config.spaceKit=null] Optional space kit from `createSpaces` supplying `worldSpace` and `steer`.
36
+ * @param {object|null} [config.space=null] Optional active space record (`{ id, ground }`); defaults to `spaceKit.worldSpace` or `{ id: 'world', ground: groundAt }`.
37
+ * @param {() => object} [config.getSpace] Returns the active space each frame; overrides `space`.
38
+ * @param {Function} [config.steer] Steering helper for alarm flight; defaults to `spaceKit?.steer`.
39
+ * @param {object[]} [config.crowds] Optional existing crowd array to populate.
40
+ * @param {() => THREE.Material} [config.figureMaterial] Material factory for assembled figure rigs.
41
+ * @param {() => THREE.Material} [config.createColourMaterial] Base colour material factory for instanced crowd batches.
42
+ * @param {() => THREE.Material} [config.herdMaterial] Material factory for instanced herd meshes.
43
+ * @param {Function} [config.buildFigure] Custom figure builder overriding the default `createFigureBuilder` + `createFigureAssembler`.
44
+ * @param {Function} [config.buildCrowdLook] Custom synchronous crowd-look builder.
45
+ * @param {Function|null} [config.orderCrowdLook=null] Optional worker look orderer.
46
+ * @param {Function} [config.crowdPose] Custom crowd poser; defaults to `createCrowdPoser()`.
47
+ * @param {object} [config.herdSkins] Custom herd skin registry; defaults to `createHerdSkins()`.
48
+ * @param {object} [config.herdRenderer] Custom herd renderer; defaults to `createHerdRenderer(...)`.
49
+ * @param {object} [config.visibility] Custom visibility tester; defaults to `createCrowdVisibility()`.
50
+ * @param {object} [config.alarms] Custom alarm controller; defaults to `createCrowdAlarms({ steer })`.
51
+ * @param {Array<[string, object]>} [config.looks] Crowd look table forwarded to `createCrowdBatches`.
52
+ * @param {number[]} [config.skins] Skin tone hex palette forwarded to `createCrowdBatches`.
53
+ * @param {number[]} [config.hair] Hair tone hex palette forwarded to `createCrowdBatches`.
54
+ * @param {(x: number, y: number, salt?: number) => number} [config.hash] Seeded 2D hash forwarded to `createCrowdBatches` and `registerCrowd`.
55
+ * @param {Function} [config.pickLook] Custom look picker forwarded to `createCrowdBatches`.
56
+ * @param {Function|null} [config.pickSkinHair] Custom skin/hair picker forwarded to `createCrowdBatches`.
57
+ * @param {Function} [config.hasFirewood] Firewood predicate forwarded to `createCrowdBatches`.
58
+ * @param {Function} [config.carryBendOf] Carry-bend resolver forwarded to `createCrowdBatches`.
59
+ * @param {Record<string, object>} [config.beastKinds] Custom street-beast kind table forwarded to `createStreetBeasts`.
60
+ * @param {() => number} [config.getTime] Optional elapsed time source (seconds) to wire the updater immediately.
61
+ * @param {() => number} [config.getFrame] Optional frame counter source.
62
+ * @param {() => { x: number, y: number, z: number }} [config.getLightDir] Optional directional light vector source.
63
+ * @param {() => boolean} [config.getShadowsEnabled] Optional shadow-enabled predicate.
64
+ * @param {number} [config.shadowRange=120] Default shadow frustum half-extent (metres).
65
+ * @param {number} [config.shadowFar=320] Default shadow frustum far depth (metres).
66
+ * @param {object} [config.updaterOptions] Additional options forwarded to `createCrowdUpdater`.
67
+ * @returns {object} Crowd system handle with `crowds`, `addCrowd`, `batches`, `poseTexture`, `herdSkins`, `herdRenderer`, `streetBeasts`, `beastsAbout`, `alarms`, `visibility`, `crowdPose`, `build`, `createUpdater`, `updater`, `updateCrowds`, `orderLooksAround`, and `dispose`.
68
+ */
69
+ export function createCrowdSystem({
70
+ scene,
71
+ camera,
72
+ renderer = null,
73
+ groundAt = () => 0,
74
+ spaceKit = null,
75
+ space = null,
76
+ getSpace = null,
77
+ steer = spaceKit?.steer,
78
+ crowds = [],
79
+ figureMaterial = () => new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.88, side: THREE.DoubleSide }),
80
+ createColourMaterial,
81
+ herdMaterial = () => new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.9 }),
82
+ buildFigure = null,
83
+ buildCrowdLook = null,
84
+ orderCrowdLook = null,
85
+ crowdPose = createCrowdPoser(),
86
+ herdSkins = createHerdSkins(),
87
+ herdRenderer = null,
88
+ visibility = createCrowdVisibility(),
89
+ alarms = null,
90
+ looks,
91
+ skins,
92
+ hair,
93
+ hash,
94
+ pickLook,
95
+ pickSkinHair,
96
+ hasFirewood,
97
+ carryBendOf,
98
+ beastKinds,
99
+ getTime = null,
100
+ getFrame = () => 0,
101
+ getLightDir = null,
102
+ getShadowsEnabled = () => (renderer ? !!renderer.shadowMap?.enabled : true),
103
+ shadowRange = 120,
104
+ shadowFar = 320,
105
+ updaterOptions = {},
106
+ }) {
107
+ const defaultSpace = space ?? spaceKit?.worldSpace ?? { id: 'world', ground: groundAt };
108
+ const resolveSpace = getSpace ?? (() => defaultSpace);
109
+
110
+ let figureBuilder = buildFigure;
111
+ let lookBuilder = buildCrowdLook;
112
+ if (!figureBuilder || !lookBuilder) {
113
+ const { buildBody, kit } = createFigureBuilder();
114
+ if (!figureBuilder) {
115
+ const { assembleFigure } = createFigureAssembler({ material: figureMaterial, holds: kit.holds });
116
+ figureBuilder = (look, lookSeed, _near, bodies) => {
117
+ const far = bodies?.[0] || buildBody(look, lookSeed, 1);
118
+ return assembleFigure(look, 'human', { ...far, geo: geometryOf(far.parts) }, null);
119
+ };
120
+ }
121
+ if (!lookBuilder) lookBuilder = createCrowdLookBuilder({ buildBody });
122
+ }
123
+
124
+ const batchConfig = {
125
+ scene,
126
+ buildFigure: figureBuilder,
127
+ buildCrowdLook: lookBuilder,
128
+ orderCrowdLook,
129
+ crowdPose,
130
+ };
131
+ if (createColourMaterial) batchConfig.createColourMaterial = createColourMaterial;
132
+ if (looks) batchConfig.looks = looks;
133
+ if (skins) batchConfig.skins = skins;
134
+ if (hair) batchConfig.hair = hair;
135
+ if (hash) batchConfig.hash = hash;
136
+ if (pickLook) batchConfig.pickLook = pickLook;
137
+ if (pickSkinHair) batchConfig.pickSkinHair = pickSkinHair;
138
+ if (hasFirewood) batchConfig.hasFirewood = hasFirewood;
139
+ if (carryBendOf) batchConfig.carryBendOf = carryBendOf;
140
+
141
+ const batches = createCrowdBatches(batchConfig);
142
+ const resolvedHerdRenderer =
143
+ herdRenderer ??
144
+ createHerdRenderer({
145
+ scene,
146
+ material: herdMaterial,
147
+ herdPoses: herdSkins.herdPoses,
148
+ });
149
+ const resolvedAlarms = alarms ?? createCrowdAlarms(steer ? { steer } : {});
150
+
151
+ const groundForCrowd = (_spaceId, x, z) => groundAt(x, z);
152
+ function addCrowd(list, tones, cx, cz, range, kind, beasts = null, sp = defaultSpace.id) {
153
+ return registerCrowd(crowds, list, tones, cx, cz, range, kind, {
154
+ beasts,
155
+ space: sp,
156
+ groundAt: groundForCrowd,
157
+ ...(hash ? { hash } : {}),
158
+ });
159
+ }
160
+
161
+ const { streetBeasts, beastsAbout } = createStreetBeasts({
162
+ addCrowd,
163
+ herdLook: herdSkins.herdLook,
164
+ ...(beastKinds ? { kinds: beastKinds } : {}),
165
+ });
166
+
167
+ function build(fars = [farCrowdFigure('distant'), farCrowdFigure('remote')]) {
168
+ return batches.buildCrowdBatches(fars, crowds);
169
+ }
170
+
171
+ let activeUpdater = null;
172
+ function createUpdater(overrides = {}) {
173
+ const {
174
+ shadowRange: range = shadowRange,
175
+ shadowFar: far = shadowFar,
176
+ getShadowRange = () => range,
177
+ getShadowFar = () => far,
178
+ ...rest
179
+ } = overrides;
180
+ activeUpdater = createCrowdUpdater({
181
+ camera,
182
+ renderer,
183
+ getTime,
184
+ getFrame,
185
+ getShadowsEnabled,
186
+ getLightDir,
187
+ getShadowRange,
188
+ getShadowFar,
189
+ getSpace: resolveSpace,
190
+ crowds,
191
+ batches,
192
+ visibility,
193
+ alarms: resolvedAlarms,
194
+ crowdPose,
195
+ herds: { ...resolvedHerdRenderer, orderHerd: herdSkins.orderHerd },
196
+ ...updaterOptions,
197
+ ...rest,
198
+ });
199
+ return activeUpdater;
200
+ }
201
+
202
+ if (getTime && getLightDir) createUpdater();
203
+
204
+ function updateCrowds() {
205
+ if (activeUpdater) activeUpdater.updateCrowds();
206
+ }
207
+
208
+ function orderLooksAround(land, x, z) {
209
+ if (activeUpdater) activeUpdater.orderLooksAround(land, x, z);
210
+ }
211
+
212
+ function dispose() {
213
+ batches.dropCrowdBatches();
214
+ }
215
+
216
+ return {
217
+ crowds,
218
+ addCrowd,
219
+ batches,
220
+ get poseTexture() {
221
+ return batches.poseTexture;
222
+ },
223
+ herdSkins,
224
+ herdRenderer: resolvedHerdRenderer,
225
+ streetBeasts,
226
+ beastsAbout,
227
+ alarms: resolvedAlarms,
228
+ visibility,
229
+ crowdPose,
230
+ build,
231
+ createUpdater,
232
+ get updater() {
233
+ return activeUpdater;
234
+ },
235
+ updateCrowds,
236
+ orderLooksAround,
237
+ dispose,
238
+ };
239
+ }
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Procedural equirectangular sky panoramas and a one-call daylight sky facade that sets up
3
+ * background sky texture, directional sun light with shadows, hemisphere fill, and exponential fog.
4
+ * @module
5
+ */
6
+
7
+ import * as THREE from 'three';
8
+ import { createNoise } from '../math/noise.js';
9
+
10
+ /**
11
+ * Wraps an RGBA pixel buffer into an equirectangular sky `THREE.DataTexture`.
12
+ *
13
+ * @param {Uint8Array} pixels Flat RGBA bytes (`width * height * 4`).
14
+ * @param {number} width Texture width in pixels.
15
+ * @param {number} height Texture height in pixels.
16
+ * @returns {THREE.DataTexture}
17
+ */
18
+ export function createSkyTexture(pixels, width, height) {
19
+ const sky = new THREE.DataTexture(pixels, width, height);
20
+ sky.colorSpace = THREE.SRGBColorSpace;
21
+ sky.mapping = THREE.EquirectangularReflectionMapping;
22
+ sky.minFilter = sky.magFilter = THREE.LinearFilter;
23
+ sky.needsUpdate = true;
24
+ return sky;
25
+ }
26
+
27
+ /**
28
+ * Paints an equirectangular sky `THREE.DataTexture` with horizon-to-zenith gradient, wispy high
29
+ * clouds, sun glow, and optional stars for dusk or night skies.
30
+ *
31
+ * @param {{ fbm: Function, vnoise: Function }} [noise] Seeded noise generator (`createNoise`); defaults to `createNoise(42)`.
32
+ * @param {object} [options]
33
+ * @param {[number, number, number]} [options.zenith=[0.27, 0.49, 0.72]] Linear-range zenith sky tint.
34
+ * @param {[number, number, number]} [options.horizon=[0.82, 0.86, 0.84]] Horizon sky tint.
35
+ * @param {[number, number, number]} [options.ground=[0.55, 0.56, 0.5]] Below-horizon tint.
36
+ * @param {[number, number, number]} [options.cloudColor=[0.99, 0.95, 0.87]] High-cloud veil tint.
37
+ * @param {[number, number, number]} [options.sunGlow=[1.0, 0.84, 0.58]] Solar halo tint.
38
+ * @param {[number, number, number]} [options.sunDir=[-0.72, 0.28, -0.63]] Direction toward the sun or moon.
39
+ * @param {number} [options.cloudCover=0.53] Cloud noise threshold in `[0, 1]`.
40
+ * @param {number} [options.stars=0] Starfield brightness multiplier (`0` disables stars).
41
+ * @param {number} [options.width=512] Panorama width in pixels.
42
+ * @param {number} [options.height=256] Panorama height in pixels.
43
+ * @returns {THREE.DataTexture}
44
+ */
45
+ export function createSkyPanorama(
46
+ noise = createNoise(42),
47
+ {
48
+ zenith = [0.27, 0.49, 0.72],
49
+ horizon = [0.82, 0.86, 0.84],
50
+ ground = [0.55, 0.56, 0.5],
51
+ cloudColor = [0.99, 0.95, 0.87],
52
+ sunGlow = [1.0, 0.84, 0.58],
53
+ sunDir = [-0.72, 0.28, -0.63],
54
+ cloudCover = 0.53,
55
+ stars = 0,
56
+ width = 512,
57
+ height = 256,
58
+ } = {},
59
+ ) {
60
+ const pixels = new Uint8Array(width * height * 4);
61
+ const sun = new THREE.Vector3(...sunDir).normalize();
62
+ for (let y = 0; y < height; y++) {
63
+ const lat = Math.PI * ((y + 0.5) / height - 0.5);
64
+ const up = Math.sin(lat),
65
+ ring = Math.cos(lat);
66
+ const skyMix = THREE.MathUtils.smoothstep(up, -0.04, 0.74);
67
+ const belowMix = THREE.MathUtils.smoothstep(-up, 0.0, 0.35);
68
+ for (let x = 0; x < width; x++) {
69
+ const lon = 2 * Math.PI * ((x + 0.5) / width - 0.5);
70
+ const ex = ring * Math.cos(lon),
71
+ ez = ring * Math.sin(lon);
72
+ const air = Math.max(0.09, up);
73
+ const cNoise = noise.fbm((ex / air) * 1.25, (ez / air) * 2.4, 4, 71);
74
+ const veil = THREE.MathUtils.smoothstep(cNoise, cloudCover, cloudCover + 0.24) * THREE.MathUtils.smoothstep(up, 0.01, 0.16);
75
+ const sd = Math.max(0, ex * sun.x + up * sun.y + ez * sun.z);
76
+ const glow = Math.pow(sd, 18) * 0.26 + Math.pow(sd, 140) * 0.65;
77
+ let r = horizon[0] + (zenith[0] - horizon[0]) * skyMix;
78
+ let g = horizon[1] + (zenith[1] - horizon[1]) * skyMix;
79
+ let b = horizon[2] + (zenith[2] - horizon[2]) * skyMix;
80
+ if (up < 0) {
81
+ r += (ground[0] - r) * belowMix;
82
+ g += (ground[1] - g) * belowMix;
83
+ b += (ground[2] - b) * belowMix;
84
+ }
85
+ r = r * (1 - veil) + cloudColor[0] * veil + sunGlow[0] * glow;
86
+ g = g * (1 - veil) + cloudColor[1] * veil + sunGlow[1] * glow;
87
+ b = b * (1 - veil) + cloudColor[2] * veil + sunGlow[2] * glow;
88
+ if (stars > 0 && up > 0.05) {
89
+ const twinkle = noise.vnoise(ex * 95 + 11, ez * 95 + up * 73, 19);
90
+ if (twinkle > 0.945) {
91
+ const s = ((twinkle - 0.945) / 0.055) * stars * THREE.MathUtils.smoothstep(up, 0.05, 0.3) * (1 - veil);
92
+ r += s * 0.9;
93
+ g += s * 0.94;
94
+ b += s;
95
+ }
96
+ }
97
+ const i = (y * width + x) * 4;
98
+ pixels[i] = Math.min(255, Math.max(0, Math.round(r * 255)));
99
+ pixels[i + 1] = Math.min(255, Math.max(0, Math.round(g * 255)));
100
+ pixels[i + 2] = Math.min(255, Math.max(0, Math.round(b * 255)));
101
+ pixels[i + 3] = 255;
102
+ }
103
+ }
104
+ return createSkyTexture(pixels, width, height);
105
+ }
106
+
107
+ /**
108
+ * Sets up a daylight sky backdrop, directional sun light with shadow frustum, hemisphere ambient
109
+ * fill, and exponential distance fog on `scene` in one call.
110
+ *
111
+ * @param {object} options
112
+ * @param {THREE.Scene} options.scene Scene receiving background, fog, sun, and hemisphere light.
113
+ * @param {THREE.WebGLRenderer} [options.renderer] Optional renderer whose shadow map is enabled and configured.
114
+ * @param {{ fbm: Function, vnoise: Function }} [options.noise] Seeded noise for the sky panorama; defaults to `createNoise(seed)`.
115
+ * @param {number} [options.seed=42] Fallback seed when `noise` is not provided.
116
+ * @param {object|THREE.Texture|false} [options.sky={}] Options passed to `createSkyPanorama`, a prebuilt `THREE.Texture`, or `false` to skip `scene.background`.
117
+ * @param {[number, number, number]} [options.sunPosition=[-65, 38, 48]] World position of the directional sun light (metres).
118
+ * @param {number} [options.sunColor=0xffe2b8] Directional sun light colour (sRGB hex).
119
+ * @param {number} [options.sunIntensity=2.6] Directional sun light intensity.
120
+ * @param {number} [options.skyColor=0xddeaf5] Hemisphere sky colour (sRGB hex).
121
+ * @param {number} [options.groundColor=0x6b6752] Hemisphere ground bounce colour (sRGB hex).
122
+ * @param {number} [options.hemiIntensity=1.25] Hemisphere light intensity.
123
+ * @param {boolean} [options.castShadow=true] Whether the directional sun casts shadows.
124
+ * @param {number} [options.shadowRadius=70] Half-extent of the orthographic shadow frustum (metres).
125
+ * @param {number} [options.shadowFar=240] Far plane of the orthographic shadow frustum (metres).
126
+ * @param {number} [options.shadowMapSize=2048] Shadow map resolution in pixels (square).
127
+ * @param {number} [options.normalBias=0.045] Shadow normal bias (metres).
128
+ * @param {boolean} [options.staticShadows=false] When true, renders the shadow map once instead of every frame.
129
+ * @param {number} [options.fogColor=0xd4ded9] Exponential fog colour (sRGB hex).
130
+ * @param {number} [options.fogDensity=0.002] Exponential fog density (`0` omits fog).
131
+ * @returns {{ sky: THREE.Texture|null, sun: THREE.DirectionalLight, hemi: THREE.HemisphereLight, fog: THREE.FogExp2|null, lightDir: THREE.Vector3, dispose: () => void }}
132
+ */
133
+ export function createDaylightSky({
134
+ scene,
135
+ renderer = null,
136
+ noise = null,
137
+ seed = 42,
138
+ sky: skyOptions = {},
139
+ sunPosition = [-65, 38, 48],
140
+ sunColor = 0xffe2b8,
141
+ sunIntensity = 2.6,
142
+ skyColor = 0xddeaf5,
143
+ groundColor = 0x6b6752,
144
+ hemiIntensity = 1.25,
145
+ castShadow = true,
146
+ shadowRadius = 70,
147
+ shadowFar = 240,
148
+ shadowMapSize = 2048,
149
+ normalBias = 0.045,
150
+ staticShadows = false,
151
+ fogColor = 0xd4ded9,
152
+ fogDensity = 0.002,
153
+ } = {}) {
154
+ let sky = null;
155
+ let ownsSky = false;
156
+ if (skyOptions && skyOptions.isTexture) {
157
+ sky = skyOptions;
158
+ scene.background = sky;
159
+ } else if (skyOptions !== false) {
160
+ sky = createSkyPanorama(noise ?? createNoise(seed), skyOptions);
161
+ ownsSky = true;
162
+ scene.background = sky;
163
+ }
164
+
165
+ let fog = null;
166
+ if (fogDensity > 0) {
167
+ fog = new THREE.FogExp2(fogColor, fogDensity);
168
+ scene.fog = fog;
169
+ }
170
+
171
+ if (renderer && castShadow) {
172
+ renderer.shadowMap.enabled = true;
173
+ renderer.shadowMap.type = THREE.PCFShadowMap;
174
+ }
175
+
176
+ const hemi = new THREE.HemisphereLight(skyColor, groundColor, hemiIntensity);
177
+ scene.add(hemi);
178
+
179
+ const sun = new THREE.DirectionalLight(sunColor, sunIntensity);
180
+ sun.position.set(...sunPosition);
181
+ sun.castShadow = castShadow;
182
+ if (castShadow) {
183
+ sun.shadow.mapSize.set(shadowMapSize, shadowMapSize);
184
+ Object.assign(sun.shadow.camera, {
185
+ left: -shadowRadius,
186
+ right: shadowRadius,
187
+ top: shadowRadius,
188
+ bottom: -shadowRadius,
189
+ near: 1,
190
+ far: shadowFar,
191
+ });
192
+ sun.shadow.camera.updateProjectionMatrix();
193
+ sun.shadow.normalBias = normalBias;
194
+ }
195
+ scene.add(sun);
196
+
197
+ if (renderer && castShadow && staticShadows) {
198
+ renderer.shadowMap.autoUpdate = false;
199
+ renderer.shadowMap.needsUpdate = true;
200
+ }
201
+
202
+ const lightDir = sun.position.clone().normalize();
203
+
204
+ function dispose() {
205
+ if (ownsSky && sky) sky.dispose();
206
+ scene.remove(sun, hemi);
207
+ sun.dispose();
208
+ hemi.dispose();
209
+ }
210
+
211
+ return { sky, sun, hemi, fog, lightDir, dispose };
212
+ }