@ikijs/mcp 0.24.0 → 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
@@ -33,12 +33,788 @@ var import_zod = require("zod");
33
33
 
34
34
  // src/tools.ts
35
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
36
451
  var import_format = require("@ikijs/format");
37
- 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
+ }
38
814
 
39
815
  // src/node-images.ts
40
816
  var import_sharp = __toESM(require("sharp"));
41
- var import_editor = require("@ikijs/editor");
817
+ var import_editor2 = require("@ikijs/editor");
42
818
 
43
819
  // src/limits.ts
44
820
  var import_node_fs = __toESM(require("fs"));
@@ -194,7 +970,7 @@ async function decodePng(filePath) {
194
970
  }
195
971
  }
196
972
  function detectAlphaBbox(rgba, width, height) {
197
- const bbox = (0, import_editor.detectAlphaBbox)(rgba, width, height);
973
+ const bbox = (0, import_editor2.detectAlphaBbox)(rgba, width, height);
198
974
  if (bbox === null) {
199
975
  throw new AutoRigInputError("layer is empty after alpha threshold");
200
976
  }
@@ -211,15 +987,15 @@ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
211
987
  for (const crop of crops) byId.set(crop.id, crop);
212
988
  const pad = layout.padding;
213
989
  const composites = await Promise.all(
214
- layout.placements.map(async (placement2) => {
215
- const crop = byId.get(placement2.id);
990
+ layout.placements.map(async (placement3) => {
991
+ const crop = byId.get(placement3.id);
216
992
  if (crop === void 0) {
217
993
  throw new AutoRigInputError(
218
- `no crop for atlas placement "${placement2.id}"`
994
+ `no crop for atlas placement "${placement3.id}"`
219
995
  );
220
996
  }
221
997
  const input = pad > 0 ? await (0, import_sharp.default)(crop.buffer).extend({ right: pad, bottom: pad, extendWith: "copy" }).png().toBuffer() : crop.buffer;
222
- return { input, left: placement2.x, top: placement2.y };
998
+ return { input, left: placement3.x, top: placement3.y };
223
999
  })
224
1000
  );
225
1001
  const page = await (0, import_sharp.default)({
@@ -238,10 +1014,10 @@ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
238
1014
  // src/tools.ts
239
1015
  function coerceModel(model) {
240
1016
  try {
241
- 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);
242
1018
  return { ok: true, model: parsed };
243
1019
  } catch (e) {
244
- 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 };
245
1021
  throw e;
246
1022
  }
247
1023
  }
@@ -315,115 +1091,115 @@ function describeIki(model) {
315
1091
  }
316
1092
  var STANDARD_PARAMETER_INFO = [
317
1093
  {
318
- id: import_format.StandardParameter.MouthOpen,
1094
+ id: import_format7.StandardParameter.MouthOpen,
319
1095
  description: "Mouth open amount for lip-sync (0 closed .. 1 open)."
320
1096
  },
321
1097
  {
322
- id: import_format.StandardParameter.MouthForm,
1098
+ id: import_format7.StandardParameter.MouthForm,
323
1099
  description: "Mouth form / smile (-1 .. 1)."
324
1100
  },
325
1101
  {
326
- id: import_format.StandardParameter.EyeOpenLeft,
1102
+ id: import_format7.StandardParameter.EyeOpenLeft,
327
1103
  description: "Left eye open (0 closed .. 1 open). Drive with the right eye for a blink."
328
1104
  },
329
1105
  {
330
- id: import_format.StandardParameter.EyeOpenRight,
1106
+ id: import_format7.StandardParameter.EyeOpenRight,
331
1107
  description: "Right eye open (0 closed .. 1 open)."
332
1108
  },
333
1109
  {
334
- id: import_format.StandardParameter.EyeballX,
1110
+ id: import_format7.StandardParameter.EyeballX,
335
1111
  description: "Eyeball gaze, horizontal (-1 .. 1)."
336
1112
  },
337
1113
  {
338
- id: import_format.StandardParameter.EyeballY,
1114
+ id: import_format7.StandardParameter.EyeballY,
339
1115
  description: "Eyeball gaze, vertical (-1 .. 1)."
340
1116
  },
341
1117
  {
342
- id: import_format.StandardParameter.AngleX,
1118
+ id: import_format7.StandardParameter.AngleX,
343
1119
  description: "Head angle, horizontal degrees."
344
1120
  },
345
1121
  {
346
- id: import_format.StandardParameter.AngleY,
1122
+ id: import_format7.StandardParameter.AngleY,
347
1123
  description: "Head angle, vertical degrees."
348
1124
  },
349
1125
  {
350
- id: import_format.StandardParameter.AngleZ,
1126
+ id: import_format7.StandardParameter.AngleZ,
351
1127
  description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
352
1128
  },
353
1129
  {
354
- id: import_format.StandardParameter.BodyAngleX,
1130
+ id: import_format7.StandardParameter.BodyAngleX,
355
1131
  description: "Body turn, degrees (-10 .. 10); positive turns the body toward the viewer's right, as AngleX does the head."
356
1132
  },
357
1133
  {
358
- id: import_format.StandardParameter.BodyAngleY,
1134
+ id: import_format7.StandardParameter.BodyAngleY,
359
1135
  description: "Body lean, degrees (-10 .. 10); positive moves the upper body up, negative bows."
360
1136
  },
361
1137
  {
362
- id: import_format.StandardParameter.BodyAngleZ,
1138
+ id: import_format7.StandardParameter.BodyAngleZ,
363
1139
  description: "Body tilt, degrees (-10 .. 10); positive tilts the top toward the viewer's right (clockwise), as AngleZ does the head."
364
1140
  },
365
1141
  {
366
- id: import_format.StandardParameter.Breath,
1142
+ id: import_format7.StandardParameter.Breath,
367
1143
  description: "Idle breath (0 .. 1), cycled by the host."
368
1144
  },
369
1145
  {
370
- id: import_format.StandardParameter.BrowLeftY,
1146
+ id: import_format7.StandardParameter.BrowLeftY,
371
1147
  description: "Left brow raise/lower (-1 .. 1)."
372
1148
  },
373
1149
  {
374
- id: import_format.StandardParameter.BrowRightY,
1150
+ id: import_format7.StandardParameter.BrowRightY,
375
1151
  description: "Right brow raise/lower (-1 .. 1)."
376
1152
  },
377
1153
  {
378
- id: import_format.StandardParameter.BrowLeftAngle,
1154
+ id: import_format7.StandardParameter.BrowLeftAngle,
379
1155
  description: "Left brow tilt/angle (-1 .. 1)."
380
1156
  },
381
1157
  {
382
- id: import_format.StandardParameter.BrowRightAngle,
1158
+ id: import_format7.StandardParameter.BrowRightAngle,
383
1159
  description: "Right brow tilt/angle (-1 .. 1)."
384
1160
  },
385
1161
  {
386
- id: import_format.StandardParameter.Cheek,
1162
+ id: import_format7.StandardParameter.Cheek,
387
1163
  description: "Cheek blush strength (0 .. 1), raised by an expression."
388
1164
  },
389
1165
  {
390
- id: import_format.StandardParameter.HairSwayX,
1166
+ id: import_format7.StandardParameter.HairSwayX,
391
1167
  description: "Horizontal hair-sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
392
1168
  },
393
1169
  {
394
- id: import_format.StandardParameter.HairSwayZ,
1170
+ id: import_format7.StandardParameter.HairSwayZ,
395
1171
  description: "Hair-sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
396
1172
  },
397
1173
  {
398
- id: import_format.StandardParameter.ArmLeft,
1174
+ id: import_format7.StandardParameter.ArmLeft,
399
1175
  description: "Left shoulder, degrees; positive raises the arm outward (mirrored on the right)."
400
1176
  },
401
1177
  {
402
- id: import_format.StandardParameter.ArmRight,
1178
+ id: import_format7.StandardParameter.ArmRight,
403
1179
  description: "Right shoulder, degrees; positive raises the arm outward (mirrored on the left)."
404
1180
  },
405
1181
  {
406
- id: import_format.StandardParameter.ElbowLeft,
1182
+ id: import_format7.StandardParameter.ElbowLeft,
407
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)."
408
1184
  },
409
1185
  {
410
- id: import_format.StandardParameter.ElbowRight,
1186
+ id: import_format7.StandardParameter.ElbowRight,
411
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)."
412
1188
  },
413
1189
  {
414
- id: import_format.StandardParameter.ArmPoseLeft,
1190
+ id: import_format7.StandardParameter.ArmPoseLeft,
415
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."
416
1192
  },
417
1193
  {
418
- id: import_format.StandardParameter.ArmPoseRight,
1194
+ id: import_format7.StandardParameter.ArmPoseRight,
419
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."
420
1196
  },
421
1197
  {
422
- id: import_format.StandardParameter.ArmPoseAngleLeft,
1198
+ id: import_format7.StandardParameter.ArmPoseAngleLeft,
423
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)."
424
1200
  },
425
1201
  {
426
- id: import_format.StandardParameter.ArmPoseAngleRight,
1202
+ id: import_format7.StandardParameter.ArmPoseAngleRight,
427
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)."
428
1204
  }
