@ikijs/mcp 0.9.0 → 0.11.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/README.md CHANGED
@@ -18,12 +18,12 @@ The `model` input for `validate_iki` and `describe_iki` accepts either a plain J
18
18
 
19
19
  ### `auto_rig_from_layers`
20
20
 
21
- Turns a set of role-named, full-canvas transparent PNG layers into a renderable, validated `.iki` model with the textures atlased and embedded as a base64 `data:image/png` URI.
21
+ Turns a set of role-named, full-canvas transparent PNG layers into a renderable, validated `.iki` model with the textures atlased and embedded as a base64 `data:image/png` URI. Under `quantizeColors` a `nose` layer is the exception: the palette rims a soft-shaded nose's feather, so the nose is atlased alone on a second, lossless page.
22
22
 
23
23
  - **`layers`** — array of `{ path, fileName? }`. `path` is a PNG file path (resolved against the server's working directory); the role is derived from `fileName ?? basename(path)`. Required roles: `face`, `eye_L`, `eye_R`, `mouth`. Optional roles include `iris_L`/`iris_R`, `brow_L`/`brow_R`, `hair_front`/`hair_back`, `lash_L`/`lash_R`, etc. All layers must share the same canvas size (taken from the first layer).
24
24
  - **`outputPath`** — optional `.iki` output path (resolved against the working directory; the parent directory must already exist, and the path must end in `.iki`). Defaults to `auto-rigged-model.iki`.
25
25
  - **`turnTargets`** — optional head-turn cues to fit the rig to, in the units `measure_turn_reference` reports off a front/turned reference pair: `eyeShift` (plus `noseShift` and `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 — a **magnitude**, since the rig turns both ways and the sign is the turn's own business; `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. An omitted field falls back to a built-in default, which is _clamped_ to what the layer set can do, and so is an `eyeShift` you pass that runs past the room the art leaves the far eye — the face plate's edge, or the bangs' side strand over the far iris — since that room is a fact about these layers, not about the reference. Any other target you **do** pass that it cannot reach is refused, including an `eyeShift` smaller than the slide the face's own turn already gives the eyes, because that number is a measurement rather than a preference. Only a layer set carrying a `nose` solves a turn at all.
26
- - **Result** — on success the result text is the written file path and `structuredContent` carries `{ ok: true, path, canvas, partCount, atlasBytes, headHalfWidth?, headHalfWidthApplied, headEdges?, strandEdges?, turn? }`. `headHalfWidth` is the head measured here rather than asked for: the layers' own opaque union at the eye row, under the same `alpha >= 128` rule and ±10-row band `measure_turn_reference` spans a render with, so the rig's own rest render measures that span back; it is **absent** when that union has no span there at all (translucent art painted below alpha 128 — still a valid layer set, just with nothing to measure). `headHalfWidthApplied` is `false` when the measured value is absent, or no wider than the face plate (a hairless set, or one widest at the plate itself) — the generator will not take such a head, so the plate stands in for it and the rig is still produced either way. `headEdges` is a companion to a measured, applied `headHalfWidth` (absent otherwise): every role with an opaque pixel in that same eye-row band, per side, each with its own rest x there — passed straight to the generator's own `options.headEdges` so it can tell which part's own deformation actually carries the union's outermost pixel through the turn. `strandEdges` is each side's iris and the `hair_front` run it would slide under on the turn, measured whenever the layers include `hair_front`, `iris_L` and `iris_R`: the iris's opaque span and the run's outer and face-side ends as pixel edges on the row holding the iris's centre (a run that reaches the other iris's centre, a fringe spanning the face, has `runFace: null`; a run narrower than half the iris's painted width on that row is hair detail the iris may cross, and is skipped as if clear) — passed straight to the generator's own `options.strandEdges`, which keeps the far iris from sliding under the bangs any further than it is painted. `turn` is what the solve settled on — `{ radius, holdBase, depths, achieved: { eyeShift, farEyeRatio, silhouetteRatio }, clamped, strandOverlap? }`, where `achieved` is what the rig does reach and `clamped` names every target the rig cut down: each _defaulted_ target this layer set could not reach, plus a passed `eyeShift` that the face plate's edge or the strand cut short. `strandOverlap` gives, per side whose far iris the bangs still cover at some far stop, the covered width — how much of the iris's painted row the run covers where that is largest (`deg`, `px`, and `hh` in head half-widths), how much it covers at rest (`restPx`), and whether the bound held (`held`: `true` means the iris is kept no deeper under the run than it is painted; `false` means the fitted radius could not do that — always so for a fringe spanning the face — so the eyes' turn depth is 0 and `px` is what stays covered); it is absent when nothing is covered. `turn` is absent without a `nose` layer. The (potentially multi-MB) model is written to disk, not inlined. Invalid input (unknown/missing role, empty layer, mismatched sizes, bad path, oversized atlas, a `turnTargets` field that is not a number or that this layer set cannot reach — any passed field other than an `eyeShift` past the art's room, and a passed `eyeShift` below the face's own slide; the message names the field and the attainable range) returns `{ ok: false, error }` with a `INVALID: …` text — not a protocol error.
26
+ - **Result** — on success the result text is the written file path and `structuredContent` carries `{ ok: true, path, canvas, partCount, atlasBytes, headHalfWidth?, headHalfWidthApplied, headEdges?, strandEdges?, noseCore?, turn? }`. `atlasBytes` is the embedded atlas's data-URI length, summed over both pages when the nose has one of its own. `headHalfWidth` is the head measured here rather than asked for: the layers' own opaque union at the eye row, under the same `alpha >= 128` rule and ±10-row band `measure_turn_reference` spans a render with, so the rig's own rest render measures that span back; it is **absent** when that union has no span there at all (translucent art painted below alpha 128 — still a valid layer set, just with nothing to measure). `headHalfWidthApplied` is `false` when the measured value is absent, or no wider than the face plate (a hairless set, or one widest at the plate itself) — the generator will not take such a head, so the plate stands in for it and the rig is still produced either way. `headEdges` is a companion to a measured, applied `headHalfWidth` (absent otherwise): every role with an opaque pixel in that same eye-row band, per side, each with its own rest x there — passed straight to the generator's own `options.headEdges` so it can tell which part's own deformation actually carries the union's outermost pixel through the turn. `strandEdges` is each side's iris and the `hair_front` run it would slide under on the turn, measured whenever the layers include `hair_front`, `iris_L` and `iris_R`: the iris's opaque span and the run's outer and face-side ends as pixel edges on the row holding the iris's centre (a run that reaches the other iris's centre, a fringe spanning the face, has `runFace: null`; a run narrower than half the iris's painted width on that row is hair detail the iris may cross, and is skipped as if clear) — passed straight to the generator's own `options.strandEdges`, which keeps the far iris from sliding under the bangs any further than it is painted. `turn` is what the solve settled on — `{ radius, holdBase, depths, achieved: { eyeShift, farEyeRatio, silhouetteRatio }, clamped, strandOverlap? }`, where `achieved` is what the rig does reach and `clamped` names every target the rig cut down: each _defaulted_ target this layer set could not reach, plus a passed `eyeShift` that the face plate's edge or the strand cut short. `strandOverlap` gives, per side whose far iris the bangs still cover at some far stop, the covered width — how much of the iris's painted row the run covers where that is largest (`deg`, `px`, and `hh` in head half-widths), how much it covers at rest (`restPx`), and whether the bound held (`held`: `true` means the iris is kept no deeper under the run than it is painted; `false` means the fitted radius could not do that — always so for a fringe spanning the face — so the eyes' turn depth is 0 and `px` is what stays covered); it is absent when nothing is covered. `noseCore` is the nose's dense core in canvas px — its pixels at alpha >= 128, not grown, the box handed to the generator as the nose layer's `denseCore` and its turn landmark — absent without a `nose` layer or when it has no pixel at that threshold (painted wholly translucent). `turn` is absent without a `nose` layer. The (potentially multi-MB) model is written to disk, not inlined. Invalid input (unknown/missing role, empty layer, mismatched sizes, bad path, oversized atlas, a `turnTargets` field that is not a number or that this layer set cannot reach — any passed field other than an `eyeShift` past the art's room, and a passed `eyeShift` below the face's own slide; the message names the field and the attainable range) returns `{ ok: false, error }` with a `INVALID: …` text — not a protocol error.
27
27
 
28
28
  The decode/atlas pipeline runs in Node via `sharp` (a native dependency confined to this package); it mirrors the browser editor app's import flow and reuses the pure `@ikijs/editor` model + atlas math, so both paths produce the same rig.
29
29
 
@@ -33,12 +33,13 @@ Composes a directory of AI-generated part PNGs into canvas-aligned, role-named l
33
33
 
34
34
  - **`partsDir`** — directory of the source part PNGs (resolved against the server's working directory). Required sources: `face.png`, `eyewhite.png` (split into the sclera + lash layers), `iris.png`, `mouth.png`, `brow.png`, `hair_front.png`. Optional: `hair_back.png`, `body.png`, `mouth_open.png`, `nose.png` — a parts dir without them still composes, minus those roles. The nose is what the auto-rig leads the head turn with (without a `nose` layer nothing on the face slides), and a face supplied alongside it must be drawn without one, or the painted nose stays on the face plate while the real one moves.
35
35
  - **`outDir`** — an existing directory (resolved against the working directory, confined to it exactly like `auto_rig_from_layers`'s `outputPath`; the tool never creates directories) to write the role layer PNGs and a flattened `preview.png` into. Reusing a directory across runs is intentional — a role this run skips (e.g. composing a head-only set that omits `body`) has its stale `<role>.png` from an earlier run deleted, so the directory always holds exactly this run's roles.
36
- - **`layout`** — optional per-role override merged over the built-in defaults, e.g. `{ "eye_L": { "cx": 660 } }`, so a character can be retuned by re-running compose rather than editing a script. Each of `cx`, `cy`, `w`, `h` is optional; `w` and `h` must be integers in 1..1100 (the canvas size). Omitting `h` keeps the part's own aspect ratio, which is what every role wants until one does not: a generated eyewhite often comes back flatter than its reference, and stretching a flat white lens costs nothing where regenerating it is billed and unreliable. Set `h` on a sclera and its lash together — they share one frame, and the blink fold tears if they diverge.
37
- - **Result** — on success the text is the written layer paths (one per line) followed by the same geometry report `measure_layers` returns; `structuredContent` is `{ ok: true, outDir, layers, skipped, preview, measure }`. Invalid input (a missing required part, an unknown `layout` role, an out-of-range `w` or `h`, a part that lands entirely off-canvas, a non-existent `outDir`) returns `{ ok: false, error }` with `INVALID: …` text.
36
+ - **`layout`** — optional per-role override merged over the built-in defaults, e.g. `{ "eye_L": { "cx": 660 } }`, so a character can be retuned by re-running compose rather than editing a script. Each of `cx`, `cy`, `w`, `h` is optional; `w` and `h` must be integers in 1..1100 (the canvas size). Omitting `h` keeps the part's own aspect ratio, which is what every role wants until one does not: a generated eyewhite often comes back flatter than its reference, and stretching a flat white lens costs nothing where regenerating it is billed and unreliable. The nose is sized and placed by its dense core — its pixels at alpha ≥ 128, the drawing a viewer reads inside a soft nose's feather — rather than its whole part, which for a shaded-bump nose is mostly feather: `w` (default 40) and `h` size the core, `cx` (default 550) centres it, and a set `cy` centres its rows. By default its `cy` is unset, and the core's bottom row (the tip) lands 0.86 of the way from the eye row down to the mouth's, so the nose follows a retuned eye or mouth row. A nose with no pixel at alpha ≥ 128 is sized and placed whole. Set `h` on a sclera and its lash together — they share one frame, and the blink fold tears if they diverge, so a pair set to land on different frames is rejected.
37
+ - **`mirrorParts`** — optional list of part files to flip left-right as they are read, e.g. `["eyewhite.png"]`. Which way a part faces is fixed by the layout, and "left eye" cannot pin it down — it reads as the viewer's left or the character's — so in image terms: `eyewhite.png` is read as the eye on the screen left, lash wing (outer corner) at the image's left end and lash-free tear duct at its right; `brow.png` as the brow on the screen right, thick head at the image's left end and tail at its right. A part drawn the other way round is fixed here for free instead of regenerated. It flips the source, so every role cut from it flips together and an eye's sclera and lash stay in one frame.
38
+ - **Result** — on success the text is the written layer paths (one per line) followed by the same geometry report `measure_layers` returns; `structuredContent` is `{ ok: true, outDir, layers, skipped, preview, measure }`. Invalid input (a missing required part, an unknown `layout` role, an out-of-range `w` or `h`, a lash placed on a different frame from its sclera's, a `mirrorParts` entry that is not a part file, a part that lands entirely off-canvas, a non-existent `outDir`) returns `{ ok: false, error }` with `INVALID: …` text.
38
39
 
39
40
  ### `measure_layers`
40
41
 
41
- Reports the same read-only geometry checks `compose_layers_from_parts` returns inline (iris size/offset relative to the sclera, eye aspect, cropped or flat-cut edges, missing optional roles), over an already-composed layers directory — for re-checking a layers dir without recomposing it.
42
+ Reports the same read-only geometry checks `compose_layers_from_parts` returns inline (iris size/offset relative to the sclera, eye aspect, an eye drawn facing the other way, cropped or flat-cut edges, missing optional roles), over an already-composed layers directory — for re-checking a layers dir without recomposing it.
42
43
 
43
44
  - **`layersDir`** — directory of role-named layer PNGs (resolved against the working directory).
44
45
  - **Result** — the text is the report: a per-layer size/bbox-centre/mass-centre/margins table, then the checks that fired. `structuredContent` is `{ ok: true, layersDir, layers, empty, warnings, passed }`. A missing or non-directory `layersDir` returns `{ ok: false, error }` with `INVALID: …` text.
@@ -222,6 +222,24 @@ var BG_HUE_MAX = 260;
222
222
  var BG_SAT_MAX = 0.2;
223
223
  var BG_V_MIN = 0.55;
224
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
+ }
239
+ }
240
+ if (maxX < 0) return null;
241
+ return { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 };
242
+ }
225
243
  function rgbToHsv(r, g, b) {
226
244
  r /= 255;
227
245
  g /= 255;
@@ -758,6 +776,19 @@ function facePlateHalfOf(layers) {
758
776
  return face.cropW / 2;
759
777
  }
760
778
  var STRAND_MIN_RUN_FRACTION = 0.5;
779
+ var LOSSLESS_PAGE_ROLE = "nose";
780
+ async function renderAtlasPage(crops, quantizeColors) {
781
+ const layout = packAtlas(
782
+ crops.map((c) => ({ id: c.id, width: c.width, height: c.height }))
783
+ );
784
+ if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {
785
+ throw new AutoRigInputError(
786
+ `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`
787
+ );
788
+ }
789
+ const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);
790
+ return { crops, layout, dataUri };
791
+ }
761
792
  async function autoRigFromLayers(input) {
762
793
  try {
763
794
  const layers = input.layers;
@@ -869,10 +900,14 @@ async function autoRigFromLayers(input) {
869
900
  );
870
901
  }
871
902
  layer.rowHalfWidths = rowHalfWidths;
903
+ } else if (role === "nose") {
904
+ const core = denseCoreOf(png.rgba, canvasW, canvasH);
905
+ if (core !== null) layer.denseCore = core;
872
906
  }
873
907
  layerInputs.push(layer);
874
908
  crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
875
909
  }
910
+ const noseCore = layerInputs.find((l) => l.role === "nose")?.denseCore;
876
911
  const eyeRow = eyeRowOf(layerInputs);
877
912
  const span = foregroundSpan(
878
913
  opaque,
@@ -982,46 +1017,58 @@ async function autoRigFromLayers(input) {
982
1017
  throw new AutoRigInputError(e.message);
983
1018
  }
984
1019
  const doc = new EditorDocument(model);
985
- const layout = packAtlas(
986
- crops.map((c) => ({ id: c.id, width: c.width, height: c.height }))
987
- );
988
- if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {
989
- throw new AutoRigInputError(
990
- `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`
991
- );
992
- }
993
- const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);
994
- if (dataUri.length > MAX_OUTPUT_BYTES) {
1020
+ const losslessCrop = quantizeColors === void 0 ? void 0 : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);
1021
+ const pages = losslessCrop === void 0 ? [await renderAtlasPage(crops, quantizeColors)] : [
1022
+ await renderAtlasPage(
1023
+ crops.filter((c) => c !== losslessCrop),
1024
+ quantizeColors
1025
+ ),
1026
+ await renderAtlasPage([losslessCrop], void 0)
1027
+ ];
1028
+ const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);
1029
+ if (atlasBytes > MAX_OUTPUT_BYTES) {
995
1030
  throw new AutoRigInputError(
996
- `atlas data URI ${dataUri.length} bytes exceeds ${MAX_OUTPUT_BYTES}`
1031
+ `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`
997
1032
  );
998
1033
  }
