@ikijs/mcp 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -28,7 +28,7 @@ var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
28
28
  var import_zod = require("zod");
29
29
 
30
30
  // src/tools.ts
31
- var import_node_path2 = __toESM(require("path"));
31
+ var import_node_path3 = __toESM(require("path"));
32
32
  var import_format = require("@ikijs/format");
33
33
  var import_editor2 = require("@ikijs/editor");
34
34
 
@@ -199,6 +199,9 @@ function detectAlphaBbox(rgba, width, height) {
199
199
  function cropToBuffer(rgba, width, height, bbox) {
200
200
  return (0, import_sharp.default)(rgba, { raw: { width, height, channels: 4 } }).extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h }).png().toBuffer();
201
201
  }
202
+ function encodeOverlayPng(filePath, svg) {
203
+ return (0, import_sharp.default)(filePath, { limitInputPixels: MAX_INPUT_PIXELS }).composite([{ input: Buffer.from(svg) }]).png().toBuffer();
204
+ }
202
205
  async function renderAtlasToDataUri(crops, layout, quantizeColors) {
203
206
  const byId = /* @__PURE__ */ new Map();
204
207
  for (const crop of crops) byId.set(crop.id, crop);
@@ -228,6 +231,373 @@ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
228
231
  return `data:image/png;base64,${page.toString("base64")}`;
229
232
  }
230
233
 
