roamwright 0.61.24 → 0.61.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,342 @@
1
+ /**
2
+ * Procedural 2D Canvas sprite painters and ridge noise for parallax title backdrops:
3
+ * multi-octave 1D value noise, sky gradients, cumulus cloud banks, sunlit mountain ranges with
4
+ * snow bands, and a finishing wash/veil for legible foreground typography.
5
+ * @module
6
+ */
7
+
8
+ /** Default vertical sky gradient stops (zenith blue warming to golden horizon). */
9
+ export const DEFAULT_BACKDROP_SKY = Object.freeze({
10
+ stops: [
11
+ [0, '#7fa3c4'],
12
+ [0.38, '#a9c2d6'],
13
+ [0.66, '#e6dccb'],
14
+ [0.78, '#f4e2c2'],
15
+ [1, '#f1d9b4'],
16
+ ],
17
+ sun: {
18
+ x: 0.34,
19
+ y: 0.7,
20
+ radius: 0.55,
21
+ stops: [
22
+ [0, 'rgba(255,246,220,0.95)'],
23
+ [0.08, 'rgba(255,232,190,0.55)'],
24
+ [0.4, 'rgba(255,220,170,0.16)'],
25
+ [1, 'rgba(255,220,170,0)'],
26
+ ],
27
+ },
28
+ });
29
+
30
+ /** Default sunlit mountain ranges for standalone backdrop rendering. */
31
+ export const DEFAULT_BACKDROP_RANGES = Object.freeze([
32
+ { rock: '#9fb0c4', haze: '#dfe3e2', snowLine: 0.3, height: 0.42, top: 0.5 },
33
+ { rock: '#7d8fa4', haze: '#dfe3e2', snowLine: 0.1, height: 0.3, top: 0.62 },
34
+ ]);
35
+
36
+ /** Default center radial veil softening the backdrop behind foreground title typography. */
37
+ export const DEFAULT_BACKDROP_VEIL = Object.freeze({
38
+ x: 0.5,
39
+ y: 0.48,
40
+ radius: 0.36,
41
+ stops: [
42
+ [0, 'rgba(250,245,234,0.5)'],
43
+ [1, 'rgba(250,245,234,0)'],
44
+ ],
45
+ });
46
+
47
+ /**
48
+ * Generates a smooth 1D multi-octave value-noise profile of `n + 1` samples in `[0, 1]`.
49
+ *
50
+ * Coarse octaves carry the largest amplitude and each subsequent octave doubles cell frequency
51
+ * while halving amplitude.
52
+ *
53
+ * @param {number} n Number of intervals along the profile (returns `n + 1` samples).
54
+ * @param {() => number} rng Seeded PRNG returning floats in `[0, 1)`.
55
+ * @param {number} [octaves=6] Number of noise octaves.
56
+ * @returns {Float32Array}
57
+ */
58
+ export function ridgeNoise(n, rng, octaves = 6) {
59
+ const out = new Float32Array(n + 1);
60
+ let amp = 1;
61
+ let total = 0;
62
+ for (let o = 0; o < octaves; o++) {
63
+ const cells = 2 << o;
64
+ const knots = Array.from({ length: cells + 2 }, rng);
65
+ for (let i = 0; i <= n; i++) {
66
+ const f = (i / n) * cells;
67
+ const k = Math.floor(f);
68
+ const t = f - k;
69
+ const e = t * t * (3 - 2 * t);
70
+ out[i] += amp * (knots[k] * (1 - e) + knots[k + 1] * e);
71
+ }
72
+ total += amp;
73
+ amp *= 0.5;
74
+ }
75
+ for (let i = 0; i <= n; i++) out[i] /= total;
76
+ return out;
77
+ }
78
+
79
+ /**
80
+ * Allocates an offscreen 2D canvas sized to at least `1 x 1` pixels, runs `draw(ctx, width, height)`,
81
+ * and returns the canvas for fast per-frame blitting.
82
+ *
83
+ * @param {number} width Desired sprite width in pixels.
84
+ * @param {number} height Desired sprite height in pixels.
85
+ * @param {(ctx: CanvasRenderingContext2D, width: number, height: number) => void} draw Sprite painter.
86
+ * @param {() => HTMLCanvasElement} [createCanvas] Canvas factory (defaults to `document.createElement('canvas')`).
87
+ * @returns {HTMLCanvasElement}
88
+ */
89
+ export function createCanvasSprite(width, height, draw, createCanvas = () => document.createElement('canvas')) {
90
+ const canvas = createCanvas();
91
+ canvas.width = Math.max(1, Math.ceil(width));
92
+ canvas.height = Math.max(1, Math.ceil(height));
93
+ draw(canvas.getContext('2d'), canvas.width, canvas.height);
94
+ return canvas;
95
+ }
96
+
97
+ /**
98
+ * Paints a vertical sky gradient sprite with an optional radial sun glow.
99
+ *
100
+ * @param {number} width Sprite width in pixels.
101
+ * @param {number} height Sprite height in pixels.
102
+ * @param {object} [options]
103
+ * @param {Array<[number, string]>} [options.stops] Vertical gradient colour stops.
104
+ * @param {{ x: number, y: number, radius: number, stops: Array<[number, string]> } | null} [options.sun] Optional sun glow definition.
105
+ * @param {() => HTMLCanvasElement} [options.createCanvas] Canvas factory.
106
+ * @returns {HTMLCanvasElement}
107
+ */
108
+ export function paintSkyGradient(width, height, { stops = DEFAULT_BACKDROP_SKY.stops, sun = DEFAULT_BACKDROP_SKY.sun, createCanvas } = {}) {
109
+ return createCanvasSprite(
110
+ width,
111
+ height,
112
+ (g, W, H) => {
113
+ const vertical = g.createLinearGradient(0, 0, 0, H);
114
+ for (let i = 0; i < stops.length; i++) vertical.addColorStop(stops[i][0], stops[i][1]);
115
+ g.fillStyle = vertical;
116
+ g.fillRect(0, 0, W, H);
117
+ if (sun) {
118
+ const sx = W * sun.x;
119
+ const sy = H * sun.y;
120
+ const glow = g.createRadialGradient(sx, sy, 0, sx, sy, Math.max(W, H) * sun.radius);
121
+ for (let i = 0; i < sun.stops.length; i++) glow.addColorStop(sun.stops[i][0], sun.stops[i][1]);
122
+ g.fillStyle = glow;
123
+ g.fillRect(0, 0, W, H);
124
+ }
125
+ },
126
+ createCanvas,
127
+ );
128
+ }
129
+
130
+ /**
131
+ * Paints a procedural cumulus cloud bank sprite with sunlit puffs above a flat shadowed base.
132
+ *
133
+ * @param {number} width Sprite width in pixels.
134
+ * @param {() => number} rng Seeded PRNG returning floats in `[0, 1)`.
135
+ * @param {object} [options]
136
+ * @param {number} [options.aspect=0.36] Sprite height as a fraction of `width`.
137
+ * @param {number} [options.puffs=46] Number of soft radial puffs.
138
+ * @param {Array<[number, string]>} [options.puffStops] Radial puff gradient colour stops.
139
+ * @param {Array<[number, string]>} [options.underStops] Base shadow gradient colour stops.
140
+ * @param {() => HTMLCanvasElement} [options.createCanvas] Canvas factory.
141
+ * @returns {HTMLCanvasElement}
142
+ */
143
+ export function paintCumulusSprite(
144
+ width,
145
+ rng,
146
+ {
147
+ aspect = 0.36,
148
+ puffs = 46,
149
+ puffStops = [
150
+ [0, 'rgba(255,251,244,0.5)'],
151
+ [0.6, 'rgba(244,240,236,0.32)'],
152
+ [1, 'rgba(232,230,232,0)'],
153
+ ],
154
+ underStops = [
155
+ [0, 'rgba(150,158,176,0)'],
156
+ [1, 'rgba(150,158,176,0.45)'],
157
+ ],
158
+ createCanvas,
159
+ } = {},
160
+ ) {
161
+ const height = width * aspect;
162
+ return createCanvasSprite(
163
+ width,
164
+ height,
165
+ (g, W, H) => {
166
+ const base = H * 0.78;
167
+ g.save();
168
+ g.beginPath();
169
+ g.rect(0, 0, W, base + H * 0.04);
170
+ g.clip();
171
+ for (let i = 0; i < puffs; i++) {
172
+ const along = rng();
173
+ const heap = Math.sin(Math.PI * along);
174
+ const x = W * (0.08 + along * 0.84);
175
+ const r = H * (0.1 + rng() * 0.16) * (0.5 + heap);
176
+ const y = base - r * (0.45 + rng() * 0.5) * (0.6 + heap * 0.8);
177
+ const body = g.createRadialGradient(x - r * 0.2, y - r * 0.3, 0, x, y, r);
178
+ for (let s = 0; s < puffStops.length; s++) body.addColorStop(puffStops[s][0], puffStops[s][1]);
179
+ g.fillStyle = body;
180
+ g.beginPath();
181
+ g.arc(x, y, r, 0, Math.PI * 2);
182
+ g.fill();
183
+ }
184
+ g.restore();
185
+ const under = g.createLinearGradient(0, base - H * 0.2, 0, base + H * 0.04);
186
+ for (let s = 0; s < underStops.length; s++) under.addColorStop(underStops[s][0], underStops[s][1]);
187
+ g.globalCompositeOperation = 'source-atop';
188
+ g.fillStyle = under;
189
+ g.fillRect(0, 0, W, H);
190
+ },
191
+ createCanvas,
192
+ );
193
+ }
194
+
195
+ /**
196
+ * Paints a layered mountain-range sprite from `ridgeNoise`, shading sunward slopes warm and
197
+ * leeward slopes cool with an optional snow band above `snowLine`.
198
+ *
199
+ * @param {number} width Sprite width in pixels.
200
+ * @param {number} height Sprite height in pixels.
201
+ * @param {() => number} rng Seeded PRNG returning floats in `[0, 1)`.
202
+ * @param {object} [options]
203
+ * @param {string} [options.rock='#7d8fa4'] Peak rock colour at the top of the range fill.
204
+ * @param {string} [options.haze='#dfe3e2'] Horizon haze colour at the foot of the range.
205
+ * @param {number} [options.snowLine=0] Fraction of sprite height down to which snow settles (`0` disables snow).
206
+ * @param {Array<[number, string]>} [options.litStops] Sunward-slope gradient stops.
207
+ * @param {Array<[number, string]>} [options.shadeStops] Shadow-slope gradient stops.
208
+ * @param {Array<[number, string]>} [options.snowStops] Horizontal snow-band gradient stops.
209
+ * @param {() => HTMLCanvasElement} [options.createCanvas] Canvas factory.
210
+ * @param {() => Path2D} [options.createPath] Path2D factory.
211
+ * @returns {HTMLCanvasElement}
212
+ */
213
+ export function paintMountainRange(
214
+ width,
215
+ height,
216
+ rng,
217
+ {
218
+ rock = '#7d8fa4',
219
+ haze = '#dfe3e2',
220
+ snowLine = 0,
221
+ litStops = [
222
+ [0, 'rgba(255,238,210,0.34)'],
223
+ [1, 'rgba(255,238,210,0)'],
224
+ ],
225
+ shadeStops = [
226
+ [0, 'rgba(46,58,84,0.3)'],
227
+ [1, 'rgba(46,58,84,0)'],
228
+ ],
229
+ snowStops = [
230
+ [0, 'rgba(255,251,242,0.9)'],
231
+ [1, 'rgba(222,230,242,0.85)'],
232
+ ],
233
+ createCanvas,
234
+ createPath = () => new Path2D(),
235
+ } = {},
236
+ ) {
237
+ return createCanvasSprite(
238
+ width,
239
+ height,
240
+ (g, W, H) => {
241
+ const n = Math.max(120, Math.round(W / 3));
242
+ const noise = ridgeNoise(n, rng);
243
+ const ridge = new Float32Array(n + 1);
244
+ let lo = 1;
245
+ let hi = 0;
246
+ for (let i = 0; i <= n; i++) {
247
+ const v = noise[i];
248
+ if (v < lo) lo = v;
249
+ if (v > hi) hi = v;
250
+ }
251
+ const fine = ridgeNoise(n, rng, 7);
252
+ for (let i = 0; i <= n; i++) {
253
+ const broad = (noise[i] - lo) / (hi - lo);
254
+ const crags = 1 - Math.abs(fine[i] * 2 - 1);
255
+ ridge[i] = H * (0.95 - 0.85 * Math.pow(broad, 1.3) - 0.12 * crags * broad);
256
+ }
257
+ const step = W / n;
258
+ const outline = createPath();
259
+ outline.moveTo(0, H);
260
+ for (let i = 0; i <= n; i++) outline.lineTo(i * step, ridge[i]);
261
+ outline.lineTo(W, H);
262
+ outline.closePath();
263
+ const fill = g.createLinearGradient(0, 0, 0, H);
264
+ fill.addColorStop(0, rock);
265
+ fill.addColorStop(1, haze);
266
+ g.fillStyle = fill;
267
+ g.fill(outline);
268
+ g.save();
269
+ g.clip(outline);
270
+ // Shade each slope from crest to neighbouring valley: left slopes face the sun, right slopes fall in cool shade.
271
+ const crest = i => i > 0 && i < n && ridge[i] <= ridge[i - 1] && ridge[i] <= ridge[i + 1];
272
+ const hollow = i => i <= 0 || i >= n || (ridge[i] >= ridge[i - 1] && ridge[i] >= ridge[i + 1]);
273
+ for (let p = 1; p < n; p++) {
274
+ if (!crest(p)) continue;
275
+ for (const dir of [-1, 1]) {
276
+ let v = p + dir;
277
+ while (!hollow(v)) v += dir;
278
+ v = Math.max(0, Math.min(n, v));
279
+ const drop = H - ridge[p];
280
+ const face = createPath();
281
+ face.moveTo(p * step, ridge[p]);
282
+ for (let k = p + dir; k !== v + dir; k += dir) face.lineTo(k * step, ridge[k]);
283
+ face.lineTo(v * step + dir * drop * 0.35, H);
284
+ face.lineTo(p * step + dir * drop * 0.12, H);
285
+ face.closePath();
286
+ const shade = g.createLinearGradient(0, ridge[p], 0, H);
287
+ const stops = dir < 0 ? litStops : shadeStops;
288
+ for (let s = 0; s < stops.length; s++) shade.addColorStop(stops[s][0], stops[s][1]);
289
+ g.fillStyle = shade;
290
+ g.fill(face);
291
+ }
292
+ }
293
+ if (snowLine > 0) {
294
+ const line = H * snowLine;
295
+ const snow = createPath();
296
+ snow.moveTo(0, ridge[0]);
297
+ for (let i = 0; i <= n; i++) snow.lineTo(i * step, ridge[i]);
298
+ for (let i = n; i >= 0; i--) {
299
+ const deep = Math.max(0, line - ridge[i]) * (0.4 + 0.5 * fine[i]);
300
+ snow.lineTo(i * step, ridge[i] + deep);
301
+ }
302
+ snow.closePath();
303
+ const white = g.createLinearGradient(0, 0, W, 0);
304
+ for (let s = 0; s < snowStops.length; s++) white.addColorStop(snowStops[s][0], snowStops[s][1]);
305
+ g.fillStyle = white;
306
+ g.fill(snow);
307
+ }
308
+ g.restore();
309
+ },
310
+ createCanvas,
311
+ );
312
+ }
313
+
314
+ /**
315
+ * Applies an optional multiplicative colour wash and soft radial centre veil so foreground title
316
+ * typography stays legible over the painted backdrop.
317
+ *
318
+ * @param {CanvasRenderingContext2D} g Target 2D rendering context.
319
+ * @param {number} W Canvas width in pixels.
320
+ * @param {number} H Canvas height in pixels.
321
+ * @param {object} [options]
322
+ * @param {string | null} [options.shade='#dcd6cc'] Multiplicative overlay colour (null to skip).
323
+ * @param {{ x: number, y: number, radius: number, stops: Array<[number, string]> } | null} [options.veil]
324
+ * Radial centre veil definition (null to skip).
325
+ */
326
+ export function applyBackdropFinish(g, W, H, { shade = '#dcd6cc', veil = DEFAULT_BACKDROP_VEIL } = {}) {
327
+ if (shade) {
328
+ g.globalAlpha = 1;
329
+ g.globalCompositeOperation = 'multiply';
330
+ g.fillStyle = shade;
331
+ g.fillRect(0, 0, W, H);
332
+ }
333
+ if (veil) {
334
+ g.globalCompositeOperation = 'source-over';
335
+ const cx = W * veil.x;
336
+ const cy = H * veil.y;
337
+ const radial = g.createRadialGradient(cx, cy, 0, cx, cy, Math.max(W, H) * veil.radius);
338
+ for (let i = 0; i < veil.stops.length; i++) radial.addColorStop(veil.stops[i][0], veil.stops[i][1]);
339
+ g.fillStyle = radial;
340
+ g.fillRect(0, 0, W, H);
341
+ }
342
+ }
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Frame-throttled 2D Canvas parallax title-screen backdrop controller supporting pixel-budget
3
+ * sizing, freeze-on-load, live resize redraws, reduced motion, and canvas snapshot handoff.
4
+ * @module
5
+ */
6
+
7
+ import { mulberry32 } from '../math/random.js';
8
+ import { fittedPixelRatio } from './viewport.js';
9
+ import {
10
+ DEFAULT_BACKDROP_RANGES,
11
+ DEFAULT_BACKDROP_SKY,
12
+ DEFAULT_BACKDROP_VEIL,
13
+ applyBackdropFinish,
14
+ createCanvasSprite,
15
+ paintCumulusSprite,
16
+ paintMountainRange,
17
+ paintSkyGradient,
18
+ ridgeNoise,
19
+ } from './title-backdrop-sprites.js';
20
+
21
+ export {
22
+ DEFAULT_BACKDROP_RANGES,
23
+ DEFAULT_BACKDROP_SKY,
24
+ DEFAULT_BACKDROP_VEIL,
25
+ applyBackdropFinish,
26
+ createCanvasSprite,
27
+ paintCumulusSprite,
28
+ paintMountainRange,
29
+ paintSkyGradient,
30
+ ridgeNoise,
31
+ };
32
+
33
+ /**
34
+ * Starts a frame-throttled 2D parallax backdrop on `canvas`.
35
+ *
36
+ * By default renders a sunlit sky gradient, layered mountain ranges, drifting cumulus clouds,
37
+ * and a subtle finish wash. Consumers may supply custom `build` and `draw` hooks to compose
38
+ * world-specific artwork while reusing pixel-budget sizing, reduced-motion handling, `freeze()`,
39
+ * live resize redraws, and `stop(keep)` snapshot handoff.
40
+ *
41
+ * @param {HTMLCanvasElement} canvas Target 2D canvas element.
42
+ * @param {object} [options]
43
+ * @param {boolean} [options.held=false] When true, renders a single static frame at `t = 0`.
44
+ * @param {number} [options.seed=1709] PRNG seed passed to sprite generation.
45
+ * @param {number} [options.frameMs=1000/30] Minimum milliseconds between animation redraws.
46
+ * @param {number | { width: number, height: number }} [options.pixelBudget=2.6e6] Backing-store pixel budget.
47
+ * @param {object} [options.sky=DEFAULT_BACKDROP_SKY] Default sky gradient configuration.
48
+ * @param {Array<{ rock: string, haze?: string, snowLine?: number, height: number, top: number }>} [options.ranges=DEFAULT_BACKDROP_RANGES]
49
+ * Default mountain range layer definitions when no custom `build` is provided.
50
+ * @param {number} [options.cloudCount=8] Number of drifting clouds in the default composition.
51
+ * @param {string | null} [options.shade='#dcd6cc'] Multiplicative finish colour in the default composition.
52
+ * @param {object | null} [options.veil=DEFAULT_BACKDROP_VEIL] Radial centre veil in the default composition.
53
+ * @param {(ctx: { width: number, height: number, unit: number, rng: () => number, createSprite: Function,
54
+ * paintSkyGradient: Function, paintMountainRange: Function, paintCumulusSprite: Function }) => any} [options.build]
55
+ * Optional custom sprite/layer builder invoked whenever backing-store dimensions change.
56
+ * @param {(frame: { ctx: CanvasRenderingContext2D, width: number, height: number, t: number, parts: any,
57
+ * applyFinish: (opts?: object) => void }) => void} [options.draw]
58
+ * Optional custom frame painter invoked at up to `1000 / frameMs` Hz.
59
+ * @param {string} [options.blobType='image/jpeg'] MIME type for the optional `stop(keep)` snapshot.
60
+ * @param {number} [options.blobQuality=0.88] Quality parameter for `canvas.toBlob`.
61
+ * @param {object} [options.host=globalThis] Host environment exposing `document`, `window`, `Path2D`, `matchMedia`,
62
+ * `devicePixelRatio`, `performance`, `requestAnimationFrame`, `cancelAnimationFrame`, and `URL`.
63
+ * @returns {{ freeze: () => void, stop: (keep?: (url: string) => void) => void }}
64
+ */
65
+ export function createTitleBackdrop(
66
+ canvas,
67
+ {
68
+ held = false,
69
+ seed = 1709,
70
+ frameMs = 1000 / 30,
71
+ pixelBudget = 2.6e6,
72
+ sky = DEFAULT_BACKDROP_SKY,
73
+ ranges = DEFAULT_BACKDROP_RANGES,
74
+ cloudCount = 8,
75
+ shade = '#dcd6cc',
76
+ veil = DEFAULT_BACKDROP_VEIL,
77
+ build = null,
78
+ draw = null,
79
+ blobType = 'image/jpeg',
80
+ blobQuality = 0.88,
81
+ host = globalThis,
82
+ } = {},
83
+ ) {
84
+ const doc = host.document;
85
+ const win = host.window ?? host;
86
+ const perf = host.performance ?? globalThis.performance;
87
+ const createCanvas = () => doc.createElement('canvas');
88
+ const createPath = () => new (host.Path2D ?? globalThis.Path2D)();
89
+ const reducedMotion = typeof host.matchMedia === 'function' ? host.matchMedia('(prefers-reduced-motion: reduce)').matches : false;
90
+ const still = held || reducedMotion;
91
+ const g = canvas.getContext('2d', { alpha: false });
92
+
93
+ let W = 0;
94
+ let H = 0;
95
+ let parts = null;
96
+ let raf = 0;
97
+ let stopped = false;
98
+ let last = -Infinity;
99
+ const t0 = perf.now();
100
+
101
+ const boundSprite = (w, h, paint) => createCanvasSprite(w, h, paint, createCanvas);
102
+ const boundSky = (w, h, opts) => paintSkyGradient(w, h, { ...opts, createCanvas });
103
+ const boundRange = (w, h, rng, opts) => paintMountainRange(w, h, rng, { ...opts, createCanvas, createPath });
104
+ const boundCloud = (w, rng, opts) => paintCumulusSprite(w, rng, { ...opts, createCanvas });
105
+
106
+ function buildDefault(width, height, unit, rng) {
107
+ return {
108
+ sky: boundSky(width, height, sky),
109
+ ranges: ranges.map(layer => ({
110
+ img: boundRange(width, height * layer.height, rng, layer),
111
+ top: layer.top,
112
+ })),
113
+ clouds: Array.from({ length: cloudCount }, (_, i) => ({
114
+ img: boundCloud(unit * (0.3 + rng() * 0.35), rng),
115
+ y: height * (0.04 + (i / Math.max(1, cloudCount)) * 0.46),
116
+ speed: (0.003 + rng() * 0.007) * width,
117
+ x: rng() * width,
118
+ })),
119
+ };
120
+ }
121
+
122
+ function drawDefault(t, P) {
123
+ g.globalCompositeOperation = 'source-over';
124
+ g.globalAlpha = 1;
125
+ g.drawImage(P.sky, 0, 0);
126
+ for (let i = 0; i < P.ranges.length; i++) {
127
+ g.drawImage(P.ranges[i].img, 0, H * P.ranges[i].top);
128
+ }
129
+ for (let i = 0; i < P.clouds.length; i++) {
130
+ const c = P.clouds[i];
131
+ const cw = c.img.width;
132
+ const x = ((((c.x + t * c.speed) % (W + cw)) + W + cw) % (W + cw)) - cw;
133
+ g.globalAlpha = 0.95;
134
+ g.drawImage(c.img, x, c.y);
135
+ }
136
+ applyBackdropFinish(g, W, H, { shade, veil });
137
+ }
138
+
139
+ function fit() {
140
+ if (stopped) return false;
141
+ const cssWidth = canvas.clientWidth;
142
+ const cssHeight = canvas.clientHeight;
143
+ if (!cssWidth || !cssHeight) return false;
144
+ const scale = fittedPixelRatio(cssWidth, cssHeight, host.devicePixelRatio || 1, pixelBudget);
145
+ const w = Math.round(cssWidth * scale);
146
+ const h = Math.round(cssHeight * scale);
147
+ if (w === W && h === H) return true;
148
+ W = canvas.width = w;
149
+ H = canvas.height = h;
150
+ const rng = mulberry32(seed);
151
+ const unit = Math.min(W, H * 1.6);
152
+ parts = build
153
+ ? build({
154
+ width: W,
155
+ height: H,
156
+ unit,
157
+ rng,
158
+ createSprite: boundSprite,
159
+ paintSkyGradient: boundSky,
160
+ paintMountainRange: boundRange,
161
+ paintCumulusSprite: boundCloud,
162
+ })
163
+ : buildDefault(W, H, unit, rng);
164
+ return true;
165
+ }
166
+
167
+ const applyFinish = opts => applyBackdropFinish(g, W, H, opts);
168
+
169
+ function renderFrame(now) {
170
+ const t = (now - t0) / 1000;
171
+ if (draw) draw({ ctx: g, width: W, height: H, t, parts, applyFinish });
172
+ else drawDefault(t, parts);
173
+ }
174
+
175
+ function frame(now) {
176
+ raf = host.requestAnimationFrame(frame);
177
+ if (now - last < frameMs) return;
178
+ last = now;
179
+ if (fit()) renderFrame(now);
180
+ }
181
+
182
+ let frozen = still;
183
+ const drawStill = () => {
184
+ host.cancelAnimationFrame(raf);
185
+ raf = host.requestAnimationFrame(now => fit() && renderFrame(still ? t0 : now));
186
+ };
187
+
188
+ raf = host.requestAnimationFrame(() => (still ? fit() && renderFrame(t0) : (raf = host.requestAnimationFrame(frame))));
189
+
190
+ const onResize = () => {
191
+ if (frozen) drawStill();
192
+ };
193
+ win?.addEventListener?.('resize', onResize);
194
+
195
+ return {
196
+ freeze() {
197
+ frozen = true;
198
+ drawStill();
199
+ },
200
+ stop(keep) {
201
+ stopped = true;
202
+ host.cancelAnimationFrame(raf);
203
+ win?.removeEventListener?.('resize', onResize);
204
+ if (keep && W && H) {
205
+ const urlApi = host.URL ?? globalThis.URL;
206
+ canvas.toBlob(blob => blob && keep(urlApi.createObjectURL(blob)), blobType, blobQuality);
207
+ }
208
+ canvas.width = canvas.height = 0;
209
+ parts = null;
210
+ },
211
+ };
212
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * HTML renderer for person and glossary-term encyclopedia pages with interactive `[[link]]`
3
+ * buttons, faction accent colours, portrait chips, and scene cross-references.
4
+ * Worker-safe: produces plain HTML strings with no DOM or Three.js dependencies.
5
+ * @module
6
+ */
7
+
8
+ import { ARTICLE_LINK } from './articles.js';
9
+
10
+ const HTML_ESCAPES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' };
11
+
12
+ /**
13
+ * Escapes `&`, `<`, `>`, and `"` for safe HTML text and double-quoted attribute insertion.
14
+ *
15
+ * @param {unknown} text Value coerced to string and escaped.
16
+ * @returns {string}
17
+ */
18
+ export function escapeHtml(text) {
19
+ return String(text).replace(/[&<>"]/g, ch => HTML_ESCAPES[ch]);
20
+ }
21
+
22
+ /**
23
+ * Renders a paragraph with resolved `[[Target]]` / `[[Target|Shown]]` tokens turned into
24
+ * `<button class="wlink k-<kind>" data-go="...">` elements; unresolved names remain plain text.
25
+ *
26
+ * @param {string} text Raw paragraph text.
27
+ * @param {(name: string) => ({ kind: string } | null | undefined)} resolveLink Link target resolver.
28
+ * @returns {string}
29
+ */
30
+ export function renderArticleParagraph(text, resolveLink) {
31
+ return escapeHtml(text).replace(ARTICLE_LINK, (_m, name, shown) => {
32
+ const target = resolveLink(name);
33
+ return target ? `<button class="wlink k-${target.kind}" data-go="${escapeHtml(name)}">${shown ?? name}</button>` : (shown ?? name);
34
+ });
35
+ }
36
+
37
+ /**
38
+ * Creates an HTML article-page renderer for entries returned by `createArticleCatalog`.
39
+ *
40
+ * @param {object} options
41
+ * @param {(name: string) => ({ kind: string } | null | undefined)} options.resolveLink Resolves `[[link]]` targets.
42
+ * @param {() => Record<string, { name: string, faction: string, role?: string, race?: string }>} options.getCharacters
43
+ * Returns the world's character definitions keyed by id.
44
+ * @param {() => Record<string, { label: string, color: string }>} options.getFactions
45
+ * Returns the faction styles keyed by faction id.
46
+ * @param {() => Array<{ n: number, title: string, who: string[] }>} [options.getEvents]
47
+ * Returns the world's scene/event list for "Seen in" footers.
48
+ * @param {Record<string | number, string>} [options.bookTitles={}] Maps optional `entry.book` keys to display titles.
49
+ * @param {(character: object, factionLabel: string) => string} [options.getSubtitle] Formats a person's header kicker.
50
+ * @param {(id: string, name: string, small?: number) => string} [options.renderPortrait] Returns portrait HTML (small=1 for chips).
51
+ * @param {(id: string) => boolean} [options.hasWorldActor] True when a character can be located in the 3D world ("Find" button).
52
+ * @param {(ev: object) => string} [options.formatSceneMark] Formats a scene badge label.
53
+ * @param {string} [options.peopleLabel='People'] Back-button and footer heading label for people.
54
+ * @param {string} [options.alsoPrefix='Also called '] Prefix shown before alternate names on term pages.
55
+ * @param {string} [options.seenInLabel='Seen in'] Footer heading label for scenes featuring a person.
56
+ * @param {string} [options.findLabel='Find'] Button label for locating a character in the world.
57
+ * @param {string} [options.emptyNotice='A longer article is still being written.'] Fallback notice when an entry has no sections.
58
+ * @returns {{ renderParagraph: (text: string) => string, renderPersonChip: (id: string) => string, renderEntryPage: (entry: object) => string }}
59
+ */
60
+ export function createArticlePageRenderer({
61
+ resolveLink,
62
+ getCharacters,
63
+ getFactions,
64
+ getEvents = () => [],
65
+ bookTitles = {},
66
+ getSubtitle = (character, label) => [character.race, label].filter(Boolean).join(' · '),
67
+ renderPortrait = () => '',
68
+ hasWorldActor = () => false,
69
+ formatSceneMark = ev => String(ev.n ?? ''),
70
+ peopleLabel = 'People',
71
+ alsoPrefix = 'Also called ',
72
+ seenInLabel = 'Seen in',
73
+ findLabel = 'Find',
74
+ emptyNotice = 'A longer article is still being written.',
75
+ }) {
76
+ const renderParagraph = text => renderArticleParagraph(text, resolveLink);
77
+
78
+ function renderPersonChip(id) {
79
+ const characters = getCharacters();
80
+ const factions = getFactions();
81
+ const character = characters[id];
82
+ return `<button data-actor="${id}" style="--c:${factions[character.faction].color}">${renderPortrait(id, character.name, 1)}${escapeHtml(character.name)}</button>`;
83
+ }
84
+
85
+ function idsOf(name) {
86
+ const characters = getCharacters();
87
+ return Object.keys(characters).filter(id => characters[id].name === name);
88
+ }
89
+
90
+ function renderEntryPage(entry) {
91
+ const characters = getCharacters();
92
+ const factions = getFactions();
93
+ const character = entry.id && characters[entry.id];
94
+ const faction = character && factions[character.faction];
95
+ const kicker =
96
+ entry.kind === 'person'
97
+ ? getSubtitle(character, faction.label)
98
+ : entry.section.title + (entry.book ? ' · ' + bookTitles[entry.book] : '');
99
+ const line = entry.kind === 'person' ? character.role : entry.also ? alsoPrefix + entry.also : '';
100
+ const face = character ? renderPortrait(entry.id, character.name) : '';
101
+ const find = character && hasWorldActor(entry.id) ? `<button class="btn sm" data-find="${entry.id}">${findLabel}</button>` : '';
102
+ const back = entry.kind === 'person' ? peopleLabel : entry.section.title;
103
+
104
+ let html = `<article class="wpage"${faction ? ` style="--c:${faction.color}"` : ''}>
105
+ <button class="wback" data-back>‹ ${escapeHtml(back)}</button>
106
+ <div class="whead">${face}<div><small>${escapeHtml(kicker)}</small><h3>${escapeHtml(entry.name)}</h3>${line ? `<p>${escapeHtml(line)}</p>` : ''}</div>${find}</div>
107
+ <p class="wlede">${renderParagraph(entry.lede)}</p>`;
108
+
109
+ for (const section of entry.sections) {
110
+ html += `<section>${section.title ? `<h4>${escapeHtml(section.title)}</h4>` : ''}${section.paras.map(p => `<p>${renderParagraph(p)}</p>`).join('')}</section>`;
111
+ }
112
+ if (!entry.sections.length) html += `<p class="wsoon">${emptyNotice}</p>`;
113
+
114
+ const ids = entry.kind === 'person' ? idsOf(entry.name) : [];
115
+ const scenes = getEvents().filter(ev => ids.some(id => ev.who.includes(id)));
116
+ const who = entry.kind === 'term' ? entry.who.filter(id => characters[id] && id !== entry.id) : [];
117
+
118
+ if (scenes.length) {
119
+ html += `<footer><b>${seenInLabel}</b><div class="prow">${scenes.map(ev => `<button class="wscene" data-scene="${ev.n}"><i>${formatSceneMark(ev)}</i>${escapeHtml(ev.title)}</button>`).join('')}</div></footer>`;
120
+ }
121
+ if (who.length) {
122
+ html += `<footer><b>${peopleLabel}</b><div class="prow">${who.map(renderPersonChip).join('')}</div></footer>`;
123
+ }
124
+ return html + '</article>';
125
+ }
126
+
127
+ return { renderParagraph, renderPersonChip, renderEntryPage };
128
+ }