procedural-bot-animations 0.1.0 → 0.2.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 (59) hide show
  1. package/README.md +167 -47
  2. package/dist/animation.d.ts +90 -0
  3. package/dist/animation.js +396 -0
  4. package/dist/brain.d.ts +194 -35
  5. package/dist/brain.js +578 -54
  6. package/dist/character.d.ts +123 -0
  7. package/dist/character.js +916 -0
  8. package/dist/characters/berry.d.ts +2 -0
  9. package/dist/characters/berry.js +38 -0
  10. package/dist/characters/flame.d.ts +2 -0
  11. package/dist/characters/flame.js +46 -0
  12. package/dist/delta.d.ts +16 -0
  13. package/dist/delta.js +146 -0
  14. package/dist/examples.d.ts +4 -0
  15. package/dist/examples.js +208 -0
  16. package/dist/focus.d.ts +46 -0
  17. package/dist/focus.js +284 -0
  18. package/dist/gaze.d.ts +41 -53
  19. package/dist/gaze.js +125 -82
  20. package/dist/index.d.ts +18 -11
  21. package/dist/index.js +18 -11
  22. package/dist/interactions.d.ts +30 -0
  23. package/dist/interactions.js +100 -0
  24. package/dist/library.d.ts +18 -0
  25. package/dist/library.js +14 -0
  26. package/dist/moods.d.ts +78 -46
  27. package/dist/moods.js +48 -73
  28. package/dist/motion.d.ts +93 -0
  29. package/dist/motion.js +167 -0
  30. package/dist/mount.d.ts +90 -0
  31. package/dist/mount.js +707 -0
  32. package/dist/parts.d.ts +36 -0
  33. package/dist/parts.js +131 -0
  34. package/dist/reactions.d.ts +184 -44
  35. package/dist/reactions.js +1851 -116
  36. package/dist/rig.d.ts +119 -0
  37. package/dist/rig.js +59 -0
  38. package/dist/scroll-traveler.js +1 -1
  39. package/dist/ticker.d.ts +10 -0
  40. package/dist/ticker.js +42 -0
  41. package/dist/transformations.d.ts +21 -0
  42. package/dist/transformations.js +306 -0
  43. package/package.json +7 -11
  44. package/dist/bind.d.ts +0 -27
  45. package/dist/bind.js +0 -42
  46. package/dist/blink.d.ts +0 -25
  47. package/dist/blink.js +0 -48
  48. package/dist/fake3d.d.ts +0 -20
  49. package/dist/fake3d.js +0 -24
  50. package/dist/noise.d.ts +0 -16
  51. package/dist/noise.js +0 -17
  52. package/dist/render.d.ts +0 -29
  53. package/dist/render.js +0 -97
  54. package/dist/rng.d.ts +0 -10
  55. package/dist/rng.js +0 -18
  56. package/dist/spring.d.ts +0 -21
  57. package/dist/spring.js +0 -33
  58. package/dist/types.d.ts +0 -63
  59. package/dist/types.js +0 -46
