@ikijs/mcp 0.11.2 → 0.12.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
@@ -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,8 +247,354 @@ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
247
247
  return `data:image/png;base64,${page.toString("base64")}`;
248
248
  }
249
249
 
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;
258
+ }
259
+ }
260
+ function validateIki(model) {
261
+ const result = coerceModel(model);
262
+ if (!result.ok) return { ok: false, error: result.error };
263
+ return { ok: true };
264
+ }
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
+ };
302
+ }
303
+ }
304
+ return entry;
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."
380
+ }
381
+ ];
382
+ function listStandardParameters() {
383
+ return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));
384
+ }
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
+ );
392
+ }
393
+ }
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 };
406
+ }
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 turnTargets = input.turnTargets;
428
+ if (turnTargets !== void 0) {
429
+ if (typeof turnTargets !== "object" || turnTargets === null || Array.isArray(turnTargets)) {
430
+ throw new AutoRigInputError("turnTargets must be a plain object");
431
+ }
432
+ if (turnTargets.headHalfWidth !== void 0) {
433
+ throw new AutoRigInputError(
434
+ "turnTargets.headHalfWidth is measured off the layers, not accepted as input"
435
+ );
436
+ }
437
+ }
438
+ const resolvedLayers = layers.map((layer) => {
439
+ const resolved = resolveInputPath(layer.path);
440
+ return { resolved, fileName: layer.fileName ?? import_node_path2.default.basename(resolved) };
441
+ });
442
+ const rolePairs = expectInput(
443
+ "role parsing",
444
+ () => (0, import_editor2.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
445
+ );
446
+ const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));
447
+ let canvasW = 0;
448
+ let canvasH = 0;
449
+ let totalPixels = 0;
450
+ let measurer;
451
+ const crops = [];
452
+ for (let i = 0; i < resolvedLayers.length; i++) {
453
+ const { resolved, fileName } = resolvedLayers[i];
454
+ const png = await decodePng(resolved);
455
+ if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {
456
+ throw new AutoRigInputError(
457
+ `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`
458
+ );
459
+ }
460
+ totalPixels += png.width * png.height;
461
+ if (totalPixels > MAX_TOTAL_PIXELS) {
462
+ throw new AutoRigInputError(
463
+ `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`
464
+ );
465
+ }
466
+ if (i === 0) {
467
+ canvasW = png.width;
468
+ canvasH = png.height;
469
+ if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {
470
+ throw new AutoRigInputError(
471
+ `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`
472
+ );
473
+ }
474
+ measurer = (0, import_editor2.createLayerSetMeasurer)({ width: canvasW, height: canvasH });
475
+ } else if (png.width !== canvasW || png.height !== canvasH) {
476
+ throw new AutoRigInputError(
477
+ `layer "${fileName}" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
478
+ );
479
+ }
480
+ const role = roleByFileName.get(fileName);
481
+ if (role === void 0) {
482
+ throw new AutoRigInputError(`no role resolved for "${fileName}"`);
483
+ }
484
+ const layer = measurer.add({ role, fileName, rgba: png.rgba });
485
+ if (layer === null) {
486
+ throw new AutoRigInputError(
487
+ `role "${role}" file "${fileName}": layer is empty after alpha threshold`
488
+ );
489
+ }
490
+ const { bbox } = layer;
491
+ const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);
492
+ crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
493
+ }
494
+ const measurement = measurer.finish();
495
+ const { headHalfWidth, headHalfWidthApplied, turnOptions } = measurement;
496
+ const { headEdges, strandEdges } = turnOptions;
497
+ const noseCore = measurement.layers.find(
498
+ (l) => l.role === "nose"
499
+ )?.denseCore;
500
+ let turn;
501
+ let model;
502
+ try {
503
+ model = (0, import_editor2.generateIkiFromLayerSet)(
504
+ measurement.layers,
505
+ { width: canvasW, height: canvasH },
506
+ {
507
+ turnTargets: {
508
+ ...input.turnTargets,
509
+ ...turnOptions.turnTargets
510
+ },
511
+ onTurnSolved: (report) => {
512
+ turn = report;
513
+ },
514
+ ...input.style === void 0 ? {} : { style: input.style },
515
+ ...headEdges === void 0 ? {} : { headEdges },
516
+ ...strandEdges === void 0 ? {} : { strandEdges }
517
+ }
518
+ );
519
+ } catch (e) {
520
+ if (!(e instanceof import_editor2.TurnTargetError)) throw e;
521
+ throw new AutoRigInputError(e.message);
522
+ }
523
+ const doc = new import_editor2.EditorDocument(model);
524
+ const losslessCrop = quantizeColors === void 0 ? void 0 : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);
525
+ const pages = losslessCrop === void 0 ? [await renderAtlasPage(crops, quantizeColors)] : [
526
+ await renderAtlasPage(
527
+ crops.filter((c) => c !== losslessCrop),
528
+ quantizeColors
529
+ ),
530
+ await renderAtlasPage([losslessCrop], void 0)
531
+ ];
532
+ const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);
533
+ if (atlasBytes > MAX_OUTPUT_BYTES) {
534
+ throw new AutoRigInputError(
535
+ `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`
536
+ );
537
+ }
538
+ const partTextureAssignments = pages.flatMap(
539
+ ({ crops: pageCrops, layout }) => pageCrops.map((crop) => {
540
+ const placement2 = layout.placements.find((p) => p.id === crop.id);
541
+ if (placement2 === void 0) {
542
+ throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
543
+ }
544
+ return {
545
+ partId: crop.id,
546
+ uv: (0, import_editor2.uvRectFor)(placement2, {
547
+ width: layout.pageWidth,
548
+ height: layout.pageHeight
549
+ })
550
+ };
551
+ })
552
+ );
553
+ doc.applyAtlas({
554
+ textures: [{ source: pages[0].dataUri }],
555
+ partTextureAssignments
556
+ });
557
+ let patched = doc.getModel();
558
+ if (losslessCrop !== void 0) {
559
+ patched = structuredClone(patched);
560
+ patched.textures = pages.map((p) => ({ source: p.dataUri }));
561
+ patched.parts.find((p) => p.id === losslessCrop.id).texture.index = 1;
562
+ }
563
+ const finalModel = (0, import_format.parseIkiModel)(patched);
564
+ writeFileAtomic(outPath, JSON.stringify(finalModel));
565
+ return {
566
+ ok: true,
567
+ path: outPath,
568
+ canvas: { width: canvasW, height: canvasH },
569
+ partCount: finalModel.parts.length,
570
+ atlasBytes,
571
+ ...headHalfWidth === void 0 ? {} : { headHalfWidth },
572
+ headHalfWidthApplied,
573
+ ...headEdges === void 0 ? {} : { headEdges },
574
+ ...strandEdges === void 0 ? {} : { strandEdges },
575
+ ...noseCore === void 0 ? {} : { noseCore },
576
+ ...turn === void 0 ? {} : { turn }
577
+ };
578
+ } catch (err) {
579
+ if (err instanceof AutoRigInputError)
580
+ return { ok: false, error: err.message };
581
+ throw err;
582
+ }
583
+ }
584
+
585
+ // src/compose.ts
586
+ var import_node_fs3 = __toESM(require("fs"));
587
+ var import_node_path5 = __toESM(require("path"));
588
+ var import_sharp2 = __toESM(require("sharp"));
589
+
590
+ // src/measure.ts
591
+ var import_node_fs2 = __toESM(require("fs"));
592
+ var import_node_path4 = __toESM(require("path"));
593
+
250
594
  // src/measure-turn.ts
251
- var import_node_path2 = __toESM(require("path"));
595
+ var import_node_path3 = __toESM(require("path"));
596
+ var import_editor3 = require("@ikijs/editor");
597
+ var import_editor4 = require("@ikijs/editor");
252
598
  var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
253
599
  var IRIS_V_MIN = 0.18;
254
600
  var IRIS_V_MAX = 0.95;
@@ -263,35 +609,11 @@ var PAIR_DX_MIN_FRAC = 0.08;
263
609
  var PAIR_DX_MAX_FRAC = 0.35;
264
610
  var PAIR_DY_MAX_FRAC = 0.05;
265
611
  var MAX_CANDIDATES = 12;
266
- var HEAD_BAND = 10;
267
- var ALPHA_OPAQUE = 128;
268
612
  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
- }
287
- }
288
- if (maxX < 0) return null;
289
- return { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 };
290
- }
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
- }
613
+ var BG_HUE_MAX = 260;
614
+ var BG_SAT_MAX = 0.2;
615
+ var BG_V_MIN = 0.55;
616
+ var BG_V_BLACK = 0.03;
295
617
  function rgbToHsv(r, g, b) {
296
618
  r /= 255;
297
619
  g /= 255;
@@ -402,21 +724,6 @@ function components(mask, width, height, minArea) {
402
724
  }
403
725
  return out.sort((a, b) => b.area - a.area);
404
726
  }
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
727
  function resolveIris(override) {
421
728
  const iris = { ...DEFAULT_IRIS, ...override };
422
729
  if (iris.hueMin < 0 || iris.hueMax > 360 || iris.hueMin >= iris.hueMax) {
@@ -437,7 +744,7 @@ async function measureTurnImage(filePath, iris) {
437
744
  let transparent = false;
438
745
  if (hasAlpha) {
439
746
  for (let i = 0; i < n; i++) {
440
- if (rgba[i * 4 + 3] < ALPHA_OPAQUE) {
747
+ if (rgba[i * 4 + 3] < import_editor3.ALPHA_OPAQUE) {
441
748
  transparent = true;
442
749
  break;
443
750
  }
@@ -448,7 +755,7 @@ async function measureTurnImage(filePath, iris) {
448
755
  const fg = new Uint8Array(n);
449
756
  const value = new Float32Array(n);
450
757
  for (let i = 0; i < n; i++) {
451
- if (rgba[i * 4 + 3] < ALPHA_OPAQUE) continue;
758
+ if (rgba[i * 4 + 3] < import_editor3.ALPHA_OPAQUE) continue;
452
759
  const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);
453
760
  if (maskMode === "alpha") {
454
761
  fg[i] = 1;
@@ -514,12 +821,12 @@ async function measureTurnImage(filePath, iris) {
514
821
  }
515
822
  const [irisL, irisR] = best.pair;
516
823
  const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);
517
- const { left, right } = foregroundSpan(
824
+ const { left, right } = (0, import_editor3.foregroundSpan)(
518
825
  fg,
519
826
  width,
520
827
  height,
521
- eyeRow - HEAD_BAND,
522
- eyeRow + HEAD_BAND
828
+ eyeRow - import_editor3.HEAD_BAND,
829
+ eyeRow + import_editor3.HEAD_BAND
523
830
  );
524
831
  if (right <= left) {
525
832
  throw new AutoRigInputError(
@@ -532,581 +839,74 @@ async function measureTurnImage(filePath, iris) {
532
839
  );
533
840
  }
534
841
  return {
535
- file: filePath,
536
- width,
537
- height,
538
- maskMode,
539
- 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;
842
+ file: filePath,
843
+ width,
844
+ height,
845
+ maskMode,
846
+ irisL,
847
+ irisR,
848
+ eyeRow,
849
+ head: {
850
+ left,
851
+ right,
852
+ cx: (left + right) / 2,
853
+ half: (0, import_editor3.headHalfOf)({ left, right })
854
+ },
855
+ pairCx: (irisL.cx + irisR.cx) / 2,
856
+ eyeGap: irisR.cx - irisL.cx
792
857
  };
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
858
  }
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 };
859
+ function farNearWidths(m, turnSign) {
860
+ return turnSign < 0 ? { far: m.irisL.w, near: m.irisR.w } : { far: m.irisR.w, near: m.irisL.w };
807
861
  }
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;
862
+ function overlaySvg(m) {
863
+ const box = (b, stroke) => `<rect x="${b.x0}" y="${b.y0}" width="${b.w}" height="${b.h}" fill="none" stroke="${stroke}" stroke-width="3"/>`;
864
+ const tick = (x, half, stroke) => `<line x1="${x}" y1="${m.eyeRow - half}" x2="${x}" y2="${m.eyeRow + half}" stroke="${stroke}" stroke-width="3"/>`;
865
+ 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
866
  }
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 }))
867
+ async function writeOverlay(debugDir, label, m) {
868
+ const outPath = import_node_path3.default.join(
869
+ debugDir,
870
+ `${label}-${import_node_path3.default.basename(m.file, ".png")}.debug.png`
820
871
  );
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 };
872
+ writeFileAtomic(outPath, await encodeOverlayPng(m.file, overlaySvg(m)));
873
+ return outPath;
828
874
  }
829
- async function autoRigFromLayers(input) {
875
+ var IRIS_HEIGHT_SCALE_TOLERANCE = 0.1;
876
+ async function measureTurnReference(input) {
830
877
  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)) {
878
+ const iris = resolveIris(input.iris);
879
+ const frontPath = resolveInputPath(input.front);
880
+ const turnedPath = resolveInputPath(input.turned);
881
+ const debugDir = input.debugDir === void 0 ? null : resolveOutputDir(input.debugDir);
882
+ const front = await measureTurnImage(frontPath, iris);
883
+ const turned = await measureTurnImage(turnedPath, iris);
884
+ const frontIrisH = (front.irisL.h + front.irisR.h) / 2;
885
+ const turnedIrisH = (turned.irisL.h + turned.irisR.h) / 2;
886
+ if (Math.abs(turnedIrisH - frontIrisH) / frontIrisH > IRIS_HEIGHT_SCALE_TOLERANCE) {
845
887
  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
- }
888
+ `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
889
  );
1052
- } catch (e) {
1053
- if (!(e instanceof import_editor2.TurnTargetError)) throw e;
1054
- throw new AutoRigInputError(e.message);
1055
890
  }
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)
891
+ const frontShift = front.pairCx - front.head.cx;
892
+ const turnedShift = turned.pairCx - turned.head.cx;
893
+ const shift = turnedShift - frontShift;
894
+ const turnSign = shift < 0 ? -1 : 1;
895
+ const f = farNearWidths(front, turnSign);
896
+ const t = farNearWidths(turned, turnSign);
897
+ const debug = debugDir === null ? void 0 : [
898
+ await writeOverlay(debugDir, "front", front),
899
+ await writeOverlay(debugDir, "turned", turned)
1064
900
  ];
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
901
  return {
1099
902
  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 }
