roamwright 0.61.15 → 0.61.17

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.
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Timed "way back" return offer after fast travel: remembers the visitor's prior spot, shows a
3
+ * temporary button when the journey moved farther than `nearDistance`, and invokes `onReturn(spot)`
4
+ * when clicked. Worker-safe: DOM button and timers enter via parameters.
5
+ * @module
6
+ */
7
+
8
+ /**
9
+ * Creates a timed way-back offer controller.
10
+ *
11
+ * @param {object} options
12
+ * @param {() => HTMLElement | null} options.getButton Returns the way-back button element.
13
+ * @param {() => boolean} [options.canReturn] Returns true when returning is currently permitted (e.g. play mode).
14
+ * @param {(spot: object) => void} options.onReturn Executes the return journey to `spot`.
15
+ * @param {number} [options.nearDistance=60] Metres within which a journey on the same land offers no way back.
16
+ * @param {number} [options.offerSeconds=5] Seconds the offer button remains shown.
17
+ * @param {number} [options.fadeMs=600] Fade-out transition time in milliseconds before hiding the button.
18
+ * @param {object} [options.host=globalThis] Host exposing `setTimeout`, `clearTimeout`, `requestAnimationFrame`.
19
+ * @returns {{ offer: (from: { land: string, x: number, z: number } | null, land: string, x: number, z: number) => void,
20
+ * hide: () => void, trigger: () => void, bind: () => () => void }}
21
+ */
22
+ export function createWayBack({
23
+ getButton,
24
+ canReturn = () => true,
25
+ onReturn,
26
+ nearDistance = 60,
27
+ offerSeconds = 5,
28
+ fadeMs = 600,
29
+ host = globalThis,
30
+ }) {
31
+ let offered = null;
32
+ let timer = 0;
33
+
34
+ function hide() {
35
+ host.clearTimeout(timer);
36
+ const button = getButton();
37
+ if (!button) return;
38
+ button.classList.remove('show');
39
+ timer = host.setTimeout(() => {
40
+ button.hidden = true;
41
+ }, fadeMs);
42
+ }
43
+
44
+ function offer(from, land, x, z) {
45
+ if (!from || (from.land === land && Math.hypot(from.x - x, from.z - z) < nearDistance)) return;
46
+ offered = from;
47
+ host.clearTimeout(timer);
48
+ const button = getButton();
49
+ if (!button) return;
50
+ button.hidden = false;
51
+ host.requestAnimationFrame(() => button.classList.add('show'));
52
+ timer = host.setTimeout(hide, offerSeconds * 1000);
53
+ }
54
+
55
+ function trigger() {
56
+ const at = offered;
57
+ offered = null;
58
+ hide();
59
+ if (!at || !canReturn()) return;
60
+ onReturn(at);
61
+ }
62
+
63
+ function bind() {
64
+ const button = getButton();
65
+ if (!button?.addEventListener) return () => {};
66
+ button.addEventListener('click', trigger);
67
+ return () => button.removeEventListener('click', trigger);
68
+ }
69
+
70
+ return { offer, hide, trigger, bind };
71
+ }
@@ -0,0 +1,210 @@
1
+ /**
2
+ * Pure geographic whereabouts calculation: compass bearings, human-readable distance rounding,
3
+ * place-of-note resolution within cities, districts, landmarks, and regions, and directional
4
+ * descriptions ("340 m north-east of …"). Zero per-frame allocations. Worker-safe.
5
+ * @module
6
+ */
7
+
8
+ /**
9
+ * Eight compass point names clockwise from north (`-z`).
10
+ * @type {ReadonlyArray<string>}
11
+ */
12
+ export const COMPASS_CARDINALS = Object.freeze(['north', 'north-east', 'east', 'south-east', 'south', 'south-west', 'west', 'north-west']);
13
+
14
+ /**
15
+ * Default whereabouts parameters by location kind: reach radius (metres), priority weight,
16
+ * whether distances may be reported from this kind, and compass-strip marking range (metres).
17
+ * @type {Readonly<Record<string, { reach: number, weight: number, from: boolean, marked: number }>>}
18
+ */
19
+ export const DEFAULT_PLACE_KINDS = Object.freeze({
20
+ city: { reach: 420, weight: 3, from: true, marked: 8000 },
21
+ district: { reach: 250, weight: 1, from: false, marked: 0 },
22
+ landmark: { reach: 130, weight: 1, from: true, marked: 1500 },
23
+ });
24
+
25
+ /**
26
+ * Compass bearing in degrees `[0, 360)` from north (`-z`) clockwise through east (`+x`).
27
+ *
28
+ * @param {number} dx East-west delta in metres.
29
+ * @param {number} dz North-south delta in metres (`-z` is north).
30
+ * @returns {number} Bearing in degrees `[0, 360)`.
31
+ */
32
+ export function bearingOf(dx, dz) {
33
+ const b = (Math.atan2(dx, -dz) * 180) / Math.PI;
34
+ return b < 0 ? b + 360 : b;
35
+ }
36
+
37
+ /**
38
+ * Rounds a distance in metres to clean display steps (tens of metres under 1 km,
39
+ * tenths of a kilometre under 10 km, whole kilometres beyond).
40
+ *
41
+ * @param {number} d Distance in metres.
42
+ * @returns {number} Rounded distance in metres.
43
+ */
44
+ export function roundedDistance(d) {
45
+ return d < 995 ? Math.round(d / 10) * 10 : d < 9950 ? Math.round(d / 100) * 100 : Math.round(d / 1000) * 1000;
46
+ }
47
+
48
+ /**
49
+ * Formats a rounded distance in metres as text (`'340 m'`, `'1.4 km'`, `'12 km'`).
50
+ *
51
+ * @param {number} m Rounded distance in metres.
52
+ * @returns {string}
53
+ */
54
+ export function distanceText(m) {
55
+ return m < 1000 ? `${m} m` : m < 10000 ? `${(m / 1000).toFixed(1)} km` : `${m / 1000} km`;
56
+ }
57
+
58
+ /**
59
+ * Adjusts a place name for mid-sentence use by lowercasing a leading `'The '`.
60
+ *
61
+ * @param {string} name
62
+ * @returns {string}
63
+ */
64
+ export function inSentence(name) {
65
+ return name.startsWith('The ') ? 'the' + name.slice(3) : name;
66
+ }
67
+
68
+ /**
69
+ * Creates a zero-allocation whereabouts tracker for a world of lands and spaces.
70
+ *
71
+ * @param {object} options
72
+ * @param {() => ReadonlyArray<object>} options.getLocations Returns all world locations.
73
+ * @param {() => { id: string, flyable?: boolean, name?: string, origin?: { x: number, z: number } }} options.getSpace Returns the active space.
74
+ * @param {Record<string, { reach: number, weight: number, from: boolean, marked: number }>} [options.kinds=DEFAULT_PLACE_KINDS]
75
+ * @param {(x: number, z: number, space: object) => string | null} [options.customPlaceName] Optional override returning a custom place name for a land (return null to use default location lookup).
76
+ * @param {(loc: object) => boolean} [options.isExcludedAnchor] Return true to skip a location as a "distance from" anchor.
77
+ * @param {number} [options.regionReach=1800] Maximum metres from a region centre within which it is named.
78
+ * @param {string} [options.defaultSpaceId='world'] Space id assumed when `loc.space` is omitted.
79
+ * @param {ReadonlyArray<string>} [options.points=COMPASS_CARDINALS] Eight compass direction names clockwise from north.
80
+ * @returns {{ kindOf: (loc: object) => object | null, placeAt: { x: number, z: number }, placeOf: (loc: object) => boolean,
81
+ * landPlaceName: (x: number, z: number) => string, placeName: (x: number, z: number) => string,
82
+ * where: { name: string, way: string, loc: object | null, m: number, point: number },
83
+ * update: (x: number, z: number) => boolean }}
84
+ */
85
+ export function createWhereabouts({
86
+ getLocations,
87
+ getSpace,
88
+ kinds = DEFAULT_PLACE_KINDS,
89
+ customPlaceName,
90
+ isExcludedAnchor = () => false,
91
+ regionReach = 1800,
92
+ defaultSpaceId = 'world',
93
+ points = COMPASS_CARDINALS,
94
+ }) {
95
+ const kindOf = loc => kinds[loc.kind] ?? null;
96
+ const placeAt = { x: 0, z: 0 };
97
+ const anchor = { loc: null, d: 0, b: 0, at: false };
98
+ const where = { name: '', way: '', loc: null, m: 0, point: 0 };
99
+
100
+ function placeOf(loc) {
101
+ const sp = getSpace();
102
+ if ((loc.space ?? defaultSpaceId) !== sp.id) return false;
103
+ if (sp.flyable) {
104
+ if (loc.x === undefined) return false;
105
+ placeAt.x = loc.x;
106
+ placeAt.z = loc.z;
107
+ return true;
108
+ }
109
+ if (!loc.off || !sp.origin) return false;
110
+ placeAt.x = sp.origin.x + loc.off[0];
111
+ placeAt.z = sp.origin.z + loc.off[1];
112
+ return true;
113
+ }
114
+
115
+ function landPlaceName(x, z) {
116
+ const locations = getLocations();
117
+ const sp = getSpace();
118
+ let city = null;
119
+ let cityD = 1;
120
+ let place = null;
121
+ let placeD = 1;
122
+ let region = null;
123
+ let regionD = regionReach;
124
+ let land = '';
125
+ for (let i = 0; i < locations.length; i++) {
126
+ const loc = locations[i];
127
+ if (!placeOf(loc)) continue;
128
+ const d = Math.sqrt((placeAt.x - x) ** 2 + (placeAt.z - z) ** 2);
129
+ if (loc.kind === 'region') {
130
+ if (loc.id === sp.id) land = loc.name;
131
+ else if (d < regionD) {
132
+ regionD = d;
133
+ region = loc;
134
+ }
135
+ continue;
136
+ }
137
+ const K = kindOf(loc);
138
+ if (!K || !K.reach) continue;
139
+ const share = d / K.reach;
140
+ if (loc.kind === 'city') {
141
+ if (share < cityD) {
142
+ cityD = share;
143
+ city = loc;
144
+ }
145
+ } else if (share < placeD) {
146
+ placeD = share;
147
+ place = loc;
148
+ }
149
+ }
150
+ if (city) return place ? `${city.name} · ${place.name}` : city.name;
151
+ return place?.name ?? region?.name ?? land;
152
+ }
153
+
154
+ function placeName(x, z) {
155
+ const sp = getSpace();
156
+ if (customPlaceName) {
157
+ const custom = customPlaceName(x, z, sp);
158
+ if (custom !== null && custom !== undefined) return custom;
159
+ }
160
+ if (!sp.flyable) return sp.name ?? '';
161
+ return landPlaceName(x, z);
162
+ }
163
+
164
+ function findAnchor(x, z, name) {
165
+ const locations = getLocations();
166
+ anchor.loc = null;
167
+ anchor.at = false;
168
+ let best = Infinity;
169
+ for (let i = 0; i < locations.length; i++) {
170
+ const loc = locations[i];
171
+ const K = kindOf(loc);
172
+ if (!K || !K.from || !placeOf(loc) || isExcludedAnchor(loc)) continue;
173
+ const dx = x - placeAt.x;
174
+ const dz = z - placeAt.z;
175
+ const d = Math.sqrt(dx * dx + dz * dz);
176
+ if (d < K.reach && (loc.kind !== 'city' || name.includes(loc.name))) anchor.at = true;
177
+ if (d / K.weight < best) {
178
+ best = d / K.weight;
179
+ anchor.loc = loc;
180
+ anchor.d = d;
181
+ anchor.b = bearingOf(dx, dz);
182
+ }
183
+ }
184
+ }
185
+
186
+ function update(x, z) {
187
+ const sp = getSpace();
188
+ const name = placeName(x, z);
189
+ let loc = null;
190
+ let m = 0;
191
+ let point = 0;
192
+ if (sp.flyable && name) {
193
+ findAnchor(x, z, name);
194
+ if (!anchor.at && anchor.loc) {
195
+ loc = anchor.loc;
196
+ m = roundedDistance(anchor.d);
197
+ point = Math.round(anchor.b / 45) % 8;
198
+ }
199
+ }
200
+ if (name === where.name && loc === where.loc && m === where.m && point === where.point) return false;
201
+ where.name = name;
202
+ where.loc = loc;
203
+ where.m = m;
204
+ where.point = point;
205
+ where.way = loc ? `${distanceText(m)} ${points[point]} of ${inSentence(loc.name)}` : '';
206
+ return true;
207
+ }
208
+
209
+ return { kindOf, placeAt, placeOf, landPlaceName, placeName, where, update };
210
+ }
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Generic first-person world input bindings: touch virtual joystick + look drag + tap picking,
3
+ * mouse drag + Pointer Lock with release cooldown + double-click escape, keyboard movement key
4
+ * tracking with double-Space flight toggle, and press-and-hold vertical flight buttons.
5
+ * Worker-safe: all DOM targets and browser hosts enter via parameters.
6
+ * @module
7
+ */
8
+
9
+ const DEFAULT_TAP = Object.freeze({ ms: 300, px: 10 });
10
+ const DEFAULT_DOUBLE = Object.freeze({ ms: 350, px: 8 });
11
+ const DEFAULT_LOCK_COOLDOWN_MS = 1600;
12
+ const DEFAULT_DOUBLE_SPACE_MS = 320;
13
+ const DEFAULT_JOY_RADIUS = 50;
14
+
15
+ /**
16
+ * Binds touch, mouse, pointer-lock, and keyboard movement controls for exploring a 3D world.
17
+ * World-specific hotkeys remain in the caller's `onKeyDown` callback.
18
+ *
19
+ * @param {object} options
20
+ * @param {HTMLElement} options.canvas Primary world canvas receiving pointer events.
21
+ * @param {Set<string>} options.keys Mutable set of currently pressed `KeyboardEvent.code` values.
22
+ * @param {object} options.pad Mutable pointer/joystick pad state (`joyId`, `lookId`, `x0`, `y0`, `x`, `y`, `up`, `lx`, `ly`, `downX`, `downY`, `downT`, `joyT`, `mouseDown`, `lockFail`).
23
+ * @param {() => boolean} options.isPlaying Returns true when world movement/look input is active.
24
+ * @param {(dx: number, dy: number, sensitivity: number) => void} options.look Applies look delta to the camera/player.
25
+ * @param {(x: number, y: number) => void} [options.onTap] Called on tap or unlocked/locked click on the world.
26
+ * @param {() => void} [options.onDoubleClick] Called on a left-button mouse double-click on the world.
27
+ * @param {(event: KeyboardEvent) => boolean | void} [options.onKeyDown] World-specific key handler; return `true` if handled (suppresses default key insertion).
28
+ * @param {(event: KeyboardEvent) => void} [options.onAfterKeyDown] Called after `keys.add(e.code)` for world shortcuts.
29
+ * @param {() => boolean} [options.canDoubleSpace] Returns true when double-pressing Space should call `onDoubleSpace`.
30
+ * @param {() => void} [options.onDoubleSpace] Called on rapid double-press of Space (e.g. take off / land).
31
+ * @param {(event: PointerEvent) => boolean} [options.isDoubleClickTarget] Tests whether a pointerdown target participates in double-click escape (defaults to `e.target === canvas`).
32
+ * @param {(locked: boolean) => void} [options.onPointerLockChange] Called when canvas pointer lock toggles.
33
+ * @param {(event: PointerEvent) => { x: number, y: number }} [options.pointerPoint] Event coordinates in the stage frame.
34
+ * @param {() => { width: number, height: number }} [options.viewportSize] Live stage dimensions in CSS pixels.
35
+ * @param {{ container?: HTMLElement | null, knob?: HTMLElement | null, hint?: HTMLElement | null, maxRadius?: number }} [options.joystick]
36
+ * @param {{ up?: HTMLElement | null, down?: HTMLElement | null }} [options.flyButtons]
37
+ * @param {{ ms: number, px: number }} [options.tap]
38
+ * @param {{ ms: number, px: number }} [options.doubleClick]
39
+ * @param {number} [options.lockCooldownMs=1600]
40
+ * @param {number} [options.doubleSpaceMs=320]
41
+ * @param {object} [options.host=globalThis]
42
+ * @returns {{ dispose: () => void, resetDoubleSpace: () => void }}
43
+ */
44
+ export function createWorldControls({
45
+ canvas,
46
+ keys,
47
+ pad,
48
+ isPlaying,
49
+ look,
50
+ onTap = () => {},
51
+ onDoubleClick = () => {},
52
+ onKeyDown,
53
+ onAfterKeyDown,
54
+ canDoubleSpace = () => false,
55
+ onDoubleSpace,
56
+ isDoubleClickTarget = e => e.target === canvas,
57
+ onPointerLockChange = () => {},
58
+ pointerPoint = e => ({ x: e.clientX, y: e.clientY }),
59
+ viewportSize = () => ({ width: canvas.clientWidth || 1, height: canvas.clientHeight || 1 }),
60
+ joystick = {},
61
+ flyButtons = {},
62
+ tap = DEFAULT_TAP,
63
+ doubleClick = DEFAULT_DOUBLE,
64
+ lockCooldownMs = DEFAULT_LOCK_COOLDOWN_MS,
65
+ doubleSpaceMs = DEFAULT_DOUBLE_SPACE_MS,
66
+ host = globalThis,
67
+ }) {
68
+ const win = host.window ?? host;
69
+ const doc = host.document;
70
+ const perf = host.performance ?? globalThis.performance;
71
+ const joyMax = joystick.maxRadius ?? DEFAULT_JOY_RADIUS;
72
+ const cleanups = [];
73
+
74
+ let spaceAt = -Infinity;
75
+ let lockFreed = -1e9;
76
+ const lastClick = { t: -1e9, x: 0, y: 0 };
77
+
78
+ const on = (target, type, fn, opts) => {
79
+ if (!target?.addEventListener) return;
80
+ target.addEventListener(type, fn, opts);
81
+ cleanups.push(() => target.removeEventListener(type, fn, opts));
82
+ };
83
+
84
+ const isTap = (pt, t, x, y) => perf.now() - t < tap.ms && Math.hypot(pt.x - x, pt.y - y) < tap.px;
85
+
86
+ function lockRefused() {
87
+ if (perf.now() - lockFreed > lockCooldownMs) pad.lockFail = true;
88
+ }
89
+
90
+ function noteClick(e) {
91
+ if (e.pointerType !== 'mouse' || e.button !== 0) return;
92
+ if (!isDoubleClickTarget(e)) return;
93
+ const pt = pointerPoint(e);
94
+ const locked = doc?.pointerLockElement === canvas;
95
+ const near = locked || Math.hypot(pt.x - lastClick.x, pt.y - lastClick.y) < doubleClick.px;
96
+ if (perf.now() - lastClick.t < doubleClick.ms && near) {
97
+ lastClick.t = -1e9;
98
+ onDoubleClick();
99
+ e.stopPropagation();
100
+ return;
101
+ }
102
+ lastClick.t = perf.now();
103
+ lastClick.x = pt.x;
104
+ lastClick.y = pt.y;
105
+ }
106
+
107
+ on(win, 'keydown', e => {
108
+ if (onKeyDown?.(e) === true) return;
109
+ keys.add(e.code);
110
+ if (e.code === 'Space' || e.code.startsWith('Arrow')) e.preventDefault();
111
+ if (e.code === 'Space' && onDoubleSpace && canDoubleSpace()) {
112
+ if (e.timeStamp - spaceAt < doubleSpaceMs) {
113
+ spaceAt = -Infinity;
114
+ onDoubleSpace(e);
115
+ } else {
116
+ spaceAt = e.timeStamp;
117
+ }
118
+ }
119
+ onAfterKeyDown?.(e);
120
+ });
121
+ on(win, 'keyup', e => keys.delete(e.code));
122
+ on(win, 'pointerdown', noteClick, true);
123
+ on(win, 'blur', () => keys.clear());
124
+ on(canvas, 'contextmenu', e => e.preventDefault());
125
+
126
+ on(canvas, 'pointerdown', e => {
127
+ if (!isPlaying()) return;
128
+ const pt = pointerPoint(e);
129
+ const vp = viewportSize();
130
+ if (e.pointerType === 'touch') {
131
+ if (pad.joyId < 0 && pt.x < vp.width * 0.42 && pt.y > vp.height * 0.32) {
132
+ pad.joyId = e.pointerId;
133
+ pad.x0 = pt.x;
134
+ pad.y0 = pt.y;
135
+ pad.x = pad.y = 0;
136
+ pad.joyT = perf.now();
137
+ if (joystick.container) {
138
+ joystick.container.hidden = false;
139
+ joystick.container.style.left = pt.x + 'px';
140
+ joystick.container.style.top = pt.y + 'px';
141
+ }
142
+ if (joystick.knob) joystick.knob.style.transform = '';
143
+ if (joystick.hint) joystick.hint.style.display = 'none';
144
+ } else if (pad.lookId < 0) {
145
+ pad.lookId = e.pointerId;
146
+ pad.lx = pt.x;
147
+ pad.ly = pt.y;
148
+ pad.downX = pt.x;
149
+ pad.downY = pt.y;
150
+ pad.downT = perf.now();
151
+ }
152
+ try {
153
+ canvas.setPointerCapture(e.pointerId);
154
+ } catch {}
155
+ } else {
156
+ pad.mouseDown = true;
157
+ pad.lx = pt.x;
158
+ pad.ly = pt.y;
159
+ pad.downX = pt.x;
160
+ pad.downY = pt.y;
161
+ pad.downT = perf.now();
162
+ if (doc?.pointerLockElement === canvas) {
163
+ onTap(vp.width / 2, vp.height / 2);
164
+ } else if (!pad.lockFail && canvas.requestPointerLock) {
165
+ try {
166
+ const p = canvas.requestPointerLock();
167
+ if (p && p.catch) p.catch(lockRefused);
168
+ } catch {
169
+ lockRefused();
170
+ }
171
+ }
172
+ }
173
+ });
174
+
175
+ on(canvas, 'pointermove', e => {
176
+ const pt = pointerPoint(e);
177
+ if (e.pointerType === 'touch') {
178
+ if (e.pointerId === pad.joyId) {
179
+ let dx = pt.x - pad.x0;
180
+ let dy = pt.y - pad.y0;
181
+ const len = Math.hypot(dx, dy);
182
+ if (len > joyMax) {
183
+ dx *= joyMax / len;
184
+ dy *= joyMax / len;
185
+ }
186
+ pad.x = dx / joyMax;
187
+ pad.y = dy / joyMax;
188
+ if (joystick.knob) joystick.knob.style.transform = `translate(${dx}px,${dy}px)`;
189
+ } else if (e.pointerId === pad.lookId) {
190
+ if (isPlaying()) look(pt.x - pad.lx, pt.y - pad.ly, 0.0052);
191
+ pad.lx = pt.x;
192
+ pad.ly = pt.y;
193
+ }
194
+ } else if (isPlaying()) {
195
+ if (doc?.pointerLockElement === canvas) {
196
+ look(e.movementX, e.movementY, 0.0023);
197
+ } else if (pad.mouseDown) {
198
+ look(pt.x - pad.lx, pt.y - pad.ly, 0.0042);
199
+ pad.lx = pt.x;
200
+ pad.ly = pt.y;
201
+ }
202
+ }
203
+ });
204
+
205
+ const end = e => {
206
+ const pt = pointerPoint(e);
207
+ if (e.pointerType === 'touch') {
208
+ if (e.pointerId === pad.joyId) {
209
+ pad.joyId = -1;
210
+ pad.x = pad.y = 0;
211
+ if (joystick.container) joystick.container.hidden = true;
212
+ if (isTap(pt, pad.joyT, pad.x0, pad.y0)) onTap(pt.x, pt.y);
213
+ } else if (e.pointerId === pad.lookId) {
214
+ pad.lookId = -1;
215
+ if (isTap(pt, pad.downT, pad.downX, pad.downY)) onTap(pt.x, pt.y);
216
+ }
217
+ } else {
218
+ if (
219
+ pad.mouseDown &&
220
+ doc?.pointerLockElement !== canvas &&
221
+ perf.now() - pad.downT < tap.ms &&
222
+ Math.hypot(pt.x - pad.downX, pt.y - pad.downY) < 6 &&
223
+ pad.lockFail
224
+ ) {
225
+ onTap(pt.x, pt.y);
226
+ }
227
+ pad.mouseDown = false;
228
+ }
229
+ };
230
+ on(canvas, 'pointerup', end);
231
+ on(canvas, 'pointercancel', end);
232
+
233
+ on(doc, 'pointerlockchange', () => {
234
+ const locked = doc.pointerLockElement === canvas;
235
+ onPointerLockChange(locked);
236
+ if (!doc.pointerLockElement) lockFreed = perf.now();
237
+ });
238
+ on(doc, 'pointerlockerror', lockRefused);
239
+
240
+ const bindHold = (el, value) => {
241
+ if (!el) return;
242
+ on(el, 'pointerdown', e => {
243
+ pad.up = value;
244
+ e.preventDefault();
245
+ });
246
+ const release = () => {
247
+ pad.up = 0;
248
+ };
249
+ on(el, 'pointerup', release);
250
+ on(el, 'pointerleave', release);
251
+ on(el, 'pointercancel', release);
252
+ };
253
+ bindHold(flyButtons.up, 1);
254
+ bindHold(flyButtons.down, -1);
255
+
256
+ return {
257
+ resetDoubleSpace() {
258
+ spaceAt = -Infinity;
259
+ },
260
+ dispose() {
261
+ for (const off of cleanups) off();
262
+ cleanups.length = 0;
263
+ },
264
+ };
265
+ }
@@ -204,10 +204,19 @@ function settleHerdBeastInPage({ debug, crowdIndex, memberIndex, hour }) {
204
204
  *
205
205
  * @param {{ debug: string, actorId: string, hour: number | null }} arg
206
206
  */
207
+ // When a scene's script first shows an actor (a `[seconds, 'show', actorId]` step of its `steps`), or null if it never does.
208
+ function sceneShowTimeInPage({ debug, sceneId, actorId }) {
209
+ const ev = window[debug].CONFIG.events.find(e => e.id === sceneId);
210
+ const step = (ev?.steps || ev?.script || []).find(s => Array.isArray(s) && s[1] === 'show' && s[2] === actorId);
211
+ return step ? step[0] : null;
212
+ }
213
+
207
214
  function settleActorInPage({ debug, actorId, hour }) {
208
215
  const app = window[debug];
209
216
  const a = app.actors?.[actorId];
210
217
  if (!a?.group) return null;
218
+ // An actor a scene has not shown yet stands where it was built (the world's origin, under the land): nothing real to frame.
219
+ if (a.active === false) return { hidden: true };
211
220
  const { THREE } = app;
212
221
  if (app.director) app.director.paused = true;
213
222
  app.env.flow = false;
@@ -395,6 +404,13 @@ async function runBeastsNear(
395
404
  actorId,
396
405
  hour: opts.hourExplicit ? opts.hour : null,
397
406
  });
407
+ if (target?.hidden) {
408
+ const shownAt = await page.evaluate(sceneShowTimeInPage, { debug: driver.debug, sceneId: meta.id, actorId });
409
+ throw new Error(
410
+ `${actorId} is not shown at ${targetAt}s of ${meta.id}` +
411
+ (Number.isFinite(shownAt) ? `: it comes on at ${shownAt}s, so ask --at ${Math.ceil(shownAt + 1)} or later` : ''),
412
+ );
413
+ }
398
414
  if (target) {
399
415
  saved.push(
400
416
  ...(await captureTargetViews(page, driver, target, {
@@ -493,6 +509,7 @@ module.exports = {
493
509
  parseBeastsNearArgs,
494
510
  poseCameraAndDrawInPage,
495
511
  runBeastsNear,
512
+ sceneShowTimeInPage,
496
513
  settleActorInPage,
497
514
  settleHerdBeastInPage,
498
515
  };
@@ -1,7 +1,14 @@
1
1
  'use strict';
2
2
  const assert = require('node:assert/strict');
3
3
  const test = require('node:test');
4
- const { frameBeastView, locateHerdBeastInPage, parseBeastsNearArgs, poseCameraAndDrawInPage } = require('./beasts-near.cjs');
4
+ const {
5
+ frameBeastView,
6
+ locateHerdBeastInPage,
7
+ parseBeastsNearArgs,
8
+ poseCameraAndDrawInPage,
9
+ sceneShowTimeInPage,
10
+ settleActorInPage,
11
+ } = require('./beasts-near.cjs');
5
12
 
6
13
  test('parseBeastsNearArgs parses kinds, scene beat options, and flags cleanly', () => {
7
14
  const parsed = parseBeastsNearArgs([
@@ -103,3 +110,31 @@ test('locateHerdBeastInPage and poseCameraAndDrawInPage talk strictly through wi
103
110
  delete globalThis.window;
104
111
  }
105
112
  });
113
+
114
+ test('a scene actor not shown yet is refused, with the second its script shows it', () => {
115
+ const debug = 'BEASTS_TEST';
116
+ globalThis.window = {
117
+ [debug]: {
118
+ actors: { hound: { group: {}, active: false } },
119
+ CONFIG: {
120
+ events: [
121
+ {
122
+ id: 'hunt',
123
+ script: [
124
+ [0, 'hour', 6],
125
+ [12.5, 'show', 'hound'],
126
+ [14, 'show', 'crow'],
127
+ ],
128
+ },
129
+ ],
130
+ },
131
+ },
132
+ };
133
+ try {
134
+ assert.deepEqual(settleActorInPage({ debug, actorId: 'hound', hour: null }), { hidden: true });
135
+ assert.equal(sceneShowTimeInPage({ debug, sceneId: 'hunt', actorId: 'hound' }), 12.5);
136
+ assert.equal(sceneShowTimeInPage({ debug, sceneId: 'hunt', actorId: 'wolf' }), null);
137
+ } finally {
138
+ delete globalThis.window;
139
+ }
140
+ });