@ikijs/mcp 0.11.1 → 0.11.3

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
@@ -44,7 +44,7 @@ __export(index_exports, {
44
44
  module.exports = __toCommonJS(index_exports);
45
45
 
46
46
  // src/tools.ts
47
- var import_node_path3 = __toESM(require("path"));
47
+ var import_node_path2 = __toESM(require("path"));
48
48
  var import_format = require("@ikijs/format");
49
49
  var import_editor2 = require("@ikijs/editor");
50
50
 
@@ -247,135 +247,450 @@ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
247
247
  return `data:image/png;base64,${page.toString("base64")}`;
248
248
  }
249
249
 
250
- // src/measure-turn.ts
251
- var import_node_path2 = __toESM(require("path"));
252
- var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
253
- var IRIS_V_MIN = 0.18;
254
- var IRIS_V_MAX = 0.95;
255
- var IRIS_MEAN_V_MIN = 0.32;
256
- var CLOSE_RADIUS = 3;
257
- var CLOSE_RADIUS_REFERENCE_PX = 1254;
258
- var BLOB_MAX_FRAC = 0.12;
259
- var KEYED_SPAN_MAX_FRAC = 0.95;
260
- var MIN_AREA_REFERENCE_PIXELS = 1254 * 1254;
261
- var MIN_AREA = 300;
262
- var PAIR_DX_MIN_FRAC = 0.08;
263
- var PAIR_DX_MAX_FRAC = 0.35;
264
- var PAIR_DY_MAX_FRAC = 0.05;
265
- var MAX_CANDIDATES = 12;
266
- var HEAD_BAND = 10;
267
- var ALPHA_OPAQUE = 128;
268
- var BG_HUE_MIN = 220;
269
- var BG_HUE_MAX = 260;
270
- var BG_SAT_MAX = 0.2;
271
- var BG_V_MIN = 0.55;
272
- var BG_V_BLACK = 0.03;
273
- function denseCoreOf(rgba, width, height) {
274
- let minX = width;
275
- let minY = height;
276
- let maxX = -1;
277
- let maxY = -1;
278
- for (let y = 0; y < height; y++) {
279
- for (let x = 0; x < width; x++) {
280
- if (rgba[(y * width + x) * 4 + 3] >= ALPHA_OPAQUE) {
281
- if (x < minX) minX = x;
282
- if (x > maxX) maxX = x;
283
- if (y < minY) minY = y;
284
- if (y > maxY) maxY = y;
285
- }
286
- }
250
+ // src/tools.ts
251
+ function coerceModel(model) {
252
+ try {
253
+ const parsed = typeof model === "string" ? (0, import_format.loadIkiModel)(model) : (0, import_format.parseIkiModel)(model);
254
+ return { ok: true, model: parsed };
255
+ } catch (e) {
256
+ if (e instanceof import_format.IkiFormatError) return { ok: false, error: e.message };
257
+ throw e;
287
258
  }
288
- if (maxX < 0) return null;
289
- return { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 };
290
259
  }
291
- var SPECK_CORE_FRACTION = 0.25;
292
- function isSpeckCore(core, part) {
293
- return core.w < SPECK_CORE_FRACTION * part.w || core.h < SPECK_CORE_FRACTION * part.h;
294
- }
295
- function rgbToHsv(r, g, b) {
296
- r /= 255;
297
- g /= 255;
298
- b /= 255;
299
- const max = Math.max(r, g, b);
300
- const min = Math.min(r, g, b);
301
- const d = max - min;
302
- let h = 0;
303
- if (d > 0) {
304
- if (max === r) h = (g - b) / d % 6;
305
- else if (max === g) h = (b - r) / d + 2;
306
- else h = (r - g) / d + 4;
307
- h *= 60;
308
- if (h < 0) h += 360;
309
- }
310
- return [h, max === 0 ? 0 : d / max, max];
260
+ function validateIki(model) {
261
+ const result = coerceModel(model);
262
+ if (!result.ok) return { ok: false, error: result.error };
263
+ return { ok: true };
311
264
  }
312
- function dilate(mask, width, height, r) {
313
- const out = new Uint8Array(width * height);
314
- for (let y = 0; y < height; y++) {
315
- for (let x = 0; x < width; x++) {
316
- if (!mask[y * width + x]) continue;
317
- for (let dy = -r; dy <= r; dy++) {
318
- for (let dx = -r; dx <= r; dx++) {
319
- const yy = y + dy;
320
- const xx = x + dx;
321
- if (yy >= 0 && yy < height && xx >= 0 && xx < width)
322
- out[yy * width + xx] = 1;
265
+ function describeIki(model) {
266
+ const result = coerceModel(model);
267
+ if (!result.ok) return { ok: false, error: result.error };
268
+ const m = result.model;
269
+ const parameters = m.parameters.map((p) => ({
270
+ id: p.id,
271
+ min: p.min,
272
+ max: p.max,
273
+ default: p.default
274
+ }));
275
+ const parts = m.parts.map((p) => {
276
+ const entry = {
277
+ id: p.id,
278
+ order: p.order
279
+ };
280
+ if (p.deformer !== void 0) entry.deformer = p.deformer;
281
+ return entry;
282
+ });
283
+ const deformers = (m.deformers ?? []).map(
284
+ (d) => {
285
+ const kind = d.kind === "warp" ? "warp" : "matrix";
286
+ const entry = { id: d.id, kind };
287
+ if (d.parent !== void 0) entry.parent = d.parent;
288
+ if (d.kind === "warp") {
289
+ if (d.warp2d !== void 0) {
290
+ entry.warp = {
291
+ mode: "2d",
292
+ parameterX: d.warp2d.parameter,
293
+ parameterY: d.warp2d.parameterY,
294
+ gridX: d.grid.cols,
295
+ gridY: d.grid.rows
296
+ };
297
+ } else if (d.warps !== void 0 && d.warps.length > 0) {
298
+ entry.warp = {
299
+ mode: "1d",
300
+ parameters: d.warps.map((w) => w.parameter)
301
+ };
323
302
  }
324
303
  }
304
+ return entry;
325
305
  }
306
+ );
307
+ const summary = {
308
+ name: m.name,
309
+ canvas: { width: m.canvas.width, height: m.canvas.height },
310
+ parameters,
311
+ parts,
312
+ deformers
313
+ };
314
+ return { ok: true, summary };
315
+ }
316
+ var STANDARD_PARAMETER_INFO = [
317
+ {
318
+ id: import_format.StandardParameter.MouthOpen,
319
+ description: "Mouth open amount for lip-sync (0 closed .. 1 open)."
320
+ },
321
+ {
322
+ id: import_format.StandardParameter.MouthForm,
323
+ description: "Mouth form / smile (-1 .. 1)."
324
+ },
325
+ {
326
+ id: import_format.StandardParameter.EyeOpenLeft,
327
+ description: "Left eye open (0 closed .. 1 open). Drive with the right eye for a blink."
328
+ },
329
+ {
330
+ id: import_format.StandardParameter.EyeOpenRight,
331
+ description: "Right eye open (0 closed .. 1 open)."
332
+ },
333
+ {
334
+ id: import_format.StandardParameter.EyeballX,
335
+ description: "Eyeball gaze, horizontal (-1 .. 1)."
336
+ },
337
+ {
338
+ id: import_format.StandardParameter.EyeballY,
339
+ description: "Eyeball gaze, vertical (-1 .. 1)."
340
+ },
341
+ {
342
+ id: import_format.StandardParameter.AngleX,
343
+ description: "Head angle, horizontal degrees."
344
+ },
345
+ {
346
+ id: import_format.StandardParameter.AngleY,
347
+ description: "Head angle, vertical degrees."
348
+ },
349
+ {
350
+ id: import_format.StandardParameter.AngleZ,
351
+ description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
352
+ },
353
+ {
354
+ id: import_format.StandardParameter.Breath,
355
+ description: "Idle breath (0 .. 1), cycled by the host."
356
+ },
357
+ {
358
+ id: import_format.StandardParameter.BrowLeftY,
359
+ description: "Left brow raise/lower (-1 .. 1)."
360
+ },
361
+ {
362
+ id: import_format.StandardParameter.BrowRightY,
363
+ description: "Right brow raise/lower (-1 .. 1)."
364
+ },
365
+ {
366
+ id: import_format.StandardParameter.BrowLeftAngle,
367
+ description: "Left brow tilt/angle (-1 .. 1)."
368
+ },
369
+ {
370
+ id: import_format.StandardParameter.BrowRightAngle,
371
+ description: "Right brow tilt/angle (-1 .. 1)."
372
+ },
373
+ {
374
+ id: import_format.StandardParameter.HairSwayX,
375
+ description: "Horizontal hair-sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
376
+ },
377
+ {
378
+ id: import_format.StandardParameter.HairSwayZ,
379
+ description: "Hair-sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
326
380
  }
327
- return out;
381
+ ];
382
+ function listStandardParameters() {
383
+ return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));
328
384
  }
329
- function erode(mask, width, height, r) {
330
- const out = new Uint8Array(width * height);
331
- for (let y = 0; y < height; y++) {
332
- for (let x = 0; x < width; x++) {
333
- if (!mask[y * width + x]) continue;
334
- let keep = true;
335
- for (let dy = -r; dy <= r && keep; dy++) {
336
- for (let dx = -r; dx <= r; dx++) {
337
- const yy = y + dy;
338
- const xx = x + dx;
339
- if (yy < 0 || yy >= height || xx < 0 || xx >= width || !mask[yy * width + xx]) {
340
- keep = false;
341
- break;
342
- }
343
- }
344
- }
345
- if (keep) out[y * width + x] = 1;
346
- }
385
+ function expectInput(label, fn) {
386
+ try {
387
+ return fn();
388
+ } catch (e) {
389
+ throw new AutoRigInputError(
390
+ `${label}: ${e instanceof Error ? e.message : String(e)}`
391
+ );
347
392
  }
348
- return out;
349
393
  }
350
- function closeMask(mask, width, height, r) {
351
- return erode(dilate(mask, width, height, r), width, height, r);
394
+ var LOSSLESS_PAGE_ROLE = "nose";
395
+ async function renderAtlasPage(crops, quantizeColors) {
396
+ const layout = (0, import_editor2.packAtlas)(
397
+ crops.map((c) => ({ id: c.id, width: c.width, height: c.height }))
398
+ );
399
+ if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {
400
+ throw new AutoRigInputError(
401
+ `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`
402
+ );
403
+ }
404
+ const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);
405
+ return { crops, layout, dataUri };
352
406
  }
353
- function components(mask, width, height, minArea) {
354
- const seen = new Uint8Array(width * height);
355
- const out = [];
356
- for (let i = 0; i < width * height; i++) {
357
- if (!mask[i] || seen[i]) continue;
358
- const stack = [i];
359
- seen[i] = 1;
360
- let x0 = width;
361
- let x1 = 0;
362
- let y0 = height;
363
- let y1 = 0;
364
- let n = 0;
365
- let sx = 0;
366
- let sy = 0;
367
- while (stack.length) {
368
- const p = stack.pop();
369
- const x = p % width;
370
- const y = p / width | 0;
371
- n++;
372
- sx += x;
373
- sy += y;
374
- if (x < x0) x0 = x;
375
- if (x > x1) x1 = x;
376
- if (y < y0) y0 = y;
377
- if (y > y1) y1 = y;
378
- const neighbours = [];
407
+ async function autoRigFromLayers(input) {
408
+ try {
409
+ const layers = input.layers;
410
+ if (!Array.isArray(layers) || layers.length === 0) {
411
+ throw new AutoRigInputError("layers must be a non-empty array");
412
+ }
413
+ if (layers.length > MAX_LAYERS) {
414
+ throw new AutoRigInputError(
415
+ `too many layers: ${layers.length} > ${MAX_LAYERS}`
416
+ );
417
+ }
418
+ const outPath = resolveOutputPath(
419
+ input.outputPath ?? "auto-rigged-model.iki"
420
+ );
421
+ const quantizeColors = input.quantizeColors;
422
+ if (quantizeColors !== void 0 && (!Number.isInteger(quantizeColors) || quantizeColors < 2 || quantizeColors > 256)) {
423
+ throw new AutoRigInputError(
424
+ `quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`
425
+ );
426
+ }
427
+ const resolvedLayers = layers.map((layer) => {
428
+ const resolved = resolveInputPath(layer.path);
429
+ return { resolved, fileName: layer.fileName ?? import_node_path2.default.basename(resolved) };
430
+ });
431
+ const rolePairs = expectInput(
432
+ "role parsing",
433
+ () => (0, import_editor2.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
434
+ );
435
+ const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));
436
+ let canvasW = 0;
437
+ let canvasH = 0;
438
+ let totalPixels = 0;
439
+ let measurer;
440
+ const crops = [];
441
+ for (let i = 0; i < resolvedLayers.length; i++) {
442
+ const { resolved, fileName } = resolvedLayers[i];
443
+ const png = await decodePng(resolved);
444
+ if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {
445
+ throw new AutoRigInputError(
446
+ `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`
447
+ );
448
+ }
449
+ totalPixels += png.width * png.height;
450
+ if (totalPixels > MAX_TOTAL_PIXELS) {
451
+ throw new AutoRigInputError(
452
+ `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`
453
+ );
454
+ }
455
+ if (i === 0) {
456
+ canvasW = png.width;
457
+ canvasH = png.height;
458
+ if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {
459
+ throw new AutoRigInputError(
460
+ `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`
461
+ );
462
+ }
463
+ measurer = (0, import_editor2.createLayerSetMeasurer)({ width: canvasW, height: canvasH });
464
+ } else if (png.width !== canvasW || png.height !== canvasH) {
465
+ throw new AutoRigInputError(
466
+ `layer "${fileName}" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
467
+ );
468
+ }
469
+ const role = roleByFileName.get(fileName);
470
+ if (role === void 0) {
471
+ throw new AutoRigInputError(`no role resolved for "${fileName}"`);
472
+ }
473
+ const layer = measurer.add({ role, fileName, rgba: png.rgba });
474
+ if (layer === null) {
475
+ throw new AutoRigInputError(
476
+ `role "${role}" file "${fileName}": layer is empty after alpha threshold`
477
+ );
478
+ }
479
+ const { bbox } = layer;
480
+ const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);
481
+ crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
482
+ }
483
+ const measurement = measurer.finish();
484
+ const { headHalfWidth, headHalfWidthApplied, turnOptions } = measurement;
485
+ const { headEdges, strandEdges } = turnOptions;
486
+ const noseCore = measurement.layers.find(
487
+ (l) => l.role === "nose"
488
+ )?.denseCore;
489
+ let turn;
490
+ let model;
491
+ try {
492
+ const { eyeShift, farEyeRatio, silhouetteRatio, noseShift, mouthShift } = input.turnTargets ?? {};
493
+ model = (0, import_editor2.generateIkiFromLayerSet)(
494
+ measurement.layers,
495
+ { width: canvasW, height: canvasH },
496
+ {
497
+ turnTargets: {
498
+ eyeShift,
499
+ farEyeRatio,
500
+ silhouetteRatio,
501
+ noseShift,
502
+ mouthShift,
503
+ ...turnOptions.turnTargets
504
+ },
505
+ onTurnSolved: (report) => {
506
+ turn = report;
507
+ },
508
+ ...headEdges === void 0 ? {} : { headEdges },
509
+ ...strandEdges === void 0 ? {} : { strandEdges }
510
+ }
511
+ );
512
+ } catch (e) {
513
+ if (!(e instanceof import_editor2.TurnTargetError)) throw e;
514
+ throw new AutoRigInputError(e.message);
515
+ }
516
+ const doc = new import_editor2.EditorDocument(model);
517
+ const losslessCrop = quantizeColors === void 0 ? void 0 : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);
518
+ const pages = losslessCrop === void 0 ? [await renderAtlasPage(crops, quantizeColors)] : [
519
+ await renderAtlasPage(
520
+ crops.filter((c) => c !== losslessCrop),
521
+ quantizeColors
522
+ ),
523
+ await renderAtlasPage([losslessCrop], void 0)
524
+ ];
525
+ const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);
526
+ if (atlasBytes > MAX_OUTPUT_BYTES) {
527
+ throw new AutoRigInputError(
528
+ `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`
529
+ );
530
+ }
531
+ const partTextureAssignments = pages.flatMap(
532
+ ({ crops: pageCrops, layout }) => pageCrops.map((crop) => {
533
+ const placement2 = layout.placements.find((p) => p.id === crop.id);
534
+ if (placement2 === void 0) {
535
+ throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
536
+ }
537
+ return {
538
+ partId: crop.id,
539
+ uv: (0, import_editor2.uvRectFor)(placement2, {
540
+ width: layout.pageWidth,
541
+ height: layout.pageHeight
542
+ })
543
+ };
544
+ })
545
+ );
546
+ doc.applyAtlas({
547
+ textures: [{ source: pages[0].dataUri }],
548
+ partTextureAssignments
549
+ });
550
+ let patched = doc.getModel();
551
+ if (losslessCrop !== void 0) {
552
+ patched = structuredClone(patched);
553
+ patched.textures = pages.map((p) => ({ source: p.dataUri }));
554
+ patched.parts.find((p) => p.id === losslessCrop.id).texture.index = 1;
555
+ }
556
+ const finalModel = (0, import_format.parseIkiModel)(patched);
557
+ writeFileAtomic(outPath, JSON.stringify(finalModel));
558
+ return {
559
+ ok: true,
560
+ path: outPath,
561
+ canvas: { width: canvasW, height: canvasH },
562
+ partCount: finalModel.parts.length,
563
+ atlasBytes,
564
+ ...headHalfWidth === void 0 ? {} : { headHalfWidth },
565
+ headHalfWidthApplied,
566
+ ...headEdges === void 0 ? {} : { headEdges },
567
+ ...strandEdges === void 0 ? {} : { strandEdges },
568
+ ...noseCore === void 0 ? {} : { noseCore },
569
+ ...turn === void 0 ? {} : { turn }
570
+ };
571
+ } catch (err) {
572
+ if (err instanceof AutoRigInputError)
573
+ return { ok: false, error: err.message };
574
+ throw err;
575
+ }
576
+ }
577
+
578
+ // src/compose.ts
579
+ var import_node_fs3 = __toESM(require("fs"));
580
+ var import_node_path5 = __toESM(require("path"));
581
+ var import_sharp2 = __toESM(require("sharp"));
582
+
583
+ // src/measure.ts
584
+ var import_node_fs2 = __toESM(require("fs"));
585
+ var import_node_path4 = __toESM(require("path"));
586
+
587
+ // src/measure-turn.ts
588
+ var import_node_path3 = __toESM(require("path"));
589
+ var import_editor3 = require("@ikijs/editor");
590
+ var import_editor4 = require("@ikijs/editor");
591
+ var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
592
+ var IRIS_V_MIN = 0.18;
593
+ var IRIS_V_MAX = 0.95;
594
+ var IRIS_MEAN_V_MIN = 0.32;
595
+ var CLOSE_RADIUS = 3;
596
+ var CLOSE_RADIUS_REFERENCE_PX = 1254;
597
+ var BLOB_MAX_FRAC = 0.12;
598
+ var KEYED_SPAN_MAX_FRAC = 0.95;
599
+ var MIN_AREA_REFERENCE_PIXELS = 1254 * 1254;
600
+ var MIN_AREA = 300;
601
+ var PAIR_DX_MIN_FRAC = 0.08;
602
+ var PAIR_DX_MAX_FRAC = 0.35;
603
+ var PAIR_DY_MAX_FRAC = 0.05;
604
+ var MAX_CANDIDATES = 12;
605
+ var BG_HUE_MIN = 220;
606
+ var BG_HUE_MAX = 260;
607
+ var BG_SAT_MAX = 0.2;
608
+ var BG_V_MIN = 0.55;
609
+ var BG_V_BLACK = 0.03;
610
+ function rgbToHsv(r, g, b) {
611
+ r /= 255;
612
+ g /= 255;
613
+ b /= 255;
614
+ const max = Math.max(r, g, b);
615
+ const min = Math.min(r, g, b);
616
+ const d = max - min;
617
+ let h = 0;
618
+ if (d > 0) {
619
+ if (max === r) h = (g - b) / d % 6;
620
+ else if (max === g) h = (b - r) / d + 2;
621
+ else h = (r - g) / d + 4;
622
+ h *= 60;
623
+ if (h < 0) h += 360;
624
+ }
625
+ return [h, max === 0 ? 0 : d / max, max];
626
+ }
627
+ function dilate(mask, width, height, r) {
628
+ const out = new Uint8Array(width * height);
629
+ for (let y = 0; y < height; y++) {
630
+ for (let x = 0; x < width; x++) {
631
+ if (!mask[y * width + x]) continue;
632
+ for (let dy = -r; dy <= r; dy++) {
633
+ for (let dx = -r; dx <= r; dx++) {
634
+ const yy = y + dy;
635
+ const xx = x + dx;
636
+ if (yy >= 0 && yy < height && xx >= 0 && xx < width)
637
+ out[yy * width + xx] = 1;
638
+ }
639
+ }
640
+ }
641
+ }
642
+ return out;
643
+ }
644
+ function erode(mask, width, height, r) {
645
+ const out = new Uint8Array(width * height);
646
+ for (let y = 0; y < height; y++) {
647
+ for (let x = 0; x < width; x++) {
648
+ if (!mask[y * width + x]) continue;
649
+ let keep = true;
650
+ for (let dy = -r; dy <= r && keep; dy++) {
651
+ for (let dx = -r; dx <= r; dx++) {
652
+ const yy = y + dy;
653
+ const xx = x + dx;
654
+ if (yy < 0 || yy >= height || xx < 0 || xx >= width || !mask[yy * width + xx]) {
655
+ keep = false;
656
+ break;
657
+ }
658
+ }
659
+ }
660
+ if (keep) out[y * width + x] = 1;
661
+ }
662
+ }
663
+ return out;
664
+ }
665
+ function closeMask(mask, width, height, r) {
666
+ return erode(dilate(mask, width, height, r), width, height, r);
667
+ }
668
+ function components(mask, width, height, minArea) {
669
+ const seen = new Uint8Array(width * height);
670
+ const out = [];
671
+ for (let i = 0; i < width * height; i++) {
672
+ if (!mask[i] || seen[i]) continue;
673
+ const stack = [i];
674
+ seen[i] = 1;
675
+ let x0 = width;
676
+ let x1 = 0;
677
+ let y0 = height;
678
+ let y1 = 0;
679
+ let n = 0;
680
+ let sx = 0;
681
+ let sy = 0;
682
+ while (stack.length) {
683
+ const p = stack.pop();
684
+ const x = p % width;
685
+ const y = p / width | 0;
686
+ n++;
687
+ sx += x;
688
+ sy += y;
689
+ if (x < x0) x0 = x;
690
+ if (x > x1) x1 = x;
691
+ if (y < y0) y0 = y;
692
+ if (y > y1) y1 = y;
693
+ const neighbours = [];
379
694
  if (x > 0) neighbours.push(p - 1);
380
695
  if (x < width - 1) neighbours.push(p + 1);
381
696
  if (y > 0) neighbours.push(p - width);
@@ -402,21 +717,6 @@ function components(mask, width, height, minArea) {
402
717
  }
403
718
  return out.sort((a, b) => b.area - a.area);
404
719
  }
405
- function foregroundSpan(mask, width, height, rowLo, rowHi) {
406
- let left = width;
407
- let right = -1;
408
- for (let y = Math.max(0, rowLo); y <= Math.min(height - 1, rowHi); y++) {
409
- for (let x = 0; x < width; x++) {
410
- if (!mask[y * width + x]) continue;
411
- if (x < left) left = x;
412
- if (x > right) right = x;
413
- }
414
- }
415
- return { left, right };
416
- }
417
- function headHalfOf(span) {
418
- return (span.right - span.left + 1) / 2;
419
- }
420
720
  function resolveIris(override) {
421
721
  const iris = { ...DEFAULT_IRIS, ...override };
422
722
  if (iris.hueMin < 0 || iris.hueMax > 360 || iris.hueMin >= iris.hueMax) {
@@ -437,7 +737,7 @@ async function measureTurnImage(filePath, iris) {
437
737
  let transparent = false;
438
738
  if (hasAlpha) {
439
739
  for (let i = 0; i < n; i++) {
440
- if (rgba[i * 4 + 3] < ALPHA_OPAQUE) {
740
+ if (rgba[i * 4 + 3] < import_editor3.ALPHA_OPAQUE) {
441
741
  transparent = true;
442
742
  break;
443
743
  }
@@ -448,7 +748,7 @@ async function measureTurnImage(filePath, iris) {
448
748
  const fg = new Uint8Array(n);
449
749
  const value = new Float32Array(n);
450
750
  for (let i = 0; i < n; i++) {
451
- if (rgba[i * 4 + 3] < ALPHA_OPAQUE) continue;
751
+ if (rgba[i * 4 + 3] < import_editor3.ALPHA_OPAQUE) continue;
452
752
  const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);
453
753
  if (maskMode === "alpha") {
454
754
  fg[i] = 1;
@@ -514,12 +814,12 @@ async function measureTurnImage(filePath, iris) {
514
814
  }
515
815
  const [irisL, irisR] = best.pair;
516
816
  const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);
517
- const { left, right } = foregroundSpan(
817
+ const { left, right } = (0, import_editor3.foregroundSpan)(
518
818
  fg,
519
819
  width,
520
820
  height,
521
- eyeRow - HEAD_BAND,
522
- eyeRow + HEAD_BAND
821
+ eyeRow - import_editor3.HEAD_BAND,
822
+ eyeRow + import_editor3.HEAD_BAND
523
823
  );
524
824
  if (right <= left) {
525
825
  throw new AutoRigInputError(
@@ -537,576 +837,69 @@ async function measureTurnImage(filePath, iris) {
537
837
  height,
538
838
  maskMode,
539
839
  irisL,
540
- irisR,
541
- eyeRow,
542
- head: {
543
- left,
544
- right,
545
- cx: (left + right) / 2,
546
- half: headHalfOf({ left, right })
547
- },
548
- pairCx: (irisL.cx + irisR.cx) / 2,
549
- eyeGap: irisR.cx - irisL.cx
550
- };
551
- }
552
- function farNearWidths(m, turnSign) {
553
- return turnSign < 0 ? { far: m.irisL.w, near: m.irisR.w } : { far: m.irisR.w, near: m.irisL.w };
554
- }
555
- function overlaySvg(m) {
556
- const box = (b, stroke) => `<rect x="${b.x0}" y="${b.y0}" width="${b.w}" height="${b.h}" fill="none" stroke="${stroke}" stroke-width="3"/>`;
557
- const tick = (x, half, stroke) => `<line x1="${x}" y1="${m.eyeRow - half}" x2="${x}" y2="${m.eyeRow + half}" stroke="${stroke}" stroke-width="3"/>`;
558
- return `<svg width="${m.width}" height="${m.height}">` + box(m.irisL, "#ff0000") + box(m.irisR, "#00c000") + tick(m.head.left, 40, "#0000ff") + tick(m.head.right, 40, "#0000ff") + tick(m.head.cx, 60, "#ff8800") + tick(m.pairCx, 60, "#ff00ff") + "</svg>";
559
- }
560
- async function writeOverlay(debugDir, label, m) {
561
- const outPath = import_node_path2.default.join(
562
- debugDir,
563
- `${label}-${import_node_path2.default.basename(m.file, ".png")}.debug.png`
564
- );
565
- writeFileAtomic(outPath, await encodeOverlayPng(m.file, overlaySvg(m)));
566
- return outPath;
567
- }
568
- var IRIS_HEIGHT_SCALE_TOLERANCE = 0.1;
569
- async function measureTurnReference(input) {
570
- try {
571
- const iris = resolveIris(input.iris);
572
- const frontPath = resolveInputPath(input.front);
573
- const turnedPath = resolveInputPath(input.turned);
574
- const debugDir = input.debugDir === void 0 ? null : resolveOutputDir(input.debugDir);
575
- const front = await measureTurnImage(frontPath, iris);
576
- const turned = await measureTurnImage(turnedPath, iris);
577
- const frontIrisH = (front.irisL.h + front.irisR.h) / 2;
578
- const turnedIrisH = (turned.irisL.h + turned.irisR.h) / 2;
579
- if (Math.abs(turnedIrisH - frontIrisH) / frontIrisH > IRIS_HEIGHT_SCALE_TOLERANCE) {
580
- throw new AutoRigInputError(
581
- `front and turned images are not at the same scale: mean iris height ${frontIrisH.toFixed(1)}px front vs ${turnedIrisH.toFixed(1)}px turned, more than ${(IRIS_HEIGHT_SCALE_TOLERANCE * 100).toFixed(0)}% apart \u2014 a yaw does not change iris height, so the pair must share the same framing and head size`
582
- );
583
- }
584
- const frontShift = front.pairCx - front.head.cx;
585
- const turnedShift = turned.pairCx - turned.head.cx;
586
- const shift = turnedShift - frontShift;
587
- const turnSign = shift < 0 ? -1 : 1;
588
- const f = farNearWidths(front, turnSign);
589
- const t = farNearWidths(turned, turnSign);
590
- const debug = debugDir === null ? void 0 : [
591
- await writeOverlay(debugDir, "front", front),
592
- await writeOverlay(debugDir, "turned", turned)
593
- ];
594
- return {
595
- ok: true,
596
- front,
597
- turned,
598
- farEyeRatio: t.far / t.near / (f.far / f.near),
599
- eyeShift: shift / front.head.half,
600
- silhouetteRatio: turned.head.half / front.head.half,
601
- turnSign,
602
- ...debug === void 0 ? {} : { debug }
603
- };
604
- } catch (err) {
605
- if (err instanceof AutoRigInputError)
606
- return { ok: false, error: err.message };
607
- throw err;
608
- }
609
- }
610
- var n1 = (v) => v.toFixed(1);
611
- var n3 = (v) => v.toFixed(3);
612
- function imageBlock(label, m) {
613
- return [
614
- `# ${label} ${m.file} ${m.width}x${m.height} mask: ${m.maskMode}`,
615
- `iris widths ${m.irisL.w} / ${m.irisR.w} px centres ${n1(m.irisL.cx)} / ${n1(m.irisR.cx)} eye row ${m.eyeRow} gap ${n1(m.eyeGap)}`,
616
- `head ${m.head.left}..${m.head.right} centre ${n1(m.head.cx)} half ${n1(m.head.half)} pair centre ${n1(m.pairCx)}`
617
- ];
618
- }
619
- function formatTurnReport(result) {
620
- const { front, turned } = result;
621
- const f = farNearWidths(front, result.turnSign);
622
- const t = farNearWidths(turned, result.turnSign);
623
- const lines = [
624
- `farEyeRatio ${n3(result.farEyeRatio)} far/near iris width ${t.far}/${t.near} turned over ${f.far}/${f.near} front`,
625
- `eyeShift ${n3(result.eyeShift)} pair-vs-head centre ${n1(turned.pairCx - turned.head.cx)} px turned, ${n1(front.pairCx - front.head.cx)} px front, over front head half ${n1(front.head.half)} px (hh)`,
626
- `silhouetteRatio ${n3(result.silhouetteRatio)} head half ${n1(turned.head.half)} px turned over ${n1(front.head.half)} px front`,
627
- `turnSign ${result.turnSign} (the head turned toward the image's ${result.turnSign < 0 ? "left" : "right"})`,
628
- "",
629
- ...imageBlock("front", front),
630
- "",
631
- ...imageBlock("turned", turned)
632
- ];
633
- if (result.debug !== void 0) {
634
- lines.push("", ...result.debug.map((p) => `debug overlay ${p}`));
635
- }
636
- return lines.join("\n");
637
- }
638
-
639
- // src/tools.ts
640
- function coerceModel(model) {
641
- try {
642
- const parsed = typeof model === "string" ? (0, import_format.loadIkiModel)(model) : (0, import_format.parseIkiModel)(model);
643
- return { ok: true, model: parsed };
644
- } catch (e) {
645
- if (e instanceof import_format.IkiFormatError) return { ok: false, error: e.message };
646
- throw e;
647
- }
648
- }
649
- function validateIki(model) {
650
- const result = coerceModel(model);
651
- if (!result.ok) return { ok: false, error: result.error };
652
- return { ok: true };
653
- }
654
- function describeIki(model) {
655
- const result = coerceModel(model);
656
- if (!result.ok) return { ok: false, error: result.error };
657
- const m = result.model;
658
- const parameters = m.parameters.map((p) => ({
659
- id: p.id,
660
- min: p.min,
661
- max: p.max,
662
- default: p.default
663
- }));
664
- const parts = m.parts.map((p) => {
665
- const entry = {
666
- id: p.id,
667
- order: p.order
668
- };
669
- if (p.deformer !== void 0) entry.deformer = p.deformer;
670
- return entry;
671
- });
672
- const deformers = (m.deformers ?? []).map(
673
- (d) => {
674
- const kind = d.kind === "warp" ? "warp" : "matrix";
675
- const entry = { id: d.id, kind };
676
- if (d.parent !== void 0) entry.parent = d.parent;
677
- if (d.kind === "warp") {
678
- if (d.warp2d !== void 0) {
679
- entry.warp = {
680
- mode: "2d",
681
- parameterX: d.warp2d.parameter,
682
- parameterY: d.warp2d.parameterY,
683
- gridX: d.grid.cols,
684
- gridY: d.grid.rows
685
- };
686
- } else if (d.warps !== void 0 && d.warps.length > 0) {
687
- entry.warp = {
688
- mode: "1d",
689
- parameters: d.warps.map((w) => w.parameter)
690
- };
691
- }
692
- }
693
- return entry;
694
- }
695
- );
696
- const summary = {
697
- name: m.name,
698
- canvas: { width: m.canvas.width, height: m.canvas.height },
699
- parameters,
700
- parts,
701
- deformers
702
- };
703
- return { ok: true, summary };
704
- }
705
- var STANDARD_PARAMETER_INFO = [
706
- {
707
- id: import_format.StandardParameter.MouthOpen,
708
- description: "Mouth open amount for lip-sync (0 closed .. 1 open)."
709
- },
710
- {
711
- id: import_format.StandardParameter.MouthForm,
712
- description: "Mouth form / smile (-1 .. 1)."
713
- },
714
- {
715
- id: import_format.StandardParameter.EyeOpenLeft,
716
- description: "Left eye open (0 closed .. 1 open). Drive with the right eye for a blink."
717
- },
718
- {
719
- id: import_format.StandardParameter.EyeOpenRight,
720
- description: "Right eye open (0 closed .. 1 open)."
721
- },
722
- {
723
- id: import_format.StandardParameter.EyeballX,
724
- description: "Eyeball gaze, horizontal (-1 .. 1)."
725
- },
726
- {
727
- id: import_format.StandardParameter.EyeballY,
728
- description: "Eyeball gaze, vertical (-1 .. 1)."
729
- },
730
- {
731
- id: import_format.StandardParameter.AngleX,
732
- description: "Head angle, horizontal degrees."
733
- },
734
- {
735
- id: import_format.StandardParameter.AngleY,
736
- description: "Head angle, vertical degrees."
737
- },
738
- {
739
- id: import_format.StandardParameter.AngleZ,
740
- description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
741
- },
742
- {
743
- id: import_format.StandardParameter.Breath,
744
- description: "Idle breath (0 .. 1), cycled by the host."
745
- },
746
- {
747
- id: import_format.StandardParameter.BrowLeftY,
748
- description: "Left brow raise/lower (-1 .. 1)."
749
- },
750
- {
751
- id: import_format.StandardParameter.BrowRightY,
752
- description: "Right brow raise/lower (-1 .. 1)."
753
- },
754
- {
755
- id: import_format.StandardParameter.BrowLeftAngle,
756
- description: "Left brow tilt/angle (-1 .. 1)."
757
- },
758
- {
759
- id: import_format.StandardParameter.BrowRightAngle,
760
- description: "Right brow tilt/angle (-1 .. 1)."
761
- },
762
- {
763
- id: import_format.StandardParameter.HairSwayX,
764
- description: "Horizontal hair-sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
765
- },
766
- {
767
- id: import_format.StandardParameter.HairSwayZ,
768
- description: "Hair-sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
769
- }
770
- ];
771
- function listStandardParameters() {
772
- return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));
773
- }
774
- function expectInput(label, fn) {
775
- try {
776
- return fn();
777
- } catch (e) {
778
- throw new AutoRigInputError(
779
- `${label}: ${e instanceof Error ? e.message : String(e)}`
780
- );
781
- }
782
- }
783
- function eyeRowOf(layers) {
784
- const centreY = (role) => {
785
- const layer = layers.find((l) => l.role === role);
786
- return layer && layer.bbox.y + layer.bbox.h / 2;
787
- };
788
- const pairRow = (left, right) => {
789
- const a = centreY(left);
790
- const b = centreY(right);
791
- return a === void 0 || b === void 0 ? void 0 : (a + b) / 2;
840
+ irisR,
841
+ eyeRow,
842
+ head: {
843
+ left,
844
+ right,
845
+ cx: (left + right) / 2,
846
+ half: (0, import_editor3.headHalfOf)({ left, right })
847
+ },
848
+ pairCx: (irisL.cx + irisR.cx) / 2,
849
+ eyeGap: irisR.cx - irisL.cx
792
850
  };
793
- const row = pairRow("iris_L", "iris_R") ?? pairRow("eye_L", "eye_R");
794
- if (row === void 0) {
795
- throw new Error("auto-rig: no eye pair to measure the head width at");
796
- }
797
- return Math.round(row);
798
851
  }
799
- function foregroundSpanOfRows(rowLeft, rowRight, rowLo, rowHi) {
800
- let left = Infinity;
801
- let right = -Infinity;
802
- for (let y = Math.max(0, rowLo); y <= Math.min(rowLeft.length - 1, rowHi); y++) {
803
- if (rowLeft[y] < left) left = rowLeft[y];
804
- if (rowRight[y] > right) right = rowRight[y];
805
- }
806
- return { left, right };
852
+ function farNearWidths(m, turnSign) {
853
+ return turnSign < 0 ? { far: m.irisL.w, near: m.irisR.w } : { far: m.irisR.w, near: m.irisL.w };
807
854
  }
808
- function facePlateHalfOf(layers) {
809
- const face = layers.find((l) => l.role === "face");
810
- if (face === void 0) {
811
- throw new Error("auto-rig: no face layer to measure the plate against");
812
- }
813
- return face.cropW / 2;
855
+ function overlaySvg(m) {
856
+ const box = (b, stroke) => `<rect x="${b.x0}" y="${b.y0}" width="${b.w}" height="${b.h}" fill="none" stroke="${stroke}" stroke-width="3"/>`;
857
+ const tick = (x, half, stroke) => `<line x1="${x}" y1="${m.eyeRow - half}" x2="${x}" y2="${m.eyeRow + half}" stroke="${stroke}" stroke-width="3"/>`;
858
+ return `<svg width="${m.width}" height="${m.height}">` + box(m.irisL, "#ff0000") + box(m.irisR, "#00c000") + tick(m.head.left, 40, "#0000ff") + tick(m.head.right, 40, "#0000ff") + tick(m.head.cx, 60, "#ff8800") + tick(m.pairCx, 60, "#ff00ff") + "</svg>";
814
859
  }
815
- var STRAND_MIN_RUN_FRACTION = 0.5;
816
- var LOSSLESS_PAGE_ROLE = "nose";
817
- async function renderAtlasPage(crops, quantizeColors) {
818
- const layout = (0, import_editor2.packAtlas)(
819
- crops.map((c) => ({ id: c.id, width: c.width, height: c.height }))
860
+ async function writeOverlay(debugDir, label, m) {
861
+ const outPath = import_node_path3.default.join(
862
+ debugDir,
863
+ `${label}-${import_node_path3.default.basename(m.file, ".png")}.debug.png`
820
864
  );
821
- if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {
822
- throw new AutoRigInputError(
823
- `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`
824
- );
825
- }
826
- const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);
827
- return { crops, layout, dataUri };
865
+ writeFileAtomic(outPath, await encodeOverlayPng(m.file, overlaySvg(m)));
866
+ return outPath;
828
867
  }
829
- async function autoRigFromLayers(input) {
868
+ var IRIS_HEIGHT_SCALE_TOLERANCE = 0.1;
869
+ async function measureTurnReference(input) {
830
870
  try {
831
- const layers = input.layers;
832
- if (!Array.isArray(layers) || layers.length === 0) {
833
- throw new AutoRigInputError("layers must be a non-empty array");
834
- }
835
- if (layers.length > MAX_LAYERS) {
836
- throw new AutoRigInputError(
837
- `too many layers: ${layers.length} > ${MAX_LAYERS}`
838
- );
839
- }
840
- const outPath = resolveOutputPath(
841
- input.outputPath ?? "auto-rigged-model.iki"
842
- );
843
- const quantizeColors = input.quantizeColors;
844
- if (quantizeColors !== void 0 && (!Number.isInteger(quantizeColors) || quantizeColors < 2 || quantizeColors > 256)) {
871
+ const iris = resolveIris(input.iris);
872
+ const frontPath = resolveInputPath(input.front);
873
+ const turnedPath = resolveInputPath(input.turned);
874
+ const debugDir = input.debugDir === void 0 ? null : resolveOutputDir(input.debugDir);
875
+ const front = await measureTurnImage(frontPath, iris);
876
+ const turned = await measureTurnImage(turnedPath, iris);
877
+ const frontIrisH = (front.irisL.h + front.irisR.h) / 2;
878
+ const turnedIrisH = (turned.irisL.h + turned.irisR.h) / 2;
879
+ if (Math.abs(turnedIrisH - frontIrisH) / frontIrisH > IRIS_HEIGHT_SCALE_TOLERANCE) {
845
880
  throw new AutoRigInputError(
846
- `quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`
847
- );
848
- }
849
- const resolvedLayers = layers.map((layer) => {
850
- const resolved = resolveInputPath(layer.path);
851
- return { resolved, fileName: layer.fileName ?? import_node_path3.default.basename(resolved) };
852
- });
853
- const rolePairs = expectInput(
854
- "role parsing",
855
- () => (0, import_editor2.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
856
- );
857
- const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));
858
- let canvasW = 0;
859
- let canvasH = 0;
860
- let totalPixels = 0;
861
- let opaque = new Uint8Array(0);
862
- const layerInputs = [];
863
- const crops = [];
864
- const rowSpansByRole = [];
865
- let hairFrontMask;
866
- for (let i = 0; i < resolvedLayers.length; i++) {
867
- const { resolved, fileName } = resolvedLayers[i];
868
- const png = await decodePng(resolved);
869
- if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {
870
- throw new AutoRigInputError(
871
- `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`
872
- );
873
- }
874
- totalPixels += png.width * png.height;
875
- if (totalPixels > MAX_TOTAL_PIXELS) {
876
- throw new AutoRigInputError(
877
- `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`
878
- );
879
- }
880
- if (i === 0) {
881
- canvasW = png.width;
882
- canvasH = png.height;
883
- if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {
884
- throw new AutoRigInputError(
885
- `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`
886
- );
887
- }
888
- opaque = new Uint8Array(canvasW * canvasH);
889
- } else if (png.width !== canvasW || png.height !== canvasH) {
890
- throw new AutoRigInputError(
891
- `layer "${fileName}" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
892
- );
893
- }
894
- const role = roleByFileName.get(fileName);
895
- if (role === void 0) {
896
- throw new AutoRigInputError(`no role resolved for "${fileName}"`);
897
- }
898
- let bbox;
899
- try {
900
- bbox = detectAlphaBbox(png.rgba, png.width, png.height);
901
- } catch (e) {
902
- const msg = e instanceof Error ? e.message : String(e);
903
- throw new AutoRigInputError(
904
- `role "${role}" file "${fileName}": ${msg}`
905
- );
906
- }
907
- const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);
908
- const rowLeft = new Int32Array(canvasH).fill(canvasW);
909
- const rowRight = new Int32Array(canvasH).fill(-1);
910
- const ownMask = role === "hair_front" ? new Uint8Array(canvasW * canvasH) : void 0;
911
- for (let y = 0; y < canvasH; y++) {
912
- for (let x = 0; x < canvasW; x++) {
913
- const p = y * canvasW + x;
914
- if (png.rgba[p * 4 + 3] < ALPHA_OPAQUE) continue;
915
- opaque[p] = 1;
916
- if (ownMask !== void 0) ownMask[p] = 1;
917
- if (x < rowLeft[y]) rowLeft[y] = x;
918
- if (x > rowRight[y]) rowRight[y] = x;
919
- }
920
- }
921
- rowSpansByRole.push({ role, rowLeft, rowRight });
922
- if (ownMask !== void 0) hairFrontMask = ownMask;
923
- const layer = {
924
- role,
925
- fileName,
926
- canvasW,
927
- canvasH,
928
- bbox,
929
- cropW: bbox.w,
930
- cropH: bbox.h
931
- };
932
- if (role === "face") {
933
- const rowHalfWidths = [];
934
- for (let y = bbox.y; y < bbox.y + bbox.h; y++) {
935
- rowHalfWidths.push(
936
- rowRight[y] >= rowLeft[y] ? headHalfOf({ left: rowLeft[y], right: rowRight[y] }) : 0
937
- );
938
- }
939
- layer.rowHalfWidths = rowHalfWidths;
940
- } else if (role === "nose") {
941
- const core = denseCoreOf(png.rgba, canvasW, canvasH);
942
- if (core !== null && !isSpeckCore(core, bbox)) layer.denseCore = core;
943
- }
944
- layerInputs.push(layer);
945
- crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
946
- }
947
- const noseCore = layerInputs.find((l) => l.role === "nose")?.denseCore;
948
- const eyeRow = eyeRowOf(layerInputs);
949
- const span = foregroundSpan(
950
- opaque,
951
- canvasW,
952
- canvasH,
953
- eyeRow - HEAD_BAND,
954
- eyeRow + HEAD_BAND
955
- );
956
- const headHalfWidth = span.right > span.left ? headHalfOf(span) : void 0;
957
- const headHalfWidthApplied = headHalfWidth !== void 0 && headHalfWidth > facePlateHalfOf(layerInputs);
958
- let headEdges;
959
- if (headHalfWidthApplied) {
960
- const bandLo = eyeRow - HEAD_BAND;
961
- const bandHi = eyeRow + HEAD_BAND;
962
- const left = [];
963
- const right = [];
964
- for (const { role, rowLeft, rowRight } of rowSpansByRole) {
965
- const own = foregroundSpanOfRows(rowLeft, rowRight, bandLo, bandHi);
966
- if (own.right <= own.left) continue;
967
- left.push({ role, x: own.left - canvasW / 2 });
968
- right.push({ role, x: own.right - canvasW / 2 });
969
- }
970
- headEdges = { left, right };
971
- }
972
- let strandEdges;
973
- const irisLayers = layerInputs.filter((l) => l.role === "iris_L" || l.role === "iris_R").sort((a, b) => a.bbox.x + a.bbox.w / 2 - (b.bbox.x + b.bbox.w / 2));
974
- if (hairFrontMask !== void 0 && irisLayers.length === 2) {
975
- const mask = hairFrontMask;
976
- const half = canvasW / 2;
977
- const strandOn = (iris, other, side) => {
978
- const r = Math.floor(iris.bbox.y + iris.bbox.h / 2);
979
- const centre = iris.bbox.x + iris.bbox.w / 2;
980
- const otherX = other.bbox.x + other.bbox.w / 2 - half;
981
- const c = side < 0 ? Math.ceil(centre) - 1 : Math.floor(centre);
982
- const span2 = rowSpansByRole.find((s) => s.role === iris.role);
983
- if (span2.rowRight[r] < span2.rowLeft[r]) return void 0;
984
- const minRun = STRAND_MIN_RUN_FRACTION * (span2.rowRight[r] + 1 - span2.rowLeft[r]);
985
- const strand = new Uint8Array(canvasW);
986
- for (let a = 0; a < canvasW; ) {
987
- if (mask[r * canvasW + a] !== 1) {
988
- a++;
989
- continue;
990
- }
991
- let b = a;
992
- while (b < canvasW && mask[r * canvasW + b] === 1) b++;
993
- if (b - a >= minRun) strand.fill(1, a, b);
994
- a = b;
995
- }
996
- const strandAt = (x2) => x2 >= 0 && x2 < canvasW && strand[x2] === 1;
997
- const outerBoundary = (x2) => (side < 0 ? x2 : x2 + 1) - half;
998
- let x = c;
999
- let runFace;
1000
- if (!strandAt(c)) {
1001
- while (x >= 0 && x < canvasW && !strandAt(x)) x += side;
1002
- if (x < 0 || x >= canvasW) return void 0;
1003
- runFace = outerBoundary(x - side);
1004
- } else {
1005
- let f = c - side;
1006
- while (strandAt(f)) f -= side;
1007
- const face = outerBoundary(f);
1008
- runFace = side * (face - otherX) > 0 ? face : null;
1009
- }
1010
- while (strandAt(x)) x += side;
1011
- return {
1012
- y: canvasH / 2 - (r + 0.5),
1013
- irisOuter: (side < 0 ? span2.rowLeft[r] : span2.rowRight[r] + 1) - half,
1014
- irisInner: (side < 0 ? span2.rowRight[r] + 1 : span2.rowLeft[r]) - half,
1015
- runOuter: outerBoundary(x - side),
1016
- runFace
1017
- };
1018
- };
1019
- const [low, high] = irisLayers;
1020
- const left = strandOn(low, high, -1);
1021
- const right = strandOn(high, low, 1);
1022
- if (left !== void 0 || right !== void 0) {
1023
- strandEdges = {
1024
- ...left === void 0 ? {} : { left },
1025
- ...right === void 0 ? {} : { right }
1026
- };
1027
- }
1028
- }
1029
- let turn;
1030
- let model;
1031
- try {
1032
- const { eyeShift, farEyeRatio, silhouetteRatio, noseShift, mouthShift } = input.turnTargets ?? {};
1033
- model = (0, import_editor2.generateIkiFromLayerSet)(
1034
- layerInputs,
1035
- { width: canvasW, height: canvasH },
1036
- {
1037
- turnTargets: {
1038
- eyeShift,
1039
- farEyeRatio,
1040
- silhouetteRatio,
1041
- noseShift,
1042
- mouthShift,
1043
- ...headHalfWidthApplied ? { headHalfWidth } : {}
1044
- },
1045
- onTurnSolved: (report) => {
1046
- turn = report;
1047
- },
1048
- ...headEdges === void 0 ? {} : { headEdges },
1049
- ...strandEdges === void 0 ? {} : { strandEdges }
1050
- }
881
+ `front and turned images are not at the same scale: mean iris height ${frontIrisH.toFixed(1)}px front vs ${turnedIrisH.toFixed(1)}px turned, more than ${(IRIS_HEIGHT_SCALE_TOLERANCE * 100).toFixed(0)}% apart \u2014 a yaw does not change iris height, so the pair must share the same framing and head size`
1051
882
  );
1052
- } catch (e) {
1053
- if (!(e instanceof import_editor2.TurnTargetError)) throw e;
1054
- throw new AutoRigInputError(e.message);
1055
883
  }
1056
- const doc = new import_editor2.EditorDocument(model);
1057
- const losslessCrop = quantizeColors === void 0 ? void 0 : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);
1058
- const pages = losslessCrop === void 0 ? [await renderAtlasPage(crops, quantizeColors)] : [
1059
- await renderAtlasPage(
1060
- crops.filter((c) => c !== losslessCrop),
1061
- quantizeColors
1062
- ),
1063
- await renderAtlasPage([losslessCrop], void 0)
884
+ const frontShift = front.pairCx - front.head.cx;
885
+ const turnedShift = turned.pairCx - turned.head.cx;
886
+ const shift = turnedShift - frontShift;
887
+ const turnSign = shift < 0 ? -1 : 1;
888
+ const f = farNearWidths(front, turnSign);
889
+ const t = farNearWidths(turned, turnSign);
890
+ const debug = debugDir === null ? void 0 : [
891
+ await writeOverlay(debugDir, "front", front),
892
+ await writeOverlay(debugDir, "turned", turned)
1064
893
  ];
1065
- const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);
1066
- if (atlasBytes > MAX_OUTPUT_BYTES) {
1067
- throw new AutoRigInputError(
1068
- `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`
1069
- );
1070
- }
1071
- const partTextureAssignments = pages.flatMap(
1072
- ({ crops: pageCrops, layout }) => pageCrops.map((crop) => {
1073
- const placement2 = layout.placements.find((p) => p.id === crop.id);
1074
- if (placement2 === void 0) {
1075
- throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
1076
- }
1077
- return {
1078
- partId: crop.id,
1079
- uv: (0, import_editor2.uvRectFor)(placement2, {
1080
- width: layout.pageWidth,
1081
- height: layout.pageHeight
1082
- })
1083
- };
1084
- })
1085
- );
1086
- doc.applyAtlas({
1087
- textures: [{ source: pages[0].dataUri }],
1088
- partTextureAssignments
1089
- });
1090
- let patched = doc.getModel();
1091
- if (losslessCrop !== void 0) {
1092
- patched = structuredClone(patched);
1093
- patched.textures = pages.map((p) => ({ source: p.dataUri }));
1094
- patched.parts.find((p) => p.id === losslessCrop.id).texture.index = 1;
1095
- }
1096
- const finalModel = (0, import_format.parseIkiModel)(patched);
1097
- writeFileAtomic(outPath, JSON.stringify(finalModel));
1098
894
  return {
1099
895
  ok: true,
1100
- path: outPath,
1101
- canvas: { width: canvasW, height: canvasH },
1102
- partCount: finalModel.parts.length,
1103
- atlasBytes,
1104
- ...headHalfWidth === void 0 ? {} : { headHalfWidth },
1105
- headHalfWidthApplied,
1106
- ...headEdges === void 0 ? {} : { headEdges },
1107
- ...strandEdges === void 0 ? {} : { strandEdges },
1108
- ...noseCore === void 0 ? {} : { noseCore },
1109
- ...turn === void 0 ? {} : { turn }
896
+ front,
897
+ turned,
898
+ farEyeRatio: t.far / t.near / (f.far / f.near),
899
+ eyeShift: shift / front.head.half,
900
+ silhouetteRatio: turned.head.half / front.head.half,
901
+ turnSign,
902
+ ...debug === void 0 ? {} : { debug }
1110
903
  };
1111
904
  } catch (err) {
1112
905
  if (err instanceof AutoRigInputError)
@@ -1114,15 +907,36 @@ async function autoRigFromLayers(input) {
1114
907
  throw err;
1115
908
  }
1116
909
  }
1117
-
1118
- // src/compose.ts
1119
- var import_node_fs3 = __toESM(require("fs"));
1120
- var import_node_path5 = __toESM(require("path"));
1121
- var import_sharp2 = __toESM(require("sharp"));
910
+ var n1 = (v) => v.toFixed(1);
911
+ var n3 = (v) => v.toFixed(3);
912
+ function imageBlock(label, m) {
913
+ return [
914
+ `# ${label} ${m.file} ${m.width}x${m.height} mask: ${m.maskMode}`,
915
+ `iris widths ${m.irisL.w} / ${m.irisR.w} px centres ${n1(m.irisL.cx)} / ${n1(m.irisR.cx)} eye row ${m.eyeRow} gap ${n1(m.eyeGap)}`,
916
+ `head ${m.head.left}..${m.head.right} centre ${n1(m.head.cx)} half ${n1(m.head.half)} pair centre ${n1(m.pairCx)}`
917
+ ];
918
+ }
919
+ function formatTurnReport(result) {
920
+ const { front, turned } = result;
921
+ const f = farNearWidths(front, result.turnSign);
922
+ const t = farNearWidths(turned, result.turnSign);
923
+ const lines = [
924
+ `farEyeRatio ${n3(result.farEyeRatio)} far/near iris width ${t.far}/${t.near} turned over ${f.far}/${f.near} front`,
925
+ `eyeShift ${n3(result.eyeShift)} pair-vs-head centre ${n1(turned.pairCx - turned.head.cx)} px turned, ${n1(front.pairCx - front.head.cx)} px front, over front head half ${n1(front.head.half)} px (hh)`,
926
+ `silhouetteRatio ${n3(result.silhouetteRatio)} head half ${n1(turned.head.half)} px turned over ${n1(front.head.half)} px front`,
927
+ `turnSign ${result.turnSign} (the head turned toward the image's ${result.turnSign < 0 ? "left" : "right"})`,
928
+ "",
929
+ ...imageBlock("front", front),
930
+ "",
931
+ ...imageBlock("turned", turned)
932
+ ];
933
+ if (result.debug !== void 0) {
934
+ lines.push("", ...result.debug.map((p) => `debug overlay ${p}`));
935
+ }
936
+ return lines.join("\n");
937
+ }
1122
938
 
1123
939
  // src/measure.ts
1124
- var import_node_fs2 = __toESM(require("fs"));
1125
- var import_node_path4 = __toESM(require("path"));
1126
940
  var IRIS_RATIO_MIN = 0.45;
1127
941
  var IRIS_RATIO_MAX = 0.72;
1128
942
  var EYE_ASPECT_MIN = 0.5;
@@ -1219,7 +1033,7 @@ function noseSpeckWarning({ core, part }, source) {
1219
1033
  `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,
1220
1034
  `auto_rig_from_layers turns and tilts the nose about its whole crop instead`
1221
1035
  ];
1222
- return `nose: ${found} \u2014 under ${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.`;
1036
+ return `nose: ${found} \u2014 under ${import_editor4.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.`;
1223
1037
  }
1224
1038
  async function lashOffSclera(eyePath, lashPath) {
1225
1039
  const eye = await decodePng(eyePath);
@@ -1346,10 +1160,10 @@ async function measureDir(absDir, noseSpeck) {
1346
1160
  warnings.push(noseSpeckWarning(noseSpeck, "compose"));
1347
1161
  } else if (layers.nose !== void 0) {
1348
1162
  const nose = await decodePng(import_node_path4.default.join(absDir, "nose.png"));
1349
- const core = denseCoreOf(nose.rgba, nose.width, nose.height);
1163
+ const core = (0, import_editor4.denseCoreOf)(nose.rgba, nose.width, nose.height);
1350
1164
  if (core !== null) {
1351
1165
  const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);
1352
- if (isSpeckCore(core, crop))
1166
+ if ((0, import_editor4.isSpeckCore)(core, crop))
1353
1167
  warnings.push(noseSpeckWarning({ core, part: crop }, "layer"));
1354
1168
  }
1355
1169
  }
@@ -1551,14 +1365,14 @@ function keyWhiteToAlpha(rgba) {
1551
1365
  async function coreAndBoundsOf(png) {
1552
1366
  const { data, info } = await (0, import_sharp2.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1553
1367
  return {
1554
- core: denseCoreOf(data, info.width, info.height),
1368
+ core: (0, import_editor4.denseCoreOf)(data, info.width, info.height),
1555
1369
  bounds: { x: 0, y: 0, w: info.width, h: info.height }
1556
1370
  };
1557
1371
  }
1558
1372
  async function noseSizingOf(png) {
1559
1373
  const { core, bounds } = await coreAndBoundsOf(png);
1560
1374
  if (core === null) return { box: bounds, whole: true };
1561
- if (isSpeckCore(core, bounds)) {
1375
+ if ((0, import_editor4.isSpeckCore)(core, bounds)) {
1562
1376
  return {
1563
1377
  box: bounds,
1564
1378
  whole: true,
@@ -1803,7 +1617,7 @@ async function composeLayersFromParts(input) {
1803
1617
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
1804
1618
  var import_zod = require("zod");
1805
1619
  function createIkiMcpServer() {
1806
- const server = new import_mcp.McpServer({ name: "iki", version: "0.11.1" });
1620
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.11.3" });
1807
1621
  server.registerTool(
1808
1622
  "validate_iki",
1809
1623
  {