roamwright 0.61.1 → 0.61.3

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
@@ -92,16 +92,17 @@ renderer.render(scene, camera);
92
92
 
93
93
  Import modules by path, for example `roamwright/geometry/builder.js`. Browse the [API reference](https://enestaylan.github.io/roamwright/docs/) for signatures, usage notes and source links.
94
94
 
95
- | Area | Main modules |
96
- | ------------------------ | ----------------------------------------------------------------------------------------------------------- |
97
- | Seeded generation | `math/noise.js`, `math/random.js` |
98
- | Geometry and terrain | `geometry/builder.js`, `geometry/heightfield.js`, `geometry/terrain-chunks.js` |
99
- | Static geometry assembly | `geometry/builder-frame.js`, `geometry/builder-cells.js`, `geometry/part-ranges.js` |
100
- | Rendering | `rendering/context.js`, `rendering/sky.js`, `rendering/water-material.js` |
101
- | Interiors | `geometry/room-kit.js`, `rendering/room-materials.js`, `rendering/room-space.js`, `rendering/room-light.js` |
102
- | Movement | `motion/player.js`, `motion/biped-stride.js` |
103
- | Scene playback | `runtime/cue-cursor.js`, `rendering/camera-track.js` |
104
- | Background jobs | `runtime/pool.js`, `runtime/worker.js`, `runtime/grid-rows.js` |
95
+ | Area | Main modules |
96
+ | ------------------------ | ----------------------------------------------------------------------------------------------------------------- |
97
+ | Seeded generation | `math/noise.js`, `math/random.js` |
98
+ | Geometry and terrain | `geometry/builder.js`, `geometry/heightfield.js`, `geometry/terrain-chunks.js` |
99
+ | Static geometry assembly | `geometry/builder-frame.js`, `geometry/builder-cells.js`, `geometry/part-ranges.js` |
100
+ | Rendering | `rendering/context.js`, `rendering/sky.js`, `rendering/water-material.js` |
101
+ | Interiors | `geometry/room-kit.js`, `rendering/room-materials.js`, `rendering/room-space.js`, `rendering/room-light.js` |
102
+ | Movement | `motion/player.js`, `motion/biped-stride.js` |
103
+ | Scene playback | `runtime/cue-cursor.js`, `rendering/camera-track.js` |
104
+ | Background jobs | `runtime/pool.js`, `runtime/worker.js`, `runtime/grid-rows.js` |
105
+ | A world's toolchain | `scripts/world.mk` (make recipes), `scripts/serve.py` (local server), `scripts/dev-engine.py` (unreleased engine) |
105
106
 
106
107
  ## Contributing and license
107
108
 
package/index.js CHANGED
@@ -63,6 +63,7 @@ export { createIrrigatedFieldSurface, IRRIGATED_FIELD_KIND, IRRIGATED_FIELD_SURF
63
63
  export { DRYSTONE_WALL, FIELD_STONE, drystoneStone, planDrystoneWall } from './geometry/drystone-wall.js';
64
64
  export { FARM_BOUNDARIES, planFieldBoundaries } from './geometry/farm-boundaries.js';
65
65
  export { meshFarmCells, scatterFarmLots } from './rendering/farm-cells.js';
66
+ export { DEFAULT_LIVESTOCK_CASTS, createLivestockCache } from './rendering/farm-livestock.js';
66
67
  export { DEFAULT_FARM_HERDS, FARM_LIFE, herdPlaces, parcelPlaces, planFarmLife, ploughSite } from './geometry/farm-life.js';
67
68
  export { STOOK, createStook } from './geometry/prop-stook.js';
68
69
  export { PLOUGH, ploughGear } from './geometry/prop-plough.js';
@@ -169,7 +170,18 @@ export { planCrewAtStations, planTownsfolk } from './motion/crowd-town.js';
169
170
  export { driveToWater, trekToWater, waterNear } from './motion/crowd-water.js';
170
171
  export { createCrowdVisibility } from './rendering/crowd-visibility.js';
171
172
  export { createHerdRenderer, createHerdSkins } from './rendering/crowd-herd.js';
172
- export { createCrowdBatches } from './rendering/crowd-batches.js';
173
+ export {
174
+ DEFAULT_BEARERS,
175
+ DEFAULT_BY_ROLE,
176
+ DEFAULT_CROWD_HAIR,
177
+ DEFAULT_CROWD_LOOKS,
178
+ DEFAULT_CROWD_SKINS,
179
+ DEFAULT_SOLDIER_BEARER,
180
+ DEFAULT_UNIFORMS,
181
+ bakeCrowdWalks,
182
+ createCrowdBatches,
183
+ createLookPicker,
184
+ } from './rendering/crowd-batches.js';
173
185
  export { createCrowdUpdater, registerCrowd } from './rendering/crowd-update.js';
174
186
  export { createCrowdSystem } from './rendering/crowd-system.js';
175
187
 
@@ -74,23 +74,21 @@ export function crowdMotion() {
74
74
 
75
75
  /**
76
76
  * Creates a crowd poser bound to a world's seeded hash, kind-to-bearing mapper, busy-focus predicate,
77
- * and optional default pose-texture buffer provider.
77
+ * and well crank dimensions. Callers pass the target pose-texture buffer directly on each call.
78
78
  *
79
79
  * @param {object} [options]
80
80
  * @param {(x: number, y: number, salt?: number) => number} [options.hash] Seeded 2D hash for combat rhythm variation.
81
81
  * @param {(kind: string, focus: string|undefined) => import('./crowd-attention.js').CrowdBearing} [options.bearing] Maps crowd kind + focus to engine bearing.
82
82
  * @param {(focus: string|undefined) => boolean} [options.busy] Returns true for focuses that ignore stage/alarm attention.
83
- * @param {() => Float32Array|null} [options.getPoseData] Optional default target buffer when `data` is omitted.
84
83
  * @param {number} [options.wellStand=WELL_STAND] Distance from well crank axle (metres).
85
84
  * @param {number} [options.wellArm=WELL_ARM] Well crank arm radius (metres).
86
85
  * @param {number} [options.wellCrank=WELL_CRANK] Well crank axle height (metres).
87
- * @returns {(g: object, variant: object, row: number, motion: ReturnType<typeof crowdMotion>, data?: Float32Array) => void}
86
+ * @returns {(g: object, variant: object, row: number, motion: ReturnType<typeof crowdMotion>, data: Float32Array) => void}
88
87
  */
89
88
  export function createCrowdPoser({
90
89
  hash = defaultHash,
91
90
  bearing = defaultBearing,
92
91
  busy = defaultBusy,
93
- getPoseData = null,
94
92
  wellStand = WELL_STAND,
95
93
  wellArm = WELL_ARM,
96
94
  wellCrank = WELL_CRANK,
@@ -167,7 +165,7 @@ export function createCrowdPoser({
167
165
  }
168
166
  }
169
167
 
170
- return function crowdPose(g, variant, row, motion, data = getPoseData?.()) {
168
+ return function crowdPose(g, variant, row, motion, data) {
171
169
  const { t, phase, speed, ground, focus } = motion,
172
170
  { head, lidA, cloak, rig } = variant,
173
171
  b = rig.bones;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roamwright",
3
- "version": "0.61.1",
3
+ "version": "0.61.3",
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",
@@ -48,6 +48,7 @@
48
48
  "tools",
49
49
  "examples",
50
50
  "scripts/serve.py",
51
+ "scripts/dev-engine.py",
51
52
  "scripts/format.sh",
52
53
  "scripts/lint.sh",
53
54
  "scripts/check-app.sh",
@@ -122,21 +122,38 @@ export function bakeCrowdWalks(geos, variant, crowdPose) {
122
122
  });
123
123
  }
124
124
 
125
- function defaultPickLook(group, member, index, pick) {
126
- const choices =
127
- DEFAULT_UNIFORMS[group.kind] ||
128
- (group.kind === 'camp' || group.kind === 'guard'
129
- ? [6]
130
- : group.kind === 'sappers'
131
- ? [14]
132
- : group.kind === 'plain'
133
- ? [7]
134
- : group.festival
135
- ? [8, 8, 0, 5]
136
- : group.kind === 'mob'
137
- ? [0, 1, 2, 3, 4, 5]
138
- : DEFAULT_BY_ROLE[member.role] || [0, 2, 3, 5]);
139
- return member.held ? (DEFAULT_BEARERS[group.kind] ?? DEFAULT_SOLDIER_BEARER) : pick(index, 38, choices);
125
+ /**
126
+ * Creates a crowd look picker from generic or world-extended uniform, bearer, and role tables.
127
+ *
128
+ * @param {object} [options]
129
+ * @param {Record<string, number[]>} [options.uniforms=DEFAULT_UNIFORMS] Uniformed look index lists keyed by crowd kind.
130
+ * @param {Record<string, number>} [options.bearers=DEFAULT_BEARERS] Bearer look indices keyed by crowd kind.
131
+ * @param {number} [options.soldierBearer=DEFAULT_SOLDIER_BEARER] Fallback bearer look index for kinds absent from `bearers`.
132
+ * @param {Record<string, number[]>} [options.byRole=DEFAULT_BY_ROLE] Civilian look index pools keyed by member role.
133
+ * @returns {(group: object, member: object, index: number, pick: Function) => number}
134
+ */
135
+ export function createLookPicker({
136
+ uniforms = DEFAULT_UNIFORMS,
137
+ bearers = DEFAULT_BEARERS,
138
+ soldierBearer = DEFAULT_SOLDIER_BEARER,
139
+ byRole = DEFAULT_BY_ROLE,
140
+ } = {}) {
141
+ return function pickLook(group, member, index, pick) {
142
+ const choices =
143
+ uniforms[group.kind] ||
144
+ (group.kind === 'camp' || group.kind === 'guard'
145
+ ? [6]
146
+ : group.kind === 'sappers'
147
+ ? [14]
148
+ : group.kind === 'plain'
149
+ ? [7]
150
+ : group.festival
151
+ ? [8, 8, 0, 5]
152
+ : group.kind === 'mob'
153
+ ? [0, 1, 2, 3, 4, 5]
154
+ : byRole[member.role] || [0, 2, 3, 5]);
155
+ return member.held ? (bearers[group.kind] ?? soldierBearer) : pick(index, 38, choices);
156
+ };
140
157
  }
141
158
 
142
159
  /**
@@ -153,9 +170,14 @@ function defaultPickLook(group, member, index, pick) {
153
170
  * @param {Array<[string, object]>} [config.looks=DEFAULT_CROWD_LOOKS] Look table `[kindName, figureLookSpec]`.
154
171
  * @param {number[]} [config.skins=DEFAULT_CROWD_SKINS] Default skin hex palette.
155
172
  * @param {number[]} [config.hair=DEFAULT_CROWD_HAIR] Default hair hex palette.
173
+ * @param {Record<string, { skins?: number[], hair?: number[] }>|null} [config.palettesByKind=null] Optional per-crowd-kind skin/hair palette overrides.
156
174
  * @param {(x: number, y: number, salt?: number) => number} [config.hash] Seeded 2D hash for look and palette picking.
157
- * @param {(group: object, member: object, index: number, pick: Function) => number} [config.pickLook] Maps a crowd member to an index in `looks`.
158
- * @param {(group: object, member: object, index: number, pick: Function) => [number, number]} [config.pickSkinHair] Returns `[skinHex, hairHex]` for a member.
175
+ * @param {Record<string, number[]>} [config.uniforms=DEFAULT_UNIFORMS] Uniformed look index lists keyed by crowd kind (used when `pickLook` is omitted).
176
+ * @param {Record<string, number>} [config.bearers=DEFAULT_BEARERS] Bearer look indices keyed by crowd kind (used when `pickLook` is omitted).
177
+ * @param {number} [config.soldierBearer=DEFAULT_SOLDIER_BEARER] Fallback bearer look index (used when `pickLook` is omitted).
178
+ * @param {Record<string, number[]>} [config.byRole=DEFAULT_BY_ROLE] Civilian look index pools keyed by member role (used when `pickLook` is omitted).
179
+ * @param {((group: object, member: object, index: number, pick: Function) => number)|null} [config.pickLook=null] Optional custom look picker overriding table-based lookup.
180
+ * @param {((group: object, member: object, index: number, pick: Function) => [number, number])|null} [config.pickSkinHair=null] Optional custom `[skinHex, hairHex]` picker overriding `palettesByKind`/`skins`/`hair`.
159
181
  * @param {(kind: string) => boolean} [config.hasFirewood=carriesFirewood] Predicate for whether a look carries firewood.
160
182
  * @param {(kind: string) => number} [config.carryBendOf] Forearm bend (radians) for left-hand carried items (`0` if none).
161
183
  */
@@ -169,12 +191,18 @@ export function createCrowdBatches({
169
191
  looks = DEFAULT_CROWD_LOOKS,
170
192
  skins = DEFAULT_CROWD_SKINS,
171
193
  hair = DEFAULT_CROWD_HAIR,
194
+ palettesByKind = null,
172
195
  hash = defaultHash,
173
- pickLook = defaultPickLook,
196
+ uniforms = DEFAULT_UNIFORMS,
197
+ bearers = DEFAULT_BEARERS,
198
+ soldierBearer = DEFAULT_SOLDIER_BEARER,
199
+ byRole = DEFAULT_BY_ROLE,
200
+ pickLook = null,
174
201
  pickSkinHair = null,
175
202
  hasFirewood = carriesFirewood,
176
203
  carryBendOf = kind => (kind === 'basket' ? -0.68 : kind === 'sack' ? -0.16 : 0),
177
204
  }) {
205
+ const resolveLook = pickLook ?? createLookPicker({ uniforms, bearers, soldierBearer, byRole });
178
206
  let poseTexture = null,
179
207
  activeBatches = null,
180
208
  warmFigure = null,
@@ -338,7 +366,7 @@ export function createCrowdBatches({
338
366
  for (const c of groups)
339
367
  for (let i = 0; i < c.list.length; i++) {
340
368
  const g = c.list[i];
341
- const look = pickLook(c, g, i, pick);
369
+ const look = resolveLook(c, g, i, pick);
342
370
  g.look = look;
343
371
  g.row = row++;
344
372
  g.lod = 0;
@@ -349,7 +377,10 @@ export function createCrowdBatches({
349
377
  sizes[look]++;
350
378
  const offset = (g.row * CROWD_POSE_WIDTH + CROWD_BONES * 3) * 4;
351
379
  g.c1.toArray(data, offset);
352
- const [skinHex, hairHex] = pickSkinHair ? pickSkinHair(c, g, i, pick) : [pick(i, 39, skins), pick(i, 40, hair)];
380
+ const kindPalette = palettesByKind?.[c.kind];
381
+ const [skinHex, hairHex] = pickSkinHair
382
+ ? pickSkinHair(c, g, i, pick)
383
+ : [pick(i, 39, kindPalette?.skins ?? skins), pick(i, 40, kindPalette?.hair ?? hair)];
353
384
  _cc.setHex(skinHex).toArray(data, offset + 4);
354
385
  _cc.setHex(hairHex).toArray(data, offset + 8);
355
386
  }
@@ -51,7 +51,12 @@ import { createFigureAssembler } from './figure-skeleton.js';
51
51
  * @param {Array<[string, object]>} [config.looks] Crowd look table forwarded to `createCrowdBatches`.
52
52
  * @param {number[]} [config.skins] Skin tone hex palette forwarded to `createCrowdBatches`.
53
53
  * @param {number[]} [config.hair] Hair tone hex palette forwarded to `createCrowdBatches`.
54
+ * @param {Record<string, { skins?: number[], hair?: number[] }>|null} [config.palettesByKind] Per-crowd-kind skin/hair overrides forwarded to `createCrowdBatches`.
54
55
  * @param {(x: number, y: number, salt?: number) => number} [config.hash] Seeded 2D hash forwarded to `createCrowdBatches` and `registerCrowd`.
56
+ * @param {Record<string, number[]>} [config.uniforms] Uniform look lists forwarded to `createCrowdBatches`.
57
+ * @param {Record<string, number>} [config.bearers] Bearer look indices forwarded to `createCrowdBatches`.
58
+ * @param {number} [config.soldierBearer] Fallback bearer look index forwarded to `createCrowdBatches`.
59
+ * @param {Record<string, number[]>} [config.byRole] Role look pools forwarded to `createCrowdBatches`.
55
60
  * @param {Function} [config.pickLook] Custom look picker forwarded to `createCrowdBatches`.
56
61
  * @param {Function|null} [config.pickSkinHair] Custom skin/hair picker forwarded to `createCrowdBatches`.
57
62
  * @param {Function} [config.hasFirewood] Firewood predicate forwarded to `createCrowdBatches`.
@@ -90,7 +95,12 @@ export function createCrowdSystem({
90
95
  looks,
91
96
  skins,
92
97
  hair,
98
+ palettesByKind,
93
99
  hash,
100
+ uniforms,
101
+ bearers,
102
+ soldierBearer,
103
+ byRole,
94
104
  pickLook,
95
105
  pickSkinHair,
96
106
  hasFirewood,
@@ -132,7 +142,12 @@ export function createCrowdSystem({
132
142
  if (looks) batchConfig.looks = looks;
133
143
  if (skins) batchConfig.skins = skins;
134
144
  if (hair) batchConfig.hair = hair;
145
+ if (palettesByKind) batchConfig.palettesByKind = palettesByKind;
135
146
  if (hash) batchConfig.hash = hash;
147
+ if (uniforms) batchConfig.uniforms = uniforms;
148
+ if (bearers) batchConfig.bearers = bearers;
149
+ if (soldierBearer !== undefined) batchConfig.soldierBearer = soldierBearer;
150
+ if (byRole) batchConfig.byRole = byRole;
136
151
  if (pickLook) batchConfig.pickLook = pickLook;
137
152
  if (pickSkinHair) batchConfig.pickSkinHair = pickSkinHair;
138
153
  if (hasFirewood) batchConfig.hasFirewood = hasFirewood;
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Worker-backed geometry cache for static posed farm livestock (cattle, oxen, sheep): pre-casts
3
+ * standing and grazing near/far geometries on background workers while a land loads, hands each
4
+ * pre-built geometry out once when consumed, and falls back synchronously to `castCattle`.
5
+ * @module
6
+ */
7
+
8
+ import { geometryOf as defaultGeometryOf } from '../geometry/builder.js';
9
+ import { NO_ANIMAL_OPTIONS } from '../geometry/animal-options.js';
10
+ import { castCattle } from '../motion/animal-cattle-cast.js';
11
+
12
+ const BOTH = Object.freeze([
13
+ Object.freeze([true, false]),
14
+ Object.freeze([true, true]),
15
+ Object.freeze([false, false]),
16
+ Object.freeze([false, true]),
17
+ ]);
18
+
19
+ /**
20
+ * Default farm livestock cast plan per animal build: `[grazing, far]` pairs for cows and sheep
21
+ * (both head poses and both LOD skins) plus a standing near ox for plough teams and carts.
22
+ */
23
+ export const DEFAULT_LIVESTOCK_CASTS = Object.freeze({
24
+ cow: BOTH,
25
+ sheep: BOTH,
26
+ ox: Object.freeze([Object.freeze([false, false])]),
27
+ });
28
+
29
+ const castKey = (build, grazing, far) => `${build}:${grazing}:${far}`;
30
+
31
+ /**
32
+ * Creates a page-scoped cache for pre-cast farm livestock geometries backed by an optional worker
33
+ * pool, with synchronous fallback via `castCattle`.
34
+ *
35
+ * @param {object} [options]
36
+ * @param {import('../geometry/animal-options.js').AnimalKitOptions} [options.animals=NO_ANIMAL_OPTIONS] World animal kit tuning forwarded to `castCattle`.
37
+ * @param {Record<string, ReadonlyArray<readonly [boolean, boolean]>>} [options.casts=DEFAULT_LIVESTOCK_CASTS] Map of build name to `[grazing, far]` pairs pre-cast by `castFarmBeasts`.
38
+ * @param {() => boolean} [options.pooled] Returns true when a worker pool is ready to accept jobs.
39
+ * @param {((job: string, spec: { build: string, casts: ReadonlyArray<readonly [boolean, boolean]> }) => Promise<object[]>)|null} [options.run=null] Worker job runner returning packed attribute arrays per cast.
40
+ * @param {string} [options.job='farm beasts'] Worker job name passed to `run`.
41
+ * @param {(arrays: object) => import('three').BufferGeometry} [options.geometryOf] Converts worker attribute arrays into a `THREE.BufferGeometry`.
42
+ * @returns {{
43
+ * castFarmBeasts: () => Promise<void> | null,
44
+ * cattleGeometry: (grazing: boolean, far: boolean, build?: string, fallen?: boolean) => import('three').BufferGeometry,
45
+ * clear: () => void,
46
+ * sheepGeometry: (grazing: boolean, far: boolean) => import('three').BufferGeometry,
47
+ * takeFarmBeasts: () => Promise<void> | null,
48
+ * }}
49
+ */
50
+ export function createLivestockCache({
51
+ animals = NO_ANIMAL_OPTIONS,
52
+ casts = DEFAULT_LIVESTOCK_CASTS,
53
+ pooled = () => false,
54
+ run = null,
55
+ job = 'farm beasts',
56
+ geometryOf = defaultGeometryOf,
57
+ } = {}) {
58
+ const cast = new Map();
59
+ let casting = null;
60
+
61
+ /**
62
+ * Returns a plain geometry for a cow, ox, or sheep facing +z on y = 0, consuming a pre-cast
63
+ * worker geometry when available or casting synchronously otherwise.
64
+ *
65
+ * @param {boolean} grazing True for head down grazing, false for head up standing.
66
+ * @param {boolean} far True for the lighter distant skin.
67
+ * @param {string} [build='cow'] Animal build (`'cow'`, `'ox'`, `'sheep'`, etc.).
68
+ * @param {boolean} [fallen=false] True for a dead animal pose (always cast synchronously).
69
+ * @returns {import('three').BufferGeometry}
70
+ */
71
+ function cattleGeometry(grazing, far, build = 'cow', fallen = false) {
72
+ const key = castKey(build, grazing, far),
73
+ done = !fallen && cast.get(key);
74
+ if (!done) return castCattle(grazing, far, build, fallen, animals);
75
+ cast.delete(key);
76
+ return done;
77
+ }
78
+
79
+ /**
80
+ * Dispatches worker jobs to cast every `[grazing, far]` variant declared in `casts` while the
81
+ * caller builds the rest of the land. Clears the cache on failure so synchronous fallback runs.
82
+ *
83
+ * @returns {Promise<void> | null} The in-flight casting promise, or `null` if no worker pool is active.
84
+ */
85
+ function castFarmBeasts() {
86
+ if (!pooled() || !run) return null;
87
+ const builds = Object.keys(casts);
88
+ casting = Promise.all(builds.map(build => run(job, { build, casts: casts[build] })))
89
+ .then(lists => {
90
+ lists.forEach((list, i) => list.forEach((arrays, k) => cast.set(castKey(builds[i], ...casts[builds[i]][k]), geometryOf(arrays))));
91
+ })
92
+ .catch(() => cast.clear());
93
+ return casting;
94
+ }
95
+
96
+ /** Returns the promise from the latest `castFarmBeasts()` call, or `null` if none was started. */
97
+ const takeFarmBeasts = () => casting;
98
+
99
+ /** Convenience wrapper returning a posed sheep geometry facing +z on y = 0. */
100
+ const sheepGeometry = (grazing, far) => cattleGeometry(grazing, far, 'sheep');
101
+
102
+ /** Drops any cached geometries and clears the pending worker promise. */
103
+ function clear() {
104
+ cast.clear();
105
+ casting = null;
106
+ }
107
+
108
+ return { castFarmBeasts, cattleGeometry, clear, sheepGeometry, takeFarmBeasts };
109
+ }
@@ -0,0 +1,104 @@
1
+ """Install a development snapshot of Roamwright into a world's checkout without changing its lockfile.
2
+
3
+ ROAMWRIGHT=<selection> python3 <engine>/scripts/dev-engine.py run from the world's root (`make dev-engine` does)
4
+
5
+ The selection is `local` (the world's embedded `./roamwright/` worktree, else a `roamwright` checkout beside the world's main
6
+ checkout), `github` or `github:<ref>` (a shallow fetch of the engine's repository), or a path to an engine checkout. The
7
+ snapshot is packed and installed over `node_modules/roamwright`; a fingerprint of the source's commit and uncommitted changes
8
+ skips the install when nothing changed since the last one.
9
+ """
10
+
11
+ import hashlib
12
+ import json
13
+ import os
14
+ import subprocess
15
+ import tempfile
16
+ from pathlib import Path
17
+
18
+ ROOT = Path.cwd() # the world's root: this file runs from the installed engine, not from the world
19
+ UPSTREAM = "https://github.com/enestaylan/roamwright.git"
20
+
21
+
22
+ def run(*args, cwd=ROOT):
23
+ return subprocess.check_output(args, cwd=cwd, text=True).strip()
24
+
25
+
26
+ def source_for(selection, scratch):
27
+ if selection == "local":
28
+ embedded = ROOT / "roamwright"
29
+ if (embedded / "package.json").is_file():
30
+ return embedded
31
+ common = Path(run("git", "rev-parse", "--path-format=absolute", "--git-common-dir"))
32
+ return common.parent.parent / "roamwright"
33
+ if selection == "github" or selection.startswith("github:"):
34
+ ref = selection.partition(":")[2] or "main"
35
+ checkout = scratch / "source"
36
+ run("git", "init", "-q", checkout)
37
+ run("git", "fetch", "-q", "--depth=1", "--", UPSTREAM, ref, cwd=checkout)
38
+ run("git", "checkout", "-q", "--detach", "FETCH_HEAD", cwd=checkout)
39
+ return checkout
40
+ return Path(selection).expanduser().resolve()
41
+
42
+
43
+ def source_fingerprint(source):
44
+ if not (source / ".git").exists():
45
+ return None
46
+ digest = hashlib.sha256()
47
+ digest.update(str(source.resolve()).encode("utf-8"))
48
+ digest.update(b"\0")
49
+ digest.update(run("git", "rev-parse", "HEAD", cwd=source).encode("utf-8"))
50
+ digest.update(b"\0")
51
+ status = run("git", "status", "--porcelain", cwd=source)
52
+ digest.update(status.encode("utf-8"))
53
+ if status:
54
+ digest.update(b"\0")
55
+ digest.update(subprocess.check_output(("git", "diff", "HEAD"), cwd=source))
56
+ untracked = run("git", "ls-files", "--others", "--exclude-standard", cwd=source)
57
+ for rel in untracked.splitlines():
58
+ target = source / rel
59
+ if target.is_file():
60
+ digest.update(b"\0" + rel.encode("utf-8") + b"\0")
61
+ digest.update(target.read_bytes())
62
+ return digest.hexdigest()
63
+
64
+
65
+ def main():
66
+ selection = os.environ["ROAMWRIGHT"]
67
+ with tempfile.TemporaryDirectory(prefix="roamwright-dev-") as directory:
68
+ scratch = Path(directory)
69
+ source = source_for(selection, scratch)
70
+ if not (source / "package.json").is_file() or json.loads((source / "package.json").read_text())["name"] != "roamwright":
71
+ raise SystemExit(f"No Roamwright package at {source}")
72
+ stamp = ROOT / "node_modules/.roamwright-dev"
73
+ installed_pkg = ROOT / "node_modules/roamwright/package.json"
74
+ fingerprint = source_fingerprint(source)
75
+ if fingerprint and installed_pkg.is_file() and stamp.is_file() and stamp.read_text().strip() == fingerprint:
76
+ return
77
+ (packed,) = json.loads(run("npm", "pack", "--ignore-scripts", "--json", "--pack-destination", scratch, cwd=source))
78
+ # Invalidate the locked-release stamp before overlaying node_modules/roamwright so a plain `make build`
79
+ # in checkouts without `./roamwright/` restores package-lock.json cleanly.
80
+ (ROOT / "node_modules/.roamwright-installed").unlink(missing_ok=True)
81
+ stamp.unlink(missing_ok=True)
82
+ subprocess.run(
83
+ [
84
+ "npm",
85
+ "install",
86
+ "--include=dev",
87
+ "--no-save",
88
+ "--package-lock=false",
89
+ "--ignore-scripts",
90
+ "--no-audit",
91
+ "--no-fund",
92
+ scratch / packed["filename"],
93
+ ],
94
+ cwd=ROOT,
95
+ check=True,
96
+ )
97
+ if fingerprint:
98
+ stamp.write_text(fingerprint + "\n")
99
+ revision = run("git", "rev-parse", "--short", "HEAD", cwd=source) if (source / ".git").exists() else ""
100
+ print(f"Using {packed['id']} from {selection} {revision} ({packed['integrity']})")
101
+
102
+
103
+ if __name__ == "__main__":
104
+ main()
package/scripts/serve.py CHANGED
@@ -1,27 +1,203 @@
1
- """Serve the checkout for the interactive examples and browser fixtures."""
1
+ """The local server for a world's built page and for the engine's examples and browser fixtures.
2
2
 
3
+ python3 scripts/serve.py [port] serve the current folder (port 0: any free port, printed on the first line)
4
+
5
+ It serves the current folder's files, gzipped when the client accepts it, each checked afresh on every load. An address of
6
+ the page that is no file (`location/harbour`, with no dot in its last part) is sent back to the page as `?r=<address>`, the
7
+ same as the published site's 404 page (`scripts/site.mjs`): to the nearest folder above it that holds an `index.html`, so a
8
+ second build served from a subfolder (a worktree, a published base such as `/world/`) keeps its own page.
9
+
10
+ Environment, all optional:
11
+ SERVE_ROUTE_PARAM the query parameter a page reads its address from (default `r`; empty: no fallback, a plain 404)
12
+ SERVE_ENTRY=<query> send every request for the page itself to `/?<query>`, whatever address was asked for, and keep
13
+ nothing in the browser's cache: the iOS Simulator's browser (`tools/ios-sim.sh`) restores its last
14
+ tab without asking the server and cannot be handed an address without a tap
15
+ SERVE_STAMP under SERVE_ENTRY, the page's script addresses not named by their contents, comma-separated, that are
16
+ given a `?v=<start time>` so a restored tab cannot run another build's copy
17
+ (default `./app/main.js,./app/worker.js`)
18
+ """
19
+
20
+ import gzip
21
+ import os
3
22
  import sys
23
+ import threading
24
+ import time
4
25
  from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
26
+ from pathlib import Path
27
+ from urllib.parse import quote, urlsplit
28
+
29
+ ROUTE_PARAM = os.environ.get("SERVE_ROUTE_PARAM", "r")
30
+ ENTRY = os.environ.get("SERVE_ENTRY", "")
31
+ UNSTAMPED = tuple(
32
+ f'"{name.strip()}"'.encode() for name in os.environ.get("SERVE_STAMP", "./app/main.js,./app/worker.js").split(",") if name.strip()
33
+ )
34
+ STAMP = str(int(time.time())).encode()
35
+ GZIP_EXTENSIONS = {
36
+ ".cjs",
37
+ ".css",
38
+ ".htm",
39
+ ".html",
40
+ ".js",
41
+ ".json",
42
+ ".md",
43
+ ".mjs",
44
+ ".svg",
45
+ ".txt",
46
+ ".webmanifest",
47
+ ".xml",
48
+ ".yaml",
49
+ ".yml",
50
+ }
51
+ GZIP_CACHE_LIMIT = 512
52
+ _gzip_cache = {}
53
+ _gzip_lock = threading.Lock()
54
+
55
+
56
+ def client_accepts_gzip(header_value):
57
+ """Return True when an Accept-Encoding header permits gzip (excluding q=0)."""
58
+ if not header_value:
59
+ return False
60
+ for item in header_value.split(","):
61
+ parts = [part.strip() for part in item.split(";")]
62
+ if parts[0].lower() not in ("gzip", "x-gzip"):
63
+ continue
64
+ for param in parts[1:]:
65
+ if param.lower().startswith("q="):
66
+ try:
67
+ if float(param[2:]) <= 0:
68
+ return False
69
+ except ValueError:
70
+ pass
71
+ return True
72
+ return False
5
73
 
6
74
 
7
- class ExampleServer(ThreadingHTTPServer):
8
- # ES modules fan out into parallel requests on a cold browser load.
9
- request_queue_size = 128
75
+ def is_compressible_file(file_path):
76
+ name = os.path.basename(file_path)
77
+ return os.path.splitext(name)[1].lower() in GZIP_EXTENSIONS or name == "LICENSE"
78
+
79
+
80
+ def stamped(page):
81
+ for name in UNSTAMPED:
82
+ page = page.replace(name, name[:-1] + b"?v=" + STAMP + b'"')
83
+ return page
84
+
85
+
86
+ def gzip_bytes_for(file_path, stat_result):
87
+ key = (file_path, stat_result.st_mtime_ns, stat_result.st_size)
88
+ with _gzip_lock:
89
+ cached = _gzip_cache.get(key)
90
+ if cached is not None:
91
+ return cached
92
+ content = Path(file_path).read_bytes()
93
+ if ENTRY and os.path.basename(file_path) == "index.html":
94
+ content = stamped(content)
95
+ compressed = gzip.compress(content, compresslevel=6)
96
+ with _gzip_lock:
97
+ if len(_gzip_cache) >= GZIP_CACHE_LIMIT:
98
+ _gzip_cache.clear()
99
+ _gzip_cache[key] = compressed
100
+ return compressed
10
101
 
11
102
 
12
103
  class Handler(SimpleHTTPRequestHandler):
13
- protocol_version = "HTTP/1.1"
104
+ protocol_version = "HTTP/1.1" # connections are kept and reused: a page asks for about a hundred script parts at once
105
+
106
+ def end_headers(self):
107
+ # Every file is checked afresh on each load: a build replaces its scripts while the browser may still hold an old
108
+ # entry script, which would ask for parts the new build no longer has and leave the page at its loading screen.
109
+ self.send_header("Cache-Control", "no-store" if ENTRY else "no-cache")
110
+ super().end_headers()
111
+
112
+ def redirect(self, location):
113
+ self.send_response(302)
114
+ self.send_header("Location", location)
115
+ self.send_header("Content-Length", "0")
116
+ self.end_headers()
117
+
118
+ def page_home(self, path):
119
+ """The nearest folder at or above an address that holds an index.html, as an address ending in '/'."""
120
+ parts = path.strip("/").split("/")[:-1]
121
+ while parts:
122
+ home = "/" + "/".join(parts) + "/"
123
+ if os.path.isfile(os.path.join(self.translate_path(home), "index.html")):
124
+ return home
125
+ parts.pop()
126
+ return "/"
127
+
128
+ def _serve_request(self, send_body):
129
+ asked = urlsplit(self.path)
130
+ path = asked.path
131
+ last = path.rstrip("/").rsplit("/", 1)[-1]
132
+ if ENTRY and path in ("/", "/index.html") and asked.query != ENTRY:
133
+ self.redirect("/?" + ENTRY)
134
+ return
135
+ fs_path = self.translate_path(path)
136
+ if ROUTE_PARAM and last and "." not in last and not os.path.exists(fs_path):
137
+ home = self.page_home(path)
138
+ self.redirect(home + "?" + ROUTE_PARAM + "=" + quote(path[len(home) :].rstrip("/"), safe="/"))
139
+ return
140
+
141
+ target = fs_path
142
+ if os.path.isdir(target):
143
+ if not path.endswith("/"):
144
+ super().do_GET() if send_body else super().do_HEAD()
145
+ return
146
+ for index_name in ("index.html", "index.htm"):
147
+ candidate = os.path.join(target, index_name)
148
+ if os.path.isfile(candidate):
149
+ target = candidate
150
+ break
151
+
152
+ if (
153
+ os.path.isfile(target)
154
+ and "Range" not in self.headers
155
+ and is_compressible_file(target)
156
+ and client_accepts_gzip(self.headers.get("Accept-Encoding", ""))
157
+ ):
158
+ try:
159
+ stat_result = os.stat(target)
160
+ payload = gzip_bytes_for(target, stat_result)
161
+ except OSError:
162
+ self.send_error(404, "File not found")
163
+ return
164
+ self.send_response(200)
165
+ self.send_header("Content-type", self.guess_type(target))
166
+ self.send_header("Content-Encoding", "gzip")
167
+ self.send_header("Vary", "Accept-Encoding")
168
+ self.send_header("Content-Length", str(len(payload)))
169
+ self.send_header("Last-Modified", self.date_time_string(stat_result.st_mtime))
170
+ self.end_headers()
171
+ if send_body:
172
+ self.wfile.write(payload)
173
+ return
174
+
175
+ super().do_GET() if send_body else super().do_HEAD()
176
+
177
+ def do_GET(self):
178
+ self._serve_request(send_body=True)
179
+
180
+ def do_HEAD(self):
181
+ self._serve_request(send_body=False)
182
+
183
+
184
+ class Server(ThreadingHTTPServer):
185
+ # Connections waiting to be accepted: the default of 5 refused some of a page's parts when they were all asked for at
186
+ # once on a busy machine, and a page whose script part never arrives stays at its loading screen with no error.
187
+ request_queue_size = 256
188
+ daemon_threads = True
14
189
 
15
190
 
16
191
  if __name__ == "__main__":
17
192
  port = int(sys.argv[1]) if len(sys.argv) > 1 else 8080
18
- with ExampleServer(("127.0.0.1", port), Handler) as server:
19
- print(f"Serving Roamwright on port {server.server_port}", flush=True)
193
+ with Server(("127.0.0.1", port), Handler) as server:
20
194
  root = f"http://127.0.0.1:{server.server_port}/"
21
- print(f"All examples: {root}", flush=True)
22
- print(f"A small world: {root}examples/small-world.html?seed=42", flush=True)
23
- print(f"Alpine viaduct: {root}examples/viaduct.html?seed=42", flush=True)
24
- print(f"Island: {root}examples/island.html?seed=42", flush=True)
195
+ print(f"Serving Roamwright on port {server.server_port}", flush=True)
196
+ if os.path.isfile("examples/index.html"):
197
+ print(f"All examples: {root}", flush=True)
198
+ print(f"A small world: {root}examples/small-world.html?seed=42", flush=True)
199
+ print(f"Alpine viaduct: {root}examples/viaduct.html?seed=42", flush=True)
200
+ print(f"Island: {root}examples/island.html?seed=42", flush=True)
25
201
  try:
26
202
  server.serve_forever()
27
203
  except KeyboardInterrupt:
package/scripts/world.mk CHANGED
@@ -2,6 +2,8 @@
2
2
  # Consumer Makefiles set any world-specific variables (PORT, ROAMWRIGHT, CLEAN_PATHS) and include this file.
3
3
 
4
4
  PORT ?= 8765
5
+ # The engine's scripts folder, wherever this file was included from (an installed package or an embedded engine worktree).
6
+ ROAMWRIGHT_SCRIPTS := $(abspath $(dir $(lastword $(MAKEFILE_LIST))))
5
7
  PYTHON := $(if $(wildcard .venv/bin/python),.venv/bin/python,python3)
6
8
  LOCAL_ROAMWRIGHT := $(if $(wildcard roamwright/package.json),$(CURDIR)/roamwright,)
7
9
  ACTIVE_ROAMWRIGHT := $(if $(strip $(ROAMWRIGHT)),$(ROAMWRIGHT),$(LOCAL_ROAMWRIGHT))
@@ -39,7 +41,7 @@ deps: node_modules/.roamwright-installed .venv/.uv-synced
39
41
  @git config core.hooksPath .githooks 2>/dev/null || true
40
42
 
41
43
  dev-engine: deps-base
42
- @ROAMWRIGHT="$(ACTIVE_ROAMWRIGHT)" $(PYTHON) scripts/dev-engine.py
44
+ @ROAMWRIGHT="$(ACTIVE_ROAMWRIGHT)" $(PYTHON) $(ROAMWRIGHT_SCRIPTS)/dev-engine.py
43
45
 
44
46
  check:
45
47
  @sh scripts/check.sh