429
1205
  ];
@@ -441,7 +1217,7 @@ function expectInput(label, fn) {
441
1217
  }
442
1218
  var LOSSLESS_PAGE_ROLE = "nose";
443
1219
  async function renderAtlasPage(crops, quantizeColors) {
444
- const layout = (0, import_editor2.packAtlas)(
1220
+ const layout = (0, import_editor3.packAtlas)(
445
1221
  crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),
446
1222
  void 0,
447
1223
  MAX_ATLAS_SIDE
@@ -495,7 +1271,7 @@ async function autoRigFromLayers(input) {
495
1271
  });
496
1272
  const rolePairs = expectInput(
497
1273
  "role parsing",
498
- () => (0, import_editor2.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
1274
+ () => (0, import_editor3.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
499
1275
  );
500
1276
  const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));
501
1277
  let canvasW = 0;
@@ -525,7 +1301,7 @@ async function autoRigFromLayers(input) {
525
1301
  `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`
526
1302
  );
527
1303
  }
528
- measurer = (0, import_editor2.createLayerSetMeasurer)({ width: canvasW, height: canvasH });
1304
+ measurer = (0, import_editor3.createLayerSetMeasurer)({ width: canvasW, height: canvasH });
529
1305
  } else if (png.width !== canvasW || png.height !== canvasH) {
530
1306
  throw new AutoRigInputError(
531
1307
  `layer "${fileName}" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
@@ -554,7 +1330,7 @@ async function autoRigFromLayers(input) {
554
1330
  let turn;
555
1331
  let model;
556
1332
  try {
557
- model = (0, import_editor2.generateIkiFromLayerSet)(
1333
+ model = (0, import_editor3.generateIkiFromLayerSet)(
558
1334
  measurement.layers,
559
1335
  { width: canvasW, height: canvasH },
560
1336
  {
@@ -571,12 +1347,12 @@ async function autoRigFromLayers(input) {
571
1347
  }
572
1348
  );
573
1349
  } catch (e) {
574
- if (!(e instanceof import_editor2.TurnTargetError || e instanceof import_editor2.LayerGeometryError)) {
1350
+ if (!(e instanceof import_editor3.TurnTargetError || e instanceof import_editor3.LayerGeometryError)) {
575
1351
  throw e;
576
1352
  }
577
1353
  throw new AutoRigInputError(e.message);
578
1354
  }
579
- const doc = new import_editor2.EditorDocument(model);
1355
+ const doc = new import_editor3.EditorDocument(model);
580
1356
  const losslessCrop = quantizeColors === void 0 ? void 0 : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);
581
1357
  const pages = losslessCrop === void 0 ? [await renderAtlasPage(crops, quantizeColors)] : [
582
1358
  await renderAtlasPage(
@@ -593,15 +1369,15 @@ async function autoRigFromLayers(input) {
593
1369
  }
594
1370
  const partTextureAssignments = pages.flatMap(
595
1371
  ({ crops: pageCrops, layout }) => pageCrops.flatMap((crop) => {
596
- const placement2 = layout.placements.find((p) => p.id === crop.id);
597
- if (placement2 === void 0) {
1372
+ const placement3 = layout.placements.find((p) => p.id === crop.id);
1373
+ if (placement3 === void 0) {
598
1374
  throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
599
1375
  }
600
- const uv = (0, import_editor2.uvRectFor)(placement2, {
1376
+ const uv = (0, import_editor3.uvRectFor)(placement3, {
601
1377
  width: layout.pageWidth,
602
1378
  height: layout.pageHeight
603
1379
  });
604
- return (0, import_editor2.partIdsOfRole)(crop.id).map((partId) => ({ partId, uv }));
1380
+ return (0, import_editor3.partIdsOfRole)(crop.id).map((partId) => ({ partId, uv }));
605
1381
  })
606
1382
  );
607
1383
  doc.applyAtlas({
@@ -612,12 +1388,13 @@ async function autoRigFromLayers(input) {
612
1388
  if (losslessCrop !== void 0) {
613
1389
  patched = structuredClone(patched);
614
1390
  patched.textures = pages.map((p) => ({ source: p.dataUri }));
615
- for (const partId of (0, import_editor2.partIdsOfRole)(losslessCrop.id)) {
1391
+ for (const partId of (0, import_editor3.partIdsOfRole)(losslessCrop.id)) {
616
1392
  patched.parts.find((p) => p.id === partId).texture.index = 1;
617
1393
  }
618
1394
  }
619
- const finalModel = (0, import_format.parseIkiModel)(patched);
1395
+ const finalModel = (0, import_format7.parseIkiModel)(patched);
620
1396
  writeFileAtomic(outPath, JSON.stringify(finalModel));
1397
+ const folds = checkModelFolds(finalModel);
621
1398
  return {
622
1399
  ok: true,
623
1400
  path: outPath,
@@ -629,7 +1406,8 @@ async function autoRigFromLayers(input) {
629
1406
  ...headEdges === void 0 ? {} : { headEdges },
630
1407
  ...strandEdges === void 0 ? {} : { strandEdges },
631
1408
  ...noseCore === void 0 ? {} : { noseCore },
632
- ...turn === void 0 ? {} : { turn }
1409
+ ...turn === void 0 ? {} : { turn },
1410
+ folds
633
1411
  };
634
1412
  } catch (err) {
635
1413
  if (err instanceof AutoRigInputError)
@@ -642,10 +1420,10 @@ async function autoRigFromLayers(input) {
642
1420
  var import_node_fs3 = __toESM(require("fs"));
643
1421
  var import_node_path7 = __toESM(require("path"));
644
1422
  var import_sharp4 = __toESM(require("sharp"));
645
- var import_editor11 = require("@ikijs/editor");
1423
+ var import_editor12 = require("@ikijs/editor");
646
1424
 
647
1425
  // src/trim.ts
648
- var import_editor3 = require("@ikijs/editor");
1426
+ var import_editor4 = require("@ikijs/editor");
649
1427
  var TRIM_THRESHOLD = 12;
650
1428
  var STRAY_SPECK_FRACTION = 0.01;
651
1429
  function luma(rgba, i) {
@@ -674,7 +1452,7 @@ function boxWithoutStraySpecks(rgba, W, H) {
674
1452
  while (depth > 0) {
675
1453
  const p = stack[--depth];
676
1454
  size++;
677
- if (rgba[p * 4 + 3] >= import_editor3.ALPHA_OPAQUE) opaque = true;
1455
+ if (rgba[p * 4 + 3] >= import_editor4.ALPHA_OPAQUE) opaque = true;
678
1456
  const px2 = p % W;
679
1457
  const py = (p - px2) / W;
680
1458
  setLeft = Math.min(setLeft, px2);
@@ -716,7 +1494,7 @@ var import_node_path6 = __toESM(require("path"));
716
1494
 
717
1495
  // src/measure-arms.ts
718
1496
  var import_node_path3 = __toESM(require("path"));
719
- var import_editor4 = require("@ikijs/editor");
1497
+ var import_editor5 = require("@ikijs/editor");
720
1498
  var ARM_ROLES = ["arm_L", "arm_R"];
721
1499
  var CAP_OVERLAP = 0.5;
722
1500
  var px = (v) => `${Number(v.toFixed(1))}`;
@@ -745,7 +1523,7 @@ async function armWarnings(absDir, layers) {
745
1523
  continue;
746
1524
  }
747
1525
  if (set === void 0) {
748
- const measurer = (0, import_editor4.createLayerSetMeasurer)({
1526
+ const measurer = (0, import_editor5.createLayerSetMeasurer)({
749
1527
  width: body.canvasW,
750
1528
  height: body.canvasH
751
1529
  });
@@ -753,12 +1531,12 @@ async function armWarnings(absDir, layers) {
753
1531
  }
754
1532
  let g;
755
1533
  try {
756
- g = (0, import_editor4.armGeometry)(
1534
+ g = (0, import_editor5.armGeometry)(
757
1535
  await measured(set.measurer, absDir, arm),
758
1536
  set.body.bbox.x + set.body.bbox.w / 2 - body.canvasW / 2
759
1537
  );
760
1538
  } catch (err) {
761
- if (err instanceof import_editor4.LayerGeometryError) {
1539
+ if (err instanceof import_editor5.LayerGeometryError) {
762
1540
  warnings.push(
763
1541
  `${arm}: ${err.message} \u2014 auto_rig_from_layers refuses it. Regenerate arm.png drawn hanging, shoulder at the top. Billed.`
764
1542
  );
@@ -786,7 +1564,7 @@ function capWarning(arm, g, body) {
786
1564
  }
787
1565
 
788
1566
  // src/measure-forearm-pose.ts
789
- var import_editor5 = require("@ikijs/editor");
1567
+ var import_editor6 = require("@ikijs/editor");
790
1568
  var POSE_ROLES = ["forearm_pose_L", "forearm_pose_R"];
791
1569
  var ARM_OF = {
792
1570
  forearm_pose_L: "arm_L",
@@ -820,7 +1598,7 @@ async function forearmPoseWarnings(absDir, layers) {
820
1598
  continue;
821
1599
  }
822
1600
  if (layers.body === void 0) continue;
823
- const measurer = (0, import_editor5.createLayerSetMeasurer)({
1601
+ const measurer = (0, import_editor6.createLayerSetMeasurer)({
824
1602
  width: stats.canvasW,
825
1603
  height: stats.canvasH
826
1604
  });
@@ -828,12 +1606,12 @@ async function forearmPoseWarnings(absDir, layers) {
828
1606
  let armLayer;
829
1607
  try {
830
1608
  armLayer = await measured(measurer, absDir, arm);
831
- a = (0, import_editor5.armGeometry)(armLayer, arm === "arm_R" ? Infinity : -Infinity);
1609
+ a = (0, import_editor6.armGeometry)(armLayer, arm === "arm_R" ? Infinity : -Infinity);
832
1610
  } catch (err) {
833
- if (err instanceof import_editor5.LayerGeometryError) continue;
1611
+ if (err instanceof import_editor6.LayerGeometryError) continue;
834
1612
  throw err;
835
1613
  }
836
- const b = (0, import_editor5.forearmPoseGeometry)(await measured(measurer, absDir, pose));
1614
+ const b = (0, import_editor6.forearmPoseGeometry)(await measured(measurer, absDir, pose));
837
1615
  warnings.push(...jointWarnings(pose, arm, stats, a, armLayer, b));
838
1616
  }
839
1617
  return warnings;
@@ -873,11 +1651,11 @@ function jointWarnings(pose, arm, stats, a, armLayer, b) {
873
1651
 
874
1652
  // src/measure-lips.ts
875
1653
  var import_node_path4 = __toESM(require("path"));
876
- var import_editor7 = require("@ikijs/editor");
1654
+ var import_editor8 = require("@ikijs/editor");
877
1655
 
878
1656
  // src/compose-lips.ts
879
1657
  var import_sharp2 = __toESM(require("sharp"));
880
- var import_editor6 = require("@ikijs/editor");
1658
+ var import_editor7 = require("@ikijs/editor");
881
1659
  var KEYED_SRC = "mouth_keyed.png";
882
1660
  var INTERIOR_SRC = "mouth_interior.png";
883
1661
  var KEY_CANDIDATE = 0.5;
@@ -975,7 +1753,7 @@ function keyGreen(rgba, W, H) {
975
1753
  let candidates = 0;
976
1754
  for (let p = 0; p < n; p++) {
977
1755
  const i = p * 4;
978
- if (rgba[i + 3] < import_editor6.ALPHA_OPAQUE) continue;
1756
+ if (rgba[i + 3] < import_editor7.ALPHA_OPAQUE) continue;
979
1757
  const excess = (rgba[i + 1] - Math.max(rgba[i], rgba[i + 2])) / 255;
980
1758
  if (excess < KEY_CANDIDATE) continue;
981
1759
  candidates++;
@@ -1002,7 +1780,7 @@ function keyGreen(rgba, W, H) {
1002
1780
  const dg = rgba[i + 1] - G[1];
1003
1781
  const db = rgba[i + 2] - G[2];
1004
1782
  const green = dr * dr + dg * dg + db * db <= KEY_FILL_DIST * KEY_FILL_DIST;
1005
- if (rgba[i + 3] < import_editor6.ALPHA_OPAQUE) {
1783
+ if (rgba[i + 3] < import_editor7.ALPHA_OPAQUE) {
1006
1784
  if (green) out[i + 3] = 0;
1007
1785
  } else if (green) {
1008
1786
  fill[p] = 1;
@@ -1178,7 +1956,7 @@ async function prepInterior(rgba, W, H) {
1178
1956
  for (let y = box.y; y < box.y + box.h; y++) {
1179
1957
  for (let x = box.x; x < box.x + box.w; x++) {
1180
1958
  const i = (y * cw + x) * 4;
1181
- if (crop[i + 3] < import_editor6.ALPHA_OPAQUE) continue;
1959
+ if (crop[i + 3] < import_editor7.ALPHA_OPAQUE) continue;
1182
1960
  count++;
1183
1961
  for (let c = 0; c < 3; c++) all[c] += crop[i + c];
1184
1962
  if (luma(crop, i) < CAVITY_LUMA) {
@@ -1201,7 +1979,7 @@ function enclosedHole(frame, w, h) {
1201
1979
  const stack = new Int32Array(n);
1202
1980
  let depth = 0;
1203
1981
  const seed = (p) => {
1204
- if (!outside[p] && alpha(p) < import_editor6.ALPHA_OPAQUE) {
1982
+ if (!outside[p] && alpha(p) < import_editor7.ALPHA_OPAQUE) {
1205
1983
  outside[p] = 1;
1206
1984
  stack[depth++] = p;
1207
1985
  }
@@ -1224,7 +2002,7 @@ function enclosedHole(frame, w, h) {
1224
2002
  }
1225
2003
  const mask = new Uint8Array(n);
1226
2004
  for (let p = 0; p < n; p++) {
1227
- 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;
1228
2006
  }
1229
2007
  const { label, sizes, boxes } = components(mask, w, h);
1230
2008
  const main2 = largest(sizes);
@@ -1251,7 +2029,7 @@ function enclosedHole(frame, w, h) {
1251
2029
  return { label, main: main2, box };
1252
2030
  }
1253
2031
  function measureLips(layers, w, h) {
1254
- const measurer = (0, import_editor6.createLayerSetMeasurer)({ width: w, height: h });
2032
+ const measurer = (0, import_editor7.createLayerSetMeasurer)({ width: w, height: h });
1255
2033
  return new Map(
1256
2034
  Object.entries(layers).map(([role, rgba]) => [
1257
2035
  role,
@@ -1269,8 +2047,8 @@ function assertFoldContract(layers, w, h) {
1269
2047
  }
1270
2048
  byRole.set(role, layer);
1271
2049
  }
1272
- const opening = (0, import_editor6.mouthOpening)(byRole);
1273
- 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"));
1274
2052
  for (let col = opening.x0; col <= opening.x1; col++) {
1275
2053
  const c = opening.at(col);
1276
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;
@@ -1300,18 +2078,18 @@ async function splitLipSet(keyedPng, w, h, interior) {
1300
2078
  }
1301
2079
  const centre = Math.round((hb.x0 + hb.x1) / 2);
1302
2080
  let stroke = 0;
1303
- 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)
1304
2082
  stroke++;
1305
2083
  const bandCap = BAND_CAP * Math.max(1, stroke);
1306
2084
  const skinRow = new Int32Array(w).fill(-1);
1307
2085
  const inM = new Uint8Array(n);
1308
2086
  for (let x = hb.x0; x <= hb.x1; x++) {
1309
2087
  let y = bot[x];
1310
- 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)
1311
2089
  y++;
1312
2090
  for (let k = top[x]; k < y; k++) inM[k * w + x] = 1;
1313
2091
  let r = y;
1314
- 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++;
1315
2093
  if (r < h) {
1316
2094
  skinRow[x] = r;
1317
2095
  inM[r * w + x] = 1;
@@ -1321,7 +2099,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
1321
2099
  for (let y = 0; y < h; y++) {
1322
2100
  for (let x = 0; x < w; x++) {
1323
2101
  const p = y * w + x;
1324
- if (inM[p] || alpha(p) < import_editor6.ALPHA_OPAQUE) continue;
2102
+ if (inM[p] || alpha(p) < import_editor7.ALPHA_OPAQUE) continue;
1325
2103
  if (top[x] >= 0 && y < top[x]) continue;
1326
2104
  if (x > 0 && inM[p - 1] || x < w - 1 && inM[p + 1]) grown[p] = 1;
1327
2105
  }
@@ -1331,7 +2109,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
1331
2109
  if (x < 0 || x >= w) continue;
1332
2110
  let first = 0;
1333
2111
  while (first < h && !(grown[first * w + x] && !inM[first * w + x])) first++;
1334
- 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)
1335
2113
  wall[x] = 1;
1336
2114
  }
1337
2115
  const gx = hb.x0 - 1;
@@ -1358,7 +2136,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
1358
2136
  if (inOpening && skinRow[x] >= 0 && y >= skinRow[x]) copy(lower, p);
1359
2137
  if (!grown[p]) {
1360
2138
  const a = alpha(p);
1361
- 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)) {
1362
2140
  inner.set(interior.cavity, p * 4);
1363
2141
  inner[p * 4 + 3] = 255 - a;
1364
2142
  }
@@ -1423,7 +2201,7 @@ async function restShiftOf(layers, width, height) {
1423
2201
  }
1424
2202
  byRole.set(role, layer);
1425
2203
  }
1426
- return (0, import_editor6.mouthRestShift)(byRole);
2204
+ return (0, import_editor7.mouthRestShift)(byRole);
1427
2205
  }
1428
2206
  async function closedLips(upper, lower, shift, left, top) {
1429
2207
  const shut = async (png, role) => {
@@ -1473,7 +2251,7 @@ async function closedLips(upper, lower, shift, left, top) {
1473
2251
  }
1474
2252
 
1475
2253
  // src/measure-lips.ts
1476
- 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);
1477
2255
  var MIN_OPENING_ROWS = 8;
1478
2256
  var MIN_LINE_ROWS = 2;
1479
2257
  var GREEN_EXCESS = 40;
@@ -1481,8 +2259,8 @@ var INTERIOR_GAP_FRACTION = 0.05;
1481
2259
  var columns = (cols) => `${cols.length} column${cols.length === 1 ? "" : "s"} (first at x=${cols[0]})`;
1482
2260
  async function lipWarnings(absDir, layers) {
1483
2261
  const warnings = [];
1484
- const present = import_editor7.LIP_ROLES.filter((role) => layers[role] !== void 0);
1485
- 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);
1486
2264
  if (present.length === 0) {
1487
2265
  if (inside.length > 0) {
1488
2266
  warnings.push(
@@ -1499,8 +2277,8 @@ async function lipWarnings(absDir, layers) {
1499
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.`
1500
2278
  );
1501
2279
  }
