@ikijs/mcp 0.33.1 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -30,8 +30,10 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ CUSTOM_GATE_LIMITS: () => CUSTOM_GATE_LIMITS,
33
34
  SWEEP_PRESETS: () => SWEEP_PRESETS,
34
35
  autoRigFromLayers: () => autoRigFromLayers,
36
+ checkCustomGate: () => checkCustomGate,
35
37
  checkModelFolds: () => checkModelFolds,
36
38
  checkNod: () => checkNod,
37
39
  checkSweep: () => checkSweep,
@@ -40,6 +42,8 @@ __export(index_exports, {
40
42
  describeIki: () => describeIki,
41
43
  describeIkiAt: () => describeIkiAt,
42
44
  describeRigPlan: () => describeRigPlan,
45
+ failedCustomGate: () => failedCustomGate,
46
+ formatCustomGate: () => formatCustomGate,
43
47
  formatFoldReport: () => formatFoldReport,
44
48
  formatHairSideReport: () => formatHairSideReport,
45
49
  formatMeasureReport: () => formatMeasureReport,
@@ -51,6 +55,7 @@ __export(index_exports, {
51
55
  listStandardParameters: () => listStandardParameters,
52
56
  measureLayers: () => measureLayers,
53
57
  measureTurnReference: () => measureTurnReference,
58
+ probeRig: () => probeRig,
54
59
  renderPoses: () => renderPoses,
55
60
  validateIki: () => validateIki
56
61
  });
@@ -61,10 +66,10 @@ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${_
61
66
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
62
67
 
63
68
  // src/tools.ts
64
- var import_node_fs5 = require("fs");
69
+ var import_node_fs6 = require("fs");
65
70
  var import_node_path5 = __toESM(require("path"));
66
- var import_format9 = require("@ikijs/format");
67
- var import_editor3 = require("@ikijs/editor");
71
+ var import_format11 = require("@ikijs/format");
72
+ var import_editor4 = require("@ikijs/editor");
68
73
 
69
74
  // ../engine/src/math.ts
70
75
  function clamp(value, min, max) {
@@ -478,6 +483,22 @@ function resolveDeformers(deformers, params) {
478
483
  return { worlds, grids };
479
484
  }
480
485
 
486
+ // ../engine/src/occlusion.ts
487
+ function occlusionAmount(occlusion, value) {
488
+ const { stops } = occlusion;
489
+ const first = stops[0];
490
+ if (value <= first.value) return first.amount;
491
+ for (let i = 1; i < stops.length; i++) {
492
+ const hi = stops[i];
493
+ if (value <= hi.value) {
494
+ const lo = stops[i - 1];
495
+ const t = (value - lo.value) / (hi.value - lo.value);
496
+ return lo.amount * (1 - t) + hi.amount * t;
497
+ }
498
+ }
499
+ return stops[stops.length - 1].amount;
500
+ }
501
+
481
502
  // ../engine/src/idle-motion.ts
482
503
  var import_format = require("@ikijs/format");
483
504
 
@@ -1736,58 +1757,6 @@ function affectedParts(model, output) {
1736
1757
  );
1737
1758
  }
1738
1759
 
1739
- // src/fold-report.ts
1740
- var import_editor = require("@ikijs/editor");
1741
- function checkModelFolds(model, extraValues = []) {
1742
- const declared = new Set(model.parameters.map((p) => p.id));
1743
- return checkFolds(model, {
1744
- poses: [...foldPoses(model), ...extraValues.map(foldPose)],
1745
- // The effective value, not the pose's overrides: the auto-rig's mouth
1746
- // rests shut at its default, so `rest` and the other parameters' singles
1747
- // are shut-mouth poses too.
1748
- expected: (target2, _pose, value) => {
1749
- if (target2.kind !== "part") return false;
1750
- const shutBy = import_editor.SHUT_BY.get(target2.id);
1751
- return shutBy !== void 0 && declared.has(shutBy) && value(shutBy) === 0;
1752
- }
1753
- });
1754
- }
1755
- function formatFoldReport(report, canvas) {
1756
- const lines = report.offenders.length === 0 ? [`FOLDS: none over ${report.poses} poses`] : report.offenders.map((t) => offenderLine(t, t.worst, canvas));
1757
- const closures = report.targets.flatMap((t) => {
1758
- if (t.expected === void 0) return [];
1759
- if (t.expected.ratio >= report.thresholds.collapse) return [];
1760
- const shutBy = import_editor.SHUT_BY.get(t.target.id);
1761
- const at = shutBy === void 0 ? "" : ` at ${shutBy}=0`;
1762
- return [`${t.target.id} ${ratioText(t.expected.ratio)}${at}`];
1763
- });
1764
- if (closures.length > 0) {
1765
- lines.push(
1766
- `FOLDS expected: by-design closures, not findings \u2014 ${closures.join(", ")}`
1767
- );
1768
- }
1769
- return lines;
1770
- }
1771
- function foldPose(values) {
1772
- const ids = Object.keys(values).sort();
1773
- const name = ids.length === 0 ? "rest" : ids.map((id) => `${id}=${values[id]}`).join(" ");
1774
- return { name, values };
1775
- }
1776
- function offenderLine(t, hit, canvas) {
1777
- const where = "triangle" in hit.where ? `triangle ${hit.where.triangle}` : `cell (${hit.where.col},${hit.where.row})`;
1778
- const { x, y } = hit.rest;
1779
- return `FOLD ${t.kind} ${t.target.kind} ${t.target.id} ${where} ratio ${ratioText(hit.ratio)} pose [${hit.pose.name}] rest at (${x.toFixed(1)}, ${y.toFixed(1)}) model space, (${(canvas.width / 2 + x).toFixed(0)}, ${(canvas.height / 2 - y).toFixed(0)}) model px from the top-left`;
1780
- }
1781
- function ratioText(ratio) {
1782
- if (ratio === 0) return "0";
1783
- return Math.abs(ratio) < 0.01 ? ratio.toExponential(1) : ratio.toFixed(2);
1784
- }
1785
-
1786
- // src/render-poses.ts
1787
- var import_node_fs4 = require("fs");
1788
- var import_node_path4 = __toESM(require("path"));
1789
- var import_format8 = require("@ikijs/format");
1790
-
1791
1760
  // src/limits.ts
1792
1761
  var import_node_fs = __toESM(require("fs"));
1793
1762
  var import_node_path = __toESM(require("path"));
@@ -1798,6 +1767,8 @@ var MAX_ATLAS_SIDE = 4096;
1798
1767
  var MAX_INPUT_PIXELS = 4096 * 4096;
1799
1768
  var MAX_TOTAL_PIXELS = 128 * 1024 * 1024;
1800
1769
  var MAX_OUTPUT_BYTES = 12 * 1024 * 1024;
1770
+ var MAX_PROBE_QUERIES = 64;
1771
+ var MAX_PROBE_POINTS = 5e3;
1801
1772
  var AutoRigInputError = class extends Error {
1802
1773
  constructor(message) {
1803
1774
  super(message);
@@ -1854,12 +1825,14 @@ function confineToWorkingDirectory(root, dir, label, original) {
1854
1825
  }
1855
1826
  return realDir;
1856
1827
  }
1857
- function resolveOutputPath(outputPath) {
1828
+ function resolveOutputPath(outputPath, extension = ".iki") {
1858
1829
  if (typeof outputPath !== "string" || outputPath.trim() === "") {
1859
1830
  throw new AutoRigInputError("output path is empty");
1860
1831
  }
1861
- if (!outputPath.toLowerCase().endsWith(".iki")) {
1862
- throw new AutoRigInputError(`output path must end in .iki: ${outputPath}`);
1832
+ if (!outputPath.toLowerCase().endsWith(extension)) {
1833
+ throw new AutoRigInputError(
1834
+ `output path must end in ${extension}: ${outputPath}`
1835
+ );
1863
1836
  }
1864
1837
  const root = process.cwd();
1865
1838
  const resolved = import_node_path.default.resolve(root, outputPath);
@@ -1909,18 +1882,1111 @@ function writeFileAtomic(outPath, data) {
1909
1882
  import_node_fs.default.rmSync(tmp, { force: true });
1910
1883
  } catch {
1911
1884
  }
1912
- throw e;
1885
+ throw e;
1886
+ }
1887
+ } catch (e) {
1888
+ throw new AutoRigInputError(
1889
+ `write: ${e instanceof Error ? e.message : String(e)}`
1890
+ );
1891
+ }
1892
+ }
1893
+
1894
+ // src/bake-report.ts
1895
+ var BAKE_TOLERANCE_PX = 0.1;
1896
+ var BUG = "the rig and the engine disagree; report this as a bug in the packages";
1897
+ function checkBakes(model, reports) {
1898
+ const restOf = /* @__PURE__ */ new Map();
1899
+ for (const id of new Set(reports.map((r) => r.part))) {
1900
+ const rest = landParts(model, {}, [id]).get(id);
1901
+ const bare = landParts(
1902
+ {
1903
+ ...model,
1904
+ parts: model.parts.map(
1905
+ (p) => p.id === id ? { ...p, warps: void 0 } : p
1906
+ )
1907
+ },
1908
+ {},
1909
+ [id]
1910
+ ).get(id);
1911
+ let restGap = 0;
1912
+ for (let i = 0; i < rest.length; i++) {
1913
+ restGap = Math.max(restGap, Math.abs(rest[i] - bare[i]));
1914
+ }
1915
+ if (restGap >= BAKE_TOLERANCE_PX) {
1916
+ throw new AutoRigInputError(
1917
+ `BAKE ERROR ${id} at rest: the part moved ${restGap.toFixed(3)} px, where the bake must leave it (limit ${BAKE_TOLERANCE_PX} px); ${BUG}`
1918
+ );
1919
+ }
1920
+ restOf.set(id, rest);
1921
+ }
1922
+ return reports.map((r) => {
1923
+ const rest = restOf.get(r.part);
1924
+ let errorPx = 0;
1925
+ const asked = [
1926
+ ...r.stops.map((value, s) => ({ value, wanted: r.wanted[s] })),
1927
+ ...r.ends
1928
+ ];
1929
+ asked.forEach(({ value, wanted }) => {
1930
+ const posed = landParts(model, { [r.param]: value }, [r.part]).get(
1931
+ r.part
1932
+ );
1933
+ let worst = 0;
1934
+ let worstVertex = 0;
1935
+ for (let v = 0; v < r.vertexCount; v++) {
1936
+ const gap = Math.hypot(
1937
+ posed[v * 2] - rest[v * 2] - wanted[v * 2],
1938
+ -(posed[v * 2 + 1] - rest[v * 2 + 1]) - wanted[v * 2 + 1]
1939
+ );
1940
+ if (gap > worst) {
1941
+ worst = gap;
1942
+ worstVertex = v;
1943
+ }
1944
+ }
1945
+ if (worst >= BAKE_TOLERANCE_PX) {
1946
+ throw new AutoRigInputError(
1947
+ `BAKE ERROR ${r.part} ${r.param}=${value}: vertex ${worstVertex} lands ${worst.toFixed(3)} px from the displacement the bake asked for (limit ${BAKE_TOLERANCE_PX} px); ${BUG}`
1948
+ );
1949
+ }
1950
+ errorPx = Math.max(errorPx, worst);
1951
+ });
1952
+ return {
1953
+ part: r.part,
1954
+ param: r.param,
1955
+ vertices: r.vertexCount,
1956
+ stops: r.stops,
1957
+ errorPx
1958
+ };
1959
+ });
1960
+ }
1961
+
1962
+ // src/custom-gate.ts
1963
+ var import_editor3 = require("@ikijs/editor");
1964
+ var import_format9 = require("@ikijs/format");
1965
+
1966
+ // src/fold-report.ts
1967
+ var import_editor = require("@ikijs/editor");
1968
+ function checkModelFolds(model, extraValues = []) {
1969
+ const declared = new Set(model.parameters.map((p) => p.id));
1970
+ return checkFolds(model, {
1971
+ poses: [...foldPoses(model), ...extraValues.map(foldPose)],
1972
+ // The effective value, not the pose's overrides: the auto-rig's mouth
1973
+ // rests shut at its default, so `rest` and the other parameters' singles
1974
+ // are shut-mouth poses too.
1975
+ expected: (target2, _pose, value) => {
1976
+ if (target2.kind !== "part") return false;
1977
+ const shutBy = import_editor.SHUT_BY.get(target2.id);
1978
+ return shutBy !== void 0 && declared.has(shutBy) && value(shutBy) === 0;
1979
+ }
1980
+ });
1981
+ }
1982
+ function formatFoldReport(report, canvas) {
1983
+ const lines = report.offenders.length === 0 ? [`FOLDS: none over ${report.poses} poses`] : report.offenders.map((t) => offenderLine(t, t.worst, canvas));
1984
+ const closures = report.targets.flatMap((t) => {
1985
+ if (t.expected === void 0) return [];
1986
+ if (t.expected.ratio >= report.thresholds.collapse) return [];
1987
+ const shutBy = import_editor.SHUT_BY.get(t.target.id);
1988
+ const at = shutBy === void 0 ? "" : ` at ${shutBy}=0`;
1989
+ return [`${t.target.id} ${ratioText(t.expected.ratio)}${at}`];
1990
+ });
1991
+ if (closures.length > 0) {
1992
+ lines.push(
1993
+ `FOLDS expected: by-design closures, not findings \u2014 ${closures.join(", ")}`
1994
+ );
1995
+ }
1996
+ return lines;
1997
+ }
1998
+ function foldPose(values) {
1999
+ const ids = Object.keys(values).sort();
2000
+ const name = ids.length === 0 ? "rest" : ids.map((id) => `${id}=${values[id]}`).join(" ");
2001
+ return { name, values };
2002
+ }
2003
+ function offenderLine(t, hit, canvas) {
2004
+ const where = "triangle" in hit.where ? `triangle ${hit.where.triangle}` : `cell (${hit.where.col},${hit.where.row})`;
2005
+ const { x, y } = hit.rest;
2006
+ return `FOLD ${t.kind} ${t.target.kind} ${t.target.id} ${where} ratio ${ratioText(hit.ratio)} pose [${hit.pose.name}] rest at (${x.toFixed(1)}, ${y.toFixed(1)}) model space, (${(canvas.width / 2 + x).toFixed(0)}, ${(canvas.height / 2 - y).toFixed(0)}) model px from the top-left`;
2007
+ }
2008
+ function ratioText(ratio) {
2009
+ if (ratio === 0) return "0";
2010
+ return Math.abs(ratio) < 0.01 ? ratio.toExponential(1) : ratio.toFixed(2);
2011
+ }
2012
+
2013
+ // src/probe.ts
2014
+ var import_node_fs2 = require("fs");
2015
+ var import_format8 = require("@ikijs/format");
2016
+
2017
+ // src/node-images.ts
2018
+ var import_sharp = __toESM(require("sharp"));
2019
+ var import_editor2 = require("@ikijs/editor");
2020
+ async function decodePng(filePath) {
2021
+ try {
2022
+ const pipeline = (0, import_sharp.default)(filePath, { limitInputPixels: MAX_INPUT_PIXELS });
2023
+ const metadata = await pipeline.metadata();
2024
+ if (metadata.format !== "png") {
2025
+ throw new AutoRigInputError(
2026
+ `non-PNG image (${metadata.format ?? "unknown"}): ${filePath}`
2027
+ );
2028
+ }
2029
+ const { data, info } = await pipeline.ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2030
+ return {
2031
+ width: info.width,
2032
+ height: info.height,
2033
+ rgba: data,
2034
+ hasAlpha: metadata.hasAlpha ?? false
2035
+ };
2036
+ } catch (e) {
2037
+ if (e instanceof AutoRigInputError) throw e;
2038
+ const msg = e instanceof Error ? e.message : String(e);
2039
+ throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);
2040
+ }
2041
+ }
2042
+ function detectAlphaBbox(rgba, width, height) {
2043
+ const bbox = (0, import_editor2.detectAlphaBbox)(rgba, width, height);
2044
+ if (bbox === null) {
2045
+ throw new AutoRigInputError("layer is empty after alpha threshold");
2046
+ }
2047
+ return bbox;
2048
+ }
2049
+ function cropToBuffer(rgba, width, height, bbox) {
2050
+ 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();
2051
+ }
2052
+ function encodeOverlayPng(filePath, svg) {
2053
+ return (0, import_sharp.default)(filePath, { limitInputPixels: MAX_INPUT_PIXELS }).composite([{ input: Buffer.from(svg) }]).png().toBuffer();
2054
+ }
2055
+ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
2056
+ const byId = /* @__PURE__ */ new Map();
2057
+ for (const crop of crops) byId.set(crop.id, crop);
2058
+ const pad = layout.padding;
2059
+ const composites = await Promise.all(
2060
+ layout.placements.map(async (placement3) => {
2061
+ const crop = byId.get(placement3.id);
2062
+ if (crop === void 0) {
2063
+ throw new AutoRigInputError(
2064
+ `no crop for atlas placement "${placement3.id}"`
2065
+ );
2066
+ }
2067
+ const input = pad > 0 ? await (0, import_sharp.default)(crop.buffer).extend({ right: pad, bottom: pad, extendWith: "copy" }).png().toBuffer() : crop.buffer;
2068
+ return { input, left: placement3.x, top: placement3.y };
2069
+ })
2070
+ );
2071
+ const page = await (0, import_sharp.default)({
2072
+ create: {
2073
+ width: layout.pageWidth,
2074
+ height: layout.pageHeight,
2075
+ channels: 4,
2076
+ background: { r: 0, g: 0, b: 0, alpha: 0 }
2077
+ }
2078
+ }).composite(composites).png(
2079
+ quantizeColors === void 0 ? {} : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 }
2080
+ ).toBuffer();
2081
+ return `data:image/png;base64,${page.toString("base64")}`;
2082
+ }
2083
+
2084
+ // src/probe.ts
2085
+ var OUTPUT_SUFFIX = ".probe.json";
2086
+ var OPAQUE = 128;
2087
+ function paintRuns(png) {
2088
+ const { width, height, rgba } = png;
2089
+ const rows = [];
2090
+ let y0 = -1;
2091
+ for (let y = 0; y < height; y++) {
2092
+ const runs = [];
2093
+ let start = -1;
2094
+ for (let x = 0; x < width; x++) {
2095
+ const on = rgba[(y * width + x) * 4 + 3] >= OPAQUE;
2096
+ if (on && start < 0) start = x;
2097
+ if (!on && start >= 0) {
2098
+ runs.push([start, x]);
2099
+ start = -1;
2100
+ }
2101
+ }
2102
+ if (start >= 0) runs.push([start, width]);
2103
+ if (runs.length > 0 && y0 < 0) y0 = y;
2104
+ if (y0 >= 0) rows.push(runs);
2105
+ }
2106
+ while (rows.length > 0 && rows[rows.length - 1].length === 0) rows.pop();
2107
+ return rows.length === 0 ? { y0: 0, rows: [] } : { y0, rows };
2108
+ }
2109
+ function toCanvas(model, pts) {
2110
+ const hw = model.canvas.width / 2;
2111
+ const hh = model.canvas.height / 2;
2112
+ const out = new Float64Array(pts.length);
2113
+ for (let i = 0; i < pts.length; i += 2) {
2114
+ out[i] = hw + pts[i];
2115
+ out[i + 1] = hh - pts[i + 1];
2116
+ }
2117
+ return out;
2118
+ }
2119
+ var round = (v) => Math.round(v * 1e3) / 1e3 + 0;
2120
+ function locate(vertices, tri, x, y) {
2121
+ const [a, b, c] = tri;
2122
+ const ax = vertices[a * 2];
2123
+ const ay = vertices[a * 2 + 1];
2124
+ const bx = vertices[b * 2];
2125
+ const by = vertices[b * 2 + 1];
2126
+ const cx = vertices[c * 2];
2127
+ const cy = vertices[c * 2 + 1];
2128
+ const d = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy);
2129
+ if (Math.abs(d) < 1e-12) return null;
2130
+ const l1 = ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / d;
2131
+ const l2 = ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / d;
2132
+ const l3 = 1 - l1 - l2;
2133
+ const eps = 1e-9;
2134
+ return l1 >= -eps && l2 >= -eps && l3 >= -eps ? [l1, l2, l3] : null;
2135
+ }
2136
+ var QUAD_INDICES = [0, 1, 2, 1, 3, 2];
2137
+ function restMesh(model, cache, partId) {
2138
+ let m = cache.get(partId);
2139
+ if (m) return m;
2140
+ const part = model.parts.find((p) => p.id === partId);
2141
+ const indices = part.mesh ? part.mesh.indices : QUAD_INDICES;
2142
+ const rest = toCanvas(model, landParts(model, {}, [partId]).get(partId));
2143
+ const boxes = new Float64Array(indices.length / 3 * 4);
2144
+ for (let t = 0; t < indices.length / 3; t++) {
2145
+ let x0 = Infinity;
2146
+ let y0 = Infinity;
2147
+ let x1 = -Infinity;
2148
+ let y1 = -Infinity;
2149
+ for (let k = 0; k < 3; k++) {
2150
+ const v = indices[t * 3 + k];
2151
+ x0 = Math.min(x0, rest[v * 2]);
2152
+ x1 = Math.max(x1, rest[v * 2]);
2153
+ y0 = Math.min(y0, rest[v * 2 + 1]);
2154
+ y1 = Math.max(y1, rest[v * 2 + 1]);
2155
+ }
2156
+ boxes.set([x0, y0, x1, y1], t * 4);
2157
+ }
2158
+ m = { indices, rest, boxes };
2159
+ cache.set(partId, m);
2160
+ return m;
2161
+ }
2162
+ function locatePoints(mesh, points) {
2163
+ const { indices, rest, boxes } = mesh;
2164
+ const slack = 1e-6;
2165
+ return points.map(([x, y]) => {
2166
+ for (let t = 0; t < indices.length / 3; t++) {
2167
+ const b = t * 4;
2168
+ if (x < boxes[b] - slack || x > boxes[b + 2] + slack || y < boxes[b + 1] - slack || y > boxes[b + 3] + slack) {
2169
+ continue;
2170
+ }
2171
+ const tri = [
2172
+ indices[t * 3],
2173
+ indices[t * 3 + 1],
2174
+ indices[t * 3 + 2]
2175
+ ];
2176
+ const w = locate(rest, tri, x, y);
2177
+ if (w) return { tri, w };
2178
+ }
2179
+ return null;
2180
+ });
2181
+ }
2182
+ function landLocated(posed, at) {
2183
+ if (at === null) return null;
2184
+ let px2 = 0;
2185
+ let py = 0;
2186
+ for (let k = 0; k < 3; k++) {
2187
+ px2 += at.w[k] * posed[at.tri[k] * 2];
2188
+ py += at.w[k] * posed[at.tri[k] * 2 + 1];
2189
+ }
2190
+ return [px2, py];
2191
+ }
2192
+ function landPoints(model, cache, partId, points, pose) {
2193
+ const located = locatePoints(restMesh(model, cache, partId), points);
2194
+ const posed = toCanvas(model, landParts(model, pose, [partId]).get(partId));
2195
+ return located.map((at) => landLocated(posed, at));
2196
+ }
2197
+ function invalid(i, field, what) {
2198
+ return new AutoRigInputError(`queries[${i}].${field} ${what}`);
2199
+ }
2200
+ function checkPoints(i, points) {
2201
+ if (!Array.isArray(points) || points.length === 0) {
2202
+ throw invalid(i, "points", "must be a non-empty list of [x, y]");
2203
+ }
2204
+ if (points.length > MAX_PROBE_POINTS) {
2205
+ throw invalid(
2206
+ i,
2207
+ "points",
2208
+ `has ${points.length} points; at most ${MAX_PROBE_POINTS} per query`
2209
+ );
2210
+ }
2211
+ points.forEach((pt, k) => {
2212
+ if (!Array.isArray(pt) || pt.length !== 2 || !pt.every((v) => Number.isFinite(v))) {
2213
+ throw invalid(i, `points[${k}]`, "must be [x, y] with finite numbers");
2214
+ }
2215
+ });
2216
+ return points;
2217
+ }
2218
+ function checkPose(model, i, pose) {
2219
+ const declared = new Set(model.parameters.map((p) => p.id));
2220
+ for (const [id, v] of Object.entries(pose ?? {})) {
2221
+ if (!declared.has(id)) {
2222
+ throw invalid(i, `pose.${id}`, "is not a parameter the model declares");
2223
+ }
2224
+ if (typeof v !== "number" || !Number.isFinite(v)) {
2225
+ throw invalid(i, `pose.${id}`, "must be a finite number");
2226
+ }
2227
+ }
2228
+ return pose ?? {};
2229
+ }
2230
+ function checkQuery(model, q, i) {
2231
+ if (q.op === "paint") return { op: "paint", path: q.path };
2232
+ if (q.op !== "land" && q.op !== "displacement") {
2233
+ throw invalid(i, "op", `must be paint, land or displacement`);
2234
+ }
2235
+ if (!model.parts.some((p) => p.id === q.part)) {
2236
+ throw invalid(i, "part", `names no part of the model: ${String(q.part)}`);
2237
+ }
2238
+ return {
2239
+ op: q.op,
2240
+ part: q.part,
2241
+ points: checkPoints(i, q.points),
2242
+ pose: checkPose(model, i, q.pose)
2243
+ };
2244
+ }
2245
+ async function runQuery(model, cache, q, i) {
2246
+ if (q.op === "paint") {
2247
+ const file = resolveInputPath(q.path, `queries[${i}].path`);
2248
+ let png;
2249
+ try {
2250
+ png = await decodePng(file);
2251
+ } catch (e) {
2252
+ if (e instanceof AutoRigInputError) throw invalid(i, "path", e.message);
2253
+ throw e;
2254
+ }
2255
+ const { width, height } = model.canvas;
2256
+ if (png.width !== width || png.height !== height) {
2257
+ throw invalid(
2258
+ i,
2259
+ "path",
2260
+ `is ${png.width}x${png.height}, not the model's canvas ${width}x${height}: ${q.path}`
2261
+ );
2262
+ }
2263
+ return { op: "paint", ...paintRuns(png) };
2264
+ }
2265
+ const { points } = q;
2266
+ const landed = landPoints(model, cache, q.part, points, q.pose);
2267
+ return {
2268
+ op: q.op,
2269
+ part: q.part,
2270
+ points: landed.map(
2271
+ (l, k) => l === null ? null : q.op === "land" ? [round(l[0]), round(l[1])] : [round(l[0] - points[k][0]), round(l[1] - points[k][1])]
2272
+ )
2273
+ };
2274
+ }
2275
+ function summarize(r, i) {
2276
+ if (r.op === "paint") {
2277
+ return `${i} paint: ${r.rows.length} rows from y ${r.y0}`;
2278
+ }
2279
+ const off = r.points.filter((p) => p === null).length;
2280
+ return `${i} ${r.op} ${r.part}: ${r.points.length} points, ${off} off the mesh`;
2281
+ }
2282
+ async function probeRig(input) {
2283
+ try {
2284
+ const outFile = input.outputPath !== void 0 ? resolveOutputPath(input.outputPath, OUTPUT_SUFFIX) : void 0;
2285
+ const modelFile = confineToWorkingDirectory(
2286
+ process.cwd(),
2287
+ resolveInputPath(input.modelPath, "model"),
2288
+ "model path",
2289
+ input.modelPath
2290
+ );
2291
+ const model = (0, import_format8.loadIkiModel)((0, import_node_fs2.readFileSync)(modelFile, "utf8"));
2292
+ if (!Array.isArray(input.queries) || input.queries.length === 0) {
2293
+ throw new AutoRigInputError("queries must be a non-empty list");
2294
+ }
2295
+ if (input.queries.length > MAX_PROBE_QUERIES) {
2296
+ throw new AutoRigInputError(
2297
+ `queries has ${input.queries.length} entries; at most ${MAX_PROBE_QUERIES} per call`
2298
+ );
2299
+ }
2300
+ const checked = input.queries.map((q, i) => checkQuery(model, q, i));
2301
+ const cache = /* @__PURE__ */ new Map();
2302
+ const results = [];
2303
+ for (const [i, q] of checked.entries()) {
2304
+ results.push(await runQuery(model, cache, q, i));
2305
+ }
2306
+ if (outFile === void 0) return { ok: true, results };
2307
+ writeFileAtomic(outFile, JSON.stringify(results));
2308
+ return {
2309
+ ok: true,
2310
+ outputPath: outFile,
2311
+ lines: results.map(summarize)
2312
+ };
2313
+ } catch (e) {
2314
+ if (e instanceof AutoRigInputError || e instanceof import_format8.IkiFormatError) {
2315
+ return { ok: false, error: e.message };
2316
+ }
2317
+ throw e;
2318
+ }
2319
+ }
2320
+
2321
+ // src/custom-gate.ts
2322
+ var CUSTOM_GATE_LIMITS = {
2323
+ tie: 5e-3,
2324
+ slide: 0.1,
2325
+ onAnchor: 0.015,
2326
+ exposed: 9e-4,
2327
+ rigid: 25e-4
2328
+ };
2329
+ function foldLimit(model) {
2330
+ return checkFolds(model, { poses: [] }).thresholds.collapse;
2331
+ }
2332
+ function failedCustomGate(model, error) {
2333
+ const message = error instanceof Error ? error.message : String(error);
2334
+ return {
2335
+ ok: false,
2336
+ faceWidth: model.parts.find((p) => p.id === "face")?.width ?? 0,
2337
+ limits: { ...CUSTOM_GATE_LIMITS, fold: foldLimit(model) },
2338
+ poses: 0,
2339
+ parts: [],
2340
+ failed: [`gate error: ${message}`]
2341
+ };
2342
+ }
2343
+ function readingOf(faceWidth, amount, dimension, pose, limit, reason) {
2344
+ const value = amount === null ? null : amount / faceWidth ** dimension;
2345
+ const pass = value !== null && value <= limit;
2346
+ return {
2347
+ value,
2348
+ ...dimension === 1 ? { px: amount } : { px2: amount },
2349
+ pose,
2350
+ limit,
2351
+ pass,
2352
+ ...pass ? {} : { reason }
2353
+ };
2354
+ }
2355
+ var TWIN_FACE = 402;
2356
+ var RING_PX = 5;
2357
+ var RING_DIAGONAL_PX = 4;
2358
+ var SAMPLE_REACH_PX = 80;
2359
+ var SAMPLE_STEP_PX = 4;
2360
+ var TIP_INSET_PX = 6;
2361
+ var EXPOSED_REACH = 0.15;
2362
+ var runsAt = (paint, y) => paint.rows[y - paint.y0] ?? [];
2363
+ function paintedAt(paint, x, y) {
2364
+ const px2 = Math.floor(x);
2365
+ return runsAt(paint, Math.floor(y)).some(([a, b]) => px2 >= a && px2 < b);
2366
+ }
2367
+ var GRID_CELLS = 64;
2368
+ function triangleGrid(posed, indices, bounds) {
2369
+ const cell = Math.max(
2370
+ 16,
2371
+ (bounds.x1 - bounds.x0) / GRID_CELLS,
2372
+ (bounds.y1 - bounds.y0) / GRID_CELLS
2373
+ );
2374
+ const cols = Math.floor((bounds.x1 - bounds.x0) / cell) + 1;
2375
+ const rows = Math.floor((bounds.y1 - bounds.y0) / cell) + 1;
2376
+ const bins = /* @__PURE__ */ new Map();
2377
+ for (let t = 0; t < indices.length / 3; t++) {
2378
+ let x0 = Infinity;
2379
+ let y0 = Infinity;
2380
+ let x1 = -Infinity;
2381
+ let y1 = -Infinity;
2382
+ for (let k = 0; k < 3; k++) {
2383
+ const v = indices[t * 3 + k];
2384
+ x0 = Math.min(x0, posed[v * 2]);
2385
+ x1 = Math.max(x1, posed[v * 2]);
2386
+ y0 = Math.min(y0, posed[v * 2 + 1]);
2387
+ y1 = Math.max(y1, posed[v * 2 + 1]);
2388
+ }
2389
+ if (x1 < bounds.x0 || x0 > bounds.x1 || y1 < bounds.y0 || y0 > bounds.y1) {
2390
+ continue;
2391
+ }
2392
+ const cx0 = Math.max(0, Math.floor((x0 - bounds.x0) / cell));
2393
+ const cx1 = Math.min(cols - 1, Math.floor((x1 - bounds.x0) / cell));
2394
+ const cy0 = Math.max(0, Math.floor((y0 - bounds.y0) / cell));
2395
+ const cy1 = Math.min(rows - 1, Math.floor((y1 - bounds.y0) / cell));
2396
+ for (let cy = cy0; cy <= cy1; cy++) {
2397
+ for (let cx = cx0; cx <= cx1; cx++) {
2398
+ const k = cx + cy * cols;
2399
+ const bin = bins.get(k);
2400
+ if (bin) bin.push(t);
2401
+ else bins.set(k, [t]);
2402
+ }
2403
+ }
2404
+ }
2405
+ return (x, y) => x < bounds.x0 || y < bounds.y0 || x > bounds.x1 || y > bounds.y1 ? [] : bins.get(
2406
+ Math.floor((x - bounds.x0) / cell) + Math.floor((y - bounds.y0) / cell) * cols
2407
+ ) ?? [];
2408
+ }
2409
+ function paintedUnder(posed, mesh, paint, points) {
2410
+ if (points.length === 0) return [];
2411
+ const bounds = { x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity };
2412
+ for (const [x, y] of points) {
2413
+ bounds.x0 = Math.min(bounds.x0, x);
2414
+ bounds.y0 = Math.min(bounds.y0, y);
2415
+ bounds.x1 = Math.max(bounds.x1, x);
2416
+ bounds.y1 = Math.max(bounds.y1, y);
2417
+ }
2418
+ const find = triangleGrid(posed, mesh.indices, bounds);
2419
+ return points.map(([x, y]) => {
2420
+ for (const t of find(x, y)) {
2421
+ const tri = [
2422
+ mesh.indices[t * 3],
2423
+ mesh.indices[t * 3 + 1],
2424
+ mesh.indices[t * 3 + 2]
2425
+ ];
2426
+ const w = locate(posed, tri, x, y);
2427
+ if (!w) continue;
2428
+ let rx = 0;
2429
+ let ry = 0;
2430
+ for (let k = 0; k < 3; k++) {
2431
+ rx += w[k] * mesh.rest[tri[k] * 2];
2432
+ ry += w[k] * mesh.rest[tri[k] * 2 + 1];
2433
+ }
2434
+ return paintedAt(paint, rx, ry);
2435
+ }
2436
+ return false;
2437
+ });
2438
+ }
2439
+ function hiddenSide(occlusion, from, direction) {
2440
+ const at = (v) => occlusionAmount(occlusion, v);
2441
+ const rest = at(from);
2442
+ const marks = occlusion.stops.map((s) => s.value).filter((v) => (v - from) * direction > 0).sort((a, b) => (a - b) * direction);
2443
+ const run2 = [from, ...marks];
2444
+ let leaves = null;
2445
+ let full = rest === 1 ? from : null;
2446
+ for (let i = 0; i + 1 < run2.length; i++) {
2447
+ if (leaves === null && at(run2[i + 1]) !== rest) leaves = run2[i];
2448
+ if (full === null && at(run2[i + 1]) === 1) full = run2[i + 1];
2449
+ }
2450
+ return { leaves, full };
2451
+ }
2452
+ function posesOf(model, baked, base) {
2453
+ const byName = new Map(base.map((p) => [p.name, p]));
2454
+ const add = (values) => {
2455
+ const pose = foldPose(values);
2456
+ if (!byName.has(pose.name)) byName.set(pose.name, pose);
2457
+ };
2458
+ const defaults = new Map(model.parameters.map((p) => [p.id, p.default]));
2459
+ for (const [param, stops] of baked) {
2460
+ for (const v of stops) if (v !== defaults.get(param)) add({ [param]: v });
2461
+ }
2462
+ const params = [...baked.keys()];
2463
+ for (let i = 0; i < params.length; i++) {
2464
+ for (let j = i + 1; j < params.length; j++) {
2465
+ for (const a of baked.get(params[i])) {
2466
+ if (a === defaults.get(params[i])) continue;
2467
+ for (const b of baked.get(params[j])) {
2468
+ if (b === defaults.get(params[j])) continue;
2469
+ add({ [params[i]]: a, [params[j]]: b });
2470
+ }
2471
+ }
2472
+ }
2473
+ }
2474
+ return [...byName.values()];
2475
+ }
2476
+ function freeEnd(paint, tie, inset) {
2477
+ if (paint.rows.length === 0) return null;
2478
+ const [top, bottom] = [paint.y0, paint.y0 + paint.rows.length - 1];
2479
+ const y = Math.abs(bottom - tie[1]) > Math.abs(top - tie[1]) ? bottom : top;
2480
+ const runs = runsAt(paint, y);
2481
+ if (runs.length === 0) return null;
2482
+ const widest = runs.reduce((a, b) => b[1] - b[0] > a[1] - a[0] ? b : a);
2483
+ return [(widest[0] + widest[1]) / 2, y > tie[1] ? y - inset : y + inset];
2484
+ }
2485
+ function checkCustomGate(model, parts, paints, options = {}) {
2486
+ const face = model.parts.find((p) => p.id === "face");
2487
+ if (face === void 0) throw new Error("custom gate: the model has no face");
2488
+ const faceWidth = face.width;
2489
+ const limits = {
2490
+ ...CUSTOM_GATE_LIMITS,
2491
+ fold: foldLimit(model)
2492
+ };
2493
+ if (parts.length === 0) {
2494
+ return {
2495
+ ok: true,
2496
+ faceWidth,
2497
+ limits,
2498
+ poses: 0,
2499
+ parts: [],
2500
+ failed: []
2501
+ };
2502
+ }
2503
+ const scale2 = faceWidth / TWIN_FACE;
2504
+ const px2 = (twin) => Math.max(1, Math.round(twin * scale2));
2505
+ const cache = /* @__PURE__ */ new Map();
2506
+ const turnParam = model.parameters.find(
2507
+ (p) => p.id === import_format9.StandardParameter.AngleX
2508
+ );
2509
+ const turns = (pose) => turnParam !== void 0 && (pose.values[import_format9.StandardParameter.AngleX] ?? turnParam.default) !== turnParam.default;
2510
+ const bakedOf = (id) => {
2511
+ const part = model.parts.find((p) => p.id === id);
2512
+ return new Map(
2513
+ (part.warps ?? []).map((w) => [
2514
+ w.parameter,
2515
+ w.keyforms.map((k) => k.value)
2516
+ ])
2517
+ );
2518
+ };
2519
+ const base = options.poses ?? foldPoses(model);
2520
+ const poseSets = parts.map((part) => {
2521
+ if (!model.parts.some((p) => p.id === part.id)) {
2522
+ throw new Error(`custom gate: the model has no part "${part.id}"`);
2523
+ }
2524
+ if (options.poses) return options.poses;
2525
+ const sampledOf = bakedOf(part.id);
2526
+ const occ = model.parts.find((p) => p.id === part.id).occlusion;
2527
+ if (occ !== void 0) {
2528
+ const at = sampledOf.get(occ.parameter) ?? [];
2529
+ sampledOf.set(occ.parameter, [
2530
+ .../* @__PURE__ */ new Set([...at, ...occ.stops.map((s) => s.value)])
2531
+ ]);
2532
+ }
2533
+ return posesOf(model, sampledOf, base);
2534
+ });
2535
+ const all = new Map(poseSets.flat().map((p) => [p.name, p]));
2536
+ const reports = parts.map((part, n) => {
2537
+ const poses = poseSets[n];
2538
+ const roleParts = (0, import_editor3.partIdsOfRole)(part.anchor).filter(
2539
+ (id) => model.parts.some((p) => p.id === id)
2540
+ );
2541
+ const anchorId = roleParts.find(
2542
+ (id) => locatePoints(restMesh(model, cache, id), [part.tie])[0] !== null
2543
+ ) ?? roleParts[0];
2544
+ const folds = checkFolds(model, { poses });
2545
+ const anchorPart = model.parts.find((p) => p.id === anchorId);
2546
+ if (anchorPart === void 0) {
2547
+ throw new Error(`custom gate: the model has no part "${anchorId}"`);
2548
+ }
2549
+ const ownPaint = paints.get(part.id);
2550
+ const anchorPaint = paints.get(part.anchor);
2551
+ if (ownPaint === void 0 || anchorPaint === void 0) {
2552
+ throw new Error(
2553
+ `custom gate: no paint for "${ownPaint === void 0 ? part.id : part.anchor}"`
2554
+ );
2555
+ }
2556
+ const partMesh = restMesh(model, cache, part.id);
2557
+ const anchorMesh = restMesh(model, cache, anchorId);
2558
+ const length = (amount, pose, limit, reason) => readingOf(faceWidth, amount, 1, pose, limit, reason);
2559
+ const ring = [
2560
+ [0, 0],
2561
+ [px2(RING_PX), 0],
2562
+ [-px2(RING_PX), 0],
2563
+ [0, px2(RING_PX)],
2564
+ [0, -px2(RING_PX)],
2565
+ [px2(RING_DIAGONAL_PX), px2(RING_DIAGONAL_PX)],
2566
+ [-px2(RING_DIAGONAL_PX), px2(RING_DIAGONAL_PX)],
2567
+ [px2(RING_DIAGONAL_PX), -px2(RING_DIAGONAL_PX)],
2568
+ [-px2(RING_DIAGONAL_PX), -px2(RING_DIAGONAL_PX)]
2569
+ ].map(([dx, dy]) => [part.tie[0] + dx, part.tie[1] + dy]);
2570
+ const onPart = locatePoints(partMesh, ring);
2571
+ const onAnchor = locatePoints(anchorMesh, ring);
2572
+ const shared = ring.flatMap(
2573
+ (_, i) => onPart[i] && onAnchor[i] ? [i] : []
2574
+ );
2575
+ const reach = px2(SAMPLE_REACH_PX);
2576
+ const step = px2(SAMPLE_STEP_PX);
2577
+ const samples = [];
2578
+ const cx = Math.round(part.tie[0]);
2579
+ const cy = Math.round(part.tie[1]);
2580
+ for (let y = cy - reach; y <= cy + reach; y += step) {
2581
+ const runs = runsAt(anchorPaint, y);
2582
+ for (let x = cx - reach; x <= cx + reach; x += step) {
2583
+ if (runs.some(([a, b]) => x >= a && x < b))
2584
+ samples.push([x + 0.5, y + 0.5]);
2585
+ }
2586
+ }
2587
+ const samplesOn = locatePoints(anchorMesh, samples).filter(
2588
+ (l) => l !== null
2589
+ );
2590
+ const [tieOnPart] = locatePoints(partMesh, [part.tie]);
2591
+ const partIndex = model.parts.findIndex((p) => p.id === part.id);
2592
+ const anchorIndex = model.parts.indexOf(anchorPart);
2593
+ const ownPart = model.parts[partIndex];
2594
+ const partLower = ownPart.order < anchorPart.order || ownPart.order === anchorPart.order && partIndex < anchorIndex;
2595
+ const [lowerId, upperId] = partLower ? [part.id, anchorId] : [anchorId, part.id];
2596
+ const [lowerMesh, upperMesh] = [
2597
+ restMesh(model, cache, lowerId),
2598
+ restMesh(model, cache, upperId)
2599
+ ];
2600
+ const upperPaint = partLower ? anchorPaint : ownPaint;
2601
+ const exposedReach = Math.round(EXPOSED_REACH * faceWidth);
2602
+ const hidden = [];
2603
+ for (let y = Math.floor(part.tie[1]) - exposedReach; y <= Math.ceil(part.tie[1]) + exposedReach; y++) {
2604
+ for (const [a0, a1] of runsAt(ownPaint, y)) {
2605
+ for (const [b0, b1] of runsAt(anchorPaint, y)) {
2606
+ for (let x = Math.max(a0, b0); x < Math.min(a1, b1); x++) {
2607
+ if (Math.hypot(x + 0.5 - part.tie[0], y + 0.5 - part.tie[1]) <= exposedReach) {
2608
+ hidden.push([x + 0.5, y + 0.5]);
2609
+ }
2610
+ }
2611
+ }
2612
+ }
2613
+ }
2614
+ const onAnchorMesh = locatePoints(anchorMesh, hidden);
2615
+ const hiddenOn = locatePoints(lowerMesh, hidden).filter(
2616
+ (l, i) => l !== null && onAnchorMesh[i] !== null
2617
+ );
2618
+ const occlusion = ownPart.occlusion;
2619
+ const coverParts = [];
2620
+ if (occlusion !== void 0) {
2621
+ for (const role of part.occludedBy ?? []) {
2622
+ for (const id of (0, import_editor3.partIdsOfRole)(role)) {
2623
+ const o = model.parts.find((p) => p.id === id);
2624
+ if (o === void 0 || !occlusion.by.includes(id)) continue;
2625
+ const steady = o.color[3] === 1 && (o.transform.opacity ?? 1) >= 1 && !(o.bindings ?? []).some((b) => b.channel === "opacity");
2626
+ if (!steady) continue;
2627
+ const paint = paints.get(role);
2628
+ if (paint === void 0) {
2629
+ throw new Error(`custom gate: no paint for "${role}"`);
2630
+ }
2631
+ coverParts.push({ id, mesh: restMesh(model, cache, id), paint });
2632
+ }
2633
+ }
2634
+ }
2635
+ const coverIds = new Set(coverParts.map((c) => c.id));
2636
+ const keyParam = occlusion === void 0 ? void 0 : model.parameters.find((p) => p.id === occlusion.parameter);
2637
+ const keyOf = (values) => Math.min(
2638
+ keyParam.max,
2639
+ Math.max(keyParam.min, values[keyParam.id] ?? keyParam.default)
2640
+ );
2641
+ const sampled = keyParam === void 0 ? [] : [
2642
+ .../* @__PURE__ */ new Set([
2643
+ keyParam.default,
2644
+ ...poses.map((p) => keyOf(p.values))
2645
+ ])
2646
+ ].sort((a, b) => a - b);
2647
+ const fullyHidden = (lo, hi) => occlusion.stops.every(
2648
+ (st) => st.value <= lo || st.value >= hi || st.amount === 1
2649
+ ) && occlusionAmount(occlusion, lo) === 1 && occlusionAmount(occlusion, hi) === 1;
2650
+ const hiddenAt = (v) => fullyHidden(
2651
+ sampled.filter((x) => x < v).at(-1) ?? v,
2652
+ sampled.find((x) => x > v) ?? v
2653
+ );
2654
+ let leftOut = 0;
2655
+ let leftOutTurning = 0;
2656
+ let readNoTurn = 0;
2657
+ const stops = bakedOf(part.id);
2658
+ const worstOf = {
2659
+ tie: { v: -1, pose: "rest" },
2660
+ slide: { v: -1, pose: "rest" },
2661
+ onAnchor: { v: -1, pose: "rest" },
2662
+ exposed: { v: -1, pose: "rest" },
2663
+ exposedTurn: { v: -1, pose: "rest" },
2664
+ rigid: { v: -1, pose: "rest" }
2665
+ };
2666
+ const keep = (w, v, pose) => {
2667
+ if (v > w.v) {
2668
+ w.v = v;
2669
+ w.pose = pose;
2670
+ }
2671
+ };
2672
+ let onAnchorNull = null;
2673
+ let turningPoses = 0;
2674
+ const rest = partMesh.rest;
2675
+ const restPoints = [];
2676
+ for (let i = 0; i < rest.length; i += 2)
2677
+ restPoints.push([rest[i], rest[i + 1]]);
2678
+ const measureRigid = (pose, posed) => {
2679
+ const moved = [];
2680
+ for (let i = 0; i < posed.length; i += 2)
2681
+ moved.push([posed[i], posed[i + 1]]);
2682
+ keep(worstOf.rigid, (0, import_editor3.rigidResidual)(restPoints, moved), pose.name);
2683
+ };
2684
+ for (const pose of poses) {
2685
+ const hiding = occlusion !== void 0 && hiddenAt(keyOf(pose.values));
2686
+ const landed = landParts(model, pose.values, [
2687
+ .../* @__PURE__ */ new Set([
2688
+ part.id,
2689
+ anchorId,
2690
+ ...hiding && coverIds.size > 0 ? coverIds : []
2691
+ ])
2692
+ ]);
2693
+ const partPosed = toCanvas(model, landed.get(part.id));
2694
+ const anchorPosed = toCanvas(model, landed.get(anchorId));
2695
+ const canvasOf = /* @__PURE__ */ new Map();
2696
+ const underCover = (points, skip) => {
2697
+ const covered = points.map(() => false);
2698
+ if (!hiding) return covered;
2699
+ for (const c of coverParts) {
2700
+ if (c.id === skip) continue;
2701
+ let posed = canvasOf.get(c.id);
2702
+ if (posed === void 0) {
2703
+ posed = toCanvas(model, landed.get(c.id));
2704
+ canvasOf.set(c.id, posed);
2705
+ }
2706
+ const under = paintedUnder(posed, c.mesh, c.paint, points);
2707
+ under.forEach((u, i) => {
2708
+ if (u) covered[i] = true;
2709
+ });
2710
+ }
2711
+ return covered;
2712
+ };
2713
+ const turning = turns(pose);
2714
+ const ringLands = onPart.map(
2715
+ (l) => l === null ? null : landLocated(partPosed, l)
2716
+ );
2717
+ const ringHidden = hiding && ringLands.every((p) => p !== null) && underCover(ringLands).every(Boolean);
2718
+ if (ringHidden) {
2719
+ leftOut++;
2720
+ if (turning) leftOutTurning++;
2721
+ } else if (turning) turningPoses++;
2722
+ else readNoTurn++;
2723
+ let gap = 0;
2724
+ for (const i of shared) {
2725
+ const a = landLocated(partPosed, onPart[i]);
2726
+ const b = landLocated(anchorPosed, onAnchor[i]);
2727
+ gap = Math.max(gap, Math.hypot(a[0] - b[0], a[1] - b[1]));
2728
+ }
2729
+ if (shared.length > 0 && !ringHidden) {
2730
+ keep(turning ? worstOf.slide : worstOf.tie, gap, pose.name);
2731
+ }
2732
+ if (turning && !ringHidden) {
2733
+ const at = landLocated(partPosed, tieOnPart);
2734
+ let nearest = null;
2735
+ if (at !== null) {
2736
+ for (const l of samplesOn) {
2737
+ const q = landLocated(anchorPosed, l);
2738
+ const d = Math.hypot(q[0] - at[0], q[1] - at[1]);
2739
+ if (nearest === null || d < nearest) nearest = d;
2740
+ }
2741
+ }
2742
+ if (nearest === null) onAnchorNull ??= pose.name;
2743
+ else keep(worstOf.onAnchor, nearest, pose.name);
2744
+ }
2745
+ if (hiddenOn.length > 0) {
2746
+ const lowerPosed = lowerId === part.id ? partPosed : anchorPosed;
2747
+ const upperPosed = upperId === part.id ? partPosed : anchorPosed;
2748
+ const lands = hiddenOn.map((l) => landLocated(lowerPosed, l));
2749
+ const underUpper = paintedUnder(
2750
+ upperPosed,
2751
+ upperMesh,
2752
+ upperPaint,
2753
+ lands
2754
+ );
2755
+ const underHider = coverIds.has(lowerId) ? lands.map(() => hiding) : underCover(lands, upperId);
2756
+ let showing = 0;
2757
+ lands.forEach((_, i) => {
2758
+ if (!underUpper[i] && !underHider[i]) showing++;
2759
+ });
2760
+ keep(
2761
+ turning ? worstOf.exposedTurn : worstOf.exposed,
2762
+ showing,
2763
+ pose.name
2764
+ );
2765
+ }
2766
+ if (part.rigid) measureRigid(pose, partPosed);
2767
+ }
2768
+ if (part.rigid) {
2769
+ for (const [param, values] of stops) {
2770
+ const def = model.parameters.find((p) => p.id === param).default;
2771
+ const sorted = [.../* @__PURE__ */ new Set([...values, def])].sort((a, b) => a - b);
2772
+ for (let i = 0; i + 1 < sorted.length; i++) {
2773
+ const mid = foldPose({ [param]: (sorted[i] + sorted[i + 1]) / 2 });
2774
+ const posed = landParts(model, mid.values, [part.id]).get(part.id);
2775
+ measureRigid(mid, toCanvas(model, posed));
2776
+ }
2777
+ }
1913
2778
  }
1914
- } catch (e) {
1915
- throw new AutoRigInputError(
1916
- `write: ${e instanceof Error ? e.message : String(e)}`
2779
+ const tieReading = shared.length === 0 ? length(
2780
+ null,
2781
+ "rest",
2782
+ limits.tie,
2783
+ `no point of the ring around the tie lies on both ${part.id} and ${anchorId}`
2784
+ ) : length(
2785
+ Math.max(0, worstOf.tie.v),
2786
+ worstOf.tie.pose,
2787
+ limits.tie,
2788
+ "the tie comes apart"
2789
+ );
2790
+ const slideReading = length(
2791
+ Math.max(0, worstOf.slide.v),
2792
+ worstOf.slide.pose,
2793
+ limits.slide,
2794
+ "the tie slides too far"
2795
+ );
2796
+ const onAnchorReading = onAnchorNull !== null ? length(
2797
+ null,
2798
+ onAnchorNull,
2799
+ limits.onAnchor,
2800
+ `the tie lands off ${part.id}'s mesh, or no painted point of ${anchorId} near it is on its mesh`
2801
+ ) : length(
2802
+ Math.max(0, worstOf.onAnchor.v),
2803
+ worstOf.onAnchor.pose,
2804
+ limits.onAnchor,
2805
+ `the tie leaves ${anchorId}'s paint`
2806
+ );
2807
+ const exposedReading = readingOf(
2808
+ faceWidth,
2809
+ Math.max(0, worstOf.exposed.v),
2810
+ 2,
2811
+ worstOf.exposed.pose,
2812
+ limits.exposed,
2813
+ "hidden art shows"
2814
+ );
2815
+ const ratioHit = folds.targets.find(
2816
+ (t) => t.target.kind === "part" && t.target.id === part.id
2817
+ )?.worst;
2818
+ const ratio = ratioHit?.ratio ?? 1;
2819
+ const foldsPass = ratio >= limits.fold;
2820
+ const rigidReading = part.rigid ? length(
2821
+ Math.max(0, worstOf.rigid.v),
2822
+ worstOf.rigid.pose,
2823
+ limits.rigid,
2824
+ "the part bends"
2825
+ ) : void 0;
2826
+ const tipAt = freeEnd(ownPaint, part.tie, px2(TIP_INSET_PX));
2827
+ const [tipLoc] = tipAt === null ? [null] : locatePoints(partMesh, [tipAt]);
2828
+ const bareModel = stops.size === 0 ? model : {
2829
+ ...model,
2830
+ parts: model.parts.map(
2831
+ (p) => p.id === part.id ? { ...p, warps: void 0 } : p
2832
+ )
2833
+ };
2834
+ const tip = [...stops.keys()].map((param) => {
2835
+ const def = model.parameters.find((p) => p.id === param);
2836
+ const ends = [def.min, def.max].map((value) => {
2837
+ const at = (m) => landLocated(
2838
+ toCanvas(
2839
+ m,
2840
+ landParts(m, { [param]: value }, [part.id]).get(part.id)
2841
+ ),
2842
+ tipLoc ?? null
2843
+ );
2844
+ const landed = at(model);
2845
+ const bare = at(bareModel);
2846
+ return {
2847
+ value,
2848
+ landed,
2849
+ bare,
2850
+ fromBare: landed && bare ? Math.hypot(landed[0] - bare[0], landed[1] - bare[1]) : null
2851
+ };
2852
+ });
2853
+ const [a, b] = ends;
2854
+ return {
2855
+ param,
2856
+ ends,
2857
+ travel: a.landed && b.landed ? Math.hypot(b.landed[0] - a.landed[0], b.landed[1] - a.landed[1]) : null
2858
+ };
2859
+ });
2860
+ const turningExposed = worstOf.exposedTurn.v < 0 ? null : (({ value, px2: px22, pose }) => ({ value, px2: px22, pose }))(
2861
+ readingOf(
2862
+ faceWidth,
2863
+ worstOf.exposedTurn.v,
2864
+ 2,
2865
+ worstOf.exposedTurn.pose,
2866
+ Infinity,
2867
+ ""
2868
+ )
2869
+ );
2870
+ const slidePass = slideReading.pass && onAnchorReading.pass;
2871
+ const ok = foldsPass && tieReading.pass && slidePass && exposedReading.pass && (rigidReading?.pass ?? true);
2872
+ return {
2873
+ id: part.id,
2874
+ anchor: part.anchor,
2875
+ folds: {
2876
+ ratio,
2877
+ pose: ratioHit?.pose.name ?? "rest",
2878
+ limit: limits.fold,
2879
+ pass: foldsPass,
2880
+ ...foldsPass ? {} : { reason: ratio <= 0 ? "a flip" : "a collapse" }
2881
+ },
2882
+ tie: tieReading,
2883
+ slide: {
2884
+ slide: slideReading,
2885
+ onAnchor: onAnchorReading,
2886
+ turningPoses,
2887
+ pass: slidePass
2888
+ },
2889
+ exposed: {
2890
+ hiddenPx: hiddenOn.length,
2891
+ noTurn: exposedReading,
2892
+ turning: turningExposed,
2893
+ pass: exposedReading.pass
2894
+ },
2895
+ ...rigidReading === void 0 ? {} : { rigid: rigidReading },
2896
+ tip,
2897
+ ...occlusion === void 0 ? {} : {
2898
+ hidden: {
2899
+ by: occlusion.by,
2900
+ cover: [...coverIds],
2901
+ parameter: occlusion.parameter,
2902
+ default: keyParam.default,
2903
+ atRest: occlusionAmount(occlusion, keyParam.default),
2904
+ below: hiddenSide(occlusion, keyParam.default, -1),
2905
+ above: hiddenSide(occlusion, keyParam.default, 1),
2906
+ leftOut,
2907
+ leftOutTurning,
2908
+ readNoTurn,
2909
+ poses: poses.length
2910
+ }
2911
+ },
2912
+ ok
2913
+ };
2914
+ });
2915
+ const failed = reports.flatMap((r) => [
2916
+ ...r.folds.pass ? [] : [`${r.id} FOLDS`],
2917
+ ...r.tie.pass ? [] : [`${r.id} TIE`],
2918
+ ...r.slide.pass ? [] : [`${r.id} SLIDE`],
2919
+ ...r.exposed.pass ? [] : [`${r.id} EXPOSED`],
2920
+ ...r.rigid === void 0 || r.rigid.pass ? [] : [`${r.id} RIGID`]
2921
+ ]);
2922
+ return {
2923
+ ok: failed.length === 0,
2924
+ faceWidth,
2925
+ limits,
2926
+ poses: all.size,
2927
+ parts: reports,
2928
+ failed
2929
+ };
2930
+ }
2931
+ var both = (faceWidth, px2, digits = 4) => px2 === null ? "off the mesh" : `${px2.toFixed(1)} px (${(px2 / faceWidth).toFixed(digits)} face widths)`;
2932
+ function formatCustomGate(report) {
2933
+ const w = report.faceWidth;
2934
+ const verdict = (pass, reason) => pass ? "pass" : `FAIL: ${reason}`;
2935
+ const limit = (fw) => `${fw} face widths, ${(fw * w).toFixed(1)} px`;
2936
+ const lines = [];
2937
+ for (const r of report.parts) {
2938
+ const at = `CUSTOM ${r.id}`;
2939
+ lines.push(
2940
+ `${at} FOLDS: least triangle area ratio ${r.folds.ratio.toFixed(3)} at [${r.folds.pose}] (limit >= ${r.folds.limit}) ${verdict(r.folds.pass, r.folds.reason)}`
2941
+ );
2942
+ const noTurnLeftOut = r.hidden !== void 0 && r.hidden.readNoTurn === 0 && r.hidden.leftOut > r.hidden.leftOutTurning;
2943
+ lines.push(
2944
+ noTurnLeftOut ? `${at} TIE: every pose that does not turn the head is left out as hidden (see HIDDEN) ${verdict(r.tie.pass, r.tie.reason)}` : `${at} TIE: at the tie and the ring around it, ${r.id} against ${r.anchor}, poses that do not turn the head: max ${both(w, r.tie.px)} at [${r.tie.pose}] (limit <= ${limit(r.tie.limit)}) ${verdict(r.tie.pass, r.tie.reason)}`
2945
+ );
2946
+ const s = r.slide;
2947
+ lines.push(
2948
+ s.turningPoses === 0 ? r.hidden !== void 0 && r.hidden.leftOutTurning > 0 ? `${at} SLIDE: every pose that turns the head is left out as hidden (see HIDDEN) pass` : `${at} SLIDE: no pose turns the head pass` : `${at} SLIDE: poses that turn the head, the same length: max ${both(w, s.slide.px)} at [${s.slide.pose}] (limit <= ${limit(s.slide.limit)}); the tie's distance to the nearest painted point of ${r.anchor} as landed: max ${both(w, s.onAnchor.px)} at [${s.onAnchor.pose}] (limit <= ${limit(s.onAnchor.limit)}) ${verdict(s.pass, s.slide.pass ? s.onAnchor.reason : s.slide.reason)}`
2949
+ );
2950
+ const e = r.exposed;
2951
+ const turnText = e.turning === null ? "no pose turns the head" : `max ${e.turning.px2.toFixed(0)} px\xB2 (${e.turning.value.toFixed(5)} face widths\xB2) at [${e.turning.pose}] (reported, no limit)`;
2952
+ lines.push(
2953
+ `${at} EXPOSED: ${e.hiddenPx} px of art both ${r.id} and ${r.anchor} paint near the tie, the lower one's hidden at rest; showing where the head does not turn: max ${(e.noTurn.px2 ?? 0).toFixed(0)} px\xB2 (${(e.noTurn.value ?? 0).toFixed(5)} face widths\xB2) at [${e.noTurn.pose}] (limit <= ${e.noTurn.limit} face widths\xB2, ${(e.noTurn.limit * w * w).toFixed(0)} px\xB2) ${verdict(e.pass, e.noTurn.reason)}; where it turns: ${turnText}`
1917
2954
  );
2955
+ if (r.hidden) {
2956
+ const h = r.hidden;
2957
+ const side = (name, s2) => h.atRest === 1 ? `${name} ${h.default} the amount is 1 at rest and ${s2.leaves === null ? "stays 1" : `leaves it at ${s2.leaves}`}` : `${name} ${h.default} the amount ${s2.leaves === null ? `never leaves ${h.atRest}` : `leaves ${h.atRest} at ${s2.leaves}`} and ${s2.full === null ? "never reaches 1" : `reaches 1 at ${s2.full}`}`;
2958
+ lines.push(
2959
+ `${at} HIDDEN: hidden by ${h.by.join(",")} on ${h.parameter}, cover from ${h.cover.length === 0 ? "none of them" : h.cover.join(",")}${h.cover.length === h.by.length ? "" : " (the rest fade or are roles not passed, and give none)"}; amount ${h.atRest} at rest; ${side("below", h.below)}; ${side("above", h.above)}; left out of TIE and SLIDE: ${h.leftOut} of ${h.poses} poses (reported, no limit)`
2960
+ );
2961
+ }
2962
+ if (r.rigid) {
2963
+ lines.push(
2964
+ `${at} RIGID: bend against rest: max ${both(w, r.rigid.px)} at [${r.rigid.pose}] (limit <= ${limit(r.rigid.limit)}) ${verdict(r.rigid.pass, r.rigid.reason)}`
2965
+ );
2966
+ }
2967
+ for (const t of r.tip) {
2968
+ const ends = t.ends.map(
2969
+ (x) => `${t.param}=${x.value} lands ${x.landed ? `(${x.landed.map((v) => v.toFixed(1)).join(", ")})` : "off the mesh"}, ${x.fromBare === null ? "-" : both(w, x.fromBare)} from where its deformer alone lands it`
2970
+ ).join("; ");
2971
+ lines.push(
2972
+ `${at} TIP ${t.param}: free end ${ends}; travel end to end ${t.travel === null ? "-" : both(w, t.travel)} (reported, no limit)`
2973
+ );
2974
+ }
1918
2975
  }
2976
+ lines.push(
2977
+ report.ok ? "CUSTOM GATE pass" : `CUSTOM GATE FAIL: ${report.failed.join(", ")}`
2978
+ );
2979
+ return lines;
1919
2980
  }
1920
2981
 
2982
+ // src/render-poses.ts
2983
+ var import_node_fs5 = require("fs");
2984
+ var import_node_path4 = __toESM(require("path"));
2985
+ var import_format10 = require("@ikijs/format");
2986
+
1921
2987
  // src/render-browser.ts
1922
2988
  var import_node_child_process = require("child_process");
1923
- var import_node_fs2 = __toESM(require("fs"));
2989
+ var import_node_fs3 = __toESM(require("fs"));
1924
2990
  var import_node_os = __toESM(require("os"));
1925
2991
  var import_node_path2 = __toESM(require("path"));
1926
2992
  var NO_BROWSER_MESSAGE = "render_poses needs a Chromium-based browser and found none. Install Google Chrome, Microsoft Edge or Chromium, or set CHROME_PATH to its executable.";
@@ -1947,8 +3013,8 @@ var DEFAULT_TIMEOUT_MS = 3e4;
1947
3013
  var BROWSER_CLOSE_MS = 1e3;
1948
3014
  function isExecutableFile(file) {
1949
3015
  try {
1950
- if (!import_node_fs2.default.statSync(file).isFile()) return false;
1951
- import_node_fs2.default.accessSync(file, import_node_fs2.default.constants.X_OK);
3016
+ if (!import_node_fs3.default.statSync(file).isFile()) return false;
3017
+ import_node_fs3.default.accessSync(file, import_node_fs3.default.constants.X_OK);
1952
3018
  return true;
1953
3019
  } catch {
1954
3020
  return false;
@@ -2107,7 +3173,7 @@ async function openPage(cdp, timeoutMs) {
2107
3173
  }
2108
3174
  function removeProfile(profile) {
2109
3175
  try {
2110
- import_node_fs2.default.rmSync(profile, {
3176
+ import_node_fs3.default.rmSync(profile, {
2111
3177
  recursive: true,
2112
3178
  force: true,
2113
3179
  maxRetries: 5,
@@ -2123,7 +3189,7 @@ async function launchBrowser(executable, timeoutMs) {
2123
3189
  "render_poses needs Node 22 or newer (the global WebSocket is missing)."
2124
3190
  );
2125
3191
  }
2126
- const profile = import_node_fs2.default.mkdtempSync(import_node_path2.default.join(import_node_os.default.tmpdir(), "iki-render-"));
3192
+ const profile = import_node_fs3.default.mkdtempSync(import_node_path2.default.join(import_node_os.default.tmpdir(), "iki-render-"));
2127
3193
  let child;
2128
3194
  try {
2129
3195
  child = (0, import_node_child_process.spawn)(
@@ -2143,7 +3209,7 @@ async function launchBrowser(executable, timeoutMs) {
2143
3209
  { stdio: ["ignore", "ignore", "pipe"] }
2144
3210
  );
2145
3211
  } catch (error) {
2146
- import_node_fs2.default.rmSync(profile, { recursive: true, force: true });
3212
+ import_node_fs3.default.rmSync(profile, { recursive: true, force: true });
2147
3213
  throw startError(executable, error);
2148
3214
  }
2149
3215
  let spawnError;
@@ -2426,13 +3492,13 @@ function formatNodReport(report) {
2426
3492
  }
2427
3493
 
2428
3494
  // src/sweep.ts
2429
- var import_node_fs3 = __toESM(require("fs"));
3495
+ var import_node_fs4 = __toESM(require("fs"));
2430
3496
  var import_node_path3 = __toESM(require("path"));
2431
3497
  var SWEEP_CLOCK_HZ = 60;
2432
3498
  var SWEEP_FPS = 30;
2433
3499
  var SWEEP_DURATION_S = 3;
2434
3500
  var BOX_DURATION_S = 6;
2435
- var SWEEP_PRESETS = ["turn", "turn-nod"];
3501
+ var SWEEP_PRESETS = ["turn", "turn-nod", "roll"];
2436
3502
  var SWEEP_WARMUP_S = 0.5;
2437
3503
  var SWEEP_FRAME_MS = 1e3 / SWEEP_CLOCK_HZ * (1 + 1e-9);
2438
3504
  var SHEET_THETAS = [-30, -20, -10, -5, 0, 5, 10, 20, 30];
@@ -2485,29 +3551,37 @@ function boxAngles(t) {
2485
3551
  }
2486
3552
  return { x: 0, y: 0 };
2487
3553
  }
2488
- function sweepDurationS(preset) {
2489
- return preset === "turn" ? SWEEP_DURATION_S : BOX_DURATION_S;
2490
- }
2491
- function schedule(preset) {
2492
- const durationS = sweepDurationS(preset);
2493
- const n = SWEEP_CLOCK_HZ * durationS;
2494
- if (preset === "turn") {
2495
- return {
2496
- parameters: ["ParamAngleX"],
2497
- steps: Array.from({ length: n }, (_, j) => ({
2498
- ParamAngleX: turnTheta(j / SWEEP_CLOCK_HZ)
2499
- })),
2500
- durationS
2501
- };
2502
- }
2503
- return {
2504
- parameters: ["ParamAngleX", "ParamAngleY"],
2505
- steps: Array.from({ length: n }, (_, j) => {
2506
- const { x, y } = boxAngles(j / SWEEP_CLOCK_HZ);
3554
+ var legSheet = (id) => (steps, n) => turnSheetFrames(steps, n, id);
3555
+ var SHAPES = {
3556
+ turn: {
3557
+ durationS: SWEEP_DURATION_S,
3558
+ angles: (t) => ({ ParamAngleX: turnTheta(t) }),
3559
+ sheetFrames: legSheet("ParamAngleX"),
3560
+ label: (s) => `\u03B8 ${signedDeg(s.ParamAngleX)}\xB0`,
3561
+ kymograph: true
3562
+ },
3563
+ // The roll rides the turn's own curve, so its frames sit at the angles the
3564
+ // turn sheet's do.
3565
+ roll: {
3566
+ durationS: SWEEP_DURATION_S,
3567
+ angles: (t) => ({ ParamAngleZ: turnTheta(t) }),
3568
+ sheetFrames: legSheet("ParamAngleZ"),
3569
+ label: (s) => `Z ${signedDeg(s.ParamAngleZ)}\xB0`,
3570
+ kymograph: false
3571
+ },
3572
+ "turn-nod": {
3573
+ durationS: BOX_DURATION_S,
3574
+ angles: (t) => {
3575
+ const { x, y } = boxAngles(t);
2507
3576
  return { ParamAngleX: x, ParamAngleY: y };
2508
- }),
2509
- durationS
2510
- };
3577
+ },
3578
+ sheetFrames: boxSheetFrames,
3579
+ label: (s) => `X ${signedDeg(s.ParamAngleX)}\xB0 Y ${signedDeg(s.ParamAngleY)}\xB0`,
3580
+ kymograph: false
3581
+ }
3582
+ };
3583
+ function sweepDurationS(preset) {
3584
+ return SHAPES[preset].durationS;
2511
3585
  }
2512
3586
  function eyeRowModelPx(model) {
2513
3587
  const landed = landParts(model, {}, ["eye_L", "eye_R"]);
@@ -2533,13 +3607,13 @@ function physicsOutputIds(model) {
2533
3607
  }
2534
3608
  return [...ids];
2535
3609
  }
2536
- function turnSheetFrames(steps, frames) {
3610
+ function turnSheetFrames(steps, frames, id) {
2537
3611
  const onLeg = [];
2538
3612
  for (let k = 0; k < frames; k++) {
2539
3613
  const t = k / SWEEP_FPS;
2540
3614
  if (t >= LEG_FROM_S && t <= LEG_TO_S) onLeg.push(k);
2541
3615
  }
2542
- const x = (k) => steps[CAPTURE_EVERY * k].ParamAngleX;
3616
+ const x = (k) => steps[CAPTURE_EVERY * k][id];
2543
3617
  const picked = [];
2544
3618
  for (const target2 of SHEET_THETAS) {
2545
3619
  let best = onLeg[0];
@@ -2569,7 +3643,13 @@ function signedDeg(angle) {
2569
3643
  return rounded > 0 ? `+${deg}` : deg.replace("-", "\u2212");
2570
3644
  }
2571
3645
  function sweepSpec(model, preset, crop) {
2572
- const { parameters, steps, durationS } = schedule(preset);
3646
+ const shape = SHAPES[preset];
3647
+ const { durationS } = shape;
3648
+ const steps = Array.from(
3649
+ { length: SWEEP_CLOCK_HZ * durationS },
3650
+ (_, j) => shape.angles(j / SWEEP_CLOCK_HZ)
3651
+ );
3652
+ const parameters = Object.keys(steps[0]);
2573
3653
  const frameCount = durationS * SWEEP_FPS;
2574
3654
  const dw = crop ? crop.dw : BUST_SIZE;
2575
3655
  const dh = crop ? crop.dh : BUST_SIZE;
@@ -2580,15 +3660,11 @@ function sweepSpec(model, preset, crop) {
2580
3660
  (SHEET_MAX_SIDE - 2 * m) / (3 * dw),
2581
3661
  (SHEET_MAX_SIDE - 2 * m - 3 * b) / (3 * dh)
2582
3662
  );
2583
- const frames = preset === "turn" ? turnSheetFrames(steps, frameCount) : boxSheetFrames(steps, frameCount);
2584
- const labelOf = (k) => {
2585
- const s = steps[CAPTURE_EVERY * k];
2586
- const t = (k / SWEEP_FPS).toFixed(2);
2587
- return preset === "turn" ? `\u03B8 ${signedDeg(s.ParamAngleX)}\xB0 t ${t} s` : `X ${signedDeg(s.ParamAngleX)}\xB0 Y ${signedDeg(s.ParamAngleY)}\xB0 t ${t} s`;
2588
- };
3663
+ const frames = shape.sheetFrames(steps, frameCount);
3664
+ const labelOf = (k) => `${shape.label(steps[CAPTURE_EVERY * k])} t ${(k / SWEEP_FPS).toFixed(2)} s`;
2589
3665
  const { width: W, height: H } = model.canvas;
2590
3666
  let kymograph;
2591
- if (preset === "turn") {
3667
+ if (shape.kymograph) {
2592
3668
  const yModel = eyeRowModelPx(model);
2593
3669
  let row = Math.round(dh / 2);
2594
3670
  let at = "middle";
@@ -2668,7 +3744,7 @@ img { max-width: 48vw; height: auto; background: #444; }
2668
3744
  scrub.max = String(n - 1);
2669
3745
  if (b) { bi.style.display = "block"; }
2670
3746
  function short(id) {
2671
- return id === "ParamAngleX" ? "X" : id === "ParamAngleY" ? "Y" : id;
3747
+ return id === "ParamAngleX" ? "X" : id === "ParamAngleY" ? "Y" : id === "ParamAngleZ" ? "Z" : id;
2672
3748
  }
2673
3749
  function show(k) {
2674
3750
  i = k;
@@ -2707,13 +3783,13 @@ var STALE_NAMES = [
2707
3783
  function prepareSweepDir(outDir, name, label) {
2708
3784
  const dir = import_node_path3.default.join(outDir, name);
2709
3785
  try {
2710
- import_node_fs3.default.mkdirSync(dir);
3786
+ import_node_fs4.default.mkdirSync(dir);
2711
3787
  } catch (e) {
2712
3788
  if (e.code !== "EEXIST") {
2713
3789
  throw new AutoRigInputError(`sweep dir: ${e.message}`);
2714
3790
  }
2715
3791
  }
2716
- const stat = import_node_fs3.default.lstatSync(dir);
3792
+ const stat = import_node_fs4.default.lstatSync(dir);
2717
3793
  if (stat.isSymbolicLink()) {
2718
3794
  throw new AutoRigInputError(`${label}.name names ${dir}, a symbolic link`);
2719
3795
  }
@@ -2723,9 +3799,9 @@ function prepareSweepDir(outDir, name, label) {
2723
3799
  return confineToWorkingDirectory(process.cwd(), dir, "sweep dir", name);
2724
3800
  }
2725
3801
  function clearSweepDir(real) {
2726
- for (const entry of import_node_fs3.default.readdirSync(real)) {
3802
+ for (const entry of import_node_fs4.default.readdirSync(real)) {
2727
3803
  if (STALE_FILE.test(entry) || STALE_NAMES.includes(entry)) {
2728
- import_node_fs3.default.rmSync(import_node_path3.default.join(real, entry));
3804
+ import_node_fs4.default.rmSync(import_node_path3.default.join(real, entry));
2729
3805
  }
2730
3806
  }
2731
3807
  }
@@ -2841,9 +3917,9 @@ function planRenders(model, requested, sweep, sweeps) {
2841
3917
  }
2842
3918
  const bodyAngles = Object.fromEntries(
2843
3919
  [
2844
- import_format8.StandardParameter.BodyAngleX,
2845
- import_format8.StandardParameter.BodyAngleY,
2846
- import_format8.StandardParameter.BodyAngleZ
3920
+ import_format10.StandardParameter.BodyAngleX,
3921
+ import_format10.StandardParameter.BodyAngleY,
3922
+ import_format10.StandardParameter.BodyAngleZ
2847
3923
  ].filter((id) => model.parameters.some((p) => p.id === id)).map((id) => [id, -10])
2848
3924
  );
2849
3925
  const poses = [
@@ -2929,7 +4005,7 @@ function planRenders(model, requested, sweep, sweeps) {
2929
4005
  whole("full-elbow-r-45", { ParamElbowR: 45 }),
2930
4006
  whole("full-elbow-r-90", { ParamElbowR: 90 })
2931
4007
  );
2932
- if (model.parameters.some((p) => p.id === import_format8.StandardParameter.ArmPoseRight)) {
4008
+ if (model.parameters.some((p) => p.id === import_format10.StandardParameter.ArmPoseRight)) {
2933
4009
  poses.push(
2934
4010
  whole("full-pose-l", { ParamArmPoseL: 1 }),
2935
4011
  whole("full-pose-r", { ParamArmPoseR: 1 }),
@@ -2970,6 +4046,33 @@ function checkRequest(requested, i) {
2970
4046
  }
2971
4047
  }
2972
4048
  }
4049
+ function withoutParts(model, hideParts) {
4050
+ const hidden = new Set(hideParts);
4051
+ hideParts.forEach((id, i) => {
4052
+ if (!model.parts.some((p) => p.id === id)) {
4053
+ throw new AutoRigInputError(
4054
+ `hideParts[${i}] ${JSON.stringify(id)} is not a part of the model`
4055
+ );
4056
+ }
4057
+ const kept = model.parts.find(
4058
+ (p) => !hidden.has(p.id) && p.clip?.masks.includes(id)
4059
+ );
4060
+ if (kept) {
4061
+ throw new AutoRigInputError(
4062
+ `hideParts[${i}] ${JSON.stringify(id)} masks ${JSON.stringify(kept.id)}, which stays; hide ${JSON.stringify(kept.id)} too`
4063
+ );
4064
+ }
4065
+ const occluded = model.parts.find(
4066
+ (p) => !hidden.has(p.id) && p.occlusion?.by.includes(id)
4067
+ );
4068
+ if (occluded) {
4069
+ throw new AutoRigInputError(
4070
+ `hideParts[${i}] ${JSON.stringify(id)} occludes ${JSON.stringify(occluded.id)}, which stays; hide ${JSON.stringify(occluded.id)} too`
4071
+ );
4072
+ }
4073
+ });
4074
+ return { ...model, parts: model.parts.filter((p) => !hidden.has(p.id)) };
4075
+ }
2973
4076
  var PNG_PREFIX = "data:image/png;base64,";
2974
4077
  var PAGE_SCRIPT_MS = 1e4;
2975
4078
  var LOAD_MS = 6e4;
@@ -2977,7 +4080,7 @@ var CAPTURE_MS = 15e3;
2977
4080
  function readPageScript() {
2978
4081
  const url = new URL("../dist/render-page.global.js", importMetaUrl);
2979
4082
  try {
2980
- return (0, import_node_fs4.readFileSync)(url, "utf8");
4083
+ return (0, import_node_fs5.readFileSync)(url, "utf8");
2981
4084
  } catch (cause) {
2982
4085
  throw new Error(
2983
4086
  "could not read the render page script; run `pnpm build` in packages/mcp",
@@ -3078,8 +4181,9 @@ async function renderPoses(input) {
3078
4181
  input.modelPath
3079
4182
  );
3080
4183
  const outDir = resolveOutputDir(input.outDir);
3081
- const model = (0, import_format8.loadIkiModel)((0, import_node_fs4.readFileSync)(modelFile, "utf8"));
4184
+ const model = (0, import_format10.loadIkiModel)((0, import_node_fs5.readFileSync)(modelFile, "utf8"));
3082
4185
  const plan = planRenders(model, input.poses, input.sweep, input.sweeps);
4186
+ const drawn = input.hideParts ? withoutParts(model, input.hideParts) : model;
3083
4187
  const browser = findBrowser();
3084
4188
  if (!browser) return { ok: false, error: NO_BROWSER_MESSAGE };
3085
4189
  const pageScript = readPageScript();
@@ -3102,7 +4206,7 @@ async function renderPoses(input) {
3102
4206
  async (evaluate) => {
3103
4207
  await evaluate(pageScript, PAGE_SCRIPT_MS);
3104
4208
  const loaded = await evaluate(
3105
- `window.__ikiRender.load(${JSON.stringify(model)}, ${JSON.stringify({ canvas: plan.canvas, view: plan.view })})`,
4209
+ `window.__ikiRender.load(${JSON.stringify(drawn)}, ${JSON.stringify({ canvas: plan.canvas, view: plan.view })})`,
3106
4210
  LOAD_MS
3107
4211
  );
3108
4212
  const written = [];
@@ -3170,87 +4274,20 @@ async function renderPoses(input) {
3170
4274
  sweeps
3171
4275
  };
3172
4276
  } catch (error) {
3173
- if (error instanceof AutoRigInputError || error instanceof import_format8.IkiFormatError) {
4277
+ if (error instanceof AutoRigInputError || error instanceof import_format10.IkiFormatError) {
3174
4278
  return { ok: false, error: error.message };
3175
4279
  }
3176
4280
  throw error;
3177
4281
  }
3178
4282
  }
3179
4283
 
3180
- // src/node-images.ts
3181
- var import_sharp = __toESM(require("sharp"));
3182
- var import_editor2 = require("@ikijs/editor");
3183
- async function decodePng(filePath) {
3184
- try {
3185
- const pipeline = (0, import_sharp.default)(filePath, { limitInputPixels: MAX_INPUT_PIXELS });
3186
- const metadata = await pipeline.metadata();
3187
- if (metadata.format !== "png") {
3188
- throw new AutoRigInputError(
3189
- `non-PNG image (${metadata.format ?? "unknown"}): ${filePath}`
3190
- );
3191
- }
3192
- const { data, info } = await pipeline.ensureAlpha().raw().toBuffer({ resolveWithObject: true });
3193
- return {
3194
- width: info.width,
3195
- height: info.height,
3196
- rgba: data,
3197
- hasAlpha: metadata.hasAlpha ?? false
3198
- };
3199
- } catch (e) {
3200
- if (e instanceof AutoRigInputError) throw e;
3201
- const msg = e instanceof Error ? e.message : String(e);
3202
- throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);
3203
- }
3204
- }
3205
- function detectAlphaBbox(rgba, width, height) {
3206
- const bbox = (0, import_editor2.detectAlphaBbox)(rgba, width, height);
3207
- if (bbox === null) {
3208
- throw new AutoRigInputError("layer is empty after alpha threshold");
3209
- }
3210
- return bbox;
3211
- }
3212
- function cropToBuffer(rgba, width, height, bbox) {
3213
- 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();
3214
- }
3215
- function encodeOverlayPng(filePath, svg) {
3216
- return (0, import_sharp.default)(filePath, { limitInputPixels: MAX_INPUT_PIXELS }).composite([{ input: Buffer.from(svg) }]).png().toBuffer();
3217
- }
3218
- async function renderAtlasToDataUri(crops, layout, quantizeColors) {
3219
- const byId = /* @__PURE__ */ new Map();
3220
- for (const crop of crops) byId.set(crop.id, crop);
3221
- const pad = layout.padding;
3222
- const composites = await Promise.all(
3223
- layout.placements.map(async (placement3) => {
3224
- const crop = byId.get(placement3.id);
3225
- if (crop === void 0) {
3226
- throw new AutoRigInputError(
3227
- `no crop for atlas placement "${placement3.id}"`
3228
- );
3229
- }
3230
- const input = pad > 0 ? await (0, import_sharp.default)(crop.buffer).extend({ right: pad, bottom: pad, extendWith: "copy" }).png().toBuffer() : crop.buffer;
3231
- return { input, left: placement3.x, top: placement3.y };
3232
- })
3233
- );
3234
- const page = await (0, import_sharp.default)({
3235
- create: {
3236
- width: layout.pageWidth,
3237
- height: layout.pageHeight,
3238
- channels: 4,
3239
- background: { r: 0, g: 0, b: 0, alpha: 0 }
3240
- }
3241
- }).composite(composites).png(
3242
- quantizeColors === void 0 ? {} : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 }
3243
- ).toBuffer();
3244
- return `data:image/png;base64,${page.toString("base64")}`;
3245
- }
3246
-
3247
4284
  // src/tools.ts
3248
4285
  function coerceModel(model) {
3249
4286
  try {
3250
- const parsed = typeof model === "string" ? (0, import_format9.loadIkiModel)(model) : (0, import_format9.parseIkiModel)(model);
4287
+ const parsed = typeof model === "string" ? (0, import_format11.loadIkiModel)(model) : (0, import_format11.parseIkiModel)(model);
3251
4288
  return { ok: true, model: parsed };
3252
4289
  } catch (e) {
3253
- if (e instanceof import_format9.IkiFormatError) return { ok: false, error: e.message };
4290
+ if (e instanceof import_format11.IkiFormatError) return { ok: false, error: e.message };
3254
4291
  throw e;
3255
4292
  }
3256
4293
  }
@@ -3359,7 +4396,7 @@ function describeIkiAt(modelPath) {
3359
4396
  "model path",
3360
4397
  modelPath
3361
4398
  );
3362
- return describeIki((0, import_node_fs5.readFileSync)(modelFile, "utf8"));
4399
+ return describeIki((0, import_node_fs6.readFileSync)(modelFile, "utf8"));
3363
4400
  } catch (e) {
3364
4401
  if (e instanceof AutoRigInputError) return { ok: false, error: e.message };
3365
4402
  throw e;
@@ -3367,123 +4404,123 @@ function describeIkiAt(modelPath) {
3367
4404
  }
3368
4405
  var STANDARD_PARAMETER_INFO = [
3369
4406
  {
3370
- id: import_format9.StandardParameter.MouthOpen,
4407
+ id: import_format11.StandardParameter.MouthOpen,
3371
4408
  description: "Mouth open amount for lip-sync (0 closed .. 1 open)."
3372
4409
  },
3373
4410
  {
3374
- id: import_format9.StandardParameter.MouthForm,
4411
+ id: import_format11.StandardParameter.MouthForm,
3375
4412
  description: "Mouth form / smile (-1 .. 1)."
3376
4413
  },
3377
4414
  {
3378
- id: import_format9.StandardParameter.EyeOpenLeft,
4415
+ id: import_format11.StandardParameter.EyeOpenLeft,
3379
4416
  description: "Left eye open (0 closed .. 1 open). Drive with the right eye for a blink."
3380
4417
  },
3381
4418
  {
3382
- id: import_format9.StandardParameter.EyeOpenRight,
4419
+ id: import_format11.StandardParameter.EyeOpenRight,
3383
4420
  description: "Right eye open (0 closed .. 1 open)."
3384
4421
  },
3385
4422
  {
3386
- id: import_format9.StandardParameter.EyeballX,
4423
+ id: import_format11.StandardParameter.EyeballX,
3387
4424
  description: "Eyeball gaze, horizontal (-1 .. 1)."
3388
4425
  },
3389
4426
  {
3390
- id: import_format9.StandardParameter.EyeballY,
4427
+ id: import_format11.StandardParameter.EyeballY,
3391
4428
  description: "Eyeball gaze, vertical (-1 .. 1)."
3392
4429
  },
3393
4430
  {
3394
- id: import_format9.StandardParameter.AngleX,
4431
+ id: import_format11.StandardParameter.AngleX,
3395
4432
  description: "Head angle, horizontal degrees."
3396
4433
  },
3397
4434
  {
3398
- id: import_format9.StandardParameter.AngleY,
4435
+ id: import_format11.StandardParameter.AngleY,
3399
4436
  description: "Head angle, vertical degrees."
3400
4437
  },
3401
4438
  {
3402
- id: import_format9.StandardParameter.AngleZ,
4439
+ id: import_format11.StandardParameter.AngleZ,
3403
4440
  description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
3404
4441
  },
3405
4442
  {
3406
- id: import_format9.StandardParameter.BodyAngleX,
4443
+ id: import_format11.StandardParameter.BodyAngleX,
3407
4444
  description: "Body turn, degrees (-10 .. 10); positive turns the body toward the viewer's right, as AngleX does the head."
3408
4445
  },
3409
4446
  {
3410
- id: import_format9.StandardParameter.BodyAngleY,
4447
+ id: import_format11.StandardParameter.BodyAngleY,
3411
4448
  description: "Body lean, degrees (-10 .. 10); positive moves the upper body up, negative bows."
3412
4449
  },
3413
4450
  {
3414
- id: import_format9.StandardParameter.BodyAngleZ,
4451
+ id: import_format11.StandardParameter.BodyAngleZ,
3415
4452
  description: "Body tilt, degrees (-10 .. 10); positive tilts the top toward the viewer's right (clockwise), as AngleZ does the head."
3416
4453
  },
3417
4454
  {
3418
- id: import_format9.StandardParameter.Breath,
4455
+ id: import_format11.StandardParameter.Breath,
3419
4456
  description: "Idle breath (0 .. 1), cycled by the host."
3420
4457
  },
3421
4458
  {
3422
- id: import_format9.StandardParameter.AmbientSway,
4459
+ id: import_format11.StandardParameter.AmbientSway,
3423
4460
  description: "Ambient sway (-1 .. 1): a slow zero-mean drift the idle writes for physics rigs to follow (the auto-rig's hair in idle). Not a wind: no bias. Stays procedural under a declared Idle group, as Breath does."
3424
4461
  },
3425
4462
  {
3426
- id: import_format9.StandardParameter.BrowLeftY,
4463
+ id: import_format11.StandardParameter.BrowLeftY,
3427
4464
  description: "Left brow raise/lower (-1 .. 1)."
3428
4465
  },
3429
4466
  {
3430
- id: import_format9.StandardParameter.BrowRightY,
4467
+ id: import_format11.StandardParameter.BrowRightY,
3431
4468
  description: "Right brow raise/lower (-1 .. 1)."
3432
4469
  },
3433
4470
  {
3434
- id: import_format9.StandardParameter.BrowLeftAngle,
4471
+ id: import_format11.StandardParameter.BrowLeftAngle,
3435
4472
  description: "Left brow tilt/angle (-1 .. 1)."
3436
4473
  },
3437
4474
  {
3438
- id: import_format9.StandardParameter.BrowRightAngle,
4475
+ id: import_format11.StandardParameter.BrowRightAngle,
3439
4476
  description: "Right brow tilt/angle (-1 .. 1)."
3440
4477
  },
3441
4478
  {
3442
- id: import_format9.StandardParameter.Cheek,
4479
+ id: import_format11.StandardParameter.Cheek,
3443
4480
  description: "Cheek blush strength (0 .. 1), raised by an expression."
3444
4481
  },
3445
4482
  {
3446
- id: import_format9.StandardParameter.HairSwayX,
4483
+ id: import_format11.StandardParameter.HairSwayX,
3447
4484
  description: "Front hair's horizontal sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
3448
4485
  },
3449
4486
  {
3450
- id: import_format9.StandardParameter.HairSwayZ,
4487
+ id: import_format11.StandardParameter.HairSwayZ,
3451
4488
  description: "Front hair's sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
3452
4489
  },
3453
4490
  {
3454
- id: import_format9.StandardParameter.HairBackSway,
4491
+ id: import_format11.StandardParameter.HairBackSway,
3455
4492
  description: "Back hair's sway driver behind the head turn, tilt and ambient drift, one spring slower than the front hair's so the two swing out of phase. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
3456
4493
  },
3457
4494
  {
3458
- id: import_format9.StandardParameter.ArmLeft,
4495
+ id: import_format11.StandardParameter.ArmLeft,
3459
4496
  description: "Left shoulder, degrees; positive raises the arm outward (mirrored on the right)."
3460
4497
  },
3461
4498
  {
3462
- id: import_format9.StandardParameter.ArmRight,
4499
+ id: import_format11.StandardParameter.ArmRight,
3463
4500
  description: "Right shoulder, degrees; positive raises the arm outward (mirrored on the left)."
3464
4501
  },
3465
4502
  {
3466
- id: import_format9.StandardParameter.ElbowLeft,
4503
+ id: import_format11.StandardParameter.ElbowLeft,
3467
4504
  description: "Left elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the right)."
3468
4505
  },
3469
4506
  {
3470
- id: import_format9.StandardParameter.ElbowRight,
4507
+ id: import_format11.StandardParameter.ElbowRight,
3471
4508
  description: "Right elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the left)."
3472
4509
  },
3473
4510
  {
3474
- id: import_format9.StandardParameter.ArmPoseLeft,
4511
+ id: import_format11.StandardParameter.ArmPoseLeft,
3475
4512
  description: "Left pose-forearm switch, 0..1; 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm."
3476
4513
  },
3477
4514
  {
3478
- id: import_format9.StandardParameter.ArmPoseRight,
4515
+ id: import_format11.StandardParameter.ArmPoseRight,
3479
4516
  description: "Right pose-forearm switch, 0..1; 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm."
3480
4517
  },
3481
4518
  {
3482
- id: import_format9.StandardParameter.ArmPoseAngleLeft,
4519
+ id: import_format11.StandardParameter.ArmPoseAngleLeft,
3483
4520
  description: "Left pose forearm's own small rotation about the elbow, degrees; positive tips the raised hand outward, away from the body (mirrored on the right)."
3484
4521
  },
3485
4522
  {
3486
- id: import_format9.StandardParameter.ArmPoseAngleRight,
4523
+ id: import_format11.StandardParameter.ArmPoseAngleRight,
3487
4524
  description: "Right pose forearm's own small rotation about the elbow, degrees; positive tips the raised hand outward, away from the body (mirrored on the left)."
3488
4525
  }
3489
4526
  ];
@@ -3491,10 +4528,10 @@ function listStandardParameters() {
3491
4528
  return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));
3492
4529
  }
3493
4530
  function describeRigPlan() {
3494
- return { fields: [...import_editor3.RIG_PLAN_FIELDS] };
4531
+ return { fields: [...import_editor4.RIG_PLAN_FIELDS] };
3495
4532
  }
3496
4533
  function formatRigPlanReport(r) {
3497
- const fields = import_editor3.RIG_PLAN_FIELDS.map((f) => {
4534
+ const fields = import_editor4.RIG_PLAN_FIELDS.map((f) => {
3498
4535
  const value = `${f.path}=${r.effective[f.path]}`;
3499
4536
  const clamp2 = r.clamped.find((c) => c.field === f.path);
3500
4537
  if (clamp2 !== void 0) {
@@ -3517,7 +4554,7 @@ function expectInput(label, fn) {
3517
4554
  }
3518
4555
  var LOSSLESS_PAGE_ROLE = "nose";
3519
4556
  async function renderAtlasPage(crops, quantizeColors) {
3520
- const layout = (0, import_editor3.packAtlas)(
4557
+ const layout = (0, import_editor4.packAtlas)(
3521
4558
  crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),
3522
4559
  void 0,
3523
4560
  MAX_ATLAS_SIDE
@@ -3540,9 +4577,20 @@ async function autoRigFromLayers(input) {
3540
4577
  if (!Array.isArray(layers) || layers.length === 0) {
3541
4578
  throw new AutoRigInputError("layers must be a non-empty array");
3542
4579
  }
3543
- if (layers.length > MAX_LAYERS) {
4580
+ const customInputs = input.customParts;
4581
+ if (customInputs !== void 0 && !Array.isArray(customInputs)) {
4582
+ throw new AutoRigInputError("customParts must be an array");
4583
+ }
4584
+ const customEntries = customInputs ?? [];
4585
+ customEntries.forEach((entry, i) => {
4586
+ const at = `customParts[${i}]`;
4587
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
4588
+ throw new AutoRigInputError(`${at} must be a plain object`);
4589
+ }
4590
+ });
4591
+ if (layers.length + customEntries.length > MAX_LAYERS) {
3544
4592
  throw new AutoRigInputError(
3545
- `too many layers: ${layers.length} > ${MAX_LAYERS}`
4593
+ `too many layers: ${layers.length + customEntries.length} > ${MAX_LAYERS}`
3546
4594
  );
3547
4595
  }
3548
4596
  const outPath = resolveOutputPath(
@@ -3555,7 +4603,7 @@ async function autoRigFromLayers(input) {
3555
4603
  );
3556
4604
  }
3557
4605
  if (input.style !== void 0) {
3558
- throw new AutoRigInputError((0, import_editor3.styleRemovedMessage)("style"));
4606
+ throw new AutoRigInputError((0, import_editor4.styleRemovedMessage)("style"));
3559
4607
  }
3560
4608
  const turnTargets = input.turnTargets;
3561
4609
  if (turnTargets !== void 0) {
@@ -3572,9 +4620,12 @@ async function autoRigFromLayers(input) {
3572
4620
  const resolved = resolveInputPath(layer.path);
3573
4621
  return { resolved, fileName: layer.fileName ?? import_node_path5.default.basename(resolved) };
3574
4622
  });
4623
+ const customPaths = customEntries.map(
4624
+ (entry, i) => resolveInputPath(entry.path, `customParts[${i}].path`)
4625
+ );
3575
4626
  const rolePairs = expectInput(
3576
4627
  "role parsing",
3577
- () => (0, import_editor3.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
4628
+ () => (0, import_editor4.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
3578
4629
  );
3579
4630
  const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));
3580
4631
  let canvasW = 0;
@@ -3582,6 +4633,10 @@ async function autoRigFromLayers(input) {
3582
4633
  let totalPixels = 0;
3583
4634
  let measurer;
3584
4635
  const crops = [];
4636
+ const paints = /* @__PURE__ */ new Map();
4637
+ const anchorRoles = new Set(
4638
+ customEntries.flatMap((e) => [e.anchor, ...e.occlusion?.by ?? []])
4639
+ );
3585
4640
  for (let i = 0; i < resolvedLayers.length; i++) {
3586
4641
  const { resolved, fileName } = resolvedLayers[i];
3587
4642
  const png = await decodePng(resolved);
@@ -3604,7 +4659,7 @@ async function autoRigFromLayers(input) {
3604
4659
  `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`
3605
4660
  );
3606
4661
  }
3607
- measurer = (0, import_editor3.createLayerSetMeasurer)({ width: canvasW, height: canvasH });
4662
+ measurer = (0, import_editor4.createLayerSetMeasurer)({ width: canvasW, height: canvasH });
3608
4663
  } else if (png.width !== canvasW || png.height !== canvasH) {
3609
4664
  throw new AutoRigInputError(
3610
4665
  `layer "${fileName}" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
@@ -3621,9 +4676,48 @@ async function autoRigFromLayers(input) {
3621
4676
  );
3622
4677
  }
3623
4678
  const { bbox } = layer;
4679
+ if (anchorRoles.has(role)) paints.set(role, paintRuns(png));
3624
4680
  const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);
3625
4681
  crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
3626
4682
  }
4683
+ const customLayers = [];
4684
+ const customCrops = [];
4685
+ for (let i = 0; i < customEntries.length; i++) {
4686
+ const at = `customParts[${i}]`;
4687
+ const { id } = customEntries[i];
4688
+ const resolved = customPaths[i];
4689
+ const png = await decodePng(resolved);
4690
+ if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {
4691
+ throw new AutoRigInputError(
4692
+ `${at}.path ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`
4693
+ );
4694
+ }
4695
+ totalPixels += png.width * png.height;
4696
+ if (totalPixels > MAX_TOTAL_PIXELS) {
4697
+ throw new AutoRigInputError(
4698
+ `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`
4699
+ );
4700
+ }
4701
+ if (png.width !== canvasW || png.height !== canvasH) {
4702
+ throw new AutoRigInputError(
4703
+ `${at}.path size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
4704
+ );
4705
+ }
4706
+ const bbox = (0, import_editor4.detectAlphaBbox)(png.rgba, png.width, png.height);
4707
+ if (bbox === null) {
4708
+ throw new AutoRigInputError(
4709
+ `${at}.path "${import_node_path5.default.basename(resolved)}": layer is empty after alpha threshold`
4710
+ );
4711
+ }
4712
+ customLayers.push({ fileName: import_node_path5.default.basename(resolved), bbox });
4713
+ paints.set(id, paintRuns(png));
4714
+ customCrops.push({
4715
+ id,
4716
+ buffer: await cropToBuffer(png.rgba, png.width, png.height, bbox),
4717
+ width: bbox.w,
4718
+ height: bbox.h
4719
+ });
4720
+ }
3627
4721
  const measurement = measurer.finish();
3628
4722
  const { headHalfWidth, headHalfWidthApplied, turnOptions } = measurement;
3629
4723
  const { headEdges, strandEdges } = turnOptions;
@@ -3633,9 +4727,10 @@ async function autoRigFromLayers(input) {
3633
4727
  let turn;
3634
4728
  let patches;
3635
4729
  let rigPlan;
4730
+ let bakeReports;
3636
4731
  let model;
3637
4732
  try {
3638
- model = (0, import_editor3.generateIkiFromLayerSet)(
4733
+ model = (0, import_editor4.generateIkiFromLayerSet)(
3639
4734
  measurement.layers,
3640
4735
  { width: canvasW, height: canvasH },
3641
4736
  {
@@ -3657,16 +4752,30 @@ async function autoRigFromLayers(input) {
3657
4752
  }
3658
4753
  },
3659
4754
  ...headEdges === void 0 ? {} : { headEdges },
3660
- ...strandEdges === void 0 ? {} : { strandEdges }
4755
+ ...strandEdges === void 0 ? {} : { strandEdges },
4756
+ ...input.customParts === void 0 ? {} : {
4757
+ customParts: customEntries.map(
4758
+ ({ path: _path, ...rest }, i) => ({
4759
+ ...rest,
4760
+ layer: customLayers[i]
4761
+ })
4762
+ )
4763
+ },
4764
+ ...input.bakes === void 0 ? {} : {
4765
+ bakes: input.bakes,
4766
+ onBakesApplied: (reports) => {
4767
+ bakeReports = reports;
4768
+ }
4769
+ }
3661
4770
  }
3662
4771
  );
3663
4772
  } catch (e) {
3664
- if (!(e instanceof import_editor3.TurnTargetError || e instanceof import_editor3.LayerGeometryError || e instanceof import_editor3.PatchError || e instanceof import_editor3.RigPlanError)) {
4773
+ if (!(e instanceof import_editor4.TurnTargetError || e instanceof import_editor4.LayerGeometryError || e instanceof import_editor4.PatchError || e instanceof import_editor4.RigPlanError || e instanceof import_editor4.CustomPartError || e instanceof import_editor4.BakeError)) {
3665
4774
  throw e;
3666
4775
  }
3667
4776
  throw new AutoRigInputError(e.message);
3668
4777
  }
3669
- const doc = new import_editor3.EditorDocument(model);
4778
+ const doc = new import_editor4.EditorDocument(model);
3670
4779
  const losslessCrop = quantizeColors === void 0 ? void 0 : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);
3671
4780
  const pages = losslessCrop === void 0 ? [await renderAtlasPage(crops, quantizeColors)] : [
3672
4781
  await renderAtlasPage(
@@ -3675,7 +4784,9 @@ async function autoRigFromLayers(input) {
3675
4784
  ),
3676
4785
  await renderAtlasPage([losslessCrop], void 0)
3677
4786
  ];
3678
- const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);
4787
+ const customPage = customCrops.length === 0 ? void 0 : await renderAtlasPage(customCrops, quantizeColors);
4788
+ const allPages = customPage === void 0 ? pages : [...pages, customPage];
4789
+ const atlasBytes = allPages.reduce((sum, p) => sum + p.dataUri.length, 0);
3679
4790
  if (atlasBytes > MAX_OUTPUT_BYTES) {
3680
4791
  throw new AutoRigInputError(
3681
4792
  `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`
@@ -3687,29 +4798,69 @@ async function autoRigFromLayers(input) {
3687
4798
  if (placement3 === void 0) {
3688
4799
  throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
3689
4800
  }
3690
- const uv = (0, import_editor3.uvRectFor)(placement3, {
4801
+ const uv = (0, import_editor4.uvRectFor)(placement3, {
3691
4802
  width: layout.pageWidth,
3692
4803
  height: layout.pageHeight
3693
4804
  });
3694
- return (0, import_editor3.partIdsOfRole)(crop.id).map((partId) => ({ partId, uv }));
4805
+ return (0, import_editor4.partIdsOfRole)(crop.id).map((partId) => ({ partId, uv }));
3695
4806
  })
3696
4807
  );
4808
+ if (customPage !== void 0) {
4809
+ partTextureAssignments.push(
4810
+ ...customPage.crops.map((crop) => {
4811
+ const placement3 = customPage.layout.placements.find(
4812
+ (p) => p.id === crop.id
4813
+ );
4814
+ return {
4815
+ partId: crop.id,
4816
+ uv: (0, import_editor4.uvRectFor)(placement3, {
4817
+ width: customPage.layout.pageWidth,
4818
+ height: customPage.layout.pageHeight
4819
+ })
4820
+ };
4821
+ })
4822
+ );
4823
+ }
3697
4824
  doc.applyAtlas({
3698
4825
  textures: [{ source: pages[0].dataUri }],
3699
4826
  partTextureAssignments
3700
4827
  });
3701
4828
  let patched = doc.getModel();
3702
- if (losslessCrop !== void 0) {
4829
+ if (losslessCrop !== void 0 || customPage !== void 0) {
3703
4830
  patched = structuredClone(patched);
3704
- patched.textures = pages.map((p) => ({ source: p.dataUri }));
3705
- for (const partId of (0, import_editor3.partIdsOfRole)(losslessCrop.id)) {
3706
- patched.parts.find((p) => p.id === partId).texture.index = 1;
4831
+ patched.textures = allPages.map((p) => ({ source: p.dataUri }));
4832
+ if (losslessCrop !== void 0) {
4833
+ for (const partId of (0, import_editor4.partIdsOfRole)(losslessCrop.id)) {
4834
+ patched.parts.find((p) => p.id === partId).texture.index = 1;
4835
+ }
4836
+ }
4837
+ for (const crop of customCrops) {
4838
+ patched.parts.find((p) => p.id === crop.id).texture.index = pages.length;
3707
4839
  }
3708
4840
  }
3709
- const finalModel = (0, import_format9.parseIkiModel)(patched);
4841
+ const finalModel = (0, import_format11.parseIkiModel)(patched);
4842
+ const bakes = bakeReports === void 0 ? void 0 : checkBakes(finalModel, bakeReports);
3710
4843
  writeFileAtomic(outPath, JSON.stringify(finalModel));
3711
4844
  const folds = checkModelFolds(finalModel);
3712
4845
  const physics = checkPhysics(finalModel);
4846
+ let gate;
4847
+ if (input.customParts !== void 0) {
4848
+ try {
4849
+ gate = checkCustomGate(
4850
+ finalModel,
4851
+ customEntries.map(({ id, anchor, tie, rigid, occlusion }) => ({
4852
+ id,
4853
+ anchor,
4854
+ tie,
4855
+ ...rigid === void 0 ? {} : { rigid },
4856
+ ...occlusion === void 0 ? {} : { occludedBy: occlusion.by }
4857
+ })),
4858
+ paints
4859
+ );
4860
+ } catch (e) {
4861
+ gate = failedCustomGate(finalModel, e);
4862
+ }
4863
+ }
3713
4864
  return {
3714
4865
  ok: true,
3715
4866
  path: outPath,
@@ -3725,7 +4876,27 @@ async function autoRigFromLayers(input) {
3725
4876
  folds,
3726
4877
  physics,
3727
4878
  ...patches === void 0 ? {} : { patches },
3728
- rigPlan
4879
+ rigPlan,
4880
+ ...input.customParts === void 0 ? {} : {
4881
+ customParts: {
4882
+ parts: customCrops.map((crop, i) => {
4883
+ const part = finalModel.parts.find((p) => p.id === crop.id);
4884
+ return {
4885
+ id: crop.id,
4886
+ box: customLayers[i].bbox,
4887
+ mesh: {
4888
+ vertices: part.mesh.vertices.length / 2,
4889
+ triangles: part.mesh.indices.length / 3
4890
+ },
4891
+ order: part.order,
4892
+ page: part.texture.index,
4893
+ ...part.occlusion === void 0 ? {} : { occlusion: part.occlusion }
4894
+ };
4895
+ }),
4896
+ ...bakes === void 0 ? {} : { bakes },
4897
+ gate
4898
+ }
4899
+ }
3729
4900
  };
3730
4901
  } catch (err) {
3731
4902
  if (err instanceof AutoRigInputError)
@@ -3735,13 +4906,13 @@ async function autoRigFromLayers(input) {
3735
4906
  }
3736
4907
 
3737
4908
  // src/compose.ts
3738
- var import_node_fs7 = __toESM(require("fs"));
4909
+ var import_node_fs8 = __toESM(require("fs"));
3739
4910
  var import_node_path10 = __toESM(require("path"));
3740
4911
  var import_sharp4 = __toESM(require("sharp"));
3741
- var import_editor13 = require("@ikijs/editor");
4912
+ var import_editor14 = require("@ikijs/editor");
3742
4913
 
3743
4914
  // src/trim.ts
3744
- var import_editor4 = require("@ikijs/editor");
4915
+ var import_editor5 = require("@ikijs/editor");
3745
4916
  var TRIM_THRESHOLD = 12;
3746
4917
  var STRAY_SPECK_FRACTION = 0.01;
3747
4918
  function luma(rgba, i) {
@@ -3770,7 +4941,7 @@ function boxWithoutStraySpecks(rgba, W, H) {
3770
4941
  while (depth > 0) {
3771
4942
  const p = stack[--depth];
3772
4943
  size++;
3773
- if (rgba[p * 4 + 3] >= import_editor4.ALPHA_OPAQUE) opaque = true;
4944
+ if (rgba[p * 4 + 3] >= import_editor5.ALPHA_OPAQUE) opaque = true;
3774
4945
  const px2 = p % W;
3775
4946
  const py = (p - px2) / W;
3776
4947
  setLeft = Math.min(setLeft, px2);
@@ -3807,12 +4978,12 @@ function boxWithoutStraySpecks(rgba, W, H) {
3807
4978
  }
3808
4979
 
3809
4980
  // src/measure.ts
3810
- var import_node_fs6 = __toESM(require("fs"));
4981
+ var import_node_fs7 = __toESM(require("fs"));
3811
4982
  var import_node_path9 = __toESM(require("path"));
3812
4983
 
3813
4984
  // src/measure-arms.ts
3814
4985
  var import_node_path6 = __toESM(require("path"));
3815
- var import_editor5 = require("@ikijs/editor");
4986
+ var import_editor6 = require("@ikijs/editor");
3816
4987
  var ARM_ROLES = ["arm_L", "arm_R"];
3817
4988
  var CAP_OVERLAP = 0.5;
3818
4989
  var px = (v) => `${Number(v.toFixed(1))}`;
@@ -3841,7 +5012,7 @@ async function armWarnings(absDir, layers) {
3841
5012
  continue;
3842
5013
  }
3843
5014
  if (set === void 0) {
3844
- const measurer = (0, import_editor5.createLayerSetMeasurer)({
5015
+ const measurer = (0, import_editor6.createLayerSetMeasurer)({
3845
5016
  width: body.canvasW,
3846
5017
  height: body.canvasH
3847
5018
  });
@@ -3849,12 +5020,12 @@ async function armWarnings(absDir, layers) {
3849
5020
  }
3850
5021
  let g;
3851
5022
  try {
3852
- g = (0, import_editor5.armGeometry)(
5023
+ g = (0, import_editor6.armGeometry)(
3853
5024
  await measured(set.measurer, absDir, arm),
3854
5025
  set.body.bbox.x + set.body.bbox.w / 2 - body.canvasW / 2
3855
5026
  );
3856
5027
  } catch (err) {
3857
- if (err instanceof import_editor5.LayerGeometryError) {
5028
+ if (err instanceof import_editor6.LayerGeometryError) {
3858
5029
  warnings.push(
3859
5030
  `${arm}: ${err.message} \u2014 auto_rig_from_layers refuses it. Regenerate arm.png drawn hanging, shoulder at the top. Billed.`
3860
5031
  );
@@ -3882,7 +5053,7 @@ function capWarning(arm, g, body) {
3882
5053
  }
3883
5054
 
3884
5055
  // src/measure-hair-side.ts
3885
- var import_editor6 = require("@ikijs/editor");
5056
+ var import_editor7 = require("@ikijs/editor");
3886
5057
  var LOCK_ROLES = ["hair_side_R", "hair_side_L"];
3887
5058
  var VISIBLE_MIN_PX = 3;
3888
5059
  var LEAN_HH = 0.12;
@@ -3894,7 +5065,7 @@ function covers(runs, x) {
3894
5065
  }
3895
5066
  return false;
3896
5067
  }
3897
- function runsAt(layer, y) {
5068
+ function runsAt2(layer, y) {
3898
5069
  return layer?.rowRuns?.[y - layer.bbox.y] ?? [];
3899
5070
  }
3900
5071
  function opaqueRows(layer) {
@@ -3930,7 +5101,7 @@ async function hairSideWarnings(absDir, layers) {
3930
5101
  }
3931
5102
  }
3932
5103
  if (mismatched) return warnings;
3933
- const measurer = (0, import_editor6.createLayerSetMeasurer)({
5104
+ const measurer = (0, import_editor7.createLayerSetMeasurer)({
3934
5105
  width: ref.canvasW,
3935
5106
  height: ref.canvasH
3936
5107
  });
@@ -3970,8 +5141,8 @@ async function hairSideWarnings(absDir, layers) {
3970
5141
  function rootWarning(role, lock, front) {
3971
5142
  const y = opaqueRows(lock)?.top;
3972
5143
  if (y === void 0) return void 0;
3973
- const frontRuns = runsAt(front, y);
3974
- const lockRuns = runsAt(lock, y);
5144
+ const frontRuns = runsAt2(front, y);
5145
+ const lockRuns = runsAt2(lock, y);
3975
5146
  let shown = 0;
3976
5147
  for (let i = 0; i + 1 < lockRuns.length; i += 2) {
3977
5148
  let stretch = 0;
@@ -3990,7 +5161,7 @@ function rootWarning(role, lock, front) {
3990
5161
  function eyeCornerWarning(role, lock, side, eyeRole, eye) {
3991
5162
  const row = Math.floor(eye.bboxCy);
3992
5163
  const corner = side < 0 ? eye.marginLeft : eye.marginLeft + eye.w - 1;
3993
- const runs = runsAt(lock, row);
5164
+ const runs = runsAt2(lock, row);
3994
5165
  let overlap = 0;
3995
5166
  for (let i = 0; i + 1 < runs.length; i += 2) {
3996
5167
  if (corner < runs[i] || corner >= runs[i + 1]) continue;
@@ -4009,14 +5180,14 @@ function leanWarning(role, lock, side, face, back, eye) {
4009
5180
  const bare = /* @__PURE__ */ new Set();
4010
5181
  const rows = /* @__PURE__ */ new Set();
4011
5182
  for (let y = lockRows.top; y <= Math.min(lockRows.bottom, faceBottom); y++) {
4012
- const runs = runsAt(lock, y);
5183
+ const runs = runsAt2(lock, y);
4013
5184
  if (runs.length === 0) continue;
4014
5185
  const from = side < 0 ? runs[0] : runs[runs.length - 2];
4015
5186
  const to = side < 0 ? runs[1] : runs[runs.length - 1];
4016
5187
  const start = side < 0 ? from : Math.max(from, to - lean);
4017
5188
  const end = side < 0 ? Math.min(to, from + lean) : to;
4018
- const faceRuns = runsAt(face, y);
4019
- const backRuns = runsAt(back, y);
5189
+ const faceRuns = runsAt2(face, y);
5190
+ const backRuns = runsAt2(back, y);
4020
5191
  for (let x = start; x < end; x++) {
4021
5192
  if (covers(faceRuns, x) || covers(backRuns, x)) continue;
4022
5193
  bare.add(x);
@@ -4058,7 +5229,7 @@ function drawsTwoLocks(lock) {
4058
5229
  }
4059
5230
 
4060
5231
  // src/measure-forearm-pose.ts
4061
- var import_editor7 = require("@ikijs/editor");
5232
+ var import_editor8 = require("@ikijs/editor");
4062
5233
  var POSE_ROLES = ["forearm_pose_L", "forearm_pose_R"];
4063
5234
  var ARM_OF = {
4064
5235
  forearm_pose_L: "arm_L",
@@ -4092,7 +5263,7 @@ async function forearmPoseWarnings(absDir, layers) {
4092
5263
  continue;
4093
5264
  }
4094
5265
  if (layers.body === void 0) continue;
4095
- const measurer = (0, import_editor7.createLayerSetMeasurer)({
5266
+ const measurer = (0, import_editor8.createLayerSetMeasurer)({
4096
5267
  width: stats.canvasW,
4097
5268
  height: stats.canvasH
4098
5269
  });
@@ -4100,12 +5271,12 @@ async function forearmPoseWarnings(absDir, layers) {
4100
5271
  let armLayer;
4101
5272
  try {
4102
5273
  armLayer = await measured(measurer, absDir, arm);
4103
- a = (0, import_editor7.armGeometry)(armLayer, arm === "arm_R" ? Infinity : -Infinity);
5274
+ a = (0, import_editor8.armGeometry)(armLayer, arm === "arm_R" ? Infinity : -Infinity);
4104
5275
  } catch (err) {
4105
- if (err instanceof import_editor7.LayerGeometryError) continue;
5276
+ if (err instanceof import_editor8.LayerGeometryError) continue;
4106
5277
  throw err;
4107
5278
  }
4108
- const b = (0, import_editor7.forearmPoseGeometry)(await measured(measurer, absDir, pose));
5279
+ const b = (0, import_editor8.forearmPoseGeometry)(await measured(measurer, absDir, pose));
4109
5280
  warnings.push(...jointWarnings(pose, arm, stats, a, armLayer, b));
4110
5281
  }
4111
5282
  return warnings;
@@ -4145,11 +5316,11 @@ function jointWarnings(pose, arm, stats, a, armLayer, b) {
4145
5316
 
4146
5317
  // src/measure-lips.ts
4147
5318
  var import_node_path7 = __toESM(require("path"));
4148
- var import_editor9 = require("@ikijs/editor");
5319
+ var import_editor10 = require("@ikijs/editor");
4149
5320
 
4150
5321
  // src/compose-lips.ts
4151
5322
  var import_sharp2 = __toESM(require("sharp"));
4152
- var import_editor8 = require("@ikijs/editor");
5323
+ var import_editor9 = require("@ikijs/editor");
4153
5324
  var KEYED_SRC = "mouth_keyed.png";
4154
5325
  var INTERIOR_SRC = "mouth_interior.png";
4155
5326
  var KEY_CANDIDATE = 0.5;
@@ -4247,7 +5418,7 @@ function keyGreen(rgba, W, H) {
4247
5418
  let candidates = 0;
4248
5419
  for (let p = 0; p < n; p++) {
4249
5420
  const i = p * 4;
4250
- if (rgba[i + 3] < import_editor8.ALPHA_OPAQUE) continue;
5421
+ if (rgba[i + 3] < import_editor9.ALPHA_OPAQUE) continue;
4251
5422
  const excess = (rgba[i + 1] - Math.max(rgba[i], rgba[i + 2])) / 255;
4252
5423
  if (excess < KEY_CANDIDATE) continue;
4253
5424
  candidates++;
@@ -4274,7 +5445,7 @@ function keyGreen(rgba, W, H) {
4274
5445
  const dg = rgba[i + 1] - G[1];
4275
5446
  const db = rgba[i + 2] - G[2];
4276
5447
  const green = dr * dr + dg * dg + db * db <= KEY_FILL_DIST * KEY_FILL_DIST;
4277
- if (rgba[i + 3] < import_editor8.ALPHA_OPAQUE) {
5448
+ if (rgba[i + 3] < import_editor9.ALPHA_OPAQUE) {
4278
5449
  if (green) out[i + 3] = 0;
4279
5450
  } else if (green) {
4280
5451
  fill[p] = 1;
@@ -4450,7 +5621,7 @@ async function prepInterior(rgba, W, H) {
4450
5621
  for (let y = box2.y; y < box2.y + box2.h; y++) {
4451
5622
  for (let x = box2.x; x < box2.x + box2.w; x++) {
4452
5623
  const i = (y * cw + x) * 4;
4453
- if (crop[i + 3] < import_editor8.ALPHA_OPAQUE) continue;
5624
+ if (crop[i + 3] < import_editor9.ALPHA_OPAQUE) continue;
4454
5625
  count++;
4455
5626
  for (let c = 0; c < 3; c++) all[c] += crop[i + c];
4456
5627
  if (luma(crop, i) < CAVITY_LUMA) {
@@ -4473,7 +5644,7 @@ function enclosedHole(frame, w, h) {
4473
5644
  const stack = new Int32Array(n);
4474
5645
  let depth = 0;
4475
5646
  const seed = (p) => {
4476
- if (!outside[p] && alpha(p) < import_editor8.ALPHA_OPAQUE) {
5647
+ if (!outside[p] && alpha(p) < import_editor9.ALPHA_OPAQUE) {
4477
5648
  outside[p] = 1;
4478
5649
  stack[depth++] = p;
4479
5650
  }
@@ -4496,7 +5667,7 @@ function enclosedHole(frame, w, h) {
4496
5667
  }
4497
5668
  const mask = new Uint8Array(n);
4498
5669
  for (let p = 0; p < n; p++) {
4499
- if (alpha(p) < import_editor8.ALPHA_OPAQUE && !outside[p]) mask[p] = 1;
5670
+ if (alpha(p) < import_editor9.ALPHA_OPAQUE && !outside[p]) mask[p] = 1;
4500
5671
  }
4501
5672
  const { label, sizes, boxes } = components(mask, w, h);
4502
5673
  const main = largest(sizes);
@@ -4523,7 +5694,7 @@ function enclosedHole(frame, w, h) {
4523
5694
  return { label, main, box: box2 };
4524
5695
  }
4525
5696
  function measureLips(layers, w, h) {
4526
- const measurer = (0, import_editor8.createLayerSetMeasurer)({ width: w, height: h });
5697
+ const measurer = (0, import_editor9.createLayerSetMeasurer)({ width: w, height: h });
4527
5698
  return new Map(
4528
5699
  Object.entries(layers).map(([role, rgba]) => [
4529
5700
  role,
@@ -4541,8 +5712,8 @@ function assertFoldContract(layers, w, h) {
4541
5712
  }
4542
5713
  byRole.set(role, layer);
4543
5714
  }
4544
- const opening = (0, import_editor8.mouthOpening)(byRole);
4545
- const runs = (0, import_editor8.columnRuns)(byRole.get("mouth_inner"));
5715
+ const opening = (0, import_editor9.mouthOpening)(byRole);
5716
+ const runs = (0, import_editor9.columnRuns)(byRole.get("mouth_inner"));
4546
5717
  for (let col = opening.x0; col <= opening.x1; col++) {
4547
5718
  const c = opening.at(col);
4548
5719
  const why = !runs.has(col) ? "has no interior run" : c.Tu > c.T ? `has a gap between the line and the interior (Tu ${c.Tu} > T ${c.T})` : c.T > c.lineTop || c.lineH <= 0 ? `has no line above the interior (T ${c.T}, line top ${c.lineTop})` : c.Bl < c.Bb ? `has a gap between the interior and the skin (Bl ${c.Bl} < Bb ${c.Bb})` : null;
@@ -4572,18 +5743,18 @@ async function splitLipSet(keyedPng, w, h, interior) {
4572
5743
  }
4573
5744
  const centre = Math.round((hb.x0 + hb.x1) / 2);
4574
5745
  let stroke = 0;
4575
- while (top[centre] - 1 - stroke >= 0 && alpha((top[centre] - 1 - stroke) * w + centre) >= import_editor8.ALPHA_OPAQUE)
5746
+ while (top[centre] - 1 - stroke >= 0 && alpha((top[centre] - 1 - stroke) * w + centre) >= import_editor9.ALPHA_OPAQUE)
4576
5747
  stroke++;
4577
5748
  const bandCap = BAND_CAP * Math.max(1, stroke);
4578
5749
  const skinRow = new Int32Array(w).fill(-1);
4579
5750
  const inM = new Uint8Array(n);
4580
5751
  for (let x = hb.x0; x <= hb.x1; x++) {
4581
5752
  let y = bot[x];
4582
- while (y < h && y - bot[x] < bandCap && alpha(y * w + x) >= import_editor8.ALPHA_OPAQUE && luma(frame, (y * w + x) * 4) < BAND_LUMA)
5753
+ while (y < h && y - bot[x] < bandCap && alpha(y * w + x) >= import_editor9.ALPHA_OPAQUE && luma(frame, (y * w + x) * 4) < BAND_LUMA)
4583
5754
  y++;
4584
5755
  for (let k = top[x]; k < y; k++) inM[k * w + x] = 1;
4585
5756
  let r = y;
4586
- while (r < h && alpha(r * w + x) < import_editor8.ALPHA_OPAQUE) r++;
5757
+ while (r < h && alpha(r * w + x) < import_editor9.ALPHA_OPAQUE) r++;
4587
5758
  if (r < h) {
4588
5759
  skinRow[x] = r;
4589
5760
  inM[r * w + x] = 1;
@@ -4593,7 +5764,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
4593
5764
  for (let y = 0; y < h; y++) {
4594
5765
  for (let x = 0; x < w; x++) {
4595
5766
  const p = y * w + x;
4596
- if (inM[p] || alpha(p) < import_editor8.ALPHA_OPAQUE) continue;
5767
+ if (inM[p] || alpha(p) < import_editor9.ALPHA_OPAQUE) continue;
4597
5768
  if (top[x] >= 0 && y < top[x]) continue;
4598
5769
  if (x > 0 && inM[p - 1] || x < w - 1 && inM[p + 1]) grown[p] = 1;
4599
5770
  }
@@ -4603,7 +5774,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
4603
5774
  if (x < 0 || x >= w) continue;
4604
5775
  let first = 0;
4605
5776
  while (first < h && !(grown[first * w + x] && !inM[first * w + x])) first++;
4606
- if (first > 0 && first < h && alpha((first - 1) * w + x) >= import_editor8.ALPHA_OPAQUE)
5777
+ if (first > 0 && first < h && alpha((first - 1) * w + x) >= import_editor9.ALPHA_OPAQUE)
4607
5778
  wall[x] = 1;
4608
5779
  }
4609
5780
  const gx = hb.x0 - 1;
@@ -4630,7 +5801,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
4630
5801
  if (inOpening && skinRow[x] >= 0 && y >= skinRow[x]) copy(lower, p);
4631
5802
  if (!grown[p]) {
4632
5803
  const a = alpha(p);
4633
- if (a >= import_editor8.ALPHA_OPAQUE && a < 255 && besideHole(p, x, y)) {
5804
+ if (a >= import_editor9.ALPHA_OPAQUE && a < 255 && besideHole(p, x, y)) {
4634
5805
  inner.set(interior.cavity, p * 4);
4635
5806
  inner[p * 4 + 3] = 255 - a;
4636
5807
  }
@@ -4695,7 +5866,7 @@ async function restShiftOf(layers, width, height) {
4695
5866
  }
4696
5867
  byRole.set(role, layer);
4697
5868
  }
4698
- return (0, import_editor8.mouthRestShift)(byRole);
5869
+ return (0, import_editor9.mouthRestShift)(byRole);
4699
5870
  }
4700
5871
  async function closedLips(upper, lower, shift, left, top) {
4701
5872
  const shut = async (png, role) => {
@@ -4745,7 +5916,7 @@ async function closedLips(upper, lower, shift, left, top) {
4745
5916
  }
4746
5917
 
4747
5918
  // src/measure-lips.ts
4748
- var isLipLayerRole = (role) => import_editor9.LIP_ROLES.includes(role) || (0, import_editor9.isLipInsideRole)(role);
5919
+ var isLipLayerRole = (role) => import_editor10.LIP_ROLES.includes(role) || (0, import_editor10.isLipInsideRole)(role);
4749
5920
  var MIN_OPENING_ROWS = 8;
4750
5921
  var MIN_LINE_ROWS = 2;
4751
5922
  var GREEN_EXCESS = 40;
@@ -4753,8 +5924,8 @@ var INTERIOR_GAP_FRACTION = 0.05;
4753
5924
  var columns = (cols) => `${cols.length} column${cols.length === 1 ? "" : "s"} (first at x=${cols[0]})`;
4754
5925
  async function lipWarnings(absDir, layers) {
4755
5926
  const warnings = [];
4756
- const present = import_editor9.LIP_ROLES.filter((role) => layers[role] !== void 0);
4757
- const inside = import_editor9.LIP_INSIDE_ROLES.filter((role) => layers[role] !== void 0);
5927
+ const present = import_editor10.LIP_ROLES.filter((role) => layers[role] !== void 0);
5928
+ const inside = import_editor10.LIP_INSIDE_ROLES.filter((role) => layers[role] !== void 0);
4758
5929
  if (present.length === 0) {
4759
5930
  if (inside.length > 0) {
4760
5931
  warnings.push(
@@ -4771,8 +5942,8 @@ async function lipWarnings(absDir, layers) {
4771
5942
  `${present.join("/")}: the lip set cannot be mixed with ${legacy.join("/")} \u2014 auto_rig_from_layers refuses it. Remove one route: compose again with only mouth_keyed.png + mouth_interior.png, or without them.`
4772
5943
  );
4773
5944
  }
4774
- if (present.length < import_editor9.LIP_ROLES.length) {
4775
- const missing = import_editor9.LIP_ROLES.filter((role) => layers[role] === void 0);
5945
+ if (present.length < import_editor10.LIP_ROLES.length) {
5946
+ const missing = import_editor10.LIP_ROLES.filter((role) => layers[role] === void 0);
4776
5947
  warnings.push(
4777
5948
  `${present.join("/")}: partial lip set, missing ${missing.join("/")} \u2014 auto_rig_from_layers refuses it. Compose mouth_keyed.png + mouth_interior.png together, which cuts all three.`
4778
5949
  );
@@ -4803,18 +5974,18 @@ async function lipWarnings(absDir, layers) {
4803
5974
  );
4804
5975
  }
4805
5976
  }
4806
- const measurer = (0, import_editor9.createLayerSetMeasurer)({
5977
+ const measurer = (0, import_editor10.createLayerSetMeasurer)({
4807
5978
  width: inner.canvasW,
4808
5979
  height: inner.canvasH
4809
5980
  });
4810
5981
  const set = /* @__PURE__ */ new Map();
4811
5982
  const green = [];
4812
- for (const role of import_editor9.LIP_ROLES) {
5983
+ for (const role of import_editor10.LIP_ROLES) {
4813
5984
  const fileName = `${role}.png`;
4814
5985
  const { rgba } = await decodePng(import_node_path7.default.join(absDir, fileName));
4815
5986
  set.set(role, measurer.add({ role, fileName, rgba }));
4816
5987
  for (let i = 0; i < rgba.length; i += 4) {
4817
- if (rgba[i + 3] >= import_editor9.ALPHA_OPAQUE && rgba[i + 1] - Math.max(rgba[i], rgba[i + 2]) > GREEN_EXCESS) {
5988
+ if (rgba[i + 3] >= import_editor10.ALPHA_OPAQUE && rgba[i + 1] - Math.max(rgba[i], rgba[i + 2]) > GREEN_EXCESS) {
4818
5989
  green.push(role);
4819
5990
  break;
4820
5991
  }
@@ -4822,15 +5993,15 @@ async function lipWarnings(absDir, layers) {
4822
5993
  }
4823
5994
  let opening;
4824
5995
  try {
4825
- opening = (0, import_editor9.mouthOpening)(set);
5996
+ opening = (0, import_editor10.mouthOpening)(set);
4826
5997
  } catch (err) {
4827
- if (err instanceof import_editor9.LayerGeometryError) {
5998
+ if (err instanceof import_editor10.LayerGeometryError) {
4828
5999
  warnings.push(err.message);
4829
6000
  return { warnings };
4830
6001
  }
4831
6002
  throw err;
4832
6003
  }
4833
- const innerRuns = (0, import_editor9.columnRuns)(set.get("mouth_inner"));
6004
+ const innerRuns = (0, import_editor10.columnRuns)(set.get("mouth_inner"));
4834
6005
  const noInterior = [];
4835
6006
  const gap = [];
4836
6007
  const noLine = [];
@@ -4916,8 +6087,8 @@ async function lipWarnings(absDir, layers) {
4916
6087
 
4917
6088
  // src/measure-turn.ts
4918
6089
  var import_node_path8 = __toESM(require("path"));
4919
- var import_editor10 = require("@ikijs/editor");
4920
6090
  var import_editor11 = require("@ikijs/editor");
6091
+ var import_editor12 = require("@ikijs/editor");
4921
6092
  var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
4922
6093
  var IRIS_V_MIN = 0.18;
4923
6094
  var IRIS_V_MAX = 0.95;
@@ -5067,7 +6238,7 @@ async function measureTurnImage(filePath, iris) {
5067
6238
  let transparent = false;
5068
6239
  if (hasAlpha) {
5069
6240
  for (let i = 0; i < n; i++) {
5070
- if (rgba[i * 4 + 3] < import_editor10.ALPHA_OPAQUE) {
6241
+ if (rgba[i * 4 + 3] < import_editor11.ALPHA_OPAQUE) {
5071
6242
  transparent = true;
5072
6243
  break;
5073
6244
  }
@@ -5078,7 +6249,7 @@ async function measureTurnImage(filePath, iris) {
5078
6249
  const fg = new Uint8Array(n);
5079
6250
  const value = new Float32Array(n);
5080
6251
  for (let i = 0; i < n; i++) {
5081
- if (rgba[i * 4 + 3] < import_editor10.ALPHA_OPAQUE) continue;
6252
+ if (rgba[i * 4 + 3] < import_editor11.ALPHA_OPAQUE) continue;
5082
6253
  const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);
5083
6254
  if (maskMode === "alpha") {
5084
6255
  fg[i] = 1;
@@ -5144,12 +6315,12 @@ async function measureTurnImage(filePath, iris) {
5144
6315
  }
5145
6316
  const [irisL, irisR] = best.pair;
5146
6317
  const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);
5147
- const { left, right } = (0, import_editor10.foregroundSpan)(
6318
+ const { left, right } = (0, import_editor11.foregroundSpan)(
5148
6319
  fg,
5149
6320
  width,
5150
6321
  height,
5151
- eyeRow - import_editor10.HEAD_BAND,
5152
- eyeRow + import_editor10.HEAD_BAND
6322
+ eyeRow - import_editor11.HEAD_BAND,
6323
+ eyeRow + import_editor11.HEAD_BAND
5153
6324
  );
5154
6325
  if (right <= left) {
5155
6326
  throw new AutoRigInputError(
@@ -5173,7 +6344,7 @@ async function measureTurnImage(filePath, iris) {
5173
6344
  left,
5174
6345
  right,
5175
6346
  cx: (left + right) / 2,
5176
- half: (0, import_editor10.headHalfOf)({ left, right })
6347
+ half: (0, import_editor11.headHalfOf)({ left, right })
5177
6348
  },
5178
6349
  pairCx: (irisL.cx + irisR.cx) / 2,
5179
6350
  eyeGap: irisR.cx - irisL.cx
@@ -5364,7 +6535,7 @@ function noseSpeckWarning({ core, part }, source) {
5364
6535
  `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,
5365
6536
  `auto_rig_from_layers turns and tilts the nose about its whole crop instead`
5366
6537
  ];
5367
- return `nose: ${found} \u2014 under ${import_editor11.SPECK_CORE_FRACTION} of its width or height, a speck: a lone nostril mark or highlight at alpha >= 128, not the drawing, so ${consequence}. Regenerate the nose with its shading painted denser, so the drawing itself reaches alpha 128. Billed.`;
6538
+ return `nose: ${found} \u2014 under ${import_editor12.SPECK_CORE_FRACTION} of its width or height, a speck: a lone nostril mark or highlight at alpha >= 128, not the drawing, so ${consequence}. Regenerate the nose with its shading painted denser, so the drawing itself reaches alpha 128. Billed.`;
5368
6539
  }
5369
6540
  async function lashOffSclera(eyePath, lashPath) {
5370
6541
  const eye = await decodePng(eyePath);
@@ -5382,7 +6553,7 @@ async function lashOffSclera(eyePath, lashPath) {
5382
6553
  return { opaque, off };
5383
6554
  }
5384
6555
  async function measureDir(absDir, noseSpeck) {
5385
- const files = import_node_fs6.default.readdirSync(absDir).filter((f) => f.endsWith(".png") && !f.startsWith("preview")).sort();
6556
+ const files = import_node_fs7.default.readdirSync(absDir).filter((f) => f.endsWith(".png") && !f.startsWith("preview")).sort();
5386
6557
  if (files.length === 0) {
5387
6558
  throw new AutoRigInputError(`no role layers in ${absDir}`);
5388
6559
  }
@@ -5502,10 +6673,10 @@ async function measureDir(absDir, noseSpeck) {
5502
6673
  warnings.push(noseSpeckWarning(noseSpeck, "compose"));
5503
6674
  } else if (layers.nose !== void 0) {
5504
6675
  const nose = await decodePng(import_node_path9.default.join(absDir, "nose.png"));
5505
- const core = (0, import_editor11.denseCoreOf)(nose.rgba, nose.width, nose.height);
6676
+ const core = (0, import_editor12.denseCoreOf)(nose.rgba, nose.width, nose.height);
5506
6677
  if (core !== null) {
5507
6678
  const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);
5508
- if ((0, import_editor11.isSpeckCore)(core, crop))
6679
+ if ((0, import_editor12.isSpeckCore)(core, crop))
5509
6680
  warnings.push(noseSpeckWarning({ core, part: crop }, "layer"));
5510
6681
  }
5511
6682
  }
@@ -5576,12 +6747,12 @@ function formatMeasureReport(result) {
5576
6747
 
5577
6748
  // src/compose-arms.ts
5578
6749
  var import_sharp3 = __toESM(require("sharp"));
5579
- var import_editor12 = require("@ikijs/editor");
6750
+ var import_editor13 = require("@ikijs/editor");
5580
6751
  var ARM_WIDTH = 0.4;
5581
6752
  var SHOULDER_DROP = 0.12;
5582
6753
  async function armPlacement(role, cfg, part, body) {
5583
6754
  const { data } = await (0, import_sharp3.default)(part.buf).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
5584
- const layer = (0, import_editor12.createLayerSetMeasurer)({ width: part.w, height: part.h }).add({
6755
+ const layer = (0, import_editor13.createLayerSetMeasurer)({ width: part.w, height: part.h }).add({
5585
6756
  role,
5586
6757
  fileName: "arm.png",
5587
6758
  rgba: data
@@ -5593,9 +6764,9 @@ async function armPlacement(role, cfg, part, body) {
5593
6764
  }
5594
6765
  let g;
5595
6766
  try {
5596
- g = (0, import_editor12.armGeometry)(layer, role === "arm_R" ? Infinity : -Infinity);
6767
+ g = (0, import_editor13.armGeometry)(layer, role === "arm_R" ? Infinity : -Infinity);
5597
6768
  } catch (err) {
5598
- if (err instanceof import_editor12.LayerGeometryError) {
6769
+ if (err instanceof import_editor13.LayerGeometryError) {
5599
6770
  throw new AutoRigInputError(`layout.${role}: ${err.message}`);
5600
6771
  }
5601
6772
  throw err;
@@ -5622,7 +6793,7 @@ async function armPlacement(role, cfg, part, body) {
5622
6793
  }
5623
6794
  async function poseGeometryOf(role, png, size, when) {
5624
6795
  const { data } = await (0, import_sharp3.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
5625
- const layer = (0, import_editor12.createLayerSetMeasurer)({
6796
+ const layer = (0, import_editor13.createLayerSetMeasurer)({
5626
6797
  width: size.w,
5627
6798
  height: size.h
5628
6799
  }).add({ role, fileName: "forearm_pose.png", rgba: data });
@@ -5631,7 +6802,7 @@ async function poseGeometryOf(role, png, size, when) {
5631
6802
  `layout.${role}: forearm_pose.png is empty after alpha threshold${when}`
5632
6803
  );
5633
6804
  }
5634
- return (0, import_editor12.forearmPoseGeometry)(layer);
6805
+ return (0, import_editor13.forearmPoseGeometry)(layer);
5635
6806
  }
5636
6807
  async function forearmPoseWidth(role, trimmed, elbowRun) {
5637
6808
  const g = await poseGeometryOf(role, trimmed.data, trimmed, "");
@@ -5929,18 +7100,18 @@ function keyWhiteToAlpha(rgba) {
5929
7100
  async function coreAndBoundsOf(png) {
5930
7101
  const { data, info } = await (0, import_sharp4.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
5931
7102
  return {
5932
- core: (0, import_editor11.denseCoreOf)(data, info.width, info.height),
7103
+ core: (0, import_editor12.denseCoreOf)(data, info.width, info.height),
5933
7104
  bounds: { x: 0, y: 0, w: info.width, h: info.height }
5934
7105
  };
5935
7106
  }
5936
7107
  async function hasCoverage(png) {
5937
7108
  const { data, info } = await (0, import_sharp4.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
5938
- return (0, import_editor13.detectAlphaBbox)(data, info.width, info.height) !== null;
7109
+ return (0, import_editor14.detectAlphaBbox)(data, info.width, info.height) !== null;
5939
7110
  }
5940
7111
  async function noseSizingOf(png) {
5941
7112
  const { core, bounds } = await coreAndBoundsOf(png);
5942
7113
  if (core === null) return { box: bounds, whole: true };
5943
- if ((0, import_editor11.isSpeckCore)(core, bounds)) {
7114
+ if ((0, import_editor12.isSpeckCore)(core, bounds)) {
5944
7115
  return {
5945
7116
  box: bounds,
5946
7117
  whole: true,
@@ -5958,7 +7129,7 @@ async function trimmedPart(role, cfg, partsDir, inMemory, flipSource) {
5958
7129
  img = (0, import_sharp4.default)(inMemory);
5959
7130
  } else {
5960
7131
  const srcPath = import_node_path10.default.join(partsDir, cfg.src);
5961
- if (!import_node_fs7.default.existsSync(srcPath)) {
7132
+ if (!import_node_fs8.default.existsSync(srcPath)) {
5962
7133
  if (cfg.optional) return null;
5963
7134
  throw new AutoRigInputError(
5964
7135
  `missing part source for role "${role}": ${srcPath}` + (role === "mouth" ? " \u2014 draw mouth.png (with mouth_open.png), or the lip set's mouth_keyed.png + mouth_interior.png" : "")
@@ -6062,7 +7233,7 @@ function detachedAboveWhite(rgba, W, H) {
6062
7233
  for (let p = 0; p < n; p++) {
6063
7234
  const alpha = rgba[p * 4 + 3];
6064
7235
  if (alpha > 0 && luma(rgba, p * 4) >= EYE_LASH_LUMA)
6065
- ink[p] = alpha >= import_editor13.ALPHA_OPAQUE ? 2 : 1;
7236
+ ink[p] = alpha >= import_editor14.ALPHA_OPAQUE ? 2 : 1;
6066
7237
  }
6067
7238
  const label = new Int32Array(n).fill(-1);
6068
7239
  const stack = new Int32Array(n);
@@ -6143,7 +7314,7 @@ function detachedAboveWhite(rgba, W, H) {
6143
7314
  }
6144
7315
  async function prepEyeSplit(partsDir) {
6145
7316
  const srcPath = import_node_path10.default.join(partsDir, EYEWHITE_SRC);
6146
- if (!import_node_fs7.default.existsSync(srcPath)) {
7317
+ if (!import_node_fs8.default.existsSync(srcPath)) {
6147
7318
  throw new AutoRigInputError(`missing eyewhite source: ${srcPath}`);
6148
7319
  }
6149
7320
  const { width: W, height: H, rgba: data } = await decodePng(srcPath);
@@ -6167,7 +7338,7 @@ async function prepEyeSplit(partsDir) {
6167
7338
  const lashCutoffY = minY + LASH_KEEP_FRACTION * (maxY - minY + 1);
6168
7339
  const detached = detachedAboveWhite(data, W, H);
6169
7340
  const isDark = (i) => data[i + 3] > 0 && luma(data, i) < EYE_LASH_LUMA;
6170
- const isLight = (i) => data[i + 3] >= import_editor13.ALPHA_OPAQUE && luma(data, i) >= EYE_LASH_LUMA;
7341
+ const isLight = (i) => data[i + 3] >= import_editor14.ALPHA_OPAQUE && luma(data, i) >= EYE_LASH_LUMA;
6171
7342
  const isWarm = (i) => data[i] - data[i + 2] >= EYE_LID_WARMTH;
6172
7343
  const whiteTop = new Int32Array(W).fill(-1);
6173
7344
  for (let x = 0; x < W; x++) {
@@ -6230,7 +7401,7 @@ function hasTransparency(rgba) {
6230
7401
  return false;
6231
7402
  }
6232
7403
  async function prepLipSources(partsDir, mirrored) {
6233
- const has = (name) => import_node_fs7.default.existsSync(import_node_path10.default.join(partsDir, name));
7404
+ const has = (name) => import_node_fs8.default.existsSync(import_node_path10.default.join(partsDir, name));
6234
7405
  const keyed = has(KEYED_SRC);
6235
7406
  const interior = has(INTERIOR_SRC);
6236
7407
  if (keyed && !interior) {
@@ -6273,7 +7444,7 @@ async function composeLayersFromParts(input) {
6273
7444
  try {
6274
7445
  const outDir = resolveOutputDir(input.outDir);
6275
7446
  const partsDir = resolveInputDir(input.partsDir);
6276
- if (import_node_fs7.default.realpathSync(partsDir) === outDir) {
7447
+ if (import_node_fs8.default.realpathSync(partsDir) === outDir) {
6277
7448
  throw new AutoRigInputError(
6278
7449
  `partsDir and outDir resolve to the same directory (${outDir}): composing would overwrite the source parts`
6279
7450
  );
@@ -6337,7 +7508,7 @@ async function composeLayersFromParts(input) {
6337
7508
  lip_lower: split2.lower,
6338
7509
  lip_upper: split2.upper
6339
7510
  }[role];
6340
- if ((0, import_editor13.isLipInsideRole)(role) && !await hasCoverage(buf)) {
7511
+ if ((0, import_editor14.isLipInsideRole)(role) && !await hasCoverage(buf)) {
6341
7512
  skipped.push(role);
6342
7513
  continue;
6343
7514
  }
@@ -6352,7 +7523,7 @@ async function composeLayersFromParts(input) {
6352
7523
  }
6353
7524
  if (key === "arm_L" || key === "arm_R") {
6354
7525
  const arm = layout[key];
6355
- if (!import_node_fs7.default.existsSync(import_node_path10.default.join(partsDir, arm.src))) continue;
7526
+ if (!import_node_fs8.default.existsSync(import_node_path10.default.join(partsDir, arm.src))) continue;
6356
7527
  const body = placed.find((p) => p.role === "body");
6357
7528
  if (body === void 0) {
6358
7529
  throw new AutoRigInputError(
@@ -6395,7 +7566,7 @@ async function composeLayersFromParts(input) {
6395
7566
  }
6396
7567
  if (key === "forearm_pose_L" || key === "forearm_pose_R") {
6397
7568
  const pose = layout[key];
6398
- if (!import_node_fs7.default.existsSync(import_node_path10.default.join(partsDir, pose.src))) continue;
7569
+ if (!import_node_fs8.default.existsSync(import_node_path10.default.join(partsDir, pose.src))) continue;
6399
7570
  const armRole = key === "forearm_pose_L" ? "arm_L" : "arm_R";
6400
7571
  const arm = placed.find((p) => p.role === armRole);
6401
7572
  if (arm?.elbow === void 0 || arm.elbowRun === void 0) {
@@ -6512,11 +7683,11 @@ async function composeLayersFromParts(input) {
6512
7683
  );
6513
7684
  for (const role of ORDER) {
6514
7685
  if (placed.some((p) => p.role === role)) continue;
6515
- import_node_fs7.default.rmSync(import_node_path10.default.join(outDir, `${role}.png`), { force: true });
7686
+ import_node_fs8.default.rmSync(import_node_path10.default.join(outDir, `${role}.png`), { force: true });
6516
7687
  }
6517
7688
  const posed = (role) => role === "forearm_pose_L" || role === "forearm_pose_R";
6518
7689
  if (!placed.some((p) => posed(p.role))) {
6519
- import_node_fs7.default.rmSync(import_node_path10.default.join(outDir, "preview-pose.png"), { force: true });
7690
+ import_node_fs8.default.rmSync(import_node_path10.default.join(outDir, "preview-pose.png"), { force: true });
6520
7691
  }
6521
7692
  const layers = [];
6522
7693
  for (const { role, part, left, top } of placed) {
@@ -6532,7 +7703,7 @@ async function composeLayersFromParts(input) {
6532
7703
  });
6533
7704
  }
6534
7705
  const restInput = (role, buf) => {
6535
- if (role === "mouth_inner" || (0, import_editor13.isLipInsideRole)(role)) return null;
7706
+ if (role === "mouth_inner" || (0, import_editor14.isLipInsideRole)(role)) return null;
6536
7707
  if (closed === void 0) return buf;
6537
7708
  if (role === "lip_upper") return closed.upper;
6538
7709
  if (role === "lip_lower") return closed.lower;
@@ -6659,8 +7830,21 @@ function formatPatchReports(reports) {
6659
7830
  return `PATCH ${r.index} ${r.target} at ${at}: ${r.moved} of ${r.of} points (${where}), largest move ${r.maxPx} model px`;
6660
7831
  });
6661
7832
  }
7833
+ function formatCustomPartReports(parts) {
7834
+ return parts.map((p) => {
7835
+ const line = `CUSTOM ${p.id}: box ${p.box.x},${p.box.y} ${p.box.w}x${p.box.h} px, mesh ${p.mesh.vertices} vertices ${p.mesh.triangles} triangles, order ${p.order}, atlas page ${p.page}`;
7836
+ if (p.occlusion === void 0) return line;
7837
+ const { by, parameter, stops } = p.occlusion;
7838
+ return `${line}, hidden by ${by.join(",")} on ${parameter} at ${stops.map((s) => `${s.value}:${s.amount}`).join(" ")}`;
7839
+ });
7840
+ }
7841
+ function formatBakeChecks(bakes) {
7842
+ return bakes.map(
7843
+ (b) => `BAKE ${b.part} ${b.param}: ${b.vertices} vertices, stops ${b.stops.join(",")}, error ${Math.round(b.errorPx * 1e3) / 1e3} px`
7844
+ );
7845
+ }
6662
7846
  function createIkiMcpServer() {
6663
- const server = new import_mcp.McpServer({ name: "iki", version: "0.33.1" });
7847
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.35.0" });
6664
7848
  server.registerTool(
6665
7849
  "validate_iki",
6666
7850
  {
@@ -6752,7 +7936,7 @@ function createIkiMcpServer() {
6752
7936
  server.registerTool(
6753
7937
  "auto_rig_from_layers",
6754
7938
  {
6755
- description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R and either mouth or the lip set (mouth_inner + lip_lower + lip_upper, a mouth that folds open instead of crossfading) required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, hair_side_L/hair_side_R, mouth_tongue/mouth_teeth (only with the lip set: drawn under its lips and clipped to mouth_inner), etc. optional; an arm needs the body, a pose forearm needs its arm, a side lock needs hair_front, and a partial lip set, one mixed with mouth/mouth_open, or mouth_tongue/mouth_teeth without it is refused) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given. The result's `folds` is the written rig's fold report, printed after the path the way render_poses prints it, and report-only: a fold never refuses the rig. The `RIGPLAN:` line (the result's `rigPlan`: `effective`, `clamped`, `overriddenBy`) follows the path and precedes the `PATCH` lines. The `PHYSICS` lines follow the fold report (the result's `physics`), one per physics rig output \u2014 a spring's, or each chain segment's \u2014 reading ok, frozen or unstable with the step and idle amplitudes, or `PHYSICS: no rigs`; report-only too. With side locks and a `nose` (which `turn` needs) the `HAIRSIDE` lines follow the `PHYSICS` lines (the result's `turn.hairSide`), each naming the lock's role, report-only as well. `patches` (see its field) adds displacements to existing keyform stops of the freshly generated rig; each op then prints one line between the path and the fold report \u2014 `PATCH <i> <target> at <Param=v \u2026>: <moved> of <of> points (cols a-b, rows c-d), largest move <maxPx> model px`, with `(vertices)` in place of the columns and rows for a mesh part \u2014 and the result's `patches` carries the same reports (`index`, `target`, `at`, `moved`, `of`, `cols`/`rows` for a grid, `maxPx`), present whenever `patches` was passed, `[]` included. An op the input schema accepts but the rig refuses comes back as `INVALID: patches[i]\u2026` and nothing is written; an op with a missing field or a field of the wrong type is the SDK's input validation error.",
7939
+ description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R and either mouth or the lip set (mouth_inner + lip_lower + lip_upper, a mouth that folds open instead of crossfading) required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, hair_side_L/hair_side_R, mouth_tongue/mouth_teeth (only with the lip set: drawn under its lips and clipped to mouth_inner), etc. optional; an arm needs the body, a pose forearm needs its arm, a side lock needs hair_front, and a partial lip set, one mixed with mouth/mouth_open, or mouth_tongue/mouth_teeth without it is refused) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given. The result's `folds` is the written rig's fold report, printed after the path the way render_poses prints it, and report-only: a fold never refuses the rig. The `RIGPLAN:` line (the result's `rigPlan`: `effective`, `clamped`, `overriddenBy`) follows the path and precedes the `PATCH` lines. The `PHYSICS` lines follow the fold report (the result's `physics`), one per physics rig output \u2014 a spring's, or each chain segment's \u2014 reading ok, frozen or unstable with the step and idle amplitudes, or `PHYSICS: no rigs`; report-only too. With side locks and a `nose` (which `turn` needs) the `HAIRSIDE` lines follow the `PHYSICS` lines (the result's `turn.hairSide`), each naming the lock's role, report-only as well. `patches` (see its field) adds displacements to existing keyform stops of the freshly generated rig; each op then prints one line between the path and the fold report \u2014 `PATCH <i> <target> at <Param=v \u2026>: <moved> of <of> points (cols a-b, rows c-d), largest move <maxPx> model px`, with `(vertices)` in place of the columns and rows for a mesh part \u2014 and the result's `patches` carries the same reports (`index`, `target`, `at`, `moved`, `of`, `cols`/`rows` for a grid, `maxPx`), present whenever `patches` was passed, `[]` included. An op the input schema accepts but the rig refuses comes back as `INVALID: patches[i]\u2026` and nothing is written; an op with a missing field or a field of the wrong type is the SDK's input validation error. `customParts` adds parts the rig has no role for (a twin tail, a hairpin), each from a canvas-sized PNG of its own, as an unrigged mesh on `headDeformer` after its `after` role's parts; it needs @ikijs/mcp 0.34.0, and an older server drops the field and returns no `customParts`. A part can declare `occlusion` (hidden where named roles' paint covers it, by an amount keyed on a parameter; it needs 0.35.0, and an older server refuses the key as `INVALID: customParts[i]\u2026`); its `CUSTOM <id>:` line then ends `, hidden by <id>,<id>\u2026 on <parameter> at <value>:<amount> <value>:<amount>\u2026`, and the result's part carries `occlusion` (`by` as the part ids written, `parameter`, `stops`). The result's `customParts` (`parts`: `id`, rest `box`, `mesh`, `order`, atlas `page`) is present whenever the input was passed, `[]` included, and one `CUSTOM <id>: \u2026` line per part follows the `HAIRSIDE` lines. `bakes` (see its field) moves the custom parts with a parameter and needs `customParts`; each part and parameter it moves then prints one `BAKE <part> <param>: <n> vertices, stops <values>, error <px> px` line after the `CUSTOM` lines (the result's `customParts.bakes`: `part`, `param`, `vertices`, `stops`, `errorPx`), the written model having been landed through the engine, and a stop off by 0.1 px or more comes back as `INVALID: BAKE ERROR <part> <param>=<value>: \u2026`, and a part the bake moves at rest as `INVALID: BAKE ERROR <part> at rest: \u2026`, with nothing written (the rig and the engine disagree: report it as a bug in the packages). Whenever `customParts` was passed, the written model is also measured per custom part (the result's `customParts.gate`: `ok`, `limits`, `parts`, `failed`) and the text ends with its lines, `CUSTOM <id> FOLDS|TIE|SLIDE|EXPOSED|RIGID|TIP: \u2026` then `CUSTOM GATE pass` or `CUSTOM GATE FAIL: <part LINE, \u2026>`, always the last line: a part's least triangle area ratio, its tie's displacement against the anchor where the head does not turn and where it does, the hidden art showing, how far a rigid part bends and where its free end lands, each in px and face widths with its worst pose; `TIP` never fails the gate and the other lines do. The model is written either way; from 0.34.0 on `customParts` always carries `gate` (a gate that throws still writes the file and ends the text `CUSTOM GATE FAIL: gate error: <message>`), so a result without `customParts` is from an older server and was never gated. The custom layers are not role layers: they are left out of the head's width and turn measurements, and an empty or wrong-size one, or an entry the rig refuses, comes back as `INVALID: customParts[i]\u2026` with nothing written. A missing field or one of the wrong type (a `tie` that is not two numbers, say) is refused by the schema itself, as the SDK's input validation error.",
6756
7940
  inputSchema: {
6757
7941
  layers: import_zod.z.array(
6758
7942
  import_zod.z.object({
@@ -6775,7 +7959,7 @@ function createIkiMcpServer() {
6775
7959
  noseShift: import_zod.z.number().optional(),
6776
7960
  mouthShift: import_zod.z.number().optional()
6777
7961
  }).passthrough().optional().describe(
6778
- "What the head turn is fitted to, as `measure_turn_reference` reports it off a front/turned reference pair. `eyeShift` (and the optional `noseShift`/`mouthShift`) is how far that feature slides across the head at full turn, as a fraction of the head's half-width \u2014 a MAGNITUDE: the rig turns both ways, so the sign is ignored. `farEyeRatio` is the far/near eye width at full turn over that same ratio at rest, `silhouetteRatio` the head's half-width turned over at rest. The half-width the shifts are fractions of is measured off the layers themselves, so it is not an input. An omitted field leaves that part of the turn at the profile the rig defaults to. A passed `eyeShift` is fitted by the turn's amount and clamped to the room the art leaves the far eye \u2014 the face plate's edge, or the bangs' side strand over the far iris (the result's `turn.clamped` lists every clamped field, `turn.achieved` what the rig reaches, and `turn.strandOverlap` how much of a far iris the bangs still cover). A passed `silhouetteRatio` is clamped too, only on a face drawn without hair and with ear islands, where narrowing the head that far would no longer cover the far ear's slide. Any other passed target this layer set cannot reach comes back as `INVALID: \u2026` naming the field and the attainable range, since it is a measurement rather than a preference. A field not named here is refused the same way."
7962
+ "What the head turn is fitted to, as `measure_turn_reference` reports it off a front/turned reference pair. `eyeShift` (and the optional `noseShift`/`mouthShift`) is how far that feature slides across the head at full turn, as a fraction of the head's half-width \u2014 a MAGNITUDE: the rig turns both ways, so the sign is ignored. `farEyeRatio` is the far/near eye width at full turn over that same ratio at rest, `silhouetteRatio` the head's half-width turned over at rest. The half-width the shifts are fractions of is measured off the layers themselves, so it is not an input. An omitted field leaves that part of the turn at the profile the rig defaults to. A passed `eyeShift` is fitted by the turn's amount and clamped to the room the art leaves the far eye \u2014 the face plate's edge, or the bangs' side strand over the far iris (the result's `turn.clamped` lists every clamped field, `turn.achieved` what the rig reaches, and `turn.strandOverlap` how much of a far iris the bangs still cover). A passed `silhouetteRatio` is clamped too, only on a face drawn without hair and with ear islands, where narrowing the head that far would no longer cover the far ear's slide. Any other passed target this layer set cannot reach comes back as `INVALID: \u2026` naming the field and the attainable range, since it is a measurement rather than a preference. A field not named here is refused the same way. A pair that shows a custom part crossing the eye row reads a wider head than the rig fits to, since the rig measures the role layers alone: measure a pair drawn without the custom parts."
6779
7963
  ),
6780
7964
  style: import_zod.z.unknown().optional().describe(
6781
7965
  "Removed in @ikijs/mcp 0.30.0: pass `rigPlan`. Any value here is refused with the field map."
@@ -6796,6 +7980,83 @@ function createIkiMcpServer() {
6796
7980
  }).passthrough().optional().describe(
6797
7981
  "Per-character tuning from the profile the rig defaults to, in three groups: `turn` (`amount`, `featureLead`, `eyeForeshorten`, `noseLead`: the last two turn only, the nod untouched, and fitted by `turnTargets.farEyeRatio` / `turnTargets.noseShift` when those are given, which the `RIGPLAN:` line then reports as overridden), `hair` (`follow`, `outlineFollow`, `sway`) and `eyes` (`blink`). `describe_rig_plan` lists every field's default, range, recommended span, step and poses. A value out of range, or a group or key not named there, comes back as `INVALID: rigPlan.<path> \u2026`; an object left out or `{}` is the profile. The result reports what the rig built with as `rigPlan` and a `RIGPLAN:` line."
6798
7982
  ),
7983
+ customParts: import_zod.z.array(
7984
+ import_zod.z.object({
7985
+ id: import_zod.z.string().describe(
7986
+ "The part's id: a plain identifier, not a role's name or a part id."
7987
+ ),
7988
+ path: import_zod.z.string().describe(
7989
+ "The part's own PNG, the same size as the role layers (resolved against cwd), drawn alone and whole on a transparent ground."
7990
+ ),
7991
+ anchor: import_zod.z.string().describe("The role whose layer the part is fixed against."),
7992
+ tie: import_zod.z.array(import_zod.z.number()).length(2).describe(
7993
+ "[x, y] in canvas px where the part meets the anchor: inside both the part's alpha box and the anchor layer's."
7994
+ ),
7995
+ after: import_zod.z.string().describe(
7996
+ "A role of the set: the part is drawn right after that role's last part."
7997
+ ),
7998
+ deformer: import_zod.z.string().optional().describe(
7999
+ "The matrix deformer it hangs on; only `headDeformer` (the default) is accepted."
8000
+ ),
8001
+ rigid: import_zod.z.boolean().optional().describe(
8002
+ "The art does not bend (a hairpin, a ribbon): a bake that bends it by more than 0.0025 face widths at a stop, from its best-fit rotation and translation, is refused as `INVALID: bakes\u2026` with nothing written. Give a rigid part one displacement for every control point, or a rotation."
8003
+ ),
8004
+ occlusion: import_zod.z.object({
8005
+ by: import_zod.z.array(import_zod.z.string()).describe(
8006
+ "Roles of the set whose paint hides the part (an arm role is its three parts); a non-empty list with no role repeated, each a role of the set. A role with a clipped or meshless part (`iris_L`, `forearm_pose_L`) is refused."
8007
+ ),
8008
+ parameter: import_zod.z.string().describe(
8009
+ "Any declared parameter but a physics output (a spring's or a chain segment's)."
8010
+ ),
8011
+ stops: import_zod.z.array(
8012
+ import_zod.z.object({
8013
+ value: import_zod.z.number(),
8014
+ amount: import_zod.z.number().describe(
8015
+ "0 to 1: 1 hides the part wherever the roles' paint lies over it."
8016
+ )
8017
+ }).passthrough()
8018
+ ).describe(
8019
+ "At least one, `value` strictly ascending and inside the parameter's range. The amount is linear between stops and held before the first and after the last."
8020
+ )
8021
+ }).passthrough().optional().describe(
8022
+ "Hide the part where the named roles' paint covers it, by an amount keyed on a parameter: `{ by, parameter, stops: [{ value, amount }] }`. Cover is where a role's drawn alpha at that pose is at least 0.5, a hard edge; a role that fades (`mouth_open`, a blush, a pose forearm) covers only while drawn at half strength or more. Use the stops as a short switch starting a degree or more past the idle sway, the hiding's progress coming from the part's baked motion. Needs @ikijs/mcp 0.35.0; an older server refuses the key as an unknown key (`INVALID: customParts[i]\u2026`). An unknown key, a bad stop or a part the key cannot be written for comes back as `INVALID: customParts[i].occlusion\u2026` with nothing written."
8023
+ )
8024
+ }).passthrough()
8025
+ ).optional().describe(
8026
+ "Parts the auto-rigger has no role for, each `{ id, path, anchor, tie, after, deformer?, rigid?, occlusion? }`. A custom layer is read apart from `layers`: never role-parsed or measured, so its name is free and it does not widen the head the turn is fitted to; it counts toward the layer and pixel limits. All custom parts share one extra atlas page, the last, quantized on a palette of its own, so the other pages keep their bytes. An entry the rig refuses (an unknown key, a bad tie) comes back as `INVALID: customParts[i]\u2026` with nothing written; a missing field or one of the wrong type (a `tie` that is not two numbers, say) is refused by the schema itself, as the SDK's input validation error. `[]` is the same rig as leaving the field out, plus an empty `customParts` in the result."
8027
+ ),
8028
+ bakes: import_zod.z.object({
8029
+ targets: import_zod.z.array(
8030
+ import_zod.z.object({
8031
+ id: import_zod.z.string().optional(),
8032
+ param: import_zod.z.string(),
8033
+ parts: import_zod.z.array(import_zod.z.string()),
8034
+ box: import_zod.z.object({
8035
+ x: import_zod.z.number(),
8036
+ y: import_zod.z.number(),
8037
+ w: import_zod.z.number(),
8038
+ h: import_zod.z.number()
8039
+ }).passthrough().optional(),
8040
+ grid: import_zod.z.object({ cols: import_zod.z.number(), rows: import_zod.z.number() }).passthrough(),
8041
+ stops: import_zod.z.record(
8042
+ import_zod.z.string(),
8043
+ import_zod.z.array(import_zod.z.array(import_zod.z.number()).length(2))
8044
+ ),
8045
+ mirror: import_zod.z.boolean().optional(),
8046
+ why: import_zod.z.string().optional()
8047
+ }).passthrough()
8048
+ ),
8049
+ meshes: import_zod.z.record(
8050
+ import_zod.z.string(),
8051
+ import_zod.z.object({
8052
+ rows: import_zod.z.array(import_zod.z.number()).optional(),
8053
+ cols: import_zod.z.number().optional(),
8054
+ cellPx: import_zod.z.number().optional()
8055
+ }).passthrough()
8056
+ ).optional()
8057
+ }).passthrough().optional().describe(
8058
+ "Lattices that move the CUSTOM parts when a parameter does, which an unrigged custom part otherwise does not: `{ targets, meshes? }`; it needs `customParts` and names no other part. A target `{ id?, param, parts, box?, grid: { cols, rows }, stops, mirror?, why? }` is `(cols + 1) x (rows + 1)` control points laid evenly over `box` (canvas px; absent, the union of the parts' rest boxes grown by 2 px), listed row-major from the top-left; `stops` is `{ \"<value>\": [[dx, dy], \u2026 one per control point] }`. FRAME: every position and displacement is in canvas px, origin top-left, x right, y DOWN, the frame of the layer PNGs and of `describe_iki`'s boxes and `probe_rig`. A STOP is the part's TOTAL landed displacement from rest when `param` alone is at that value and every other parameter is at its default: the head's own carry is inside it, so a neighbour's displacement as `probe_rig` measures it is written as it is. Stop keys are values of `param` inside its range, never its default (rest is implicit). The landing is exact at rest, at each stop and at one end key at the range end on a side whose outermost stop is inside the range (it holds that stop's displacement); a side with no stop is not moved by the target. Between keys the offsets blend linearly, so under the head's roll (ParamAngleZ) the path bows off the line, about 1 px midway over 15\xB0: put a stop where the path matters. Each vertex takes the bilinear value of the lattice at its REST position, and a vertex outside `box` takes the nearest edge's value. `mirror: true` fills a missing stop from the one at the value mirrored about the rest value, when that value is inside the parameter's range: the lattice reflected about the box's vertical centre line, `dx` negated; a stop you wrote is never overwritten. Targets that name the same part and parameter SUM; a part in targets on two parameters gets one warp per parameter, and the two add in the head's frame, so under a roll a sway tilts with the head. `meshes` re-meshes a custom part before the bake, `{ <id>: { rows: [canvas-px y, \u2026], cols } }` (the first row at the part's top and the last at its bottom, within 0.5 px) or `{ <id>: { cellPx } }`; the rest picture is unchanged. The written model is then landed through the engine at every stop and at the range end each side holds its outermost stop to, and refused when one is off by 0.1 px or more. An input the rig refuses comes back as `INVALID: bakes\u2026` (`bakes.targets[2].stops[\"30\"][7]\u2026`) and nothing is written; a field of the wrong type is refused by the schema itself, as the SDK's input validation error. A bake is measured on one rig: after a retune of the layout or `rigPlan`, a regenerated anchor, a changed custom layer or an accepted patch batch, measure the stops again."
8059
+ ),
6799
8060
  patches: import_zod.z.array(
6800
8061
  import_zod.z.object({
6801
8062
  target: import_zod.z.string(),
@@ -6822,7 +8083,11 @@ function createIkiMcpServer() {
6822
8083
  ...args,
6823
8084
  // `.length(2)` makes each region span a pair, which its inferred
6824
8085
  // `number[]` cannot say.
6825
- patches: args.patches
8086
+ patches: args.patches,
8087
+ customParts: args.customParts,
8088
+ // Each stop's `.length(2)` makes it a pair, which its inferred
8089
+ // `number[]` cannot say.
8090
+ bakes: args.bakes
6826
8091
  });
6827
8092
  const text = r.ok ? [
6828
8093
  r.path,
@@ -6830,7 +8095,10 @@ function createIkiMcpServer() {
6830
8095
  ...formatPatchReports(r.patches ?? []),
6831
8096
  ...formatFoldReport(r.folds, r.canvas),
6832
8097
  ...formatPhysicsReport(r.physics),
6833
- ...formatHairSideReport(r.turn?.hairSide, r.canvas)
8098
+ ...formatHairSideReport(r.turn?.hairSide, r.canvas),
8099
+ ...formatCustomPartReports(r.customParts?.parts ?? []),
8100
+ ...formatBakeChecks(r.customParts?.bakes ?? []),
8101
+ ...r.customParts ? formatCustomGate(r.customParts.gate) : []
6834
8102
  ].join("\n") : `INVALID: ${r.error}`;
6835
8103
  return { content: [{ type: "text", text }], structuredContent: r };
6836
8104
  } catch (err) {
@@ -6922,7 +8190,7 @@ function createIkiMcpServer() {
6922
8190
  server.registerTool(
6923
8191
  "measure_turn_reference",
6924
8192
  {
6925
- 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.",
8193
+ 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. A pair that shows a custom part crossing the eye row reads a wider head than the rig fits to, so measure a pair drawn without the custom parts.",
6926
8194
  inputSchema: {
6927
8195
  front: import_zod.z.string().describe("Front-facing PNG file path (resolved against cwd)."),
6928
8196
  turned: import_zod.z.string().describe("The same character turned, as a PNG file path."),
@@ -7005,7 +8273,10 @@ function createIkiMcpServer() {
7005
8273
  }).optional()
7006
8274
  })
7007
8275
  ).optional().describe(
7008
- "More sweeps rendered after `sweep`, each `{ name, preset, crop? }` into its own `<outDir>/<name>/` (files and `crop` as `sweep`'s). Names are distinct from `sweep`'s and from each other's ignoring case, and presets are distinct (at most one of each). `turn` is `sweep`'s. `turn-nod` is the box (0,0) -> (0,-30) -> (-30,-30) -> (-30,+30) -> (+30,+30) -> (+30,-30) -> (0,-30) -> (0,0) of `ParamAngleX` x `ParamAngleY`, each leg eased, 6 s, 180 frames; its `sheet.png` is a 3 x 3 grid BY ANGLE (columns AngleX -30/0/+30, rows AngleY +30/0/-30, rest in the centre, cells labelled X, Y and t) and it has no kymograph. `manifest.json` is version 2 (`parameters`, and per frame `t` and `values`). A sweep dir's earlier frames, sheet, kymograph, manifest and flipbook are cleared first. An empty list, a repeated name or preset, or a bad crop comes back as `INVALID: sweeps...`. A server before 0.32.0 strips `sweeps` and renders the rest. The `SWEEP nod` lines (the eye-pair and iris-pair gap range and the mouth width range along the nod at each turn, in face widths) and `SWEEP corner` lines (the additivity residual per landmark at the four corners, the rest term included; 0 on an additive rig) print once per call whenever `sweep` or `sweeps` was asked for, report-only like `FOLD` and `PHYSICS`."
8276
+ "More sweeps rendered after `sweep`, each `{ name, preset, crop? }` into its own `<outDir>/<name>/` (files and `crop` as `sweep`'s). Names are distinct from `sweep`'s and from each other's ignoring case, and presets are distinct (at most one of each). `turn` is `sweep`'s. `roll` is the same eased curve on `ParamAngleZ` (0 to -30 to +30 to 0 over 3 s, 90 frames, physics running, idle off); its `sheet.png` is the nine frames nearest the turn sheet's angles on the -30 to +30 leg, labelled with the angle (Z) and time, and it has no kymograph (the eye row moves with the roll). `turn-nod` is the box (0,0) -> (0,-30) -> (-30,-30) -> (-30,+30) -> (+30,+30) -> (+30,-30) -> (0,-30) -> (0,0) of `ParamAngleX` x `ParamAngleY`, each leg eased, 6 s, 180 frames; its `sheet.png` is a 3 x 3 grid BY ANGLE (columns AngleX -30/0/+30, rows AngleY +30/0/-30, rest in the centre, cells labelled X, Y and t) and it has no kymograph. `manifest.json` is version 2 (`parameters`, and per frame `t` and `values`). A sweep dir's earlier frames, sheet, kymograph, manifest and flipbook are cleared first. An empty list, a repeated name or preset, or a bad crop comes back as `INVALID: sweeps...`. A server before 0.32.0 strips `sweeps` and renders the rest. The `SWEEP nod` lines (the eye-pair and iris-pair gap range and the mouth width range along the nod at each turn, in face widths) and `SWEEP corner` lines (the additivity residual per landmark at the four corners, the rest term included; 0 on an additive rig) print once per call whenever `sweep` or `sweeps` was asked for, report-only like `FOLD` and `PHYSICS`. A `roll` adds no `SWEEP` line of its own and changes none: they are read from the model. `roll` needs @ikijs/mcp 0.34.0; an older server refuses it as an input validation error."
8277
+ ),
8278
+ hideParts: import_zod.z.array(import_zod.z.string()).optional().describe(
8279
+ "Part ids left out of the drawn frames (poses and sweeps); the fold, physics and sweep reports still read the whole model. Use it to render a character without its custom parts, so `measure_turn_reference` reads the rig's own head (a custom part crossing the eye row widens the head it measures, as it does on a drawn reference). An id the model lacks, or one that is the clip mask of a part that stays, or one a part that stays names in its `occlusion.by` (hide that part too), comes back as `INVALID: hideParts[i] \u2026` and nothing is rendered. Needs @ikijs/mcp 0.34.0; an older server drops the field and draws every part."
7009
8280
  )
7010
8281
  }
7011
8282
  },
@@ -7041,12 +8312,62 @@ function createIkiMcpServer() {
7041
8312
  }
7042
8313
  }
7043
8314
  );
8315
+ server.registerTool(
8316
+ "probe_rig",
8317
+ {
8318
+ description: "Measures a rigged .iki without rendering it, through the engine's own landing. Each query is one of: `paint` (the opaque runs, alpha 128 and over, of a layer PNG, per canvas row, as `{ y0, rows }` with `[x0, x1)` runs; read from the PNG you give, not the atlas, so a quantized model reads the same, and the PNG must be the model's canvas size), `land` (where each canvas-px point of a part lands in a pose) or `displacement` (the landing minus the point). The frame is canvas px, origin top-left, x right, y down \u2014 the frame of the layer PNGs and describe_iki's boxes. A point is `[x, y]` and must lie on the part at rest, inside one of its mesh triangles (a part without a mesh, its unit quad); its landing is then found by barycentric interpolation inside that triangle. A point outside the part's mesh comes back as `null`, never an extrapolation. `pose` is parameter settings: every parameter it does not name is at its default, a value outside the parameter's range is clamped as the player does, and an id the model does not declare or a non-finite value is refused. The text is the results as JSON, one entry per query in order. With `outputPath` (a `.probe.json` under the working directory, its folder existing) the results are written there as the same JSON and the text is the path and one line per query, so a part's paint stays out of your context for a rigging program to read. A query's refusal comes back as `INVALID: queries[i].<field> \u2026`, any refusal writes nothing.",
8319
+ inputSchema: {
8320
+ modelPath: import_zod.z.string().describe(
8321
+ "Rigged .iki file path (resolved against cwd; must sit under the working directory)."
8322
+ ),
8323
+ queries: import_zod.z.array(
8324
+ import_zod.z.discriminatedUnion("op", [
8325
+ import_zod.z.object({
8326
+ op: import_zod.z.literal("paint"),
8327
+ path: import_zod.z.string().describe(
8328
+ "Canvas-sized layer PNG (resolved against cwd), the drawing the part was built from."
8329
+ )
8330
+ }),
8331
+ import_zod.z.object({
8332
+ op: import_zod.z.enum(["land", "displacement"]),
8333
+ part: import_zod.z.string().describe("A part id of the model."),
8334
+ points: import_zod.z.array(import_zod.z.array(import_zod.z.number()).length(2)).describe(
8335
+ "Canvas-px points `[x, y]`, at most 5000, each on the part at rest."
8336
+ ),
8337
+ pose: import_zod.z.record(import_zod.z.string(), import_zod.z.number()).optional().describe(
8338
+ "Parameter id to value; the others stay at their defaults."
8339
+ )
8340
+ })
8341
+ ])
8342
+ ).describe("The queries, answered in order; at most 64 per call."),
8343
+ outputPath: import_zod.z.string().optional().describe(
8344
+ "A path ending in `.probe.json` (resolved against cwd, under it; its folder must exist) to write the results to."
8345
+ )
8346
+ }
8347
+ },
8348
+ async (args) => {
8349
+ try {
8350
+ const r = await probeRig(args);
8351
+ const text = !r.ok ? `INVALID: ${r.error}` : "results" in r ? JSON.stringify(r.results) : [r.outputPath, ...r.lines].join("\n");
8352
+ return { content: [{ type: "text", text }], structuredContent: r };
8353
+ } catch (err) {
8354
+ const error = err instanceof Error ? err.message : String(err);
8355
+ return {
8356
+ content: [{ type: "text", text: `Unexpected error: ${error}` }],
8357
+ structuredContent: { ok: false, error },
8358
+ isError: true
8359
+ };
8360
+ }
8361
+ }
8362
+ );
7044
8363
  return server;
7045
8364
  }
7046
8365
  // Annotate the CommonJS export names for ESM import in node:
7047
8366
  0 && (module.exports = {
8367
+ CUSTOM_GATE_LIMITS,
7048
8368
  SWEEP_PRESETS,
7049
8369
  autoRigFromLayers,
8370
+ checkCustomGate,
7050
8371
  checkModelFolds,
7051
8372
  checkNod,
7052
8373
  checkSweep,
@@ -7055,6 +8376,8 @@ function createIkiMcpServer() {
7055
8376
  describeIki,
7056
8377
  describeIkiAt,
7057
8378
  describeRigPlan,
8379
+ failedCustomGate,
8380
+ formatCustomGate,
7058
8381
  formatFoldReport,
7059
8382
  formatHairSideReport,
7060
8383
  formatMeasureReport,
@@ -7066,6 +8389,7 @@ function createIkiMcpServer() {
7066
8389
  listStandardParameters,
7067
8390
  measureLayers,
7068
8391
  measureTurnReference,
8392
+ probeRig,
7069
8393
  renderPoses,
7070
8394
  validateIki
7071
8395
  });