903
+ front,
904
+ turned,
905
+ farEyeRatio: t.far / t.near / (f.far / f.near),
906
+ eyeShift: shift / front.head.half,
907
+ silhouetteRatio: turned.head.half / front.head.half,
908
+ turnSign,
909
+ ...debug === void 0 ? {} : { debug }
1110
910
  };
1111
911
  } catch (err) {
1112
912
  if (err instanceof AutoRigInputError)
@@ -1114,15 +914,36 @@ async function autoRigFromLayers(input) {
1114
914
  throw err;
1115
915
  }
1116
916
  }
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"));
917
+ var n1 = (v) => v.toFixed(1);
918
+ var n3 = (v) => v.toFixed(3);
919
+ function imageBlock(label, m) {
920
+ return [
921
+ `# ${label} ${m.file} ${m.width}x${m.height} mask: ${m.maskMode}`,
922
+ `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)}`,
923
+ `head ${m.head.left}..${m.head.right} centre ${n1(m.head.cx)} half ${n1(m.head.half)} pair centre ${n1(m.pairCx)}`
924
+ ];
925
+ }
926
+ function formatTurnReport(result) {
927
+ const { front, turned } = result;
928
+ const f = farNearWidths(front, result.turnSign);
929
+ const t = farNearWidths(turned, result.turnSign);
930
+ const lines = [
931
+ `farEyeRatio ${n3(result.farEyeRatio)} far/near iris width ${t.far}/${t.near} turned over ${f.far}/${f.near} front`,
932
+ `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)`,
933
+ `silhouetteRatio ${n3(result.silhouetteRatio)} head half ${n1(turned.head.half)} px turned over ${n1(front.head.half)} px front`,
934
+ `turnSign ${result.turnSign} (the head turned toward the image's ${result.turnSign < 0 ? "left" : "right"})`,
935
+ "",
936
+ ...imageBlock("front", front),
937
+ "",
938
+ ...imageBlock("turned", turned)
939
+ ];
940
+ if (result.debug !== void 0) {
941
+ lines.push("", ...result.debug.map((p) => `debug overlay ${p}`));
942
+ }
943
+ return lines.join("\n");
944
+ }
1122
945
 