999
- const partTextureAssignments = crops.map((crop) => {
1000
- const placement2 = layout.placements.find((p) => p.id === crop.id);
1001
- if (placement2 === void 0) {
1002
- throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
1003
- }
1004
- return {
1005
- partId: crop.id,
1006
- uv: uvRectFor(placement2, {
1007
- width: layout.pageWidth,
1008
- height: layout.pageHeight
1009
- })
1010
- };
1034
+ const partTextureAssignments = pages.flatMap(
1035
+ ({ crops: pageCrops, layout }) => pageCrops.map((crop) => {
1036
+ const placement2 = layout.placements.find((p) => p.id === crop.id);
1037
+ if (placement2 === void 0) {
1038
+ throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
1039
+ }
1040
+ return {
1041
+ partId: crop.id,
1042
+ uv: uvRectFor(placement2, {
1043
+ width: layout.pageWidth,
1044
+ height: layout.pageHeight
1045
+ })
1046
+ };
1047
+ })
1048
+ );
1049
+ doc.applyAtlas({
1050
+ textures: [{ source: pages[0].dataUri }],
1051
+ partTextureAssignments
1011
1052
  });
1012
- doc.applyAtlas({ textures: [{ source: dataUri }], partTextureAssignments });
1013
- const finalModel = parseIkiModel(doc.getModel());
1053
+ let patched = doc.getModel();
1054
+ if (losslessCrop !== void 0) {
1055
+ patched = structuredClone(patched);
1056
+ patched.textures = pages.map((p) => ({ source: p.dataUri }));
1057
+ patched.parts.find((p) => p.id === losslessCrop.id).texture.index = 1;
1058
+ }
1059
+ const finalModel = parseIkiModel(patched);
1014
1060
  writeFileAtomic(outPath, JSON.stringify(finalModel));
1015
1061
  return {
1016
1062
  ok: true,
1017
1063
  path: outPath,
1018
1064
  canvas: { width: canvasW, height: canvasH },
1019
1065
  partCount: finalModel.parts.length,
1020
- atlasBytes: dataUri.length,
1066
+ atlasBytes,
1021
1067
  ...headHalfWidth === void 0 ? {} : { headHalfWidth },
1022
1068
  headHalfWidthApplied,
1023
1069
  ...headEdges === void 0 ? {} : { headEdges },
1024
1070
  ...strandEdges === void 0 ? {} : { strandEdges },
1071
+ ...noseCore === void 0 ? {} : { noseCore },
1025
1072
  ...turn === void 0 ? {} : { turn }
1026
1073
  };
1027
1074
  } catch (err) {
@@ -1040,7 +1087,8 @@ var EYE_ASPECT_MIN = 0.5;
1040
1087
  var IRIS_OFFSET_MAX_X = 3;
1041
1088
  var IRIS_OFFSET_MAX_Y = 10;
1042
1089
  var EDGE_SOLID_MAX = 0.5;
1043
- var LASH_CENTRE_TOL_FRAC = 0.03;
1090
+ var LASH_STRAY_TOL_FRAC = 0.02;
1091
+ var EYE_FACING_TOL_FRAC = 0.02;
1044
1092
  var EDGE_RUN_MIN_PX = 40;
1045
1093
  var FLAT_CUT_MAX_FRAC = 0.1;
1046
1094
  var FLAT_CUT_MIN_PX = 40;
@@ -1121,6 +1169,21 @@ async function layerStats(filePath) {
1121
1169
  };
1122
1170
  }
1123
1171
  var pct = (v) => `${(v * 100).toFixed(0)}%`;
1172
+ async function lashOffSclera(eyePath, lashPath) {
1173
+ const eye = await decodePng(eyePath);
1174
+ const lash = await decodePng(lashPath);
1175
+ let opaque = 0;
1176
+ let off = 0;
1177
+ for (let y = 0; y < lash.height; y++) {
1178
+ for (let x = 0; x < lash.width; x++) {
1179
+ if (lash.rgba[(y * lash.width + x) * 4 + 3] < 128) continue;
1180
+ opaque++;
1181
+ const onEye = x < eye.width && y < eye.height;
1182
+ if (!onEye || eye.rgba[(y * eye.width + x) * 4 + 3] <= 8) off++;
1183
+ }
1184
+ }
1185
+ return { opaque, off };
1186
+ }
1124
1187
  async function measureDir(absDir) {
1125
1188
  const files = fs2.readdirSync(absDir).filter((f) => f.endsWith(".png") && f !== "preview.png").sort();
1126
1189
  if (files.length === 0) {
@@ -1202,12 +1265,28 @@ async function measureDir(absDir) {
1202
1265
  }
1203
1266
  }
1204
1267
  if (lash) {
1205
- const dx = lash.bboxCx - eye.bboxCx;
1268
+ const { opaque, off } = await lashOffSclera(
1269
+ path4.join(absDir, `eye_${side}.png`),
1270
+ path4.join(absDir, `lash_${side}.png`)
1271
+ );
1206
1272
  const dTop = lash.marginTop - eye.marginTop;
1207
- if (Math.abs(dx) > eye.w * LASH_CENTRE_TOL_FRAC || Math.abs(dTop) > 0.5) {
1273
+ const faults = [
1274
+ ...off > opaque * LASH_STRAY_TOL_FRAC ? [`${off} of its ${opaque} opaque px lie off eye_${side}'s sclera`] : [],
1275
+ ...Math.abs(dTop) > 0.5 ? [`its top edge is ${dTop.toFixed(1)} px off the sclera's`] : []
1276
+ ];
1277
+ if (faults.length > 0) {
1208
1278
  warnings.push(
1209
- `lash_${side}: centre is ${dx.toFixed(1)} px and top edge ${dTop.toFixed(1)} px off eye_${side}. They are split from one source and MUST share cx/cy/w in layout, or the blink fold tears. Retune to match.`
1279
+ `lash_${side}: ${faults.join(" and ")} \u2014 they are split from one source and MUST share cx/cy/w/h in layout, or the blink fold tears. Retune to match.`
1210
1280
  );
1281
+ } else {
1282
+ const bareLeft = lash.marginLeft - eye.marginLeft;
1283
+ const bareRight = lash.marginRight - eye.marginRight;
1284
+ const [bareOuter, bareInner] = side === "R" ? [bareLeft, bareRight] : [bareRight, bareLeft];
1285
+ if ((bareOuter - bareInner) / eye.w > EYE_FACING_TOL_FRAC) {
1286
+ warnings.push(
1287
+ `eye_${side}: its lash stops ${pct(bareOuter / eye.w)} of the eye width short of the outer corner and ${pct(bareInner / eye.w)} short of the nose side \u2014 the eyewhite is drawn facing the other way, lash wing at the inner corner. The composer reads eyewhite.png as the eye on the screen LEFT: lash wing at the image's left end, lash-free tear duct at its right. Free fix: compose again with mirrorParts: ["eyewhite.png"] \u2014 no regeneration.`
1288
+ );
1289
+ }
1211
1290
  }
1212
1291
  }
1213
1292
  }
@@ -1274,6 +1353,7 @@ var IRIS_W = Math.round(EYE_W * 0.5625);
1274
1353
  var EYEWHITE_SRC = "eyewhite.png";
1275
1354
  var EYE_LASH_LUMA = 120;
1276
1355
  var LASH_KEEP_FRACTION = 0.5;
1356
+ var NOSE_TIP_AT = 0.86;
1277
1357
  var DEFAULT_LAYOUT = {
1278
1358
  // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir
1279
1359
  // without them still composes (head-only character).
@@ -1285,9 +1365,11 @@ var DEFAULT_LAYOUT = {
1285
1365
  face: { src: "face.png", cx: 550, cy: 475, w: 400 },
1286
1366
  // The nose, drawn on its own (the face is drawn without one): the auto-rig
1287
1367
  // leads the head turn with it and keys the other features' slide on its
1288
- // presence, so without it the features stay on the face plate. Sits between
1289
- // the eyes and above the mouth. OPTIONAL: a parts dir without it composes.
1290
- nose: { src: "nose.png", cx: 550, cy: 586, w: 40, optional: true },
1368
+ // presence, so without it the features stay on the face plate. `w` is the
1369
+ // width of its dense core, and it has no `cy`: its row comes from the tip
1370
+ // rule (NOSE_TIP_AT), between the eyes and the mouth, so it follows them
1371
+ // when they are retuned. OPTIONAL: a parts dir without it composes.
1372
+ nose: { src: "nose.png", cx: 550, w: 40, optional: true },
1291
1373
  mouth: { src: "mouth.png", cx: 550, cy: 619, w: 68 },
1292
1374
  // Cross-fades with `mouth` on ParamMouthOpenY (opacity, not scaleY) once the
1293
1375
  // auto-rig sees both roles. Same cx/w as `mouth` so the lip width matches;
@@ -1342,6 +1424,12 @@ var ORDER = [
1342
1424
  "brow_R",
1343
1425
  "hair_front"
1344
1426
  ];
1427
+ var PART_FILES = [
1428
+ ...new Set(
1429
+ Object.values(DEFAULT_LAYOUT).map((cfg) => cfg.src).filter((src) => !src.startsWith("eyewhite_"))
1430
+ ),
1431
+ EYEWHITE_SRC
1432
+ ];
1345
1433
  function resolveLayout(overrides) {
1346
1434
  const resolved = { ...DEFAULT_LAYOUT };
1347
1435
  if (overrides === void 0) return resolved;
@@ -1352,7 +1440,7 @@ function resolveLayout(overrides) {
1352
1440
  );
1353
1441
  }
1354
1442
  if (override === void 0) continue;
1355
- const next = { ...resolved[role] };
1443
+ const set = {};
1356
1444
  for (const field of ["cx", "cy"]) {
1357
1445
  const value = override[field];
1358
1446
  if (value === void 0) continue;
@@ -1361,7 +1449,7 @@ function resolveLayout(overrides) {
1361
1449
  `layout.${role}.${field} must be a finite number, got ${String(value)}`
1362
1450
  );
1363
1451
  }
1364
- next[field] = value;
1452
+ set[field] = value;
1365
1453
  }
1366
1454
  for (const field of ["w", "h"]) {
1367
1455
  const value = override[field];
@@ -1371,12 +1459,26 @@ function resolveLayout(overrides) {
1371
1459
  `layout.${role}.${field} must be an integer in 1..${CANVAS}, got ${String(value)}`
1372
1460
  );
1373
1461
  }
1374
- next[field] = value;
1462
+ set[field] = value;
1375
1463
  }
1376
- resolved[role] = next;
1464
+ const key = role;
1465
+ if (key === "nose") resolved.nose = { ...resolved.nose, ...set };
1466
+ else resolved[key] = { ...resolved[key], ...set };
1377
1467
  }
1378
1468
  return resolved;
1379
1469
  }
