@guilhermebkel/scenec 0.0.0-stage → 0.1.1

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 (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +242 -2
  3. package/dist/catalog.d.ts +21 -0
  4. package/dist/catalog.js +35 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +118 -0
  7. package/dist/data/europe.json +1 -0
  8. package/dist/drawing/assets.d.ts +8 -0
  9. package/dist/drawing/assets.js +612 -0
  10. package/dist/drawing/kits.d.ts +7 -0
  11. package/dist/drawing/kits.js +92 -0
  12. package/dist/drawing/person.d.ts +18 -0
  13. package/dist/drawing/person.js +287 -0
  14. package/dist/drawing/themes.d.ts +4 -0
  15. package/dist/drawing/themes.js +45 -0
  16. package/dist/index.d.ts +6 -0
  17. package/dist/index.js +2 -0
  18. package/dist/modes/map.d.ts +5 -0
  19. package/dist/modes/map.js +365 -0
  20. package/dist/modes/plane.d.ts +5 -0
  21. package/dist/modes/plane.js +716 -0
  22. package/dist/pipeline/compile.d.ts +2 -0
  23. package/dist/pipeline/compile.js +581 -0
  24. package/dist/pipeline/custom.d.ts +2 -0
  25. package/dist/pipeline/custom.js +120 -0
  26. package/dist/pipeline/groups.d.ts +2 -0
  27. package/dist/pipeline/groups.js +189 -0
  28. package/dist/pipeline/index.d.ts +16 -0
  29. package/dist/pipeline/index.js +7 -0
  30. package/dist/pipeline/parse.d.ts +10 -0
  31. package/dist/pipeline/parse.js +80 -0
  32. package/dist/protocols/options.d.ts +14 -0
  33. package/dist/protocols/options.js +1 -0
  34. package/dist/protocols/scene.d.ts +299 -0
  35. package/dist/protocols/scene.js +118 -0
  36. package/dist/protocols/theme.d.ts +25 -0
  37. package/dist/protocols/theme.js +1 -0
  38. package/dist/render/check.d.ts +6 -0
  39. package/dist/render/check.js +10 -0
  40. package/dist/render/critic.d.ts +1 -0
  41. package/dist/render/critic.js +235 -0
  42. package/dist/render/files.d.ts +2 -0
  43. package/dist/render/files.js +16 -0
  44. package/dist/render/fonts.d.ts +2 -0
  45. package/dist/render/fonts.js +4 -0
  46. package/dist/render/png.d.ts +9 -0
  47. package/dist/render/png.js +13 -0
  48. package/dist/render.d.ts +5 -0
  49. package/dist/render.js +3 -0
  50. package/dist/schema.d.ts +3 -0
  51. package/dist/schema.js +6 -0
  52. package/dist/utils/color.d.ts +5 -0
  53. package/dist/utils/color.js +35 -0
  54. package/dist/utils/recolor.d.ts +1 -0
  55. package/dist/utils/recolor.js +56 -0
  56. package/dist/utils/sanitize.d.ts +5 -0
  57. package/dist/utils/sanitize.js +169 -0
  58. package/dist/utils/suggest.d.ts +1 -0
  59. package/dist/utils/suggest.js +22 -0
  60. package/dist/utils/svg.d.ts +2 -0
  61. package/dist/utils/svg.js +11 -0
  62. package/fonts/OFL.txt +50 -0
  63. package/fonts/Poppins-Bold.ttf +0 -0
  64. package/fonts/Poppins-Medium.ttf +0 -0
  65. package/fonts/Poppins-Regular.ttf +0 -0
  66. package/package.json +96 -4
  67. package/skills/scenec/SKILL.md +46 -0
  68. package/skills/scenec/recipes/anuncios-variacoes.yaml +58 -0
  69. package/skills/scenec/recipes/carrossel.yaml +58 -0
  70. package/skills/scenec/recipes/elearning.yaml +64 -0
  71. package/skills/scenec/recipes/historia-ilustrada.yaml +48 -0
  72. package/skills/scenec/recipes/ilustracoes-produto.yaml +44 -0
  73. package/skills/scenec/recipes/mapas-jornadas.yaml +27 -0
  74. package/skills/scenec/recipes/reels-explicativo.yaml +41 -0
  75. package/skills/scenec/recipes/wrapped-personalizado.yaml +64 -0
  76. package/skills/scenec/references/catalog.md +125 -0
  77. package/skills/scenec/references/dsl.md +111 -0
  78. package/skills/scenec/references/fontes.md +8 -0
@@ -0,0 +1,716 @@
1
+ // Modo 2.5D: o chão é um plano contínuo (x, z) visto em perspectiva.
2
+ // x ∈ [0,1] esquerda→direita; z ∈ [0,1] perto→longe (z>1 vai para o horizonte).
3
+ // Objetos continuam desenhados de frente ("recortes em pé"), escalados pela distância.
4
+ // Recursos: caminho com casas e checkpoints, zonas com cenário próprio, rótulos,
5
+ // espalhamento de vegetação que evita o caminho e posicionamento automático em espaço livre.
6
+ import { sh } from "../utils/color.js";
7
+ const SLOTS = { "far-left": 0.08, left: 0.2, "center-left": 0.35, center: 0.5, "center-right": 0.65, right: 0.8, "far-right": 0.92 };
8
+ const SIZES = { tiny: 0.5, small: 0.75, medium: 1, large: 1.3, huge: 1.7 };
9
+ const FONT = "Poppins";
10
+ const esc = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;");
11
+ const f1 = (n) => (+n).toFixed(1);
12
+ // Cenários prontos para zonas (o autor pode sobrescrever em `zones:`)
13
+ const ZONE_PRESETS = {
14
+ home: { tint: (t) => sh(t.foliage[1], 0.5), decor: [{ asset: "house", size: 0.75 }, { asset: "tree", size: 0.7 }, { asset: "bush", size: 0.8 }] },
15
+ school: { tint: (t) => sh(t.accent, 0.68), decor: [{ asset: "school", size: 0.85 }, { asset: "tree", size: 0.7 }, { asset: "pennant", size: 0.8 }] },
16
+ campus: { tint: (t) => sh(t.foliage[1], 0.6), decor: [{ asset: "university", size: 0.85 }, { asset: "tree", size: 0.75 }, { asset: "bench", size: 0.8 }] },
17
+ office: { tint: (t) => sh(t.metal, 0.5), decor: [{ asset: "building", floors: 7, width: 90, size: 0.75 }, { asset: "building", floors: 5, width: 80, seed: 2, color: "primary", size: 0.75 }, { asset: "streetlight", size: 0.7 }] },
18
+ lab: { tint: (t) => sh(t.glass, 0.05), decor: [{ asset: "lab", size: 0.85 }, { asset: "pine", size: 0.6 }, { asset: "bush", size: 0.8 }] },
19
+ ceremony: { tint: (t) => sh(t.accent, 0.4), decor: [{ asset: "stage", size: 0.9 }, { asset: "balloons", size: 0.9 }, { asset: "balloons", size: 0.8 }, { asset: "pennant", color: "primary", size: 0.8 }] },
20
+ park: { tint: (t) => sh(t.foliage[0], 0.3), decor: [{ asset: "tree", size: 0.8 }, { asset: "bench", size: 0.8 }, { asset: "flowers", size: 0.9 }] },
21
+ city: { tint: (t) => sh(t.metal, 0.5), decor: [{ asset: "building", floors: 8, size: 0.75 }, { asset: "car", size: 0.8 }, { asset: "streetlight", size: 0.7 }] },
22
+ beach: { tint: (t) => sh(t.accent, 0.7), decor: [{ asset: "palm", size: 0.6 }, { asset: "umbrella", size: 0.8 }] },
23
+ };
24
+ function rng(seed) { let s = (seed >>> 0) || 1; return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296); }
25
+ function catmull(pts, per = 48) {
26
+ if (pts.length < 2)
27
+ return pts.slice();
28
+ const P = [pts[0], ...pts, pts[pts.length - 1]], out = [];
29
+ for (let i = 1; i < P.length - 2; i++)
30
+ for (let k = 0; k < per; k++) {
31
+ const t = k / per, t2 = t * t, t3 = t2 * t, [p0, p1, p2, p3] = [P[i - 1], P[i], P[i + 1], P[i + 2]];
32
+ out.push([0, 1].map((j) => 0.5 * (2 * p1[j] + (-p0[j] + p2[j]) * t + (2 * p0[j] - 5 * p1[j] + 4 * p2[j] - p3[j]) * t2 + (-p0[j] + 3 * p1[j] - 3 * p2[j] + p3[j]) * t3)));
33
+ }
34
+ out.push(pts[pts.length - 1]);
35
+ return out;
36
+ }
37
+ export function compilePlane(scene, { LIB, theme: t, warnings, W, H, resolveAsset, contrast }) {
38
+ const c = scene.canvas || {};
39
+ // ---------- projeção ----------
40
+ // Dois tipos de câmera: 'board' (padrão, alta e distante, para mapas e tabuleiros) e 'room'
41
+ // (perspectiva real, mais baixa e próxima, para interiores). Todos os valores podem ser sobrescritos em canvas.camera.
42
+ const camIn = typeof c.camera === "string" ? { preset: c.camera } : (c.camera || {});
43
+ const ROOM = camIn.preset === "room" || c.camera === "room" || camIn.horizon != null;
44
+ const cam = ROOM ? { horizon: 0.48, near_y: 1.0, depth: 0.7, vanish_x: 0.5, cx: 0.5, x_span: 1.17, unit: 0.0093, ...camIn } : camIn;
45
+ const K = ROOM ? cam.depth : (c.depth ?? 0.9);
46
+ const S = (z) => 1 / (1 + K * Math.max(z, -0.85 / K));
47
+ let yInf, yN, xs, X;
48
+ if (ROOM) {
49
+ yInf = H * cam.horizon;
50
+ yN = H * cam.near_y;
51
+ xs = (z) => cam.x_span * S(z) / 0.98;
52
+ X = (x, z) => W * cam.vanish_x + (x - cam.cx) * W * cam.x_span * S(z);
53
+ }
54
+ else {
55
+ yN = H * (c.near_y ?? 0.97);
56
+ const yF = H * (c.far_y ?? 0.32);
57
+ yInf = (yF * (1 + K) - yN) / K;
58
+ const sF = 1 / (1 + K);
59
+ xs = (z) => 0.72 + 0.28 * (S(z) - sF) / (1 - sF);
60
+ X = (x, z) => W / 2 + (x - 0.5) * W * 0.98 * xs(z);
61
+ }
62
+ const Y = (z) => yInf + (yN - yInf) * S(z);
63
+ const U = ROOM ? H * cam.unit * (c.scale ?? 1) : H * 0.00165 * (c.scale ?? 1);
64
+ const pxPerUnit = (z, k = 1) => U * S(z) * k;
65
+ const worldR = (wUnits, z, k = 1) => (wUnits * pxPerUnit(z, k)) / 2 / (W * 0.98 * xs(z)); // raio no eixo x do mundo
66
+ const P3 = (x, z, h = 0) => [X(x, z), Y(z) - h * U * S(z)]; // ponto do mundo (x, z, altura em unidades) -> tela
67
+ const HAZE = (c.haze === false || ROOM && c.haze !== true) ? null : [[0.6, 0.1], [0.85, 0.2], [1.15, 0.34]];
68
+ const hazeLevel = (z) => { if (!HAZE)
69
+ return 0; let lv = 0; HAZE.forEach(([zz], i) => { if (z >= zz)
70
+ lv = i + 1; }); return lv; };
71
+ const air = t.skyBottom;
72
+ const [ar, ag, ab] = [1, 3, 5].map((i) => parseInt(air.slice(i, i + 2), 16) / 255);
73
+ const sprites = []; // objetos desenhados (ordenados por profundidade)
74
+ const anchors = {}; // id -> [x, z]
75
+ const footprints = []; // { x, z, r, id } para checar espaço livre
76
+ // ---------- caminho ----------
77
+ const pathDef = scene.path || null;
78
+ let samples = [], cps = [], arc = [];
79
+ const roadW = pathDef?.width ?? 0.075;
80
+ const cpR = pathDef?.checkpoint_size ?? 0.042;
81
+ if (pathDef) {
82
+ const pts = (pathDef.points || []).map((p, i) => ({ ...p, id: p.id || `ponto${i + 1}`, i }));
83
+ if (pts.length < 2)
84
+ warnings.push("path precisa de pelo menos 2 pontos");
85
+ for (const p of pts) {
86
+ if (!Array.isArray(p.at) || p.at.length !== 2) {
87
+ warnings.push(`ponto '${p.id}' do caminho sem 'at: [x, z]'`);
88
+ p.at = [0.5, 0.5];
89
+ }
90
+ anchors[p.id] = p.at;
91
+ }
92
+ samples = catmull(pts.map((p) => p.at), 40);
93
+ arc = [0];
94
+ for (let i = 1; i < samples.length; i++)
95
+ arc.push(arc[i - 1] + Math.hypot(samples[i][0] - samples[i - 1][0], samples[i][1] - samples[i - 1][1]));
96
+ cps = pts.map((p) => {
97
+ let best = 0, bd = 1e9;
98
+ samples.forEach((s, i) => { const d = Math.hypot(s[0] - p.at[0], s[1] - p.at[1]); if (d < bd) {
99
+ bd = d;
100
+ best = i;
101
+ } });
102
+ return { ...p, arc: arc[best] };
103
+ });
104
+ }
105
+ const distToRoad = (x, z) => { let d = 1e9; for (const s of samples)
106
+ d = Math.min(d, Math.hypot(s[0] - x, s[1] - z)); return d; };
107
+ const pointAt = (u) => {
108
+ const L = arc[arc.length - 1] * Math.min(1, Math.max(0, u));
109
+ let i = arc.findIndex((a) => a >= L);
110
+ if (i <= 0)
111
+ i = 1;
112
+ const a = samples[i - 1], b = samples[i], k = (L - arc[i - 1]) / ((arc[i] - arc[i - 1]) || 1);
113
+ const p = [a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k];
114
+ const tg = [b[0] - a[0], b[1] - a[1]], n = Math.hypot(...tg) || 1;
115
+ return { p, normal: [-tg[1] / n, tg[0] / n] };
116
+ };
117
+ // ---------- espaço livre ----------
118
+ const free = (x, z, r, ignore = []) => {
119
+ if (x - r < 0.02 || x + r > 0.98 || z < -0.04 || z > 1.08)
120
+ return false;
121
+ if (samples.length && distToRoad(x, z) < roadW / 2 + r * 0.9)
122
+ return false;
123
+ for (const cp of cps)
124
+ if (Math.hypot(cp.at[0] - x, cp.at[1] - z) < cpR + r)
125
+ return false;
126
+ for (const f of footprints)
127
+ if (!ignore.includes(f.id) && Math.hypot(f.x - x, (f.z - z) * 1.6) < (f.r + r) * 0.85)
128
+ return false;
129
+ return true;
130
+ };
131
+ // um objeto mais perto da câmera não pode tapar o caminho, checkpoints ou elementos importantes atrás dele
132
+ const protectedSprites = [];
133
+ const occludes = (x, z, A, k, o = {}) => {
134
+ const dims = A.size ? A.size(o) : A, ppu = pxPerUnit(z, k);
135
+ const sx = X(x, z), sy = Y(z), w = dims.w * ppu, h = dims.h * ppu;
136
+ const b = { x0: sx - w * 0.42, x1: sx + w * 0.42, y0: sy - h * 0.95, y1: sy - h * 0.04 };
137
+ for (let i = 0; i < samples.length; i += 2) {
138
+ const p = samples[i];
139
+ if (p[1] > z + 0.005) {
140
+ const px = X(p[0], p[1]), py = Y(p[1]);
141
+ if (px > b.x0 && px < b.x1 && py > b.y0 && py < b.y1)
142
+ return true;
143
+ }
144
+ }
145
+ for (const cp of cps)
146
+ if (cp.at[1] > z) {
147
+ const px = X(...cp.at), py = Y(cp.at[1]);
148
+ if (px > b.x0 - 10 && px < b.x1 + 10 && py > b.y0 && py < b.y1 + 10)
149
+ return true;
150
+ }
151
+ for (const ps of protectedSprites)
152
+ if (ps.z > z) {
153
+ const ov = Math.max(0, Math.min(b.x1, ps.bx1) - Math.max(b.x0, ps.bx0)) * Math.max(0, Math.min(b.y1, ps.by1) - Math.max(b.y0, ps.by0));
154
+ if (ov > 0.12 * ps.w * ps.h)
155
+ return true;
156
+ }
157
+ return false;
158
+ };
159
+ const autoPlace = (ax, az, wUnits, k, opts = {}) => {
160
+ const angles = opts.angles || [90, 60, 120, 30, 150, 0, 180, 20, 160, -30, 210, -90];
161
+ const dists = opts.dists || [0.12, 0.16, 0.2, 0.25, 0.09];
162
+ for (const d of dists)
163
+ for (const a of angles) {
164
+ const x = ax + Math.cos((a * Math.PI) / 180) * d, z = az + Math.sin((a * Math.PI) / 180) * d * 0.9;
165
+ const r = worldR(wUnits, z, k);
166
+ if (free(x, z, r) && !(opts.A && occludes(x, z, opts.A, k, opts.o)))
167
+ return [x, z];
168
+ }
169
+ return null;
170
+ };
171
+ // ---------- adicionar sprite ----------
172
+ const addSprite = (id, o, x, z, opts = {}) => {
173
+ const res = resolveAsset(o.asset || id, LIB);
174
+ if (!res.id) {
175
+ warnings.push(`asset '${o.asset || id}' (em '${id}') não existe; você quis dizer: ${res.suggest.join(", ")}?`);
176
+ return null;
177
+ }
178
+ const A = LIB[res.id];
179
+ const k = typeof o.size === "number" ? o.size : (SIZES[o.size || "medium"] ?? 1);
180
+ const ppu = pxPerUnit(z, k);
181
+ const drawn = A.draw({ ...o }, t);
182
+ const svg = typeof drawn === "string" ? drawn : drawn.svg;
183
+ const dims = A.size ? A.size(o) : { w: A.w, h: A.h };
184
+ const lift = opts.lift ?? o.lift ?? 0;
185
+ const sx = X(x, z), sy = Y(z) - lift * U * S(z);
186
+ const sp = { id, asset: res.id, kind: A.kind, x, z, lift, sx, sy, ppu, svg, w: dims.w * ppu, h: dims.h * ppu, hu: dims.h * k, decor: !!opts.decor, person: res.id === "person" };
187
+ sp.wx = (sp.w / 2) / (W * 0.98 * xs(z)) * (A.footprint ?? 0.55); // meia-largura do pé no mundo
188
+ sp.bx0 = sx - sp.w / 2;
189
+ sp.bx1 = sx + sp.w / 2;
190
+ sp.by0 = sy - sp.h;
191
+ sp.by1 = sy;
192
+ sprites.push(sp);
193
+ if (!opts.noFootprint)
194
+ footprints.push({ id, x, z, r: worldR(dims.w, z, k) * (res.id === "person" ? 0.6 : 1) });
195
+ anchors[id] = [x, z];
196
+ return sp;
197
+ };
198
+ // ---------- zonas (decoração automática perto do checkpoint) ----------
199
+ const zoneDefs = { ...ZONE_PRESETS, ...(scene.zones || {}) };
200
+ const tints = [];
201
+ for (const cp of cps) {
202
+ if (!cp.zone)
203
+ continue;
204
+ const Z = zoneDefs[cp.zone];
205
+ if (!Z) {
206
+ warnings.push(`zona '${cp.zone}' (ponto '${cp.id}') não existe; disponíveis: ${Object.keys(zoneDefs).join(", ")}`);
207
+ continue;
208
+ }
209
+ const tint = typeof Z.tint === "function" ? Z.tint(t) : (t[Z.tint] || Z.tint || sh(t.ground, 0.3));
210
+ tints.push({ x: cp.at[0], z: cp.at[1], r: Z.radius ?? 0.24, color: tint });
211
+ cp.tint = tint;
212
+ }
213
+ // ---------- caixas com volume (móveis, bancadas, construções) ----------
214
+ const boxes = [];
215
+ for (const [id, b] of Object.entries(scene.boxes || {})) {
216
+ if (!Array.isArray(b.from) || !Array.isArray(b.to)) {
217
+ warnings.push(`caixa '${id}' precisa de from: [x, z] e to: [x, z]`);
218
+ continue;
219
+ }
220
+ const x0 = Math.min(b.from[0], b.to[0]), x1 = Math.max(b.from[0], b.to[0]);
221
+ const z0 = Math.min(b.from[1], b.to[1]), z1 = Math.max(b.from[1], b.to[1]);
222
+ const h = b.height ?? 40, e = b.elevation ?? (b.thickness ? h - b.thickness : 0);
223
+ if (e >= h) {
224
+ warnings.push(`caixa '${id}': elevation (${e}) deve ser menor que height (${h})`);
225
+ continue;
226
+ }
227
+ boxes.push({ id, x0, x1, z0, z1, e, h, b, color: t[b.color] || b.color || t.wood });
228
+ anchors[id] = [(x0 + x1) / 2, (z0 + z1) / 2];
229
+ }
230
+ for (let i = 0; i < boxes.length; i++)
231
+ for (let j = i + 1; j < boxes.length; j++) {
232
+ const a = boxes[i], q = boxes[j];
233
+ const ix = Math.min(a.x1, q.x1) - Math.max(a.x0, q.x0), iz = Math.min(a.z1, q.z1) - Math.max(a.z0, q.z0), ih = Math.min(a.h, q.h) - Math.max(a.e, q.e);
234
+ if (ix > 0.002 && iz > 0.002 && ih > 0.5)
235
+ warnings.push(`caixas '${a.id}' e '${q.id}' se interpenetram; ajuste from/to ou elevation`);
236
+ }
237
+ const boxById = Object.fromEntries(boxes.map((bx) => [bx.id, bx]));
238
+ // ordem de desenho: caixa embaixo de outra (ex.: gaveteiro sob o tampo) é desenhada antes dela
239
+ boxes.forEach((bx) => { bx.key = bx.z1; });
240
+ for (let pass = 0; pass < 3; pass++)
241
+ for (const a2 of boxes)
242
+ for (const b2 of boxes) {
243
+ if (a2 === b2)
244
+ continue;
245
+ const ix = Math.min(a2.x1, b2.x1) - Math.max(a2.x0, b2.x0), iz = Math.min(a2.z1, b2.z1) - Math.max(a2.z0, b2.z0);
246
+ if (ix > 0 && iz > 0 && a2.h <= b2.e + 0.5 && a2.key <= b2.key)
247
+ a2.key = b2.key + 1e-4;
248
+ }
249
+ // ---------- objetos explícitos do autor ----------
250
+ const objs = scene.objects || {};
251
+ const order = Object.keys(objs);
252
+ // resolve âncoras em ordem de dependência simples (near precisa existir)
253
+ const pending = new Set(order);
254
+ for (let pass = 0; pass < 4 && pending.size; pass++)
255
+ for (const id of [...pending]) {
256
+ const o = objs[id];
257
+ let x, z;
258
+ if (Array.isArray(o.at))
259
+ [x, z] = o.at;
260
+ else if (o.along != null) {
261
+ if (!samples.length) {
262
+ warnings.push(`'${id}' usa 'along', mas a cena não tem path`);
263
+ pending.delete(id);
264
+ continue;
265
+ }
266
+ const { p, normal } = pointAt(o.along);
267
+ const side = o.side === "left" ? 1 : o.side === "right" ? -1 : 0;
268
+ const d = o.dist ?? (side ? roadW / 2 + 0.05 : 0);
269
+ [x, z] = [p[0] + normal[0] * d * side, p[1] + normal[1] * d * side];
270
+ }
271
+ else if (o.near) {
272
+ if (!anchors[o.near]) {
273
+ if (pass === 3) {
274
+ warnings.push(`'${id}' está 'near: ${o.near}', que não existe`);
275
+ pending.delete(id);
276
+ }
277
+ continue;
278
+ }
279
+ const [ax, az] = anchors[o.near];
280
+ if (o.offset)
281
+ [x, z] = [ax + o.offset[0], az + o.offset[1]];
282
+ else if ((o.asset || id) === "person" || o.on_spot)
283
+ [x, z] = [ax, az - 0.005];
284
+ else {
285
+ const res = resolveAsset(o.asset || id, LIB);
286
+ const A = res.id && LIB[res.id];
287
+ const k = typeof o.size === "number" ? o.size : (SIZES[o.size || "medium"] ?? 1);
288
+ const spot = A && autoPlace(ax, az, (A.size ? A.size(o) : A).w, k);
289
+ if (!spot) {
290
+ warnings.push(`não encontrei espaço livre perto de '${o.near}' para '${id}'; use 'offset: [dx, dz]'`);
291
+ [x, z] = [ax + 0.1, az + 0.1];
292
+ }
293
+ else
294
+ [x, z] = spot;
295
+ }
296
+ }
297
+ else if (typeof o.at === "string" && LIB[resolveAsset(o.asset || id, LIB).id || ""]?.kind === "sky") {
298
+ [x, z] = [SLOTS[o.at.replace("top-", "")] ?? 0.5, 99];
299
+ }
300
+ else {
301
+ warnings.push(`'${id}' sem posição: use at: [x, z], near, ou along`);
302
+ pending.delete(id);
303
+ continue;
304
+ }
305
+ pending.delete(id);
306
+ if (z === 99) { // objeto de céu
307
+ const res = resolveAsset(o.asset || id, LIB);
308
+ if (!res.id)
309
+ continue;
310
+ const A = LIB[res.id], k = typeof o.size === "number" ? o.size : (SIZES[o.size || "medium"] ?? 1), ppu = H * 0.0017 * k;
311
+ sprites.push({ id, asset: res.id, kind: "sky", sx: x * W, sy: H * (o.altitude ?? 0.12) + A.h * ppu / 2, ppu, z: 50, svg: A.draw({ ...o }, t), w: A.w * ppu, h: A.h * ppu, sky: true });
312
+ continue;
313
+ }
314
+ let lift;
315
+ if (o.on && boxById[o.on]) {
316
+ const bx = boxById[o.on];
317
+ lift = bx.h;
318
+ if (x < bx.x0 - 0.005 || x > bx.x1 + 0.005 || z < bx.z0 - 0.005 || z > bx.z1 + 0.005)
319
+ warnings.push(`'${id}' está 'on: ${o.on}', mas a posição [${x}, ${z}] fica fora do topo da caixa`);
320
+ }
321
+ else if (o.on)
322
+ warnings.push(`'${id}' está 'on: ${o.on}', que não é uma caixa`);
323
+ const sp = addSprite(id, o, x, z, lift != null ? { lift } : {});
324
+ if (sp)
325
+ protectedSprites.push(sp);
326
+ if (sp && samples.length && !sp.person && !["sky"].includes(sp.kind) && o.on_path !== true && distToRoad(x, z) < roadW / 2)
327
+ warnings.push(`'${id}' está em cima do caminho; mova-o ou use 'on_path: true' se for intencional`);
328
+ }
329
+ // decoração das zonas (depois dos objetos do autor, para respeitar o espaço deles)
330
+ for (const cp of cps) {
331
+ const Z = cp.zone && zoneDefs[cp.zone];
332
+ if (!Z || cp.decor === false)
333
+ continue;
334
+ (Z.decor || []).forEach((d, i) => {
335
+ const A = LIB[resolveAsset(d.asset, LIB).id || ""];
336
+ if (!A)
337
+ return;
338
+ const k = d.size ?? 1;
339
+ const spot = autoPlace(cp.at[0], cp.at[1], (A.size ? A.size(d) : A).w, k, i === 0 ? { A, o: d } : { A, o: d, dists: [0.1, 0.14, 0.18, 0.22, 0.27] });
340
+ if (!spot) {
341
+ if (i === 0)
342
+ warnings.push(`zona '${cp.zone}': sem espaço livre para '${d.asset}' perto de '${cp.id}'`);
343
+ return;
344
+ }
345
+ const sp = addSprite(`${cp.id}_${d.asset}_${i}`, { ...d, size: k }, spot[0], spot[1], { decor: true });
346
+ if (sp && i === 0)
347
+ protectedSprites.push(sp);
348
+ });
349
+ }
350
+ // espalhamento (vegetação etc.)
351
+ for (const [si, sc] of (scene.scatter || []).entries()) {
352
+ const R = rng(sc.seed ?? 7 + si), list = sc.assets || ["tree", "bush"];
353
+ const [x0, z0, x1, z1] = sc.area || [0.02, 0, 0.98, 1.05];
354
+ let placedN = 0, tries = 0;
355
+ while (placedN < (sc.count ?? 15) && tries++ < 3000) {
356
+ const x = x0 + R() * (x1 - x0), z = z0 + R() * (z1 - z0), a = list[Math.floor(R() * list.length)];
357
+ const A = LIB[resolveAsset(a, LIB).id || ""];
358
+ if (!A) {
359
+ warnings.push(`scatter: asset '${a}' não existe`);
360
+ break;
361
+ }
362
+ const k = (sc.size ?? 0.8) * (0.8 + R() * 0.4);
363
+ if (!free(x, z, worldR(A.w, z, k) * 0.9) || occludes(x, z, A, k))
364
+ continue;
365
+ addSprite(`scatter${si}_${placedN}`, { asset: a, size: k, facing: R() < 0.5 ? "left" : "right" }, x, z, { decor: true });
366
+ placedN++;
367
+ }
368
+ }
369
+ for (const cp of cps)
370
+ cp.occupied = sprites.some((sp) => sp.person && Math.hypot(sp.x - cp.at[0], sp.z - cp.at[1]) < cpR);
371
+ // ---------- desenho: céu, horizonte, chão ----------
372
+ const zH = c.horizon_z ?? 1.45, yH = Y(zH);
373
+ let defs = `<linearGradient id="sky" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${t.skyTop}"/><stop offset="1" stop-color="${t.skyBottom}"/></linearGradient>` +
374
+ `<linearGradient id="ground" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${sh(t.ground, 0.18)}"/><stop offset="1" stop-color="${t.ground}"/></linearGradient>`;
375
+ const sm = (t.shadow.match(/[\d.]+/g) || [0, 0, 0, 0.15]).map(Number);
376
+ defs += `<radialGradient id="cshadow"><stop offset="0" stop-color="rgb(${sm[0]},${sm[1]},${sm[2]})" stop-opacity="${sm[3] * 1.5}"/><stop offset="0.55" stop-color="rgb(${sm[0]},${sm[1]},${sm[2]})" stop-opacity="${sm[3] * 1.1}"/><stop offset="1" stop-color="rgb(${sm[0]},${sm[1]},${sm[2]})" stop-opacity="0"/></radialGradient>`;
377
+ if (HAZE)
378
+ HAZE.forEach(([, k], i) => { defs += `<filter id="haze${i + 1}" color-interpolation-filters="sRGB"><feColorMatrix type="matrix" values="${1 - k} 0 0 0 ${(ar * k).toFixed(3)} 0 ${1 - k} 0 0 ${(ag * k).toFixed(3)} 0 0 ${1 - k} 0 ${(ab * k).toFixed(3)} 0 0 0 1 0"/></filter>`; });
379
+ tints.forEach((tn, i) => { defs += `<radialGradient id="zone${i}"><stop offset="0" stop-color="${tn.color}" stop-opacity="1"/><stop offset="0.62" stop-color="${tn.color}" stop-opacity="0.9"/><stop offset="1" stop-color="${tn.color}" stop-opacity="0"/></radialGradient>`; });
380
+ let bg = ROOM ? "" : `<rect width="${W}" height="${H}" fill="url(#sky)"/>`;
381
+ const poly = (pts, fill, extra = "") => `<polygon points="${pts.map((p) => f1(p[0]) + "," + f1(p[1])).join(" ")}" fill="${fill}" ${extra}/>`;
382
+ if (ROOM) {
383
+ const wl = scene.walls || {}, fl = scene.floor || {};
384
+ const zB = wl.back?.z ?? 1, xR = wl.right?.x ?? (wl.right === false ? 3 : 1), xL = wl.left?.x ?? -3, zMin = fl.from_z ?? -0.8, wh = wl.height ?? 320;
385
+ const backC = t[wl.back?.color] || wl.back?.color || t.wall, rightC = t[wl.right?.color] || wl.right?.color || sh(backC, -0.07), leftC = t[wl.left?.color] || wl.left?.color || sh(backC, -0.04);
386
+ const floorC = t[fl.color] || fl.color || t.floor;
387
+ bg += `<rect width="${W}" height="${H}" fill="${backC}"/>`;
388
+ bg += poly([P3(xL, zMin), P3(xR, zMin), P3(xR, zB), P3(xL, zB)], floorC);
389
+ if (fl.planks !== false) {
390
+ const pw = fl.plank_width ?? 0.05;
391
+ for (let x = xL, i = 0; x < xR; x += pw, i++) {
392
+ const a = Math.max(x, xL), b2 = Math.min(x + pw, xR);
393
+ if (b2 - a < 1e-4)
394
+ continue; // evita caminhos de comprimento zero (o resvg não aceita)
395
+ {
396
+ const xa = P3(a, zMin)[0], xb = P3(b2, zMin)[0], xc = P3(a, zB)[0];
397
+ if (Math.max(xa, xb, xc) < -40 || Math.min(xa, xb, xc) > W + 40)
398
+ continue;
399
+ } // fora do quadro
400
+ bg += poly([P3(a, zMin), P3(b2, zMin), P3(b2, zB), P3(a, zB)], sh(floorC, ((i * 7) % 3) * 0.025 - 0.02)) +
401
+ `<path d="M${P3(a, zMin).map(f1).join(" ")} L${P3(a, zB).map(f1).join(" ")}" stroke="${sh(floorC, -0.3)}" stroke-width="1" opacity="0.55"/>`;
402
+ // juntas transversais
403
+ // juntas como faixas finas (linhas perfeitamente horizontais derrubam o renderizador)
404
+ for (let zz = zMin + ((i * 0.37) % 0.5); zz < zB; zz += 0.55) {
405
+ const p1 = P3(a, zz), p2 = P3(b2, zz), th = Math.max(0.6, 1.2 * S(zz));
406
+ bg += poly([[p1[0], p1[1] - th / 2], [p2[0], p2[1] - th / 2], [p2[0], p2[1] + th / 2], [p1[0], p1[1] + th / 2]], sh(floorC, -0.3), "opacity=\"0.4\"");
407
+ }
408
+ }
409
+ }
410
+ bg += poly([P3(xL, zB, 0), P3(xR, zB, 0), P3(xR, zB, wh), P3(xL, zB, wh)], backC);
411
+ bg += poly([P3(xL, zB, 0), P3(xR, zB, 0), P3(xR, zB, 4), P3(xL, zB, 4)], sh(backC, -0.08));
412
+ if (xR < 2)
413
+ bg += poly([P3(xR, zMin, 0), P3(xR, zB, 0), P3(xR, zB, wh), P3(xR, zMin, wh)], rightC) + poly([P3(xR, zMin, 0), P3(xR, zB, 0), P3(xR, zB, 4), P3(xR, zMin, 4)], sh(rightC, -0.08)) +
414
+ `<path d="M${P3(xR, zB, 0).map(f1).join(" ")} L${P3(xR, zB, wh).map(f1).join(" ")}" stroke="${sh(backC, -0.12)}" stroke-width="1.2"/>`;
415
+ if (xL > -2)
416
+ bg += poly([P3(xL, zMin, 0), P3(xL, zB, 0), P3(xL, zB, wh), P3(xL, zMin, wh)], leftC);
417
+ // sombra de contato das caixas no chão
418
+ for (const bx of boxes)
419
+ if (bx.e < 8 && bx.b.shadow !== false) {
420
+ const m = 0.012;
421
+ bg += poly([P3(bx.x0 - m, bx.z0 - m), P3(bx.x1 + m, bx.z0 - m), P3(bx.x1 + m, bx.z1), P3(bx.x0 - m, bx.z1)], t.shadow);
422
+ }
423
+ }
424
+ if (!ROOM) {
425
+ // morros distantes
426
+ const hill = sh(t.groundDark || t.ground, 0.25);
427
+ bg += `<path d="M0 ${f1(yH)} Q${W * 0.12} ${f1(yH - H * 0.07)} ${W * 0.28} ${f1(yH - H * 0.02)} T${W * 0.6} ${f1(yH - H * 0.04)} T${W} ${f1(yH - H * 0.05)} L${W} ${f1(yH + 4)} L0 ${f1(yH + 4)} Z" fill="${hill}" opacity="0.7"/>`;
428
+ bg += `<path d="M0 ${f1(yH + 2)} Q${W * 0.25} ${f1(yH - H * 0.035)} ${W * 0.5} ${f1(yH)} T${W} ${f1(yH - H * 0.02)} L${W} ${H} L0 ${H} Z" fill="url(#ground)"/>`;
429
+ }
430
+ // manchas de zona
431
+ tints.forEach((tn, i) => {
432
+ const cx = X(tn.x, tn.z), cy = Y(tn.z), rx = tn.r * W * 0.98 * xs(tn.z), ry = (Y(tn.z - tn.r) - Y(tn.z + tn.r)) / 2;
433
+ bg += `<ellipse cx="${f1(cx)}" cy="${f1(cy)}" rx="${f1(rx)}" ry="${f1(ry)}" fill="url(#zone${i})"/>`;
434
+ });
435
+ // caminho: espessura, base, casas e checkpoints
436
+ let road = "";
437
+ if (samples.length) {
438
+ const edge = (sign, extra = 0) => samples.map((p, i) => {
439
+ const a = samples[Math.max(0, i - 1)], b = samples[Math.min(samples.length - 1, i + 1)];
440
+ const tx = b[0] - a[0], tz = b[1] - a[1], n = Math.hypot(tx, tz) || 1;
441
+ const hw = roadW / 2 + extra;
442
+ return [p[0] - (tz / n) * hw * sign, p[1] + (tx / n) * hw * sign];
443
+ });
444
+ const poly = (extra, dy = 0) => {
445
+ const L = edge(1, extra), R = edge(-1, extra).reverse();
446
+ return [...L, ...R].map(([x, z]) => `${f1(X(x, z))},${f1(Y(z) + dy * S(z))}`).join(" ");
447
+ };
448
+ const roadC = pathDef.color ? (t[pathDef.color] || pathDef.color) : sh(t.paper, -0.04);
449
+ road += `<polygon points="${poly(0.006, 7)}" fill="${sh(t.ground, -0.35)}" opacity="0.55"/>`;
450
+ road += `<polygon points="${poly(0.006)}" fill="${sh(roadC, -0.25)}"/><polygon points="${poly(0)}" fill="${roadC}"/>`;
451
+ if (pathDef.tiles !== false) {
452
+ const total = arc[arc.length - 1], tile = pathDef.tile_length ?? 0.045;
453
+ const tileColors = [sh(t.accent, 0.55), sh(t.primary, 0.62), sh(t.secondary, 0.65)];
454
+ let k = 0;
455
+ for (let a = tile * 0.2; a < total - tile * 0.5; a += tile) {
456
+ const b = a + tile * 0.8;
457
+ if (cps.some((cp) => Math.abs(cp.arc - (a + b) / 2) < cpR + tile * 0.45)) {
458
+ k++;
459
+ continue;
460
+ }
461
+ const P1 = pointAt(a / total), P2 = pointAt(b / total), hw = roadW / 2 * 0.8;
462
+ const q = [[P1.p, P1.normal, 1], [P2.p, P2.normal, 1], [P2.p, P2.normal, -1], [P1.p, P1.normal, -1]]
463
+ .map(([p, n, sgn]) => [p[0] + n[0] * hw * sgn, p[1] + n[1] * hw * sgn]).map(([x, z]) => `${f1(X(x, z))},${f1(Y(z))}`).join(" ");
464
+ road += `<polygon points="${q}" fill="${tileColors[k++ % tileColors.length]}"/>`;
465
+ }
466
+ }
467
+ // checkpoints
468
+ cps.forEach((cp, idx) => {
469
+ const [x, z] = cp.at, cx = X(x, z), cy = Y(z), rx = cpR * W * 0.98 * xs(z), ry = (Y(z - cpR) - Y(z + cpR)) / 2;
470
+ const col = cp.finish ? t.accent : (t[cp.color] || cp.color || t.primary);
471
+ road += `<ellipse cx="${f1(cx)}" cy="${f1(cy + 6 * S(z))}" rx="${f1(rx)}" ry="${f1(ry)}" fill="${sh(col, -0.3)}"/>` +
472
+ `<ellipse cx="${f1(cx)}" cy="${f1(cy)}" rx="${f1(rx)}" ry="${f1(ry)}" fill="${col}"/>` +
473
+ `<ellipse cx="${f1(cx)}" cy="${f1(cy)}" rx="${f1(rx * 0.78)}" ry="${f1(ry * 0.78)}" fill="none" stroke="${t.paper}" stroke-width="${f1(2.5 * S(z))}" opacity="0.8"/>`;
474
+ if (!cp.occupied)
475
+ road += `<text x="${f1(cx)}" y="${f1(cy + ry * 0.35)}" font-family="${FONT}" font-weight="700" font-size="${f1(ry * 1.1)}" fill="${t.paper}" text-anchor="middle">${cp.finish ? "★" : idx + 1}</text>`;
476
+ });
477
+ }
478
+ // ---------- sprites ordenados por profundidade ----------
479
+ const groundSprites = sprites.filter((s) => !s.sky).sort((a, b) => b.z - a.z || a.sy - b.sy);
480
+ const skySprites = sprites.filter((s) => s.sky);
481
+ const drawSprite = (s) => {
482
+ const lv = s.sky ? 0 : hazeLevel(s.z);
483
+ const art = s.svg.replace(/<ellipse cx="([-\d.]+)" cy="0" rx="([\d.]+)" ry="([\d.]+)" fill="[^"]*"( stroke="none")?\s*\/>/, (m, cx, rx, ry) => m.includes(t.shadow) ? `<ellipse cx="${cx}" cy="0" rx="${(rx * 1.25).toFixed(1)}" ry="${(ry * 1.6).toFixed(1)}" fill="url(#cshadow)"/>` : m);
484
+ return `<g id="${s.id}" transform="translate(${f1(s.sx)} ${f1(s.sy)}) scale(${s.ppu.toFixed(3)})"${lv ? ` filter="url(#haze${lv})"` : ""}>${art}</g>`;
485
+ };
486
+ // ---------- caixas: só as faces visíveis, com detalhes de portas/gavetas na face escolhida ----------
487
+ const camX = ROOM ? cam.cx : 0.5;
488
+ const drawBox = (bx) => {
489
+ const { x0, x1, z0, z1, e, h, color, b } = bx;
490
+ const q = P3, poly2 = (pts, fill, extra = "") => `<polygon points="${pts.map((pp) => f1(pp[0]) + "," + f1(pp[1])).join(" ")}" fill="${fill}" ${extra}/>`;
491
+ const faces = {
492
+ front: [q(x0, z0, e), q(x1, z0, e), q(x1, z0, h), q(x0, z0, h)],
493
+ left: [q(x0, z1, e), q(x0, z0, e), q(x0, z0, h), q(x0, z1, h)],
494
+ right: [q(x1, z0, e), q(x1, z1, e), q(x1, z1, h), q(x1, z0, h)],
495
+ };
496
+ const det = b.details || (b.front ? { type: b.front, count: b.count, face: "front" } : null);
497
+ const dFace = det?.face || "front";
498
+ const topC = t[b.top_color] || b.top_color || sh(color, 0.1), sideC = sh(color, -0.12);
499
+ let g = "";
500
+ if (e > 0 && q(x0, z1, e)[1] > q(x0, z0, e)[1])
501
+ g += poly2([q(x0, z0, e), q(x1, z0, e), q(x1, z1, e), q(x0, z1, e)], sh(color, -0.32));
502
+ if (camX < x0)
503
+ g += poly2(faces.left, dFace === "left" ? color : sideC);
504
+ if (camX > x1)
505
+ g += poly2(faces.right, dFace === "right" ? color : sideC);
506
+ const top = [q(x0, z0, h), q(x1, z0, h), q(x1, z1, h), q(x0, z1, h)];
507
+ if (top[3][1] < top[0][1] - 0.3)
508
+ g += poly2(top, topC);
509
+ g += poly2(faces.front, dFace === "front" ? color : sh(color, -0.04));
510
+ g += `<path d="M${top[0].map(f1).join(" ")} L${top[1].map(f1).join(" ")}" stroke="${sh(color, 0.3)}" stroke-width="1"/>`;
511
+ if (det && faces[dFace] && (dFace === "front" || (dFace === "left" ? camX < x0 : camX > x1))) {
512
+ const [BL, BR, TR, TL] = faces[dFace];
513
+ const bil = (u, v) => { const bx2 = BL[0] + (BR[0] - BL[0]) * u, by2 = BL[1] + (BR[1] - BL[1]) * u, tx = TL[0] + (TR[0] - TL[0]) * u, ty = TL[1] + (TR[1] - TL[1]) * u; return [bx2 + (tx - bx2) * v, by2 + (ty - by2) * v]; };
514
+ const zm = dFace === "front" ? z0 : (z0 + z1) / 2, sw = Math.max(0.7, U * S(zm) * 0.16);
515
+ const ln = (a, bb, col2, w2) => `<path d="M${a.map(f1).join(" ")} L${bb.map(f1).join(" ")}" stroke="${col2}" stroke-width="${f1(w2)}" stroke-linecap="round"/>`;
516
+ const pv = (det.plinth ?? 2) / (h - e);
517
+ if (pv > 0)
518
+ g += poly2([bil(0, 0), bil(1, 0), bil(1, pv), bil(0, pv)], sh(color, -0.28));
519
+ const n = det.count || (det.type === "drawers" ? 4 : 2), gap = sh(color, -0.3), metal = t[det.handle] || det.handle || t.metal;
520
+ if (det.type === "drawers") {
521
+ for (let i = 0; i < n; i++) {
522
+ const v1 = 1 - i * (1 - pv) / n, v0 = v1 - (1 - pv) / n, vm = (v0 + v1) / 2 + (v1 - v0) * 0.08;
523
+ if (i > 0)
524
+ g += ln(bil(0.02, v1), bil(0.98, v1), gap, sw);
525
+ g += ln(bil(0.28, vm), bil(0.72, vm), metal, sw * 1.8) + ln(bil(0.28, vm - (v1 - v0) * 0.06), bil(0.72, vm - (v1 - v0) * 0.06), sh(metal, -0.35), sw * 0.6);
526
+ }
527
+ }
528
+ else if (det.type === "doors") {
529
+ for (let i = 1; i < n; i++)
530
+ g += ln(bil(i / n, pv), bil(i / n, 0.99), gap, sw);
531
+ for (let i = 0; i < n; i++) {
532
+ const u = n === 1 ? 0.88 : (i < n / 2 ? (i + 1) / n - 0.045 : i / n + 0.045);
533
+ g += ln(bil(u, 0.42), bil(u, 0.74), metal, sw * 1.8);
534
+ }
535
+ }
536
+ else if (det.type === "open") {
537
+ g += poly2([bil(0.05, pv + 0.04), bil(0.95, pv + 0.04), bil(0.95, 0.95), bil(0.05, 0.95)], sh(color, -0.38));
538
+ for (const vv of (det.shelves || [0.5]))
539
+ g += ln(bil(0.05, vv), bil(0.95, vv), color, sw * 2.2);
540
+ }
541
+ }
542
+ return `<g id="${bx.id}"${b.opacity != null ? ` opacity="${b.opacity}"` : ""}>${g}</g>`;
543
+ };
544
+ // ---------- ordem de desenho (pintor com relações par a par) ----------
545
+ // Cada item vira um volume no mundo: caixa = [x0,x1]×[z0,z1]×[e,h]; recorte = pé fino em z com largura do desenho.
546
+ // Para cada par que se sobrepõe na tela decidimos quem está atrás (separação em z, depois em x vista da câmera,
547
+ // depois em altura, com a câmera acima) e desenhamos numa ordem topológica que respeita todas essas relações.
548
+ const drawOrdered = () => {
549
+ const items = [
550
+ ...groundSprites.map((sp) => ({ kind: "sprite", cx: sp.x, x0: sp.x - sp.wx, x1: sp.x + sp.wx, z0: sp.z, z1: sp.z, e: sp.lift, h: sp.lift + sp.hu, sb: [sp.bx0, sp.by0, sp.bx1, sp.by1], svg: () => drawSprite(sp), ref: sp })),
551
+ ...boxes.map((bx) => {
552
+ const pts = [bx.x0, bx.x1].flatMap((xx) => [bx.z0, bx.z1].flatMap((zz) => [bx.e, bx.h].map((hh) => P3(xx, zz, hh))));
553
+ const xsS = pts.map((p) => p[0]), ysS = pts.map((p) => p[1]);
554
+ return { kind: "box", x0: bx.x0, x1: bx.x1, z0: bx.z0, z1: bx.z1, e: bx.e, h: bx.h, sb: [Math.min(...xsS), Math.min(...ysS), Math.max(...xsS), Math.max(...ysS)], svg: () => drawBox(bx), ref: bx };
555
+ }),
556
+ ];
557
+ const EPS = 1e-4;
558
+ const behind = (A, B) => {
559
+ const sameZ = A.z0 === A.z1 && B.z0 === B.z1 && Math.abs(A.z0 - B.z0) < EPS;
560
+ if (!sameZ) {
561
+ if (A.z0 >= B.z1 - EPS)
562
+ return true;
563
+ if (B.z0 >= A.z1 - EPS)
564
+ return false;
565
+ }
566
+ // recortes não têm volume: se o centro do recorte está fora da caixa no eixo x, tratamos como separados
567
+ const ax0 = A.kind === "sprite" && B.kind === "box" && (A.cx > B.x1 || A.cx < B.x0) ? A.cx : A.x0, ax1 = A.kind === "sprite" && B.kind === "box" && (A.cx > B.x1 || A.cx < B.x0) ? A.cx : A.x1;
568
+ const bx0 = B.kind === "sprite" && A.kind === "box" && (B.cx > A.x1 || B.cx < A.x0) ? B.cx : B.x0, bx1 = B.kind === "sprite" && A.kind === "box" && (B.cx > A.x1 || B.cx < A.x0) ? B.cx : B.x1;
569
+ if (ax1 <= bx0 + EPS)
570
+ return camX >= (ax1 + bx0) / 2;
571
+ if (bx1 <= ax0 + EPS)
572
+ return camX <= (bx1 + ax0) / 2;
573
+ if (A.h <= B.e + 0.5)
574
+ return true; // A embaixo de B (câmera acima): A primeiro
575
+ if (B.h <= A.e + 0.5)
576
+ return false;
577
+ return (A.z0 + A.z1) / 2 > (B.z0 + B.z1) / 2; // volumes que se cruzam: centro mais distante primeiro
578
+ };
579
+ const n = items.length, edges = items.map(() => []), indeg = new Array(n).fill(0);
580
+ const ov = (a, b) => a.sb[0] < b.sb[2] && b.sb[0] < a.sb[2] && a.sb[1] < b.sb[3] && b.sb[1] < a.sb[3];
581
+ for (let i = 0; i < n; i++)
582
+ for (let j = i + 1; j < n; j++) {
583
+ if (!ov(items[i], items[j]))
584
+ continue;
585
+ const [a, b] = behind(items[i], items[j]) ? [i, j] : [j, i];
586
+ edges[a].push(b);
587
+ indeg[b]++;
588
+ }
589
+ // Kahn; empate e ciclos resolvidos pelo mais distante primeiro
590
+ const far = (i) => -((items[i].z0 + items[i].z1) / 2) * 1000 + items[i].e * 0.001;
591
+ const done = new Array(n).fill(false), out = [];
592
+ while (out.length < n) {
593
+ let pick = -1;
594
+ for (let i = 0; i < n; i++)
595
+ if (!done[i] && indeg[i] === 0 && (pick < 0 || far(i) < far(pick)))
596
+ pick = i;
597
+ if (pick < 0) {
598
+ for (let i = 0; i < n; i++)
599
+ if (!done[i] && (pick < 0 || indeg[i] < indeg[pick] || (indeg[i] === indeg[pick] && far(i) < far(pick))))
600
+ pick = i;
601
+ warnings.push(`ordem de profundidade ambígua envolvendo '${items[pick].ref.id}' (volumes se cruzando); afaste os objetos ou ajuste from/to`);
602
+ }
603
+ done[pick] = true;
604
+ out.push(pick);
605
+ for (const j of edges[pick])
606
+ indeg[j]--;
607
+ }
608
+ return out.map((i) => items[i].svg()).join("\n");
609
+ };
610
+ // ---------- rótulos dos checkpoints ----------
611
+ const labels = [];
612
+ const labelBlockers = groundSprites.filter((s) => !s.decor || s.h > 40).map((s) => ({ x0: s.bx0, x1: s.bx1, y0: s.by0, y1: s.by1, id: s.id }));
613
+ const overlap = (a, b) => Math.max(0, Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0)) * Math.max(0, Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0));
614
+ const titleBox = [];
615
+ for (const [idx, cp] of cps.entries()) {
616
+ if (!cp.label)
617
+ continue;
618
+ const [x, z] = cp.at, cx = X(x, z), cy = Y(z);
619
+ const fs = Math.max(13, H * 0.024 * (0.75 + 0.25 * S(z) / 1));
620
+ const txt = `${cp.finish ? "★" : idx + 1} ${cp.label}`;
621
+ const w = txt.length * fs * 0.56 + fs * 1.4, h = fs * 1.8;
622
+ const ry = (Y(z - cpR) - Y(z + cpR)) / 2;
623
+ const personAbove = groundSprites.find((s) => s.person && Math.abs(s.sx - cx) < 20 && Math.abs(s.sy - cy) < 20);
624
+ const up = personAbove ? personAbove.h + fs * 0.6 : fs * 2.4;
625
+ const cands = [
626
+ [cx - w / 2, cy - up - h], [cx + ry * 2.2, cy - h * 0.5], [cx - ry * 2.2 - w, cy - h * 0.5],
627
+ [cx + ry * 1.6, cy - up * 0.7 - h], [cx - ry * 1.6 - w, cy - up * 0.7 - h], [cx - w / 2, cy + ry * 2],
628
+ ];
629
+ if (cp.label_side === "left")
630
+ cands.unshift(cands[2]);
631
+ if (cp.label_side === "right")
632
+ cands.unshift(cands[1]);
633
+ if (cp.label_side === "below")
634
+ cands.unshift(cands[5]);
635
+ let best = null, bestScore = Infinity;
636
+ for (const [lx, ly] of cands) {
637
+ const b = { x0: lx, x1: lx + w, y0: ly, y1: ly + h };
638
+ let score = 0;
639
+ if (b.x0 < 6 || b.x1 > W - 6 || b.y0 < 6 || b.y1 > H - 6)
640
+ score += 1e6;
641
+ for (const o of [...labelBlockers, ...labels, ...titleBox])
642
+ score += overlap(b, o) * (o.label ? 3 : 1);
643
+ if (score < bestScore) {
644
+ bestScore = score;
645
+ best = b;
646
+ }
647
+ }
648
+ if (bestScore > w * h * 0.15)
649
+ warnings.push(`rótulo '${cp.label}' sobrepõe outros elementos (${Math.round(bestScore / (w * h) * 100)}% da área); ajuste 'label_side' ou a posição do ponto`);
650
+ best.label = true;
651
+ best.cx = cx;
652
+ best.cy = cy;
653
+ best.txt = txt;
654
+ best.fs = fs;
655
+ best.finish = cp.finish;
656
+ best.color = cp.finish ? t.accent : (t[cp.color] || cp.color || t.primary);
657
+ labels.push(best);
658
+ }
659
+ const labelSvg = labels.map((b) => {
660
+ const ax = Math.min(Math.max(b.cx, b.x0 + 8), b.x1 - 8), ay = b.y1 < b.cy ? b.y1 : b.y0;
661
+ return `<path d="M${f1(ax)} ${f1(ay)} L${f1(b.cx)} ${f1(b.cy)}" stroke="${t.ink}" stroke-width="1.5" opacity="0.45" stroke-dasharray="3 3"/>` +
662
+ `<rect x="${f1(b.x0 + 2)}" y="${f1(b.y0 + 3)}" width="${f1(b.x1 - b.x0)}" height="${f1(b.y1 - b.y0)}" rx="${f1((b.y1 - b.y0) / 2)}" fill="${t.ink}" opacity="0.15"/>` +
663
+ `<rect x="${f1(b.x0)}" y="${f1(b.y0)}" width="${f1(b.x1 - b.x0)}" height="${f1(b.y1 - b.y0)}" rx="${f1((b.y1 - b.y0) / 2)}" fill="${t.paper}"/>` +
664
+ `<circle cx="${f1(b.x0 + (b.y1 - b.y0) / 2)}" cy="${f1((b.y0 + b.y1) / 2)}" r="${f1((b.y1 - b.y0) / 2 - 3)}" fill="${b.color}"/>` +
665
+ `<text x="${f1(b.x0 + (b.y1 - b.y0) / 2)}" y="${f1((b.y0 + b.y1) / 2 + b.fs * 0.36)}" font-family="${FONT}" font-weight="700" font-size="${f1(b.fs)}" fill="${t.paper}" text-anchor="middle">${esc(b.txt.split(" ")[0])}</text>` +
666
+ `<text x="${f1(b.x0 + (b.y1 - b.y0) + b.fs * 0.35)}" y="${f1((b.y0 + b.y1) / 2 + b.fs * 0.36)}" font-family="${FONT}" font-weight="600" font-size="${f1(b.fs)}" fill="${t.text === t.paper ? t.ink : t.text}">${esc(b.txt.split(" ")[1])}</text>`;
667
+ }).join("");
668
+ // ---------- título ----------
669
+ let textSvg = "";
670
+ for (const tx of scene.text || []) {
671
+ const role = tx.role || "title", fs = { title: H * 0.06, subtitle: H * 0.03 }[role] || H * 0.035;
672
+ const [vy, hx] = (tx.at || "top-left").split("-");
673
+ const m = W * 0.04;
674
+ const anchor = hx === "center" ? "middle" : hx === "right" ? "end" : "start";
675
+ const xx = hx === "center" ? W / 2 : hx === "right" ? W - m : m;
676
+ let yy = vy === "bottom" ? H - m * 0.7 : m + fs * 0.9;
677
+ if (role === "subtitle" && (scene.text || []).some((o) => (o.role || "title") === "title" && o.at === tx.at))
678
+ yy += H * 0.06 * 0.9 + fs * 0.8;
679
+ const color = tx.color ? (t[tx.color] || tx.color) : t.text;
680
+ const estW = tx.content.length * fs * 0.56, x0 = anchor === "start" ? xx : anchor === "end" ? xx - estW : xx - estW / 2;
681
+ let ratio = contrast(color, t.skyTop);
682
+ if (tx.box) {
683
+ const bf = t[tx.box] || tx.box;
684
+ ratio = contrast(color, bf);
685
+ textSvg += `<rect x="${f1(x0 - fs * 0.45)}" y="${f1(yy - fs * 1.05)}" width="${f1(estW + fs * 0.9)}" height="${f1(fs * 1.45)}" rx="${f1(fs * 0.35)}" fill="${bf}"/>`;
686
+ }
687
+ if (ratio < 4.5)
688
+ warnings.push(`texto "${tx.content}" com contraste ${ratio.toFixed(1)}:1 (mín. 4.5)`);
689
+ const tb = { x0, x1: x0 + estW, y0: yy - fs, y1: yy + fs * 0.25 };
690
+ for (const s of [...groundSprites, ...skySprites]) {
691
+ const sb = s.sky ? { x0: s.sx - s.w / 2, x1: s.sx + s.w / 2, y0: s.sy - s.h, y1: s.sy } : { x0: s.bx0, x1: s.bx1, y0: s.by0, y1: s.by1 };
692
+ const ov = overlap(tb, sb);
693
+ if (ov > 0.08 * estW * fs || ov > 0.15 * (sb.x1 - sb.x0) * (sb.y1 - sb.y0))
694
+ warnings.push(`texto "${tx.content}" cobre '${s.id}'`);
695
+ }
696
+ for (const l of labels)
697
+ if (overlap(tb, l) > 0)
698
+ warnings.push(`texto "${tx.content}" cobre o rótulo '${l.txt.split(" ")[1]}'`);
699
+ textSvg += `<text x="${f1(xx)}" y="${f1(yy)}" font-family="${FONT}" font-size="${f1(fs)}" font-weight="${role === "title" ? 700 : 500}" fill="${color}" text-anchor="${anchor}">${esc(tx.content)}</text>`;
700
+ }
701
+ // ---------- verificações ----------
702
+ for (const s of groundSprites) {
703
+ if (s.decor)
704
+ continue;
705
+ if (s.bx0 < -s.w * 0.05 || s.bx1 > W + s.w * 0.05 || s.by0 < -s.h * 0.05)
706
+ warnings.push(`'${s.id}' sai do quadro`);
707
+ }
708
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">\n<defs>${defs}</defs>\n${bg}\n` +
709
+ skySprites.map(drawSprite).join("\n") + "\n" + road + "\n" + drawOrdered() + "\n" + labelSvg + "\n" + textSvg + "\n</svg>";
710
+ const description = [
711
+ ...cps.map((cp, i) => `ponto ${i + 1} '${cp.id}' (${cp.label || "sem rótulo"}): x=${cp.at[0]}, z=${cp.at[1]}, tela=(${Math.round(X(...cp.at) / W * 100)}%, ${Math.round(Y(cp.at[1]) / H * 100)}%)${cp.zone ? ", zona " + cp.zone : ""}`),
712
+ ...groundSprites.filter((s) => !s.decor).map((s) => `${s.id} (${s.asset}): x=${s.x.toFixed(2)}, z=${s.z.toFixed(2)}, ${Math.round(s.h / H * 100)}% da altura`),
713
+ `${groundSprites.filter((s) => s.decor).length} elementos de cenário automáticos (zonas e scatter)`,
714
+ ].join("\n");
715
+ return { svg, warnings: [...new Set(warnings)], description };
716
+ }