roamwright 0.61.16 → 0.61.18

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.
Files changed (49) hide show
  1. package/README.md +25 -24
  2. package/examples/land-features.js +130 -9
  3. package/examples/land.html +2 -1
  4. package/examples/land.js +17 -2
  5. package/examples/ruins.html +3 -2
  6. package/examples/ruins.js +184 -37
  7. package/examples/world-map.html +162 -0
  8. package/examples/world-map.js +475 -0
  9. package/geometry/farm-props.js +59 -0
  10. package/geometry/field-map.js +147 -0
  11. package/geometry/instances.js +40 -0
  12. package/geometry/plant-tuft.js +138 -0
  13. package/geometry/ruins-breach.js +329 -0
  14. package/geometry/ruins-crater.js +269 -0
  15. package/geometry/ruins-masonry.js +323 -0
  16. package/geometry/ruins-walls.js +272 -0
  17. package/geometry/strata-mesa.js +114 -0
  18. package/geometry/strata-rocks.js +73 -2
  19. package/index.js +109 -1
  20. package/package.json +1 -1
  21. package/rendering/contact-shadows.js +56 -0
  22. package/rendering/crowd-lifecycle.js +80 -0
  23. package/rendering/farm-plough.js +145 -0
  24. package/rendering/map-glyphs.js +494 -0
  25. package/rendering/map-input.js +143 -0
  26. package/rendering/map-labels.js +181 -0
  27. package/rendering/map-relief.js +330 -0
  28. package/rendering/map-signs.js +124 -0
  29. package/rendering/place-names.js +408 -0
  30. package/rendering/plant-tuft.js +190 -0
  31. package/rendering/portrait-studio.js +213 -0
  32. package/rendering/ruins-fittings.js +199 -0
  33. package/rendering/ruins-mound.js +103 -0
  34. package/rendering/screen-pick.js +75 -0
  35. package/runtime/build-freshness.js +133 -0
  36. package/runtime/compass-strip.js +232 -0
  37. package/runtime/context-lost.js +108 -0
  38. package/runtime/doorways.js +98 -0
  39. package/runtime/hud-frame.js +74 -0
  40. package/runtime/map-relief.js +236 -0
  41. package/runtime/map-spot.js +120 -0
  42. package/runtime/map-view.js +229 -0
  43. package/runtime/panel-shell.js +90 -0
  44. package/runtime/relation-graph.js +163 -0
  45. package/runtime/stage-frame.js +263 -0
  46. package/runtime/url-router.js +162 -0
  47. package/runtime/way-back.js +71 -0
  48. package/runtime/whereabouts.js +210 -0
  49. package/runtime/world-controls.js +265 -0
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Published build freshness watcher: extracts the content-hashed build id from the running script
3
+ * URL, registers the service worker once settled, polls `version.json`, and renews open tabs
4
+ * without interrupting active exploration (renews immediately on the title screen, or on return
5
+ * from a long background stay; notifies once otherwise). Worker-safe: host enters via parameters.
6
+ * @module
7
+ */
8
+
9
+ /**
10
+ * Extracts a hexadecimal build id from a versioned script URL (`.../app-<hash>/...`).
11
+ * Returns null for local unversioned development builds.
12
+ *
13
+ * @param {string} scriptUrl Running module URL (`import.meta.url`).
14
+ * @param {RegExp} [pattern=/\/app-([0-9a-f]+)\//]
15
+ * @returns {string | null}
16
+ */
17
+ export function extractBuildId(scriptUrl, pattern = /\/app-([0-9a-f]+)\//) {
18
+ try {
19
+ return new URL(scriptUrl).pathname.match(pattern)?.[1] ?? null;
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Starts polling for newer published builds and registering the site's service worker when running
27
+ * from a content-hashed build folder. Does nothing on local builds (`extractBuildId` returns null).
28
+ *
29
+ * @param {object} options
30
+ * @param {string} options.scriptUrl Running script URL (`import.meta.url`).
31
+ * @param {string} options.versionUrl URL of `version.json`.
32
+ * @param {string} [options.serviceWorkerUrl] URL of `sw.js` to register after `workerAfterMs`.
33
+ * @param {string} [options.storageKey='roamwright:renewed'] Session storage key guarding against repeat renewal.
34
+ * @param {() => boolean} options.isInWorld Returns true once the visitor has left the title screen.
35
+ * @param {() => boolean} options.canRenewInWorld Returns true when renewing in-world is safe (play mode, no panel).
36
+ * @param {() => void} options.onRenewInWorld Renews the active world page where the visitor stands.
37
+ * @param {(message: string, seconds: number) => void} [options.onNotify] Shows a toast message.
38
+ * @param {number} [options.askEveryMs=180000] Polling interval in milliseconds.
39
+ * @param {number} [options.awayMs=600000] Background duration in milliseconds after which returning allows in-world renewal.
40
+ * @param {number} [options.workerAfterMs=4000] Delay before registering the service worker.
41
+ * @param {number} [options.warningMs=1500] Delay between toast warning and in-world renewal.
42
+ * @param {number} [options.toldSeconds=7] Duration of the manual-reload notification.
43
+ * @param {object} [options.host=globalThis]
44
+ * @returns {{ build: string | null, ask: (returned?: boolean) => Promise<void>, dispose: () => void }}
45
+ */
46
+ export function watchBuildFreshness({
47
+ scriptUrl,
48
+ versionUrl,
49
+ serviceWorkerUrl,
50
+ storageKey = 'roamwright:renewed',
51
+ isInWorld,
52
+ canRenewInWorld,
53
+ onRenewInWorld,
54
+ onNotify = () => {},
55
+ askEveryMs = 180000,
56
+ awayMs = 600000,
57
+ workerAfterMs = 4000,
58
+ warningMs = 1500,
59
+ toldSeconds = 7,
60
+ host = globalThis,
61
+ }) {
62
+ const build = extractBuildId(scriptUrl);
63
+ const doc = host.document;
64
+ const loc = host.location;
65
+ const storage = host.sessionStorage;
66
+ const nav = host.navigator;
67
+ let newer = null;
68
+ let hiddenAt = 0;
69
+ let told = false;
70
+ let pollTimer = 0;
71
+ let swTimer = 0;
72
+
73
+ function renew(returned) {
74
+ if (!newer || doc?.hidden) return;
75
+ const inWorld = isInWorld();
76
+ if (inWorld && !(returned && canRenewInWorld())) {
77
+ if (!told) onNotify('A newer build of the world is out: reload the page to see it.', toldSeconds);
78
+ told = true;
79
+ return;
80
+ }
81
+ storage?.setItem(storageKey, newer);
82
+ if (!inWorld) {
83
+ const title = new URL(loc.href);
84
+ title.searchParams.set('b', newer);
85
+ loc.replace(title);
86
+ return;
87
+ }
88
+ onNotify('A newer build of the world is out: loading it.', 3);
89
+ host.setTimeout(onRenewInWorld, warningMs);
90
+ }
91
+
92
+ async function ask(returned = false) {
93
+ if (!build || newer) return;
94
+ try {
95
+ const response = await host.fetch(versionUrl, { cache: 'no-store' });
96
+ const current = (await response.json()).build;
97
+ if (!current || current === build || storage?.getItem(storageKey) === current) return;
98
+ newer = current;
99
+ renew(returned);
100
+ } catch {
101
+ // Offline or missing version manifest: try again later.
102
+ }
103
+ }
104
+
105
+ function onVisibility() {
106
+ if (doc.hidden) {
107
+ hiddenAt = Date.now();
108
+ return;
109
+ }
110
+ const returned = hiddenAt > 0 && Date.now() - hiddenAt >= awayMs;
111
+ hiddenAt = 0;
112
+ if (newer) renew(returned);
113
+ else ask(returned);
114
+ }
115
+
116
+ if (build) {
117
+ if (nav?.serviceWorker && serviceWorkerUrl) {
118
+ swTimer = host.setTimeout(() => nav.serviceWorker.register(serviceWorkerUrl).catch(() => {}), workerAfterMs);
119
+ }
120
+ pollTimer = host.setInterval(() => ask(), askEveryMs);
121
+ doc?.addEventListener?.('visibilitychange', onVisibility);
122
+ }
123
+
124
+ return {
125
+ build,
126
+ ask,
127
+ dispose() {
128
+ host.clearTimeout(swTimer);
129
+ host.clearInterval(pollTimer);
130
+ doc?.removeEventListener?.('visibilitychange', onVisibility);
131
+ },
132
+ };
133
+ }
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Scrolling HUD compass strip with bearing-separated landmark marks, waypoint marker, and
3
+ * centre-aligned active mark caption. Zero per-frame allocations once built.
4
+ * Worker-safe: DOM elements enter via parameters.
5
+ * @module
6
+ */
7
+
8
+ /**
9
+ * Eight compass point labels in clockwise order starting at north.
10
+ * @type {ReadonlyArray<string>}
11
+ */
12
+ export const COMPASS_POINTS = Object.freeze(['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']);
13
+
14
+ /**
15
+ * Generates the static HTML markup for a 3-turn scrolling compass strip (0 to 1080 degrees,
16
+ * ticks every 15 degrees, cardinal/intercardinal labels every 45 degrees).
17
+ *
18
+ * @param {object} [options]
19
+ * @param {number} [options.pxPerDeg=2] Horizontal strip scale in CSS pixels per degree.
20
+ * @param {ReadonlyArray<string>} [options.names=COMPASS_POINTS] Eight compass point labels.
21
+ * @returns {string}
22
+ */
23
+ export function compassStripHtml({ pxPerDeg = 2, names = COMPASS_POINTS } = {}) {
24
+ let html = '';
25
+ for (let d = 0; d <= 1080; d += 15) {
26
+ const x = d * pxPerDeg;
27
+ if (d % 45 === 0) {
28
+ const n = names[(d / 45) % 8];
29
+ html += `<span class="${n.length === 1 ? 'c' : ''}${n === 'N' ? ' n' : ''}" style="left:${x}px">${n}</span>`;
30
+ } else {
31
+ html += `<i style="left:${x}px"></i>`;
32
+ }
33
+ }
34
+ return html;
35
+ }
36
+
37
+ /**
38
+ * Creates a zero-allocation HUD compass strip controller.
39
+ *
40
+ * @param {object} options
41
+ * @param {() => HTMLElement} options.getStrip Returns the scrolling strip element.
42
+ * @param {() => HTMLElement} options.getContainer Returns the clipping outer compass element.
43
+ * @param {() => ReadonlyArray<object>} options.getLocations Returns all candidate world locations.
44
+ * @param {() => { x: number, z: number, yaw: number }} options.getCamera Returns current camera X, Z, and Y-axis rotation (radians).
45
+ * @param {() => { pos: { x: number, z: number }, title: string } | null} [options.getWaypoint] Active waypoint in the current space, or null.
46
+ * @param {(loc: object) => { reach: number, weight: number, marked: number } | null} options.kindOf
47
+ * @param {(loc: object, out: { x: number, z: number }) => boolean} options.placeOf Writes `(x, z)` into `out` and returns true if `loc` lies in the active space.
48
+ * @param {(dx: number, dz: number) => number} options.bearingOf Compass bearing in degrees `[0, 360)`.
49
+ * @param {(d: number) => number} options.roundDistance Rounds distance in metres for caption caching.
50
+ * @param {(m: number) => string} options.formatDistance Formats rounded distance in metres.
51
+ * @param {(loc: object) => boolean} [options.isDynamic] Returns true if `loc` moves each frame (for example a drifting fortress).
52
+ * @param {number} [options.pxPerDeg=2]
53
+ * @param {number} [options.maxMarks=4] Maximum landmark marks shown besides the waypoint.
54
+ * @param {number} [options.markSeparationDeg=9] Minimum bearing separation between two marks, degrees.
55
+ * @param {number} [options.labelDeg=12] Half-angle from strip centre within which the nearest mark displays its caption.
56
+ * @param {number} [options.closeDistance=25] Metres below which a non-city landmark is omitted as already reached.
57
+ * @param {number} [options.pickEvery=0.5] Seconds between re-selecting which places are marked.
58
+ * @param {(tag: string) => HTMLElement} [options.createElement] Element factory (defaults to `document.createElement`).
59
+ * @returns {{ build: () => void, update: (dt: number) => void }}
60
+ */
61
+ export function createCompassStrip({
62
+ getStrip,
63
+ getContainer,
64
+ getLocations,
65
+ getCamera,
66
+ getWaypoint = () => null,
67
+ kindOf,
68
+ placeOf,
69
+ bearingOf,
70
+ roundDistance,
71
+ formatDistance,
72
+ isDynamic = () => false,
73
+ pxPerDeg = 2,
74
+ maxMarks = 4,
75
+ markSeparationDeg = 9,
76
+ labelDeg = 12,
77
+ closeDistance = 25,
78
+ pickEvery = 0.5,
79
+ createElement = tag => globalThis.document.createElement(tag),
80
+ }) {
81
+ const state = { heading: 999, width: 0, pickT: 0, labelled: -1 };
82
+ const marks = [];
83
+ const waypointIndex = maxMarks;
84
+ const chosen = new Array(maxMarks).fill(null);
85
+ const chosenBearing = new Float64Array(maxMarks + 1);
86
+ const placePos = { x: 0, z: 0 };
87
+
88
+ function build() {
89
+ const strip = getStrip();
90
+ strip.innerHTML = compassStripHtml({ pxPerDeg });
91
+ marks.length = 0;
92
+ for (let i = 0; i <= maxMarks; i++) {
93
+ const el = createElement('div');
94
+ const cap = createElement('b');
95
+ el.className = i === waypointIndex ? 'mk wp' : 'mk';
96
+ el.hidden = true;
97
+ el.appendChild(cap);
98
+ strip.appendChild(el);
99
+ marks.push({ el, cap, loc: null, pos: null, name: '', x: 0, z: 0, d: 0, left: NaN, m: -1 });
100
+ }
101
+ }
102
+
103
+ function crowded(bearing, count, hasWaypoint) {
104
+ for (let i = 0; i <= maxMarks; i++) {
105
+ if (i < maxMarks ? i >= count : !hasWaypoint) continue;
106
+ let diff = Math.abs(chosenBearing[i] - bearing);
107
+ if (diff > 180) diff = 360 - diff;
108
+ if (diff < markSeparationDeg) return true;
109
+ }
110
+ return false;
111
+ }
112
+
113
+ function setMark(slot, loc, pos, name) {
114
+ if (slot.loc === loc && slot.pos === pos) return;
115
+ slot.loc = loc;
116
+ slot.pos = pos;
117
+ slot.name = name;
118
+ slot.m = -1;
119
+ slot.el.classList.toggle('city', !!loc && kindOf(loc).weight > 1);
120
+ }
121
+
122
+ function pickMarks(cx, cz) {
123
+ const wp = getWaypoint();
124
+ const hasWp = !!(wp && wp.pos);
125
+ setMark(marks[waypointIndex], null, hasWp ? wp.pos : null, hasWp ? wp.title : '');
126
+ if (hasWp) chosenBearing[maxMarks] = bearingOf(wp.pos.x - cx, wp.pos.z - cz);
127
+ const locations = getLocations();
128
+ let count = 0;
129
+ for (; count < maxMarks; count++) {
130
+ let best = null;
131
+ let bestScore = Infinity;
132
+ let bestBearing = 0;
133
+ for (let i = 0; i < locations.length; i++) {
134
+ const loc = locations[i];
135
+ const kind = kindOf(loc);
136
+ if (!kind || !kind.marked || !placeOf(loc, placePos)) continue;
137
+ const dx = placePos.x - cx;
138
+ const dz = placePos.z - cz;
139
+ const d = Math.sqrt(dx * dx + dz * dz);
140
+ const score = d / kind.weight;
141
+ if (d > kind.marked || d < (loc.kind === 'city' ? kind.reach : closeDistance) || score >= bestScore) continue;
142
+ const b = bearingOf(dx, dz);
143
+ if (crowded(b, count, hasWp)) continue;
144
+ bestScore = score;
145
+ best = loc;
146
+ bestBearing = b;
147
+ }
148
+ if (!best) break;
149
+ chosen[count] = best;
150
+ chosenBearing[count] = bestBearing;
151
+ }
152
+ for (let k = 0; k < maxMarks; k++) {
153
+ const loc = k < count ? chosen[k] : null;
154
+ setMark(marks[k], loc, null, loc ? loc.name : '');
155
+ if (loc && placeOf(loc, placePos)) {
156
+ marks[k].x = placePos.x;
157
+ marks[k].z = placePos.z;
158
+ }
159
+ }
160
+ }
161
+
162
+ function update(dt) {
163
+ const cam = getCamera();
164
+ let h = ((-cam.yaw * 180) / Math.PI) % 360;
165
+ if (h < 0) h += 360;
166
+ state.pickT -= dt;
167
+ if (state.pickT <= 0) {
168
+ state.pickT = pickEvery;
169
+ const w = getContainer().clientWidth;
170
+ if (w !== state.width) {
171
+ state.width = w;
172
+ state.heading = 999;
173
+ }
174
+ pickMarks(cam.x, cam.z);
175
+ }
176
+ if (Math.abs(h - state.heading) > 0.25) {
177
+ state.heading = h;
178
+ getStrip().style.transform = `translateX(${(state.width / 2 - (h + 360) * pxPerDeg).toFixed(1)}px)`;
179
+ }
180
+ const cx = cam.x;
181
+ const cz = cam.z;
182
+ let label = -1;
183
+ let nearest = labelDeg;
184
+ for (let i = 0; i <= maxMarks; i++) {
185
+ const slot = marks[i];
186
+ const on = !!(slot.loc || slot.pos);
187
+ if (slot.el.hidden === on) slot.el.hidden = !on;
188
+ if (!on) continue;
189
+ if (slot.pos) {
190
+ slot.x = slot.pos.x;
191
+ slot.z = slot.pos.z;
192
+ } else if (isDynamic(slot.loc) && placeOf(slot.loc, placePos)) {
193
+ slot.x = placePos.x;
194
+ slot.z = placePos.z;
195
+ }
196
+ const dx = slot.x - cx;
197
+ const dz = slot.z - cz;
198
+ slot.d = Math.sqrt(dx * dx + dz * dz);
199
+ let r = bearingOf(dx, dz) - h;
200
+ if (r > 180) r -= 360;
201
+ else if (r < -180) r += 360;
202
+ const left = Math.round((h + r + 360) * pxPerDeg * 2) / 2;
203
+ if (left !== slot.left) {
204
+ slot.left = left;
205
+ slot.el.style.left = left + 'px';
206
+ }
207
+ const off = Math.abs(r);
208
+ if (off < nearest) {
209
+ nearest = off;
210
+ label = i;
211
+ }
212
+ }
213
+ if (label !== state.labelled) {
214
+ if (state.labelled >= 0) marks[state.labelled].el.classList.remove('on');
215
+ if (label >= 0) {
216
+ marks[label].el.classList.add('on');
217
+ marks[label].m = -1;
218
+ }
219
+ state.labelled = label;
220
+ }
221
+ if (label >= 0) {
222
+ const slot = marks[label];
223
+ const m = roundDistance(slot.d);
224
+ if (m !== slot.m) {
225
+ slot.m = m;
226
+ slot.cap.textContent = `${slot.name} · ${formatDistance(m)}`;
227
+ }
228
+ }
229
+ }
230
+
231
+ return { build, update };
232
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * WebGL context-loss recovery controller: steps down quality for one visit when a visible page
3
+ * drops its GPU context, preserves manual Settings choices, ignores background-tab or pagehide
4
+ * losses, caps consecutive renewals per session, and reloads or renews the page in place.
5
+ * Worker-safe: canvas and browser host enter via parameters.
6
+ * @module
7
+ */
8
+ import { LEVELS } from './quality-store.js';
9
+
10
+ /**
11
+ * Returns the next lower quality level in `levels`, or the lowest level if already at the bottom.
12
+ *
13
+ * @param {string} name Current quality level name.
14
+ * @param {ReadonlyArray<string>} [levels=LEVELS] Ordered preset names from lowest to highest.
15
+ * @returns {string}
16
+ */
17
+ export function lowerQualityLevel(name, levels = LEVELS) {
18
+ return levels[Math.max(0, levels.indexOf(name) - 1)];
19
+ }
20
+
21
+ /**
22
+ * Watches a WebGL canvas for `webglcontextlost` and schedules automatic recovery.
23
+ *
24
+ * @param {object} options
25
+ * @param {HTMLCanvasElement} options.canvas WebGL canvas element.
26
+ * @param {() => string} options.getQuality Returns the active quality preset name.
27
+ * @param {() => boolean} options.isInWorld Returns true when the visitor is in the world (false on title).
28
+ * @param {(preset: string) => void} options.keepOnce Stores a one-visit preset override for the next page.
29
+ * @param {(preset: string) => void} options.keepFit Stores the fitted preset when no manual choice exists.
30
+ * @param {() => string | null} options.hasManualChoice Returns the saved manual quality choice, or null.
31
+ * @param {() => void} options.onRenew Renews the world in place where the visitor stands.
32
+ * @param {() => void} [options.onReload] Reloads the page when not yet in the world (defaults to `location.reload()`).
33
+ * @param {(message: string, seconds: number) => void} [options.onNotify] Displays a user-facing notice.
34
+ * @param {(category: string, message: string) => void} [options.onLog] Records a diagnostic log note.
35
+ * @param {ReadonlyArray<string>} [options.levels=LEVELS]
36
+ * @param {string} [options.storageKey='roamwright:context-renews'] Session storage key counting renewals.
37
+ * @param {number} [options.maxRenews=3] Maximum automatic renewals in one tab session.
38
+ * @param {number} [options.restoreWaitMs=1500] Milliseconds to wait before renewing after context loss.
39
+ * @param {object} [options.host=globalThis] Host exposing `window`, `document`, `sessionStorage`, `location`, `setTimeout`.
40
+ * @returns {{ dispose: () => void }}
41
+ */
42
+ export function watchContextLost({
43
+ canvas,
44
+ getQuality,
45
+ isInWorld,
46
+ keepOnce,
47
+ keepFit,
48
+ hasManualChoice,
49
+ onRenew,
50
+ onReload,
51
+ onNotify = () => {},
52
+ onLog = () => {},
53
+ levels = LEVELS,
54
+ storageKey = 'roamwright:context-renews',
55
+ maxRenews = 3,
56
+ restoreWaitMs = 1500,
57
+ host = globalThis,
58
+ }) {
59
+ const win = host.window ?? host;
60
+ const doc = host.document;
61
+ const storage = host.sessionStorage;
62
+ let lost = false;
63
+ let leaving = false;
64
+
65
+ const onPageHide = () => {
66
+ leaving = true;
67
+ };
68
+
69
+ function renew() {
70
+ const renews = +(storage?.getItem(storageKey) || 0);
71
+ if (renews >= maxRenews) return;
72
+ storage?.setItem(storageKey, String(renews + 1));
73
+ if (!isInWorld()) {
74
+ if (onReload) onReload();
75
+ else host.location?.reload?.();
76
+ return;
77
+ }
78
+ onNotify('The graphics card dropped the picture: loading it again where you are.', 3);
79
+ onRenew();
80
+ }
81
+
82
+ const onLost = () => {
83
+ if (lost || leaving) return;
84
+ lost = true;
85
+ const unseen = !!doc?.hidden;
86
+ const quality = getQuality();
87
+ onLog(
88
+ 'perf',
89
+ `the graphics card dropped the page's picture (WebGL context lost) at ${quality}: loading afresh ${unseen ? 'as it was (the page was not shown)' : 'a preset lower'}`,
90
+ );
91
+ if (!unseen) {
92
+ const next = lowerQualityLevel(quality, levels);
93
+ keepOnce(next);
94
+ if (!hasManualChoice()) keepFit(next);
95
+ }
96
+ host.setTimeout(renew, restoreWaitMs);
97
+ };
98
+
99
+ win?.addEventListener?.('pagehide', onPageHide);
100
+ canvas?.addEventListener?.('webglcontextlost', onLost);
101
+
102
+ return {
103
+ dispose() {
104
+ win?.removeEventListener?.('pagehide', onPageHide);
105
+ canvas?.removeEventListener?.('webglcontextlost', onLost);
106
+ },
107
+ };
108
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Pure doorway exit-spot finder and proximity re-arm/entry trigger helpers for enterable
3
+ * buildings. Worker-safe: imports nothing of Three.js or the DOM.
4
+ * @module
5
+ */
6
+
7
+ const DEFAULT_EXIT = Object.freeze({ step: 1.2, far: 3.6, behind: 1.5, body: 0.45, bearings: 16 });
8
+
9
+ /**
10
+ * Finds a collision-free standing spot outside a doorway at `(x, z)`, preferring a bearing whose
11
+ * opposite side backs into the building wall so a departing visitor faces away from the door.
12
+ *
13
+ * @param {number} x Doorway X in metres.
14
+ * @param {number} z Doorway Z in metres.
15
+ * @param {(x: number, z: number, radius: number) => boolean} collide Returns true when a disc hits a wall.
16
+ * @param {(x: number, z: number) => number} groundAt Ground height in metres at `(x, z)`.
17
+ * @param {object} [options]
18
+ * @param {number} [options.eyeHeight=1.7] Standing eye height above ground in metres.
19
+ * @param {number} [options.step=1.2] Clearance probe step in metres.
20
+ * @param {number} [options.far=3.6] Maximum probe reach in metres.
21
+ * @param {number} [options.behind=1.5] Distance behind the doorway tested for the building wall.
22
+ * @param {number} [options.body=0.45] Visitor body collision radius in metres.
23
+ * @param {number} [options.bearings=16] Number of evenly spaced compass bearings tested.
24
+ * @returns {{ x: number, y: number, z: number, yaw: number }}
25
+ */
26
+ export function findClearExit(
27
+ x,
28
+ z,
29
+ collide,
30
+ groundAt,
31
+ {
32
+ eyeHeight = 1.7,
33
+ step = DEFAULT_EXIT.step,
34
+ far = DEFAULT_EXIT.far,
35
+ behind = DEFAULT_EXIT.behind,
36
+ body = DEFAULT_EXIT.body,
37
+ bearings = DEFAULT_EXIT.bearings,
38
+ } = {},
39
+ ) {
40
+ let best = null;
41
+ let score = -1;
42
+ for (let i = 0; i < bearings; i++) {
43
+ const a = (i / bearings) * Math.PI * 2;
44
+ const sx = Math.sin(a);
45
+ const sz = Math.cos(a);
46
+ let clear = true;
47
+ for (let r = step; r <= far + 1e-6; r += step) {
48
+ if (collide(x + sx * r, z + sz * r, body)) clear = false;
49
+ }
50
+ if (!clear) continue;
51
+ const backed = collide(x - sx * behind, z - sz * behind, body) ? 2 : 0;
52
+ if (backed + 1 > score) {
53
+ score = backed + 1;
54
+ best = a;
55
+ }
56
+ }
57
+ const a = best ?? 0;
58
+ const ex = x + Math.sin(a) * step * 2;
59
+ const ez = z + Math.cos(a) * step * 2;
60
+ return { x: ex, y: groundAt(ex, ez) + eyeHeight, z: ez, yaw: a + Math.PI };
61
+ }
62
+
63
+ /**
64
+ * Evaluates doorway arming and proximity entry for one doorway against the player's position.
65
+ * Mutates `door.armed` so leaving a building requires stepping past `rearm` before re-entering.
66
+ *
67
+ * @param {{ x: number, y: number, z: number, armed: boolean }} door
68
+ * @param {{ x: number, y: number, z: number }} player
69
+ * @param {boolean} flying True while flying (wider reach and headroom).
70
+ * @param {object} [options]
71
+ * @param {number} [options.eyeHeight=1.7]
72
+ * @param {number} [options.reach=1.8]
73
+ * @param {number} [options.flyReach=3]
74
+ * @param {number} [options.rearm=6]
75
+ * @param {number} [options.headRoom=4]
76
+ * @param {number} [options.flyRoom=6]
77
+ * @returns {boolean} True when the visitor crossed into the doorway on this step.
78
+ */
79
+ export function stepDoorwayTrigger(
80
+ door,
81
+ player,
82
+ flying,
83
+ { eyeHeight = 1.7, reach = 1.8, flyReach = 3, rearm = 6, headRoom = 4, flyRoom = 6 } = {},
84
+ ) {
85
+ const dx = player.x - door.x;
86
+ const dz = player.z - door.z;
87
+ const apart = dx * dx + dz * dz;
88
+ if (apart > rearm * rearm) {
89
+ door.armed = true;
90
+ return false;
91
+ }
92
+ const r = flying ? flyReach : reach;
93
+ if (door.armed && apart < r * r && Math.abs(player.y - eyeHeight - door.y) < (flying ? flyRoom : headRoom)) {
94
+ door.armed = false;
95
+ return true;
96
+ }
97
+ return false;
98
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Generic HUD frame controller: periodic whereabouts readout refresh, auto-expiring inspection card
3
+ * and toast banner timers, and 24-hour day-clock formatting. Zero per-frame allocations.
4
+ * Worker-safe: DOM elements enter via parameters.
5
+ * @module
6
+ */
7
+
8
+ /**
9
+ * Formats a normalised time of day (`0..1`, where 0 is midnight and 0.5 is noon) as `HH:MM`.
10
+ *
11
+ * @param {number} timeOfDay Fraction of the day in `[0, 1)`.
12
+ * @returns {string} Zero-padded 24-hour clock string (e.g. `'09:30'`).
13
+ */
14
+ export function formatDayClock(timeOfDay) {
15
+ const m = Math.round(timeOfDay * 1440) % 1440;
16
+ const h = (m / 60) | 0;
17
+ const mm = m % 60;
18
+ return `${h < 10 ? '0' : ''}${h}:${mm < 10 ? '0' : ''}${mm}`;
19
+ }
20
+
21
+ /**
22
+ * Creates a HUD timer and whereabouts frame controller.
23
+ *
24
+ * @param {object} options
25
+ * @param {() => HTMLElement} options.getLocName Returns the element showing the current place name.
26
+ * @param {() => HTMLElement} options.getLocWay Returns the element showing distance and direction.
27
+ * @param {() => HTMLElement} options.getCard Returns the inspection card container.
28
+ * @param {() => HTMLElement} options.getToast Returns the toast notification element.
29
+ * @param {(dt: number) => void} [options.updateCompass] Per-frame compass updater.
30
+ * @param {() => { name: string, way: string } | null} options.readWhereabouts Returns updated `{ name, way }` when changed, or null.
31
+ * @param {number} [options.lineEvery=0.5] Seconds between whereabouts recalculations.
32
+ * @returns {{ state: { locT: number, toastT: number, cardT: number, cardOf: any }, update: (dt: number) => void,
33
+ * toast: (msg: string, secs?: number) => void, resetLocation: () => void }}
34
+ */
35
+ export function createHudFrame({ getLocName, getLocWay, getCard, getToast, updateCompass = () => {}, readWhereabouts, lineEvery = 0.5 }) {
36
+ const state = { locT: 0, toastT: 0, cardT: 0, cardOf: null };
37
+
38
+ function update(dt) {
39
+ updateCompass(dt);
40
+ state.locT -= dt;
41
+ if (state.locT <= 0) {
42
+ state.locT = lineEvery;
43
+ const next = readWhereabouts();
44
+ if (next) {
45
+ getLocName().textContent = next.name;
46
+ getLocWay().textContent = next.way;
47
+ }
48
+ }
49
+ if (state.cardT > 0) {
50
+ state.cardT -= dt;
51
+ if (state.cardT <= 0) {
52
+ getCard().hidden = true;
53
+ state.cardOf = null;
54
+ }
55
+ }
56
+ if (state.toastT > 0) {
57
+ state.toastT -= dt;
58
+ if (state.toastT <= 0) getToast().classList.remove('show');
59
+ }
60
+ }
61
+
62
+ function toast(msg, secs = 3.2) {
63
+ const el = getToast();
64
+ el.textContent = msg;
65
+ el.classList.add('show');
66
+ state.toastT = secs;
67
+ }
68
+
69
+ function resetLocation() {
70
+ state.locT = 0;
71
+ }
72
+
73
+ return { state, update, toast, resetLocation };
74
+ }