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