1470
+ function resolveMirrorParts(names) {
1471
+ const mirrored = /* @__PURE__ */ new Set();
1472
+ for (const [i, name] of (names ?? []).entries()) {
1473
+ if (!PART_FILES.includes(name)) {
1474
+ throw new AutoRigInputError(
1475
+ `mirrorParts[${i}]: unknown part ${JSON.stringify(name)} \u2014 expected one of ${PART_FILES.join(", ")}`
1476
+ );
1477
+ }
1478
+ mirrored.add(name);
1479
+ }
1480
+ return mirrored;
1481
+ }
1380
1482
  function keyWhiteToAlpha(rgba) {
1381
1483
  const keyed = Buffer.from(rgba);
1382
1484
  for (let i = 0; i < keyed.length; i += 4) {
@@ -1386,7 +1488,16 @@ function keyWhiteToAlpha(rgba) {
1386
1488
  }
1387
1489
  return keyed;
1388
1490
  }
1389
- async function partBuffer(role, cfg, partsDir, inMemory) {
1491
+ async function coreOf(png) {
1492
+ const { data, info } = await sharp2(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1493
+ return denseCoreOf(data, info.width, info.height) ?? {
1494
+ x: 0,
1495
+ y: 0,
1496
+ w: info.width,
1497
+ h: info.height
1498
+ };
1499
+ }
1500
+ async function partBuffer(role, cfg, partsDir, inMemory, flipSource) {
1390
1501
  let img;
1391
1502
  if (inMemory !== void 0) {
1392
1503
  img = sharp2(inMemory);
@@ -1404,35 +1515,58 @@ async function partBuffer(role, cfg, partsDir, inMemory) {
1404
1515
  });
1405
1516
  }
1406
1517
  if (!cfg.noTrim) img = img.trim({ threshold: 12 });
1407
- if (cfg.mirror) img = img.flop();
1518
+ if ((cfg.mirror ?? false) !== flipSource) img = img.flop();
1408
1519
  const trimmed = await img.png().toBuffer({ resolveWithObject: true });
1409
- if (cfg.h === void 0) {
1410
- const scaledH = Math.round(
1411
- trimmed.info.height * cfg.w / trimmed.info.width
1520
+ const { width: trimmedW, height: trimmedH } = trimmed.info;
1521
+ const sized = role === "nose" ? await coreOf(trimmed.data) : { x: 0, y: 0, w: trimmedW, h: trimmedH };
1522
+ const width = Math.round(trimmedW * cfg.w / sized.w);
1523
+ const height = cfg.h === void 0 ? Math.round(trimmedH * width / trimmedW) : Math.round(trimmedH * cfg.h / sized.h);
1524
+ if (width > CANVAS || height > CANVAS) {
1525
+ const field = width > CANVAS || cfg.h === void 0 ? "w" : "h";
1526
+ throw new AutoRigInputError(
1527
+ `layout.${role}.${field}: resized part ${width}x${height} exceeds the ${CANVAS} canvas`
1412
1528
  );
1413
- if (scaledH > CANVAS) {
1414
- throw new AutoRigInputError(
1415
- `layout.${role}.w: resized part ${cfg.w}x${scaledH} exceeds the ${CANVAS} canvas`
1416
- );
1417
- }
1418
1529
  }
1419
- const resized = await sharp2(trimmed.data).resize(
1420
- cfg.h === void 0 ? { width: cfg.w } : { width: cfg.w, height: cfg.h, fit: "fill" }
1421
- ).png().toBuffer({ resolveWithObject: true });
1530
+ const resized = await sharp2(trimmed.data).resize(cfg.h === void 0 ? { width } : { width, height, fit: "fill" }).png().toBuffer({ resolveWithObject: true });
1422
1531
  return {
1423
1532
  buf: resized.data,
1424
1533
  w: resized.info.width,
1425
1534
  h: resized.info.height
1426
1535
  };
1427
1536
  }
1428
- function placement(role, cfg, w, h) {
1429
- const left = Math.round(cfg.cx - w / 2);
1430
- const top = Math.round(cfg.cy - h / 2);
1537
+ function assertOnCanvas(source, w, h, left, top) {
1431
1538
  if (left + w <= 0 || top + h <= 0 || left >= CANVAS || top >= CANVAS) {
1432
1539
  throw new AutoRigInputError(
1433
- `layout.${role}.cx/cy: the placed part (${w}x${h} at ${left},${top}) falls entirely outside the ${CANVAS} canvas`
1540
+ `${source}: the placed part (${w}x${h} at ${left},${top}) falls entirely outside the ${CANVAS} canvas`
1434
1541
  );
1435
1542
  }
1543
+ }
1544
+ function placement(role, cfg, w, h) {
1545
+ const left = Math.round(cfg.cx - w / 2);
1546
+ const top = Math.round(cfg.cy - h / 2);
1547
+ assertOnCanvas(`layout.${role}.cx/cy`, w, h, left, top);
1548
+ return { left, top };
1549
+ }
1550
+ function nosePlacement(layout, core, w, h) {
1551
+ const { cx, cy } = layout.nose;
1552
+ const left = Math.round(cx - (core.x + core.w / 2));
1553
+ let top;
1554
+ if (cy !== void 0) {
1555
+ top = Math.round(cy - (core.y + core.h / 2));
1556
+ } else {
1557
+ const eyeRow = (layout.eye_L.cy + layout.eye_R.cy) / 2;
1558
+ const tipRow = Math.round(
1559
+ eyeRow + NOSE_TIP_AT * (layout.mouth.cy - eyeRow)
1560
+ );
1561
+ top = tipRow - (core.y + core.h - 1);
1562
+ }
1563
+ assertOnCanvas(
1564
+ cy !== void 0 ? "layout.nose.cx/cy" : "layout.nose.cx/cy (cy unset: its tip row comes from layout.eye_L/eye_R/mouth.cy)",
1565
+ w,
1566
+ h,
1567
+ left,
1568
+ top
1569
+ );
1436
1570
  return { left, top };
1437
1571
  }
1438
1572
  function blankCanvas() {
@@ -1501,28 +1635,47 @@ async function composeLayersFromParts(input) {
1501
1635
  );
1502
1636
  }
1503
1637
  const layout = resolveLayout(input.layout);
1638
+ const mirrored = resolveMirrorParts(input.mirrorParts);
1504
1639
  const split = await prepEyeSplit(partsDir);
1505
1640
  const splitSources = /* @__PURE__ */ new Map([
1506
1641
  ["eyewhite_sclera.png", split.sclera],
1507
1642
  ["eyewhite_lash.png", split.lash]
1508
1643
  ]);
1509
- const layers = [];
1644
+ const placed = [];
1510
1645
  const skipped = [];
1511
- const preview = [];
1512
1646
  for (const role of ORDER) {
1513
1647
  const cfg = layout[role];
1648
+ const inMemory = splitSources.get(cfg.src);
1514
1649
  const part = await partBuffer(
1515
1650
  role,
1516
1651
  cfg,
1517
1652
  partsDir,
1518
- splitSources.get(cfg.src)
1653
+ inMemory,
1654
+ // The split halves are cut from eyewhite.png, the file a caller names.
1655
+ mirrored.has(inMemory === void 0 ? cfg.src : EYEWHITE_SRC)
1519
1656
  );
1520
1657
  if (part === null) {
1521
1658
  skipped.push(role);
1522
- fs3.rmSync(path5.join(outDir, `${role}.png`), { force: true });
1523
1659
  continue;
1524
1660
  }
1525
- const { left, top } = placement(role, cfg, part.w, part.h);
1661
+ const { left, top } = role === "nose" ? nosePlacement(layout, await coreOf(part.buf), part.w, part.h) : placement(role, layout[role], part.w, part.h);
1662
+ if (role === "lash_L" || role === "lash_R") {
1663
+ const eyeRole = role === "lash_L" ? "eye_L" : "eye_R";
1664
+ const eye = placed.find((p) => p.role === eyeRole);
1665
+ if (eye !== void 0 && (eye.left !== left || eye.top !== top || eye.part.w !== part.w || eye.part.h !== part.h)) {
1666
+ throw new AutoRigInputError(
1667
+ `layout.${role} places the lash at ${part.w}x${part.h} (${left},${top}), but layout.${eyeRole} places its sclera at ${eye.part.w}x${eye.part.h} (${eye.left},${eye.top}) \u2014 they are cut from one eyewhite into one frame, and the blink fold tears where they part. Set cx/cy/w/h the same on both.`
1668
+ );
1669
+ }
1670
+ }
1671
+ placed.push({ role, part, left, top });
1672
+ }
1673
+ for (const role of skipped) {
1674
+ fs3.rmSync(path5.join(outDir, `${role}.png`), { force: true });
1675
+ }
1676
+ const layers = [];
1677
+ const preview = [];
1678
+ for (const { role, part, left, top } of placed) {
1526
1679
  const layer = await blankCanvas().composite([{ input: part.buf, left, top }]).png().toBuffer();
1527
1680
  const outPath = path5.join(outDir, `${role}.png`);
1528
1681
  writeFileAtomic(outPath, layer);
@@ -1565,7 +1718,7 @@ async function composeLayersFromParts(input) {
1565
1718
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1566
1719
  import { z } from "zod";
1567
1720
  function createIkiMcpServer() {
1568
- const server = new McpServer({ name: "iki", version: "0.9.0" });
1721
+ const server = new McpServer({ name: "iki", version: "0.11.0" });
1569
1722
  server.registerTool(
1570
1723
  "validate_iki",
1571
1724
  {
@@ -1644,7 +1797,7 @@ function createIkiMcpServer() {
1644
1797
  "Output .iki path (resolved against cwd; parent dir must exist)."
1645
1798
  ),
1646
1799
  quantizeColors: z.number().int().min(2).max(256).optional().describe(
1647
- "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."
1800
+ "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. A `nose` layer stays lossless on a second atlas page of its own, since the palette rims a soft-shaded nose's feather; the nose's own lossless page adds a content-dependent amount, since splitting it off also changes how page 0 re-quantizes without it; the result's `atlasBytes` sums both pages."
1648
1801
  ),
1649
1802
  turnTargets: z.object({
1650
1803
  eyeShift: z.number().optional(),
@@ -1692,7 +1845,10 @@ function createIkiMcpServer() {
1692
1845
  h: z.number()
1693
1846
  }).partial()
1694
1847
  ).optional().describe(
1695
- "Per-role override merged over the built-in defaults, keyed by role \u2014 hair_back, body, face, nose, mouth, mouth_open, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front \u2014 e.g. `{ eye_L: { cx: 660 } }`. `w` and `h` are integers in 1..1100; omit `h` to keep the part's own aspect, set it to stretch (set it on a sclera and its lash together, or the blink fold tears)."
1848
+ "Per-role override merged over the built-in defaults, keyed by role \u2014 hair_back, body, face, nose, mouth, mouth_open, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front \u2014 e.g. `{ eye_L: { cx: 660 } }`. `w` and `h` are integers in 1..1100; omit `h` to keep the part's own aspect, set it to stretch. The nose is sized and placed by its dense core (its pixels at alpha >= 128, the drawing inside a soft nose's feather), not its whole part: `w`/`h` size the core, `cx` centres it, and a set `cy` centres its rows. Its `cy` defaults to unset, which lands the core's bottom row (the tip) 0.86 of the way from the eye row down to the mouth's, so the nose follows a retuned eye or mouth row. eye_L/lash_L and eye_R/lash_R are cut from one eyewhite into one frame, so each pair must land on the same frame \u2014 a pair set to land apart is rejected."
1849
+ ),
1850
+ mirrorParts: z.array(z.string()).optional().describe(
1851
+ "Part files to flip left-right as they are read, e.g. `[\"eyewhite.png\"]`. The composer reads eyewhite.png as the eye on the screen LEFT (lash wing at the image's left end, lash-free tear duct at its right) and brow.png as the brow on the screen RIGHT (thick head at the image's left end, tail at its right); a part drawn the other way round is fixed here for free. It flips the source, so every role cut from it flips together and an eye's sclera and lash stay in one frame."
1696
1852
  )
1697
1853
  }
1698
1854
  },
@@ -1794,4 +1950,4 @@ export {
1794
1950
  composeLayersFromParts,
1795
1951
  createIkiMcpServer
1796
1952
  };
1797
- //# sourceMappingURL=chunk-R6LYJVYC.mjs.map
1953
+ //# sourceMappingURL=chunk-LOOIWB2J.mjs.map