1123
946
  // src/measure.ts
1124
- var import_node_fs2 = __toESM(require("fs"));
1125
- var import_node_path4 = __toESM(require("path"));
1126
947
  var IRIS_RATIO_MIN = 0.45;
1127
948
  var IRIS_RATIO_MAX = 0.72;
1128
949
  var EYE_ASPECT_MIN = 0.5;
@@ -1219,7 +1040,7 @@ function noseSpeckWarning({ core, part }, source) {
1219
1040
  `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,
1220
1041
  `auto_rig_from_layers turns and tilts the nose about its whole crop instead`
1221
1042
  ];
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.`;
1043
+ 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
1044
  }
1224
1045
  async function lashOffSclera(eyePath, lashPath) {
1225
1046
  const eye = await decodePng(eyePath);
@@ -1346,10 +1167,10 @@ async function measureDir(absDir, noseSpeck) {
1346
1167
  warnings.push(noseSpeckWarning(noseSpeck, "compose"));
1347
1168
  } else if (layers.nose !== void 0) {
1348
1169
  const nose = await decodePng(import_node_path4.default.join(absDir, "nose.png"));
1349
- const core = denseCoreOf(nose.rgba, nose.width, nose.height);
1170
+ const core = (0, import_editor4.denseCoreOf)(nose.rgba, nose.width, nose.height);
1350
1171
  if (core !== null) {
1351
1172
  const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);
1352
- if (isSpeckCore(core, crop))
1173
+ if ((0, import_editor4.isSpeckCore)(core, crop))
1353
1174
  warnings.push(noseSpeckWarning({ core, part: crop }, "layer"));
1354
1175
  }
1355
1176
  }
