iso-explainer 0.0.0-stage → 1.0.0

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 (38) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +110 -2
  3. package/README.pt-BR.md +88 -0
  4. package/bin/iso-explainer.mjs +75 -0
  5. package/package.json +37 -4
  6. package/skills/iso-explainer/SKILL.md +92 -0
  7. package/skills/iso-explainer/assets/fonts/OFL.txt +93 -0
  8. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-400-normal.woff2 +0 -0
  9. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-500-normal.woff2 +0 -0
  10. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-600-normal.woff2 +0 -0
  11. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-700-normal.woff2 +0 -0
  12. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-800-normal.woff2 +0 -0
  13. package/skills/iso-explainer/assets/runtime/LUCIDE-LICENSE.txt +43 -0
  14. package/skills/iso-explainer/assets/runtime/app.js +687 -0
  15. package/skills/iso-explainer/assets/runtime/engine.js +1177 -0
  16. package/skills/iso-explainer/assets/runtime/icons.js +205 -0
  17. package/skills/iso-explainer/assets/runtime/styles.css +447 -0
  18. package/skills/iso-explainer/assets/runtime/template.html +29 -0
  19. package/skills/iso-explainer/assets/templates/starter.course.json +134 -0
  20. package/skills/iso-explainer/examples/arquitetura-pedidos.docs.json +1743 -0
  21. package/skills/iso-explainer/examples/engenharia-na-pratica.course.json +2074 -0
  22. package/skills/iso-explainer/examples/figures/token-bucket.html +98 -0
  23. package/skills/iso-explainer/examples/historia-pedidos.story.json +1872 -0
  24. package/skills/iso-explainer/references/architecture-mode.md +82 -0
  25. package/skills/iso-explainer/references/design-system.md +58 -0
  26. package/skills/iso-explainer/references/engine.md +64 -0
  27. package/skills/iso-explainer/references/entities.md +70 -0
  28. package/skills/iso-explainer/references/flows.md +67 -0
  29. package/skills/iso-explainer/references/inside.md +64 -0
  30. package/skills/iso-explainer/references/layout.md +122 -0
  31. package/skills/iso-explainer/references/schema.md +157 -0
  32. package/skills/iso-explainer/references/story-mode.md +72 -0
  33. package/skills/iso-explainer/references/storytelling.md +56 -0
  34. package/skills/iso-explainer/scripts/build.mjs +80 -0
  35. package/skills/iso-explainer/scripts/harvest.mjs +240 -0
  36. package/skills/iso-explainer/scripts/lib/resolve.mjs +251 -0
  37. package/skills/iso-explainer/scripts/snapshot.mjs +97 -0
  38. package/skills/iso-explainer/scripts/validate.mjs +41 -0