1502
- if (present.length < import_editor7.LIP_ROLES.length) {
1503
- 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);
1504
2282
  warnings.push(
1505
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.`
1506
2284
  );
@@ -1531,18 +2309,18 @@ async function lipWarnings(absDir, layers) {
1531
2309
  );
1532
2310
  }
1533
2311
  }
1534
- const measurer = (0, import_editor7.createLayerSetMeasurer)({
2312
+ const measurer = (0, import_editor8.createLayerSetMeasurer)({
1535
2313
  width: inner.canvasW,
1536
2314
  height: inner.canvasH
1537
2315
  });
1538
2316
  const set = /* @__PURE__ */ new Map();
1539
2317
  const green = [];
1540
- for (const role of import_editor7.LIP_ROLES) {
2318
+ for (const role of import_editor8.LIP_ROLES) {
1541
2319
  const fileName = `${role}.png`;
1542
2320
  const { rgba } = await decodePng(import_node_path4.default.join(absDir, fileName));
1543
2321
  set.set(role, measurer.add({ role, fileName, rgba }));
1544
2322
  for (let i = 0; i < rgba.length; i += 4) {
1545
- 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) {
1546
2324
  green.push(role);
1547
2325
  break;
1548
2326
  }
@@ -1550,15 +2328,15 @@ async function lipWarnings(absDir, layers) {
1550
2328
  }
1551
2329
  let opening;
1552
2330
  try {
1553
- opening = (0, import_editor7.mouthOpening)(set);
2331
+ opening = (0, import_editor8.mouthOpening)(set);
1554
2332
  } catch (err) {
1555
- if (err instanceof import_editor7.LayerGeometryError) {
2333
+ if (err instanceof import_editor8.LayerGeometryError) {
1556
2334
  warnings.push(err.message);
1557
2335
  return { warnings };
1558
2336
  }
1559
2337
  throw err;
1560
2338
  }
1561
- const innerRuns = (0, import_editor7.columnRuns)(set.get("mouth_inner"));
2339
+ const innerRuns = (0, import_editor8.columnRuns)(set.get("mouth_inner"));
1562
2340
  const noInterior = [];
1563
2341
  const gap = [];
1564
2342
  const noLine = [];
@@ -1644,8 +2422,8 @@ async function lipWarnings(absDir, layers) {
1644
2422
 
1645
2423
  // src/measure-turn.ts
1646
2424
  var import_node_path5 = __toESM(require("path"));
1647
- var import_editor8 = require("@ikijs/editor");
1648
2425
  var import_editor9 = require("@ikijs/editor");
2426
+ var import_editor10 = require("@ikijs/editor");
1649
2427
  var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
1650
2428
  var IRIS_V_MIN = 0.18;
1651
2429
  var IRIS_V_MAX = 0.95;
@@ -1795,7 +2573,7 @@ async function measureTurnImage(filePath, iris) {
1795
2573
  let transparent = false;
1796
2574
  if (hasAlpha) {
1797
2575
  for (let i = 0; i < n; i++) {
1798
- if (rgba[i * 4 + 3] < import_editor8.ALPHA_OPAQUE) {
2576
+ if (rgba[i * 4 + 3] < import_editor9.ALPHA_OPAQUE) {
1799
2577
  transparent = true;
1800
2578
  break;
1801
2579
  }
@@ -1806,7 +2584,7 @@ async function measureTurnImage(filePath, iris) {
1806
2584
  const fg = new Uint8Array(n);
1807
2585
  const value = new Float32Array(n);
1808
2586
  for (let i = 0; i < n; i++) {
1809
- if (rgba[i * 4 + 3] < import_editor8.ALPHA_OPAQUE) continue;
2587
+ if (rgba[i * 4 + 3] < import_editor9.ALPHA_OPAQUE) continue;
1810
2588
  const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);
1811
2589
  if (maskMode === "alpha") {
1812
2590
  fg[i] = 1;
@@ -1872,12 +2650,12 @@ async function measureTurnImage(filePath, iris) {
1872
2650
  }
1873
2651
  const [irisL, irisR] = best.pair;
1874
2652
  const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);
1875
- const { left, right } = (0, import_editor8.foregroundSpan)(
2653
+ const { left, right } = (0, import_editor9.foregroundSpan)(
1876
2654
  fg,
1877
2655
  width,
1878
2656
  height,
1879
- eyeRow - import_editor8.HEAD_BAND,
1880
- eyeRow + import_editor8.HEAD_BAND
2657
+ eyeRow - import_editor9.HEAD_BAND,
2658
+ eyeRow + import_editor9.HEAD_BAND
1881
2659
  );
1882
2660
  if (right <= left) {
1883
2661
  throw new AutoRigInputError(
@@ -1901,7 +2679,7 @@ async function measureTurnImage(filePath, iris) {
1901
2679
  left,
1902
2680
  right,
1903
2681
  cx: (left + right) / 2,
1904
- half: (0, import_editor8.headHalfOf)({ left, right })
2682
+ half: (0, import_editor9.headHalfOf)({ left, right })
1905
2683
  },
1906
2684
  pairCx: (irisL.cx + irisR.cx) / 2,
1907
2685
  eyeGap: irisR.cx - irisL.cx
@@ -2092,7 +2870,7 @@ function noseSpeckWarning({ core, part }, source) {
2092
2870
  `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,
2093
2871
  `auto_rig_from_layers turns and tilts the nose about its whole crop instead`
2094
2872
  ];