@@ -1418,9 +1239,8 @@ var DEFAULT_LAYOUT = {
1418
1239
  // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir
1419
1240
  // without them still composes (head-only character).
1420
1241
  hair_back: { src: "hair_back.png", cx: 550, cy: 523, w: 800, optional: true },
1421
- // The torso, cut off by the canvas bottom. It rides its own `bodyDeformer`: a
1422
- // light share of the head turn and half its breath bob, so the character is
1423
- // not a floating head.
1242
+ // The torso, cut off by the canvas bottom, so the character is not a
1243
+ // floating head. It rides its own `bodyDeformer`, which only breathes.
1424
1244
  body: { src: "body.png", cx: 550, cy: 1017, w: 840, optional: true },
1425
1245
  face: { src: "face.png", cx: 550, cy: 475, w: 400 },
1426
1246
  // The nose, drawn on its own (the face is drawn without one): the auto-rig
@@ -1551,14 +1371,14 @@ function keyWhiteToAlpha(rgba) {
1551
1371
  async function coreAndBoundsOf(png) {
1552
1372
  const { data, info } = await (0, import_sharp2.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1553
1373
  return {
1554
- core: denseCoreOf(data, info.width, info.height),
1374
+ core: (0, import_editor4.denseCoreOf)(data, info.width, info.height),
1555
1375
  bounds: { x: 0, y: 0, w: info.width, h: info.height }
1556
1376
  };
1557
1377
  }
1558
1378
  async function noseSizingOf(png) {
1559
1379
  const { core, bounds } = await coreAndBoundsOf(png);
1560
1380
  if (core === null) return { box: bounds, whole: true };
1561
- if (isSpeckCore(core, bounds)) {
1381
+ if ((0, import_editor4.isSpeckCore)(core, bounds)) {
1562
1382
  return {
1563
1383
  box: bounds,
1564
1384
  whole: true,
@@ -1803,7 +1623,7 @@ async function composeLayersFromParts(input) {
1803
1623
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
1804
1624
  var import_zod = require("zod");
1805
1625
  function createIkiMcpServer() {
1806
- const server = new import_mcp.McpServer({ name: "iki", version: "0.11.2" });
1626
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.12.0" });
1807
1627
  server.registerTool(
1808
1628
  "validate_iki",
1809
1629
  {
@@ -1890,8 +1710,18 @@ function createIkiMcpServer() {
1890
1710
  silhouetteRatio: import_zod.z.number().optional(),
1891
1711
  noseShift: import_zod.z.number().optional(),
1892
1712
  mouthShift: import_zod.z.number().optional()
1893
- }).optional().describe(
1894
- "What the head turn is fitted to, as `measure_turn_reference` reports it off a front/turned reference pair. `eyeShift` (and the optional `noseShift`/`mouthShift`, derived from it when absent) is how far that feature slides across the head at full turn, as a fraction of the head's half-width \u2014 a MAGNITUDE: the rig turns both ways, so the sign is ignored. `farEyeRatio` is the far/near eye width at full turn over that same ratio at rest, `silhouetteRatio` the head's half-width turned over at rest. The half-width the shifts are fractions of is measured off the layers themselves, so it is not an input. An omitted field falls back to a default, which is clamped to what this layer set can do, and so is a passed `eyeShift` past the room the art leaves the far eye \u2014 the face plate's edge, or the bangs' side strand over the far iris (the result's `turn.clamped` lists every clamped field, `turn.achieved` what the rig reaches, and `turn.strandOverlap` how much of a far iris the bangs still cover). Any other passed target this layer set cannot reach, including an `eyeShift` smaller than the slide the face's own turn already gives the eyes, comes back as `INVALID: \u2026` naming the field and the attainable range, since it is a measurement rather than a preference \u2014 except a passed `silhouetteRatio` when no ratio in its whole accepted range renders on this layer set: that refusal reads `\u2026 is unreachable for this layer set, and so is every silhouetteRatio in [0.5, 1.5]` and names no range, so leave the field out, since a defaulted one clamps."
1713
+ }).passthrough().optional().describe(
1714
+ "What the head turn is fitted to, as `measure_turn_reference` reports it off a front/turned reference pair. `eyeShift` (and the optional `noseShift`/`mouthShift`) is how far that feature slides across the head at full turn, as a fraction of the head's half-width \u2014 a MAGNITUDE: the rig turns both ways, so the sign is ignored. `farEyeRatio` is the far/near eye width at full turn over that same ratio at rest, `silhouetteRatio` the head's half-width turned over at rest. The half-width the shifts are fractions of is measured off the layers themselves, so it is not an input. An omitted field leaves that part of the turn at the Live2D profile the rig defaults to. A passed `eyeShift` is fitted by the turn's amount and clamped to the room the art leaves the far eye \u2014 the face plate's edge, or the bangs' side strand over the far iris (the result's `turn.clamped` lists every clamped field, `turn.achieved` what the rig reaches, and `turn.strandOverlap` how much of a far iris the bangs still cover). Any other passed target this layer set cannot reach comes back as `INVALID: \u2026` naming the field and the attainable range, since it is a measurement rather than a preference. A field not named here is refused the same way."
1715
+ ),
1716
+ style: import_zod.z.object({
1717
+ turn: import_zod.z.number().optional(),
1718
+ featureLead: import_zod.z.number().optional(),
1719
+ hairFollow: import_zod.z.number().optional(),
1720
+ outlineFollow: import_zod.z.number().optional(),
1721
+ blink: import_zod.z.number().optional(),
1722
+ sway: import_zod.z.number().optional()
1723
+ }).passthrough().optional().describe(
1724
+ "Per-character tuning from the Live2D profile the rig defaults to \u2014 only what the Live2D samples themselves disagree on: `turn` scales the whole head turn (plate, features, hair and the eyes' foreshortening; 0..3, 1 = the profile; ignored when `turnTargets.eyeShift` is given), `featureLead` how far the features lead the face plate (0..3, 1 = the profile), `hairFollow` the front hair's share of the face's turn (0..2, profile 1.1), `outlineFollow` its outer edge's share where the front hair draws the head's outline (0..2, profile 0: the outline holds), `blink` how far the upper lid comes down over the eye's height (0.1..1, profile 0.58), `sway` the hair sway amplitude (0..5, 1 = the profile). A value out of range, or a knob not named here, comes back as `INVALID: \u2026`."
1895
1725
  )
1896
1726
  }
1897
1727
  },