@ikijs/mcp 0.23.2 → 0.25.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.
package/dist/cli.js CHANGED
@@ -23,18 +23,798 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  mod
24
24
  ));
25
25
 
26
+ // ../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.15_supports-color@7.2.0_typescript@5.9.3/node_modules/tsup/assets/cjs_shims.js
27
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
28
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
29
+
26
30
  // src/server.ts
27
31
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
28
32
  var import_zod = require("zod");
29
33
 
30
34
  // src/tools.ts
31
35
  var import_node_path2 = __toESM(require("path"));
36
+ var import_format7 = require("@ikijs/format");
37
+ var import_editor3 = require("@ikijs/editor");
38
+
39
+ // src/fold-report.ts
40
+ var import_editor = require("@ikijs/editor");
41
+
42
+ // ../engine/src/math.ts
43
+ function clamp(value, min, max) {
44
+ return Math.max(min, Math.min(max, value));
45
+ }
46
+ function lerp(a, b, t) {
47
+ return a + (b - a) * t;
48
+ }
49
+
50
+ // ../engine/src/parameter-store.ts
51
+ var ParameterStore = class {
52
+ params = /* @__PURE__ */ new Map();
53
+ values = /* @__PURE__ */ new Map();
54
+ /**
55
+ * Resting value per id: the declared default clamped into range, resolved
56
+ * ONCE here so `reset()` is a straight copy and a malformed descriptor is
57
+ * reported once rather than on every reset.
58
+ */
59
+ defaults = /* @__PURE__ */ new Map();
60
+ constructor(parameters) {
61
+ for (const param of parameters) {
62
+ this.params.set(param.id, param);
63
+ if (!Number.isFinite(param.default)) {
64
+ console.error(
65
+ `Iki: parameter "${param.id}" has a non-finite default; resting at the neutral in-range value instead`
66
+ );
67
+ }
68
+ const base = Number.isFinite(param.default) ? param.default : 0;
69
+ this.defaults.set(param.id, clamp(base, param.min, param.max));
70
+ }
71
+ for (const [id, value] of this.defaults) this.values.set(id, value);
72
+ }
73
+ /**
74
+ * Set a parameter's value, clamped to its range. Unknown ids are ignored, as
75
+ * are non-finite values: this is the boundary a host drives with live signals,
76
+ * and `clamp` cannot filter NaN (`Math.max(min, Math.min(max, NaN))` is NaN),
77
+ * so one bad lip-sync/gaze frame would otherwise poison every binding that
78
+ * reads the parameter. A dropped write holds the last good pose.
79
+ */
80
+ set(id, value) {
81
+ const param = this.params.get(id);
82
+ if (!param) return;
83
+ if (!Number.isFinite(value)) return;
84
+ this.values.set(id, clamp(value, param.min, param.max));
85
+ }
86
+ /** Current value, or 0 if the id is unknown. */
87
+ get(id) {
88
+ return this.values.get(id) ?? 0;
89
+ }
90
+ /** Position of a parameter within its range, 0..1. */
91
+ normalized(id) {
92
+ const param = this.params.get(id);
93
+ if (!param || param.max === param.min) return 0;
94
+ return (this.get(id) - param.min) / (param.max - param.min);
95
+ }
96
+ /** Reset every parameter to its resting value (see `defaults`). */
97
+ reset() {
98
+ for (const [id, value] of this.defaults) this.values.set(id, value);
99
+ }
100
+ list() {
101
+ return [...this.params.values()];
102
+ }
103
+ };
104
+
105
+ // ../engine/src/affine.ts
106
+ function translate(tx, ty) {
107
+ return [1, 0, 0, 1, tx, ty];
108
+ }
109
+ function scale(sx, sy) {
110
+ return [sx, 0, 0, sy, 0, 0];
111
+ }
112
+ function rotate(degrees) {
113
+ const r = degrees * Math.PI / 180;
114
+ const c = Math.cos(r);
115
+ const s = Math.sin(r);
116
+ return [c, s, -s, c, 0, 0];
117
+ }
118
+ function multiply(a, b) {
119
+ return [
120
+ a[0] * b[0] + a[2] * b[1],
121
+ a[1] * b[0] + a[3] * b[1],
122
+ a[0] * b[2] + a[2] * b[3],
123
+ a[1] * b[2] + a[3] * b[3],
124
+ a[0] * b[4] + a[2] * b[5] + a[4],
125
+ a[1] * b[4] + a[3] * b[5] + a[5]
126
+ ];
127
+ }
128
+
129
+ // ../engine/src/warp.ts
130
+ function accumulateKeyformOffsets(keyforms, value, out) {
131
+ const ks = keyforms;
132
+ if (value <= ks[0].value) {
133
+ const { offsets } = ks[0];
134
+ for (let i = 0; i < offsets.length; i++) {
135
+ out[i] += offsets[i];
136
+ }
137
+ } else if (value >= ks[ks.length - 1].value) {
138
+ const { offsets } = ks[ks.length - 1];
139
+ for (let i = 0; i < offsets.length; i++) {
140
+ out[i] += offsets[i];
141
+ }
142
+ } else {
143
+ let lo = ks[0];
144
+ let hi = ks[1];
145
+ for (let k = 1; k < ks.length - 1; k++) {
146
+ if (ks[k].value <= value) {
147
+ lo = ks[k];
148
+ hi = ks[k + 1];
149
+ }
150
+ }
151
+ const t = (value - lo.value) / (hi.value - lo.value);
152
+ const loOff = lo.offsets;
153
+ const hiOff = hi.offsets;
154
+ for (let i = 0; i < loOff.length; i++) {
155
+ out[i] += loOff[i] + (hiOff[i] - loOff[i]) * t;
156
+ }
157
+ }
158
+ }
159
+ function accumulate2DKeyformOffsets(valuesX, valuesY, keyforms2d, vx, vy, out) {
160
+ const lastX = valuesX.length - 1;
161
+ const lastY = valuesY.length - 1;
162
+ let ix;
163
+ let tx;
164
+ if (vx <= valuesX[0]) {
165
+ ix = 0;
166
+ tx = 0;
167
+ } else if (vx >= valuesX[lastX]) {
168
+ ix = lastX - 1;
169
+ tx = 1;
170
+ } else {
171
+ ix = 0;
172
+ for (let k = 0; k < lastX - 1; k++) {
173
+ if (valuesX[k + 1] <= vx) ix = k + 1;
174
+ }
175
+ tx = (vx - valuesX[ix]) / (valuesX[ix + 1] - valuesX[ix]);
176
+ }
177
+ let iy;
178
+ let ty;
179
+ if (vy <= valuesY[0]) {
180
+ iy = 0;
181
+ ty = 0;
182
+ } else if (vy >= valuesY[lastY]) {
183
+ iy = lastY - 1;
184
+ ty = 1;
185
+ } else {
186
+ iy = 0;
187
+ for (let k = 0; k < lastY - 1; k++) {
188
+ if (valuesY[k + 1] <= vy) iy = k + 1;
189
+ }
190
+ ty = (vy - valuesY[iy]) / (valuesY[iy + 1] - valuesY[iy]);
191
+ }
192
+ const W = valuesX.length;
193
+ const c00 = keyforms2d[iy * W + ix];
194
+ const c10 = keyforms2d[iy * W + ix + 1];
195
+ const c01 = keyforms2d[(iy + 1) * W + ix];
196
+ const c11 = keyforms2d[(iy + 1) * W + ix + 1];
197
+ const o00 = c00.offsets;
198
+ const o10 = c10.offsets;
199
+ const o01 = c01.offsets;
200
+ const o11 = c11.offsets;
201
+ for (let n = 0; n < o00.length; n++) {
202
+ const top = o00[n] + (o10[n] - o00[n]) * tx;
203
+ const bot = o01[n] + (o11[n] - o01[n]) * tx;
204
+ out[n] += top + (bot - top) * ty;
205
+ }
206
+ }
207
+ function applyWarps(rest, warps, params, out) {
208
+ out.set(rest);
209
+ if (!warps || warps.length === 0) return;
210
+ for (const warp of warps) {
211
+ accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), out);
212
+ }
213
+ }
214
+
215
+ // ../engine/src/warp-grid.ts
216
+ function deformWarpGrid(d, params) {
217
+ const points = Float32Array.from(d.grid.points);
218
+ for (const warp of d.warps ?? []) {
219
+ accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), points);
220
+ }
221
+ if (d.warp2d !== void 0) {
222
+ accumulate2DKeyformOffsets(
223
+ d.warp2d.valuesX,
224
+ d.warp2d.valuesY,
225
+ d.warp2d.keyforms2d,
226
+ params.get(d.warp2d.parameter),
227
+ params.get(d.warp2d.parameterY),
228
+ points
229
+ );
230
+ }
231
+ return points;
232
+ }
233
+ function transformGridPoints(points, affine, out = new Float32Array(points.length)) {
234
+ for (let i = 0; i < points.length; i += 2) {
235
+ const x = points[i];
236
+ const y = points[i + 1];
237
+ out[i] = affine[0] * x + affine[2] * y + affine[4];
238
+ out[i + 1] = affine[1] * x + affine[3] * y + affine[5];
239
+ }
240
+ return out;
241
+ }
242
+ function bindPointToRestGrid(x, y, restGrid) {
243
+ const { cols, rows, points } = restGrid;
244
+ const stride = cols + 1;
245
+ let col = cols - 1;
246
+ for (let c = 0; c < cols; c++) {
247
+ const xRight2 = points[(c + 1) * 2];
248
+ if (x < xRight2) {
249
+ col = c;
250
+ break;
251
+ }
252
+ }
253
+ const xLeft = points[col * 2];
254
+ const xRight = points[(col + 1) * 2];
255
+ const s = clamp((x - xLeft) / (xRight - xLeft), 0, 1);
256
+ let row = rows - 1;
257
+ for (let r = 0; r < rows; r++) {
258
+ const yBottom2 = points[(r + 1) * stride * 2 + 1];
259
+ if (y > yBottom2) {
260
+ row = r;
261
+ break;
262
+ }
263
+ }
264
+ const yTop = points[row * stride * 2 + 1];
265
+ const yBottom = points[(row + 1) * stride * 2 + 1];
266
+ const t = clamp((yTop - y) / (yTop - yBottom), 0, 1);
267
+ return { cell: row * cols + col, s, t };
268
+ }
269
+ function applyWarpToChild(localVerts, partAffine, restGrid, deformedGrid, out) {
270
+ const n = localVerts.length / 2;
271
+ for (let v = 0; v < n; v++) {
272
+ const lx = localVerts[v * 2];
273
+ const ly = localVerts[v * 2 + 1];
274
+ const mx = partAffine[0] * lx + partAffine[2] * ly + partAffine[4];
275
+ const my = partAffine[1] * lx + partAffine[3] * ly + partAffine[5];
276
+ const binding = bindPointToRestGrid(mx, my, restGrid);
277
+ const [sx, sy] = sampleWarpGrid(deformedGrid, binding);
278
+ out[v * 2] = sx;
279
+ out[v * 2 + 1] = sy;
280
+ }
281
+ }
282
+ function sampleWarpGrid(grid, binding) {
283
+ const { cols, points } = grid;
284
+ const stride = cols + 1;
285
+ const row = Math.floor(binding.cell / cols);
286
+ const col = binding.cell % cols;
287
+ const { s, t } = binding;
288
+ const i00 = (row * stride + col) * 2;
289
+ const i10 = (row * stride + col + 1) * 2;
290
+ const i01 = ((row + 1) * stride + col) * 2;
291
+ const i11 = ((row + 1) * stride + col + 1) * 2;
292
+ const topX = points[i00] + (points[i10] - points[i00]) * s;
293
+ const topY = points[i00 + 1] + (points[i10 + 1] - points[i00 + 1]) * s;
294
+ const botX = points[i01] + (points[i11] - points[i01]) * s;
295
+ const botY = points[i01 + 1] + (points[i11 + 1] - points[i01 + 1]) * s;
296
+ return [topX + (botX - topX) * t, topY + (botY - topY) * t];
297
+ }
298
+ function warpRigidFrame(pivot, restGrid, localPoints) {
299
+ const { cols, rows } = restGrid;
300
+ const binding = bindPointToRestGrid(pivot.x, pivot.y, restGrid);
301
+ const [px2, py] = sampleWarpGrid({ cols, rows, points: localPoints }, binding);
302
+ const stride = cols + 1;
303
+ const row = Math.floor(binding.cell / cols);
304
+ const col = binding.cell % cols;
305
+ const { s, t } = binding;
306
+ const i00 = (row * stride + col) * 2;
307
+ const i10 = (row * stride + col + 1) * 2;
308
+ const i01 = ((row + 1) * stride + col) * 2;
309
+ const i11 = ((row + 1) * stride + col + 1) * 2;
310
+ const rest = restGrid.points;
311
+ const cellWidth = rest[(col + 1) * 2] - rest[col * 2];
312
+ const cellHeight = rest[row * stride * 2 + 1] - rest[(row + 1) * stride * 2 + 1];
313
+ const q = localPoints;
314
+ const exX = lerp(q[i10] - q[i00], q[i11] - q[i01], t) / cellWidth;
315
+ const exY = lerp(q[i10 + 1] - q[i00 + 1], q[i11 + 1] - q[i01 + 1], t) / cellWidth;
316
+ const eyX = -lerp(q[i01] - q[i00], q[i11] - q[i10], s) / cellHeight;
317
+ const eyY = -lerp(q[i01 + 1] - q[i00 + 1], q[i11 + 1] - q[i10 + 1], s) / cellHeight;
318
+ const theta = Math.atan2(exY - eyX, exX + eyY);
319
+ const c = Math.cos(theta);
320
+ const sn = Math.sin(theta);
321
+ return [
322
+ c,
323
+ sn,
324
+ -sn,
325
+ c,
326
+ px2 - (c * pivot.x - sn * pivot.y),
327
+ py - (sn * pivot.x + c * pivot.y)
328
+ ];
329
+ }
330
+
331
+ // ../engine/src/deform.ts
332
+ var IDENTITY_TRANSFORM = {
333
+ x: 0,
334
+ y: 0,
335
+ rotation: 0,
336
+ scaleX: 1,
337
+ scaleY: 1,
338
+ opacity: 1
339
+ };
340
+ function evaluateTransform(transform, bindings, params) {
341
+ const base = transform ?? IDENTITY_TRANSFORM;
342
+ const result = {
343
+ x: base.x,
344
+ y: base.y,
345
+ rotation: base.rotation ?? 0,
346
+ scaleX: base.scaleX ?? 1,
347
+ scaleY: base.scaleY ?? 1,
348
+ opacity: base.opacity ?? 1
349
+ };
350
+ for (const binding of bindings ?? []) {
351
+ const t = params.normalized(binding.parameter);
352
+ const value = binding.from + (binding.to - binding.from) * t;
353
+ switch (binding.channel) {
354
+ case "translateX":
355
+ result.x += value;
356
+ break;
357
+ case "translateY":
358
+ result.y += value;
359
+ break;
360
+ case "rotate":
361
+ result.rotation += value;
362
+ break;
363
+ case "scaleX":
364
+ result.scaleX += value;
365
+ break;
366
+ case "scaleY":
367
+ result.scaleY += value;
368
+ break;
369
+ case "opacity":
370
+ result.opacity *= value;
371
+ break;
372
+ }
373
+ }
374
+ return result;
375
+ }
376
+ function deformerLocalMatrix(d, params) {
377
+ const t = evaluateTransform(d.transform, d.bindings, params);
378
+ const trs = multiply(
379
+ multiply(translate(t.x, t.y), rotate(t.rotation)),
380
+ scale(t.scaleX, t.scaleY)
381
+ );
382
+ return multiply(
383
+ multiply(translate(d.pivot.x, d.pivot.y), trs),
384
+ translate(-d.pivot.x, -d.pivot.y)
385
+ );
386
+ }
387
+ function resolveDeformers(deformers, params) {
388
+ const byId = new Map(deformers.map((d) => [d.id, d]));
389
+ const worlds = /* @__PURE__ */ new Map();
390
+ const grids = /* @__PURE__ */ new Map();
391
+ const localWarps = /* @__PURE__ */ new Map();
392
+ function parentOf(d) {
393
+ if (d.parent === void 0) return void 0;
394
+ const parent = byId.get(d.parent);
395
+ if (!parent) {
396
+ throw new Error(
397
+ `unresolved deformer parent "${d.parent}" \u2014 model not validated?`
398
+ );
399
+ }
400
+ return parent;
401
+ }
402
+ function resolveWorld(d) {
403
+ const cached = worlds.get(d.id);
404
+ if (cached) return cached;
405
+ const local = deformerLocalMatrix(d, params);
406
+ const parent = parentOf(d);
407
+ let world;
408
+ if (parent === void 0) {
409
+ world = local;
410
+ } else if (parent.kind === "warp") {
411
+ const warp = resolveWarp(parent);
412
+ const ridden = multiply(
413
+ warpRigidFrame(d.pivot, parent.grid, warp.localGrid),
414
+ local
415
+ );
416
+ world = warp.parentWorld ? multiply(warp.parentWorld, ridden) : ridden;
417
+ } else {
418
+ world = multiply(resolveWorld(parent), local);
419
+ }
420
+ worlds.set(d.id, world);
421
+ return world;
422
+ }
423
+ function resolveWarp(d) {
424
+ const cached = localWarps.get(d.id);
425
+ if (cached) return cached;
426
+ const parent = parentOf(d);
427
+ if (parent?.kind === "warp") {
428
+ throw new Error(
429
+ `warp deformer "${d.id}" hangs from warp "${parent.id}" \u2014 model not validated?`
430
+ );
431
+ }
432
+ const parentWorld = parent && resolveWorld(parent);
433
+ const localGrid = deformWarpGrid(d, params);
434
+ grids.set(d.id, {
435
+ cols: d.grid.cols,
436
+ rows: d.grid.rows,
437
+ points: parentWorld ? transformGridPoints(localGrid, parentWorld) : localGrid
438
+ });
439
+ const resolved = { localGrid, parentWorld };
440
+ localWarps.set(d.id, resolved);
441
+ return resolved;
442
+ }
443
+ for (const d of deformers) {
444
+ if (d.kind === "warp") resolveWarp(d);
445
+ else resolveWorld(d);
446
+ }
447
+ return { worlds, grids };
448
+ }
449
+
450
+ // ../engine/src/idle-motion.ts
32
451
  var import_format = require("@ikijs/format");