234
+ // src/measure-turn.ts
235
+ var import_node_path2 = __toESM(require("path"));
236
+ var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
237
+ var IRIS_V_MIN = 0.18;
238
+ var IRIS_V_MAX = 0.95;
239
+ var IRIS_MEAN_V_MIN = 0.32;
240
+ var CLOSE_RADIUS = 3;
241
+ var CLOSE_RADIUS_REFERENCE_PX = 1254;
242
+ var BLOB_MAX_FRAC = 0.12;
243
+ var KEYED_SPAN_MAX_FRAC = 0.95;
244
+ var MIN_AREA_REFERENCE_PIXELS = 1254 * 1254;
245
+ var MIN_AREA = 300;
246
+ var PAIR_DX_MIN_FRAC = 0.08;
247
+ var PAIR_DX_MAX_FRAC = 0.35;
248
+ var PAIR_DY_MAX_FRAC = 0.05;
249
+ var MAX_CANDIDATES = 12;
250
+ var HEAD_BAND = 10;
251
+ var ALPHA_OPAQUE = 128;
252
+ var BG_HUE_MIN = 220;
253
+ var BG_HUE_MAX = 260;
254
+ var BG_SAT_MAX = 0.2;
255
+ var BG_V_MIN = 0.55;
256
+ var BG_V_BLACK = 0.03;
257
+ function rgbToHsv(r, g, b) {
258
+ r /= 255;
259
+ g /= 255;
260
+ b /= 255;
261
+ const max = Math.max(r, g, b);
262
+ const min = Math.min(r, g, b);
263
+ const d = max - min;
264
+ let h = 0;
265
+ if (d > 0) {
266
+ if (max === r) h = (g - b) / d % 6;
267
+ else if (max === g) h = (b - r) / d + 2;
268
+ else h = (r - g) / d + 4;
269
+ h *= 60;
270
+ if (h < 0) h += 360;
271
+ }
272
+ return [h, max === 0 ? 0 : d / max, max];
273
+ }
274
+ function dilate(mask, width, height, r) {
275
+ const out = new Uint8Array(width * height);
276
+ for (let y = 0; y < height; y++) {
277
+ for (let x = 0; x < width; x++) {
278
+ if (!mask[y * width + x]) continue;
279
+ for (let dy = -r; dy <= r; dy++) {
280
+ for (let dx = -r; dx <= r; dx++) {
281
+ const yy = y + dy;
282
+ const xx = x + dx;
283
+ if (yy >= 0 && yy < height && xx >= 0 && xx < width)
284
+ out[yy * width + xx] = 1;
285
+ }
286
+ }
287
+ }
288
+ }
289
+ return out;
290
+ }
291
+ function erode(mask, width, height, r) {
292
+ const out = new Uint8Array(width * height);
293
+ for (let y = 0; y < height; y++) {
294
+ for (let x = 0; x < width; x++) {
295
+ if (!mask[y * width + x]) continue;
296
+ let keep = true;
297
+ for (let dy = -r; dy <= r && keep; dy++) {
298
+ for (let dx = -r; dx <= r; dx++) {
299
+ const yy = y + dy;
300
+ const xx = x + dx;
301
+ if (yy < 0 || yy >= height || xx < 0 || xx >= width || !mask[yy * width + xx]) {
302
+ keep = false;
303
+ break;
304
+ }
305
+ }
306
+ }
307
+ if (keep) out[y * width + x] = 1;
308
+ }
309
+ }
310
+ return out;
311
+ }
312
+ function closeMask(mask, width, height, r) {
313
+ return erode(dilate(mask, width, height, r), width, height, r);
314
+ }
315
+ function components(mask, width, height, minArea) {
316
+ const seen = new Uint8Array(width * height);
317
+ const out = [];
318
+ for (let i = 0; i < width * height; i++) {
319
+ if (!mask[i] || seen[i]) continue;
320
+ const stack = [i];
321
+ seen[i] = 1;
322
+ let x0 = width;
323
+ let x1 = 0;
324
+ let y0 = height;
325
+ let y1 = 0;
326
+ let n = 0;
327
+ let sx = 0;
328
+ let sy = 0;
329
+ while (stack.length) {
330
+ const p = stack.pop();
331
+ const x = p % width;
332
+ const y = p / width | 0;
333
+ n++;
334
+ sx += x;
335
+ sy += y;
336
+ if (x < x0) x0 = x;
337
+ if (x > x1) x1 = x;
338
+ if (y < y0) y0 = y;
339
+ if (y > y1) y1 = y;
340
+ const neighbours = [];
341
+ if (x > 0) neighbours.push(p - 1);
342
+ if (x < width - 1) neighbours.push(p + 1);
343
+ if (y > 0) neighbours.push(p - width);
344
+ if (y < height - 1) neighbours.push(p + width);
345
+ for (const q of neighbours) {
346
+ if (seen[q] || !mask[q]) continue;
347
+ seen[q] = 1;
348
+ stack.push(q);
349
+ }
350
+ }
351
+ if (n >= minArea) {
352
+ out.push({
353
+ x0,
354
+ x1,
355
+ y0,
356
+ y1,
357
+ w: x1 - x0 + 1,
358
+ h: y1 - y0 + 1,
359
+ area: n,
360
+ cx: sx / n,
361
+ cy: sy / n
362
+ });
363
+ }
364
+ }
365
+ return out.sort((a, b) => b.area - a.area);
366
+ }
367
+ function foregroundSpan(mask, width, height, rowLo, rowHi) {
368
+ let left = width;
369
+ let right = -1;
370
+ for (let y = Math.max(0, rowLo); y <= Math.min(height - 1, rowHi); y++) {
371
+ for (let x = 0; x < width; x++) {
372
+ if (!mask[y * width + x]) continue;
373
+ if (x < left) left = x;
374
+ if (x > right) right = x;
375
+ }
376
+ }
377
+ return { left, right };
378
+ }
379
+ function headHalfOf(span) {
380
+ return (span.right - span.left + 1) / 2;
381
+ }
382
+ function resolveIris(override) {
383
+ const iris = { ...DEFAULT_IRIS, ...override };
384
+ if (iris.hueMin < 0 || iris.hueMax > 360 || iris.hueMin >= iris.hueMax) {
385
+ throw new AutoRigInputError(
386
+ `iris hue window must be 0 <= hueMin < hueMax <= 360, got ${iris.hueMin}..${iris.hueMax}`
387
+ );
388
+ }
389
+ if (iris.satMin < 0 || iris.satMin > 1) {
390
+ throw new AutoRigInputError(
391
+ `iris satMin must be within 0..1, got ${iris.satMin}`
392
+ );
393
+ }
394
+ return iris;
395
+ }
396
+ async function measureTurnImage(filePath, iris) {
397
+ const { width, height, rgba, hasAlpha } = await decodePng(filePath);
398
+ const n = width * height;
399
+ let transparent = false;
400
+ if (hasAlpha) {
401
+ for (let i = 0; i < n; i++) {
402
+ if (rgba[i * 4 + 3] < ALPHA_OPAQUE) {
403
+ transparent = true;
404
+ break;
405
+ }
406
+ }
407
+ }
408
+ const maskMode = hasAlpha && transparent ? "alpha" : "keyed";
409
+ const irisMask = new Uint8Array(n);
410
+ const fg = new Uint8Array(n);
411
+ const value = new Float32Array(n);
412
+ for (let i = 0; i < n; i++) {
413
+ if (rgba[i * 4 + 3] < ALPHA_OPAQUE) continue;
414
+ const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);
415
+ if (maskMode === "alpha") {
416
+ fg[i] = 1;
417
+ } else {
418
+ const isBg = hue >= BG_HUE_MIN && hue <= BG_HUE_MAX && s < BG_SAT_MAX && v > BG_V_MIN || v < BG_V_BLACK;
419
+ if (!isBg) fg[i] = 1;
420
+ }
421
+ if (hue >= iris.hueMin && hue <= iris.hueMax && s > iris.satMin && v > IRIS_V_MIN && v < IRIS_V_MAX) {
422
+ irisMask[i] = 1;
423
+ value[i] = v;
424
+ }
425
+ }
426
+ const minArea = Math.max(
427
+ 1,
428
+ Math.round(MIN_AREA * n / MIN_AREA_REFERENCE_PIXELS)
429
+ );
430
+ const closeRadius = Math.max(
431
+ 1,
432
+ Math.round(
433
+ CLOSE_RADIUS * Math.max(width, height) / CLOSE_RADIUS_REFERENCE_PX
434
+ )
435
+ );
436
+ const meanValue = (b) => {
437
+ let count = 0;
438
+ let total = 0;
439
+ for (let y = b.y0; y <= b.y1; y++) {
440
+ for (let x = b.x0; x <= b.x1; x++) {
441
+ const i = y * width + x;
442
+ if (!irisMask[i]) continue;
443
+ count++;
444
+ total += value[i];
445
+ }
446
+ }
447
+ return count ? total / count : 0;
448
+ };
449
+ const candidates = components(
450
+ closeMask(irisMask, width, height, closeRadius),
451
+ width,
452
+ height,
453
+ minArea
454
+ ).filter((b) => b.w < width * BLOB_MAX_FRAC && b.h < height * BLOB_MAX_FRAC).filter((b) => meanValue(b) > IRIS_MEAN_V_MIN).slice(0, MAX_CANDIDATES);
455
+ let best = null;
456
+ for (let i = 0; i < candidates.length; i++) {
457
+ for (let j = i + 1; j < candidates.length; j++) {
458
+ const a = candidates[i];
459
+ const b = candidates[j];
460
+ const dx = Math.abs(a.cx - b.cx);
461
+ const dy = Math.abs(a.cy - b.cy);
462
+ if (dx < width * PAIR_DX_MIN_FRAC || dx > width * PAIR_DX_MAX_FRAC)
463
+ continue;
464
+ if (dy > height * PAIR_DY_MAX_FRAC) continue;
465
+ const score = a.area + b.area;
466
+ if (best === null || score > best.score) {
467
+ const pair = a.cx <= b.cx ? [a, b] : [b, a];
468
+ best = { score, pair };
469
+ }
470
+ }
471
+ }
472
+ if (best === null) {
473
+ throw new AutoRigInputError(
474
+ `no iris pair found in ${filePath} among ${candidates.length} candidate blobs (iris hue ${iris.hueMin}..${iris.hueMax}, sat > ${iris.satMin})`
475
+ );
476
+ }
477
+ const [irisL, irisR] = best.pair;
478
+ const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);
479
+ const { left, right } = foregroundSpan(
480
+ fg,
481
+ width,
482
+ height,
483
+ eyeRow - HEAD_BAND,
484
+ eyeRow + HEAD_BAND
485
+ );
486
+ if (right <= left) {
487
+ throw new AutoRigInputError(
488
+ `no head span at the eye row (y=${eyeRow}) in ${filePath}: the ${maskMode} foreground mask is empty there`
489
+ );
490
+ }
491
+ if (maskMode === "keyed" && right - left + 1 > width * KEYED_SPAN_MAX_FRAC) {
492
+ throw new AutoRigInputError(
493
+ `head span at the eye row (y=${eyeRow}) in ${filePath} covers ${right - left + 1}/${width} px: background not keyed / not an engine render`
494
+ );
495
+ }
496
+ return {
497
+ file: filePath,
498
+ width,
499
+ height,
500
+ maskMode,
501
+ irisL,
502
+ irisR,
503
+ eyeRow,
504
+ head: {
505
+ left,
506
+ right,
507
+ cx: (left + right) / 2,
508
+ half: headHalfOf({ left, right })
509
+ },
510
+ pairCx: (irisL.cx + irisR.cx) / 2,
511
+ eyeGap: irisR.cx - irisL.cx
512
+ };
513
+ }
514
+ function farNearWidths(m, turnSign) {
515
+ return turnSign < 0 ? { far: m.irisL.w, near: m.irisR.w } : { far: m.irisR.w, near: m.irisL.w };
516
+ }
517
+ function overlaySvg(m) {
518
+ const box = (b, stroke) => `<rect x="${b.x0}" y="${b.y0}" width="${b.w}" height="${b.h}" fill="none" stroke="${stroke}" stroke-width="3"/>`;
519
+ const tick = (x, half, stroke) => `<line x1="${x}" y1="${m.eyeRow - half}" x2="${x}" y2="${m.eyeRow + half}" stroke="${stroke}" stroke-width="3"/>`;
520
+ 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>";
521
+ }
522
+ async function writeOverlay(debugDir, label, m) {
523
+ const outPath = import_node_path2.default.join(
524
+ debugDir,
525
+ `${label}-${import_node_path2.default.basename(m.file, ".png")}.debug.png`
526
+ );
527
+ writeFileAtomic(outPath, await encodeOverlayPng(m.file, overlaySvg(m)));
528
+ return outPath;
529
+ }
530
+ var IRIS_HEIGHT_SCALE_TOLERANCE = 0.1;
531
+ async function measureTurnReference(input) {
532
+ try {
533
+ const iris = resolveIris(input.iris);
534
+ const frontPath = resolveInputPath(input.front);
535
+ const turnedPath = resolveInputPath(input.turned);
536
+ const debugDir = input.debugDir === void 0 ? null : resolveOutputDir(input.debugDir);
537
+ const front = await measureTurnImage(frontPath, iris);
538
+ const turned = await measureTurnImage(turnedPath, iris);
539
+ const frontIrisH = (front.irisL.h + front.irisR.h) / 2;
540
+ const turnedIrisH = (turned.irisL.h + turned.irisR.h) / 2;
541
+ if (Math.abs(turnedIrisH - frontIrisH) / frontIrisH > IRIS_HEIGHT_SCALE_TOLERANCE) {
542
+ throw new AutoRigInputError(
543
+ `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`
544
+ );
545
+ }
546
+ const frontShift = front.pairCx - front.head.cx;
547
+ const turnedShift = turned.pairCx - turned.head.cx;
548
+ const shift = turnedShift - frontShift;
549
+ const turnSign = shift < 0 ? -1 : 1;
550
+ const f = farNearWidths(front, turnSign);
551
+ const t = farNearWidths(turned, turnSign);
552
+ const debug = debugDir === null ? void 0 : [
553
+ await writeOverlay(debugDir, "front", front),
554
+ await writeOverlay(debugDir, "turned", turned)
555
+ ];
556
+ return {
557
+ ok: true,
558
+ front,
559
+ turned,
560
+ farEyeRatio: t.far / t.near / (f.far / f.near),
561
+ eyeShift: shift / front.head.half,
562
+ silhouetteRatio: turned.head.half / front.head.half,
563
+ turnSign,
564
+ ...debug === void 0 ? {} : { debug }
565
+ };
566
+ } catch (err) {
567
+ if (err instanceof AutoRigInputError)
568
+ return { ok: false, error: err.message };
569
+ throw err;
570
+ }
571
+ }
572
+ var n1 = (v) => v.toFixed(1);
573
+ var n3 = (v) => v.toFixed(3);
574
+ function imageBlock(label, m) {
575
+ return [
576
+ `# ${label} ${m.file} ${m.width}x${m.height} mask: ${m.maskMode}`,
577
+ `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)}`,
578
+ `head ${m.head.left}..${m.head.right} centre ${n1(m.head.cx)} half ${n1(m.head.half)} pair centre ${n1(m.pairCx)}`
579
+ ];
580
+ }
581
+ function formatTurnReport(result) {
582
+ const { front, turned } = result;
583
+ const f = farNearWidths(front, result.turnSign);
584
+ const t = farNearWidths(turned, result.turnSign);
585
+ const lines = [
586
+ `farEyeRatio ${n3(result.farEyeRatio)} far/near iris width ${t.far}/${t.near} turned over ${f.far}/${f.near} front`,
587
+ `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)`,
588
+ `silhouetteRatio ${n3(result.silhouetteRatio)} head half ${n1(turned.head.half)} px turned over ${n1(front.head.half)} px front`,
589
+ `turnSign ${result.turnSign} (the head turned toward the image's ${result.turnSign < 0 ? "left" : "right"})`,
590
+ "",
591
+ ...imageBlock("front", front),
592
+ "",
593
+ ...imageBlock("turned", turned)
594
+ ];
595
+ if (result.debug !== void 0) {
596
+ lines.push("", ...result.debug.map((p) => `debug overlay ${p}`));
597
+ }
598
+ return lines.join("\n");
599
+ }
600
+
231
601
  // src/tools.ts