@@ -0,0 +1,916 @@
1
+ /*
2
+ * Character definitions: plain JSON that describes a silhouette, two eyes and
3
+ * (optionally) a few moving parts, compiled into the engine's `Rig`.
4
+ *
5
+ * The base of the format (`version`, `id`, `name`, `body`, `eyes`) is the
6
+ * Open Bot Avatar definition, accepted unchanged. The optional `rig` key is
7
+ * this engine's extension.
8
+ *
9
+ * The path grammar, the arc handling and the point-in-outline test are adapted
10
+ * from open-bot-avatar (MIT, Copyright (c) Dominik Scholz,
11
+ * https://github.com/dominikscholz/open-bot-avatar). No code is imported.
12
+ */
13
+ import { RIG_BERRY } from "./characters/berry.js";
14
+ /** Scale from the 0..100 box to the engine's drawing space (Flame was made with the same 9.5). */
15
+ export const CHARACTER_SCALE = 9.5;
16
+ /** Where the character stands in engine space: ground line and horizontal centre of every rig. */
17
+ const GROUND = { x: 627, y: 960 };
18
+ /* ---------- limits ---------- */
19
+ export const CHARACTER_LIMITS = {
20
+ pathChars: 6000,
21
+ pathSegments: 400,
22
+ pathSubpaths: 16,
23
+ coordMin: -20,
24
+ coordMax: 120,
25
+ /** Hard limits for the body bounding box (error). */
26
+ bodyHardMin: 6,
27
+ bodyHardMax: 94,
28
+ /** Soft limits (warning). */
29
+ bodySoftMin: 8,
30
+ bodySoftMax: 92,
31
+ bodyMinSize: 30,
32
+ eyeScale: [0.4, 3],
33
+ eyeSpacing: [4, 60],
34
+ eyeMargin: 0.8,
35
+ nameMax: 60,
36
+ pivotSlack: 3,
37
+ minPartLength: 4,
38
+ };
39
+ /**
40
+ * Classic eye at scale 1, in the 0..100 box. The height is Open Bot Avatar's (11); the width is NOT:
41
+ * Open Bot Avatar draws a 4-wide pill, which is too thin for the eyelid and happy-arc expressions to read.
42
+ * This engine deliberately draws Berry's ratio instead, width = height / 2 (5.5). Open Bot Avatar's own
43
+ * 4-wide pill is kept (EYE_W_OBA) only to decide whether a definition that was valid there stays accepted.
44
+ */
45
+ const EYE_H = 11;
46
+ const EYE_W = EYE_H / 2;
47
+ const EYE_W_OBA = 4;
48
+ /** Eyes must not overlap: spacing >= EYE_W * scale * (1 + EYE_GAP), i.e. 6.05 * scale (a 10 % gap). */
49
+ const EYE_GAP = 0.1;
50
+ /** Classic eye height below this share of the body height is flagged as small; 26 % is the suggested target. */
51
+ const EYE_SMALL_RATIO = 0.18;
52
+ const EYE_TARGET_RATIO = 0.26;
53
+ /* ======================================================================== */
54
+ /* Path handling */
55
+ /* ======================================================================== */
56
+ export class PathError extends Error {
57
+ }
58
+ const ARG_COUNT = { M: 2, L: 2, H: 1, V: 1, C: 6, S: 4, Q: 4, T: 2, A: 7, Z: 0 };
59
+ const NUMBER_RE = /[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y;
60
+ function skipSep(s) {
61
+ while (s.i < s.d.length && /[\s,]/.test(s.d[s.i]))
62
+ s.i++;
63
+ }
64
+ function readNumber(s) {
65
+ skipSep(s);
66
+ NUMBER_RE.lastIndex = s.i;
67
+ const m = NUMBER_RE.exec(s.d);
68
+ if (!m)
69
+ return null;
70
+ s.i = NUMBER_RE.lastIndex;
71
+ const v = Number(m[0]);
72
+ return Number.isFinite(v) ? v : null;
73
+ }
74
+ /** Arc flags may be written glued together ("a1 1 0 01 5 5"): read exactly one digit. */
75
+ function readFlag(s) {
76
+ skipSep(s);
77
+ const ch = s.d[s.i];
78
+ if (ch === "0" || ch === "1") {
79
+ s.i++;
80
+ return Number(ch);
81
+ }
82
+ return null;
83
+ }
84
+ const cubicFromQuad = (x0, y0, qx, qy, x, y) => [
85
+ x0 + (2 / 3) * (qx - x0),
86
+ y0 + (2 / 3) * (qy - y0),
87
+ x + (2 / 3) * (qx - x),
88
+ y + (2 / 3) * (qy - y),
89
+ x,
90
+ y,
91
+ ];
92
+ /**
93
+ * SVG endpoint arc to cubic segments (SVG 1.1 implementation notes F.6.5,
94
+ * then the standard `4/3·tan(δ/4)` handle length), at most 90° per segment.
95
+ */
96
+ function arcToCubics(x0, y0, rxIn, ryIn, rotDeg, large, sweep, x, y) {
97
+ let rx = Math.abs(rxIn);
98
+ let ry = Math.abs(ryIn);
99
+ if (rx === 0 || ry === 0)
100
+ return [[x0, y0, x, y, x, y]]; // straight line, as a cubic
101
+ const phi = (rotDeg * Math.PI) / 180;
102
+ const cos = Math.cos(phi);
103
+ const sin = Math.sin(phi);
104
+ const dx = (x0 - x) / 2;
105
+ const dy = (y0 - y) / 2;
106
+ const x1p = cos * dx + sin * dy;
107
+ const y1p = -sin * dx + cos * dy;
108
+ const lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
109
+ if (lambda > 1) {
110
+ const k = Math.sqrt(lambda);
111
+ rx *= k;
112
+ ry *= k;
113
+ }
114
+ const num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
115
+ const den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
116
+ let coef = Math.sqrt(Math.max(0, num / den));
117
+ if (large === sweep)
118
+ coef = -coef;
119
+ const cxp = (coef * rx * y1p) / ry;
120
+ const cyp = (-coef * ry * x1p) / rx;
121
+ const cx = cos * cxp - sin * cyp + (x0 + x) / 2;
122
+ const cy = sin * cxp + cos * cyp + (y0 + y) / 2;
123
+ const ang = (ux, uy, vx, vy) => Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);
124
+ const t1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry);
125
+ let dt = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry);
126
+ if (!sweep && dt > 0)
127
+ dt -= 2 * Math.PI;
128
+ if (sweep && dt < 0)
129
+ dt += 2 * Math.PI;
130
+ const n = Math.max(1, Math.ceil(Math.abs(dt) / (Math.PI / 2) - 1e-9));
131
+ const delta = dt / n;
132
+ const k = (4 / 3) * Math.tan(delta / 4);
133
+ const point = (t) => {
134
+ const ex = rx * Math.cos(t);
135
+ const ey = ry * Math.sin(t);
136
+ return [cos * ex - sin * ey + cx, sin * ex + cos * ey + cy];
137
+ };
138
+ const deriv = (t) => {
139
+ const ex = -rx * Math.sin(t);
140
+ const ey = ry * Math.cos(t);
141
+ return [cos * ex - sin * ey, sin * ex + cos * ey];
142
+ };
143
+ const out = [];
144
+ for (let s = 0; s < n; s++) {
145
+ const a = t1 + delta * s;
146
+ const b = a + delta;
147
+ const [pax, pay] = point(a);
148
+ const [pbx, pby] = point(b);
149
+ const [dax, day] = deriv(a);
150
+ const [dbx, dby] = deriv(b);
151
+ // The last segment ends exactly on the requested end point.
152
+ const ex = s === n - 1 ? x : pbx;
153
+ const ey = s === n - 1 ? y : pby;
154
+ out.push([pax + k * dax, pay + k * day, ex - k * dbx, ey - k * dby, ex, ey]);
155
+ }
156
+ return out;
157
+ }
158
+ /**
159
+ * Parses the full SVG path grammar (M L H V C S Q T A Z, absolute and
160
+ * relative, implicit repeats, several subpaths) into ABSOLUTE commands using
161
+ * only M, L, C and Z: the format `parsePath` / `bendPath` / `mixPath` read.
162
+ * Q, T and S become exact cubics; arcs become cubic segments of at most 90°.
163
+ * `segments` is the number of commands in the source (for the limits).
164
+ * With `closeOpen`, unclosed subpaths get a `Z` and `closed` lists their (1-based) numbers.
165
+ * Throws `PathError` on malformed input.
166
+ */
167
+ export function normalizeWithStats(d, closeOpen = false) {
168
+ if (typeof d !== "string" || d.trim() === "")
169
+ throw new PathError("path is empty");
170
+ const bad = d.match(/[^MmLlHhVvCcSsQqTtAaZz0-9.,eE+\-\s]/);
171
+ if (bad)
172
+ throw new PathError(`unsupported character ${JSON.stringify(bad[0])} (allowed commands: M L H V C S Q T A Z)`);
173
+ const s = { d, i: 0 };
174
+ const out = [];
175
+ let segments = 0;
176
+ let cx = 0;
177
+ let cy = 0;
178
+ let sx = 0;
179
+ let sy = 0;
180
+ let prevC = null;
181
+ let prevQ = null;
182
+ let cmd = "";
183
+ let open = false; // a subpath is being drawn (M seen, no Z yet)
184
+ let first = true;
185
+ const closed = []; // 1-based numbers of the subpaths that were closed automatically
186
+ const autoClose = () => {
187
+ out.push({ c: "Z", pts: [] });
188
+ closed.push(out.filter((c) => c.c === "M").length);
189
+ open = false;
190
+ };
191
+ for (;;) {
192
+ skipSep(s);
193
+ if (s.i >= d.length)
194
+ break;
195
+ const ch = d[s.i];
196
+ if (/[A-Za-z]/.test(ch)) {
197
+ cmd = ch;
198
+ s.i++;
199
+ if (cmd === "Z" || cmd === "z") {
200
+ if (!open)
201
+ throw new PathError("Z without an open subpath");
202
+ out.push({ c: "Z", pts: [] });
203
+ segments++;
204
+ cx = sx;
205
+ cy = sy;
206
+ prevC = prevQ = null;
207
+ open = false;
208
+ continue;
209
+ }
210
+ }
211
+ else if (!cmd)
212
+ throw new PathError("path must start with M");
213
+ else if (cmd === "Z" || cmd === "z")
214
+ throw new PathError("numbers after Z");
215
+ else if (!/[0-9.+-]/.test(ch))
216
+ throw new PathError(`cannot parse path near ${JSON.stringify(d.slice(s.i, s.i + 12))}`);
217
+ const up = cmd.toUpperCase();
218
+ const rel = cmd !== up;
219
+ if (first && up !== "M")
220
+ throw new PathError("path must start with M");
221
+ first = false;
222
+ const n = ARG_COUNT[up];
223
+ if (n === undefined)
224
+ throw new PathError(`unsupported command ${cmd}`);
225
+ const args = [];
226
+ for (let k = 0; k < n; k++) {
227
+ const v = up === "A" && (k === 3 || k === 4) ? readFlag(s) : readNumber(s);
228
+ if (v === null)
229
+ throw new PathError(`command ${cmd} expects ${n} numbers`);
230
+ args.push(v);
231
+ }
232
+ segments++;
233
+ const ox = rel ? cx : 0;
234
+ const oy = rel ? cy : 0;
235
+ // A drawing command after Z (without a new M) starts a subpath at the previous start point.
236
+ if (!open && up !== "M") {
237
+ out.push({ c: "M", pts: [cx, cy] });
238
+ sx = cx;
239
+ sy = cy;
240
+ open = true;
241
+ }
242
+ let nextC = null;
243
+ let nextQ = null;
244
+ switch (up) {
245
+ case "M":
246
+ if (open && closeOpen)
247
+ autoClose();
248
+ cx = args[0] + ox;
249
+ cy = args[1] + oy;
250
+ sx = cx;
251
+ sy = cy;
252
+ out.push({ c: "M", pts: [cx, cy] });
253
+ open = true;
254
+ cmd = rel ? "l" : "L"; // extra pairs are implicit lineto
255
+ break;
256
+ case "L":
257
+ cx = args[0] + ox;
258
+ cy = args[1] + oy;
259
+ out.push({ c: "L", pts: [cx, cy] });
260
+ break;
261
+ case "H":
262
+ cx = args[0] + ox;
263
+ out.push({ c: "L", pts: [cx, cy] });
264
+ break;
265
+ case "V":
266
+ cy = args[0] + oy;
267
+ out.push({ c: "L", pts: [cx, cy] });
268
+ break;
269
+ case "C": {
270
+ const p = [args[0] + ox, args[1] + oy, args[2] + ox, args[3] + oy, args[4] + ox, args[5] + oy];
271
+ out.push({ c: "C", pts: p });
272
+ nextC = [p[2], p[3]];
273
+ cx = p[4];
274
+ cy = p[5];
275
+ break;
276
+ }
277
+ case "S": {
278
+ const x1 = prevC ? 2 * cx - prevC[0] : cx;
279
+ const y1 = prevC ? 2 * cy - prevC[1] : cy;
280
+ const p = [x1, y1, args[0] + ox, args[1] + oy, args[2] + ox, args[3] + oy];
281
+ out.push({ c: "C", pts: p });
282
+ nextC = [p[2], p[3]];
283
+ cx = p[4];
284
+ cy = p[5];
285
+ break;
286
+ }
287
+ case "Q": {
288
+ const qx = args[0] + ox;
289
+ const qy = args[1] + oy;
290
+ const x = args[2] + ox;
291
+ const y = args[3] + oy;
292
+ out.push({ c: "C", pts: cubicFromQuad(cx, cy, qx, qy, x, y) });
293
+ nextQ = [qx, qy];
294
+ cx = x;
295
+ cy = y;
296
+ break;
297
+ }
298
+ case "T": {
299
+ const qx = prevQ ? 2 * cx - prevQ[0] : cx;
300
+ const qy = prevQ ? 2 * cy - prevQ[1] : cy;
301
+ const x = args[0] + ox;
302
+ const y = args[1] + oy;
303
+ out.push({ c: "C", pts: cubicFromQuad(cx, cy, qx, qy, x, y) });
304
+ nextQ = [qx, qy];
305
+ cx = x;
306
+ cy = y;
307
+ break;
308
+ }
309
+ case "A": {
310
+ const [rx, ry, rot, large, sweep] = args;
311
+ const x = args[5] + ox;
312
+ const y = args[6] + oy;
313
+ if (rx < 0 || ry < 0)
314
+ throw new PathError("arc radii must be non-negative");
315
+ if (x !== cx || y !== cy) {
316
+ if (rx === 0 || ry === 0)
317
+ out.push({ c: "L", pts: [x, y] });
318
+ else
319
+ for (const p of arcToCubics(cx, cy, rx, ry, rot, large, sweep, x, y))
320
+ out.push({ c: "C", pts: p });
321
+ }
322
+ cx = x;
323
+ cy = y;
324
+ break;
325
+ }
326
+ }
327
+ prevC = nextC;
328
+ prevQ = nextQ;
329
+ if (segments > CHARACTER_LIMITS.pathSegments * 4)
330
+ throw new PathError("path is far too long");
331
+ }
332
+ if (out.length === 0)
333
+ throw new PathError("path is empty");
334
+ if (open && closeOpen)
335
+ autoClose();
336
+ return { cmds: out, segments, closed };
337
+ }
338
+ /** Absolute M/L/C/Z commands for any SVG path (see `normalizeWithStats`). */
339
+ export function normalizePath(d, closeOpen = false) {
340
+ return normalizeWithStats(d, closeOpen).cmds;
341
+ }
342
+ const r2 = (v) => {
343
+ const r = Math.round(v * 100) / 100;
344
+ return Object.is(r, -0) ? 0 : r;
345
+ };
346
+ /** Writes commands back as `M x,y C x,y x,y x,y L x,y Z` (no exponents: `parsePath` cannot read them). */
347
+ export function serializePath(cmds) {
348
+ return cmds
349
+ .map(({ c, pts }) => {
350
+ const pairs = [];
351
+ for (let i = 0; i < pts.length; i += 2)
352
+ pairs.push(`${r2(pts[i]).toFixed(2).replace(/\.?0+$/, "")},${r2(pts[i + 1]).toFixed(2).replace(/\.?0+$/, "")}`);
353
+ return pairs.length ? `${c}${pairs.join(" ")}` : c;
354
+ })
355
+ .join(" ");
356
+ }
357
+ /** Flattens into one polygon per subpath (cubics sampled within 0.02 units of the curve). */
358
+ export function flattenPath(cmds) {
359
+ const polys = [];
360
+ let cur = [];
361
+ let px = 0;
362
+ let py = 0;
363
+ for (const { c, pts } of cmds) {
364
+ if (c === "M") {
365
+ if (cur.length)
366
+ polys.push(cur);
367
+ cur = [[pts[0], pts[1]]];
368
+ px = pts[0];
369
+ py = pts[1];
370
+ }
371
+ else if (c === "L") {
372
+ cur.push([pts[0], pts[1]]);
373
+ px = pts[0];
374
+ py = pts[1];
375
+ }
376
+ else if (c === "C") {
377
+ const [x1, y1, x2, y2, x, y] = pts;
378
+ const m = Math.max(Math.hypot(px - 2 * x1 + x2, py - 2 * y1 + y2), Math.hypot(x1 - 2 * x2 + x, y1 - 2 * y2 + y));
379
+ const n = Math.min(128, Math.max(2, Math.ceil(Math.sqrt((0.75 * m) / 0.02))));
380
+ for (let k = 1; k <= n; k++) {
381
+ const t = k / n;
382
+ const u = 1 - t;
383
+ cur.push([
384
+ u * u * u * px + 3 * u * u * t * x1 + 3 * u * t * t * x2 + t * t * t * x,
385
+ u * u * u * py + 3 * u * u * t * y1 + 3 * u * t * t * y2 + t * t * t * y,
386
+ ]);
387
+ }
388
+ px = x;
389
+ py = y;
390
+ }
391
+ else if (c === "Z") {
392
+ if (cur.length) {
393
+ polys.push(cur);
394
+ px = cur[0][0];
395
+ py = cur[0][1];
396
+ }
397
+ cur = [];
398
+ }
399
+ }
400
+ if (cur.length)
401
+ polys.push(cur);
402
+ return polys.filter((p) => p.length >= 3);
403
+ }
404
+ export function polyBounds(polys) {
405
+ const b = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
406
+ for (const p of polys)
407
+ for (const [x, y] of p) {
408
+ if (x < b.minX)
409
+ b.minX = x;
410
+ if (y < b.minY)
411
+ b.minY = y;
412
+ if (x > b.maxX)
413
+ b.maxX = x;
414
+ if (y > b.maxY)
415
+ b.maxY = y;
416
+ }
417
+ return b;
418
+ }
419
+ /** Non-zero winding test (the SVG default fill rule). */
420
+ function inside(polys, x, y) {
421
+ let w = 0;
422
+ for (const poly of polys) {
423
+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
424
+ const [xi, yi] = poly[i];
425
+ const [xj, yj] = poly[j];
426
+ if (yj <= y) {
427
+ if (yi > y && (xi - xj) * (y - yj) - (x - xj) * (yi - yj) > 0)
428
+ w++;
429
+ }
430
+ else if (yi <= y && (xi - xj) * (y - yj) - (x - xj) * (yi - yj) < 0)
431
+ w--;
432
+ }
433
+ }
434
+ return w !== 0;
435
+ }
436
+ /** Points on the outline of a pill (`w × h`, centred on `cx, cy`) grown by `margin`, plus its centre. */
437
+ function pillRing(cx, cy, w, h, margin) {
438
+ const hw = w / 2 + margin;
439
+ const hh = h / 2 + margin;
440
+ const straight = Math.max(0, hh - hw);
441
+ const pts = [[cx, cy]];
442
+ for (let k = 0; k < 32; k++) {
443
+ const a = (k / 32) * Math.PI * 2;
444
+ pts.push([cx + Math.cos(a) * hw, cy + Math.sin(a) * hw + Math.sign(Math.sin(a)) * straight]);
445
+ }
446
+ for (const f of [-1, -0.5, 0, 0.5, 1])
447
+ pts.push([cx - hw, cy + f * straight], [cx + hw, cy + f * straight]);
448
+ return pts;
449
+ }
450
+ /* ======================================================================== */
451
+ /* Validation */
452
+ /* ======================================================================== */
453
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
454
+ const isNum = (v) => typeof v === "number" && Number.isFinite(v);
455
+ const r1 = (n) => Math.round(n * 10) / 10;
456
+ const TOP_KEYS = ["version", "id", "name", "body", "eyes", "rig"];
457
+ const BODY_KEYS = ["path"];
458
+ const EYE_KEYS = ["x", "y", "spacing", "scale"];
459
+ const RIG_KEYS = ["parts", "eyeStyles", "idle", "flicker", "color"];
460
+ const PART_KEYS = ["role", "path", "pivot", "tip"];
461
+ const EYE_STYLE_NAMES = ["classic", "pumpy", "big"];
462
+ const EYE_SHAPE_KEYS = ["w", "h", "tilt", "dx", "dy"];
463
+ const ID_RE = /^[a-z0-9][a-z0-9-]{0,39}$/;
464
+ const COLOR_RE = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
465
+ /** Allowed ranges of the `rig.eyeStyles` overrides (0..100 units; tilt in degrees). */
466
+ const EYE_SHAPE_RANGE = {
467
+ w: [0.5, 40],
468
+ h: [0.5, 60],
469
+ tilt: [-45, 45],
470
+ dx: [-20, 20],
471
+ dy: [-20, 20],
472
+ };
473
+ /** Parses and checks a path (limits, coordinate range, unclosed subpaths get closed with a warning). Pushes errors, returns null on failure. */
474
+ function checkPath(label, d, errors, warnings, limits) {
475
+ if (typeof d !== "string") {
476
+ errors.push(`${label}: must be a string with an SVG path`);
477
+ return null;
478
+ }
479
+ if (d.length > CHARACTER_LIMITS.pathChars) {
480
+ errors.push(`${label}: longer than ${CHARACTER_LIMITS.pathChars} characters`);
481
+ return null;
482
+ }
483
+ let parsed;
484
+ try {
485
+ parsed = normalizeWithStats(d, true);
486
+ }
487
+ catch (err) {
488
+ if (err instanceof PathError) {
489
+ errors.push(`${label}: ${err.message}`);
490
+ return null;
491
+ }
492
+ throw err;
493
+ }
494
+ const before = errors.length;
495
+ if (parsed.segments > CHARACTER_LIMITS.pathSegments)
496
+ errors.push(`${label}: ${parsed.segments} segments, the limit is ${CHARACTER_LIMITS.pathSegments}`);
497
+ const subpaths = parsed.cmds.filter((c) => c.c === "M").length;
498
+ if (subpaths > limits.subpaths)
499
+ errors.push(`${label}: ${subpaths} subpaths, the limit is ${limits.subpaths}`);
500
+ // Open Bot Avatar closes unclosed subpaths implicitly; so do we (the normaliser already did), with a warning.
501
+ for (const n of parsed.closed)
502
+ warnings.push(`${label}: subpath ${n} is not closed; closed automatically`);
503
+ const bad = parsed.cmds.some((c) => c.pts.some((v) => v < CHARACTER_LIMITS.coordMin || v > CHARACTER_LIMITS.coordMax));
504
+ if (bad)
505
+ errors.push(`${label}: coordinates must stay within ${CHARACTER_LIMITS.coordMin}..${CHARACTER_LIMITS.coordMax}`);
506
+ if (errors.length > before)
507
+ return null;
508
+ const polys = flattenPath(parsed.cmds);
509
+ if (!polys.length) {
510
+ errors.push(`${label}: the path draws no area`);
511
+ return null;
512
+ }
513
+ return { cmds: parsed.cmds, polys, bounds: polyBounds(polys) };
514
+ }
515
+ function warnUnknown(obj, allowed, where, warnings) {
516
+ for (const k of Object.keys(obj))
517
+ if (!allowed.includes(k))
518
+ warnings.push(`${where ? `${where}.` : ""}${k}: unknown key, ignored`);
519
+ }
520
+ function readPoint(v, label, errors) {
521
+ if (!Array.isArray(v) || v.length !== 2 || !isNum(v[0]) || !isNum(v[1])) {
522
+ errors.push(`${label}: must be [x, y], two finite numbers`);
523
+ return null;
524
+ }
525
+ if (v[0] < CHARACTER_LIMITS.coordMin || v[0] > CHARACTER_LIMITS.coordMax || v[1] < CHARACTER_LIMITS.coordMin || v[1] > CHARACTER_LIMITS.coordMax) {
526
+ errors.push(`${label}: coordinates must stay within ${CHARACTER_LIMITS.coordMin}..${CHARACTER_LIMITS.coordMax}`);
527
+ return null;
528
+ }
529
+ return [v[0], v[1]];
530
+ }
531
+ /** Checks a definition (any JSON value). Collects every problem; warnings never block. */
532
+ export function validateCharacter(input) {
533
+ const errors = [];
534
+ const warnings = [];
535
+ if (!isRecord(input))
536
+ return { ok: false, errors: ["(root): must be a JSON object"] };
537
+ warnUnknown(input, TOP_KEYS, "", warnings);
538
+ if (input.version !== 1)
539
+ errors.push("version: must be the number 1");
540
+ const id = input.id;
541
+ if (typeof id !== "string" || !ID_RE.test(id))
542
+ errors.push("id: must be a lowercase slug of 1 to 40 characters [a-z0-9-], starting with a letter or digit");
543
+ let name = "";
544
+ if (typeof input.name !== "string")
545
+ errors.push("name: must be a string");
546
+ else {
547
+ name = input.name.trim();
548
+ // eslint-disable-next-line no-control-regex
549
+ if (name.length < 1 || name.length > CHARACTER_LIMITS.nameMax || /[\u0000-\u001f<>]/.test(name))
550
+ errors.push(`name: must be 1 to ${CHARACTER_LIMITS.nameMax} printable characters, without < or >`);
551
+ }
552
+ /* body */
553
+ let body = null;
554
+ let bodyPath = "";
555
+ if (!isRecord(input.body))
556
+ errors.push('body: must be an object { "path": "..." }');
557
+ else {
558
+ warnUnknown(input.body, BODY_KEYS, "body", warnings);
559
+ body = checkPath("body.path", input.body.path, errors, warnings, { subpaths: CHARACTER_LIMITS.pathSubpaths });
560
+ if (typeof input.body.path === "string")
561
+ bodyPath = input.body.path;
562
+ }
563
+ if (body) {
564
+ const b = body.bounds;
565
+ const w = b.maxX - b.minX;
566
+ const h = b.maxY - b.minY;
567
+ const edges = [];
568
+ if (b.minX < CHARACTER_LIMITS.bodyHardMin)
569
+ edges.push(`left edge x=${r1(b.minX)}`);
570
+ if (b.minY < CHARACTER_LIMITS.bodyHardMin)
571
+ edges.push(`top edge y=${r1(b.minY)}`);
572
+ if (b.maxX > CHARACTER_LIMITS.bodyHardMax)
573
+ edges.push(`right edge x=${r1(b.maxX)}`);
574
+ if (b.maxY > CHARACTER_LIMITS.bodyHardMax)
575
+ edges.push(`bottom edge y=${r1(b.maxY)}`);
576
+ if (edges.length)
577
+ errors.push(`body.path: leaves the safe area ${CHARACTER_LIMITS.bodyHardMin}..${CHARACTER_LIMITS.bodyHardMax} (${edges.join(", ")})`);
578
+ else if (b.minX < CHARACTER_LIMITS.bodySoftMin ||
579
+ b.minY < CHARACTER_LIMITS.bodySoftMin ||
580
+ b.maxX > CHARACTER_LIMITS.bodySoftMax ||
581
+ b.maxY > CHARACTER_LIMITS.bodySoftMax)
582
+ warnings.push(`body.path: reaches outside ${CHARACTER_LIMITS.bodySoftMin}..${CHARACTER_LIMITS.bodySoftMax}; keeping the outline inside leaves room for the animations`);
583
+ if (w < CHARACTER_LIMITS.bodyMinSize || h < CHARACTER_LIMITS.bodyMinSize)
584
+ errors.push(`body.path: the outline is ${r1(w)}×${r1(h)}; it must be at least ${CHARACTER_LIMITS.bodyMinSize}×${CHARACTER_LIMITS.bodyMinSize}`);
585
+ }
586
+ /* eyes */
587
+ let eyes = null;
588
+ if (!isRecord(input.eyes))
589
+ errors.push("eyes: must be an object { x, y, spacing, scale }");
590
+ else {
591
+ const e = input.eyes;
592
+ warnUnknown(e, EYE_KEYS, "eyes", warnings);
593
+ let ok = true;
594
+ const need = (k, lo, hi) => {
595
+ const v = e[k];
596
+ if (!isNum(v) || v < lo || v > hi) {
597
+ errors.push(`eyes.${k}: must be a number between ${lo} and ${hi}`);
598
+ ok = false;
599
+ }
600
+ };
601
+ need("x", 0, 100);
602
+ need("y", 0, 100);
603
+ need("spacing", CHARACTER_LIMITS.eyeSpacing[0], CHARACTER_LIMITS.eyeSpacing[1]);
604
+ need("scale", CHARACTER_LIMITS.eyeScale[0], CHARACTER_LIMITS.eyeScale[1]);
605
+ if (ok) {
606
+ eyes = { x: e.x, y: e.y, spacing: e.spacing, scale: e.scale };
607
+ const minSpacing = EYE_W * eyes.scale * (1 + EYE_GAP);
608
+ if (eyes.spacing < minSpacing) {
609
+ const hint = `makes the eyes overlap at scale ${eyes.scale}; use at least ${r1(minSpacing)} or a smaller eyes.scale`;
610
+ // Open Bot Avatar's 4-wide pill needed only 5 * scale: never reject what was valid there.
611
+ if (eyes.spacing >= EYE_W_OBA * eyes.scale * 1.25)
612
+ warnings.push(`eyes.spacing: ${eyes.spacing} ${hint}`);
613
+ else {
614
+ errors.push(`eyes.spacing: ${eyes.spacing} ${hint}`);
615
+ eyes = null;
616
+ }
617
+ }
618
+ }
619
+ }
620
+ if (body && eyes) {
621
+ const w = EYE_W * eyes.scale;
622
+ const h = EYE_H * eyes.scale;
623
+ for (const [label, cx] of [
624
+ ["left", eyes.x - eyes.spacing / 2],
625
+ ["right", eyes.x + eyes.spacing / 2],
626
+ ]) {
627
+ const miss = pillRing(cx, eyes.y, w, h, CHARACTER_LIMITS.eyeMargin).find(([x, y]) => !inside(body.polys, x, y));
628
+ if (miss) {
629
+ const msg = `eyes: the ${label} eye (${r1(w)}×${r1(h)} at ${r1(cx)}, ${r1(eyes.y)}) pokes outside the body near (${r1(miss[0])}, ${r1(miss[1])}); move eyes.x / eyes.y toward the middle of the body or reduce eyes.spacing / eyes.scale`;
630
+ const thin = pillRing(cx, eyes.y, EYE_W_OBA * eyes.scale, h, CHARACTER_LIMITS.eyeMargin).find(([x, y]) => !inside(body.polys, x, y));
631
+ // Valid for Open Bot Avatar's thinner pill: keep it accepted, only warn.
632
+ if (thin)
633
+ errors.push(msg);
634
+ else
635
+ warnings.push(msg.replace("pokes outside the body", "is close to the body outline (wider pill than Open Bot Avatar's)"));
636
+ }
637
+ }
638
+ const bodyH = body.bounds.maxY - body.bounds.minY;
639
+ if (bodyH > 0 && h / bodyH < EYE_SMALL_RATIO) {
640
+ const want = (EYE_TARGET_RATIO * bodyH) / EYE_H;
641
+ warnings.push(`eyes.scale: eyes are small for this body (${Math.round((100 * h) / bodyH)} % of body height); expressions read best at 22–30 % — try scale ≈ ${Math.round(want * 100) / 100}`);
642
+ }
643
+ }
644
+ /* rig extension */
645
+ let rigOut;
646
+ if (input.rig !== undefined) {
647
+ if (!isRecord(input.rig))
648
+ errors.push("rig: must be an object");
649
+ else {
650
+ const rig = input.rig;
651
+ warnUnknown(rig, RIG_KEYS, "rig", warnings);
652
+ rigOut = {};
653
+ if (rig.parts !== undefined) {
654
+ if (!Array.isArray(rig.parts))
655
+ errors.push("rig.parts: must be an array");
656
+ else {
657
+ if (rig.parts.length > 3)
658
+ errors.push("rig.parts: at most 3 parts (one per role C, L, R)");
659
+ const seen = new Set();
660
+ const parts = [];
661
+ rig.parts.slice(0, 3).forEach((p, i) => {
662
+ const at = `rig.parts[${i}]`;
663
+ if (!isRecord(p)) {
664
+ errors.push(`${at}: must be an object { role, path, pivot, tip }`);
665
+ return;
666
+ }
667
+ warnUnknown(p, PART_KEYS, at, warnings);
668
+ let good = true;
669
+ const role = p.role;
670
+ if (role !== "C" && role !== "L" && role !== "R") {
671
+ errors.push(`${at}.role: must be "C", "L" or "R"`);
672
+ good = false;
673
+ }
674
+ else if (seen.has(role)) {
675
+ errors.push(`${at}.role: "${role}" is used twice; each role can appear once`);
676
+ good = false;
677
+ }
678
+ else
679
+ seen.add(role);
680
+ const path = checkPath(`${at}.path`, p.path, errors, warnings, { subpaths: 1 });
681
+ if (!path)
682
+ good = false;
683
+ const pivot = readPoint(p.pivot, `${at}.pivot`, errors);
684
+ const tip = readPoint(p.tip, `${at}.tip`, errors);
685
+ if (!pivot || !tip)
686
+ good = false;
687
+ if (pivot && tip) {
688
+ if (Math.hypot(tip[0] - pivot[0], tip[1] - pivot[1]) < CHARACTER_LIMITS.minPartLength) {
689
+ errors.push(`${at}.tip: must be at least ${CHARACTER_LIMITS.minPartLength} units away from the pivot`);
690
+ good = false;
691
+ }
692
+ if (body) {
693
+ const b = body.bounds;
694
+ const s = CHARACTER_LIMITS.pivotSlack;
695
+ if (pivot[0] < b.minX - s || pivot[0] > b.maxX + s || pivot[1] < b.minY - s || pivot[1] > b.maxY + s) {
696
+ errors.push(`${at}.pivot: (${r1(pivot[0])}, ${r1(pivot[1])}) must be inside the body's bounding box (or within ${s} units of it); the base of a part belongs inside the body`);
697
+ good = false;
698
+ }
699
+ }
700
+ }
701
+ if (good)
702
+ parts.push({ role: role, path: p.path, pivot: pivot, tip: tip });
703
+ });
704
+ if (parts.length)
705
+ rigOut.parts = parts;
706
+ }
707
+ }
708
+ if (rig.eyeStyles !== undefined) {
709
+ if (!isRecord(rig.eyeStyles))
710
+ errors.push("rig.eyeStyles: must be an object keyed by classic, pumpy, big");
711
+ else {
712
+ warnUnknown(rig.eyeStyles, EYE_STYLE_NAMES, "rig.eyeStyles", warnings);
713
+ const styles = {};
714
+ for (const name2 of EYE_STYLE_NAMES) {
715
+ const s = rig.eyeStyles[name2];
716
+ if (s === undefined)
717
+ continue;
718
+ const at = `rig.eyeStyles.${name2}`;
719
+ if (!isRecord(s)) {
720
+ errors.push(`${at}: must be an object with any of w, h, tilt, dx, dy`);
721
+ continue;
722
+ }
723
+ warnUnknown(s, EYE_SHAPE_KEYS, at, warnings);
724
+ const shape = {};
725
+ for (const k of EYE_SHAPE_KEYS) {
726
+ if (s[k] === undefined)
727
+ continue;
728
+ const [lo, hi] = EYE_SHAPE_RANGE[k];
729
+ if (!isNum(s[k]) || s[k] < lo || s[k] > hi)
730
+ errors.push(`${at}.${k}: must be a number between ${lo} and ${hi}`);
731
+ else
732
+ shape[k] = s[k];
733
+ }
734
+ styles[name2] = shape;
735
+ }
736
+ if (Object.keys(styles).length)
737
+ rigOut.eyeStyles = styles;
738
+ }
739
+ }
740
+ if (rig.idle !== undefined) {
741
+ if (!isRecord(rig.idle))
742
+ errors.push("rig.idle: must be an object { amp, freq }");
743
+ else {
744
+ warnUnknown(rig.idle, ["amp", "freq"], "rig.idle", warnings);
745
+ const idle = {};
746
+ for (const k of ["amp", "freq"]) {
747
+ if (rig.idle[k] === undefined)
748
+ continue;
749
+ if (!isNum(rig.idle[k]) || rig.idle[k] < 0 || rig.idle[k] > 6)
750
+ errors.push(`rig.idle.${k}: must be a number between 0 and 6`);
751
+ else
752
+ idle[k] = rig.idle[k];
753
+ }
754
+ rigOut.idle = idle;
755
+ }
756
+ }
757
+ if (rig.flicker !== undefined) {
758
+ if (!isNum(rig.flicker) || rig.flicker < 0 || rig.flicker > 1)
759
+ errors.push("rig.flicker: must be a number between 0 and 1");
760
+ else
761
+ rigOut.flicker = rig.flicker;
762
+ }
763
+ if (rig.color !== undefined) {
764
+ if (typeof rig.color !== "string" || !COLOR_RE.test(rig.color))
765
+ errors.push("rig.color: must be a hex colour such as #3fa66b or #3a6");
766
+ else
767
+ rigOut.color = rig.color;
768
+ }
769
+ }
770
+ }
771
+ if (errors.length || !body || !eyes)
772
+ return { ok: false, errors: errors.length ? errors : ["(root): invalid definition"] };
773
+ const value = { version: 1, id: id, name, body: { path: bodyPath }, eyes };
774
+ if (rigOut)
775
+ value.rig = rigOut;
776
+ // Does the whole figure fit the stage once scaled? (Only a warning: animations may exceed it anyway.)
777
+ const fit = stageFit(value, body);
778
+ if (fit)
779
+ warnings.push(fit);
780
+ return { ok: true, value, warnings };
781
+ }
782
+ /** Warns when body plus parts would stick out of the engine's viewBox at rest. */
783
+ function stageFit(def, body) {
784
+ let minY = body.bounds.minY;
785
+ let minX = body.bounds.minX;
786
+ let maxX = body.bounds.maxX;
787
+ for (const p of def.rig?.parts ?? []) {
788
+ const polys = flattenPath(normalizePath(p.path));
789
+ const b = polyBounds(polys);
790
+ minY = Math.min(minY, b.minY);
791
+ minX = Math.min(minX, b.minX);
792
+ maxX = Math.max(maxX, b.maxX);
793
+ }
794
+ const cx = (body.bounds.minX + body.bounds.maxX) / 2;
795
+ const top = GROUND.y - (body.bounds.maxY - minY) * CHARACTER_SCALE;
796
+ const left = GROUND.x + (minX - cx) * CHARACTER_SCALE;
797
+ const right = GROUND.x + (maxX - cx) * CHARACTER_SCALE;
798
+ if (top < 60 || left < 190 || right > 1070)
799
+ return "the figure (body plus parts) is larger than the stage once scaled; it will be clipped. Make it smaller or lower the parts";
800
+ return null;
801
+ }
802
+ /* ======================================================================== */
803
+ /* Definition → Rig */
804
+ /* ======================================================================== */
805
+ /**
806
+ * Ratios that turn the `classic` eye into `pumpy` and `big`, read from Berry's
807
+ * hand-tuned styles: `w`/`h` as multiples of the classic, `dx` as a fraction
808
+ * of the classic width, `dy` as a fraction of the classic height; `tilt` is kept.
809
+ */
810
+ const STYLE_RATIOS = (() => {
811
+ const c = RIG_BERRY.eyeStyles.classic;
812
+ const of = (s) => ({ w: s.w / c.w, h: s.h / c.h, dx: s.dx / c.w, dy: s.dy / c.h, tilt: s.tilt });
813
+ return { pumpy: of(RIG_BERRY.eyeStyles.pumpy), big: of(RIG_BERRY.eyeStyles.big) };
814
+ })();
815
+ /** Accessory anchor relative to the body box, measured on Berry (880,300 on a 320..934 × 392..960 body). */
816
+ const ACCESSORY = { fromRight: (934 - 880) / (934 - 320), aboveTop: (392 - 300) / (960 - 392), fromTopAll: (300 - 252) / (960 - 252) };
817
+ /**
818
+ * Compiles a validated definition into a `Rig`. Derivations (S = CHARACTER_SCALE):
819
+ * - transform: x' = 627 + (x − bboxCenterX)·S, y' = 960 + (y − bboxBottom)·S, where the bbox is that of
820
+ * the flattened body outline. Parts, pivots, tips and eyes use the same transform.
821
+ * - eyes.left/right = (eyes.x ∓ spacing/2, eyes.y) transformed.
822
+ * - eyeStyles.classic = a pill: h = 11·scale·S and w = h / 2 (Berry's ratio; deliberately wider than Open Bot Avatar's 4-wide pill), so w = 5.5·scale·S, tilt 0, dx 0, dy 0.
823
+ * - pumpy / big = classic × Berry's ratios (w, h multiples; dx as a fraction of classic w, dy of classic h;
824
+ * tilt copied), built from the classic AFTER its override; then each style's own `rig.eyeStyles`
825
+ * override (w/h/dx/dy × S) is applied.
826
+ * - ground = (627, 960); anchor = (627, 660); center = bbox centre (transformed).
827
+ * - shadow = (627, 988), rx = 0.41 × body width, ry = 22 (Berry: 250 / 614 ≈ 0.41).
828
+ * - accessory: x = bboxRight − 0.088 × body width; y = min(topOfEverything + 0.068 × total height,
829
+ * bodyTop − 0.16 × body height), never above 100 (Berry's proportions: 880,300).
830
+ * - baseHeight = 960 − mean pivot y, or 0.6 × body height with no parts.
831
+ * - idleAppendage = rig.idle (default 1/1); flicker = rig.flicker (default 0); no core.
832
+ * Throws if the definition is invalid; run `validateCharacter` first.
833
+ */
834
+ export function characterToRig(def) {
835
+ const S = CHARACTER_SCALE;
836
+ const bodyCmds = normalizePath(def.body.path, true);
837
+ const b = polyBounds(flattenPath(bodyCmds));
838
+ const cx0 = (b.minX + b.maxX) / 2;
839
+ const tx = (x) => GROUND.x + (x - cx0) * S;
840
+ const ty = (y) => GROUND.y + (y - b.maxY) * S;
841
+ const place = (cmds) => serializePath(cmds.map(({ c, pts }) => ({ c, pts: pts.map((v, i) => (i % 2 === 0 ? tx(v) : ty(v))) })));
842
+ const bodyW = (b.maxX - b.minX) * S;
843
+ const bodyH = (b.maxY - b.minY) * S;
844
+ const bodyTop = ty(b.minY);
845
+ const appendages = [];
846
+ let topAll = bodyTop;
847
+ for (const p of def.rig?.parts ?? []) {
848
+ const cmds = normalizePath(p.path, true);
849
+ const pb = polyBounds(flattenPath(cmds));
850
+ topAll = Math.min(topAll, ty(pb.minY));
851
+ appendages.push({
852
+ role: p.role,
853
+ path: place(cmds),
854
+ pivot: { x: tx(p.pivot[0]), y: ty(p.pivot[1]) },
855
+ tip: { x: tx(p.tip[0]), y: ty(p.tip[1]) },
856
+ });
857
+ }
858
+ const ov = def.rig?.eyeStyles ?? {};
859
+ const apply = (base, o) => ({
860
+ w: o?.w !== undefined ? o.w * S : base.w,
861
+ h: o?.h !== undefined ? o.h * S : base.h,
862
+ tilt: o?.tilt ?? base.tilt,
863
+ dx: o?.dx !== undefined ? o.dx * S : base.dx,
864
+ dy: o?.dy !== undefined ? o.dy * S : base.dy,
865
+ });
866
+ const classic = apply({ w: EYE_W * def.eyes.scale * S, h: EYE_H * def.eyes.scale * S, tilt: 0, dx: 0, dy: 0 }, ov.classic);
867
+ const from = (r) => ({
868
+ w: classic.w * r.w,
869
+ h: classic.h * r.h,
870
+ tilt: r.tilt,
871
+ dx: classic.w * r.dx,
872
+ dy: classic.h * r.dy,
873
+ });
874
+ const pivotY = appendages.length ? appendages.reduce((s, a) => s + a.pivot.y, 0) / appendages.length : 0;
875
+ const totalH = GROUND.y - topAll;
876
+ return {
877
+ id: def.id,
878
+ body: place(bodyCmds),
879
+ appendages,
880
+ eyes: {
881
+ left: { x: tx(def.eyes.x - def.eyes.spacing / 2), y: ty(def.eyes.y) },
882
+ right: { x: tx(def.eyes.x + def.eyes.spacing / 2), y: ty(def.eyes.y) },
883
+ },
884
+ eyeStyles: { classic, pumpy: apply(from(STYLE_RATIOS.pumpy), ov.pumpy), big: apply(from(STYLE_RATIOS.big), ov.big) },
885
+ ground: { ...GROUND },
886
+ center: { x: tx(cx0), y: (bodyTop + GROUND.y) / 2 },
887
+ shadow: { x: GROUND.x, y: 988, rx: 0.41 * bodyW, ry: 22 },
888
+ accessory: {
889
+ x: tx(b.maxX) - ACCESSORY.fromRight * bodyW,
890
+ y: Math.max(100, Math.min(topAll + ACCESSORY.fromTopAll * totalH, bodyTop - ACCESSORY.aboveTop * bodyH)),
891
+ },
892
+ anchor: { x: 627, y: 660 },
893
+ baseHeight: appendages.length ? GROUND.y - pivotY : 0.6 * bodyH,
894
+ idleAppendage: { amp: def.rig?.idle?.amp ?? 1, freq: def.rig?.idle?.freq ?? 1 },
895
+ flicker: def.rig?.flicker ?? 0,
896
+ };
897
+ }
898
+ /** JSON text → validated definition plus rig. Never throws. */
899
+ export function parseCharacter(json) {
900
+ let raw;
901
+ try {
902
+ raw = JSON.parse(json);
903
+ }
904
+ catch (err) {
905
+ return { ok: false, errors: [`(root): not valid JSON (${err instanceof Error ? err.message : String(err)})`] };
906
+ }
907
+ const v = validateCharacter(raw);
908
+ if (!v.ok)
909
+ return v;
910
+ try {
911
+ return { ok: true, value: { definition: v.value, rig: characterToRig(v.value) }, warnings: v.warnings };
912
+ }
913
+ catch (err) {
914
+ return { ok: false, errors: [`(root): could not build the rig (${err instanceof Error ? err.message : String(err)})`] };
915
+ }
916
+ }