@spellkave/world-map 0.0.0-bootstrap

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,578 @@
1
+ import { mapBounds } from "./layout.ts";
2
+ import {
3
+ chooseScaleBar,
4
+ formatMetresLabel,
5
+ type ScaleBarSpec,
6
+ sharedMetresPerGraphUnit,
7
+ } from "./scale.ts";
8
+ import type {
9
+ RenderSvgOptions,
10
+ SpatialGraphBackdrop,
11
+ SpatialGraphEdge,
12
+ SpatialGraphLayout,
13
+ SpatialGraphModel,
14
+ SpatialGraphNode,
15
+ } from "./types.ts";
16
+
17
+ /** Canonical web-vector draw product for a laid-out spatial graph. */
18
+ export function renderSpatialGraphSvg(
19
+ model: SpatialGraphModel,
20
+ layout: SpatialGraphLayout,
21
+ options: RenderSvgOptions = {},
22
+ ): string {
23
+ const maxWidth = options.width ?? 1200;
24
+ const maxHeight = options.height ?? 760;
25
+ const pad = options.pad ?? 40;
26
+ const titleH = 36;
27
+ const ornamentPadY = 32;
28
+ const chromeH = 40;
29
+ const labelFontPx = 12;
30
+ const estimateLabelHalfPx = (label: string): number => (label.length * labelFontPx * 0.58) / 2;
31
+ const hasPanels = (layout.floorPanels?.length ?? 0) > 0;
32
+ const maxLabelHalfPx = layout.nodes.reduce((max, node) => {
33
+ // An unlabeled node (composed grid cell) draws no text, so it must not
34
+ // widen the canvas padding either — otherwise 100 suppressed "Cell 4,7"
35
+ // strings still push the margins out for labels nobody ever sees.
36
+ if (node.unlabeled) return max;
37
+ const text = hasPanels
38
+ ? node.label
39
+ : labelWithElev(node.label, node.elevation, node.elevationPresent);
40
+ return Math.max(max, estimateLabelHalfPx(text));
41
+ }, 0);
42
+ const badgeOutsetPx = 21;
43
+ const padX = Math.max(pad, Math.ceil(maxLabelHalfPx + 12), badgeOutsetPx + 10);
44
+ const minWidth = Math.min(maxWidth, 360);
45
+ const minHeight = Math.min(maxHeight, 160 + chromeH + titleH);
46
+ const backdrops = options.backdrops ?? [];
47
+ const bounds = layoutBounds(layout, backdrops);
48
+ const contentW = Math.max(bounds.maxX - bounds.minX, 1);
49
+ const contentH = Math.max(bounds.maxY - bounds.minY, 0);
50
+ const scaleByW = (maxWidth - padX * 2) / contentW;
51
+ const scaleByH =
52
+ contentH > 0
53
+ ? (maxHeight - pad * 2 - ornamentPadY - chromeH - titleH) / contentH
54
+ : Number.POSITIVE_INFINITY;
55
+ const scale = Math.min(scaleByW, scaleByH);
56
+ const width = clamp(Math.ceil(contentW * scale + padX * 2), minWidth, maxWidth);
57
+ const height = clamp(
58
+ Math.ceil(contentH * scale + pad * 2 + ornamentPadY + chromeH + titleH),
59
+ minHeight,
60
+ maxHeight,
61
+ );
62
+ const usedW = contentW * scale + padX * 2;
63
+ const usedH = contentH * scale + pad * 2 + ornamentPadY;
64
+ const originX = (width - usedW) / 2;
65
+ const originY = titleH + (height - chromeH - titleH - usedH) / 2;
66
+ const project = (x: number, y: number): [number, number] => [
67
+ originX + padX + (x - bounds.minX) * scale,
68
+ originY + pad + ornamentPadY / 2 + (y - bounds.minY) * scale,
69
+ ];
70
+ const nodeById = new Map(layout.nodes.map((node) => [node.id, node] as const));
71
+ const actorsByPlace = new Map(
72
+ model.actorClusters.map((cluster) => [cluster.placeNodeId, cluster.count] as const),
73
+ );
74
+ const cross = new Set(layout.crossFloorEdgeKeys ?? []);
75
+
76
+ const hexMarks = (layout.hexes ?? []).map((hex) => {
77
+ const pts = hex.ring
78
+ .map((p) => {
79
+ const [px, py] = project(p.x, p.y);
80
+ return `${fmt(px)},${fmt(py)}`;
81
+ })
82
+ .join(" ");
83
+ const kind = hex.fillKind ?? "default";
84
+ return `<polygon data-h3="${escapeXml(hex.hex)}" data-fill="${escapeXml(kind)}" points="${pts}" class="h3-cell h3-cell--${escapeXml(kind)}" />`;
85
+ });
86
+ const worldMap = (layout.hexes?.length ?? 0) > 0;
87
+
88
+ // Backdrop masking (written and tested; NOT enabled by any caller today —
89
+ // see RenderSvgOptions.maskBackdropToNodes doc comment). AUTHOR mode never
90
+ // sets the flag, so `maskId`/`maskAttr` stay unused there and the <image>
91
+ // markup is byte-identical to before this option existed. bead sk-ubx
92
+ // tracks turning this on for the player tool.
93
+ const maskId = "backdrop-known-mask";
94
+ const maskShapes =
95
+ options.maskBackdropToNodes === true
96
+ ? layout.nodes.map((node) => {
97
+ const [x, y] = project(node.x, node.y);
98
+ return renderExtentShape(node, x, y, scale, "extent-mask", BACKDROP_REVEAL_MARGIN_CELLS);
99
+ })
100
+ : [];
101
+ const maskBlock =
102
+ maskShapes.length === 0
103
+ ? ""
104
+ : `<defs><mask id="${maskId}" maskUnits="userSpaceOnUse" x="0" y="0" width="${width}" height="${height}"><rect x="0" y="0" width="${width}" height="${height}" fill="#000" />${maskShapes.join("")}</mask></defs>\n`;
105
+ const maskAttr = maskShapes.length === 0 ? "" : ` mask="url(#${maskId})"`;
106
+
107
+ const images = layout.graphs.flatMap((graph) => {
108
+ const backdrop = backdrops.find((candidate) => candidate.graph_id === graph.graphId);
109
+ const href =
110
+ backdrop === undefined || options.backdropHref === undefined
111
+ ? null
112
+ : options.backdropHref(backdrop);
113
+ if (backdrop === undefined || href === null) return [];
114
+ const [ox, oy] = backdrop.image_origin_cells;
115
+ const [x, y] = project(ox + graph.offsetX, oy + graph.offsetY);
116
+ const imageWidth = backdrop.width_cells * scale;
117
+ const imageHeight = backdrop.height_cells * scale;
118
+ const rotate =
119
+ backdrop.rotation_deg === 0
120
+ ? ""
121
+ : ` transform="rotate(${fmt(backdrop.rotation_deg)} ${fmt(x + imageWidth / 2)} ${fmt(y + imageHeight / 2)})"`;
122
+ return [
123
+ `<image href="${escapeXml(href)}" x="${fmt(x)}" y="${fmt(y)}" width="${fmt(imageWidth)}" height="${fmt(imageHeight)}" opacity="0.62" preserveAspectRatio="none"${rotate}${maskAttr} />`,
124
+ ];
125
+ });
126
+
127
+ // Battle-map treatment for composed tactical-grid cells (operator request
128
+ // 2026-08-14): cells render as a GRID — stroke-only squares tiling the
129
+ // battlefield — not as a matrix of place dots, and an occupant badge sits
130
+ // in the CENTRE of its cell. The square side is measured empirically as
131
+ // the smallest positive projected distance between any two cells (they
132
+ // are a uniform lattice, so that IS the cell pitch); fallback covers the
133
+ // degenerate single-cell case.
134
+ const gridCells = layout.nodes.filter((n) => n.unlabeled);
135
+ const gridCellPx = (() => {
136
+ let min = Number.POSITIVE_INFINITY;
137
+ const pts = gridCells.map((n) => project(n.x, n.y));
138
+ for (let i = 0; i < pts.length; i++) {
139
+ for (let j = i + 1; j < pts.length; j++) {
140
+ const d = Math.hypot(pts[i]![0] - pts[j]![0], pts[i]![1] - pts[j]![1]);
141
+ if (d > 0.5 && d < min) min = d;
142
+ }
143
+ }
144
+ return Number.isFinite(min) ? min : 18;
145
+ })();
146
+
147
+ const edgeLines = uniqueEdges(layout.edges).flatMap((edge) => {
148
+ const from = nodeById.get(edge.from);
149
+ const to = nodeById.get(edge.to);
150
+ if (from === undefined || to === undefined) return [];
151
+ // Cell-to-cell adjacency is already legible from the grid squares —
152
+ // route lines between cells would redraw the whole lattice as an
153
+ // orange mesh. Edges that LEAVE the grid (cell ↔ named place, e.g.
154
+ // the anchor-node connection) stay drawn.
155
+ if (from.unlabeled && to.unlabeled) return [];
156
+ const [x1, y1] = project(from.x, from.y);
157
+ const [x2, y2] = project(to.x, to.y);
158
+ const key = edge.from < edge.to ? `${edge.from}|${edge.to}` : `${edge.to}|${edge.from}`;
159
+ const isStairs = cross.has(key);
160
+ const cls = isStairs ? "route-stairs" : "route";
161
+ const midX = (x1 + x2) / 2;
162
+ const midY = (y1 + y2) / 2;
163
+ const label = isStairs
164
+ ? `<text x="${fmt(midX)}" y="${fmt(midY - 6)}" class="stairs-label">stairs</text>`
165
+ : "";
166
+ return [
167
+ `<line data-from="${escapeXml(edge.from)}" data-to="${escapeXml(edge.to)}" x1="${fmt(x1)}" y1="${fmt(y1)}" x2="${fmt(x2)}" y2="${fmt(y2)}" class="${cls}" />${label}`,
168
+ ];
169
+ });
170
+
171
+ const hideOcc = options.hideOccupancy === true;
172
+ const commonExtentDepth = extentDepthSummary(model, options);
173
+ const nodeMarks = layout.nodes.map((node, idx) => {
174
+ const [x, y] = project(node.x, node.y);
175
+ const actorCount = hideOcc ? 0 : (actorsByPlace.get(node.id) ?? 0);
176
+ // Grid cells centre their occupant badge IN the cell (a token on a
177
+ // battle map); ordinary places keep the offset badge beside the dot.
178
+ const badgeR = node.unlabeled ? Math.min(9, Math.max(5, gridCellPx * 0.32)) : 9;
179
+ const [bx, by] = node.unlabeled ? [x, y] : [x + 12, y - 12];
180
+ const actor =
181
+ actorCount > 0
182
+ ? `<circle cx="${fmt(bx)}" cy="${fmt(by)}" r="${fmt(badgeR)}" class="actor" /><text x="${fmt(bx)}" y="${fmt(by + 3.5)}" class="actor-label">${actorCount}</text>`
183
+ : "";
184
+ // The floor rides its own <tspan class="label-floor"> (sk-jay0.4.21): the
185
+ // drawn text and textContent are unchanged ("Cellar (z=-3)"), but a host
186
+ // that already says the floor elsewhere hides it by class, with no label
187
+ // parsing. World maps and floor panels never carry the suffix. The
188
+ // separating space stays in the parent text node: resvg drops a space
189
+ // that leads a tspan, which would glue the floor onto the name.
190
+ const plainLabel = worldMap ? (node.shortLabel ?? node.label) : node.label;
191
+ const floorSuffix =
192
+ worldMap || hasPanels ? "" : elevSuffix(node.elevation, node.elevationPresent);
193
+ const floorSpan =
194
+ floorSuffix === ""
195
+ ? ""
196
+ : ` <tspan class="label-floor">${escapeXml(floorSuffix.trimStart())}</tspan>`;
197
+ // Slight radial label offset on world maps to reduce pile-ups.
198
+ const ang = worldMap ? (idx * 2.4) % (Math.PI * 2) : 0;
199
+ const lx = worldMap ? x + Math.cos(ang) * 14 : x;
200
+ const ly = worldMap ? y + 18 + Math.sin(ang) * 10 : y + 20;
201
+ const extentMark =
202
+ !node.unlabeled && node.extent ? renderExtentShape(node, x, y, scale, "place-extent") : "";
203
+ const depthMark =
204
+ !node.unlabeled &&
205
+ node.extent &&
206
+ options.showExtentDepth === true &&
207
+ commonExtentDepth === null
208
+ ? renderExtentDepth(node, x, y, scale)
209
+ : "";
210
+ const mark = node.portalEntrance
211
+ ? `<polygon points="${fmt(x)},${fmt(y - 9)} ${fmt(x + 8)},${fmt(y)} ${fmt(x)},${fmt(y + 9)} ${fmt(x - 8)},${fmt(y)}" class="place place-portal" />`
212
+ : node.unlabeled
213
+ ? `<rect x="${fmt(x - gridCellPx / 2)}" y="${fmt(y - gridCellPx / 2)}" width="${fmt(gridCellPx)}" height="${fmt(gridCellPx)}" class="grid-cell" />`
214
+ : `<circle cx="${fmt(x)}" cy="${fmt(y)}" r="7" class="place" />`;
215
+ const portalTag = node.portalEntrance
216
+ ? `<text x="${fmt(lx)}" y="${fmt(ly + 11)}" class="portal-tag">in</text>`
217
+ : "";
218
+ // sk-pej D-3: composed tactical-grid cells draw their mark but no text.
219
+ // The node keeps its data-node-id, so the SVG stays as addressable as
220
+ // before, and the text `inventory` output still names every cell.
221
+ const labelText = node.unlabeled
222
+ ? ""
223
+ : `<text x="${fmt(lx)}" y="${fmt(ly)}" class="label${node.portalEntrance ? " label-portal" : ""}">${escapeXml(plainLabel)}${floorSpan}</text>`;
224
+ return `<g data-node-id="${escapeXml(node.id)}">${extentMark}${depthMark}${mark}${actor}${labelText}${portalTag}</g>`;
225
+ });
226
+
227
+ const floorPanels = (layout.floorPanels ?? []).map((panel) => {
228
+ const [x1, y1] = project(panel.minX, panel.minY);
229
+ const [x2, y2] = project(panel.maxX, panel.maxY);
230
+ const w = Math.max(x2 - x1, 40);
231
+ const h = Math.max(y2 - y1, 40);
232
+ const zLabel = Number.isInteger(panel.elevation)
233
+ ? String(panel.elevation)
234
+ : panel.elevation.toFixed(1);
235
+ return `<g class="floor-panel" data-elevation="${escapeXml(zLabel)}"><rect x="${fmt(x1)}" y="${fmt(y1)}" width="${fmt(w)}" height="${fmt(h)}" rx="10" ry="10" class="floor-box" /><text x="${fmt(x1 + 12)}" y="${fmt(y1 + 18)}" class="floor-label">${escapeXml(panel.title)}</text></g>`;
236
+ });
237
+
238
+ const metresPerUnit = sharedMetresPerGraphUnit(model.graphs);
239
+ const scaleBar =
240
+ metresPerUnit === null
241
+ ? null
242
+ : chooseScaleBar(scale, metresPerUnit, {
243
+ targetPx: Math.min(120, width * 0.18),
244
+ maxPx: Math.max(48, width * 0.28),
245
+ });
246
+ const chrome = renderMapChrome(width, height, chromeH, scaleBar, hasPanels, commonExtentDepth);
247
+ const title = renderTitleBar(width, titleH, model, options);
248
+
249
+ const aria = escapeXml(options.ariaLabel ?? titlePlain(model, options));
250
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-label="${aria}">
251
+ <style>
252
+ svg{font-family:Inter,system-ui,Arial,sans-serif}
253
+ .h3-cell{fill:#c9d8cf;fill-opacity:.32;stroke:#536758;stroke-width:1.4;stroke-opacity:.9}
254
+ .h3-cell--root{fill:#9bb8a8;fill-opacity:.45}
255
+ .h3-cell--settlement{fill:#d4b896;fill-opacity:.5}
256
+ .h3-cell--wilderness{fill:#b7c9b0;fill-opacity:.38}
257
+ .h3-cell--default{fill:#c9d8cf;fill-opacity:.28}
258
+ .place-portal{fill:#8b4513;stroke:#fff;stroke-width:2}
259
+ .portal-tag{fill:#6b3a12;font-size:9px;font-weight:600;text-anchor:middle}
260
+ .label-portal{font-weight:700}
261
+ .route{stroke:#b97012;stroke-width:3;stroke-linecap:round;opacity:.9}
262
+ .route-stairs{stroke:#6b4f9a;stroke-width:2.5;stroke-linecap:round;stroke-dasharray:7 5;opacity:.95}
263
+ .place{fill:#148284;stroke:#fff;stroke-width:2.2}
264
+ .place-extent{fill:#148284;fill-opacity:.18;stroke:#0f5f61;stroke-width:1.5}
265
+ .grid-cell{fill:#148284;fill-opacity:.06;stroke:#0f5f61;stroke-opacity:.55;stroke-width:1}
266
+ .actor{fill:#245ebe;stroke:#fff;stroke-width:2}
267
+ .label{fill:#1d2428;font-size:12px;font-weight:700;text-anchor:middle;paint-order:stroke;stroke:#fff;stroke-width:4px;stroke-linejoin:round}
268
+ .actor-label{fill:#fff;font-size:9px;font-weight:800;text-anchor:middle}
269
+ .chrome-label{fill:#3a454b;font-size:11px;font-weight:600;text-anchor:start}
270
+ .scale-bar{stroke:#3a454b;stroke-width:2;stroke-linecap:square}
271
+ .scale-bar-label{fill:#3a454b;font-size:11px;font-weight:700;text-anchor:middle}
272
+ .floor-box{fill:#e7efed;stroke:#7a9690;stroke-width:1.5;opacity:.95}
273
+ .floor-label{fill:#1d3a36;font-size:13px;font-weight:800;text-anchor:start}
274
+ .stairs-label{fill:#6b4f9a;font-size:11px;font-weight:700;text-anchor:middle;paint-order:stroke;stroke:#fff;stroke-width:3px}
275
+ .title-main{fill:#14201e;font-size:15px;font-weight:800;text-anchor:start}
276
+ .title-sub{fill:#4a5a56;font-size:12px;font-weight:600;text-anchor:start}
277
+ .title-rule{stroke:#c5d0cc;stroke-width:1}
278
+ </style>
279
+ <rect width="100%" height="100%" fill="#f4f7f6" />
280
+ ${maskBlock}${title}
281
+ ${floorPanels.join("\n")}
282
+ ${images.join("\n")}
283
+ ${hexMarks.join("\n")}
284
+ ${edgeLines.join("\n")}
285
+ ${nodeMarks.join("\n")}
286
+ ${chrome}
287
+ </svg>
288
+ `;
289
+ }
290
+
291
+ /**
292
+ * Legibility pad (graph-local units) added to a node's own `extentUnits`
293
+ * reveal footprint. Current fixtures author no explicit per-node extents
294
+ * (rooms ride the bundle DEFAULT extent, which the model deliberately does
295
+ * not resolve — see `SpatialGraphNode.extentUnits`) — a bare 1-unit reveal
296
+ * would be an unreadable pinprick against a 30+-cell backdrop, so this
297
+ * constant is a rendering/legibility choice, not a domain concept; it grows
298
+ * the reveal automatically once real per-node extents get authored.
299
+ */
300
+ const BACKDROP_REVEAL_MARGIN_CELLS = 1.5;
301
+
302
+ /** Render one node's planar extent. Mask callers add a graph-local legibility
303
+ * margin; ordinary map marks use the authored geometry exactly. */
304
+ function renderExtentShape(
305
+ node: SpatialGraphNode,
306
+ x: number,
307
+ y: number,
308
+ scale: number,
309
+ className: string,
310
+ marginUnits = 0,
311
+ ): string {
312
+ const extent = node.extent;
313
+ const width = ((extent?.widthUnits ?? 1) + marginUnits * 2) * scale;
314
+ const height = ((extent?.heightUnits ?? 1) + marginUnits * 2) * scale;
315
+ const attrs = className === "extent-mask" ? 'fill="#fff"' : `class="${className}"`;
316
+ if (extent?.shapeId === "core/area/cube") {
317
+ return `<rect x="${fmt(x - width / 2)}" y="${fmt(y - height / 2)}" width="${fmt(width)}" height="${fmt(height)}" ${attrs} />`;
318
+ }
319
+ // Sphere and the no-explicit-extent reveal fallback are circles. Unknown
320
+ // explicit shapes intentionally retain the ordinary point mark until a
321
+ // renderer arm defines their geometry.
322
+ const rx = width / 2;
323
+ const ry = height / 2;
324
+ if (extent === undefined || extent.shapeId === "core/area/sphere") {
325
+ return rx === ry
326
+ ? `<circle cx="${fmt(x)}" cy="${fmt(y)}" r="${fmt(rx)}" ${attrs} />`
327
+ : `<ellipse cx="${fmt(x)}" cy="${fmt(y)}" rx="${fmt(rx)}" ry="${fmt(ry)}" ${attrs} />`;
328
+ }
329
+ return "";
330
+ }
331
+
332
+ /** Z has no honest screen-space projection on a plan. Keep x/y aligned to the
333
+ * backdrop and annotate the footprint's full vertical span at its top-right. */
334
+ function renderExtentDepth(node: SpatialGraphNode, x: number, y: number, scale: number): string {
335
+ const extent = node.extent;
336
+ if (extent === undefined) return "";
337
+ const right = x + (extent.widthUnits * scale) / 2 - 3;
338
+ const top = y - (extent.heightUnits * scale) / 2 + 11;
339
+ return `<text x="${fmt(right)}" y="${fmt(top)}" class="extent-depth" fill="#0f5f61" font-size="9" font-weight="800" text-anchor="end" paint-order="stroke" stroke="#fff" stroke-width="3" stroke-linejoin="round">↕ ${escapeXml(formatMetresLabel(extent.depthMetres))}</text>`;
340
+ }
341
+
342
+ /** The floor part of a node label (` (z=-3)`), or "" on the ground floor and
343
+ * for a node with no authored elevation. Drawn as `tspan.label-floor`. */
344
+ function elevSuffix(elevation: number, present: boolean): string {
345
+ if (!present || elevation === 0) return "";
346
+ const z = Number.isInteger(elevation) ? String(elevation) : elevation.toFixed(1);
347
+ return ` (z=${z})`;
348
+ }
349
+
350
+ function labelWithElev(label: string, elevation: number, present: boolean): string {
351
+ return `${label}${elevSuffix(elevation, present)}`;
352
+ }
353
+
354
+ function titlePlain(model: SpatialGraphModel, options: RenderSvgOptions): string {
355
+ const name = model.graphs[0]?.graphId ?? "spatial graph";
356
+ return options.sliceCaption ? `${name} — ${options.sliceCaption}` : name;
357
+ }
358
+
359
+ function renderTitleBar(
360
+ width: number,
361
+ titleH: number,
362
+ model: SpatialGraphModel,
363
+ options: RenderSvgOptions,
364
+ ): string {
365
+ const graphName = humanGraphName(model);
366
+ const sub =
367
+ options.sliceCaption ??
368
+ model.sliceLabel ??
369
+ (model.floors.length > 1 ? `floors ${model.floors.join(", ")}` : "plan");
370
+ const substrate = model.graphs[0]?.substrateId;
371
+ const subFull = substrate ? `${humanSlice(sub)} · ${substrate}` : humanSlice(sub);
372
+ return `<g class="title-bar">
373
+ <text class="title-main" x="16" y="22">${escapeXml(graphName)}</text>
374
+ <text class="title-sub" x="16" y="38">${escapeXml(subFull)}</text>
375
+ <line class="title-rule" x1="12" y1="${fmt(titleH - 2)}" x2="${fmt(width - 12)}" y2="${fmt(titleH - 2)}" />
376
+ </g>`;
377
+ }
378
+
379
+ /** Collapse a uniform authored z span into the title instead of repeating the
380
+ * same badge over every small room. Mixed depths stay node-local. */
381
+ function extentDepthSummary(model: SpatialGraphModel, options: RenderSvgOptions): number | null {
382
+ if (options.showExtentDepth !== true) return null;
383
+ const depths = [
384
+ ...new Set(
385
+ model.nodes.flatMap((node) =>
386
+ !node.unlabeled && node.extent !== undefined
387
+ ? [Number(node.extent.depthMetres.toFixed(6))]
388
+ : [],
389
+ ),
390
+ ),
391
+ ];
392
+ return depths.length === 1 ? (depths.at(0) ?? null) : null;
393
+ }
394
+
395
+ function humanGraphName(model: SpatialGraphModel): string {
396
+ const named = model.graphs[0]?.displayName?.trim();
397
+ if (named) return named;
398
+ const id = model.graphs[0]?.graphId ?? model.root ?? "Spatial graph";
399
+ const leaf = id.split("/").at(-1) ?? id;
400
+ return leaf.replaceAll("_", " ").replace(/\b\w/g, (c) => c.toUpperCase());
401
+ }
402
+
403
+ function humanSlice(raw: string): string {
404
+ if (raw.startsWith("elevation_band")) {
405
+ const m = /z=([-\d.]+)/.exec(raw);
406
+ const z = m?.[1] ?? "0";
407
+ if (z === "0" || z === "0.0") return "Ground floor only";
408
+ return `Floor slice z=${z}`;
409
+ }
410
+ if (raw.startsWith("all_floors_offset")) return "All floors (stacked panels)";
411
+ if (raw.startsWith("topology_only")) return "Topology layout (no metric positions)";
412
+ if (raw === "metric") return "Metric plan (all elevations flattened)";
413
+ return raw;
414
+ }
415
+
416
+ function renderMapChrome(
417
+ width: number,
418
+ height: number,
419
+ chromeH: number,
420
+ scaleBar: ScaleBarSpec | null,
421
+ showStairsLegend: boolean,
422
+ commonExtentDepth: number | null,
423
+ ): string {
424
+ const y0 = height - chromeH;
425
+ const pad = 12;
426
+ const parts: string[] = [
427
+ `<g class="map-chrome" data-chrome="legend" transform="translate(0 ${fmt(y0)})">`,
428
+ `<line x1="${pad}" y1="0.5" x2="${fmt(width - pad)}" y2="0.5" stroke="#c5d0cc" stroke-width="1" />`,
429
+ ];
430
+
431
+ let cursorX = pad;
432
+ if (scaleBar !== null && scaleBar.px >= 12) {
433
+ const barY = 14;
434
+ const barPx = scaleBar.px;
435
+ const label = formatMetresLabel(scaleBar.metres);
436
+ parts.push(
437
+ `<g class="scale-bar-group" data-scale-metres="${escapeXml(String(scaleBar.metres))}" data-scale-px="${fmt(barPx)}">`,
438
+ `<line class="scale-bar" x1="${fmt(cursorX)}" y1="${barY}" x2="${fmt(cursorX + barPx)}" y2="${barY}" />`,
439
+ `<line class="scale-bar" x1="${fmt(cursorX)}" y1="${barY - 5}" x2="${fmt(cursorX)}" y2="${barY + 5}" />`,
440
+ `<line class="scale-bar" x1="${fmt(cursorX + barPx)}" y1="${barY - 5}" x2="${fmt(cursorX + barPx)}" y2="${barY + 5}" />`,
441
+ `<text class="scale-bar-label" x="${fmt(cursorX + barPx / 2)}" y="${barY + 16}">${escapeXml(label)}</text>`,
442
+ `</g>`,
443
+ );
444
+ cursorX += barPx + 28;
445
+ }
446
+
447
+ const symY = 14;
448
+ parts.push(`<g class="symbol-legend" transform="translate(${fmt(cursorX)} 0)">`);
449
+ parts.push(
450
+ `<circle cx="6" cy="${symY}" r="6" class="place" />`,
451
+ `<text class="chrome-label" x="18" y="${symY + 4}">place</text>`,
452
+ `<line class="route" x1="62" y1="${symY}" x2="86" y2="${symY}" />`,
453
+ `<text class="chrome-label" x="92" y="${symY + 4}">route</text>`,
454
+ `<circle cx="148" cy="${symY}" r="9" class="actor" />`,
455
+ `<text class="actor-label" x="148" y="${symY + 3.5}">n</text>`,
456
+ `<text class="chrome-label" x="164" y="${symY + 4}">occupants</text>`,
457
+ );
458
+ if (showStairsLegend) {
459
+ parts.push(
460
+ `<line class="route-stairs" x1="248" y1="${symY}" x2="278" y2="${symY}" />`,
461
+ `<text class="chrome-label" x="284" y="${symY + 4}">stairs / floor link</text>`,
462
+ );
463
+ }
464
+ if (commonExtentDepth !== null) {
465
+ parts.push(
466
+ `<text class="chrome-label" style="text-anchor:end" x="${fmt(width - pad - cursorX)}" y="${symY + 4}">footprints ↕ ${escapeXml(formatMetresLabel(commonExtentDepth))}</text>`,
467
+ );
468
+ }
469
+ parts.push(`</g></g>`);
470
+ return parts.join("\n");
471
+ }
472
+
473
+ function clamp(value: number, min: number, max: number): number {
474
+ return Math.min(max, Math.max(min, value));
475
+ }
476
+
477
+ function layoutBounds(
478
+ layout: SpatialGraphLayout,
479
+ backdrops: readonly SpatialGraphBackdrop[],
480
+ ): { minX: number; minY: number; maxX: number; maxY: number } {
481
+ const pts = [...layout.nodes];
482
+ for (const panel of layout.floorPanels ?? []) {
483
+ pts.push(
484
+ {
485
+ x: panel.minX,
486
+ y: panel.minY,
487
+ id: "",
488
+ label: "",
489
+ graphId: "",
490
+ elevation: 0,
491
+ elevationPresent: false,
492
+ substrateId: null,
493
+ },
494
+ {
495
+ x: panel.maxX,
496
+ y: panel.maxY,
497
+ id: "",
498
+ label: "",
499
+ graphId: "",
500
+ elevation: 0,
501
+ elevationPresent: false,
502
+ substrateId: null,
503
+ },
504
+ );
505
+ }
506
+ const bounds = mapBounds(pts.length > 0 ? pts : [{ x: 0, y: 0 }]);
507
+ // A node coordinate is its extent centre. Include explicit half-extents so
508
+ // large rooms and pools participate in fit-to-canvas instead of clipping at
509
+ // the viewport edge.
510
+ for (const node of layout.nodes) {
511
+ if (node.extent === undefined) continue;
512
+ const halfW = node.extent.widthUnits / 2;
513
+ const halfH = node.extent.heightUnits / 2;
514
+ bounds.minX = Math.min(bounds.minX, node.x - halfW);
515
+ bounds.minY = Math.min(bounds.minY, node.y - halfH);
516
+ bounds.maxX = Math.max(bounds.maxX, node.x + halfW);
517
+ bounds.maxY = Math.max(bounds.maxY, node.y + halfH);
518
+ }
519
+ for (const graph of layout.graphs) {
520
+ const backdrop = backdrops.find((candidate) => candidate.graph_id === graph.graphId);
521
+ if (backdrop === undefined) continue;
522
+ for (const [x, y] of backdrop.image_bounds_cells) {
523
+ bounds.minX = Math.min(bounds.minX, x + graph.offsetX);
524
+ bounds.minY = Math.min(bounds.minY, y + graph.offsetY);
525
+ bounds.maxX = Math.max(bounds.maxX, x + graph.offsetX);
526
+ bounds.maxY = Math.max(bounds.maxY, y + graph.offsetY);
527
+ }
528
+ }
529
+ for (const hex of layout.hexes ?? []) {
530
+ for (const p of hex.ring) {
531
+ bounds.minX = Math.min(bounds.minX, p.x);
532
+ bounds.minY = Math.min(bounds.minY, p.y);
533
+ bounds.maxX = Math.max(bounds.maxX, p.x);
534
+ bounds.maxY = Math.max(bounds.maxY, p.y);
535
+ }
536
+ }
537
+ return bounds;
538
+ }
539
+
540
+ function uniqueEdges(edges: readonly SpatialGraphEdge[]): SpatialGraphEdge[] {
541
+ const byPair = new Map<string, SpatialGraphEdge>();
542
+ for (const edge of edges) {
543
+ const key = edge.from < edge.to ? `${edge.from}|${edge.to}` : `${edge.to}|${edge.from}`;
544
+ if (!byPair.has(key)) byPair.set(key, edge);
545
+ }
546
+ return [...byPair.values()];
547
+ }
548
+
549
+ function fmt(value: number): string {
550
+ if (!Number.isFinite(value)) return "0";
551
+ const rounded = Math.round(value * 100) / 100;
552
+ return Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(2);
553
+ }
554
+
555
+ function escapeXml(value: string): string {
556
+ return value
557
+ .replaceAll("&", "&amp;")
558
+ .replaceAll("<", "&lt;")
559
+ .replaceAll(">", "&gt;")
560
+ .replaceAll('"', "&quot;")
561
+ .replaceAll("'", "&apos;");
562
+ }
563
+
564
+ /** Test helper: node ids stamped on the SVG. */
565
+ export function svgNodeIds(svg: string): string[] {
566
+ return [...svg.matchAll(/data-node-id="([^"]+)"/g)].map((m) => m[1]!);
567
+ }
568
+
569
+ /** Test helper: undirected edge pairs. */
570
+ export function svgEdgePairs(svg: string): string[] {
571
+ return [...svg.matchAll(/data-from="([^"]+)" data-to="([^"]+)"/g)]
572
+ .map((m) => {
573
+ const a = m[1]!;
574
+ const b = m[2]!;
575
+ return a < b ? `${a}|${b}` : `${b}|${a}`;
576
+ })
577
+ .sort((a, b) => a.localeCompare(b));
578
+ }
@@ -0,0 +1,99 @@
1
+ /** Metric scale-bar helpers for the spatial-graph SVG chrome (cartographic nice lengths). */
2
+
3
+ export interface ScaleBarSpec {
4
+ /** Bar length in world metres. */
5
+ metres: number;
6
+ /** Bar length in SVG pixels. */
7
+ px: number;
8
+ /** Graph-unit → metres used for the bar (place_graph.metres_per_unit). */
9
+ metresPerGraphUnit: number;
10
+ /** Layout pixels per world metre. */
11
+ pxPerMetre: number;
12
+ }
13
+
14
+ /**
15
+ * Resolve a single metres-per-graph-unit for the drawn set.
16
+ * Same scale across graphs → that value; mixed scales → null (omit bar).
17
+ */
18
+ export function sharedMetresPerGraphUnit(
19
+ graphs: readonly { metresPerUnit: number }[],
20
+ ): number | null {
21
+ if (graphs.length === 0) return null;
22
+ const first = graphs[0]!.metresPerUnit;
23
+ for (const graph of graphs) {
24
+ if (!(graph.metresPerUnit > 0) || Math.abs(graph.metresPerUnit - first) > 1e-9) return null;
25
+ }
26
+ return first;
27
+ }
28
+
29
+ /**
30
+ * Pick a 1–2–5×10ⁿ bar length near `targetPx`, capped at `maxPx`.
31
+ * `layoutPxPerGraphUnit` is the SVG fit scale (pixels per pos_x unit).
32
+ */
33
+ export function chooseScaleBar(
34
+ layoutPxPerGraphUnit: number,
35
+ metresPerGraphUnit: number,
36
+ options: { targetPx?: number; maxPx?: number } = {},
37
+ ): ScaleBarSpec | null {
38
+ if (!(layoutPxPerGraphUnit > 0) || !(metresPerGraphUnit > 0)) return null;
39
+ const targetPx = options.targetPx ?? 100;
40
+ const maxPx = options.maxPx ?? 200;
41
+ const pxPerMetre = layoutPxPerGraphUnit / metresPerGraphUnit;
42
+ if (!(pxPerMetre > 0) || !Number.isFinite(pxPerMetre)) return null;
43
+
44
+ const rawMetres = targetPx / pxPerMetre;
45
+ if (!(rawMetres > 0) || !Number.isFinite(rawMetres)) return null;
46
+
47
+ const exp = Math.floor(Math.log10(rawMetres));
48
+ const base = 10 ** exp;
49
+ const candidates = [1, 2, 5, 10, 20, 50]
50
+ .flatMap((m) => [m * base * 0.1, m * base, m * base * 10])
51
+ .filter((m) => m > 0 && Number.isFinite(m));
52
+ const unique = [...new Set(candidates.map((m) => roundMetres(m)))].sort((a, b) => a - b);
53
+
54
+ let best: { metres: number; px: number } | null = null;
55
+ for (const metres of unique) {
56
+ const px = metres * pxPerMetre;
57
+ if (px < 24) continue; // too short to read
58
+ if (px > maxPx) {
59
+ if (best === null) {
60
+ // nothing fit yet — take this if still vaguely usable after clamp intent
61
+ continue;
62
+ }
63
+ break;
64
+ }
65
+ if (best === null || Math.abs(px - targetPx) < Math.abs(best.px - targetPx)) {
66
+ best = { metres, px };
67
+ }
68
+ }
69
+ // Fallback: largest candidate under maxPx, or min readable fraction of span
70
+ if (best === null) {
71
+ for (const metres of unique) {
72
+ const px = metres * pxPerMetre;
73
+ if (px <= maxPx && px >= 12) best = { metres, px };
74
+ }
75
+ }
76
+ if (best === null) return null;
77
+ return {
78
+ metres: best.metres,
79
+ px: best.px,
80
+ metresPerGraphUnit,
81
+ pxPerMetre,
82
+ };
83
+ }
84
+
85
+ export function formatMetresLabel(metres: number): string {
86
+ if (Number.isInteger(metres) || Math.abs(metres - Math.round(metres)) < 1e-9) {
87
+ return `${Math.round(metres)} m`;
88
+ }
89
+ const rounded = Math.round(metres * 100) / 100;
90
+ return `${rounded} m`;
91
+ }
92
+
93
+ function roundMetres(value: number): number {
94
+ if (value >= 1) return Math.round(value * 1000) / 1000;
95
+ // keep short decimals for sub-metre bars
96
+ const digits = value >= 0.1 ? 2 : 3;
97
+ const f = 10 ** digits;
98
+ return Math.round(value * f) / f;
99
+ }