2095
- 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.`;
2096
2874
  }
2097
2875
  async function lashOffSclera(eyePath, lashPath) {
2098
2876
  const eye = await decodePng(eyePath);
@@ -2229,10 +3007,10 @@ async function measureDir(absDir, noseSpeck) {
2229
3007
  warnings.push(noseSpeckWarning(noseSpeck, "compose"));
2230
3008
  } else if (layers.nose !== void 0) {
2231
3009
  const nose = await decodePng(import_node_path6.default.join(absDir, "nose.png"));
2232
- 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);
2233
3011
  if (core !== null) {
2234
3012
  const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);
2235
- if ((0, import_editor9.isSpeckCore)(core, crop))
3013
+ if ((0, import_editor10.isSpeckCore)(core, crop))
2236
3014
  warnings.push(noseSpeckWarning({ core, part: crop }, "layer"));
2237
3015
  }
2238
3016
  }
@@ -2303,12 +3081,12 @@ function formatMeasureReport(result) {
2303
3081
 
2304
3082
  // src/compose-arms.ts
2305
3083
  var import_sharp3 = __toESM(require("sharp"));
2306
- var import_editor10 = require("@ikijs/editor");
3084
+ var import_editor11 = require("@ikijs/editor");
2307
3085
  var ARM_WIDTH = 0.4;
2308
3086
  var SHOULDER_DROP = 0.12;
2309
3087
  async function armPlacement(role, cfg, part, body) {
2310
3088
  const { data } = await (0, import_sharp3.default)(part.buf).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2311
- 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({
2312
3090
  role,
2313
3091
  fileName: "arm.png",
2314
3092
  rgba: data
@@ -2320,9 +3098,9 @@ async function armPlacement(role, cfg, part, body) {
2320
3098
  }
2321
3099
  let g;
2322
3100
  try {
2323
- g = (0, import_editor10.armGeometry)(layer, role === "arm_R" ? Infinity : -Infinity);
3101
+ g = (0, import_editor11.armGeometry)(layer, role === "arm_R" ? Infinity : -Infinity);
2324
3102
  } catch (err) {
2325
- if (err instanceof import_editor10.LayerGeometryError) {
3103
+ if (err instanceof import_editor11.LayerGeometryError) {
2326
3104
  throw new AutoRigInputError(`layout.${role}: ${err.message}`);
2327
3105
  }
2328
3106
  throw err;
@@ -2349,7 +3127,7 @@ async function armPlacement(role, cfg, part, body) {
2349
3127
  }
2350
3128
  async function poseGeometryOf(role, png, size, when) {
2351
3129
  const { data } = await (0, import_sharp3.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2352
- const layer = (0, import_editor10.createLayerSetMeasurer)({
3130
+ const layer = (0, import_editor11.createLayerSetMeasurer)({
2353
3131
  width: size.w,
2354
3132
  height: size.h
2355
3133
  }).add({ role, fileName: "forearm_pose.png", rgba: data });
@@ -2358,7 +3136,7 @@ async function poseGeometryOf(role, png, size, when) {
2358
3136
  `layout.${role}: forearm_pose.png is empty after alpha threshold${when}`
2359
3137
  );
2360
3138
  }
2361
- return (0, import_editor10.forearmPoseGeometry)(layer);
3139
+ return (0, import_editor11.forearmPoseGeometry)(layer);
2362
3140
  }
2363
3141
  async function forearmPoseWidth(role, trimmed, elbowRun) {
2364
3142
  const g = await poseGeometryOf(role, trimmed.data, trimmed, "");
@@ -2576,12 +3354,12 @@ function resolveLayout(overrides, canvas) {
2576
3354
  const face = { ...resolved.face, ...sets.get("face") };
2577
3355
  resolved.face = face;
2578
3356
  const base = DEFAULT_LAYOUT.face;
2579
- const scale = face.w / base.w;
2580
- const x = (cx) => face.cx + (cx - base.cx) * scale;
2581
- 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));
2582
3360
  for (const role of FACE_FEATURES) {
2583
3361
  const d = DEFAULT_LAYOUT[role];
2584
- const cy = face.cy + (d.cy - base.cy) * scale;
3362
+ const cy = face.cy + (d.cy - base.cy) * scale2;
2585
3363
  resolved[role] = { ...d, cx: x(d.cx), cy, w: w(d.w), ...sets.get(role) };
2586
3364
  }
2587
3365
  const nose = DEFAULT_LAYOUT.nose;
@@ -2634,18 +3412,18 @@ function keyWhiteToAlpha(rgba) {
2634
3412
  async function coreAndBoundsOf(png) {
2635
3413
  const { data, info } = await (0, import_sharp4.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2636
3414
  return {
2637
- core: (0, import_editor9.denseCoreOf)(data, info.width, info.height),
3415
+ core: (0, import_editor10.denseCoreOf)(data, info.width, info.height),
2638
3416
  bounds: { x: 0, y: 0, w: info.width, h: info.height }
2639
3417
  };
2640
3418
  }
2641
3419
  async function hasCoverage(png) {
2642
3420
  const { data, info } = await (0, import_sharp4.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2643
- return (0, import_editor11.detectAlphaBbox)(data, info.width, info.height) !== null;
3421
+ return (0, import_editor12.detectAlphaBbox)(data, info.width, info.height) !== null;
2644
3422
  }
2645
3423
  async function noseSizingOf(png) {
2646
3424
  const { core, bounds } = await coreAndBoundsOf(png);
2647
3425
  if (core === null) return { box: bounds, whole: true };
2648
- if ((0, import_editor9.isSpeckCore)(core, bounds)) {
3426
+ if ((0, import_editor10.isSpeckCore)(core, bounds)) {
2649
3427
  return {
2650
3428
  box: bounds,
2651
3429
  whole: true,
@@ -2722,7 +3500,7 @@ function assertOnCanvas(source, w, h, left, top, canvas) {
2722
3500
  );
2723
3501
  }
2724
3502
  }
2725
- function placement(role, cfg, w, h, canvas) {
3503
+ function placement2(role, cfg, w, h, canvas) {
2726
3504
  const left = Math.round(cfg.cx - w / 2);
2727
3505
  const top = Math.round(cfg.cy - h / 2);
2728
3506
  assertOnCanvas(`layout.${role}.cx/cy`, w, h, left, top, canvas);
@@ -2767,7 +3545,7 @@ function detachedAboveWhite(rgba, W, H) {
2767
3545
  for (let p = 0; p < n; p++) {
2768
3546
  const alpha = rgba[p * 4 + 3];
2769
3547
  if (alpha > 0 && luma(rgba, p * 4) >= EYE_LASH_LUMA)
2770
- ink[p] = alpha >= import_editor11.ALPHA_OPAQUE ? 2 : 1;
3548
+ ink[p] = alpha >= import_editor12.ALPHA_OPAQUE ? 2 : 1;
2771
3549
  }
2772
3550
  const label = new Int32Array(n).fill(-1);
2773
3551
  const stack = new Int32Array(n);
@@ -2992,7 +3770,7 @@ async function composeLayersFromParts(input) {
2992
3770
  part2.h,
2993
3771
  lips.interior
2994
3772
  );
2995
- 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);
2996
3774
  lipSplit = { split: split2, w: part2.w, h: part2.h, left: left2, top: top2 };
2997
3775
  placed.push({
2998
3776
  role,
@@ -3011,7 +3789,7 @@ async function composeLayersFromParts(input) {
3011
3789
  lip_lower: split2.lower,
3012
3790
  lip_upper: split2.upper
3013
3791
  }[role];
3014
- if ((0, import_editor11.isLipInsideRole)(role) && !await hasCoverage(buf)) {
3792
+ if ((0, import_editor12.isLipInsideRole)(role) && !await hasCoverage(buf)) {
3015
3793
  skipped.push(role);
3016
3794
  continue;
3017
3795
  }
@@ -3149,7 +3927,7 @@ async function composeLayersFromParts(input) {
3149
3927
  canvas
3150
3928
  ));
3151
3929
  } else {
3152
- ({ left, top } = placement(key, layout[key], part.w, part.h, canvas));
3930
+ ({ left, top } = placement2(key, layout[key], part.w, part.h, canvas));
3153
3931
  }
3154
3932
  if (role === "lash_L" || role === "lash_R") {
3155
3933
  const eyeRole = role === "lash_L" ? "eye_L" : "eye_R";
@@ -3206,7 +3984,7 @@ async function composeLayersFromParts(input) {
3206
3984
  });
3207
3985
  }
3208
3986
  const restInput = (role, buf) => {
3209
- if (role === "mouth_inner" || (0, import_editor11.isLipInsideRole)(role)) return null;
3987
+ if (role === "mouth_inner" || (0, import_editor12.isLipInsideRole)(role)) return null;
3210
3988
  if (closed === void 0) return buf;
3211
3989
  if (role === "lip_upper") return closed.upper;
3212
3990
  if (role === "lip_lower") return closed.lower;
@@ -3276,7 +4054,7 @@ async function composeLayersFromParts(input) {
3276
4054
  // src/render-poses.ts
3277
4055
  var import_node_fs5 = require("fs");
3278
4056
  var import_node_path9 = __toESM(require("path"));
3279
- var import_format2 = require("@ikijs/format");
4057
+ var import_format8 = require("@ikijs/format");
3280
4058
 
3281
4059
  // src/render-browser.ts
3282
4060
  var import_node_child_process = require("child_process");
@@ -3603,6 +4381,13 @@ function planRenders(model) {
3603
4381
  name,
3604
4382
  values
3605
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
+ );
3606
4391
  const poses = [
3607
4392
  square("rest"),
3608
4393
  square("turn-m30", { ParamAngleX: -30 }),
@@ -3612,7 +4397,22 @@ function planRenders(model) {
3612
4397
  square("blink", { ParamEyeLOpen: 0 }),
3613
4398
  square("blink-half", { ParamEyeLOpen: 0.5 }),
3614
4399
  square("gaze", { ParamEyeBallX: 1 }),
3615
- square("combined", { ParamAngleX: 30, ParamAngleY: 30, ParamAngleZ: 30 })
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
+ })
3616
4416
  ];
3617
4417
  if (mouth) {
3618
4418
  const crop = {
@@ -3671,7 +4471,7 @@ function planRenders(model) {
3671
4471
  whole("full-elbow-r-45", { ParamElbowR: 45 }),
3672
4472
  whole("full-elbow-r-90", { ParamElbowR: 90 })
3673
4473
  );
3674
- if (model.parameters.some((p) => p.id === import_format2.StandardParameter.ArmPoseRight)) {
4474
+ if (model.parameters.some((p) => p.id === import_format8.StandardParameter.ArmPoseRight)) {
3675
4475
  poses.push(
3676
4476
  whole("full-pose-l", { ParamArmPoseL: 1 }),
3677
4477
  whole("full-pose-r", { ParamArmPoseR: 1 }),
@@ -3713,11 +4513,12 @@ async function renderPoses(input) {
3713
4513
  input.modelPath
3714
4514
  );
3715
4515
  const outDir = resolveOutputDir(input.outDir);
3716
- const model = (0, import_format2.loadIkiModel)((0, import_node_fs5.readFileSync)(modelFile, "utf8"));
4516
+ const model = (0, import_format8.loadIkiModel)((0, import_node_fs5.readFileSync)(modelFile, "utf8"));
3717
4517
  const plan = planRenders(model);
3718
4518
  const browser = findBrowser();
3719
4519
  if (!browser) return { ok: false, error: NO_BROWSER_MESSAGE };
3720
4520
  const pageScript = readPageScript();
4521
+ const folds = checkModelFolds(model);
3721
4522
  const { failedTextures, poses } = await withBrowser(
3722
4523
  browser,
3723
4524
  async (evaluate) => {
@@ -3752,10 +4553,12 @@ async function renderPoses(input) {
3752
4553
  fullBody: plan.fullBody,
3753
4554
  mouth: plan.mouth,
3754
4555
  failedTextures,
3755
- poses
4556
+ poses,
4557
+ modelCanvas: model.canvas,
4558
+ folds
3756
4559
  };
3757
4560
  } catch (error) {
3758
- if (error instanceof AutoRigInputError || error instanceof import_format2.IkiFormatError) {
4561
+ if (error instanceof AutoRigInputError || error instanceof import_format8.IkiFormatError) {
3759
4562
  return { ok: false, error: error.message };
3760
4563
  }
3761
4564
  throw error;
@@ -3764,7 +4567,7 @@ async function renderPoses(input) {
3764
4567
 
3765
4568
  // src/server.ts
3766
4569
  function createIkiMcpServer() {
3767
- const server = new import_mcp.McpServer({ name: "iki", version: "0.24.0" });
4570
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.25.0" });
3768
4571
  server.registerTool(
3769
4572
  "validate_iki",
3770
4573
  {
@@ -3829,7 +4632,7 @@ function createIkiMcpServer() {
3829
4632
  server.registerTool(
3830
4633
  "auto_rig_from_layers",
3831
4634
  {
3832
- 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.",
3833
4636
  inputSchema: {
3834
4637
  layers: import_zod.z.array(
3835
4638
  import_zod.z.object({
@@ -3869,7 +4672,7 @@ function createIkiMcpServer() {
3869
4672
  async (args) => {
3870
4673
  try {
3871
4674
  const r = await autoRigFromLayers(args);
3872
- 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}`;
3873
4676
  return { content: [{ type: "text", text }], structuredContent: r };