232
602
  function coerceModel(model) {
233
603
  try {
@@ -372,6 +742,38 @@ function expectInput(label, fn) {
372
742
  );
373
743
  }
374
744
  }
745
+ function eyeRowOf(layers) {
746
+ const centreY = (role) => {
747
+ const layer = layers.find((l) => l.role === role);
748
+ return layer && layer.bbox.y + layer.bbox.h / 2;
749
+ };
750
+ const pairRow = (left, right) => {
751
+ const a = centreY(left);
752
+ const b = centreY(right);
753
+ return a === void 0 || b === void 0 ? void 0 : (a + b) / 2;
754
+ };
755
+ const row = pairRow("iris_L", "iris_R") ?? pairRow("eye_L", "eye_R");
756
+ if (row === void 0) {
757
+ throw new Error("auto-rig: no eye pair to measure the head width at");
758
+ }
759
+ return Math.round(row);
760
+ }
761
+ function foregroundSpanOfRows(rowLeft, rowRight, rowLo, rowHi) {
762
+ let left = Infinity;
763
+ let right = -Infinity;
764
+ for (let y = Math.max(0, rowLo); y <= Math.min(rowLeft.length - 1, rowHi); y++) {
765
+ if (rowLeft[y] < left) left = rowLeft[y];
766
+ if (rowRight[y] > right) right = rowRight[y];
767
+ }
768
+ return { left, right };
769
+ }
770
+ function facePlateHalfOf(layers) {
771
+ const face = layers.find((l) => l.role === "face");
772
+ if (face === void 0) {
773
+ throw new Error("auto-rig: no face layer to measure the plate against");
774
+ }
775
+ return face.cropW / 2;
776
+ }
375
777
  async function autoRigFromLayers(input) {
376
778
  try {
377
779
  const layers = input.layers;
@@ -394,7 +796,7 @@ async function autoRigFromLayers(input) {
394
796
  }
395
797
  const resolvedLayers = layers.map((layer) => {
396
798
  const resolved = resolveInputPath(layer.path);
397
- return { resolved, fileName: layer.fileName ?? import_node_path2.default.basename(resolved) };
799
+ return { resolved, fileName: layer.fileName ?? import_node_path3.default.basename(resolved) };
398
800
  });
399
801
  const rolePairs = expectInput(
400
802
  "role parsing",
@@ -404,8 +806,10 @@ async function autoRigFromLayers(input) {
404
806
  let canvasW = 0;
405
807
  let canvasH = 0;
406
808
  let totalPixels = 0;
809
+ let opaque = new Uint8Array(0);
407
810
  const layerInputs = [];
408
811
  const crops = [];
812
+ const rowSpansByRole = [];
409
813
  for (let i = 0; i < resolvedLayers.length; i++) {
410
814
  const { resolved, fileName } = resolvedLayers[i];
411
815
  const png = await decodePng(resolved);
@@ -428,6 +832,7 @@ async function autoRigFromLayers(input) {
428
832
  `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`
429
833
  );
430
834
  }
835
+ opaque = new Uint8Array(canvasW * canvasH);
431
836
  } else if (png.width !== canvasW || png.height !== canvasH) {
432
837
  throw new AutoRigInputError(
433
838
  `layer "${fileName}" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
@@ -447,7 +852,19 @@ async function autoRigFromLayers(input) {
447
852
  );
448
853
  }
449
854
  const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);
450
- layerInputs.push({
855
+ const rowLeft = new Int32Array(canvasH).fill(canvasW);
856
+ const rowRight = new Int32Array(canvasH).fill(-1);
857
+ for (let y = 0; y < canvasH; y++) {
858
+ for (let x = 0; x < canvasW; x++) {
859
+ const p = y * canvasW + x;
860
+ if (png.rgba[p * 4 + 3] < ALPHA_OPAQUE) continue;
861
+ opaque[p] = 1;
862
+ if (x < rowLeft[y]) rowLeft[y] = x;
863
+ if (x > rowRight[y]) rowRight[y] = x;
864
+ }
865
+ }
866
+ rowSpansByRole.push({ role, rowLeft, rowRight });
867
+ const layer = {
451
868
  role,
452
869
  fileName,
453
870
  canvasW,
@@ -455,13 +872,69 @@ async function autoRigFromLayers(input) {
455
872
  bbox,
456
873
  cropW: bbox.w,
457
874
  cropH: bbox.h
458
- });
875
+ };
876
+ if (role === "face") {
877
+ const rowHalfWidths = [];
878
+ for (let y = bbox.y; y < bbox.y + bbox.h; y++) {
879
+ rowHalfWidths.push(
880
+ rowRight[y] >= rowLeft[y] ? headHalfOf({ left: rowLeft[y], right: rowRight[y] }) : 0
881
+ );
882
+ }
883
+ layer.rowHalfWidths = rowHalfWidths;
884
+ }
885
+ layerInputs.push(layer);
459
886
  crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
460
887
  }
461
- const model = (0, import_editor2.generateIkiFromLayerSet)(layerInputs, {
462
- width: canvasW,
463
- height: canvasH
464
- });
888
+ const eyeRow = eyeRowOf(layerInputs);
889
+ const span = foregroundSpan(
890
+ opaque,
891
+ canvasW,
892
+ canvasH,
893
+ eyeRow - HEAD_BAND,
894
+ eyeRow + HEAD_BAND
895
+ );
896
+ const headHalfWidth = span.right > span.left ? headHalfOf(span) : void 0;
897
+ const headHalfWidthApplied = headHalfWidth !== void 0 && headHalfWidth > facePlateHalfOf(layerInputs);
898
+ let headEdges;
899
+ if (headHalfWidthApplied) {
900
+ const bandLo = eyeRow - HEAD_BAND;
901
+ const bandHi = eyeRow + HEAD_BAND;
902
+ const left = [];
903
+ const right = [];
904
+ for (const { role, rowLeft, rowRight } of rowSpansByRole) {
905
+ const own = foregroundSpanOfRows(rowLeft, rowRight, bandLo, bandHi);
906
+ if (own.right <= own.left) continue;
907
+ left.push({ role, x: own.left - canvasW / 2 });
908
+ right.push({ role, x: own.right - canvasW / 2 });
909
+ }
910
+ headEdges = { left, right };
911
+ }
912
+ let turn;
913
+ let model;
914
+ try {
915
+ const { eyeShift, farEyeRatio, silhouetteRatio, noseShift, mouthShift } = input.turnTargets ?? {};
916
+ model = (0, import_editor2.generateIkiFromLayerSet)(
917
+ layerInputs,
918
+ { width: canvasW, height: canvasH },
919
+ {
920
+ turnTargets: {
921
+ eyeShift,
922
+ farEyeRatio,
923
+ silhouetteRatio,
924
+ noseShift,
925
+ mouthShift,
926
+ ...headHalfWidthApplied ? { headHalfWidth } : {}
927
+ },
928
+ onTurnSolved: (report) => {
929
+ turn = report;
930
+ },
931
+ ...headEdges === void 0 ? {} : { headEdges }
932
+ }
933
+ );
934
+ } catch (e) {
935
+ if (!(e instanceof import_editor2.TurnTargetError)) throw e;
936
+ throw new AutoRigInputError(e.message);
937
+ }
465
938
  const doc = new import_editor2.EditorDocument(model);
466
939
  const layout = (0, import_editor2.packAtlas)(
467
940
  crops.map((c) => ({ id: c.id, width: c.width, height: c.height }))
@@ -498,7 +971,11 @@ async function autoRigFromLayers(input) {
498
971
  path: outPath,
499
972
  canvas: { width: canvasW, height: canvasH },
500
973
  partCount: finalModel.parts.length,
501
- atlasBytes: dataUri.length
974
+ atlasBytes: dataUri.length,
975
+ ...headHalfWidth === void 0 ? {} : { headHalfWidth },
976
+ headHalfWidthApplied,
977
+ ...headEdges === void 0 ? {} : { headEdges },
978
+ ...turn === void 0 ? {} : { turn }
502
979
  };
503
980
  } catch (err) {
504
981
  if (err instanceof AutoRigInputError)
@@ -509,12 +986,12 @@ async function autoRigFromLayers(input) {
509
986
 
510
987
  // src/compose.ts
511
988
  var import_node_fs3 = __toESM(require("fs"));
512
- var import_node_path4 = __toESM(require("path"));
989
+ var import_node_path5 = __toESM(require("path"));
513
990
  var import_sharp2 = __toESM(require("sharp"));
514
991
 
515
992
  // src/measure.ts
516
993
  var import_node_fs2 = __toESM(require("fs"));
517
- var import_node_path3 = __toESM(require("path"));
994
+ var import_node_path4 = __toESM(require("path"));
518
995
  var IRIS_RATIO_MIN = 0.45;
519
996
  var IRIS_RATIO_MAX = 0.72;
520
997
  var EYE_ASPECT_MIN = 0.5;
@@ -615,8 +1092,8 @@ async function measureDir(absDir) {
615
1092
  const layers = {};
616
1093
  const empty = [];
617
1094
  for (const f of files) {
618
- const role = import_node_path3.default.basename(f, ".png");
619
- const m = await layerStats(import_node_path3.default.join(absDir, f));
1095
+ const role = import_node_path4.default.basename(f, ".png");
1096
+ const m = await layerStats(import_node_path4.default.join(absDir, f));
620
1097
  if (!m) {
621
1098
  empty.push(role);
622
1099
  continue;
@@ -869,7 +1346,7 @@ async function partBuffer(role, cfg, partsDir, inMemory) {
869
1346
  if (inMemory !== void 0) {
870
1347
  img = (0, import_sharp2.default)(inMemory);
871
1348
  } else {
872
- const srcPath = import_node_path4.default.join(partsDir, cfg.src);
1349
+ const srcPath = import_node_path5.default.join(partsDir, cfg.src);
873
1350
  if (!import_node_fs3.default.existsSync(srcPath)) {
874
1351
  if (cfg.optional) return null;
875
1352
  throw new AutoRigInputError(
@@ -924,7 +1401,7 @@ function blankCanvas() {
924
1401
  });
925
1402
  }
926
1403
  async function prepEyeSplit(partsDir) {
927
- const srcPath = import_node_path4.default.join(partsDir, EYEWHITE_SRC);
1404
+ const srcPath = import_node_path5.default.join(partsDir, EYEWHITE_SRC);
928
1405
  if (!import_node_fs3.default.existsSync(srcPath)) {
929
1406
  throw new AutoRigInputError(`missing eyewhite source: ${srcPath}`);
930
1407
  }
@@ -997,12 +1474,12 @@ async function composeLayersFromParts(input) {
997
1474
  );
998
1475
  if (part === null) {
999
1476
  skipped.push(role);
1000
- import_node_fs3.default.rmSync(import_node_path4.default.join(outDir, `${role}.png`), { force: true });
1477
+ import_node_fs3.default.rmSync(import_node_path5.default.join(outDir, `${role}.png`), { force: true });
1001
1478
  continue;
1002
1479
  }
1003
1480
  const { left, top } = placement(role, cfg, part.w, part.h);
1004
1481
  const layer = await blankCanvas().composite([{ input: part.buf, left, top }]).png().toBuffer();
1005
- const outPath = import_node_path4.default.join(outDir, `${role}.png`);
1482
+ const outPath = import_node_path5.default.join(outDir, `${role}.png`);
1006
1483
  writeFileAtomic(outPath, layer);
1007
1484
  layers.push({
1008
1485
  role,
@@ -1022,7 +1499,7 @@ async function composeLayersFromParts(input) {
1022
1499
  background: { r: 245, g: 245, b: 248, alpha: 1 }
1023
1500
  }
1024
1501
  }).composite(preview).png().toBuffer();
1025
- const previewPath = import_node_path4.default.join(outDir, "preview.png");
1502
+ const previewPath = import_node_path5.default.join(outDir, "preview.png");
1026
1503
  writeFileAtomic(previewPath, previewPng);
1027
1504
  return {
1028
1505
  ok: true,
@@ -1041,7 +1518,7 @@ async function composeLayersFromParts(input) {
1041
1518
 
1042
1519
  // src/server.ts
1043
1520
  function createIkiMcpServer() {
1044
- const server = new import_mcp.McpServer({ name: "iki", version: "0.7.0" });
1521
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.8.1" });
1045
1522
  server.registerTool(
1046
1523
  "validate_iki",
1047
1524
  {
@@ -1121,6 +1598,15 @@ function createIkiMcpServer() {
1121
1598
  ),
1122
1599
  quantizeColors: import_zod.z.number().int().min(2).max(256).optional().describe(
1123
1600
  "Palette-quantize the atlas PNG to this many colours (2..256). Flat-shaded art keeps its look at 256 and the model shrinks to about a quarter; omit for lossless."
1601
+ ),
1602
+ turnTargets: import_zod.z.object({
1603
+ eyeShift: import_zod.z.number().optional(),
1604
+ farEyeRatio: import_zod.z.number().optional(),
1605
+ silhouetteRatio: import_zod.z.number().optional(),
1606
+ noseShift: import_zod.z.number().optional(),
1607
+ mouthShift: import_zod.z.number().optional()
1608
+ }).optional().describe(
1609
+ "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 (the result's `turn.clamped` lists the ones that were, `turn.achieved` what the rig reaches); a target you DO pass that 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."
1124
1610
  )
1125
1611
  }
1126
1612
  },
@@ -1209,6 +1695,43 @@ function createIkiMcpServer() {
1209
1695
  }
1210
1696
  }
1211
1697
  );
1698
+ server.registerTool(
1699
+ "measure_turn_reference",
1700
+ {
1701
+ description: "Measures how far a head turns between two images of the same character \u2014 a front view and a turned one, at the SAME scale \u2014 as three ratios, so a rigged turn can be compared to a reference turn (or to an earlier rig) without registering the images: farEyeRatio (turned far/near iris width over the same ratio at rest), eyeShift (how far the eye pair slides across the head, in units of the FRONT head half-width; NEGATIVE = toward the image's left), silhouetteRatio (head half-width, turned over front). The ratios divide out crop and position, not scale, so the pair must already share framing and head size; since a yaw never changes iris height, a pair whose mean iris height differs by more than 10% is refused instead of measured as a turn. Reads engine renders (transparent backdrop) and opaque reference art alike.",
1702
+ inputSchema: {
1703
+ front: import_zod.z.string().describe("Front-facing PNG file path (resolved against cwd)."),
1704
+ turned: import_zod.z.string().describe("The same character turned, as a PNG file path."),
1705
+ iris: import_zod.z.object({
1706
+ hueMin: import_zod.z.number().min(0).max(360),
1707
+ hueMax: import_zod.z.number().min(0).max(360),
1708
+ satMin: import_zod.z.number().min(0).max(1)
1709
+ }).partial().optional().describe(
1710
+ "Iris colour window override merged over the violet default (hue 230..300, sat > 0.22) \u2014 set it for a character whose eyes are another colour."
1711
+ ),
1712
+ debugDir: import_zod.z.string().optional().describe(
1713
+ "Existing directory (resolved against cwd; confined to the working directory) to write `front-<name>.debug.png` / `turned-<name>.debug.png` overlays into, with the iris boxes and head edges drawn."
1714
+ )
1715
+ }
1716
+ },
1717
+ async (args) => {
1718
+ try {
1719
+ const r = await measureTurnReference(args);
1720
+ const text = r.ok ? formatTurnReport(r) : `INVALID: ${r.error}`;
1721
+ return {
1722
+ content: [{ type: "text", text }],
1723
+ structuredContent: { ...r }
1724
+ };
1725
+ } catch (err) {
1726
+ const error = err instanceof Error ? err.message : String(err);
1727
+ return {
1728
+ content: [{ type: "text", text: `Unexpected error: ${error}` }],
1729
+ structuredContent: { ok: false, error },
1730
+ isError: true
1731
+ };
1732
+ }
1733
+ }
1734
+ );
1212
1735
  return server;
1213
1736
  }
1214
1737