@@ -0,0 +1,1177 @@
1
+ // iso-explainer · engine.js
2
+ // Isometric SVG stage: projection, primitives, entity renderers, dark-theme remap,
3
+ // and the Stage class (scene diff -> tween timeline, auto camera, link labels, packets).
4
+ // Original implementation. Depends only on icons.js.
5
+ import { ICONS } from './icons.js';
6
+
7
+ /* ───────────────────────── numbers & projection ───────────────────────── */
8
+
9
+ export const r2 = (v) => Math.round(v * 100) / 100;
10
+ export const clamp01 = (v) => Math.max(0, Math.min(1, v));
11
+ export const lerp = (a, b, t) => a + (b - a) * t;
12
+ export const EASE = {
13
+ inOut: (t) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2),
14
+ out: (t) => 1 - (1 - t) ** 3,
15
+ back: (t) => 1 + 2.35 * (t - 1) ** 3 + 1.35 * (t - 1) ** 2,
16
+ };
17
+
18
+ // 2:1 dimetric projection. One grid unit = 28px wide x 14px tall tile.
19
+ // +x goes screen ↘ (down-right), +y goes screen ↗ (up-right), z lifts straight up.
20
+ export const iso = (x, y, z = 0) => [r2(14 * (x + y)), r2(7 * (x - y) - z)];
21
+ // Screen-aligned helper: col = one tile (28px) to the right, row = half a tile (14px) down.
22
+ export const fromColRow = (col, row) => [col + row, col - row];
23
+
24
+ // Affine maps for drawing flat 2D artwork onto planes (origin at iso(x,y,z)).
25
+ const mapRightFace = (x, y, z) => { const [a, b] = iso(x, y, z); return `matrix(1 -0.5 0 1 ${a} ${b})`; }; // plane x=const: u→+y, v→down
26
+ const mapTop = (x, y, z) => { const [a, b] = iso(x, y, z); return `matrix(1 -0.5 1 0.5 ${a} ${b})`; }; // floor: u→+y, v→+x
27
+ const mapTopX = (x, y, z) => { const [a, b] = iso(x, y, z); return `matrix(1 0.5 -1 0.5 ${a} ${b})`; }; // floor: u→+x, v→-y
28
+
29
+ /* ───────────────────────── colours ───────────────────────── */
30
+
31
+ export const INK = '#211e1b';
32
+ export const DROP = '#1c1a17';
33
+ // Block palette: top & side gradients (light → dark). Lowercase hex = remapped in dark theme.
34
+ export const PALETTE = {
35
+ orange: { top: ['#fee6cc', '#fcd4ad'], side: ['#f9c697', '#f3b47f'] },
36
+ green: { top: ['#e2f2d7', '#d1e9c2'], side: ['#c3e1b2', '#b3d79f'] },
37
+ blue: { top: ['#dfebf9', '#cde0f5'], side: ['#bcd3ef', '#a9c5e8'] },
38
+ yellow: { top: ['#fff3d6', '#fee7b8'], side: ['#fcdb9c', '#f6cd82'] },
39
+ purple: { top: ['#f2eaf9', '#e6dbf4'], side: ['#d9cbef', '#cbbae6'] },
40
+ teal: { top: ['#dcf3ef', '#c7ebe4'], side: ['#b2e0d7', '#9dd3c8'] },
41
+ rose: { top: ['#fde4e8', '#f9d0d8'], side: ['#f3bcc7', '#eaa8b6'] },
42
+ gray: { top: ['#f1ede7', '#e5dfd6'], side: ['#d9d2c7', '#cbc3b7'] },
43
+ slab: { top: ['#f7f0e7', '#f0e7dc'], side: ['#ece2d5', '#e3d7c8'] },
44
+ };
45
+ export const TONES = {
46
+ paper: { bg: '#fbf6ef', fg: INK },
47
+ red: { bg: '#f8d5cf', fg: '#8f2a22' },
48
+ green: { bg: '#dcefd2', fg: '#24521c' },
49
+ amber: { bg: '#fbe5bd', fg: '#6d4a0c' },
50
+ violet: { bg: '#e7ddf5', fg: '#47306f' },
51
+ blue: { bg: '#dbe8f7', fg: '#1f4f80' },
52
+ gray: { bg: '#ebe5dc', fg: '#5f5850' },
53
+ };
54
+ const LEVEL = (v) => (v < 0.6 ? '#7fc278' : v < 0.85 ? '#efb041' : '#e5534b');
55
+
56
+ /* Dark theme: every lowercase hex in generated SVG is remapped in HSL.
57
+ - near-neutral warm colours invert lightness (paper → charcoal, ink → cream)
58
+ - light pastels become deep, low-saturation tones
59
+ - mid tones stay, dark tones become light.
60
+ UPPERCASE hex is never remapped (use it for colours that must stay fixed). */
61
+ const hexToHsl = (hex) => {
62
+ const n = parseInt(hex.length === 4 ? hex.slice(1).replace(/./g, '$&$&') : hex.slice(1), 16);
63
+ const r = ((n >> 16) & 255) / 255, g = ((n >> 8) & 255) / 255, b = (n & 255) / 255;
64
+ const max = Math.max(r, g, b), min = Math.min(r, g, b), c = max - min, l = (max + min) / 2;
65
+ let h = 0;
66
+ if (c) {
67
+ h = max === r ? ((g - b) / c) % 6 : max === g ? (b - r) / c + 2 : (r - g) / c + 4;
68
+ h *= 60; if (h < 0) h += 360;
69
+ }
70
+ const s = c ? c / (1 - Math.abs(2 * l - 1)) : 0;
71
+ return { h, s, l, c };
72
+ };
73
+ const hslToHex = (h, s, l) => {
74
+ const c = (1 - Math.abs(2 * l - 1)) * s, x = c * (1 - Math.abs(((h / 60) % 2) - 1)), m = l - c / 2;
75
+ const [r, g, b] = h < 60 ? [c, x, 0] : h < 120 ? [x, c, 0] : h < 180 ? [0, c, x] : h < 240 ? [0, x, c] : h < 300 ? [x, 0, c] : [c, 0, x];
76
+ const t = (v) => Math.round(clamp01(v + m) * 255).toString(16).padStart(2, '0');
77
+ return `#${t(r)}${t(g)}${t(b)}`;
78
+ };
79
+ const darkCache = new Map();
80
+ export function darkHex(hex) {
81
+ if (darkCache.has(hex)) return darkCache.get(hex);
82
+ const { h, s, l, c } = hexToHsl(hex);
83
+ let out;
84
+ if (c < 0.05 || (c < 0.14 && h >= 10 && h <= 64)) {
85
+ const L = l >= 0.88 ? 0.11 + (l - 0.9) * 0.9 : 1 - l;
86
+ out = hslToHex(c < 0.02 ? 34 : h, 0.12, Math.max(0.06, Math.min(0.93, L)));
87
+ } else if (l >= 0.66) out = hslToHex(h, Math.min(s, 0.5) * 0.62, 0.17 + (l - 0.66) * 0.55);
88
+ else if (l >= 0.36) out = hex;
89
+ else out = hslToHex(h, Math.min(s, 0.6), 0.8);
90
+ darkCache.set(hex, out);
91
+ return out;
92
+ }
93
+ export const isDark = () => typeof document !== 'undefined' && document.documentElement.dataset.theme === 'dark';
94
+ export const themed = (svg) => (!svg || !isDark() ? svg : svg.replace(/#[0-9a-f]{6}\b|#[0-9a-f]{3}\b/g, darkHex));
95
+
96
+ /* ───────────────────────── text & icons ───────────────────────── */
97
+
98
+ const esc = (s) => String(s ?? '').replace(/&(?![a-z#0-9]+;)/gi, '&amp;').replace(/</g, '&lt;');
99
+ let measureCtx = null;
100
+ const MONO_SAFE = /^[\u0000-ɏ -⯿]*$/;
101
+ export function textWidth(text, size, weight = 700) {
102
+ text = String(text);
103
+ if (MONO_SAFE.test(text) || typeof document === 'undefined') return text.length * size * 0.6; // JetBrains Mono advance = 0.6em
104
+ measureCtx ||= document.createElement('canvas').getContext('2d');
105
+ measureCtx.font = `${weight} ${size}px "JetBrains Mono", monospace`;
106
+ return measureCtx.measureText(text).width;
107
+ }
108
+ const svgText = (x, y, s, size = 12.5, weight = 700, fill = INK, extra = '') =>
109
+ `<text x="${r2(x)}" y="${r2(y)}" text-anchor="middle" font-size="${size}" font-weight="${weight}" fill="${fill}" ${extra}>${esc(s)}</text>`;
110
+
111
+ const attrs = (o) => Object.entries(o).map(([k, v]) => `${k}="${v}"`).join(' ');
112
+ const iconNodes = (name) => (ICONS[name] || ICONS.box).map(([t, a]) => `<${t} ${attrs(a)}/>`).join('');
113
+ // Icon as inline <svg> for HTML.
114
+ export function iconHTML(name, { size = 16, stroke = 1.9, cls = '' } = {}) {
115
+ return `<svg class="i ${cls}" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${stroke}" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${iconNodes(name)}</svg>`;
116
+ }
117
+ // Icon as <g> centred on (cx, cy) inside the stage SVG.
118
+ export function iconSVG(name, cx, cy, size = 22, { stroke = 1.9, color = INK } = {}) {
119
+ const k = size / 24;
120
+ return `<g transform="translate(${r2(cx - size / 2)} ${r2(cy - size / 2)}) scale(${r2(k)})" fill="none" stroke="${color}" stroke-width="${r2(stroke / k)}" stroke-linecap="round" stroke-linejoin="round">${iconNodes(name)}</g>`;
121
+ }
122
+
123
+ /* ───────────────────────── path primitives ───────────────────────── */
124
+
125
+ // Closed polygon with rounded corners (r: number or per-vertex array).
126
+ export function roundPoly(pts, r) {
127
+ const n = pts.length, R = (i) => (Array.isArray(r) ? r[i] : r);
128
+ const toward = (a, b, d) => { const dx = b[0] - a[0], dy = b[1] - a[1], L = Math.hypot(dx, dy) || 1, k = Math.min(d, L / 2) / L; return [a[0] + dx * k, a[1] + dy * k]; };
129
+ let d = '';
130
+ for (let i = 0; i < n; i++) {
131
+ const p = pts[(i - 1 + n) % n], c = pts[i], q = pts[(i + 1) % n];
132
+ const a = toward(c, p, R(i)), b = toward(c, q, R(i));
133
+ d += `${i ? 'L' : 'M'}${r2(a[0])},${r2(a[1])} Q${r2(c[0])},${r2(c[1])} ${r2(b[0])},${r2(b[1])} `;
134
+ }
135
+ return d + 'Z';
136
+ }
137
+ // Open polyline with rounded joints.
138
+ export function roundLine(pts, r = 9) {
139
+ let d = `M${r2(pts[0][0])},${r2(pts[0][1])}`;
140
+ for (let i = 1; i < pts.length - 1; i++) {
141
+ const [ax, ay] = pts[i - 1], [bx, by] = pts[i], [cx, cy] = pts[i + 1];
142
+ const l1 = Math.hypot(bx - ax, by - ay), l2 = Math.hypot(cx - bx, cy - by);
143
+ if (l1 < 0.01 || l2 < 0.01) continue;
144
+ const k = Math.min(r, l1 / 2, l2 / 2);
145
+ d += ` L${r2(bx + ((ax - bx) / l1) * k)},${r2(by + ((ay - by) / l1) * k)} Q${r2(bx)},${r2(by)} ${r2(bx + ((cx - bx) / l2) * k)},${r2(by + ((cy - by) / l2) * k)}`;
146
+ }
147
+ const z = pts[pts.length - 1];
148
+ return d + ` L${r2(z[0])},${r2(z[1])}`;
149
+ }
150
+ export function pointInPoly([x, y], poly) {
151
+ let inside = false;
152
+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
153
+ const [xi, yi] = poly[i], [xj, yj] = poly[j];
154
+ if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;
155
+ }
156
+ return inside;
157
+ }
158
+ // Trim the start of a polyline so it begins `gap` px outside `poly`.
159
+ export function clipStart(pts, poly, gap) {
160
+ if (!poly || !pointInPoly(pts[0], poly)) return pts;
161
+ for (let i = 0; i < pts.length - 1; i++) {
162
+ const a = pts[i], b = pts[i + 1];
163
+ if (pointInPoly(b, poly)) continue;
164
+ let lo = 0, hi = 1;
165
+ for (let k = 0; k < 28; k++) { const m = (lo + hi) / 2; pointInPoly([a[0] + (b[0] - a[0]) * m, a[1] + (b[1] - a[1]) * m], poly) ? (lo = m) : (hi = m); }
166
+ const L = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1, t = Math.min(1, hi + gap / L);
167
+ return [[a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t], ...pts.slice(i + 1)];
168
+ }
169
+ return pts;
170
+ }
171
+ export const clipEnd = (pts, poly, gap) => clipStart([...pts].reverse(), poly, gap).reverse();
172
+ const boxOf = (pts, pad = [0, 0, 0, 0]) => {
173
+ const xs = pts.map((p) => p[0]), ys = pts.map((p) => p[1]);
174
+ return [Math.min(...xs) - pad[0], Math.min(...ys) - pad[1], Math.max(...xs) + pad[2], Math.max(...ys) + pad[3]];
175
+ };
176
+ const overlap = (a, b) => Math.max(0, Math.min(a[2], b[2]) - Math.max(a[0], b[0])) * Math.max(0, Math.min(a[3], b[3]) - Math.max(a[1], b[1]));
177
+ const hits = (a, b) => a[0] < b[2] && a[2] > b[0] && a[1] < b[3] && a[3] > b[1];
178
+ function pointAt(pts, t) {
179
+ const seg = []; let total = 0;
180
+ for (let i = 0; i < pts.length - 1; i++) { const L = Math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]); seg.push(L); total += L; }
181
+ let d = total * t;
182
+ for (let i = 0; i < seg.length; i++) {
183
+ if (d <= seg[i] || i === seg.length - 1) {
184
+ const k = seg[i] ? Math.min(1, d / seg[i]) : 0, [ax, ay] = pts[i], [bx, by] = pts[i + 1];
185
+ return { x: ax + (bx - ax) * k, y: ay + (by - ay) * k, dx: (bx - ax) / (seg[i] || 1), dy: (by - ay) / (seg[i] || 1) };
186
+ }
187
+ d -= seg[i];
188
+ }
189
+ return { x: pts[0][0], y: pts[0][1], dx: 1, dy: 0 };
190
+ }
191
+ const samplePath = (pts, step = 12) => {
192
+ const out = [];
193
+ for (let i = 0; i < pts.length - 1; i++) {
194
+ const [ax, ay] = pts[i], [bx, by] = pts[i + 1], n = Math.max(1, Math.round(Math.hypot(bx - ax, by - ay) / step));
195
+ for (let k = 0; k <= n; k++) out.push([ax + ((bx - ax) * k) / n, ay + ((by - ay) * k) / n]);
196
+ }
197
+ return out;
198
+ };
199
+
200
+ /* ───────────────────────── iso prism ───────────────────────── */
201
+
202
+ // Rounded box from (x0,y0) to (x1,y1), height h. Returns paths + outline polygon.
203
+ export function prism({ x0, x1, y0, y1, h, radius = 9 }) {
204
+ const T = iso(x0, y1, h), R = iso(x1, y1, h), B = iso(x1, y0, h), L = iso(x0, y0, h);
205
+ const Rd = iso(x1, y1, 0), Bd = iso(x1, y0, 0), Ld = iso(x0, y0, 0);
206
+ const p = Math.max(1, Math.min(radius, h / 2 - 0.5));
207
+ const ty = iso((x0 + x1) / 2, (y0 + y1) / 2, h)[1];
208
+ const outline = [T, R, Rd, Bd, Ld, L];
209
+ return {
210
+ T, R, B, L, Rd, Bd, Ld, ty, outline,
211
+ sil: roundPoly(outline, [radius + 1, p, p, radius + 3, p, p]),
212
+ top: roundPoly([T, R, B, L], [radius + 1, p, 6, p]),
213
+ sheen: roundPoly([T, R, B, L].map(([x, y]) => [x, y - 3 + (y - ty) * -0.25]), [radius + 1, p, 6, p]),
214
+ right: roundPoly([B, R, Rd, Bd], [6, p, p, radius + 3]),
215
+ bevel: roundLine([L, B, R], 8),
216
+ };
217
+ }
218
+ function paintPrism(g, color, { stroke = INK, sw = 1.9 } = {}) {
219
+ return `
220
+ <path d="${g.sil}" fill="url(#g-${color}-side)"/>
221
+ <path d="${g.right}" fill="#3a2a14" opacity=".06"/>
222
+ <path d="${g.top}" fill="url(#g-${color}-top)"/>
223
+ <path d="${g.sheen}" fill="#ffffff" opacity=".22" filter="url(#blur-sm)"/>
224
+ <path d="${g.bevel}" transform="translate(0 1.4)" fill="none" stroke="#ffffff" stroke-opacity=".75" stroke-width="1.6" stroke-linecap="round"/>
225
+ <path d="${g.bevel}" transform="translate(0 3.4)" fill="none" stroke="#5a4123" stroke-opacity=".07" stroke-width="2.4" stroke-linecap="round"/>
226
+ <path d="${g.sil}" fill="none" stroke="${stroke}" stroke-width="${sw}" stroke-linejoin="round"/>`;
227
+ }
228
+ const shadowOf = (g, h, lift, alpha) => {
229
+ const dy = Math.min(9, 3 + h * 0.15), fade = 1 - Math.min(1, lift / 140) * 0.85;
230
+ return `<path d="${g.sil}" transform="translate(0 ${r2(dy + lift)})" fill="#6b5236" opacity="${r2(alpha * fade)}" filter="url(#blur-lg)"/>`;
231
+ };
232
+
233
+ /* ───────────────────────── pills ───────────────────────── */
234
+
235
+ export const PILL_H = 21;
236
+ export const pillWidth = (text, size = 10.5, icon = null) =>
237
+ Math.max(...String(text).split('\n').map((l) => textWidth(l, size))) + 18 + (icon ? 15 : 0);
238
+ export function pill(cx, cy, text, { tone = 'paper', size = 10.5, icon = null } = {}) {
239
+ const t = TONES[tone] || TONES.paper, lines = String(text).split('\n');
240
+ const lh = Math.round(size * 1.3), h = PILL_H + (lines.length - 1) * lh;
241
+ const tw = Math.max(...lines.map((l) => textWidth(l, size))), w = tw + 18 + (icon ? 15 : 0);
242
+ const x = cx - w / 2, y = cy - h / 2, tx = x + 9 + (icon ? 15 : 0) + tw / 2;
243
+ const body = lines.map((l, i) => svgText(tx, cy + size * 0.36 + (i - (lines.length - 1) / 2) * lh, l, size, 700, t.fg)).join('');
244
+ return `<g class="pill">
245
+ <rect x="${r2(x)}" y="${r2(y + 2)}" width="${r2(w)}" height="${h}" rx="10.5" fill="${DROP}"/>
246
+ <rect x="${r2(x)}" y="${r2(y)}" width="${r2(w)}" height="${h}" rx="10.5" fill="${t.bg}" stroke="${INK}" stroke-width="1.3"/>
247
+ ${icon ? iconSVG(icon, x + 15, cy, 12, { stroke: 2.2, color: t.fg }) : ''}${body}</g>`;
248
+ }
249
+ function meterPill(cx, cy, v, icon = 'cpu') {
250
+ const x = cx - 43, y = cy - PILL_H / 2, bx = x + 23;
251
+ return `<g class="pill">
252
+ <rect x="${r2(x)}" y="${r2(y + 2)}" width="86" height="${PILL_H}" rx="10.5" fill="${DROP}"/>
253
+ <rect x="${r2(x)}" y="${r2(y)}" width="86" height="${PILL_H}" rx="10.5" fill="#fbf6ef" stroke="${INK}" stroke-width="1.3"/>
254
+ ${iconSVG(icon, x + 13, cy, 11, { stroke: 2.2, color: '#6f6961' })}
255
+ <rect x="${r2(bx)}" y="${r2(cy - 3.5)}" width="28" height="7" rx="3.5" fill="#e6ddd0"/>
256
+ <rect x="${r2(bx)}" y="${r2(cy - 3.5)}" width="${r2(Math.max(3, 28 * clamp01(v)))}" height="7" rx="3.5" fill="${LEVEL(v)}"/>
257
+ <text x="${r2(x + 77)}" y="${r2(cy + 3.6)}" text-anchor="end" font-size="10.5" font-weight="800" fill="${INK}">${Math.round(clamp01(v) * 100)}%</text></g>`;
258
+ }
259
+ // Stack of meter + tags above (or below) an anchor point.
260
+ function pillStack(e, cx, y0, below) {
261
+ const items = [];
262
+ if (e.cpu >= 0) items.push(meterPill(cx, 0, e.cpu, e.meterIcon || 'cpu'));
263
+ for (const t of e.tags || []) items.push(`<g opacity="${r2(e.tagFade ?? 1)}">${pill(cx, 0, t.text, t)}</g>`);
264
+ let y = y0, out = '';
265
+ for (const it of items) { out += `<g transform="translate(0 ${r2(y)})">${it}</g>`; y += below ? 26 : -26; }
266
+ return { svg: out, n: items.length };
267
+ }
268
+ const pillRect = (cx, cy, text, icon, size = 10.5) => { const w = pillWidth(text, size, icon); return [cx - w / 2, cy - PILL_H / 2, cx + w / 2, cy + PILL_H / 2 + 2]; };
269
+ function stackRects(e, cx, y0, below) {
270
+ const out = []; let y = y0;
271
+ if (e.cpu >= 0) { out.push([cx - 43, y - PILL_H / 2, cx + 43, y + PILL_H / 2 + 2]); y += below ? 26 : -26; }
272
+ for (const t of e.tags || []) { out.push(pillRect(cx, y, t.text, t.icon)); y += below ? 26 : -26; }
273
+ return out;
274
+ }
275
+ const stackHalfWidth = (e) => Math.max(0, e.cpu >= 0 ? 43 : 0, ...(e.tags || []).map((t) => pillWidth(t.text, 10.5, t.icon) / 2));
276
+ const widen = (b, cx, half) => (half ? [Math.min(b[0], cx - half - 5), b[1], Math.max(b[2], cx + half + 5), b[3]] : b);
277
+
278
+ /* ───────────────────────── entity renderers ─────────────────────────
279
+ Each returns { body, over, poly, bounds }:
280
+ body → depth-sorted geometry layer over → labels/pills (always on top)
281
+ poly → screen outline (links clip to it) bounds → [x0,y0,x1,y1] incl. pills */
282
+
283
+ const GLYPHS = {
284
+ server: (x, y, k = 1) => `<g transform="translate(${r2(x)} ${r2(y)}) scale(${k})" fill="none" stroke="${INK}" stroke-width="1.9" stroke-linecap="round">
285
+ <rect x="-11" y="-10" width="22" height="8.5" rx="2.2"/><rect x="-11" y="1.5" width="22" height="8.5" rx="2.2"/>
286
+ <path d="M-6.5 -5.75h.01M-6.5 5.75h.01" stroke-width="2.6"/><path d="M1 -5.75h5.5M1 5.75h5.5"/></g>`,
287
+ balancer: (x, y, k = 1) => `<g transform="translate(${r2(x)} ${r2(y)}) scale(${k})" fill="none" stroke="${INK}" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round">
288
+ <circle cx="-8" cy="0" r="3" fill="${INK}"/><path d="M-5 0h4M-1 0C3 0 3-8 8-8M-1 0C3 0 3 8 8 8M-1 0h9"/>
289
+ <path d="M5.5-10.5l3 2.5-3 2.5M5.5-2.5l3 2.5-3 2.5M5.5 5.5l3 2.5-3 2.5"/></g>`,
290
+ };
291
+
292
+ export const DEFAULTS = {
293
+ block: { s: 4, h: 46, color: 'blue', glyph: 'server', label: [], sub: '', heat: 0, dead: 0, dim: 0, opacity: 1, lift: 0, cpu: -1, tags: [], pills: 'above' },
294
+ device: { form: 'laptop', w: 6, d: 6, dim: 0, label: '', tags: [], opacity: 1, lift: 0 },
295
+ db: { r: 1.7, h: 38, dim: 0, color: 'purple', glyph: 'database', label: '', tags: [], opacity: 1, lift: 0, heat: 0, dead: 0, cpu: -1 },
296
+ crowd: { count: 0, dim: 0, label: '', opacity: 1, lift: 0 },
297
+ queue: { n: 0, dim: 0, gap: 1, dir: [0, -1], opacity: 1, color: '#efb041' },
298
+ zone: { label: '', dim: 0, tone: 'paper', opacity: 1 },
299
+ ghost: { s: 6, dim: 0, h: 90, opacity: 1, label: '' },
300
+ panel: { title: '', icon: 'sparkles', lines: [], bars: [], w: 0, opacity: 1, lift: 0, corner: null },
301
+ };
302
+
303
+ function renderBlock(e) {
304
+ const hx = (e.d ?? e.s) / 2, hy = (e.w ?? e.s) / 2;
305
+ const g = prism({ x0: e.x - hx, x1: e.x + hx, y0: e.y - hy, y1: e.y + hy, h: e.h, radius: e.radius ?? 9 });
306
+ const lift = e.lift, ty = g.ty;
307
+ const X = (iso(e.x - hx, e.y + hy, e.h)[0] + iso(e.x + hx, e.y - hy, e.h)[0]) / 2;
308
+ const labels = Array.isArray(e.label) ? e.label : e.label ? [e.label] : [];
309
+ const ly = ty + ((hx + hy) * 7 * 0.5 + e.h) * 0.4;
310
+ let text = '';
311
+ if (labels.length === 1 && !e.sub) text = svgText(X, ly + 4.5, labels[0], 13.5, 800);
312
+ else if (labels.length === 1) text = svgText(X, ly, labels[0], 13.5, 800) + svgText(X, ly + 14, e.sub, 10, 600);
313
+ else if (labels.length >= 2 && e.sub) text = svgText(X, ly - 9, labels[0], 13, 800) + svgText(X, ly + 6.5, labels[1], 13, 800) + svgText(X, ly + 20.5, e.sub, 10, 600);
314
+ else if (labels.length >= 2) text = svgText(X, ly - 3.5, labels[0], 13, 800) + svgText(X, ly + 12, labels[1], 13, 800);
315
+ const k = e.s >= 6 ? 1.15 : e.s < 3.5 ? 0.8 : 1;
316
+ const gy = labels.length ? ty - 1 : ty + 2;
317
+ const glyph = GLYPHS[e.glyph] ? GLYPHS[e.glyph](X, gy, k) : e.glyph ? iconSVG(e.glyph, X, gy, 24 * k, { stroke: 1.9 }) : '';
318
+ const fade = 1 - e.dead * 0.5 - e.dim * 0.35;
319
+ const cross = e.dead > 0.01 ? `<g opacity="${r2(e.dead)}" stroke="#c0392b" stroke-width="3.2" stroke-linecap="round"><path d="M${r2(X - 9)},${r2(ty - 10)} L${r2(X + 9)},${r2(ty + 8)} M${r2(X + 9)},${r2(ty - 10)} L${r2(X - 9)},${r2(ty + 8)}"/></g>` : '';
320
+ const body = `<g opacity="${r2(e.opacity)}">
321
+ ${shadowOf(g, e.h, lift, 0.26)}
322
+ <g transform="translate(0 ${r2(-lift)})">
323
+ ${e.heat > 0.01 ? `<g class="pulse"><path d="${g.sil}" fill="#f0552f" opacity="${r2(e.heat * 0.7)}" filter="url(#glow)"/></g>` : ''}
324
+ ${paintPrism(g, PALETTE[e.color] ? e.color : 'blue')}
325
+ ${e.heat > 0.01 ? `<path d="${g.sil}" fill="#f0552f" opacity="${r2(e.heat * 0.3)}"/>` : ''}
326
+ ${e.dead > 0.01 ? `<path d="${g.sil}" fill="#b9b2a8" opacity="${r2(e.dead * 0.62)}"/><path d="${g.sil}" fill="none" stroke="${INK}" stroke-width="1.9" stroke-linejoin="round"/>` : ''}
327
+ ${e.dim > 0.01 ? `<path d="${g.sil}" fill="#f4ebe0" opacity="${r2(e.dim * 0.45)}"/>` : ''}
328
+ <g opacity="${r2(fade)}">${e.dead > 0.5 ? '' : glyph}<g opacity="${r2(e.labelFade ?? 1)}">${text}</g></g>
329
+ ${cross}
330
+ </g></g>`;
331
+ const below = e.pills === 'below';
332
+ const y0 = below ? g.Bd[1] - lift + 20 : g.T[1] - lift - 17;
333
+ const st = pillStack(e, X, y0, below);
334
+ const over = st.svg ? `<g opacity="${r2(e.opacity)}">${st.svg}</g>` : '';
335
+ const poly = g.outline.map(([x, y]) => [x, y - lift]);
336
+ return {
337
+ body, over, poly,
338
+ boxes: [boxOf(poly), ...stackRects(e, X, y0, below)],
339
+ bounds: widen(boxOf(g.outline, below ? [8, 8, 8, 14 + st.n * 26] : [8, 8 + Math.max(st.n, 1) * 26, 8, 14]), X, stackHalfWidth(e)),
340
+ };
341
+ }
342
+
343
+ // small flat box with three visible faces (used for laptop parts)
344
+ function boxFaces({ x0, x1, y0, y1, z0, z1 }, { top, front, left, sw = 1.5, r = 2 }) {
345
+ const T = [iso(x0, y0, z1), iso(x0, y1, z1), iso(x1, y1, z1), iso(x1, y0, z1)];
346
+ const F = [iso(x1, y0, z1), iso(x1, y1, z1), iso(x1, y1, z0), iso(x1, y0, z0)];
347
+ const Lf = [iso(x0, y0, z1), iso(x1, y0, z1), iso(x1, y0, z0), iso(x0, y0, z0)];
348
+ const O = [iso(x0, y0, z1), iso(x0, y1, z1), iso(x1, y1, z1), iso(x1, y1, z0), iso(x1, y0, z0), iso(x0, y0, z0)];
349
+ return `<path d="${roundPoly(Lf, r)}" fill="${left}"/><path d="${roundPoly(F, r)}" fill="${front}"/><path d="${roundPoly(T, r)}" fill="${top}"/>
350
+ <path d="${roundPoly(O, r)}" fill="none" stroke="${INK}" stroke-width="${sw}" stroke-linejoin="round"/>`;
351
+ }
352
+ const tagStackBounds = (tags = [], ax, outline) => {
353
+ const half = Math.max(0, ...tags.map((t) => pillWidth(t.text, 10.5, t.icon) / 2));
354
+ const xs = outline.map((p) => p[0]);
355
+ return [Math.max(8, Math.min(...xs) - (ax - half) + 8), 18 + tags.length * 26, Math.max(8, ax + half + 8 - Math.max(...xs)), 40];
356
+ };
357
+
358
+ function renderDevice(e) {
359
+ const x0 = e.x - e.d / 2, x1 = e.x + e.d / 2, y0 = e.y - e.w / 2, y1 = e.y + e.w / 2, lift = e.lift;
360
+ const base = prism({ x0, x1, y0, y1, h: 16, radius: 9 });
361
+ let art, anchor;
362
+ if (e.form === 'phone') {
363
+ const P = { x0: e.x - 0.2, x1: e.x + 0.25, y0: e.y - 1.2, y1: e.y + 1.2, z0: 17, z1: 80 };
364
+ const sw = (P.y1 - P.y0) * 14, sh = P.z1 - P.z0, iw = sw - 5;
365
+ const screen = `<rect x="2.5" y="2.5" width="${r2(iw)}" height="${r2(sh - 5)}" rx="3.5" fill="#FBF8F4"/>
366
+ <rect x="${r2(sw / 2 - 4)}" y="3.6" width="8" height="2.2" rx="1.1" fill="#3D3935"/>
367
+ <rect x="2.5" y="8" width="${r2(iw)}" height="7" fill="#E4D9CB"/>
368
+ <rect x="5" y="19" width="${r2(iw * 0.62)}" height="7" rx="3" fill="#ECE6DC"/>
369
+ <rect x="${r2(2.5 + iw * 0.32)}" y="29" width="${r2(iw * 0.6)}" height="7" rx="3" fill="#CBBAE6"/>
370
+ <rect x="5" y="39" width="${r2(iw * 0.5)}" height="7" rx="3" fill="#ECE6DC"/>
371
+ <rect x="5" y="${r2(sh - 12)}" width="${r2(iw - 5)}" height="5" rx="2.5" fill="#E4D9CB"/>
372
+ <rect x="2.5" y="2.5" width="${r2(iw)}" height="${r2(sh - 5)}" rx="3.5" fill="url(#screen-glare)"/>`;
373
+ art = `<path d="${roundPoly([iso(P.x0 - 0.5, P.y0 - 0.3, 16), iso(P.x0 - 0.5, P.y1 + 0.3, 16), iso(P.x1 + 0.9, P.y1 + 0.3, 16), iso(P.x1 + 0.9, P.y0 - 0.3, 16)], 5)}" fill="#6b5236" opacity=".16" filter="url(#blur-sm)"/>
374
+ ${boxFaces(P, { top: '#8B8580', front: '#3D3935', left: '#6E6862', r: 3.5 })}
375
+ <g transform="${mapRightFace(P.x1, P.y0, P.z1)}">${screen}</g>`;
376
+ anchor = iso(P.x0, e.y, P.z1);
377
+ } else {
378
+ const S = { x0: x0 + 0.7, x1: x0 + 1.05, y0: y0 + 0.9, y1: y1 - 0.9, z0: 19, z1: 66 }; // lid
379
+ const K = { x0: S.x1, x1: S.x1 + 2.7, y0: S.y0, y1: S.y1, z0: 16, z1: 19 }; // keyboard deck
380
+ const sw = (S.y1 - S.y0) * 14, sh = S.z1 - S.z0, cols = Math.floor((sw - 6) / 4.7);
381
+ let keys = '';
382
+ for (let r = 0; r < 4; r++) for (let c = 0; c < cols; c++) keys += `<rect x="${r2(3 + c * 4.7)}" y="${r2(2.5 + r * 4.3)}" width="3.8" height="3.3" rx=".7"/>`;
383
+ const iw = sw - 6.8, ih = sh - 8;
384
+ const screen = `<rect x="3.4" y="3.4" width="${r2(iw)}" height="${r2(ih)}" rx="1.5" fill="#FBF8F4"/>
385
+ <rect x="3.4" y="3.4" width="${r2(iw)}" height="7" rx="1.5" fill="#E4D9CB"/>
386
+ <circle cx="6.6" cy="6.9" r="1" fill="#E5534B"/><circle cx="9.6" cy="6.9" r="1" fill="#EFB041"/><circle cx="12.6" cy="6.9" r="1" fill="#7FC278"/>
387
+ <rect x="16" y="5" width="${r2(iw - 16)}" height="3.8" rx="1.9" fill="#FBF8F4"/>
388
+ <rect x="7" y="14.5" width="${r2(iw - 7.2)}" height="12" rx="1.5" fill="url(#screen)"/>
389
+ <rect x="7" y="29.5" width="${r2((iw - 7.2) * 0.62)}" height="2.6" rx="1.3" fill="#D6CCBF"/>
390
+ <rect x="7" y="34" width="${r2((iw - 7.2) * 0.8)}" height="2.6" rx="1.3" fill="#D6CCBF"/>
391
+ <rect x="3.4" y="3.4" width="${r2(iw)}" height="${r2(ih)}" rx="1.5" fill="url(#screen-glare)"/>`;
392
+ art = `<path d="${roundPoly([iso(S.x0 - 0.3, S.y0 - 0.3, 16), iso(S.x0 - 0.3, S.y1 + 0.3, 16), iso(K.x1 + 0.3, K.y1 + 0.3, 16), iso(K.x1 + 0.3, K.y0 - 0.3, 16)], 6)}" fill="#6b5236" opacity=".14" filter="url(#blur-sm)"/>
393
+ ${boxFaces(K, { top: '#efeae4', front: '#cfc8c0', left: '#ddd6ce', r: 2.5, sw: 1.4 })}
394
+ <g transform="${mapTop(K.x0 + 0.15, K.y0, K.z1)}" fill="#fbf8f4" stroke="#b9b1a7" stroke-width=".55">${keys}<rect x="${r2(sw / 2 - 10)}" y="21.5" width="20" height="9" rx="1.6"/></g>
395
+ ${boxFaces(S, { top: '#8B8580', front: '#3D3935', left: '#6E6862', r: 3 })}
396
+ <g transform="${mapRightFace(S.x1, S.y0, S.z1)}">${screen}</g>`;
397
+ anchor = iso(S.x0, (S.y0 + S.y1) / 2, S.z1);
398
+ }
399
+ const body = `<g opacity="${r2(e.opacity)}">${shadowOf(base, 16, lift, 0.2)}<g transform="translate(0 ${r2(-lift)})">${paintPrism(base, 'slab', { stroke: '#3b3631', sw: 1.5 })}${art}</g></g>`;
400
+ const [lx, ly] = iso(x1, y0, 0), [ax, ay] = anchor;
401
+ let over = e.label ? `<g opacity="${r2(e.labelFade ?? 1)}">${pill(lx, ly + 22, e.label, { icon: e.labelIcon || 'user' })}</g>` : '';
402
+ let ty = ay - 22;
403
+ for (const t of e.tags || []) { over += `<g transform="translate(0 ${r2(ty)})" opacity="${r2(e.tagFade ?? 1)}">${pill(ax, 0, t.text, t)}</g>`; ty -= 26; }
404
+ over = over ? `<g opacity="${r2(e.opacity)}" transform="translate(0 ${r2(-lift)})">${over}</g>` : '';
405
+ const dpoly = base.outline.map(([x, y]) => [x, y - lift]);
406
+ const dboxes = [boxOf([...dpoly, [anchor[0], anchor[1] - lift]])];
407
+ if (e.label) dboxes.push(pillRect(lx, ly + 22 - lift, e.label, 'x'));
408
+ (e.tags || []).forEach((tg, i) => dboxes.push(pillRect(ax, ay - 22 - i * 26 - lift, tg.text, tg.icon)));
409
+ return { body, over, poly: dpoly, boxes: dboxes, bounds: boxOf([...base.outline, anchor], tagStackBounds(e.tags, ax, base.outline)) };
410
+ }
411
+
412
+ function renderDb(e) {
413
+ const rx = Math.SQRT2 * 14 * e.r, ry = rx / 2, [cx, cy] = iso(e.x, e.y, 0), lift = e.lift;
414
+ const bot = cy - lift, top = bot - e.h;
415
+ const col = PALETTE[e.color] ? e.color : 'purple';
416
+ const shape = `M${r2(cx - rx)},${r2(top)} V${r2(bot)} A${r2(rx)},${r2(ry)} 0 0 0 ${r2(cx + rx)},${r2(bot)} V${r2(top)} Z`;
417
+ const edge = `M${r2(cx - rx)},${r2(top)} V${r2(bot)} A${r2(rx)},${r2(ry)} 0 0 0 ${r2(cx + rx)},${r2(bot)} V${r2(top)}`;
418
+ const fadeShadow = 1 - Math.min(1, lift / 140) * 0.85, f = e.cpu >= 0 ? clamp01(e.cpu) : 0;
419
+ let fill = '';
420
+ if (f > 0.004) {
421
+ const fy = bot - f * e.h, [c1, c2] = e.cpu < 0.6 ? ['#cfe8c0', '#5fa95a'] : e.cpu < 0.85 ? ['#f9dca3', '#d99a2b'] : ['#f5bdb2', '#d9473d'];
422
+ fill = `<path d="M${r2(cx - rx)},${r2(fy)} A${r2(rx)},${r2(ry)} 0 0 0 ${r2(cx + rx)},${r2(fy)} V${r2(bot)} A${r2(rx)},${r2(ry)} 0 0 1 ${r2(cx - rx)},${r2(bot)} Z" fill="${c1}" opacity=".92"/>
423
+ ${f < 0.995 ? `<path d="M${r2(cx - rx + 1)},${r2(fy)} A${r2(rx - 1)},${r2(ry - 0.5)} 0 0 0 ${r2(cx + rx - 1)},${r2(fy)}" fill="none" stroke="${c2}" stroke-width="1.6" stroke-linecap="round"/>` : ''}`;
424
+ }
425
+ const body = `<g opacity="${r2(e.opacity)}">
426
+ <ellipse cx="${r2(cx)}" cy="${r2(cy + 5)}" rx="${r2(rx + 3)}" ry="${r2(ry + 1)}" fill="#6b5236" opacity="${r2(0.22 * fadeShadow)}" filter="url(#blur-md)"/>
427
+ ${e.heat > 0.01 ? `<g class="pulse"><path d="${shape}" fill="#f0552f" opacity="${r2(e.heat * 0.7)}" filter="url(#glow)"/></g>` : ''}
428
+ <path d="${shape}" fill="url(#g-${col}-side)"/>${fill}<path d="${shape}" fill="url(#cyl-sheen)"/>
429
+ <ellipse cx="${r2(cx)}" cy="${r2(top)}" rx="${r2(rx)}" ry="${r2(ry)}" fill="url(#g-${col}-top)"/>
430
+ <path d="M${r2(cx - rx + 3)},${r2(top + 2.5)} A${r2(rx - 3)},${r2(ry - 2)} 0 0 0 ${r2(cx + rx - 3)},${r2(top + 2.5)}" fill="none" stroke="#ffffff" stroke-opacity=".7" stroke-width="1.4"/>
431
+ ${e.dead > 0.01 ? `<path d="${shape}" fill="#b9b2a8" opacity="${r2(e.dead * 0.62)}"/>` : ''}
432
+ <path d="${edge}" fill="none" stroke="${INK}" stroke-width="1.9" stroke-linejoin="round"/>
433
+ <ellipse cx="${r2(cx)}" cy="${r2(top)}" rx="${r2(rx)}" ry="${r2(ry)}" fill="none" stroke="${INK}" stroke-width="1.9"/>
434
+ ${e.glyph ? iconSVG(e.glyph, cx, top + ry + e.h / 2, 19, { stroke: 1.8 }) : ''}
435
+ ${e.dead > 0.01 ? `<g opacity="${r2(e.dead)}" stroke="#c0392b" stroke-width="3.2" stroke-linecap="round"><path d="M${r2(cx - 9)},${r2(top + 8)} L${r2(cx + 9)},${r2(top + 26)} M${r2(cx + 9)},${r2(top + 8)} L${r2(cx - 9)},${r2(top + 26)}"/></g>` : ''}
436
+ </g>`;
437
+ const lw = e.label ? pillWidth(e.label, 10.5, 'x') : 0;
438
+ let over = e.label ? `<g opacity="${r2(e.labelFade ?? 1)}">${pill(cx + rx + 10 + lw / 2, bot - e.h * 0.35, e.label, { icon: e.labelIcon || 'database' })}</g>` : '';
439
+ const st = pillStack(e, cx, top - ry - 15, false);
440
+ over += st.svg;
441
+ over = over ? `<g opacity="${r2(e.opacity)}">${over}</g>` : '';
442
+ const poly = [];
443
+ for (let i = 0; i <= 8; i++) poly.push([cx - rx * Math.cos((Math.PI * i) / 8), top - ry * Math.sin((Math.PI * i) / 8)]);
444
+ for (let i = 0; i <= 8; i++) poly.push([cx + rx * Math.cos((Math.PI * i) / 8), bot + ry * Math.sin((Math.PI * i) / 8)]);
445
+ const boxes = [[cx - rx, top - ry, cx + rx, bot + ry], ...stackRects(e, cx, top - ry - 15, false)];
446
+ if (e.label) boxes.push([cx + rx + 10, bot - e.h * 0.35 - PILL_H / 2, cx + rx + 10 + lw, bot - e.h * 0.35 + PILL_H / 2 + 2]);
447
+ return { body, over, poly, boxes, bounds: widen([cx - rx - 8, top - ry - 12 - st.n * 26, cx + rx + (e.label ? lw + 18 : 8), bot + ry + 10], cx, stackHalfWidth(e)) };
448
+ }
449
+
450
+ const PEOPLE = ['#F3B47F', '#A9C5E8', '#B3D79F', '#CBBAE6', '#F6CD82'];
451
+ const hash2 = (a, b) => { const n = Math.sin(a * 127.1 + b * 311.7) * 43758.5453; return n - Math.floor(n); };
452
+ function person(x, y, z, a, color) {
453
+ const [px, py] = iso(x, y, z), k = (0.35 + 0.65 * a) * 1.3;
454
+ return `<g opacity="${r2(a)}" transform="translate(${r2(px)} ${r2(py - (1 - a) * 10)}) scale(${r2(k)})">
455
+ <ellipse cx="0" cy="0" rx="5.6" ry="2.8" fill="#6b5236" opacity=".18"/>
456
+ <path d="M-5.2,0 V-9 A5.2,5.2 0 0 1 5.2,-9 V0 A5.2,2.4 0 0 1 -5.2,0 Z" fill="${color}" stroke="${INK}" stroke-width="1.25"/>
457
+ <circle cx="0" cy="-17.6" r="4.3" fill="#fdf6ec" stroke="${INK}" stroke-width="1.25"/></g>`;
458
+ }
459
+ function renderCrowd(e) {
460
+ const g = prism({ x0: e.x0, x1: e.x1, y0: e.y0, y1: e.y1, h: 10, radius: 8 });
461
+ const mx = (e.x0 + e.x1) / 2, my = (e.y0 + e.y1) / 2, sp = 1.75;
462
+ const ni = Math.floor(((e.x1 - e.x0) / 2 - 0.85) / sp), nj = Math.floor(((e.y1 - e.y0) / 2 - 0.85) / sp);
463
+ const cells = [];
464
+ for (let i = -ni; i <= ni; i++) for (let j = -nj; j <= nj; j++) cells.push({ i, j, key: Math.abs(i) + hash2(i, j) * 1.6 });
465
+ cells.sort((a, b) => a.key - b.key);
466
+ const people = cells.map((c, n) => ({ ...c, a: clamp01(e.count - n) })).filter((c) => c.a > 0.01)
467
+ .sort((a, b) => a.i - a.j - (b.i - b.j))
468
+ .map((c) => person(mx + c.i * sp, my + c.j * sp, 10, c.a, PEOPLE[Math.abs(c.i * 3 + c.j * 7) % PEOPLE.length])).join('');
469
+ const lift = e.lift, [lx, ly] = iso(e.x1, e.y0, 0);
470
+ return {
471
+ body: `<g opacity="${r2(e.opacity)}">${shadowOf(g, 10, lift, 0.2)}<g transform="translate(0 ${r2(-lift)})">${paintPrism(g, 'slab', { stroke: '#3b3631', sw: 1.5 })}${people}</g></g>`,
472
+ over: e.label ? `<g opacity="${r2(e.opacity * (e.labelFade ?? 1))}" transform="translate(0 ${r2(-lift)})">${pill(lx, ly + 22, e.label, { icon: 'users' })}</g>` : '',
473
+ poly: g.outline.map(([x, y]) => [x, y - lift]),
474
+ boxes: [boxOf(g.outline, [0, 30, 0, 0]), ...(e.label ? [pillRect(lx, ly + 22, e.label, 'x')] : [])],
475
+ bounds: boxOf(g.outline, [8, 34, 8, 40]),
476
+ };
477
+ }
478
+ function renderQueue(e) {
479
+ let body = ''; const pts = [];
480
+ for (let i = Math.ceil(e.n) - 1; i >= 0; i--) {
481
+ const a = clamp01(e.n - i), [x, y] = iso(e.x + e.dir[0] * e.gap * i, e.y + e.dir[1] * e.gap * i, 0);
482
+ pts.push([x, y]);
483
+ body += `<g opacity="${r2(a * e.opacity)}" transform="translate(${r2(x)} ${r2(y - (1 - a) * 8)}) scale(${r2(0.5 + a * 0.5)})"><circle r="4.6" fill="${e.color}" stroke="${INK}" stroke-width="1.5"/></g>`;
484
+ }
485
+ return { body, over: '', poly: null, bounds: pts.length ? boxOf(pts, [8, 8, 8, 8]) : [0, 0, 0, 0] };
486
+ }
487
+ function renderZone(e) {
488
+ const pts = [iso(e.x0, e.y0), iso(e.x0, e.y1), iso(e.x1, e.y1), iso(e.x1, e.y0)];
489
+ const fill = e.tone && e.tone !== 'paper' && TONES[e.tone] ? TONES[e.tone].bg : '#fffaf2';
490
+ const label = e.label ? `<text transform="${mapTopX(e.x0 + 0.9, e.y0 + 0.55, 0)}" font-size="10.5" font-weight="800" letter-spacing="1.6" fill="#6f6961">${esc(String(e.label).toUpperCase())}</text>` : '';
491
+ return {
492
+ body: `<g opacity="${r2(e.opacity)}"><path d="${roundPoly(pts, 8)}" fill="${fill}" fill-opacity=".55" stroke="${INK}" stroke-opacity=".55" stroke-width="1.5" stroke-dasharray="6 5"/>${label}</g>`,
493
+ over: '', poly: pts, bounds: boxOf(pts, [6, 6, 6, 6]),
494
+ };
495
+ }
496
+ function renderGhost(e) {
497
+ const x0 = e.x - e.s / 2, x1 = e.x + e.s / 2, y0 = e.y - e.s / 2, y1 = e.y + e.s / 2;
498
+ const t = [iso(x0, y0, e.h), iso(x0, y1, e.h), iso(x1, y1, e.h), iso(x1, y0, e.h)], b = [iso(x0, y0), iso(x0, y1), iso(x1, y1), iso(x1, y0)];
499
+ const ln = (p, q, back) => `<path d="M${p[0]},${p[1]} L${q[0]},${q[1]}" stroke="${INK}" stroke-opacity="${back ? 0.22 : 0.55}" stroke-width="1.4" stroke-dasharray="5 4" fill="none"/>`;
500
+ const lines = [ln(t[0], t[1]), ln(t[1], t[2]), ln(t[2], t[3]), ln(t[3], t[0]), ln(b[0], b[3]), ln(b[3], b[2]), ln(t[0], b[0]), ln(t[2], b[2]), ln(t[3], b[3]), ln(b[0], b[1], 1), ln(b[1], b[2], 1), ln(t[1], b[1], 1)].join('');
501
+ const [ux, uy] = t[2], lw = pillWidth(e.label || '', 10.5, 'x');
502
+ return {
503
+ body: `<g opacity="${r2(e.opacity)}">${lines}</g>`,
504
+ over: e.label ? `<g opacity="${r2(e.opacity)}">${pill(ux + 14 + lw / 2, uy + 18, e.label, { tone: 'gray', icon: e.icon || 'triangle' })}</g>` : '',
505
+ poly: null, bounds: boxOf([...t, ...b, [ux + 22 + lw, uy]], [8, 30, 8, 8]),
506
+ };
507
+ }
508
+ // Panel = a docked "info card" (lines with markers, optional bar chart). Lives in screen space.
509
+ // Line markers: "= " good row, "! " bad row, "# " muted comment, **bold** inline.
510
+ function richLine(s) {
511
+ return esc(s).split('**').map((p, i) => (i % 2 ? `<tspan font-weight="800" fill="${INK}">${p}</tspan>` : p)).join('');
512
+ }
513
+ const BAR = { green: '#9FD28F', amber: '#EFB041', red: '#E5534B', gray: '#B5AB9E', violet: '#CBBAE6', blue: '#A9C5E8' };
514
+ export function renderPanel(e) {
515
+ const strip = (l) => l.replace(/\*\*/g, '').replace(/^[=#!] /, '');
516
+ const labW = e.bars.length ? Math.max(...e.bars.map((b) => textWidth(b.label, 10.5))) + 14 : 0;
517
+ const noteW = e.bars.length ? Math.max(46, ...e.bars.map((b) => textWidth(b.note || '', 10) + 12)) : 0;
518
+ const W = Math.max(e.w, textWidth(e.title, 10) + e.title.length + 48, ...e.lines.map((l) => textWidth(strip(l), 11.5) + 30), e.bars.length ? labW + 184 + noteW : 0);
519
+ const chartH = e.bars.length * 19;
520
+ const H = 34 + e.lines.length * 18 + (e.bars.length ? chartH + 12 : 0) + 6;
521
+ const w = e.boxW ?? W, h = e.boxH ?? H, x = 0, y = 0;
522
+ let rows = '';
523
+ e.lines.forEach((l, i) => {
524
+ const ly = y + 34 + i * 18 + 12;
525
+ if (l.startsWith('= ')) rows += `<rect x="${x + 10}" y="${ly - 13}" width="${W - 20}" height="18" rx="5" fill="#dcefd2"/><text x="${x + 16}" y="${ly}" font-size="11.5" font-weight="800" fill="#24521c">${richLine(l.slice(2))}</text>`;
526
+ else if (l.startsWith('! ')) rows += `<rect x="${x + 10}" y="${ly - 13}" width="${W - 20}" height="18" rx="5" fill="#f8d5cf"/><text x="${x + 16}" y="${ly}" font-size="11.5" font-weight="800" fill="#8f2a22">${richLine(l.slice(2))}</text>`;
527
+ else if (l.startsWith('# ')) rows += `<text x="${x + 16}" y="${ly}" font-size="10.5" font-weight="500" fill="#8b847a">${richLine(l.slice(2))}</text>`;
528
+ else rows += `<text x="${x + 16}" y="${ly}" font-size="11.5" font-weight="500" fill="#34302b">${richLine(l)}</text>`;
529
+ });
530
+ let bars = '';
531
+ if (e.bars.length) {
532
+ const top = y + 34 + e.lines.length * 18 + 8, bx = x + 16 + labW, bw = W - 32 - labW - noteW;
533
+ e.bars.forEach((b, i) => {
534
+ const by = top + i * 19, from = b.from || 0, to = b.to ?? b.value ?? 1, ax = bx + from * bw, aw = Math.max(3, (to - from) * bw);
535
+ bars += `<text x="${x + 16}" y="${r2(by + 12)}" font-size="10.5" font-weight="${b.bold ? 800 : 500}" fill="#34302b">${esc(b.label)}</text>
536
+ <rect x="${r2(bx)}" y="${r2(by + 3)}" width="${r2(bw)}" height="11" rx="3" fill="#f1e8db"/>
537
+ <rect x="${r2(ax)}" y="${r2(by + 3)}" width="${r2(aw)}" height="11" rx="3" fill="${BAR[b.tone || 'gray']}" stroke="${INK}" stroke-opacity=".55" stroke-width="1"/>
538
+ <text x="${r2(ax + aw + 6)}" y="${r2(by + 12)}" font-size="10" font-weight="800" fill="${INK}">${esc(b.note || '')}</text>`;
539
+ });
540
+ }
541
+ const svg = `<g opacity="${r2(e.opacity)}">
542
+ <rect x="${x}" y="${y + 2.5}" width="${r2(w)}" height="${r2(h)}" rx="10" fill="${DROP}"/>
543
+ <rect x="${x}" y="${y}" width="${r2(w)}" height="${r2(h)}" rx="10" fill="#fbf7f1" stroke="${INK}" stroke-width="1.4"/>
544
+ <path d="M${x + 12},${y + 30} H${r2(x + w - 12)}" stroke="#e6ddd0" stroke-width="1"/>
545
+ <g opacity="${r2(e.fade ?? 1)}">
546
+ ${iconSVG(e.icon, x + 20, y + 18, 13, { stroke: 2.1, color: '#6f6961' })}
547
+ <text x="${x + 33}" y="${y + 21.5}" font-size="10" font-weight="800" letter-spacing="1" fill="#6f6961">${esc(String(e.title).toUpperCase())}</text>
548
+ ${rows}${bars}
549
+ </g></g>`;
550
+ return { body: '', over: svg, poly: null, bounds: null, size: { w: W, h: H } };
551
+ }
552
+
553
+ export const RENDER = { block: renderBlock, device: renderDevice, db: renderDb, crowd: renderCrowd, queue: renderQueue, zone: renderZone, ghost: renderGhost, panel: renderPanel };
554
+ const FLOOR = new Set(['zone']);
555
+ export const withDefaults = (e) => ({ ...DEFAULTS[e.type], ...e });
556
+ export function footprint(e) { // iso-space rect [x0,x1,y0,y1]
557
+ if (e.type === 'crowd' || e.type === 'zone') return [e.x0, e.x1, e.y0, e.y1];
558
+ if (e.type === 'device') return [e.x - e.d / 2, e.x + e.d / 2, e.y - e.w / 2, e.y + e.w / 2];
559
+ if (e.type === 'db') return [e.x - e.r, e.x + e.r, e.y - e.r, e.y + e.r];
560
+ const hx = (e.d ?? e.s ?? 4) / 2, hy = (e.w ?? e.s ?? 4) / 2;
561
+ return [e.x - hx, e.x + hx, e.y - hy, e.y + hy];
562
+ }
563
+ export const centerOf = (e) => (e.type === 'crowd' || e.type === 'zone' ? [(e.x0 + e.x1) / 2, (e.y0 + e.y1) / 2] : [e.x, e.y]);
564
+ const depthKey = (e) => (e.type === 'zone' ? -1e4 : e.type === 'queue' ? -1e3 : e.type === 'panel' ? 1e4 : centerOf(e)[0] - centerOf(e)[1] - (e.type === 'ghost' ? 0.5 : 0));
565
+
566
+ // Resolve a link waypoint: "id", "id+2", [x,y], ["idA","idB"] (x of A, y of B), ["id+1", 4]…
567
+ export function resolvePoint(p, centerOfId) {
568
+ const one = (s, axis) => { const m = /^([\w.-]+?)([+-][\d.]+)?$/.exec(s); const c = centerOfId(m[1]); if (!c) throw new Error(`unknown entity "${m[1]}" in link point`); return c[axis] + (m[2] ? parseFloat(m[2]) : 0); };
569
+ if (typeof p === 'string') return [one(p, 0), one(p, 1)];
570
+ return [typeof p[0] === 'string' ? one(p[0], 0) : p[0], typeof p[1] === 'string' ? one(p[1], 1) : p[1]];
571
+ }
572
+
573
+ /* ───────────────────────── link labels ───────────────────────── */
574
+
575
+ const LABEL_SIZE = 9.5;
576
+ const labelBox = (text) => { const lines = String(text).split('\n'); return { w: pillWidth(text, LABEL_SIZE), h: PILL_H + (lines.length - 1) * Math.round(LABEL_SIZE * 1.3) }; };
577
+ // Candidate label spots along a path (screen px). Each: { key, cx, cy, rect }.
578
+ function labelSpots(pts, t0, w, h) {
579
+ const out = [];
580
+ [0, -0.08, 0.08, -0.16, 0.16, -0.24, 0.24, -0.32, 0.32, -0.4, 0.4].forEach((dt, k) => {
581
+ const t = t0 + dt;
582
+ if (k && (t < 0.06 || t > 0.94)) return;
583
+ const p = pointAt(pts, t), nx = -p.dy, ny = p.dx;
584
+ // on the line itself (pill has an opaque fill), then beside it, near and far
585
+ out.push({ t, side: 0, gap: 0, cx: p.x, cy: p.y, rect: [p.x - w / 2, p.y - h / 2, p.x + w / 2, p.y + h / 2], drift: Math.abs(dt) + 0.1, onLine: true });
586
+ [7, 19].forEach((gap, gi) => {
587
+ const off = Math.abs(nx) * (w / 2) + Math.abs(ny) * (h / 2) + gap;
588
+ [1, -1].forEach((side) => {
589
+ const cx = p.x + nx * off * side, cy = p.y + ny * off * side;
590
+ out.push({ t, side, gap, cx, cy, rect: [cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2], drift: Math.abs(dt) + gi * 0.12 });
591
+ });
592
+ });
593
+ });
594
+ return out;
595
+ }
596
+ function spotAt(pts, pick, w, h) {
597
+ const p = pointAt(pts, pick.t), nx = -p.dy, ny = p.dx, off = Math.abs(nx) * (w / 2) + Math.abs(ny) * (h / 2) + (pick.gap ?? 7);
598
+ if (!pick.side) return [p.x, p.y];
599
+ return [p.x + nx * off * pick.side, p.y + ny * off * pick.side];
600
+ }
601
+
602
+ /* ───────────────────────── Stage ───────────────────────── */
603
+
604
+ const NS = 'http://www.w3.org/2000/svg';
605
+ const el = (tag, a = {}) => { const n = document.createElementNS(NS, tag); for (const [k, v] of Object.entries(a)) n.setAttribute(k, v); return n; };
606
+ export const TIMING = { exit: 420, move: 820, enter: 680, stagger: 130, draw: 560 };
607
+ const MAX_ZOOM = 1.6, MIN_ZOOM = 0.3, PAD = 16, HEAD_GAP = 16;
608
+ const PKT_SPEED = 155, KIND_SPEED = { heavy: 0.7, ping: 0.85, slow: 0.32 };
609
+ const ENTER_FROM = { crowd: { count: 0, lift: 26 }, device: { lift: 40 }, ghost: {}, zone: {}, queue: { n: 0, opacity: 1 }, panel: { lift: -14 } };
610
+ const EXIT_TO = { crowd: { count: 0 }, queue: { n: 0, opacity: 1 }, ghost: {}, zone: {}, panel: { lift: -10 } };
611
+ const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
612
+
613
+ function defsSVG() {
614
+ let g = '';
615
+ for (const [k, c] of Object.entries(PALETTE)) {
616
+ g += `<linearGradient id="g-${k}-top" x1="0" y1="0" x2="0.35" y2="1"><stop offset="0" stop-color="${c.top[0]}"/><stop offset="1" stop-color="${c.top[1]}"/></linearGradient>
617
+ <linearGradient id="g-${k}-side" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${c.side[0]}"/><stop offset="1" stop-color="${c.side[1]}"/></linearGradient>`;
618
+ }
619
+ return `${g}
620
+ <linearGradient id="screen" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#E3D6F3"/><stop offset="1" stop-color="#C9B5E6"/></linearGradient>
621
+ <linearGradient id="screen-glare" x1="0" y1="0" x2="1" y2="0.6"><stop offset="0" stop-color="#FFFFFF" stop-opacity=".35"/><stop offset=".45" stop-color="#FFFFFF" stop-opacity="0"/></linearGradient>
622
+ <linearGradient id="cyl-sheen" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#ffffff" stop-opacity="0"/><stop offset=".3" stop-color="#ffffff" stop-opacity=".35"/><stop offset=".55" stop-color="#ffffff" stop-opacity=".05"/><stop offset="1" stop-color="#4b2f6b" stop-opacity=".08"/></linearGradient>
623
+ <filter id="blur-sm" x="-20%" y="-20%" width="140%" height="140%"><feGaussianBlur stdDeviation="2.2"/></filter>
624
+ <filter id="blur-md" x="-30%" y="-30%" width="160%" height="160%"><feGaussianBlur stdDeviation="4"/></filter>
625
+ <filter id="blur-lg" x="-30%" y="-30%" width="160%" height="160%"><feGaussianBlur stdDeviation="6.5"/></filter>
626
+ <filter id="glow" x="-40%" y="-40%" width="180%" height="180%"><feGaussianBlur stdDeviation="9"/></filter>
627
+ <marker id="arrow" viewBox="0 0 10 10" refX="8.6" refY="5" markerWidth="5.2" markerHeight="5.2" orient="auto-start-reverse" markerUnits="strokeWidth"><path d="M1,1.2 L9,5 L1,8.8 Z" fill="${INK}" stroke="${INK}" stroke-width="1" stroke-linejoin="round"/></marker>
628
+ <marker id="arrow-muted" viewBox="0 0 10 10" refX="8.6" refY="5" markerWidth="5.2" markerHeight="5.2" orient="auto-start-reverse" markerUnits="strokeWidth"><path d="M1,1.2 L9,5 L1,8.8 Z" fill="#a59c90" stroke="#a59c90" stroke-width="1" stroke-linejoin="round"/></marker>
629
+ <marker id="arrow-red" viewBox="0 0 10 10" refX="8.6" refY="5" markerWidth="5.2" markerHeight="5.2" orient="auto-start-reverse" markerUnits="strokeWidth"><path d="M1,1.2 L9,5 L1,8.8 Z" fill="#c0392b" stroke="#c0392b" stroke-width="1" stroke-linejoin="round"/></marker>
630
+ <pattern id="iso-grid" patternUnits="userSpaceOnUse" x="0" y="-7" width="28" height="14"><path d="M0 7 L14 0 L28 7 L14 14 Z" fill="none" stroke="#a8916f" stroke-opacity=".3" stroke-width=".8"/></pattern>`;
631
+ }
632
+
633
+ export class Stage {
634
+ constructor(host, { reducedMotion = false } = {}) {
635
+ this.host = host;
636
+ this.reduced = reducedMotion;
637
+ this.svg = el('svg', { class: 'stage-svg', xmlns: NS, preserveAspectRatio: 'xMidYMid meet', role: 'img' });
638
+ this.svg.innerHTML = `<defs class="defs-theme">${themed(defsSVG())}</defs>
639
+ <defs><radialGradient id="grid-fade" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#fff"/><stop offset=".42" stop-color="#fff" stop-opacity=".92"/><stop offset=".78" stop-color="#fff" stop-opacity=".35"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></radialGradient>
640
+ <mask id="grid-mask" maskUnits="userSpaceOnUse" x="-6000" y="-6000" width="12000" height="12000"><rect x="-6000" y="-6000" width="12000" height="12000" fill="url(#grid-fade)"/></mask></defs>
641
+ <rect class="stage-grid" x="-6000" y="-6000" width="12000" height="12000" fill="url(#iso-grid)" mask="url(#grid-mask)"/>
642
+ <g class="layer-floor"></g><g class="layer-links"></g><g class="layer-packets"></g><g class="layer-ents"></g><g class="layer-over"></g><g class="layer-hud"></g>`;
643
+ host.appendChild(this.svg);
644
+ const q = (s) => this.svg.querySelector(s);
645
+ this.L = { floor: q('.layer-floor'), links: q('.layer-links'), packets: q('.layer-packets'), ents: q('.layer-ents'), over: q('.layer-over'), hud: q('.layer-hud') };
646
+ this.fadeGrad = q('#grid-fade');
647
+ this.defs = q('.defs-theme');
648
+ this.ents = new Map(); this.links = new Map(); this.plans = new Map();
649
+ this.scenes = []; this.scene = null; this.flows = []; this.packets = [];
650
+ this.anim = null; this.paused = false; this.view = null; this.blend = null;
651
+ this.showCards = true; this.hudScale = 1.12; this.last = performance.now();
652
+ this.onCards = null; this.onView = null; this.onSwipe = null; this.onSettle = null;
653
+ this.size = '';
654
+ this.onInspect = null;
655
+ this.ro = new ResizeObserver(() => { const s = `${host.clientWidth}x${host.clientHeight}`; if (s !== this.size) { this.size = s; this.refit(); } });
656
+ this.ro.observe(host);
657
+ this.gestures();
658
+ // entities with `inside` open their drill-down on click / Enter
659
+ const pick = (ev) => { const g = ev.target.closest?.('[data-id]'); const e = g && this.ents.get(g.dataset.id); return e && e.cur.inside ? e : null; };
660
+ this.svg.addEventListener('click', (ev) => {
661
+ const e = pick(ev);
662
+ if (e) { ev.stopPropagation(); this.onInspect?.(e.id, e.cur); return; }
663
+ const g = ev.target.closest?.('[data-id]'), other = g && this.ents.get(g.dataset.id);
664
+ if (other && !['zone', 'queue', 'panel'].includes(other.cur.type)) this.onPlainClick?.(other.id, other.cur);
665
+ });
666
+ this.svg.addEventListener('keydown', (ev) => { if (ev.key !== 'Enter' && ev.key !== ' ') return; const e = pick(ev); if (e) { ev.preventDefault(); ev.stopPropagation(); this.onInspect?.(e.id, e.cur); } });
667
+ const loop = (t) => { if (this.dead) return; this.tick(t); requestAnimationFrame(loop); };
668
+ requestAnimationFrame(loop);
669
+ }
670
+ destroy() { this.dead = true; this.ro.disconnect(); this.clear(); this.svg.remove(); }
671
+ // Zoom the camera into one entity (used before opening its inside view).
672
+ focusOn(id, k = 2.4) {
673
+ const e = this.ents.get(id); if (!e?.bounds) return;
674
+ const [x0, y0, x1, y1] = e.poly ? [Math.min(...e.poly.map((p) => p[0])), Math.min(...e.poly.map((p) => p[1])), Math.max(...e.poly.map((p) => p[0])), Math.max(...e.poly.map((p) => p[1]))] : e.bounds;
675
+ this.setView({ k, cx: (x0 + x1) / 2, cy: (y0 + y1) / 2 }, true);
676
+ }
677
+
678
+ /* ── layout & camera ── */
679
+ layoutOf(scene) {
680
+ const ents = Object.fromEntries(Object.entries(scene.entities || {}).map(([k, v]) => [k, withDefaults(v)]));
681
+ const center = (id) => ents[id] && centerOf(ents[id]);
682
+ const boxes = [], polys = [], obstacles = [], texts = [], labelRects = [];
683
+ let b = [Infinity, Infinity, -Infinity, -Infinity], panel = null;
684
+ const grow = (r) => { b = [Math.min(b[0], r[0]), Math.min(b[1], r[1]), Math.max(b[2], r[2]), Math.max(b[3], r[3])]; };
685
+ const shapes = {};
686
+ for (const [id, e] of Object.entries(ents)) {
687
+ if (e.type === 'panel') { if (this.showCards) panel = { ...renderPanel(e).size, corner: e.corner }; continue; }
688
+ const r = RENDER[e.type](e);
689
+ shapes[id] = r.poly; grow(r.bounds); boxes.push(r.bounds);
690
+ if (e.type !== 'zone') { const bx = r.boxes || [r.bounds]; obstacles.push(bx[0]); texts.push(...bx.slice(1)); }
691
+ if (r.poly && e.type !== 'zone') polys.push(r.poly);
692
+ }
693
+ const paths = {}; const samples = [];
694
+ for (const [id, l] of Object.entries(scene.links || {})) {
695
+ if (!ents[l.from] || (l.to && !ents[l.to])) continue;
696
+ let pts = l.pts.map((p) => iso(...resolvePoint(p, center)));
697
+ pts = clipStart(pts, shapes[l.from], 3);
698
+ if (l.to) pts = clipEnd(pts, shapes[l.to], l.heads === 'none' ? 3 : 4);
699
+ paths[id] = pts;
700
+ for (const [x, y] of samplePath(pts)) { samples.push([x, y, id]); grow([x - 3, y - 3, x + 3, y + 3]); }
701
+ }
702
+ const picks = {};
703
+ for (const [id, l] of Object.entries(scene.links || {})) {
704
+ if (!l.label || !paths[id]) continue;
705
+ const { w, h } = labelBox(l.label);
706
+ let best = null;
707
+ for (const s of labelSpots(paths[id], l.labelAt ?? 0.5, w, h)) {
708
+ let cost = s.drift * 90 + (s.side < 0 ? 2 : 0) + (s.onLine ? 12 : 0);
709
+ const pad = [s.rect[0] - 3, s.rect[1] - 3, s.rect[2] + 3, s.rect[3] + 3];
710
+ for (const o of obstacles) { const a = overlap(pad, o); if (a) cost += 110 + a / 5; }
711
+ for (const o of texts) { const a = overlap(pad, o); if (a) cost += 260 + a / 2; }
712
+ for (const o of labelRects) { const a = overlap([s.rect[0] - 4, s.rect[1] - 4, s.rect[2] + 4, s.rect[3] + 4], o); if (a) cost += 300 + a / 2; }
713
+ for (const [x, y, lid] of samples) if (lid !== id && x > s.rect[0] - 3 && x < s.rect[2] + 3 && y > s.rect[1] - 3 && y < s.rect[3] + 3) cost += 14;
714
+ if (!best || cost < best.cost) best = { ...s, cost };
715
+ }
716
+ picks[id] = { t: best.t, side: best.side, gap: best.gap };
717
+ labelRects.push(best.rect); grow([best.rect[0] - 2, best.rect[1] - 2, best.rect[2] + 2, best.rect[3] + 4]);
718
+ }
719
+ if (b[0] === Infinity) b = [-100, -60, 100, 60];
720
+ return { b, boxes: [...obstacles, ...texts, ...labelRects], polys, panel, picks };
721
+ }
722
+ panelRect(corner, size) {
723
+ const W = this.host.clientWidth, H = this.host.clientHeight, w = size.w * this.hudScale, h = (size.h + 4) * this.hudScale;
724
+ const x = corner[1] === 'l' ? 10 : W - 10 - w, y = corner[0] === 't' ? HEAD_GAP : H - 10 - h;
725
+ return [x, y, x + w, y + h];
726
+ }
727
+ planFor(scene, prev) {
728
+ const lay = this.layoutOf(scene), W = Math.max(1, this.host.clientWidth), H = Math.max(1, this.host.clientHeight);
729
+ const [x0, y0, x1, y1] = lay.b, bw = Math.max(1, x1 - x0), bh = Math.max(1, y1 - y0);
730
+ const camFor = (z, ax, ay) => {
731
+ const sx = ax === 0 ? (W - bw * z) / 2 : ax < 0 ? PAD : W - PAD - bw * z;
732
+ const sy = ay === 0 ? (H - bh * z) / 2 : ay < 0 ? PAD : H - PAD - bh * z;
733
+ return { x: x0 - sx / z, y: y0 - sy / z, w: W / z, h: H / z };
734
+ };
735
+ const snap = (z) => Math.max(MIN_ZOOM, Math.floor(z * 20 + 1e-6) / 20);
736
+ const fit = Math.min(MAX_ZOOM, (W - 2 * PAD) / bw, (H - 2 * PAD) / bh);
737
+ const clear = (cam, corner) => {
738
+ const k = W / cam.w, r = this.panelRect(corner, lay.panel);
739
+ const wr = [cam.x + (r[0] - 12) / k, cam.y + (r[1] - 12) / k, cam.x + (r[2] + 12) / k, cam.y + (r[3] + 12) / k];
740
+ return !lay.boxes.some((bx) => hits(bx, wr));
741
+ };
742
+ let pick = null;
743
+ if (!lay.panel) pick = { zoom: snap(fit), ax: 0, ay: 0, corner: null };
744
+ else {
745
+ const corners = lay.panel.corner ? [lay.panel.corner] : ['tr', 'br', 'tl', 'bl'];
746
+ corners.forEach((corner, ci) => {
747
+ const ax = corner[1] === 'l' ? 1 : -1, ay = corner[0] === 't' ? 1 : -1;
748
+ const aligns = [[0, 0], [ax, 0], [0, ay], [ax, ay]];
749
+ let found = null;
750
+ for (let z = snap(fit); z >= MIN_ZOOM - 1e-6 && !found; z = Math.round((z - 0.05) * 100) / 100)
751
+ for (const [ai, [a, c]] of aligns.entries())
752
+ if (clear(camFor(z, a, c), corner)) { found = { zoom: z, ax: a, ay: c, corner, score: z - ai * 0.004 - ci * 0.001 + (prev && prev.corner === corner ? 0.045 : 0) }; break; }
753
+ if (found && (!pick || found.score > pick.score)) pick = found;
754
+ });
755
+ pick ||= { zoom: snap(fit * 0.7), ax: -1, ay: 1, corner: lay.panel.corner || 'tr' };
756
+ }
757
+ let cam = camFor(pick.zoom, pick.ax, pick.ay), corner = pick.corner;
758
+ // Camera stability: if the new content still fits the previous framing, keep it (no jitter between steps).
759
+ if (prev) {
760
+ const sameZ = Math.abs(prev.zoom - pick.zoom) < 1e-6, near = prev.zoom < pick.zoom && prev.zoom >= pick.zoom * 0.9;
761
+ if (sameZ || near) {
762
+ const c = prev.cam, m = 12 / prev.zoom;
763
+ const inside = x0 >= c.x + m && y0 >= c.y + m && x1 <= c.x + c.w - m && y1 <= c.y + c.h - m;
764
+ const dx = Math.abs((x0 + x1) / 2 - (c.x + c.w / 2)) / c.w, dy = Math.abs((y0 + y1) / 2 - (c.y + c.h / 2)) / c.h, lim = sameZ ? 0.12 : 0.18;
765
+ if (inside && dx < lim && dy < lim) {
766
+ const keep = lay.panel ? [prev.corner, 'tr', 'br', 'tl', 'bl'].filter(Boolean).find((k) => clear(c, k)) : null;
767
+ if (!lay.panel || keep) { cam = c; corner = lay.panel ? keep : null; pick = { ...pick, zoom: prev.zoom }; }
768
+ }
769
+ }
770
+ }
771
+ const dock = lay.panel ? this.panelRect(corner, lay.panel) : null;
772
+ return { cam, zoom: pick.zoom, corner, dock: dock && { x: dock[0], y: dock[1], corner }, picks: lay.picks, bounds: lay.b };
773
+ }
774
+ measure() {
775
+ const W = this.host.clientWidth; if (!W) return false;
776
+ this.hudScale = Math.min(1.12, Math.max(0.86, W / 780));
777
+ const show = W >= 520;
778
+ if (show !== this.showCards) { this.showCards = show; this.onCards?.(show); return true; }
779
+ return false;
780
+ }
781
+ frame(scenes) { // precompute camera plans for a whole lesson so framing is stable across steps
782
+ this.measure(); this.scenes = scenes; this.plans = new Map();
783
+ let prev = null;
784
+ for (const s of scenes) { prev = this.planFor(s, prev); this.plans.set(s, prev); }
785
+ this.scene = scenes[0]; this.setCam(this.plans.get(scenes[0]).cam);
786
+ }
787
+ plan(scene) { if (!this.plans.has(scene)) this.plans.set(scene, this.planFor(scene, null)); return this.plans.get(scene); }
788
+ displayCam(c = this.cam) {
789
+ let t = c;
790
+ if (this.view) { const w = c.w / this.view.k, h = c.h / this.view.k; t = { x: this.view.cx - w / 2, y: this.view.cy - h / 2, w, h }; }
791
+ const b = this.blend; if (!b) return t;
792
+ const k = EASE.inOut(clamp01((performance.now() - b.start) / b.dur));
793
+ if (k >= 1) { this.blend = null; return t; }
794
+ return { x: lerp(b.from.x, t.x, k), y: lerp(b.from.y, t.y, k), w: lerp(b.from.w, t.w, k), h: lerp(b.from.h, t.h, k) };
795
+ }
796
+ setCam(c) {
797
+ this.cam = c;
798
+ const d = this.displayCam(c);
799
+ this.svg.setAttribute('viewBox', `${r2(d.x)} ${r2(d.y)} ${r2(d.w)} ${r2(d.h)}`);
800
+ this.L.hud.setAttribute('transform', `translate(${r2(d.x)} ${r2(d.y)}) scale(${(d.w / Math.max(1, this.host.clientWidth)).toFixed(5)})`);
801
+ const cx = d.x + d.w / 2, cy = d.y + d.h / 2;
802
+ this.fadeGrad.setAttribute('cx', r2(cx)); this.fadeGrad.setAttribute('cy', r2(cy)); this.fadeGrad.setAttribute('r', r2(d.w * 0.56));
803
+ this.fadeGrad.setAttribute('gradientTransform', `translate(${r2(cx)} ${r2(cy)}) scale(1 0.6) translate(${r2(-cx)} ${r2(-cy)})`);
804
+ }
805
+ refit() {
806
+ if (!this.scene) return;
807
+ this.clearView();
808
+ const changed = this.measure(), list = this.scenes.length ? this.scenes : [this.scene];
809
+ this.plans = new Map(); let prev = null;
810
+ for (const s of list) { prev = this.planFor(s, prev); this.plans.set(s, prev); }
811
+ const p = this.plan(this.scene);
812
+ if (changed) { this.goTo(this.scene, { instant: true }); return; }
813
+ if (this.anim) this.anim.cam.to = p.cam; else this.setCam(p.cam);
814
+ for (const e of this.ents.values()) {
815
+ if (e.cur.type !== 'panel' || !p.dock) continue;
816
+ const d = { sx: p.dock.x, sy: p.dock.y, corner: p.dock.corner };
817
+ e.cur = { ...e.cur, ...d }; if (e.tween && !e.tween.remove) e.tween.to = { ...e.tween.to, ...d };
818
+ this.renderEntity(e);
819
+ }
820
+ this.updateLinks(true);
821
+ }
822
+
823
+ /* ── zoom & gestures ── */
824
+ clampView(v) {
825
+ if (!v) return null;
826
+ const c = this.cam, px = this.host.clientWidth / c.w, maxK = Math.max(1.5, Math.min(6, 3.2 / px)), k = Math.max(1, Math.min(maxK, v.k));
827
+ if (k <= 1.001) return null;
828
+ const w = c.w / k, h = c.h / k;
829
+ return { k, cx: Math.max(c.x + w / 2, Math.min(c.x + c.w - w / 2, v.cx)), cy: Math.max(c.y + h / 2, Math.min(c.y + c.h - h / 2, v.cy)) };
830
+ }
831
+ setView(v, animate = false) {
832
+ const had = !!this.view, from = animate ? { ...this.displayCam() } : null;
833
+ this.view = this.clampView(v);
834
+ this.blend = animate ? { from, start: performance.now(), dur: 360 } : null;
835
+ this.setCam(this.cam);
836
+ if (had !== !!this.view) { this.host.classList.toggle('is-zoomed', !!this.view); this.onView?.(!!this.view); }
837
+ }
838
+ clearView() { if (!this.view && !this.blend) return; const had = !!this.view; this.view = null; this.blend = null; if (had) { this.host.classList.remove('is-zoomed'); this.onView?.(false); } }
839
+ zoomAt(fx, fy, f) {
840
+ const d = this.displayCam(), px = d.x + fx * d.w, py = d.y + fy * d.h, k = (this.view ? this.view.k : 1) * f, w = this.cam.w / k, h = this.cam.h / k;
841
+ this.setView({ k, cx: px - fx * w + w / 2, cy: py - fy * h + h / 2 });
842
+ }
843
+ panBy(fx, fy) { if (!this.view) return; const d = this.displayCam(); this.setView({ ...this.view, cx: this.view.cx - fx * d.w, cy: this.view.cy - fy * d.h }); }
844
+ toggleZoomAt(fx, fy) {
845
+ if (this.view) { this.setView(null, true); return; }
846
+ const c = this.cam, w = c.w / 2, h = c.h / 2, px = c.x + fx * c.w, py = c.y + fy * c.h;
847
+ this.setView({ k: 2, cx: px - fx * w + w / 2, cy: py - fy * h + h / 2 }, true);
848
+ }
849
+ fit() { if (this.view) this.setView(null, true); }
850
+ gestures() {
851
+ const host = this.host, rect = () => host.getBoundingClientRect();
852
+ const frac = (x, y) => { const r = rect(); return [(x - r.left) / r.width, (y - r.top) / r.height]; };
853
+ const two = (t) => ({ d: Math.hypot(t[0].clientX - t[1].clientX, t[0].clientY - t[1].clientY), x: (t[0].clientX + t[1].clientX) / 2, y: (t[0].clientY + t[1].clientY) / 2 });
854
+ let g = null, tap = { at: 0, x: 0, y: 0 };
855
+ host.addEventListener('touchstart', (ev) => {
856
+ if (ev.touches.length >= 2) { ev.preventDefault(); g = { mode: 'two', ...two(ev.touches), pinched: true }; }
857
+ else if (ev.touches.length === 1) { const t = ev.touches[0]; g = { mode: 'one', x: t.clientX, y: t.clientY, x0: t.clientX, y0: t.clientY, t0: performance.now(), moved: false, pinched: false }; }
858
+ }, { passive: false });
859
+ host.addEventListener('touchmove', (ev) => {
860
+ if (!g) return;
861
+ if (ev.touches.length >= 2) {
862
+ ev.preventDefault(); const p = two(ev.touches);
863
+ if (g.mode !== 'two') g = { mode: 'two', ...p, pinched: true };
864
+ const [fx, fy] = frac(p.x, p.y); if (g.d > 0) this.zoomAt(fx, fy, p.d / g.d);
865
+ const r = rect(); this.panBy((p.x - g.x) / r.width, (p.y - g.y) / r.height); Object.assign(g, { d: p.d, x: p.x, y: p.y }); return;
866
+ }
867
+ if (g.mode !== 'one') return;
868
+ const t = ev.touches[0];
869
+ if (Math.hypot(t.clientX - g.x0, t.clientY - g.y0) > 8) g.moved = true;
870
+ if (this.view) { ev.preventDefault(); const r = rect(); this.panBy((t.clientX - g.x) / r.width, (t.clientY - g.y) / r.height); }
871
+ g.x = t.clientX; g.y = t.clientY;
872
+ }, { passive: false });
873
+ host.addEventListener('touchend', (ev) => {
874
+ if (!g) return;
875
+ if (ev.touches.length === 1 && g.mode === 'two') { const t = ev.touches[0]; g = { mode: 'one', x: t.clientX, y: t.clientY, x0: t.clientX, y0: t.clientY, t0: 0, moved: true, pinched: true }; return; }
876
+ if (ev.touches.length) return;
877
+ const now = performance.now();
878
+ if (g.mode === 'one' && !g.pinched) {
879
+ const t = ev.changedTouches[0], dx = t.clientX - g.x0, dy = t.clientY - g.y0;
880
+ if (!this.view && now - g.t0 < 700 && Math.abs(dx) > 50 && Math.abs(dy) < Math.abs(dx) * 0.6) this.onSwipe?.(dx < 0 ? 1 : -1);
881
+ else if (!g.moved && now - g.t0 < 300) {
882
+ if (now - tap.at < 320 && Math.hypot(t.clientX - tap.x, t.clientY - tap.y) < 40) { ev.preventDefault(); const [fx, fy] = frac(t.clientX, t.clientY); this.toggleZoomAt(fx, fy); tap = { at: 0, x: 0, y: 0 }; }
883
+ else tap = { at: now, x: t.clientX, y: t.clientY };
884
+ }
885
+ }
886
+ g = null;
887
+ });
888
+ host.addEventListener('touchcancel', () => (g = null));
889
+ let drag = null;
890
+ host.addEventListener('pointerdown', (ev) => { if (ev.pointerType === 'mouse' && ev.button === 0 && this.view) { drag = { x: ev.clientX, y: ev.clientY }; host.setPointerCapture(ev.pointerId); host.classList.add('is-dragging'); } });
891
+ host.addEventListener('pointermove', (ev) => { if (!drag) return; const r = rect(); this.panBy((ev.clientX - drag.x) / r.width, (ev.clientY - drag.y) / r.height); drag = { x: ev.clientX, y: ev.clientY }; });
892
+ const up = () => { drag = null; host.classList.remove('is-dragging'); };
893
+ host.addEventListener('pointerup', up); host.addEventListener('pointercancel', up);
894
+ host.addEventListener('dblclick', (ev) => { const [fx, fy] = frac(ev.clientX, ev.clientY); this.toggleZoomAt(fx, fy); });
895
+ host.addEventListener('wheel', (ev) => {
896
+ const unit = ev.deltaMode === 1 ? 16 : 1;
897
+ if (ev.ctrlKey || ev.metaKey) { ev.preventDefault(); const [fx, fy] = frac(ev.clientX, ev.clientY); this.zoomAt(fx, fy, Math.exp(-ev.deltaY * unit * 0.01)); }
898
+ else if (this.view) { ev.preventDefault(); const r = rect(); this.panBy((-ev.deltaX * unit) / r.width, (-ev.deltaY * unit) / r.height); }
899
+ }, { passive: false });
900
+ }
901
+
902
+ /* ── scene transitions ── */
903
+ clear() {
904
+ this.finish(true);
905
+ for (const e of this.ents.values()) { e.el.remove(); e.overEl.remove(); }
906
+ for (const l of this.links.values()) { l.el.remove(); l.label.remove(); }
907
+ this.ents.clear(); this.links.clear(); this.clearPackets(true); this.flows = []; this.L.floor.innerHTML = '';
908
+ }
909
+ goTo(scene, { instant = false } = {}) {
910
+ this.finish(true); this.clearPackets(); this.flows = [];
911
+ const now = performance.now(), plan = this.plan(scene), T = TIMING;
912
+ const next = {};
913
+ for (const [id, e] of Object.entries(scene.entities || {})) {
914
+ if (e.type === 'panel') { if (!this.showCards || !plan.dock) continue; next.__panel = { ...withDefaults(e), sx: plan.dock.x, sy: plan.dock.y, corner: plan.dock.corner }; }
915
+ else next[id] = withDefaults(e);
916
+ }
917
+ const leaving = [...this.ents.keys()].filter((id) => !next[id]);
918
+ const moving = Object.keys(next).filter((id) => this.ents.has(id) && !same(this.ents.get(id).cur, next[id]));
919
+ const entering = Object.keys(next).filter((id) => !this.ents.has(id)).sort((a, b) => depthKey(next[a]) - depthKey(next[b]));
920
+ const moveDelay = leaving.length ? T.exit * 0.55 : 0;
921
+ const enterAt = moving.length ? moveDelay + T.move * 0.75 : leaving.length ? T.exit * 0.7 : 0;
922
+ const ready = {}; let end = 0;
923
+ for (const id of leaving) {
924
+ const e = this.ents.get(id);
925
+ e.tween = { from: { ...e.cur }, to: { ...e.cur, opacity: 0, ...(EXIT_TO[e.cur.type] || { lift: -22 }) }, start: now, delay: 0, dur: T.exit, ease: EASE.inOut, remove: true };
926
+ end = Math.max(end, T.exit);
927
+ }
928
+ for (const id of Object.keys(next)) {
929
+ if (!this.ents.has(id)) continue;
930
+ const e = this.ents.get(id);
931
+ if (moving.includes(id)) {
932
+ e.tween = { from: { ...e.cur }, to: next[id], start: now, delay: moveDelay, dur: T.move, ease: EASE.inOut, ...this.swapInfo(e.cur, next[id]) };
933
+ ready[id] = moveDelay + T.move; end = Math.max(end, ready[id]);
934
+ } else ready[id] = 0;
935
+ }
936
+ entering.forEach((id, i) => {
937
+ const to = next[id], from = { ...to, opacity: 0, ...(ENTER_FROM[to.type] || { lift: 120 }) };
938
+ const e = this.addEntity(id, from), delay = enterAt + i * T.stagger;
939
+ e.tween = { from, to, start: now, delay, dur: T.enter, ease: EASE.out, liftEase: EASE.back, countEase: EASE.inOut };
940
+ ready[id] = delay + T.enter * 0.8; end = Math.max(end, delay + T.enter);
941
+ });
942
+ for (const [id, l] of this.links) if (!scene.links?.[id]) l.tween = { from: l.opacity, to: 0, key: 'opacity', start: now, delay: 0, dur: 300, remove: true };
943
+ let k = 0;
944
+ for (const [id, spec] of Object.entries(scene.links || {})) {
945
+ if (this.links.has(id)) { const l = this.links.get(id); l.spec = spec; this.linkClass(l); continue; }
946
+ const l = this.addLink(id, spec), delay = Math.max(ready[spec.from] ?? 0, ready[spec.to] ?? 0, moveDelay + (moving.length ? T.move * 0.6 : 0)) + 60 + k * 90;
947
+ k++; l.draw = 0; l.tween = { from: 0, to: 1, key: 'draw', start: now, delay, dur: T.draw };
948
+ end = Math.max(end, delay + T.draw);
949
+ }
950
+ this.scene = scene;
951
+ const camDelay = leaving.length ? T.exit * 0.4 : 0;
952
+ end = Math.max(end, camDelay + T.move);
953
+ const from = { ...this.displayCam() }; this.clearView();
954
+ this.anim = { cam: { from, to: plan.cam, delay: camDelay, dur: T.move }, start: now, end: now + end, flows: scene.flows || [], spot: [...entering, ...moving.filter((id) => !next[id].dead || this.ents.get(id).cur.dead !== next[id].dead)] };
955
+ if (instant || this.reduced) this.finish();
956
+ }
957
+ swapInfo(a, b) {
958
+ const o = {};
959
+ if (!same(a.tags, b.tags)) o.tagSwap = true;
960
+ if (!same(a.label, b.label) || (a.sub || '') !== (b.sub || '')) o.labelSwap = true;
961
+ if (a.type === 'panel') {
962
+ const key = (p) => [p.title, p.icon, p.lines, p.bars, p.w];
963
+ const s0 = renderPanel({ ...a, boxW: undefined, boxH: undefined }).size, s1 = renderPanel({ ...b, boxW: undefined, boxH: undefined }).size;
964
+ o.card = { swap: !same(key(a), key(b)), w0: s0.w, h0: s0.h, w1: s1.w, h1: s1.h };
965
+ }
966
+ return o;
967
+ }
968
+ finish(silent = false) {
969
+ if (!this.anim) return;
970
+ for (const [id, e] of [...this.ents]) if (e.tween) { if (e.tween.remove) this.removeEntity(id); else { e.cur = e.tween.to; e.tween = null; this.renderEntity(e); } }
971
+ for (const [id, l] of [...this.links]) if (l.tween) { if (l.tween.remove) { l.el.remove(); l.label.remove(); this.links.delete(id); } else { l[l.tween.key] = l.tween.to; l.tween = null; } }
972
+ this.setCam(this.anim.cam.to); this.sortDepth(); this.updateLinks(true);
973
+ const a = this.anim; this.anim = null;
974
+ if (!silent) this.settle(a);
975
+ }
976
+ settle(a) {
977
+ this.flows = a.flows.map((f) => ({ ...f, acc: 0.6, n: 0, rr: 0 }));
978
+ for (const id of a.spot) this.spotlight(id);
979
+ this.onSettle?.();
980
+ }
981
+ retheme() {
982
+ this.defs.innerHTML = themed(defsSVG());
983
+ for (const e of this.ents.values()) this.renderEntity(e);
984
+ for (const l of this.links.values()) l.labelKey = null;
985
+ this.updateLinks(true);
986
+ }
987
+ addEntity(id, cur) {
988
+ const g = el('g', { 'data-id': id, class: `ent ent--${cur.type}` }), o = el('g', { 'data-id': id });
989
+ (FLOOR.has(cur.type) ? this.L.floor : this.L.ents).appendChild(g);
990
+ (cur.type === 'panel' ? this.L.hud : this.L.over).appendChild(o);
991
+ const e = { id, cur: { ...cur }, el: g, overEl: o, poly: null, tween: null };
992
+ this.ents.set(id, e); this.renderEntity(e); return e;
993
+ }
994
+ removeEntity(id) { const e = this.ents.get(id); e.el.remove(); e.overEl.remove(); this.ents.delete(id); }
995
+ renderEntity(e) {
996
+ if (e.cur.type === 'panel') {
997
+ const p = renderPanel(e.cur);
998
+ e.overEl.innerHTML = `<g transform="translate(${r2(e.cur.sx || 0)} ${r2((e.cur.sy || 0) - (e.cur.lift || 0))}) scale(${r2(this.hudScale)})">${themed(p.over)}</g>`;
999
+ e.poly = null; return;
1000
+ }
1001
+ const r = RENDER[e.cur.type](e.cur);
1002
+ let over = r.over;
1003
+ const insp = !!e.cur.inside && !!r.poly;
1004
+ if (insp) { // magnifier badge on the right-top corner of the outline
1005
+ const tip = r.poly.reduce((a, p) => (p[0] > a[0] + 0.5 || (Math.abs(p[0] - a[0]) <= 0.5 && p[1] < a[1]) ? p : a), r.poly[0]);
1006
+ over += `<g class="inspect-badge" opacity="${r2(e.cur.opacity ?? 1)}" transform="translate(${r2(tip[0] - 2)} ${r2(tip[1] - 6)})"><circle class="inspect-badge__ring" r="11" fill="none" stroke="#5fae57" stroke-width="2"/><circle r="10" fill="${DROP}" transform="translate(0 1.5)"/><circle r="10" fill="#dcefd2" stroke="${INK}" stroke-width="1.4"/>${iconSVG('zoom-in', 0, 0, 12, { stroke: 2.4, color: INK })}</g>`;
1007
+ }
1008
+ e.el.innerHTML = themed(r.body); e.overEl.innerHTML = themed(over); e.poly = r.poly; e.bounds = r.bounds;
1009
+ if (insp !== !!e.insp) {
1010
+ e.insp = insp;
1011
+ for (const n of [e.el, e.overEl]) { n.classList.toggle('is-inspectable', insp); if (insp) { n.setAttribute('tabindex', '0'); n.setAttribute('role', 'button'); } else { n.removeAttribute('tabindex'); n.removeAttribute('role'); } }
1012
+ }
1013
+ const dim = clamp01(e.cur.dim || 0);
1014
+ e.el.style.opacity = dim && e.cur.type !== 'block' ? r2(1 - dim * 0.55) : '';
1015
+ e.overEl.style.opacity = dim ? r2(1 - dim * 0.6) : '';
1016
+ }
1017
+ sortDepth() {
1018
+ const list = [...this.ents.values()].filter((e) => !FLOOR.has(e.cur.type) && e.cur.type !== 'panel').sort((a, b) => depthKey(a.cur) - depthKey(b.cur));
1019
+ const kids = [...this.L.ents.children];
1020
+ if (list.some((e, i) => kids[i] !== e.el)) for (const e of list) this.L.ents.appendChild(e.el);
1021
+ }
1022
+ spotlight(id) {
1023
+ const e = this.ents.get(id);
1024
+ if (!e || ['panel', 'queue', 'zone'].includes(e.cur.type)) return;
1025
+ const [x0, x1, y0, y1] = footprint(e.cur), m = 0.6;
1026
+ const p = el('path', { class: 'spot', d: roundPoly([iso(x0 - m, y0 - m), iso(x0 - m, y1 + m), iso(x1 + m, y1 + m), iso(x1 + m, y0 - m)], 7) });
1027
+ this.L.floor.appendChild(p); setTimeout(() => p.remove(), 1600);
1028
+ }
1029
+
1030
+ /* ── links ── */
1031
+ linkClass(l) {
1032
+ l.el.setAttribute('class', `link link--${l.spec.style || 'solid'}${l.spec.dim ? ' is-dim' : ''}`);
1033
+ l.label.setAttribute('class', `link-label${l.spec.dim ? ' is-dim' : ''}`);
1034
+ }
1035
+ addLink(id, spec) {
1036
+ const p = el('path', { class: `link link--${spec.style || 'solid'}${spec.dim ? ' is-dim' : ''}` }), g = el('g', { class: `link-label${spec.dim ? ' is-dim' : ''}` });
1037
+ this.L.links.appendChild(p); this.L.over.appendChild(g);
1038
+ const l = { id, spec, el: p, label: g, draw: 1, opacity: 1, tween: null, len: 0 };
1039
+ this.links.set(id, l); return l;
1040
+ }
1041
+ updateLinks(force = false) {
1042
+ const center = (id) => this.ents.has(id) && centerOf(this.ents.get(id).cur);
1043
+ const picks = this.plans.get(this.scene)?.picks || {};
1044
+ for (const l of this.links.values()) {
1045
+ const s = l.spec;
1046
+ if (!this.ents.has(s.from) || (s.to && !this.ents.has(s.to))) continue;
1047
+ let pts = s.pts.map((p) => iso(...resolvePoint(p, center)));
1048
+ pts = clipStart(pts, this.ents.get(s.from).poly, 3);
1049
+ if (s.to) pts = clipEnd(pts, this.ents.get(s.to).poly, s.heads === 'none' ? 3 : 4);
1050
+ l.pts = pts; l.el.setAttribute('d', roundLine(pts, 9)); l.len = l.el.getTotalLength();
1051
+ const style = s.style || 'solid', marker = style === 'off' ? 'url(#arrow-muted)' : style === 'cut' ? 'url(#arrow-red)' : 'url(#arrow)';
1052
+ const heads = l.draw > 0.97 && style !== 'beat';
1053
+ l.el.setAttribute('marker-end', heads && s.heads !== 'none' ? marker : '');
1054
+ l.el.setAttribute('marker-start', heads && s.heads === 'both' ? marker : '');
1055
+ if (l.draw < 1 && style === 'solid') { l.el.style.strokeDasharray = `${r2(l.len)} ${r2(l.len)}`; l.el.style.strokeDashoffset = r2(l.len * (1 - l.draw)); l.el.style.opacity = 1; }
1056
+ else { l.el.style.strokeDasharray = ''; l.el.style.strokeDashoffset = ''; l.el.style.opacity = r2(l.opacity * (style === 'solid' ? 1 : clamp01(l.draw * 1.4))); }
1057
+ if (s.label) {
1058
+ const key = `${s.label}|${s.labelTone || ''}|${isDark()}`;
1059
+ if (l.labelKey !== key) { if (l.labelKey) l.labelBorn = performance.now(); l.label.innerHTML = themed(pill(0, 0, s.label, { tone: s.labelTone || 'paper', size: LABEL_SIZE, icon: s.labelIcon || null })); l.labelKey = key; }
1060
+ const born = l.labelBorn ? clamp01((performance.now() - l.labelBorn) / 320) : 1;
1061
+ l.label.style.opacity = r2(clamp01((l.draw - 0.6) / 0.4) * l.opacity * born);
1062
+ const { w, h } = labelBox(s.label), pick = picks[l.id] || { t: s.labelAt ?? 0.5, side: 1 };
1063
+ const [cx, cy] = spotAt(pts, pick, w + (s.labelIcon ? 15 : 0), h);
1064
+ l.lpos = l.lpos && this.anim && !force ? [lerp(l.lpos[0], cx, 0.16), lerp(l.lpos[1], cy, 0.16)] : [cx, cy];
1065
+ l.label.setAttribute('transform', `translate(${r2(l.lpos[0])} ${r2(l.lpos[1])})`);
1066
+ } else if (l.labelKey) { l.label.innerHTML = ''; l.labelKey = null; }
1067
+ }
1068
+ }
1069
+
1070
+ /* ── packets ── */
1071
+ clearPackets(now = false) {
1072
+ for (const p of this.packets) { if (now) p.el.remove(); else { p.el.classList.add('pkt--leave'); setTimeout(() => p.el.remove(), 260); } }
1073
+ this.packets = [];
1074
+ }
1075
+ pickRoute(f) {
1076
+ const kind = f.pattern ? f.pattern[f.n % f.pattern.length] : f.kind || 'req';
1077
+ if (f.routes) {
1078
+ let i;
1079
+ if (f.pick === 'weights') { const w = f.routes.map((r) => r.weight ?? 1); let x = Math.random() * w.reduce((a, b) => a + b, 0); i = w.findIndex((v) => (x -= v) <= 0); if (i < 0) i = w.length - 1; }
1080
+ else { i = f.rr % f.routes.length; f.rr++; }
1081
+ f.n++; return { route: f.routes[i].path, kind: f.routes[i].kind || kind };
1082
+ }
1083
+ const route = f.route.map((seg) => {
1084
+ if (typeof seg === 'string') return seg;
1085
+ if (f.pick === 'weights') { let x = Math.random() * f.weights.reduce((a, b) => a + b, 0); for (let i = 0; i < seg.length; i++) if ((x -= f.weights[i]) <= 0) return seg[i]; return seg[seg.length - 1]; }
1086
+ const s = seg[f.rr % seg.length]; f.rr++; return s;
1087
+ });
1088
+ f.n++; return { route, kind };
1089
+ }
1090
+ spawn(f) {
1091
+ if (f.fanout) { f.n++; for (const r of f.routes) this.launch(r.path, r.kind || f.kind || 'req', f); return; }
1092
+ const { route, kind } = this.pickRoute(f); this.launch(route, kind, f);
1093
+ }
1094
+ launch(route, kind, f) {
1095
+ if (!route.every((id) => this.links.has(id))) return;
1096
+ const g = el('g', { class: `pkt pkt--${kind}` });
1097
+ g.innerHTML = kind === 'ping' || kind === 'kill' ? '<circle r="3.6"/>' : kind === 'heavy' ? '<rect x="-6" y="-6" width="12" height="12" rx="3.5"/>'
1098
+ : kind === 'write' ? '<rect x="-4.2" y="-4.2" width="8.4" height="8.4" rx="2"/>' : kind === 'msg' || kind === 'poison' ? '<rect x="-4.8" y="-4.8" width="9.6" height="9.6" rx="2.4"/>' : '<circle r="4.3"/>';
1099
+ this.L.packets.appendChild(g);
1100
+ this.packets.push({ route, seg: 0, d: 0, kind, el: g, back: false, bounce: !!f.bounce, dwell: 0, speed: f.speed || 1, hold: f.hold || 0 });
1101
+ }
1102
+ burst(x, y, kind) {
1103
+ const g = el('g', { class: `fx fx--${kind}`, transform: `translate(${r2(x)} ${r2(y)})` });
1104
+ g.innerHTML = kind === 'fail' ? '<circle r="5" class="fx-ring"/><path d="M-3.6,-3.6 L3.6,3.6 M3.6,-3.6 L-3.6,3.6" class="fx-x"/>' : '<circle r="4.3" class="fx-ring"/>';
1105
+ this.L.packets.appendChild(g); setTimeout(() => g.remove(), 700);
1106
+ }
1107
+ stepPackets(dt) {
1108
+ for (const f of this.flows) for (f.acc += dt * (f.rate ?? 1) * (this.reduced ? 0.5 : 1); f.acc >= 1; ) { f.acc--; this.spawn(f); }
1109
+ const keep = [];
1110
+ for (const p of this.packets) {
1111
+ if (p.dwell > 0) { p.dwell -= dt; if (p.dwell > 0) { keep.push(p); continue; } p.el.style.opacity = 1; if (p.back) { p.el.classList.remove('pkt--held'); p.el.classList.add('pkt--back'); } }
1112
+ const l = this.links.get(p.route[p.seg]);
1113
+ if (!l) { p.el.remove(); continue; }
1114
+ p.d += PKT_SPEED * p.speed * (KIND_SPEED[p.kind] || 1) * dt;
1115
+ const len = l.len || l.el.getTotalLength(), style = l.spec.style || 'solid', heads = style === 'beat' ? 'none' : l.spec.heads;
1116
+ let a = heads === 'both' ? 16 : 0, b = len - (heads === 'none' ? 0 : 16);
1117
+ if (b - a < 10) { a = 0; b = len; }
1118
+ const span = b - a;
1119
+ if (p.d >= span) {
1120
+ const end = l.el.getPointAtLength(p.back ? a : b);
1121
+ if (!p.back && Math.random() < (l.spec.fail || 0)) { this.burst(end.x, end.y, 'fail'); p.el.remove(); continue; }
1122
+ if (!p.back && p.seg < p.route.length - 1) { p.seg++; p.d = 0; p.dwell = 0.16; p.el.style.opacity = 0; keep.push(p); continue; }
1123
+ if (p.bounce && !p.back) { p.back = true; p.d = 0; if (p.hold) { p.dwell = p.hold; p.el.classList.add('pkt--held'); } else p.el.classList.add('pkt--back'); keep.push(p); continue; }
1124
+ if (p.back && p.seg > 0) { p.seg--; p.d = 0; p.dwell = 0.16; p.el.style.opacity = 0; keep.push(p); continue; }
1125
+ this.burst(end.x, end.y, 'ok'); p.el.remove(); continue;
1126
+ }
1127
+ const pt = l.el.getPointAtLength(p.back ? b - p.d : a + p.d);
1128
+ p.el.setAttribute('transform', `translate(${r2(pt.x)} ${r2(pt.y)})`);
1129
+ keep.push(p);
1130
+ }
1131
+ this.packets = keep;
1132
+ }
1133
+
1134
+ /* ── frame loop ── */
1135
+ tick(t) {
1136
+ const dt = Math.min(0.05, (t - this.last) / 1000); this.last = t;
1137
+ if (this.anim) {
1138
+ const c = this.anim.cam, k = EASE.inOut(clamp01((t - this.anim.start - c.delay) / c.dur));
1139
+ this.setCam({ x: lerp(c.from.x, c.to.x, k), y: lerp(c.from.y, c.to.y, k), w: lerp(c.from.w, c.to.w, k), h: lerp(c.from.h, c.to.h, k) });
1140
+ let moved = false;
1141
+ for (const [id, e] of [...this.ents]) {
1142
+ const tw = e.tween; if (!tw) continue;
1143
+ const raw = (t - tw.start - tw.delay) / tw.dur;
1144
+ if (raw < 0 && !tw.started) continue;
1145
+ tw.started = true;
1146
+ const p = clamp01(raw), s = tw.ease(p), cur = tw.remove || p >= 0.5 ? { ...tw.to } : { ...tw.from };
1147
+ if (!tw.remove && p < 0.5) cur.cpu = tw.from.cpu;
1148
+ for (const key in tw.to) {
1149
+ const a = tw.from[key], b = tw.to[key];
1150
+ if (typeof a !== 'number' || typeof b !== 'number' || (key === 'cpu' && (a < 0 || b < 0))) continue;
1151
+ cur[key] = lerp(a, b, key === 'lift' && tw.liftEase ? tw.liftEase(p) : (key === 'count' || key === 'n') && tw.countEase ? tw.countEase(p) : s);
1152
+ }
1153
+ const out = 1 - clamp01(p / 0.42), inn = clamp01((p - 0.55) / 0.4);
1154
+ if (tw.tagSwap) cur.tagFade = p < 0.5 ? out : inn;
1155
+ if (tw.labelSwap) cur.labelFade = p < 0.5 ? out : inn;
1156
+ if (tw.card && tw.card.swap) {
1157
+ const q = EASE.inOut(clamp01((p - 0.24) / 0.48));
1158
+ cur.boxW = lerp(tw.card.w0, tw.card.w1, q); cur.boxH = lerp(tw.card.h0, tw.card.h1, q);
1159
+ cur.fade = p < 0.5 ? 1 - clamp01(p / 0.24) : clamp01((p - 0.72) / 0.28);
1160
+ }
1161
+ e.cur = cur; this.renderEntity(e); moved = true;
1162
+ if (p >= 1) { if (tw.remove) this.removeEntity(id); else { e.cur = tw.to; e.tween = null; this.renderEntity(e); } }
1163
+ }
1164
+ for (const [id, l] of [...this.links]) {
1165
+ const tw = l.tween; if (!tw) continue;
1166
+ const p = clamp01((t - tw.start - tw.delay) / tw.dur);
1167
+ l[tw.key] = lerp(tw.from, tw.to, EASE.inOut(p));
1168
+ if (p >= 1) { if (tw.remove) { l.el.remove(); l.label.remove(); this.links.delete(id); } else l.tween = null; }
1169
+ }
1170
+ if (moved) this.sortDepth();
1171
+ this.updateLinks();
1172
+ if (t >= this.anim.end) { const a = this.anim; this.anim = null; this.updateLinks(true); this.settle(a); }
1173
+ }
1174
+ if (this.blend && !this.anim) this.setCam(this.cam);
1175
+ if (!this.paused) this.stepPackets(dt);
1176
+ }
1177
+ }