33
- var import_editor2 = require("@ikijs/editor");
452
+
453
+ // ../engine/src/frame-clock.ts
454
+ var FIXED_DT_S = 1 / 60;
455
+
456
+ // ../engine/src/idle-motion.ts
457
+ var BLINK_CLOSE_MS = 60;
458
+ var BLINK_HOLD_MS = 20;
459
+ var BLINK_OPEN_MS = 100;
460
+ var BLINK_DURATION_MS = BLINK_CLOSE_MS + BLINK_HOLD_MS + BLINK_OPEN_MS;
461
+
462
+ // ../engine/src/hair-chain-motion.ts
463
+ var DEG2RAD = Math.PI / 180;
464
+ var RAD2DEG = 180 / Math.PI;
465
+
466
+ // ../engine/src/iki-motion.ts
467
+ var import_format4 = require("@ikijs/format");
468
+
469
+ // ../engine/src/clip-player.ts
470
+ var import_format2 = require("@ikijs/format");
471
+
472
+ // ../engine/src/expression-player.ts
473
+ var import_format3 = require("@ikijs/format");
474
+
475
+ // ../engine/src/iki-motion.ts
476
+ var HEAD_AND_GAZE = /* @__PURE__ */ new Set([
477
+ import_format4.StandardParameter.AngleX,
478
+ import_format4.StandardParameter.AngleY,
479
+ import_format4.StandardParameter.AngleZ,
480
+ import_format4.StandardParameter.EyeballX,
481
+ import_format4.StandardParameter.EyeballY
482
+ ]);
483
+
484
+ // ../engine/src/folds.ts
485
+ var import_format5 = require("@ikijs/format");
486
+ var FLIP = 0;
487
+ var COLLAPSE = 0.1;
488
+ var ANGLES = [
489
+ import_format5.StandardParameter.AngleX,
490
+ import_format5.StandardParameter.AngleY,
491
+ import_format5.StandardParameter.AngleZ,
492
+ import_format5.StandardParameter.BodyAngleX,
493
+ import_format5.StandardParameter.BodyAngleY,
494
+ import_format5.StandardParameter.BodyAngleZ
495
+ ];
496
+ var CROSSES = [
497
+ [import_format5.StandardParameter.EyeOpenLeft],
498
+ [import_format5.StandardParameter.EyeOpenRight],
499
+ [import_format5.StandardParameter.MouthOpen],
500
+ [import_format5.StandardParameter.ArmLeft, import_format5.StandardParameter.ArmRight],
501
+ [import_format5.StandardParameter.ElbowLeft, import_format5.StandardParameter.ElbowRight]
502
+ ];
503
+ function foldPoses(model) {
504
+ const byId = new Map(
505
+ model.parameters.filter((p) => p.min !== p.max).map((p) => [p.id, p])
506
+ );
507
+ const declared = (ids) => ids.flatMap((id) => byId.get(id) ?? []);
508
+ const poses = [];
509
+ const names = /* @__PURE__ */ new Set();
510
+ const add = (values) => {
511
+ const name = poseName(values);
512
+ if (names.has(name)) return;
513
+ names.add(name);
514
+ poses.push({ name, values });
515
+ };
516
+ add({});
517
+ for (const p of byId.values()) {
518
+ add({ [p.id]: p.min });
519
+ add({ [p.id]: p.max });
520
+ }
521
+ const angles = declared(ANGLES);
522
+ if (angles.length === 0) return poses;
523
+ const expand = (corners, groups) => {
524
+ for (const group of groups) {
525
+ corners = corners.flatMap(
526
+ (values) => ["min", "max"].map((end) => {
527
+ const next = { ...values };
528
+ for (const p of group) next[p.id] = p[end];
529
+ return next;
530
+ })
531
+ );
532
+ }
533
+ return corners;
534
+ };
535
+ const angleCorners = expand(
536
+ [{}],
537
+ angles.map((p) => [p])
538
+ );
539
+ for (const values of angleCorners) add(values);
540
+ const crosses = CROSSES.map(declared).filter((g) => g.length > 0);
541
+ for (const values of expand(angleCorners, crosses)) add(values);
542
+ return poses;
543
+ }
544
+ function poseName(values) {
545
+ const ids = Object.keys(values).sort();
546
+ if (ids.length === 0) return "rest";
547
+ return ids.map((id) => `${id}=${values[id]}`).join(" ");
548
+ }
549
+ function staticDeformers(model) {
550
+ return (model.deformers ?? []).map(
551
+ (d) => d.kind === "warp" ? { ...d, warps: void 0, warp2d: void 0 } : { ...d, bindings: void 0 }
552
+ );
553
+ }
554
+ function cornerAreas(points, cols, rows) {
555
+ const stride = cols + 1;
556
+ const out = new Float64Array(cols * rows * 4);
557
+ for (let r = 0; r < rows; r++) {
558
+ for (let c = 0; c < cols; c++) {
559
+ const tl = r * stride + c;
560
+ const [tr, bl, br] = [tl + 1, tl + stride, tl + stride + 1];
561
+ const i = (r * cols + c) * 4;
562
+ out[i] = doubledArea(points, bl, br, tl);
563
+ out[i + 1] = doubledArea(points, br, tr, bl);
564
+ out[i + 2] = doubledArea(points, tr, tl, br);
565
+ out[i + 3] = doubledArea(points, tl, bl, tr);
566
+ }
567
+ }
568
+ return out;
569
+ }
570
+ function doubledArea(points, p, q, s) {
571
+ const ax = points[q * 2] - points[p * 2];
572
+ const ay = points[q * 2 + 1] - points[p * 2 + 1];
573
+ const bx = points[s * 2] - points[p * 2];
574
+ const by = points[s * 2 + 1] - points[p * 2 + 1];
575
+ return ax * by - ay * bx;
576
+ }
577
+ function triangleAreas(points, indices) {
578
+ const out = new Float64Array(indices.length / 3);
579
+ for (let t = 0; t < out.length; t++) {
580
+ const i = t * 3;
581
+ out[t] = doubledArea(points, indices[i], indices[i + 1], indices[i + 2]);
582
+ }
583
+ return out;
584
+ }
585
+ function placement(part, t) {
586
+ return multiply(
587
+ multiply(translate(t.x, t.y), rotate(t.rotation)),
588
+ scale(part.width * t.scaleX, part.height * t.scaleY)
589
+ );
590
+ }
591
+ function keepLeast(sweep, areas, pose, expected) {
592
+ const slot = expected(sweep.target) ? "expected" : "worst";
593
+ for (let i = 0; i < areas.length; i++) {
594
+ const rest = sweep.restAreas[i];
595
+ if (Math.abs(rest) < sweep.tiny) continue;
596
+ const ratio = areas[i] / rest;
597
+ if (ratio < (sweep[slot]?.ratio ?? Infinity)) {
598
+ sweep[slot] = { ratio, at: i, pose };
599
+ }
600
+ }
601
+ }
602
+ function partSweep(part, mesh, deformers, worlds, store) {
603
+ const warpDeformer = deformers.find(
604
+ (d) => d.kind === "warp" && d.id === part.deformer
605
+ );
606
+ const frame = warpDeformer ? warpDeformer.parent : part.deformer;
607
+ const placed = placement(
608
+ part,
609
+ evaluateTransform(part.transform, void 0, store)
610
+ );
611
+ const restPoints = transformGridPoints(
612
+ mesh.vertices,
613
+ frame === void 0 ? placed : multiply(worlds.get(frame), placed),
614
+ new Float64Array(mesh.vertices.length)
615
+ );
616
+ return {
617
+ target: { kind: "part", id: part.id },
618
+ restAreas: triangleAreas(restPoints, mesh.indices),
619
+ tiny: 1e-9 * part.width * part.height,
620
+ part,
621
+ indices: mesh.indices,
622
+ warpDeformer,
623
+ vertices: Float32Array.from(mesh.vertices),
624
+ local: new Float32Array(mesh.vertices.length),
625
+ landed: new Float32Array(mesh.vertices.length),
626
+ restPoints
627
+ };
628
+ }
629
+ function landPart(sweep, store, { worlds, grids }) {
630
+ const { part, warpDeformer, local, landed } = sweep;
631
+ applyWarps(sweep.vertices, part.warps, store, local);
632
+ const placed = placement(
633
+ part,
634
+ evaluateTransform(part.transform, part.bindings, store)
635
+ );
636
+ if (warpDeformer) {
637
+ const grid = grids.get(warpDeformer.id);
638
+ applyWarpToChild(local, placed, warpDeformer.grid, grid, landed);
639
+ } else if (part.deformer !== void 0) {
640
+ const world = worlds.get(part.deformer);
641
+ transformGridPoints(local, multiply(world, placed), landed);
642
+ } else {
643
+ transformGridPoints(local, placed, landed);
644
+ }
645
+ return landed;
646
+ }
647
+ function checkFolds(model, options = {}) {
648
+ const poses = options.poses ?? foldPoses(model);
649
+ const deformers = model.deformers ?? [];
650
+ const restStore = new ParameterStore(model.parameters);
651
+ const { worlds } = resolveDeformers(staticDeformers(model), restStore);
652
+ const gridSweeps = [];
653
+ for (const d of deformers) {
654
+ if (d.kind !== "warp") continue;
655
+ const { cols, rows, points } = d.grid;
656
+ const width = points[cols * 2] - points[0];
657
+ const height = points[1] - points[rows * (cols + 1) * 2 + 1];
658
+ gridSweeps.push({
659
+ deformer: d,
660
+ target: { kind: "deformer", id: d.id },
661
+ restAreas: cornerAreas(points, cols, rows),
662
+ // The validator tolerates 1e-6 of jitter, which can zero a corner's area.
663
+ tiny: 1e-9 * width * height
664
+ });
665
+ }
666
+ const partSweeps = model.parts.flatMap(
667
+ (part) => part.mesh ? [partSweep(part, part.mesh, deformers, worlds, restStore)] : []
668
+ );
669
+ for (const pose of poses) {
670
+ const store = new ParameterStore(model.parameters);
671
+ for (const [id, v] of Object.entries(pose.values)) store.set(id, v);
672
+ const value = (id) => store.get(id);
673
+ const expected = (target) => options.expected?.(target, pose, value) === true;
674
+ for (const sweep of gridSweeps) {
675
+ const { cols, rows } = sweep.deformer.grid;
676
+ const areas = cornerAreas(
677
+ deformWarpGrid(sweep.deformer, store),
678
+ cols,
679
+ rows
680
+ );
681
+ keepLeast(sweep, areas, pose, expected);
682
+ }
683
+ const resolved = resolveDeformers(deformers, store);
684
+ for (const sweep of partSweeps) {
685
+ const areas = triangleAreas(
686
+ landPart(sweep, store, resolved),
687
+ sweep.indices
688
+ );
689
+ keepLeast(sweep, areas, pose, expected);
690
+ }
691
+ }
692
+ const targets = [
693
+ ...gridSweeps.map((sweep) => {
694
+ const { parent } = sweep.deformer;
695
+ const world = parent === void 0 ? void 0 : worlds.get(parent);
696
+ return foldTarget(
697
+ sweep,
698
+ (least) => cellHit(sweep.deformer, least, world)
699
+ );
700
+ }),
701
+ ...partSweeps.map(
702
+ (sweep) => foldTarget(sweep, (least) => triangleHit(sweep, least))
703
+ )
704
+ ];
705
+ const offenders = targets.filter((t) => t.kind !== "ok").sort((a, b) => a.worst.ratio - b.worst.ratio);
706
+ return {
707
+ poses: poses.length,
708
+ thresholds: { flip: FLIP, collapse: COLLAPSE },
709
+ targets,
710
+ offenders
711
+ };
712
+ }
713
+ function foldTarget(sweep, hit) {
714
+ const worst = sweep.worst && hit(sweep.worst);
715
+ const expected = sweep.expected && hit(sweep.expected);
716
+ return { target: sweep.target, kind: classify(worst), worst, expected };
717
+ }
718
+ function cellHit(d, least, parent) {
719
+ const { cols, points } = d.grid;
720
+ const cell = Math.floor(least.at / 4);
721
+ const col = cell % cols;
722
+ const row = Math.floor(cell / cols);
723
+ const stride = cols + 1;
724
+ let x = 0;
725
+ let y = 0;
726
+ for (const i of [
727
+ row * stride + col,
728
+ row * stride + col + 1,
729
+ (row + 1) * stride + col,
730
+ (row + 1) * stride + col + 1
731
+ ]) {
732
+ x += points[i * 2] / 4;
733
+ y += points[i * 2 + 1] / 4;
734
+ }
735
+ const rest = parent ? {
736
+ x: parent[0] * x + parent[2] * y + parent[4],
737
+ y: parent[1] * x + parent[3] * y + parent[5]
738
+ } : { x, y };
739
+ return { ratio: least.ratio, where: { col, row }, pose: least.pose, rest };
740
+ }
741
+ function triangleHit(sweep, least) {
742
+ const { indices, restPoints } = sweep;
743
+ let x = 0;
744
+ let y = 0;
745
+ for (let k = 0; k < 3; k++) {
746
+ const i = indices[least.at * 3 + k];
747
+ x += restPoints[i * 2] / 3;
748
+ y += restPoints[i * 2 + 1] / 3;
749
+ }
750
+ return {
751
+ ratio: least.ratio,
752
+ where: { triangle: least.at },
753
+ pose: least.pose,
754
+ rest: { x, y }
755
+ };
756
+ }
757
+ function classify(worst) {
758
+ if (worst === void 0) return "ok";
759
+ if (worst.ratio <= FLIP) return "flip";
760
+ if (worst.ratio < COLLAPSE) return "collapse";
761
+ return "ok";
762
+ }
763
+
764
+ // src/fold-report.ts
765
+ var import_format6 = require("@ikijs/format");
766
+ var SHUT_BY = new Map([
767
+ ["eye_L", import_format6.StandardParameter.EyeOpenLeft],
768
+ ["lash_lower_L", import_format6.StandardParameter.EyeOpenLeft],
769
+ ["eye_R", import_format6.StandardParameter.EyeOpenRight],
770
+ ["lash_lower_R", import_format6.StandardParameter.EyeOpenRight],
771
+ ...[...import_editor.LIP_ROLES, ...import_editor.LIP_INSIDE_ROLES].map((id) => [
772
+ id,
773
+ import_format6.StandardParameter.MouthOpen
774
+ ])
775
+ ]);
776
+ function checkModelFolds(model) {
777
+ const declared = new Set(model.parameters.map((p) => p.id));
778
+ return checkFolds(model, {
779
+ // The effective value, not the pose's overrides: the auto-rig's mouth
780
+ // rests shut at its default, so `rest` and the other parameters' singles
781
+ // are shut-mouth poses too.
782
+ expected: (target, _pose, value) => {
783
+ if (target.kind !== "part") return false;
784
+ const shutBy = SHUT_BY.get(target.id);
785
+ return shutBy !== void 0 && declared.has(shutBy) && value(shutBy) === 0;
786
+ }
787
+ });
788
+ }
789
+ function formatFoldReport(report, canvas) {
790
+ const lines = report.offenders.length === 0 ? [`FOLDS: none over ${report.poses} poses`] : report.offenders.map((t) => offenderLine(t, t.worst, canvas));
791
+ const closures = report.targets.flatMap((t) => {
792
+ if (t.expected === void 0) return [];
793
+ if (t.expected.ratio >= report.thresholds.collapse) return [];
794
+ const shutBy = SHUT_BY.get(t.target.id);
795
+ const at = shutBy === void 0 ? "" : ` at ${shutBy}=0`;
796
+ return [`${t.target.id} ${ratioText(t.expected.ratio)}${at}`];
797
+ });
798
+ if (closures.length > 0) {
799
+ lines.push(
800
+ `FOLDS expected: by-design closures, not findings \u2014 ${closures.join(", ")}`
801
+ );
802
+ }
803
+ return lines;
804
+ }
805
+ function offenderLine(t, hit, canvas) {
806
+ const where = "triangle" in hit.where ? `triangle ${hit.where.triangle}` : `cell (${hit.where.col},${hit.where.row})`;
807
+ const { x, y } = hit.rest;
808
+ return `FOLD ${t.kind} ${t.target.kind} ${t.target.id} ${where} ratio ${ratioText(hit.ratio)} pose [${hit.pose.name}] rest at (${x.toFixed(1)}, ${y.toFixed(1)}) model space, (${(canvas.width / 2 + x).toFixed(0)}, ${(canvas.height / 2 - y).toFixed(0)}) model px from the top-left`;
809
+ }
810
+ function ratioText(ratio) {
811
+ if (ratio === 0) return "0";
812
+ return Math.abs(ratio) < 0.01 ? ratio.toExponential(1) : ratio.toFixed(2);
813
+ }
34
814
 
