@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/index.js CHANGED
@@ -31,26 +31,809 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
33
  autoRigFromLayers: () => autoRigFromLayers,
34
+ checkModelFolds: () => checkModelFolds,
34
35
  composeLayersFromParts: () => composeLayersFromParts,
35
36
  createIkiMcpServer: () => createIkiMcpServer,
36
37
  describeIki: () => describeIki,
38
+ formatFoldReport: () => formatFoldReport,
37
39
  formatMeasureReport: () => formatMeasureReport,
38
40
  formatTurnReport: () => formatTurnReport,
39
41
  listStandardParameters: () => listStandardParameters,
40
42
  measureLayers: () => measureLayers,
41
43
  measureTurnReference: () => measureTurnReference,
44
+ renderPoses: () => renderPoses,
42
45
  validateIki: () => validateIki
43
46
  });
44
47
  module.exports = __toCommonJS(index_exports);
45
48
 
49
+ // ../../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
50
+ 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;
51
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
52
+
46
53
  // src/tools.ts
47
54
  var import_node_path2 = __toESM(require("path"));
55
+ var import_format7 = require("@ikijs/format");
56
+ var import_editor3 = require("@ikijs/editor");
57
+
58
+ // src/fold-report.ts
59
+ var import_editor = require("@ikijs/editor");
60
+
61
+ // ../engine/src/math.ts
62
+ function clamp(value, min, max) {
63
+ return Math.max(min, Math.min(max, value));
64
+ }
65
+ function lerp(a, b, t) {
66
+ return a + (b - a) * t;
67
+ }
68
+
69
+ // ../engine/src/parameter-store.ts
70
+ var ParameterStore = class {
71
+ params = /* @__PURE__ */ new Map();
72
+ values = /* @__PURE__ */ new Map();
73
+ /**
74
+ * Resting value per id: the declared default clamped into range, resolved
75
+ * ONCE here so `reset()` is a straight copy and a malformed descriptor is
76
+ * reported once rather than on every reset.
77
+ */
78
+ defaults = /* @__PURE__ */ new Map();
79
+ constructor(parameters) {
80
+ for (const param of parameters) {
81
+ this.params.set(param.id, param);
82
+ if (!Number.isFinite(param.default)) {
83
+ console.error(
84
+ `Iki: parameter "${param.id}" has a non-finite default; resting at the neutral in-range value instead`
85
+ );
86
+ }
87
+ const base = Number.isFinite(param.default) ? param.default : 0;
88
+ this.defaults.set(param.id, clamp(base, param.min, param.max));
89
+ }
90
+ for (const [id, value] of this.defaults) this.values.set(id, value);
91
+ }
92
+ /**
93
+ * Set a parameter's value, clamped to its range. Unknown ids are ignored, as
94
+ * are non-finite values: this is the boundary a host drives with live signals,
95
+ * and `clamp` cannot filter NaN (`Math.max(min, Math.min(max, NaN))` is NaN),
96
+ * so one bad lip-sync/gaze frame would otherwise poison every binding that
97
+ * reads the parameter. A dropped write holds the last good pose.
98
+ */
99
+ set(id, value) {
100
+ const param = this.params.get(id);
101
+ if (!param) return;
102
+ if (!Number.isFinite(value)) return;
103
+ this.values.set(id, clamp(value, param.min, param.max));
104
+ }
105
+ /** Current value, or 0 if the id is unknown. */
106
+ get(id) {
107
+ return this.values.get(id) ?? 0;
108
+ }
109
+ /** Position of a parameter within its range, 0..1. */
110
+ normalized(id) {
111
+ const param = this.params.get(id);
112
+ if (!param || param.max === param.min) return 0;
113
+ return (this.get(id) - param.min) / (param.max - param.min);
114
+ }
115
+ /** Reset every parameter to its resting value (see `defaults`). */
116
+ reset() {
117
+ for (const [id, value] of this.defaults) this.values.set(id, value);
118
+ }
119
+ list() {
120
+ return [...this.params.values()];
121
+ }
122
+ };
123
+
124
+ // ../engine/src/affine.ts
125
+ function translate(tx, ty) {
126
+ return [1, 0, 0, 1, tx, ty];
127
+ }
128
+ function scale(sx, sy) {
129
+ return [sx, 0, 0, sy, 0, 0];
130
+ }
131
+ function rotate(degrees) {
132
+ const r = degrees * Math.PI / 180;
133
+ const c = Math.cos(r);
134
+ const s = Math.sin(r);
135
+ return [c, s, -s, c, 0, 0];
136
+ }
137
+ function multiply(a, b) {
138
+ return [
139
+ a[0] * b[0] + a[2] * b[1],
140
+ a[1] * b[0] + a[3] * b[1],
141
+ a[0] * b[2] + a[2] * b[3],
142
+ a[1] * b[2] + a[3] * b[3],
143
+ a[0] * b[4] + a[2] * b[5] + a[4],
144
+ a[1] * b[4] + a[3] * b[5] + a[5]
145
+ ];
146
+ }
147
+
148
+ // ../engine/src/warp.ts
149
+ function accumulateKeyformOffsets(keyforms, value, out) {
150
+ const ks = keyforms;
151
+ if (value <= ks[0].value) {
152
+ const { offsets } = ks[0];
153
+ for (let i = 0; i < offsets.length; i++) {
154
+ out[i] += offsets[i];
155
+ }
156
+ } else if (value >= ks[ks.length - 1].value) {
157
+ const { offsets } = ks[ks.length - 1];
158
+ for (let i = 0; i < offsets.length; i++) {
159
+ out[i] += offsets[i];
160
+ }
161
+ } else {
162
+ let lo = ks[0];
163
+ let hi = ks[1];
164
+ for (let k = 1; k < ks.length - 1; k++) {
165
+ if (ks[k].value <= value) {
166
+ lo = ks[k];
167
+ hi = ks[k + 1];
168
+ }
169
+ }
170
+ const t = (value - lo.value) / (hi.value - lo.value);
171
+ const loOff = lo.offsets;
172
+ const hiOff = hi.offsets;
173
+ for (let i = 0; i < loOff.length; i++) {
174
+ out[i] += loOff[i] + (hiOff[i] - loOff[i]) * t;
175
+ }
176
+ }
177
+ }
178
+ function accumulate2DKeyformOffsets(valuesX, valuesY, keyforms2d, vx, vy, out) {
179
+ const lastX = valuesX.length - 1;
180
+ const lastY = valuesY.length - 1;
181
+ let ix;
182
+ let tx;
183
+ if (vx <= valuesX[0]) {
184
+ ix = 0;
185
+ tx = 0;
186
+ } else if (vx >= valuesX[lastX]) {
187
+ ix = lastX - 1;
188
+ tx = 1;
189
+ } else {
190
+ ix = 0;
191
+ for (let k = 0; k < lastX - 1; k++) {
192
+ if (valuesX[k + 1] <= vx) ix = k + 1;
193
+ }
194
+ tx = (vx - valuesX[ix]) / (valuesX[ix + 1] - valuesX[ix]);
195
+ }
196
+ let iy;
197
+ let ty;
198
+ if (vy <= valuesY[0]) {
199
+ iy = 0;
200
+ ty = 0;
201
+ } else if (vy >= valuesY[lastY]) {
202
+ iy = lastY - 1;
203
+ ty = 1;
204
+ } else {
205
+ iy = 0;
206
+ for (let k = 0; k < lastY - 1; k++) {
207
+ if (valuesY[k + 1] <= vy) iy = k + 1;
208
+ }
209
+ ty = (vy - valuesY[iy]) / (valuesY[iy + 1] - valuesY[iy]);
210
+ }
211
+ const W = valuesX.length;
212
+ const c00 = keyforms2d[iy * W + ix];
213
+ const c10 = keyforms2d[iy * W + ix + 1];
214
+ const c01 = keyforms2d[(iy + 1) * W + ix];
215
+ const c11 = keyforms2d[(iy + 1) * W + ix + 1];
216
+ const o00 = c00.offsets;
217
+ const o10 = c10.offsets;
218
+ const o01 = c01.offsets;
219
+ const o11 = c11.offsets;
220
+ for (let n = 0; n < o00.length; n++) {
221
+ const top = o00[n] + (o10[n] - o00[n]) * tx;
222
+ const bot = o01[n] + (o11[n] - o01[n]) * tx;
223
+ out[n] += top + (bot - top) * ty;
224
+ }
225
+ }
226
+ function applyWarps(rest, warps, params, out) {
227
+ out.set(rest);
228
+ if (!warps || warps.length === 0) return;
229
+ for (const warp of warps) {
230
+ accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), out);
231
+ }
232
+ }
233
+
234
+ // ../engine/src/warp-grid.ts
235
+ function deformWarpGrid(d, params) {
236
+ const points = Float32Array.from(d.grid.points);
237
+ for (const warp of d.warps ?? []) {
238
+ accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), points);
239
+ }
240
+ if (d.warp2d !== void 0) {
241
+ accumulate2DKeyformOffsets(
242
+ d.warp2d.valuesX,
243
+ d.warp2d.valuesY,
244
+ d.warp2d.keyforms2d,
245
+ params.get(d.warp2d.parameter),
246
+ params.get(d.warp2d.parameterY),
247
+ points
248
+ );
249
+ }
250
+ return points;
251
+ }
252
+ function transformGridPoints(points, affine, out = new Float32Array(points.length)) {
253
+ for (let i = 0; i < points.length; i += 2) {
254
+ const x = points[i];
255
+ const y = points[i + 1];
256
+ out[i] = affine[0] * x + affine[2] * y + affine[4];
257
+ out[i + 1] = affine[1] * x + affine[3] * y + affine[5];
258
+ }
259
+ return out;
260
+ }
261
+ function bindPointToRestGrid(x, y, restGrid) {
262
+ const { cols, rows, points } = restGrid;
263
+ const stride = cols + 1;
264
+ let col = cols - 1;
265
+ for (let c = 0; c < cols; c++) {
266
+ const xRight2 = points[(c + 1) * 2];
267
+ if (x < xRight2) {
268
+ col = c;
269
+ break;
270
+ }
271
+ }
272
+ const xLeft = points[col * 2];
273
+ const xRight = points[(col + 1) * 2];
274
+ const s = clamp((x - xLeft) / (xRight - xLeft), 0, 1);
275
+ let row = rows - 1;
276
+ for (let r = 0; r < rows; r++) {
277
+ const yBottom2 = points[(r + 1) * stride * 2 + 1];
278
+ if (y > yBottom2) {
279
+ row = r;
280
+ break;
281
+ }
282
+ }
283
+ const yTop = points[row * stride * 2 + 1];
284
+ const yBottom = points[(row + 1) * stride * 2 + 1];
285
+ const t = clamp((yTop - y) / (yTop - yBottom), 0, 1);
286
+ return { cell: row * cols + col, s, t };
287
+ }
288
+ function applyWarpToChild(localVerts, partAffine, restGrid, deformedGrid, out) {
289
+ const n = localVerts.length / 2;
290
+ for (let v = 0; v < n; v++) {
291
+ const lx = localVerts[v * 2];
292
+ const ly = localVerts[v * 2 + 1];
293
+ const mx = partAffine[0] * lx + partAffine[2] * ly + partAffine[4];
294
+ const my = partAffine[1] * lx + partAffine[3] * ly + partAffine[5];
295
+ const binding = bindPointToRestGrid(mx, my, restGrid);
296
+ const [sx, sy] = sampleWarpGrid(deformedGrid, binding);
297
+ out[v * 2] = sx;
298
+ out[v * 2 + 1] = sy;
299
+ }
300
+ }
301
+ function sampleWarpGrid(grid, binding) {
302
+ const { cols, points } = grid;
303
+ const stride = cols + 1;
304
+ const row = Math.floor(binding.cell / cols);
305
+ const col = binding.cell % cols;
306
+ const { s, t } = binding;
307
+ const i00 = (row * stride + col) * 2;
308
+ const i10 = (row * stride + col + 1) * 2;
309
+ const i01 = ((row + 1) * stride + col) * 2;
310
+ const i11 = ((row + 1) * stride + col + 1) * 2;
311
+ const topX = points[i00] + (points[i10] - points[i00]) * s;
312
+ const topY = points[i00 + 1] + (points[i10 + 1] - points[i00 + 1]) * s;
313
+ const botX = points[i01] + (points[i11] - points[i01]) * s;
314
+ const botY = points[i01 + 1] + (points[i11 + 1] - points[i01 + 1]) * s;
315
+ return [topX + (botX - topX) * t, topY + (botY - topY) * t];
316
+ }
317
+ function warpRigidFrame(pivot, restGrid, localPoints) {
318
+ const { cols, rows } = restGrid;
319
+ const binding = bindPointToRestGrid(pivot.x, pivot.y, restGrid);
320
+ const [px2, py] = sampleWarpGrid({ cols, rows, points: localPoints }, binding);
321
+ const stride = cols + 1;
322
+ const row = Math.floor(binding.cell / cols);
323
+ const col = binding.cell % cols;
324
+ const { s, t } = binding;
325
+ const i00 = (row * stride + col) * 2;
326
+ const i10 = (row * stride + col + 1) * 2;
327
+ const i01 = ((row + 1) * stride + col) * 2;
328
+ const i11 = ((row + 1) * stride + col + 1) * 2;
329
+ const rest = restGrid.points;
330
+ const cellWidth = rest[(col + 1) * 2] - rest[col * 2];
331
+ const cellHeight = rest[row * stride * 2 + 1] - rest[(row + 1) * stride * 2 + 1];
332
+ const q = localPoints;
333
+ const exX = lerp(q[i10] - q[i00], q[i11] - q[i01], t) / cellWidth;
334
+ const exY = lerp(q[i10 + 1] - q[i00 + 1], q[i11 + 1] - q[i01 + 1], t) / cellWidth;
335
+ const eyX = -lerp(q[i01] - q[i00], q[i11] - q[i10], s) / cellHeight;
336
+ const eyY = -lerp(q[i01 + 1] - q[i00 + 1], q[i11 + 1] - q[i10 + 1], s) / cellHeight;
337
+ const theta = Math.atan2(exY - eyX, exX + eyY);
338
+ const c = Math.cos(theta);
339
+ const sn = Math.sin(theta);
340
+ return [
341
+ c,
342
+ sn,
343
+ -sn,
344
+ c,
345
+ px2 - (c * pivot.x - sn * pivot.y),
346
+ py - (sn * pivot.x + c * pivot.y)
347
+ ];
348
+ }
349
+
350
+ // ../engine/src/deform.ts
351
+ var IDENTITY_TRANSFORM = {
352
+ x: 0,
353
+ y: 0,
354
+ rotation: 0,
355
+ scaleX: 1,
356
+ scaleY: 1,
357
+ opacity: 1
358
+ };
359
+ function evaluateTransform(transform, bindings, params) {
360
+ const base = transform ?? IDENTITY_TRANSFORM;
361
+ const result = {
362
+ x: base.x,
363
+ y: base.y,
364
+ rotation: base.rotation ?? 0,
365
+ scaleX: base.scaleX ?? 1,
366
+ scaleY: base.scaleY ?? 1,
367
+ opacity: base.opacity ?? 1
368
+ };
369
+ for (const binding of bindings ?? []) {
370
+ const t = params.normalized(binding.parameter);
371
+ const value = binding.from + (binding.to - binding.from) * t;
372
+ switch (binding.channel) {
373
+ case "translateX":
374
+ result.x += value;
375
+ break;
376
+ case "translateY":
377
+ result.y += value;
378
+ break;
379
+ case "rotate":
380
+ result.rotation += value;
381
+ break;
382
+ case "scaleX":
383
+ result.scaleX += value;
384
+ break;
385
+ case "scaleY":
386
+ result.scaleY += value;
387
+ break;
388
+ case "opacity":
389
+ result.opacity *= value;
390
+ break;
391
+ }
392
+ }
393
+ return result;
394
+ }
395
+ function deformerLocalMatrix(d, params) {
396
+ const t = evaluateTransform(d.transform, d.bindings, params);
397
+ const trs = multiply(
398
+ multiply(translate(t.x, t.y), rotate(t.rotation)),
399
+ scale(t.scaleX, t.scaleY)
400
+ );
401
+ return multiply(
402
+ multiply(translate(d.pivot.x, d.pivot.y), trs),
403
+ translate(-d.pivot.x, -d.pivot.y)
404
+ );
405
+ }
406
+ function resolveDeformers(deformers, params) {
407
+ const byId = new Map(deformers.map((d) => [d.id, d]));
408
+ const worlds = /* @__PURE__ */ new Map();
409
+ const grids = /* @__PURE__ */ new Map();
410
+ const localWarps = /* @__PURE__ */ new Map();
411
+ function parentOf(d) {
412
+ if (d.parent === void 0) return void 0;
413
+ const parent = byId.get(d.parent);
414
+ if (!parent) {
415
+ throw new Error(
416
+ `unresolved deformer parent "${d.parent}" \u2014 model not validated?`
417
+ );
418
+ }
419
+ return parent;
420
+ }
421
+ function resolveWorld(d) {
422
+ const cached = worlds.get(d.id);
423
+ if (cached) return cached;
424
+ const local = deformerLocalMatrix(d, params);
425
+ const parent = parentOf(d);
426
+ let world;
427
+ if (parent === void 0) {
428
+ world = local;
429
+ } else if (parent.kind === "warp") {
430
+ const warp = resolveWarp(parent);
431
+ const ridden = multiply(
432
+ warpRigidFrame(d.pivot, parent.grid, warp.localGrid),
433
+ local
434
+ );
435
+ world = warp.parentWorld ? multiply(warp.parentWorld, ridden) : ridden;
436
+ } else {
437
+ world = multiply(resolveWorld(parent), local);
438
+ }
439
+ worlds.set(d.id, world);
440
+ return world;
441
+ }
442
+ function resolveWarp(d) {
443
+ const cached = localWarps.get(d.id);
444
+ if (cached) return cached;
445
+ const parent = parentOf(d);
446
+ if (parent?.kind === "warp") {
447
+ throw new Error(
448
+ `warp deformer "${d.id}" hangs from warp "${parent.id}" \u2014 model not validated?`
449
+ );
450
+ }
451
+ const parentWorld = parent && resolveWorld(parent);
452
+ const localGrid = deformWarpGrid(d, params);
453
+ grids.set(d.id, {
454
+ cols: d.grid.cols,
455
+ rows: d.grid.rows,
456
+ points: parentWorld ? transformGridPoints(localGrid, parentWorld) : localGrid
457
+ });
458
+ const resolved = { localGrid, parentWorld };
459
+ localWarps.set(d.id, resolved);
460
+ return resolved;
461
+ }
462
+ for (const d of deformers) {
463
+ if (d.kind === "warp") resolveWarp(d);
464
+ else resolveWorld(d);
465
+ }
466
+ return { worlds, grids };
467
+ }
468
+
469
+ // ../engine/src/idle-motion.ts
48
470
  var import_format = require("@ikijs/format");