3874
4677
  } catch (err) {
3875
4678
  const error = err instanceof Error ? err.message : String(err);
@@ -3997,7 +4800,7 @@ function createIkiMcpServer() {
3997
4800
  server.registerTool(
3998
4801
  "render_poses",
3999
4802
  {
4000
- 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); 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. Fails with INVALID when no browser is found or an input is refused; a browser that cannot start is a tool error.",
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.",
4001
4804
  inputSchema: {
4002
4805
  modelPath: import_zod.z.string().describe(
4003
4806
  "Rigged .iki file path (resolved against cwd; must sit under the working directory)."
@@ -4010,7 +4813,10 @@ function createIkiMcpServer() {
4010
4813
  async (args) => {
4011
4814
  try {
4012
4815
  const r = await renderPoses(args);
4013
- const text = r.ok ? r.poses.map((p) => p.path).join("\n") : `INVALID: ${r.error}`;
4816
+ const text = r.ok ? [
4817
+ ...r.poses.map((p) => p.path),
4818
+ ...formatFoldReport(r.folds, r.modelCanvas)
4819
+ ].join("\n") : `INVALID: ${r.error}`;
4014
4820
  return { content: [{ type: "text", text }], structuredContent: r };
4015
4821
  } catch (err) {
4016
4822
  const error = err instanceof Error ? err.message : String(err);