35
815
  // src/node-images.ts
36
816
  var import_sharp = __toESM(require("sharp"));
37
- var import_editor = require("@ikijs/editor");
817
+ var import_editor2 = require("@ikijs/editor");
38
818
 
39
819
  // src/limits.ts
40
820
  var import_node_fs = __toESM(require("fs"));
@@ -62,18 +842,18 @@ function rejectEmptyOrUrl(inputPath, noun, kind) {
62
842
  );
63
843
  }
64
844
  }
65
- function resolveInputPath(inputPath) {
66
- rejectEmptyOrUrl(inputPath, "layer path", "file path");
845
+ function resolveInputPath(inputPath, what = "layer") {
846
+ rejectEmptyOrUrl(inputPath, `${what} path`, "file path");
67
847
  const resolved = import_node_path.default.resolve(process.cwd(), inputPath);
68
848
  let stat;
69
849
  try {
70
850
  stat = import_node_fs.default.statSync(resolved);
71
851
  } catch {
72
- throw new AutoRigInputError(`layer file not found: ${resolved}`);
852
+ throw new AutoRigInputError(`${what} file not found: ${resolved}`);
73
853
  }
74
854
  if (stat.isDirectory()) {
75
855
  throw new AutoRigInputError(
76
- `layer path is a directory, not a file: ${resolved}`
856
+ `${what} path is a directory, not a file: ${resolved}`
77
857
  );
78
858
  }
79
859
  return resolved;
@@ -190,7 +970,7 @@ async function decodePng(filePath) {
190
970
  }
191
971
  }
192
972
  function detectAlphaBbox(rgba, width, height) {
193
- const bbox = (0, import_editor.detectAlphaBbox)(rgba, width, height);
973
+ const bbox = (0, import_editor2.detectAlphaBbox)(rgba, width, height);
194
974
  if (bbox === null) {
195
975
  throw new AutoRigInputError("layer is empty after alpha threshold");
196
976
  }
@@ -207,15 +987,15 @@ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
207
987
  for (const crop of crops) byId.set(crop.id, crop);
208
988
  const pad = layout.padding;
209
989
  const composites = await Promise.all(
210
- layout.placements.map(async (placement2) => {
211
- const crop = byId.get(placement2.id);
990
+ layout.placements.map(async (placement3) => {
991
+ const crop = byId.get(placement3.id);
212
992
  if (crop === void 0) {
213
993
  throw new AutoRigInputError(
214
- `no crop for atlas placement "${placement2.id}"`
994
+ `no crop for atlas placement "${placement3.id}"`
215
995
  );
216
996
  }
217
997
  const input = pad > 0 ? await (0, import_sharp.default)(crop.buffer).extend({ right: pad, bottom: pad, extendWith: "copy" }).png().toBuffer() : crop.buffer;
218
- return { input, left: placement2.x, top: placement2.y };
998
+ return { input, left: placement3.x, top: placement3.y };
219
999
  })
220
1000
  );
221
1001
  const page = await (0, import_sharp.default)({
@@ -234,10 +1014,10 @@ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
234
1014
  // src/tools.ts
235
1015
  function coerceModel(model) {
236
1016
  try {
237
- const parsed = typeof model === "string" ? (0, import_format.loadIkiModel)(model) : (0, import_format.parseIkiModel)(model);
1017
+ const parsed = typeof model === "string" ? (0, import_format7.loadIkiModel)(model) : (0, import_format7.parseIkiModel)(model);
238
1018
  return { ok: true, model: parsed };
239
1019
  } catch (e) {
240
- if (e instanceof import_format.IkiFormatError) return { ok: false, error: e.message };
1020
+ if (e instanceof import_format7.IkiFormatError) return { ok: false, error: e.message };
241
1021
  throw e;
242
1022
  }
243
1023
  }
@@ -311,115 +1091,115 @@ function describeIki(model) {
311
1091
  }
312
1092
  var STANDARD_PARAMETER_INFO = [
313
1093
  {
314
- id: import_format.StandardParameter.MouthOpen,
1094
+ id: import_format7.StandardParameter.MouthOpen,
315
1095
  description: "Mouth open amount for lip-sync (0 closed .. 1 open)."
316
1096
  },
317
1097
  {
318
- id: import_format.StandardParameter.MouthForm,
1098
+ id: import_format7.StandardParameter.MouthForm,
319
1099
  description: "Mouth form / smile (-1 .. 1)."
320
1100
  },
321
1101
  {
322
- id: import_format.StandardParameter.EyeOpenLeft,
1102
+ id: import_format7.StandardParameter.EyeOpenLeft,
323
1103
  description: "Left eye open (0 closed .. 1 open). Drive with the right eye for a blink."
324
1104
  },
325
1105
  {
326
- id: import_format.StandardParameter.EyeOpenRight,
1106
+ id: import_format7.StandardParameter.EyeOpenRight,
327
1107
  description: "Right eye open (0 closed .. 1 open)."
328
1108
  },
329
1109
  {
330
- id: import_format.StandardParameter.EyeballX,
1110
+ id: import_format7.StandardParameter.EyeballX,
331
1111
  description: "Eyeball gaze, horizontal (-1 .. 1)."
332
1112
  },
333
1113
  {
334
- id: import_format.StandardParameter.EyeballY,
1114
+ id: import_format7.StandardParameter.EyeballY,
335
1115
  description: "Eyeball gaze, vertical (-1 .. 1)."
336
1116
  },
337
1117
  {
338
- id: import_format.StandardParameter.AngleX,
1118
+ id: import_format7.StandardParameter.AngleX,
339
1119
  description: "Head angle, horizontal degrees."
340
1120
  },
341
1121
  {
342
- id: import_format.StandardParameter.AngleY,
1122
+ id: import_format7.StandardParameter.AngleY,
343
1123
  description: "Head angle, vertical degrees."
344
1124
  },
345
1125
  {
346
- id: import_format.StandardParameter.AngleZ,
1126
+ id: import_format7.StandardParameter.AngleZ,
347
1127
  description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
348
1128
  },
349
1129
  {
350
- id: import_format.StandardParameter.BodyAngleX,
1130
+ id: import_format7.StandardParameter.BodyAngleX,
351
1131
  description: "Body turn, degrees (-10 .. 10); positive turns the body toward the viewer's right, as AngleX does the head."
352
1132
  },
353
1133
  {
354
- id: import_format.StandardParameter.BodyAngleY,
1134
+ id: import_format7.StandardParameter.BodyAngleY,
355
1135
  description: "Body lean, degrees (-10 .. 10); positive moves the upper body up, negative bows."
356
1136
  },
357
1137
  {
358
- id: import_format.StandardParameter.BodyAngleZ,
1138
+ id: import_format7.StandardParameter.BodyAngleZ,
359
1139
  description: "Body tilt, degrees (-10 .. 10); positive tilts the top toward the viewer's right (clockwise), as AngleZ does the head."
360
1140
  },
361
1141
  {
362
- id: import_format.StandardParameter.Breath,
1142
+ id: import_format7.StandardParameter.Breath,
363
1143
  description: "Idle breath (0 .. 1), cycled by the host."
364
1144
  },
365
1145
  {
366
- id: import_format.StandardParameter.BrowLeftY,
1146
+ id: import_format7.StandardParameter.BrowLeftY,
367
1147
  description: "Left brow raise/lower (-1 .. 1)."
368
1148
  },
369
1149
  {
370
- id: import_format.StandardParameter.BrowRightY,
1150
+ id: import_format7.StandardParameter.BrowRightY,
371
1151
  description: "Right brow raise/lower (-1 .. 1)."
372
1152
  },
373
1153
  {
374
- id: import_format.StandardParameter.BrowLeftAngle,
1154
+ id: import_format7.StandardParameter.BrowLeftAngle,
375
1155
  description: "Left brow tilt/angle (-1 .. 1)."
376
1156
  },
377
1157
  {
378
- id: import_format.StandardParameter.BrowRightAngle,
1158
+ id: import_format7.StandardParameter.BrowRightAngle,
379
1159
  description: "Right brow tilt/angle (-1 .. 1)."
380
1160
  },
381
1161
  {
382
- id: import_format.StandardParameter.Cheek,
1162
+ id: import_format7.StandardParameter.Cheek,
383
1163
  description: "Cheek blush strength (0 .. 1), raised by an expression."
384
1164
  },
385
1165
  {
386
- id: import_format.StandardParameter.HairSwayX,
1166
+ id: import_format7.StandardParameter.HairSwayX,
387
1167
  description: "Horizontal hair-sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
388
1168
  },
389
1169
  {
390
- id: import_format.StandardParameter.HairSwayZ,
1170
+ id: import_format7.StandardParameter.HairSwayZ,
391
1171
  description: "Hair-sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
392
1172
  },
393
1173
  {
394
- id: import_format.StandardParameter.ArmLeft,
1174
+ id: import_format7.StandardParameter.ArmLeft,
395
1175
  description: "Left shoulder, degrees; positive raises the arm outward (mirrored on the right)."
396
1176
  },
397
1177
  {
398
- id: import_format.StandardParameter.ArmRight,
1178
+ id: import_format7.StandardParameter.ArmRight,
399
1179
  description: "Right shoulder, degrees; positive raises the arm outward (mirrored on the left)."
400
1180
  },
401
1181
  {
402
- id: import_format.StandardParameter.ElbowLeft,
1182
+ id: import_format7.StandardParameter.ElbowLeft,
403
1183
  description: "Left elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the right)."
404
1184
  },
405
1185
  {
406
- id: import_format.StandardParameter.ElbowRight,
1186
+ id: import_format7.StandardParameter.ElbowRight,
407
1187
  description: "Right elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the left)."
408
1188
  },
409
1189
  {
410
- id: import_format.StandardParameter.ArmPoseLeft,
1190
+ id: import_format7.StandardParameter.ArmPoseLeft,
411
1191
  description: "Left pose-forearm switch, 0..1; 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm."
412
1192
  },
413
1193
  {
414
- id: import_format.StandardParameter.ArmPoseRight,
1194
+ id: import_format7.StandardParameter.ArmPoseRight,
415
1195
  description: "Right pose-forearm switch, 0..1; 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm."
416
1196
  },
417
1197
  {
418
- id: import_format.StandardParameter.ArmPoseAngleLeft,
1198
+ id: import_format7.StandardParameter.ArmPoseAngleLeft,
419
1199
  description: "Left pose forearm's own small rotation about the elbow, degrees; positive tips the raised hand outward, away from the body (mirrored on the right)."
420
1200
  },
421
1201
  {
422
- id: import_format.StandardParameter.ArmPoseAngleRight,
1202
+ id: import_format7.StandardParameter.ArmPoseAngleRight,
423
1203
  description: "Right pose forearm's own small rotation about the elbow, degrees; positive tips the raised hand outward, away from the body (mirrored on the left)."
424
1204
  }
425
1205
  ];
@@ -437,7 +1217,7 @@ function expectInput(label, fn) {
437
1217
  }
438
1218
  var LOSSLESS_PAGE_ROLE = "nose";
439
1219
  async function renderAtlasPage(crops, quantizeColors) {
440
- const layout = (0, import_editor2.packAtlas)(
1220
+ const layout = (0, import_editor3.packAtlas)(
441
1221
  crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),
442
1222
  void 0,
443
1223
  MAX_ATLAS_SIDE
@@ -491,7 +1271,7 @@ async function autoRigFromLayers(input) {
491
1271
  });
492
1272
  const rolePairs = expectInput(
493
1273
  "role parsing",
494
- () => (0, import_editor2.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
1274
+ () => (0, import_editor3.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
495
1275
  );
496
1276
  const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));
497
1277
  let canvasW = 0;
@@ -521,7 +1301,7 @@ async function autoRigFromLayers(input) {
521
1301
  `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`
522
1302
  );
523
1303
  }
524
- measurer = (0, import_editor2.createLayerSetMeasurer)({ width: canvasW, height: canvasH });
1304
+ measurer = (0, import_editor3.createLayerSetMeasurer)({ width: canvasW, height: canvasH });
525
1305
  } else if (png.width !== canvasW || png.height !== canvasH) {
526
1306
  throw new AutoRigInputError(
527
1307
  `layer "${fileName}" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
@@ -550,7 +1330,7 @@ async function autoRigFromLayers(input) {
550
1330
  let turn;
551
1331
  let model;
552
1332
  try {
553
- model = (0, import_editor2.generateIkiFromLayerSet)(
1333
+ model = (0, import_editor3.generateIkiFromLayerSet)(
554
1334
  measurement.layers,
555
1335
  { width: canvasW, height: canvasH },
556
1336
  {
@@ -567,12 +1347,12 @@ async function autoRigFromLayers(input) {
567
1347
  }
568
1348
  );
569
1349
  } catch (e) {
570
- if (!(e instanceof import_editor2.TurnTargetError || e instanceof import_editor2.LayerGeometryError)) {
1350
+ if (!(e instanceof import_editor3.TurnTargetError || e instanceof import_editor3.LayerGeometryError)) {
571
1351
  throw e;
572
1352
  }
573
1353
  throw new AutoRigInputError(e.message);
574
1354
  }
575
- const doc = new import_editor2.EditorDocument(model);
1355
+ const doc = new import_editor3.EditorDocument(model);
576
1356
  const losslessCrop = quantizeColors === void 0 ? void 0 : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);
577
1357
  const pages = losslessCrop === void 0 ? [await renderAtlasPage(crops, quantizeColors)] : [
578
1358
  await renderAtlasPage(
@@ -589,15 +1369,15 @@ async function autoRigFromLayers(input) {
589
1369
  }
590
1370
  const partTextureAssignments = pages.flatMap(
591
1371
  ({ crops: pageCrops, layout }) => pageCrops.flatMap((crop) => {
592
- const placement2 = layout.placements.find((p) => p.id === crop.id);
593
- if (placement2 === void 0) {
1372
+ const placement3 = layout.placements.find((p) => p.id === crop.id);
1373
+ if (placement3 === void 0) {
594
1374
  throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
595
1375
  }
596
- const uv = (0, import_editor2.uvRectFor)(placement2, {
1376
+ const uv = (0, import_editor3.uvRectFor)(placement3, {
597
1377
  width: layout.pageWidth,
598
1378
  height: layout.pageHeight
599
1379
  });
600
- return (0, import_editor2.partIdsOfRole)(crop.id).map((partId) => ({ partId, uv }));
1380
+ return (0, import_editor3.partIdsOfRole)(crop.id).map((partId) => ({ partId, uv }));
601
1381
  })
602
1382
  );
603
1383
  doc.applyAtlas({
@@ -608,12 +1388,13 @@ async function autoRigFromLayers(input) {
608
1388
  if (losslessCrop !== void 0) {
609
1389
  patched = structuredClone(patched);
610
1390
  patched.textures = pages.map((p) => ({ source: p.dataUri }));
611
- for (const partId of (0, import_editor2.partIdsOfRole)(losslessCrop.id)) {
1391
+ for (const partId of (0, import_editor3.partIdsOfRole)(losslessCrop.id)) {
612
1392
  patched.parts.find((p) => p.id === partId).texture.index = 1;
613
1393
  }
614
1394
  }
615
- const finalModel = (0, import_format.parseIkiModel)(patched);
1395
+ const finalModel = (0, import_format7.parseIkiModel)(patched);
616
1396
  writeFileAtomic(outPath, JSON.stringify(finalModel));
1397
+ const folds = checkModelFolds(finalModel);
617
1398
  return {
618
1399
  ok: true,
619
1400
  path: outPath,
@@ -625,7 +1406,8 @@ async function autoRigFromLayers(input) {
625
1406
  ...headEdges === void 0 ? {} : { headEdges },
626
1407
  ...strandEdges === void 0 ? {} : { strandEdges },
627
1408
  ...noseCore === void 0 ? {} : { noseCore },
628
- ...turn === void 0 ? {} : { turn }
1409
+ ...turn === void 0 ? {} : { turn },
1410
+ folds
629
1411
  };
630
1412
  } catch (err) {
631
1413
  if (err instanceof AutoRigInputError)
@@ -638,10 +1420,10 @@ async function autoRigFromLayers(input) {
638
1420
  var import_node_fs3 = __toESM(require("fs"));
639
1421
  var import_node_path7 = __toESM(require("path"));
640
1422
  var import_sharp4 = __toESM(require("sharp"));
641
- var import_editor11 = require("@ikijs/editor");
1423
+ var import_editor12 = require("@ikijs/editor");
642
1424
 
643
1425
  // src/trim.ts
644
- var import_editor3 = require("@ikijs/editor");
1426
+ var import_editor4 = require("@ikijs/editor");
645
1427
  var TRIM_THRESHOLD = 12;
646
1428
  var STRAY_SPECK_FRACTION = 0.01;
647
1429
  function luma(rgba, i) {
@@ -670,7 +1452,7 @@ function boxWithoutStraySpecks(rgba, W, H) {
670
1452
  while (depth > 0) {
671
1453
  const p = stack[--depth];
672
1454
  size++;
673
- if (rgba[p * 4 + 3] >= import_editor3.ALPHA_OPAQUE) opaque = true;
1455
+ if (rgba[p * 4 + 3] >= import_editor4.ALPHA_OPAQUE) opaque = true;
674
1456
  const px2 = p % W;
675
1457
  const py = (p - px2) / W;
676
1458
  setLeft = Math.min(setLeft, px2);
@@ -712,7 +1494,7 @@ var import_node_path6 = __toESM(require("path"));
712
1494
 
713
1495
  // src/measure-arms.ts
714
1496
  var import_node_path3 = __toESM(require("path"));
715
- var import_editor4 = require("@ikijs/editor");
1497
+ var import_editor5 = require("@ikijs/editor");
716
1498
  var ARM_ROLES = ["arm_L", "arm_R"];
717
1499
  var CAP_OVERLAP = 0.5;
718
1500
  var px = (v) => `${Number(v.toFixed(1))}`;
@@ -741,7 +1523,7 @@ async function armWarnings(absDir, layers) {
741
1523
  continue;
742
1524
  }
743
1525
  if (set === void 0) {
744
- const measurer = (0, import_editor4.createLayerSetMeasurer)({
1526
+ const measurer = (0, import_editor5.createLayerSetMeasurer)({
745
1527
  width: body.canvasW,
746
1528
  height: body.canvasH
747
1529
  });
@@ -749,12 +1531,12 @@ async function armWarnings(absDir, layers) {
749
1531
  }
750
1532
  let g;
751
1533
  try {
752
- g = (0, import_editor4.armGeometry)(
1534
+ g = (0, import_editor5.armGeometry)(
753
1535
  await measured(set.measurer, absDir, arm),
754
1536
  set.body.bbox.x + set.body.bbox.w / 2 - body.canvasW / 2
755
1537
  );
756
1538
  } catch (err) {
757
- if (err instanceof import_editor4.LayerGeometryError) {
1539
+ if (err instanceof import_editor5.LayerGeometryError) {
758
1540
  warnings.push(
759
1541
  `${arm}: ${err.message} \u2014 auto_rig_from_layers refuses it. Regenerate arm.png drawn hanging, shoulder at the top. Billed.`
760
1542
  );
@@ -782,7 +1564,7 @@ function capWarning(arm, g, body) {
782
1564
  }
783
1565
 
784
1566
  // src/measure-forearm-pose.ts
785
- var import_editor5 = require("@ikijs/editor");
1567
+ var import_editor6 = require("@ikijs/editor");
786
1568
  var POSE_ROLES = ["forearm_pose_L", "forearm_pose_R"];
787
1569
  var ARM_OF = {
788
1570
  forearm_pose_L: "arm_L",
@@ -816,7 +1598,7 @@ async function forearmPoseWarnings(absDir, layers) {
816
1598
  continue;
817
1599
  }
818
1600
  if (layers.body === void 0) continue;
819
- const measurer = (0, import_editor5.createLayerSetMeasurer)({
1601
+ const measurer = (0, import_editor6.createLayerSetMeasurer)({
820
1602
  width: stats.canvasW,
821
1603
  height: stats.canvasH
822
1604
  });
@@ -824,12 +1606,12 @@ async function forearmPoseWarnings(absDir, layers) {
824
1606
  let armLayer;
825
1607
  try {
826
1608
  armLayer = await measured(measurer, absDir, arm);
827
- a = (0, import_editor5.armGeometry)(armLayer, arm === "arm_R" ? Infinity : -Infinity);
1609
+ a = (0, import_editor6.armGeometry)(armLayer, arm === "arm_R" ? Infinity : -Infinity);
828
1610
  } catch (err) {
829
- if (err instanceof import_editor5.LayerGeometryError) continue;
1611
+ if (err instanceof import_editor6.LayerGeometryError) continue;
830
1612
  throw err;
831
1613
  }
832
- const b = (0, import_editor5.forearmPoseGeometry)(await measured(measurer, absDir, pose));
1614
+ const b = (0, import_editor6.forearmPoseGeometry)(await measured(measurer, absDir, pose));
833
1615
  warnings.push(...jointWarnings(pose, arm, stats, a, armLayer, b));
834
1616
  }
835
1617
  return warnings;
@@ -869,11 +1651,11 @@ function jointWarnings(pose, arm, stats, a, armLayer, b) {
869
1651
 
870
1652
  // src/measure-lips.ts
871
1653
  var import_node_path4 = __toESM(require("path"));
872
- var import_editor7 = require("@ikijs/editor");
1654
+ var import_editor8 = require("@ikijs/editor");
873
1655
 
874
1656
  // src/compose-lips.ts
875
1657
  var import_sharp2 = __toESM(require("sharp"));
876
- var import_editor6 = require("@ikijs/editor");
1658
+ var import_editor7 = require("@ikijs/editor");
877
1659
  var KEYED_SRC = "mouth_keyed.png";
878
1660
  var INTERIOR_SRC = "mouth_interior.png";
879
1661
  var KEY_CANDIDATE = 0.5;
@@ -971,7 +1753,7 @@ function keyGreen(rgba, W, H) {
971
1753
  let candidates = 0;
972
1754
  for (let p = 0; p < n; p++) {
973
1755
  const i = p * 4;
974
- if (rgba[i + 3] < import_editor6.ALPHA_OPAQUE) continue;
1756
+ if (rgba[i + 3] < import_editor7.ALPHA_OPAQUE) continue;
975
1757
  const excess = (rgba[i + 1] - Math.max(rgba[i], rgba[i + 2])) / 255;
976
1758
  if (excess < KEY_CANDIDATE) continue;
977
1759
  candidates++;
@@ -998,7 +1780,7 @@ function keyGreen(rgba, W, H) {
998
1780
  const dg = rgba[i + 1] - G[1];
999
1781
  const db = rgba[i + 2] - G[2];
1000
1782
  const green = dr * dr + dg * dg + db * db <= KEY_FILL_DIST * KEY_FILL_DIST;
1001
- if (rgba[i + 3] < import_editor6.ALPHA_OPAQUE) {
1783
+ if (rgba[i + 3] < import_editor7.ALPHA_OPAQUE) {
1002
1784
  if (green) out[i + 3] = 0;
1003
1785
  } else if (green) {
1004
1786
  fill[p] = 1;
@@ -1174,7 +1956,7 @@ async function prepInterior(rgba, W, H) {
1174
1956
  for (let y = box.y; y < box.y + box.h; y++) {
1175
1957
  for (let x = box.x; x < box.x + box.w; x++) {
1176
1958
  const i = (y * cw + x) * 4;
1177
- if (crop[i + 3] < import_editor6.ALPHA_OPAQUE) continue;
1959
+ if (crop[i + 3] < import_editor7.ALPHA_OPAQUE) continue;
1178
1960
  count++;
1179
1961
  for (let c = 0; c < 3; c++) all[c] += crop[i + c];
1180
1962
  if (luma(crop, i) < CAVITY_LUMA) {
@@ -1197,7 +1979,7 @@ function enclosedHole(frame, w, h) {
1197
1979
  const stack = new Int32Array(n);
1198
1980
  let depth = 0;
1199
1981
  const seed = (p) => {
1200
- if (!outside[p] && alpha(p) < import_editor6.ALPHA_OPAQUE) {
1982
+ if (!outside[p] && alpha(p) < import_editor7.ALPHA_OPAQUE) {
1201
1983
  outside[p] = 1;
1202
1984
  stack[depth++] = p;
1203
1985
  }
@@ -1220,7 +2002,7 @@ function enclosedHole(frame, w, h) {
1220
2002
  }
1221
2003
  const mask = new Uint8Array(n);
1222
2004
  for (let p = 0; p < n; p++) {
1223
- if (alpha(p) < import_editor6.ALPHA_OPAQUE && !outside[p]) mask[p] = 1;
2005
+ if (alpha(p) < import_editor7.ALPHA_OPAQUE && !outside[p]) mask[p] = 1;
1224
2006
  }
1225
2007
  const { label, sizes, boxes } = components(mask, w, h);
1226
2008
  const main2 = largest(sizes);
@@ -1247,7 +2029,7 @@ function enclosedHole(frame, w, h) {
1247
2029
  return { label, main: main2, box };
1248
2030
  }
1249
2031
  function measureLips(layers, w, h) {
1250
- const measurer = (0, import_editor6.createLayerSetMeasurer)({ width: w, height: h });
2032
+ const measurer = (0, import_editor7.createLayerSetMeasurer)({ width: w, height: h });
1251
2033
  return new Map(
1252
2034
  Object.entries(layers).map(([role, rgba]) => [
1253
2035
  role,
@@ -1265,8 +2047,8 @@ function assertFoldContract(layers, w, h) {
1265
2047
  }
1266
2048
  byRole.set(role, layer);
1267
2049
  }
1268
- const opening = (0, import_editor6.mouthOpening)(byRole);
1269
- const runs = (0, import_editor6.columnRuns)(byRole.get("mouth_inner"));
2050
+ const opening = (0, import_editor7.mouthOpening)(byRole);
2051
+ const runs = (0, import_editor7.columnRuns)(byRole.get("mouth_inner"));
1270
2052
  for (let col = opening.x0; col <= opening.x1; col++) {
1271
2053
  const c = opening.at(col);
1272
2054
  const why = !runs.has(col) ? "has no interior run" : c.Tu > c.T ? `has a gap between the line and the interior (Tu ${c.Tu} > T ${c.T})` : c.T > c.lineTop || c.lineH <= 0 ? `has no line above the interior (T ${c.T}, line top ${c.lineTop})` : c.Bl < c.Bb ? `has a gap between the interior and the skin (Bl ${c.Bl} < Bb ${c.Bb})` : null;
@@ -1296,18 +2078,18 @@ async function splitLipSet(keyedPng, w, h, interior) {
1296
2078
  }
1297
2079
  const centre = Math.round((hb.x0 + hb.x1) / 2);
1298
2080
  let stroke = 0;
1299
- while (top[centre] - 1 - stroke >= 0 && alpha((top[centre] - 1 - stroke) * w + centre) >= import_editor6.ALPHA_OPAQUE)
2081
+ while (top[centre] - 1 - stroke >= 0 && alpha((top[centre] - 1 - stroke) * w + centre) >= import_editor7.ALPHA_OPAQUE)
1300
2082
  stroke++;
1301
2083
  const bandCap = BAND_CAP * Math.max(1, stroke);
1302
2084
  const skinRow = new Int32Array(w).fill(-1);
1303
2085
  const inM = new Uint8Array(n);
1304
2086
  for (let x = hb.x0; x <= hb.x1; x++) {
1305
2087
  let y = bot[x];
1306
- while (y < h && y - bot[x] < bandCap && alpha(y * w + x) >= import_editor6.ALPHA_OPAQUE && luma(frame, (y * w + x) * 4) < BAND_LUMA)
2088
+ while (y < h && y - bot[x] < bandCap && alpha(y * w + x) >= import_editor7.ALPHA_OPAQUE && luma(frame, (y * w + x) * 4) < BAND_LUMA)
1307
2089
  y++;
1308
2090
  for (let k = top[x]; k < y; k++) inM[k * w + x] = 1;
1309
2091
  let r = y;
1310
- while (r < h && alpha(r * w + x) < import_editor6.ALPHA_OPAQUE) r++;
2092
+ while (r < h && alpha(r * w + x) < import_editor7.ALPHA_OPAQUE) r++;
1311
2093
  if (r < h) {
1312
2094
  skinRow[x] = r;
1313
2095
  inM[r * w + x] = 1;
@@ -1317,7 +2099,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
1317
2099
  for (let y = 0; y < h; y++) {
1318
2100
  for (let x = 0; x < w; x++) {
1319
2101
  const p = y * w + x;
1320
- if (inM[p] || alpha(p) < import_editor6.ALPHA_OPAQUE) continue;
2102
+ if (inM[p] || alpha(p) < import_editor7.ALPHA_OPAQUE) continue;
1321
2103
  if (top[x] >= 0 && y < top[x]) continue;
1322
2104
  if (x > 0 && inM[p - 1] || x < w - 1 && inM[p + 1]) grown[p] = 1;
1323
2105
  }
@@ -1327,7 +2109,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
1327
2109
  if (x < 0 || x >= w) continue;
1328
2110
  let first = 0;
1329
2111
  while (first < h && !(grown[first * w + x] && !inM[first * w + x])) first++;
1330
- if (first > 0 && first < h && alpha((first - 1) * w + x) >= import_editor6.ALPHA_OPAQUE)
2112
+ if (first > 0 && first < h && alpha((first - 1) * w + x) >= import_editor7.ALPHA_OPAQUE)
1331
2113
  wall[x] = 1;
1332
2114
  }
1333
2115
  const gx = hb.x0 - 1;
@@ -1354,7 +2136,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
1354
2136
  if (inOpening && skinRow[x] >= 0 && y >= skinRow[x]) copy(lower, p);
1355
2137
  if (!grown[p]) {
1356
2138
  const a = alpha(p);
1357
- if (a >= import_editor6.ALPHA_OPAQUE && a < 255 && besideHole(p, x, y)) {
2139
+ if (a >= import_editor7.ALPHA_OPAQUE && a < 255 && besideHole(p, x, y)) {
1358
2140
  inner.set(interior.cavity, p * 4);
1359
2141
  inner[p * 4 + 3] = 255 - a;
1360
2142
  }
@@ -1419,7 +2201,7 @@ async function restShiftOf(layers, width, height) {
1419
2201
  }
1420
2202
  byRole.set(role, layer);
1421
2203
  }
1422
- return (0, import_editor6.mouthRestShift)(byRole);
2204
+ return (0, import_editor7.mouthRestShift)(byRole);
1423
2205
  }
1424
2206
  async function closedLips(upper, lower, shift, left, top) {
1425
2207
  const shut = async (png, role) => {
@@ -1469,7 +2251,7 @@ async function closedLips(upper, lower, shift, left, top) {
1469
2251
  }
1470
2252
 
1471
2253
  // src/measure-lips.ts
1472
- var isLipLayerRole = (role) => import_editor7.LIP_ROLES.includes(role) || (0, import_editor7.isLipInsideRole)(role);
2254
+ var isLipLayerRole = (role) => import_editor8.LIP_ROLES.includes(role) || (0, import_editor8.isLipInsideRole)(role);
1473
2255
  var MIN_OPENING_ROWS = 8;
1474
2256
  var MIN_LINE_ROWS = 2;
1475
2257
  var GREEN_EXCESS = 40;
@@ -1477,8 +2259,8 @@ var INTERIOR_GAP_FRACTION = 0.05;
1477
2259
  var columns = (cols) => `${cols.length} column${cols.length === 1 ? "" : "s"} (first at x=${cols[0]})`;
1478
2260
  async function lipWarnings(absDir, layers) {
1479
2261
  const warnings = [];
1480
- const present = import_editor7.LIP_ROLES.filter((role) => layers[role] !== void 0);
1481
- const inside = import_editor7.LIP_INSIDE_ROLES.filter((role) => layers[role] !== void 0);
2262
+ const present = import_editor8.LIP_ROLES.filter((role) => layers[role] !== void 0);
2263
+ const inside = import_editor8.LIP_INSIDE_ROLES.filter((role) => layers[role] !== void 0);
1482
2264
  if (present.length === 0) {
1483
2265
  if (inside.length > 0) {
1484
2266
  warnings.push(
@@ -1495,8 +2277,8 @@ async function lipWarnings(absDir, layers) {
1495
2277
  `${present.join("/")}: the lip set cannot be mixed with ${legacy.join("/")} \u2014 auto_rig_from_layers refuses it. Remove one route: compose again with only mouth_keyed.png + mouth_interior.png, or without them.`
1496
2278
  );
1497
2279
  }
1498
- if (present.length < import_editor7.LIP_ROLES.length) {
1499
- const missing = import_editor7.LIP_ROLES.filter((role) => layers[role] === void 0);
2280
+ if (present.length < import_editor8.LIP_ROLES.length) {
2281
+ const missing = import_editor8.LIP_ROLES.filter((role) => layers[role] === void 0);
1500
2282
  warnings.push(
1501
2283
  `${present.join("/")}: partial lip set, missing ${missing.join("/")} \u2014 auto_rig_from_layers refuses it. Compose mouth_keyed.png + mouth_interior.png together, which cuts all three.`
1502
2284
  );
@@ -1527,18 +2309,18 @@ async function lipWarnings(absDir, layers) {
1527
2309
  );
1528
2310
  }
1529
2311
  }
1530
- const measurer = (0, import_editor7.createLayerSetMeasurer)({
2312
+ const measurer = (0, import_editor8.createLayerSetMeasurer)({
1531
2313
  width: inner.canvasW,
1532
2314
  height: inner.canvasH
1533
2315
  });
1534
2316
  const set = /* @__PURE__ */ new Map();
1535
2317
  const green = [];
1536
- for (const role of import_editor7.LIP_ROLES) {
2318
+ for (const role of import_editor8.LIP_ROLES) {
1537
2319
  const fileName = `${role}.png`;
1538
2320
  const { rgba } = await decodePng(import_node_path4.default.join(absDir, fileName));
1539
2321
  set.set(role, measurer.add({ role, fileName, rgba }));
1540
2322
  for (let i = 0; i < rgba.length; i += 4) {
1541
- if (rgba[i + 3] >= import_editor7.ALPHA_OPAQUE && rgba[i + 1] - Math.max(rgba[i], rgba[i + 2]) > GREEN_EXCESS) {
2323
+ if (rgba[i + 3] >= import_editor8.ALPHA_OPAQUE && rgba[i + 1] - Math.max(rgba[i], rgba[i + 2]) > GREEN_EXCESS) {
1542
2324
  green.push(role);
1543
2325
  break;
1544
2326
  }
@@ -1546,15 +2328,15 @@ async function lipWarnings(absDir, layers) {
1546
2328
  }
1547
2329
  let opening;
1548
2330
  try {
1549
- opening = (0, import_editor7.mouthOpening)(set);
2331
+ opening = (0, import_editor8.mouthOpening)(set);
1550
2332
  } catch (err) {
1551
- if (err instanceof import_editor7.LayerGeometryError) {
2333
+ if (err instanceof import_editor8.LayerGeometryError) {
1552
2334
  warnings.push(err.message);
1553
2335
  return { warnings };
1554
2336
  }
1555
2337
  throw err;
1556
2338
  }
1557
- const innerRuns = (0, import_editor7.columnRuns)(set.get("mouth_inner"));
2339
+ const innerRuns = (0, import_editor8.columnRuns)(set.get("mouth_inner"));
1558
2340
  const noInterior = [];
1559
2341
  const gap = [];
1560
2342
  const noLine = [];
@@ -1640,8 +2422,8 @@ async function lipWarnings(absDir, layers) {
1640
2422
 
1641
2423
  // src/measure-turn.ts
1642
2424
  var import_node_path5 = __toESM(require("path"));
1643
- var import_editor8 = require("@ikijs/editor");
1644
2425
  var import_editor9 = require("@ikijs/editor");
2426
+ var import_editor10 = require("@ikijs/editor");
1645
2427
  var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
1646
2428
  var IRIS_V_MIN = 0.18;
1647
2429
  var IRIS_V_MAX = 0.95;
@@ -1791,7 +2573,7 @@ async function measureTurnImage(filePath, iris) {
1791
2573
  let transparent = false;
1792
2574
  if (hasAlpha) {
1793
2575
  for (let i = 0; i < n; i++) {
1794
- if (rgba[i * 4 + 3] < import_editor8.ALPHA_OPAQUE) {
2576
+ if (rgba[i * 4 + 3] < import_editor9.ALPHA_OPAQUE) {
1795
2577
  transparent = true;
1796
2578
  break;
1797
2579
  }
@@ -1802,7 +2584,7 @@ async function measureTurnImage(filePath, iris) {
1802
2584
  const fg = new Uint8Array(n);
1803
2585
  const value = new Float32Array(n);
1804
2586
  for (let i = 0; i < n; i++) {
1805
- if (rgba[i * 4 + 3] < import_editor8.ALPHA_OPAQUE) continue;
2587
+ if (rgba[i * 4 + 3] < import_editor9.ALPHA_OPAQUE) continue;
1806
2588
  const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);
1807
2589
  if (maskMode === "alpha") {
1808
2590
  fg[i] = 1;
@@ -1868,12 +2650,12 @@ async function measureTurnImage(filePath, iris) {
1868
2650
  }
1869
2651
  const [irisL, irisR] = best.pair;
1870
2652
  const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);
1871
- const { left, right } = (0, import_editor8.foregroundSpan)(
2653
+ const { left, right } = (0, import_editor9.foregroundSpan)(
1872
2654
  fg,
1873
2655
  width,
1874
2656
  height,
1875
- eyeRow - import_editor8.HEAD_BAND,
1876
- eyeRow + import_editor8.HEAD_BAND
2657
+ eyeRow - import_editor9.HEAD_BAND,
2658
+ eyeRow + import_editor9.HEAD_BAND
1877
2659
  );
1878
2660
  if (right <= left) {
1879
2661
  throw new AutoRigInputError(
@@ -1897,7 +2679,7 @@ async function measureTurnImage(filePath, iris) {
1897
2679
  left,
1898
2680
  right,
1899
2681
  cx: (left + right) / 2,
1900
- half: (0, import_editor8.headHalfOf)({ left, right })
2682
+ half: (0, import_editor9.headHalfOf)({ left, right })
1901
2683
  },
1902
2684
  pairCx: (irisL.cx + irisR.cx) / 2,
1903
2685
  eyeGap: irisR.cx - irisL.cx
@@ -2088,7 +2870,7 @@ function noseSpeckWarning({ core, part }, source) {
2088
2870
  `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,
2089
2871
  `auto_rig_from_layers turns and tilts the nose about its whole crop instead`
2090
2872
  ];
2091
- return `nose: ${found} \u2014 under ${import_editor9.SPECK_CORE_FRACTION} of its width or height, a speck: a lone nostril mark or highlight at alpha >= 128, not the drawing, so ${consequence}. Regenerate the nose with its shading painted denser, so the drawing itself reaches alpha 128. Billed.`;
2873
+ return `nose: ${found} \u2014 under ${import_editor10.SPECK_CORE_FRACTION} of its width or height, a speck: a lone nostril mark or highlight at alpha >= 128, not the drawing, so ${consequence}. Regenerate the nose with its shading painted denser, so the drawing itself reaches alpha 128. Billed.`;
2092
2874
  }
2093
2875
  async function lashOffSclera(eyePath, lashPath) {
2094
2876
  const eye = await decodePng(eyePath);
@@ -2225,10 +3007,10 @@ async function measureDir(absDir, noseSpeck) {
2225
3007
  warnings.push(noseSpeckWarning(noseSpeck, "compose"));
2226
3008
  } else if (layers.nose !== void 0) {
2227
3009
  const nose = await decodePng(import_node_path6.default.join(absDir, "nose.png"));
2228
- const core = (0, import_editor9.denseCoreOf)(nose.rgba, nose.width, nose.height);
3010
+ const core = (0, import_editor10.denseCoreOf)(nose.rgba, nose.width, nose.height);
2229
3011
  if (core !== null) {
2230
3012
  const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);
2231
- if ((0, import_editor9.isSpeckCore)(core, crop))
3013
+ if ((0, import_editor10.isSpeckCore)(core, crop))
2232
3014
  warnings.push(noseSpeckWarning({ core, part: crop }, "layer"));
2233
3015
  }
2234
3016
  }
@@ -2299,12 +3081,12 @@ function formatMeasureReport(result) {
2299
3081
 
2300
3082
  // src/compose-arms.ts
2301
3083
  var import_sharp3 = __toESM(require("sharp"));
2302
- var import_editor10 = require("@ikijs/editor");
3084
+ var import_editor11 = require("@ikijs/editor");
2303
3085
  var ARM_WIDTH = 0.4;
2304
3086
  var SHOULDER_DROP = 0.12;
2305
3087
  async function armPlacement(role, cfg, part, body) {
2306
3088
  const { data } = await (0, import_sharp3.default)(part.buf).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2307
- const layer = (0, import_editor10.createLayerSetMeasurer)({ width: part.w, height: part.h }).add({
3089
+ const layer = (0, import_editor11.createLayerSetMeasurer)({ width: part.w, height: part.h }).add({
2308
3090
  role,
2309
3091
  fileName: "arm.png",
2310
3092
  rgba: data
@@ -2316,9 +3098,9 @@ async function armPlacement(role, cfg, part, body) {
2316
3098
  }
2317
3099
  let g;
2318
3100
  try {
2319
- g = (0, import_editor10.armGeometry)(layer, role === "arm_R" ? Infinity : -Infinity);
3101
+ g = (0, import_editor11.armGeometry)(layer, role === "arm_R" ? Infinity : -Infinity);
2320
3102
  } catch (err) {
2321
- if (err instanceof import_editor10.LayerGeometryError) {
3103
+ if (err instanceof import_editor11.LayerGeometryError) {
2322
3104
  throw new AutoRigInputError(`layout.${role}: ${err.message}`);
2323
3105
  }
2324
3106
  throw err;
@@ -2345,7 +3127,7 @@ async function armPlacement(role, cfg, part, body) {
2345
3127
  }
2346
3128
  async function poseGeometryOf(role, png, size, when) {
2347
3129
  const { data } = await (0, import_sharp3.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2348
- const layer = (0, import_editor10.createLayerSetMeasurer)({
3130
+ const layer = (0, import_editor11.createLayerSetMeasurer)({
2349
3131
  width: size.w,
2350
3132
  height: size.h
2351
3133
  }).add({ role, fileName: "forearm_pose.png", rgba: data });
@@ -2354,7 +3136,7 @@ async function poseGeometryOf(role, png, size, when) {
2354
3136
  `layout.${role}: forearm_pose.png is empty after alpha threshold${when}`
2355
3137
  );
2356
3138
  }
2357
- return (0, import_editor10.forearmPoseGeometry)(layer);
3139
+ return (0, import_editor11.forearmPoseGeometry)(layer);
2358
3140
  }
2359
3141
  async function forearmPoseWidth(role, trimmed, elbowRun) {
2360
3142
  const g = await poseGeometryOf(role, trimmed.data, trimmed, "");
@@ -2572,12 +3354,12 @@ function resolveLayout(overrides, canvas) {
2572
3354
  const face = { ...resolved.face, ...sets.get("face") };
2573
3355
  resolved.face = face;
2574
3356
  const base = DEFAULT_LAYOUT.face;
2575
- const scale = face.w / base.w;
2576
- const x = (cx) => face.cx + (cx - base.cx) * scale;
2577
- const w = (width) => Math.max(1, Math.round(width * scale));
3357
+ const scale2 = face.w / base.w;
3358
+ const x = (cx) => face.cx + (cx - base.cx) * scale2;
3359
+ const w = (width) => Math.max(1, Math.round(width * scale2));
2578
3360
  for (const role of FACE_FEATURES) {
2579
3361
  const d = DEFAULT_LAYOUT[role];
2580
- const cy = face.cy + (d.cy - base.cy) * scale;
3362
+ const cy = face.cy + (d.cy - base.cy) * scale2;
2581
3363
  resolved[role] = { ...d, cx: x(d.cx), cy, w: w(d.w), ...sets.get(role) };
2582
3364
  }
2583
3365
  const nose = DEFAULT_LAYOUT.nose;
@@ -2630,18 +3412,18 @@ function keyWhiteToAlpha(rgba) {
2630
3412
  async function coreAndBoundsOf(png) {
2631
3413
  const { data, info } = await (0, import_sharp4.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2632
3414
  return {
2633
- core: (0, import_editor9.denseCoreOf)(data, info.width, info.height),
3415
+ core: (0, import_editor10.denseCoreOf)(data, info.width, info.height),
2634
3416
  bounds: { x: 0, y: 0, w: info.width, h: info.height }
2635
3417
  };
2636
3418
  }
2637
3419
  async function hasCoverage(png) {
2638
3420
  const { data, info } = await (0, import_sharp4.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2639
- return (0, import_editor11.detectAlphaBbox)(data, info.width, info.height) !== null;
3421
+ return (0, import_editor12.detectAlphaBbox)(data, info.width, info.height) !== null;
2640
3422
  }
2641
3423
  async function noseSizingOf(png) {
2642
3424
  const { core, bounds } = await coreAndBoundsOf(png);
2643
3425
  if (core === null) return { box: bounds, whole: true };
2644
- if ((0, import_editor9.isSpeckCore)(core, bounds)) {
3426
+ if ((0, import_editor10.isSpeckCore)(core, bounds)) {
2645
3427
  return {
2646
3428
  box: bounds,
2647
3429
  whole: true,
@@ -2718,7 +3500,7 @@ function assertOnCanvas(source, w, h, left, top, canvas) {
2718
3500
  );
2719
3501
  }
2720
3502
  }
2721
- function placement(role, cfg, w, h, canvas) {
3503
+ function placement2(role, cfg, w, h, canvas) {
2722
3504
  const left = Math.round(cfg.cx - w / 2);
2723
3505
  const top = Math.round(cfg.cy - h / 2);
2724
3506
  assertOnCanvas(`layout.${role}.cx/cy`, w, h, left, top, canvas);
@@ -2763,7 +3545,7 @@ function detachedAboveWhite(rgba, W, H) {
2763
3545
  for (let p = 0; p < n; p++) {
2764
3546
  const alpha = rgba[p * 4 + 3];
2765
3547
  if (alpha > 0 && luma(rgba, p * 4) >= EYE_LASH_LUMA)
2766
- ink[p] = alpha >= import_editor11.ALPHA_OPAQUE ? 2 : 1;
3548
+ ink[p] = alpha >= import_editor12.ALPHA_OPAQUE ? 2 : 1;
2767
3549
  }
2768
3550
  const label = new Int32Array(n).fill(-1);
2769
3551
  const stack = new Int32Array(n);
@@ -2988,7 +3770,7 @@ async function composeLayersFromParts(input) {
2988
3770
  part2.h,
2989
3771
  lips.interior
2990
3772
  );
2991
- const { left: left2, top: top2 } = placement(role, cfg2, part2.w, part2.h, canvas);
3773
+ const { left: left2, top: top2 } = placement2(role, cfg2, part2.w, part2.h, canvas);
2992
3774
  lipSplit = { split: split2, w: part2.w, h: part2.h, left: left2, top: top2 };
2993
3775
  placed.push({
2994
3776
  role,
@@ -3007,7 +3789,7 @@ async function composeLayersFromParts(input) {
3007
3789
  lip_lower: split2.lower,
3008
3790
  lip_upper: split2.upper
3009
3791
  }[role];
3010
- if ((0, import_editor11.isLipInsideRole)(role) && !await hasCoverage(buf)) {
3792
+ if ((0, import_editor12.isLipInsideRole)(role) && !await hasCoverage(buf)) {
3011
3793
  skipped.push(role);
3012
3794
  continue;
3013
3795
  }
@@ -3145,7 +3927,7 @@ async function composeLayersFromParts(input) {
3145
3927
  canvas
3146
3928
  ));
3147
3929
  } else {
3148
- ({ left, top } = placement(key, layout[key], part.w, part.h, canvas));
3930
+ ({ left, top } = placement2(key, layout[key], part.w, part.h, canvas));
3149
3931
  }
3150
3932
  if (role === "lash_L" || role === "lash_R") {
3151
3933
  const eyeRole = role === "lash_L" ? "eye_L" : "eye_R";
@@ -3202,7 +3984,7 @@ async function composeLayersFromParts(input) {
3202
3984
  });
3203
3985
  }
3204
3986
  const restInput = (role, buf) => {
3205
- if (role === "mouth_inner" || (0, import_editor11.isLipInsideRole)(role)) return null;
3987
+ if (role === "mouth_inner" || (0, import_editor12.isLipInsideRole)(role)) return null;
3206
3988
  if (closed === void 0) return buf;
3207
3989
  if (role === "lip_upper") return closed.upper;
3208
3990
  if (role === "lip_lower") return closed.lower;
@@ -3269,9 +4051,523 @@ async function composeLayersFromParts(input) {
3269
4051
  }
3270
4052
  }
3271
4053
 
4054
+ // src/render-poses.ts
4055
+ var import_node_fs5 = require("fs");
4056
+ var import_node_path9 = __toESM(require("path"));
4057
+ var import_format8 = require("@ikijs/format");
4058
+
4059
+ // src/render-browser.ts
4060
+ var import_node_child_process = require("child_process");
4061
+ var import_node_fs4 = __toESM(require("fs"));
4062
+ var import_node_os = __toESM(require("os"));
4063
+ var import_node_path8 = __toESM(require("path"));
4064
+ var NO_BROWSER_MESSAGE = "render_poses needs a Chromium-based browser and found none. Install Google Chrome, Microsoft Edge or Chromium, or set CHROME_PATH to its executable.";
4065
+ var DARWIN_CANDIDATES = [
4066
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
4067
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
4068
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
4069
+ ];
4070
+ var LINUX_CANDIDATES = [
4071
+ "/usr/bin/google-chrome",
4072
+ "/usr/bin/google-chrome-stable",
4073
+ "/usr/bin/chromium",
4074
+ "/usr/bin/chromium-browser",
4075
+ "/usr/bin/microsoft-edge",
4076
+ "/snap/bin/chromium"
4077
+ ];
4078
+ var WIN32_ROOTS = ["PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"];
4079
+ var WIN32_SUFFIXES = [
4080
+ ["Google", "Chrome", "Application", "chrome.exe"],
4081
+ ["Microsoft", "Edge", "Application", "msedge.exe"]
4082
+ ];
4083
+ var CLOSE_GRACE_MS = 2e3;
4084
+ var DEFAULT_TIMEOUT_MS = 3e4;
4085
+ var BROWSER_CLOSE_MS = 1e3;
4086
+ function isExecutableFile(file) {
4087
+ try {
4088
+ if (!import_node_fs4.default.statSync(file).isFile()) return false;
4089
+ import_node_fs4.default.accessSync(file, import_node_fs4.default.constants.X_OK);
4090
+ return true;
4091
+ } catch {
4092
+ return false;
4093
+ }
4094
+ }
4095
+ function findBrowser({
4096
+ env = process.env,
4097
+ platform = process.platform,
4098
+ isExecutable = isExecutableFile
4099
+ } = {}) {
4100
+ const override = env.CHROME_PATH;
4101
+ if (override) {
4102
+ if (!isExecutable(override)) {
4103
+ throw new AutoRigInputError(
4104
+ `CHROME_PATH is not an executable file: ${override}`
4105
+ );
4106
+ }
4107
+ return override;
4108
+ }
4109
+ let candidates;
4110
+ if (platform === "darwin") candidates = DARWIN_CANDIDATES;
4111
+ else if (platform === "win32") {
4112
+ candidates = [];
4113
+ for (const suffix of WIN32_SUFFIXES) {
4114
+ for (const root of WIN32_ROOTS) {
4115
+ const base = env[root];
4116
+ if (base) candidates.push(import_node_path8.default.win32.join(base, ...suffix));
4117
+ }
4118
+ }
4119
+ } else candidates = LINUX_CANDIDATES;
4120
+ return candidates.find((file) => isExecutable(file));
4121
+ }
4122
+ function within(promise, ms, what, detail) {
4123
+ let timer;
4124
+ const timeout = new Promise((_, reject) => {
4125
+ timer = setTimeout(
4126
+ () => reject(
4127
+ new Error(
4128
+ `${what} timed out after ${ms} ms${detail ? `: ${detail()}` : ""}`
4129
+ )
4130
+ ),
4131
+ ms
4132
+ );
4133
+ });
4134
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
4135
+ }
4136
+ function connectCdp(url, timeoutMs) {
4137
+ const socket = new WebSocket(url);
4138
+ let nextId = 0;
4139
+ let socketClosed = false;
4140
+ const pending = /* @__PURE__ */ new Map();
4141
+ socket.addEventListener("message", (event) => {
4142
+ const message = JSON.parse(String(event.data));
4143
+ const entry = pending.get(message.id);
4144
+ if (!entry) return;
4145
+ pending.delete(message.id);
4146
+ if (message.error) {
4147
+ entry.reject(
4148
+ new Error(`${message.error.message} (${message.error.code})`)
4149
+ );
4150
+ } else entry.resolve(message.result);
4151
+ });
4152
+ socket.addEventListener("close", () => {
4153
+ socketClosed = true;
4154
+ for (const entry of pending.values()) {
4155
+ entry.reject(new Error("DevTools connection closed"));
4156
+ }
4157
+ pending.clear();
4158
+ });
4159
+ const opened = new Promise((resolve, reject) => {
4160
+ socket.addEventListener(
4161
+ "error",
4162
+ () => reject(new Error("DevTools connection failed"))
4163
+ );
4164
+ socket.addEventListener(
4165
+ "open",
4166
+ () => resolve({
4167
+ send(method, callTimeoutMs, params, sessionId) {
4168
+ if (socketClosed) {
4169
+ return Promise.reject(new Error("DevTools connection closed"));
4170
+ }
4171
+ const id = ++nextId;
4172
+ const reply = new Promise((res, rej) => {
4173
+ pending.set(id, {
4174
+ resolve: res,
4175
+ reject: rej
4176
+ });
4177
+ });
4178
+ socket.send(JSON.stringify({ id, method, params, sessionId }));
4179
+ return within(reply, callTimeoutMs, method).finally(
4180
+ () => pending.delete(id)
4181
+ );
4182
+ }
4183
+ })
4184
+ );
4185
+ });
4186
+ return within(opened, timeoutMs, "DevTools connection").catch((error) => {
4187
+ socket.close();
4188
+ throw error;
4189
+ });
4190
+ }
4191
+ function startError(executable, error) {
4192
+ return new Error(
4193
+ `could not start ${executable}: ${error.code ?? error.message}`
4194
+ );
4195
+ }
4196
+ function waitForDevTools(child, closed, getSpawnError, executable, timeoutMs) {
4197
+ let tail = "";
4198
+ return within(
4199
+ new Promise((resolve, reject) => {
4200
+ child.stderr.on("data", (chunk) => {
4201
+ tail = (tail + chunk).slice(-2e3);
4202
+ const match = /DevTools listening on (ws:\/\/\S+)/.exec(tail);
4203
+ if (match) resolve(match[1]);
4204
+ });
4205
+ void closed.then(() => {
4206
+ const spawnError = getSpawnError();
4207
+ reject(
4208
+ spawnError ? startError(executable, spawnError) : new Error(
4209
+ `${executable} exited before DevTools was ready: ${tail.trim()}`
4210
+ )
4211
+ );
4212
+ });
4213
+ }),
4214
+ timeoutMs,
4215
+ "browser startup",
4216
+ () => tail.trim() || "no output"
4217
+ );
4218
+ }
4219
+ async function openPage(cdp, timeoutMs) {
4220
+ const { targetId } = await cdp.send(
4221
+ "Target.createTarget",
4222
+ timeoutMs,
4223
+ { url: "about:blank" }
4224
+ );
4225
+ const { sessionId } = await cdp.send(
4226
+ "Target.attachToTarget",
4227
+ timeoutMs,
4228
+ { targetId, flatten: true }
4229
+ );
4230
+ return async (expression, evalTimeoutMs) => {
4231
+ const { result, exceptionDetails } = await cdp.send(
4232
+ "Runtime.evaluate",
4233
+ evalTimeoutMs,
4234
+ { expression, awaitPromise: true, returnByValue: true },
4235
+ sessionId
4236
+ );
4237
+ if (exceptionDetails) {
4238
+ const thrown = exceptionDetails.exception;
4239
+ throw new Error(
4240
+ thrown?.description ?? (thrown && "value" in thrown ? String(thrown.value) : exceptionDetails.text)
4241
+ );
4242
+ }
4243
+ return result.value;
4244
+ };
4245
+ }
4246
+ function removeProfile(profile) {
4247
+ try {
4248
+ import_node_fs4.default.rmSync(profile, {
4249
+ recursive: true,
4250
+ force: true,
4251
+ maxRetries: 5,
4252
+ retryDelay: 100
4253
+ });
4254
+ } catch (error) {
4255
+ console.error(`could not remove browser profile ${profile}:`, error);
4256
+ }
4257
+ }
4258
+ async function launchBrowser(executable, timeoutMs) {
4259
+ if (typeof globalThis.WebSocket === "undefined") {
4260
+ throw new AutoRigInputError(
4261
+ "render_poses needs Node 22 or newer (the global WebSocket is missing)."
4262
+ );
4263
+ }
4264
+ const profile = import_node_fs4.default.mkdtempSync(import_node_path8.default.join(import_node_os.default.tmpdir(), "iki-render-"));
4265
+ let child;
4266
+ try {
4267
+ child = (0, import_node_child_process.spawn)(
4268
+ executable,
4269
+ [
4270
+ "--headless=new",
4271
+ "--remote-debugging-port=0",
4272
+ `--user-data-dir=${profile}`,
4273
+ "--no-first-run",
4274
+ "--no-default-browser-check",
4275
+ // Output pixel sizes must equal the plan's, whatever the display.
4276
+ "--force-device-scale-factor=1",
4277
+ // WebGL without a GPU; recent Chrome no longer falls back by itself.
4278
+ "--enable-unsafe-swiftshader",
4279
+ "about:blank"
4280
+ ],
4281
+ { stdio: ["ignore", "ignore", "pipe"] }
4282
+ );
4283
+ } catch (error) {
4284
+ import_node_fs4.default.rmSync(profile, { recursive: true, force: true });
4285
+ throw startError(executable, error);
4286
+ }
4287
+ let spawnError;
4288
+ child.on("error", (error) => {
4289
+ spawnError = error;
4290
+ });
4291
+ let exited = false;
4292
+ const closed = new Promise((resolve) => {
4293
+ child.on("close", () => {
4294
+ exited = true;
4295
+ resolve();
4296
+ });
4297
+ });
4298
+ const settle = (ms) => within(closed, ms, "browser close").catch(() => {
4299
+ });
4300
+ const onProcessExit = () => {
4301
+ child.kill("SIGKILL");
4302
+ removeProfile(profile);
4303
+ };
4304
+ process.once("exit", onProcessExit);
4305
+ let shutdownPromise;
4306
+ const shutdown = () => shutdownPromise ??= (async () => {
4307
+ if (!exited) {
4308
+ child.kill();
4309
+ await settle(CLOSE_GRACE_MS);
4310
+ if (!exited) {
4311
+ child.kill("SIGKILL");
4312
+ await settle(CLOSE_GRACE_MS);
4313
+ }
4314
+ }
4315
+ process.removeListener("exit", onProcessExit);
4316
+ removeProfile(profile);
4317
+ })();
4318
+ let cdp;
4319
+ try {
4320
+ const endpoint = await waitForDevTools(
4321
+ child,
4322
+ closed,
4323
+ () => spawnError,
4324
+ executable,
4325
+ timeoutMs
4326
+ );
4327
+ cdp = await connectCdp(endpoint, timeoutMs);
4328
+ } catch (error) {
4329
+ await shutdown();
4330
+ throw error;
4331
+ }
4332
+ return {
4333
+ openPage: () => openPage(cdp, timeoutMs),
4334
+ async close() {
4335
+ if (!exited) {
4336
+ await cdp.send("Browser.close", BROWSER_CLOSE_MS).catch(() => {
4337
+ });
4338
+ }
4339
+ await shutdown();
4340
+ }
4341
+ };
4342
+ }
4343
+ async function withBrowser(executable, fn) {
4344
+ const browser = await launchBrowser(executable, DEFAULT_TIMEOUT_MS);
4345
+ try {
4346
+ return await fn(await browser.openPage());
4347
+ } finally {
4348
+ await browser.close();
4349
+ }
4350
+ }
4351
+
4352
+ // src/render-poses.ts
4353
+ var FULL_BODY_VIEW_WIDTH = 2.5;
4354
+ var BUST_SIZE = 560;
4355
+ function planRenders(model) {
4356
+ const { width: W, height: H } = model.canvas;
4357
+ const fullBody = H > W;
4358
+ const canvas = fullBody ? {
4359
+ width: FULL_BODY_VIEW_WIDTH * BUST_SIZE,
4360
+ height: Math.ceil(BUST_SIZE * H / W)
4361
+ } : { width: BUST_SIZE, height: BUST_SIZE };
4362
+ const view = fullBody ? { x: 0, y: 0, width: FULL_BODY_VIEW_WIDTH * W, height: H } : void 0;
4363
+ const x0 = (canvas.width - BUST_SIZE) / 2;
4364
+ const s = BUST_SIZE / W;
4365
+ const mouthPart = model.parts.find((p) => p.id === "mouth_inner") ?? model.parts.find((p) => p.id === "mouth");
4366
+ const mouth = mouthPart ? { cx: W / 2 + mouthPart.transform.x, cy: H / 2 - mouthPart.transform.y } : void 0;
4367
+ const squareCrop = fullBody ? {
4368
+ sx: x0,
4369
+ sy: 0,
4370
+ sw: BUST_SIZE,
4371
+ sh: BUST_SIZE,
4372
+ dw: BUST_SIZE,
4373
+ dh: BUST_SIZE
4374
+ } : void 0;
4375
+ const square = (name, values = {}) => ({
4376
+ name,
4377
+ values,
4378
+ crop: squareCrop
4379
+ });
4380
+ const whole = (name, values = {}) => ({
4381
+ name,
4382
+ values
4383
+ });
4384
+ const bodyAngles = Object.fromEntries(
4385
+ [
4386
+ import_format8.StandardParameter.BodyAngleX,
4387
+ import_format8.StandardParameter.BodyAngleY,
4388
+ import_format8.StandardParameter.BodyAngleZ
4389
+ ].filter((id) => model.parameters.some((p) => p.id === id)).map((id) => [id, -10])
4390
+ );
4391
+ const poses = [
4392
+ square("rest"),
4393
+ square("turn-m30", { ParamAngleX: -30 }),
4394
+ square("turn-p30", { ParamAngleX: 30 }),
4395
+ square("turn-15", { ParamAngleX: 15 }),
4396
+ square("nod-15", { ParamAngleY: 15 }),
4397
+ square("blink", { ParamEyeLOpen: 0 }),
4398
+ square("blink-half", { ParamEyeLOpen: 0.5 }),
4399
+ square("gaze", { ParamEyeBallX: 1 }),
4400
+ square("combined", { ParamAngleX: 30, ParamAngleY: 30, ParamAngleZ: 30 }),
4401
+ // Every head angle at its other extreme with the face moving too, where
4402
+ // moves that each look fine alone stack up into a fold.
4403
+ square("stress", {
4404
+ ParamAngleX: -30,
4405
+ ParamAngleY: -30,
4406
+ ParamAngleZ: -30,
4407
+ ParamMouthOpenY: 1,
4408
+ ParamEyeLOpen: 0.5,
4409
+ ParamEyeROpen: 0.5,
4410
+ ParamBrowLY: -1,
4411
+ ParamBrowRY: 1,
4412
+ ParamBrowLAngle: 1,
4413
+ ParamBrowRAngle: -1,
4414
+ ...bodyAngles
4415
+ })
4416
+ ];
4417
+ if (mouth) {
4418
+ const crop = {
4419
+ sx: x0 + (mouth.cx - 90) * s,
4420
+ sy: (mouth.cy - 60) * s,
4421
+ sw: 180 * s,
4422
+ sh: 120 * s,
4423
+ dw: 720,
4424
+ dh: 480
4425
+ };
4426
+ for (const open of [0, 0.3, 0.6, 1]) {
4427
+ for (const [name, form] of [
4428
+ ["m1", -1],
4429
+ ["0", 0],
4430
+ ["p1", 1]
4431
+ ]) {
4432
+ poses.push({
4433
+ name: `mouth-open-${open}-form-${name}`,
4434
+ values: { ParamMouthOpenY: open, ParamMouthForm: form },
4435
+ crop
4436
+ });
4437
+ }
4438
+ }
4439
+ poses.push(
4440
+ {
4441
+ name: "mouth-laugh",
4442
+ values: { ParamMouthOpenY: 0.8, ParamMouthForm: 1 },
4443
+ crop
4444
+ },
4445
+ { name: "mouth-surprised", values: { ParamMouthOpenY: 0.9 }, crop },
4446
+ {
4447
+ name: "mouth-turn-p30-half",
4448
+ values: { ParamAngleX: 30, ParamMouthOpenY: 0.5 },
4449
+ crop
4450
+ }
4451
+ );
4452
+ }
4453
+ if (fullBody) {
4454
+ poses.push(
4455
+ whole("full-rest"),
4456
+ whole("full-turn-p30", { ParamAngleX: 30 }),
4457
+ whole("full-body-x-m10", { ParamBodyAngleX: -10 }),
4458
+ whole("full-body-x-p10", { ParamBodyAngleX: 10 }),
4459
+ whole("full-body-y-m10", { ParamBodyAngleY: -10 }),
4460
+ whole("full-body-y-p10", { ParamBodyAngleY: 10 }),
4461
+ whole("full-body-z-m10", { ParamBodyAngleZ: -10 }),
4462
+ whole("full-body-z-p10", { ParamBodyAngleZ: 10 }),
4463
+ whole("full-arm-l-16", { ParamArmL: 16 }),
4464
+ whole("full-arm-l-32", { ParamArmL: 32 }),
4465
+ whole("full-arm-r-16", { ParamArmR: 16 }),
4466
+ whole("full-arm-r-32", { ParamArmR: 32 }),
4467
+ whole("full-elbow-l-m10", { ParamElbowL: -10 }),
4468
+ whole("full-elbow-l-45", { ParamElbowL: 45 }),
4469
+ whole("full-elbow-l-90", { ParamElbowL: 90 }),
4470
+ whole("full-elbow-r-m10", { ParamElbowR: -10 }),
4471
+ whole("full-elbow-r-45", { ParamElbowR: 45 }),
4472
+ whole("full-elbow-r-90", { ParamElbowR: 90 })
4473
+ );
4474
+ if (model.parameters.some((p) => p.id === import_format8.StandardParameter.ArmPoseRight)) {
4475
+ poses.push(
4476
+ whole("full-pose-l", { ParamArmPoseL: 1 }),
4477
+ whole("full-pose-r", { ParamArmPoseR: 1 }),
4478
+ whole("full-pose-r-angle-m15", {
4479
+ ParamArmPoseR: 1,
4480
+ ParamArmPoseAngleR: -15
4481
+ }),
4482
+ whole("full-pose-r-angle-p15", {
4483
+ ParamArmPoseR: 1,
4484
+ ParamArmPoseAngleR: 15
4485
+ }),
4486
+ whole("full-pose-r-half", { ParamArmPoseR: 0.5 })
4487
+ );
4488
+ }
4489
+ }
4490
+ return { canvas, view, fullBody, mouth, poses };
4491
+ }
4492
+ var PNG_PREFIX = "data:image/png;base64,";
4493
+ var PAGE_SCRIPT_MS = 1e4;
4494
+ var LOAD_MS = 6e4;
4495
+ var CAPTURE_MS = 15e3;
4496
+ function readPageScript() {
4497
+ const url = new URL("../dist/render-page.global.js", importMetaUrl);
4498
+ try {
4499
+ return (0, import_node_fs5.readFileSync)(url, "utf8");
4500
+ } catch (cause) {
4501
+ throw new Error(
4502
+ "could not read the render page script; run `pnpm build` in packages/mcp",
4503
+ { cause }
4504
+ );
4505
+ }
4506
+ }
4507
+ async function renderPoses(input) {
4508
+ try {
4509
+ const modelFile = confineToWorkingDirectory(
4510
+ process.cwd(),
4511
+ resolveInputPath(input.modelPath, "model"),
4512
+ "model path",
4513
+ input.modelPath
4514
+ );
4515
+ const outDir = resolveOutputDir(input.outDir);
4516
+ const model = (0, import_format8.loadIkiModel)((0, import_node_fs5.readFileSync)(modelFile, "utf8"));
4517
+ const plan = planRenders(model);
4518
+ const browser = findBrowser();
4519
+ if (!browser) return { ok: false, error: NO_BROWSER_MESSAGE };
4520
+ const pageScript = readPageScript();
4521
+ const folds = checkModelFolds(model);
4522
+ const { failedTextures, poses } = await withBrowser(
4523
+ browser,
4524
+ async (evaluate) => {
4525
+ await evaluate(pageScript, PAGE_SCRIPT_MS);
4526
+ const loaded = await evaluate(
4527
+ `window.__ikiRender.load(${JSON.stringify(model)}, ${JSON.stringify({ canvas: plan.canvas, view: plan.view })})`,
4528
+ LOAD_MS
4529
+ );
4530
+ const written = [];
4531
+ for (const pose of plan.poses) {
4532
+ const url = await evaluate(
4533
+ `window.__ikiRender.capture(${JSON.stringify(pose.values)}, ${JSON.stringify(pose.crop)})`,
4534
+ CAPTURE_MS
4535
+ );
4536
+ if (typeof url !== "string" || !url.startsWith(PNG_PREFIX)) {
4537
+ throw new Error(`pose ${pose.name}: the page returned no PNG`);
4538
+ }
4539
+ const file = import_node_path9.default.join(outDir, `${pose.name}.png`);
4540
+ writeFileAtomic(
4541
+ file,
4542
+ Buffer.from(url.slice(PNG_PREFIX.length), "base64")
4543
+ );
4544
+ written.push({ name: pose.name, path: file });
4545
+ }
4546
+ return { failedTextures: loaded.failedTextures, poses: written };
4547
+ }
4548
+ );
4549
+ return {
4550
+ ok: true,
4551
+ outDir,
4552
+ canvas: plan.canvas,
4553
+ fullBody: plan.fullBody,
4554
+ mouth: plan.mouth,
4555
+ failedTextures,
4556
+ poses,
4557
+ modelCanvas: model.canvas,
4558
+ folds
4559
+ };
4560
+ } catch (error) {
4561
+ if (error instanceof AutoRigInputError || error instanceof import_format8.IkiFormatError) {
4562
+ return { ok: false, error: error.message };
4563
+ }
4564
+ throw error;
4565
+ }
4566
+ }
4567
+
3272
4568
  // src/server.ts
3273
4569
  function createIkiMcpServer() {
3274
- const server = new import_mcp.McpServer({ name: "iki", version: "0.23.2" });
4570
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.25.0" });
3275
4571
  server.registerTool(
3276
4572
  "validate_iki",
3277
4573
  {
@@ -3336,7 +4632,7 @@ function createIkiMcpServer() {
3336
4632
  server.registerTool(
3337
4633
  "auto_rig_from_layers",
3338
4634
  {
3339
- description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R and either mouth or the lip set (mouth_inner + lip_lower + lip_upper, a mouth that folds open instead of crossfading) required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, mouth_tongue/mouth_teeth (only with the lip set: drawn under its lips and clipped to mouth_inner), etc. optional; an arm needs the body, a pose forearm needs its arm, and a partial lip set, one mixed with mouth/mouth_open, or mouth_tongue/mouth_teeth without it is refused) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given.",
4635
+ description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R and either mouth or the lip set (mouth_inner + lip_lower + lip_upper, a mouth that folds open instead of crossfading) required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, mouth_tongue/mouth_teeth (only with the lip set: drawn under its lips and clipped to mouth_inner), etc. optional; an arm needs the body, a pose forearm needs its arm, and a partial lip set, one mixed with mouth/mouth_open, or mouth_tongue/mouth_teeth without it is refused) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given. The result's `folds` is the written rig's fold report, printed after the path the way render_poses prints it, and report-only: a fold never refuses the rig.",
3340
4636
  inputSchema: {
3341
4637
  layers: import_zod.z.array(
3342
4638
  import_zod.z.object({
@@ -3376,7 +4672,7 @@ function createIkiMcpServer() {
3376
4672
  async (args) => {
3377
4673
  try {
3378
4674
  const r = await autoRigFromLayers(args);
3379
- const text = r.ok ? r.path : `INVALID: ${r.error}`;
4675
+ const text = r.ok ? [r.path, ...formatFoldReport(r.folds, r.canvas)].join("\n") : `INVALID: ${r.error}`;
3380
4676
  return { content: [{ type: "text", text }], structuredContent: r };
3381
4677
  } catch (err) {
3382
4678
  const error = err instanceof Error ? err.message : String(err);
@@ -3501,6 +4797,37 @@ function createIkiMcpServer() {
3501
4797
  }
3502
4798
  }
3503
4799
  );
4800
+ server.registerTool(
4801
+ "render_poses",
4802
+ {
4803
+ description: "Renders a rigged .iki into the character loop's pose PNGs with the real engine, through the installed Chrome, Edge or Chromium run headless (set CHROME_PATH to pick one). The model decides the set: a bust gets 560x560 shots (rest, turns, nod, blinks, gaze, combined \u2014 ParamAngleX/Y/Z all at 30 \u2014 and stress: ParamAngleX/Y/Z all at -30, ParamMouthOpenY 1, both eyes at 0.5, the brows at opposite extremes (ParamBrowLY -1, ParamBrowRY 1, ParamBrowLAngle 1, ParamBrowRAngle -1) and each body angle the model declares at -10); a mouth adds 720x480 mouth crops; a full body (taller than wide) adds the full-canvas body, arm and elbow poses on a 1400-wide canvas, and a model with a pose forearm adds the full-pose-* shots. Writes <pose>.png files into outDir, overwriting same-named files in place; returns the written paths one per line, then the model's fold report (the result's `folds`), checked by the engine over its own pose set: a `FOLD` line per warp deformer or mesh part that flips (ratio <= 0) or collapses (under 0.1) at some pose \u2014 its cell or triangle, the ratio of its area there to at rest, the pose as its parameter settings (`rest` for none) and where it rests, in model space and in model px from the top-left (the layer PNGs' own pixels, not a render's) \u2014 or `FOLDS: none over N poses`, then a `FOLDS expected:` line naming the closures the rig draws on purpose (an eye or the mouth shut), each by part id, ratio and the parameter that shuts it. Report-only: a fold never fails the render. Fails with INVALID when no browser is found or an input is refused; a browser that cannot start is a tool error.",
4804
+ inputSchema: {
4805
+ modelPath: import_zod.z.string().describe(
4806
+ "Rigged .iki file path (resolved against cwd; must sit under the working directory)."
4807
+ ),
4808
+ outDir: import_zod.z.string().describe(
4809
+ "Existing directory to write the pose PNGs into (resolved against cwd; must already exist; confined to the working directory)."
4810
+ )
4811
+ }
4812
+ },
4813
+ async (args) => {
4814
+ try {
4815
+ const r = await renderPoses(args);
4816
+ const text = r.ok ? [
4817
+ ...r.poses.map((p) => p.path),
4818
+ ...formatFoldReport(r.folds, r.modelCanvas)
4819
+ ].join("\n") : `INVALID: ${r.error}`;
4820
+ return { content: [{ type: "text", text }], structuredContent: r };
4821
+ } catch (err) {
4822
+ const error = err instanceof Error ? err.message : String(err);
4823
+ return {
4824
+ content: [{ type: "text", text: `Unexpected error: ${error}` }],
4825
+ structuredContent: { ok: false, error },
4826
+ isError: true
4827
+ };
4828
+ }
4829
+ }
4830
+ );
3504
4831
  return server;
3505
4832
  }
3506
4833
 
@@ -3510,6 +4837,9 @@ async function main() {
3510
4837
  const server = createIkiMcpServer();
3511
4838
  await server.connect(new import_stdio.StdioServerTransport());
3512
4839
  }
4840
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
4841
+ process.on(signal, () => process.exit(0));
4842
+ }
3513
4843
  main().catch((err) => {
3514
4844
  console.error(err);
3515
4845
  process.exit(1);