49
- var import_editor2 = require("@ikijs/editor");
471
+
472
+ // ../engine/src/frame-clock.ts
473
+ var FIXED_DT_S = 1 / 60;
474
+
475
+ // ../engine/src/idle-motion.ts
476
+ var BLINK_CLOSE_MS = 60;
477
+ var BLINK_HOLD_MS = 20;
478
+ var BLINK_OPEN_MS = 100;
479
+ var BLINK_DURATION_MS = BLINK_CLOSE_MS + BLINK_HOLD_MS + BLINK_OPEN_MS;
480
+
481
+ // ../engine/src/hair-chain-motion.ts
482
+ var DEG2RAD = Math.PI / 180;
483
+ var RAD2DEG = 180 / Math.PI;
484
+
485
+ // ../engine/src/iki-motion.ts
486
+ var import_format4 = require("@ikijs/format");
487
+
488
+ // ../engine/src/clip-player.ts
489
+ var import_format2 = require("@ikijs/format");
490
+
491
+ // ../engine/src/expression-player.ts
492
+ var import_format3 = require("@ikijs/format");
493
+
494
+ // ../engine/src/iki-motion.ts
495
+ var HEAD_AND_GAZE = /* @__PURE__ */ new Set([
496
+ import_format4.StandardParameter.AngleX,
497
+ import_format4.StandardParameter.AngleY,
498
+ import_format4.StandardParameter.AngleZ,
499
+ import_format4.StandardParameter.EyeballX,
500
+ import_format4.StandardParameter.EyeballY
501
+ ]);
502
+
503
+ // ../engine/src/folds.ts
504
+ var import_format5 = require("@ikijs/format");
505
+ var FLIP = 0;
506
+ var COLLAPSE = 0.1;
507
+ var ANGLES = [
508
+ import_format5.StandardParameter.AngleX,
509
+ import_format5.StandardParameter.AngleY,
510
+ import_format5.StandardParameter.AngleZ,
511
+ import_format5.StandardParameter.BodyAngleX,
512
+ import_format5.StandardParameter.BodyAngleY,
513
+ import_format5.StandardParameter.BodyAngleZ
514
+ ];
515
+ var CROSSES = [
516
+ [import_format5.StandardParameter.EyeOpenLeft],
517
+ [import_format5.StandardParameter.EyeOpenRight],
518
+ [import_format5.StandardParameter.MouthOpen],
519
+ [import_format5.StandardParameter.ArmLeft, import_format5.StandardParameter.ArmRight],
520
+ [import_format5.StandardParameter.ElbowLeft, import_format5.StandardParameter.ElbowRight]
521
+ ];
522
+ function foldPoses(model) {
523
+ const byId = new Map(
524
+ model.parameters.filter((p) => p.min !== p.max).map((p) => [p.id, p])
525
+ );
526
+ const declared = (ids) => ids.flatMap((id) => byId.get(id) ?? []);
527
+ const poses = [];
528
+ const names = /* @__PURE__ */ new Set();
529
+ const add = (values) => {
530
+ const name = poseName(values);
531
+ if (names.has(name)) return;
532
+ names.add(name);
533
+ poses.push({ name, values });
534
+ };
535
+ add({});
536
+ for (const p of byId.values()) {
537
+ add({ [p.id]: p.min });
538
+ add({ [p.id]: p.max });
539
+ }
540
+ const angles = declared(ANGLES);
541
+ if (angles.length === 0) return poses;
542
+ const expand = (corners, groups) => {
543
+ for (const group of groups) {
544
+ corners = corners.flatMap(
545
+ (values) => ["min", "max"].map((end) => {
546
+ const next = { ...values };
547
+ for (const p of group) next[p.id] = p[end];
548
+ return next;
549
+ })
550
+ );
551
+ }
552
+ return corners;
553
+ };
554
+ const angleCorners = expand(
555
+ [{}],
556
+ angles.map((p) => [p])
557
+ );
558
+ for (const values of angleCorners) add(values);
559
+ const crosses = CROSSES.map(declared).filter((g) => g.length > 0);
560
+ for (const values of expand(angleCorners, crosses)) add(values);
561
+ return poses;
562
+ }
563
+ function poseName(values) {
564
+ const ids = Object.keys(values).sort();
565
+ if (ids.length === 0) return "rest";
566
+ return ids.map((id) => `${id}=${values[id]}`).join(" ");
567
+ }
568
+ function staticDeformers(model) {
569
+ return (model.deformers ?? []).map(
570
+ (d) => d.kind === "warp" ? { ...d, warps: void 0, warp2d: void 0 } : { ...d, bindings: void 0 }
571
+ );
572
+ }
573
+ function cornerAreas(points, cols, rows) {
574
+ const stride = cols + 1;
575
+ const out = new Float64Array(cols * rows * 4);
576
+ for (let r = 0; r < rows; r++) {
577
+ for (let c = 0; c < cols; c++) {
578
+ const tl = r * stride + c;
579
+ const [tr, bl, br] = [tl + 1, tl + stride, tl + stride + 1];
580
+ const i = (r * cols + c) * 4;
581
+ out[i] = doubledArea(points, bl, br, tl);
582
+ out[i + 1] = doubledArea(points, br, tr, bl);
583
+ out[i + 2] = doubledArea(points, tr, tl, br);
584
+ out[i + 3] = doubledArea(points, tl, bl, tr);
585
+ }
586
+ }
587
+ return out;
588
+ }
589
+ function doubledArea(points, p, q, s) {
590
+ const ax = points[q * 2] - points[p * 2];
591
+ const ay = points[q * 2 + 1] - points[p * 2 + 1];
592
+ const bx = points[s * 2] - points[p * 2];
593
+ const by = points[s * 2 + 1] - points[p * 2 + 1];
594
+ return ax * by - ay * bx;
595
+ }
596
+ function triangleAreas(points, indices) {
597
+ const out = new Float64Array(indices.length / 3);
598
+ for (let t = 0; t < out.length; t++) {
599
+ const i = t * 3;
600
+ out[t] = doubledArea(points, indices[i], indices[i + 1], indices[i + 2]);
601
+ }
602
+ return out;
603
+ }
604
+ function placement(part, t) {
605
+ return multiply(
606
+ multiply(translate(t.x, t.y), rotate(t.rotation)),
607
+ scale(part.width * t.scaleX, part.height * t.scaleY)
608
+ );
609
+ }
610
+ function keepLeast(sweep, areas, pose, expected) {
611
+ const slot = expected(sweep.target) ? "expected" : "worst";
612
+ for (let i = 0; i < areas.length; i++) {
613
+ const rest = sweep.restAreas[i];
614
+ if (Math.abs(rest) < sweep.tiny) continue;
615
+ const ratio = areas[i] / rest;
616
+ if (ratio < (sweep[slot]?.ratio ?? Infinity)) {
617
+ sweep[slot] = { ratio, at: i, pose };
618
+ }
619
+ }
620
+ }
621
+ function partSweep(part, mesh, deformers, worlds, store) {
622
+ const warpDeformer = deformers.find(
623
+ (d) => d.kind === "warp" && d.id === part.deformer
624
+ );
625
+ const frame = warpDeformer ? warpDeformer.parent : part.deformer;
626
+ const placed = placement(
627
+ part,
628
+ evaluateTransform(part.transform, void 0, store)
629
+ );
630
+ const restPoints = transformGridPoints(
631
+ mesh.vertices,
632
+ frame === void 0 ? placed : multiply(worlds.get(frame), placed),
633
+ new Float64Array(mesh.vertices.length)
634
+ );
635
+ return {
636
+ target: { kind: "part", id: part.id },
637
+ restAreas: triangleAreas(restPoints, mesh.indices),
638
+ tiny: 1e-9 * part.width * part.height,
639
+ part,
640
+ indices: mesh.indices,
641
+ warpDeformer,
642
+ vertices: Float32Array.from(mesh.vertices),
643
+ local: new Float32Array(mesh.vertices.length),
644
+ landed: new Float32Array(mesh.vertices.length),
645
+ restPoints
646
+ };
647
+ }
648
+ function landPart(sweep, store, { worlds, grids }) {
649
+ const { part, warpDeformer, local, landed } = sweep;
650
+ applyWarps(sweep.vertices, part.warps, store, local);
651
+ const placed = placement(
652
+ part,
653
+ evaluateTransform(part.transform, part.bindings, store)
654
+ );
655
+ if (warpDeformer) {
656
+ const grid = grids.get(warpDeformer.id);
657
+ applyWarpToChild(local, placed, warpDeformer.grid, grid, landed);
658
+ } else if (part.deformer !== void 0) {
659
+ const world = worlds.get(part.deformer);
660
+ transformGridPoints(local, multiply(world, placed), landed);
661
+ } else {
662
+ transformGridPoints(local, placed, landed);
663
+ }
664
+ return landed;
665
+ }
666
+ function checkFolds(model, options = {}) {
667
+ const poses = options.poses ?? foldPoses(model);
668
+ const deformers = model.deformers ?? [];
669
+ const restStore = new ParameterStore(model.parameters);
670
+ const { worlds } = resolveDeformers(staticDeformers(model), restStore);
671
+ const gridSweeps = [];
672
+ for (const d of deformers) {
673
+ if (d.kind !== "warp") continue;
674
+ const { cols, rows, points } = d.grid;
675
+ const width = points[cols * 2] - points[0];
676
+ const height = points[1] - points[rows * (cols + 1) * 2 + 1];
677
+ gridSweeps.push({
678
+ deformer: d,
679
+ target: { kind: "deformer", id: d.id },
680
+ restAreas: cornerAreas(points, cols, rows),
681
+ // The validator tolerates 1e-6 of jitter, which can zero a corner's area.
682
+ tiny: 1e-9 * width * height
683
+ });
684
+ }
685
+ const partSweeps = model.parts.flatMap(
686
+ (part) => part.mesh ? [partSweep(part, part.mesh, deformers, worlds, restStore)] : []
687
+ );
688
+ for (const pose of poses) {
689
+ const store = new ParameterStore(model.parameters);
690
+ for (const [id, v] of Object.entries(pose.values)) store.set(id, v);
691
+ const value = (id) => store.get(id);
692
+ const expected = (target) => options.expected?.(target, pose, value) === true;
693
+ for (const sweep of gridSweeps) {
694
+ const { cols, rows } = sweep.deformer.grid;
695
+ const areas = cornerAreas(
696
+ deformWarpGrid(sweep.deformer, store),
697
+ cols,
698
+ rows
699
+ );
700
+ keepLeast(sweep, areas, pose, expected);
701
+ }
702
+ const resolved = resolveDeformers(deformers, store);
703
+ for (const sweep of partSweeps) {
704
+ const areas = triangleAreas(
705
+ landPart(sweep, store, resolved),
706
+ sweep.indices
707
+ );
708
+ keepLeast(sweep, areas, pose, expected);
709
+ }
710
+ }
711
+ const targets = [
712
+ ...gridSweeps.map((sweep) => {
713
+ const { parent } = sweep.deformer;
714
+ const world = parent === void 0 ? void 0 : worlds.get(parent);
715
+ return foldTarget(
716
+ sweep,
717
+ (least) => cellHit(sweep.deformer, least, world)
718
+ );
719
+ }),
720
+ ...partSweeps.map(
721
+ (sweep) => foldTarget(sweep, (least) => triangleHit(sweep, least))
722
+ )
723
+ ];
724
+ const offenders = targets.filter((t) => t.kind !== "ok").sort((a, b) => a.worst.ratio - b.worst.ratio);
725
+ return {
726
+ poses: poses.length,
727
+ thresholds: { flip: FLIP, collapse: COLLAPSE },
728
+ targets,
729
+ offenders
730
+ };
731
+ }
732
+ function foldTarget(sweep, hit) {
733
+ const worst = sweep.worst && hit(sweep.worst);
734
+ const expected = sweep.expected && hit(sweep.expected);
735
+ return { target: sweep.target, kind: classify(worst), worst, expected };
736
+ }
737
+ function cellHit(d, least, parent) {
738
+ const { cols, points } = d.grid;
739
+ const cell = Math.floor(least.at / 4);
740
+ const col = cell % cols;
741
+ const row = Math.floor(cell / cols);
742
+ const stride = cols + 1;
743
+ let x = 0;
744
+ let y = 0;
745
+ for (const i of [
746
+ row * stride + col,
747
+ row * stride + col + 1,
748
+ (row + 1) * stride + col,
749
+ (row + 1) * stride + col + 1
750
+ ]) {
751
+ x += points[i * 2] / 4;
752
+ y += points[i * 2 + 1] / 4;
753
+ }
754
+ const rest = parent ? {
755
+ x: parent[0] * x + parent[2] * y + parent[4],
756
+ y: parent[1] * x + parent[3] * y + parent[5]
757
+ } : { x, y };
758
+ return { ratio: least.ratio, where: { col, row }, pose: least.pose, rest };
759
+ }
760
+ function triangleHit(sweep, least) {
761
+ const { indices, restPoints } = sweep;
762
+ let x = 0;
763
+ let y = 0;
764
+ for (let k = 0; k < 3; k++) {
765
+ const i = indices[least.at * 3 + k];
766
+ x += restPoints[i * 2] / 3;
767
+ y += restPoints[i * 2 + 1] / 3;
768
+ }
769
+ return {
770
+ ratio: least.ratio,
771
+ where: { triangle: least.at },
772
+ pose: least.pose,
773
+ rest: { x, y }
774
+ };
775
+ }
776
+ function classify(worst) {
777
+ if (worst === void 0) return "ok";
778
+ if (worst.ratio <= FLIP) return "flip";
779
+ if (worst.ratio < COLLAPSE) return "collapse";
780
+ return "ok";
781
+ }
782
+
783
+ // src/fold-report.ts
784
+ var import_format6 = require("@ikijs/format");
785
+ var SHUT_BY = new Map([
786
+ ["eye_L", import_format6.StandardParameter.EyeOpenLeft],
787
+ ["lash_lower_L", import_format6.StandardParameter.EyeOpenLeft],
788
+ ["eye_R", import_format6.StandardParameter.EyeOpenRight],
789
+ ["lash_lower_R", import_format6.StandardParameter.EyeOpenRight],
790
+ ...[...import_editor.LIP_ROLES, ...import_editor.LIP_INSIDE_ROLES].map((id) => [
791
+ id,
792
+ import_format6.StandardParameter.MouthOpen
793
+ ])
794
+ ]);
795
+ function checkModelFolds(model) {
796
+ const declared = new Set(model.parameters.map((p) => p.id));
797
+ return checkFolds(model, {
798
+ // The effective value, not the pose's overrides: the auto-rig's mouth
799
+ // rests shut at its default, so `rest` and the other parameters' singles
800
+ // are shut-mouth poses too.
801
+ expected: (target, _pose, value) => {
802
+ if (target.kind !== "part") return false;
803
+ const shutBy = SHUT_BY.get(target.id);
804
+ return shutBy !== void 0 && declared.has(shutBy) && value(shutBy) === 0;
805
+ }
806
+ });
807
+ }
808
+ function formatFoldReport(report, canvas) {
809
+ const lines = report.offenders.length === 0 ? [`FOLDS: none over ${report.poses} poses`] : report.offenders.map((t) => offenderLine(t, t.worst, canvas));
810
+ const closures = report.targets.flatMap((t) => {
811
+ if (t.expected === void 0) return [];
812
+ if (t.expected.ratio >= report.thresholds.collapse) return [];
813
+ const shutBy = SHUT_BY.get(t.target.id);
814
+ const at = shutBy === void 0 ? "" : ` at ${shutBy}=0`;
815
+ return [`${t.target.id} ${ratioText(t.expected.ratio)}${at}`];
816
+ });
817
+ if (closures.length > 0) {
818
+ lines.push(
819
+ `FOLDS expected: by-design closures, not findings \u2014 ${closures.join(", ")}`
820
+ );
821
+ }
822
+ return lines;
823
+ }
824
+ function offenderLine(t, hit, canvas) {
825
+ const where = "triangle" in hit.where ? `triangle ${hit.where.triangle}` : `cell (${hit.where.col},${hit.where.row})`;
826
+ const { x, y } = hit.rest;
827
+ 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`;
828
+ }
829
+ function ratioText(ratio) {
830
+ if (ratio === 0) return "0";
831
+ return Math.abs(ratio) < 0.01 ? ratio.toExponential(1) : ratio.toFixed(2);
832
+ }
50
833
 
51
834
  // src/node-images.ts
52
835
  var import_sharp = __toESM(require("sharp"));
53
- var import_editor = require("@ikijs/editor");
836
+ var import_editor2 = require("@ikijs/editor");
54
837
 
55
838
  // src/limits.ts
56
839
  var import_node_fs = __toESM(require("fs"));
@@ -78,18 +861,18 @@ function rejectEmptyOrUrl(inputPath, noun, kind) {
78
861
  );
79
862
  }
80
863
  }
81
- function resolveInputPath(inputPath) {
82
- rejectEmptyOrUrl(inputPath, "layer path", "file path");
864
+ function resolveInputPath(inputPath, what = "layer") {
865
+ rejectEmptyOrUrl(inputPath, `${what} path`, "file path");
83
866
  const resolved = import_node_path.default.resolve(process.cwd(), inputPath);
84
867
  let stat;
85
868
  try {
86
869
  stat = import_node_fs.default.statSync(resolved);
87
870
  } catch {
88
- throw new AutoRigInputError(`layer file not found: ${resolved}`);
871
+ throw new AutoRigInputError(`${what} file not found: ${resolved}`);
89
872
  }
90
873
  if (stat.isDirectory()) {
91
874
  throw new AutoRigInputError(
92
- `layer path is a directory, not a file: ${resolved}`
875
+ `${what} path is a directory, not a file: ${resolved}`
93
876
  );
94
877
  }
95
878
  return resolved;
@@ -206,7 +989,7 @@ async function decodePng(filePath) {
206
989
  }
207
990
  }
208
991
  function detectAlphaBbox(rgba, width, height) {
209
- const bbox = (0, import_editor.detectAlphaBbox)(rgba, width, height);
992
+ const bbox = (0, import_editor2.detectAlphaBbox)(rgba, width, height);
210
993
  if (bbox === null) {
211
994
  throw new AutoRigInputError("layer is empty after alpha threshold");
212
995
  }
@@ -223,15 +1006,15 @@ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
223
1006
  for (const crop of crops) byId.set(crop.id, crop);
224
1007
  const pad = layout.padding;
225
1008
  const composites = await Promise.all(
226
- layout.placements.map(async (placement2) => {
227
- const crop = byId.get(placement2.id);
1009
+ layout.placements.map(async (placement3) => {
1010
+ const crop = byId.get(placement3.id);
228
1011
  if (crop === void 0) {
229
1012
  throw new AutoRigInputError(
230
- `no crop for atlas placement "${placement2.id}"`
1013
+ `no crop for atlas placement "${placement3.id}"`
231
1014
  );
232
1015
  }
233
1016
  const input = pad > 0 ? await (0, import_sharp.default)(crop.buffer).extend({ right: pad, bottom: pad, extendWith: "copy" }).png().toBuffer() : crop.buffer;
234
- return { input, left: placement2.x, top: placement2.y };
1017
+ return { input, left: placement3.x, top: placement3.y };
235
1018
  })
236
1019
  );
237
1020
  const page = await (0, import_sharp.default)({
@@ -250,10 +1033,10 @@ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
250
1033
  // src/tools.ts
251
1034
  function coerceModel(model) {
252
1035
  try {
253
- const parsed = typeof model === "string" ? (0, import_format.loadIkiModel)(model) : (0, import_format.parseIkiModel)(model);
1036
+ const parsed = typeof model === "string" ? (0, import_format7.loadIkiModel)(model) : (0, import_format7.parseIkiModel)(model);
254
1037
  return { ok: true, model: parsed };
255
1038
  } catch (e) {
256
- if (e instanceof import_format.IkiFormatError) return { ok: false, error: e.message };
1039
+ if (e instanceof import_format7.IkiFormatError) return { ok: false, error: e.message };
257
1040
  throw e;
258
1041
  }
259
1042
  }
@@ -327,115 +1110,115 @@ function describeIki(model) {
327
1110
  }
328
1111
  var STANDARD_PARAMETER_INFO = [
329
1112
  {
330
- id: import_format.StandardParameter.MouthOpen,
1113
+ id: import_format7.StandardParameter.MouthOpen,
331
1114
  description: "Mouth open amount for lip-sync (0 closed .. 1 open)."
332
1115
  },
333
1116
  {
334
- id: import_format.StandardParameter.MouthForm,
1117
+ id: import_format7.StandardParameter.MouthForm,
335
1118
  description: "Mouth form / smile (-1 .. 1)."
336
1119
  },
337
1120
  {
338
- id: import_format.StandardParameter.EyeOpenLeft,
1121
+ id: import_format7.StandardParameter.EyeOpenLeft,
339
1122
  description: "Left eye open (0 closed .. 1 open). Drive with the right eye for a blink."
340
1123
  },
341
1124
  {
342
- id: import_format.StandardParameter.EyeOpenRight,
1125
+ id: import_format7.StandardParameter.EyeOpenRight,
343
1126
  description: "Right eye open (0 closed .. 1 open)."
344
1127
  },
345
1128
  {
346
- id: import_format.StandardParameter.EyeballX,
1129
+ id: import_format7.StandardParameter.EyeballX,
347
1130
  description: "Eyeball gaze, horizontal (-1 .. 1)."
348
1131
  },
349
1132
  {
350
- id: import_format.StandardParameter.EyeballY,
1133
+ id: import_format7.StandardParameter.EyeballY,
351
1134
  description: "Eyeball gaze, vertical (-1 .. 1)."
352
1135
  },
353
1136
  {
354
- id: import_format.StandardParameter.AngleX,
1137
+ id: import_format7.StandardParameter.AngleX,
355
1138
  description: "Head angle, horizontal degrees."
356
1139
  },
357
1140
  {
358
- id: import_format.StandardParameter.AngleY,
1141
+ id: import_format7.StandardParameter.AngleY,
359
1142
  description: "Head angle, vertical degrees."
360
1143
  },
361
1144
  {
362
- id: import_format.StandardParameter.AngleZ,
1145
+ id: import_format7.StandardParameter.AngleZ,
363
1146
  description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
364
1147
  },
365
1148
  {
366
- id: import_format.StandardParameter.BodyAngleX,
1149
+ id: import_format7.StandardParameter.BodyAngleX,
367
1150
  description: "Body turn, degrees (-10 .. 10); positive turns the body toward the viewer's right, as AngleX does the head."
368
1151
  },
369
1152
  {
370
- id: import_format.StandardParameter.BodyAngleY,
1153
+ id: import_format7.StandardParameter.BodyAngleY,
371
1154
  description: "Body lean, degrees (-10 .. 10); positive moves the upper body up, negative bows."
372
1155
  },
373
1156
  {
374
- id: import_format.StandardParameter.BodyAngleZ,
1157
+ id: import_format7.StandardParameter.BodyAngleZ,
375
1158
  description: "Body tilt, degrees (-10 .. 10); positive tilts the top toward the viewer's right (clockwise), as AngleZ does the head."
376
1159
  },
377
1160
  {
378
- id: import_format.StandardParameter.Breath,
1161
+ id: import_format7.StandardParameter.Breath,
379
1162
  description: "Idle breath (0 .. 1), cycled by the host."
380
1163
  },
381
1164
  {
382
- id: import_format.StandardParameter.BrowLeftY,
1165
+ id: import_format7.StandardParameter.BrowLeftY,
383
1166
  description: "Left brow raise/lower (-1 .. 1)."
384
1167
  },
385
1168
  {
386
- id: import_format.StandardParameter.BrowRightY,
1169
+ id: import_format7.StandardParameter.BrowRightY,
387
1170
  description: "Right brow raise/lower (-1 .. 1)."
388
1171
  },
389
1172
  {
390
- id: import_format.StandardParameter.BrowLeftAngle,
1173
+ id: import_format7.StandardParameter.BrowLeftAngle,
391
1174
  description: "Left brow tilt/angle (-1 .. 1)."
392
1175
  },
393
1176
  {
394
- id: import_format.StandardParameter.BrowRightAngle,
1177
+ id: import_format7.StandardParameter.BrowRightAngle,
395
1178
  description: "Right brow tilt/angle (-1 .. 1)."
396
1179
  },
397
1180
  {
398
- id: import_format.StandardParameter.Cheek,
1181
+ id: import_format7.StandardParameter.Cheek,
399
1182
  description: "Cheek blush strength (0 .. 1), raised by an expression."
400
1183
  },
401
1184
  {
402
- id: import_format.StandardParameter.HairSwayX,
1185
+ id: import_format7.StandardParameter.HairSwayX,
403
1186
  description: "Horizontal hair-sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
404
1187
  },
405
1188
  {
406
- id: import_format.StandardParameter.HairSwayZ,
1189
+ id: import_format7.StandardParameter.HairSwayZ,
407
1190
  description: "Hair-sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
408
1191
  },
409
1192
  {
410
- id: import_format.StandardParameter.ArmLeft,
1193
+ id: import_format7.StandardParameter.ArmLeft,
411
1194
  description: "Left shoulder, degrees; positive raises the arm outward (mirrored on the right)."
412
1195
  },
413
1196
  {
414
- id: import_format.StandardParameter.ArmRight,
1197
+ id: import_format7.StandardParameter.ArmRight,
415
1198
  description: "Right shoulder, degrees; positive raises the arm outward (mirrored on the left)."
416
1199
  },
417
1200
  {
418
- id: import_format.StandardParameter.ElbowLeft,
1201
+ id: import_format7.StandardParameter.ElbowLeft,
419
1202
  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)."
420
1203
  },
421
1204
  {
422
- id: import_format.StandardParameter.ElbowRight,
1205
+ id: import_format7.StandardParameter.ElbowRight,
423
1206
  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)."
424
1207
  },
425
1208
  {
426
- id: import_format.StandardParameter.ArmPoseLeft,
1209
+ id: import_format7.StandardParameter.ArmPoseLeft,
427
1210
  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."
428
1211
  },
429
1212
  {
430
- id: import_format.StandardParameter.ArmPoseRight,
1213
+ id: import_format7.StandardParameter.ArmPoseRight,
431
1214
  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."
432
1215
  },
433
1216
  {
434
- id: import_format.StandardParameter.ArmPoseAngleLeft,
1217
+ id: import_format7.StandardParameter.ArmPoseAngleLeft,
435
1218
  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)."
436
1219
  },
437
1220
  {
438
- id: import_format.StandardParameter.ArmPoseAngleRight,
1221
+ id: import_format7.StandardParameter.ArmPoseAngleRight,
439
1222
  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)."
440
1223
  }
441
1224
  ];
@@ -453,7 +1236,7 @@ function expectInput(label, fn) {
453
1236
  }
454
1237
  var LOSSLESS_PAGE_ROLE = "nose";
455
1238
  async function renderAtlasPage(crops, quantizeColors) {
456
- const layout = (0, import_editor2.packAtlas)(
1239
+ const layout = (0, import_editor3.packAtlas)(
457
1240
  crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),
458
1241
  void 0,
459
1242
  MAX_ATLAS_SIDE
@@ -507,7 +1290,7 @@ async function autoRigFromLayers(input) {
507
1290
  });
508
1291
  const rolePairs = expectInput(
509
1292
  "role parsing",
510
- () => (0, import_editor2.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
1293
+ () => (0, import_editor3.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
511
1294
  );
512
1295
  const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));
513
1296
  let canvasW = 0;
@@ -537,7 +1320,7 @@ async function autoRigFromLayers(input) {
537
1320
  `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`
538
1321
  );
539
1322
  }
540
- measurer = (0, import_editor2.createLayerSetMeasurer)({ width: canvasW, height: canvasH });
1323
+ measurer = (0, import_editor3.createLayerSetMeasurer)({ width: canvasW, height: canvasH });
541
1324
  } else if (png.width !== canvasW || png.height !== canvasH) {
542
1325
  throw new AutoRigInputError(
543
1326
  `layer "${fileName}" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
@@ -566,7 +1349,7 @@ async function autoRigFromLayers(input) {
566
1349
  let turn;
567
1350
  let model;
568
1351
  try {
569
- model = (0, import_editor2.generateIkiFromLayerSet)(
1352
+ model = (0, import_editor3.generateIkiFromLayerSet)(
570
1353
  measurement.layers,
571
1354
  { width: canvasW, height: canvasH },
572
1355
  {
@@ -583,12 +1366,12 @@ async function autoRigFromLayers(input) {
583
1366
  }
584
1367
  );
585
1368
  } catch (e) {
586
- if (!(e instanceof import_editor2.TurnTargetError || e instanceof import_editor2.LayerGeometryError)) {
1369
+ if (!(e instanceof import_editor3.TurnTargetError || e instanceof import_editor3.LayerGeometryError)) {
587
1370
  throw e;
588
1371
  }
589
1372
  throw new AutoRigInputError(e.message);
590
1373
  }
591
- const doc = new import_editor2.EditorDocument(model);
1374
+ const doc = new import_editor3.EditorDocument(model);
592
1375
  const losslessCrop = quantizeColors === void 0 ? void 0 : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);
593
1376
  const pages = losslessCrop === void 0 ? [await renderAtlasPage(crops, quantizeColors)] : [
594
1377
  await renderAtlasPage(
@@ -605,15 +1388,15 @@ async function autoRigFromLayers(input) {
605
1388
  }
606
1389
  const partTextureAssignments = pages.flatMap(
607
1390
  ({ crops: pageCrops, layout }) => pageCrops.flatMap((crop) => {
608
- const placement2 = layout.placements.find((p) => p.id === crop.id);
609
- if (placement2 === void 0) {
1391
+ const placement3 = layout.placements.find((p) => p.id === crop.id);
1392
+ if (placement3 === void 0) {
610
1393
  throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
611
1394
  }
612
- const uv = (0, import_editor2.uvRectFor)(placement2, {
1395
+ const uv = (0, import_editor3.uvRectFor)(placement3, {
613
1396
  width: layout.pageWidth,
614
1397
  height: layout.pageHeight
615
1398
  });
616
- return (0, import_editor2.partIdsOfRole)(crop.id).map((partId) => ({ partId, uv }));
1399
+ return (0, import_editor3.partIdsOfRole)(crop.id).map((partId) => ({ partId, uv }));
617
1400
  })
618
1401
  );
619
1402
  doc.applyAtlas({
@@ -624,12 +1407,13 @@ async function autoRigFromLayers(input) {
624
1407
  if (losslessCrop !== void 0) {
625
1408
  patched = structuredClone(patched);
626
1409
  patched.textures = pages.map((p) => ({ source: p.dataUri }));
627
- for (const partId of (0, import_editor2.partIdsOfRole)(losslessCrop.id)) {
1410
+ for (const partId of (0, import_editor3.partIdsOfRole)(losslessCrop.id)) {
628
1411
  patched.parts.find((p) => p.id === partId).texture.index = 1;
629
1412
  }
630
1413
  }
631
- const finalModel = (0, import_format.parseIkiModel)(patched);
1414
+ const finalModel = (0, import_format7.parseIkiModel)(patched);
632
1415
  writeFileAtomic(outPath, JSON.stringify(finalModel));
1416
+ const folds = checkModelFolds(finalModel);
633
1417
  return {
634
1418
  ok: true,
635
1419
  path: outPath,
@@ -641,7 +1425,8 @@ async function autoRigFromLayers(input) {
641
1425
  ...headEdges === void 0 ? {} : { headEdges },
642
1426
  ...strandEdges === void 0 ? {} : { strandEdges },
643
1427
  ...noseCore === void 0 ? {} : { noseCore },
644
- ...turn === void 0 ? {} : { turn }
1428
+ ...turn === void 0 ? {} : { turn },
1429
+ folds
645
1430
  };
646
1431
  } catch (err) {
647
1432
  if (err instanceof AutoRigInputError)
@@ -654,10 +1439,10 @@ async function autoRigFromLayers(input) {
654
1439
  var import_node_fs3 = __toESM(require("fs"));
655
1440
  var import_node_path7 = __toESM(require("path"));
656
1441
  var import_sharp4 = __toESM(require("sharp"));
657
- var import_editor11 = require("@ikijs/editor");
1442
+ var import_editor12 = require("@ikijs/editor");
658
1443
 
659
1444
  // src/trim.ts
660
- var import_editor3 = require("@ikijs/editor");
1445
+ var import_editor4 = require("@ikijs/editor");
661
1446
  var TRIM_THRESHOLD = 12;
662
1447
  var STRAY_SPECK_FRACTION = 0.01;
663
1448
  function luma(rgba, i) {
@@ -686,7 +1471,7 @@ function boxWithoutStraySpecks(rgba, W, H) {
686
1471
  while (depth > 0) {
687
1472
  const p = stack[--depth];
688
1473
  size++;
689
- if (rgba[p * 4 + 3] >= import_editor3.ALPHA_OPAQUE) opaque = true;
1474
+ if (rgba[p * 4 + 3] >= import_editor4.ALPHA_OPAQUE) opaque = true;
690
1475
  const px2 = p % W;
691
1476
  const py = (p - px2) / W;
692
1477
  setLeft = Math.min(setLeft, px2);
@@ -728,7 +1513,7 @@ var import_node_path6 = __toESM(require("path"));
728
1513
 
729
1514
  // src/measure-arms.ts
730
1515
  var import_node_path3 = __toESM(require("path"));
731
- var import_editor4 = require("@ikijs/editor");
1516
+ var import_editor5 = require("@ikijs/editor");
732
1517
  var ARM_ROLES = ["arm_L", "arm_R"];
733
1518
  var CAP_OVERLAP = 0.5;
734
1519
  var px = (v) => `${Number(v.toFixed(1))}`;
@@ -757,7 +1542,7 @@ async function armWarnings(absDir, layers) {
757
1542
  continue;
758
1543
  }
759
1544
  if (set === void 0) {
760
- const measurer = (0, import_editor4.createLayerSetMeasurer)({
1545
+ const measurer = (0, import_editor5.createLayerSetMeasurer)({
761
1546
  width: body.canvasW,
762
1547
  height: body.canvasH
763
1548
  });
@@ -765,12 +1550,12 @@ async function armWarnings(absDir, layers) {
765
1550
  }
766
1551
  let g;
767
1552
  try {
768
- g = (0, import_editor4.armGeometry)(
1553
+ g = (0, import_editor5.armGeometry)(
769
1554
  await measured(set.measurer, absDir, arm),
770
1555
  set.body.bbox.x + set.body.bbox.w / 2 - body.canvasW / 2
771
1556
  );
772
1557
  } catch (err) {
773
- if (err instanceof import_editor4.LayerGeometryError) {
1558
+ if (err instanceof import_editor5.LayerGeometryError) {
774
1559
  warnings.push(
775
1560
  `${arm}: ${err.message} \u2014 auto_rig_from_layers refuses it. Regenerate arm.png drawn hanging, shoulder at the top. Billed.`
776
1561
  );
@@ -798,7 +1583,7 @@ function capWarning(arm, g, body) {
798
1583
  }
799
1584
 
800
1585
  // src/measure-forearm-pose.ts
801
- var import_editor5 = require("@ikijs/editor");
1586
+ var import_editor6 = require("@ikijs/editor");
802
1587
  var POSE_ROLES = ["forearm_pose_L", "forearm_pose_R"];
803
1588
  var ARM_OF = {
804
1589
  forearm_pose_L: "arm_L",
@@ -832,7 +1617,7 @@ async function forearmPoseWarnings(absDir, layers) {
832
1617
  continue;
833
1618
  }
834
1619
  if (layers.body === void 0) continue;
835
- const measurer = (0, import_editor5.createLayerSetMeasurer)({
1620
+ const measurer = (0, import_editor6.createLayerSetMeasurer)({
836
1621
  width: stats.canvasW,
837
1622
  height: stats.canvasH
838
1623
  });
@@ -840,12 +1625,12 @@ async function forearmPoseWarnings(absDir, layers) {
840
1625
  let armLayer;
841
1626
  try {
842
1627
  armLayer = await measured(measurer, absDir, arm);
843
- a = (0, import_editor5.armGeometry)(armLayer, arm === "arm_R" ? Infinity : -Infinity);
1628
+ a = (0, import_editor6.armGeometry)(armLayer, arm === "arm_R" ? Infinity : -Infinity);
844
1629
  } catch (err) {
845
- if (err instanceof import_editor5.LayerGeometryError) continue;
1630
+ if (err instanceof import_editor6.LayerGeometryError) continue;
846
1631
  throw err;
847
1632
  }
848
- const b = (0, import_editor5.forearmPoseGeometry)(await measured(measurer, absDir, pose));
1633
+ const b = (0, import_editor6.forearmPoseGeometry)(await measured(measurer, absDir, pose));
849
1634
  warnings.push(...jointWarnings(pose, arm, stats, a, armLayer, b));
850
1635
  }
851
1636
  return warnings;
@@ -885,11 +1670,11 @@ function jointWarnings(pose, arm, stats, a, armLayer, b) {
885
1670
 
886
1671
  // src/measure-lips.ts
887
1672
  var import_node_path4 = __toESM(require("path"));
888
- var import_editor7 = require("@ikijs/editor");
1673
+ var import_editor8 = require("@ikijs/editor");
889
1674
 
890
1675
  // src/compose-lips.ts
891
1676
  var import_sharp2 = __toESM(require("sharp"));
892
- var import_editor6 = require("@ikijs/editor");
1677
+ var import_editor7 = require("@ikijs/editor");
893
1678
  var KEYED_SRC = "mouth_keyed.png";
894
1679
  var INTERIOR_SRC = "mouth_interior.png";
895
1680
  var KEY_CANDIDATE = 0.5;
@@ -987,7 +1772,7 @@ function keyGreen(rgba, W, H) {
987
1772
  let candidates = 0;
988
1773
  for (let p = 0; p < n; p++) {
989
1774
  const i = p * 4;
990
- if (rgba[i + 3] < import_editor6.ALPHA_OPAQUE) continue;
1775
+ if (rgba[i + 3] < import_editor7.ALPHA_OPAQUE) continue;
991
1776
  const excess = (rgba[i + 1] - Math.max(rgba[i], rgba[i + 2])) / 255;
992
1777
  if (excess < KEY_CANDIDATE) continue;
993
1778
  candidates++;
@@ -1014,7 +1799,7 @@ function keyGreen(rgba, W, H) {
1014
1799
  const dg = rgba[i + 1] - G[1];
1015
1800
  const db = rgba[i + 2] - G[2];
1016
1801
  const green = dr * dr + dg * dg + db * db <= KEY_FILL_DIST * KEY_FILL_DIST;
1017
- if (rgba[i + 3] < import_editor6.ALPHA_OPAQUE) {
1802
+ if (rgba[i + 3] < import_editor7.ALPHA_OPAQUE) {
1018
1803
  if (green) out[i + 3] = 0;
1019
1804
  } else if (green) {
1020
1805
  fill[p] = 1;
@@ -1190,7 +1975,7 @@ async function prepInterior(rgba, W, H) {
1190
1975
  for (let y = box.y; y < box.y + box.h; y++) {
1191
1976
  for (let x = box.x; x < box.x + box.w; x++) {
1192
1977
  const i = (y * cw + x) * 4;
1193
- if (crop[i + 3] < import_editor6.ALPHA_OPAQUE) continue;
1978
+ if (crop[i + 3] < import_editor7.ALPHA_OPAQUE) continue;
1194
1979
  count++;
1195
1980
  for (let c = 0; c < 3; c++) all[c] += crop[i + c];
1196
1981
  if (luma(crop, i) < CAVITY_LUMA) {
@@ -1213,7 +1998,7 @@ function enclosedHole(frame, w, h) {
1213
1998
  const stack = new Int32Array(n);
1214
1999
  let depth = 0;
1215
2000
  const seed = (p) => {
1216
- if (!outside[p] && alpha(p) < import_editor6.ALPHA_OPAQUE) {
2001
+ if (!outside[p] && alpha(p) < import_editor7.ALPHA_OPAQUE) {
1217
2002
  outside[p] = 1;
1218
2003
  stack[depth++] = p;
1219
2004
  }
@@ -1236,7 +2021,7 @@ function enclosedHole(frame, w, h) {
1236
2021
  }
1237
2022
  const mask = new Uint8Array(n);
1238
2023
  for (let p = 0; p < n; p++) {
1239
- if (alpha(p) < import_editor6.ALPHA_OPAQUE && !outside[p]) mask[p] = 1;
2024
+ if (alpha(p) < import_editor7.ALPHA_OPAQUE && !outside[p]) mask[p] = 1;
1240
2025
  }
1241
2026
  const { label, sizes, boxes } = components(mask, w, h);
1242
2027
  const main = largest(sizes);
@@ -1263,7 +2048,7 @@ function enclosedHole(frame, w, h) {
1263
2048
  return { label, main, box };
1264
2049
  }
1265
2050
  function measureLips(layers, w, h) {
1266
- const measurer = (0, import_editor6.createLayerSetMeasurer)({ width: w, height: h });
2051
+ const measurer = (0, import_editor7.createLayerSetMeasurer)({ width: w, height: h });
1267
2052
  return new Map(
1268
2053
  Object.entries(layers).map(([role, rgba]) => [
1269
2054
  role,
@@ -1281,8 +2066,8 @@ function assertFoldContract(layers, w, h) {
1281
2066
  }
1282
2067
  byRole.set(role, layer);
1283
2068
  }
1284
- const opening = (0, import_editor6.mouthOpening)(byRole);
1285
- const runs = (0, import_editor6.columnRuns)(byRole.get("mouth_inner"));
2069
+ const opening = (0, import_editor7.mouthOpening)(byRole);
2070
+ const runs = (0, import_editor7.columnRuns)(byRole.get("mouth_inner"));
1286
2071
  for (let col = opening.x0; col <= opening.x1; col++) {
1287
2072
  const c = opening.at(col);
1288
2073
  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;
@@ -1312,18 +2097,18 @@ async function splitLipSet(keyedPng, w, h, interior) {
1312
2097
  }
1313
2098
  const centre = Math.round((hb.x0 + hb.x1) / 2);
1314
2099
  let stroke = 0;
1315
- while (top[centre] - 1 - stroke >= 0 && alpha((top[centre] - 1 - stroke) * w + centre) >= import_editor6.ALPHA_OPAQUE)
2100
+ while (top[centre] - 1 - stroke >= 0 && alpha((top[centre] - 1 - stroke) * w + centre) >= import_editor7.ALPHA_OPAQUE)
1316
2101
  stroke++;
1317
2102
  const bandCap = BAND_CAP * Math.max(1, stroke);
1318
2103
  const skinRow = new Int32Array(w).fill(-1);
1319
2104
  const inM = new Uint8Array(n);
1320
2105
  for (let x = hb.x0; x <= hb.x1; x++) {
1321
2106
  let y = bot[x];
1322
- while (y < h && y - bot[x] < bandCap && alpha(y * w + x) >= import_editor6.ALPHA_OPAQUE && luma(frame, (y * w + x) * 4) < BAND_LUMA)
2107
+ while (y < h && y - bot[x] < bandCap && alpha(y * w + x) >= import_editor7.ALPHA_OPAQUE && luma(frame, (y * w + x) * 4) < BAND_LUMA)
1323
2108
  y++;
1324
2109
  for (let k = top[x]; k < y; k++) inM[k * w + x] = 1;
1325
2110
  let r = y;
1326
- while (r < h && alpha(r * w + x) < import_editor6.ALPHA_OPAQUE) r++;
2111
+ while (r < h && alpha(r * w + x) < import_editor7.ALPHA_OPAQUE) r++;
1327
2112
  if (r < h) {
1328
2113
  skinRow[x] = r;
1329
2114
  inM[r * w + x] = 1;
@@ -1333,7 +2118,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
1333
2118
  for (let y = 0; y < h; y++) {
1334
2119
  for (let x = 0; x < w; x++) {
1335
2120
  const p = y * w + x;
1336
- if (inM[p] || alpha(p) < import_editor6.ALPHA_OPAQUE) continue;
2121
+ if (inM[p] || alpha(p) < import_editor7.ALPHA_OPAQUE) continue;
1337
2122
  if (top[x] >= 0 && y < top[x]) continue;
1338
2123
  if (x > 0 && inM[p - 1] || x < w - 1 && inM[p + 1]) grown[p] = 1;
1339
2124
  }
@@ -1343,7 +2128,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
1343
2128
  if (x < 0 || x >= w) continue;
1344
2129
  let first = 0;
1345
2130
  while (first < h && !(grown[first * w + x] && !inM[first * w + x])) first++;
1346
- if (first > 0 && first < h && alpha((first - 1) * w + x) >= import_editor6.ALPHA_OPAQUE)
2131
+ if (first > 0 && first < h && alpha((first - 1) * w + x) >= import_editor7.ALPHA_OPAQUE)
1347
2132
  wall[x] = 1;
1348
2133
  }
1349
2134
  const gx = hb.x0 - 1;
@@ -1370,7 +2155,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
1370
2155
  if (inOpening && skinRow[x] >= 0 && y >= skinRow[x]) copy(lower, p);
1371
2156
  if (!grown[p]) {
1372
2157
  const a = alpha(p);
1373
- if (a >= import_editor6.ALPHA_OPAQUE && a < 255 && besideHole(p, x, y)) {
2158
+ if (a >= import_editor7.ALPHA_OPAQUE && a < 255 && besideHole(p, x, y)) {
1374
2159
  inner.set(interior.cavity, p * 4);
1375
2160
  inner[p * 4 + 3] = 255 - a;
1376
2161
  }
@@ -1435,7 +2220,7 @@ async function restShiftOf(layers, width, height) {
1435
2220
  }
1436
2221
  byRole.set(role, layer);
1437
2222
  }
1438
- return (0, import_editor6.mouthRestShift)(byRole);
2223
+ return (0, import_editor7.mouthRestShift)(byRole);
1439
2224
  }
1440
2225
  async function closedLips(upper, lower, shift, left, top) {
1441
2226
  const shut = async (png, role) => {
@@ -1485,7 +2270,7 @@ async function closedLips(upper, lower, shift, left, top) {
1485
2270
  }
1486
2271
 
1487
2272
  // src/measure-lips.ts
1488
- var isLipLayerRole = (role) => import_editor7.LIP_ROLES.includes(role) || (0, import_editor7.isLipInsideRole)(role);
2273
+ var isLipLayerRole = (role) => import_editor8.LIP_ROLES.includes(role) || (0, import_editor8.isLipInsideRole)(role);
1489
2274
  var MIN_OPENING_ROWS = 8;
1490
2275
  var MIN_LINE_ROWS = 2;
1491
2276
  var GREEN_EXCESS = 40;
@@ -1493,8 +2278,8 @@ var INTERIOR_GAP_FRACTION = 0.05;
1493
2278
  var columns = (cols) => `${cols.length} column${cols.length === 1 ? "" : "s"} (first at x=${cols[0]})`;
1494
2279
  async function lipWarnings(absDir, layers) {
1495
2280
  const warnings = [];
1496
- const present = import_editor7.LIP_ROLES.filter((role) => layers[role] !== void 0);
1497
- const inside = import_editor7.LIP_INSIDE_ROLES.filter((role) => layers[role] !== void 0);
2281
+ const present = import_editor8.LIP_ROLES.filter((role) => layers[role] !== void 0);
2282
+ const inside = import_editor8.LIP_INSIDE_ROLES.filter((role) => layers[role] !== void 0);
1498
2283
  if (present.length === 0) {
1499
2284
  if (inside.length > 0) {
1500
2285
  warnings.push(
@@ -1511,8 +2296,8 @@ async function lipWarnings(absDir, layers) {
1511
2296
  `${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.`
1512
2297
  );
1513
2298
  }
1514
- if (present.length < import_editor7.LIP_ROLES.length) {
1515
- const missing = import_editor7.LIP_ROLES.filter((role) => layers[role] === void 0);
2299
+ if (present.length < import_editor8.LIP_ROLES.length) {
2300
+ const missing = import_editor8.LIP_ROLES.filter((role) => layers[role] === void 0);
1516
2301
  warnings.push(
1517
2302
  `${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.`
1518
2303
  );
@@ -1543,18 +2328,18 @@ async function lipWarnings(absDir, layers) {
1543
2328
  );
1544
2329
  }
1545
2330
  }
1546
- const measurer = (0, import_editor7.createLayerSetMeasurer)({
2331
+ const measurer = (0, import_editor8.createLayerSetMeasurer)({
1547
2332
  width: inner.canvasW,
1548
2333
  height: inner.canvasH
1549
2334
  });
1550
2335
  const set = /* @__PURE__ */ new Map();
1551
2336
  const green = [];
1552
- for (const role of import_editor7.LIP_ROLES) {
2337
+ for (const role of import_editor8.LIP_ROLES) {
1553
2338
  const fileName = `${role}.png`;
1554
2339
  const { rgba } = await decodePng(import_node_path4.default.join(absDir, fileName));
1555
2340
  set.set(role, measurer.add({ role, fileName, rgba }));
1556
2341
  for (let i = 0; i < rgba.length; i += 4) {
1557
- if (rgba[i + 3] >= import_editor7.ALPHA_OPAQUE && rgba[i + 1] - Math.max(rgba[i], rgba[i + 2]) > GREEN_EXCESS) {
2342
+ if (rgba[i + 3] >= import_editor8.ALPHA_OPAQUE && rgba[i + 1] - Math.max(rgba[i], rgba[i + 2]) > GREEN_EXCESS) {
1558
2343
  green.push(role);
1559
2344
  break;
1560
2345
  }
@@ -1562,15 +2347,15 @@ async function lipWarnings(absDir, layers) {
1562
2347
  }
1563
2348
  let opening;
1564
2349
  try {
1565
- opening = (0, import_editor7.mouthOpening)(set);
2350
+ opening = (0, import_editor8.mouthOpening)(set);
1566
2351
  } catch (err) {
1567
- if (err instanceof import_editor7.LayerGeometryError) {
2352
+ if (err instanceof import_editor8.LayerGeometryError) {
1568
2353
  warnings.push(err.message);
1569
2354
  return { warnings };
1570
2355
  }
1571
2356
  throw err;
1572
2357
  }
1573
- const innerRuns = (0, import_editor7.columnRuns)(set.get("mouth_inner"));
2358
+ const innerRuns = (0, import_editor8.columnRuns)(set.get("mouth_inner"));
1574
2359
  const noInterior = [];
1575
2360
  const gap = [];
1576
2361
  const noLine = [];
@@ -1656,8 +2441,8 @@ async function lipWarnings(absDir, layers) {
1656
2441
 
1657
2442
  // src/measure-turn.ts
1658
2443
  var import_node_path5 = __toESM(require("path"));
1659
- var import_editor8 = require("@ikijs/editor");
1660
2444
  var import_editor9 = require("@ikijs/editor");
2445
+ var import_editor10 = require("@ikijs/editor");
1661
2446
  var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
1662
2447
  var IRIS_V_MIN = 0.18;
1663
2448
  var IRIS_V_MAX = 0.95;
@@ -1807,7 +2592,7 @@ async function measureTurnImage(filePath, iris) {
1807
2592
  let transparent = false;
1808
2593
  if (hasAlpha) {
1809
2594
  for (let i = 0; i < n; i++) {
1810
- if (rgba[i * 4 + 3] < import_editor8.ALPHA_OPAQUE) {
2595
+ if (rgba[i * 4 + 3] < import_editor9.ALPHA_OPAQUE) {
1811
2596
  transparent = true;
1812
2597
  break;
1813
2598
  }
@@ -1818,7 +2603,7 @@ async function measureTurnImage(filePath, iris) {
1818
2603
  const fg = new Uint8Array(n);
1819
2604
  const value = new Float32Array(n);
1820
2605
  for (let i = 0; i < n; i++) {
1821
- if (rgba[i * 4 + 3] < import_editor8.ALPHA_OPAQUE) continue;
2606
+ if (rgba[i * 4 + 3] < import_editor9.ALPHA_OPAQUE) continue;
1822
2607
  const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);
1823
2608
  if (maskMode === "alpha") {
1824
2609
  fg[i] = 1;
@@ -1884,12 +2669,12 @@ async function measureTurnImage(filePath, iris) {
1884
2669
  }
1885
2670
  const [irisL, irisR] = best.pair;
1886
2671
  const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);
1887
- const { left, right } = (0, import_editor8.foregroundSpan)(
2672
+ const { left, right } = (0, import_editor9.foregroundSpan)(
1888
2673
  fg,
1889
2674
  width,
1890
2675
  height,
1891
- eyeRow - import_editor8.HEAD_BAND,
1892
- eyeRow + import_editor8.HEAD_BAND
2676
+ eyeRow - import_editor9.HEAD_BAND,
2677
+ eyeRow + import_editor9.HEAD_BAND
1893
2678
  );
1894
2679
  if (right <= left) {
1895
2680
  throw new AutoRigInputError(
@@ -1913,7 +2698,7 @@ async function measureTurnImage(filePath, iris) {
1913
2698
  left,
1914
2699
  right,
1915
2700
  cx: (left + right) / 2,
1916
- half: (0, import_editor8.headHalfOf)({ left, right })
2701
+ half: (0, import_editor9.headHalfOf)({ left, right })
1917
2702
  },
1918
2703
  pairCx: (irisL.cx + irisR.cx) / 2,
1919
2704
  eyeGap: irisR.cx - irisL.cx
@@ -2104,7 +2889,7 @@ function noseSpeckWarning({ core, part }, source) {
2104
2889
  `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,
2105
2890
  `auto_rig_from_layers turns and tilts the nose about its whole crop instead`
2106
2891
  ];
2107
- 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.`;
2892
+ 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.`;
2108
2893
  }
2109
2894
  async function lashOffSclera(eyePath, lashPath) {
2110
2895
  const eye = await decodePng(eyePath);
@@ -2241,10 +3026,10 @@ async function measureDir(absDir, noseSpeck) {
2241
3026
  warnings.push(noseSpeckWarning(noseSpeck, "compose"));
2242
3027
  } else if (layers.nose !== void 0) {
2243
3028
  const nose = await decodePng(import_node_path6.default.join(absDir, "nose.png"));
2244
- const core = (0, import_editor9.denseCoreOf)(nose.rgba, nose.width, nose.height);
3029
+ const core = (0, import_editor10.denseCoreOf)(nose.rgba, nose.width, nose.height);
2245
3030
  if (core !== null) {
2246
3031
  const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);
2247
- if ((0, import_editor9.isSpeckCore)(core, crop))
3032
+ if ((0, import_editor10.isSpeckCore)(core, crop))
2248
3033
  warnings.push(noseSpeckWarning({ core, part: crop }, "layer"));
2249
3034
  }
2250
3035
  }
@@ -2315,12 +3100,12 @@ function formatMeasureReport(result) {
2315
3100
 
2316
3101
  // src/compose-arms.ts
2317
3102
  var import_sharp3 = __toESM(require("sharp"));
2318
- var import_editor10 = require("@ikijs/editor");
3103
+ var import_editor11 = require("@ikijs/editor");
2319
3104
  var ARM_WIDTH = 0.4;
2320
3105
  var SHOULDER_DROP = 0.12;
2321
3106
  async function armPlacement(role, cfg, part, body) {
2322
3107
  const { data } = await (0, import_sharp3.default)(part.buf).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2323
- const layer = (0, import_editor10.createLayerSetMeasurer)({ width: part.w, height: part.h }).add({
3108
+ const layer = (0, import_editor11.createLayerSetMeasurer)({ width: part.w, height: part.h }).add({
2324
3109
  role,
2325
3110
  fileName: "arm.png",
2326
3111
  rgba: data
@@ -2332,9 +3117,9 @@ async function armPlacement(role, cfg, part, body) {
2332
3117
  }
2333
3118
  let g;
2334
3119
  try {
2335
- g = (0, import_editor10.armGeometry)(layer, role === "arm_R" ? Infinity : -Infinity);
3120
+ g = (0, import_editor11.armGeometry)(layer, role === "arm_R" ? Infinity : -Infinity);
2336
3121
  } catch (err) {
2337
- if (err instanceof import_editor10.LayerGeometryError) {
3122
+ if (err instanceof import_editor11.LayerGeometryError) {
2338
3123
  throw new AutoRigInputError(`layout.${role}: ${err.message}`);
2339
3124
  }
2340
3125
  throw err;
@@ -2361,7 +3146,7 @@ async function armPlacement(role, cfg, part, body) {
2361
3146
  }
2362
3147
  async function poseGeometryOf(role, png, size, when) {
2363
3148
  const { data } = await (0, import_sharp3.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2364
- const layer = (0, import_editor10.createLayerSetMeasurer)({
3149
+ const layer = (0, import_editor11.createLayerSetMeasurer)({
2365
3150
  width: size.w,
2366
3151
  height: size.h
2367
3152
  }).add({ role, fileName: "forearm_pose.png", rgba: data });
@@ -2370,7 +3155,7 @@ async function poseGeometryOf(role, png, size, when) {
2370
3155
  `layout.${role}: forearm_pose.png is empty after alpha threshold${when}`
2371
3156
  );
2372
3157
  }
2373
- return (0, import_editor10.forearmPoseGeometry)(layer);
3158
+ return (0, import_editor11.forearmPoseGeometry)(layer);
2374
3159
  }
2375
3160
  async function forearmPoseWidth(role, trimmed, elbowRun) {
2376
3161
  const g = await poseGeometryOf(role, trimmed.data, trimmed, "");
@@ -2588,12 +3373,12 @@ function resolveLayout(overrides, canvas) {
2588
3373
  const face = { ...resolved.face, ...sets.get("face") };
2589
3374
  resolved.face = face;
2590
3375
  const base = DEFAULT_LAYOUT.face;
2591
- const scale = face.w / base.w;
2592
- const x = (cx) => face.cx + (cx - base.cx) * scale;
2593
- const w = (width) => Math.max(1, Math.round(width * scale));
3376
+ const scale2 = face.w / base.w;
3377
+ const x = (cx) => face.cx + (cx - base.cx) * scale2;
3378
+ const w = (width) => Math.max(1, Math.round(width * scale2));
2594
3379
  for (const role of FACE_FEATURES) {
2595
3380
  const d = DEFAULT_LAYOUT[role];
2596
- const cy = face.cy + (d.cy - base.cy) * scale;
3381
+ const cy = face.cy + (d.cy - base.cy) * scale2;
2597
3382
  resolved[role] = { ...d, cx: x(d.cx), cy, w: w(d.w), ...sets.get(role) };
2598
3383
  }
2599
3384
  const nose = DEFAULT_LAYOUT.nose;
@@ -2646,18 +3431,18 @@ function keyWhiteToAlpha(rgba) {
2646
3431
  async function coreAndBoundsOf(png) {
2647
3432
  const { data, info } = await (0, import_sharp4.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2648
3433
  return {
2649
- core: (0, import_editor9.denseCoreOf)(data, info.width, info.height),
3434
+ core: (0, import_editor10.denseCoreOf)(data, info.width, info.height),
2650
3435
  bounds: { x: 0, y: 0, w: info.width, h: info.height }
2651
3436
  };
2652
3437
  }
2653
3438
  async function hasCoverage(png) {
2654
3439
  const { data, info } = await (0, import_sharp4.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2655
- return (0, import_editor11.detectAlphaBbox)(data, info.width, info.height) !== null;
3440
+ return (0, import_editor12.detectAlphaBbox)(data, info.width, info.height) !== null;
2656
3441
  }
2657
3442
  async function noseSizingOf(png) {
2658
3443
  const { core, bounds } = await coreAndBoundsOf(png);
2659
3444
  if (core === null) return { box: bounds, whole: true };
2660
- if ((0, import_editor9.isSpeckCore)(core, bounds)) {
3445
+ if ((0, import_editor10.isSpeckCore)(core, bounds)) {
2661
3446
  return {
2662
3447
  box: bounds,
2663
3448
  whole: true,
@@ -2734,7 +3519,7 @@ function assertOnCanvas(source, w, h, left, top, canvas) {
2734
3519
  );
2735
3520
  }
2736
3521
  }
2737
- function placement(role, cfg, w, h, canvas) {
3522
+ function placement2(role, cfg, w, h, canvas) {
2738
3523
  const left = Math.round(cfg.cx - w / 2);
2739
3524
  const top = Math.round(cfg.cy - h / 2);
2740
3525
  assertOnCanvas(`layout.${role}.cx/cy`, w, h, left, top, canvas);
@@ -2779,7 +3564,7 @@ function detachedAboveWhite(rgba, W, H) {
2779
3564
  for (let p = 0; p < n; p++) {
2780
3565
  const alpha = rgba[p * 4 + 3];
2781
3566
  if (alpha > 0 && luma(rgba, p * 4) >= EYE_LASH_LUMA)
2782
- ink[p] = alpha >= import_editor11.ALPHA_OPAQUE ? 2 : 1;
3567
+ ink[p] = alpha >= import_editor12.ALPHA_OPAQUE ? 2 : 1;
2783
3568
  }
2784
3569
  const label = new Int32Array(n).fill(-1);
2785
3570
  const stack = new Int32Array(n);
@@ -3004,7 +3789,7 @@ async function composeLayersFromParts(input) {
3004
3789
  part2.h,
3005
3790
  lips.interior
3006
3791
  );
3007
- const { left: left2, top: top2 } = placement(role, cfg2, part2.w, part2.h, canvas);
3792
+ const { left: left2, top: top2 } = placement2(role, cfg2, part2.w, part2.h, canvas);
3008
3793
  lipSplit = { split: split2, w: part2.w, h: part2.h, left: left2, top: top2 };
3009
3794
  placed.push({
3010
3795
  role,
@@ -3023,7 +3808,7 @@ async function composeLayersFromParts(input) {
3023
3808
  lip_lower: split2.lower,
3024
3809
  lip_upper: split2.upper
3025
3810
  }[role];
3026
- if ((0, import_editor11.isLipInsideRole)(role) && !await hasCoverage(buf)) {
3811
+ if ((0, import_editor12.isLipInsideRole)(role) && !await hasCoverage(buf)) {
3027
3812
  skipped.push(role);
3028
3813
  continue;
3029
3814
  }
@@ -3161,7 +3946,7 @@ async function composeLayersFromParts(input) {
3161
3946
  canvas
3162
3947
  ));
3163
3948
  } else {
3164
- ({ left, top } = placement(key, layout[key], part.w, part.h, canvas));
3949
+ ({ left, top } = placement2(key, layout[key], part.w, part.h, canvas));
3165
3950
  }
3166
3951
  if (role === "lash_L" || role === "lash_R") {
3167
3952
  const eyeRole = role === "lash_L" ? "eye_L" : "eye_R";
@@ -3218,7 +4003,7 @@ async function composeLayersFromParts(input) {
3218
4003
  });
3219
4004
  }
3220
4005
  const restInput = (role, buf) => {
3221
- if (role === "mouth_inner" || (0, import_editor11.isLipInsideRole)(role)) return null;
4006
+ if (role === "mouth_inner" || (0, import_editor12.isLipInsideRole)(role)) return null;
3222
4007
  if (closed === void 0) return buf;
3223
4008
  if (role === "lip_upper") return closed.upper;
3224
4009
  if (role === "lip_lower") return closed.lower;
@@ -3285,11 +4070,525 @@ async function composeLayersFromParts(input) {
3285
4070
  }
3286
4071
  }
3287
4072
 
4073
+ // src/render-poses.ts
4074
+ var import_node_fs5 = require("fs");
4075
+ var import_node_path9 = __toESM(require("path"));
4076
+ var import_format8 = require("@ikijs/format");
4077
+
4078
+ // src/render-browser.ts
4079
+ var import_node_child_process = require("child_process");
4080
+ var import_node_fs4 = __toESM(require("fs"));
4081
+ var import_node_os = __toESM(require("os"));
4082
+ var import_node_path8 = __toESM(require("path"));
4083
+ 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.";
4084
+ var DARWIN_CANDIDATES = [
4085
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
4086
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
4087
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
4088
+ ];
4089
+ var LINUX_CANDIDATES = [
4090
+ "/usr/bin/google-chrome",
4091
+ "/usr/bin/google-chrome-stable",
4092
+ "/usr/bin/chromium",
4093
+ "/usr/bin/chromium-browser",
4094
+ "/usr/bin/microsoft-edge",
4095
+ "/snap/bin/chromium"
4096
+ ];
4097
+ var WIN32_ROOTS = ["PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"];
4098
+ var WIN32_SUFFIXES = [
4099
+ ["Google", "Chrome", "Application", "chrome.exe"],
4100
+ ["Microsoft", "Edge", "Application", "msedge.exe"]
4101
+ ];
4102
+ var CLOSE_GRACE_MS = 2e3;
4103
+ var DEFAULT_TIMEOUT_MS = 3e4;
4104
+ var BROWSER_CLOSE_MS = 1e3;
4105
+ function isExecutableFile(file) {
4106
+ try {
4107
+ if (!import_node_fs4.default.statSync(file).isFile()) return false;
4108
+ import_node_fs4.default.accessSync(file, import_node_fs4.default.constants.X_OK);
4109
+ return true;
4110
+ } catch {
4111
+ return false;
4112
+ }
4113
+ }
4114
+ function findBrowser({
4115
+ env = process.env,
4116
+ platform = process.platform,
4117
+ isExecutable = isExecutableFile
4118
+ } = {}) {
4119
+ const override = env.CHROME_PATH;
4120
+ if (override) {
4121
+ if (!isExecutable(override)) {
4122
+ throw new AutoRigInputError(
4123
+ `CHROME_PATH is not an executable file: ${override}`
4124
+ );
4125
+ }
4126
+ return override;
4127
+ }
4128
+ let candidates;
4129
+ if (platform === "darwin") candidates = DARWIN_CANDIDATES;
4130
+ else if (platform === "win32") {
4131
+ candidates = [];
4132
+ for (const suffix of WIN32_SUFFIXES) {
4133
+ for (const root of WIN32_ROOTS) {
4134
+ const base = env[root];
4135
+ if (base) candidates.push(import_node_path8.default.win32.join(base, ...suffix));
4136
+ }
4137
+ }
4138
+ } else candidates = LINUX_CANDIDATES;
4139
+ return candidates.find((file) => isExecutable(file));
4140
+ }
4141
+ function within(promise, ms, what, detail) {
4142
+ let timer;
4143
+ const timeout = new Promise((_, reject) => {
4144
+ timer = setTimeout(
4145
+ () => reject(
4146
+ new Error(
4147
+ `${what} timed out after ${ms} ms${detail ? `: ${detail()}` : ""}`
4148
+ )
4149
+ ),
4150
+ ms
4151
+ );
4152
+ });
4153
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
4154
+ }
4155
+ function connectCdp(url, timeoutMs) {
4156
+ const socket = new WebSocket(url);
4157
+ let nextId = 0;
4158
+ let socketClosed = false;
4159
+ const pending = /* @__PURE__ */ new Map();
4160
+ socket.addEventListener("message", (event) => {
4161
+ const message = JSON.parse(String(event.data));
4162
+ const entry = pending.get(message.id);
4163
+ if (!entry) return;
4164
+ pending.delete(message.id);
4165
+ if (message.error) {
4166
+ entry.reject(
4167
+ new Error(`${message.error.message} (${message.error.code})`)
4168
+ );
4169
+ } else entry.resolve(message.result);
4170
+ });
4171
+ socket.addEventListener("close", () => {
4172
+ socketClosed = true;
4173
+ for (const entry of pending.values()) {
4174
+ entry.reject(new Error("DevTools connection closed"));
4175
+ }
4176
+ pending.clear();
4177
+ });
4178
+ const opened = new Promise((resolve, reject) => {
4179
+ socket.addEventListener(
4180
+ "error",
4181
+ () => reject(new Error("DevTools connection failed"))
4182
+ );
4183
+ socket.addEventListener(
4184
+ "open",
4185
+ () => resolve({
4186
+ send(method, callTimeoutMs, params, sessionId) {
4187
+ if (socketClosed) {
4188
+ return Promise.reject(new Error("DevTools connection closed"));
4189
+ }
4190
+ const id = ++nextId;
4191
+ const reply = new Promise((res, rej) => {
4192
+ pending.set(id, {
4193
+ resolve: res,
4194
+ reject: rej
4195
+ });
4196
+ });
4197
+ socket.send(JSON.stringify({ id, method, params, sessionId }));
4198
+ return within(reply, callTimeoutMs, method).finally(
4199
+ () => pending.delete(id)
4200
+ );
4201
+ }
4202
+ })
4203
+ );
4204
+ });
4205
+ return within(opened, timeoutMs, "DevTools connection").catch((error) => {
4206
+ socket.close();
4207
+ throw error;
4208
+ });
4209
+ }
4210
+ function startError(executable, error) {
4211
+ return new Error(
4212
+ `could not start ${executable}: ${error.code ?? error.message}`
4213
+ );
4214
+ }
4215
+ function waitForDevTools(child, closed, getSpawnError, executable, timeoutMs) {
4216
+ let tail = "";
4217
+ return within(
4218
+ new Promise((resolve, reject) => {
4219
+ child.stderr.on("data", (chunk) => {
4220
+ tail = (tail + chunk).slice(-2e3);
4221
+ const match = /DevTools listening on (ws:\/\/\S+)/.exec(tail);
4222
+ if (match) resolve(match[1]);
4223
+ });
4224
+ void closed.then(() => {
4225
+ const spawnError = getSpawnError();
4226
+ reject(
4227
+ spawnError ? startError(executable, spawnError) : new Error(
4228
+ `${executable} exited before DevTools was ready: ${tail.trim()}`
4229
+ )
4230
+ );
4231
+ });
4232
+ }),
4233
+ timeoutMs,
4234
+ "browser startup",
4235
+ () => tail.trim() || "no output"
4236
+ );
4237
+ }
4238
+ async function openPage(cdp, timeoutMs) {
4239
+ const { targetId } = await cdp.send(
4240
+ "Target.createTarget",
4241
+ timeoutMs,
4242
+ { url: "about:blank" }
4243
+ );
4244
+ const { sessionId } = await cdp.send(
4245
+ "Target.attachToTarget",
4246
+ timeoutMs,
4247
+ { targetId, flatten: true }
4248
+ );
4249
+ return async (expression, evalTimeoutMs) => {
4250
+ const { result, exceptionDetails } = await cdp.send(
4251
+ "Runtime.evaluate",
4252
+ evalTimeoutMs,
4253
+ { expression, awaitPromise: true, returnByValue: true },
4254
+ sessionId
4255
+ );
4256
+ if (exceptionDetails) {
4257
+ const thrown = exceptionDetails.exception;
4258
+ throw new Error(
4259
+ thrown?.description ?? (thrown && "value" in thrown ? String(thrown.value) : exceptionDetails.text)
4260
+ );
4261
+ }
4262
+ return result.value;
4263
+ };
4264
+ }
4265
+ function removeProfile(profile) {
4266
+ try {
4267
+ import_node_fs4.default.rmSync(profile, {
4268
+ recursive: true,
4269
+ force: true,
4270
+ maxRetries: 5,
4271
+ retryDelay: 100
4272
+ });
4273
+ } catch (error) {
4274
+ console.error(`could not remove browser profile ${profile}:`, error);
4275
+ }
4276
+ }
4277
+ async function launchBrowser(executable, timeoutMs) {
4278
+ if (typeof globalThis.WebSocket === "undefined") {
4279
+ throw new AutoRigInputError(
4280
+ "render_poses needs Node 22 or newer (the global WebSocket is missing)."
4281
+ );
4282
+ }
4283
+ const profile = import_node_fs4.default.mkdtempSync(import_node_path8.default.join(import_node_os.default.tmpdir(), "iki-render-"));
4284
+ let child;
4285
+ try {
4286
+ child = (0, import_node_child_process.spawn)(
4287
+ executable,
4288
+ [
4289
+ "--headless=new",
4290
+ "--remote-debugging-port=0",
4291
+ `--user-data-dir=${profile}`,
4292
+ "--no-first-run",
4293
+ "--no-default-browser-check",
4294
+ // Output pixel sizes must equal the plan's, whatever the display.
4295
+ "--force-device-scale-factor=1",
4296
+ // WebGL without a GPU; recent Chrome no longer falls back by itself.
4297
+ "--enable-unsafe-swiftshader",
4298
+ "about:blank"
4299
+ ],
4300
+ { stdio: ["ignore", "ignore", "pipe"] }
4301
+ );
4302
+ } catch (error) {
4303
+ import_node_fs4.default.rmSync(profile, { recursive: true, force: true });
4304
+ throw startError(executable, error);
4305
+ }
4306
+ let spawnError;
4307
+ child.on("error", (error) => {
4308
+ spawnError = error;
4309
+ });
4310
+ let exited = false;
4311
+ const closed = new Promise((resolve) => {
4312
+ child.on("close", () => {
4313
+ exited = true;
4314
+ resolve();
4315
+ });
4316
+ });
4317
+ const settle = (ms) => within(closed, ms, "browser close").catch(() => {
4318
+ });
4319
+ const onProcessExit = () => {
4320
+ child.kill("SIGKILL");
4321
+ removeProfile(profile);
4322
+ };
4323
+ process.once("exit", onProcessExit);
4324
+ let shutdownPromise;
4325
+ const shutdown = () => shutdownPromise ??= (async () => {
4326
+ if (!exited) {
4327
+ child.kill();
4328
+ await settle(CLOSE_GRACE_MS);
4329
+ if (!exited) {
4330
+ child.kill("SIGKILL");
4331
+ await settle(CLOSE_GRACE_MS);
4332
+ }
4333
+ }
4334
+ process.removeListener("exit", onProcessExit);
4335
+ removeProfile(profile);
4336
+ })();
4337
+ let cdp;
4338
+ try {
4339
+ const endpoint = await waitForDevTools(
4340
+ child,
4341
+ closed,
4342
+ () => spawnError,
4343
+ executable,
4344
+ timeoutMs
4345
+ );
4346
+ cdp = await connectCdp(endpoint, timeoutMs);
4347
+ } catch (error) {
4348
+ await shutdown();
4349
+ throw error;
4350
+ }
4351
+ return {
4352
+ openPage: () => openPage(cdp, timeoutMs),
4353
+ async close() {
4354
+ if (!exited) {
4355
+ await cdp.send("Browser.close", BROWSER_CLOSE_MS).catch(() => {
4356
+ });
4357
+ }
4358
+ await shutdown();
4359
+ }
4360
+ };
4361
+ }
4362
+ async function withBrowser(executable, fn) {
4363
+ const browser = await launchBrowser(executable, DEFAULT_TIMEOUT_MS);
4364
+ try {
4365
+ return await fn(await browser.openPage());
4366
+ } finally {
4367
+ await browser.close();
4368
+ }
4369
+ }
4370
+
4371
+ // src/render-poses.ts
4372
+ var FULL_BODY_VIEW_WIDTH = 2.5;
4373
+ var BUST_SIZE = 560;
4374
+ function planRenders(model) {
4375
+ const { width: W, height: H } = model.canvas;
4376
+ const fullBody = H > W;
4377
+ const canvas = fullBody ? {
4378
+ width: FULL_BODY_VIEW_WIDTH * BUST_SIZE,
4379
+ height: Math.ceil(BUST_SIZE * H / W)
4380
+ } : { width: BUST_SIZE, height: BUST_SIZE };
4381
+ const view = fullBody ? { x: 0, y: 0, width: FULL_BODY_VIEW_WIDTH * W, height: H } : void 0;
4382
+ const x0 = (canvas.width - BUST_SIZE) / 2;
4383
+ const s = BUST_SIZE / W;
4384
+ const mouthPart = model.parts.find((p) => p.id === "mouth_inner") ?? model.parts.find((p) => p.id === "mouth");
4385
+ const mouth = mouthPart ? { cx: W / 2 + mouthPart.transform.x, cy: H / 2 - mouthPart.transform.y } : void 0;
4386
+ const squareCrop = fullBody ? {
4387
+ sx: x0,
4388
+ sy: 0,
4389
+ sw: BUST_SIZE,
4390
+ sh: BUST_SIZE,
4391
+ dw: BUST_SIZE,
4392
+ dh: BUST_SIZE
4393
+ } : void 0;
4394
+ const square = (name, values = {}) => ({
4395
+ name,
4396
+ values,
4397
+ crop: squareCrop
4398
+ });
4399
+ const whole = (name, values = {}) => ({
4400
+ name,
4401
+ values
4402
+ });
4403
+ const bodyAngles = Object.fromEntries(
4404
+ [
4405
+ import_format8.StandardParameter.BodyAngleX,
4406
+ import_format8.StandardParameter.BodyAngleY,
4407
+ import_format8.StandardParameter.BodyAngleZ
4408
+ ].filter((id) => model.parameters.some((p) => p.id === id)).map((id) => [id, -10])
4409
+ );
4410
+ const poses = [
4411
+ square("rest"),
4412
+ square("turn-m30", { ParamAngleX: -30 }),
4413
+ square("turn-p30", { ParamAngleX: 30 }),
4414
+ square("turn-15", { ParamAngleX: 15 }),
4415
+ square("nod-15", { ParamAngleY: 15 }),
4416
+ square("blink", { ParamEyeLOpen: 0 }),
4417
+ square("blink-half", { ParamEyeLOpen: 0.5 }),
4418
+ square("gaze", { ParamEyeBallX: 1 }),
4419
+ square("combined", { ParamAngleX: 30, ParamAngleY: 30, ParamAngleZ: 30 }),
4420
+ // Every head angle at its other extreme with the face moving too, where
4421
+ // moves that each look fine alone stack up into a fold.
4422
+ square("stress", {
4423
+ ParamAngleX: -30,
4424
+ ParamAngleY: -30,
4425
+ ParamAngleZ: -30,
4426
+ ParamMouthOpenY: 1,
4427
+ ParamEyeLOpen: 0.5,
4428
+ ParamEyeROpen: 0.5,
4429
+ ParamBrowLY: -1,
4430
+ ParamBrowRY: 1,
4431
+ ParamBrowLAngle: 1,
4432
+ ParamBrowRAngle: -1,
4433
+ ...bodyAngles
4434
+ })
4435
+ ];
4436
+ if (mouth) {
4437
+ const crop = {
4438
+ sx: x0 + (mouth.cx - 90) * s,
4439
+ sy: (mouth.cy - 60) * s,
4440
+ sw: 180 * s,
4441
+ sh: 120 * s,
4442
+ dw: 720,
4443
+ dh: 480
4444
+ };
4445
+ for (const open of [0, 0.3, 0.6, 1]) {
4446
+ for (const [name, form] of [
4447
+ ["m1", -1],
4448
+ ["0", 0],
4449
+ ["p1", 1]
4450
+ ]) {
4451
+ poses.push({
4452
+ name: `mouth-open-${open}-form-${name}`,
4453
+ values: { ParamMouthOpenY: open, ParamMouthForm: form },
4454
+ crop
4455
+ });
4456
+ }
4457
+ }
4458
+ poses.push(
4459
+ {
4460
+ name: "mouth-laugh",
4461
+ values: { ParamMouthOpenY: 0.8, ParamMouthForm: 1 },
4462
+ crop
4463
+ },
4464
+ { name: "mouth-surprised", values: { ParamMouthOpenY: 0.9 }, crop },
4465
+ {
4466
+ name: "mouth-turn-p30-half",
4467
+ values: { ParamAngleX: 30, ParamMouthOpenY: 0.5 },
4468
+ crop
4469
+ }
4470
+ );
4471
+ }
4472
+ if (fullBody) {
4473
+ poses.push(
4474
+ whole("full-rest"),
4475
+ whole("full-turn-p30", { ParamAngleX: 30 }),
4476
+ whole("full-body-x-m10", { ParamBodyAngleX: -10 }),
4477
+ whole("full-body-x-p10", { ParamBodyAngleX: 10 }),
4478
+ whole("full-body-y-m10", { ParamBodyAngleY: -10 }),
4479
+ whole("full-body-y-p10", { ParamBodyAngleY: 10 }),
4480
+ whole("full-body-z-m10", { ParamBodyAngleZ: -10 }),
4481
+ whole("full-body-z-p10", { ParamBodyAngleZ: 10 }),
4482
+ whole("full-arm-l-16", { ParamArmL: 16 }),
4483
+ whole("full-arm-l-32", { ParamArmL: 32 }),
4484
+ whole("full-arm-r-16", { ParamArmR: 16 }),
4485
+ whole("full-arm-r-32", { ParamArmR: 32 }),
4486
+ whole("full-elbow-l-m10", { ParamElbowL: -10 }),
4487
+ whole("full-elbow-l-45", { ParamElbowL: 45 }),
4488
+ whole("full-elbow-l-90", { ParamElbowL: 90 }),
4489
+ whole("full-elbow-r-m10", { ParamElbowR: -10 }),
4490
+ whole("full-elbow-r-45", { ParamElbowR: 45 }),
4491
+ whole("full-elbow-r-90", { ParamElbowR: 90 })
4492
+ );
4493
+ if (model.parameters.some((p) => p.id === import_format8.StandardParameter.ArmPoseRight)) {
4494
+ poses.push(
4495
+ whole("full-pose-l", { ParamArmPoseL: 1 }),
4496
+ whole("full-pose-r", { ParamArmPoseR: 1 }),
4497
+ whole("full-pose-r-angle-m15", {
4498
+ ParamArmPoseR: 1,
4499
+ ParamArmPoseAngleR: -15
4500
+ }),
4501
+ whole("full-pose-r-angle-p15", {
4502
+ ParamArmPoseR: 1,
4503
+ ParamArmPoseAngleR: 15
4504
+ }),
4505
+ whole("full-pose-r-half", { ParamArmPoseR: 0.5 })
4506
+ );
4507
+ }
4508
+ }
4509
+ return { canvas, view, fullBody, mouth, poses };
4510
+ }
4511
+ var PNG_PREFIX = "data:image/png;base64,";
4512
+ var PAGE_SCRIPT_MS = 1e4;
4513
+ var LOAD_MS = 6e4;
4514
+ var CAPTURE_MS = 15e3;
4515
+ function readPageScript() {
4516
+ const url = new URL("../dist/render-page.global.js", importMetaUrl);
4517
+ try {
4518
+ return (0, import_node_fs5.readFileSync)(url, "utf8");
4519
+ } catch (cause) {
4520
+ throw new Error(
4521
+ "could not read the render page script; run `pnpm build` in packages/mcp",
4522
+ { cause }
4523
+ );
4524
+ }
4525
+ }
4526
+ async function renderPoses(input) {
4527
+ try {
4528
+ const modelFile = confineToWorkingDirectory(
4529
+ process.cwd(),
4530
+ resolveInputPath(input.modelPath, "model"),
4531
+ "model path",
4532
+ input.modelPath
4533
+ );
4534
+ const outDir = resolveOutputDir(input.outDir);
4535
+ const model = (0, import_format8.loadIkiModel)((0, import_node_fs5.readFileSync)(modelFile, "utf8"));
4536
+ const plan = planRenders(model);
4537
+ const browser = findBrowser();
4538
+ if (!browser) return { ok: false, error: NO_BROWSER_MESSAGE };
4539
+ const pageScript = readPageScript();
4540
+ const folds = checkModelFolds(model);
4541
+ const { failedTextures, poses } = await withBrowser(
4542
+ browser,
4543
+ async (evaluate) => {
4544
+ await evaluate(pageScript, PAGE_SCRIPT_MS);
4545
+ const loaded = await evaluate(
4546
+ `window.__ikiRender.load(${JSON.stringify(model)}, ${JSON.stringify({ canvas: plan.canvas, view: plan.view })})`,
4547
+ LOAD_MS
4548
+ );
4549
+ const written = [];
4550
+ for (const pose of plan.poses) {
4551
+ const url = await evaluate(
4552
+ `window.__ikiRender.capture(${JSON.stringify(pose.values)}, ${JSON.stringify(pose.crop)})`,
4553
+ CAPTURE_MS
4554
+ );
4555
+ if (typeof url !== "string" || !url.startsWith(PNG_PREFIX)) {
4556
+ throw new Error(`pose ${pose.name}: the page returned no PNG`);
4557
+ }
4558
+ const file = import_node_path9.default.join(outDir, `${pose.name}.png`);
4559
+ writeFileAtomic(
4560
+ file,
4561
+ Buffer.from(url.slice(PNG_PREFIX.length), "base64")
4562
+ );
4563
+ written.push({ name: pose.name, path: file });
4564
+ }
4565
+ return { failedTextures: loaded.failedTextures, poses: written };
4566
+ }
4567
+ );
4568
+ return {
4569
+ ok: true,
4570
+ outDir,
4571
+ canvas: plan.canvas,
4572
+ fullBody: plan.fullBody,
4573
+ mouth: plan.mouth,
4574
+ failedTextures,
4575
+ poses,
4576
+ modelCanvas: model.canvas,
4577
+ folds
4578
+ };
4579
+ } catch (error) {
4580
+ if (error instanceof AutoRigInputError || error instanceof import_format8.IkiFormatError) {
4581
+ return { ok: false, error: error.message };
4582
+ }
4583
+ throw error;
4584
+ }
4585
+ }
4586
+
3288
4587
  // src/server.ts
3289
4588
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
3290
4589
  var import_zod = require("zod");
3291
4590
  function createIkiMcpServer() {
3292
- const server = new import_mcp.McpServer({ name: "iki", version: "0.23.2" });
4591
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.25.0" });
3293
4592
  server.registerTool(
3294
4593
  "validate_iki",
3295
4594
  {
@@ -3354,7 +4653,7 @@ function createIkiMcpServer() {
3354
4653
  server.registerTool(
3355
4654
  "auto_rig_from_layers",
3356
4655
  {
3357
- 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.",
4656
+ 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.",
3358
4657
  inputSchema: {
3359
4658
  layers: import_zod.z.array(
3360
4659
  import_zod.z.object({
@@ -3394,7 +4693,7 @@ function createIkiMcpServer() {
3394
4693
  async (args) => {
3395
4694
  try {
3396
4695
  const r = await autoRigFromLayers(args);
3397
- const text = r.ok ? r.path : `INVALID: ${r.error}`;
4696
+ const text = r.ok ? [r.path, ...formatFoldReport(r.folds, r.canvas)].join("\n") : `INVALID: ${r.error}`;
3398
4697
  return { content: [{ type: "text", text }], structuredContent: r };
3399
4698
  } catch (err) {
3400
4699
  const error = err instanceof Error ? err.message : String(err);
@@ -3519,19 +4818,53 @@ function createIkiMcpServer() {
3519
4818
  }
3520
4819
  }
3521
4820
  );
4821
+ server.registerTool(
4822
+ "render_poses",
4823
+ {
4824
+ 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.",
4825
+ inputSchema: {
4826
+ modelPath: import_zod.z.string().describe(
4827
+ "Rigged .iki file path (resolved against cwd; must sit under the working directory)."
4828
+ ),
4829
+ outDir: import_zod.z.string().describe(
4830
+ "Existing directory to write the pose PNGs into (resolved against cwd; must already exist; confined to the working directory)."
4831
+ )
4832
+ }
4833
+ },
4834
+ async (args) => {
4835
+ try {
4836
+ const r = await renderPoses(args);
4837
+ const text = r.ok ? [
4838
+ ...r.poses.map((p) => p.path),
4839
+ ...formatFoldReport(r.folds, r.modelCanvas)
4840
+ ].join("\n") : `INVALID: ${r.error}`;
4841
+ return { content: [{ type: "text", text }], structuredContent: r };
4842
+ } catch (err) {
4843
+ const error = err instanceof Error ? err.message : String(err);
4844
+ return {
4845
+ content: [{ type: "text", text: `Unexpected error: ${error}` }],
4846
+ structuredContent: { ok: false, error },
4847
+ isError: true
4848
+ };
4849
+ }
4850
+ }
4851
+ );
3522
4852
  return server;
3523
4853
  }
3524
4854
  // Annotate the CommonJS export names for ESM import in node:
3525
4855
  0 && (module.exports = {
3526
4856
  autoRigFromLayers,
4857
+ checkModelFolds,
3527
4858
  composeLayersFromParts,
3528
4859
  createIkiMcpServer,
3529
4860
  describeIki,
4861
+ formatFoldReport,
3530
4862
  formatMeasureReport,
3531
4863
  formatTurnReport,
3532
4864
  listStandardParameters,
3533
4865
  measureLayers,
3534
4866
  measureTurnReference,
4867
+ renderPoses,
3535
4868
  validateIki
3536
4869
  });
3537
4870
  //# sourceMappingURL=index.js.map