@ikijs/mcp 0.29.0 → 0.30.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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.15_supports-color@7.2.0_typescript@5.9.3/node_modules/tsup/assets/cjs_shims.js","../src/tools.ts","../../engine/src/math.ts","../../engine/src/parameter-store.ts","../../engine/src/affine.ts","../../engine/src/warp.ts","../../engine/src/warp-grid.ts","../../engine/src/deform.ts","../../engine/src/idle-motion.ts","../../engine/src/frame-clock.ts","../../engine/src/physics-motion.ts","../../engine/src/hair-chain-motion.ts","../../engine/src/iki-motion.ts","../../engine/src/clip-player.ts","../../engine/src/expression-player.ts","../../engine/src/folds.ts","../../engine/src/land.ts","../../engine/src/physics-check.ts","../../engine/src/physics-runs.ts","../src/fold-report.ts","../src/render-poses.ts","../src/limits.ts","../src/render-browser.ts","../src/node-images.ts","../src/compose.ts","../src/trim.ts","../src/measure.ts","../src/measure-arms.ts","../src/measure-forearm-pose.ts","../src/measure-lips.ts","../src/compose-lips.ts","../src/measure-turn.ts","../src/compose-arms.ts","../src/physics-report.ts","../src/server.ts"],"sourcesContent":["export {\n validateIki,\n describeIki,\n describeIkiAt,\n listStandardParameters,\n autoRigFromLayers,\n type ValidateResult,\n type DescribeResult,\n type IkiSummary,\n type PartSummary,\n type DeformerSummary,\n type StandardParameterInfo,\n type AutoRigInput,\n type AutoRigLayerInput,\n type AutoRigResult,\n type AutoRigTurnTargets,\n type TurnSolveReport,\n} from \"./tools\";\nexport {\n composeLayersFromParts,\n type ComposeInput,\n type ComposeResult,\n type LayoutOverride,\n} from \"./compose\";\nexport {\n measureLayers,\n formatMeasureReport,\n type MeasureInput,\n type MeasureResult,\n} from \"./measure\";\nexport { checkModelFolds, formatFoldReport } from \"./fold-report\";\nexport { formatPhysicsReport } from \"./physics-report\";\nexport {\n measureTurnReference,\n formatTurnReport,\n type MeasureTurnInput,\n type MeasureTurnResult,\n type TurnMeasurement,\n type TurnImageMeasure,\n type IrisBlob,\n type IrisColor,\n} from \"./measure-turn\";\nexport {\n renderPoses,\n type RenderPosesInput,\n type RequestedPose,\n type RenderPosesResult,\n} from \"./render-poses\";\nexport { createIkiMcpServer } from \"./server\";\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n parseIkiModel,\n loadIkiModel,\n IkiFormatError,\n StandardParameter,\n type IkiModel,\n type IkiDeformer,\n} from \"@ikijs/format\";\nimport {\n EditorDocument,\n packAtlas,\n uvRectFor,\n createLayerSetMeasurer,\n generateIkiFromLayerSet,\n parseLayerRoles,\n partIdsOfRole,\n LayerGeometryError,\n PatchError,\n TurnTargetError,\n type IrisStrand,\n type LayerSetMeasurer,\n type AtlasAssignment,\n type AtlasLayout,\n type PatchReport,\n type RigPatch,\n type RigStyle,\n type TurnTargets,\n type TurnSolveReport,\n} from \"@ikijs/editor\";\nimport {\n checkPhysics,\n type FoldReport,\n type PhysicsReport,\n} from \"@ikijs/engine\";\nimport { checkModelFolds } from \"./fold-report\";\nimport { BUST_SIZE, bustPadY } from \"./render-poses\";\nimport {\n decodePng,\n cropToBuffer,\n renderAtlasToDataUri,\n type AtlasCrop,\n} from \"./node-images\";\nimport {\n AutoRigInputError,\n MAX_LAYERS,\n MAX_LAYER_DIM,\n MAX_CANVAS_DIM,\n MAX_ATLAS_SIDE,\n MAX_TOTAL_PIXELS,\n MAX_OUTPUT_BYTES,\n resolveInputPath,\n confineToWorkingDirectory,\n resolveOutputPath,\n writeFileAtomic,\n} from \"./limits\";\n\nexport type ValidateResult = { ok: true } | { ok: false; error: string };\n\nexport interface IkiSummary {\n name: string;\n canvas: { width: number; height: number };\n parameters: { id: string; min: number; max: number; default: number }[];\n parts: PartSummary[];\n deformers: DeformerSummary[];\n /** The `face` part's width in model px: the unit a rig patch op's `by` and `falloff` are measured in. */\n faceWidth?: number;\n /** Bust-render px per model px (`BUST_SIZE / canvas.width`). */\n bustScale: number;\n /** Each expression's id and the description a host picks it by. */\n expressions: { id: string; description: string }[];\n /** Each motion group's clip descriptions, by clip index. */\n motions: Record<string, string[]>;\n}\n\nexport interface PartSummary {\n id: string;\n order: number;\n deformer?: string;\n /** Rest box in model px from the canvas top-left, y down; the frame of the fold lines and `layout.json`. */\n box: { x: number; y: number; w: number; h: number };\n /** The same box in bust-render px, including the padding above a landscape model. */\n bustBox: { x: number; y: number; w: number; h: number };\n /** The part's own warps: parameter and the keyform stop values. */\n warps?: { parameter: string; stops: number[] }[];\n}\n\nexport interface DeformerSummary {\n id: string;\n kind: \"matrix\" | \"warp\";\n parent?: string;\n warp?:\n | { mode: \"1d\"; parameters: string[] }\n | {\n mode: \"2d\";\n parameterX: string;\n parameterY: string;\n gridX: number;\n gridY: number;\n stopsX: number[];\n stopsY: number[];\n };\n}\n\nexport type DescribeResult =\n | { ok: true; summary: IkiSummary }\n | { ok: false; error: string };\n\nexport interface StandardParameterInfo {\n id: string;\n description: string;\n}\n\nfunction coerceModel(\n model: unknown,\n): { ok: true; model: IkiModel } | { ok: false; error: string } {\n try {\n const parsed =\n typeof model === \"string\" ? loadIkiModel(model) : parseIkiModel(model);\n return { ok: true, model: parsed };\n } catch (e) {\n if (e instanceof IkiFormatError) return { ok: false, error: e.message };\n throw e;\n }\n}\n\nexport function validateIki(model: unknown): ValidateResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n return { ok: true };\n}\n\nexport function describeIki(model: unknown): DescribeResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n\n const m = result.model;\n\n const parameters = m.parameters.map((p) => ({\n id: p.id,\n min: p.min,\n max: p.max,\n default: p.default,\n }));\n\n const W = m.canvas.width;\n const H = m.canvas.height;\n const bustScale = BUST_SIZE / W;\n const padY = bustPadY(W, H);\n const tenth = (n: number) => Math.round(n * 10) / 10;\n const parts = m.parts.map((p): PartSummary => {\n // The auto-rig's deformers carry no rest transform, so the part's own\n // transform places it.\n const box = {\n x: W / 2 + p.transform.x - p.width / 2,\n y: H / 2 - p.transform.y - p.height / 2,\n w: p.width,\n h: p.height,\n };\n const entry: PartSummary = {\n id: p.id,\n order: p.order,\n box,\n bustBox: {\n x: tenth(box.x * bustScale),\n y: tenth(padY + box.y * bustScale),\n w: tenth(box.w * bustScale),\n h: tenth(box.h * bustScale),\n },\n };\n if (p.deformer !== undefined) entry.deformer = p.deformer;\n if (p.warps !== undefined && p.warps.length > 0) {\n entry.warps = p.warps.map((w) => ({\n parameter: w.parameter,\n stops: w.keyforms.map((k) => k.value),\n }));\n }\n return entry;\n });\n\n const deformers = (m.deformers ?? []).map(\n (d: IkiDeformer): DeformerSummary => {\n const kind = d.kind === \"warp\" ? \"warp\" : \"matrix\";\n const entry: DeformerSummary = { id: d.id, kind };\n if (d.parent !== undefined) entry.parent = d.parent;\n\n if (d.kind === \"warp\") {\n if (d.warp2d !== undefined) {\n entry.warp = {\n mode: \"2d\",\n parameterX: d.warp2d.parameter,\n parameterY: d.warp2d.parameterY,\n gridX: d.grid.cols,\n gridY: d.grid.rows,\n stopsX: d.warp2d.valuesX,\n stopsY: d.warp2d.valuesY,\n };\n } else if (d.warps !== undefined && d.warps.length > 0) {\n entry.warp = {\n mode: \"1d\",\n parameters: d.warps.map((w) => w.parameter),\n };\n }\n }\n\n return entry;\n },\n );\n\n const expressions = (m.expressions ?? []).map((e) => ({\n id: e.id,\n description: e.description,\n }));\n\n const motions = Object.fromEntries(\n Object.entries(m.motions ?? {}).map(([group, clips]) => [\n group,\n clips.map((c) => c.description),\n ]),\n );\n\n const summary: IkiSummary = {\n name: m.name,\n canvas: { width: m.canvas.width, height: m.canvas.height },\n parameters,\n parts,\n deformers,\n expressions,\n motions,\n bustScale,\n };\n const face = m.parts.find((p) => p.id === \"face\");\n if (face !== undefined) summary.faceWidth = face.width;\n\n return { ok: true, summary };\n}\n\n/**\n * `describeIki` on a written model, read from `modelPath` (confined to the\n * working directory like `renderPoses`), so a large model never crosses an\n * agent's context inline.\n */\nexport function describeIkiAt(modelPath: string): DescribeResult {\n try {\n const modelFile = confineToWorkingDirectory(\n process.cwd(),\n resolveInputPath(modelPath, \"model\"),\n \"model path\",\n modelPath,\n );\n return describeIki(readFileSync(modelFile, \"utf8\"));\n } catch (e) {\n if (e instanceof AutoRigInputError) return { ok: false, error: e.message };\n throw e;\n }\n}\n\n// Static map of standard parameter ids to human-readable descriptions,\n// sourced from JSDoc comments in parameters.ts (including range hints).\nconst STANDARD_PARAMETER_INFO: StandardParameterInfo[] = [\n {\n id: StandardParameter.MouthOpen,\n description: \"Mouth open amount for lip-sync (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.MouthForm,\n description: \"Mouth form / smile (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeOpenLeft,\n description:\n \"Left eye open (0 closed .. 1 open). Drive with the right eye for a blink.\",\n },\n {\n id: StandardParameter.EyeOpenRight,\n description: \"Right eye open (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.EyeballX,\n description: \"Eyeball gaze, horizontal (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeballY,\n description: \"Eyeball gaze, vertical (-1 .. 1).\",\n },\n {\n id: StandardParameter.AngleX,\n description: \"Head angle, horizontal degrees.\",\n },\n {\n id: StandardParameter.AngleY,\n description: \"Head angle, vertical degrees.\",\n },\n {\n id: StandardParameter.AngleZ,\n description:\n \"Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D.\",\n },\n {\n id: StandardParameter.BodyAngleX,\n description:\n \"Body turn, degrees (-10 .. 10); positive turns the body toward the viewer's right, as AngleX does the head.\",\n },\n {\n id: StandardParameter.BodyAngleY,\n description:\n \"Body lean, degrees (-10 .. 10); positive moves the upper body up, negative bows.\",\n },\n {\n id: StandardParameter.BodyAngleZ,\n description:\n \"Body tilt, degrees (-10 .. 10); positive tilts the top toward the viewer's right (clockwise), as AngleZ does the head.\",\n },\n {\n id: StandardParameter.Breath,\n description: \"Idle breath (0 .. 1), cycled by the host.\",\n },\n {\n id: StandardParameter.AmbientSway,\n description:\n \"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.\",\n },\n {\n id: StandardParameter.BrowLeftY,\n description: \"Left brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightY,\n description: \"Right brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowLeftAngle,\n description: \"Left brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightAngle,\n description: \"Right brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.Cheek,\n description: \"Cheek blush strength (0 .. 1), raised by an expression.\",\n },\n {\n id: StandardParameter.HairSwayX,\n description:\n \"Front hair's horizontal sway driver. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n {\n id: StandardParameter.HairSwayZ,\n description:\n \"Front hair's sway driver behind a head tilt. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n {\n id: StandardParameter.HairBackSway,\n description:\n \"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 — driven by the spring, hosts should not set it directly.\",\n },\n {\n id: StandardParameter.ArmLeft,\n description:\n \"Left shoulder, degrees; positive raises the arm outward (mirrored on the right).\",\n },\n {\n id: StandardParameter.ArmRight,\n description:\n \"Right shoulder, degrees; positive raises the arm outward (mirrored on the left).\",\n },\n {\n id: StandardParameter.ElbowLeft,\n description:\n \"Left elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the right).\",\n },\n {\n id: StandardParameter.ElbowRight,\n description:\n \"Right elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the left).\",\n },\n {\n id: StandardParameter.ArmPoseLeft,\n description:\n \"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.\",\n },\n {\n id: StandardParameter.ArmPoseRight,\n description:\n \"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.\",\n },\n {\n id: StandardParameter.ArmPoseAngleLeft,\n description:\n \"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).\",\n },\n {\n id: StandardParameter.ArmPoseAngleRight,\n description:\n \"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).\",\n },\n];\n\nexport function listStandardParameters(): StandardParameterInfo[] {\n return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));\n}\n\n// ── auto_rig_from_layers ──────────────────────────────────────────────────────\n\n/** One role-named PNG layer; role is derived from `fileName ?? basename(path)`. */\nexport interface AutoRigLayerInput {\n fileName?: string;\n path: string;\n}\n\nexport interface AutoRigInput {\n layers: AutoRigLayerInput[];\n /** Output `.iki` path (relative paths resolve against the process cwd). */\n outputPath?: string;\n /** Palette-quantize the atlas PNG to this many colours (integer, 2..256).\n * Omitted = lossless. See renderAtlasToDataUri for the size/quality trade.\n * A `nose` layer is left out of the quantized page, on a second, lossless\n * page of its own, because the palette rims a soft-shaded nose's feather. */\n quantizeColors?: number;\n /** Head-turn cues to fit the rig to, as `measure_turn_reference` reports\n * them. */\n turnTargets?: AutoRigTurnTargets;\n /** Per-character tuning from the profile's defaults (see\n * @ikijs/editor's `RigStyle`). */\n style?: RigStyle;\n /** Displacements added to existing keyform stops of the freshly generated\n * rig, replayed on every rig of these inputs (see @ikijs/editor's\n * `RigPatch`). */\n patches?: RigPatch[];\n}\n\n/** The turn cues a caller may pass, which is every one but `headHalfWidth`:\n * the pixels the shift fractions are fractions of are measured off the layers\n * themselves, not accepted from the caller. */\nexport type AutoRigTurnTargets = Omit<TurnTargets, \"headHalfWidth\">;\n\nexport type AutoRigResult =\n | {\n ok: true;\n path: string;\n canvas: { width: number; height: number };\n partCount: number;\n /** The atlas's embedded size: its data URI's length, summed over both\n * pages when a quantized rig puts the nose on a page of its own. */\n atlasBytes: number;\n /** The head's half-width at the eye row, measured off the layers.\n * Absent when the opaque (alpha >= 128) union has no span there — a\n * layer set painted translucent below that threshold — in which case\n * the face plate stands in for it, same as a span that measures\n * narrower than the plate. */\n headHalfWidth?: number;\n /** Whether the measured value was handed to the generator; the\n * face-half fallback applies otherwise, which is what happens when it\n * is no wider than the face plate, or absent entirely. */\n headHalfWidthApplied: boolean;\n /** Every role with an opaque pixel in the same eye-row band as\n * `headHalfWidth`, per side, each with its own rest x there (canvas px)\n * — present only when `headHalfWidthApplied` is true, since the\n * fallback path has no measured edge to report at all. Passed to the\n * generator so it can land each candidate through its OWN motion\n * (hair_front's silhouette hold, a turn group's grid for the face and\n * its features, the body's own turn translate; `hair_back` holds the\n * outline and lands where it rests, and a role outside that table is\n * refused) and take the outermost LANDING, not just the outermost\n * REST pixel. */\n headEdges?: {\n left: { role: string; x: number }[];\n right: { role: string; x: number }[];\n };\n /** Each side's iris and the `hair_front` run it would slide under on\n * the turn, as pixel edges on the row holding that iris's centre, in\n * model coordinates (`IrisStrand`: canvas x minus half the canvas\n * width) — measured whenever the layer set has `hair_front`, `iris_L`\n * and `iris_R`, and passed to the generator as `options.strandEdges`.\n * A run narrower than half that iris's painted width on the row is\n * hair detail, not a strand, and is skipped as if clear. A side is\n * absent only when its iris has no opaque pixel on that row, or when no\n * run it keeps covers the pixel on that side of the iris's centre or\n * lies outward of it; the whole field only when neither side has one. */\n strandEdges?: { left?: IrisStrand; right?: IrisStrand };\n /** The nose's dense core, canvas px — its pixels at alpha >= 128, not\n * grown — the box handed to the generator as the nose layer's\n * `denseCore` and, there, its turn landmark. Absent without a `nose`\n * layer, when the nose has no pixel at that threshold (painted wholly\n * translucent), or when its core is a speck of its crop\n * (`isSpeckCore`: a lone nostril mark or highlight); the crop stands\n * in for it in both cases. */\n noseCore?: { x: number; y: number; w: number; h: number };\n /** What the turn solve settled on — the cues the rig reaches, the\n * targets it had to cut down (`clamped`) and, per side whose far iris\n * the bangs' run still covers at some far stop, how much of it\n * (`strandOverlap`). Absent for a layer set with no nose, which solves\n * no turn at all. */\n turn?: TurnSolveReport;\n /** The written model's folds over the engine's pose set, its eyes and\n * mouth shutting on purpose set apart as `expected`. Report-only: a\n * fold never refuses the rig. */\n folds: FoldReport;\n /** The written model's physics rigs, each output excited through the\n * engine's real drivers — a step held at the input's far end and the\n * procedural idle — and read as ok, frozen or unstable with both\n * windows' amplitudes. Report-only: it never refuses the rig. */\n physics: PhysicsReport;\n /** What each of `input.patches` moved on this rig, in order — present\n * whenever `patches` was passed, `[]` included, so a caller can tell\n * this server from one that drops the field. */\n patches?: PatchReport[];\n }\n | { ok: false; error: string };\n\nexport type { TurnSolveReport };\n\n/**\n * Run a fallible input/environment-boundary call, re-tagging any throw as an\n * AutoRigInputError with context so the tool reports it as `{ ok:false }` rather\n * than an unexpected `isError`. Use ONLY around true caller-input / filesystem\n * boundaries — never around internal pipeline math (a throw there is a bug).\n */\nfunction expectInput<T>(label: string, fn: () => T): T {\n try {\n return fn();\n } catch (e) {\n throw new AutoRigInputError(\n `${label}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\n/**\n * The role that keeps a lossless atlas page of its own under `quantizeColors`.\n * At 256 colours a soft nose's feather took the hair edge's lavender palette\n * entries and drew a rim around the nose; changing the dither, the effort, the\n * alpha floor or the alpha curve did not fix it. A lossless page for the nose\n * alone did, and the hero's model came to about 1.28 MB, against 3.18 MB with\n * the whole atlas lossless.\n */\nconst LOSSLESS_PAGE_ROLE = \"nose\";\n\n/** Pack `crops` onto one atlas page and render it — palette-quantized to\n * `quantizeColors` when that is set. A page over MAX_ATLAS_SIDE on either side\n * is refused before rendering, naming its widest (or tallest) crop — after\n * every shelf attempt up to and including the max side overflowed. */\nasync function renderAtlasPage(\n crops: AtlasCrop[],\n quantizeColors: number | undefined,\n): Promise<{ crops: AtlasCrop[]; layout: AtlasLayout; dataUri: string }> {\n const layout = packAtlas(\n crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),\n undefined,\n MAX_ATLAS_SIDE,\n );\n const over =\n layout.pageWidth > MAX_ATLAS_SIDE\n ? ({ side: \"width\", crop: \"widest\" } as const)\n : layout.pageHeight > MAX_ATLAS_SIDE\n ? ({ side: \"height\", crop: \"tallest\" } as const)\n : undefined;\n if (over !== undefined) {\n const crop = layout.placements.reduce((a, b) =>\n b[over.side] > a[over.side] ? b : a,\n );\n throw new AutoRigInputError(\n `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max side ${MAX_ATLAS_SIDE} (its ${over.crop} crop: \"${crop.id}\" ${crop.width}x${crop.height})`,\n );\n }\n const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);\n return { crops, layout, dataUri };\n}\n\n/**\n * Decode role-named PNG file paths, auto-rig a model from them, atlas + embed\n * the textures (Node sharp), validate, and write the renderable `.iki` to disk.\n * Returns the output path + summary stats (the multi-MB model is never inlined).\n *\n * The head turn is fitted to `input.turnTargets`, on what @ikijs/editor's\n * `createLayerSetMeasurer` measures off the decoded layers (the head\n * half-width, `headEdges`, `strandEdges`, the face's `rowHalfWidths`, the face's\n * and hair layers' opaque runs and the nose's dense core, returned as\n * `noseCore`); what the solve settled on comes back in `turn`. Under\n * `quantizeColors` the nose is atlased alone on a second, lossless page, which\n * the palette would otherwise rim; `atlasBytes` sums both pages. The\n * generator replays `input.patches` on the fresh rig before it validates and\n * reports the turn, and what each op moved comes back in `patches`; a refused\n * op writes nothing.\n *\n * Re-host of examples/editor/src/store.ts `importLayerSet` with the three DOM\n * pixel functions swapped for the sharp-backed ./node-images helpers; the pure\n * model math is reused from @ikijs/editor.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) → `{ ok:false }`;\n * any other throw (invariant break, programmer bug) propagates to `isError`.\n */\nexport async function autoRigFromLayers(\n input: AutoRigInput,\n): Promise<AutoRigResult> {\n try {\n const layers = input.layers;\n if (!Array.isArray(layers) || layers.length === 0) {\n throw new AutoRigInputError(\"layers must be a non-empty array\");\n }\n if (layers.length > MAX_LAYERS) {\n throw new AutoRigInputError(\n `too many layers: ${layers.length} > ${MAX_LAYERS}`,\n );\n }\n\n // Resolve the output path FIRST (fail-fast): reject a bad/escaping/non-.iki\n // target before spending the image-decode budget on a request that can't\n // be written anyway.\n const outPath = resolveOutputPath(\n input.outputPath ?? \"auto-rigged-model.iki\",\n );\n const quantizeColors = input.quantizeColors;\n if (\n quantizeColors !== undefined &&\n (!Number.isInteger(quantizeColors) ||\n quantizeColors < 2 ||\n quantizeColors > 256)\n ) {\n throw new AutoRigInputError(\n `quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`,\n );\n }\n // Checked before the generator call spreads it: a spread turns null or an\n // array into {}, which would rig on the defaults instead of refusing.\n const turnTargets: unknown = input.turnTargets;\n if (turnTargets !== undefined) {\n if (\n typeof turnTargets !== \"object\" ||\n turnTargets === null ||\n Array.isArray(turnTargets)\n ) {\n throw new AutoRigInputError(\"turnTargets must be a plain object\");\n }\n // Excluded from AutoRigTurnTargets, but a JS caller can still pass one:\n // the half-width is measured off the layers below, so a caller's own is\n // refused rather than silently dropped.\n if ((turnTargets as TurnTargets).headHalfWidth !== undefined) {\n throw new AutoRigInputError(\n \"turnTargets.headHalfWidth is measured off the layers, not accepted as input\",\n );\n }\n }\n\n // Resolve paths + role-map up front (input boundary; no decode needed).\n // parseLayerRoles throws on unknown/duplicate/missing-required roles.\n const resolvedLayers = layers.map((layer) => {\n const resolved = resolveInputPath(layer.path);\n return { resolved, fileName: layer.fileName ?? path.basename(resolved) };\n });\n const rolePairs = expectInput(\"role parsing\", () =>\n parseLayerRoles(resolvedLayers.map((r) => r.fileName)),\n );\n const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));\n\n // Decode + alpha-bbox + crop SEQUENTIALLY: only ONE full-canvas RGBA buffer\n // is live at a time (a Promise.all over all layers would hold every decoded\n // buffer at once, allowing a multi-GB spike on inputs that each pass\n // MAX_LAYER_DIM). MAX_TOTAL_PIXELS bounds the aggregate work. Canvas size =\n // the first layer's full PNG dims (parity with buildLayerInputs in\n // examples/editor/src/auto-rig-image.ts); all layers must match it.\n let canvasW = 0;\n let canvasH = 0;\n let totalPixels = 0;\n // Measures each layer while its decoded pixels are live, keeping none of\n // them (see createLayerSetMeasurer). Created once the first layer gives the\n // canvas.\n let measurer: LayerSetMeasurer | undefined;\n const crops: AtlasCrop[] = [];\n for (let i = 0; i < resolvedLayers.length; i++) {\n const { resolved, fileName } = resolvedLayers[i];\n const png = await decodePng(resolved);\n if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {\n throw new AutoRigInputError(\n `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`,\n );\n }\n totalPixels += png.width * png.height;\n if (totalPixels > MAX_TOTAL_PIXELS) {\n throw new AutoRigInputError(\n `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`,\n );\n }\n if (i === 0) {\n canvasW = png.width;\n canvasH = png.height;\n if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {\n throw new AutoRigInputError(\n `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`,\n );\n }\n measurer = createLayerSetMeasurer({ width: canvasW, height: canvasH });\n } else if (png.width !== canvasW || png.height !== canvasH) {\n throw new AutoRigInputError(\n `layer \"${fileName}\" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`,\n );\n }\n\n const role = roleByFileName.get(fileName);\n if (role === undefined) {\n throw new AutoRigInputError(`no role resolved for \"${fileName}\"`);\n }\n // Created at i === 0 above.\n const layer = measurer!.add({ role, fileName, rgba: png.rgba });\n if (layer === null) {\n throw new AutoRigInputError(\n `role \"${role}\" file \"${fileName}\": layer is empty after alpha threshold`,\n );\n }\n const { bbox } = layer;\n const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);\n // png.rgba (full-canvas) is dropped at the next iteration — GC reclaims it\n // before the next decode, so peak memory stays ~one canvas + the crops.\n crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });\n }\n // `layers` is non-empty (checked above), so the loop created the measurer.\n const measurement = measurer!.finish();\n const { headHalfWidth, headHalfWidthApplied, turnOptions } = measurement;\n const { headEdges, strandEdges } = turnOptions;\n\n // The nose layer's own denseCore, for the result — undefined without a\n // `nose` layer, or when the measurer's denseCoreOf found no pixel at\n // ALPHA_OPAQUE or a speck of the crop.\n const noseCore = measurement.layers.find(\n (l) => l.role === \"nose\",\n )?.denseCore;\n\n // Internal pipeline — direct calls. By here roles + bboxes are validated, so\n // a throw is an invariant break / bug and must propagate to `isError` —\n // except for the generator's three input errors, each a fact about the\n // request, not a bug: the turn solve, which reads CALLER input, throws\n // TurnTargetError (a field that is not a number, a target this layer set\n // cannot reach); the patch replay, which reads the caller's `patches`,\n // throws PatchError (a malformed op, or one that misses this rig); and\n // art geometry the rig cannot build on (a body's hips with no room under\n // its pivots, an arm too short for its pivots, a lip set whose\n // mouth_inner has no opaque pixel) throws LayerGeometryError.\n let turn: TurnSolveReport | undefined;\n let patches: PatchReport[] | undefined;\n let model: IkiModel;\n try {\n // The caller's fields cross as passed (a headHalfWidth was refused\n // above), so the generator refuses a misspelt one; the measured\n // headHalfWidth, when applied, is merged in after them.\n model = generateIkiFromLayerSet(\n measurement.layers,\n { width: canvasW, height: canvasH },\n {\n turnTargets: {\n ...input.turnTargets,\n ...turnOptions.turnTargets,\n },\n onTurnSolved: (report) => {\n turn = report;\n },\n ...(input.style === undefined ? {} : { style: input.style }),\n ...(input.patches === undefined\n ? {}\n : {\n patches: input.patches,\n onPatchesApplied: (reports: PatchReport[]) => {\n patches = reports;\n },\n }),\n ...(headEdges === undefined ? {} : { headEdges }),\n ...(strandEdges === undefined ? {} : { strandEdges }),\n },\n );\n } catch (e) {\n if (\n !(\n e instanceof TurnTargetError ||\n e instanceof LayerGeometryError ||\n e instanceof PatchError\n )\n ) {\n throw e;\n }\n throw new AutoRigInputError(e.message);\n }\n const doc = new EditorDocument(model);\n\n // Under quantizeColors the nose is page 1, alone and lossless (see\n // LOSSLESS_PAGE_ROLE), and page 0 every other crop; otherwise one page.\n const losslessCrop =\n quantizeColors === undefined\n ? undefined\n : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);\n const pages =\n losslessCrop === undefined\n ? [await renderAtlasPage(crops, quantizeColors)]\n : [\n await renderAtlasPage(\n crops.filter((c) => c !== losslessCrop),\n quantizeColors,\n ),\n await renderAtlasPage([losslessCrop], undefined),\n ];\n const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);\n if (atlasBytes > MAX_OUTPUT_BYTES) {\n throw new AutoRigInputError(\n `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`,\n );\n }\n\n // Each crop's uv is on its own page, normalised to that page's size.\n const partTextureAssignments: AtlasAssignment[] = pages.flatMap(\n ({ crops: pageCrops, layout }) =>\n pageCrops.flatMap((crop) => {\n const placement = layout.placements.find((p) => p.id === crop.id);\n if (placement === undefined) {\n throw new Error(`auto-rig: no atlas placement for \"${crop.id}\"`);\n }\n const uv = uvRectFor(placement, {\n width: layout.pageWidth,\n height: layout.pageHeight,\n });\n // Every part of a role samples its crop: a forearm shares its arm's.\n return partIdsOfRole(crop.id).map((partId) => ({ partId, uv }));\n }),\n );\n\n // applyAtlas takes a single page: it sets every part's index to 0 and\n // remaps each mesh's uvs into its rect, which for the nose is already in\n // page 1's space — so the nose only needs its index, set on a clone\n // because getModel() hands back the document's live model, read-only.\n doc.applyAtlas({\n textures: [{ source: pages[0].dataUri }],\n partTextureAssignments,\n });\n let patched = doc.getModel();\n if (losslessCrop !== undefined) {\n patched = structuredClone(patched);\n patched.textures = pages.map((p) => ({ source: p.dataUri }));\n for (const partId of partIdsOfRole(losslessCrop.id)) {\n patched.parts.find((p) => p.id === partId)!.texture!.index = 1;\n }\n }\n // Validate the patched model before writing — never persist an invalid model.\n const finalModel = parseIkiModel(patched);\n\n // Write to a fresh temp file in the verified directory, then atomically\n // rename over the target — see writeFileAtomic for why an existing `.iki`\n // symlink at outPath cannot redirect the write outside the working tree.\n writeFileAtomic(outPath, JSON.stringify(finalModel));\n\n // Report-only, and after the write so a throw here — an engine bug,\n // surfacing as a tool error, never an input refusal — keeps the rig.\n const folds = checkModelFolds(finalModel);\n const physics = checkPhysics(finalModel);\n\n return {\n ok: true,\n path: outPath,\n canvas: { width: canvasW, height: canvasH },\n partCount: finalModel.parts.length,\n atlasBytes,\n ...(headHalfWidth === undefined ? {} : { headHalfWidth }),\n headHalfWidthApplied,\n ...(headEdges === undefined ? {} : { headEdges }),\n ...(strandEdges === undefined ? {} : { strandEdges }),\n ...(noseCore === undefined ? {} : { noseCore }),\n ...(turn === undefined ? {} : { turn }),\n folds,\n physics,\n ...(patches === undefined ? {} : { patches }),\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n","/**\n * Clamp `value` into `[min, max]`.\n *\n * NaN in, NaN out — `Math.max(min, Math.min(max, NaN))` is `NaN`, so this\n * cannot be used to sanitize external input. Anything taking values from a\n * host must reject non-finite input itself before clamping (see\n * {@link ParameterStore.set}).\n */\nexport function clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * Linear interpolation from `a` (at `t = 0`) to `b` (at `t = 1`). Exact at\n * `t = 0` and when `a === b`; at `t = 1` it can differ from `b` by rounding.\n */\nexport function lerp(a: number, b: number, t: number): number {\n return a + (b - a) * t;\n}\n\n/**\n * Smoothstep `x²(3 − 2x)` of `x` clamped to `[0, 1]`: 0 at 0, 1 at 1, with zero\n * slope at both ends, so a fade along it starts and lands without a kink.\n * Exact at 0, 1/2 and 1.\n */\nexport function smoothstep(x: number): number {\n const t = clamp(x, 0, 1);\n return t * t * (3 - 2 * t);\n}\n","import type { IkiParameter } from \"@ikijs/format\";\nimport { clamp } from \"./math\";\n\n/**\n * Holds the live value of every model parameter, clamped to its declared\n * range. This is the single surface a host drives (lip-sync, gaze, blink) and\n * the engine reads each frame to evaluate bindings.\n */\nexport class ParameterStore {\n private readonly params = new Map<string, IkiParameter>();\n private readonly values = new Map<string, number>();\n /**\n * Resting value per id: the declared default clamped into range, resolved\n * ONCE here so `reset()` is a straight copy and a malformed descriptor is\n * reported once rather than on every reset.\n */\n private readonly defaults = new Map<string, number>();\n\n constructor(parameters: IkiParameter[]) {\n for (const param of parameters) {\n this.params.set(param.id, param);\n // A non-finite default would survive `clamp` and poison every read, so it\n // falls back to the neutral in-range value — but say so rather than\n // repairing a broken descriptor silently. `parseIkiModel` requires a\n // finite default, so this only reaches a host that skipped the validator.\n if (!Number.isFinite(param.default)) {\n console.error(\n `Iki: parameter \"${param.id}\" has a non-finite default; resting at the neutral in-range value instead`,\n );\n }\n const base = Number.isFinite(param.default) ? param.default : 0;\n this.defaults.set(param.id, clamp(base, param.min, param.max));\n }\n for (const [id, value] of this.defaults) this.values.set(id, value);\n }\n\n /**\n * Set a parameter's value, clamped to its range. Unknown ids are ignored, as\n * are non-finite values: this is the boundary a host drives with live signals,\n * and `clamp` cannot filter NaN (`Math.max(min, Math.min(max, NaN))` is NaN),\n * so one bad lip-sync/gaze frame would otherwise poison every binding that\n * reads the parameter. A dropped write holds the last good pose.\n */\n set(id: string, value: number): void {\n const param = this.params.get(id);\n if (!param) return;\n if (!Number.isFinite(value)) return;\n this.values.set(id, clamp(value, param.min, param.max));\n }\n\n /** Current value, or 0 if the id is unknown. */\n get(id: string): number {\n return this.values.get(id) ?? 0;\n }\n\n /** Position of a parameter within its range, 0..1. */\n normalized(id: string): number {\n const param = this.params.get(id);\n if (!param || param.max === param.min) return 0;\n return (this.get(id) - param.min) / (param.max - param.min);\n }\n\n /** Reset every parameter to its resting value (see `defaults`). */\n reset(): void {\n for (const [id, value] of this.defaults) this.values.set(id, value);\n }\n\n list(): IkiParameter[] {\n return [...this.params.values()];\n }\n}\n","// --- 2D affine helpers ------------------------------------------------------\n// Affine stored as [a, b, c, d, e, f] => | a c e |\n// | b d f |\n// | 0 0 1 |\nexport type Affine = [number, number, number, number, number, number];\n\nexport function translate(tx: number, ty: number): Affine {\n return [1, 0, 0, 1, tx, ty];\n}\n\nexport function scale(sx: number, sy: number): Affine {\n return [sx, 0, 0, sy, 0, 0];\n}\n\nexport function rotate(degrees: number): Affine {\n const r = (degrees * Math.PI) / 180;\n const c = Math.cos(r);\n const s = Math.sin(r);\n return [c, s, -s, c, 0, 0];\n}\n\nexport function multiply(a: Affine, b: Affine): Affine {\n return [\n a[0] * b[0] + a[2] * b[1],\n a[1] * b[0] + a[3] * b[1],\n a[0] * b[2] + a[2] * b[3],\n a[1] * b[2] + a[3] * b[3],\n a[0] * b[4] + a[2] * b[5] + a[4],\n a[1] * b[4] + a[3] * b[5] + a[5],\n ];\n}\n\n/** Expand a 2D affine into a column-major mat3 for `uniformMatrix3fv`. */\nexport function toMat3(a: Affine): Float32Array {\n return new Float32Array([a[0], a[1], 0, a[2], a[3], 0, a[4], a[5], 1]);\n}\n","import type { IkiGrid2DKeyform, IkiWarp } from \"@ikijs/format\";\nimport type { ParameterStore } from \"./parameter-store\";\n\n/**\n * Accumulate one keyform set's interpolated offsets into `out` (out += ...).\n * Clamps `value` to [keyforms[0].value, keyforms[last].value] (no extrapolation),\n * linearly interpolates the bracketing pair, and adds. `out.length` must be >=\n * each keyform's `offsets.length`. Shared by part-local mesh warps and grid warps.\n */\nexport function accumulateKeyformOffsets(\n keyforms: { value: number; offsets: ArrayLike<number> }[],\n value: number,\n out: Float32Array,\n): void {\n const ks = keyforms;\n\n if (value <= ks[0].value) {\n // Clamp to first keyform.\n const { offsets } = ks[0];\n for (let i = 0; i < offsets.length; i++) {\n out[i] += offsets[i];\n }\n } else if (value >= ks[ks.length - 1].value) {\n // Clamp to last keyform.\n const { offsets } = ks[ks.length - 1];\n for (let i = 0; i < offsets.length; i++) {\n out[i] += offsets[i];\n }\n } else {\n // Find bracketing pair with a linear scan (keyforms are small in practice).\n let lo = ks[0];\n let hi = ks[1];\n for (let k = 1; k < ks.length - 1; k++) {\n if (ks[k].value <= value) {\n lo = ks[k];\n hi = ks[k + 1];\n }\n }\n const t = (value - lo.value) / (hi.value - lo.value);\n const loOff = lo.offsets;\n const hiOff = hi.offsets;\n for (let i = 0; i < loOff.length; i++) {\n out[i] += loOff[i] + (hiOff[i] - loOff[i]) * t;\n }\n }\n}\n\n/**\n * Accumulate a 2D keyform grid's bilinear-interpolated offsets into `out` (out += ...).\n *\n * This is PARAMETER bilinear interpolation driven by two live parameter values\n * (`vx` along `valuesX`, `vy` along `valuesY`). It is DISTINCT from\n * {@link sampleWarpGrid}'s spatial bilinear (which interpolates model-space\n * control-point positions). Name params `tx`/`ty` to avoid confusion with\n * the spatial `s`/`t` in sampleWarpGrid.\n *\n * Contract mirrors {@link accumulateKeyformOffsets}: `out += blended offsets`,\n * pure, deterministic, no allocation inside the function, O(points).\n *\n * Bracket rule (applied identically to X and Y; length ≥ 2 is validator-guaranteed):\n * - v <= values[0] → i = 0, t = 0\n * - v >= values[last] → i = length - 2, t = 1\n * - interior → i such that values[i] <= v < values[i+1], t = (v - values[i]) / (values[i+1] - values[i])\n * This keeps i ∈ [0, length-2] so i+1 is always in range.\n *\n * Corner index (row-major): k(i, j) = j * valuesX.length + i\n */\nexport function accumulate2DKeyformOffsets(\n valuesX: number[],\n valuesY: number[],\n keyforms2d: IkiGrid2DKeyform[],\n vx: number,\n vy: number,\n out: Float32Array,\n): void {\n const lastX = valuesX.length - 1;\n const lastY = valuesY.length - 1;\n\n // Per-axis bracket: clamp at both ends, interior normal scan.\n let ix: number;\n let tx: number;\n if (vx <= valuesX[0]) {\n ix = 0;\n tx = 0;\n } else if (vx >= valuesX[lastX]) {\n ix = lastX - 1;\n tx = 1;\n } else {\n ix = 0;\n for (let k = 0; k < lastX - 1; k++) {\n if (valuesX[k + 1] <= vx) ix = k + 1;\n }\n tx = (vx - valuesX[ix]) / (valuesX[ix + 1] - valuesX[ix]);\n }\n\n let iy: number;\n let ty: number;\n if (vy <= valuesY[0]) {\n iy = 0;\n ty = 0;\n } else if (vy >= valuesY[lastY]) {\n iy = lastY - 1;\n ty = 1;\n } else {\n iy = 0;\n for (let k = 0; k < lastY - 1; k++) {\n if (valuesY[k + 1] <= vy) iy = k + 1;\n }\n ty = (vy - valuesY[iy]) / (valuesY[iy + 1] - valuesY[iy]);\n }\n\n // Row-major corners: k(i, j) = j * valuesX.length + i.\n const W = valuesX.length;\n const c00 = keyforms2d[iy * W + ix];\n const c10 = keyforms2d[iy * W + ix + 1];\n const c01 = keyforms2d[(iy + 1) * W + ix];\n const c11 = keyforms2d[(iy + 1) * W + ix + 1];\n\n // Per-component bilinear: top/bot over tx, then ty into out.\n const o00 = c00.offsets;\n const o10 = c10.offsets;\n const o01 = c01.offsets;\n const o11 = c11.offsets;\n for (let n = 0; n < o00.length; n++) {\n const top = o00[n] + (o10[n] - o00[n]) * tx;\n const bot = o01[n] + (o11[n] - o01[n]) * tx;\n out[n] += top + (bot - top) * ty;\n }\n}\n\n/**\n * Apply all warps to `rest`, accumulating per-vertex offsets into `out`.\n *\n * - Copies `rest` into `out` first (out = rest).\n * - For each warp: looks up the live parameter value (REAL range, not\n * normalized), clamps to the keyform range (no extrapolation), linearly\n * interpolates the bracketing pair, and ADDS the result to `out`.\n * - No allocation: writes into the caller-supplied `out`. `rest` is never\n * mutated.\n * - `undefined` warps → identity copy (out equals rest).\n */\nexport function applyWarps(\n rest: Float32Array,\n warps: IkiWarp[] | undefined,\n params: ParameterStore,\n out: Float32Array,\n): void {\n out.set(rest);\n\n if (!warps || warps.length === 0) return;\n\n for (const warp of warps) {\n accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), out);\n }\n}\n","import type { IkiWarpDeformer, IkiWarpGrid } from \"@ikijs/format\";\nimport type { Affine } from \"./affine\";\nimport type { ParameterStore } from \"./parameter-store\";\nimport { clamp, lerp } from \"./math\";\nimport { accumulate2DKeyformOffsets, accumulateKeyformOffsets } from \"./warp\";\n\n/** A warp deformer's deformed control grid for one frame. */\nexport interface ResolvedWarpGrid {\n cols: number;\n rows: number;\n /** Deformed control points, MODEL space, length (cols+1)*(rows+1)*2. */\n points: Float32Array;\n}\n\n/**\n * A warp deformer's LOCAL deformed grid: its rest `grid.points` plus the\n * interpolated offsets of EVERY entry of `warps` (each clamped and lerped on\n * its own parameter, then added, so several 1D warps sum) or of `warp2d`, in\n * the deformer's own rest frame — no parent affine. Returns a new array; the\n * rest grid is never written.\n */\nexport function deformWarpGrid(\n d: IkiWarpDeformer,\n params: ParameterStore,\n): Float32Array {\n const points = Float32Array.from(d.grid.points);\n for (const warp of d.warps ?? []) {\n accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), points);\n }\n // 1D xor 2D is validator-enforced; at most one branch contributes per deformer.\n if (d.warp2d !== undefined) {\n accumulate2DKeyformOffsets(\n d.warp2d.valuesX,\n d.warp2d.valuesY,\n d.warp2d.keyforms2d,\n params.get(d.warp2d.parameter),\n params.get(d.warp2d.parameterY),\n points,\n );\n }\n return points;\n}\n\n/**\n * `affine` applied to every [x, y] of a flat point list, into `out` — a NEW\n * array unless one is given — so the input (a warp's local grid, which a\n * matrix child's rigid frame still reads) is left as is.\n */\nexport function transformGridPoints(\n points: ArrayLike<number>,\n affine: Affine,\n): Float32Array;\nexport function transformGridPoints<T extends Float32Array | Float64Array>(\n points: ArrayLike<number>,\n affine: Affine,\n out: T,\n): T;\nexport function transformGridPoints(\n points: ArrayLike<number>,\n affine: Affine,\n out: Float32Array | Float64Array = new Float32Array(points.length),\n): Float32Array | Float64Array {\n for (let i = 0; i < points.length; i += 2) {\n const x = points[i];\n const y = points[i + 1];\n out[i] = affine[0] * x + affine[2] * y + affine[4];\n out[i + 1] = affine[1] * x + affine[3] * y + affine[5];\n }\n return out;\n}\n\n/** A model-space point bound to a rest-grid cell with within-cell (s,t). */\nexport interface GridBinding {\n /** row*cols + col index of the containing cell. */\n cell: number;\n /** [0,1] within-cell horizontal, 0 at the left (smaller-x) edge. */\n s: number;\n /** [0,1] within-cell vertical, 0 at the TOP (larger-y) edge. */\n t: number;\n}\n\n/**\n * Bind a model-space point to the REST grid: computes the containing cell +\n * local (s,t) by linear mapping over the grid's actual column/row boundaries.\n * Out-of-bounds points clamp to an edge cell with s/t pinned to 0/1. Never\n * returns NaN. Do NOT call against a deformed grid.\n *\n * The rest grid is validated to be a regular axis-aligned lattice with EXACT\n * ordering, so boundaries are read DIRECTLY from `restGrid.points` (no sorting):\n * - row-major, +y up; row 0 = TOP (LARGEST y, y DECREASES with row index);\n * - column 0 = LEFT (smallest x, x INCREASES with column index).\n * Column x-boundaries are row 0's x values `points[col*2]`; row y-boundaries are\n * column 0's y values `points[(row*(cols+1))*2 + 1]`. Maps x left→right and y\n * top→bottom: `s = (x - xLeft)/(xRight - xLeft)`, `t = (yTop - y)/(yTop - yBottom)`\n * (numerator `yTop - y`, NOT `y - minY`, so rows are not vertically flipped).\n */\nexport function bindPointToRestGrid(\n x: number,\n y: number,\n restGrid: IkiWarpGrid,\n): GridBinding {\n const { cols, rows, points } = restGrid;\n const stride = cols + 1;\n\n // Column boundaries: row 0's x values, increasing with column index.\n let col = cols - 1;\n for (let c = 0; c < cols; c++) {\n const xRight = points[(c + 1) * 2];\n if (x < xRight) {\n col = c;\n break;\n }\n }\n const xLeft = points[col * 2];\n const xRight = points[(col + 1) * 2];\n const s = clamp((x - xLeft) / (xRight - xLeft), 0, 1);\n\n // Row boundaries: column 0's y values, decreasing with row index (top→bottom).\n let row = rows - 1;\n for (let r = 0; r < rows; r++) {\n const yBottom = points[(r + 1) * stride * 2 + 1];\n if (y > yBottom) {\n row = r;\n break;\n }\n }\n const yTop = points[row * stride * 2 + 1];\n const yBottom = points[(row + 1) * stride * 2 + 1];\n const t = clamp((yTop - y) / (yTop - yBottom), 0, 1);\n\n return { cell: row * cols + col, s, t };\n}\n\n/**\n * Compute model-space positions for a warp-deformer child's mesh vertices:\n * transform each LOCAL-space vertex by `partAffine`, rebind to the RAW rest\n * grid, and bilinear-sample the deformed grid. Writes `out` (length ===\n * localVerts.length). Affine layout [a,b,c,d,e,f]: x'=a*x+c*y+e, y'=b*x+d*y+f.\n */\nexport function applyWarpToChild(\n localVerts: Float32Array | number[],\n partAffine: Affine,\n restGrid: IkiWarpGrid,\n deformedGrid: ResolvedWarpGrid,\n out: Float32Array,\n): void {\n const n = localVerts.length / 2;\n for (let v = 0; v < n; v++) {\n const lx = localVerts[v * 2];\n const ly = localVerts[v * 2 + 1];\n const mx = partAffine[0] * lx + partAffine[2] * ly + partAffine[4];\n const my = partAffine[1] * lx + partAffine[3] * ly + partAffine[5];\n const binding = bindPointToRestGrid(mx, my, restGrid);\n const [sx, sy] = sampleWarpGrid(deformedGrid, binding);\n out[v * 2] = sx;\n out[v * 2 + 1] = sy;\n }\n}\n\n/**\n * Bilinear-sample a deformed grid at a binding, returning model-space [x, y].\n * Reads the 4 corner control points of `binding.cell` from `grid.points`, using\n * the SAME row/col convention as `bindPointToRestGrid` (s left→right between\n * col and col+1, t top→bottom between row and row+1).\n */\nexport function sampleWarpGrid(\n grid: ResolvedWarpGrid,\n binding: GridBinding,\n): [number, number] {\n const { cols, points } = grid;\n const stride = cols + 1;\n const row = Math.floor(binding.cell / cols);\n const col = binding.cell % cols;\n const { s, t } = binding;\n\n const i00 = (row * stride + col) * 2;\n const i10 = (row * stride + col + 1) * 2;\n const i01 = ((row + 1) * stride + col) * 2;\n const i11 = ((row + 1) * stride + col + 1) * 2;\n\n // Top edge: lerp p00→p10 by s; bottom edge: lerp p01→p11 by s.\n const topX = points[i00] + (points[i10] - points[i00]) * s;\n const topY = points[i00 + 1] + (points[i10 + 1] - points[i00 + 1]) * s;\n const botX = points[i01] + (points[i11] - points[i01]) * s;\n const botY = points[i01 + 1] + (points[i11 + 1] - points[i01 + 1]) * s;\n\n // Vertical: lerp top→bottom by t.\n return [topX + (botX - topX) * t, topY + (botY - topY) * t];\n}\n\n/**\n * Rigid frame of a matrix deformer hung from a warp: returns\n * `translate(p') · rotate(θ) · translate(−p)`, where `p` is `pivot` bound to the\n * RAW rest grid and `p'` is that binding sampled on `localPoints`, the warp's\n * LOCAL deformed grid (rest + keyform offsets, no ancestor affine — the caller\n * composes that on top). θ is the rotation part (polar decomposition) of the\n * bilinear cell's Jacobian at the binding, each tangent divided by the rest\n * cell's width/height so the rest grid gives θ = 0. The warp's scale and shear\n * are deliberately dropped: a narrowing torso warp moves the head but never\n * squashes it.\n */\nexport function warpRigidFrame(\n pivot: { x: number; y: number },\n restGrid: IkiWarpGrid,\n localPoints: Float32Array,\n): Affine {\n const { cols, rows } = restGrid;\n const binding = bindPointToRestGrid(pivot.x, pivot.y, restGrid);\n const [px, py] = sampleWarpGrid({ cols, rows, points: localPoints }, binding);\n\n const stride = cols + 1;\n const row = Math.floor(binding.cell / cols);\n const col = binding.cell % cols;\n const { s, t } = binding;\n const i00 = (row * stride + col) * 2;\n const i10 = (row * stride + col + 1) * 2;\n const i01 = ((row + 1) * stride + col) * 2;\n const i11 = ((row + 1) * stride + col + 1) * 2;\n\n const rest = restGrid.points;\n // Same boundaries as bindPointToRestGrid (row 0's x, column 0's y): the\n // validator tolerates 1e-6 of jitter elsewhere, which can zero a cell's own\n // corner difference.\n const cellWidth = rest[(col + 1) * 2] - rest[col * 2];\n const cellHeight =\n rest[row * stride * 2 + 1] - rest[(row + 1) * stride * 2 + 1];\n\n // Images of the rest x/y axes. t runs top→bottom, i.e. against +y, hence\n // the minus on ey.\n const q = localPoints;\n const exX = lerp(q[i10] - q[i00], q[i11] - q[i01], t) / cellWidth;\n const exY =\n lerp(q[i10 + 1] - q[i00 + 1], q[i11 + 1] - q[i01 + 1], t) / cellWidth;\n const eyX = -lerp(q[i01] - q[i00], q[i11] - q[i10], s) / cellHeight;\n const eyY =\n -lerp(q[i01 + 1] - q[i00 + 1], q[i11 + 1] - q[i10 + 1], s) / cellHeight;\n\n // A collapsed cell gives atan2(0, 0) = 0: the frame stays finite.\n const theta = Math.atan2(exY - eyX, exX + eyY);\n const c = Math.cos(theta);\n const sn = Math.sin(theta);\n return [\n c,\n sn,\n -sn,\n c,\n px - (c * pivot.x - sn * pivot.y),\n py - (sn * pivot.x + c * pivot.y),\n ];\n}\n","import type {\n IkiBinding,\n IkiDeformer,\n IkiDeformerBinding,\n IkiDeformerTransform,\n IkiMatrixDeformer,\n IkiTransform,\n IkiWarpDeformer,\n} from \"@ikijs/format\";\nimport { type Affine, multiply, rotate, scale, translate } from \"./affine\";\nimport type { ParameterStore } from \"./parameter-store\";\nimport {\n type ResolvedWarpGrid,\n deformWarpGrid,\n transformGridPoints,\n warpRigidFrame,\n} from \"./warp-grid\";\n\n/** Resolved TRS + opacity from a transform + bindings at current parameter values. */\nexport interface ResolvedTransform {\n x: number;\n y: number;\n rotation: number;\n scaleX: number;\n scaleY: number;\n opacity: number;\n}\n\nconst IDENTITY_TRANSFORM: Required<IkiTransform> = {\n x: 0,\n y: 0,\n rotation: 0,\n scaleX: 1,\n scaleY: 1,\n opacity: 1,\n};\n\n/**\n * Shared transform evaluator: resolves the effective TRS + opacity from a\n * (possibly absent) base transform plus bindings at current parameter values.\n *\n * - Part callers pass `IkiTransform` (which may include opacity) and use all 6\n * fields including `opacity`.\n * - Deformer callers pass `IkiDeformerTransform` (no opacity field) and\n * `IkiDeformerBinding[]` (no opacity channel); the returned `opacity` is\n * always 1 on the deformer path and should be ignored by the caller.\n */\nexport function evaluateTransform(\n transform: IkiTransform | IkiDeformerTransform | undefined,\n bindings: IkiBinding[] | IkiDeformerBinding[] | undefined,\n params: ParameterStore,\n): ResolvedTransform {\n const base = transform ?? IDENTITY_TRANSFORM;\n const result: ResolvedTransform = {\n x: base.x,\n y: base.y,\n rotation: base.rotation ?? 0,\n scaleX: base.scaleX ?? 1,\n scaleY: base.scaleY ?? 1,\n opacity: (base as IkiTransform).opacity ?? 1,\n };\n\n for (const binding of bindings ?? []) {\n const t = params.normalized(binding.parameter);\n const value = binding.from + (binding.to - binding.from) * t;\n switch (binding.channel) {\n case \"translateX\":\n result.x += value;\n break;\n case \"translateY\":\n result.y += value;\n break;\n case \"rotate\":\n result.rotation += value;\n break;\n case \"scaleX\":\n result.scaleX += value;\n break;\n case \"scaleY\":\n result.scaleY += value;\n break;\n case \"opacity\":\n result.opacity *= value;\n break;\n }\n }\n\n return result;\n}\n\n/**\n * Build the local deformer matrix about its pivot:\n * translate(pivot) · TRS · translate(-pivot)\n */\nfunction deformerLocalMatrix(\n d: IkiMatrixDeformer,\n params: ParameterStore,\n): Affine {\n const t = evaluateTransform(d.transform, d.bindings, params);\n const trs: Affine = multiply(\n multiply(translate(t.x, t.y), rotate(t.rotation)),\n scale(t.scaleX, t.scaleY),\n );\n return multiply(\n multiply(translate(d.pivot.x, d.pivot.y), trs),\n translate(-d.pivot.x, -d.pivot.y),\n );\n}\n\n/** Every deformer of a model resolved for one frame. */\nexport interface ResolvedDeformers {\n /** Matrix deformer id → world affine. */\n worlds: Map<string, Affine>;\n /** Warp deformer id → deformed control grid, model space. */\n grids: Map<string, ResolvedWarpGrid>;\n}\n\n/**\n * A warp's grid before its parent affine, and that affine (absent at a root)\n * — what a matrix child of the warp reads its rigid frame from.\n */\ninterface LocalWarp {\n localGrid: Float32Array;\n parentWorld: Affine | undefined;\n}\n\n/**\n * Resolve every deformer — matrix worlds and warp grids — in topological\n * order, regardless of array ordering.\n *\n * The validator guarantees the hierarchy is acyclic, that every `parent` id\n * exists and that no warp hangs from a warp; the engine resolves on-demand\n * with memoization so any valid array order is handled correctly.\n *\n * Throws a clear internal Error if a parent is unexpectedly absent or a warp\n * hangs from a warp (defense-in-depth — indicates an unvalidated model was\n * passed to the engine).\n */\nexport function resolveDeformers(\n deformers: IkiDeformer[],\n params: ParameterStore,\n): ResolvedDeformers {\n const byId = new Map<string, IkiDeformer>(deformers.map((d) => [d.id, d]));\n const worlds = new Map<string, Affine>();\n const grids = new Map<string, ResolvedWarpGrid>();\n const localWarps = new Map<string, LocalWarp>();\n\n function parentOf(d: IkiDeformer): IkiDeformer | undefined {\n if (d.parent === undefined) return undefined;\n const parent = byId.get(d.parent);\n if (!parent) {\n throw new Error(\n `unresolved deformer parent \"${d.parent}\" — model not validated?`,\n );\n }\n return parent;\n }\n\n function resolveWorld(d: IkiMatrixDeformer): Affine {\n const cached = worlds.get(d.id);\n if (cached) return cached;\n\n const local = deformerLocalMatrix(d, params);\n const parent = parentOf(d);\n let world: Affine;\n if (parent === undefined) {\n world = local;\n } else if (parent.kind === \"warp\") {\n // The frame comes off the warp's LOCAL grid and the warp's own parent\n // affine goes on top — the same order the grid itself is resolved in,\n // so a rest warp between two matrices changes nothing.\n const warp = resolveWarp(parent);\n const ridden = multiply(\n warpRigidFrame(d.pivot, parent.grid, warp.localGrid),\n local,\n );\n world = warp.parentWorld ? multiply(warp.parentWorld, ridden) : ridden;\n } else {\n world = multiply(resolveWorld(parent), local);\n }\n\n worlds.set(d.id, world);\n return world;\n }\n\n function resolveWarp(d: IkiWarpDeformer): LocalWarp {\n const cached = localWarps.get(d.id);\n if (cached) return cached;\n\n const parent = parentOf(d);\n if (parent?.kind === \"warp\") {\n throw new Error(\n `warp deformer \"${d.id}\" hangs from warp \"${parent.id}\" — model not validated?`,\n );\n }\n const parentWorld = parent && resolveWorld(parent);\n // ORDER IS CRITICAL: keyform offsets FIRST (curvature added in the rest\n // frame), parent affine SECOND — so the curvature rotates WITH the parent\n // head rather than staying pinned to world axes. The reversed order\n // (affine then offsets) pushes the bend along world-x even when the head\n // is turned (coordinate bug).\n const localGrid = deformWarpGrid(d, params);\n grids.set(d.id, {\n cols: d.grid.cols,\n rows: d.grid.rows,\n points: parentWorld\n ? transformGridPoints(localGrid, parentWorld)\n : localGrid,\n });\n\n const resolved = { localGrid, parentWorld };\n localWarps.set(d.id, resolved);\n return resolved;\n }\n\n for (const d of deformers) {\n if (d.kind === \"warp\") resolveWarp(d);\n else resolveWorld(d);\n }\n\n return { worlds, grids };\n}\n","import { StandardParameter } from \"@ikijs/format\";\nimport { MAX_DT_MS } from \"./frame-clock\";\nimport { clamp, lerp, smoothstep } from \"./math\";\n\n// --- Module-internal timing/easing constants -----------------------------------\n// These are intentionally private; tests assert observable behavior, not config.\n\nconst BLINK_INTERVAL_MIN_MS = 1500;\nconst BLINK_INTERVAL_MAX_MS = 6000;\n// A blink closes fast and opens slower, with a moment shut in between. The\n// human blink-kinematics literature has the down-phase at roughly a third of\n// the whole and the up-phase decelerating into the open pose. These three are\n// a judgement inside the 150–180 ms range.\nconst BLINK_CLOSE_MS = 60;\nconst BLINK_HOLD_MS = 20;\nconst BLINK_OPEN_MS = 100;\nconst BLINK_DURATION_MS = BLINK_CLOSE_MS + BLINK_HOLD_MS + BLINK_OPEN_MS; // 180\n\nconst BREATH_PERIOD_MS = 3500;\n\nconst GAZE_RADIUS = 0.3;\nconst GAZE_RETARGET_MIN_MS = 1200;\nconst GAZE_RETARGET_MAX_MS = 3000;\n// Fraction of the gap to close each millisecond of clamped dt.\n// Chosen so a typical 16ms frame moves ~1.5 % of remaining distance.\nconst GAZE_EASE_RATE = 0.001;\n\n// Head sway: sums of slow sines with near-coprime periods, so the drift never\n// visibly repeats. Degrees — small against the ±30° standard AngleX/Y/Z range,\n// but enough continuous head motion to keep hair physics from sleeping.\nconst SWAY_X_AMP_A_DEG = 2.2;\nconst SWAY_X_PERIOD_A_MS = 6100;\nconst SWAY_X_AMP_B_DEG = 1.3;\nconst SWAY_X_PERIOD_B_MS = 9700;\nconst SWAY_Y_AMP_DEG = 1.6;\nconst SWAY_Y_PERIOD_MS = 7300;\n// Roll is the smallest and slowest of the three: an idle head barely tilts,\n// and a tilt reads much larger than a turn of the same degrees.\nconst SWAY_Z_AMP_DEG = 1.1;\nconst SWAY_Z_PERIOD_MS = 11300;\n\n// Ambient sway: the drift hair physics follows in idle, where the head sway\n// alone barely moves it. Two near-coprime periods (29:43) inside 2.5–5 s, away\n// from the breath and the head sines above so nothing beats in step; the\n// amplitudes sum to exactly ±1, the parameter's range. Zero phase, so the\n// resting pose writes 0 and it takes no rng draw (the blink and gaze\n// schedules keep their sequence).\nconst AMBIENT_AMP_A = 0.6;\nconst AMBIENT_PERIOD_A_MS = 2900;\nconst AMBIENT_AMP_B = 0.4;\nconst AMBIENT_PERIOD_B_MS = 4300;\n\n// --- Small pure helpers -------------------------------------------------------\n\n/**\n * Eye-open value over one blink, `phase` ∈ [0, 1]: 1 at both ends, 0 across the\n * hold. Close is a smoothstep (soft start, soft landing on the lid); open is a\n * quadratic ease-out (the lid leaves the hold at speed and settles). Exported\n * for the shape tests; not part of the package entry.\n */\nexport function blinkEnvelope(phase: number): number {\n const ms = phase * BLINK_DURATION_MS;\n if (ms <= 0) return 1;\n if (ms < BLINK_CLOSE_MS) return 1 - smoothstep(ms / BLINK_CLOSE_MS);\n if (ms <= BLINK_CLOSE_MS + BLINK_HOLD_MS) return 0; // inclusive: the close point is exactly 0 for any retune\n if (ms < BLINK_DURATION_MS) {\n const t = (ms - BLINK_CLOSE_MS - BLINK_HOLD_MS) / BLINK_OPEN_MS;\n return 1 - (1 - t) * (1 - t);\n }\n return 1;\n}\n\n/** Pick a random point within a disk of `radius` using the injected rng. */\nfunction randomInDisk(rng: () => number, radius: number): [number, number] {\n // Polar sampling: bounded, no rejection loop, safe with any [0,1) rng.\n // r = sqrt(u) gives uniform area distribution; θ spans the full circle.\n const r = Math.sqrt(rng()) * radius;\n const theta = rng() * 2 * Math.PI;\n return [r * Math.cos(theta), r * Math.sin(theta)];\n}\n\n// --- Public API ---------------------------------------------------------------\n\nexport interface IdleMotionOptions {\n /** Inject a deterministic rng for testing. Defaults to Math.random. */\n rng?: () => number;\n}\n\n/**\n * Pure-logic idle-animation driver. Animates the nine \"life\" parameters\n * (eyes, breath, gaze, head sway, ambient sway) on an internal clock so\n * tab-backgrounding or irregular frame delivery can't produce teleports or\n * snap-close blinks.\n *\n * Usage:\n * const idle = new IdleMotion(player.setParameter.bind(player));\n * // inside your rAF loop:\n * idle.update(performance.now());\n *\n * The host is responsible for scheduling; this class has no timers or rAF.\n */\nexport class IdleMotion {\n /**\n * Every parameter id {@link update} and `emitRestingPose` write, in write\n * order. Published so a host (or IkiMotion) can restore them after it\n * stops driving — keep in step with those two methods; the test suite\n * pins this list to the actual emissions.\n */\n readonly drivenParameterIds: readonly string[] = [\n StandardParameter.EyeOpenLeft,\n StandardParameter.EyeOpenRight,\n StandardParameter.Breath,\n StandardParameter.EyeballX,\n StandardParameter.EyeballY,\n StandardParameter.AngleX,\n StandardParameter.AngleY,\n StandardParameter.AngleZ,\n StandardParameter.AmbientSway,\n ];\n private readonly sink: (id: string, value: number) => void;\n private readonly rng: () => number;\n\n // Internal clock: advances by clamped dt, NOT by raw wall-clock jumps.\n // This is the only clock blink/breath/gaze scheduling reads.\n private clockMs = 0;\n private prevNowMs: number | undefined = undefined;\n\n // Blink state\n private nextBlinkAtMs: number;\n private blinkStartMs = -1; // -1 means not currently blinking\n\n // Gaze state\n private gazeCurrentX = 0;\n private gazeCurrentY = 0;\n private gazeTargetX = 0;\n private gazeTargetY = 0;\n private nextGazeRetargetMs: number;\n\n constructor(\n sink: (id: string, value: number) => void,\n options?: IdleMotionOptions,\n ) {\n this.sink = sink;\n // Math.random is the single allowed default reference; all other uses go\n // through this.rng so tests can inject a deterministic substitute.\n this.rng = options?.rng ?? Math.random;\n\n // Schedule the first blink and gaze retarget relative to clock zero.\n this.nextBlinkAtMs = lerp(\n BLINK_INTERVAL_MIN_MS,\n BLINK_INTERVAL_MAX_MS,\n this.rng(),\n );\n this.nextGazeRetargetMs = lerp(\n GAZE_RETARGET_MIN_MS,\n GAZE_RETARGET_MAX_MS,\n this.rng(),\n );\n }\n\n /**\n * Advance the idle animation to the given wall-clock timestamp (milliseconds).\n *\n * On the first call: record prevNowMs, emit the resting pose, and return —\n * no animation advance happens so there is no jump from time 0.\n *\n * On subsequent calls: compute dt = clamp(nowMs - prevNowMs, 0, MAX_DT_MS)\n * and advance the internal clock by dt. A non-monotonic nowMs produces a\n * negative raw delta that the clamp floors to 0 — no rewind.\n */\n update(nowMs: number): void {\n // Host-supplied timestamp, same boundary rule as FixedStepClock.advance and\n // ParameterStore.set: drop the frame, touch nothing. `clockMs += NaN` would\n // stick, and every blink/gaze schedule reads clockMs — the face would go\n // still permanently. A host driving from media time hands you NaN through an\n // ordinary path (`duration * pct` before metadata loads).\n if (!Number.isFinite(nowMs)) return;\n if (this.prevNowMs === undefined) {\n this.prevNowMs = nowMs;\n // Emit resting pose so the host mirror stays in sync from frame 1.\n this.emitRestingPose();\n return;\n }\n\n // Clamp dt so a backgrounded tab or long GC pause advances the internal\n // clock by at most MAX_DT_MS — blink can't snap shut, gaze can't teleport.\n const rawDt = nowMs - this.prevNowMs;\n const dt = clamp(rawDt, 0, MAX_DT_MS);\n this.prevNowMs = nowMs;\n this.clockMs += dt;\n\n // Both eyes always carry the identical value (unified blink).\n const eyeVal = this.advanceBlink();\n this.sink(StandardParameter.EyeOpenLeft, eyeVal);\n this.sink(StandardParameter.EyeOpenRight, eyeVal);\n\n const breath = this.advanceBreath();\n this.advanceGaze(dt);\n\n this.sink(StandardParameter.Breath, breath);\n this.sink(StandardParameter.EyeballX, this.gazeCurrentX);\n this.sink(StandardParameter.EyeballY, this.gazeCurrentY);\n\n // Head sway keeps the character (and any hair physics reading AngleX/Y/Z)\n // from freezing solid between blinks. Models without these parameters\n // ignore the writes (ParameterStore drops unknown ids).\n this.sink(StandardParameter.AngleX, this.swayX());\n this.sink(StandardParameter.AngleY, this.swayY());\n this.sink(StandardParameter.AngleZ, this.swayZ());\n this.sink(StandardParameter.AmbientSway, this.ambientSway());\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private emitRestingPose(): void {\n this.sink(StandardParameter.EyeOpenLeft, 1);\n this.sink(StandardParameter.EyeOpenRight, 1);\n // Breath at phase 0: sin(0) = 0 → 0.5 + 0.5*0 = 0.5\n this.sink(StandardParameter.Breath, 0.5);\n this.sink(StandardParameter.EyeballX, 0);\n this.sink(StandardParameter.EyeballY, 0);\n // Sway sines are all 0 at clock 0 — the head starts centered.\n this.sink(StandardParameter.AngleX, 0);\n this.sink(StandardParameter.AngleY, 0);\n this.sink(StandardParameter.AngleZ, 0);\n this.sink(StandardParameter.AmbientSway, 0);\n }\n\n /** Returns the current eye-open value (0..1) and advances blink state. */\n private advanceBlink(): number {\n const { clockMs } = this;\n\n // If a blink is in progress, evaluate the envelope.\n if (this.blinkStartMs >= 0) {\n const phase = (clockMs - this.blinkStartMs) / BLINK_DURATION_MS;\n if (phase >= 1) {\n // Blink finished — schedule the next one on the internal clock.\n this.blinkStartMs = -1;\n this.nextBlinkAtMs =\n clockMs +\n lerp(BLINK_INTERVAL_MIN_MS, BLINK_INTERVAL_MAX_MS, this.rng());\n return 1;\n }\n return blinkEnvelope(phase);\n }\n\n // Check if it is time to start a new blink.\n if (clockMs >= this.nextBlinkAtMs) {\n this.blinkStartMs = clockMs;\n // Return the first envelope sample (exactly 1 at phase 0).\n return blinkEnvelope(0);\n }\n\n // Between blinks: eyes fully open.\n return 1;\n }\n\n private advanceBreath(): number {\n return (\n 0.5 + 0.5 * Math.sin((2 * Math.PI * this.clockMs) / BREATH_PERIOD_MS)\n );\n }\n\n /** Horizontal head sway in degrees, pure function of the internal clock. */\n private swayX(): number {\n const t = 2 * Math.PI * this.clockMs;\n return (\n SWAY_X_AMP_A_DEG * Math.sin(t / SWAY_X_PERIOD_A_MS) +\n SWAY_X_AMP_B_DEG * Math.sin(t / SWAY_X_PERIOD_B_MS)\n );\n }\n\n /** Vertical head sway in degrees, pure function of the internal clock. */\n private swayY(): number {\n return (\n SWAY_Y_AMP_DEG * Math.sin((2 * Math.PI * this.clockMs) / SWAY_Y_PERIOD_MS)\n );\n }\n\n /** Head roll sway in degrees, pure function of the internal clock. */\n private swayZ(): number {\n return (\n SWAY_Z_AMP_DEG * Math.sin((2 * Math.PI * this.clockMs) / SWAY_Z_PERIOD_MS)\n );\n }\n\n /** Ambient sway (-1..1), pure function of the internal clock. */\n private ambientSway(): number {\n const t = 2 * Math.PI * this.clockMs;\n return (\n AMBIENT_AMP_A * Math.sin(t / AMBIENT_PERIOD_A_MS) +\n AMBIENT_AMP_B * Math.sin(t / AMBIENT_PERIOD_B_MS)\n );\n }\n\n /** Ease gaze current toward target; pick a new target on the internal clock. */\n private advanceGaze(dt: number): void {\n // Retarget check reads clockMs so a clamped pause can't skip retargets.\n if (this.clockMs >= this.nextGazeRetargetMs) {\n const [tx, ty] = randomInDisk(this.rng, GAZE_RADIUS);\n this.gazeTargetX = tx;\n this.gazeTargetY = ty;\n this.nextGazeRetargetMs =\n this.clockMs +\n lerp(GAZE_RETARGET_MIN_MS, GAZE_RETARGET_MAX_MS, this.rng());\n }\n\n // Exponential ease toward target. The ease factor is derived from the\n // CLAMPED dt so a paused tab moves at most one normal step, never a teleport.\n const factor = 1 - Math.pow(1 - GAZE_EASE_RATE, dt);\n this.gazeCurrentX = lerp(this.gazeCurrentX, this.gazeTargetX, factor);\n this.gazeCurrentY = lerp(this.gazeCurrentY, this.gazeTargetY, factor);\n }\n}\n","import { clamp } from \"./math\";\n\n/** Per-frame dt ceiling: a backgrounded tab or a long GC pause must not snap state. */\nexport const MAX_DT_MS = 100;\n/** Fixed integration sub-step, in SECONDS. */\nexport const FIXED_DT_S = 1 / 60;\n/** Catch-up cap per frame (spiral-of-death guard). */\nexport const MAX_SUBSTEPS = 6;\n\n/**\n * Fixed-timestep accumulator shared by the physics drivers, so a stability fix\n * lands in one place instead of one of two near-identical copies.\n *\n * A driver calls {@link advance} once per frame and runs its integration body\n * that many times. Leftover time carries to the next frame, which is what keeps\n * the simulation frame-rate independent; the dt clamp and the sub-step cap keep\n * a hitch from either snapping the rig or spiralling into catch-up work.\n */\nexport class FixedStepClock {\n private prevNowMs: number | undefined = undefined;\n private accumulatorS = 0;\n\n /**\n * True until the first {@link advance}. Drivers seed their rest pose on that\n * frame and integrate nothing, so a model loaded mid-motion does not kick.\n */\n get isSeedFrame(): boolean {\n return this.prevNowMs === undefined;\n }\n\n /**\n * Time carried in the accumulator, in seconds: how far the frame's timestamp is\n * past the last whole sub-step. Drivers extrapolate their state by it so what\n * they emit is the state at the frame's time, not at the last sub-step.\n */\n get remainderS(): number {\n return this.accumulatorS;\n }\n\n /**\n * Fold `nowMs` into the accumulator and return how many {@link FIXED_DT_S}\n * sub-steps to run this frame. On the seed frame it only records the\n * timestamp and returns 0. A non-monotonic `nowMs` floors to 0 — no rewind.\n */\n advance(nowMs: number): number {\n // Host-supplied timestamp, so the same rule as ParameterStore.set: reject\n // non-finite input at the boundary. `clamp(NaN, ...)` is NaN, which would\n // make the accumulator NaN and every `NaN >= FIXED_DT_S` false FOREVER —\n // the rig would freeze silently with no way back. Pre-existing; hardened\n // here so both host entry points behave the same way.\n if (!Number.isFinite(nowMs)) return 0;\n if (this.prevNowMs === undefined) {\n this.prevNowMs = nowMs;\n return 0;\n }\n const dtMs = clamp(nowMs - this.prevNowMs, 0, MAX_DT_MS);\n this.prevNowMs = nowMs;\n this.accumulatorS += dtMs / 1000; // boundary ms->s conversion\n\n let steps = 0;\n while (this.accumulatorS >= FIXED_DT_S && steps < MAX_SUBSTEPS) {\n this.accumulatorS -= FIXED_DT_S;\n steps++;\n }\n return steps;\n }\n}\n","import {\n type IkiParameter,\n type IkiPhysics,\n physicsInputs,\n} from \"@ikijs/format\";\nimport { FIXED_DT_S, FixedStepClock } from \"./frame-clock\";\nimport { clamp } from \"./math\";\n\n// --- Small pure helpers ------------------------------------------------------\n\n/**\n * Map a parameter value to [-1, 1] around its engine-effective default. Portable\n * across param ranges: the wider side (rest→max vs min→rest) sets the unit, so\n * ±1 lands at the farther extreme. Returns 0 for a zero-width range.\n *\n * The rest center is `clamp(default, min, max)` to match ParameterStore, which\n * clamps an out-of-range default — so the spring rests where the model actually\n * renders, not at a raw out-of-range default.\n */\nfunction signedNormalized(\n value: number,\n param: { min: number; max: number; default: number },\n): number {\n const rest = clamp(param.default, param.min, param.max);\n const den = Math.max(Math.abs(param.max - rest), Math.abs(rest - param.min));\n if (den === 0) return 0;\n return clamp((value - rest) / den, -1, 1);\n}\n\n// --- Public API --------------------------------------------------------------\n\ninterface RigState {\n x: number; // spring position (lagging, normalized-ish units)\n v: number; // spring velocity\n lag: number; // Σ wᵢ·nᵢ over the lag inputs, as the last finite frame read it\n}\n\n/** One input of a rig, resolved once so the frame loop never branches on shape. */\ninterface RigInput {\n parameter: string;\n weight: number;\n lag: boolean;\n}\n\n/**\n * Host-agnostic 1D spring-mass-damper secondary-motion driver — the physics\n * peer of {@link IdleMotion}. For each rig it reads every input parameter,\n * signed-normalizes it around its default × `weight`, sums those into one spring\n * target `T`, integrates a lagging spring position `x` with semi-implicit\n * (symplectic) Euler on a fixed 1/60s sub-step accumulator, and writes\n * `outputDefault + (x − L) * scale` (x carried forward by the clock's leftover time) onto the output parameter, `L` being the\n * lag inputs' share of `T` — so the output lags and overshoots the inputs\n * (hair/accessory sway).\n *\n * By superposition a follow input's held value stays in the output (the spring\n * settles at `T`), while a lag input's held value settles out, returning the\n * output to rest: it swings only while that input moves. A rig seeded with a\n * lag input already displaced emits rest, without a kick. Inputs are not\n * smoothed, so a one-frame step on a lag input snaps the output by\n * `−scale·weight·Δn` before the spring catches up — deferred until a captured\n * snap calls for a rate limit.\n *\n * Usage:\n * const physics = new PhysicsMotion(\n * model.physics ?? [],\n * model.parameters,\n * (id) => currentValue(id),\n * player.setParameter.bind(player),\n * );\n * // inside your rAF loop, right AFTER idle.update(now):\n * physics.update(performance.now());\n *\n * The host schedules updates; this class has no timers, rAF, DOM, or Date.now.\n * Writes go through the sink, exactly like IdleMotion; the player renders the\n * updated params on its own render loop (drivers and rendering are decoupled).\n */\nexport class PhysicsMotion {\n /** The output parameter of every rig, in rig order — what `emit` writes. */\n readonly drivenParameterIds: readonly string[];\n /**\n * Per rig: how many times the finiteness guard reset its state or `emit`\n * replaced its non-finite product. Up to two per frame, so guard activations,\n * not repaired frames. A diagnostic; emitted values are unchanged.\n */\n readonly resets: readonly number[];\n private readonly resetCounts: number[];\n private readonly rigs: readonly IkiPhysics[];\n private readonly inputs: readonly (readonly RigInput[])[];\n private readonly read: (id: string) => number;\n private readonly sink: (id: string, value: number) => void;\n private readonly params: Map<string, IkiParameter>;\n\n // Integrator state, owned here — never stored in a ParameterStore.\n private readonly state: RigState[];\n private readonly clock = new FixedStepClock();\n\n constructor(\n rigs: IkiPhysics[],\n params: IkiParameter[],\n read: (id: string) => number,\n sink: (id: string, value: number) => void,\n ) {\n this.rigs = rigs;\n this.inputs = rigs.map((rig) =>\n physicsInputs(rig).map(({ parameter, weight, mode }) => ({\n parameter,\n weight,\n lag: mode === \"lag\",\n })),\n );\n this.read = read;\n this.sink = sink;\n this.params = new Map(params.map((p) => [p.id, p]));\n this.state = rigs.map(() => ({ x: 0, v: 0, lag: 0 }));\n this.drivenParameterIds = rigs.map((rig) => rig.output.parameter);\n this.resetCounts = rigs.map(() => 0);\n this.resets = this.resetCounts;\n }\n\n /**\n * Advance every rig to the given wall-clock timestamp (milliseconds).\n *\n * First call: seed each spring to rest AT its current target (so a model\n * loaded with a nonzero input does not kick: a lag input emits rest, a follow\n * input its value), emit that output, and return without integrating —\n * mirroring IdleMotion's first-frame behavior.\n *\n * A non-finite `nowMs` after that is a dropped frame: every rig re-emits its\n * last output from its stored state without reading its inputs.\n *\n * Subsequent calls: {@link FixedStepClock} folds the clamped frame delta into\n * its accumulator and returns how many {@link FIXED_DT_S} sub-steps are due;\n * the spring advances that many semi-implicit Euler steps, then each rig emits\n * its output once. The clock's dt clamp and sub-step cap plus the symplectic\n * integrator are what keep it stable across hitches.\n */\n update(nowMs: number): void {\n if (this.clock.isSeedFrame) {\n this.clock.advance(nowMs);\n for (let i = 0; i < this.rigs.length; i++) {\n const st = this.state[i];\n const { target, lag } = this.targetFor(i);\n st.x = target;\n st.v = 0;\n st.lag = lag;\n this.emit(i, st);\n }\n return;\n }\n\n // A dropped frame (the clock rejects it as well). Re-emit from the stored\n // `L` rather than read the inputs, or a lag rig's output would move on it.\n if (!Number.isFinite(nowMs)) {\n for (let i = 0; i < this.rigs.length; i++) this.emit(i, this.state[i]);\n return;\n }\n\n const steps = this.clock.advance(nowMs);\n\n // update() is synchronous, so the inputs cannot change mid-loop — read each\n // rig's target ONCE per frame and reuse it across the sub-steps.\n const targets = this.rigs.map((_, i) => this.targetFor(i));\n\n for (let s = 0; s < steps; s++) {\n for (let i = 0; i < this.rigs.length; i++) {\n this.step(this.rigs[i], this.state[i], targets[i].target);\n }\n }\n\n // Always emit (even when zero sub-steps ran) so the sink stays in sync.\n for (let i = 0; i < this.rigs.length; i++) {\n const st = this.state[i];\n // The fixed 1/60s sub-step can diverge for an extreme-but-parse-valid rig\n // (tiny mass / huge stiffness push ω·dt past the explicit-integrator\n // stability limit). If state goes non-finite, snap back to rest at the\n // current target: the store DROPS a non-finite write, so an un-reset rig\n // would emit NaN every frame and silently freeze the part at its last\n // good pose instead of visibly diverging.\n const { target, lag } = targets[i];\n if (!Number.isFinite(st.x) || !Number.isFinite(st.v)) {\n st.x = Number.isFinite(target) ? target : 0;\n st.v = 0;\n this.resetCounts[i]++;\n }\n st.lag = lag;\n this.emit(i, st);\n }\n }\n\n /**\n * Rig `index`'s spring target `T` = Σ signed-normalized input value × weight,\n * and `L`, the lag inputs' share of it. Reads each input once.\n */\n private targetFor(index: number): { target: number; lag: number } {\n let target = 0;\n let lag = 0;\n for (const input of this.inputs[index]) {\n const param = this.params.get(input.parameter);\n const value = this.read(input.parameter);\n const share = (param ? signedNormalized(value, param) : 0) * input.weight;\n target += share;\n if (input.lag) lag += share;\n }\n return { target, lag };\n }\n\n /** One semi-implicit (symplectic) Euler sub-step of FIXED_DT_S seconds. */\n private step(rig: IkiPhysics, st: RigState, target: number): void {\n const accel =\n (rig.stiffness * (target - st.x) - rig.damping * st.v) / rig.mass;\n st.v += accel * FIXED_DT_S;\n st.x += st.v * FIXED_DT_S;\n }\n\n /** Write outputDefault + (x − L) * scale onto the output param via the sink. */\n private emit(index: number, st: RigState): void {\n const rig = this.rigs[index];\n const outParam = this.params.get(rig.output.parameter);\n // clamp to match ParameterStore's engine-effective default (see signedNormalized).\n const outDefault = outParam\n ? clamp(outParam.default, outParam.min, outParam.max)\n : 0;\n // `x` only moves in whole sub-steps while `lag` is this frame's, so emit x\n // carried forward by the time since its last sub-step: the output then\n // follows the frame's time, not how many sub-steps happened to be due.\n // Extrapolating (not interpolating from the previous state) adds no lag, and\n // at rest (v = 0) it changes nothing.\n const x = st.x + st.v * this.clock.remainderS;\n const value = outDefault + (x - st.lag) * rig.output.scale;\n // Final guard: even a finite-but-enormous `x` could overflow the product to\n // ±Infinity. Emit the rest pose rather than hand a non-finite value to the\n // sink, which would drop the write and leave the output stuck where it was.\n const finite = Number.isFinite(value);\n if (!finite) this.resetCounts[index]++;\n this.sink(rig.output.parameter, finite ? value : outDefault);\n }\n}\n","import type {\n IkiDeformer,\n IkiParameter,\n IkiPhysicsChain,\n IkiPhysicsChainSegment,\n} from \"@ikijs/format\";\nimport type { Affine } from \"./affine\";\nimport { resolveDeformers } from \"./deform\";\n// The two physics drivers stay independent of EACH OTHER; the timing primitives\n// they both need live in frame-clock.ts so a stability fix lands once.\nimport { FIXED_DT_S, FixedStepClock } from \"./frame-clock\";\nimport { clamp } from \"./math\";\nimport { ParameterStore } from \"./parameter-store\";\n\nconst DEG2RAD = Math.PI / 180;\nconst RAD2DEG = 180 / Math.PI;\n\n// --- Per-chain / per-segment state -------------------------------------------\n\n/** Integrator state for one segment. angle = θ displacement in RADIANS. */\ninterface SegmentState {\n angle: number; // θ_i in radians (displacement from rest)\n angularVelocity: number; // ω_i in radians/s\n}\n\n/** All precomputed per-chain data (rest angles already in radians). */\ninterface ChainData {\n chain: IkiPhysicsChain;\n restAnglesRad: number[]; // restAngle_j in radians; 0 when omitted\n state: SegmentState[]; // preallocated, length = segments.length\n}\n\n// --- Public API --------------------------------------------------------------\n\n/**\n * Host-agnostic multi-segment angular-pendulum-chain secondary-motion driver.\n * Peer of {@link PhysicsMotion} and {@link IdleMotion}.\n *\n * Each chain anchors to a matrix deformer in the model hierarchy. The driver\n * self-computes the anchor's world rotation via `resolveDeformers` (a\n * private `ParameterStore` is filled from `read` ONCE per frame) and integrates\n * a per-segment angular pendulum with semi-implicit Euler on a fixed 1/60s\n * sub-step accumulator. Each segment's angular displacement θ (in radians\n * internally) is emitted in DEGREES on its output parameter, so `rotate = 0`\n * when the chain is at its authored rest pose.\n *\n * Usage:\n * const chains = new HairChainMotion(\n * model.physicsChains ?? [],\n * model.parameters,\n * model.deformers ?? [],\n * (id) => currentValue(id),\n * player.setParameter.bind(player),\n * );\n * // inside your rAF loop, right AFTER physics.update(now):\n * chains.update(performance.now());\n *\n * The host schedules updates; this class has no timers, rAF, DOM, or Date.now.\n */\nexport class HairChainMotion {\n /** Every segment's output, chain by chain — what `emitSegment` writes. */\n readonly drivenParameterIds: readonly string[];\n /**\n * Per segment, in `drivenParameterIds` order: how many times the finiteness\n * guard reset its state or `emitSegment` replaced its non-finite product. Up\n * to two per frame, so guard activations, not repaired frames. A diagnostic;\n * emitted values are unchanged.\n */\n readonly resets: readonly number[];\n private readonly resetCounts: number[];\n private readonly chainData: ChainData[];\n private readonly params: Map<string, IkiParameter>;\n private readonly deformers: IkiDeformer[];\n private readonly store: ParameterStore;\n private readonly read: (id: string) => number;\n private readonly sink: (id: string, value: number) => void;\n\n private readonly clock = new FixedStepClock();\n\n constructor(\n chains: IkiPhysicsChain[],\n params: IkiParameter[],\n deformers: IkiDeformer[],\n read: (id: string) => number,\n sink: (id: string, value: number) => void,\n ) {\n this.params = new Map(params.map((p) => [p.id, p]));\n this.deformers = deformers;\n // Private ParameterStore reused every frame for anchor-world resolution.\n this.store = new ParameterStore(params);\n this.read = read;\n this.sink = sink;\n\n // Precompute rest angles in radians; preallocate segment state (no per-substep alloc).\n this.chainData = chains.map((chain) => ({\n chain,\n restAnglesRad: chain.segments.map((seg) =>\n seg.restAngle !== undefined ? seg.restAngle * DEG2RAD : 0,\n ),\n state: chain.segments.map(() => ({ angle: 0, angularVelocity: 0 })),\n }));\n this.drivenParameterIds = chains.flatMap((c) =>\n c.segments.map((s) => s.output.parameter),\n );\n this.resetCounts = this.drivenParameterIds.map(() => 0);\n this.resets = this.resetCounts;\n }\n\n /**\n * Advance every chain to the given wall-clock timestamp (milliseconds).\n *\n * First call: seed every segment to θ=0/ω=0 (rest), emit the rest output\n * (outDefault + 0), and return without integrating — mirrors PhysicsMotion's\n * first-frame behavior so a model loaded in motion does not kick.\n *\n * Subsequent calls: dt = clamp(nowMs - prevNowMs, 0, MAX_DT_MS) → seconds into\n * accumulator. The per-frame world snapshot (anchor world angles) is taken ONCE\n * per update() — NOT per chain — so all chains share a consistent frame snapshot.\n * Fixed FIXED_DT_S sub-steps are run root→tip, capped at MAX_SUBSTEPS; leftover\n * time is carried to the next frame. Segments emit after substeps (even on zero\n * substeps) with a non-finite guard.\n */\n update(nowMs: number): void {\n // IkiMotion steps this driver every frame even for a chainless model;\n // with nothing to integrate or emit, skip the per-frame deformer resolve.\n if (this.chainData.length === 0) return;\n if (this.clock.isSeedFrame) {\n // FIRST FRAME: seed rest, emit outDefault for every segment, NO integration.\n this.clock.advance(nowMs);\n let flat = 0;\n for (const cd of this.chainData) {\n for (let i = 0; i < cd.chain.segments.length; i++) {\n cd.state[i].angle = 0;\n cd.state[i].angularVelocity = 0;\n this.emitSegment(flat++, cd.chain.segments[i], cd.state[i]);\n }\n }\n return;\n }\n\n const steps = this.clock.advance(nowMs);\n\n // Take the per-frame world snapshot ONCE per update() — NOT per chain.\n // Fill the private store from read, then resolve every deformer (warp grids\n // too, though only the matrix worlds are read here).\n for (const param of this.params.values()) {\n this.store.set(param.id, this.read(param.id));\n }\n const worldMap = resolveDeformers(this.deformers, this.store).worlds;\n\n // Read each chain's anchor world angle ONCE per frame (consistent across substeps,\n // like physics-motion.ts:122 `targets`).\n const anchorAnglesRad = this.chainData.map((cd) =>\n this.anchorWorldAngleRad(worldMap, cd.chain.anchorDeformer),\n );\n\n for (let s = 0; s < steps; s++) {\n for (let c = 0; c < this.chainData.length; c++) {\n this.stepChain(this.chainData[c], anchorAnglesRad[c]);\n }\n }\n\n // Emit always (even on zero substeps) so the sink stays in sync.\n let flat = 0;\n for (const cd of this.chainData) {\n for (let i = 0; i < cd.chain.segments.length; i++) {\n const st = cd.state[i];\n // FINITENESS GUARD (mirror physics-motion.ts:141): a pathological rig\n // (tiny mass / huge stiffness) can push the fixed-substep integrator\n // past its explicit-stability limit. Snap the segment back to rest so\n // a validated model can never poison the sink with NaN/Infinity.\n if (\n !Number.isFinite(st.angle) ||\n !Number.isFinite(st.angularVelocity)\n ) {\n st.angle = 0;\n st.angularVelocity = 0;\n this.resetCounts[flat]++;\n }\n this.emitSegment(flat++, cd.chain.segments[i], st);\n }\n }\n }\n\n /**\n * Extract world rotation (radians) from the anchor's Affine tuple.\n * Affine = [a,b,c,d,e,f]; rotation column = (a,b) → atan2(b,a).\n *\n * If the anchor id is absent from the map, THROWS an internal Error — the\n * format validator guarantees the anchor exists, so absence is an invariant\n * break (mirrors resolveDeformers' throw on an unresolved parent).\n */\n private anchorWorldAngleRad(\n worldMap: Map<string, Affine>,\n anchorId: string,\n ): number {\n const world = worldMap.get(anchorId);\n if (!world) {\n throw new Error(\n `HairChainMotion: anchor deformer \"${anchorId}\" not found in resolved world map — model not validated?`,\n );\n }\n // Affine [a,b,c,d,e,f]: the first column (a,b) is the x-axis direction\n // after rotation, so atan2(b,a) gives the world rotation angle in radians.\n return Math.atan2(world[1], world[0]);\n }\n\n /**\n * One fixed sub-step of FIXED_DT_S seconds for all segments in a chain.\n *\n * Segments are integrated ROOT→TIP so each segment can read its upstream\n * neighbor's current-substep state when computing the world angle Φ_i.\n * (The chain is causal root-to-tip; reversing the order would use stale θ\n * values from the previous substep for Φ_i computation.)\n *\n * Per-segment semi-implicit (symplectic) Euler:\n * Φ_i = anchorWorldAngleRad + Σ_{j≤i}(restAngle_j + θ_j)\n * α_i = (−stiffness_i·θ_i − strength·sin(Φ_i − gravityAngle_rad) − damping_i·ω_i) / mass_i\n * ω_i += α_i · FIXED_DT_S (velocity updated FIRST = semi-implicit)\n * θ_i += ω_i · FIXED_DT_S (position updated from NEW velocity)\n *\n * The spring term is −stiffness·θ (restoring θ→0); restAngle does NOT appear\n * in the spring term, only in Φ_i for the gravity torque.\n */\n private stepChain(cd: ChainData, anchorAngleRad: number): void {\n const { chain, restAnglesRad, state } = cd;\n const gravityAngleRad = chain.gravity.angle * DEG2RAD;\n const strength = chain.gravity.strength;\n\n // Accumulate world angle root→tip as we go.\n let worldAngleAccumRad = anchorAngleRad;\n\n for (let i = 0; i < chain.segments.length; i++) {\n const seg: IkiPhysicsChainSegment = chain.segments[i];\n const st = state[i];\n\n // World angle of this segment: anchor + sum of all segments 0..i.\n worldAngleAccumRad += restAnglesRad[i] + st.angle;\n const phi = worldAngleAccumRad;\n\n const alpha =\n (-seg.stiffness * st.angle -\n strength * Math.sin(phi - gravityAngleRad) -\n seg.damping * st.angularVelocity) /\n seg.mass;\n\n // Semi-implicit Euler: update velocity first, then position with new velocity.\n st.angularVelocity += alpha * FIXED_DT_S;\n st.angle += st.angularVelocity * FIXED_DT_S;\n }\n }\n\n /** Emit outDefault + (θ_i · RAD2DEG) · scale for one segment. */\n private emitSegment(\n flat: number,\n seg: IkiPhysicsChainSegment,\n st: SegmentState,\n ): void {\n const outParam = this.params.get(seg.output.parameter);\n const outDefault = outParam\n ? clamp(outParam.default, outParam.min, outParam.max)\n : 0;\n const value = outDefault + st.angle * RAD2DEG * seg.output.scale;\n // Final guard: even a finite-but-enormous θ could overflow to ±Infinity.\n const finite = Number.isFinite(value);\n if (!finite) this.resetCounts[flat]++;\n this.sink(seg.output.parameter, finite ? value : outDefault);\n }\n}\n","import { type IkiModel, StandardParameter } from \"@ikijs/format\";\nimport { ClipPlayer } from \"./clip-player\";\nimport { ExpressionPlayer } from \"./expression-player\";\nimport { MAX_DT_MS } from \"./frame-clock\";\nimport { HairChainMotion } from \"./hair-chain-motion\";\nimport { IdleMotion } from \"./idle-motion\";\nimport { clamp } from \"./math\";\nimport { ParameterStore } from \"./parameter-store\";\nimport { PhysicsMotion } from \"./physics-motion\";\n\n/** IdleMotion's head sway and gaze: what a declared Idle group replaces. */\nconst HEAD_AND_GAZE: ReadonlySet<string> = new Set([\n StandardParameter.AngleX,\n StandardParameter.AngleY,\n StandardParameter.AngleZ,\n StandardParameter.EyeballX,\n StandardParameter.EyeballY,\n]);\n\n/**\n * Bundles the model's motion into the one loop every host otherwise\n * hand-builds: the procedural {@link IdleMotion}, the model's motion clips and\n * expressions, then {@link PhysicsMotion} and {@link HairChainMotion} — stepped\n * in the order physics and chains depend on, with a record of what they write.\n *\n * Usage:\n * const motion = new IkiMotion(\n * model,\n * (id) => player.getParameter(id),\n * (id, value) => player.setParameter(id, value),\n * );\n * motion.playExpression(\"smile\");\n * motion.playMotion(\"Nod\", 0);\n * // inside your rAF loop:\n * motion.update(performance.now());\n * // then the signals the host owns, e.g. lip-sync:\n * player.setParameter(StandardParameter.MouthOpen, mouth);\n *\n * The model is the catalog: a host lists what it can play from\n * `model.expressions` (ids) and `model.motions` (group names and clip\n * indices). There are no getters for them here.\n *\n * Clips and expressions compose over a base, never over the store's current\n * value: an id's base is the value an earlier stage put in this update's\n * frame (for the one-shot: the procedural idle and the `Idle` loop; for an\n * expression: those and the one-shot), else its resting value\n * `clamp(default, min, max)`. So an `add` on a brow cannot accumulate across\n * frames, and an expression composes with the blink and a clip-driven head.\n * When an expression's stop completes or a one-shot ends, the ids it drove\n * are written once more at base and then dropped; so are the ids only a\n * replaced clip or expression held, once the one replacing it finishes its\n * fade-in. A parameter nothing else writes therefore rests at its default.\n *\n * Idle replacement: when the model declares an `Idle` motion group, its clips\n * loop in place of the procedural head sway and gaze — IdleMotion's AngleX/Y/Z\n * and EyeballX/Y writes are dropped. A head or gaze parameter the Idle clips\n * don't animate is left unwritten by idle and rests where it is (a one-shot or\n * an expression can still drive it). Blink (EyeOpen L/R), Breath and the\n * ambient sway stay procedural: the format rejects an Idle curve on them.\n * Without an `Idle` group the procedural idle runs whole.\n *\n * The host schedules; this class has no timers, rAF, DOM, or Date.now.\n *\n * Stopping is the host's too: stop calling update(). The drivers leave the\n * pose where it was — a host that wants it back writes its own resting values\n * to `drivenParameterIds`.\n */\nexport class IkiMotion {\n /**\n * Everything {@link update} may write, deduplicated, in this order: idle ids\n * (without head and gaze when the model declares an `Idle` group), the curve\n * parameters of every motion group, expression parameters, rig outputs,\n * then chain-segment outputs. May name ids the model lacks (idle writes the\n * standard ids regardless, and the player silently drops writes to unknown\n * ids) — intersect with the model's parameters if you mirror into your own\n * store.\n */\n readonly drivenParameterIds: readonly string[];\n private readonly sink: (id: string, value: number) => void;\n private readonly idle: IdleMotion;\n private readonly clips: ClipPlayer;\n private readonly expressions: ExpressionPlayer;\n private readonly physics: PhysicsMotion;\n private readonly chains: HairChainMotion;\n /** Resting value per id; 0 for an undeclared id. */\n private readonly rest: (id: string) => number;\n /** This update's idle, clip and expression writes, in first-write order. */\n private readonly frame = new Map<string, number>();\n /** Bound once: `Map.forEach` hands it each entry without a tuple per id. */\n private readonly flush = (value: number, id: string): void =>\n this.sink(id, value);\n private prevNowMs: number | undefined = undefined;\n\n constructor(\n model: IkiModel,\n read: (id: string) => number,\n sink: (id: string, value: number) => void,\n ) {\n const rigs = model.physics ?? [];\n const chains = model.physicsChains ?? [];\n // A store nobody writes holds every parameter at rest, resolved the way\n // the player's store resolves it (a non-finite default rests at 0,\n // clamped), and reads 0 for an undeclared id.\n const restPose = new ParameterStore(model.parameters);\n this.sink = sink;\n this.rest = (id) => restPose.get(id);\n this.clips = new ClipPlayer(model.motions, model.parameters);\n this.expressions = new ExpressionPlayer(\n model.expressions,\n model.parameters,\n );\n const idleKeeps: (id: string) => boolean = this.clips.hasIdleLoop\n ? (id) => !HEAD_AND_GAZE.has(id)\n : () => true;\n this.idle = new IdleMotion((id, value) => {\n if (idleKeeps(id)) this.frame.set(id, value);\n });\n this.physics = new PhysicsMotion(rigs, model.parameters, read, sink);\n this.chains = new HairChainMotion(\n chains,\n model.parameters,\n model.deformers ?? [],\n read,\n sink,\n );\n this.drivenParameterIds = [\n ...new Set([\n ...this.idle.drivenParameterIds.filter(idleKeeps),\n ...this.clips.parameterIds,\n ...this.expressions.parameterIds,\n ...this.physics.drivenParameterIds,\n ...this.chains.drivenParameterIds,\n ]),\n ];\n }\n\n /**\n * Make expression `id` active, fading it in over its `fadeIn` from the\n * current pose: it replaces the active one and blends from that one's\n * current output, as {@link playMotion} does, so nothing dips toward base on\n * the way. Returns false, and changes nothing, for an id the model does not\n * declare. Playing the active id again changes nothing and returns true; an\n * expression never stacks on itself.\n */\n playExpression(id: string): boolean {\n return this.expressions.play(id);\n }\n\n /** Fade the active expression, if any, back to base over its `fadeOut`. */\n stopExpression(): void {\n this.expressions.stop();\n }\n\n /**\n * Start clip `index` of motion group `group` at once. A running one-shot\n * stops, and the new clip fades in from the old one's last pose. Returns\n * false, and changes nothing, for a group the model does not declare or an\n * index that is not an integer in range. Any group plays one-shot, `Idle`\n * included; there is no queue.\n */\n playMotion(group: string, index: number): boolean {\n return this.clips.play(group, index);\n }\n\n /**\n * Advance everything to the same wall-clock timestamp (milliseconds), in\n * this order:\n *\n * 1. Idle writes blink, breath, the ambient sway (and head and gaze, unless\n * replaced) into this update's frame.\n * 2. The clip stage writes the `Idle` loop, then the one-shot over it.\n * 3. The expression stage writes the active expression, fading in from the\n * pose it replaced, or a stop fading back to base.\n * 4. The frame goes to `sink`, each id exactly once, in the order its first\n * writer gave it: an expression on EyeOpenL is flushed in idle's slot.\n * 5. Physics, then chains. They read their inputs through `read`, so the\n * springs lag the head this update put on screen (idle sway or clips),\n * and a chain resolves its anchor from that same pose (which may include\n * a physics output). Physics outputs are physics-owned: a clip or\n * expression that writes one is overwritten here.\n *\n * The host writes the signals it owns (lip-sync MouthOpen, gaze overrides)\n * AFTER update(); the last write wins. That is how lip-sync beats an\n * expression that opens the mouth.\n *\n * The clips and expressions advance by `clamp(now − prev, 0, MAX_DT_MS)`,\n * 0 on the first update. A non-finite `nowMs` is a dropped frame: idle and\n * both players write nothing and do not advance (physics and chains re-emit\n * their outputs unchanged), and the next finite frame measures from the\n * last finite one, as IdleMotion does.\n */\n update(nowMs: number): void {\n this.frame.clear();\n this.idle.update(nowMs);\n if (Number.isFinite(nowMs)) {\n const dtS =\n this.prevNowMs === undefined\n ? 0\n : clamp(nowMs - this.prevNowMs, 0, MAX_DT_MS) / 1000;\n this.prevNowMs = nowMs;\n this.clips.apply(dtS, this.frame, this.rest);\n this.expressions.apply(dtS, this.frame, this.rest);\n }\n this.frame.forEach(this.flush);\n this.physics.update(nowMs);\n this.chains.update(nowMs);\n }\n}\n","import {\n DEFAULT_FADE_SECONDS,\n IDLE_MOTION_GROUP,\n type IkiMotionClip,\n type IkiMotionCurve,\n type IkiParameter,\n} from \"@ikijs/format\";\nimport { clamp, lerp, smoothstep } from \"./math\";\n\n// --- Small pure helpers ------------------------------------------------------\n\n/**\n * The slope at each key of a `\"smooth\"` curve, by Steffen's monotone cubic\n * (M. Steffen, \"A simple method for monotonic interpolation in one\n * dimension\", 1990): each inner key's slope is capped by the slopes of the two\n * lines either side, so no segment overshoots its keys, and it is zero where\n * those lines change direction or one is flat. Chosen over Fritsch–Carlson\n * because it is one closed form per key, with no second pass to rescale. The\n * first and last key get slope zero (not Steffen's own end rule) so the curve\n * meets the holds before and after it without a kink. Exported for the tests;\n * not part of the package entry.\n */\nexport function curveSlopes(keys: IkiMotionCurve[\"keys\"]): number[] {\n const slopes = keys.map(() => 0);\n for (let i = 1; i < keys.length - 1; i++) {\n const [t0, v0] = keys[i - 1];\n const [t1, v1] = keys[i];\n const [t2, v2] = keys[i + 1];\n const h0 = t1 - t0;\n const h1 = t2 - t1;\n const s0 = (v1 - v0) / h0;\n const s1 = (v2 - v1) / h1;\n // The slope at key i of the parabola through the three keys.\n const p = (s0 * h1 + s1 * h0) / (h0 + h1);\n slopes[i] =\n (Math.sign(s0) + Math.sign(s1)) *\n Math.min(Math.abs(s0), Math.abs(s1), Math.abs(p) / 2);\n }\n return slopes;\n}\n\n/**\n * A curve's value at `t` seconds, holding the first key's value before it and\n * the last key's value after it. Between two keys it is a straight line, or,\n * given the keys' `slopes` ({@link curveSlopes}), the cubic Hermite through\n * them. Exported for the tests; not part of the package entry.\n */\nexport function sampleCurve(\n keys: IkiMotionCurve[\"keys\"],\n t: number,\n slopes?: readonly number[],\n): number {\n const first = keys[0];\n if (t <= first[0]) return first[1];\n const last = keys[keys.length - 1];\n if (t >= last[0]) return last[1];\n // first[0] < t < last[0], so the scan stops on a key after `t`; `<=` puts a\n // `t` exactly on a key at the start of its segment, where both forms are\n // exact.\n let i = 1;\n while (keys[i][0] <= t) i++;\n const [t0, v0] = keys[i - 1];\n const [t1, v1] = keys[i];\n const h = t1 - t0;\n const u = (t - t0) / h;\n if (!slopes) return lerp(v0, v1, u);\n // The Hermite basis regrouped: the eased move between the two values, plus\n // each key's slope term, which vanishes at both ends of the segment.\n return (\n lerp(v0, v1, smoothstep(u)) +\n h * u * (1 - u) * (slopes[i - 1] * (1 - u) - slopes[i] * u)\n );\n}\n\n/**\n * The clip's fade-in and fade-out weights at `t` seconds into it, each easing\n * along {@link smoothstep} and clamped to `[0, 1]`. A zero fade gives 1 — no\n * fade on that side. An absent one lasts `DEFAULT_FADE_SECONDS`, capped at\n * half the clip's duration: two absent fades never overlap, so a short clip\n * still reaches full weight, and, like a declared fade, each fits inside the\n * clip: the fade-out never starts before t = 0, so a replacing clip's first\n * frame (wOut = 1) is still the old pose. Exported for the tests; not part of\n * the package entry.\n */\nexport function fadeWeights(\n clip: IkiMotionClip,\n t: number,\n): { wIn: number; wOut: number } {\n const fallback = Math.min(DEFAULT_FADE_SECONDS, clip.duration / 2);\n const fadeIn = clip.fadeIn ?? fallback;\n const fadeOut = clip.fadeOut ?? fallback;\n return {\n wIn: fadeIn > 0 ? smoothstep(t / fadeIn) : 1,\n wOut: fadeOut > 0 ? smoothstep((clip.duration - t) / fadeOut) : 1,\n };\n}\n\n// --- Clip player -------------------------------------------------------------\n\n/** The one-shot slot: one playing clip, no queue. */\ninterface Slot {\n clip: IkiMotionClip;\n /** Seconds since the clip started. */\n t: number;\n /** The pose the clip fades in from: the replaced clip's last output. */\n from: Map<string, number>;\n /**\n * What the slot wrote on its last apply, clamped to each parameter's range;\n * `from` until the first apply, since that is still what is on screen.\n */\n last: Map<string, number>;\n}\n\n/**\n * Plays a model's motion clips into a per-update frame map. Internal to\n * {@link IkiMotion}, which owns the frame: the base rule below only holds\n * inside that frame, so this is not exported from the package entry.\n *\n * Two layers, written in this order on every {@link apply}:\n * - the Idle loop, when the model declares {@link IDLE_MOTION_GROUP}: its clips\n * back-to-back at full weight, wrapping from the last to the first;\n * - the one-shot slot over it, started by {@link play}. A clip blends between\n * the frame's base value and its own curves with its fade-in and fade-out;\n * a new `play` replaces the running clip and fades in from its last output.\n *\n * IkiMotion steps it once per update; this class has no timers, rAF, DOM, or\n * Date.now.\n */\nexport class ClipPlayer {\n /** True when the model declares the {@link IDLE_MOTION_GROUP} group. */\n readonly hasIdleLoop: boolean;\n /** Every curve parameter across all groups, deduplicated, insertion-ordered. */\n readonly parameterIds: readonly string[];\n private readonly motions: Record<string, IkiMotionClip[]>;\n private readonly params: Map<string, IkiParameter>;\n /** Key slopes of every `\"smooth\"` curve; a linear curve has no entry. */\n private readonly slopes: Map<IkiMotionCurve, readonly number[]>;\n\n private readonly idleClips: readonly IkiMotionClip[];\n private readonly idleLength: number;\n private idleIndex = 0;\n /** Seconds into the current Idle clip. */\n private idleTime = 0;\n\n private slot: Slot | undefined = undefined;\n\n constructor(\n motions: Record<string, IkiMotionClip[]> | undefined,\n parameters: IkiParameter[],\n ) {\n this.motions = motions ?? {};\n this.params = new Map(parameters.map((p) => [p.id, p]));\n // Own-property checks throughout: a group named after an Object.prototype\n // member (\"toString\") is not declared.\n this.hasIdleLoop = Object.hasOwn(this.motions, IDLE_MOTION_GROUP);\n this.idleClips = this.hasIdleLoop ? this.motions[IDLE_MOTION_GROUP] : [];\n this.idleLength = this.idleClips.reduce((sum, c) => sum + c.duration, 0);\n const curves = Object.values(this.motions).flatMap((clips) =>\n clips.flatMap((c) => c.curves),\n );\n this.parameterIds = [...new Set(curves.map((curve) => curve.parameter))];\n // Worked out once here, so a frame only evaluates the cubic.\n this.slopes = new Map(\n curves\n .filter((curve) => curve.interpolation !== \"linear\")\n .map((curve) => [curve, curveSlopes(curve.keys)]),\n );\n }\n\n /**\n * Start clip `index` of `group` at once, replacing any running one-shot.\n * Returns false, and changes nothing, for a group the model does not declare\n * or an index that is not an integer in range. Any group plays one-shot,\n * Idle included.\n */\n play(group: string, index: number): boolean {\n if (!Object.hasOwn(this.motions, group)) return false;\n const clips = this.motions[group];\n if (!Number.isInteger(index) || index < 0 || index >= clips.length) {\n return false;\n }\n // The new clip fades in from what the old one last put on screen. Until\n // the new one's first apply the screen still shows `from`, so that is its\n // last output too: a second play before the next apply inherits the same\n // pose instead of dropping the ids the first one never got to write.\n const from = this.slot?.last ?? new Map<string, number>();\n this.slot = { clip: clips[index], t: 0, from, last: from };\n return true;\n }\n\n /**\n * Advance `dtS` seconds and write into `frame`: the Idle loop layer, then\n * the one-shot slot over it.\n *\n * `frame` holds what earlier stages wrote this update. An id's base is its\n * frame value, else `rest(id)` — the parameter's resting value,\n * `clamp(default, min, max)`. The base is never the store's current value,\n * so a clip cannot accumulate across frames.\n */\n apply(\n dtS: number,\n frame: Map<string, number>,\n rest: (id: string) => number,\n ): void {\n if (this.hasIdleLoop) this.applyIdle(dtS, frame);\n if (this.slot) this.applySlot(this.slot, dtS, frame, rest);\n }\n\n /**\n * The Idle clips play as one continuous loop, so their fades are ignored:\n * fading each clip at its seams would dip the pose toward rest on every\n * clip boundary.\n */\n private applyIdle(dtS: number, frame: Map<string, number>): void {\n const clips = this.idleClips;\n let clip = clips[this.idleIndex];\n this.idleTime += dtS;\n if (this.idleTime >= clip.duration) {\n // A frame can cross many clips shorter than a frame. Whole passes of the\n // group land back at this same clip, so dropping them first leaves at\n // most one pass to walk, whatever dt is. The cap on the walk guards\n // float rounding: summing the durations one by one need not match the\n // precomputed total exactly.\n this.idleTime %= this.idleLength;\n for (\n let step = 0;\n step < clips.length && this.idleTime >= clip.duration;\n step++\n ) {\n this.idleTime -= clip.duration;\n this.idleIndex = (this.idleIndex + 1) % clips.length;\n clip = clips[this.idleIndex];\n }\n }\n for (const curve of clip.curves) {\n frame.set(curve.parameter, this.sample(curve, this.idleTime));\n }\n }\n\n private applySlot(\n slot: Slot,\n dtS: number,\n frame: Map<string, number>,\n rest: (id: string) => number,\n ): void {\n const { clip, from } = slot;\n // What earlier stages (and the Idle layer) wrote this update, else rest.\n const base = (id: string): number => frame.get(id) ?? rest(id);\n slot.t += dtS;\n\n if (slot.t >= clip.duration) {\n // One last write at base for every id the slot drove, then the slot is\n // gone: a parameter nothing else writes settles at its default instead\n // of holding the clip's final value.\n const ids = new Set(clip.curves.map((curve) => curve.parameter));\n for (const id of from.keys()) ids.add(id);\n for (const id of ids) frame.set(id, base(id));\n this.slot = undefined;\n return;\n }\n\n // Fade-in moves from the old pose to the new sample; fade-out pulls the\n // result to base. With an empty `from` this is lerp(base, s, wIn * wOut).\n const { wIn, wOut } = fadeWeights(clip, slot.t);\n const last = new Map<string, number>();\n const write = (id: string, sample: number | undefined): void => {\n const b = base(id);\n const f = from.get(id) ?? b;\n const value = lerp(b, lerp(f, sample ?? b, wIn), wOut);\n frame.set(id, value);\n last.set(id, this.displayed(id, value));\n };\n for (const curve of clip.curves) {\n write(curve.parameter, this.sample(curve, slot.t));\n }\n for (const id of from.keys()) if (!last.has(id)) write(id, undefined);\n slot.last = last;\n\n // From here on every value equals the no-`from` value, to rounding, and an\n // id only `from` held was just written at base, to rounding: drop them so\n // they are not written again.\n if (wIn >= 1) from.clear();\n }\n\n /** The curve at `t`, smooth unless it is marked `\"linear\"`. */\n private sample(curve: IkiMotionCurve, t: number): number {\n return sampleCurve(curve.keys, t, this.slopes.get(curve));\n }\n\n /**\n * The clip stage's output for an id, clamped to the parameter's range as\n * the store clamps every write. A replacing clip fades in from this, not\n * the raw value — a curve past the max would otherwise sit still on screen\n * until the fade got back inside the range.\n */\n private displayed(id: string, value: number): number {\n const param = this.params.get(id);\n return param ? clamp(value, param.min, param.max) : value;\n }\n}\n","import {\n DEFAULT_FADE_SECONDS,\n type IkiExpression,\n type IkiExpressionParameter,\n type IkiParameter,\n} from \"@ikijs/format\";\nimport { clamp, lerp, smoothstep } from \"./math\";\n\n/**\n * A parameter's value as a line in its base: `scale · base + offset`. Every\n * blend is one (add c is 1·base + c, multiply c is c·base, overwrite c is\n * 0·base + c) and so is leaving a parameter alone (1·base); a lerp between two\n * lines is a line too. So whatever mix of expressions is on screen, however\n * many were cut off mid-fade, is one line per parameter, and it still follows\n * the live base: a multiply on EyeOpen keeps the blink.\n */\ninterface Line {\n scale: number;\n offset: number;\n}\n\n/** The line of a parameter an expression leaves alone: the base itself. */\nconst BASE: Line = { scale: 1, offset: 0 };\n\nfunction lineOf({ value, blend = \"add\" }: IkiExpressionParameter): Line {\n switch (blend) {\n case \"add\":\n return { scale: 1, offset: value };\n case \"multiply\":\n return { scale: value, offset: 0 };\n case \"overwrite\":\n return { scale: 0, offset: value };\n }\n}\n\n/** The line's value over `base`. */\nfunction at({ scale, offset }: Line, base: number): number {\n return scale * base + offset;\n}\n\n/**\n * {@link lerp}, but exactly `b` at `t = 1` (lerp is exact only at 0): a\n * finished fade lands on its target, and an id it lets go of on base itself.\n */\nfunction mix(a: number, b: number, t: number): number {\n return t === 1 ? b : lerp(a, b, t);\n}\n\n/** What the player can fade to: an expression, or the base itself. */\ninterface Pose {\n /** Undefined for {@link RELEASE}. */\n expression: IkiExpression | undefined;\n /** The parameters it drives, by id. */\n lines: ReadonlyMap<string, Line>;\n}\n\n/** The pose a stop fades to: it drives nothing, so every id goes to base. */\nconst RELEASE: Pose = { expression: undefined, lines: new Map() };\n\n/**\n * The fade in progress: toward `pose`, from the pose on screen when it began.\n */\ninterface Fade {\n pose: Pose;\n /** How long it lasts, in seconds. */\n seconds: number;\n /** Seconds since it began. */\n elapsed: number;\n}\n\n/**\n * The fade's weight, eased along {@link smoothstep} from 0 to 1 over its\n * seconds; at or past its end exactly 1. A zero fade is at 1 the moment it\n * begins, with no division by zero: an expression with a zero `fadeIn` is\n * fully on as soon as it is played, so a stop before the next apply fades it\n * out from full.\n */\nfunction weight({ seconds, elapsed }: Fade): number {\n return elapsed >= seconds ? 1 : smoothstep(elapsed / seconds);\n}\n\n/** An id the player writes on every apply. */\ninterface Held {\n id: string;\n /**\n * Its base on the last apply, where a fold matches the screen (see\n * {@link ExpressionPlayer.begin}); NaN before the first apply.\n */\n base: number;\n}\n\n/**\n * Plays a model's expressions into a per-update frame map. Internal to\n * {@link IkiMotion}, which owns the frame: the base rule below only holds\n * inside that frame, so this is not exported from the package entry.\n *\n * One fade runs at a time, from the pose on screen when it began to its\n * target. {@link play} fades an expression in over its `fadeIn`; {@link stop}\n * fades back to base over the playing expression's `fadeOut`. Either one\n * interrupting a fade starts from where that fade got to, as a replacing\n * motion clip does, so the screen never jumps or dips toward base; unlike a\n * clip's, that starting pose keeps following the live base (see {@link Line}),\n * save a part of it the screen showed held at a range limit, which stays there.\n * Each target is taken over the base, never over what is on screen, so an\n * `add` never stacks on itself however often it is replayed.\n *\n * IkiMotion steps it once per update; this class has no timers, rAF, DOM, or\n * Date.now.\n */\nexport class ExpressionPlayer {\n /** Every expression parameter, deduplicated, insertion-ordered. */\n readonly parameterIds: readonly string[];\n private readonly poses: Map<string, Pose & { expression: IkiExpression }>;\n private readonly params: Map<string, IkiParameter>;\n\n /** Undefined while nothing is held. */\n private fade: Fade | undefined = undefined;\n /**\n * The pose on screen when {@link fade} began, a line per id; empty once the\n * fade has finished, since the screen is then its target alone.\n */\n private from = new Map<string, Line>();\n /** Every id `from` or the fade drives: what each apply writes. */\n private held: Held[] = [];\n\n constructor(\n expressions: IkiExpression[] | undefined,\n parameters: IkiParameter[],\n ) {\n const list = expressions ?? [];\n this.params = new Map(parameters.map((p) => [p.id, p]));\n this.poses = new Map(\n list.map((expression) => [\n expression.id,\n {\n expression,\n lines: new Map(\n expression.parameters.map((p) => [p.parameter, lineOf(p)]),\n ),\n },\n ]),\n );\n this.parameterIds = [\n ...new Set(list.flatMap((e) => e.parameters.map((p) => p.parameter))),\n ];\n }\n\n /**\n * Fade expression `id` in over its `fadeIn`, from what is on screen: the\n * base, or the output of the expression it replaces, or of a stop still\n * fading out. Returns false, and changes nothing, for an expression id the\n * model does not declare; playing the expression already fading in or held\n * changes nothing and returns true.\n */\n play(id: string): boolean {\n const pose = this.poses.get(id);\n if (!pose) return false;\n if (this.fade?.pose === pose) return true;\n this.begin(pose, pose.expression.fadeIn ?? DEFAULT_FADE_SECONDS);\n return true;\n }\n\n /**\n * Fade back to base over the playing expression's `fadeOut`, from what is\n * on screen. Does nothing when nothing is playing or a stop is already\n * fading out.\n */\n stop(): void {\n const playing = this.fade?.pose.expression;\n if (!playing) return;\n this.begin(RELEASE, playing.fadeOut ?? DEFAULT_FADE_SECONDS);\n }\n\n /**\n * Freeze what is on screen into {@link from}, at the weight the current\n * fade has reached, and start a fade from it toward `pose`. Folding keeps\n * this to one `from` and one fade however fast the plays come.\n *\n * {@link apply} clamps each end before it mixes, so each end folds in as\n * the screen showed it at the last apply's base ({@link pinned}): the new\n * fade starts on what was on screen, an end held at a range limit stays\n * there as the base moves, and the rest still follow the live base. Should\n * the base move so far that the old pose would have left the limit, the\n * start holds it instead: a little off, but continuous, and it fades out.\n */\n private begin(pose: Pose, seconds: number): void {\n if (this.fade) {\n const { lines } = this.fade.pose;\n const w = weight(this.fade);\n const from = new Map<string, Line>();\n for (const { id, base } of this.held) {\n const a = this.pinned(id, this.from.get(id) ?? BASE, base);\n const b = this.pinned(id, lines.get(id) ?? BASE, base);\n from.set(id, {\n scale: mix(a.scale, b.scale, w),\n offset: mix(a.offset, b.offset, w),\n });\n }\n this.from = from;\n }\n this.fade = { pose, seconds, elapsed: 0 };\n this.held = [...new Set([...this.from.keys(), ...pose.lines.keys()])].map(\n (id) => ({ id, base: NaN }),\n );\n }\n\n /**\n * Advance `dtS` seconds and write every held id into `frame`: the pose on\n * screen when the fade began, lerped toward the fade's target by its\n * weight, each end clamped to the parameter's range. An id the target does\n * not drive goes to base.\n *\n * `frame` holds what earlier stages wrote this update. A parameter id's base\n * is its frame value, else `rest(id)` — the parameter's resting value,\n * `clamp(default, min, max)`. The base is never the store's current value,\n * so an `add` cannot accumulate across frames.\n */\n apply(\n dtS: number,\n frame: Map<string, number>,\n rest: (id: string) => number,\n ): void {\n // IkiMotion calls this every frame for every model; most hold nothing.\n const fade = this.fade;\n if (!fade) return;\n fade.elapsed += dtS;\n const w = weight(fade);\n const { lines } = fade.pose;\n for (const held of this.held) {\n const { id } = held;\n const base = frame.get(id) ?? rest(id);\n held.base = base;\n const start = this.displayed(id, at(this.from.get(id) ?? BASE, base));\n const end = this.displayed(id, at(lines.get(id) ?? BASE, base));\n frame.set(id, mix(start, end, w));\n }\n if (w < 1) return;\n // The fade is done and the screen is its target alone. An id only `from`\n // drove was just written at base, exactly; dropping it now makes that its\n // last write, so a parameter nothing else writes rests at its default\n // instead of being held. A finished stop drives nothing, so it goes too.\n if (!fade.pose.expression) {\n this.fade = undefined;\n this.from.clear();\n this.held = [];\n } else if (this.from.size > 0) {\n this.from.clear();\n // Kept entries carry their last base into the next fold.\n this.held = this.held.filter(({ id }) => lines.has(id));\n }\n }\n\n /**\n * A value as the screen shows it: clamped to the parameter's range, as the\n * store clamps every write; an id the model does not declare as is. A fade\n * mixes these, so it leaves a value held past the max from the max at once\n * instead of sitting there until the mix gets back inside the range.\n */\n private displayed(id: string, value: number): number {\n const param = this.params.get(id);\n return param ? clamp(value, param.min, param.max) : value;\n }\n\n /**\n * `line`, or, where its value at `base` is past the parameter's range, the\n * constant line at the limit it crossed: the line as the screen shows it\n * there. An id the model does not declare pins nothing, and nor does a NaN\n * base (no apply yet), which compares false both ways.\n */\n private pinned(id: string, line: Line, base: number): Line {\n const param = this.params.get(id);\n if (!param) return line;\n const value = at(line, base);\n if (value > param.max) return { scale: 0, offset: param.max };\n if (value < param.min) return { scale: 0, offset: param.min };\n return line;\n }\n}\n","import {\n type IkiDeformer,\n type IkiMesh,\n type IkiModel,\n type IkiParameter,\n type IkiPart,\n type IkiWarpDeformer,\n StandardParameter as P,\n} from \"@ikijs/format\";\nimport type { Affine } from \"./affine\";\nimport { resolveDeformers } from \"./deform\";\nimport { type LandedPart, landPart, landedPart, staticDeformers } from \"./land\";\nimport { ParameterStore } from \"./parameter-store\";\nimport { deformWarpGrid } from \"./warp-grid\";\n\n/** A parameter setting to check the rig at; every other parameter rests at its default. */\nexport interface FoldPose {\n /** Its sorted `id=value` pairs joined by one space; `rest` when empty. */\n name: string;\n values: Record<string, number>;\n}\n\n/** Where and when a target comes nearest to folding over one class of poses. */\nexport interface FoldHit {\n /** Doubled signed area at the pose over the same at rest. */\n ratio: number;\n /** The warp grid's cell, or the part mesh's triangle (its index into `mesh.indices` / 3). */\n where: { col: number; row: number } | { triangle: number };\n pose: FoldPose;\n /** Where it sits at rest, model space, through the static matrix chain. */\n rest: { x: number; y: number };\n}\n\nexport interface FoldTarget {\n target: { kind: \"deformer\" | \"part\"; id: string };\n /** Read off `worst` alone; `ok` when it is absent. */\n kind: \"flip\" | \"collapse\" | \"ok\";\n /** Least ratio over the poses `expected` rejects (every pose without it). */\n worst?: FoldHit;\n /** Least ratio over the poses `expected` accepts. */\n expected?: FoldHit;\n}\n\nexport interface FoldOptions {\n /** The poses to check; `foldPoses(model)` when absent. */\n poses?: FoldPose[];\n /**\n * Whether `target` closes by design at `pose` (a mouth shut), which keeps a\n * fold there out of `worst`. `value(id)` is the parameter's effective value\n * at the pose: its override, else the clamped default — a pose carries only\n * overrides, so a closure at a default shows only through `value`.\n */\n expected?: (\n target: FoldTarget[\"target\"],\n pose: FoldPose,\n value: (id: string) => number,\n ) => boolean;\n}\n\nexport interface FoldReport {\n /** How many poses were checked. */\n poses: number;\n thresholds: { flip: 0; collapse: 0.1 };\n /** One per warp deformer, then one per mesh part, each in model order. */\n targets: FoldTarget[];\n /** The targets that are not `ok`, worst first. */\n offenders: FoldTarget[];\n}\n\nconst FLIP = 0;\nconst COLLAPSE = 0.1;\n\nconst ANGLES = [\n P.AngleX,\n P.AngleY,\n P.AngleZ,\n P.BodyAngleX,\n P.BodyAngleY,\n P.BodyAngleZ,\n];\n\n/** Crossed with every angle corner, each group's parameters at min then at max together. */\nconst CROSSES = [\n [P.EyeOpenLeft],\n [P.EyeOpenRight],\n [P.MouthOpen],\n [P.ArmLeft, P.ArmRight],\n [P.ElbowLeft, P.ElbowRight],\n];\n\n/**\n * The poses `checkFolds` checks by default: `rest`; every movable parameter\n * alone at its min and at its max; and, on a model declaring any head or body\n * angle, every min/max corner of those angles alone, then crossed with each\n * eye on its own, the mouth, the arms and the elbows (the last two paired)\n * shut/open — 2⁶ + 2⁶ · 2⁵ = 2112 corner poses at most — where moves no single extreme\n * shows stack up. Deduplicated by `name`.\n */\nexport function foldPoses(model: IkiModel): FoldPose[] {\n const byId = new Map(\n model.parameters.filter((p) => p.min !== p.max).map((p) => [p.id, p]),\n );\n const declared = (ids: string[]) => ids.flatMap((id) => byId.get(id) ?? []);\n\n const poses: FoldPose[] = [];\n const names = new Set<string>();\n const add = (values: Record<string, number>) => {\n const name = poseName(values);\n if (names.has(name)) return;\n names.add(name);\n poses.push({ name, values });\n };\n\n add({});\n for (const p of byId.values()) {\n add({ [p.id]: p.min });\n add({ [p.id]: p.max });\n }\n\n const angles = declared(ANGLES);\n if (angles.length === 0) return poses;\n const expand = (\n corners: Record<string, number>[],\n groups: IkiParameter[][],\n ) => {\n for (const group of groups) {\n corners = corners.flatMap((values) =>\n ([\"min\", \"max\"] as const).map((end) => {\n const next = { ...values };\n for (const p of group) next[p.id] = p[end];\n return next;\n }),\n );\n }\n return corners;\n };\n // The angle corners alone come first: the other parameters rest at their\n // defaults there, which no min/max cross reaches.\n const angleCorners = expand(\n [{}],\n angles.map((p) => [p]),\n );\n for (const values of angleCorners) add(values);\n const crosses = CROSSES.map(declared).filter((g) => g.length > 0);\n for (const values of expand(angleCorners, crosses)) add(values);\n return poses;\n}\n\nfunction poseName(values: Record<string, number>): string {\n const ids = Object.keys(values).sort();\n if (ids.length === 0) return \"rest\";\n return ids.map((id) => `${id}=${values[id]}`).join(\" \");\n}\n\n/**\n * Doubled signed area of each cell's four corner triangles — the corner, then\n * its two neighbours counter-clockwise (y up), as the auto-rig's body fold\n * refusal takes them — at index `cell * 4 + k`. Positive on a rest lattice.\n */\nfunction cornerAreas(\n points: ArrayLike<number>,\n cols: number,\n rows: number,\n): Float64Array {\n const stride = cols + 1;\n const out = new Float64Array(cols * rows * 4);\n for (let r = 0; r < rows; r++) {\n for (let c = 0; c < cols; c++) {\n const tl = r * stride + c;\n const [tr, bl, br] = [tl + 1, tl + stride, tl + stride + 1];\n const i = (r * cols + c) * 4;\n out[i] = doubledArea(points, bl, br, tl);\n out[i + 1] = doubledArea(points, br, tr, bl);\n out[i + 2] = doubledArea(points, tr, tl, br);\n out[i + 3] = doubledArea(points, tl, bl, tr);\n }\n }\n return out;\n}\n\nfunction doubledArea(\n points: ArrayLike<number>,\n p: number,\n q: number,\n s: number,\n): number {\n const ax = points[q * 2] - points[p * 2];\n const ay = points[q * 2 + 1] - points[p * 2 + 1];\n const bx = points[s * 2] - points[p * 2];\n const by = points[s * 2 + 1] - points[p * 2 + 1];\n return ax * by - ay * bx;\n}\n\n/** Doubled signed area of each of a mesh's triangles, at its triangle index. */\nfunction triangleAreas(\n points: ArrayLike<number>,\n indices: number[],\n): Float64Array {\n const out = new Float64Array(indices.length / 3);\n for (let t = 0; t < out.length; t++) {\n const i = t * 3;\n out[t] = doubledArea(points, indices[i], indices[i + 1], indices[i + 2]);\n }\n return out;\n}\n\n/** A target's least ratio so far over one class of poses. */\ninterface Least {\n ratio: number;\n /** Its index into the target's areas: `cell * 4 + corner`, or the triangle. */\n at: number;\n pose: FoldPose;\n}\n\n/** What a target keeps across the poses. */\ninterface Sweep {\n target: FoldTarget[\"target\"];\n restAreas: Float64Array;\n /** Rest areas below this have no ratio. */\n tiny: number;\n worst?: Least;\n expected?: Least;\n}\n\ninterface GridSweep extends Sweep {\n deformer: IkiWarpDeformer;\n}\n\ninterface PartSweep extends Sweep, LandedPart {\n indices: number[];\n}\n\n/**\n * Merges one pose's `areas` into `sweep`: each ratio to its rest area goes to\n * the class `expected` puts the pose in, which keeps its least.\n */\nfunction keepLeast(\n sweep: Sweep,\n areas: Float64Array,\n pose: FoldPose,\n expected: (target: FoldTarget[\"target\"]) => boolean,\n): void {\n const slot = expected(sweep.target) ? \"expected\" : \"worst\";\n for (let i = 0; i < areas.length; i++) {\n const rest = sweep.restAreas[i];\n if (Math.abs(rest) < sweep.tiny) continue;\n const ratio = areas[i] / rest;\n if (ratio < (sweep[slot]?.ratio ?? Infinity)) {\n sweep[slot] = { ratio, at: i, pose };\n }\n }\n}\n\n/** A mesh part's sweep: its landing, with the triangles' rest areas measured on its baseline. */\nfunction partSweep(\n part: IkiPart,\n mesh: IkiMesh,\n deformers: IkiDeformer[],\n worlds: Map<string, Affine>,\n store: ParameterStore,\n): PartSweep {\n const landing = landedPart(part, mesh.vertices, deformers, worlds, store);\n return {\n ...landing,\n target: { kind: \"part\", id: part.id },\n restAreas: triangleAreas(landing.restPoints, mesh.indices),\n tiny: 1e-9 * part.width * part.height,\n indices: mesh.indices,\n };\n}\n\n/**\n * Checks every warp deformer's grid cells and every mesh part's triangles for\n * folds over `options.poses` (`foldPoses(model)` by default) and reports, per\n * target, the least ratio of a triangle's doubled signed area at a pose to\n * the same at rest: `<= 0` a flip, `< 0.1` a collapse. Cells are measured on\n * the deformer's LOCAL grid, so a parent matrix's scale, which multiplies\n * every area alike, never reads as a fold. A part's triangles land as\n * drawPart lands them — its keyforms, its live transform, then its warp's\n * resolved grid or its matrix deformer's world — against its authored mesh on\n * the static matrix chain: a static scale or reflection cancels, a bound one\n * counts, and a vertex its warp grid pins to the edge shows already at\n * `rest` (a triangle wholly past the edge flattens, one across it thins).\n * Report-only: nothing is refused.\n */\nexport function checkFolds(\n model: IkiModel,\n options: FoldOptions = {},\n): FoldReport {\n const poses = options.poses ?? foldPoses(model);\n const deformers = model.deformers ?? [];\n const restStore = new ParameterStore(model.parameters);\n const { worlds } = resolveDeformers(staticDeformers(model), restStore);\n\n const gridSweeps: GridSweep[] = [];\n for (const d of deformers) {\n if (d.kind !== \"warp\") continue;\n const { cols, rows, points } = d.grid;\n // Row 0's x and column 0's y bound the lattice (the validator's own read).\n const width = points[cols * 2] - points[0];\n const height = points[1] - points[rows * (cols + 1) * 2 + 1];\n gridSweeps.push({\n deformer: d,\n target: { kind: \"deformer\", id: d.id },\n restAreas: cornerAreas(points, cols, rows),\n // The validator tolerates 1e-6 of jitter, which can zero a corner's area.\n tiny: 1e-9 * width * height,\n });\n }\n const partSweeps = model.parts.flatMap((part) =>\n part.mesh ? [partSweep(part, part.mesh, deformers, worlds, restStore)] : [],\n );\n\n for (const pose of poses) {\n const store = new ParameterStore(model.parameters);\n for (const [id, v] of Object.entries(pose.values)) store.set(id, v);\n const value = (id: string) => store.get(id);\n const expected = (target: FoldTarget[\"target\"]) =>\n options.expected?.(target, pose, value) === true;\n for (const sweep of gridSweeps) {\n const { cols, rows } = sweep.deformer.grid;\n const areas = cornerAreas(\n deformWarpGrid(sweep.deformer, store),\n cols,\n rows,\n );\n keepLeast(sweep, areas, pose, expected);\n }\n const resolved = resolveDeformers(deformers, store);\n for (const sweep of partSweeps) {\n const areas = triangleAreas(\n landPart(sweep, store, resolved),\n sweep.indices,\n );\n keepLeast(sweep, areas, pose, expected);\n }\n }\n\n const targets = [\n ...gridSweeps.map((sweep) => {\n const { parent } = sweep.deformer;\n const world = parent === undefined ? undefined : worlds.get(parent);\n return foldTarget(sweep, (least) =>\n cellHit(sweep.deformer, least, world),\n );\n }),\n ...partSweeps.map((sweep) =>\n foldTarget(sweep, (least) => triangleHit(sweep, least)),\n ),\n ];\n const offenders = targets\n .filter((t) => t.kind !== \"ok\")\n .sort((a, b) => a.worst!.ratio - b.worst!.ratio);\n return {\n poses: poses.length,\n thresholds: { flip: FLIP, collapse: COLLAPSE },\n targets,\n offenders,\n };\n}\n\n/** A sweep's two minima, each located by `hit`, and the kind they make. */\nfunction foldTarget(sweep: Sweep, hit: (least: Least) => FoldHit): FoldTarget {\n const worst = sweep.worst && hit(sweep.worst);\n const expected = sweep.expected && hit(sweep.expected);\n return { target: sweep.target, kind: classify(worst), worst, expected };\n}\n\n/** `least` located: its cell and that cell's rest centre through `parent`. */\nfunction cellHit(\n d: IkiWarpDeformer,\n least: Least,\n parent: Affine | undefined,\n): FoldHit {\n const { cols, points } = d.grid;\n const cell = Math.floor(least.at / 4);\n const col = cell % cols;\n const row = Math.floor(cell / cols);\n const stride = cols + 1;\n let x = 0;\n let y = 0;\n for (const i of [\n row * stride + col,\n row * stride + col + 1,\n (row + 1) * stride + col,\n (row + 1) * stride + col + 1,\n ]) {\n x += points[i * 2] / 4;\n y += points[i * 2 + 1] / 4;\n }\n const rest = parent\n ? {\n x: parent[0] * x + parent[2] * y + parent[4],\n y: parent[1] * x + parent[3] * y + parent[5],\n }\n : { x, y };\n return { ratio: least.ratio, where: { col, row }, pose: least.pose, rest };\n}\n\n/** `least` located: its triangle and that triangle's centroid on the static chain. */\nfunction triangleHit(sweep: PartSweep, least: Least): FoldHit {\n const { indices, restPoints } = sweep;\n let x = 0;\n let y = 0;\n for (let k = 0; k < 3; k++) {\n const i = indices[least.at * 3 + k];\n x += restPoints[i * 2] / 3;\n y += restPoints[i * 2 + 1] / 3;\n }\n return {\n ratio: least.ratio,\n where: { triangle: least.at },\n pose: least.pose,\n rest: { x, y },\n };\n}\n\nfunction classify(worst: FoldHit | undefined): FoldTarget[\"kind\"] {\n if (worst === undefined) return \"ok\";\n if (worst.ratio <= FLIP) return \"flip\";\n if (worst.ratio < COLLAPSE) return \"collapse\";\n return \"ok\";\n}\n","import type {\n IkiDeformer,\n IkiModel,\n IkiPart,\n IkiWarpDeformer,\n} from \"@ikijs/format\";\nimport { type Affine, multiply, rotate, scale, translate } from \"./affine\";\nimport {\n type ResolvedDeformers,\n type ResolvedTransform,\n evaluateTransform,\n} from \"./deform\";\nimport type { ParameterStore } from \"./parameter-store\";\nimport { applyWarps } from \"./warp\";\nimport { applyWarpToChild, transformGridPoints } from \"./warp-grid\";\n\n/**\n * The model's deformers with every binding and keyform removed: the rig no\n * parameter moves. Its matrix worlds place a rest location, and a part's\n * baseline, in model space.\n */\nexport function staticDeformers(model: IkiModel): IkiDeformer[] {\n return (model.deformers ?? []).map((d) =>\n d.kind === \"warp\"\n ? { ...d, warps: undefined, warp2d: undefined }\n : { ...d, bindings: undefined },\n );\n}\n\n/** A part's placement as `player.ts` drawPart builds it: translate · rotate · scale(size). */\nexport function placement(part: IkiPart, t: ResolvedTransform): Affine {\n return multiply(\n multiply(translate(t.x, t.y), rotate(t.rotation)),\n scale(part.width * t.scaleX, part.height * t.scaleY),\n );\n}\n\n/** A part's points set up to land at any pose, and their baseline. */\nexport interface LandedPart {\n part: IkiPart;\n /** The warp deformer it hangs from, which lands it instead of a matrix. */\n warpDeformer?: IkiWarpDeformer;\n /** The points as the renderer holds them: part-local, float32. */\n vertices: Float32Array;\n /** Per-pose scratch: the points after the part's keyforms, then where they land. */\n local: Float32Array;\n landed: Float32Array;\n /**\n * The baseline's points: `vertices` on the STATIC chain, model space — for\n * folds, the authored mesh. Not the rendered rest pose, which is `landPart`\n * at a resting store.\n */\n restPoints: Float64Array;\n}\n\n/**\n * A part's landing, its baseline set once: `vertices` (its mesh's, or any\n * part-local points) through the part's base transform and the static world\n * it hangs from — its matrix deformer's, or its warp's PARENT's (identity at\n * a root). The grid never enters it, so a vertex the grid pins to its edge is\n * measured, not cancelled.\n */\nexport function landedPart(\n part: IkiPart,\n vertices: number[],\n deformers: IkiDeformer[],\n worlds: Map<string, Affine>,\n store: ParameterStore,\n): LandedPart {\n // Found as drawPart finds it: a part hung from a warp is that warp's child.\n const warpDeformer = deformers.find(\n (d): d is IkiWarpDeformer => d.kind === \"warp\" && d.id === part.deformer,\n );\n const frame = warpDeformer ? warpDeformer.parent : part.deformer;\n const placed = placement(\n part,\n evaluateTransform(part.transform, undefined, store),\n );\n // Float64: a triangle authored degenerate stays exactly so, under folds'\n // `tiny`.\n const restPoints = transformGridPoints(\n vertices,\n frame === undefined ? placed : multiply(worlds.get(frame)!, placed),\n new Float64Array(vertices.length),\n );\n return {\n part,\n warpDeformer,\n vertices: Float32Array.from(vertices),\n local: new Float32Array(vertices.length),\n landed: new Float32Array(vertices.length),\n restPoints,\n };\n}\n\n/**\n * Where `landing`'s part lands at a pose, model space, by drawPart's three\n * branches: a warp child bound to its RAW rest grid and sampled on the\n * resolved one, a matrix child through its deformer's world, a free part by\n * its placement alone. `resolved` is the live rig at `store`'s pose, not the\n * static chain's worlds.\n */\nexport function landPart(\n landing: LandedPart,\n store: ParameterStore,\n { worlds, grids }: ResolvedDeformers,\n): Float32Array {\n const { part, warpDeformer, local, landed } = landing;\n applyWarps(landing.vertices, part.warps, store, local);\n const placed = placement(\n part,\n evaluateTransform(part.transform, part.bindings, store),\n );\n if (warpDeformer) {\n const grid = grids.get(warpDeformer.id)!;\n applyWarpToChild(local, placed, warpDeformer.grid, grid, landed);\n } else if (part.deformer !== undefined) {\n const world = worlds.get(part.deformer)!;\n transformGridPoints(local, multiply(world, placed), landed);\n } else {\n transformGridPoints(local, placed, landed);\n }\n return landed;\n}\n","import {\n type IkiDeformer,\n type IkiModel,\n type IkiParameter,\n type IkiPart,\n type IkiPhysics,\n physicsInputs,\n} from \"@ikijs/format\";\nimport { resolveDeformers } from \"./deform\";\nimport { FIXED_DT_S } from \"./frame-clock\";\nimport { landPart, landedPart, staticDeformers } from \"./land\";\nimport { ParameterStore } from \"./parameter-store\";\nimport {\n type Reading,\n anchorInputs,\n farEnd,\n idleRun,\n stepRun,\n} from \"./physics-runs\";\n\n/** How a driven output moves over one excitation window. */\nexport interface PhysicsResponse {\n /**\n * Its largest displacement from its resting value, as the store holds it\n * (clamped): signed in `step`, which has a direction; its size in `idle`,\n * whose sway goes both ways, so a sign there would carry nothing.\n */\n peak: number;\n /**\n * When it peaks, seconds into the window. Between two near-equal extremes\n * of the idle it may name either.\n */\n at: number;\n /**\n * The largest vertex move of any part, model px, with the output alone\n * (every other parameter resting) at the values the window reached.\n */\n displacementPx: number;\n}\n\n/** One output a physics rig drives: a spring's, or one chain segment's. */\nexport interface PhysicsTarget {\n rig:\n | { kind: \"spring\"; id: string }\n | { kind: \"chain\"; id: string; segment: number };\n /**\n * The spring's inputs, in rig order; for a chain, every parameter that turns\n * its anchor.\n */\n input: string[];\n /** The driven parameter. */\n output: string;\n /** What reads `output`: parts, then deformers, each in model order. */\n drives: { kind: \"part\" | \"deformer\"; id: string }[];\n kind: \"ok\" | \"frozen\" | \"unstable\";\n /** One phrase saying why, naming the window it came from; present when not `ok`. */\n why?: string;\n /**\n * An input stepped from rest to `values` and held: its displacement over\n * every value the run emitted, `final` the output at the window's end.\n */\n step: PhysicsResponse & { values: Record<string, number>; final: number };\n /** Every rig and chain together behind the procedural idle, displaced at every value it emitted. */\n idle: PhysicsResponse;\n}\n\nexport interface PhysicsReport {\n thresholds: { displacementPx: 1; pinnedFrames: 60 };\n /** One per `model.physics` rig, then one per chain segment, each in model order. */\n targets: PhysicsTarget[];\n /** The targets that are not `ok`, unstable first. */\n offenders: PhysicsTarget[];\n}\n\n/** Under 1 model px is sub-pixel in every render the loop looks at (0.51 render px each). */\nconst DISPLACEMENT_PX = 1;\n/** One second outside the range: longer than any transient overshoot clip. */\nconst PINNED_FRAMES = 60;\n/** Slack on the spring's stability limits. */\nconst TOLERANCE = 1e-9;\n/** The corners `createUnitQuad` uploads, which a part without a mesh draws. */\nconst UNIT_QUAD = [-0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5];\n\n/** A run's reading of one output, the window `why` names it by, and how far it moves the parts. */\ninterface Excitation {\n name: string;\n reading: Reading;\n displacementPx: number;\n}\n\n/** A step excitation and the setting it held. */\ninterface StepExcitation extends Excitation {\n values: Record<string, number>;\n}\n\n/**\n * Excites every physics rig through the real drivers (`PhysicsMotion`,\n * `HairChainMotion`, `IdleMotion`) on a synthetic 60 Hz clock, one FIXED_DT_S\n * sub-step per frame, and reports per driven output whether it moves the\n * parts (`ok`), cannot (`frozen`) or runs away (`unstable`).\n *\n * Step: a fresh store and a driver holding only that rig, seeded at rest,\n * then an input set to its far end — the end farther from its clamped\n * default, `max` on a tie — and held for 5 s. A spring steps each input that\n * has a range alone, in its own run. A chain steps each parameter that alone\n * turns its anchor (probed at its max, min and every warp keyform stop) in\n * its own run, at the probe value that turned it most. Either reports the run\n * moving the parts most among the runs that are not unstable. A lag input's\n * step peaks at once at the bound `−scale·weight` (less one sub-step) and its\n * `final` reads rest: the bound is what a one-frame step shows, a gradual\n * turn swings less. Idle: every rig and chain together behind `IdleMotion`\n * (seeded) for 30 s.\n *\n * `displacementPx` is the largest vertex move of any part with the output\n * alone at every distinct value the run emitted, step or idle, against the\n * parts landed at rest. `frozen` when nothing reads the output, no input of a\n * spring has a range, nothing turns a chain's anchor, or the step moves the\n * parts under 1 model px. `unstable`, before frozen, when a\n * spring's one-sub-step map has a spectral radius over 1 or sits on its\n * undamped boundary (springs only: a chain's update is nonlinear), when a\n * driver's finiteness guard fires, or when the raw output stays outside its\n * range for 60 consecutive frames, in any run. Deferred by the user: a chain\n * that grows yet stays finite and inside its range trips none of these and\n * is not flagged. Idle amplitude never flags. Report-only: nothing is refused.\n */\nexport function checkPhysics(model: IkiModel): PhysicsReport {\n const idle = idleRun(model);\n const displace = displacer(model);\n const idleExcitation = (output: IkiParameter): Excitation => {\n const reading = idle.get(output.id)!;\n return {\n name: \"the idle\",\n reading,\n displacementPx: displace(output, reading.values),\n };\n };\n const param = (id: string) => model.parameters.find((p) => p.id === id)!;\n\n const springs = (model.physics ?? []).map((rig) => {\n const inputs = physicsInputs(rig).map((i) => param(i.parameter));\n const ids = inputs.map((p) => p.id);\n const output = param(rig.output.parameter);\n const ranged = inputs.flatMap((input) => {\n const far = farEnd(input);\n return far === undefined ? [] : [{ [input.id]: far }];\n });\n // One unexcited run when nothing has a range, so mostMoving has a run.\n const settings = ranged.length === 0 ? [{}] : ranged;\n const steps = settings.map((values): StepExcitation => {\n const reading = stepRun(model, [rig], [], values).get(output.id)!;\n // A one-input rig has one run, so naming its setting would add nothing.\n const setting =\n inputs.length === 1\n ? []\n : Object.entries(values).map(([id, v]) => `${id}=${v}`);\n return {\n name: [\"the step\", ...setting].join(\" \"),\n reading,\n displacementPx: displace(output, reading.values),\n values,\n };\n });\n const atIdle = idleExcitation(output);\n const clean = steps.filter((s) => !unstableWhy(output, [s]));\n return target(model, {\n rig: { kind: \"spring\", id: rig.id },\n input: ids,\n output,\n step: mostMoving(clean.length > 0 ? clean : steps),\n idle: atIdle,\n unstable: springWhy(rig) ?? unstableWhy(output, [...steps, atIdle]),\n inert:\n ranged.length === 0\n ? `${ids.join(\", \")} ${ids.length === 1 ? \"has\" : \"have\"} no range`\n : undefined,\n });\n });\n\n const chains = (model.physicsChains ?? []).flatMap((chain) => {\n const candidates = anchorInputs(model, chain);\n const settings =\n candidates.length === 0\n ? [{}]\n : candidates.map((c) => ({ [c.parameter]: c.value }));\n const runs = settings.map((values) => ({\n values,\n readings: stepRun(model, [], [chain], values),\n }));\n return chain.segments.map((segment, i) => {\n const output = param(segment.output.parameter);\n const steps = runs.map(({ values, readings }): StepExcitation => {\n const reading = readings.get(output.id)!;\n const setting = Object.entries(values).map(([id, v]) => `${id}=${v}`);\n return {\n name: [\"the step\", ...setting].join(\" \"),\n reading,\n displacementPx: displace(output, reading.values),\n values,\n };\n });\n const atIdle = idleExcitation(output);\n const clean = steps.filter((s) => !unstableWhy(output, [s]));\n return target(model, {\n rig: { kind: \"chain\", id: chain.id, segment: i },\n input: candidates.map((c) => c.parameter),\n output,\n step: mostMoving(clean.length > 0 ? clean : steps),\n idle: atIdle,\n unstable: unstableWhy(output, [...steps, atIdle]),\n inert:\n candidates.length === 0\n ? `nothing turns anchor ${chain.anchorDeformer}`\n : undefined,\n });\n });\n });\n\n const targets = [...springs, ...chains];\n return {\n thresholds: {\n displacementPx: DISPLACEMENT_PX,\n pinnedFrames: PINNED_FRAMES,\n },\n targets,\n offenders: [\n ...targets.filter((t) => t.kind === \"unstable\"),\n ...targets.filter((t) => t.kind === \"frozen\"),\n ],\n };\n}\n\n/**\n * A target from its excitations: `unstable` with its reason, else `frozen`\n * when nothing reads the output, by the input-side reason `inert`, or under\n * 1 px.\n */\nfunction target(\n model: IkiModel,\n t: {\n rig: PhysicsTarget[\"rig\"];\n input: string[];\n output: IkiParameter;\n step: StepExcitation;\n idle: Excitation;\n unstable: string | undefined;\n inert: string | undefined;\n },\n): PhysicsTarget {\n const { step, idle, output } = t;\n const drives = drivesOf(model, output.id);\n // Floored, so a frozen 0.96 px never reads as 1.0.\n const px = Math.floor(step.displacementPx * 10) / 10;\n const still =\n step.displacementPx < DISPLACEMENT_PX\n ? `moves ${px.toFixed(1)} model px over ${step.name}`\n : undefined;\n const frozen = drives.length === 0 ? \"drives nothing\" : (t.inert ?? still);\n const { peak, at, final } = step.reading;\n return {\n rig: t.rig,\n input: t.input,\n output: output.id,\n drives,\n kind: t.unstable ? \"unstable\" : frozen ? \"frozen\" : \"ok\",\n why: t.unstable ?? frozen,\n step: {\n values: step.values,\n peak,\n at,\n final,\n displacementPx: step.displacementPx,\n },\n idle: {\n peak: Math.abs(idle.reading.peak),\n at: idle.reading.at,\n displacementPx: idle.displacementPx,\n },\n };\n}\n\n/** The excitation moving the parts most, ties by `|peak|`, the first on a full tie. */\nfunction mostMoving(steps: StepExcitation[]): StepExcitation {\n return steps.reduce((best, s) => {\n if (s.displacementPx !== best.displacementPx) {\n return s.displacementPx > best.displacementPx ? s : best;\n }\n return Math.abs(s.reading.peak) > Math.abs(best.reading.peak) ? s : best;\n });\n}\n\n/** The parts, then the deformers, that read `output`, each in model order. */\nfunction drivesOf(model: IkiModel, output: string): PhysicsTarget[\"drives\"] {\n const parts = model.parts.filter((p) =>\n [\n ...(p.bindings ?? []).map((b) => b.parameter),\n ...(p.warps ?? []).map((w) => w.parameter),\n ].includes(output),\n );\n const deformers = (model.deformers ?? []).filter((d) =>\n (d.kind === \"warp\"\n ? [\n ...(d.warps ?? []).map((w) => w.parameter),\n d.warp2d?.parameter,\n d.warp2d?.parameterY,\n ]\n : (d.bindings ?? []).map((b) => b.parameter)\n ).includes(output),\n );\n return [\n ...parts.map((p) => ({ kind: \"part\" as const, id: p.id })),\n ...deformers.map((d) => ({ kind: \"deformer\" as const, id: d.id })),\n ];\n}\n\n/**\n * The spectral radius of the map `PhysicsMotion.step` applies to the state\n * (x, v) each FIXED_DT_S sub-step — linear, constant coefficients:\n * `[[1 − h²k/m, h(1 − hc/m)], [−hk/m, 1 − hc/m]]` — by the closed form: a real\n * pair from trace and determinant, a complex pair's modulus `√det`. With it,\n * `k` = h²k/m, the term the undamped boundary reads.\n */\nfunction springStepRadius({ mass, stiffness, damping }: IkiPhysics): {\n radius: number;\n k: number;\n} {\n const k = (FIXED_DT_S * FIXED_DT_S * stiffness) / mass;\n const c = (FIXED_DT_S * damping) / mass;\n const trace = 2 - k - c;\n const det = 1 - c;\n const disc = trace * trace - 4 * det;\n const radius =\n disc >= 0 ? (Math.abs(trace) + Math.sqrt(disc)) / 2 : Math.sqrt(det);\n return { radius, k };\n}\n\n/**\n * Why a spring's constants make it unstable, if they do: a radius over 1, or\n * the undamped boundary `dt²k/m = 4`, where the radius is exactly 1 but the\n * matrix is defective (double eigenvalue −1) and the state grows linearly.\n */\nfunction springWhy(rig: IkiPhysics): string | undefined {\n const { radius, k } = springStepRadius(rig);\n if (radius > 1 + TOLERANCE) {\n // As many decimals as it takes to print the radius over 1.\n let digits = 2;\n while (Number(radius.toFixed(digits)) <= 1) digits++;\n return `spring step map radius ${radius.toFixed(digits)} over 1 at 1/60 s`;\n }\n if (rig.damping === 0 && k >= 4 - TOLERANCE) {\n return `spring on its undamped boundary, dt²k/m ${k.toFixed(2)}`;\n }\n return undefined;\n}\n\n/** Why `output` is unstable over `excitations`, if it is: a guard activation in any, else a pin. */\nfunction unstableWhy(\n output: IkiParameter,\n excitations: Excitation[],\n): string | undefined {\n for (const { name, reading } of excitations) {\n const n = reading.resets;\n if (n === 0) continue;\n return `finiteness guard reset it ${n} time${n === 1 ? \"\" : \"s\"} in ${name}`;\n }\n for (const { name, reading } of excitations) {\n const { frames, end } = reading.pinned;\n if (frames < PINNED_FRAMES) continue;\n return `pinned at ${output.id} ${end} ${output[end]} for ${frames} frames of ${name}`;\n }\n return undefined;\n}\n\n/**\n * The largest vertex move, model px, of any part with an output alone at\n * each of a list of values (every other parameter resting), against every\n * part landed at the resting store through the live deformers resolved at\n * rest — so a binding or keyform away from zero at rest is not motion. Every\n * part lands, so a deformer- or chain-driven part counts by the same path.\n */\nfunction displacer(\n model: IkiModel,\n): (output: IkiParameter, values: number[]) => number {\n const deformers = model.deformers ?? [];\n const store = new ParameterStore(model.parameters);\n // Only `landedPart`'s `restPoints` (folds' baseline) reads the static\n // worlds; this check lands its own baseline below.\n const { worlds } = resolveDeformers(staticDeformers(model), store);\n const landings = model.parts.map((part) =>\n landedPart(\n part,\n part.mesh?.vertices ?? UNIT_QUAD,\n deformers,\n worlds,\n store,\n ),\n );\n const atRest = resolveDeformers(deformers, store);\n // Copied out: landPart returns the landing's shared scratch.\n const baselines = landings.map((l) =>\n Float32Array.from(landPart(l, store, atRest)),\n );\n return (output, values) => {\n let most = 0;\n const affected = affectedParts(model, output.id);\n for (const value of values) {\n store.set(output.id, value);\n const resolved = resolveDeformers(deformers, store);\n landings.forEach((landing, i) => {\n if (!affected.has(landing.part)) return;\n const landed = landPart(landing, store, resolved);\n const base = baselines[i];\n for (let j = 0; j < landed.length; j += 2) {\n const dx = landed[j] - base[j];\n const dy = landed[j + 1] - base[j + 1];\n most = Math.max(most, dx * dx + dy * dy);\n }\n });\n }\n store.reset();\n return Math.sqrt(most);\n };\n}\n\n/**\n * The parts whose geometry can depend on `output`: those that read it\n * themselves, or hang from a deformer that reads it or has an ancestor that\n * does. The rest land exactly at rest, so landing them adds nothing.\n */\nfunction affectedParts(model: IkiModel, output: string): Set<IkiPart> {\n const deformers = new Map((model.deformers ?? []).map((d) => [d.id, d]));\n const reads = (d: IkiDeformer) =>\n (d.kind === \"warp\"\n ? [\n ...(d.warps ?? []).map((w) => w.parameter),\n d.warp2d?.parameter,\n d.warp2d?.parameterY,\n ]\n : (d.bindings ?? []).map((b) => b.parameter)\n ).includes(output);\n const hung = (id: string | undefined): boolean => {\n for (\n let d = id && deformers.get(id);\n d;\n d = d.parent && deformers.get(d.parent)\n ) {\n if (reads(d)) return true;\n }\n return false;\n };\n return new Set(\n model.parts.filter(\n (p) =>\n [\n ...(p.bindings ?? []).map((b) => b.parameter),\n ...(p.warps ?? []).map((w) => w.parameter),\n ].includes(output) || hung(p.deformer),\n ),\n );\n}\n","import type {\n IkiModel,\n IkiParameter,\n IkiPhysics,\n IkiPhysicsChain,\n} from \"@ikijs/format\";\nimport { resolveDeformers } from \"./deform\";\nimport { FIXED_DT_S } from \"./frame-clock\";\nimport { HairChainMotion } from \"./hair-chain-motion\";\nimport { IdleMotion } from \"./idle-motion\";\nimport { clamp } from \"./math\";\nimport { ParameterStore } from \"./parameter-store\";\nimport { PhysicsMotion } from \"./physics-motion\";\n\n// The excitation runs behind `checkPhysics`: the real drivers on a synthetic\n// 60 Hz clock, never a re-implemented integrator.\n\n/**\n * A hair over one sub-step: at exactly 1000/60 ms, float rounding leaves the\n * drivers' accumulator just short or just over, so about one frame in three\n * runs no sub-step (re-emitting the last value) and about as many run two\n * (emitting only the second) — and a skipped sub-step can be the peak.\n */\nconst FRAME_MS = FIXED_DT_S * 1000 * (1 + 1e-9);\n/** Frames after the seed frame: 5 s of step (the defaults settle in ~2 s), 30 s of idle. */\nconst STEP_FRAMES = 300;\nconst IDLE_FRAMES = 1800;\n/** Any constant keeps two checks equal; it only matters for a gaze- or eye-driven rig. */\nconst IDLE_SEED = 1;\n/** An anchor turn, or a lead over another, under this many radians is float noise (a uniform scale over a rotated anchor). */\nconst MIN_TURN = 1e-9;\n\n/** What a driver handed its sink for one output, read against the output's range and resting value. */\nexport interface Reading {\n /** The largest signed displacement of the clamped value from rest, and when, seconds in. */\n peak: number;\n at: number;\n /** The clamped value at the window's end. */\n final: number;\n /** Every distinct clamped value emitted except the resting one. */\n values: number[];\n /** The least and greatest clamped values emitted. */\n lo: number;\n hi: number;\n /** The longest run of frames with the raw value outside the range, and the bound it began past. */\n pinned: { frames: number; end: \"min\" | \"max\" };\n /** The driver's finiteness-guard activations for the output. */\n resets: number;\n}\n\n/**\n * Runs a `PhysicsMotion` over `rigs` and a `HairChainMotion` over `chains`,\n * both reading and writing `store`, for the seed frame and `frames` more —\n * one FIXED_DT_S sub-step each — calling `excite` ahead of them every frame;\n * reads what they hand the sink, per output.\n */\nfunction run(\n model: IkiModel,\n store: ParameterStore,\n rigs: IkiPhysics[],\n chains: IkiPhysicsChain[],\n frames: number,\n excite: (frame: number, nowMs: number) => void,\n): Map<string, Reading> {\n const raw = new Map<string, number[]>();\n const read = (id: string) => store.get(id);\n const sink = (id: string, value: number) => {\n let trace = raw.get(id);\n if (trace === undefined) raw.set(id, (trace = []));\n trace.push(value);\n store.set(id, value);\n };\n const { parameters } = model;\n const drivers = [\n new PhysicsMotion(rigs, parameters, read, sink),\n new HairChainMotion(chains, parameters, model.deformers ?? [], read, sink),\n ];\n for (let frame = 0; frame <= frames; frame++) {\n const nowMs = frame * FRAME_MS;\n excite(frame, nowMs);\n for (const driver of drivers) driver.update(nowMs);\n }\n const readings = new Map<string, Reading>();\n for (const driver of drivers) {\n driver.drivenParameterIds.forEach((id, i) => {\n const param = parameters.find((p) => p.id === id)!;\n readings.set(id, readTrace(raw.get(id)!, param, driver.resets[i]));\n });\n }\n return readings;\n}\n\n/** Reads `raw`, one sink value per frame from the seed frame on, against `param`. */\nfunction readTrace(\n raw: number[],\n param: IkiParameter,\n resets: number,\n): Reading {\n const rest = clamp(param.default, param.min, param.max);\n const reading: Reading = {\n peak: 0,\n at: 0,\n final: rest,\n values: [],\n lo: rest,\n hi: rest,\n pinned: { frames: 0, end: \"max\" },\n resets,\n };\n const seen = new Set([rest]);\n let outside = 0;\n let end: Reading[\"pinned\"][\"end\"] = \"max\";\n raw.forEach((value, frame) => {\n const held = clamp(value, param.min, param.max);\n if (Math.abs(held - rest) > Math.abs(reading.peak)) {\n reading.peak = held - rest;\n reading.at = frame * FIXED_DT_S;\n }\n if (!seen.has(held)) {\n seen.add(held);\n reading.values.push(held);\n }\n reading.lo = Math.min(reading.lo, held);\n reading.hi = Math.max(reading.hi, held);\n reading.final = held;\n if (value >= param.min && value <= param.max) {\n outside = 0;\n return;\n }\n const side = value < param.min ? \"min\" : \"max\";\n // Crossing to the other bound ends the run: a swing between the two is\n // not pinning.\n if (outside === 0 || side !== end) {\n outside = 0;\n end = side;\n }\n outside++;\n if (outside > reading.pinned.frames) {\n reading.pinned = { frames: outside, end };\n }\n });\n return reading;\n}\n\n/**\n * The end farther from the clamped default — the one `signedNormalized`\n * takes as its unit, `max` on a tie — or `undefined` for a zero-width range.\n */\nexport function farEnd(param: IkiParameter): number | undefined {\n if (param.min === param.max) return undefined;\n const rest = clamp(param.default, param.min, param.max);\n return param.max - rest >= rest - param.min ? param.max : param.min;\n}\n\n/**\n * The step run: `rigs` and `chains` from rest, `values` set after the seed\n * frame and held for the window, every other parameter resting.\n */\nexport function stepRun(\n model: IkiModel,\n rigs: IkiPhysics[],\n chains: IkiPhysicsChain[],\n values: Record<string, number>,\n): Map<string, Reading> {\n const store = new ParameterStore(model.parameters);\n return run(model, store, rigs, chains, STEP_FRAMES, (frame) => {\n if (frame !== 1) return;\n for (const [id, v] of Object.entries(values)) store.set(id, v);\n });\n}\n\n/**\n * The idle run: every rig and chain together behind the procedural\n * `IdleMotion` on a seeded rng, stepped idle → physics → chains each frame as\n * `IkiMotion` orders them. A declared `Idle` group is not played.\n */\nexport function idleRun(model: IkiModel): Map<string, Reading> {\n const store = new ParameterStore(model.parameters);\n const idle = new IdleMotion((id, v) => store.set(id, v), {\n rng: lcg(IDLE_SEED),\n });\n return run(\n model,\n store,\n model.physics ?? [],\n model.physicsChains ?? [],\n IDLE_FRAMES,\n (_, nowMs) => idle.update(nowMs),\n );\n}\n\n/** Numerical Recipes' 32-bit LCG, in [0, 1). */\nfunction lcg(seed: number): () => number {\n let state = seed >>> 0;\n return () => {\n state = (Math.imul(state, 1664525) + 1013904223) >>> 0;\n return state / 2 ** 32;\n };\n}\n\n/** A parameter that turns a chain's anchor, at the probe value that turns it most. */\nexport interface Candidate {\n parameter: string;\n value: number;\n}\n\n/**\n * Every parameter that alone changes `chain`'s anchor world rotation at one\n * of its probe values — its `max`, its `min` and every keyform stop of a warp\n * deformer keyed on it, all but the resting value — in model order. Both\n * ends and the stops, since a warp parent can turn the anchor at one end\n * alone or at an interior stop while its other end matches rest. A probe\n * turning it no more than `MIN_TURN` past an earlier one does not replace it,\n * so a symmetric rig steps to `max`, as `farEnd` does, and float noise never\n * decides a near-tie.\n */\nexport function anchorInputs(\n model: IkiModel,\n chain: IkiPhysicsChain,\n): Candidate[] {\n const store = new ParameterStore(model.parameters);\n const angle = () => {\n const { worlds } = resolveDeformers(model.deformers ?? [], store);\n const world = worlds.get(chain.anchorDeformer)!;\n return Math.atan2(world[1], world[0]);\n };\n const rest = angle();\n const found: Candidate[] = [];\n for (const p of model.parameters) {\n const probes = new Set(\n [p.max, p.min, ...stopsOf(model, p.id)].map((v) =>\n clamp(v, p.min, p.max),\n ),\n );\n probes.delete(store.get(p.id));\n let most = 0;\n let best: Candidate | undefined;\n for (const value of probes) {\n store.set(p.id, value);\n const d = angle() - rest;\n const turn = Math.abs(Math.atan2(Math.sin(d), Math.cos(d)));\n if (turn <= most + MIN_TURN) continue;\n [most, best] = [turn, { parameter: p.id, value }];\n }\n store.reset();\n if (best) found.push(best);\n }\n return found;\n}\n\n/** The sorted distinct keyform values of every deformer warp and `warp2d` axis keyed on `parameter`. */\nfunction stopsOf(model: IkiModel, parameter: string): number[] {\n const stops = new Set<number>();\n for (const d of model.deformers ?? []) {\n if (d.kind !== \"warp\") continue;\n for (const w of d.warps ?? []) {\n if (w.parameter !== parameter) continue;\n for (const k of w.keyforms) stops.add(k.value);\n }\n const { warp2d } = d;\n if (warp2d?.parameter === parameter) {\n for (const v of warp2d.valuesX) stops.add(v);\n }\n if (warp2d?.parameterY === parameter) {\n for (const v of warp2d.valuesY) stops.add(v);\n }\n }\n return [...stops].sort((a, b) => a - b);\n}\n","/**\n * The fold check `auto_rig_from_layers` and `render_poses` report: the\n * engine's `checkFolds` with the auto-rig's by-design closures set apart, and\n * the text lines both tools print it as.\n */\n\nimport { SHUT_BY } from \"@ikijs/editor\";\nimport {\n checkFolds,\n foldPoses,\n type FoldHit,\n type FoldPose,\n type FoldReport,\n type FoldTarget,\n} from \"@ikijs/engine\";\nimport type { IkiModel } from \"@ikijs/format\";\n\n/**\n * `checkFolds` over `foldPoses(model)` then one pose per `extraValues` set,\n * appended as given (a set equal to a default pose is checked twice), with\n * the auto-rig's by-design closures (`SHUT_BY`) kept out of `worst`.\n */\nexport function checkModelFolds(\n model: IkiModel,\n extraValues: Record<string, number>[] = [],\n): FoldReport {\n // An undeclared parameter reads 0 from the store, which is no closure.\n const declared = new Set(model.parameters.map((p) => p.id));\n return checkFolds(model, {\n poses: [...foldPoses(model), ...extraValues.map(foldPose)],\n // The effective value, not the pose's overrides: the auto-rig's mouth\n // rests shut at its default, so `rest` and the other parameters' singles\n // are shut-mouth poses too.\n expected: (target, _pose, value) => {\n if (target.kind !== \"part\") return false;\n const shutBy = SHUT_BY.get(target.id);\n return (\n shutBy !== undefined && declared.has(shutBy) && value(shutBy) === 0\n );\n },\n });\n}\n\n/**\n * `report` as text lines: one `FOLD` line per offender, worst first, or\n * `FOLDS: none over N poses`; then, when a by-design closure folds, one\n * `FOLDS expected:` line naming each such part, its ratio and the parameter\n * that shuts it. A `FOLD` line gives its rest point in model space and in\n * model px from the top-left of the model's `canvas` — the layer PNGs' own\n * pixels, the frame `RenderPlan.mouth` is in, not a render's.\n */\nexport function formatFoldReport(\n report: FoldReport,\n canvas: { width: number; height: number },\n): string[] {\n const lines =\n report.offenders.length === 0\n ? [`FOLDS: none over ${report.poses} poses`]\n : report.offenders.map((t) => offenderLine(t, t.worst!, canvas));\n\n // An expected hit that never came near folding is no closure to list.\n const closures = report.targets.flatMap((t) => {\n if (t.expected === undefined) return [];\n if (t.expected.ratio >= report.thresholds.collapse) return [];\n const shutBy = SHUT_BY.get(t.target.id);\n const at = shutBy === undefined ? \"\" : ` at ${shutBy}=0`;\n return [`${t.target.id} ${ratioText(t.expected.ratio)}${at}`];\n });\n if (closures.length > 0) {\n lines.push(\n `FOLDS expected: by-design closures, not findings — ${closures.join(\", \")}`,\n );\n }\n return lines;\n}\n\n/**\n * `values` named by the `FoldPose.name` contract, as the engine names its own\n * poses (its helper is not exported): sorted `id=value` pairs joined by one\n * space, `rest` when empty. Never a caller's PNG name, so a `FOLD` line keeps\n * settings a host can reproduce.\n */\nexport function foldPose(values: Record<string, number>): FoldPose {\n const ids = Object.keys(values).sort();\n const name =\n ids.length === 0\n ? \"rest\"\n : ids.map((id) => `${id}=${values[id]}`).join(\" \");\n return { name, values };\n}\n\nfunction offenderLine(\n t: FoldTarget,\n hit: FoldHit,\n canvas: { width: number; height: number },\n): string {\n const where =\n \"triangle\" in hit.where\n ? `triangle ${hit.where.triangle}`\n : `cell (${hit.where.col},${hit.where.row})`;\n const { x, y } = hit.rest;\n return (\n `FOLD ${t.kind} ${t.target.kind} ${t.target.id} ${where} ratio ${ratioText(hit.ratio)} ` +\n `pose [${hit.pose.name}] rest at (${x.toFixed(1)}, ${y.toFixed(1)}) model space, ` +\n `(${(canvas.width / 2 + x).toFixed(0)}, ${(canvas.height / 2 - y).toFixed(0)}) model px from the top-left`\n );\n}\n\n/** Two decimals, or two significant figures under 0.01, so a flip a hair\n * under 0 never reads `-0.00`. */\nfunction ratioText(ratio: number): string {\n if (ratio === 0) return \"0\";\n return Math.abs(ratio) < 0.01 ? ratio.toExponential(1) : ratio.toFixed(2);\n}\n","/**\n * The pose plan `render_poses` captures: the canvas framing, the crops and the\n * pose list, all decided from the model. It is the iki-character-loop's\n * render recipe, minus the page that ran it.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n IkiFormatError,\n StandardParameter,\n loadIkiModel,\n type IkiModel,\n} from \"@ikijs/format\";\nimport {\n checkPhysics,\n type FoldReport,\n type PhysicsReport,\n} from \"@ikijs/engine\";\nimport { checkModelFolds } from \"./fold-report\";\nimport {\n AutoRigInputError,\n confineToWorkingDirectory,\n resolveInputPath,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\nimport { NO_BROWSER_MESSAGE, findBrowser, withBrowser } from \"./render-browser\";\n\nexport interface RenderCrop {\n sx: number;\n sy: number;\n sw: number;\n sh: number;\n dw: number;\n dh: number;\n}\n\nexport interface RenderPose {\n name: string;\n values: Record<string, number>;\n /** Canvas px source and output size; absent = the whole canvas. */\n crop?: RenderCrop;\n}\n\nexport interface RenderPlan {\n canvas: { width: number; height: number };\n /** The player's view; absent = the model's own canvas. */\n view?: { x: number; y: number; width: number; height: number };\n fullBody: boolean;\n /** The mouth's centre in model px from the top-left. */\n mouth?: { cx: number; cy: number };\n poses: RenderPose[];\n}\n\n/** A pose the caller names, rendered in place of the model's own set. */\nexport interface RequestedPose {\n /** Written as `<outDir>/<name>.png`. */\n name: string;\n values: Record<string, number>;\n /** Model px from the top-left; absent = framed as the standard shots. */\n crop?: { x: number; y: number; w: number; h: number };\n}\n\n// The playground's view width for a full body, in model widths.\nconst FULL_BODY_VIEW_WIDTH = 2.5;\n// The model's square is drawn this many px wide, in the whole shot or a crop.\nexport const BUST_SIZE = 560;\n// A requested crop is drawn this many px wide, at its own aspect, and at\n// most this many tall: the page sizes a canvas to it.\nconst CROP_WIDTH = 720;\nconst CROP_MAX_HEIGHT = 8192;\n// The name becomes a file in outDir: no separator can climb out of it.\nconst POSE_NAME = /^[A-Za-z0-9_.-]+$/;\n\n/**\n * Bust-render px of vertical padding above a landscape model: the renderer\n * fits it into the square canvas and centres it. Zero for square and tall ones.\n */\nexport function bustPadY(width: number, height: number): number {\n return Math.max(0, (BUST_SIZE - (BUST_SIZE * height) / width) / 2);\n}\n\n/**\n * The model's own pose set, or `requested` alone when given. Throws\n * `AutoRigInputError` for a request it cannot render.\n */\nexport function planRenders(\n model: IkiModel,\n requested?: RequestedPose[],\n): RenderPlan {\n const { width: W, height: H } = model.canvas;\n const fullBody = H > W;\n const canvas = fullBody\n ? {\n width: FULL_BODY_VIEW_WIDTH * BUST_SIZE,\n height: Math.ceil((BUST_SIZE * H) / W),\n }\n : { width: BUST_SIZE, height: BUST_SIZE };\n const view = fullBody\n ? { x: 0, y: 0, width: FULL_BODY_VIEW_WIDTH * W, height: H }\n : undefined;\n\n // The model's square sits in the middle of the canvas.\n const x0 = (canvas.width - BUST_SIZE) / 2;\n const s = BUST_SIZE / W;\n const y0 = bustPadY(W, H);\n\n // The auto-rigger writes world-space part transforms and its deformers carry\n // no base transform, so the rest transform alone places the part.\n const mouthPart =\n model.parts.find((p) => p.id === \"mouth_inner\") ??\n model.parts.find((p) => p.id === \"mouth\");\n const mouth = mouthPart\n ? { cx: W / 2 + mouthPart.transform.x, cy: H / 2 - mouthPart.transform.y }\n : undefined;\n\n const squareCrop: RenderCrop | undefined = fullBody\n ? {\n sx: x0,\n sy: 0,\n sw: BUST_SIZE,\n sh: BUST_SIZE,\n dw: BUST_SIZE,\n dh: BUST_SIZE,\n }\n : undefined;\n const square = (name: string, values: Record<string, number> = {}) => ({\n name,\n values,\n crop: squareCrop,\n });\n const whole = (name: string, values: Record<string, number> = {}) => ({\n name,\n values,\n });\n\n if (requested) {\n if (requested.length === 0) throw new AutoRigInputError(\"poses is empty\");\n const poses = requested.map((pose, i): RenderPose => {\n checkRequest(requested, i);\n if (!pose.crop) return square(pose.name, pose.values);\n // Clamped to the canvas first, so a box grown past an edge still renders.\n const left = Math.max(pose.crop.x, 0);\n const top = Math.max(pose.crop.y, 0);\n const w = Math.min(pose.crop.x + pose.crop.w, W) - left;\n const h = Math.min(pose.crop.y + pose.crop.h, H) - top;\n // Negated so a NaN corner is refused too.\n if (!(w > 0 && h > 0)) {\n throw new AutoRigInputError(\n `poses[${i}].crop does not overlap the model's ${W}x${H} canvas`,\n );\n }\n // Refused here, not by the page after earlier poses were written.\n const dh = Math.round((CROP_WIDTH * h) / w);\n if (dh < 1 || dh > CROP_MAX_HEIGHT) {\n throw new AutoRigInputError(\n `poses[${i}].crop meets the canvas in ${w}x${h} model px, which ${CROP_WIDTH} px wide draws ${dh} px tall, outside 1..${CROP_MAX_HEIGHT}`,\n );\n }\n return {\n name: pose.name,\n values: pose.values,\n crop: {\n sx: x0 + left * s,\n sy: y0 + top * s,\n sw: w * s,\n sh: h * s,\n dw: CROP_WIDTH,\n dh,\n },\n };\n });\n return { canvas, view, fullBody, mouth, poses };\n }\n\n // The engine ignores an undeclared id, so this only keeps `stress` from\n // naming settings the rig lacks: every loop rig declares its other ids (the\n // composer requires brows), but the body angles only with a `body` layer.\n const bodyAngles = Object.fromEntries(\n [\n StandardParameter.BodyAngleX,\n StandardParameter.BodyAngleY,\n StandardParameter.BodyAngleZ,\n ]\n .filter((id) => model.parameters.some((p) => p.id === id))\n .map((id) => [id, -10]),\n );\n\n const poses: RenderPose[] = [\n square(\"rest\"),\n square(\"turn-m30\", { ParamAngleX: -30 }),\n square(\"turn-p30\", { ParamAngleX: 30 }),\n square(\"turn-15\", { ParamAngleX: 15 }),\n square(\"nod-15\", { ParamAngleY: 15 }),\n square(\"blink\", { ParamEyeLOpen: 0 }),\n square(\"blink-half\", { ParamEyeLOpen: 0.5 }),\n square(\"gaze\", { ParamEyeBallX: 1 }),\n square(\"combined\", { ParamAngleX: 30, ParamAngleY: 30, ParamAngleZ: 30 }),\n // Every head angle at its other extreme with the face moving too, where\n // moves that each look fine alone stack up into a fold.\n square(\"stress\", {\n ParamAngleX: -30,\n ParamAngleY: -30,\n ParamAngleZ: -30,\n ParamMouthOpenY: 1,\n ParamEyeLOpen: 0.5,\n ParamEyeROpen: 0.5,\n ParamBrowLY: -1,\n ParamBrowRY: 1,\n ParamBrowLAngle: 1,\n ParamBrowRAngle: -1,\n ...bodyAngles,\n }),\n ];\n\n if (mouth) {\n // 180 x 120 model px centred on the mouth, drawn x4 onto 720 x 480: a\n // small mouth is unreadable in the whole shot.\n const crop = {\n sx: x0 + (mouth.cx - 90) * s,\n sy: y0 + (mouth.cy - 60) * s,\n sw: 180 * s,\n sh: 120 * s,\n dw: 720,\n dh: 480,\n };\n for (const open of [0, 0.3, 0.6, 1]) {\n for (const [name, form] of [\n [\"m1\", -1],\n [\"0\", 0],\n [\"p1\", 1],\n ] as const) {\n poses.push({\n name: `mouth-open-${open}-form-${name}`,\n values: { ParamMouthOpenY: open, ParamMouthForm: form },\n crop,\n });\n }\n }\n poses.push(\n {\n name: \"mouth-laugh\",\n values: { ParamMouthOpenY: 0.8, ParamMouthForm: 1 },\n crop,\n },\n { name: \"mouth-surprised\", values: { ParamMouthOpenY: 0.9 }, crop },\n {\n name: \"mouth-turn-p30-half\",\n values: { ParamAngleX: 30, ParamMouthOpenY: 0.5 },\n crop,\n },\n );\n }\n\n if (fullBody) {\n poses.push(\n whole(\"full-rest\"),\n whole(\"full-turn-p30\", { ParamAngleX: 30 }),\n whole(\"full-body-x-m10\", { ParamBodyAngleX: -10 }),\n whole(\"full-body-x-p10\", { ParamBodyAngleX: 10 }),\n whole(\"full-body-y-m10\", { ParamBodyAngleY: -10 }),\n whole(\"full-body-y-p10\", { ParamBodyAngleY: 10 }),\n whole(\"full-body-z-m10\", { ParamBodyAngleZ: -10 }),\n whole(\"full-body-z-p10\", { ParamBodyAngleZ: 10 }),\n whole(\"full-arm-l-16\", { ParamArmL: 16 }),\n whole(\"full-arm-l-32\", { ParamArmL: 32 }),\n whole(\"full-arm-r-16\", { ParamArmR: 16 }),\n whole(\"full-arm-r-32\", { ParamArmR: 32 }),\n whole(\"full-elbow-l-m10\", { ParamElbowL: -10 }),\n whole(\"full-elbow-l-45\", { ParamElbowL: 45 }),\n whole(\"full-elbow-l-90\", { ParamElbowL: 90 }),\n whole(\"full-elbow-r-m10\", { ParamElbowR: -10 }),\n whole(\"full-elbow-r-45\", { ParamElbowR: 45 }),\n whole(\"full-elbow-r-90\", { ParamElbowR: 90 }),\n );\n if (model.parameters.some((p) => p.id === StandardParameter.ArmPoseRight)) {\n poses.push(\n whole(\"full-pose-l\", { ParamArmPoseL: 1 }),\n whole(\"full-pose-r\", { ParamArmPoseR: 1 }),\n whole(\"full-pose-r-angle-m15\", {\n ParamArmPoseR: 1,\n ParamArmPoseAngleR: -15,\n }),\n whole(\"full-pose-r-angle-p15\", {\n ParamArmPoseR: 1,\n ParamArmPoseAngleR: 15,\n }),\n whole(\"full-pose-r-half\", { ParamArmPoseR: 0.5 }),\n );\n }\n }\n\n return { canvas, view, fullBody, mouth, poses };\n}\n\n/** `requested[i]`'s name and values, as `planRenders` takes them. */\nfunction checkRequest(requested: RequestedPose[], i: number): void {\n const { name, values } = requested[i];\n if (!POSE_NAME.test(name)) {\n throw new AutoRigInputError(\n `poses[${i}].name must match ${POSE_NAME.source} (it names <outDir>/<name>.png): ${JSON.stringify(name)}`,\n );\n }\n const first = requested.findIndex(\n (p) => p.name.toLowerCase() === name.toLowerCase(),\n );\n if (first < i) {\n throw new AutoRigInputError(\n `poses[${i}].name ${JSON.stringify(name)} repeats poses[${first}].name ${JSON.stringify(requested[first].name)} (ignoring case: one file on a case-insensitive disk)`,\n );\n }\n for (const [id, value] of Object.entries(values)) {\n if (!Number.isFinite(value)) {\n throw new AutoRigInputError(\n `poses[${i}].values.${id} must be a finite number, got ${value}`,\n );\n }\n }\n}\n\nexport interface RenderPosesInput {\n /** The rigged `.iki` to render (resolved against cwd). */\n modelPath: string;\n /** Existing directory under cwd the pose PNGs are written into. */\n outDir: string;\n /** Rendered in place of the model's own set; each is also fold-checked. */\n poses?: RequestedPose[];\n}\n\nexport type RenderPosesResult =\n | {\n ok: true;\n outDir: string;\n canvas: RenderPlan[\"canvas\"];\n fullBody: boolean;\n mouth?: RenderPlan[\"mouth\"];\n /** Texture indices the engine could not load; the renders lack them. */\n failedTextures: number[];\n poses: { name: string; path: string }[];\n /** The model's own canvas, which `folds`' rest points are placed on in\n * the text (`canvas` is the render's). */\n modelCanvas: IkiModel[\"canvas\"];\n /** The model's folds, as `auto_rig_from_layers` reports them.\n * Report-only: a fold never fails the render. */\n folds: FoldReport;\n /** The model's own physics rigs (`poses` do not enter it), as\n * `auto_rig_from_layers` reports them. Report-only: it never fails\n * the render. */\n physics: PhysicsReport;\n }\n | { ok: false; error: string };\n\nconst PNG_PREFIX = \"data:image/png;base64,\";\nconst PAGE_SCRIPT_MS = 10_000;\nconst LOAD_MS = 60_000;\nconst CAPTURE_MS = 15_000;\n\nfunction readPageScript(): string {\n // Resolves from both src/ (vitest) and dist/: each sits one level under the package.\n const url = new URL(\"../dist/render-page.global.js\", import.meta.url);\n try {\n return readFileSync(url, \"utf8\");\n } catch (cause) {\n // A broken build or install, not caller input: it surfaces as a tool error.\n throw new Error(\n \"could not read the render page script; run `pnpm build` in packages/mcp\",\n { cause },\n );\n }\n}\n\n/**\n * Render the model's pose set into `outDir`. Only caller-input failures\n * (`AutoRigInputError`, `IkiFormatError`, and no installed browser) come back as\n * `{ ok: false, error }`; a browser or page failure throws.\n */\nexport async function renderPoses(\n input: RenderPosesInput,\n): Promise<RenderPosesResult> {\n try {\n const modelFile = confineToWorkingDirectory(\n process.cwd(),\n resolveInputPath(input.modelPath, \"model\"),\n \"model path\",\n input.modelPath,\n );\n const outDir = resolveOutputDir(input.outDir);\n const model = loadIkiModel(readFileSync(modelFile, \"utf8\"));\n const plan = planRenders(model, input.poses);\n const browser = findBrowser();\n if (!browser) return { ok: false, error: NO_BROWSER_MESSAGE };\n const pageScript = readPageScript();\n const folds = checkModelFolds(\n model,\n input.poses?.map((p) => p.values),\n );\n const physics = checkPhysics(model);\n\n const { failedTextures, poses } = await withBrowser(\n browser,\n async (evaluate) => {\n await evaluate(pageScript, PAGE_SCRIPT_MS);\n const loaded = (await evaluate(\n `window.__ikiRender.load(${JSON.stringify(model)}, ${JSON.stringify({ canvas: plan.canvas, view: plan.view })})`,\n LOAD_MS,\n )) as { failedTextures: number[] };\n const written: { name: string; path: string }[] = [];\n for (const pose of plan.poses) {\n const url = await evaluate(\n `window.__ikiRender.capture(${JSON.stringify(pose.values)}, ${JSON.stringify(pose.crop)})`,\n CAPTURE_MS,\n );\n if (typeof url !== \"string\" || !url.startsWith(PNG_PREFIX)) {\n throw new Error(`pose ${pose.name}: the page returned no PNG`);\n }\n const file = path.join(outDir, `${pose.name}.png`);\n writeFileAtomic(\n file,\n Buffer.from(url.slice(PNG_PREFIX.length), \"base64\"),\n );\n written.push({ name: pose.name, path: file });\n }\n return { failedTextures: loaded.failedTextures, poses: written };\n },\n );\n return {\n ok: true,\n outDir,\n canvas: plan.canvas,\n fullBody: plan.fullBody,\n mouth: plan.mouth,\n failedTextures,\n poses,\n modelCanvas: model.canvas,\n folds,\n physics,\n };\n } catch (error) {\n if (error instanceof AutoRigInputError || error instanceof IkiFormatError) {\n return { ok: false, error: error.message };\n }\n throw error;\n }\n}\n","/**\n * Resource guards + fail-fast path resolution and atomic writes for the Node\n * auto-rig tool.\n *\n * These constants bound an agent-supplied layer set so a malformed or oversized\n * request fails fast with a path-qualified message rather than exhausting memory\n * or producing a multi-MB MCP response. All guards REJECT (never downscale).\n *\n * `sharp` must stay confined to @ikijs/mcp — none of @ikijs/engine, @ikijs/editor,\n * or @ikijs/format may take a heavy Node image dependency.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\n/** Max number of input layers in one request. */\nexport const MAX_LAYERS = 64;\n/** Max per-side dimension (px) of any single input PNG. */\nexport const MAX_LAYER_DIM = 4096;\n/** Max per-side dimension (px) of the derived canvas. */\nexport const MAX_CANVAS_DIM = 4096;\n/** Max per-side length (px) of each packed atlas page. WebGL2 guarantees only\n * 2048, but 4096 or more is near-universal; the engine refuses a texture over\n * the device's own limit on either side and leaves its parts untextured. Both\n * sides within it also bound a page's area at 4096². */\nexport const MAX_ATLAS_SIDE = 4096;\n/** Decoded-pixel ceiling per input PNG, passed to sharp `limitInputPixels`. */\nexport const MAX_INPUT_PIXELS = 4096 * 4096;\n/** Aggregate decoded-pixel budget across ALL layers in one request. Layers\n * decode one at a time, so it bounds the request's total work, not its peak\n * memory. A full body's 21 layers at 1100 × 3650 decode 84.3 M px. */\nexport const MAX_TOTAL_PIXELS = 128 * 1024 * 1024;\n/** Max length (bytes) of the base64 atlas data URI embedded in the model,\n * summed over its pages. Sized for the loop's lossless re-rig of a full body:\n * measured on bob's layers, a lossless atlas costs 1.56 data-URI bytes per\n * crop px (1,677,898 B over 1,075,888 px), and a full body on a canvas up to\n * 4096 tall crops to at most ~5 M px, about 8 MB. */\nexport const MAX_OUTPUT_BYTES = 12 * 1024 * 1024;\n\n/**\n * Expected, caller-input-caused failure. The tool catches ONLY this class and\n * returns `{ ok: false, error }`; any other thrown Error (TypeError, invariant\n * break, programmer bug) propagates so the SDK handler surfaces `isError: true`.\n */\nexport class AutoRigInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AutoRigInputError\";\n }\n}\n\n/**\n * Reject an empty/whitespace or URL-looking caller-supplied path, shared by\n * {@link resolveInputPath} and {@link resolveInputDir}. `noun` and `kind`\n * shape the thrown message so each caller reports in its own vocabulary\n * (e.g. a directory input was never supposed to look like \"a file path\").\n */\nfunction rejectEmptyOrUrl(inputPath: string, noun: string, kind: string): void {\n if (typeof inputPath !== \"string\" || inputPath.trim() === \"\") {\n throw new AutoRigInputError(`${noun} is empty`);\n }\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(inputPath)) {\n throw new AutoRigInputError(\n `${noun} must be a ${kind}, not a URL: ${inputPath}`,\n );\n }\n}\n\n/**\n * Resolve a caller-supplied input file path against the MCP process cwd and\n * confirm it points at a readable file. Throws AutoRigInputError (path-qualified)\n * for empty/URL-looking strings, a missing file, or a directory.\n * `what` names the input in those messages (\"layer\" -> \"layer file not found\").\n *\n * READS ARE DELIBERATELY NOT CONFINED to the working directory, unlike\n * {@link resolveOutputPath}. The asymmetry is intentional, not an oversight: a\n * stray write destroys data, while a read only surfaces a PNG the agent already\n * named and the user's own account can already open. Confining reads would also\n * break the documented generate-a-character flow, which reads its part PNGs\n * from wherever the image generator dropped them (a downloads folder, a scratch\n * dir) while everything it writes — the composed layers, the model — stays\n * under the working directory. Revisit only if this server ever runs with wider\n * privileges than the person driving it. The same reasoning covers\n * {@link resolveInputDir}, its directory counterpart.\n *\n * Param is named `inputPath` (not `path`) to avoid shadowing the node:path import.\n */\nexport function resolveInputPath(inputPath: string, what = \"layer\"): string {\n rejectEmptyOrUrl(inputPath, `${what} path`, \"file path\");\n const resolved = path.resolve(process.cwd(), inputPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`${what} file not found: ${resolved}`);\n }\n if (stat.isDirectory()) {\n throw new AutoRigInputError(\n `${what} path is a directory, not a file: ${resolved}`,\n );\n }\n return resolved;\n}\n\n/** Directory counterpart to {@link resolveInputPath} — see its doc comment. */\nexport function resolveInputDir(dirPath: string): string {\n rejectEmptyOrUrl(dirPath, \"layers dir\", \"directory path\");\n const resolved = path.resolve(process.cwd(), dirPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`layers dir not found: ${resolved}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`layers path is not a directory: ${resolved}`);\n }\n return resolved;\n}\n\n/**\n * Confine an already-verified-to-exist directory to the MCP process working\n * directory, comparing REAL paths (statSync/writeFileSync follow symlinks, so\n * a lexical startsWith check can be bypassed by a symlinked dir under cwd).\n * Shared by {@link resolveOutputPath} and {@link resolveOutputDir} — both are\n * write-side boundaries where an unrestricted target is an\n * arbitrary-file-overwrite surface — and by `render_poses` for its model file,\n * whose first bytes a parse error would otherwise echo back. `label` and `original` shape the thrown\n * message (path-qualified with the caller's original, unresolved string).\n */\nexport function confineToWorkingDirectory(\n root: string,\n dir: string,\n label: string,\n original: string,\n): string {\n const realRoot = fs.realpathSync(root);\n const realDir = fs.realpathSync(dir);\n if (realDir !== realRoot && !realDir.startsWith(realRoot + path.sep)) {\n throw new AutoRigInputError(\n `${label} escapes the working directory: ${original}`,\n );\n }\n return realDir;\n}\n\n/**\n * Resolve a caller-supplied output path against the MCP process cwd. Throws\n * AutoRigInputError (path-qualified) if the parent directory does not exist —\n * the tool never creates directories (fail-fast).\n *\n * Writes are confined to the MCP process working directory: the path must end\n * in `.iki` AND resolve to a location under `process.cwd()`. The MCP server runs\n * with the user's own permissions on agent-supplied input, so an unrestricted\n * `outputPath` is an arbitrary-file-overwrite surface — absolute paths and `..`\n * traversal that escape the working directory are rejected. (Overwriting an\n * existing `.iki` UNDER the working directory is intentional: re-running the tool\n * regenerates the named model.)\n */\nexport function resolveOutputPath(outputPath: string): string {\n if (typeof outputPath !== \"string\" || outputPath.trim() === \"\") {\n throw new AutoRigInputError(\"output path is empty\");\n }\n if (!outputPath.toLowerCase().endsWith(\".iki\")) {\n throw new AutoRigInputError(`output path must end in .iki: ${outputPath}`);\n }\n const root = process.cwd();\n const resolved = path.resolve(root, outputPath);\n const dir = path.dirname(resolved);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(dir);\n } catch {\n throw new AutoRigInputError(`output directory does not exist: ${dir}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output parent is not a directory: ${dir}`);\n }\n const realDir = confineToWorkingDirectory(\n root,\n dir,\n \"output path\",\n outputPath,\n );\n return path.join(realDir, path.basename(resolved));\n}\n\n/**\n * Resolve a caller-supplied output DIRECTORY against the MCP process cwd.\n * Unlike {@link resolveOutputPath}, no filename is appended — the directory\n * itself must already exist (the tool never creates directories, fail-fast) —\n * and is confined via {@link confineToWorkingDirectory}. Returns the\n * realpath'd directory.\n */\nexport function resolveOutputDir(dirPath: string): string {\n if (typeof dirPath !== \"string\" || dirPath.trim() === \"\") {\n throw new AutoRigInputError(\"output dir is empty\");\n }\n const root = process.cwd();\n const resolved = path.resolve(root, dirPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`output dir not found: ${resolved}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output dir is not a directory: ${resolved}`);\n }\n return confineToWorkingDirectory(root, resolved, \"output dir\", dirPath);\n}\n\n/**\n * Write `data` to `outPath` atomically: write to a fresh temp file in the\n * same directory, then `renameSync` over the target. `rename` REPLACES the\n * destination directory entry rather than following it, so an existing\n * symlink at `outPath` cannot redirect the write outside the working tree.\n * Throws AutoRigInputError(\"write: …\") on failure.\n */\nexport function writeFileAtomic(\n outPath: string,\n data: string | Uint8Array,\n): void {\n const tmp = `${outPath}.${process.pid}.${Date.now()}.tmp`;\n try {\n fs.writeFileSync(tmp, data);\n try {\n fs.renameSync(tmp, outPath);\n } catch (e) {\n try {\n fs.rmSync(tmp, { force: true });\n } catch {\n // best-effort temp cleanup; surface the original rename error\n }\n throw e;\n }\n } catch (e) {\n throw new AutoRigInputError(\n `write: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n","/**\n * Browser discovery and a headless DevTools driver for `render_poses`: find a\n * system Chrome/Edge/Chromium, launch it, and evaluate scripts over the\n * DevTools protocol on Node's global `WebSocket`. No Playwright, no dependency.\n */\n\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { AutoRigInputError } from \"./limits\";\n\nexport const NO_BROWSER_MESSAGE =\n \"render_poses needs a Chromium-based browser and found none. Install Google Chrome, Microsoft Edge or Chromium, or set CHROME_PATH to its executable.\";\n\nconst DARWIN_CANDIDATES = [\n \"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\",\n \"/Applications/Chromium.app/Contents/MacOS/Chromium\",\n \"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge\",\n];\nconst LINUX_CANDIDATES = [\n \"/usr/bin/google-chrome\",\n \"/usr/bin/google-chrome-stable\",\n \"/usr/bin/chromium\",\n \"/usr/bin/chromium-browser\",\n \"/usr/bin/microsoft-edge\",\n \"/snap/bin/chromium\",\n];\nconst WIN32_ROOTS = [\"PROGRAMFILES\", \"PROGRAMFILES(X86)\", \"LOCALAPPDATA\"];\nconst WIN32_SUFFIXES = [\n [\"Google\", \"Chrome\", \"Application\", \"chrome.exe\"],\n [\"Microsoft\", \"Edge\", \"Application\", \"msedge.exe\"],\n];\n\nconst CLOSE_GRACE_MS = 2000;\nconst DEFAULT_TIMEOUT_MS = 30000;\nconst BROWSER_CLOSE_MS = 1000;\n\nfunction isExecutableFile(file: string): boolean {\n try {\n if (!fs.statSync(file).isFile()) return false;\n fs.accessSync(file, fs.constants.X_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nexport interface FindBrowserOptions {\n env: NodeJS.ProcessEnv;\n platform: NodeJS.Platform;\n isExecutable: (file: string) => boolean;\n}\n\n/** The browser to drive, or `undefined` when none is installed. */\nexport function findBrowser({\n env = process.env,\n platform = process.platform,\n isExecutable = isExecutableFile,\n}: Partial<FindBrowserOptions> = {}): string | undefined {\n const override = env.CHROME_PATH;\n if (override) {\n // A bad override must not fall through to spawn, where it fails obscurely.\n if (!isExecutable(override)) {\n throw new AutoRigInputError(\n `CHROME_PATH is not an executable file: ${override}`,\n );\n }\n return override;\n }\n let candidates: string[];\n if (platform === \"darwin\") candidates = DARWIN_CANDIDATES;\n else if (platform === \"win32\") {\n candidates = [];\n for (const suffix of WIN32_SUFFIXES) {\n for (const root of WIN32_ROOTS) {\n const base = env[root];\n if (base) candidates.push(path.win32.join(base, ...suffix));\n }\n }\n } else candidates = LINUX_CANDIDATES;\n return candidates.find((file) => isExecutable(file));\n}\n\nexport type Evaluate = (\n expression: string,\n timeoutMs: number,\n) => Promise<unknown>;\n\nexport interface Browser {\n openPage(): Promise<Evaluate>;\n close(): Promise<void>;\n}\n\ninterface RuntimeEvaluate {\n result: { value?: unknown };\n exceptionDetails?: {\n text: string;\n exception?: { description?: string; value?: unknown };\n };\n}\n\n/**\n * Race `promise` against a timer, clearing the timer either way. `detail`\n * adds context to the timeout message, read only when it fires.\n */\nfunction within<T>(\n promise: Promise<T>,\n ms: number,\n what: string,\n detail?: () => string,\n): Promise<T> {\n let timer: NodeJS.Timeout;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () =>\n reject(\n new Error(\n `${what} timed out after ${ms} ms${detail ? `: ${detail()}` : \"\"}`,\n ),\n ),\n ms,\n );\n });\n return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));\n}\n\ninterface CdpClient {\n send<T = unknown>(\n method: string,\n timeoutMs: number,\n params?: object,\n sessionId?: string,\n ): Promise<T>;\n}\n\nfunction connectCdp(url: string, timeoutMs: number): Promise<CdpClient> {\n const socket = new WebSocket(url);\n let nextId = 0;\n let socketClosed = false;\n const pending = new Map<\n number,\n { resolve: (v: unknown) => void; reject: (e: Error) => void }\n >();\n socket.addEventListener(\"message\", (event) => {\n const message = JSON.parse(String(event.data));\n const entry = pending.get(message.id);\n if (!entry) return; // a protocol event, not a reply\n pending.delete(message.id);\n if (message.error) {\n entry.reject(\n new Error(`${message.error.message} (${message.error.code})`),\n );\n } else entry.resolve(message.result);\n });\n socket.addEventListener(\"close\", () => {\n socketClosed = true;\n for (const entry of pending.values()) {\n entry.reject(new Error(\"DevTools connection closed\"));\n }\n pending.clear();\n });\n const opened = new Promise<CdpClient>((resolve, reject) => {\n socket.addEventListener(\"error\", () =>\n reject(new Error(\"DevTools connection failed\")),\n );\n socket.addEventListener(\"open\", () =>\n resolve({\n send<T>(\n method: string,\n callTimeoutMs: number,\n params?: object,\n sessionId?: string,\n ) {\n // send() on a closed socket is silent; fail now, not at the timeout.\n if (socketClosed) {\n return Promise.reject(new Error(\"DevTools connection closed\"));\n }\n const id = ++nextId;\n const reply = new Promise<T>((res, rej) => {\n pending.set(id, {\n resolve: res as (v: unknown) => void,\n reject: rej,\n });\n });\n socket.send(JSON.stringify({ id, method, params, sessionId }));\n return within(reply, callTimeoutMs, method).finally(() =>\n pending.delete(id),\n );\n },\n }),\n );\n });\n // Closing the socket on failure lets a hung connect not outlive the launch.\n return within(opened, timeoutMs, \"DevTools connection\").catch((error) => {\n socket.close();\n throw error;\n });\n}\n\nfunction startError(executable: string, error: NodeJS.ErrnoException): Error {\n return new Error(\n `could not start ${executable}: ${error.code ?? error.message}`,\n );\n}\n\n/** The DevTools websocket URL Chrome prints on stderr once it is ready. */\nfunction waitForDevTools(\n child: ChildProcess,\n closed: Promise<void>,\n getSpawnError: () => NodeJS.ErrnoException | undefined,\n executable: string,\n timeoutMs: number,\n): Promise<string> {\n let tail = \"\";\n return within(\n new Promise<string>((resolve, reject) => {\n // Keeps draining after the match so Chrome never blocks on a full pipe.\n child.stderr!.on(\"data\", (chunk) => {\n tail = (tail + chunk).slice(-2000);\n const match = /DevTools listening on (ws:\\/\\/\\S+)/.exec(tail);\n if (match) resolve(match[1]);\n });\n void closed.then(() => {\n const spawnError = getSpawnError();\n reject(\n spawnError\n ? startError(executable, spawnError)\n : new Error(\n `${executable} exited before DevTools was ready: ${tail.trim()}`,\n ),\n );\n });\n }),\n timeoutMs,\n \"browser startup\",\n () => tail.trim() || \"no output\",\n );\n}\n\nasync function openPage(cdp: CdpClient, timeoutMs: number): Promise<Evaluate> {\n const { targetId } = await cdp.send<{ targetId: string }>(\n \"Target.createTarget\",\n timeoutMs,\n { url: \"about:blank\" },\n );\n const { sessionId } = await cdp.send<{ sessionId: string }>(\n \"Target.attachToTarget\",\n timeoutMs,\n { targetId, flatten: true },\n );\n return async (expression, evalTimeoutMs) => {\n const { result, exceptionDetails } = await cdp.send<RuntimeEvaluate>(\n \"Runtime.evaluate\",\n evalTimeoutMs,\n { expression, awaitPromise: true, returnByValue: true },\n sessionId,\n );\n if (exceptionDetails) {\n // A thrown non-Error has no description; its value beats \"Uncaught\".\n const thrown = exceptionDetails.exception;\n throw new Error(\n thrown?.description ??\n (thrown && \"value\" in thrown\n ? String(thrown.value)\n : exceptionDetails.text),\n );\n }\n return result.value;\n };\n}\n\n/** Cleanup must not replace the result of a render that already finished. */\nfunction removeProfile(profile: string): void {\n try {\n fs.rmSync(profile, {\n recursive: true,\n force: true,\n maxRetries: 5,\n retryDelay: 100,\n });\n } catch (error) {\n console.error(`could not remove browser profile ${profile}:`, error);\n }\n}\n\n/**\n * Start `executable` headless and connect to it. `timeoutMs` bounds startup\n * and every DevTools call `openPage` makes; each evaluate has its own.\n */\nexport async function launchBrowser(\n executable: string,\n timeoutMs: number,\n): Promise<Browser> {\n if (typeof globalThis.WebSocket === \"undefined\") {\n throw new AutoRigInputError(\n \"render_poses needs Node 22 or newer (the global WebSocket is missing).\",\n );\n }\n const profile = fs.mkdtempSync(path.join(os.tmpdir(), \"iki-render-\"));\n let child: ChildProcess;\n try {\n child = spawn(\n executable,\n [\n \"--headless=new\",\n \"--remote-debugging-port=0\",\n `--user-data-dir=${profile}`,\n \"--no-first-run\",\n \"--no-default-browser-check\",\n // Output pixel sizes must equal the plan's, whatever the display.\n \"--force-device-scale-factor=1\",\n // WebGL without a GPU; recent Chrome no longer falls back by itself.\n \"--enable-unsafe-swiftshader\",\n \"about:blank\",\n ],\n { stdio: [\"ignore\", \"ignore\", \"pipe\"] },\n );\n } catch (error) {\n // Some failures (ENOEXEC, EINVAL on Windows) throw instead of emitting.\n fs.rmSync(profile, { recursive: true, force: true });\n throw startError(executable, error as NodeJS.ErrnoException);\n }\n // Both in the spawn tick: a failed spawn is an `error` event, not a throw,\n // and `close` fires even when no `exit` does.\n let spawnError: NodeJS.ErrnoException | undefined;\n child.on(\"error\", (error) => {\n spawnError = error;\n });\n let exited = false;\n const closed = new Promise<void>((resolve) => {\n child.on(\"close\", () => {\n exited = true;\n resolve();\n });\n });\n const settle = (ms: number) =>\n within(closed, ms, \"browser close\").catch(() => {});\n\n // The server can die mid-render (SIGTERM, host gone); 'exit' handlers run\n // synchronously, so the browser and its profile do not outlive it.\n const onProcessExit = () => {\n child.kill(\"SIGKILL\");\n removeProfile(profile);\n };\n process.once(\"exit\", onProcessExit);\n\n let shutdownPromise: Promise<void> | undefined;\n const shutdown = () =>\n (shutdownPromise ??= (async () => {\n if (!exited) {\n child.kill();\n await settle(CLOSE_GRACE_MS);\n if (!exited) {\n child.kill(\"SIGKILL\");\n await settle(CLOSE_GRACE_MS);\n }\n }\n process.removeListener(\"exit\", onProcessExit);\n removeProfile(profile);\n })());\n\n let cdp: CdpClient;\n try {\n const endpoint = await waitForDevTools(\n child,\n closed,\n () => spawnError,\n executable,\n timeoutMs,\n );\n cdp = await connectCdp(endpoint, timeoutMs);\n } catch (error) {\n await shutdown();\n throw error;\n }\n\n return {\n openPage: () => openPage(cdp, timeoutMs),\n async close() {\n if (!exited) {\n // Best effort: a polite close lets Chrome flush; kill follows anyway.\n await cdp.send(\"Browser.close\", BROWSER_CLOSE_MS).catch(() => {});\n }\n await shutdown();\n },\n };\n}\n\n/** Launch, open a page, run `fn`, and always close the browser. */\nexport async function withBrowser<T>(\n executable: string,\n fn: (evaluate: Evaluate) => Promise<T>,\n): Promise<T> {\n const browser = await launchBrowser(executable, DEFAULT_TIMEOUT_MS);\n try {\n return await fn(await browser.openPage());\n } finally {\n await browser.close();\n }\n}\n","/**\n * Node (sharp-backed) re-host of the browser-only pixel functions used by the\n * auto-rig import flow. Only the DECODE/ENCODE halves are re-hosted here — the\n * alpha-bbox scan itself is shared with the browser path via\n * @ikijs/editor, so the two cannot drift. Still a controlled duplicate of:\n * - crop ← examples/editor/src/auto-rig-image.ts\n * - atlas render + edge-extrude ← examples/editor/src/atlas-image.ts\n * The pure parts (packAtlas / uvRectFor / generateIkiFromLayerSet / role parsing\n * / bbox→model math) are reused from @ikijs/editor, not reimplemented here.\n *\n * `sharp` is a heavy native dependency and MUST stay confined to @ikijs/mcp — it\n * may never reach @ikijs/editor, @ikijs/engine, or @ikijs/format.\n */\n\nimport sharp from \"sharp\";\nimport type { AtlasLayout } from \"@ikijs/editor\";\nimport { detectAlphaBbox as scanAlphaBbox } from \"@ikijs/editor\";\nimport { AutoRigInputError, MAX_INPUT_PIXELS } from \"./limits\";\n\nexport interface DecodedPng {\n width: number;\n height: number;\n /** Straight-alpha RGBA bytes, stride-4 (parity with canvas getImageData). */\n rgba: Buffer;\n /** Whether the FILE carried an alpha channel, before `.ensureAlpha()` added\n * one. A generated part without it is opaque on a white background and needs\n * that white keyed out before it can layer (see ./compose). */\n hasAlpha: boolean;\n}\n\n/**\n * Decode a PNG file to straight-alpha RGBA bytes + dimensions.\n *\n * Decode is an input boundary: a missing/corrupt/unsupported file or a\n * limitInputPixels overflow surfaces as a path-qualified AutoRigInputError so\n * the tool returns { ok:false } rather than { isError:true }.\n *\n * `.ensureAlpha()` promotes RGB PNGs to RGBA so the alpha scan matches the\n * browser canvas getImageData path (which is always RGBA).\n */\nexport async function decodePng(filePath: string): Promise<DecodedPng> {\n try {\n const pipeline = sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS });\n const metadata = await pipeline.metadata();\n if (metadata.format !== \"png\") {\n throw new AutoRigInputError(\n `non-PNG image (${metadata.format ?? \"unknown\"}): ${filePath}`,\n );\n }\n const { data, info } = await pipeline\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return {\n width: info.width,\n height: info.height,\n rgba: data,\n hasAlpha: metadata.hasAlpha ?? false,\n };\n } catch (e) {\n if (e instanceof AutoRigInputError) throw e;\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);\n }\n}\n\n/**\n * Node-side wrapper over the shared scan in @ikijs/editor: same bbox rule\n * as the browser path by construction, with this package's error type for an\n * empty layer.\n */\nexport function detectAlphaBbox(\n rgba: Buffer,\n width: number,\n height: number,\n): { x: number; y: number; w: number; h: number } {\n const bbox = scanAlphaBbox(rgba, width, height);\n if (bbox === null) {\n throw new AutoRigInputError(\"layer is empty after alpha threshold\");\n }\n return bbox;\n}\n\n/**\n * Crop the already-decoded RGBA to bbox, returning a PNG buffer. One decode per\n * file: the crop is taken from the raw RGBA, not a re-read of the file. Parity\n * with cropBitmap in examples/editor/src/auto-rig-image.ts.\n */\nexport function cropToBuffer(\n rgba: Buffer,\n width: number,\n height: number,\n bbox: { x: number; y: number; w: number; h: number },\n): Promise<Buffer> {\n return sharp(rgba, { raw: { width, height, channels: 4 } })\n .extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h })\n .png()\n .toBuffer();\n}\n\n/**\n * Draw `svg` over the image at `filePath` and return the composited PNG bytes.\n * The debug half of ./measure-turn: the measurement is only believable once the\n * boxes are seen sitting on the irises. The caller has already decoded the file\n * through {@link decodePng}, so a failure here is an encode/environment fault,\n * not caller input, and propagates as itself.\n */\nexport function encodeOverlayPng(\n filePath: string,\n svg: string,\n): Promise<Buffer> {\n return sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS })\n .composite([{ input: Buffer.from(svg) }])\n .png()\n .toBuffer();\n}\n\nexport interface AtlasCrop {\n id: string;\n buffer: Buffer;\n width: number;\n height: number;\n}\n\n/**\n * Composite packed crops onto a transparent page and return a base64 PNG data\n * URI. Each crop's right + bottom edge pixels are extruded across the padding\n * gutter (replicating renderAtlas's right/bottom/corner drawImage extrudes in\n * examples/editor/src/atlas-image.ts) so LINEAR sampling at the inset UV never\n * reads a transparent neighbor texel. packAtlas reserves padding on the RIGHT\n * and BOTTOM only, so a one-sided `extend` matches its layout exactly.\n *\n * Crops are looked up BY placement.id (packAtlas sorts placements by id).\n * ASSUMES a non-empty layout (the empty case is handled by the caller).\n *\n * `quantizeColors` palette-quantizes the page PNG (libimagequant via sharp).\n * Flat-shaded character art keeps its look at 256 colours while the atlas\n * drops to roughly a quarter of its lossless size — the hero demo went from\n * 3.5MB to 0.9MB at a mean channel delta of 1.5/255 — which is what makes a\n * generated model shippable on a page. Omitted = lossless, as before. Soft\n * alpha is where it fails: a shaded nose's feather rims in borrowed palette\n * entries, so the auto-rig renders the nose on its own page without it.\n * Splitting it off also changes how page 0 re-quantizes, so the size effect\n * is content-dependent — on the playground hero the split model came to\n * 1.28MB, about the same as the all-quantized 1.29MB and well under the\n * 3.18MB lossless model.\n */\nexport async function renderAtlasToDataUri(\n crops: AtlasCrop[],\n layout: AtlasLayout,\n quantizeColors?: number,\n): Promise<string> {\n const byId = new Map<string, AtlasCrop>();\n for (const crop of crops) byId.set(crop.id, crop);\n\n const pad = layout.padding;\n\n const composites = await Promise.all(\n layout.placements.map(async (placement) => {\n const crop = byId.get(placement.id);\n if (crop === undefined) {\n throw new AutoRigInputError(\n `no crop for atlas placement \"${placement.id}\"`,\n );\n }\n // Replicate the right + bottom (+ corner) edge pixels into the gutter.\n const input =\n pad > 0\n ? await sharp(crop.buffer)\n .extend({ right: pad, bottom: pad, extendWith: \"copy\" })\n .png()\n .toBuffer()\n : crop.buffer;\n return { input, left: placement.x, top: placement.y };\n }),\n );\n\n const page = await sharp({\n create: {\n width: layout.pageWidth,\n height: layout.pageHeight,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n })\n .composite(composites)\n .png(\n quantizeColors === undefined\n ? {}\n : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 },\n )\n .toBuffer();\n\n return `data:image/png;base64,${page.toString(\"base64\")}`;\n}\n","/**\n * Compose AI-generated part PNGs into canvas-aligned, role-named layers for the\n * Iki auto-rig (`auto_rig_from_layers` / `@ikijs/editor` generateIkiFromLayerSet).\n * Each part is alpha-trimmed, resized to a target width, optionally mirrored,\n * and pasted at a chosen center on a shared transparent canvas, CANVAS wide and\n * `canvasHeight` tall (CANVAS unless a full body sets it) — the nose by its\n * dense core, the drawing inside a soft nose's feather.\n *\n * Ports the composer that shipped as a script in the Claude Code plugin, so a\n * plugin user gets it from the MCP server instead of an ad-hoc `sharp` install.\n * Composing is deterministic: same parts -> same layers, so re-run freely after\n * tuning `layout` (no image re-generation needed).\n *\n * The mouth has two routes. `mouth.png` (+ optional `mouth_open.png`) is a\n * closed drawing and an open one that cross-fade. `mouth_keyed.png` (the open\n * mouth, its inside flat #00FF00) + `mouth_interior.png` is the lip set: the\n * composer keys and splits it into `mouth_inner` / `lip_lower` / `lip_upper` on\n * one frame (./compose-lips), which the rig folds open like an eyelid, and the\n * interior's light paint into `mouth_tongue` / `mouth_teeth` clipped to it.\n *\n * `sharp` must stay confined to @ikijs/mcp; part decoding goes through\n * ./node-images, this package's single image-decode boundary.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport sharp from \"sharp\";\nimport {\n ALPHA_OPAQUE,\n isLipInsideRole,\n detectAlphaBbox as scanAlphaBbox,\n} from \"@ikijs/editor\";\nimport { cropToBuffer, decodePng } from \"./node-images\";\nimport { TRIM_THRESHOLD, boxWithoutStraySpecks, luma } from \"./trim\";\nimport { measureDir, type MeasureReport, type NoseSpeck } from \"./measure\";\nimport { denseCoreOf, isSpeckCore } from \"./measure-turn\";\nimport {\n ARM_WIDTH,\n armPlacement,\n forearmPosePlacement,\n forearmPoseWidth,\n} from \"./compose-arms\";\nimport {\n INTERIOR_SRC,\n KEYED_SRC,\n closedLips,\n keyBorderWhite,\n keyGreen,\n prepInterior,\n restShiftOf,\n splitLipSet,\n} from \"./compose-lips\";\nimport {\n AutoRigInputError,\n MAX_CANVAS_DIM,\n resolveInputDir,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\n\n/**\n * The layer canvas's width, and its default height, in px. The width is NOT an\n * input: the layout defaults below place parts against it (hair_front alone is\n * 660px wide, and sharp rejects a composite input larger than its\n * destination), so a different width would need its own layout. The height is\n * `canvasHeight`: the canvas grows downward from this square, so every default\n * keeps its place. The tuning surface is `layout` overrides.\n */\nexport const CANVAS = 1100;\n\n/** The layer canvas, in px: CANVAS wide and `canvasHeight` tall. */\ninterface Canvas {\n width: number;\n height: number;\n}\n\n/**\n * The canvas as error messages name it: \"1100\" when square, as every message\n * did before the height could grow, and \"1100x3650\" when tall.\n */\nfunction canvasName(canvas: Canvas): string {\n return canvas.width === canvas.height\n ? `${canvas.width}`\n : `${canvas.width}x${canvas.height}`;\n}\n\n// Iris width as a fraction of the sclera width. Anime irises fill most of the\n// eye opening and are clipped by the lids — the auto-rig clips iris->sclera at\n// runtime, so a large iris cannot spill. The first sample's 32% iris read as a\n// bead floating in white; the defaults below are the hero bob's, 50px in a\n// 98px opening (0.51). A caller retunes eye size through\n// `layout.eye_L/eye_R.w` and MUST move `layout.iris_L/iris_R.w` with it to keep\n// that ratio.\nconst EYE_W = 98;\nconst IRIS_W = 50;\n\n/** The eyewhite source that prepEyeSplit() splits into sclera + lash. */\nconst EYEWHITE_SRC = \"eyewhite.png\";\n/** Luminance below this (0..255) = a dark lash/outline pixel in the eyewhite. */\nconst EYE_LASH_LUMA = 120;\n// Of the eye's dark pixels, those in the TOP this-fraction are the upper lash,\n// an arc that folds DOWN over the eye on blink instead of a full ring that\n// shrinks in place; those below it are the lower lid's line and lashes.\nconst LASH_KEEP_FRACTION = 0.5;\n// A light pixel whose red exceeds its blue by this much is the lid's skin, not\n// the white. Measured on five drawn eyewhites: each sclera's median r - b sits\n// between -11 (mint's blue-white) and 0, and each lid band's 5th percentile\n// between 37 and 55 (silver-hood's band 242,208,191, mint's 231,196,184). A\n// cool shade painted on the white (the test fixture's 200,205,225) runs blue\n// over red, so it can never match.\nconst EYE_LID_WARMTH = 30;\n\ninterface RoleLayout {\n /** Part file name in the parts dir (the eye pair's two are split in memory). */\n src: string;\n /** Center in canvas px, origin top-left, y down. */\n cx: number;\n cy: number;\n /** Target width in px. */\n w: number;\n /**\n * Target height in px. Omitted, the height follows the part's own aspect\n * ratio — which is the right default for every role whose drawing already has\n * the proportions it should. It exists for the one that does not: an eyewhite\n * comes back flatter than the reference often enough that three generations\n * asking for \"taller\" landed at 0.47, while stretching a flat white lens ~15%\n * is invisible and free. Set it on the sclera and its lash together or the\n * fold tears — they share one frame.\n */\n h?: number;\n optional?: boolean;\n mirror?: boolean;\n noTrim?: boolean;\n}\n\n/**\n * The nose's layout. Its `w`, `h` and `cx` size and place its dense core\n * (`denseCoreOf`), not its whole trimmed part: a soft nose is mostly feather,\n * and sized by its extent it renders as a dot. A part with no core, or whose\n * core is a speck of it (`isSpeckCore`: a lone nostril mark or highlight,\n * which sized to `w` would blow the whole nose up), is sized and placed whole\n * instead, and the speck is warned about. Unlike every other role's, its `cy`\n * is optional. Set, it is the core's centre row; absent, the core's bottom row\n * — the tip — lands NOSE_TIP_AT of the way from the eye row down to the\n * mouth's.\n */\ninterface NoseLayout extends Omit<RoleLayout, \"cy\"> {\n cy?: number;\n}\n\n/**\n * An arm's layout. Its `cx`, `cy` and `w` are optional, each derived from the\n * placed body when unset (compose-arms.ts): `w` is ARM_WIDTH of the body's\n * width, and an unset `cx` or `cy` hangs the arm's shoulder pivot, the one\n * the rig turns it about, on the body box's shoulder corner on that axis. A\n * set one keeps every other role's meaning. The pose forearms share its shape\n * with their own derivation (compose-arms.ts): an unset `w` scales the\n * forearm's elbow end to the placed arm's elbow run, and an unset `cx` or\n * `cy` pins its elbow-end pivot on the arm's elbow.\n */\nexport interface ArmLayout extends Omit<RoleLayout, \"cx\" | \"cy\" | \"w\"> {\n cx?: number;\n cy?: number;\n w?: number;\n}\n\n/** A box in a part's own px, origin top-left. */\ninterface Box {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/**\n * Where a nose with no `cy` puts its tip, as a fraction of the way from the\n * eye row down to the mouth's. Bob's: tip row 554 between eye row 475 and\n * mouth row 594 (79/119 ≈ 0.66), so the default rows land bob's nose where his\n * own layout placed it.\n */\nconst NOSE_TIP_AT = 0.66;\n\n// ── DEFAULT LAYOUT (tune per character through `layout`) ──────────────────────\n// These defaults assume the standard framing the character skill prompts for\n// (a front-facing face centred across the canvas, in its top CANVAS rows).\n// They are canvas px from the top-left, so a taller canvas only adds room\n// below them. The face, eyes, irises,\n// lashes, brows, nose and mouth are the hero bob's own tuning; bob wears his\n// blush at its default placement, picked on his face (below). The features'\n// defaults are proportions of the face: resolveLayout carries them with the\n// face's cx, cy and w. The hair and\n// the torso depend on the hairstyle and on how the torso is framed, so they are\n// older defaults every character retunes from the report. If the rendered model is misaligned, tune cx/cy/w through the\n// `layout` override and re-run — composing is cheap and the parts do not need\n// regenerating.\n//\n// eyeSide reminder: eye_L = character's LEFT eye = screen RIGHT (larger cx).\n// Which way a source faces is fixed by the mirror flags below, and \"left eye\"\n// cannot say it — it reads as the viewer's left or the character's. So in\n// image terms: eyewhite.png is the eye on the SCREEN LEFT, its lash wing (outer\n// corner) at the image's left end and its lash-free tear duct at the right;\n// brow.png is the brow on the SCREEN RIGHT, its thick head at the image's left\n// end and its tail at the right; blush.png is the blush on the SCREEN LEFT,\n// its outer end (toward the face's edge) at the image's left end and its\n// inner end (toward the nose) at the right; arm.png is the arm on the SCREEN\n// LEFT (the character's right), hanging, its shoulder at the image's top and\n// its hand at the bottom; forearm_pose.png is that arm's forearm raised, on\n// the SCREEN LEFT too: standing up from its elbow, the open hand at the\n// image's top with the thumb at its right (toward the body), a rounded\n// closed elbow end at the bottom. A part drawn the other way round is\n// flipped for free with `mirrorParts`.\n// eye_* = the WHITE sclera (upper lashes recolored white) = the blink clip mask + fold.\n// iris_* = colored disc on top, clipped to the sclera, drives gaze.\n// lash_lower_* = the lower lid's dark line and lashes, ABOVE the iris (it\n// covers the iris's bottom edge, as the drawing does) and folding\n// with the white. Placed on the eye's frame, so it has no layout key.\n// lash_* = the dark upper lashes, a separate layer ABOVE the iris that folds\n// down to cover the closed-eye seam. eye_*, lash_lower_* and lash_* are\n// split from a single `eyewhite.png` (white almond + dark lashes) by\n// prepEyeSplit().\nconst DEFAULT_LAYOUT = {\n // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir\n // without them still composes (head-only character).\n hair_back: { src: \"hair_back.png\", cx: 550, cy: 523, w: 800, optional: true },\n // The bust's torso, cut off by a square canvas's bottom, so the character is\n // not a floating head; a full body on a tall canvas sets `layout.body`\n // itself. It rides the rig's `bodyWarp`, which the head hangs from.\n body: { src: \"body.png\", cx: 550, cy: 1017, w: 840, optional: true },\n // The arms, one part for both: arm_R (screen left) takes arm.png as drawn\n // and arm_L mirrors it, like the blush. They draw over the body and under\n // the face. They have no cx/cy/w defaults: each is derived from the placed\n // body (ArmLayout). OPTIONAL and opt-in: a parts dir without arm.png\n // composes as a bust does, and `skipped` never lists them.\n arm_L: { src: \"arm.png\", optional: true, mirror: true },\n arm_R: { src: \"arm.png\", optional: true, mirror: false },\n // The face is drawn without a neck, so its box is the skull and centres\n // above the eye row (bob's skull at 437 against his eyes' 475).\n face: { src: \"face.png\", cx: 550, cy: 437, w: 400 },\n // The cheek blush, one part for both cheeks: blush_R (screen left) takes it\n // as drawn and blush_L mirrors it, like the eyewhite. It draws over the face\n // and under the nose. Its box sits below each eye, centred 5 px outside the\n // eye's centre and 55 px under its row, above the nose tip: on bob's face,\n // which narrows fast below the eye row, a 2:1 blush there stays on the\n // cheek through the turn, where one 26 px further out reached the ears.\n // OPTIONAL: a parts dir without it composes, and nothing reports it missing.\n blush_L: { src: \"blush.png\", cx: 641, cy: 530, w: 56, optional: true, mirror: true }, // prettier-ignore\n blush_R: { src: \"blush.png\", cx: 459, cy: 530, w: 56, optional: true, mirror: false }, // prettier-ignore\n // The nose, drawn on its own (the face is drawn without one): the auto-rig\n // leads the head turn with it and keys the other features' slide on its\n // presence, so without it the features stay on the face plate. `w` is the\n // width of its dense core, and it has no `cy`: its row comes from the tip\n // rule (NOSE_TIP_AT), between the eyes and the mouth, so it follows them\n // when they are retuned. OPTIONAL: a parts dir without it composes.\n nose: { src: \"nose.png\", cx: 550, w: 20, optional: true },\n mouth: { src: \"mouth.png\", cx: 550, cy: 594, w: 76 },\n // Cross-fades with `mouth` on ParamMouthOpenY (opacity, not scaleY) once the\n // auto-rig sees both roles. Same cx/w as `mouth` so the lip width matches;\n // its top edge (not center) lines up with the closed mouth's top edge since\n // the mouth opens downward from a fixed upper lip — hence the +2 cy nudge\n // rather than sharing cy outright. Optional: composes fine without it.\n mouth_open: {\n src: \"mouth_open.png\",\n cx: 550,\n cy: 596,\n w: 76,\n optional: true,\n },\n // The lip set's ONE frame, mouth_open's place: the keyed mouth is split into\n // mouth_inner / lip_lower / lip_upper, the interior's light paint into\n // mouth_tongue / mouth_teeth, and all of them land here, so a retune moves\n // them together. The other four have no key of their own (LIP_FRAME).\n // OPTIONAL and opt-in: with mouth_keyed.png + mouth_interior.png it stands\n // in for mouth and mouth_open.\n mouth_inner: {\n src: KEYED_SRC,\n cx: 550,\n cy: 596,\n w: 76,\n optional: true,\n },\n // eye_* (sclera) and lash_* share the eyewhite's cropped frame via noTrim (so\n // they are NOT re-bboxed independently): the upper lash stays anchored ABOVE\n // the sclera center, so on blink it folds DOWN over the eye like the sample\n // model instead of the whole eye shrinking in place. Same cx/cy/w.\n eye_L: { src: \"eyewhite_sclera.png\", cx: 636, cy: 475, w: EYE_W, mirror: true, noTrim: true }, // prettier-ignore\n eye_R: { src: \"eyewhite_sclera.png\", cx: 464, cy: 475, w: EYE_W, mirror: false, noTrim: true }, // prettier-ignore\n // A little under the white's centre and toward the nose, as bob's sits.\n iris_L: { src: \"iris.png\", cx: 631, cy: 480, w: IRIS_W, mirror: false },\n iris_R: { src: \"iris.png\", cx: 469, cy: 480, w: IRIS_W, mirror: false },\n lash_L: {\n src: \"eyewhite_lash.png\",\n cx: 636,\n cy: 475,\n w: EYE_W,\n mirror: true,\n noTrim: true,\n },\n lash_R: { src: \"eyewhite_lash.png\", cx: 464, cy: 475, w: EYE_W, mirror: false, noTrim: true }, // prettier-ignore\n brow_L: { src: \"brow.png\", cx: 645, cy: 405, w: 105, mirror: false },\n brow_R: { src: \"brow.png\", cx: 455, cy: 405, w: 105, mirror: true },\n hair_front: { src: \"hair_front.png\", cx: 550, cy: 425, w: 660 },\n // The pose forearms, one drawing for both: forearm_pose_R (screen left)\n // takes forearm_pose.png as drawn and forearm_pose_L mirrors it, like the\n // arms. The rig draws them above the face and the hair, so they come last.\n // No cx/cy/w defaults: an unset `w` scales the forearm's elbow end to the\n // placed arm's elbow run, an unset `cx` or `cy` pins its elbow-end pivot\n // on the arm's elbow (ArmLayout). OPTIONAL and opt-in, like the arms.\n forearm_pose_L: { src: \"forearm_pose.png\", optional: true, mirror: true },\n forearm_pose_R: { src: \"forearm_pose.png\", optional: true, mirror: false },\n} satisfies Record<string, RoleLayout | NoseLayout | ArmLayout>;\n\nexport type Role = keyof typeof DEFAULT_LAYOUT;\n\n/** The lower lash of each eye, and the eye whose placement it takes. */\nconst LOWER_LASH = { lash_lower_L: \"eye_L\", lash_lower_R: \"eye_R\" } as const;\n/** The eyewhite's lower lid, split in memory like the sclera and lash. */\nconst LOWER_LASH_SRC = \"eyewhite_lash_lower.png\";\n\n/** The lip set's other layers, and the role whose frame they are cut on. */\nconst LIP_FRAME = {\n mouth_tongue: \"mouth_inner\",\n mouth_teeth: \"mouth_inner\",\n lip_lower: \"mouth_inner\",\n lip_upper: \"mouth_inner\",\n} as const;\n\n/** A role the composer writes a layer for. */\nexport type LayerRole = Role | keyof typeof LOWER_LASH | keyof typeof LIP_FRAME;\n\n/** The arm roles, placed off the body (ArmLayout). */\ntype ArmRole = \"arm_L\" | \"arm_R\";\n/** The pose forearm roles, placed off their arm's elbow (ArmLayout). */\ntype PoseRole = \"forearm_pose_L\" | \"forearm_pose_R\";\n\n/**\n * The merged layout, typed so a default other than the nose's, the arms' and\n * the pose forearms' that drops its `cy` fails to compile: `resolveLayout` builds it from\n * DEFAULT_LAYOUT.\n */\ntype ResolvedLayout = Record<\n Exclude<Role, \"nose\" | ArmRole | PoseRole>,\n RoleLayout\n> & {\n nose: NoseLayout;\n} & Record<ArmRole | PoseRole, ArmLayout>;\n\n/**\n * Draw order (back -> front): the roles of @ikijs/editor ROLE_TABLE the\n * composer writes, in its order — a test holds it to that subsequence.\n */\nexport const ORDER: LayerRole[] = [\n \"hair_back\",\n \"body\",\n \"arm_L\",\n \"arm_R\",\n \"face\",\n \"blush_L\",\n \"blush_R\",\n \"nose\",\n \"mouth\",\n \"mouth_open\",\n \"mouth_inner\",\n \"mouth_tongue\",\n \"mouth_teeth\",\n \"lip_lower\",\n \"lip_upper\",\n \"eye_L\",\n \"eye_R\",\n \"iris_L\",\n \"iris_R\",\n \"lash_lower_L\",\n \"lash_lower_R\",\n \"lash_L\",\n \"lash_R\",\n \"brow_L\",\n \"brow_R\",\n \"hair_front\",\n \"forearm_pose_L\",\n \"forearm_pose_R\",\n];\n\n/**\n * The part files a parts dir holds: every source the layout reads from disk,\n * and the eyewhite the eye pair is split from in memory.\n */\nconst PART_FILES = [\n ...new Set(\n Object.values(DEFAULT_LAYOUT)\n .map((cfg) => cfg.src)\n .filter((src) => !src.startsWith(\"eyewhite_\")),\n ),\n EYEWHITE_SRC,\n INTERIOR_SRC,\n];\n\n/** Per-role placement overrides; anything omitted keeps the default above. */\nexport type LayoutOverride = Partial<\n Record<Role, { cx?: number; cy?: number; w?: number; h?: number }>\n>;\n\nexport interface ComposeInput {\n /** Directory of the generated part PNGs (relative paths resolve against cwd). */\n partsDir: string;\n /**\n * Existing directory under cwd to write the role layers into. Callers reuse\n * one across runs (it must pre-exist), so the compose leaves it holding\n * exactly the roles it reports: the layer an earlier run wrote for any role\n * this run does not write — a skipped role, or an arm once arm.png is gone\n * — is removed rather than left for the next tool to pick up.\n */\n outDir: string;\n layout?: LayoutOverride;\n /**\n * Part files to flip left-right as they are read, e.g. `[\"eyewhite.png\"]`\n * for an eye drawn facing the other way. It flips the SOURCE, so every role\n * cut from it flips together — the eye pair's sclera and lash stay in one\n * frame, which a per-role flag would leave to the caller to keep in sync.\n */\n mirrorParts?: string[];\n /**\n * The canvas's height in px: an even integer in CANVAS..MAX_CANVAS_DIM,\n * CANVAS (a square bust canvas) when omitted, and every output at CANVAS is\n * byte-identical to an omitted one. The width stays CANVAS. The canvas grows\n * downward: every default and every override keeps its canvas px from the\n * top-left, so the head lands where it does on a bust and a full body gets\n * room below. Model space is centred on the canvas, so an odd height, which\n * would put the head on a half pixel, is refused.\n */\n canvasHeight?: number;\n}\n\nexport interface ComposedLayer {\n role: LayerRole;\n path: string;\n /** Size of the placed part itself (the file is always CANVAS x the canvas\n * height). */\n width: number;\n height: number;\n left: number;\n top: number;\n}\n\nexport type ComposeResult =\n | {\n ok: true;\n outDir: string;\n layers: ComposedLayer[];\n /**\n * Roles whose optional part was absent from the parts dir, and the lower\n * lashes when the eyewhite draws no dark lower lid. The arms and the\n * pose forearms are opt-in and never listed: a parts dir without\n * arm.png composes as a bust does, though an earlier compose's arm\n * layers are still removed. The lip roles are never listed either, and\n * with the lip set neither are `mouth` and `mouth_open`, which the set\n * stands in for.\n */\n skipped: LayerRole[];\n /** The rest pose, flattened: a pose forearm is invisible there, so it\n * never shows in this one, and the lip set shows closed, as the rig\n * draws the rest pose. */\n preview: string;\n /** Written only with a pose forearm: the switch at 1 as the rig draws\n * it — each arm with a pose forearm cropped to the rows above its\n * elbow (the hanging forearm hidden), the pose forearms over\n * everything. */\n previewPose?: string;\n measure: MeasureReport;\n }\n | { ok: false; error: string };\n\n/**\n * The roles drawn on the face, but the nose (resolveLayout places it on its\n * own). Their defaults are placed relative to the face's: a layout that moves\n * or scales the face carries them with it.\n */\nconst FACE_FEATURES = [\n \"blush_L\",\n \"blush_R\",\n \"mouth\",\n \"mouth_open\",\n \"mouth_inner\",\n \"eye_L\",\n \"eye_R\",\n \"iris_L\",\n \"iris_R\",\n \"lash_L\",\n \"lash_R\",\n \"brow_L\",\n \"brow_R\",\n] as const satisfies readonly Exclude<Role, \"nose\">[];\n\n/**\n * Merge caller overrides onto the defaults. Input boundary: an unknown role, a\n * non-finite centre or an out-of-range width or height fails fast,\n * path-qualified, before any decode. `w` is capped at the canvas's width and\n * `h` at its height, so a part sized whole can never exceed the canvas width\n * (a nose, sized by its core, is checked in partBuffer); `cx`/`cy` are\n * unbounded here because a part may legitimately hang off an edge —\n * assertOnCanvas() rejects the one that lands nowhere on it.\n *\n * The face's override applies first. Each feature's default is then moved\n * with the face's centre and scaled by its width against the default face's,\n * so the defaults are proportions of the face; a feature's own override still\n * names canvas px.\n */\nfunction resolveLayout(\n overrides: LayoutOverride | undefined,\n canvas: Canvas,\n): ResolvedLayout {\n const resolved: ResolvedLayout = { ...DEFAULT_LAYOUT };\n if (overrides === undefined) return resolved;\n const sets = new Map<\n Role,\n { cx?: number; cy?: number; w?: number; h?: number }\n >();\n for (const [role, override] of Object.entries(overrides)) {\n if (!Object.prototype.hasOwnProperty.call(DEFAULT_LAYOUT, role)) {\n throw new AutoRigInputError(\n `layout.${role}: unknown role — expected one of ${Object.keys(DEFAULT_LAYOUT).join(\", \")}`,\n );\n }\n if (override === undefined) continue;\n // Only the fields the override sets: spread over the entry, an explicit\n // undefined would erase the default it leaves alone.\n const set: { cx?: number; cy?: number; w?: number; h?: number } = {};\n for (const field of [\"cx\", \"cy\"] as const) {\n const value = override[field];\n if (value === undefined) continue;\n if (!Number.isFinite(value)) {\n throw new AutoRigInputError(\n `layout.${role}.${field} must be a finite number, got ${String(value)}`,\n );\n }\n set[field] = value;\n }\n for (const field of [\"w\", \"h\"] as const) {\n const value = override[field];\n if (value === undefined) continue;\n const max = field === \"w\" ? canvas.width : canvas.height;\n if (!Number.isInteger(value) || value < 1 || value > max) {\n throw new AutoRigInputError(\n `layout.${role}.${field} must be an integer in 1..${max}, got ${String(value)}`,\n );\n }\n set[field] = value;\n }\n sets.set(role as Role, set);\n }\n const face = { ...resolved.face, ...sets.get(\"face\") };\n resolved.face = face;\n const base = DEFAULT_LAYOUT.face;\n const scale = face.w / base.w;\n const x = (cx: number) => face.cx + (cx - base.cx) * scale;\n const w = (width: number) => Math.max(1, Math.round(width * scale));\n for (const role of FACE_FEATURES) {\n const d = DEFAULT_LAYOUT[role];\n const cy = face.cy + (d.cy - base.cy) * scale;\n resolved[role] = { ...d, cx: x(d.cx), cy, w: w(d.w), ...sets.get(role) };\n }\n // The nose has no default cy (the tip rule places it, off the eye and\n // mouth rows above), so it merges on its own.\n const nose = DEFAULT_LAYOUT.nose;\n resolved.nose = {\n ...nose,\n cx: x(nose.cx),\n w: w(nose.w),\n ...sets.get(\"nose\"),\n };\n for (const [role, set] of sets) {\n if (role === \"face\" || role === \"nose\") continue;\n if ((FACE_FEATURES as readonly Role[]).includes(role)) continue;\n mergeRole(resolved, role, set);\n }\n return resolved;\n}\n\n/**\n * Merge an override's set fields onto a role's resolved entry. Generic over\n * the role so one statement types for every kind of entry, the arms' among\n * them, whose cx/cy/w may stay unset.\n */\nfunction mergeRole<R extends Role>(\n resolved: ResolvedLayout,\n role: R,\n set: { cx?: number; cy?: number; w?: number; h?: number },\n): void {\n resolved[role] = { ...resolved[role], ...set };\n}\n\n/**\n * Input boundary for `canvasHeight`: an even integer in CANVAS..MAX_CANVAS_DIM,\n * CANVAS when omitted. Model space is centred on the canvas, so an odd height\n * would put the head on a half pixel.\n */\nfunction resolveCanvasHeight(value: number | undefined): number {\n if (value === undefined) return CANVAS;\n if (\n !Number.isInteger(value) ||\n value % 2 !== 0 ||\n value < CANVAS ||\n value > MAX_CANVAS_DIM\n ) {\n throw new AutoRigInputError(\n `canvasHeight must be an even integer in ${CANVAS}..${MAX_CANVAS_DIM}, got ${String(value)}`,\n );\n }\n return value;\n}\n\n/**\n * Input boundary for `mirrorParts`: a name that is not a part file (a typo, or\n * a role such as `eye_L`) would otherwise flip nothing and read as success.\n */\nfunction resolveMirrorParts(names: string[] | undefined): Set<string> {\n const mirrored = new Set<string>();\n for (const [i, name] of (names ?? []).entries()) {\n if (!PART_FILES.includes(name)) {\n throw new AutoRigInputError(\n `mirrorParts[${i}]: unknown part ${JSON.stringify(name)} — expected one of ${PART_FILES.join(\", \")}`,\n );\n }\n mirrored.add(name);\n }\n return mirrored;\n}\n\n/**\n * Some generated parts come back opaque on a white background (no alpha).\n * Key near-white pixels to transparent so they can layer cleanly.\n */\nfunction keyWhiteToAlpha(rgba: Buffer): Buffer {\n const keyed = Buffer.from(rgba);\n for (let i = 0; i < keyed.length; i += 4) {\n if (keyed[i] > 238 && keyed[i + 1] > 238 && keyed[i + 2] > 238) {\n keyed[i + 3] = 0;\n }\n }\n return keyed;\n}\n\n/** A PNG part's dense core (`null` when no pixel reaches the core's alpha)\n * and its own bounds, both in its own px. */\nasync function coreAndBoundsOf(\n png: Buffer,\n): Promise<{ core: Box | null; bounds: Box }> {\n const { data, info } = await sharp(png)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return {\n core: denseCoreOf(data, info.width, info.height),\n bounds: { x: 0, y: 0, w: info.width, h: info.height },\n };\n}\n\n/** Whether a part keeps a pixel the auto-rig counts as coverage. */\nasync function hasCoverage(png: Buffer): Promise<boolean> {\n const { data, info } = await sharp(png)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return scanAlphaBbox(data, info.width, info.height) !== null;\n}\n\n/** What a nose part's layout sizes, decided on the trimmed source part. */\ninterface NoseSizing {\n /** The box layout `w`/`h` size, in the trimmed source part's px (not the\n * resized part's). */\n box: Box;\n /** The whole part stood in for the core: it has none, or it is a speck. */\n whole: boolean;\n /** The core's and the part's sizes when a speck was the reason. */\n speck?: NoseSpeck;\n}\n\n/**\n * What a nose part's layout sizes: its dense core, in its own px — or its own\n * bounds, so it is sized and placed whole, when no pixel reaches the core's\n * alpha (a nose painted wholly translucent) or the core is a speck of those\n * bounds (`isSpeckCore`).\n */\nasync function noseSizingOf(png: Buffer): Promise<NoseSizing> {\n const { core, bounds } = await coreAndBoundsOf(png);\n if (core === null) return { box: bounds, whole: true };\n if (isSpeckCore(core, bounds)) {\n return {\n box: bounds,\n whole: true,\n speck: {\n core: { w: core.w, h: core.h },\n part: { w: bounds.w, h: bounds.h },\n },\n };\n }\n return { box: core, whole: false };\n}\n\n/** A part trimmed and flipped, not yet resized: a PNG and its size. */\ninterface Trimmed {\n data: Buffer;\n w: number;\n h: number;\n}\n\n/**\n * Trim/mirror a part, ready to be resized (`sizedPart`). `inMemory` carries\n * the eye pair's two split buffers and the lip set's keyed mouth; every other\n * role is read from the parts dir. `flipSource` is a `mirrorParts` entry for\n * the file the role is cut from. A pose forearm is measured between this and\n * the resize, to learn the width that fits it to its arm.\n * Missing optional part -> null; missing required part -> AutoRigInputError.\n */\nasync function trimmedPart(\n role: LayerRole,\n cfg: Omit<RoleLayout, \"cx\" | \"cy\" | \"w\">,\n partsDir: string,\n inMemory: Buffer | undefined,\n flipSource: boolean,\n): Promise<Trimmed | null> {\n let img: sharp.Sharp;\n if (inMemory !== undefined) {\n img = sharp(inMemory);\n } else {\n const srcPath = path.join(partsDir, cfg.src);\n if (!fs.existsSync(srcPath)) {\n // An optional role's part may be absent from the parts dir; the\n // auto-rig only requires face/eye_L/eye_R/mouth.\n if (cfg.optional) return null;\n // Name the role, not just the file: one source feeds two roles\n // (brow.png -> brow_L/brow_R), so the path alone does not say what broke.\n throw new AutoRigInputError(\n `missing part source for role \"${role}\": ${srcPath}` +\n (role === \"mouth\"\n ? \" — draw mouth.png (with mouth_open.png), or the lip set's mouth_keyed.png + mouth_interior.png\"\n : \"\"),\n );\n }\n const png = await decodePng(srcPath);\n // decodePng is the package's decode boundary: it caps the source at\n // MAX_INPUT_PIXELS and reports a bad/corrupt file as a path-qualified\n // AutoRigInputError, so the raw re-wrap below is already bounded.\n img = sharp(png.hasAlpha ? png.rgba : keyWhiteToAlpha(png.rgba), {\n raw: { width: png.width, height: png.height, channels: 4 },\n });\n }\n // noTrim parts (the eye and lash pairs) keep their shared pre-cropped frame so\n // sclera and lash stay aligned; everything else is alpha-trimmed to its own\n // bbox, less any stray speck beside the drawing.\n if (!cfg.noTrim) {\n // The rest of the pipeline reads this trimmed raw, so the source is\n // decoded and trimmed once. Only file sources and the keyed mouth are\n // trimmed (the eye pair's halves are noTrim), and the file sources are\n // raw already, so a part with no stray speck composes byte-identically.\n const kept = await img\n .trim({ threshold: TRIM_THRESHOLD })\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n const { width: keptW, height: keptH } = kept.info;\n img = sharp(kept.data, {\n raw: { width: keptW, height: keptH, channels: 4 },\n });\n const box = boxWithoutStraySpecks(kept.data, keptW, keptH);\n if (box !== null) img = img.extract(box);\n }\n // A flipped source under a mirrored role cancels out. sharp's flop() sets a\n // flag rather than toggling it, so the two cannot simply be applied in turn.\n if ((cfg.mirror ?? false) !== flipSource) img = img.flop();\n // Materialise the trimmed part BEFORE resizing: its size is bounded by the\n // source decode limit, so the size the resize WOULD produce can be checked\n // against the canvas while only the bounded buffer is allocated.\n const trimmed = await img.png().toBuffer({ resolveWithObject: true });\n return {\n data: trimmed.data,\n w: trimmed.info.width,\n h: trimmed.info.height,\n };\n}\n\n/**\n * Resize a trimmed part to its layout width. The nose is resized so its dense\n * core, not its whole part, comes out `w` wide (and `h` tall when set),\n * unless its whole part stood in for the core. Either way the nose's sizing\n * decision (`noseSizingOf`) always comes back as `nose`, and no other role\n * has one.\n */\nasync function sizedPart(\n role: LayerRole,\n cfg: Omit<RoleLayout, \"cx\" | \"cy\">,\n trimmed: Trimmed,\n canvas: Canvas,\n): Promise<{ buf: Buffer; w: number; h: number; nose?: NoseSizing }> {\n const { w: trimmedW, h: trimmedH } = trimmed;\n // What `w`/`h` size: the nose's dense core, measured on the trimmed, flipped\n // part — the whole part scales with it, feather and all — or that whole\n // part when it has no core or the core is a speck, and every other role's\n // whole part.\n const nose = role === \"nose\" ? await noseSizingOf(trimmed.data) : undefined;\n const sized = nose?.box ?? { x: 0, y: 0, w: trimmedW, h: trimmedH };\n const width = Math.round((trimmedW * cfg.w) / sized.w);\n const height =\n cfg.h === undefined\n ? Math.round((trimmedH * width) / trimmedW)\n : Math.round((trimmedH * cfg.h) / sized.h);\n // resolveLayout bounds w and an explicit h, so for a part sized whole only\n // the aspect-derived height can run past the canvas; a nose sized by its\n // core can overrun either dimension.\n if (width > canvas.width || height > canvas.height) {\n const field = width > canvas.width || cfg.h === undefined ? \"w\" : \"h\";\n throw new AutoRigInputError(\n `layout.${role}.${field}: resized part ${width}x${height} exceeds the ${canvasName(canvas)} canvas`,\n );\n }\n const resized = await sharp(trimmed.data)\n // Width alone keeps the source aspect. With h, fit:\"fill\" is the point —\n // stretch to the given box instead. Both options stay off the width-only\n // path: passing height:undefined alongside fit:\"fill\" makes sharp drop the\n // aspect it would otherwise preserve.\n .resize(cfg.h === undefined ? { width } : { width, height, fit: \"fill\" })\n .png()\n .toBuffer({ resolveWithObject: true });\n return {\n buf: resized.data,\n w: resized.info.width,\n h: resized.info.height,\n nose,\n };\n}\n\n/**\n * Trim/mirror a part and resize it to its layout width: `trimmedPart` then\n * `sizedPart`. Missing optional part -> null; missing required part ->\n * AutoRigInputError.\n */\nasync function partBuffer(\n role: LayerRole,\n cfg: Omit<RoleLayout, \"cx\" | \"cy\">,\n partsDir: string,\n inMemory: Buffer | undefined,\n flipSource: boolean,\n canvas: Canvas,\n): Promise<{ buf: Buffer; w: number; h: number; nose?: NoseSizing } | null> {\n const trimmed = await trimmedPart(role, cfg, partsDir, inMemory, flipSource);\n return trimmed === null ? null : sizedPart(role, cfg, trimmed, canvas);\n}\n\n/**\n * Refuse a placed part that lands nowhere on the canvas. Running off an edge is\n * legitimate — a bust's `body` is meant to be cut off by the canvas bottom — so\n * the test is INTERSECTION, not containment. A part that misses the canvas\n * entirely composes to a fully transparent layer that nothing downstream flags\n * (measureDir warns per measured layer, and an empty one has no geometry), so a\n * sign-flipped centre would otherwise read as success.\n */\nfunction assertOnCanvas(\n source: string,\n w: number,\n h: number,\n left: number,\n top: number,\n canvas: Canvas,\n): void {\n if (\n left + w <= 0 ||\n top + h <= 0 ||\n left >= canvas.width ||\n top >= canvas.height\n ) {\n throw new AutoRigInputError(\n `${source}: the placed part (${w}x${h} at ${left},${top}) falls entirely outside the ${canvasName(canvas)} canvas`,\n );\n }\n}\n\n/** Where a part lands, centred on its layout cx/cy. The nose has its own. */\nfunction placement(\n role: Exclude<Role, \"nose\" | ArmRole | PoseRole>,\n cfg: RoleLayout,\n w: number,\n h: number,\n canvas: Canvas,\n) {\n const left = Math.round(cfg.cx - w / 2);\n const top = Math.round(cfg.cy - h / 2);\n assertOnCanvas(`layout.${role}.cx/cy`, w, h, left, top, canvas);\n return { left, top };\n}\n\n/**\n * Where the nose lands: by the box it was sized by (`noseSizingOf`), in the\n * resized part's px — its dense core, or its whole bounds when those stood in.\n * `cx` centres the box's columns. A set `cy` centres its rows; absent, its\n * bottom row — the tip, the last row index at alpha ≥ 128 — lands on\n * round(E + NOSE_TIP_AT·(M − E)), E the eyes' mean row and M the mouth's. A\n * box's centre is `x + w/2`, as placement() takes it: pixel x covers\n * [x, x + 1).\n */\nfunction nosePlacement(\n layout: ResolvedLayout,\n mouthKey: \"mouth\" | \"mouth_inner\",\n box: Box,\n w: number,\n h: number,\n canvas: Canvas,\n) {\n const { cx, cy } = layout.nose;\n const left = Math.round(cx - (box.x + box.w / 2));\n let top: number;\n if (cy !== undefined) {\n top = Math.round(cy - (box.y + box.h / 2));\n } else {\n const eyeRow = (layout.eye_L.cy + layout.eye_R.cy) / 2;\n const tipRow = Math.round(\n eyeRow + NOSE_TIP_AT * (layout[mouthKey].cy - eyeRow),\n );\n top = tipRow - (box.y + box.h - 1);\n }\n assertOnCanvas(\n cy !== undefined\n ? \"layout.nose.cx/cy\"\n : `layout.nose.cx/cy (cy unset: its tip row comes from layout.eye_L/eye_R/${mouthKey}.cy)`,\n w,\n h,\n left,\n top,\n canvas,\n );\n return { left, top };\n}\n\nfunction blankCanvas(canvas: Canvas) {\n return sharp({\n create: {\n width: canvas.width,\n height: canvas.height,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n });\n}\n\n/**\n * The eyewhite's light ink drawn detached above its white, as a row-major\n * mask (1 = detached). Light ink is non-transparent at luma EYE_LASH_LUMA or\n * over. Its sets are 8-connected through visibly painted pixels only (alpha\n * ALPHA_OPAQUE or over), so a faint antialiased pixel between a crease and\n * the white does not join them. Each fainter pixel is fringe of the nearest\n * painted set it reaches through faint pixels whose alpha never rises on the\n * way (ties go to the set met first in row-major order, the higher one).\n * Antialiasing fades away from what it edges, so a translucent stroke past a\n * fainter halo does not become the fringe of the set the halo edges. Faint\n * ink that no painted set reaches this way forms sets of its own. So does a\n * noisy faint pixel brighter than every claimed neighbour and touching no\n * painted pixel: above the white's top, it is dropped. The white is the\n * largest painted set. Another set is detached above it when each of its own\n * pixels, fringe aside, lies above the white's topmost painted pixel in its\n * column, or, past either end of the white, above the top of that end's\n * column; it goes with its fringe. A crease often runs on past the eye's\n * corners, and judged only over the white, one pixel out there would keep\n * the whole crease. A shade painted on the white touches it, so it is part\n * of the white; a mark below the white, or beside an end and level with it,\n * is left.\n */\nfunction detachedAboveWhite(rgba: Buffer, W: number, H: number): Uint8Array {\n const n = W * H;\n // 2 = painted light ink, 1 = fainter light ink, 0 = neither.\n const ink = new Uint8Array(n);\n for (let p = 0; p < n; p++) {\n const alpha = rgba[p * 4 + 3];\n if (alpha > 0 && luma(rgba, p * 4) >= EYE_LASH_LUMA)\n ink[p] = alpha >= ALPHA_OPAQUE ? 2 : 1;\n }\n const label = new Int32Array(n).fill(-1);\n // A pixel is labelled as it is pushed, so it is pushed once and neither the\n // flood fill's stack nor the fringe's queue outgrows the image.\n const stack = new Int32Array(n);\n const near = (p: number, visit: (q: number) => void) => {\n const px = p % W;\n const py = (p - px) / W;\n for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {\n for (let x = Math.max(0, px - 1); x <= Math.min(W - 1, px + 1); x++) {\n visit(y * W + x);\n }\n }\n };\n const sizes: number[] = [];\n const fill = (start: number) => {\n const id = sizes.length;\n let size = 0;\n let depth = 0;\n label[start] = id;\n stack[depth++] = start;\n while (depth > 0) {\n const p = stack[--depth];\n size++;\n near(p, (q) => {\n if (ink[q] === ink[start] && label[q] === -1) {\n label[q] = id;\n stack[depth++] = q;\n }\n });\n }\n sizes.push(size);\n };\n for (let p = 0; p < n; p++) if (ink[p] === 2 && label[p] === -1) fill(p);\n const paintedSets = sizes.length;\n // The fringe: breadth-first from every painted pixel at once, each faint\n // pixel no more opaque than the one before taking the set that reaches it\n // first.\n let head = 0;\n let tail = 0;\n for (let p = 0; p < n; p++) if (ink[p] === 2) stack[tail++] = p;\n while (head < tail) {\n const p = stack[head++];\n near(p, (q) => {\n if (\n ink[q] === 1 &&\n label[q] === -1 &&\n rgba[q * 4 + 3] <= rgba[p * 4 + 3]\n ) {\n label[q] = label[p];\n stack[tail++] = q;\n }\n });\n }\n for (let p = 0; p < n; p++) if (ink[p] === 1 && label[p] === -1) fill(p);\n\n const detached = new Uint8Array(n);\n if (paintedSets === 0 || sizes.length < 2) return detached;\n let white = 0;\n for (let id = 1; id < paintedSets; id++) {\n if (sizes[id] > sizes[white]) white = id;\n }\n // A set's own pixels: a painted set's painted ones, a faint set's all.\n const own = (p: number) => ink[p] === 2 || label[p] >= paintedSets;\n // The white's topmost painted row per column (the scan is row-major, so\n // the first pixel met is the top).\n const whiteTop = new Int32Array(W).fill(-1);\n for (let p = 0; p < n; p++) {\n const x = p % W;\n if (label[p] === white && own(p) && whiteTop[x] === -1)\n whiteTop[x] = (p - x) / W;\n }\n // An 8-connected set covers one unbroken run of columns, so every column\n // the white misses lies past one of its ends and takes that end's top.\n let first = 0;\n while (whiteTop[first] === -1) first++;\n let last = W - 1;\n while (whiteTop[last] === -1) last--;\n whiteTop.fill(whiteTop[first], 0, first);\n whiteTop.fill(whiteTop[last], last + 1);\n const above = new Uint8Array(sizes.length).fill(1);\n for (let p = 0; p < n; p++) {\n const id = label[p];\n if (id === -1 || id === white || !own(p)) continue;\n const x = p % W;\n if ((p - x) / W >= whiteTop[x]) above[id] = 0;\n }\n for (let p = 0; p < n; p++) {\n const id = label[p];\n if (id !== -1 && id !== white && above[id]) detached[p] = 1;\n }\n return detached;\n}\n\n/**\n * Split eyewhite.png (white almond + dark lashes) into a sclera (the upper\n * lash recolored to white; the whole drawing's alpha = the blink clip-mask\n * shape), a dark UPPER-lash layer and a dark LOWER-lid layer. All are cropped\n * to the SAME eye bbox so they stay aligned (consumed with noTrim): the lash\n * arc keeps its position at the top of the sclera, so on blink it folds DOWN\n * over the eye rather than the eye shrinking in place.\n *\n * The lower lid's dark line and lashes stay in the sclera as drawn and are\n * copied into their own layer, which draws over the iris. Recolored white they\n * would show as white flicks wherever a lash hangs below the white, and left\n * in the sclera alone the iris would paint over the line. The sclera keeps\n * them so its alpha, which the rig measures the eye by, is the drawing's.\n * `lashLower` is null when the eyewhite draws no dark pixel below the upper\n * lash's fraction.\n *\n * A light mark drawn detached above the white, such as a double-eyelid crease,\n * is dropped from the sclera (`detachedAboveWhite`). The sclera is the iris's\n * clip, and at half blink the fold carries such a mark down into the iris's\n * path. The frame is still the source's alpha bbox, crease and all, so the\n * layout places the pair where it did before.\n *\n * The lid's skin drawn as a band over the lash is dropped from the sclera too.\n * It meets the white at the corners, so the detached rule keeps it as the\n * white's; left in the clip, the rig's `blinkFold` carries it over the iris's\n * rows at half blink, where the lash its `lashFold` folds does not cover it,\n * and a taller iris shows through it above the lash at rest. The cut takes\n * only warm skin (painted, light, red over blue by EYE_LID_WARMTH) above the\n * lowest dark row over the white, in the columns that have a lash there.\n * Its limits: a band drawn over a lash-free column (the tear duct, the\n * corners) stays, since there colour alone cannot tell it from the white's\n * own warm shading or caruncle; a lid as cool as the white is not told apart\n * from it; the band's antialiased edge\n * under alpha ALPHA_OPAQUE is not cut, so it stays in the clip as the white's\n * fringe, a faint outline of the band; and a sclera tinted warmer than the\n * rule everywhere has no white top, so it is left whole. The frame is\n * unchanged.\n *\n * Both come back as PNG buffers. The script this ports wrote them back into the\n * parts dir, but that dir is an INPUT here (reads are deliberately unconfined),\n * so the tool never writes there — only under the confined outDir.\n */\nasync function prepEyeSplit(\n partsDir: string,\n): Promise<{ sclera: Buffer; lash: Buffer; lashLower: Buffer | null }> {\n const srcPath = path.join(partsDir, EYEWHITE_SRC);\n if (!fs.existsSync(srcPath)) {\n throw new AutoRigInputError(`missing eyewhite source: ${srcPath}`);\n }\n const { width: W, height: H, rgba: data } = await decodePng(srcPath);\n\n // Eye content bbox (alpha) → the shared cropped frame for both outputs.\n let minX = W;\n let minY = H;\n let maxX = -1;\n let maxY = -1;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n if (data[(y * W + x) * 4 + 3] > 8) {\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n }\n }\n if (maxX < 0) {\n throw new AutoRigInputError(`eyewhite is fully transparent: ${srcPath}`);\n }\n // Dark pixels above this row are the upper lash; below it, the lower lid.\n const lashCutoffY = minY + LASH_KEEP_FRACTION * (maxY - minY + 1);\n const detached = detachedAboveWhite(data, W, H);\n const isDark = (i: number) =>\n data[i + 3] > 0 && luma(data, i) < EYE_LASH_LUMA;\n const isLight = (i: number) =>\n data[i + 3] >= ALPHA_OPAQUE && luma(data, i) >= EYE_LASH_LUMA;\n const isWarm = (i: number) => data[i] - data[i + 2] >= EYE_LID_WARMTH;\n // Each column's white top: its first painted, light, cool pixel that is not\n // a mark detached above the white (a cool crease would stop the cut).\n const whiteTop = new Int32Array(W).fill(-1);\n for (let x = 0; x < W; x++) {\n for (let y = 0; y < H; y++) {\n const i = (y * W + x) * 4;\n if (!detached[y * W + x] && isLight(i) && !isWarm(i)) {\n whiteTop[x] = y;\n break;\n }\n }\n }\n // The columns outside the outermost two with a white top take the nearer\n // one's. A column between them with no cool pixel stays -1 and is left\n // uncut, and with no white top anywhere nothing is cut.\n let first = 0;\n while (first < W && whiteTop[first] === -1) first++;\n if (first < W) {\n let last = W - 1;\n while (whiteTop[last] === -1) last--;\n whiteTop.fill(whiteTop[first], 0, first);\n whiteTop.fill(whiteTop[last], last + 1);\n }\n // The row the lid's skin is cut above: the lowest dark row over the white,\n // in a column with one only (-1: no cut). Any dark pixel counts, a lash\n // tail hanging past lashCutoffY too, so a misread keeps skin rather than\n // cutting under the lash. A lash-free column is never cut: there a lid band\n // and the white's own warm shading or caruncle sit on the white alike.\n const lidStop = new Int32Array(W).fill(-1);\n for (let x = 0; x < W; x++) {\n for (let y = whiteTop[x] - 1; y >= 0; y--) {\n if (isDark((y * W + x) * 4)) {\n lidStop[x] = y;\n break;\n }\n }\n }\n\n const sclera = Buffer.from(data);\n const lash = Buffer.from(data);\n const lashLower = Buffer.from(data);\n let lowerInk = false;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n const i = (y * W + x) * 4;\n const dark = isDark(i);\n const upper = y <= lashCutoffY;\n if (dark && upper) sclera[i] = sclera[i + 1] = sclera[i + 2] = 255; // dark -> white\n if (detached[y * W + x]) sclera[i + 3] = 0;\n if (y < lidStop[x] && isLight(i) && isWarm(i)) sclera[i + 3] = 0;\n if (!(dark && upper)) lash[i + 3] = 0;\n if (dark && !upper) lowerInk = true;\n else lashLower[i + 3] = 0;\n }\n }\n const region = {\n x: minX,\n y: minY,\n w: maxX - minX + 1,\n h: maxY - minY + 1,\n };\n return {\n sclera: await cropToBuffer(sclera, W, H, region),\n lash: await cropToBuffer(lash, W, H, region),\n lashLower: lowerInk ? await cropToBuffer(lashLower, W, H, region) : null,\n };\n}\n\n/** Whether any pixel is not fully opaque. An alpha channel alone proves\n * nothing: an image saved as RGBA can still be opaque on its white ground. */\nfunction hasTransparency(rgba: Buffer): boolean {\n for (let p = 3; p < rgba.length; p += 4) if (rgba[p] < 255) return true;\n return false;\n}\n\n/**\n * The lip set's two sources, keyed and prepared, or `undefined` for the legacy\n * mouth. Opt-in like the arms: both files present is the set, neither is the\n * legacy route, and one without the other, or either beside the legacy\n * drawings, is refused (auto_rig_from_layers refuses the mix; the composer\n * refuses it first, naming what to remove). Both are decoded here, at source\n * resolution, because the key reads the antialiasing of the source's own\n * pixels (./compose-lips); a part with no alpha has its white ground keyed\n * first.\n */\nasync function prepLipSources(\n partsDir: string,\n mirrored: Set<string>,\n): Promise<\n | {\n keyedPng: Buffer;\n interior: { png: Buffer; cavity: [number, number, number] };\n }\n | undefined\n> {\n const has = (name: string) => fs.existsSync(path.join(partsDir, name));\n const keyed = has(KEYED_SRC);\n const interior = has(INTERIOR_SRC);\n if (keyed && !interior) {\n throw new AutoRigInputError(\n `${KEYED_SRC} needs ${INTERIOR_SRC}: the composer fits the drawn interior into the keyed opening — draw it (billed)`,\n );\n }\n if (interior && !keyed) {\n throw new AutoRigInputError(\n `${INTERIOR_SRC} needs ${KEYED_SRC}: the composer cuts the lip set from the keyed open mouth and fits the interior into its opening — draw it (billed)`,\n );\n }\n if (!keyed) return undefined;\n const legacy = [\"mouth.png\", \"mouth_open.png\"].filter(has);\n if (legacy.length > 0) {\n throw new AutoRigInputError(\n `${KEYED_SRC}/${INTERIOR_SRC} cannot be composed beside mouth.png/mouth_open.png (the lip set replaces the mouth drawings, and auto_rig_from_layers refuses the mix) — remove ${legacy.join(\" and \")}`,\n );\n }\n\n const k = await decodePng(path.join(partsDir, KEYED_SRC));\n const keyedRgba = keyGreen(\n hasTransparency(k.rgba) ? k.rgba : keyWhiteToAlpha(k.rgba),\n k.width,\n k.height,\n );\n const i = await decodePng(path.join(partsDir, INTERIOR_SRC));\n const prepared = await prepInterior(\n hasTransparency(i.rgba)\n ? i.rgba\n : keyBorderWhite(i.rgba, i.width, i.height),\n i.width,\n i.height,\n );\n return {\n keyedPng: await sharp(keyedRgba, {\n raw: { width: k.width, height: k.height, channels: 4 },\n })\n .png()\n .toBuffer(),\n interior: mirrored.has(INTERIOR_SRC)\n ? { ...prepared, png: await sharp(prepared.png).flop().png().toBuffer() }\n : prepared,\n };\n}\n\n/**\n * Compose a parts directory into role-named layers plus a flattened preview,\n * then measure the result so the caller sees the geometry checks inline.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) →\n * `{ ok:false }`, matching autoRigFromLayers; any other throw propagates.\n */\nexport async function composeLayersFromParts(\n input: ComposeInput,\n): Promise<ComposeResult> {\n try {\n // Resolve the output dir FIRST (fail-fast): reject a missing or escaping\n // target before spending the decode budget on a run that cannot be written.\n const outDir = resolveOutputDir(input.outDir);\n const partsDir = resolveInputDir(input.partsDir);\n // resolveOutputDir already realpath's outDir; resolveInputDir does not (its\n // reads are deliberately unconfined), so realpath partsDir here too before\n // comparing — otherwise a symlink alias of the same directory would slip\n // past a lexical check. Composing a parts dir into itself would overwrite\n // originals like face.png/hair_front.png with resized, cropped layers, and\n // skipped-role cleanup would delete sources with no surviving part.\n if (fs.realpathSync(partsDir) === outDir) {\n throw new AutoRigInputError(\n `partsDir and outDir resolve to the same directory (${outDir}): composing would overwrite the source parts`,\n );\n }\n // Before anything decodes, like every other input check.\n const canvas: Canvas = {\n width: CANVAS,\n height: resolveCanvasHeight(input.canvasHeight),\n };\n const layout = resolveLayout(input.layout, canvas);\n const mirrored = resolveMirrorParts(input.mirrorParts);\n\n const split = await prepEyeSplit(partsDir);\n const splitSources = new Map<string, Buffer>([\n [\"eyewhite_sclera.png\", split.sclera],\n [\"eyewhite_lash.png\", split.lash],\n ]);\n if (split.lashLower !== null) {\n splitSources.set(LOWER_LASH_SRC, split.lashLower);\n }\n\n const lips = await prepLipSources(partsDir, mirrored);\n // The set's split, stashed where mouth_inner is placed for the two lip\n // layers cut on the same frame.\n let lipSplit:\n | {\n split: Awaited<ReturnType<typeof splitLipSet>>;\n w: number;\n h: number;\n left: number;\n top: number;\n }\n | undefined;\n\n // Place every role before writing any: a rejected placement must leave\n // outDir as the last compose left it, not half overwritten.\n const placed: {\n role: LayerRole;\n part: { buf: Buffer; w: number; h: number };\n left: number;\n top: number;\n /** An arm's, for a pose forearm to hang from: the rig's elbow pivot on\n * the canvas and the elbow seam's run, px. */\n elbow?: { x: number; y: number };\n elbowRun?: number;\n }[] = [];\n const skipped: LayerRole[] = [];\n // Compose's verdict on the nose's source part when its core was a speck,\n // for the report; otherwise the report judges the composed nose layer.\n let noseSpeck: NoseSpeck | undefined;\n for (const role of ORDER) {\n // With the lip set, mouth and mouth_open are neither placed nor listed in\n // `skipped`: the set stands in for them.\n if (lips !== undefined && (role === \"mouth\" || role === \"mouth_open\")) {\n continue;\n }\n if (role === \"mouth_inner\") {\n // Opt-in like the arms: without the lip set, nothing to place.\n if (lips === undefined) continue;\n const cfg = layout.mouth_inner;\n // Never null: the keyed part is in memory.\n const part = (await partBuffer(\n role,\n cfg,\n partsDir,\n lips.keyedPng,\n mirrored.has(KEYED_SRC),\n canvas,\n ))!;\n const split = await splitLipSet(\n part.buf,\n part.w,\n part.h,\n lips.interior,\n );\n const { left, top } = placement(role, cfg, part.w, part.h, canvas);\n lipSplit = { split, w: part.w, h: part.h, left, top };\n placed.push({\n role,\n part: { buf: split.inner, w: part.w, h: part.h },\n left,\n top,\n });\n continue;\n }\n if (\n role === \"mouth_tongue\" ||\n role === \"mouth_teeth\" ||\n role === \"lip_lower\" ||\n role === \"lip_upper\"\n ) {\n if (lipSplit === undefined) continue;\n const { split, w, h, left, top } = lipSplit;\n const buf = {\n mouth_tongue: split.tongue,\n mouth_teeth: split.teeth,\n lip_lower: split.lower,\n lip_upper: split.upper,\n }[role];\n // An interior with no light paint has no tongue or teeth to cut.\n if (isLipInsideRole(role) && !(await hasCoverage(buf))) {\n skipped.push(role);\n continue;\n }\n placed.push({ role, part: { buf, w, h }, left, top });\n continue;\n }\n // A lower lash is placed by its eye's layout, on the sclera's frame.\n const lower = role === \"lash_lower_L\" || role === \"lash_lower_R\";\n const key: Role = lower ? LOWER_LASH[role] : role;\n if (lower && split.lashLower === null) {\n skipped.push(role);\n continue;\n }\n if (key === \"arm_L\" || key === \"arm_R\") {\n const arm = layout[key];\n // Arms are opt-in: a parts dir without arm.png composes as a bust\n // does, the arms neither placed nor listed in `skipped`.\n if (!fs.existsSync(path.join(partsDir, arm.src))) continue;\n const body = placed.find((p) => p.role === \"body\");\n if (body === undefined) {\n throw new AutoRigInputError(\n \"arm.png: an arm needs body.png — the composer hangs each arm on the body's shoulder, and auto_rig_from_layers hangs it from the body\",\n );\n }\n const w = arm.w ?? Math.max(1, Math.round(ARM_WIDTH * body.part.w));\n // Never null: the part is there, checked above.\n const part = (await partBuffer(\n role,\n { ...arm, w },\n partsDir,\n undefined,\n mirrored.has(arm.src),\n canvas,\n ))!;\n const { left, top, elbow, elbowRun } = await armPlacement(\n key,\n arm,\n part,\n {\n left: body.left,\n top: body.top,\n w: body.part.w,\n h: body.part.h,\n },\n );\n const unset = ([\"cx\", \"cy\"] as const).filter(\n (field) => arm[field] === undefined,\n );\n assertOnCanvas(\n unset.length === 0\n ? `layout.${key}.cx/cy`\n : `layout.${key}.cx/cy (${unset.join(\"/\")} unset: its shoulder pivot hangs on the shoulder corner of layout.body's box)`,\n part.w,\n part.h,\n left,\n top,\n canvas,\n );\n placed.push({ role, part, left, top, elbow, elbowRun });\n continue;\n }\n if (key === \"forearm_pose_L\" || key === \"forearm_pose_R\") {\n const pose = layout[key];\n // Opt-in like the arms: neither placed nor listed in `skipped`.\n if (!fs.existsSync(path.join(partsDir, pose.src))) continue;\n const armRole = key === \"forearm_pose_L\" ? \"arm_L\" : \"arm_R\";\n const arm = placed.find((p) => p.role === armRole);\n if (arm?.elbow === undefined || arm.elbowRun === undefined) {\n throw new AutoRigInputError(\n \"forearm_pose.png: a pose forearm needs arm.png — the composer pins it on the arm's elbow, and auto_rig_from_layers hangs it from the arm\",\n );\n }\n // Never null: the part is there, checked above.\n const trimmed = (await trimmedPart(\n role,\n pose,\n partsDir,\n undefined,\n mirrored.has(pose.src),\n ))!;\n const w =\n pose.w ?? (await forearmPoseWidth(key, trimmed, arm.elbowRun));\n let part;\n try {\n part = await sizedPart(role, { ...pose, w }, trimmed, canvas);\n } catch (err) {\n // A derived w the user never set is not blamed on the layout key.\n if (pose.w === undefined && err instanceof AutoRigInputError) {\n throw new AutoRigInputError(\n err.message.replace(\n `layout.${role}.w:`,\n `layout.${role}.w (unset: scaled to ${armRole}'s elbow run):`,\n ),\n );\n }\n throw err;\n }\n const { left, top } = await forearmPosePlacement(\n key,\n pose,\n part,\n arm.elbow,\n );\n const unset = ([\"cx\", \"cy\"] as const).filter(\n (field) => pose[field] === undefined,\n );\n assertOnCanvas(\n unset.length === 0\n ? `layout.${key}.cx/cy`\n : `layout.${key}.cx/cy (${unset.join(\"/\")} unset: its elbow-end pivot hangs on the elbow of layout.${armRole}'s placed arm)`,\n part.w,\n part.h,\n left,\n top,\n canvas,\n );\n placed.push({ role, part, left, top });\n continue;\n }\n const cfg = lower ? { ...layout[key], src: LOWER_LASH_SRC } : layout[key];\n const inMemory = splitSources.get(cfg.src);\n const part = await partBuffer(\n role,\n cfg,\n partsDir,\n inMemory,\n // The split halves are cut from eyewhite.png, the file a caller names.\n mirrored.has(inMemory === undefined ? cfg.src : EYEWHITE_SRC),\n canvas,\n );\n // A lower lid too faint for the alpha the rig reads coverage at, or\n // that the resize erased, would be a layer it refuses as empty.\n if (part === null || (lower && !(await hasCoverage(part.buf)))) {\n skipped.push(role);\n continue;\n }\n // The nose is placed by the box it was sized by. A whole part that stood\n // in is placed by the resized part's own bounds. A core is measured\n // again on the resized part rather than scaled, since resampling moves\n // its edges and the tip rule lands its exact bottom row — and is not\n // judged again here: the source part's verdict decided how it was sized.\n let left: number;\n let top: number;\n if (key === \"nose\") {\n noseSpeck = part.nose?.speck;\n const { core, bounds } = await coreAndBoundsOf(part.buf);\n const box = part.nose?.whole ? bounds : (core ?? bounds);\n ({ left, top } = nosePlacement(\n layout,\n lips === undefined ? \"mouth\" : \"mouth_inner\",\n box,\n part.w,\n part.h,\n canvas,\n ));\n } else {\n ({ left, top } = placement(key, layout[key], part.w, part.h, canvas));\n }\n // The eye pair's halves are cut from one eyewhite into one frame. Set\n // apart, the blink fold tears — and a lash narrowed inside its sclera\n // still lies on it and inks its top row, so nothing in the composed\n // layers would show it. Compared as placed, not as set: an h equal to\n // the one the aspect gives lands on the same frame as leaving it unset.\n if (role === \"lash_L\" || role === \"lash_R\") {\n const eyeRole = role === \"lash_L\" ? \"eye_L\" : \"eye_R\";\n const eye = placed.find((p) => p.role === eyeRole);\n if (\n eye !== undefined &&\n (eye.left !== left ||\n eye.top !== top ||\n eye.part.w !== part.w ||\n eye.part.h !== part.h)\n ) {\n throw new AutoRigInputError(\n `layout.${role} places the lash at ${part.w}x${part.h} (${left},${top}), but layout.${eyeRole} ` +\n `places its sclera at ${eye.part.w}x${eye.part.h} (${eye.left},${eye.top}) — they are cut from one ` +\n `eyewhite into one frame, and the blink fold tears where they part. Set cx/cy/w/h the same on both.`,\n );\n }\n }\n placed.push({ role, part, left, top });\n }\n\n // Every layer is built, and the closed lip preview measured from them,\n // before the first sweep or write: a lip layer the canvas clips away is\n // refused with outDir as the last compose left it.\n const built = new Map<LayerRole, Buffer>();\n for (const { role, part, left, top } of placed) {\n // role layer: this part alone on a full canvas at its position.\n built.set(\n role,\n await blankCanvas(canvas)\n .composite([{ input: part.buf, left, top }])\n .png()\n .toBuffer(),\n );\n }\n // The preview shows the lip set shut by the field the rig's own\n // measurement of the written layers gives, as it draws the rest pose.\n const closed =\n lipSplit === undefined\n ? undefined\n : await closedLips(\n lipSplit.split.upper,\n lipSplit.split.lower,\n await restShiftOf(\n {\n mouth_inner: built.get(\"mouth_inner\")!,\n lip_lower: built.get(\"lip_lower\")!,\n lip_upper: built.get(\"lip_upper\")!,\n },\n canvas.width,\n canvas.height,\n ),\n lipSplit.left,\n lipSplit.top,\n );\n\n // Drop the layer an earlier compose into the same dir wrote for each role\n // this run does not write — a skipped one, or an arm once arm.png is\n // gone: left behind it would contradict the result, since measureDir\n // globs the directory (the report would still show a body) and the next\n // auto_rig_from_layers would rig the stale file into the model. Only the\n // fixed ORDER role names, under the confined outDir, are ever removed.\n for (const role of ORDER) {\n if (placed.some((p) => p.role === role)) continue;\n fs.rmSync(path.join(outDir, `${role}.png`), { force: true });\n }\n // The pose preview exists only with a pose forearm, so it is swept with\n // the layers: left behind it would show a forearm the layers no longer\n // hold.\n const posed = (role: LayerRole) =>\n role === \"forearm_pose_L\" || role === \"forearm_pose_R\";\n if (!placed.some((p) => posed(p.role))) {\n fs.rmSync(path.join(outDir, \"preview-pose.png\"), { force: true });\n }\n const layers: ComposedLayer[] = [];\n for (const { role, part, left, top } of placed) {\n const outPath = path.join(outDir, `${role}.png`);\n writeFileAtomic(outPath, built.get(role)!);\n layers.push({\n role,\n path: outPath,\n width: part.w,\n height: part.h,\n left,\n top,\n });\n }\n // What a role contributes to a rest-pose preview: the lips shut, the\n // interior and what it clips left out (shut, it has no height); null for\n // nothing.\n const restInput = (role: LayerRole, buf: Buffer): Buffer | null => {\n if (role === \"mouth_inner\" || isLipInsideRole(role)) return null;\n if (closed === undefined) return buf;\n if (role === \"lip_upper\") return closed.upper;\n if (role === \"lip_lower\") return closed.lower;\n return buf;\n };\n const preview: { input: Buffer; left: number; top: number }[] = [];\n for (const { role, part, left, top } of placed) {\n const input = restInput(role, part.buf);\n if (!posed(role) && input !== null) preview.push({ input, left, top });\n }\n\n // Flattened preview over a light bg so transparency reads clearly.\n const previewPng = await sharp({\n create: {\n width: canvas.width,\n height: canvas.height,\n channels: 4,\n background: { r: 245, g: 245, b: 248, alpha: 1 },\n },\n })\n .composite(preview)\n .png()\n .toBuffer();\n const previewPath = path.join(outDir, \"preview.png\");\n writeFileAtomic(previewPath, previewPng);\n\n // The switch at 1, as the rig draws it: an arm whose side has a pose\n // forearm keeps the rows above its elbow (the upper arm and the sleeve;\n // the hanging forearm hides), and the pose forearms, last in `placed`,\n // draw over everything.\n let previewPosePath: string | undefined;\n if (placed.some((p) => posed(p.role))) {\n const pose: { input: Buffer; left: number; top: number }[] = [];\n for (const { role, part, left, top, elbow } of placed) {\n const armPosed =\n elbow !== undefined &&\n placed.some(\n (p) =>\n p.role ===\n (role === \"arm_L\" ? \"forearm_pose_L\" : \"forearm_pose_R\"),\n );\n if (!armPosed) {\n const input = restInput(role, part.buf);\n if (input !== null) pose.push({ input, left, top });\n continue;\n }\n const rows = Math.min(part.h, Math.max(1, Math.round(elbow.y - top)));\n pose.push({\n input: await sharp(part.buf)\n .extract({ left: 0, top: 0, width: part.w, height: rows })\n .png()\n .toBuffer(),\n left,\n top,\n });\n }\n const posePng = await sharp({\n create: {\n width: canvas.width,\n height: canvas.height,\n channels: 4,\n background: { r: 245, g: 245, b: 248, alpha: 1 },\n },\n })\n .composite(pose)\n .png()\n .toBuffer();\n previewPosePath = path.join(outDir, \"preview-pose.png\");\n writeFileAtomic(previewPosePath, posePng);\n }\n\n return {\n ok: true,\n outDir,\n layers,\n skipped,\n preview: previewPath,\n ...(previewPosePath === undefined\n ? {}\n : { previewPose: previewPosePath }),\n measure: await measureDir(outDir, noseSpeck),\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n","/**\n * The trim the composer cuts every part by, shared with the lip set's interior:\n * the alpha a trim keeps, and the stray specks a background removal leaves\n * beside a drawing.\n */\n\nimport { ALPHA_OPAQUE } from \"@ikijs/editor\";\n\n/** The alpha a part's trim cuts at: what it keeps is over this. */\nexport const TRIM_THRESHOLD = 12;\n/** Of a part's kept pixels, the share under which a faint detached set is a stray speck. */\nexport const STRAY_SPECK_FRACTION = 0.01;\n\n/** Luma (0..255) of the RGBA pixel at byte offset `i`. */\nexport function luma(rgba: Buffer, i: number): number {\n return 0.299 * rgba[i] + 0.587 * rgba[i + 1] + 0.114 * rgba[i + 2];\n}\n\n/**\n * The box of a trimmed part without its stray specks, or null when no stray\n * speck lies outside its drawing. The part's kept pixels (alpha over\n * TRIM_THRESHOLD, the trim's own cut) form 8-connected sets; a stray speck is\n * a set that never reaches ALPHA_OPAQUE and holds under STRAY_SPECK_FRACTION of\n * them, the residue a background removal leaves beside a drawing. Kept, one\n * such speck widened a generated body's box by 70 px on one side and placed\n * the body 32 px off its centre. A drawn stroke reaches ALPHA_OPAQUE, so a\n * detached wisp or strand is never dropped, and a part painted wholly under\n * it (a soft blush) drops nothing.\n */\nexport function boxWithoutStraySpecks(\n rgba: Buffer,\n W: number,\n H: number,\n): { left: number; top: number; width: number; height: number } | null {\n const n = W * H;\n // The share is of the whole part, so count it before any set is judged.\n let kept = 0;\n for (let p = 0; p < n; p++) if (rgba[p * 4 + 3] > TRIM_THRESHOLD) kept++;\n // Each set is judged as its fill ends and only its box is kept, so memory\n // is a byte per pixel plus a stack grown to the deepest fill, not a label\n // per pixel and a record per set. A pixel is marked as it is pushed, so the\n // stack never outgrows the image.\n const visited = new Uint8Array(n);\n let stack = new Int32Array(1024);\n // [left, top, right, bottom] of the drawing's sets and of the stray ones.\n const drawing = [W, H, -1, -1];\n const strays = [W, H, -1, -1];\n let anyOpaque = false;\n for (let start = 0; start < n; start++) {\n if (visited[start] || rgba[start * 4 + 3] <= TRIM_THRESHOLD) continue;\n let setLeft = W;\n let setTop = H;\n let setRight = -1;\n let setBottom = -1;\n let size = 0;\n let opaque = false;\n let depth = 0;\n visited[start] = 1;\n stack[depth++] = start;\n while (depth > 0) {\n const p = stack[--depth];\n size++;\n if (rgba[p * 4 + 3] >= ALPHA_OPAQUE) opaque = true;\n const px = p % W;\n const py = (p - px) / W;\n setLeft = Math.min(setLeft, px);\n setTop = Math.min(setTop, py);\n setRight = Math.max(setRight, px);\n setBottom = Math.max(setBottom, py);\n for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {\n for (let x = Math.max(0, px - 1); x <= Math.min(W - 1, px + 1); x++) {\n const q = y * W + x;\n if (!visited[q] && rgba[q * 4 + 3] > TRIM_THRESHOLD) {\n visited[q] = 1;\n if (depth === stack.length) {\n const grown = new Int32Array(Math.min(n, stack.length * 2));\n grown.set(stack);\n stack = grown;\n }\n stack[depth++] = q;\n }\n }\n }\n }\n anyOpaque ||= opaque;\n const into =\n !opaque && size < kept * STRAY_SPECK_FRACTION ? strays : drawing;\n into[0] = Math.min(into[0], setLeft);\n into[1] = Math.min(into[1], setTop);\n into[2] = Math.max(into[2], setRight);\n into[3] = Math.max(into[3], setBottom);\n }\n if (!anyOpaque || strays[2] < 0) return null;\n const [left, top, right, bottom] = drawing;\n // A set's box reaches past the drawing's only where one of its pixels does,\n // and a speck inside the drawing's box moves nothing, so it is left be.\n if (\n strays[0] >= left &&\n strays[1] >= top &&\n strays[2] <= right &&\n strays[3] <= bottom\n )\n return null;\n return { left, top, width: right - left + 1, height: bottom - top + 1 };\n}\n","/**\n * Measure composed Iki role layers and flag the failure modes that have\n * actually shipped broken characters. Read-only: it never edits anything.\n *\n * Ports the geometry checks that shipped as a script in the Claude Code plugin,\n * so a plugin user gets them from the MCP server instead of an ad-hoc `sharp`\n * install. They exist because \"the eyes look too big\" is not actionable but\n * \"the iris is 33% of the sclera width, target 0.45-0.72\" is. Every check below\n * is one that cost a real regeneration or re-tune round to find by eye.\n *\n * `sharp` must stay confined to @ikijs/mcp; the decode goes through\n * ./node-images, this package's single image-decode boundary.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { decodePng, detectAlphaBbox } from \"./node-images\";\nimport { AutoRigInputError, MAX_LAYERS, resolveInputDir } from \"./limits\";\nimport { ARM_ROLES, armWarnings } from \"./measure-arms\";\nimport { POSE_ROLES, forearmPoseWarnings } from \"./measure-forearm-pose\";\nimport { isLipLayerRole, lipWarnings, type LipFacts } from \"./measure-lips\";\nimport { SPECK_CORE_FRACTION, denseCoreOf, isSpeckCore } from \"./measure-turn\";\n\n// Iris width as a fraction of sclera width. Below the floor the eye reads as a\n// bead floating in white — that is the failure this check was written for, and\n// it caught a model that shipped at 0.33. The ceiling was a guess and it was\n// too tight: measured on a real anime reference the iris runs about 0.70 of the\n// eye, with the white reduced to corner crescents, so 0.6 flagged the correct\n// value as a fault three rounds running.\nconst IRIS_RATIO_MIN = 0.45;\nconst IRIS_RATIO_MAX = 0.72;\n// A sclera flatter than this cannot hold a round iris: the iris overflows the\n// lids no matter how narrow it is.\nconst EYE_ASPECT_MIN = 0.5;\n// How far the iris centre may sit from the white's centre of mass. The two axes\n// are not the same problem. Sideways drift is always a fault — that is the bug\n// this check was written for, a lash that fell out of sync with its sclera by\n// 14px. Vertically the reference itself rides its iris HIGH, tucked under the\n// lash with roughly a sixth of the aperture showing as white below it, so a\n// deliberate lift of that order is correct and a 3px ceiling flagged it.\nconst IRIS_OFFSET_MAX_X = 3;\nconst IRIS_OFFSET_MAX_Y = 10;\n// A cropped part shows a long, nearly-continuous opaque run along one bbox edge,\n// and that straight seam appears the moment the head turns. A round part's edge\n// row is a short tangent run, so a fraction test alone flags every iris; both a\n// high fraction AND real length are required to separate the two. Observed:\n// genuine crops read 60-93%, circle tangents 8-14%.\nconst EDGE_SOLID_MAX = 0.5;\n/** Share of a lash's opaque pixels tolerated off its sclera. In sync there\n * are none — the sclera was recoloured from those very pixels. A real eye\n * measured 0 of 934 in sync, then 6-12 at a 1 px drift, 45-50 at 2 px and\n * 104-110 at 4 px, whichever way it drifted. */\nconst LASH_STRAY_TOL_FRAC = 0.02;\n/** How much further short of the outer corner than of the nose side an eye's\n * lash may stop, as a fraction of the eye width, before the eye reads as\n * drawn facing the other way. Three real eyewhites drawn reversed stopped\n * 4.0-6.1% further short there; one drawn the right way stops short at the\n * nose side instead, and one with a wing at each end at neither. */\nconst EYE_FACING_TOL_FRAC = 0.02;\nconst EDGE_RUN_MIN_PX = 40;\n// Longest straight \"art appears out of nothing\" run tolerated inside a part, as\n// a fraction of its width. A body generated with hair draped over the shoulders\n// had that hair cut flat by its own frame; the cut hid behind the head at rest\n// and opened into a seam on turn. Measured: that part ran 15% of its width,\n// a clean one 5%, so the boundary sits between them.\nconst FLAT_CUT_MAX_FRAC = 0.1;\n// ...and long in absolute terms. A mouth's upper lip is a naturally horizontal\n// run that clears the fraction test on a narrow part while being only ~15px.\nconst FLAT_CUT_MIN_PX = 40;\n// The cut is antialiased, so the transition is a soft cliff rather than\n// transparent-to-opaque; 8/200 finds nothing at all on real art.\nconst FLAT_CUT_ALPHA_ABOVE = 120;\nconst FLAT_CUT_ALPHA_BELOW = 140;\n\n/** Alpha-derived geometry of one layer, in canvas pixels. */\nexport interface LayerStats {\n w: number;\n h: number;\n /** Longest flat cut through the art, and the row it runs along (-1 if none). */\n flatCutRun: number;\n flatCutY: number;\n bboxCx: number;\n bboxCy: number;\n massCx: number;\n massCy: number;\n /** Distance from the layer's content to each canvas edge. */\n marginTop: number;\n marginBottom: number;\n marginLeft: number;\n marginRight: number;\n /** Fraction of each bbox edge that is opaque. */\n edgeTop: number;\n edgeBottom: number;\n edgeLeft: number;\n edgeRight: number;\n canvasW: number;\n canvasH: number;\n}\n\nexport interface MeasureReport {\n /** Measured stats by role (the layer's file name without `.png`). */\n layers: Record<string, LayerStats>;\n /** Roles whose PNG is fully transparent — nothing to measure. */\n empty: string[];\n warnings: string[];\n /**\n * The lip set's opening as the rig reads it, set whenever the three lip\n * layers are present and readable. The fold's dead zone `deadZone` is the\n * `MouthOpen` below which the slit between the lips has not opened, and\n * it varies with the drawing (0.03 on one opening, 0.26 on another), so a\n * half-open mouth that shows no slit is judged against it, not against a\n * fixed number.\n */\n lips?: LipFacts;\n}\n\nexport type MeasureResult =\n | ({ ok: true; layersDir: string; passed: boolean } & MeasureReport)\n | { ok: false; error: string };\n\nexport interface MeasureInput {\n /** Directory of role-named layer PNGs (relative paths resolve against cwd). */\n layersDir: string;\n}\n\n/**\n * Scan one layer PNG's alpha channel. Returns null for a fully transparent\n * layer. A decode failure surfaces as a path-qualified AutoRigInputError.\n */\nexport async function layerStats(filePath: string): Promise<LayerStats | null> {\n const { width: W, height: H, rgba } = await decodePng(filePath);\n const alpha = (x: number, y: number) => rgba[(y * W + x) * 4 + 3];\n\n let minX = W;\n let minY = H;\n let maxX = -1;\n let maxY = -1;\n let sumX = 0;\n let sumY = 0;\n let n = 0;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n if (alpha(x, y) > 8) {\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n sumX += x;\n sumY += y;\n n++;\n }\n }\n }\n if (maxX < 0) return null; // fully transparent\n\n const edge = (pts: number[]) =>\n pts.filter((v) => v > 200).length / pts.length;\n const top: number[] = [];\n const bottom: number[] = [];\n const left: number[] = [];\n const right: number[] = [];\n for (let x = minX; x <= maxX; x++) {\n top.push(alpha(x, minY));\n bottom.push(alpha(x, maxY));\n }\n for (let y = minY; y <= maxY; y++) {\n left.push(alpha(minX, y));\n right.push(alpha(maxX, y));\n }\n\n // Longest contiguous run of pixels where the art appears out of nothing along\n // one row — transparent above, opaque below. Organic art (hair, cloth) meets\n // its silhouette at an angle, so a long FLAT run like this means the source\n // image was cropped through the drawing. It is often interior to the bbox\n // (a hair strand cut short above a wider shoulder line), which is why the\n // bbox-edge test alone misses it, and it only becomes visible once the head\n // turns and uncovers the cut.\n let flatCutRun = 0;\n let flatCutY = -1;\n for (let y = minY + 1; y <= maxY; y++) {\n let run = 0;\n for (let x = minX; x <= maxX; x++) {\n if (\n alpha(x, y - 1) < FLAT_CUT_ALPHA_ABOVE &&\n alpha(x, y) > FLAT_CUT_ALPHA_BELOW\n ) {\n run++;\n if (run > flatCutRun) {\n flatCutRun = run;\n flatCutY = y;\n }\n } else {\n run = 0;\n }\n }\n }\n\n return {\n w: maxX - minX + 1,\n h: maxY - minY + 1,\n flatCutRun,\n flatCutY,\n bboxCx: (minX + maxX) / 2,\n bboxCy: (minY + maxY) / 2,\n massCx: sumX / n,\n massCy: sumY / n,\n marginTop: minY,\n marginBottom: H - 1 - maxY,\n marginLeft: minX,\n marginRight: W - 1 - maxX,\n edgeTop: edge(top),\n edgeBottom: edge(bottom),\n edgeLeft: edge(left),\n edgeRight: edge(right),\n canvasW: W,\n canvasH: H,\n };\n}\n\nconst pct = (v: number) => `${(v * 100).toFixed(0)}%`;\n\n/** An arm's seams show once it raises, every other part's on the head turn. A\n * pose forearm raises with its arm, and shows only once the switch is on. */\nconst isArm = (role: string) =>\n (ARM_ROLES as readonly string[]).includes(role) ||\n (POSE_ROLES as readonly string[]).includes(role);\n\n/** A nose's dense core that `isSpeckCore` judged a speck of its part, as sizes\n * in px: compose's verdict on the trimmed source part, or the composed\n * layer's against its crop. */\nexport interface NoseSpeck {\n core: { w: number; h: number };\n part: { w: number; h: number };\n}\n\n/**\n * The nose-speck warning. Each source says only what its own reader did:\n * `\"compose\"` judged the trimmed source part, before resampling, and composed\n * it whole; `\"layer\"` judged the layer file against its crop, which is what\n * `auto_rig_from_layers` reads. The remedy is the same either way.\n */\nfunction noseSpeckWarning(\n { core, part }: NoseSpeck,\n source: \"compose\" | \"layer\",\n): string {\n const [found, consequence] =\n source === \"compose\"\n ? [\n `the source part's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} trimmed part`,\n `compose_layers_from_parts sized and placed the whole part instead — layout.nose's w and h now size it, feather included`,\n ]\n : [\n `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,\n `auto_rig_from_layers turns and tilts the nose about its whole crop instead`,\n ];\n return (\n `nose: ${found} — under ${SPECK_CORE_FRACTION} of its width or height, a speck: a lone nostril ` +\n `mark or highlight at alpha >= 128, not the drawing, so ${consequence}. Regenerate the nose with ` +\n `its shading painted denser, so the drawing itself reaches alpha 128. Billed.`\n );\n}\n\n/**\n * Count the lash's opaque pixels, and those of them that land where its\n * sclera is transparent. Both are canvas-sized layers, so a pixel's position\n * is the same canvas point in each.\n */\nasync function lashOffSclera(\n eyePath: string,\n lashPath: string,\n): Promise<{ opaque: number; off: number }> {\n const eye = await decodePng(eyePath);\n const lash = await decodePng(lashPath);\n let opaque = 0;\n let off = 0;\n for (let y = 0; y < lash.height; y++) {\n for (let x = 0; x < lash.width; x++) {\n if (lash.rgba[(y * lash.width + x) * 4 + 3] < 128) continue;\n opaque++;\n const onEye = x < eye.width && y < eye.height;\n if (!onEye || eye.rgba[(y * eye.width + x) * 4 + 3] <= 8) off++;\n }\n }\n return { opaque, off };\n}\n\n/**\n * Measure every `*.png` in an already-resolved layers directory but the\n * `preview*.png` ones (`preview.png` is the composer's contact sheet, and a\n * caller's own previews sit beside it; none is a role) and run the geometry\n * checks.\n * `noseSpeck` is compose's own verdict on the nose's source part when that\n * part's core was a speck, and the nose check reports it as given. Left out —\n * compose found no speck, or `measure_layers` — that check judges the `nose`\n * layer file against its crop instead, as `auto_rig_from_layers` does.\n */\nexport async function measureDir(\n absDir: string,\n noseSpeck?: NoseSpeck,\n): Promise<MeasureReport> {\n const files = fs\n .readdirSync(absDir)\n .filter((f) => f.endsWith(\".png\") && !f.startsWith(\"preview\"))\n .sort();\n if (files.length === 0) {\n throw new AutoRigInputError(`no role layers in ${absDir}`);\n }\n // Same agent-supplied-input surface autoRigFromLayers bounds: a `layersDir`\n // pointed at an asset folder would decode every PNG in it before reporting.\n if (files.length > MAX_LAYERS) {\n throw new AutoRigInputError(\n `too many layers in ${absDir}: ${files.length} > ${MAX_LAYERS}`,\n );\n }\n\n const layers: Record<string, LayerStats> = {};\n const empty: string[] = [];\n for (const f of files) {\n const role = path.basename(f, \".png\");\n const m = await layerStats(path.join(absDir, f));\n if (!m) {\n empty.push(role);\n continue;\n }\n layers[role] = m;\n }\n\n const warnings: string[] = [];\n\n // 1. Art running to its own edge → a straight seam appears on head turn.\n // Two very different faults look identical in the flattened layer, and the\n // remedies cost differently, so tell them apart before prescribing one: a\n // part the CANVAS clipped has no margin left on that side (retune, free),\n // while a part placed with room whose own drawing runs to its frame does\n // (regenerate, billed). A real run lost a regeneration to this: the source\n // kept 44 px of margin and the default layout pushed it 70 px off-canvas,\n // so redrawing it reproduced the clip exactly.\n for (const [role, m] of Object.entries(layers)) {\n // A lip layer's straight edges are the split's cuts, not the art's; the\n // lip checks read what the rig does with them.\n if (isLipLayerRole(role)) continue;\n const edges: [string, number, number, number][] = [\n [\"top\", m.edgeTop, m.w, m.marginTop],\n [\"left\", m.edgeLeft, m.h, m.marginLeft],\n [\"right\", m.edgeRight, m.h, m.marginRight],\n ];\n // A bust's torso is meant to run off the bottom of a square canvas. A\n // full body stands on a taller one with its soles inside it, where two\n // soles' flat bottoms could trip the generic check, so a check of its own\n // replaces it: paint on the canvas's last row is feet cut off.\n if (role !== \"body\") {\n edges.push([\"bottom\", m.edgeBottom, m.w, m.marginBottom]);\n } else if (m.canvasH > m.canvasW && m.marginBottom === 0) {\n warnings.push(\n `body: its bottom row is the canvas's last — on a tall canvas that cuts the feet off. ` +\n `Free fix: raise canvasHeight (the canvas grows downward, nothing else moves) and ` +\n `remeasure; regenerate body.png only if the drawing itself stops short of the soles.`,\n );\n }\n for (const [side, v, span, margin] of edges) {\n if (v > EDGE_SOLID_MAX && v * span >= EDGE_RUN_MIN_PX) {\n const remedy =\n margin === 0\n ? // margin 0 is consistent with a clipped placement AND with art\n // already cropped flush that happens to sit on the boundary, and\n // the flattened layer cannot separate them — so name the free\n // move rather than the cause. If moving it inward leaves the\n // edge opaque, the drawing is the one at fault.\n `it sits flush against the canvas ${side}, which a clipped placement and already-cropped ` +\n `art both produce. Move it inward first — retune layout.${role}.cx/cy/w, free — and ` +\n `remeasure; regenerate only if the edge is still opaque with margin to spare.`\n : `its own drawing runs to the frame ${margin} px inside the canvas — regenerate that part ` +\n `with empty margin on that side. Billed.`;\n warnings.push(\n `${role}: ${pct(v)} of its ${side} edge is opaque — the art is cut off there, ` +\n `which shows as a straight seam ${isArm(role) ? \"once the arm raises\" : \"once the head turns\"}. ` +\n `Cause: ${remedy}`,\n );\n }\n }\n }\n\n // 1b. A straight cut through the drawing, wherever it falls in the bbox.\n for (const [role, m] of Object.entries(layers)) {\n // `body` bends as one drawing, so no pose opens a cut in it; its top is\n // deliberately cut flat where the jaw covers it, and stays under the jaw\n // because the head rides the body.\n if (role === \"body\" || isLipLayerRole(role)) continue;\n if (\n m.flatCutRun > FLAT_CUT_MAX_FRAC * m.w &&\n m.flatCutRun >= FLAT_CUT_MIN_PX\n ) {\n warnings.push(\n `${role}: ${m.flatCutRun}px of straight flat edge at y=${m.flatCutY} ` +\n `(${pct(m.flatCutRun / m.w)} of its width) — the source art is cut through there. ` +\n (isArm(role)\n ? `It hides at rest and opens into a seam once the arm raises. `\n : `It hides while the head faces front and opens into a seam on turn. `) +\n `Regenerate this part with the whole subject inside the frame.`,\n );\n }\n }\n\n // 1c. The arms: each needs a body, and its shoulder cap the torso under it.\n warnings.push(...(await armWarnings(absDir, layers)));\n\n // 1d. The pose forearms: each needs its arm, and its elbow end the arm's elbow.\n warnings.push(...(await forearmPoseWarnings(absDir, layers)));\n\n // 1e. The lip set: the fold's contract per column, the opening's size, the\n // line's weight, key green left, an interior with holes.\n const lip = await lipWarnings(absDir, layers);\n warnings.push(...lip.warnings);\n\n // 2/3/4. Eye stack geometry, per side.\n for (const side of [\"L\", \"R\"]) {\n const eye: LayerStats | undefined = layers[`eye_${side}`];\n const iris: LayerStats | undefined = layers[`iris_${side}`];\n const lash: LayerStats | undefined = layers[`lash_${side}`];\n if (!eye) continue;\n\n const aspect = eye.h / eye.w;\n if (aspect < EYE_ASPECT_MIN) {\n warnings.push(\n `eye_${side}: sclera aspect h/w=${aspect.toFixed(2)} is flatter than ${EYE_ASPECT_MIN} — ` +\n `a round iris cannot sit inside it. Free fix first: set layout.eye_${side}.h and ` +\n `layout.lash_${side}.h to ${Math.ceil(eye.w * EYE_ASPECT_MIN)} (both, or the fold tears) — ` +\n `stretching a flat white lens is invisible. Regenerate the eyewhite taller only if that ` +\n `distorts the lash.`,\n );\n }\n\n if (iris) {\n const ratio = iris.w / eye.w;\n if (ratio < IRIS_RATIO_MIN || ratio > IRIS_RATIO_MAX) {\n warnings.push(\n `iris_${side}: width is ${pct(ratio)} of the sclera (target ${IRIS_RATIO_MIN}-${IRIS_RATIO_MAX}) — ` +\n `retune layout.iris_${side}.w (keep it a fraction of the eye width), no regeneration needed.`,\n );\n }\n const dx = iris.bboxCx - eye.massCx;\n const dy = iris.bboxCy - eye.massCy;\n if (\n Math.abs(dx) > IRIS_OFFSET_MAX_X ||\n Math.abs(dy) > IRIS_OFFSET_MAX_Y\n ) {\n warnings.push(\n `iris_${side}: sits (${dx.toFixed(1)}, ${dy.toFixed(1)}) px from the white's centre of mass — ` +\n `retune layout.iris_${side}.cx/cy. The sclera's bbox centre is NOT its visual centre when the ` +\n `lash flick stretches the box.`,\n );\n }\n }\n\n // 5. The lash and the white are split from ONE source and pasted with the\n // same cx/cy/w, so their frames coincide even though the lash only inks the\n // upper part of it (its content sits higher — that is the fold working, not\n // a fault). In sync, the lash is ink the sclera was recoloured from, so\n // every opaque lash pixel lies on the sclera, and both ink the same top\n // row; a drift moves pixels off it, and a lash scaled down inside it (a w\n // or h out of sync) drops its top row — the seam the fold rides — either\n // way tearing the fold. Neither the ink centres nor the frame's sides can\n // stand in for that: a lash stops short of the tear duct (5b), so a\n // correctly composed eye's ink sits 3-5% of its width off the sclera's\n // centre, while a lash drifting in toward that bare end stays inside the\n // frame.\n //\n // 5b. Which way the eye was drawn. A lash runs out to the outer corner,\n // wing and all, and stops short of the tear duct at the inner one, so in\n // the frame it shares with the sclera it is the nose end that the lash\n // leaves bare. A lash that stops short of the OUTER end instead is an\n // eyewhite drawn facing the other way: the wings point in, and \"left eye\"\n // in a prompt cannot prevent it, since it reads as the viewer's left or\n // the character's. The ends are read, not the ink's centroid: a thin wing\n // widens the frame far more than it moves the centroid, which reads a\n // correctly drawn eye as reversed. Only a lash in sync is read — a drift\n // moves the ends too, and is check 5's to report, not the drawing's.\n if (lash) {\n const { opaque, off } = await lashOffSclera(\n path.join(absDir, `eye_${side}.png`),\n path.join(absDir, `lash_${side}.png`),\n );\n const dTop = lash.marginTop - eye.marginTop;\n const faults = [\n ...(off > opaque * LASH_STRAY_TOL_FRAC\n ? [`${off} of its ${opaque} opaque px lie off eye_${side}'s sclera`]\n : []),\n ...(Math.abs(dTop) > 0.5\n ? [`its top edge is ${dTop.toFixed(1)} px off the sclera's`]\n : []),\n ];\n if (faults.length > 0) {\n warnings.push(\n `lash_${side}: ${faults.join(\" and \")} — they are split from one source and MUST share ` +\n `cx/cy/w/h in layout, or the blink fold tears. Retune to match.`,\n );\n } else {\n // How far short of each side of the frame the lash stops.\n const bareLeft = lash.marginLeft - eye.marginLeft;\n const bareRight = lash.marginRight - eye.marginRight;\n // eye_R is the screen-left eye: its outer corner is its left end.\n const [bareOuter, bareInner] =\n side === \"R\" ? [bareLeft, bareRight] : [bareRight, bareLeft];\n if ((bareOuter - bareInner) / eye.w > EYE_FACING_TOL_FRAC) {\n warnings.push(\n `eye_${side}: its lash stops ${pct(bareOuter / eye.w)} of the eye width short of the outer corner ` +\n `and ${pct(bareInner / eye.w)} short of the nose side — the eyewhite is drawn facing the other way, ` +\n `lash wing at the inner corner. The composer reads eyewhite.png as the eye on the screen LEFT: lash ` +\n `wing at the image's left end, lash-free tear duct at its right. Free fix: compose again with ` +\n `mirrorParts: [\"eyewhite.png\"] — no regeneration.`,\n );\n }\n }\n }\n }\n\n // 6. A nose whose dense core is a speck of its part (`isSpeckCore`). A\n // speck compose found in the source part, before resampling, is reported\n // as given: a dot blurred under alpha 128 no longer shows in the file.\n // Otherwise the file is judged against its crop — what the rig reads —\n // which also catches a core that only resampling made a speck.\n if (noseSpeck !== undefined) {\n warnings.push(noseSpeckWarning(noseSpeck, \"compose\"));\n } else if (layers.nose !== undefined) {\n const nose = await decodePng(path.join(absDir, \"nose.png\"));\n const core = denseCoreOf(nose.rgba, nose.width, nose.height);\n if (core !== null) {\n const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);\n if (isSpeckCore(core, crop))\n warnings.push(noseSpeckWarning({ core, part: crop }, \"layer\"));\n }\n }\n\n // 7. Optional roles that change how finished the character reads.\n for (const [role, why] of [\n [\"body\", \"without it the character reads as a floating head on head-turn\"],\n [\"hair_back\", \"without it the silhouette is flat behind the face\"],\n [\n \"nose\",\n \"without it the head still turns on the default profile, but there is no nose to lead it, and no turn fit to the art (`turnTargets` is inert, no `turn` report)\",\n ],\n ]) {\n if (layers[role] === undefined) warnings.push(`${role}: missing — ${why}.`);\n }\n\n return {\n layers,\n empty,\n warnings,\n ...(lip.lips === undefined ? {} : { lips: lip.lips }),\n };\n}\n\n/**\n * Measure a caller-supplied layers directory.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) →\n * `{ ok:false }`, matching autoRigFromLayers; any other throw propagates.\n */\nexport async function measureLayers(\n input: MeasureInput,\n): Promise<MeasureResult> {\n try {\n const layersDir = resolveInputDir(input.layersDir);\n const report = await measureDir(layersDir);\n return {\n ok: true,\n layersDir,\n ...report,\n passed: report.warnings.length === 0,\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n\n/**\n * Render a measurement as plain text: the per-layer table first (numbers to\n * argue with), then the checks that fired. Takes the report itself rather than\n * a MeasureResult so a caller holding one inline (no `ok` to unwrap) can print\n * it too; a failed measurement has no report to render.\n */\nexport function formatMeasureReport(\n result: MeasureReport & { layersDir: string },\n): string {\n const lines = [\n `# layers (${result.layersDir})`,\n \"\",\n \"role size bbox-centre mass-centre margins t/b/l/r\",\n ];\n // Roles come off a sorted file listing, so sorting the two groups back\n // together restores that order.\n for (const role of [...Object.keys(result.layers), ...result.empty].sort()) {\n const m = result.layers[role];\n if (m === undefined) {\n lines.push(`${role.padEnd(13)} EMPTY (fully transparent)`);\n continue;\n }\n lines.push(\n `${role.padEnd(13)} ${`${m.w}x${m.h}`.padEnd(11)} ` +\n `${`${m.bboxCx.toFixed(0)},${m.bboxCy.toFixed(0)}`.padEnd(14)} ` +\n `${`${m.massCx.toFixed(0)},${m.massCy.toFixed(0)}`.padEnd(13)} ` +\n `${m.marginTop}/${m.marginBottom}/${m.marginLeft}/${m.marginRight}`,\n );\n }\n\n if (result.lips !== undefined) {\n const { opening, deadZone } = result.lips;\n lines.push(\n \"\",\n `lips: opening ${opening.width} px wide, ${opening.height} px tall at its centre under a ${opening.line} px line — no slit below MouthOpen ${deadZone.toFixed(2)}`,\n );\n }\n\n lines.push(\"\", \"# checks\", \"\");\n if (result.warnings.length === 0) {\n lines.push(\"all geometry checks passed\");\n } else {\n for (const w of result.warnings) lines.push(`- ${w}`);\n }\n return lines.join(\"\\n\");\n}\n","/**\n * The measure's arm checks. An arm hangs from the body's shoulder, and raising\n * it turns its shoulder cap about the rig's shoulder pivot, so the torso has\n * to reach under that cap or a gap opens beside the shoulder. The pivot is\n * the rig's own: `armGeometry`, run on the layer as `auto_rig_from_layers`\n * runs it, so the cap measured here is the one the rig turns.\n */\n\nimport path from \"node:path\";\nimport {\n LayerGeometryError,\n armGeometry,\n createLayerSetMeasurer,\n type ArmGeometry,\n type LayerInput,\n type LayerSetMeasurer,\n} from \"@ikijs/editor\";\nimport type { LayerStats } from \"./measure\";\nimport { decodePng } from \"./node-images\";\n\n/** The arm roles, screen right (`arm_L`) then screen left (`arm_R`). */\nexport const ARM_ROLES = [\"arm_L\", \"arm_R\"] as const;\n\n/** How far an arm's shoulder cap must reach under the torso's edge on the\n * shoulder pivot's row, as a share of its radius r_u. Our own value: a\n * raised arm turns its cap about the pivot, so a cap that barely meets the\n * torso's edge swings clear of it and bares the gap beside the shoulder. */\nexport const CAP_OVERLAP = 0.5;\n\n/** A px figure as the report prints it: pivots sit on half px. */\nexport const px = (v: number) => `${Number(v.toFixed(1))}`;\n\n/** Decode a role's layer in `absDir` and measure it on `measurer`. */\nexport async function measured(\n measurer: LayerSetMeasurer,\n absDir: string,\n role: string,\n): Promise<LayerInput> {\n const fileName = `${role}.png`;\n const { rgba } = await decodePng(path.join(absDir, fileName));\n // layerStats counts alpha > 8 and the measurer alpha >= 8, so a layer\n // measured non-empty is never empty here.\n return measurer.add({ role, fileName, rgba })!;\n}\n\n/**\n * Warn of an arm layer the rig refuses or would hang with a gap at the\n * shoulder: one without a body, one on another canvas than the body's, one\n * too short to place an elbow under its shoulder, and one whose shoulder cap\n * does not reach `CAP_OVERLAP` of its radius under the torso's edge.\n * `layers` holds the measured, non-empty layers of `absDir` by role.\n */\nexport async function armWarnings(\n absDir: string,\n layers: Record<string, LayerStats>,\n): Promise<string[]> {\n const warnings: string[] = [];\n const body = layers.body;\n // Opened for the first arm that reaches the overlap, so the body decodes once.\n let set: { measurer: LayerSetMeasurer; body: LayerInput } | undefined;\n\n for (const arm of ARM_ROLES) {\n const stats = layers[arm];\n if (stats === undefined) continue;\n if (body === undefined) {\n warnings.push(\n `${arm}: no body layer — an arm hangs from the body's shoulder, and auto_rig_from_layers refuses it.`,\n );\n continue;\n }\n // One measurer reads every buffer at one size, and a buffer of another\n // shape but the same area would pass its length check and be read with\n // the wrong stride.\n if (stats.canvasW !== body.canvasW || stats.canvasH !== body.canvasH) {\n warnings.push(\n `${arm}: its canvas ${stats.canvasW}x${stats.canvasH} differs from body's ` +\n `${body.canvasW}x${body.canvasH} — auto_rig_from_layers refuses layers of different ` +\n `sizes; recompose them together.`,\n );\n continue;\n }\n if (set === undefined) {\n const measurer = createLayerSetMeasurer({\n width: body.canvasW,\n height: body.canvasH,\n });\n set = { measurer, body: await measured(measurer, absDir, \"body\") };\n }\n\n let g: ArmGeometry;\n try {\n // The body box's centre, model x: the axis the rig reads an arm's side\n // off.\n g = armGeometry(\n await measured(set.measurer, absDir, arm),\n set.body.bbox.x + set.body.bbox.w / 2 - body.canvasW / 2,\n );\n } catch (err) {\n if (err instanceof LayerGeometryError) {\n warnings.push(\n `${arm}: ${err.message} — auto_rig_from_layers refuses it. Regenerate arm.png drawn ` +\n `hanging, shoulder at the top. Billed.`,\n );\n continue;\n }\n throw err;\n }\n const cap = capWarning(arm, g, set.body);\n if (cap !== undefined) warnings.push(cap);\n }\n return warnings;\n}\n\n/**\n * The shoulder cap against the torso's edge on the arm's side, on the canvas\n * row holding the shoulder pivot: the cap reaches r_u past the pivot, so it\n * overlaps the torso by r_u less the pivot's distance outside that edge.\n */\nfunction capWarning(\n arm: (typeof ARM_ROLES)[number],\n g: ArmGeometry,\n body: LayerInput,\n): string | undefined {\n // Model space is centred on the canvas, y up.\n const pivotX = g.shoulder.x + body.canvasW / 2;\n const row = Math.floor(body.canvasH / 2 - g.shoulder.y);\n const runs = body.rowRuns?.[row - body.bbox.y] ?? [];\n if (runs.length === 0) {\n return (\n `${arm}: the body has no paint on its shoulder pivot's row (y=${row}) — the torso shows a ` +\n `gap beside the shoulder once the arm raises. Retune layout.${arm}.cy onto the shoulder (free).`\n );\n }\n // The outermost run's end on the arm's side; a run's end column is exclusive.\n const edge = g.side === 1 ? runs[runs.length - 1] : runs[0];\n const overlap = g.shoulderRadius - g.side * (pivotX - edge);\n const need = CAP_OVERLAP * g.shoulderRadius;\n if (overlap >= need) return undefined;\n return (\n `${arm}: its shoulder cap reaches ${px(overlap)} px under the torso's edge on its pivot row ` +\n `(y=${row}), under half its radius (${px(need)} px) — a gap opens beside the shoulder once ` +\n `the arm raises. Move layout.${arm}.cx ${Math.ceil(need - overlap)} px toward the body (free).`\n );\n}\n","/**\n * The measure's pose forearm checks. A pose forearm hangs from its arm's\n * elbow and is swapped in for the hanging forearm, so it has to meet the arm\n * where the rig turns it: the rig puts its pivot on the arm's elbow and\n * `forearm_pose.png` is composed so that its elbow end lands there, at the\n * arm's elbow width. The geometry is the rig's own: `armGeometry` on the arm\n * and `forearmPoseGeometry` on the pose forearm, run on one measurer as\n * `auto_rig_from_layers` runs them. A pose forearm too far off in any of\n * pivot, width or length shows a broken joint once the switch is on; the\n * canvas-edge check is the generic one in `measureDir`.\n */\n\nimport {\n LayerGeometryError,\n armGeometry,\n createLayerSetMeasurer,\n forearmPoseGeometry,\n type ArmGeometry,\n type ForearmPoseGeometry,\n type LayerInput,\n type LayerSetMeasurer,\n} from \"@ikijs/editor\";\nimport type { LayerStats } from \"./measure\";\nimport { measured, px } from \"./measure-arms\";\n\n/** The pose forearm roles, each with the arm it hangs from. */\nexport const POSE_ROLES = [\"forearm_pose_L\", \"forearm_pose_R\"] as const;\nconst ARM_OF: Record<(typeof POSE_ROLES)[number], \"arm_L\" | \"arm_R\"> = {\n forearm_pose_L: \"arm_L\",\n forearm_pose_R: \"arm_R\",\n};\n\n/** How far off the arm's elbow the pose forearm's pivot may be, px. Our own\n * value: the composer pins it to within a pixel, so more is a layout `cx` /\n * `cy` that moved it. */\nexport const POSE_PIVOT_TOLERANCE = 2;\n/** How far the pose forearm's elbow end may differ from the arm's elbow run,\n * as a share of the run. Our own value: past it the joint shows a step in\n * the sleeve. */\nexport const POSE_WIDTH_TOLERANCE = 0.1;\n/** How far the pose forearm's length (pivot to its top painted row) may\n * differ from the hanging arm's (elbow to its last painted row), as a\n * share of it. Our own value, looser than the width's: a raised hand is\n * not a hanging one, but one twice as long is another arm. */\nexport const POSE_LENGTH_TOLERANCE = 0.15;\n\n/** Model y of the last painted row of a layer, y up. */\nfunction bottomRowY(layer: LayerInput): number {\n const painted =\n layer.rowRuns?.flatMap((runs, k) => (runs.length > 0 ? [k] : [])) ?? [];\n const k = painted.at(-1) ?? layer.bbox.h - 1;\n return layer.canvasH / 2 - (layer.bbox.y + k + 0.5);\n}\n\n/**\n * Warn of a pose forearm the rig refuses or would hang off its arm's elbow:\n * one without its arm, one on another canvas than its arm's, and one whose\n * pivot, elbow-end width or length is off the arm's. Each names its free\n * retune (`layout.forearm_pose_*`) or, where only a new drawing helps, the\n * regeneration. `layers` holds the measured, non-empty layers of `absDir` by\n * role.\n */\nexport async function forearmPoseWarnings(\n absDir: string,\n layers: Record<string, LayerStats>,\n): Promise<string[]> {\n const warnings: string[] = [];\n for (const pose of POSE_ROLES) {\n const stats = layers[pose];\n if (stats === undefined) continue;\n const arm = ARM_OF[pose];\n const armStats = layers[arm];\n if (armStats === undefined) {\n warnings.push(\n `${pose}: no ${arm} layer — a pose forearm hangs from its arm's elbow, and auto_rig_from_layers refuses it.`,\n );\n continue;\n }\n if (\n stats.canvasW !== armStats.canvasW ||\n stats.canvasH !== armStats.canvasH\n ) {\n warnings.push(\n `${pose}: its canvas ${stats.canvasW}x${stats.canvasH} differs from ${arm}'s ` +\n `${armStats.canvasW}x${armStats.canvasH} — auto_rig_from_layers refuses layers of different ` +\n `sizes; recompose them together.`,\n );\n continue;\n }\n // Without a body the arm is already warned of (armWarnings).\n if (layers.body === undefined) continue;\n\n const measurer: LayerSetMeasurer = createLayerSetMeasurer({\n width: stats.canvasW,\n height: stats.canvasH,\n });\n let a: ArmGeometry;\n let armLayer: LayerInput;\n try {\n armLayer = await measured(measurer, absDir, arm);\n // Only the elbow and the seam run are read, none of which depends on\n // the side, so the body is not decoded: the axis is the role's own, as\n // the composer passes it.\n a = armGeometry(armLayer, arm === \"arm_R\" ? Infinity : -Infinity);\n } catch (err) {\n // The arm's own warning says it.\n if (err instanceof LayerGeometryError) continue;\n throw err;\n }\n const b = forearmPoseGeometry(await measured(measurer, absDir, pose));\n warnings.push(...jointWarnings(pose, arm, stats, a, armLayer, b));\n }\n return warnings;\n}\n\nfunction jointWarnings(\n pose: (typeof POSE_ROLES)[number],\n arm: string,\n stats: LayerStats,\n a: ArmGeometry,\n armLayer: LayerInput,\n b: ForearmPoseGeometry,\n): string[] {\n const warnings: string[] = [];\n const key = `layout.${pose}`;\n\n // Pivot: model x grows right, y up; the layout's cy grows down. A layout\n // centre is the box's: the bbox's pixel centre (bboxCx) plus half a pixel.\n const dx = a.elbow.x - b.pivot.x;\n const dy = a.elbow.y - b.pivot.y;\n const off = Math.hypot(dx, dy);\n if (off > POSE_PIVOT_TOLERANCE) {\n warnings.push(\n `${pose}: its elbow end is ${px(off)} px off ${arm}'s elbow — the raised forearm detaches ` +\n `from the arm at the joint once it swaps in. Remove ${key}.cx/cy from the layout so it stays ` +\n `pinned on the elbow through later arm retunes (free), or set ${key}.cx to ` +\n `${Math.round(stats.bboxCx + 0.5 + dx)} and ${key}.cy to ${Math.round(stats.bboxCy + 0.5 - dy)} (free).`,\n );\n }\n\n // Width: B's elbow end against A's elbow run, by the w to set.\n const armRun = a.seamRun[1] - a.seamRun[0];\n const poseRun = 2 * b.radius;\n const widthRatio = poseRun / armRun;\n const widthBad = Math.abs(widthRatio - 1) > POSE_WIDTH_TOLERANCE;\n if (widthBad) {\n warnings.push(\n `${pose}: its elbow end is ${px(poseRun)} px wide, ${Math.round(Math.abs(widthRatio - 1) * 100)}% off ` +\n `${arm}'s elbow run (${px(armRun)} px) — the sleeve steps at the joint once it swaps in. ` +\n `Set ${key}.w to ${Math.round(stats.w / widthRatio)} (free).`,\n );\n }\n\n // Length: B from its pivot up to its hand, A from its elbow down to its\n // hand. A new w scales the width with it, so it only mends the length when\n // the width fits after.\n const armLen = a.elbow.y - bottomRowY(armLayer);\n const poseLen = b.top - b.pivot.y;\n const lengthRatio = poseLen / armLen;\n if (Math.abs(lengthRatio - 1) > POSE_LENGTH_TOLERANCE) {\n const fix = 1 / lengthRatio;\n const freeFix = Math.abs(widthRatio * fix - 1) <= POSE_WIDTH_TOLERANCE;\n warnings.push(\n `${pose}: its length from the elbow end to the hand is ${px(poseLen)} px against ${arm}'s ` +\n `${px(armLen)} px from its elbow to its hand — ` +\n (freeFix\n ? `the raised hand reaches the wrong height. Set ${key}.w to ${Math.round(stats.w * fix)} (free)` +\n (widthBad ? `, which fixes the width too.` : `.`)\n : `the raised hand reaches the wrong height, and no single w fits both its length and its width. ` +\n `Regenerate forearm_pose.png with the forearm and hand as long as the hanging arm's below its elbow. Billed.`),\n );\n }\n return warnings;\n}\n","/**\n * The measure's lip set checks. The rig folds the mouth open off the layers'\n * own alpha edges, per canvas column inside the opening (where `mouth_inner`\n * has a run): the interior's top must reach the line above it and the skin must\n * reach the interior, or a gap shows the face between them at rest. The\n * geometry is the rig's own: `mouthOpening`, run on the three layers as\n * `auto_rig_from_layers` runs it. The composer meets that contract by\n * construction; these checks are for a set it did not cut (hand-prepared\n * layers, a re-cut) and for the drawings the contract cannot save: a mouth too\n * small to fold, a line too thin to close on, green the key left, an interior\n * with holes. The lip layers' straight edges are the split's cuts, and so are\n * the inside layers' (`mouth_tongue`, `mouth_teeth`), so the generic edge and\n * flat-cut checks skip them all (`isLipLayerRole`). Of an inside layer the rig reads\n * only its box, so it is checked for the set it needs, its canvas and its box.\n */\n\nimport path from \"node:path\";\nimport {\n ALPHA_OPAQUE,\n LIP_INSIDE_ROLES,\n LIP_ROLES,\n LayerGeometryError,\n columnRuns,\n createLayerSetMeasurer,\n isLipInsideRole,\n mouthOpening,\n type LayerInput,\n type LipInsideRole,\n type LipRole,\n type Opening,\n} from \"@ikijs/editor\";\nimport type { LayerStats } from \"./measure\";\nimport { MIN_OPENING_WIDTH } from \"./compose-lips\";\nimport { decodePng } from \"./node-images\";\n\n/** A lip set's layer: one of its three, or an inside layer. */\nexport const isLipLayerRole = (role: string): role is LipRole | LipInsideRole =>\n (LIP_ROLES as readonly string[]).includes(role) || isLipInsideRole(role);\n\n/** The opening's height at its centre, rows, under which it is too small to\n * fold. Our own value, provisional. */\nconst MIN_OPENING_ROWS = 8;\n/** The line's height at the centre, rows, under which a closed mouth has no\n * line to close on (a hairline folds to nothing). Our own value, provisional. */\nconst MIN_LINE_ROWS = 2;\n/** Green excess `g - max(r, b)` above which an opaque lip pixel is key green\n * left over rather than art. Our own value, provisional. */\nconst GREEN_EXCESS = 40;\n/** The share of the opening's area that may be transparent inside\n * `mouth_inner`'s own span before the face shows through it. Our own value,\n * provisional. */\nconst INTERIOR_GAP_FRACTION = 0.05;\n\n/** What the report says of the opening, for judging a half-open mouth. */\nexport interface LipFacts {\n opening: { width: number; height: number; line: number };\n /** `MouthOpen` below which the slit has not opened: `v* = w' / (H + w')`. */\n deadZone: number;\n}\n\n/** A list of columns as the warning names it: the count and the first. */\nconst columns = (cols: number[]) =>\n `${cols.length} column${cols.length === 1 ? \"\" : \"s\"} (first at x=${cols[0]})`;\n\n/**\n * Warn of a lip set the rig refuses or would fold badly, and report the\n * opening it reads. `layers` holds the measured, non-empty layers of `absDir`\n * by role; a set with no lip layer is a legacy mouth and says nothing.\n */\nexport async function lipWarnings(\n absDir: string,\n layers: Record<string, LayerStats>,\n): Promise<{ warnings: string[]; lips?: LipFacts }> {\n const warnings: string[] = [];\n const present = LIP_ROLES.filter((role) => layers[role] !== undefined);\n const inside = LIP_INSIDE_ROLES.filter((role) => layers[role] !== undefined);\n if (present.length === 0) {\n if (inside.length > 0) {\n warnings.push(\n `${inside.join(\"/\")}: a lip set's inside layer with no lip set — auto_rig_from_layers refuses ` +\n `it (it is cut from the interior and clipped to it). Recompose from mouth_keyed.png + ` +\n `mouth_interior.png, or remove it.`,\n );\n }\n return { warnings };\n }\n\n const legacy = [\"mouth\", \"mouth_open\"].filter(\n (role) => layers[role] !== undefined,\n );\n if (legacy.length > 0) {\n warnings.push(\n `${present.join(\"/\")}: the lip set cannot be mixed with ${legacy.join(\"/\")} — auto_rig_from_layers ` +\n `refuses it. Remove one route: compose again with only mouth_keyed.png + mouth_interior.png, ` +\n `or without them.`,\n );\n }\n if (present.length < LIP_ROLES.length) {\n const missing = LIP_ROLES.filter((role) => layers[role] === undefined);\n warnings.push(\n `${present.join(\"/\")}: partial lip set, missing ${missing.join(\"/\")} — auto_rig_from_layers ` +\n `refuses it. Compose mouth_keyed.png + mouth_interior.png together, which cuts all three.`,\n );\n return { warnings };\n }\n\n const { mouth_inner: inner, lip_upper: upper } = layers;\n for (const role of [\"lip_lower\", \"lip_upper\", ...inside]) {\n const stats = layers[role];\n if (stats.canvasW !== inner.canvasW || stats.canvasH !== inner.canvasH) {\n warnings.push(\n `${role}: its canvas ${stats.canvasW}x${stats.canvasH} differs from mouth_inner's ` +\n `${inner.canvasW}x${inner.canvasH} — auto_rig_from_layers refuses layers of different ` +\n `sizes; recompose them together.`,\n );\n return { warnings };\n }\n }\n // Of an inside layer the rig reads only its box, and the cavity clips\n // whatever leaves its own: the measured alpha > 8 box (`bboxCx ± w/2`), in\n // pixel edges.\n const box = (m: LayerStats) => ({\n x0: m.bboxCx - m.w / 2,\n x1: m.bboxCx + m.w / 2,\n y0: m.bboxCy - m.h / 2,\n y1: m.bboxCy + m.h / 2,\n });\n const cavity = box(inner);\n for (const role of inside) {\n const b = box(layers[role]);\n if (\n b.x0 < cavity.x0 ||\n b.x1 > cavity.x1 ||\n b.y0 < cavity.y0 ||\n b.y1 > cavity.y1\n ) {\n warnings.push(\n `${role}: its box leaves mouth_inner's — the cavity clips it away there. Recompose from ` +\n `mouth_keyed.png + mouth_interior.png (free).`,\n );\n }\n }\n\n const measurer = createLayerSetMeasurer({\n width: inner.canvasW,\n height: inner.canvasH,\n });\n const set = new Map<string, LayerInput>();\n const green: string[] = [];\n for (const role of LIP_ROLES) {\n const fileName = `${role}.png`;\n const { rgba } = await decodePng(path.join(absDir, fileName));\n // Decoded here rather than through `measured`: the green scan below needs\n // the pixels. layerStats counts alpha > 8 and the measurer alpha >= 8, so\n // a layer measured non-empty is never empty here.\n set.set(role, measurer.add({ role, fileName, rgba })!);\n for (let i = 0; i < rgba.length; i += 4) {\n if (\n rgba[i + 3] >= ALPHA_OPAQUE &&\n rgba[i + 1] - Math.max(rgba[i], rgba[i + 2]) > GREEN_EXCESS\n ) {\n green.push(role);\n break;\n }\n }\n }\n let opening: Opening;\n try {\n opening = mouthOpening(set);\n } catch (err) {\n if (err instanceof LayerGeometryError) {\n warnings.push(err.message);\n return { warnings };\n }\n throw err;\n }\n\n const innerRuns = columnRuns(set.get(\"mouth_inner\")!);\n const noInterior: number[] = [];\n const gap: number[] = [];\n const noLine: number[] = [];\n const skinGap: number[] = [];\n let area = 0;\n let hollow = 0;\n for (let x = opening.x0; x <= opening.x1; x++) {\n const runs = innerRuns.get(x);\n if (runs === undefined) {\n noInterior.push(x);\n continue;\n }\n const span = runs[runs.length - 1][1] - runs[0][0];\n area += span;\n hollow += span - runs.reduce((n, r) => n + r[1] - r[0], 0);\n const c = opening.at(x);\n if (c.lineH <= 0) noLine.push(x);\n else if (c.Tu > c.T) gap.push(x);\n if (c.Bl < c.Bb) skinGap.push(x);\n }\n // The composer always cuts to the contract, so these come from a set it did\n // not cut: recomposing from the two sources is the free fix.\n const recompose = (file: string, ask: string) =>\n `Recompose from mouth_keyed.png + mouth_interior.png (free); if it persists, regenerate ${file} ${ask}. Billed.`;\n const regenKeyed = recompose(\n \"mouth_keyed.png\",\n \"with a closed outline and solid lips under it\",\n );\n if (noInterior.length > 0) {\n warnings.push(\n `mouth_inner: no interior in ${columns(noInterior)} of the opening — the fold has nothing to scale there. ${recompose(\"mouth_interior.png\", \"as one solid cavity\")}`,\n );\n }\n if (gap.length > 0) {\n warnings.push(\n `lip_upper: a gap between the line and the interior in ${columns(gap)} — the face shows through it ` +\n `at rest (the interior's top must reach the line's ink). ${regenKeyed}`,\n );\n }\n if (noLine.length > 0) {\n warnings.push(\n `lip_upper: no line above the interior in ${columns(noLine)} — nothing closes the mouth there. ${regenKeyed}`,\n );\n }\n if (skinGap.length > 0) {\n warnings.push(\n `lip_lower: a gap between the interior and the skin in ${columns(skinGap)} — the face shows through ` +\n `it once the mouth opens (the skin must reach the interior's bottom). ${regenKeyed}`,\n );\n }\n\n const width = opening.x1 - opening.x0 + 1;\n const centre = opening.at(opening.centre);\n if (width < MIN_OPENING_WIDTH * upper.w) {\n warnings.push(\n `mouth_inner: the opening is ${width} px wide, ${Math.round((100 * width) / upper.w)}% of lip_upper's ${upper.w} px ` +\n `(under ${Math.round(100 * MIN_OPENING_WIDTH)}%) — too narrow to fold; the slit stays a hairline. ` +\n `Regenerate mouth_keyed.png with the mouth open wider. Billed.`,\n );\n }\n if (centre.H < MIN_OPENING_ROWS) {\n // measure_layers sees only the layers, so a set layout.mouth_inner.h is\n // named in the message; a w past the canvas is not suggested at all.\n const w = Math.ceil((upper.w * MIN_OPENING_ROWS) / centre.H);\n const retune = w <= inner.canvasW ? w : null;\n warnings.push(\n `mouth_inner: the opening is ${centre.H} px tall at its centre (under ${MIN_OPENING_ROWS}) — too small to fold; ` +\n `the slit stays shut until MouthOpen is nearly 1. ` +\n (retune === null\n ? \"\"\n : `If the mouth is smaller than the reference's, set layout.mouth_inner.w to ${retune} ` +\n `(free; the whole set scales with it, so scale layout.mouth_inner.h too if it is set). Otherwise `) +\n `${retune === null ? \"R\" : \"r\"}egenerate mouth_keyed.png with the mouth open taller. Billed.`,\n );\n }\n if (opening.w < MIN_LINE_ROWS) {\n warnings.push(\n `lip_upper: the upper line is ${opening.w} px at the opening's centre (under ${MIN_LINE_ROWS}) — a hairline ` +\n `closes to nothing. Regenerate mouth_keyed.png ` +\n `with a bolder upper line, never thinner than the reference's mouth line. Billed.`,\n );\n }\n if (green.length > 0) {\n warnings.push(\n `${green.join(\"/\")}: opaque green left (key green, g exceeds r and b by over ${GREEN_EXCESS}) — it shows as a ` +\n `green fringe on the lips. Regenerate mouth_keyed.png with the green only inside the opening, or ` +\n `mouth_interior.png without green in it. Billed.`,\n );\n }\n if (area > 0 && hollow > INTERIOR_GAP_FRACTION * area) {\n warnings.push(\n `mouth_inner: ${Math.round((100 * hollow) / area)}% of the opening is transparent inside the interior's ` +\n `own span (over ${Math.round(100 * INTERIOR_GAP_FRACTION)}%) — the face shows through it. ` +\n `Regenerate mouth_interior.png as one solid cavity. Billed.`,\n );\n }\n\n return {\n warnings,\n lips: {\n opening: { width, height: centre.H, line: opening.w },\n deadZone: centre.overlap / (centre.H + centre.overlap),\n },\n };\n}\n","/**\n * The pixel work that turns a green-keyed open mouth plus a drawn interior\n * into the lip set the rig folds (`mouth_inner`, `lip_lower`, `lip_upper`),\n * with the interior's light paint as `mouth_tongue` and `mouth_teeth`.\n * Buffers in, buffers out: no file is read here, the composer hands over what\n * it decoded and gets PNGs back.\n *\n * The key (`keyGreen`) runs at SOURCE resolution. A model's \"flat #00FF00\" is\n * never that (bob's came back as (9, 245, 3)) and its line has less green than\n * red, so no formula of a pixel's own colour gives a half-mixed pixel half its\n * alpha. The fill's colour is therefore read off the art (the median of the\n * clearly green pixels), and each pixel near the fill is read against the far\n * end of ITS OWN ramp: the farthest pixel in reach that lies on the line from\n * the fill's colour through the pixel. The antialiasing becomes alpha, which\n * the premultiplied resize that follows carries cleanly.\n *\n * The split (`splitLipSet`) runs at the COMPOSED size. Every boundary it cuts\n * on is then an integer row of the pixels the rig reads, and its assertion\n * reads them through the rig's own `mouthOpening`, so what the composer checks\n * is what the rig will see. The interior is grown sideways only under ink and\n * never above its own column's hole top, which is what keeps the rig's\n * per-column contract (`Tu <= T <= lineTop`, `Bl >= Bb`) true by construction\n * rather than by luck of the art.\n *\n * The interior is split by lightness on the hole: a pixel at or over\n * CAVITY_LUMA (a tooth, the tongue) goes to `mouth_teeth` above its column's\n * hole middle and to `mouth_tongue` below it, and `mouth_inner` takes the\n * cavity's fill there, so the cavity is a dark fill with its own shading that\n * the rig clips the two to, the teeth riding the line and the tongue the\n * opening's bottom. Its edge is soft: a frame pixel beside the hole whose ink\n * is partial (alpha 128..254) was ink mixed with green, and the cavity takes\n * its share of it, `255 - alpha`, under ALPHA_OPAQUE, so no read of the\n * contract changes.\n *\n * The two columns beside the hole are grown into under the outline's side\n * wall. When the frame has ink above the first grown row the wall is the\n * line's own end, and it folds with the interior (its grown rows join\n * `mouth_inner`, not `lip_upper`), so the rig reads the line's bottom at the\n * interior's top there too and the closed line's ends are the drawn ends,\n * tapered. A column with no ink above its first grown row (an under-the-line\n * end) keeps every pixel in `lip_upper`; the rig still accepts it, its wall\n * past the opening thinned and, shut, shaped like a drawn flick.\n *\n * The preview (`closedLips`) shows the set as the rig draws it at rest: the\n * lips resampled through the lip meshes' own landed rows (`mouthRestShift`,\n * measured as the rig measures the final canvas layers), so the thinned line\n * and its tapered ends are in it, the interior left out (shut, it has zero\n * height).\n */\n\nimport sharp from \"sharp\";\nimport {\n ALPHA_OPAQUE,\n columnRuns,\n createLayerSetMeasurer,\n mouthOpening,\n mouthRestShift,\n type LayerInput,\n type Opening,\n} from \"@ikijs/editor\";\nimport { AutoRigInputError } from \"./limits\";\nimport { cropToBuffer } from \"./node-images\";\nimport { TRIM_THRESHOLD, boxWithoutStraySpecks, luma } from \"./trim\";\n\nexport const KEYED_SRC = \"mouth_keyed.png\";\nexport const INTERIOR_SRC = \"mouth_interior.png\";\n\n/** Green excess `(g - max(r, b)) / 255` at which a visible pixel is a fill\n * candidate; the fill is never full excess (bob's is 0.925). */\nconst KEY_CANDIDATE = 0.5;\n/** Levels (Euclidean) from the fill's median colour within which a pixel is\n * the fill. A ramp's last pixels past it are cut with the fill. */\nconst KEY_FILL_DIST = 20;\n/** Px (Chebyshev) from the fill within which a pixel may be a mix with it, and\n * within which the plateau of its ramp is sought. */\nconst KEY_REACH = 8;\n/** Levels a reference may sit off the segment from its colour to the fill's. */\nconst KEY_COLLINEAR = 12;\n/** A share of green under this is a stroke's own shading, not a mix: read as\n * zero, a true mix this small left opaque is 13 levels off at most. */\nconst KEY_MIN_SHARE = 0.05;\n/** Green outside the opening's region, as a share of the opening's, over\n * which the key is refused. */\nconst STRAY_KEY_FRACTION = 0.02;\n/** The opening's width, as a share of the frame's, under which it is too\n * small to fold. */\nexport const MIN_OPENING_WIDTH = 0.3;\n/** A second hole as a share of the largest, from which the opening is not\n * one region. */\nconst SECOND_HOLE_FRACTION = 0.05;\n/** A dark pixel (luma under this) under the opening belongs to its lower\n * outline band; skin is lighter. */\nconst BAND_LUMA = 150;\n/** The band's cap, in strokes: more is not an outline. */\nconst BAND_CAP = 3;\n/** Luma under which an interior's pixel is cavity rather than tooth or tongue:\n * the cavity's fill is read under it, and the hole's pixels at or over it are\n * cut into `mouth_teeth` / `mouth_tongue`. */\nexport const CAVITY_LUMA = 100;\n/** The lip rim's skin rule, the spike's: a pixel is skin at red, green and\n * blue over these floors, which a peach lip clears and a cavity's dark red or\n * a tongue's pink does not; but not a tooth, whose green and blue are over\n * these ceilings (near-white). */\nconst SKIN_MIN_R = 225;\nconst SKIN_MIN_G = 160;\nconst SKIN_MIN_B = 135;\nconst TEETH_MIN_G = 215;\nconst TEETH_MIN_B = 205;\nconst isSkin = (r: number, g: number, b: number): boolean =>\n r > SKIN_MIN_R &&\n g > SKIN_MIN_G &&\n b > SKIN_MIN_B &&\n !(g > TEETH_MIN_G && b > TEETH_MIN_B);\n\ninterface Components {\n /** Per pixel: its set's index, or -1 off the mask. */\n label: Int32Array;\n sizes: number[];\n /** Inclusive pixel boxes. */\n boxes: { x0: number; y0: number; x1: number; y1: number }[];\n}\n\n/** The sets of a mask, 4-connected, flood-filled on a stack that never\n * outgrows the image: a pixel is marked as it is pushed. */\nfunction components(mask: Uint8Array, W: number, H: number): Components {\n const n = W * H;\n const label = new Int32Array(n).fill(-1);\n const stack = new Int32Array(n);\n const sizes: number[] = [];\n const boxes: Components[\"boxes\"] = [];\n for (let start = 0; start < n; start++) {\n if (!mask[start] || label[start] >= 0) continue;\n const id = sizes.length;\n const box = { x0: W, y0: H, x1: -1, y1: -1 };\n let size = 0;\n let depth = 0;\n label[start] = id;\n stack[depth++] = start;\n while (depth > 0) {\n const p = stack[--depth];\n size++;\n const px = p % W;\n const py = (p - px) / W;\n box.x0 = Math.min(box.x0, px);\n box.x1 = Math.max(box.x1, px);\n box.y0 = Math.min(box.y0, py);\n box.y1 = Math.max(box.y1, py);\n for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {\n for (let x = Math.max(0, px - 1); x <= Math.min(W - 1, px + 1); x++) {\n if (x !== px && y !== py) continue;\n const q = y * W + x;\n if (mask[q] && label[q] < 0) {\n label[q] = id;\n stack[depth++] = q;\n }\n }\n }\n }\n sizes.push(size);\n boxes.push(box);\n }\n return { label, sizes, boxes };\n}\n\n/** The largest set's index, or -1 for none. */\nconst largest = (sizes: number[]): number =>\n sizes.reduce((best, s, i) => (best < 0 || s > sizes[best] ? i : best), -1);\n\n/**\n * Chebyshev dilation of `mask` by `reach`: done along the rows and then down\n * the columns, which is the same box as one pass over the square.\n */\nfunction dilate(mask: Uint8Array, W: number, H: number, reach: number) {\n const rows = new Uint8Array(W * H);\n const prefix = new Int32Array(Math.max(W, H) + 1);\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) prefix[x + 1] = prefix[x] + mask[y * W + x];\n for (let x = 0; x < W; x++) {\n rows[y * W + x] =\n prefix[Math.min(W, x + reach + 1)] - prefix[Math.max(0, x - reach)] > 0\n ? 1\n : 0;\n }\n }\n const out = new Uint8Array(W * H);\n for (let x = 0; x < W; x++) {\n for (let y = 0; y < H; y++) prefix[y + 1] = prefix[y] + rows[y * W + x];\n for (let y = 0; y < H; y++) {\n out[y * W + x] =\n prefix[Math.min(H, y + reach + 1)] - prefix[Math.max(0, y - reach)] > 0\n ? 1\n : 0;\n }\n }\n return out;\n}\n\n/**\n * The share of green in the pixel at byte offset `i`, read against the\n * foreground at `j`: where it lies on the segment from `j`'s colour to `g`,\n * clamped to 0..1. `j`'s colour must not be `g`'s.\n */\nfunction shareOf(rgba: Buffer, i: number, j: number, g: number[]): number {\n const dr = g[0] - rgba[j];\n const dg = g[1] - rgba[j + 1];\n const db = g[2] - rgba[j + 2];\n const t =\n ((rgba[i] - rgba[j]) * dr +\n (rgba[i + 1] - rgba[j + 1]) * dg +\n (rgba[i + 2] - rgba[j + 2]) * db) /\n (dr * dr + dg * dg + db * db);\n return Math.min(1, Math.max(0, t));\n}\n\n/**\n * Key the green out of a straight-alpha RGBA mouth, estimating each mixed\n * pixel's real alpha. See the header: the fill is the art's own green, a pixel\n * near it is read against the farthest pixel in reach on its own colour ramp,\n * and a share under KEY_MIN_SHARE is shading, not green. A pixel under alpha\n * 128 is a candidate for nothing and a reference for nobody (a PNG keeps RGB\n * under zero alpha, so invisible green must neither open a hole nor spoil the\n * region check), but green left faintly visible is cleared with the fill: it\n * would come out of the resize as a green fringe on the lip.\n */\nexport function keyGreen(rgba: Buffer, W: number, H: number): Buffer {\n const n = W * H;\n const noGreen = new AutoRigInputError(\n `${KEYED_SRC}: no green opening (#00FF00) to key — regenerate it with the inside of the open mouth painted ONE flat pure green`,\n );\n\n const hist = [\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n ];\n let candidates = 0;\n for (let p = 0; p < n; p++) {\n const i = p * 4;\n if (rgba[i + 3] < ALPHA_OPAQUE) continue;\n const excess = (rgba[i + 1] - Math.max(rgba[i], rgba[i + 2])) / 255;\n if (excess < KEY_CANDIDATE) continue;\n candidates++;\n for (let c = 0; c < 3; c++) hist[c][rgba[i + c]]++;\n }\n if (candidates === 0) throw noGreen;\n const median = (h: Uint32Array): number => {\n let seen = 0;\n for (let v = 0; v < 256; v++) {\n seen += h[v];\n if (seen * 2 >= candidates) return v;\n }\n return 255;\n };\n const G = [median(hist[0]), median(hist[1]), median(hist[2])];\n\n // The fill: visible pixels the art's key colour owns. `ref` is every visible\n // pixel that is not (the only ones a mixed pixel may read itself against).\n const out = Buffer.from(rgba);\n const fill = new Uint8Array(n);\n const ref = new Uint8Array(n);\n let fillCount = 0;\n for (let p = 0; p < n; p++) {\n const i = p * 4;\n if (rgba[i + 3] === 0) continue;\n const dr = rgba[i] - G[0];\n const dg = rgba[i + 1] - G[1];\n const db = rgba[i + 2] - G[2];\n const green = dr * dr + dg * dg + db * db <= KEY_FILL_DIST * KEY_FILL_DIST;\n if (rgba[i + 3] < ALPHA_OPAQUE) {\n if (green) out[i + 3] = 0;\n } else if (green) {\n fill[p] = 1;\n fillCount++;\n } else {\n ref[p] = 1;\n }\n }\n if (fillCount === 0) throw noGreen;\n\n const reach = dilate(fill, W, H, KEY_REACH);\n const collinear = KEY_COLLINEAR * KEY_COLLINEAR;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n const p = y * W + x;\n if (!reach[p] || fill[p] || out[p * 4 + 3] === 0) continue;\n const i = p * 4;\n // The pixel itself always qualifies, so there is no fallback.\n let best = i;\n let bestD2 =\n (rgba[i] - G[0]) ** 2 +\n (rgba[i + 1] - G[1]) ** 2 +\n (rgba[i + 2] - G[2]) ** 2;\n const y1 = Math.min(H - 1, y + KEY_REACH);\n const x1 = Math.min(W - 1, x + KEY_REACH);\n for (let qy = Math.max(0, y - KEY_REACH); qy <= y1; qy++) {\n for (let qx = Math.max(0, x - KEY_REACH); qx <= x1; qx++) {\n const q = qy * W + qx;\n if (q === p || !ref[q]) continue;\n const j = q * 4;\n const d2 =\n (rgba[j] - G[0]) ** 2 +\n (rgba[j + 1] - G[1]) ** 2 +\n (rgba[j + 2] - G[2]) ** 2;\n if (d2 <= bestD2) continue;\n const t = shareOf(rgba, i, j, G);\n const er = rgba[i] - rgba[j] - t * (G[0] - rgba[j]);\n const eg = rgba[i + 1] - rgba[j + 1] - t * (G[1] - rgba[j + 1]);\n const eb = rgba[i + 2] - rgba[j + 2] - t * (G[2] - rgba[j + 2]);\n if (er * er + eg * eg + eb * eb > collinear) continue;\n bestD2 = d2;\n best = j;\n }\n }\n const k = shareOf(rgba, i, best, G);\n if (k < KEY_MIN_SHARE) continue;\n rgba.copy(out, i, best, best + 3);\n out[i + 3] = Math.round(rgba[i + 3] * (1 - k));\n }\n }\n for (let p = 0; p < n; p++) if (fill[p]) out[p * 4 + 3] = 0;\n\n const { sizes } = components(fill, W, H);\n const main = largest(sizes);\n const strays = sizes.filter((_, i) => i !== main);\n const strayPx = strays.reduce((a, b) => a + b, 0);\n if (strayPx > STRAY_KEY_FRACTION * sizes[main]) {\n throw new AutoRigInputError(\n `${KEYED_SRC}: green outside the opening (${strayPx} px in ${strays.length} regions beside the opening's) — the key must be one flat region inside the outline; regenerate with no green elsewhere`,\n );\n }\n return out;\n}\n\n/** Levels (per channel) from the ground's median colour within which a pixel\n * is the ground. Near-white teeth (250, 248, 245) sit 5..10 off a pure white\n * ground, so a floor like the legacy parts' 238 would key them out. */\nconst GROUND_TOLERANCE = 4;\n/** A border whose median is light in every channel (over this) is a ground,\n * not the drawing: a darker or more saturated one means the drawing itself\n * reaches the edges. A mid-grey ground under it therefore passes through, read\n * as the drawing reaching the edges. */\nconst GROUND_LIGHT = 200;\n/** The floor of a light ground the interior is keyed against: a light ground\n * under it in some channel (cream, grey) is not white. */\nconst GROUND_MIN = 238;\n/** The share of the border a white ground must own: under it the ground has\n * heavy noise, a gradient or a checkerboard \"fake transparency\" along the\n * border itself (a checkerboard owns about half), and the key would leave a\n * rind of it round the drawing. A drawing may touch about a third of the\n * border and still pass. */\nconst GROUND_BORDER_SHARE = 0.65;\n\n/**\n * Key the white ground out of an interior that came without alpha: the pixels\n * 4-connected to the border within GROUND_TOLERANCE of the border's median\n * colour. The legacy parts' rule (every near-white pixel) would take the teeth\n * with it, and the teeth are what this part is for. A light ground that is\n * not white (cream, grey), or a white one with heavy noise or a gradient along\n * the border that leaves it owning under half of it, cannot be keyed cleanly\n * and is refused: stretched into the opening it would show as a box. A border\n * that is not light is the drawing itself reaching the edges (\"filling the\n * image\"): only the white connected to the border is keyed, the corners an oval\n * leaves.\n */\nexport function keyBorderWhite(rgba: Buffer, W: number, H: number): Buffer {\n const border: number[][] = [[], [], []];\n const edge = (p: number) => {\n for (let c = 0; c < 3; c++) border[c].push(rgba[p * 4 + c]);\n };\n for (let x = 0; x < W; x++) {\n edge(x);\n edge((H - 1) * W + x);\n }\n for (let y = 1; y < H - 1; y++) {\n edge(y * W);\n edge(y * W + W - 1);\n }\n const ground = border.map((v) => v.sort((a, b) => a - b)[v.length >> 1]);\n const light = ground.every((v) => v >= GROUND_LIGHT);\n if (light && ground.some((v) => v < GROUND_MIN)) {\n throw new AutoRigInputError(\n `${INTERIOR_SRC} came back opaque on a non-white ground — regenerate it with a transparent background. Billed.`,\n );\n }\n if (!light) ground.fill(255);\n\n const out = Buffer.from(rgba);\n const seen = new Uint8Array(W * H);\n const stack = new Int32Array(W * H);\n let depth = 0;\n const seed = (p: number) => {\n if (seen[p]) return;\n for (let c = 0; c < 3; c++) {\n if (Math.abs(rgba[p * 4 + c] - ground[c]) > GROUND_TOLERANCE) return;\n }\n seen[p] = 1;\n stack[depth++] = p;\n };\n for (let x = 0; x < W; x++) {\n seed(x);\n seed((H - 1) * W + x);\n }\n for (let y = 0; y < H; y++) {\n seed(y * W);\n seed(y * W + W - 1);\n }\n if (light && depth < GROUND_BORDER_SHARE * border[0].length) {\n throw new AutoRigInputError(\n `${INTERIOR_SRC} came back opaque on a white ground too noisy or shaded to key cleanly — regenerate it with a transparent background. Billed.`,\n );\n }\n while (depth > 0) {\n const p = stack[--depth];\n out[p * 4 + 3] = 0;\n const x = p % W;\n if (x > 0) seed(p - 1);\n if (x < W - 1) seed(p + 1);\n if (p >= W) seed(p - W);\n if (p < W * H - W) seed(p + W);\n }\n return out;\n}\n\n/** The box of the part's drawing: the composer's trim (stray specks aside),\n * or every pixel the trim keeps when no speck lies outside the drawing.\n * null when nothing is kept. */\nfunction drawingBox(rgba: Buffer, W: number, H: number) {\n const speckless = boxWithoutStraySpecks(rgba, W, H);\n if (speckless !== null) {\n return {\n x: speckless.left,\n y: speckless.top,\n w: speckless.width,\n h: speckless.height,\n };\n }\n let x0 = W;\n let y0 = H;\n let x1 = -1;\n let y1 = -1;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n if (rgba[(y * W + x) * 4 + 3] <= TRIM_THRESHOLD) continue;\n x0 = Math.min(x0, x);\n x1 = Math.max(x1, x);\n y0 = Math.min(y0, y);\n y1 = Math.max(y1, y);\n }\n }\n return x1 < 0 ? null : { x: x0, y: y0, w: x1 - x0 + 1, h: y1 - y0 + 1 };\n}\n\n/**\n * The drawn interior, ready to fit into the opening: trimmed, with the lip rim\n * a generator draws round the cavity removed (the skin-coloured sets touching\n * the trimmed border: the spike's interior prompt drew a peach lower lip\n * twice), and the cavity's colour read off what is left, for the flat fill the\n * split lays under it. The caller has keyed a white ground out of an interior\n * that came without alpha.\n */\nexport async function prepInterior(\n rgba: Buffer,\n W: number,\n H: number,\n): Promise<{ png: Buffer; cavity: [number, number, number] }> {\n const empty = new AutoRigInputError(\n `${INTERIOR_SRC}: nothing but lips/skin after trimming — regenerate it with the cavity, the teeth and the tongue only, NO lips`,\n );\n const first = drawingBox(rgba, W, H);\n if (first === null) throw empty;\n const cw = first.w;\n const ch = first.h;\n const crop = Buffer.alloc(cw * ch * 4);\n for (let y = 0; y < ch; y++) {\n const from = ((first.y + y) * W + first.x) * 4;\n rgba.copy(crop, y * cw * 4, from, from + cw * 4);\n }\n\n const skin = new Uint8Array(cw * ch);\n for (let p = 0; p < cw * ch; p++) {\n const i = p * 4;\n if (\n crop[i + 3] > TRIM_THRESHOLD &&\n isSkin(crop[i], crop[i + 1], crop[i + 2])\n )\n skin[p] = 1;\n }\n const { label, boxes } = components(skin, cw, ch);\n const rim = boxes.map(\n (b) => b.x0 === 0 || b.y0 === 0 || b.x1 === cw - 1 || b.y1 === ch - 1,\n );\n for (let p = 0; p < cw * ch; p++) {\n if (label[p] >= 0 && rim[label[p]]) crop[p * 4 + 3] = 0;\n }\n\n const box = drawingBox(crop, cw, ch);\n if (box === null) throw empty;\n\n // The cavity: the dark pixels' mean, or everything's when none is dark.\n const sum = [0, 0, 0];\n const all = [0, 0, 0];\n let dark = 0;\n let count = 0;\n for (let y = box.y; y < box.y + box.h; y++) {\n for (let x = box.x; x < box.x + box.w; x++) {\n const i = (y * cw + x) * 4;\n if (crop[i + 3] < ALPHA_OPAQUE) continue;\n count++;\n for (let c = 0; c < 3; c++) all[c] += crop[i + c];\n if (luma(crop, i) < CAVITY_LUMA) {\n dark++;\n for (let c = 0; c < 3; c++) sum[c] += crop[i + c];\n }\n }\n }\n if (count === 0) throw empty;\n const [from, over] = dark > 0 ? [sum, dark] : [all, count];\n const cavity = from.map((v) => Math.round(v / over)) as [\n number,\n number,\n number,\n ];\n return { png: await cropToBuffer(crop, cw, ch, box), cavity };\n}\n\nconst rawOf = async (png: Buffer) =>\n sharp(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });\n\nconst encode = (rgba: Buffer, w: number, h: number) =>\n sharp(rgba, { raw: { width: w, height: h, channels: 4 } })\n .png()\n .toBuffer();\n\n/**\n * The opening of a keyed frame: its transparent pixels the outside cannot\n * reach through transparent pixels (so its boundary is at or above\n * ALPHA_OPAQUE), as the largest set of them. Refuses a frame with no such hole,\n * one too narrow to fold, and one with a second hole of\n * SECOND_HOLE_FRACTION of the largest or more.\n */\nfunction enclosedHole(frame: Buffer, w: number, h: number) {\n const n = w * h;\n const alpha = (p: number) => frame[p * 4 + 3];\n const outside = new Uint8Array(n);\n const stack = new Int32Array(n);\n let depth = 0;\n const seed = (p: number) => {\n if (!outside[p] && alpha(p) < ALPHA_OPAQUE) {\n outside[p] = 1;\n stack[depth++] = p;\n }\n };\n for (let x = 0; x < w; x++) {\n seed(x);\n seed((h - 1) * w + x);\n }\n for (let y = 0; y < h; y++) {\n seed(y * w);\n seed(y * w + w - 1);\n }\n while (depth > 0) {\n const p = stack[--depth];\n const x = p % w;\n if (x > 0) seed(p - 1);\n if (x < w - 1) seed(p + 1);\n if (p >= w) seed(p - w);\n if (p < n - w) seed(p + w);\n }\n const mask = new Uint8Array(n);\n for (let p = 0; p < n; p++) {\n if (alpha(p) < ALPHA_OPAQUE && !outside[p]) mask[p] = 1;\n }\n const { label, sizes, boxes } = components(mask, w, h);\n const main = largest(sizes);\n if (main < 0) {\n throw new AutoRigInputError(\n `${KEYED_SRC}: the outline is not closed round the opening (the key reached the outside, or the line is broken or too thin at this size) — regenerate with ONE closed, bolder outline`,\n );\n }\n const box = boxes[main];\n const holeW = box.x1 - box.x0 + 1;\n if (holeW < MIN_OPENING_WIDTH * w) {\n throw new AutoRigInputError(\n `${KEYED_SRC}: the opening is only ${holeW} px wide of the mouth's ${w} — too small to fold; regenerate with the mouth open wider, or, if its outline is broken (only a small pocket of the opening was enclosed), with ONE closed, bolder outline`,\n );\n }\n const others = sizes.filter(\n (s, i) => i !== main && s >= SECOND_HOLE_FRACTION * sizes[main],\n );\n if (others.length > 0) {\n throw new AutoRigInputError(\n `${KEYED_SRC}: the opening is not one connected region (${others.length + 1} holes: teeth or tongue drawn into the green?) — regenerate with nothing drawn inside the green`,\n );\n }\n return { label, main, box };\n}\n\ntype LipRgba = { mouth_inner: Buffer; lip_lower: Buffer; lip_upper: Buffer };\n\n/** The three layers, raw RGBA on a `w` x `h` canvas, as the rig measures\n * them; null for a layer with no opaque pixel. */\nfunction measureLips(\n layers: LipRgba,\n w: number,\n h: number,\n): Map<string, LayerInput | null> {\n const measurer = createLayerSetMeasurer({ width: w, height: h });\n return new Map(\n Object.entries(layers).map(([role, rgba]) => [\n role,\n measurer.add({ role, fileName: `${role}.png`, rgba }),\n ]),\n );\n}\n\n/**\n * Read the three layers back through the rig's own `mouthOpening` and assert\n * the fold's contract on every column of the opening it reads. A violation is\n * an invariant of the split, not input, so it throws a plain Error naming the\n * column.\n */\nfunction assertFoldContract(layers: LipRgba, w: number, h: number): Opening {\n const byRole = new Map<string, LayerInput>();\n for (const [role, layer] of measureLips(layers, w, h)) {\n // The outline above the opening and the interior in it always exist; the\n // skin under it is the art's.\n if (layer === null && role === \"lip_lower\") {\n throw new AutoRigInputError(\n `${KEYED_SRC}: no lip_lower after the split — there is no skin under the opening; draw the lower lip under the outline`,\n );\n }\n byRole.set(role, layer!);\n }\n const opening = mouthOpening(byRole);\n const runs = columnRuns(byRole.get(\"mouth_inner\")!);\n for (let col = opening.x0; col <= opening.x1; col++) {\n const c = opening.at(col);\n const why = !runs.has(col)\n ? \"has no interior run\"\n : c.Tu > c.T\n ? `has a gap between the line and the interior (Tu ${c.Tu} > T ${c.T})`\n : c.T > c.lineTop || c.lineH <= 0\n ? `has no line above the interior (T ${c.T}, line top ${c.lineTop})`\n : c.Bl < c.Bb\n ? `has a gap between the interior and the skin (Bl ${c.Bl} < Bb ${c.Bb})`\n : null;\n if (why !== null) throw new Error(`splitLipSet: column ${col} ${why}`);\n }\n return opening;\n}\n\n/**\n * Split a keyed, trimmed and composed-size mouth frame into the lip set. Per\n * opening column (a column of the enclosed hole) `top` / `bot` are the hole's\n * first row and last row + 1:\n * lip_upper every pixel above `top`, every pixel of a column outside the\n * opening (the corner hooks) except a side wall's grown rows, the\n * hole's faint upper half;\n * mouth_inner the band (the ink from `bot` down while dark, at most\n * BAND_CAP strokes) over the interior over a flat cavity fill, on\n * the hole, the band and the first skin row `R`, grown once\n * sideways under ink and never above its own column's `top`\n * (the grown rows of a side column with ink above them are\n * `lip_upper`'s no longer: the wall folds with the interior);\n * lip_lower every row from `R` down (row `R` is in both: a one-row overlap,\n * not a gap);\n * mouth_teeth / mouth_tongue the hole's pixels whose colour in `mouth_inner`\n * is at or over CAVITY_LUMA, above / below the column's hole\n * middle, opaque; `mouth_inner` takes the cavity's fill there;\n * the rim a frame pixel outside `mouth_inner` beside the hole with alpha\n * 128..254: the cavity's fill at `255 - alpha` in `mouth_inner`.\n * A side column (beside the hole) whose frame has no ink above its first grown\n * row keeps those rows in `lip_upper` and out of `mouth_inner`'s fold.\n * The result is read back through the rig's own `mouthOpening` and the\n * contract asserted (`assertFoldContract`).\n */\nexport async function splitLipSet(\n keyedPng: Buffer,\n w: number,\n h: number,\n interior: { png: Buffer; cavity: [number, number, number] },\n): Promise<{\n inner: Buffer;\n lower: Buffer;\n upper: Buffer;\n tongue: Buffer;\n teeth: Buffer;\n opening: Opening;\n}> {\n const { data: frame, info } = await rawOf(keyedPng);\n if (info.width !== w || info.height !== h) {\n throw new Error(\n `splitLipSet: the frame is ${info.width}x${info.height}, not ${w}x${h}`,\n );\n }\n const n = w * h;\n const alpha = (p: number) => frame[p * 4 + 3];\n const { label, main, box: hb } = enclosedHole(frame, w, h);\n const holeW = hb.x1 - hb.x0 + 1;\n\n const top = new Int32Array(w).fill(-1);\n const bot = new Int32Array(w).fill(-1);\n for (let y = 0; y < h; y++) {\n for (let x = hb.x0; x <= hb.x1; x++) {\n if (label[y * w + x] !== main) continue;\n if (top[x] < 0) top[x] = y;\n bot[x] = y + 1;\n }\n }\n // The stroke: the opaque rows directly above the hole at its centre column.\n const centre = Math.round((hb.x0 + hb.x1) / 2);\n let stroke = 0;\n while (\n top[centre] - 1 - stroke >= 0 &&\n alpha((top[centre] - 1 - stroke) * w + centre) >= ALPHA_OPAQUE\n )\n stroke++;\n const bandCap = BAND_CAP * Math.max(1, stroke);\n\n // Per opening column: the band's end and the first skin row R (-1: none).\n const skinRow = new Int32Array(w).fill(-1);\n const inM = new Uint8Array(n);\n for (let x = hb.x0; x <= hb.x1; x++) {\n let y = bot[x];\n while (\n y < h &&\n y - bot[x] < bandCap &&\n alpha(y * w + x) >= ALPHA_OPAQUE &&\n luma(frame, (y * w + x) * 4) < BAND_LUMA\n )\n y++;\n for (let k = top[x]; k < y; k++) inM[k * w + x] = 1;\n let r = y;\n while (r < h && alpha(r * w + x) < ALPHA_OPAQUE) r++;\n if (r < h) {\n skinRow[x] = r;\n inM[r * w + x] = 1;\n }\n }\n\n // Grown once, from M as it was: sideways, under ink only, and in an opening\n // column never above its own hole top.\n const grown = Uint8Array.from(inM);\n for (let y = 0; y < h; y++) {\n for (let x = 0; x < w; x++) {\n const p = y * w + x;\n if (inM[p] || alpha(p) < ALPHA_OPAQUE) continue;\n if (top[x] >= 0 && y < top[x]) continue;\n if ((x > 0 && inM[p - 1]) || (x < w - 1 && inM[p + 1])) grown[p] = 1;\n }\n }\n\n // The columns beside the hole whose grown rows are the outline's side wall:\n // the frame is opaque on the row above the first one. Those rows fold with\n // the interior; a column with no ink above them keeps its pixels in the\n // line (an under-the-line end the rig still accepts, its wall thinned and,\n // shut, shaped like a drawn flick).\n const wall = new Uint8Array(w);\n for (const x of [hb.x0 - 1, hb.x1 + 1]) {\n if (x < 0 || x >= w) continue;\n let first = 0;\n while (first < h && !(grown[first * w + x] && !inM[first * w + x])) first++;\n if (first > 0 && first < h && alpha((first - 1) * w + x) >= ALPHA_OPAQUE)\n wall[x] = 1;\n }\n\n // The interior fitted to the hole's box grown one pixel each side.\n const gx = hb.x0 - 1;\n const gy = hb.y0 - 1;\n const gw = holeW + 2;\n const gh = hb.y1 - hb.y0 + 3;\n const { data: fitted } = await sharp(interior.png)\n .resize(gw, gh, { fit: \"fill\" })\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n\n const hole = (q: number) => label[q] === main;\n // Above its column's hole middle: the line's half of the opening, for the\n // faint pixels and for the light paint alike.\n const upperHalf = (x: number, y: number) => 2 * y < top[x] + bot[x];\n // The hole's faint pixels in its upper half are the line's antialiasing, the\n // lower half's the band's.\n const faintUpper = (p: number, x: number, y: number) =>\n y < bot[x] && hole(p) && upperHalf(x, y);\n const besideHole = (p: number, x: number, y: number) =>\n (x > 0 && hole(p - 1)) ||\n (x < w - 1 && hole(p + 1)) ||\n (y > 0 && hole(p - w)) ||\n (y < h - 1 && hole(p + w));\n\n const upper = Buffer.alloc(n * 4);\n const lower = Buffer.alloc(n * 4);\n const inner = Buffer.alloc(n * 4);\n const tongue = Buffer.alloc(n * 4);\n const teeth = Buffer.alloc(n * 4);\n const copy = (to: Buffer, p: number) =>\n frame.copy(to, p * 4, p * 4, p * 4 + 4);\n for (let y = 0; y < h; y++) {\n for (let x = 0; x < w; x++) {\n const p = y * w + x;\n const inOpening = top[x] >= 0;\n if (\n (!inOpening || y < top[x] || faintUpper(p, x, y)) &&\n !(wall[x] && grown[p])\n )\n copy(upper, p);\n if (inOpening && skinRow[x] >= 0 && y >= skinRow[x]) copy(lower, p);\n\n if (!grown[p]) {\n // The rim: the ink's partial alpha is its coverage, the rest the\n // opening's, which the cavity fills.\n const a = alpha(p);\n if (a >= ALPHA_OPAQUE && a < 255 && besideHole(p, x, y)) {\n inner.set(interior.cavity, p * 4);\n inner[p * 4 + 3] = 255 - a;\n }\n continue;\n }\n const out = [...interior.cavity];\n const ix = x - gx;\n const iy = y - gy;\n if (ix >= 0 && ix < gw && iy >= 0 && iy < gh) {\n const i = (iy * gw + ix) * 4;\n const a = fitted[i + 3] / 255;\n for (let c = 0; c < 3; c++) out[c] += (fitted[i + c] - out[c]) * a;\n }\n // The frame's own ink goes over it on the hole's rows (but not the faint\n // upper half, which is the line's), on the band and the skin row, and on\n // a side wall's rows.\n if ((inM[p] || wall[x]) && !faintUpper(p, x, y)) {\n const a = alpha(p) / 255;\n for (let c = 0; c < 3; c++) out[c] += (frame[p * 4 + c] - out[c]) * a;\n }\n inner[p * 4] = Math.round(out[0]);\n inner[p * 4 + 1] = Math.round(out[1]);\n inner[p * 4 + 2] = Math.round(out[2]);\n inner[p * 4 + 3] = 255;\n // The hole's light paint is a layer of its own, and the cavity is\n // repainted its fill under it.\n if (hole(p) && luma(inner, p * 4) >= CAVITY_LUMA) {\n const to = upperHalf(x, y) ? teeth : tongue;\n inner.copy(to, p * 4, p * 4, p * 4 + 4);\n inner.set(interior.cavity, p * 4);\n }\n }\n }\n\n const opening = assertFoldContract(\n { mouth_inner: inner, lip_lower: lower, lip_upper: upper },\n w,\n h,\n );\n const [innerPng, lowerPng, upperPng, tonguePng, teethPng] = await Promise.all(\n [inner, lower, upper, tongue, teeth].map((b) => encode(b, w, h)),\n );\n return {\n inner: innerPng,\n lower: lowerPng,\n upper: upperPng,\n tongue: tonguePng,\n teeth: teethPng,\n opening,\n };\n}\n\n/**\n * The rig's rest shift of the lips for the three canvas-sized layers: the\n * lip meshes' own field at MouthOpen 0 (`mouthRestShift`). Measured on the\n * canvas, not on the mouth-sized frame: `detectAlphaBbox` grows a box a pixel\n * each side and clamps it to the image, so a frame clamps where the canvas\n * does not, and the knot grid, which starts at the union's edge, lands\n * elsewhere. The measurement is the rig's own, of the same bytes.\n */\nexport async function restShiftOf(\n layers: { mouth_inner: Buffer; lip_lower: Buffer; lip_upper: Buffer },\n width: number,\n height: number,\n): Promise<ReturnType<typeof mouthRestShift>> {\n const [mouth_inner, lip_lower, lip_upper] = await Promise.all(\n [layers.mouth_inner, layers.lip_lower, layers.lip_upper].map(\n async (png) => (await rawOf(png)).data,\n ),\n );\n const byRole = new Map<string, LayerInput>();\n for (const [role, layer] of measureLips(\n { mouth_inner, lip_lower, lip_upper },\n width,\n height,\n )) {\n if (layer === null) {\n throw new AutoRigInputError(\n `layout.mouth_inner places the lip set so that ${role} falls off the canvas (nothing of it is left) — move it back on the canvas`,\n );\n }\n byRole.set(role, layer);\n }\n return mouthRestShift(byRole);\n}\n\n/**\n * The lips as the rig draws them at rest (MouthOpen 0), each column resampled\n * through the lip mesh's own landed rows: a source row lands at its centre\n * moved by the field there (`mouthRestShift`, the same knots, triangles and\n * stored offsets the rig has, so the preview is what the mesh draws; a\n * per-column fold is a pixel or more off on the lower lip, whose fold carries\n * integer-row reads). Only the rows whose centres the field answers land:\n * those inside the part's box, the layer's alpha box, so every row outside it\n * is transparent and contributes nothing, but for the one beyond each end,\n * landed a step past the edge row for the edge to blend into. The thin and\n * the squashes are positive scales, so the landed rows keep their order; each\n * destination row is blended linearly from the two consecutive landed rows\n * bracketing its centre, the way the GPU samples the mesh (rounding per row\n * would turn the smooth arc into a staircase the rig never draws),\n * premultiplied so an edge neither darkens nor lightens, and is transparent\n * when no pair brackets it. A constant field is a plain sub-pixel shift. The\n * flick's sideways pull is not previewed: the field is a column's dy alone.\n * `left` and `top` are the\n * frame's column and row on the canvas; +y is up and rows go down the image,\n * so a row lands at -dy. The interior is left out: shut, it has no height.\n */\nexport async function closedLips(\n upper: Buffer,\n lower: Buffer,\n shift: ReturnType<typeof mouthRestShift>,\n left: number,\n top: number,\n): Promise<{ upper: Buffer; lower: Buffer }> {\n const shut = async (png: Buffer, role: \"lip_upper\" | \"lip_lower\") => {\n const { data, info } = await rawOf(png);\n const { width: w, height: h } = info;\n const out = Buffer.alloc(w * h * 4);\n for (let x = 0; x < w; x++) {\n const px = (row: number, c: number) =>\n row < 0 || row >= h ? 0 : data[(row * w + x) * 4 + c];\n // [source row, its landed centre], in row order.\n const landed: [number, number][] = [];\n for (let row = 0; row < h; row++) {\n const dy = shift(role, left + x, top + row);\n if (dy !== undefined) landed.push([row, row + 0.5 - dy]);\n }\n // The rows just past the box (transparent), a landed step beyond its\n // edge rows: the edge rows blend into nothing over their outer half,\n // as a drawn edge does, rather than ending at their centres.\n if (landed.length > 1) {\n const [a, b] = landed;\n const [y, z] = landed.slice(-2);\n landed.unshift([a[0] - 1, 2 * a[1] - b[1]]);\n landed.push([z[0] + 1, 2 * z[1] - y[1]]);\n }\n let i = 0;\n for (let to = 0; to < h; to++) {\n const centre = to + 0.5;\n while (i + 1 < landed.length && landed[i + 1][1] < centre) i++;\n if (i + 1 >= landed.length || landed[i][1] > centre) continue;\n const [r0, y0] = landed[i];\n const [r1, y1] = landed[i + 1];\n const t = (centre - y0) / (y1 - y0);\n const a0 = px(r0, 3);\n const a1 = px(r1, 3);\n const a = (1 - t) * a0 + t * a1;\n if (a === 0) continue;\n const o = (to * w + x) * 4;\n for (let c = 0; c < 3; c++)\n out[o + c] = Math.round(\n ((1 - t) * a0 * px(r0, c) + t * a1 * px(r1, c)) / a,\n );\n out[o + 3] = Math.round(a);\n }\n }\n return encode(out, w, h);\n };\n const [u, l] = await Promise.all([\n shut(upper, \"lip_upper\"),\n shut(lower, \"lip_lower\"),\n ]);\n return { upper: u, lower: l };\n}\n","/**\n * Measure the head-turn cues in a PAIR of images of the same character — one\n * facing front, one turned — and report them as three ratios. It is how a\n * rigged turn gets compared to a reference turn without either image being\n * registered to the other: every number below is a front→turned CHANGE,\n * divided by something measured in the same image. That cancels crop and\n * position, not SCALE: the head span is sampled over a FIXED ±HEAD_BAND row\n * band, so a pair at different resolutions — or a character redrawn larger or\n * smaller between the two shots — would read as a turn that never happened.\n * The pair MUST already share framing and head size; this only checks it, it\n * does not correct for it. The check is a yaw does not change iris HEIGHT, so\n * a front/turned pair whose mean iris height differs is refused rather than\n * measured (see `measureTurnReference`).\n *\n * farEyeRatio how much the far eye narrows, over what it already was at\n * rest (a resting asymmetry in the art is divided out)\n * eyeShift how far the eye pair slides across the head, in units of\n * the FRONT head half-width (hh); negative = toward the\n * image's left\n * silhouetteRatio how much the head narrows, turned over front\n *\n * Read-only over two files; it edits nothing. Ported from the measurement\n * script this repo's turn work ran by hand, so the numbers a rig is tuned\n * against come out of the server every agent already has.\n *\n * `sharp` must stay confined to @ikijs/mcp; the decode and the debug-overlay\n * encode both go through ./node-images, this package's single image boundary.\n */\n\nimport path from \"node:path\";\nimport {\n ALPHA_OPAQUE,\n HEAD_BAND,\n foregroundSpan,\n headHalfOf,\n} from \"@ikijs/editor\";\nimport { decodePng, encodeOverlayPng } from \"./node-images\";\nimport {\n AutoRigInputError,\n resolveInputPath,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\n\n// Re-exported so compose.ts, measure.ts and the tests keep their imports.\nexport {\n SPECK_CORE_FRACTION,\n denseCoreOf,\n headHalfOf,\n isSpeckCore,\n} from \"@ikijs/editor\";\n\n/**\n * Hue/saturation window that selects the iris. Anime irises are a saturated\n * colour on a face that is not, which is what makes them findable at all; the\n * default window is violet-to-blue because that is what the characters this was\n * tuned on have. A character with, say, amber eyes passes its own window.\n */\nexport interface IrisColor {\n /** Inclusive hue bounds in degrees (0..360). */\n hueMin: number;\n hueMax: number;\n /** Minimum HSV saturation (0..1) — separates the iris from the skin. */\n satMin: number;\n}\n\nconst DEFAULT_IRIS: IrisColor = { hueMin: 230, hueMax: 300, satMin: 0.22 };\n\n// Value window, NOT a parameter: it excludes the specular highlight (near\n// white) and the pupil/lash ink (near black) whatever the iris hue is, so the\n// blob that survives is the coloured ring itself.\nconst IRIS_V_MIN = 0.18;\nconst IRIS_V_MAX = 0.95;\n// A blob whose surviving pixels average darker than this is lash ink or a\n// shadow that crept through the hue window, not an iris.\nconst IRIS_MEAN_V_MIN = 0.32;\n// The pupil and the specular highlight split the coloured ring into pieces; a\n// morphological CLOSE (dilate, then erode by the same radius) welds them back\n// into one component WITHOUT moving the blob's edges. A bare dilate would do\n// the welding too, but it adds its radius to every width, and that bias does\n// not cancel in far/near — it pushes the ratio toward 1 by an amount that\n// depends on how many pixels wide the iris happens to be.\nconst CLOSE_RADIUS = 3;\n// ...at the size it was tuned on; a smaller image gets a proportionally smaller\n// radius (at least 1 px), the way the area floor below is scaled.\nconst CLOSE_RADIUS_REFERENCE_PX = 1254;\n// An iris is small. Anything wider or taller than this fraction of the image is\n// hair, a collar, or the face itself leaking through the hue window.\nconst BLOB_MAX_FRAC = 0.12;\n// A KEYED head span this wide is not a head: the hue/sat/value backdrop rule\n// found no background at all, so the whole frame reads as foreground — a\n// backdrop that is not the lavender-grey it keys on (a plain screenshot, a\n// different key colour), not a character that fills the canvas edge to edge.\nconst KEYED_SPAN_MAX_FRAC = 0.95;\n// Area floor, scaled from the 300 px it was tuned at on a 1254² reference so\n// the same physical blob survives on a smaller render.\nconst MIN_AREA_REFERENCE_PIXELS = 1254 * 1254;\nconst MIN_AREA = 300;\n// Two irises sit apart but level. Below the dx floor is one iris found twice\n// (highlight vs ring), above the ceiling is an iris paired with a hair clip.\nconst PAIR_DX_MIN_FRAC = 0.08;\nconst PAIR_DX_MAX_FRAC = 0.35;\nconst PAIR_DY_MAX_FRAC = 0.05;\n/** Blobs kept as pair candidates, largest first — the pair search is O(n²). */\nconst MAX_CANDIDATES = 12;\n\n// --- Foreground (silhouette) rule -----------------------------------------\n// Two modes, chosen per image, because the two kinds of image this compares\n// carry their background differently and neither rule works on both.\n//\n// \"alpha\" an ENGINE RENDER: transparent backdrop. Foreground is alpha alone\n// — and nothing else. Its character pixels include near-black hair\n// ink and pale lavender highlights, both of which the keyed rule\n// below would eat, and the head would come back narrower than it is.\n// It is also the rule to follow when measuring the same silhouette\n// from the layer PNGs' own alpha, so the two are comparable.\n// \"keyed\" a fully opaque REFERENCE: no alpha to read, so the flat\n// lavender-grey backdrop is keyed out by colour instead, along with\n// a near-black frame/letterbox border.\nconst BG_HUE_MIN = 220;\nconst BG_HUE_MAX = 260;\nconst BG_SAT_MAX = 0.2;\nconst BG_V_MIN = 0.55;\nconst BG_V_BLACK = 0.03;\n\n/** Connected blob of iris-coloured pixels, in image px. */\nexport interface IrisBlob {\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n w: number;\n h: number;\n area: number;\n cx: number;\n cy: number;\n}\n\n/** One image's measurement. `irisL`/`irisR` are ordered by x in the IMAGE. */\nexport interface TurnImageMeasure {\n file: string;\n width: number;\n height: number;\n maskMode: \"alpha\" | \"keyed\";\n irisL: IrisBlob;\n irisR: IrisBlob;\n /** Mean row of the two iris centres. */\n eyeRow: number;\n /** Head silhouette span at the eye row. */\n head: { left: number; right: number; cx: number; half: number };\n /** Mean column of the two iris centres. */\n pairCx: number;\n eyeGap: number;\n}\n\nexport interface TurnMeasurement {\n front: TurnImageMeasure;\n turned: TurnImageMeasure;\n /** Turned far/near iris width over the same ratio at rest. */\n farEyeRatio: number;\n /** Front→turned slide of the eye pair across the head, in FRONT hh units. */\n eyeShift: number;\n /** Head half-width, turned over front. */\n silhouetteRatio: number;\n /** -1 = the head turned toward the image's left, +1 = toward its right. */\n turnSign: -1 | 1;\n /** Debug overlays written, when `debugDir` was given. */\n debug?: string[];\n}\n\nexport type MeasureTurnResult =\n | ({ ok: true } & TurnMeasurement)\n | { ok: false; error: string };\n\nexport interface MeasureTurnInput {\n /** Front-facing image (relative paths resolve against cwd). */\n front: string;\n /** The same character turned. */\n turned: string;\n /** Iris colour window override, merged over the violet default. */\n iris?: Partial<IrisColor>;\n /** Existing directory to write `<name>.debug.png` overlays into. */\n debugDir?: string;\n}\n\n/** HSV of an 8-bit RGB triple: hue in degrees, saturation and value in 0..1. */\nfunction rgbToHsv(r: number, g: number, b: number): [number, number, number] {\n r /= 255;\n g /= 255;\n b /= 255;\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const d = max - min;\n let h = 0;\n if (d > 0) {\n if (max === r) h = ((g - b) / d) % 6;\n else if (max === g) h = (b - r) / d + 2;\n else h = (r - g) / d + 4;\n h *= 60;\n if (h < 0) h += 360;\n }\n return [h, max === 0 ? 0 : d / max, max];\n}\n\n/** Grow `mask` by `r` px in every direction (square kernel). */\nfunction dilate(\n mask: Uint8Array,\n width: number,\n height: number,\n r: number,\n): Uint8Array {\n const out = new Uint8Array(width * height);\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n if (!mask[y * width + x]) continue;\n for (let dy = -r; dy <= r; dy++) {\n for (let dx = -r; dx <= r; dx++) {\n const yy = y + dy;\n const xx = x + dx;\n if (yy >= 0 && yy < height && xx >= 0 && xx < width)\n out[yy * width + xx] = 1;\n }\n }\n }\n }\n return out;\n}\n\n/** Shrink `mask` by `r` px in every direction; outside the image counts as\n * background. Erosion only ever clears pixels, so set ones are all it visits. */\nfunction erode(\n mask: Uint8Array,\n width: number,\n height: number,\n r: number,\n): Uint8Array {\n const out = new Uint8Array(width * height);\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n if (!mask[y * width + x]) continue;\n let keep = true;\n for (let dy = -r; dy <= r && keep; dy++) {\n for (let dx = -r; dx <= r; dx++) {\n const yy = y + dy;\n const xx = x + dx;\n if (\n yy < 0 ||\n yy >= height ||\n xx < 0 ||\n xx >= width ||\n !mask[yy * width + xx]\n ) {\n keep = false;\n break;\n }\n }\n }\n if (keep) out[y * width + x] = 1;\n }\n }\n return out;\n}\n\n/** Morphological close: weld pieces up to 2r apart, leaving the outer edges\n * where they were (a closed set never spills past the original's bbox). */\nfunction closeMask(\n mask: Uint8Array,\n width: number,\n height: number,\n r: number,\n): Uint8Array {\n return erode(dilate(mask, width, height, r), width, height, r);\n}\n\n/** 4-connected components of `mask` with at least `minArea` px, largest first. */\nfunction components(\n mask: Uint8Array,\n width: number,\n height: number,\n minArea: number,\n): IrisBlob[] {\n const seen = new Uint8Array(width * height);\n const out: IrisBlob[] = [];\n for (let i = 0; i < width * height; i++) {\n if (!mask[i] || seen[i]) continue;\n const stack = [i];\n seen[i] = 1;\n let x0 = width;\n let x1 = 0;\n let y0 = height;\n let y1 = 0;\n let n = 0;\n let sx = 0;\n let sy = 0;\n while (stack.length) {\n const p = stack.pop() as number;\n const x = p % width;\n const y = (p / width) | 0;\n n++;\n sx += x;\n sy += y;\n if (x < x0) x0 = x;\n if (x > x1) x1 = x;\n if (y < y0) y0 = y;\n if (y > y1) y1 = y;\n const neighbours: number[] = [];\n if (x > 0) neighbours.push(p - 1);\n if (x < width - 1) neighbours.push(p + 1);\n if (y > 0) neighbours.push(p - width);\n if (y < height - 1) neighbours.push(p + width);\n for (const q of neighbours) {\n if (seen[q] || !mask[q]) continue;\n seen[q] = 1;\n stack.push(q);\n }\n }\n if (n >= minArea) {\n out.push({\n x0,\n x1,\n y0,\n y1,\n w: x1 - x0 + 1,\n h: y1 - y0 + 1,\n area: n,\n cx: sx / n,\n cy: sy / n,\n });\n }\n }\n return out.sort((a, b) => b.area - a.area);\n}\n\n/** Merge a caller's partial iris window over the default, rejecting nonsense. */\nfunction resolveIris(override: Partial<IrisColor> | undefined): IrisColor {\n const iris = { ...DEFAULT_IRIS, ...override };\n if (iris.hueMin < 0 || iris.hueMax > 360 || iris.hueMin >= iris.hueMax) {\n throw new AutoRigInputError(\n `iris hue window must be 0 <= hueMin < hueMax <= 360, got ${iris.hueMin}..${iris.hueMax}`,\n );\n }\n if (iris.satMin < 0 || iris.satMin > 1) {\n throw new AutoRigInputError(\n `iris satMin must be within 0..1, got ${iris.satMin}`,\n );\n }\n return iris;\n}\n\n/**\n * Find the iris pair and the head silhouette in one image.\n *\n * Throws a path-qualified AutoRigInputError when no pair survives the filters\n * (the candidate count says whether the hue window found nothing at all or\n * found too much) or when the eye-row band holds no foreground.\n */\nasync function measureTurnImage(\n filePath: string,\n iris: IrisColor,\n): Promise<TurnImageMeasure> {\n const { width, height, rgba, hasAlpha } = await decodePng(filePath);\n const n = width * height;\n\n // An RGBA file whose alpha is entirely opaque is a reference that merely\n // carries a channel, not a render with a cut-out backdrop — key it by colour.\n let transparent = false;\n if (hasAlpha) {\n for (let i = 0; i < n; i++) {\n if (rgba[i * 4 + 3] < ALPHA_OPAQUE) {\n transparent = true;\n break;\n }\n }\n }\n const maskMode: \"alpha\" | \"keyed\" =\n hasAlpha && transparent ? \"alpha\" : \"keyed\";\n\n const irisMask = new Uint8Array(n);\n const fg = new Uint8Array(n);\n const value = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n if (rgba[i * 4 + 3] < ALPHA_OPAQUE) continue; // transparent = background\n const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);\n if (maskMode === \"alpha\") {\n fg[i] = 1;\n } else {\n const isBg =\n (hue >= BG_HUE_MIN &&\n hue <= BG_HUE_MAX &&\n s < BG_SAT_MAX &&\n v > BG_V_MIN) ||\n v < BG_V_BLACK;\n if (!isBg) fg[i] = 1;\n }\n if (\n hue >= iris.hueMin &&\n hue <= iris.hueMax &&\n s > iris.satMin &&\n v > IRIS_V_MIN &&\n v < IRIS_V_MAX\n ) {\n irisMask[i] = 1;\n value[i] = v;\n }\n }\n\n const minArea = Math.max(\n 1,\n Math.round((MIN_AREA * n) / MIN_AREA_REFERENCE_PIXELS),\n );\n const closeRadius = Math.max(\n 1,\n Math.round(\n (CLOSE_RADIUS * Math.max(width, height)) / CLOSE_RADIUS_REFERENCE_PX,\n ),\n );\n const meanValue = (b: IrisBlob): number => {\n let count = 0;\n let total = 0;\n for (let y = b.y0; y <= b.y1; y++) {\n for (let x = b.x0; x <= b.x1; x++) {\n const i = y * width + x;\n if (!irisMask[i]) continue;\n count++;\n total += value[i];\n }\n }\n return count ? total / count : 0;\n };\n const candidates = components(\n closeMask(irisMask, width, height, closeRadius),\n width,\n height,\n minArea,\n )\n .filter((b) => b.w < width * BLOB_MAX_FRAC && b.h < height * BLOB_MAX_FRAC)\n .filter((b) => meanValue(b) > IRIS_MEAN_V_MIN)\n .slice(0, MAX_CANDIDATES);\n\n let best: { score: number; pair: [IrisBlob, IrisBlob] } | null = null;\n for (let i = 0; i < candidates.length; i++) {\n for (let j = i + 1; j < candidates.length; j++) {\n const a = candidates[i];\n const b = candidates[j];\n const dx = Math.abs(a.cx - b.cx);\n const dy = Math.abs(a.cy - b.cy);\n if (dx < width * PAIR_DX_MIN_FRAC || dx > width * PAIR_DX_MAX_FRAC)\n continue;\n if (dy > height * PAIR_DY_MAX_FRAC) continue;\n const score = a.area + b.area;\n if (best === null || score > best.score) {\n const pair: [IrisBlob, IrisBlob] = a.cx <= b.cx ? [a, b] : [b, a];\n best = { score, pair };\n }\n }\n }\n if (best === null) {\n throw new AutoRigInputError(\n `no iris pair found in ${filePath} among ${candidates.length} candidate blobs ` +\n `(iris hue ${iris.hueMin}..${iris.hueMax}, sat > ${iris.satMin})`,\n );\n }\n\n const [irisL, irisR] = best.pair;\n const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);\n const { left, right } = foregroundSpan(\n fg,\n width,\n height,\n eyeRow - HEAD_BAND,\n eyeRow + HEAD_BAND,\n );\n // Every ratio divides by this half-width, so a band that keyed down to\n // nothing (or to a single column) must fail rather than report Infinity.\n if (right <= left) {\n throw new AutoRigInputError(\n `no head span at the eye row (y=${eyeRow}) in ${filePath}: the ${maskMode} foreground mask is empty there`,\n );\n }\n if (maskMode === \"keyed\" && right - left + 1 > width * KEYED_SPAN_MAX_FRAC) {\n throw new AutoRigInputError(\n `head span at the eye row (y=${eyeRow}) in ${filePath} covers ${right - left + 1}/${width} px: background not keyed / not an engine render`,\n );\n }\n\n return {\n file: filePath,\n width,\n height,\n maskMode,\n irisL,\n irisR,\n eyeRow,\n head: {\n left,\n right,\n cx: (left + right) / 2,\n half: headHalfOf({ left, right }),\n },\n pairCx: (irisL.cx + irisR.cx) / 2,\n eyeGap: irisR.cx - irisL.cx,\n };\n}\n\n/**\n * Iris widths split into far and near. FAR = the eye on the side the pair moved\n * TOWARD, which is the one rotating away from the viewer; `turnSign` says which\n * side that is. The measurement and the report must split them the same way, so\n * they share this.\n */\nfunction farNearWidths(\n m: TurnImageMeasure,\n turnSign: -1 | 1,\n): { far: number; near: number } {\n return turnSign < 0\n ? { far: m.irisL.w, near: m.irisR.w }\n : { far: m.irisR.w, near: m.irisL.w };\n}\n\n/** The overlay: iris boxes, head edges, head centre, pair centre. */\nfunction overlaySvg(m: TurnImageMeasure): string {\n const box = (b: IrisBlob, stroke: string) =>\n `<rect x=\"${b.x0}\" y=\"${b.y0}\" width=\"${b.w}\" height=\"${b.h}\" fill=\"none\" stroke=\"${stroke}\" stroke-width=\"3\"/>`;\n const tick = (x: number, half: number, stroke: string) =>\n `<line x1=\"${x}\" y1=\"${m.eyeRow - half}\" x2=\"${x}\" y2=\"${m.eyeRow + half}\" stroke=\"${stroke}\" stroke-width=\"3\"/>`;\n return (\n `<svg width=\"${m.width}\" height=\"${m.height}\">` +\n box(m.irisL, \"#ff0000\") +\n box(m.irisR, \"#00c000\") +\n tick(m.head.left, 40, \"#0000ff\") +\n tick(m.head.right, 40, \"#0000ff\") +\n tick(m.head.cx, 60, \"#ff8800\") +\n tick(m.pairCx, 60, \"#ff00ff\") +\n \"</svg>\"\n );\n}\n\n/** `label` prefixes the file name: the two inputs often share a basename\n * (`renders/head.png` + `ref/head.png`), and one would overwrite the other. */\nasync function writeOverlay(\n debugDir: string,\n label: \"front\" | \"turned\",\n m: TurnImageMeasure,\n): Promise<string> {\n const outPath = path.join(\n debugDir,\n `${label}-${path.basename(m.file, \".png\")}.debug.png`,\n );\n writeFileAtomic(outPath, await encodeOverlayPng(m.file, overlaySvg(m)));\n return outPath;\n}\n\n/** How far the front/turned mean iris heights may differ before the pair is\n * refused as not being at the same scale. A yaw foreshortens iris WIDTH, never\n * its height, so any difference here is framing/scale, not turn — 10% is\n * comfortably above the paint/detection noise a same-scale pair shows (the\n * fixtures in measure-turn.test.ts read within a percent) and comfortably\n * below a deliberate rescale. */\nconst IRIS_HEIGHT_SCALE_TOLERANCE = 0.1;\n\n/**\n * Measure a front/turned image pair and report the three turn ratios plus both\n * raw per-image measurements.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) →\n * `{ ok:false }`, matching measureLayers; any other throw propagates.\n */\nexport async function measureTurnReference(\n input: MeasureTurnInput,\n): Promise<MeasureTurnResult> {\n try {\n const iris = resolveIris(input.iris);\n const frontPath = resolveInputPath(input.front);\n const turnedPath = resolveInputPath(input.turned);\n // Resolve the debug dir before measuring (fail-fast): a missing or escaping\n // target should not cost two full decodes first.\n const debugDir =\n input.debugDir === undefined ? null : resolveOutputDir(input.debugDir);\n\n const front = await measureTurnImage(frontPath, iris);\n const turned = await measureTurnImage(turnedPath, iris);\n\n // A yaw does not change iris HEIGHT — only width, via foreshortening — so\n // a front/turned pair whose mean iris height differs is not at the same\n // scale/framing, and every ratio below would be measuring that instead of\n // the turn. Refuse it rather than silently reporting a scale change as one.\n const frontIrisH = (front.irisL.h + front.irisR.h) / 2;\n const turnedIrisH = (turned.irisL.h + turned.irisR.h) / 2;\n if (\n Math.abs(turnedIrisH - frontIrisH) / frontIrisH >\n IRIS_HEIGHT_SCALE_TOLERANCE\n ) {\n throw new AutoRigInputError(\n `front and turned images are not at the same scale: mean iris height ${frontIrisH.toFixed(1)}px front vs ${turnedIrisH.toFixed(1)}px turned, more than ${(IRIS_HEIGHT_SCALE_TOLERANCE * 100).toFixed(0)}% apart — a yaw does not change iris height, so the pair must share the same framing and head size`,\n );\n }\n\n // Where the eye pair sits on the head, per image; the CHANGE is the turn.\n const frontShift = front.pairCx - front.head.cx;\n const turnedShift = turned.pairCx - turned.head.cx;\n const shift = turnedShift - frontShift;\n // A pair that did not move has no far side, so there is no third value the\n // far/near rule below could use: treat a zero shift as a right turn, where\n // the ratio reads ~1 from either assignment anyway.\n const turnSign: -1 | 1 = shift < 0 ? -1 : 1;\n // Dividing the turned far/near by the same ratio at rest cancels a resting\n // asymmetry in the art, so what is left is the turn alone.\n const f = farNearWidths(front, turnSign);\n const t = farNearWidths(turned, turnSign);\n\n const debug =\n debugDir === null\n ? undefined\n : [\n await writeOverlay(debugDir, \"front\", front),\n await writeOverlay(debugDir, \"turned\", turned),\n ];\n\n return {\n ok: true,\n front,\n turned,\n farEyeRatio: t.far / t.near / (f.far / f.near),\n eyeShift: shift / front.head.half,\n silhouetteRatio: turned.head.half / front.head.half,\n turnSign,\n ...(debug === undefined ? {} : { debug }),\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n\nconst n1 = (v: number) => v.toFixed(1);\nconst n3 = (v: number) => v.toFixed(3);\n\n/** One image's raw block: what the ratios above were computed from. */\nfunction imageBlock(label: string, m: TurnImageMeasure): string[] {\n return [\n `# ${label} ${m.file} ${m.width}x${m.height} mask: ${m.maskMode}`,\n `iris widths ${m.irisL.w} / ${m.irisR.w} px centres ${n1(m.irisL.cx)} / ${n1(m.irisR.cx)} ` +\n `eye row ${m.eyeRow} gap ${n1(m.eyeGap)}`,\n `head ${m.head.left}..${m.head.right} centre ${n1(m.head.cx)} half ${n1(m.head.half)} ` +\n `pair centre ${n1(m.pairCx)}`,\n ];\n}\n\n/** Render a measurement as plain text: the three ratios with the raw numbers\n * behind each, then one block per image. */\nexport function formatTurnReport(result: TurnMeasurement): string {\n const { front, turned } = result;\n const f = farNearWidths(front, result.turnSign);\n const t = farNearWidths(turned, result.turnSign);\n const lines = [\n `farEyeRatio ${n3(result.farEyeRatio)} far/near iris width ${t.far}/${t.near} turned ` +\n `over ${f.far}/${f.near} front`,\n `eyeShift ${n3(result.eyeShift)} pair-vs-head centre ${n1(turned.pairCx - turned.head.cx)} px turned, ` +\n `${n1(front.pairCx - front.head.cx)} px front, over front head half ${n1(front.head.half)} px (hh)`,\n `silhouetteRatio ${n3(result.silhouetteRatio)} head half ${n1(turned.head.half)} px turned over ` +\n `${n1(front.head.half)} px front`,\n `turnSign ${result.turnSign} (the head turned toward the image's ${\n result.turnSign < 0 ? \"left\" : \"right\"\n })`,\n \"\",\n ...imageBlock(\"front\", front),\n \"\",\n ...imageBlock(\"turned\", turned),\n ];\n if (result.debug !== undefined) {\n lines.push(\"\", ...result.debug.map((p) => `debug overlay ${p}`));\n }\n return lines.join(\"\\n\");\n}\n","/**\n * Where the composer hangs an arm. One arm.png is the arm on the screen LEFT:\n * `arm_R` takes it as drawn and `arm_L` mirrored. Each of an arm's `cx` / `cy`\n * that the layout leaves unset is derived from the placed body's box: the\n * arm's shoulder pivot lands on the box's shoulder corner on that axis — the\n * box's left edge for `arm_R`, its right edge for `arm_L`, SHOULDER_DROP of\n * its height under its top. On a torso widest at its shoulders, the cap's\n * centre then sits on the torso's edge, overlapping it by the cap's radius.\n * An unset `w` is ARM_WIDTH of the body's width.\n *\n * The pivot is the rig's own: `armGeometry`, run on the resized part as\n * `auto_rig_from_layers` runs it on the composed layer, so the rig turns the\n * composed arm about the target to the pixel, with no second copy of its\n * shoulder rule here to keep in step.\n *\n * A pose forearm (`forearm_pose.png`: the screen-left forearm raised,\n * `forearm_pose_R` as drawn and `forearm_pose_L` mirrored) hangs from its\n * arm's elbow, so the composer puts its elbow end where the rig turns it. An\n * unset `w` scales it so its elbow-end width (2 r_e, measured on the trimmed\n * source) equals the placed arm's seam run, and an unset `cx` or `cy` pins\n * its elbow-end pivot (`forearmPoseGeometry`, measured on the resized part as\n * the shoulder is) on the arm's placed elbow. Both read the rig's geometry,\n * none of it copied here.\n */\n\nimport sharp from \"sharp\";\nimport {\n LayerGeometryError,\n armGeometry,\n createLayerSetMeasurer,\n forearmPoseGeometry,\n type ArmGeometry,\n type ForearmPoseGeometry,\n} from \"@ikijs/editor\";\nimport type { ArmLayout } from \"./compose\";\nimport { AutoRigInputError } from \"./limits\";\n\n/** An arm's default width, as a share of the placed body's width. Our own\n * value, provisional: to be picked by eye on the first full-body character. */\nexport const ARM_WIDTH = 0.4;\n/** How far under the body box's top its shoulder corners lie, as a share of\n * its height. Our own value, provisional: to be picked by eye on the first\n * full-body character. */\nexport const SHOULDER_DROP = 0.12;\n\n/** A placed part's box on the canvas, px. */\ninterface PlacedBox {\n left: number;\n top: number;\n w: number;\n h: number;\n}\n\n/**\n * Where an arm's resized part lands: by its rig shoulder pivot on the body\n * box's shoulder corner for each of `cx` / `cy` left unset, centred on a set\n * one as every other role's part is. An arm the rig would refuse as too short\n * is refused here, path-qualified.\n */\nexport async function armPlacement(\n role: \"arm_L\" | \"arm_R\",\n cfg: Pick<ArmLayout, \"cx\" | \"cy\">,\n part: { buf: Buffer; w: number; h: number },\n body: PlacedBox,\n): Promise<{\n left: number;\n top: number;\n /** The rig's elbow pivot on the canvas, px. */\n elbow: { x: number; y: number };\n /** The elbow seam's widest run, px: what a pose forearm's elbow end fits. */\n elbowRun: number;\n}> {\n const { data } = await sharp(part.buf)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n const layer = createLayerSetMeasurer({ width: part.w, height: part.h }).add({\n role,\n fileName: \"arm.png\",\n rgba: data,\n });\n if (layer === null) {\n throw new AutoRigInputError(\n `layout.${role}: arm.png is empty after alpha threshold once resized`,\n );\n }\n let g: ArmGeometry;\n try {\n // The axis keeps `side` the role's own all the same: arm_R on the screen\n // left, arm_L on the right.\n g = armGeometry(layer, role === \"arm_R\" ? Infinity : -Infinity);\n } catch (err) {\n if (err instanceof LayerGeometryError) {\n throw new AutoRigInputError(`layout.${role}: ${err.message}`);\n }\n throw err;\n }\n // Model space is centred on the measured canvas, here the part itself.\n const pivotX = g.shoulder.x + part.w / 2;\n const pivotY = part.h / 2 - g.shoulder.y;\n const cornerX = role === \"arm_R\" ? body.left : body.left + body.w;\n const cornerY = body.top + SHOULDER_DROP * body.h;\n const left = Math.round(\n cfg.cx === undefined ? cornerX - pivotX : cfg.cx - part.w / 2,\n );\n const top = Math.round(\n cfg.cy === undefined ? cornerY - pivotY : cfg.cy - part.h / 2,\n );\n return {\n left,\n top,\n elbow: {\n x: left + g.elbow.x + part.w / 2,\n y: top + part.h / 2 - g.elbow.y,\n },\n elbowRun: g.seamRun[1] - g.seamRun[0],\n };\n}\n\ntype PoseRole = \"forearm_pose_L\" | \"forearm_pose_R\";\n\n/** A pose forearm's geometry on a PNG of the given size, read as the rig\n * reads a layer; an empty one is refused path-qualified. */\nasync function poseGeometryOf(\n role: PoseRole,\n png: Buffer,\n size: { w: number; h: number },\n when: string,\n): Promise<ForearmPoseGeometry> {\n const { data } = await sharp(png)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n const layer = createLayerSetMeasurer({\n width: size.w,\n height: size.h,\n }).add({ role, fileName: \"forearm_pose.png\", rgba: data });\n if (layer === null) {\n throw new AutoRigInputError(\n `layout.${role}: forearm_pose.png is empty after alpha threshold${when}`,\n );\n }\n return forearmPoseGeometry(layer);\n}\n\n/**\n * The width that fits a pose forearm to its arm: the trimmed source scaled\n * so its elbow end's width (2 r_e) equals the arm's elbow run, at least 1.\n */\nexport async function forearmPoseWidth(\n role: PoseRole,\n trimmed: { data: Buffer; w: number; h: number },\n elbowRun: number,\n): Promise<number> {\n const g = await poseGeometryOf(role, trimmed.data, trimmed, \"\");\n return Math.max(1, Math.round((trimmed.w * elbowRun) / (2 * g.radius)));\n}\n\n/**\n * Where a pose forearm's resized part lands: its elbow-end pivot on the\n * arm's placed elbow for each of `cx` / `cy` left unset, centred on a set one\n * as every other role's part is.\n */\nexport async function forearmPosePlacement(\n role: PoseRole,\n cfg: Pick<ArmLayout, \"cx\" | \"cy\">,\n part: { buf: Buffer; w: number; h: number },\n elbow: { x: number; y: number },\n): Promise<{ left: number; top: number }> {\n const { pivot } = await poseGeometryOf(role, part.buf, part, \" once resized\");\n // Model space is centred on the canvas, here the part itself.\n const pivotX = pivot.x + part.w / 2;\n const pivotY = part.h / 2 - pivot.y;\n return {\n left: Math.round(\n cfg.cx === undefined ? elbow.x - pivotX : cfg.cx - part.w / 2,\n ),\n top: Math.round(\n cfg.cy === undefined ? elbow.y - pivotY : cfg.cy - part.h / 2,\n ),\n };\n}\n","/**\n * The text lines `auto_rig_from_layers` and `render_poses` print the engine's\n * `checkPhysics` report as, after the fold report.\n */\n\nimport type { PhysicsReport, PhysicsTarget } from \"@ikijs/engine\";\nimport { foldPose } from \"./fold-report\";\n\n/**\n * `report` as text lines: one `PHYSICS` line per target in the report's\n * order, or `PHYSICS: no rigs`. A line gives the target's kind, its rig (`id`,\n * or `id/segment [inputs]` for a chain segment), `input -> output`, the step's\n * setting with the output's peak, when, its final value and the largest part\n * move with what the output drives, then the idle's peak, when and move, and\n * ` — <why>` when the target is not `ok`.\n */\nexport function formatPhysicsReport(report: PhysicsReport): string[] {\n if (report.targets.length === 0) return [\"PHYSICS: no rigs\"];\n return report.targets.map(targetLine);\n}\n\nfunction targetLine(t: PhysicsTarget): string {\n const inputs = t.input.join(\", \");\n const rig =\n t.rig.kind === \"chain\"\n ? `${t.rig.id}/${t.rig.segment} [${inputs}]`\n : `${t.rig.id} ${inputs}`;\n const drives =\n t.drives.length === 0 ? \"\" : ` (${t.drives.map((d) => d.id).join(\", \")})`;\n const { step, idle } = t;\n return (\n `PHYSICS ${t.kind} ${rig} -> ${t.output}: ` +\n `step ${foldPose(step.values).name} peak ${step.peak.toFixed(2)} at ${step.at.toFixed(2)} s, ` +\n `final ${step.final.toFixed(2)}, moves ${pxText(step.displacementPx)} model px${drives}; ` +\n `idle peak ${idle.peak.toFixed(2)} at ${idle.at.toFixed(2)} s, ${pxText(idle.displacementPx)} model px` +\n (t.why === undefined ? \"\" : ` — ${t.why}`)\n );\n}\n\n/** One decimal, floored as the engine's frozen `why` is, so a frozen 0.96 px\n * never reads `1.0` on its own line. */\nfunction pxText(px: number): string {\n return (Math.floor(px * 10) / 10).toFixed(1);\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport type { PatchReport, RigPatch } from \"@ikijs/editor\";\nimport {\n validateIki,\n describeIki,\n describeIkiAt,\n listStandardParameters,\n autoRigFromLayers,\n} from \"./tools\";\nimport { composeLayersFromParts } from \"./compose\";\nimport { formatFoldReport } from \"./fold-report\";\nimport { formatPhysicsReport } from \"./physics-report\";\nimport { measureLayers, formatMeasureReport } from \"./measure\";\nimport { measureTurnReference, formatTurnReport } from \"./measure-turn\";\nimport { renderPoses } from \"./render-poses\";\n\n/** Injected by tsup (and vitest) from this package's package.json version. */\ndeclare const __MCP_VERSION__: string;\n\n/** One `PATCH` line per op `auto_rig_from_layers` replayed. */\nfunction formatPatchReports(reports: PatchReport[]): string[] {\n return reports.map((r) => {\n const at = Object.keys(r.at)\n .sort()\n .map((p) => `${p}=${r.at[p]}`)\n .join(\" \");\n const where =\n r.cols !== undefined && r.rows !== undefined\n ? `cols ${r.cols[0]}-${r.cols[1]}, rows ${r.rows[0]}-${r.rows[1]}`\n : \"vertices\";\n return `PATCH ${r.index} ${r.target} at ${at}: ${r.moved} of ${r.of} points (${where}), largest move ${r.maxPx} model px`;\n });\n}\n\nexport function createIkiMcpServer(): McpServer {\n const server = new McpServer({ name: \"iki\", version: __MCP_VERSION__ });\n\n server.registerTool(\n \"validate_iki\",\n {\n description:\n \"Validates a raw .iki model (object or JSON string); fail-fast — returns at most ONE error, so fix one, re-run.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = validateIki(model);\n const text = r.ok ? \"OK\" : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"describe_iki\",\n {\n description:\n \"Summarizes a valid model's canvas/params/parts/deformers and its expressions and motion clips (with the descriptions a host picks them by); returns an error for an invalid model. It is also the patch writer's view of a rigged model: each part's rest box in model px and in bust-render px, each part's warp stops, each warp2d's stops, and faceWidth, which is what an auto_rig_from_layers `patches` op is aimed with. Pass exactly one of model or modelPath; prefer modelPath for a written rig so a large model never crosses your context.\",\n inputSchema: {\n model: z\n .unknown()\n .optional()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n modelPath: z\n .string()\n .optional()\n .describe(\n \"Path to a written .iki model (relative to the working directory, inside it)\",\n ),\n },\n },\n async ({ model, modelPath }) => {\n try {\n if ((model === undefined) === (modelPath === undefined)) {\n const error = \"pass model or modelPath\";\n return {\n content: [{ type: \"text\", text: `INVALID: ${error}` }],\n structuredContent: { ok: false, error },\n };\n }\n const r =\n modelPath !== undefined\n ? describeIkiAt(modelPath)\n : describeIki(model);\n const text = r.ok\n ? JSON.stringify(r.summary, null, 2)\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"list_standard_parameters\",\n {\n description:\n \"Lists the recommended standard parameter ids a host can drive without per-model wiring.\",\n inputSchema: {},\n },\n async () => {\n const params = listStandardParameters();\n const text = params.map((p) => `${p.id} — ${p.description}`).join(\"\\n\");\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { parameters: params },\n };\n },\n );\n\n server.registerTool(\n \"auto_rig_from_layers\",\n {\n description:\n \"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, 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, 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 `PHYSICS` lines follow the fold report (the result's `physics`), one per physics rig output — a spring's, or each chain segment's — reading ok, frozen or unstable with the step and idle amplitudes, or `PHYSICS: no rigs`; report-only too. `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 — `PATCH <i> <target> at <Param=v …>: <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 — 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]…` and nothing is written; an op with a missing field or a field of the wrong type is the SDK's input validation error.\",\n inputSchema: {\n layers: z\n .array(\n z.object({\n fileName: z\n .string()\n .optional()\n .describe(\n \"Role-bearing filename; defaults to the basename of `path`.\",\n ),\n path: z\n .string()\n .describe(\"PNG file path (resolved against cwd).\"),\n }),\n )\n .describe(\"Full-canvas PNG layers; all must share the same size.\"),\n outputPath: z\n .string()\n .optional()\n .describe(\n \"Output .iki path (resolved against cwd; parent dir must exist).\",\n ),\n quantizeColors: z\n .number()\n .int()\n .min(2)\n .max(256)\n .optional()\n .describe(\n \"Palette-quantize the atlas PNG to this many colours (2..256). Flat-shaded art keeps its look at 256 and the model shrinks to about a quarter; omit for lossless. A `nose` layer stays lossless on a second atlas page of its own, since the palette rims a soft-shaded nose's feather; the nose's own lossless page adds a content-dependent amount, since splitting it off also changes how page 0 re-quantizes without it; the result's `atlasBytes` sums both pages.\",\n ),\n turnTargets: z\n .object({\n eyeShift: z.number().optional(),\n farEyeRatio: z.number().optional(),\n silhouetteRatio: z.number().optional(),\n noseShift: z.number().optional(),\n mouthShift: z.number().optional(),\n })\n .passthrough()\n .optional()\n .describe(\n \"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 — 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 — 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: …` 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.\",\n ),\n style: z\n .object({\n turn: z.number().optional(),\n featureLead: z.number().optional(),\n hairFollow: z.number().optional(),\n outlineFollow: z.number().optional(),\n blink: z.number().optional(),\n sway: z.number().optional(),\n })\n .passthrough()\n .optional()\n .describe(\n \"Per-character tuning from the profile the rig defaults to: `turn` scales the whole head turn (plate, features, hair and the eyes' foreshortening; 0..3, 1 = the profile; ignored when `turnTargets.eyeShift` is given), `featureLead` how far the features lead the face plate (0..3, 1 = the profile), `hairFollow` the front hair's share of the face's turn (0..2, profile 1), `outlineFollow` its outer edge's share where the front hair draws the head's outline (0..2, profile 0: the outline holds), `blink` how far the upper lid comes down over the eye's height (0.1..1, profile 0.6), `sway` the hair sway amplitude (0..5, 1 = the profile). A value out of range, or a knob not named here, comes back as `INVALID: …`.\",\n ),\n patches: z\n .array(\n z\n .object({\n target: z.string(),\n at: z.record(z.string(), z.number()),\n region: z\n .object({\n role: z.string(),\n // Not z.tuple: its JSON Schema is the array-form `items`\n // draft 2020-12 forbids. The rig checks the pair's order.\n x: z.array(z.number()).length(2),\n y: z.array(z.number()).length(2),\n })\n .passthrough(),\n by: z.object({ dx: z.number(), dy: z.number() }).passthrough(),\n falloff: z.number().optional(),\n why: z.string().optional(),\n })\n .passthrough(),\n )\n .optional()\n .describe(\n \"Displacements ADDED to EXISTING keyform stops of the freshly generated rig, each op `{ target, at, region, by, falloff?, why? }`. They are replayed on every rig of these inputs, over whatever the rig now bakes, so they hold through a layout or `style` retune; ops on one stop add up, whatever their order. `target` is a feature grid — `eyeWarp_L`, `eyeWarp_R`, `browWarp_L`, `browWarp_R`, `noseWarp`, `mouthWarp`, whose `at` names both `ParamAngleX` and `ParamAngleY`, each -30, 0 or 30, never both 0 — or a mesh part with warps (`face`, `hair_front`, …), whose `at` names exactly one parameter at one of that part's warp keyform values, never the parameter's default nor the stop where the rig shuts the part on purpose (`eye_*` and `lash_lower_*` at their `ParamEye*Open` 0, the lip set and its tongue and teeth at `ParamMouthOpenY` 0), which the fold check exempts, nor a `ParamAngleZ` or `ParamBodyAngleZ` stop (they roll the deformers the part hangs under, so a displacement there is turned off the screen axes). The rest pose is the drawn art and no patch changes it. `bodyWarp` and the matrix deformers are not targets, and a patch adds no stop and changes no parameter range. `region` `{ role, x: [from, to], y: [from, to] }` is a rectangle in fractions of the REST layer box (the opaque crop) of `role`, origin top-left, x right, y DOWN, and may reach past the box: the target's points whose REST position lies inside take the whole of `by`, those within `falloff` of it a smooth share, the rest nothing. `by` `{ dx, dy }` and `falloff` are in face widths (the `face` layer's crop width), on screen axes: +dx toward the viewer's right (a character's `_L` side), +dy DOWN. Between stops the engine blends linearly, so a fix at ParamAngleX -30 shows at half strength at -15 and none at rest. `why` is a note the rig ignores. An op this schema accepts but the rig refuses — an unknown key, target, role or stop, the rest stop or a shut stop, a region running backwards or catching none of the target's points — comes back as `INVALID: patches[i]…`, listing the keys, targets, stops or roles there are, or where the target's points lie in the role's box, and nothing is written; a missing field or one of the wrong type is refused by the schema itself, as the SDK's input validation error.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await autoRigFromLayers({\n ...args,\n // `.length(2)` makes each region span a pair, which its inferred\n // `number[]` cannot say.\n patches: args.patches as RigPatch[] | undefined,\n });\n const text = r.ok\n ? [\n r.path,\n ...formatPatchReports(r.patches ?? []),\n ...formatFoldReport(r.folds, r.canvas),\n ...formatPhysicsReport(r.physics),\n ].join(\"\\n\")\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"compose_layers_from_parts\",\n {\n description:\n \"Composes AI-generated part PNGs into canvas-aligned, role-named PNG layers on disk, ready for auto_rig_from_layers (the eyewhite split, alpha-trim/white-key, and placement pipeline the character-generation skill needs), with the same geometry report measure_layers returns standalone included inline. face, eyewhite, iris, brow, hair_front are required, with mouth.png — or the lip set's mouth_keyed.png (the open mouth, its inside painted flat #00FF00) + mouth_interior.png (the cavity, teeth and tongue alone), which the composer keys and splits into mouth_inner / lip_lower / lip_upper on one frame so auto_rig_from_layers folds the mouth open like the eyelid, the interior's light paint (luma 100 and over) written as mouth_tongue and mouth_teeth on the same frame, riding the opening's bottom and the upper line and clipped to the cavity (listed in `skipped` when the interior has none); the two routes cannot be mixed, one keyed file without the other is refused, and a key that fails (no green, green outside the opening, an outline not closed round it, more than one opening, no skin under the opening, an interior that is only lips, or one drawn opaque on a non-white or noisy ground) is refused naming the regeneration; with the lip set neither mouth nor mouth_open is written and preview.png shows the mouth closed, as the rig draws the rest pose. hair_back, body, mouth_open (legacy route only), blush (one blush.png makes the blush_L/blush_R pair) and nose are optional — without a nose layer the head still turns on the rig's default profile, but it has no nose to lead the turn, and `auto_rig_from_layers` fits no turn to the art (`turnTargets` is inert, no `turn` report). One arm.png — the arm on the screen LEFT, drawn hanging with its shoulder at the top — makes both arms of a full body: arm_R takes it as drawn and arm_L mirrored. The arms are opt-in: without arm.png the compose is a bust's and `skipped` never lists them. arm.png needs body.png, and each arm is hung on the body's shoulder by default (see `layout`). One forearm_pose.png — the arm's forearm raised, on the screen LEFT, standing up from its elbow with the hand at the top — makes both pose forearms (forearm_pose_R as drawn, forearm_pose_L mirrored): each is scaled so its elbow end is as wide as its arm's elbow run and pinned on that arm's elbow (see `layout`), and it needs arm.png. With one, preview-pose.png shows the switch at 1 as the rig draws it (the hanging forearms hidden below the elbow, the pose forearms over everything) while preview.png stays the rest pose; without one it is removed. The inline report carries the full-body checks too: a body whose feet a tall canvas's bottom cuts off, an arm without a body, an arm whose shoulder cap does not reach under the torso's edge, and a pose forearm without its arm or off its arm's elbow in pivot, width or length. A nose whose dense core is a speck — under a quarter of its trimmed part's width or height, such as a lone nostril mark or highlight — is sized and placed whole, and the inline report warns of it. A light mark drawn detached above the eye white, such as a double-eyelid crease, is dropped from the sclera (the iris's clip); dark strokes there stay lash ink. The eyewhite's dark lower lid — its line and lashes — becomes lash_lower_L/lash_lower_R, drawn over the iris; a white with none writes none and lists them in `skipped`.\",\n inputSchema: {\n partsDir: z\n .string()\n .describe(\n \"Directory of the source part PNGs (resolved against cwd).\",\n ),\n outDir: z\n .string()\n .describe(\n \"Existing directory to write the role layer PNGs + preview.png (and preview-pose.png when there is a forearm_pose.png) into (resolved against cwd; must already exist; confined to the working directory). Reused across runs: a role this run does not write — one it skips, or an arm or pose forearm once arm.png or forearm_pose.png is gone, preview-pose.png included — has its stale PNG from an earlier run deleted.\",\n ),\n layout: z\n .record(\n z.string(),\n z\n .object({\n cx: z.number(),\n cy: z.number(),\n w: z.number(),\n h: z.number(),\n })\n .partial(),\n )\n .optional()\n .describe(\n \"Per-role override merged over the built-in defaults, keyed by role — hair_back, body, arm_L, arm_R, face, blush_L, blush_R, nose, mouth, mouth_open, mouth_inner, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front, forearm_pose_L, forearm_pose_R — e.g. `{ eye_L: { cx: 660 } }`. `w` is an integer in 1..1100 (the canvas width) and `h` in 1..canvasHeight; omit `h` to keep the part's own aspect, set it to stretch. The defaults of the face's features — blush, nose, mouth, mouth_open, mouth_inner, eyes, irises, lashes, brows — are proportions of the face: an override of face.cx, face.cy or face.w carries them with it (scaled by the width; face.h stretches the face alone), while a feature's own override names canvas px. The nose is sized and placed by its dense core (its pixels at alpha >= 128, the drawing inside a soft nose's feather), not its whole part: `w`/`h` size the core, `cx` centres it, and a set `cy` centres its rows. A nose whose core is a speck — under a quarter of the trimmed part's width or height, such as a lone nostril mark or highlight — is sized and placed whole instead, and the report warns of it. Its `cy` defaults to unset, which lands the core's bottom row (the tip) 0.66 of the way from the eye row down to the mouth's, so the nose follows a retuned eye or mouth row. eye_L/lash_L and eye_R/lash_R are cut from one eyewhite into one frame, so each pair must land on the same frame — a pair set to land apart is rejected. lash_lower_L/lash_lower_R are cut from it too and have no key: they land on their eye's frame. mouth_inner is the lip set's one frame (mouth_open's place by default; lip_lower, lip_upper, mouth_tongue and mouth_teeth have no key and land on it, so a retune moves them together), and with the lip set the nose's tip rule reads layout.mouth_inner.cy. arm_L/arm_R have no cx/cy/w defaults: an unset `w` is 0.4 of the placed body's width, and an unset `cx` or `cy` hangs the arm's shoulder pivot — the one auto_rig_from_layers turns it about — on the body box's shoulder corner on that axis: its left edge for arm_R, its right edge for arm_L, 0.12 of its height under its top. A set one centres the arm as for every other role. forearm_pose_L/forearm_pose_R have no cx/cy/w defaults either: an unset `w` scales the forearm so its elbow end (the shoulder rule run from its bottom) is as wide as the placed arm's elbow run, and an unset `cx` or `cy` pins that elbow end's pivot on the arm's elbow — the one auto_rig_from_layers hangs it from.\",\n ),\n mirrorParts: z\n .array(z.string())\n .optional()\n .describe(\n \"Part files to flip left-right as they are read, e.g. `[\\\"eyewhite.png\\\"]`. The composer reads eyewhite.png as the eye on the screen LEFT (lash wing at the image's left end, lash-free tear duct at its right), brow.png as the brow on the screen RIGHT (thick head at the image's left end, tail at its right), blush.png as the blush on the screen LEFT (outer end, toward the face's edge, at the image's left end, inner end at its right), arm.png as the arm on the screen LEFT (the character's right, hanging, its shoulder at the image's top), and forearm_pose.png as the raised forearm on the screen LEFT (standing up from its elbow, the hand at the image's top, the thumb toward the body at the image's right); a part drawn the other way round is fixed here for free. It flips the source, so every role cut from it flips together and an eye's sclera and lash stay in one frame.\",\n ),\n canvasHeight: z\n .number()\n .optional()\n .describe(\n \"The canvas's height in px: an even integer in 1100..4096, default 1100 (a square bust canvas; at 1100 every output is byte-identical to leaving it out). The width stays 1100. The canvas grows downward: every default and every override keeps its canvas px from the top-left, so the head lands where it does on a bust and a full body gets room below. An odd height is refused — model space is centred on the canvas, so it would put the head on a half pixel — and it is checked before any part decodes.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await composeLayersFromParts(args);\n const text = r.ok\n ? [\n ...r.layers.map((l) => l.path),\n formatMeasureReport({ ...r.measure, layersDir: r.outDir }),\n ].join(\"\\n\")\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"measure_layers\",\n {\n description:\n \"Reports read-only geometry checks over an already-composed layers directory — the same checks compose_layers_from_parts returns inline (iris ratio/offset, eye aspect, cropped/cut edges, a nose whose dense core is a speck of its crop, missing optional roles, a body whose feet a tall canvas's bottom cuts off, an arm without a body, an arm whose shoulder cap does not reach under the torso's edge on its shoulder pivot's row, a pose forearm without its arm or whose elbow end is off its arm's elbow in pivot, width or length, and the lip set: a partial one or one beside mouth/mouth_open, the fold's contract per column of the opening, an opening too narrow or short, a line too thin, green left, an interior with holes, and of mouth_tongue/mouth_teeth: one with no lip set, one on another canvas, one whose box leaves mouth_inner's — with the opening's size and the MouthOpen below which no slit shows). Every preview*.png is skipped. Use to re-check a layers dir without recomposing. Its nose check reads the composed file against its crop, which is what auto_rig_from_layers acts on. Compose's inline report does the same unless the composer found the source part's core a speck, which it reports instead — so a speck that resampling erased from the layer shows there and not here.\",\n inputSchema: {\n layersDir: z\n .string()\n .describe(\n \"Directory of role-named layer PNGs (resolved against cwd).\",\n ),\n },\n },\n async ({ layersDir }) => {\n try {\n const r = await measureLayers({ layersDir });\n const text = r.ok ? formatMeasureReport(r) : `INVALID: ${r.error}`;\n // Spread into a fresh object: MeasureResult's ok:true arm is an\n // intersection with the MeasureReport interface, which TS won't accept\n // directly against the SDK's `Record<string, unknown>` structuredContent\n // — spreading drops that nominal interface identity, same value.\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { ...r },\n };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"measure_turn_reference\",\n {\n description:\n \"Measures how far a head turns between two images of the same character — a front view and a turned one, at the SAME scale — 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.\",\n inputSchema: {\n front: z\n .string()\n .describe(\"Front-facing PNG file path (resolved against cwd).\"),\n turned: z\n .string()\n .describe(\"The same character turned, as a PNG file path.\"),\n iris: z\n .object({\n hueMin: z.number().min(0).max(360),\n hueMax: z.number().min(0).max(360),\n satMin: z.number().min(0).max(1),\n })\n .partial()\n .optional()\n .describe(\n \"Iris colour window override merged over the violet default (hue 230..300, sat > 0.22) — set it for a character whose eyes are another colour.\",\n ),\n debugDir: z\n .string()\n .optional()\n .describe(\n \"Existing directory (resolved against cwd; confined to the working directory) to write `front-<name>.debug.png` / `turned-<name>.debug.png` overlays into, with the iris boxes and head edges drawn.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await measureTurnReference(args);\n const text = r.ok ? formatTurnReport(r) : `INVALID: ${r.error}`;\n // Spread into a fresh object: the ok:true arm is an intersection with\n // the TurnMeasurement interface, which TS won't accept directly against\n // the SDK's Record<string, unknown> structuredContent.\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { ...r },\n };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"render_poses\",\n {\n description:\n \"Renders a rigged .iki into the character loop's pose PNGs with the real engine, through the installed Chrome, Edge or Chromium run headless (set CHROME_PATH to pick one). The model decides the set: a bust gets 560x560 shots (rest, turns, nod, blinks, gaze, combined — ParamAngleX/Y/Z all at 30 — and stress: ParamAngleX/Y/Z all at -30, ParamMouthOpenY 1, both eyes at 0.5, the brows at opposite extremes (ParamBrowLY -1, ParamBrowRY 1, ParamBrowLAngle 1, ParamBrowRAngle -1) and each body angle the model declares at -10); a mouth adds 720x480 mouth crops; a full body (taller than wide) adds the full-canvas body, arm and elbow poses on a 1400-wide canvas, and a model with a pose forearm adds the full-pose-* shots. Given `poses` (see its field), the standard set is not rendered: only those poses are, each crop clamped to the model's canvas. Writes <pose>.png files into outDir, overwriting same-named files in place; returns the written paths one per line, then the model's fold report (the result's `folds`), checked by the engine over its own pose set plus any `poses`, each of which a `FOLD` line names by its settings, not its PNG name: a `FOLD` line per warp deformer or mesh part that flips (ratio <= 0) or collapses (under 0.1) at some pose — its cell or triangle, the ratio of its area there to at rest, the pose as its parameter settings (`rest` for none) and where it rests, in model space and in model px from the top-left (the layer PNGs' own pixels, not a render's) — or `FOLDS: none over N poses`, then a `FOLDS expected:` line naming the closures the rig draws on purpose (an eye or the mouth shut), each by part id, ratio and the parameter that shuts it. Report-only: a fold never fails the render. The `PHYSICS` lines follow the fold report (the result's `physics`), one per physics rig output of the model's own rigs — `poses` do not enter it — reading ok, frozen or unstable with the step and idle amplitudes, or `PHYSICS: no rigs`; report-only too. Fails with INVALID when no browser is found or an input is refused; a browser that cannot start is a tool error.\",\n inputSchema: {\n modelPath: z\n .string()\n .describe(\n \"Rigged .iki file path (resolved against cwd; must sit under the working directory).\",\n ),\n outDir: z\n .string()\n .describe(\n \"Existing directory to write the pose PNGs into (resolved against cwd; must already exist; confined to the working directory).\",\n ),\n poses: z\n .array(\n z.object({\n name: z.string(),\n values: z.record(z.string(), z.number()),\n crop: z\n .object({\n x: z.number(),\n y: z.number(),\n w: z.number(),\n h: z.number(),\n })\n .optional(),\n }),\n )\n .optional()\n .describe(\n \"Caller-named poses rendered INSTEAD of the standard set, each `{ name, values, crop? }`, in order. `name` becomes `<outDir>/<name>.png` and the result's pose name: letters, digits, `_`, `.` and `-` only, unique in the list ignoring case. `values` are parameter settings (every other parameter at its default; an id the model lacks is ignored). `crop` `{ x, y, w, h }` is a rectangle in model px from the top-left — the frame of describe_iki's boxes and of the `FOLD` lines — clamped to the model's canvas, then drawn 720 px wide at its own aspect; without one a pose is framed as the standard shots (560x560, the middle square on a full body). Each pose is also added to the fold sweep, after the engine's own poses. An empty list, a bad or repeated name, a non-finite value, or a crop that misses the canvas or would draw under 1 or over 8192 px tall comes back as `INVALID: poses…` and nothing is rendered.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await renderPoses(args);\n const text = r.ok\n ? [\n ...r.poses.map((p) => p.path),\n ...formatFoldReport(r.folds, r.modelCanvas),\n ...formatPhysicsReport(r.physics),\n ].join(\"\\n\")\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n return server;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACK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":["import_node_fs","import_node_path","import_format","import_editor","xRight","yBottom","px","import_format","target","flat","import_format","import_format","import_format","import_format","P","target","import_format","px","target","import_node_fs","import_node_path","import_format","path","fs","import_node_fs","import_node_path","fs","path","os","poses","path","import_editor","sharp","scanAlphaBbox","placement","path","placement","import_node_fs","import_node_path","import_sharp","import_editor","import_editor","px","import_node_fs","import_node_path","import_node_path","import_editor","path","import_editor","k","import_node_path","import_editor","import_sharp","import_editor","px","from","sharp","z","path","import_node_path","import_editor","import_editor","dilate","components","path","run","fs","path","import_sharp","import_editor","sharp","scale","sharp","scanAlphaBbox","path","fs","placement","px","cfg","part","split","left","top","input","px"]}
1
+ {"version":3,"sources":["../src/index.ts","../../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.15_supports-color@7.2.0_typescript@5.9.3/node_modules/tsup/assets/cjs_shims.js","../src/tools.ts","../../engine/src/math.ts","../../engine/src/parameter-store.ts","../../engine/src/affine.ts","../../engine/src/warp.ts","../../engine/src/warp-grid.ts","../../engine/src/deform.ts","../../engine/src/idle-motion.ts","../../engine/src/frame-clock.ts","../../engine/src/physics-motion.ts","../../engine/src/hair-chain-motion.ts","../../engine/src/iki-motion.ts","../../engine/src/clip-player.ts","../../engine/src/expression-player.ts","../../engine/src/folds.ts","../../engine/src/land.ts","../../engine/src/physics-check.ts","../../engine/src/physics-runs.ts","../src/fold-report.ts","../src/render-poses.ts","../src/limits.ts","../src/render-browser.ts","../src/node-images.ts","../src/compose.ts","../src/trim.ts","../src/measure.ts","../src/measure-arms.ts","../src/measure-forearm-pose.ts","../src/measure-lips.ts","../src/compose-lips.ts","../src/measure-turn.ts","../src/compose-arms.ts","../src/physics-report.ts","../src/server.ts"],"sourcesContent":["export {\n validateIki,\n describeIki,\n describeIkiAt,\n listStandardParameters,\n describeRigPlan,\n formatRigPlanReport,\n autoRigFromLayers,\n type ValidateResult,\n type DescribeResult,\n type IkiSummary,\n type PartSummary,\n type DeformerSummary,\n type StandardParameterInfo,\n type AutoRigInput,\n type AutoRigLayerInput,\n type AutoRigResult,\n type AutoRigTurnTargets,\n type TurnSolveReport,\n} from \"./tools\";\nexport {\n composeLayersFromParts,\n type ComposeInput,\n type ComposeResult,\n type LayoutOverride,\n} from \"./compose\";\nexport {\n measureLayers,\n formatMeasureReport,\n type MeasureInput,\n type MeasureResult,\n} from \"./measure\";\nexport { type RigPlanReport } from \"@ikijs/editor\";\nexport { checkModelFolds, formatFoldReport } from \"./fold-report\";\nexport { formatPhysicsReport } from \"./physics-report\";\nexport {\n measureTurnReference,\n formatTurnReport,\n type MeasureTurnInput,\n type MeasureTurnResult,\n type TurnMeasurement,\n type TurnImageMeasure,\n type IrisBlob,\n type IrisColor,\n} from \"./measure-turn\";\nexport {\n renderPoses,\n type RenderPosesInput,\n type RequestedPose,\n type RenderPosesResult,\n} from \"./render-poses\";\nexport { createIkiMcpServer } from \"./server\";\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n parseIkiModel,\n loadIkiModel,\n IkiFormatError,\n StandardParameter,\n type IkiModel,\n type IkiDeformer,\n} from \"@ikijs/format\";\nimport {\n EditorDocument,\n packAtlas,\n uvRectFor,\n createLayerSetMeasurer,\n generateIkiFromLayerSet,\n parseLayerRoles,\n partIdsOfRole,\n LayerGeometryError,\n PatchError,\n RigPlanError,\n RIG_PLAN_FIELDS,\n styleRemovedMessage,\n TurnTargetError,\n type IrisStrand,\n type LayerSetMeasurer,\n type AtlasAssignment,\n type AtlasLayout,\n type PatchReport,\n type RigPatch,\n type RigPlan,\n type RigPlanField,\n type RigPlanReport,\n type TurnTargets,\n type TurnSolveReport,\n} from \"@ikijs/editor\";\nimport {\n checkPhysics,\n type FoldReport,\n type PhysicsReport,\n} from \"@ikijs/engine\";\nimport { checkModelFolds } from \"./fold-report\";\nimport { BUST_SIZE, bustPadY } from \"./render-poses\";\nimport {\n decodePng,\n cropToBuffer,\n renderAtlasToDataUri,\n type AtlasCrop,\n} from \"./node-images\";\nimport {\n AutoRigInputError,\n MAX_LAYERS,\n MAX_LAYER_DIM,\n MAX_CANVAS_DIM,\n MAX_ATLAS_SIDE,\n MAX_TOTAL_PIXELS,\n MAX_OUTPUT_BYTES,\n resolveInputPath,\n confineToWorkingDirectory,\n resolveOutputPath,\n writeFileAtomic,\n} from \"./limits\";\n\nexport type ValidateResult = { ok: true } | { ok: false; error: string };\n\nexport interface IkiSummary {\n name: string;\n canvas: { width: number; height: number };\n parameters: { id: string; min: number; max: number; default: number }[];\n parts: PartSummary[];\n deformers: DeformerSummary[];\n /** The `face` part's width in model px: the unit a rig patch op's `by` and `falloff` are measured in. */\n faceWidth?: number;\n /** Bust-render px per model px (`BUST_SIZE / canvas.width`). */\n bustScale: number;\n /** Each expression's id and the description a host picks it by. */\n expressions: { id: string; description: string }[];\n /** Each motion group's clip descriptions, by clip index. */\n motions: Record<string, string[]>;\n}\n\nexport interface PartSummary {\n id: string;\n order: number;\n deformer?: string;\n /** Rest box in model px from the canvas top-left, y down; the frame of the fold lines and `layout.json`. */\n box: { x: number; y: number; w: number; h: number };\n /** The same box in bust-render px, including the padding above a landscape model. */\n bustBox: { x: number; y: number; w: number; h: number };\n /** The part's own warps: parameter and the keyform stop values. */\n warps?: { parameter: string; stops: number[] }[];\n}\n\nexport interface DeformerSummary {\n id: string;\n kind: \"matrix\" | \"warp\";\n parent?: string;\n warp?:\n | { mode: \"1d\"; parameters: string[] }\n | {\n mode: \"2d\";\n parameterX: string;\n parameterY: string;\n gridX: number;\n gridY: number;\n stopsX: number[];\n stopsY: number[];\n };\n}\n\nexport type DescribeResult =\n | { ok: true; summary: IkiSummary }\n | { ok: false; error: string };\n\nexport interface StandardParameterInfo {\n id: string;\n description: string;\n}\n\nfunction coerceModel(\n model: unknown,\n): { ok: true; model: IkiModel } | { ok: false; error: string } {\n try {\n const parsed =\n typeof model === \"string\" ? loadIkiModel(model) : parseIkiModel(model);\n return { ok: true, model: parsed };\n } catch (e) {\n if (e instanceof IkiFormatError) return { ok: false, error: e.message };\n throw e;\n }\n}\n\nexport function validateIki(model: unknown): ValidateResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n return { ok: true };\n}\n\nexport function describeIki(model: unknown): DescribeResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n\n const m = result.model;\n\n const parameters = m.parameters.map((p) => ({\n id: p.id,\n min: p.min,\n max: p.max,\n default: p.default,\n }));\n\n const W = m.canvas.width;\n const H = m.canvas.height;\n const bustScale = BUST_SIZE / W;\n const padY = bustPadY(W, H);\n const tenth = (n: number) => Math.round(n * 10) / 10;\n const parts = m.parts.map((p): PartSummary => {\n // The auto-rig's deformers carry no rest transform, so the part's own\n // transform places it.\n const box = {\n x: W / 2 + p.transform.x - p.width / 2,\n y: H / 2 - p.transform.y - p.height / 2,\n w: p.width,\n h: p.height,\n };\n const entry: PartSummary = {\n id: p.id,\n order: p.order,\n box,\n bustBox: {\n x: tenth(box.x * bustScale),\n y: tenth(padY + box.y * bustScale),\n w: tenth(box.w * bustScale),\n h: tenth(box.h * bustScale),\n },\n };\n if (p.deformer !== undefined) entry.deformer = p.deformer;\n if (p.warps !== undefined && p.warps.length > 0) {\n entry.warps = p.warps.map((w) => ({\n parameter: w.parameter,\n stops: w.keyforms.map((k) => k.value),\n }));\n }\n return entry;\n });\n\n const deformers = (m.deformers ?? []).map(\n (d: IkiDeformer): DeformerSummary => {\n const kind = d.kind === \"warp\" ? \"warp\" : \"matrix\";\n const entry: DeformerSummary = { id: d.id, kind };\n if (d.parent !== undefined) entry.parent = d.parent;\n\n if (d.kind === \"warp\") {\n if (d.warp2d !== undefined) {\n entry.warp = {\n mode: \"2d\",\n parameterX: d.warp2d.parameter,\n parameterY: d.warp2d.parameterY,\n gridX: d.grid.cols,\n gridY: d.grid.rows,\n stopsX: d.warp2d.valuesX,\n stopsY: d.warp2d.valuesY,\n };\n } else if (d.warps !== undefined && d.warps.length > 0) {\n entry.warp = {\n mode: \"1d\",\n parameters: d.warps.map((w) => w.parameter),\n };\n }\n }\n\n return entry;\n },\n );\n\n const expressions = (m.expressions ?? []).map((e) => ({\n id: e.id,\n description: e.description,\n }));\n\n const motions = Object.fromEntries(\n Object.entries(m.motions ?? {}).map(([group, clips]) => [\n group,\n clips.map((c) => c.description),\n ]),\n );\n\n const summary: IkiSummary = {\n name: m.name,\n canvas: { width: m.canvas.width, height: m.canvas.height },\n parameters,\n parts,\n deformers,\n expressions,\n motions,\n bustScale,\n };\n const face = m.parts.find((p) => p.id === \"face\");\n if (face !== undefined) summary.faceWidth = face.width;\n\n return { ok: true, summary };\n}\n\n/**\n * `describeIki` on a written model, read from `modelPath` (confined to the\n * working directory like `renderPoses`), so a large model never crosses an\n * agent's context inline.\n */\nexport function describeIkiAt(modelPath: string): DescribeResult {\n try {\n const modelFile = confineToWorkingDirectory(\n process.cwd(),\n resolveInputPath(modelPath, \"model\"),\n \"model path\",\n modelPath,\n );\n return describeIki(readFileSync(modelFile, \"utf8\"));\n } catch (e) {\n if (e instanceof AutoRigInputError) return { ok: false, error: e.message };\n throw e;\n }\n}\n\n// Static map of standard parameter ids to human-readable descriptions,\n// sourced from JSDoc comments in parameters.ts (including range hints).\nconst STANDARD_PARAMETER_INFO: StandardParameterInfo[] = [\n {\n id: StandardParameter.MouthOpen,\n description: \"Mouth open amount for lip-sync (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.MouthForm,\n description: \"Mouth form / smile (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeOpenLeft,\n description:\n \"Left eye open (0 closed .. 1 open). Drive with the right eye for a blink.\",\n },\n {\n id: StandardParameter.EyeOpenRight,\n description: \"Right eye open (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.EyeballX,\n description: \"Eyeball gaze, horizontal (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeballY,\n description: \"Eyeball gaze, vertical (-1 .. 1).\",\n },\n {\n id: StandardParameter.AngleX,\n description: \"Head angle, horizontal degrees.\",\n },\n {\n id: StandardParameter.AngleY,\n description: \"Head angle, vertical degrees.\",\n },\n {\n id: StandardParameter.AngleZ,\n description:\n \"Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D.\",\n },\n {\n id: StandardParameter.BodyAngleX,\n description:\n \"Body turn, degrees (-10 .. 10); positive turns the body toward the viewer's right, as AngleX does the head.\",\n },\n {\n id: StandardParameter.BodyAngleY,\n description:\n \"Body lean, degrees (-10 .. 10); positive moves the upper body up, negative bows.\",\n },\n {\n id: StandardParameter.BodyAngleZ,\n description:\n \"Body tilt, degrees (-10 .. 10); positive tilts the top toward the viewer's right (clockwise), as AngleZ does the head.\",\n },\n {\n id: StandardParameter.Breath,\n description: \"Idle breath (0 .. 1), cycled by the host.\",\n },\n {\n id: StandardParameter.AmbientSway,\n description:\n \"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.\",\n },\n {\n id: StandardParameter.BrowLeftY,\n description: \"Left brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightY,\n description: \"Right brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowLeftAngle,\n description: \"Left brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightAngle,\n description: \"Right brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.Cheek,\n description: \"Cheek blush strength (0 .. 1), raised by an expression.\",\n },\n {\n id: StandardParameter.HairSwayX,\n description:\n \"Front hair's horizontal sway driver. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n {\n id: StandardParameter.HairSwayZ,\n description:\n \"Front hair's sway driver behind a head tilt. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n {\n id: StandardParameter.HairBackSway,\n description:\n \"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 — driven by the spring, hosts should not set it directly.\",\n },\n {\n id: StandardParameter.ArmLeft,\n description:\n \"Left shoulder, degrees; positive raises the arm outward (mirrored on the right).\",\n },\n {\n id: StandardParameter.ArmRight,\n description:\n \"Right shoulder, degrees; positive raises the arm outward (mirrored on the left).\",\n },\n {\n id: StandardParameter.ElbowLeft,\n description:\n \"Left elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the right).\",\n },\n {\n id: StandardParameter.ElbowRight,\n description:\n \"Right elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the left).\",\n },\n {\n id: StandardParameter.ArmPoseLeft,\n description:\n \"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.\",\n },\n {\n id: StandardParameter.ArmPoseRight,\n description:\n \"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.\",\n },\n {\n id: StandardParameter.ArmPoseAngleLeft,\n description:\n \"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).\",\n },\n {\n id: StandardParameter.ArmPoseAngleRight,\n description:\n \"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).\",\n },\n];\n\nexport function listStandardParameters(): StandardParameterInfo[] {\n return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));\n}\n\n/** The rig plan's field catalog: the one source of the fields' defaults,\n * ranges, recommended spans, steps and poses. */\nexport function describeRigPlan(): { fields: RigPlanField[] } {\n return { fields: [...RIG_PLAN_FIELDS] };\n}\n\n/** The `RIGPLAN:` line: every field's effective value, with the requested one\n * and the bound when the art's room cut it, or the cue that fitted it. */\nexport function formatRigPlanReport(r: RigPlanReport): string {\n const fields = RIG_PLAN_FIELDS.map((f) => {\n const value = `${f.path}=${r.effective[f.path]}`;\n const clamp = r.clamped.find((c) => c.field === f.path);\n if (clamp !== undefined) {\n const asked =\n (r.requested as Record<string, Record<string, number>>)[f.group]?.[\n f.key\n ] ?? f.default;\n return `${value} (requested ${asked}, clamped at ${clamp.bound})`;\n }\n const cue = r.overriddenBy[f.path];\n return cue === undefined ? value : `${value} (fitted by ${cue})`;\n });\n return `RIGPLAN: ${fields.join(\" \")}`;\n}\n\n// ── auto_rig_from_layers ──────────────────────────────────────────────────────\n\n/** One role-named PNG layer; role is derived from `fileName ?? basename(path)`. */\nexport interface AutoRigLayerInput {\n fileName?: string;\n path: string;\n}\n\nexport interface AutoRigInput {\n layers: AutoRigLayerInput[];\n /** Output `.iki` path (relative paths resolve against the process cwd). */\n outputPath?: string;\n /** Palette-quantize the atlas PNG to this many colours (integer, 2..256).\n * Omitted = lossless. See renderAtlasToDataUri for the size/quality trade.\n * A `nose` layer is left out of the quantized page, on a second, lossless\n * page of its own, because the palette rims a soft-shaded nose's feather. */\n quantizeColors?: number;\n /** Head-turn cues to fit the rig to, as `measure_turn_reference` reports\n * them. */\n turnTargets?: AutoRigTurnTargets;\n /** Per-character tuning from the profile's defaults, validated against\n * `RIG_PLAN_FIELDS` (see @ikijs/editor's `RigPlan`; `describe_rig_plan`\n * lists the fields). */\n rigPlan?: RigPlan;\n /** Removed in 0.30.0: any value is refused with the field map. */\n style?: unknown;\n /** Displacements added to existing keyform stops of the freshly generated\n * rig, replayed on every rig of these inputs (see @ikijs/editor's\n * `RigPatch`). */\n patches?: RigPatch[];\n}\n\n/** The turn cues a caller may pass, which is every one but `headHalfWidth`:\n * the pixels the shift fractions are fractions of are measured off the layers\n * themselves, not accepted from the caller. */\nexport type AutoRigTurnTargets = Omit<TurnTargets, \"headHalfWidth\">;\n\nexport type AutoRigResult =\n | {\n ok: true;\n path: string;\n canvas: { width: number; height: number };\n partCount: number;\n /** The atlas's embedded size: its data URI's length, summed over both\n * pages when a quantized rig puts the nose on a page of its own. */\n atlasBytes: number;\n /** The head's half-width at the eye row, measured off the layers.\n * Absent when the opaque (alpha >= 128) union has no span there — a\n * layer set painted translucent below that threshold — in which case\n * the face plate stands in for it, same as a span that measures\n * narrower than the plate. */\n headHalfWidth?: number;\n /** Whether the measured value was handed to the generator; the\n * face-half fallback applies otherwise, which is what happens when it\n * is no wider than the face plate, or absent entirely. */\n headHalfWidthApplied: boolean;\n /** Every role with an opaque pixel in the same eye-row band as\n * `headHalfWidth`, per side, each with its own rest x there (canvas px)\n * — present only when `headHalfWidthApplied` is true, since the\n * fallback path has no measured edge to report at all. Passed to the\n * generator so it can land each candidate through its OWN motion\n * (hair_front's silhouette hold, a turn group's grid for the face and\n * its features, the body's own turn translate; `hair_back` holds the\n * outline and lands where it rests, and a role outside that table is\n * refused) and take the outermost LANDING, not just the outermost\n * REST pixel. */\n headEdges?: {\n left: { role: string; x: number }[];\n right: { role: string; x: number }[];\n };\n /** Each side's iris and the `hair_front` run it would slide under on\n * the turn, as pixel edges on the row holding that iris's centre, in\n * model coordinates (`IrisStrand`: canvas x minus half the canvas\n * width) — measured whenever the layer set has `hair_front`, `iris_L`\n * and `iris_R`, and passed to the generator as `options.strandEdges`.\n * A run narrower than half that iris's painted width on the row is\n * hair detail, not a strand, and is skipped as if clear. A side is\n * absent only when its iris has no opaque pixel on that row, or when no\n * run it keeps covers the pixel on that side of the iris's centre or\n * lies outward of it; the whole field only when neither side has one. */\n strandEdges?: { left?: IrisStrand; right?: IrisStrand };\n /** The nose's dense core, canvas px — its pixels at alpha >= 128, not\n * grown — the box handed to the generator as the nose layer's\n * `denseCore` and, there, its turn landmark. Absent without a `nose`\n * layer, when the nose has no pixel at that threshold (painted wholly\n * translucent), or when its core is a speck of its crop\n * (`isSpeckCore`: a lone nostril mark or highlight); the crop stands\n * in for it in both cases. */\n noseCore?: { x: number; y: number; w: number; h: number };\n /** What the turn solve settled on — the cues the rig reaches, the\n * targets it had to cut down (`clamped`) and, per side whose far iris\n * the bangs' run still covers at some far stop, how much of it\n * (`strandOverlap`). Absent for a layer set with no nose, which solves\n * no turn at all. */\n turn?: TurnSolveReport;\n /** The written model's folds over the engine's pose set, its eyes and\n * mouth shutting on purpose set apart as `expected`. Report-only: a\n * fold never refuses the rig. */\n folds: FoldReport;\n /** The written model's physics rigs, each output excited through the\n * engine's real drivers — a step held at the input's far end and the\n * procedural idle — and read as ok, frozen or unstable with both\n * windows' amplitudes. Report-only: it never refuses the rig. */\n physics: PhysicsReport;\n /** What each of `input.patches` moved on this rig, in order — present\n * whenever `patches` was passed, `[]` included, so a caller can tell\n * this server from one that drops the field. */\n patches?: PatchReport[];\n /** What the rig built with next to what `input.rigPlan` asked, and the\n * fields the art's room cut or a `turnTargets` cue fitted instead.\n * Always present on a rigged model; absent only from a server before\n * 0.30.0. */\n rigPlan: RigPlanReport;\n }\n | { ok: false; error: string };\n\nexport type { TurnSolveReport };\n\n/**\n * Run a fallible input/environment-boundary call, re-tagging any throw as an\n * AutoRigInputError with context so the tool reports it as `{ ok:false }` rather\n * than an unexpected `isError`. Use ONLY around true caller-input / filesystem\n * boundaries — never around internal pipeline math (a throw there is a bug).\n */\nfunction expectInput<T>(label: string, fn: () => T): T {\n try {\n return fn();\n } catch (e) {\n throw new AutoRigInputError(\n `${label}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\n/**\n * The role that keeps a lossless atlas page of its own under `quantizeColors`.\n * At 256 colours a soft nose's feather took the hair edge's lavender palette\n * entries and drew a rim around the nose; changing the dither, the effort, the\n * alpha floor or the alpha curve did not fix it. A lossless page for the nose\n * alone did, and the hero's model came to about 1.28 MB, against 3.18 MB with\n * the whole atlas lossless.\n */\nconst LOSSLESS_PAGE_ROLE = \"nose\";\n\n/** Pack `crops` onto one atlas page and render it — palette-quantized to\n * `quantizeColors` when that is set. A page over MAX_ATLAS_SIDE on either side\n * is refused before rendering, naming its widest (or tallest) crop — after\n * every shelf attempt up to and including the max side overflowed. */\nasync function renderAtlasPage(\n crops: AtlasCrop[],\n quantizeColors: number | undefined,\n): Promise<{ crops: AtlasCrop[]; layout: AtlasLayout; dataUri: string }> {\n const layout = packAtlas(\n crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),\n undefined,\n MAX_ATLAS_SIDE,\n );\n const over =\n layout.pageWidth > MAX_ATLAS_SIDE\n ? ({ side: \"width\", crop: \"widest\" } as const)\n : layout.pageHeight > MAX_ATLAS_SIDE\n ? ({ side: \"height\", crop: \"tallest\" } as const)\n : undefined;\n if (over !== undefined) {\n const crop = layout.placements.reduce((a, b) =>\n b[over.side] > a[over.side] ? b : a,\n );\n throw new AutoRigInputError(\n `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max side ${MAX_ATLAS_SIDE} (its ${over.crop} crop: \"${crop.id}\" ${crop.width}x${crop.height})`,\n );\n }\n const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);\n return { crops, layout, dataUri };\n}\n\n/**\n * Decode role-named PNG file paths, auto-rig a model from them, atlas + embed\n * the textures (Node sharp), validate, and write the renderable `.iki` to disk.\n * Returns the output path + summary stats (the multi-MB model is never inlined).\n *\n * The head turn is fitted to `input.turnTargets`, on what @ikijs/editor's\n * `createLayerSetMeasurer` measures off the decoded layers (the head\n * half-width, `headEdges`, `strandEdges`, the face's `rowHalfWidths`, the face's\n * and hair layers' opaque runs and the nose's dense core, returned as\n * `noseCore`); what the solve settled on comes back in `turn`. Under\n * `quantizeColors` the nose is atlased alone on a second, lossless page, which\n * the palette would otherwise rim; `atlasBytes` sums both pages. The\n * generator replays `input.patches` on the fresh rig before it validates and\n * reports the turn, and what each op moved comes back in `patches`; a refused\n * op writes nothing.\n *\n * Re-host of examples/editor/src/store.ts `importLayerSet` with the three DOM\n * pixel functions swapped for the sharp-backed ./node-images helpers; the pure\n * model math is reused from @ikijs/editor.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) → `{ ok:false }`;\n * any other throw (invariant break, programmer bug) propagates to `isError`.\n */\nexport async function autoRigFromLayers(\n input: AutoRigInput,\n): Promise<AutoRigResult> {\n try {\n const layers = input.layers;\n if (!Array.isArray(layers) || layers.length === 0) {\n throw new AutoRigInputError(\"layers must be a non-empty array\");\n }\n if (layers.length > MAX_LAYERS) {\n throw new AutoRigInputError(\n `too many layers: ${layers.length} > ${MAX_LAYERS}`,\n );\n }\n\n // Resolve the output path FIRST (fail-fast): reject a bad/escaping/non-.iki\n // target before spending the image-decode budget on a request that can't\n // be written anyway.\n const outPath = resolveOutputPath(\n input.outputPath ?? \"auto-rigged-model.iki\",\n );\n const quantizeColors = input.quantizeColors;\n if (\n quantizeColors !== undefined &&\n (!Number.isInteger(quantizeColors) ||\n quantizeColors < 2 ||\n quantizeColors > 256)\n ) {\n throw new AutoRigInputError(\n `quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`,\n );\n }\n // Removed with no alias: undeclared keys are stripped by the schema, so\n // the tool keeps a tombstone for it and refuses here, before decoding.\n if (input.style !== undefined) {\n throw new AutoRigInputError(styleRemovedMessage(\"style\"));\n }\n // Checked before the generator call spreads it: a spread turns null or an\n // array into {}, which would rig on the defaults instead of refusing.\n const turnTargets: unknown = input.turnTargets;\n if (turnTargets !== undefined) {\n if (\n typeof turnTargets !== \"object\" ||\n turnTargets === null ||\n Array.isArray(turnTargets)\n ) {\n throw new AutoRigInputError(\"turnTargets must be a plain object\");\n }\n // Excluded from AutoRigTurnTargets, but a JS caller can still pass one:\n // the half-width is measured off the layers below, so a caller's own is\n // refused rather than silently dropped.\n if ((turnTargets as TurnTargets).headHalfWidth !== undefined) {\n throw new AutoRigInputError(\n \"turnTargets.headHalfWidth is measured off the layers, not accepted as input\",\n );\n }\n }\n\n // Resolve paths + role-map up front (input boundary; no decode needed).\n // parseLayerRoles throws on unknown/duplicate/missing-required roles.\n const resolvedLayers = layers.map((layer) => {\n const resolved = resolveInputPath(layer.path);\n return { resolved, fileName: layer.fileName ?? path.basename(resolved) };\n });\n const rolePairs = expectInput(\"role parsing\", () =>\n parseLayerRoles(resolvedLayers.map((r) => r.fileName)),\n );\n const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));\n\n // Decode + alpha-bbox + crop SEQUENTIALLY: only ONE full-canvas RGBA buffer\n // is live at a time (a Promise.all over all layers would hold every decoded\n // buffer at once, allowing a multi-GB spike on inputs that each pass\n // MAX_LAYER_DIM). MAX_TOTAL_PIXELS bounds the aggregate work. Canvas size =\n // the first layer's full PNG dims (parity with buildLayerInputs in\n // examples/editor/src/auto-rig-image.ts); all layers must match it.\n let canvasW = 0;\n let canvasH = 0;\n let totalPixels = 0;\n // Measures each layer while its decoded pixels are live, keeping none of\n // them (see createLayerSetMeasurer). Created once the first layer gives the\n // canvas.\n let measurer: LayerSetMeasurer | undefined;\n const crops: AtlasCrop[] = [];\n for (let i = 0; i < resolvedLayers.length; i++) {\n const { resolved, fileName } = resolvedLayers[i];\n const png = await decodePng(resolved);\n if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {\n throw new AutoRigInputError(\n `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`,\n );\n }\n totalPixels += png.width * png.height;\n if (totalPixels > MAX_TOTAL_PIXELS) {\n throw new AutoRigInputError(\n `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`,\n );\n }\n if (i === 0) {\n canvasW = png.width;\n canvasH = png.height;\n if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {\n throw new AutoRigInputError(\n `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`,\n );\n }\n measurer = createLayerSetMeasurer({ width: canvasW, height: canvasH });\n } else if (png.width !== canvasW || png.height !== canvasH) {\n throw new AutoRigInputError(\n `layer \"${fileName}\" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`,\n );\n }\n\n const role = roleByFileName.get(fileName);\n if (role === undefined) {\n throw new AutoRigInputError(`no role resolved for \"${fileName}\"`);\n }\n // Created at i === 0 above.\n const layer = measurer!.add({ role, fileName, rgba: png.rgba });\n if (layer === null) {\n throw new AutoRigInputError(\n `role \"${role}\" file \"${fileName}\": layer is empty after alpha threshold`,\n );\n }\n const { bbox } = layer;\n const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);\n // png.rgba (full-canvas) is dropped at the next iteration — GC reclaims it\n // before the next decode, so peak memory stays ~one canvas + the crops.\n crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });\n }\n // `layers` is non-empty (checked above), so the loop created the measurer.\n const measurement = measurer!.finish();\n const { headHalfWidth, headHalfWidthApplied, turnOptions } = measurement;\n const { headEdges, strandEdges } = turnOptions;\n\n // The nose layer's own denseCore, for the result — undefined without a\n // `nose` layer, or when the measurer's denseCoreOf found no pixel at\n // ALPHA_OPAQUE or a speck of the crop.\n const noseCore = measurement.layers.find(\n (l) => l.role === \"nose\",\n )?.denseCore;\n\n // Internal pipeline — direct calls. By here roles + bboxes are validated, so\n // a throw is an invariant break / bug and must propagate to `isError` —\n // except for the generator's four input errors, each a fact about the\n // request, not a bug: the turn solve, which reads CALLER input, throws\n // TurnTargetError (a field that is not a number, a target this layer set\n // cannot reach); the patch replay, which reads the caller's `patches`,\n // throws PatchError (a malformed op, or one that misses this rig); the rig\n // plan, which reads the caller's `rigPlan`, throws RigPlanError; and\n // art geometry the rig cannot build on (a body's hips with no room under\n // its pivots, an arm too short for its pivots, a lip set whose\n // mouth_inner has no opaque pixel) throws LayerGeometryError.\n let turn: TurnSolveReport | undefined;\n let patches: PatchReport[] | undefined;\n let rigPlan: RigPlanReport | undefined;\n let model: IkiModel;\n try {\n // The caller's fields cross as passed (a headHalfWidth was refused\n // above), so the generator refuses a misspelt one; the measured\n // headHalfWidth, when applied, is merged in after them.\n model = generateIkiFromLayerSet(\n measurement.layers,\n { width: canvasW, height: canvasH },\n {\n turnTargets: {\n ...input.turnTargets,\n ...turnOptions.turnTargets,\n },\n onTurnSolved: (report) => {\n turn = report;\n },\n ...(input.rigPlan === undefined ? {} : { rigPlan: input.rigPlan }),\n onRigPlanResolved: (report) => {\n rigPlan = report;\n },\n ...(input.patches === undefined\n ? {}\n : {\n patches: input.patches,\n onPatchesApplied: (reports: PatchReport[]) => {\n patches = reports;\n },\n }),\n ...(headEdges === undefined ? {} : { headEdges }),\n ...(strandEdges === undefined ? {} : { strandEdges }),\n },\n );\n } catch (e) {\n if (\n !(\n e instanceof TurnTargetError ||\n e instanceof LayerGeometryError ||\n e instanceof PatchError ||\n e instanceof RigPlanError\n )\n ) {\n throw e;\n }\n throw new AutoRigInputError(e.message);\n }\n const doc = new EditorDocument(model);\n\n // Under quantizeColors the nose is page 1, alone and lossless (see\n // LOSSLESS_PAGE_ROLE), and page 0 every other crop; otherwise one page.\n const losslessCrop =\n quantizeColors === undefined\n ? undefined\n : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);\n const pages =\n losslessCrop === undefined\n ? [await renderAtlasPage(crops, quantizeColors)]\n : [\n await renderAtlasPage(\n crops.filter((c) => c !== losslessCrop),\n quantizeColors,\n ),\n await renderAtlasPage([losslessCrop], undefined),\n ];\n const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);\n if (atlasBytes > MAX_OUTPUT_BYTES) {\n throw new AutoRigInputError(\n `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`,\n );\n }\n\n // Each crop's uv is on its own page, normalised to that page's size.\n const partTextureAssignments: AtlasAssignment[] = pages.flatMap(\n ({ crops: pageCrops, layout }) =>\n pageCrops.flatMap((crop) => {\n const placement = layout.placements.find((p) => p.id === crop.id);\n if (placement === undefined) {\n throw new Error(`auto-rig: no atlas placement for \"${crop.id}\"`);\n }\n const uv = uvRectFor(placement, {\n width: layout.pageWidth,\n height: layout.pageHeight,\n });\n // Every part of a role samples its crop: a forearm shares its arm's.\n return partIdsOfRole(crop.id).map((partId) => ({ partId, uv }));\n }),\n );\n\n // applyAtlas takes a single page: it sets every part's index to 0 and\n // remaps each mesh's uvs into its rect, which for the nose is already in\n // page 1's space — so the nose only needs its index, set on a clone\n // because getModel() hands back the document's live model, read-only.\n doc.applyAtlas({\n textures: [{ source: pages[0].dataUri }],\n partTextureAssignments,\n });\n let patched = doc.getModel();\n if (losslessCrop !== undefined) {\n patched = structuredClone(patched);\n patched.textures = pages.map((p) => ({ source: p.dataUri }));\n for (const partId of partIdsOfRole(losslessCrop.id)) {\n patched.parts.find((p) => p.id === partId)!.texture!.index = 1;\n }\n }\n // Validate the patched model before writing — never persist an invalid model.\n const finalModel = parseIkiModel(patched);\n\n // Write to a fresh temp file in the verified directory, then atomically\n // rename over the target — see writeFileAtomic for why an existing `.iki`\n // symlink at outPath cannot redirect the write outside the working tree.\n writeFileAtomic(outPath, JSON.stringify(finalModel));\n\n // Report-only, and after the write so a throw here — an engine bug,\n // surfacing as a tool error, never an input refusal — keeps the rig.\n const folds = checkModelFolds(finalModel);\n const physics = checkPhysics(finalModel);\n\n return {\n ok: true,\n path: outPath,\n canvas: { width: canvasW, height: canvasH },\n partCount: finalModel.parts.length,\n atlasBytes,\n ...(headHalfWidth === undefined ? {} : { headHalfWidth }),\n headHalfWidthApplied,\n ...(headEdges === undefined ? {} : { headEdges }),\n ...(strandEdges === undefined ? {} : { strandEdges }),\n ...(noseCore === undefined ? {} : { noseCore }),\n ...(turn === undefined ? {} : { turn }),\n folds,\n physics,\n ...(patches === undefined ? {} : { patches }),\n rigPlan: rigPlan!,\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n","/**\n * Clamp `value` into `[min, max]`.\n *\n * NaN in, NaN out — `Math.max(min, Math.min(max, NaN))` is `NaN`, so this\n * cannot be used to sanitize external input. Anything taking values from a\n * host must reject non-finite input itself before clamping (see\n * {@link ParameterStore.set}).\n */\nexport function clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * Linear interpolation from `a` (at `t = 0`) to `b` (at `t = 1`). Exact at\n * `t = 0` and when `a === b`; at `t = 1` it can differ from `b` by rounding.\n */\nexport function lerp(a: number, b: number, t: number): number {\n return a + (b - a) * t;\n}\n\n/**\n * Smoothstep `x²(3 − 2x)` of `x` clamped to `[0, 1]`: 0 at 0, 1 at 1, with zero\n * slope at both ends, so a fade along it starts and lands without a kink.\n * Exact at 0, 1/2 and 1.\n */\nexport function smoothstep(x: number): number {\n const t = clamp(x, 0, 1);\n return t * t * (3 - 2 * t);\n}\n","import type { IkiParameter } from \"@ikijs/format\";\nimport { clamp } from \"./math\";\n\n/**\n * Holds the live value of every model parameter, clamped to its declared\n * range. This is the single surface a host drives (lip-sync, gaze, blink) and\n * the engine reads each frame to evaluate bindings.\n */\nexport class ParameterStore {\n private readonly params = new Map<string, IkiParameter>();\n private readonly values = new Map<string, number>();\n /**\n * Resting value per id: the declared default clamped into range, resolved\n * ONCE here so `reset()` is a straight copy and a malformed descriptor is\n * reported once rather than on every reset.\n */\n private readonly defaults = new Map<string, number>();\n\n constructor(parameters: IkiParameter[]) {\n for (const param of parameters) {\n this.params.set(param.id, param);\n // A non-finite default would survive `clamp` and poison every read, so it\n // falls back to the neutral in-range value — but say so rather than\n // repairing a broken descriptor silently. `parseIkiModel` requires a\n // finite default, so this only reaches a host that skipped the validator.\n if (!Number.isFinite(param.default)) {\n console.error(\n `Iki: parameter \"${param.id}\" has a non-finite default; resting at the neutral in-range value instead`,\n );\n }\n const base = Number.isFinite(param.default) ? param.default : 0;\n this.defaults.set(param.id, clamp(base, param.min, param.max));\n }\n for (const [id, value] of this.defaults) this.values.set(id, value);\n }\n\n /**\n * Set a parameter's value, clamped to its range. Unknown ids are ignored, as\n * are non-finite values: this is the boundary a host drives with live signals,\n * and `clamp` cannot filter NaN (`Math.max(min, Math.min(max, NaN))` is NaN),\n * so one bad lip-sync/gaze frame would otherwise poison every binding that\n * reads the parameter. A dropped write holds the last good pose.\n */\n set(id: string, value: number): void {\n const param = this.params.get(id);\n if (!param) return;\n if (!Number.isFinite(value)) return;\n this.values.set(id, clamp(value, param.min, param.max));\n }\n\n /** Current value, or 0 if the id is unknown. */\n get(id: string): number {\n return this.values.get(id) ?? 0;\n }\n\n /** Position of a parameter within its range, 0..1. */\n normalized(id: string): number {\n const param = this.params.get(id);\n if (!param || param.max === param.min) return 0;\n return (this.get(id) - param.min) / (param.max - param.min);\n }\n\n /** Reset every parameter to its resting value (see `defaults`). */\n reset(): void {\n for (const [id, value] of this.defaults) this.values.set(id, value);\n }\n\n list(): IkiParameter[] {\n return [...this.params.values()];\n }\n}\n","// --- 2D affine helpers ------------------------------------------------------\n// Affine stored as [a, b, c, d, e, f] => | a c e |\n// | b d f |\n// | 0 0 1 |\nexport type Affine = [number, number, number, number, number, number];\n\nexport function translate(tx: number, ty: number): Affine {\n return [1, 0, 0, 1, tx, ty];\n}\n\nexport function scale(sx: number, sy: number): Affine {\n return [sx, 0, 0, sy, 0, 0];\n}\n\nexport function rotate(degrees: number): Affine {\n const r = (degrees * Math.PI) / 180;\n const c = Math.cos(r);\n const s = Math.sin(r);\n return [c, s, -s, c, 0, 0];\n}\n\nexport function multiply(a: Affine, b: Affine): Affine {\n return [\n a[0] * b[0] + a[2] * b[1],\n a[1] * b[0] + a[3] * b[1],\n a[0] * b[2] + a[2] * b[3],\n a[1] * b[2] + a[3] * b[3],\n a[0] * b[4] + a[2] * b[5] + a[4],\n a[1] * b[4] + a[3] * b[5] + a[5],\n ];\n}\n\n/** Expand a 2D affine into a column-major mat3 for `uniformMatrix3fv`. */\nexport function toMat3(a: Affine): Float32Array {\n return new Float32Array([a[0], a[1], 0, a[2], a[3], 0, a[4], a[5], 1]);\n}\n","import type { IkiGrid2DKeyform, IkiWarp } from \"@ikijs/format\";\nimport type { ParameterStore } from \"./parameter-store\";\n\n/**\n * Accumulate one keyform set's interpolated offsets into `out` (out += ...).\n * Clamps `value` to [keyforms[0].value, keyforms[last].value] (no extrapolation),\n * linearly interpolates the bracketing pair, and adds. `out.length` must be >=\n * each keyform's `offsets.length`. Shared by part-local mesh warps and grid warps.\n */\nexport function accumulateKeyformOffsets(\n keyforms: { value: number; offsets: ArrayLike<number> }[],\n value: number,\n out: Float32Array,\n): void {\n const ks = keyforms;\n\n if (value <= ks[0].value) {\n // Clamp to first keyform.\n const { offsets } = ks[0];\n for (let i = 0; i < offsets.length; i++) {\n out[i] += offsets[i];\n }\n } else if (value >= ks[ks.length - 1].value) {\n // Clamp to last keyform.\n const { offsets } = ks[ks.length - 1];\n for (let i = 0; i < offsets.length; i++) {\n out[i] += offsets[i];\n }\n } else {\n // Find bracketing pair with a linear scan (keyforms are small in practice).\n let lo = ks[0];\n let hi = ks[1];\n for (let k = 1; k < ks.length - 1; k++) {\n if (ks[k].value <= value) {\n lo = ks[k];\n hi = ks[k + 1];\n }\n }\n const t = (value - lo.value) / (hi.value - lo.value);\n const loOff = lo.offsets;\n const hiOff = hi.offsets;\n for (let i = 0; i < loOff.length; i++) {\n out[i] += loOff[i] + (hiOff[i] - loOff[i]) * t;\n }\n }\n}\n\n/**\n * Accumulate a 2D keyform grid's bilinear-interpolated offsets into `out` (out += ...).\n *\n * This is PARAMETER bilinear interpolation driven by two live parameter values\n * (`vx` along `valuesX`, `vy` along `valuesY`). It is DISTINCT from\n * {@link sampleWarpGrid}'s spatial bilinear (which interpolates model-space\n * control-point positions). Name params `tx`/`ty` to avoid confusion with\n * the spatial `s`/`t` in sampleWarpGrid.\n *\n * Contract mirrors {@link accumulateKeyformOffsets}: `out += blended offsets`,\n * pure, deterministic, no allocation inside the function, O(points).\n *\n * Bracket rule (applied identically to X and Y; length ≥ 2 is validator-guaranteed):\n * - v <= values[0] → i = 0, t = 0\n * - v >= values[last] → i = length - 2, t = 1\n * - interior → i such that values[i] <= v < values[i+1], t = (v - values[i]) / (values[i+1] - values[i])\n * This keeps i ∈ [0, length-2] so i+1 is always in range.\n *\n * Corner index (row-major): k(i, j) = j * valuesX.length + i\n */\nexport function accumulate2DKeyformOffsets(\n valuesX: number[],\n valuesY: number[],\n keyforms2d: IkiGrid2DKeyform[],\n vx: number,\n vy: number,\n out: Float32Array,\n): void {\n const lastX = valuesX.length - 1;\n const lastY = valuesY.length - 1;\n\n // Per-axis bracket: clamp at both ends, interior normal scan.\n let ix: number;\n let tx: number;\n if (vx <= valuesX[0]) {\n ix = 0;\n tx = 0;\n } else if (vx >= valuesX[lastX]) {\n ix = lastX - 1;\n tx = 1;\n } else {\n ix = 0;\n for (let k = 0; k < lastX - 1; k++) {\n if (valuesX[k + 1] <= vx) ix = k + 1;\n }\n tx = (vx - valuesX[ix]) / (valuesX[ix + 1] - valuesX[ix]);\n }\n\n let iy: number;\n let ty: number;\n if (vy <= valuesY[0]) {\n iy = 0;\n ty = 0;\n } else if (vy >= valuesY[lastY]) {\n iy = lastY - 1;\n ty = 1;\n } else {\n iy = 0;\n for (let k = 0; k < lastY - 1; k++) {\n if (valuesY[k + 1] <= vy) iy = k + 1;\n }\n ty = (vy - valuesY[iy]) / (valuesY[iy + 1] - valuesY[iy]);\n }\n\n // Row-major corners: k(i, j) = j * valuesX.length + i.\n const W = valuesX.length;\n const c00 = keyforms2d[iy * W + ix];\n const c10 = keyforms2d[iy * W + ix + 1];\n const c01 = keyforms2d[(iy + 1) * W + ix];\n const c11 = keyforms2d[(iy + 1) * W + ix + 1];\n\n // Per-component bilinear: top/bot over tx, then ty into out.\n const o00 = c00.offsets;\n const o10 = c10.offsets;\n const o01 = c01.offsets;\n const o11 = c11.offsets;\n for (let n = 0; n < o00.length; n++) {\n const top = o00[n] + (o10[n] - o00[n]) * tx;\n const bot = o01[n] + (o11[n] - o01[n]) * tx;\n out[n] += top + (bot - top) * ty;\n }\n}\n\n/**\n * Apply all warps to `rest`, accumulating per-vertex offsets into `out`.\n *\n * - Copies `rest` into `out` first (out = rest).\n * - For each warp: looks up the live parameter value (REAL range, not\n * normalized), clamps to the keyform range (no extrapolation), linearly\n * interpolates the bracketing pair, and ADDS the result to `out`.\n * - No allocation: writes into the caller-supplied `out`. `rest` is never\n * mutated.\n * - `undefined` warps → identity copy (out equals rest).\n */\nexport function applyWarps(\n rest: Float32Array,\n warps: IkiWarp[] | undefined,\n params: ParameterStore,\n out: Float32Array,\n): void {\n out.set(rest);\n\n if (!warps || warps.length === 0) return;\n\n for (const warp of warps) {\n accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), out);\n }\n}\n","import type { IkiWarpDeformer, IkiWarpGrid } from \"@ikijs/format\";\nimport type { Affine } from \"./affine\";\nimport type { ParameterStore } from \"./parameter-store\";\nimport { clamp, lerp } from \"./math\";\nimport { accumulate2DKeyformOffsets, accumulateKeyformOffsets } from \"./warp\";\n\n/** A warp deformer's deformed control grid for one frame. */\nexport interface ResolvedWarpGrid {\n cols: number;\n rows: number;\n /** Deformed control points, MODEL space, length (cols+1)*(rows+1)*2. */\n points: Float32Array;\n}\n\n/**\n * A warp deformer's LOCAL deformed grid: its rest `grid.points` plus the\n * interpolated offsets of EVERY entry of `warps` (each clamped and lerped on\n * its own parameter, then added, so several 1D warps sum) or of `warp2d`, in\n * the deformer's own rest frame — no parent affine. Returns a new array; the\n * rest grid is never written.\n */\nexport function deformWarpGrid(\n d: IkiWarpDeformer,\n params: ParameterStore,\n): Float32Array {\n const points = Float32Array.from(d.grid.points);\n for (const warp of d.warps ?? []) {\n accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), points);\n }\n // 1D xor 2D is validator-enforced; at most one branch contributes per deformer.\n if (d.warp2d !== undefined) {\n accumulate2DKeyformOffsets(\n d.warp2d.valuesX,\n d.warp2d.valuesY,\n d.warp2d.keyforms2d,\n params.get(d.warp2d.parameter),\n params.get(d.warp2d.parameterY),\n points,\n );\n }\n return points;\n}\n\n/**\n * `affine` applied to every [x, y] of a flat point list, into `out` — a NEW\n * array unless one is given — so the input (a warp's local grid, which a\n * matrix child's rigid frame still reads) is left as is.\n */\nexport function transformGridPoints(\n points: ArrayLike<number>,\n affine: Affine,\n): Float32Array;\nexport function transformGridPoints<T extends Float32Array | Float64Array>(\n points: ArrayLike<number>,\n affine: Affine,\n out: T,\n): T;\nexport function transformGridPoints(\n points: ArrayLike<number>,\n affine: Affine,\n out: Float32Array | Float64Array = new Float32Array(points.length),\n): Float32Array | Float64Array {\n for (let i = 0; i < points.length; i += 2) {\n const x = points[i];\n const y = points[i + 1];\n out[i] = affine[0] * x + affine[2] * y + affine[4];\n out[i + 1] = affine[1] * x + affine[3] * y + affine[5];\n }\n return out;\n}\n\n/** A model-space point bound to a rest-grid cell with within-cell (s,t). */\nexport interface GridBinding {\n /** row*cols + col index of the containing cell. */\n cell: number;\n /** [0,1] within-cell horizontal, 0 at the left (smaller-x) edge. */\n s: number;\n /** [0,1] within-cell vertical, 0 at the TOP (larger-y) edge. */\n t: number;\n}\n\n/**\n * Bind a model-space point to the REST grid: computes the containing cell +\n * local (s,t) by linear mapping over the grid's actual column/row boundaries.\n * Out-of-bounds points clamp to an edge cell with s/t pinned to 0/1. Never\n * returns NaN. Do NOT call against a deformed grid.\n *\n * The rest grid is validated to be a regular axis-aligned lattice with EXACT\n * ordering, so boundaries are read DIRECTLY from `restGrid.points` (no sorting):\n * - row-major, +y up; row 0 = TOP (LARGEST y, y DECREASES with row index);\n * - column 0 = LEFT (smallest x, x INCREASES with column index).\n * Column x-boundaries are row 0's x values `points[col*2]`; row y-boundaries are\n * column 0's y values `points[(row*(cols+1))*2 + 1]`. Maps x left→right and y\n * top→bottom: `s = (x - xLeft)/(xRight - xLeft)`, `t = (yTop - y)/(yTop - yBottom)`\n * (numerator `yTop - y`, NOT `y - minY`, so rows are not vertically flipped).\n */\nexport function bindPointToRestGrid(\n x: number,\n y: number,\n restGrid: IkiWarpGrid,\n): GridBinding {\n const { cols, rows, points } = restGrid;\n const stride = cols + 1;\n\n // Column boundaries: row 0's x values, increasing with column index.\n let col = cols - 1;\n for (let c = 0; c < cols; c++) {\n const xRight = points[(c + 1) * 2];\n if (x < xRight) {\n col = c;\n break;\n }\n }\n const xLeft = points[col * 2];\n const xRight = points[(col + 1) * 2];\n const s = clamp((x - xLeft) / (xRight - xLeft), 0, 1);\n\n // Row boundaries: column 0's y values, decreasing with row index (top→bottom).\n let row = rows - 1;\n for (let r = 0; r < rows; r++) {\n const yBottom = points[(r + 1) * stride * 2 + 1];\n if (y > yBottom) {\n row = r;\n break;\n }\n }\n const yTop = points[row * stride * 2 + 1];\n const yBottom = points[(row + 1) * stride * 2 + 1];\n const t = clamp((yTop - y) / (yTop - yBottom), 0, 1);\n\n return { cell: row * cols + col, s, t };\n}\n\n/**\n * Compute model-space positions for a warp-deformer child's mesh vertices:\n * transform each LOCAL-space vertex by `partAffine`, rebind to the RAW rest\n * grid, and bilinear-sample the deformed grid. Writes `out` (length ===\n * localVerts.length). Affine layout [a,b,c,d,e,f]: x'=a*x+c*y+e, y'=b*x+d*y+f.\n */\nexport function applyWarpToChild(\n localVerts: Float32Array | number[],\n partAffine: Affine,\n restGrid: IkiWarpGrid,\n deformedGrid: ResolvedWarpGrid,\n out: Float32Array,\n): void {\n const n = localVerts.length / 2;\n for (let v = 0; v < n; v++) {\n const lx = localVerts[v * 2];\n const ly = localVerts[v * 2 + 1];\n const mx = partAffine[0] * lx + partAffine[2] * ly + partAffine[4];\n const my = partAffine[1] * lx + partAffine[3] * ly + partAffine[5];\n const binding = bindPointToRestGrid(mx, my, restGrid);\n const [sx, sy] = sampleWarpGrid(deformedGrid, binding);\n out[v * 2] = sx;\n out[v * 2 + 1] = sy;\n }\n}\n\n/**\n * Bilinear-sample a deformed grid at a binding, returning model-space [x, y].\n * Reads the 4 corner control points of `binding.cell` from `grid.points`, using\n * the SAME row/col convention as `bindPointToRestGrid` (s left→right between\n * col and col+1, t top→bottom between row and row+1).\n */\nexport function sampleWarpGrid(\n grid: ResolvedWarpGrid,\n binding: GridBinding,\n): [number, number] {\n const { cols, points } = grid;\n const stride = cols + 1;\n const row = Math.floor(binding.cell / cols);\n const col = binding.cell % cols;\n const { s, t } = binding;\n\n const i00 = (row * stride + col) * 2;\n const i10 = (row * stride + col + 1) * 2;\n const i01 = ((row + 1) * stride + col) * 2;\n const i11 = ((row + 1) * stride + col + 1) * 2;\n\n // Top edge: lerp p00→p10 by s; bottom edge: lerp p01→p11 by s.\n const topX = points[i00] + (points[i10] - points[i00]) * s;\n const topY = points[i00 + 1] + (points[i10 + 1] - points[i00 + 1]) * s;\n const botX = points[i01] + (points[i11] - points[i01]) * s;\n const botY = points[i01 + 1] + (points[i11 + 1] - points[i01 + 1]) * s;\n\n // Vertical: lerp top→bottom by t.\n return [topX + (botX - topX) * t, topY + (botY - topY) * t];\n}\n\n/**\n * Rigid frame of a matrix deformer hung from a warp: returns\n * `translate(p') · rotate(θ) · translate(−p)`, where `p` is `pivot` bound to the\n * RAW rest grid and `p'` is that binding sampled on `localPoints`, the warp's\n * LOCAL deformed grid (rest + keyform offsets, no ancestor affine — the caller\n * composes that on top). θ is the rotation part (polar decomposition) of the\n * bilinear cell's Jacobian at the binding, each tangent divided by the rest\n * cell's width/height so the rest grid gives θ = 0. The warp's scale and shear\n * are deliberately dropped: a narrowing torso warp moves the head but never\n * squashes it.\n */\nexport function warpRigidFrame(\n pivot: { x: number; y: number },\n restGrid: IkiWarpGrid,\n localPoints: Float32Array,\n): Affine {\n const { cols, rows } = restGrid;\n const binding = bindPointToRestGrid(pivot.x, pivot.y, restGrid);\n const [px, py] = sampleWarpGrid({ cols, rows, points: localPoints }, binding);\n\n const stride = cols + 1;\n const row = Math.floor(binding.cell / cols);\n const col = binding.cell % cols;\n const { s, t } = binding;\n const i00 = (row * stride + col) * 2;\n const i10 = (row * stride + col + 1) * 2;\n const i01 = ((row + 1) * stride + col) * 2;\n const i11 = ((row + 1) * stride + col + 1) * 2;\n\n const rest = restGrid.points;\n // Same boundaries as bindPointToRestGrid (row 0's x, column 0's y): the\n // validator tolerates 1e-6 of jitter elsewhere, which can zero a cell's own\n // corner difference.\n const cellWidth = rest[(col + 1) * 2] - rest[col * 2];\n const cellHeight =\n rest[row * stride * 2 + 1] - rest[(row + 1) * stride * 2 + 1];\n\n // Images of the rest x/y axes. t runs top→bottom, i.e. against +y, hence\n // the minus on ey.\n const q = localPoints;\n const exX = lerp(q[i10] - q[i00], q[i11] - q[i01], t) / cellWidth;\n const exY =\n lerp(q[i10 + 1] - q[i00 + 1], q[i11 + 1] - q[i01 + 1], t) / cellWidth;\n const eyX = -lerp(q[i01] - q[i00], q[i11] - q[i10], s) / cellHeight;\n const eyY =\n -lerp(q[i01 + 1] - q[i00 + 1], q[i11 + 1] - q[i10 + 1], s) / cellHeight;\n\n // A collapsed cell gives atan2(0, 0) = 0: the frame stays finite.\n const theta = Math.atan2(exY - eyX, exX + eyY);\n const c = Math.cos(theta);\n const sn = Math.sin(theta);\n return [\n c,\n sn,\n -sn,\n c,\n px - (c * pivot.x - sn * pivot.y),\n py - (sn * pivot.x + c * pivot.y),\n ];\n}\n","import type {\n IkiBinding,\n IkiDeformer,\n IkiDeformerBinding,\n IkiDeformerTransform,\n IkiMatrixDeformer,\n IkiTransform,\n IkiWarpDeformer,\n} from \"@ikijs/format\";\nimport { type Affine, multiply, rotate, scale, translate } from \"./affine\";\nimport type { ParameterStore } from \"./parameter-store\";\nimport {\n type ResolvedWarpGrid,\n deformWarpGrid,\n transformGridPoints,\n warpRigidFrame,\n} from \"./warp-grid\";\n\n/** Resolved TRS + opacity from a transform + bindings at current parameter values. */\nexport interface ResolvedTransform {\n x: number;\n y: number;\n rotation: number;\n scaleX: number;\n scaleY: number;\n opacity: number;\n}\n\nconst IDENTITY_TRANSFORM: Required<IkiTransform> = {\n x: 0,\n y: 0,\n rotation: 0,\n scaleX: 1,\n scaleY: 1,\n opacity: 1,\n};\n\n/**\n * Shared transform evaluator: resolves the effective TRS + opacity from a\n * (possibly absent) base transform plus bindings at current parameter values.\n *\n * - Part callers pass `IkiTransform` (which may include opacity) and use all 6\n * fields including `opacity`.\n * - Deformer callers pass `IkiDeformerTransform` (no opacity field) and\n * `IkiDeformerBinding[]` (no opacity channel); the returned `opacity` is\n * always 1 on the deformer path and should be ignored by the caller.\n */\nexport function evaluateTransform(\n transform: IkiTransform | IkiDeformerTransform | undefined,\n bindings: IkiBinding[] | IkiDeformerBinding[] | undefined,\n params: ParameterStore,\n): ResolvedTransform {\n const base = transform ?? IDENTITY_TRANSFORM;\n const result: ResolvedTransform = {\n x: base.x,\n y: base.y,\n rotation: base.rotation ?? 0,\n scaleX: base.scaleX ?? 1,\n scaleY: base.scaleY ?? 1,\n opacity: (base as IkiTransform).opacity ?? 1,\n };\n\n for (const binding of bindings ?? []) {\n const t = params.normalized(binding.parameter);\n const value = binding.from + (binding.to - binding.from) * t;\n switch (binding.channel) {\n case \"translateX\":\n result.x += value;\n break;\n case \"translateY\":\n result.y += value;\n break;\n case \"rotate\":\n result.rotation += value;\n break;\n case \"scaleX\":\n result.scaleX += value;\n break;\n case \"scaleY\":\n result.scaleY += value;\n break;\n case \"opacity\":\n result.opacity *= value;\n break;\n }\n }\n\n return result;\n}\n\n/**\n * Build the local deformer matrix about its pivot:\n * translate(pivot) · TRS · translate(-pivot)\n */\nfunction deformerLocalMatrix(\n d: IkiMatrixDeformer,\n params: ParameterStore,\n): Affine {\n const t = evaluateTransform(d.transform, d.bindings, params);\n const trs: Affine = multiply(\n multiply(translate(t.x, t.y), rotate(t.rotation)),\n scale(t.scaleX, t.scaleY),\n );\n return multiply(\n multiply(translate(d.pivot.x, d.pivot.y), trs),\n translate(-d.pivot.x, -d.pivot.y),\n );\n}\n\n/** Every deformer of a model resolved for one frame. */\nexport interface ResolvedDeformers {\n /** Matrix deformer id → world affine. */\n worlds: Map<string, Affine>;\n /** Warp deformer id → deformed control grid, model space. */\n grids: Map<string, ResolvedWarpGrid>;\n}\n\n/**\n * A warp's grid before its parent affine, and that affine (absent at a root)\n * — what a matrix child of the warp reads its rigid frame from.\n */\ninterface LocalWarp {\n localGrid: Float32Array;\n parentWorld: Affine | undefined;\n}\n\n/**\n * Resolve every deformer — matrix worlds and warp grids — in topological\n * order, regardless of array ordering.\n *\n * The validator guarantees the hierarchy is acyclic, that every `parent` id\n * exists and that no warp hangs from a warp; the engine resolves on-demand\n * with memoization so any valid array order is handled correctly.\n *\n * Throws a clear internal Error if a parent is unexpectedly absent or a warp\n * hangs from a warp (defense-in-depth — indicates an unvalidated model was\n * passed to the engine).\n */\nexport function resolveDeformers(\n deformers: IkiDeformer[],\n params: ParameterStore,\n): ResolvedDeformers {\n const byId = new Map<string, IkiDeformer>(deformers.map((d) => [d.id, d]));\n const worlds = new Map<string, Affine>();\n const grids = new Map<string, ResolvedWarpGrid>();\n const localWarps = new Map<string, LocalWarp>();\n\n function parentOf(d: IkiDeformer): IkiDeformer | undefined {\n if (d.parent === undefined) return undefined;\n const parent = byId.get(d.parent);\n if (!parent) {\n throw new Error(\n `unresolved deformer parent \"${d.parent}\" — model not validated?`,\n );\n }\n return parent;\n }\n\n function resolveWorld(d: IkiMatrixDeformer): Affine {\n const cached = worlds.get(d.id);\n if (cached) return cached;\n\n const local = deformerLocalMatrix(d, params);\n const parent = parentOf(d);\n let world: Affine;\n if (parent === undefined) {\n world = local;\n } else if (parent.kind === \"warp\") {\n // The frame comes off the warp's LOCAL grid and the warp's own parent\n // affine goes on top — the same order the grid itself is resolved in,\n // so a rest warp between two matrices changes nothing.\n const warp = resolveWarp(parent);\n const ridden = multiply(\n warpRigidFrame(d.pivot, parent.grid, warp.localGrid),\n local,\n );\n world = warp.parentWorld ? multiply(warp.parentWorld, ridden) : ridden;\n } else {\n world = multiply(resolveWorld(parent), local);\n }\n\n worlds.set(d.id, world);\n return world;\n }\n\n function resolveWarp(d: IkiWarpDeformer): LocalWarp {\n const cached = localWarps.get(d.id);\n if (cached) return cached;\n\n const parent = parentOf(d);\n if (parent?.kind === \"warp\") {\n throw new Error(\n `warp deformer \"${d.id}\" hangs from warp \"${parent.id}\" — model not validated?`,\n );\n }\n const parentWorld = parent && resolveWorld(parent);\n // ORDER IS CRITICAL: keyform offsets FIRST (curvature added in the rest\n // frame), parent affine SECOND — so the curvature rotates WITH the parent\n // head rather than staying pinned to world axes. The reversed order\n // (affine then offsets) pushes the bend along world-x even when the head\n // is turned (coordinate bug).\n const localGrid = deformWarpGrid(d, params);\n grids.set(d.id, {\n cols: d.grid.cols,\n rows: d.grid.rows,\n points: parentWorld\n ? transformGridPoints(localGrid, parentWorld)\n : localGrid,\n });\n\n const resolved = { localGrid, parentWorld };\n localWarps.set(d.id, resolved);\n return resolved;\n }\n\n for (const d of deformers) {\n if (d.kind === \"warp\") resolveWarp(d);\n else resolveWorld(d);\n }\n\n return { worlds, grids };\n}\n","import { StandardParameter } from \"@ikijs/format\";\nimport { MAX_DT_MS } from \"./frame-clock\";\nimport { clamp, lerp, smoothstep } from \"./math\";\n\n// --- Module-internal timing/easing constants -----------------------------------\n// These are intentionally private; tests assert observable behavior, not config.\n\nconst BLINK_INTERVAL_MIN_MS = 1500;\nconst BLINK_INTERVAL_MAX_MS = 6000;\n// A blink closes fast and opens slower, with a moment shut in between. The\n// human blink-kinematics literature has the down-phase at roughly a third of\n// the whole and the up-phase decelerating into the open pose. These three are\n// a judgement inside the 150–180 ms range.\nconst BLINK_CLOSE_MS = 60;\nconst BLINK_HOLD_MS = 20;\nconst BLINK_OPEN_MS = 100;\nconst BLINK_DURATION_MS = BLINK_CLOSE_MS + BLINK_HOLD_MS + BLINK_OPEN_MS; // 180\n\nconst BREATH_PERIOD_MS = 3500;\n\nconst GAZE_RADIUS = 0.3;\nconst GAZE_RETARGET_MIN_MS = 1200;\nconst GAZE_RETARGET_MAX_MS = 3000;\n// Fraction of the gap to close each millisecond of clamped dt.\n// Chosen so a typical 16ms frame moves ~1.5 % of remaining distance.\nconst GAZE_EASE_RATE = 0.001;\n\n// Head sway: sums of slow sines with near-coprime periods, so the drift never\n// visibly repeats. Degrees — small against the ±30° standard AngleX/Y/Z range,\n// but enough continuous head motion to keep hair physics from sleeping.\nconst SWAY_X_AMP_A_DEG = 2.2;\nconst SWAY_X_PERIOD_A_MS = 6100;\nconst SWAY_X_AMP_B_DEG = 1.3;\nconst SWAY_X_PERIOD_B_MS = 9700;\nconst SWAY_Y_AMP_DEG = 1.6;\nconst SWAY_Y_PERIOD_MS = 7300;\n// Roll is the smallest and slowest of the three: an idle head barely tilts,\n// and a tilt reads much larger than a turn of the same degrees.\nconst SWAY_Z_AMP_DEG = 1.1;\nconst SWAY_Z_PERIOD_MS = 11300;\n\n// Ambient sway: the drift hair physics follows in idle, where the head sway\n// alone barely moves it. Two near-coprime periods (29:43) inside 2.5–5 s, away\n// from the breath and the head sines above so nothing beats in step; the\n// amplitudes sum to exactly ±1, the parameter's range. Zero phase, so the\n// resting pose writes 0 and it takes no rng draw (the blink and gaze\n// schedules keep their sequence).\nconst AMBIENT_AMP_A = 0.6;\nconst AMBIENT_PERIOD_A_MS = 2900;\nconst AMBIENT_AMP_B = 0.4;\nconst AMBIENT_PERIOD_B_MS = 4300;\n\n// --- Small pure helpers -------------------------------------------------------\n\n/**\n * Eye-open value over one blink, `phase` ∈ [0, 1]: 1 at both ends, 0 across the\n * hold. Close is a smoothstep (soft start, soft landing on the lid); open is a\n * quadratic ease-out (the lid leaves the hold at speed and settles). Exported\n * for the shape tests; not part of the package entry.\n */\nexport function blinkEnvelope(phase: number): number {\n const ms = phase * BLINK_DURATION_MS;\n if (ms <= 0) return 1;\n if (ms < BLINK_CLOSE_MS) return 1 - smoothstep(ms / BLINK_CLOSE_MS);\n if (ms <= BLINK_CLOSE_MS + BLINK_HOLD_MS) return 0; // inclusive: the close point is exactly 0 for any retune\n if (ms < BLINK_DURATION_MS) {\n const t = (ms - BLINK_CLOSE_MS - BLINK_HOLD_MS) / BLINK_OPEN_MS;\n return 1 - (1 - t) * (1 - t);\n }\n return 1;\n}\n\n/** Pick a random point within a disk of `radius` using the injected rng. */\nfunction randomInDisk(rng: () => number, radius: number): [number, number] {\n // Polar sampling: bounded, no rejection loop, safe with any [0,1) rng.\n // r = sqrt(u) gives uniform area distribution; θ spans the full circle.\n const r = Math.sqrt(rng()) * radius;\n const theta = rng() * 2 * Math.PI;\n return [r * Math.cos(theta), r * Math.sin(theta)];\n}\n\n// --- Public API ---------------------------------------------------------------\n\nexport interface IdleMotionOptions {\n /** Inject a deterministic rng for testing. Defaults to Math.random. */\n rng?: () => number;\n}\n\n/**\n * Pure-logic idle-animation driver. Animates the nine \"life\" parameters\n * (eyes, breath, gaze, head sway, ambient sway) on an internal clock so\n * tab-backgrounding or irregular frame delivery can't produce teleports or\n * snap-close blinks.\n *\n * Usage:\n * const idle = new IdleMotion(player.setParameter.bind(player));\n * // inside your rAF loop:\n * idle.update(performance.now());\n *\n * The host is responsible for scheduling; this class has no timers or rAF.\n */\nexport class IdleMotion {\n /**\n * Every parameter id {@link update} and `emitRestingPose` write, in write\n * order. Published so a host (or IkiMotion) can restore them after it\n * stops driving — keep in step with those two methods; the test suite\n * pins this list to the actual emissions.\n */\n readonly drivenParameterIds: readonly string[] = [\n StandardParameter.EyeOpenLeft,\n StandardParameter.EyeOpenRight,\n StandardParameter.Breath,\n StandardParameter.EyeballX,\n StandardParameter.EyeballY,\n StandardParameter.AngleX,\n StandardParameter.AngleY,\n StandardParameter.AngleZ,\n StandardParameter.AmbientSway,\n ];\n private readonly sink: (id: string, value: number) => void;\n private readonly rng: () => number;\n\n // Internal clock: advances by clamped dt, NOT by raw wall-clock jumps.\n // This is the only clock blink/breath/gaze scheduling reads.\n private clockMs = 0;\n private prevNowMs: number | undefined = undefined;\n\n // Blink state\n private nextBlinkAtMs: number;\n private blinkStartMs = -1; // -1 means not currently blinking\n\n // Gaze state\n private gazeCurrentX = 0;\n private gazeCurrentY = 0;\n private gazeTargetX = 0;\n private gazeTargetY = 0;\n private nextGazeRetargetMs: number;\n\n constructor(\n sink: (id: string, value: number) => void,\n options?: IdleMotionOptions,\n ) {\n this.sink = sink;\n // Math.random is the single allowed default reference; all other uses go\n // through this.rng so tests can inject a deterministic substitute.\n this.rng = options?.rng ?? Math.random;\n\n // Schedule the first blink and gaze retarget relative to clock zero.\n this.nextBlinkAtMs = lerp(\n BLINK_INTERVAL_MIN_MS,\n BLINK_INTERVAL_MAX_MS,\n this.rng(),\n );\n this.nextGazeRetargetMs = lerp(\n GAZE_RETARGET_MIN_MS,\n GAZE_RETARGET_MAX_MS,\n this.rng(),\n );\n }\n\n /**\n * Advance the idle animation to the given wall-clock timestamp (milliseconds).\n *\n * On the first call: record prevNowMs, emit the resting pose, and return —\n * no animation advance happens so there is no jump from time 0.\n *\n * On subsequent calls: compute dt = clamp(nowMs - prevNowMs, 0, MAX_DT_MS)\n * and advance the internal clock by dt. A non-monotonic nowMs produces a\n * negative raw delta that the clamp floors to 0 — no rewind.\n */\n update(nowMs: number): void {\n // Host-supplied timestamp, same boundary rule as FixedStepClock.advance and\n // ParameterStore.set: drop the frame, touch nothing. `clockMs += NaN` would\n // stick, and every blink/gaze schedule reads clockMs — the face would go\n // still permanently. A host driving from media time hands you NaN through an\n // ordinary path (`duration * pct` before metadata loads).\n if (!Number.isFinite(nowMs)) return;\n if (this.prevNowMs === undefined) {\n this.prevNowMs = nowMs;\n // Emit resting pose so the host mirror stays in sync from frame 1.\n this.emitRestingPose();\n return;\n }\n\n // Clamp dt so a backgrounded tab or long GC pause advances the internal\n // clock by at most MAX_DT_MS — blink can't snap shut, gaze can't teleport.\n const rawDt = nowMs - this.prevNowMs;\n const dt = clamp(rawDt, 0, MAX_DT_MS);\n this.prevNowMs = nowMs;\n this.clockMs += dt;\n\n // Both eyes always carry the identical value (unified blink).\n const eyeVal = this.advanceBlink();\n this.sink(StandardParameter.EyeOpenLeft, eyeVal);\n this.sink(StandardParameter.EyeOpenRight, eyeVal);\n\n const breath = this.advanceBreath();\n this.advanceGaze(dt);\n\n this.sink(StandardParameter.Breath, breath);\n this.sink(StandardParameter.EyeballX, this.gazeCurrentX);\n this.sink(StandardParameter.EyeballY, this.gazeCurrentY);\n\n // Head sway keeps the character (and any hair physics reading AngleX/Y/Z)\n // from freezing solid between blinks. Models without these parameters\n // ignore the writes (ParameterStore drops unknown ids).\n this.sink(StandardParameter.AngleX, this.swayX());\n this.sink(StandardParameter.AngleY, this.swayY());\n this.sink(StandardParameter.AngleZ, this.swayZ());\n this.sink(StandardParameter.AmbientSway, this.ambientSway());\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private emitRestingPose(): void {\n this.sink(StandardParameter.EyeOpenLeft, 1);\n this.sink(StandardParameter.EyeOpenRight, 1);\n // Breath at phase 0: sin(0) = 0 → 0.5 + 0.5*0 = 0.5\n this.sink(StandardParameter.Breath, 0.5);\n this.sink(StandardParameter.EyeballX, 0);\n this.sink(StandardParameter.EyeballY, 0);\n // Sway sines are all 0 at clock 0 — the head starts centered.\n this.sink(StandardParameter.AngleX, 0);\n this.sink(StandardParameter.AngleY, 0);\n this.sink(StandardParameter.AngleZ, 0);\n this.sink(StandardParameter.AmbientSway, 0);\n }\n\n /** Returns the current eye-open value (0..1) and advances blink state. */\n private advanceBlink(): number {\n const { clockMs } = this;\n\n // If a blink is in progress, evaluate the envelope.\n if (this.blinkStartMs >= 0) {\n const phase = (clockMs - this.blinkStartMs) / BLINK_DURATION_MS;\n if (phase >= 1) {\n // Blink finished — schedule the next one on the internal clock.\n this.blinkStartMs = -1;\n this.nextBlinkAtMs =\n clockMs +\n lerp(BLINK_INTERVAL_MIN_MS, BLINK_INTERVAL_MAX_MS, this.rng());\n return 1;\n }\n return blinkEnvelope(phase);\n }\n\n // Check if it is time to start a new blink.\n if (clockMs >= this.nextBlinkAtMs) {\n this.blinkStartMs = clockMs;\n // Return the first envelope sample (exactly 1 at phase 0).\n return blinkEnvelope(0);\n }\n\n // Between blinks: eyes fully open.\n return 1;\n }\n\n private advanceBreath(): number {\n return (\n 0.5 + 0.5 * Math.sin((2 * Math.PI * this.clockMs) / BREATH_PERIOD_MS)\n );\n }\n\n /** Horizontal head sway in degrees, pure function of the internal clock. */\n private swayX(): number {\n const t = 2 * Math.PI * this.clockMs;\n return (\n SWAY_X_AMP_A_DEG * Math.sin(t / SWAY_X_PERIOD_A_MS) +\n SWAY_X_AMP_B_DEG * Math.sin(t / SWAY_X_PERIOD_B_MS)\n );\n }\n\n /** Vertical head sway in degrees, pure function of the internal clock. */\n private swayY(): number {\n return (\n SWAY_Y_AMP_DEG * Math.sin((2 * Math.PI * this.clockMs) / SWAY_Y_PERIOD_MS)\n );\n }\n\n /** Head roll sway in degrees, pure function of the internal clock. */\n private swayZ(): number {\n return (\n SWAY_Z_AMP_DEG * Math.sin((2 * Math.PI * this.clockMs) / SWAY_Z_PERIOD_MS)\n );\n }\n\n /** Ambient sway (-1..1), pure function of the internal clock. */\n private ambientSway(): number {\n const t = 2 * Math.PI * this.clockMs;\n return (\n AMBIENT_AMP_A * Math.sin(t / AMBIENT_PERIOD_A_MS) +\n AMBIENT_AMP_B * Math.sin(t / AMBIENT_PERIOD_B_MS)\n );\n }\n\n /** Ease gaze current toward target; pick a new target on the internal clock. */\n private advanceGaze(dt: number): void {\n // Retarget check reads clockMs so a clamped pause can't skip retargets.\n if (this.clockMs >= this.nextGazeRetargetMs) {\n const [tx, ty] = randomInDisk(this.rng, GAZE_RADIUS);\n this.gazeTargetX = tx;\n this.gazeTargetY = ty;\n this.nextGazeRetargetMs =\n this.clockMs +\n lerp(GAZE_RETARGET_MIN_MS, GAZE_RETARGET_MAX_MS, this.rng());\n }\n\n // Exponential ease toward target. The ease factor is derived from the\n // CLAMPED dt so a paused tab moves at most one normal step, never a teleport.\n const factor = 1 - Math.pow(1 - GAZE_EASE_RATE, dt);\n this.gazeCurrentX = lerp(this.gazeCurrentX, this.gazeTargetX, factor);\n this.gazeCurrentY = lerp(this.gazeCurrentY, this.gazeTargetY, factor);\n }\n}\n","import { clamp } from \"./math\";\n\n/** Per-frame dt ceiling: a backgrounded tab or a long GC pause must not snap state. */\nexport const MAX_DT_MS = 100;\n/** Fixed integration sub-step, in SECONDS. */\nexport const FIXED_DT_S = 1 / 60;\n/** Catch-up cap per frame (spiral-of-death guard). */\nexport const MAX_SUBSTEPS = 6;\n\n/**\n * Fixed-timestep accumulator shared by the physics drivers, so a stability fix\n * lands in one place instead of one of two near-identical copies.\n *\n * A driver calls {@link advance} once per frame and runs its integration body\n * that many times. Leftover time carries to the next frame, which is what keeps\n * the simulation frame-rate independent; the dt clamp and the sub-step cap keep\n * a hitch from either snapping the rig or spiralling into catch-up work.\n */\nexport class FixedStepClock {\n private prevNowMs: number | undefined = undefined;\n private accumulatorS = 0;\n\n /**\n * True until the first {@link advance}. Drivers seed their rest pose on that\n * frame and integrate nothing, so a model loaded mid-motion does not kick.\n */\n get isSeedFrame(): boolean {\n return this.prevNowMs === undefined;\n }\n\n /**\n * Time carried in the accumulator, in seconds: how far the frame's timestamp is\n * past the last whole sub-step. Drivers extrapolate their state by it so what\n * they emit is the state at the frame's time, not at the last sub-step.\n */\n get remainderS(): number {\n return this.accumulatorS;\n }\n\n /**\n * Fold `nowMs` into the accumulator and return how many {@link FIXED_DT_S}\n * sub-steps to run this frame. On the seed frame it only records the\n * timestamp and returns 0. A non-monotonic `nowMs` floors to 0 — no rewind.\n */\n advance(nowMs: number): number {\n // Host-supplied timestamp, so the same rule as ParameterStore.set: reject\n // non-finite input at the boundary. `clamp(NaN, ...)` is NaN, which would\n // make the accumulator NaN and every `NaN >= FIXED_DT_S` false FOREVER —\n // the rig would freeze silently with no way back. Pre-existing; hardened\n // here so both host entry points behave the same way.\n if (!Number.isFinite(nowMs)) return 0;\n if (this.prevNowMs === undefined) {\n this.prevNowMs = nowMs;\n return 0;\n }\n const dtMs = clamp(nowMs - this.prevNowMs, 0, MAX_DT_MS);\n this.prevNowMs = nowMs;\n this.accumulatorS += dtMs / 1000; // boundary ms->s conversion\n\n let steps = 0;\n while (this.accumulatorS >= FIXED_DT_S && steps < MAX_SUBSTEPS) {\n this.accumulatorS -= FIXED_DT_S;\n steps++;\n }\n return steps;\n }\n}\n","import {\n type IkiParameter,\n type IkiPhysics,\n physicsInputs,\n} from \"@ikijs/format\";\nimport { FIXED_DT_S, FixedStepClock } from \"./frame-clock\";\nimport { clamp } from \"./math\";\n\n// --- Small pure helpers ------------------------------------------------------\n\n/**\n * Map a parameter value to [-1, 1] around its engine-effective default. Portable\n * across param ranges: the wider side (rest→max vs min→rest) sets the unit, so\n * ±1 lands at the farther extreme. Returns 0 for a zero-width range.\n *\n * The rest center is `clamp(default, min, max)` to match ParameterStore, which\n * clamps an out-of-range default — so the spring rests where the model actually\n * renders, not at a raw out-of-range default.\n */\nfunction signedNormalized(\n value: number,\n param: { min: number; max: number; default: number },\n): number {\n const rest = clamp(param.default, param.min, param.max);\n const den = Math.max(Math.abs(param.max - rest), Math.abs(rest - param.min));\n if (den === 0) return 0;\n return clamp((value - rest) / den, -1, 1);\n}\n\n// --- Public API --------------------------------------------------------------\n\ninterface RigState {\n x: number; // spring position (lagging, normalized-ish units)\n v: number; // spring velocity\n lag: number; // Σ wᵢ·nᵢ over the lag inputs, as the last finite frame read it\n}\n\n/** One input of a rig, resolved once so the frame loop never branches on shape. */\ninterface RigInput {\n parameter: string;\n weight: number;\n lag: boolean;\n}\n\n/**\n * Host-agnostic 1D spring-mass-damper secondary-motion driver — the physics\n * peer of {@link IdleMotion}. For each rig it reads every input parameter,\n * signed-normalizes it around its default × `weight`, sums those into one spring\n * target `T`, integrates a lagging spring position `x` with semi-implicit\n * (symplectic) Euler on a fixed 1/60s sub-step accumulator, and writes\n * `outputDefault + (x − L) * scale` (x carried forward by the clock's leftover time) onto the output parameter, `L` being the\n * lag inputs' share of `T` — so the output lags and overshoots the inputs\n * (hair/accessory sway).\n *\n * By superposition a follow input's held value stays in the output (the spring\n * settles at `T`), while a lag input's held value settles out, returning the\n * output to rest: it swings only while that input moves. A rig seeded with a\n * lag input already displaced emits rest, without a kick. Inputs are not\n * smoothed, so a one-frame step on a lag input snaps the output by\n * `−scale·weight·Δn` before the spring catches up — deferred until a captured\n * snap calls for a rate limit.\n *\n * Usage:\n * const physics = new PhysicsMotion(\n * model.physics ?? [],\n * model.parameters,\n * (id) => currentValue(id),\n * player.setParameter.bind(player),\n * );\n * // inside your rAF loop, right AFTER idle.update(now):\n * physics.update(performance.now());\n *\n * The host schedules updates; this class has no timers, rAF, DOM, or Date.now.\n * Writes go through the sink, exactly like IdleMotion; the player renders the\n * updated params on its own render loop (drivers and rendering are decoupled).\n */\nexport class PhysicsMotion {\n /** The output parameter of every rig, in rig order — what `emit` writes. */\n readonly drivenParameterIds: readonly string[];\n /**\n * Per rig: how many times the finiteness guard reset its state or `emit`\n * replaced its non-finite product. Up to two per frame, so guard activations,\n * not repaired frames. A diagnostic; emitted values are unchanged.\n */\n readonly resets: readonly number[];\n private readonly resetCounts: number[];\n private readonly rigs: readonly IkiPhysics[];\n private readonly inputs: readonly (readonly RigInput[])[];\n private readonly read: (id: string) => number;\n private readonly sink: (id: string, value: number) => void;\n private readonly params: Map<string, IkiParameter>;\n\n // Integrator state, owned here — never stored in a ParameterStore.\n private readonly state: RigState[];\n private readonly clock = new FixedStepClock();\n\n constructor(\n rigs: IkiPhysics[],\n params: IkiParameter[],\n read: (id: string) => number,\n sink: (id: string, value: number) => void,\n ) {\n this.rigs = rigs;\n this.inputs = rigs.map((rig) =>\n physicsInputs(rig).map(({ parameter, weight, mode }) => ({\n parameter,\n weight,\n lag: mode === \"lag\",\n })),\n );\n this.read = read;\n this.sink = sink;\n this.params = new Map(params.map((p) => [p.id, p]));\n this.state = rigs.map(() => ({ x: 0, v: 0, lag: 0 }));\n this.drivenParameterIds = rigs.map((rig) => rig.output.parameter);\n this.resetCounts = rigs.map(() => 0);\n this.resets = this.resetCounts;\n }\n\n /**\n * Advance every rig to the given wall-clock timestamp (milliseconds).\n *\n * First call: seed each spring to rest AT its current target (so a model\n * loaded with a nonzero input does not kick: a lag input emits rest, a follow\n * input its value), emit that output, and return without integrating —\n * mirroring IdleMotion's first-frame behavior.\n *\n * A non-finite `nowMs` after that is a dropped frame: every rig re-emits its\n * last output from its stored state without reading its inputs.\n *\n * Subsequent calls: {@link FixedStepClock} folds the clamped frame delta into\n * its accumulator and returns how many {@link FIXED_DT_S} sub-steps are due;\n * the spring advances that many semi-implicit Euler steps, then each rig emits\n * its output once. The clock's dt clamp and sub-step cap plus the symplectic\n * integrator are what keep it stable across hitches.\n */\n update(nowMs: number): void {\n if (this.clock.isSeedFrame) {\n this.clock.advance(nowMs);\n for (let i = 0; i < this.rigs.length; i++) {\n const st = this.state[i];\n const { target, lag } = this.targetFor(i);\n st.x = target;\n st.v = 0;\n st.lag = lag;\n this.emit(i, st);\n }\n return;\n }\n\n // A dropped frame (the clock rejects it as well). Re-emit from the stored\n // `L` rather than read the inputs, or a lag rig's output would move on it.\n if (!Number.isFinite(nowMs)) {\n for (let i = 0; i < this.rigs.length; i++) this.emit(i, this.state[i]);\n return;\n }\n\n const steps = this.clock.advance(nowMs);\n\n // update() is synchronous, so the inputs cannot change mid-loop — read each\n // rig's target ONCE per frame and reuse it across the sub-steps.\n const targets = this.rigs.map((_, i) => this.targetFor(i));\n\n for (let s = 0; s < steps; s++) {\n for (let i = 0; i < this.rigs.length; i++) {\n this.step(this.rigs[i], this.state[i], targets[i].target);\n }\n }\n\n // Always emit (even when zero sub-steps ran) so the sink stays in sync.\n for (let i = 0; i < this.rigs.length; i++) {\n const st = this.state[i];\n // The fixed 1/60s sub-step can diverge for an extreme-but-parse-valid rig\n // (tiny mass / huge stiffness push ω·dt past the explicit-integrator\n // stability limit). If state goes non-finite, snap back to rest at the\n // current target: the store DROPS a non-finite write, so an un-reset rig\n // would emit NaN every frame and silently freeze the part at its last\n // good pose instead of visibly diverging.\n const { target, lag } = targets[i];\n if (!Number.isFinite(st.x) || !Number.isFinite(st.v)) {\n st.x = Number.isFinite(target) ? target : 0;\n st.v = 0;\n this.resetCounts[i]++;\n }\n st.lag = lag;\n this.emit(i, st);\n }\n }\n\n /**\n * Rig `index`'s spring target `T` = Σ signed-normalized input value × weight,\n * and `L`, the lag inputs' share of it. Reads each input once.\n */\n private targetFor(index: number): { target: number; lag: number } {\n let target = 0;\n let lag = 0;\n for (const input of this.inputs[index]) {\n const param = this.params.get(input.parameter);\n const value = this.read(input.parameter);\n const share = (param ? signedNormalized(value, param) : 0) * input.weight;\n target += share;\n if (input.lag) lag += share;\n }\n return { target, lag };\n }\n\n /** One semi-implicit (symplectic) Euler sub-step of FIXED_DT_S seconds. */\n private step(rig: IkiPhysics, st: RigState, target: number): void {\n const accel =\n (rig.stiffness * (target - st.x) - rig.damping * st.v) / rig.mass;\n st.v += accel * FIXED_DT_S;\n st.x += st.v * FIXED_DT_S;\n }\n\n /** Write outputDefault + (x − L) * scale onto the output param via the sink. */\n private emit(index: number, st: RigState): void {\n const rig = this.rigs[index];\n const outParam = this.params.get(rig.output.parameter);\n // clamp to match ParameterStore's engine-effective default (see signedNormalized).\n const outDefault = outParam\n ? clamp(outParam.default, outParam.min, outParam.max)\n : 0;\n // `x` only moves in whole sub-steps while `lag` is this frame's, so emit x\n // carried forward by the time since its last sub-step: the output then\n // follows the frame's time, not how many sub-steps happened to be due.\n // Extrapolating (not interpolating from the previous state) adds no lag, and\n // at rest (v = 0) it changes nothing.\n const x = st.x + st.v * this.clock.remainderS;\n const value = outDefault + (x - st.lag) * rig.output.scale;\n // Final guard: even a finite-but-enormous `x` could overflow the product to\n // ±Infinity. Emit the rest pose rather than hand a non-finite value to the\n // sink, which would drop the write and leave the output stuck where it was.\n const finite = Number.isFinite(value);\n if (!finite) this.resetCounts[index]++;\n this.sink(rig.output.parameter, finite ? value : outDefault);\n }\n}\n","import type {\n IkiDeformer,\n IkiParameter,\n IkiPhysicsChain,\n IkiPhysicsChainSegment,\n} from \"@ikijs/format\";\nimport type { Affine } from \"./affine\";\nimport { resolveDeformers } from \"./deform\";\n// The two physics drivers stay independent of EACH OTHER; the timing primitives\n// they both need live in frame-clock.ts so a stability fix lands once.\nimport { FIXED_DT_S, FixedStepClock } from \"./frame-clock\";\nimport { clamp } from \"./math\";\nimport { ParameterStore } from \"./parameter-store\";\n\nconst DEG2RAD = Math.PI / 180;\nconst RAD2DEG = 180 / Math.PI;\n\n// --- Per-chain / per-segment state -------------------------------------------\n\n/** Integrator state for one segment. angle = θ displacement in RADIANS. */\ninterface SegmentState {\n angle: number; // θ_i in radians (displacement from rest)\n angularVelocity: number; // ω_i in radians/s\n}\n\n/** All precomputed per-chain data (rest angles already in radians). */\ninterface ChainData {\n chain: IkiPhysicsChain;\n restAnglesRad: number[]; // restAngle_j in radians; 0 when omitted\n state: SegmentState[]; // preallocated, length = segments.length\n}\n\n// --- Public API --------------------------------------------------------------\n\n/**\n * Host-agnostic multi-segment angular-pendulum-chain secondary-motion driver.\n * Peer of {@link PhysicsMotion} and {@link IdleMotion}.\n *\n * Each chain anchors to a matrix deformer in the model hierarchy. The driver\n * self-computes the anchor's world rotation via `resolveDeformers` (a\n * private `ParameterStore` is filled from `read` ONCE per frame) and integrates\n * a per-segment angular pendulum with semi-implicit Euler on a fixed 1/60s\n * sub-step accumulator. Each segment's angular displacement θ (in radians\n * internally) is emitted in DEGREES on its output parameter, so `rotate = 0`\n * when the chain is at its authored rest pose.\n *\n * Usage:\n * const chains = new HairChainMotion(\n * model.physicsChains ?? [],\n * model.parameters,\n * model.deformers ?? [],\n * (id) => currentValue(id),\n * player.setParameter.bind(player),\n * );\n * // inside your rAF loop, right AFTER physics.update(now):\n * chains.update(performance.now());\n *\n * The host schedules updates; this class has no timers, rAF, DOM, or Date.now.\n */\nexport class HairChainMotion {\n /** Every segment's output, chain by chain — what `emitSegment` writes. */\n readonly drivenParameterIds: readonly string[];\n /**\n * Per segment, in `drivenParameterIds` order: how many times the finiteness\n * guard reset its state or `emitSegment` replaced its non-finite product. Up\n * to two per frame, so guard activations, not repaired frames. A diagnostic;\n * emitted values are unchanged.\n */\n readonly resets: readonly number[];\n private readonly resetCounts: number[];\n private readonly chainData: ChainData[];\n private readonly params: Map<string, IkiParameter>;\n private readonly deformers: IkiDeformer[];\n private readonly store: ParameterStore;\n private readonly read: (id: string) => number;\n private readonly sink: (id: string, value: number) => void;\n\n private readonly clock = new FixedStepClock();\n\n constructor(\n chains: IkiPhysicsChain[],\n params: IkiParameter[],\n deformers: IkiDeformer[],\n read: (id: string) => number,\n sink: (id: string, value: number) => void,\n ) {\n this.params = new Map(params.map((p) => [p.id, p]));\n this.deformers = deformers;\n // Private ParameterStore reused every frame for anchor-world resolution.\n this.store = new ParameterStore(params);\n this.read = read;\n this.sink = sink;\n\n // Precompute rest angles in radians; preallocate segment state (no per-substep alloc).\n this.chainData = chains.map((chain) => ({\n chain,\n restAnglesRad: chain.segments.map((seg) =>\n seg.restAngle !== undefined ? seg.restAngle * DEG2RAD : 0,\n ),\n state: chain.segments.map(() => ({ angle: 0, angularVelocity: 0 })),\n }));\n this.drivenParameterIds = chains.flatMap((c) =>\n c.segments.map((s) => s.output.parameter),\n );\n this.resetCounts = this.drivenParameterIds.map(() => 0);\n this.resets = this.resetCounts;\n }\n\n /**\n * Advance every chain to the given wall-clock timestamp (milliseconds).\n *\n * First call: seed every segment to θ=0/ω=0 (rest), emit the rest output\n * (outDefault + 0), and return without integrating — mirrors PhysicsMotion's\n * first-frame behavior so a model loaded in motion does not kick.\n *\n * Subsequent calls: dt = clamp(nowMs - prevNowMs, 0, MAX_DT_MS) → seconds into\n * accumulator. The per-frame world snapshot (anchor world angles) is taken ONCE\n * per update() — NOT per chain — so all chains share a consistent frame snapshot.\n * Fixed FIXED_DT_S sub-steps are run root→tip, capped at MAX_SUBSTEPS; leftover\n * time is carried to the next frame. Segments emit after substeps (even on zero\n * substeps) with a non-finite guard.\n */\n update(nowMs: number): void {\n // IkiMotion steps this driver every frame even for a chainless model;\n // with nothing to integrate or emit, skip the per-frame deformer resolve.\n if (this.chainData.length === 0) return;\n if (this.clock.isSeedFrame) {\n // FIRST FRAME: seed rest, emit outDefault for every segment, NO integration.\n this.clock.advance(nowMs);\n let flat = 0;\n for (const cd of this.chainData) {\n for (let i = 0; i < cd.chain.segments.length; i++) {\n cd.state[i].angle = 0;\n cd.state[i].angularVelocity = 0;\n this.emitSegment(flat++, cd.chain.segments[i], cd.state[i]);\n }\n }\n return;\n }\n\n const steps = this.clock.advance(nowMs);\n\n // Take the per-frame world snapshot ONCE per update() — NOT per chain.\n // Fill the private store from read, then resolve every deformer (warp grids\n // too, though only the matrix worlds are read here).\n for (const param of this.params.values()) {\n this.store.set(param.id, this.read(param.id));\n }\n const worldMap = resolveDeformers(this.deformers, this.store).worlds;\n\n // Read each chain's anchor world angle ONCE per frame (consistent across substeps,\n // like physics-motion.ts:122 `targets`).\n const anchorAnglesRad = this.chainData.map((cd) =>\n this.anchorWorldAngleRad(worldMap, cd.chain.anchorDeformer),\n );\n\n for (let s = 0; s < steps; s++) {\n for (let c = 0; c < this.chainData.length; c++) {\n this.stepChain(this.chainData[c], anchorAnglesRad[c]);\n }\n }\n\n // Emit always (even on zero substeps) so the sink stays in sync.\n let flat = 0;\n for (const cd of this.chainData) {\n for (let i = 0; i < cd.chain.segments.length; i++) {\n const st = cd.state[i];\n // FINITENESS GUARD (mirror physics-motion.ts:141): a pathological rig\n // (tiny mass / huge stiffness) can push the fixed-substep integrator\n // past its explicit-stability limit. Snap the segment back to rest so\n // a validated model can never poison the sink with NaN/Infinity.\n if (\n !Number.isFinite(st.angle) ||\n !Number.isFinite(st.angularVelocity)\n ) {\n st.angle = 0;\n st.angularVelocity = 0;\n this.resetCounts[flat]++;\n }\n this.emitSegment(flat++, cd.chain.segments[i], st);\n }\n }\n }\n\n /**\n * Extract world rotation (radians) from the anchor's Affine tuple.\n * Affine = [a,b,c,d,e,f]; rotation column = (a,b) → atan2(b,a).\n *\n * If the anchor id is absent from the map, THROWS an internal Error — the\n * format validator guarantees the anchor exists, so absence is an invariant\n * break (mirrors resolveDeformers' throw on an unresolved parent).\n */\n private anchorWorldAngleRad(\n worldMap: Map<string, Affine>,\n anchorId: string,\n ): number {\n const world = worldMap.get(anchorId);\n if (!world) {\n throw new Error(\n `HairChainMotion: anchor deformer \"${anchorId}\" not found in resolved world map — model not validated?`,\n );\n }\n // Affine [a,b,c,d,e,f]: the first column (a,b) is the x-axis direction\n // after rotation, so atan2(b,a) gives the world rotation angle in radians.\n return Math.atan2(world[1], world[0]);\n }\n\n /**\n * One fixed sub-step of FIXED_DT_S seconds for all segments in a chain.\n *\n * Segments are integrated ROOT→TIP so each segment can read its upstream\n * neighbor's current-substep state when computing the world angle Φ_i.\n * (The chain is causal root-to-tip; reversing the order would use stale θ\n * values from the previous substep for Φ_i computation.)\n *\n * Per-segment semi-implicit (symplectic) Euler:\n * Φ_i = anchorWorldAngleRad + Σ_{j≤i}(restAngle_j + θ_j)\n * α_i = (−stiffness_i·θ_i − strength·sin(Φ_i − gravityAngle_rad) − damping_i·ω_i) / mass_i\n * ω_i += α_i · FIXED_DT_S (velocity updated FIRST = semi-implicit)\n * θ_i += ω_i · FIXED_DT_S (position updated from NEW velocity)\n *\n * The spring term is −stiffness·θ (restoring θ→0); restAngle does NOT appear\n * in the spring term, only in Φ_i for the gravity torque.\n */\n private stepChain(cd: ChainData, anchorAngleRad: number): void {\n const { chain, restAnglesRad, state } = cd;\n const gravityAngleRad = chain.gravity.angle * DEG2RAD;\n const strength = chain.gravity.strength;\n\n // Accumulate world angle root→tip as we go.\n let worldAngleAccumRad = anchorAngleRad;\n\n for (let i = 0; i < chain.segments.length; i++) {\n const seg: IkiPhysicsChainSegment = chain.segments[i];\n const st = state[i];\n\n // World angle of this segment: anchor + sum of all segments 0..i.\n worldAngleAccumRad += restAnglesRad[i] + st.angle;\n const phi = worldAngleAccumRad;\n\n const alpha =\n (-seg.stiffness * st.angle -\n strength * Math.sin(phi - gravityAngleRad) -\n seg.damping * st.angularVelocity) /\n seg.mass;\n\n // Semi-implicit Euler: update velocity first, then position with new velocity.\n st.angularVelocity += alpha * FIXED_DT_S;\n st.angle += st.angularVelocity * FIXED_DT_S;\n }\n }\n\n /** Emit outDefault + (θ_i · RAD2DEG) · scale for one segment. */\n private emitSegment(\n flat: number,\n seg: IkiPhysicsChainSegment,\n st: SegmentState,\n ): void {\n const outParam = this.params.get(seg.output.parameter);\n const outDefault = outParam\n ? clamp(outParam.default, outParam.min, outParam.max)\n : 0;\n const value = outDefault + st.angle * RAD2DEG * seg.output.scale;\n // Final guard: even a finite-but-enormous θ could overflow to ±Infinity.\n const finite = Number.isFinite(value);\n if (!finite) this.resetCounts[flat]++;\n this.sink(seg.output.parameter, finite ? value : outDefault);\n }\n}\n","import { type IkiModel, StandardParameter } from \"@ikijs/format\";\nimport { ClipPlayer } from \"./clip-player\";\nimport { ExpressionPlayer } from \"./expression-player\";\nimport { MAX_DT_MS } from \"./frame-clock\";\nimport { HairChainMotion } from \"./hair-chain-motion\";\nimport { IdleMotion } from \"./idle-motion\";\nimport { clamp } from \"./math\";\nimport { ParameterStore } from \"./parameter-store\";\nimport { PhysicsMotion } from \"./physics-motion\";\n\n/** IdleMotion's head sway and gaze: what a declared Idle group replaces. */\nconst HEAD_AND_GAZE: ReadonlySet<string> = new Set([\n StandardParameter.AngleX,\n StandardParameter.AngleY,\n StandardParameter.AngleZ,\n StandardParameter.EyeballX,\n StandardParameter.EyeballY,\n]);\n\n/**\n * Bundles the model's motion into the one loop every host otherwise\n * hand-builds: the procedural {@link IdleMotion}, the model's motion clips and\n * expressions, then {@link PhysicsMotion} and {@link HairChainMotion} — stepped\n * in the order physics and chains depend on, with a record of what they write.\n *\n * Usage:\n * const motion = new IkiMotion(\n * model,\n * (id) => player.getParameter(id),\n * (id, value) => player.setParameter(id, value),\n * );\n * motion.playExpression(\"smile\");\n * motion.playMotion(\"Nod\", 0);\n * // inside your rAF loop:\n * motion.update(performance.now());\n * // then the signals the host owns, e.g. lip-sync:\n * player.setParameter(StandardParameter.MouthOpen, mouth);\n *\n * The model is the catalog: a host lists what it can play from\n * `model.expressions` (ids) and `model.motions` (group names and clip\n * indices). There are no getters for them here.\n *\n * Clips and expressions compose over a base, never over the store's current\n * value: an id's base is the value an earlier stage put in this update's\n * frame (for the one-shot: the procedural idle and the `Idle` loop; for an\n * expression: those and the one-shot), else its resting value\n * `clamp(default, min, max)`. So an `add` on a brow cannot accumulate across\n * frames, and an expression composes with the blink and a clip-driven head.\n * When an expression's stop completes or a one-shot ends, the ids it drove\n * are written once more at base and then dropped; so are the ids only a\n * replaced clip or expression held, once the one replacing it finishes its\n * fade-in. A parameter nothing else writes therefore rests at its default.\n *\n * Idle replacement: when the model declares an `Idle` motion group, its clips\n * loop in place of the procedural head sway and gaze — IdleMotion's AngleX/Y/Z\n * and EyeballX/Y writes are dropped. A head or gaze parameter the Idle clips\n * don't animate is left unwritten by idle and rests where it is (a one-shot or\n * an expression can still drive it). Blink (EyeOpen L/R), Breath and the\n * ambient sway stay procedural: the format rejects an Idle curve on them.\n * Without an `Idle` group the procedural idle runs whole.\n *\n * The host schedules; this class has no timers, rAF, DOM, or Date.now.\n *\n * Stopping is the host's too: stop calling update(). The drivers leave the\n * pose where it was — a host that wants it back writes its own resting values\n * to `drivenParameterIds`.\n */\nexport class IkiMotion {\n /**\n * Everything {@link update} may write, deduplicated, in this order: idle ids\n * (without head and gaze when the model declares an `Idle` group), the curve\n * parameters of every motion group, expression parameters, rig outputs,\n * then chain-segment outputs. May name ids the model lacks (idle writes the\n * standard ids regardless, and the player silently drops writes to unknown\n * ids) — intersect with the model's parameters if you mirror into your own\n * store.\n */\n readonly drivenParameterIds: readonly string[];\n private readonly sink: (id: string, value: number) => void;\n private readonly idle: IdleMotion;\n private readonly clips: ClipPlayer;\n private readonly expressions: ExpressionPlayer;\n private readonly physics: PhysicsMotion;\n private readonly chains: HairChainMotion;\n /** Resting value per id; 0 for an undeclared id. */\n private readonly rest: (id: string) => number;\n /** This update's idle, clip and expression writes, in first-write order. */\n private readonly frame = new Map<string, number>();\n /** Bound once: `Map.forEach` hands it each entry without a tuple per id. */\n private readonly flush = (value: number, id: string): void =>\n this.sink(id, value);\n private prevNowMs: number | undefined = undefined;\n\n constructor(\n model: IkiModel,\n read: (id: string) => number,\n sink: (id: string, value: number) => void,\n ) {\n const rigs = model.physics ?? [];\n const chains = model.physicsChains ?? [];\n // A store nobody writes holds every parameter at rest, resolved the way\n // the player's store resolves it (a non-finite default rests at 0,\n // clamped), and reads 0 for an undeclared id.\n const restPose = new ParameterStore(model.parameters);\n this.sink = sink;\n this.rest = (id) => restPose.get(id);\n this.clips = new ClipPlayer(model.motions, model.parameters);\n this.expressions = new ExpressionPlayer(\n model.expressions,\n model.parameters,\n );\n const idleKeeps: (id: string) => boolean = this.clips.hasIdleLoop\n ? (id) => !HEAD_AND_GAZE.has(id)\n : () => true;\n this.idle = new IdleMotion((id, value) => {\n if (idleKeeps(id)) this.frame.set(id, value);\n });\n this.physics = new PhysicsMotion(rigs, model.parameters, read, sink);\n this.chains = new HairChainMotion(\n chains,\n model.parameters,\n model.deformers ?? [],\n read,\n sink,\n );\n this.drivenParameterIds = [\n ...new Set([\n ...this.idle.drivenParameterIds.filter(idleKeeps),\n ...this.clips.parameterIds,\n ...this.expressions.parameterIds,\n ...this.physics.drivenParameterIds,\n ...this.chains.drivenParameterIds,\n ]),\n ];\n }\n\n /**\n * Make expression `id` active, fading it in over its `fadeIn` from the\n * current pose: it replaces the active one and blends from that one's\n * current output, as {@link playMotion} does, so nothing dips toward base on\n * the way. Returns false, and changes nothing, for an id the model does not\n * declare. Playing the active id again changes nothing and returns true; an\n * expression never stacks on itself.\n */\n playExpression(id: string): boolean {\n return this.expressions.play(id);\n }\n\n /** Fade the active expression, if any, back to base over its `fadeOut`. */\n stopExpression(): void {\n this.expressions.stop();\n }\n\n /**\n * Start clip `index` of motion group `group` at once. A running one-shot\n * stops, and the new clip fades in from the old one's last pose. Returns\n * false, and changes nothing, for a group the model does not declare or an\n * index that is not an integer in range. Any group plays one-shot, `Idle`\n * included; there is no queue.\n */\n playMotion(group: string, index: number): boolean {\n return this.clips.play(group, index);\n }\n\n /**\n * Advance everything to the same wall-clock timestamp (milliseconds), in\n * this order:\n *\n * 1. Idle writes blink, breath, the ambient sway (and head and gaze, unless\n * replaced) into this update's frame.\n * 2. The clip stage writes the `Idle` loop, then the one-shot over it.\n * 3. The expression stage writes the active expression, fading in from the\n * pose it replaced, or a stop fading back to base.\n * 4. The frame goes to `sink`, each id exactly once, in the order its first\n * writer gave it: an expression on EyeOpenL is flushed in idle's slot.\n * 5. Physics, then chains. They read their inputs through `read`, so the\n * springs lag the head this update put on screen (idle sway or clips),\n * and a chain resolves its anchor from that same pose (which may include\n * a physics output). Physics outputs are physics-owned: a clip or\n * expression that writes one is overwritten here.\n *\n * The host writes the signals it owns (lip-sync MouthOpen, gaze overrides)\n * AFTER update(); the last write wins. That is how lip-sync beats an\n * expression that opens the mouth.\n *\n * The clips and expressions advance by `clamp(now − prev, 0, MAX_DT_MS)`,\n * 0 on the first update. A non-finite `nowMs` is a dropped frame: idle and\n * both players write nothing and do not advance (physics and chains re-emit\n * their outputs unchanged), and the next finite frame measures from the\n * last finite one, as IdleMotion does.\n */\n update(nowMs: number): void {\n this.frame.clear();\n this.idle.update(nowMs);\n if (Number.isFinite(nowMs)) {\n const dtS =\n this.prevNowMs === undefined\n ? 0\n : clamp(nowMs - this.prevNowMs, 0, MAX_DT_MS) / 1000;\n this.prevNowMs = nowMs;\n this.clips.apply(dtS, this.frame, this.rest);\n this.expressions.apply(dtS, this.frame, this.rest);\n }\n this.frame.forEach(this.flush);\n this.physics.update(nowMs);\n this.chains.update(nowMs);\n }\n}\n","import {\n DEFAULT_FADE_SECONDS,\n IDLE_MOTION_GROUP,\n type IkiMotionClip,\n type IkiMotionCurve,\n type IkiParameter,\n} from \"@ikijs/format\";\nimport { clamp, lerp, smoothstep } from \"./math\";\n\n// --- Small pure helpers ------------------------------------------------------\n\n/**\n * The slope at each key of a `\"smooth\"` curve, by Steffen's monotone cubic\n * (M. Steffen, \"A simple method for monotonic interpolation in one\n * dimension\", 1990): each inner key's slope is capped by the slopes of the two\n * lines either side, so no segment overshoots its keys, and it is zero where\n * those lines change direction or one is flat. Chosen over Fritsch–Carlson\n * because it is one closed form per key, with no second pass to rescale. The\n * first and last key get slope zero (not Steffen's own end rule) so the curve\n * meets the holds before and after it without a kink. Exported for the tests;\n * not part of the package entry.\n */\nexport function curveSlopes(keys: IkiMotionCurve[\"keys\"]): number[] {\n const slopes = keys.map(() => 0);\n for (let i = 1; i < keys.length - 1; i++) {\n const [t0, v0] = keys[i - 1];\n const [t1, v1] = keys[i];\n const [t2, v2] = keys[i + 1];\n const h0 = t1 - t0;\n const h1 = t2 - t1;\n const s0 = (v1 - v0) / h0;\n const s1 = (v2 - v1) / h1;\n // The slope at key i of the parabola through the three keys.\n const p = (s0 * h1 + s1 * h0) / (h0 + h1);\n slopes[i] =\n (Math.sign(s0) + Math.sign(s1)) *\n Math.min(Math.abs(s0), Math.abs(s1), Math.abs(p) / 2);\n }\n return slopes;\n}\n\n/**\n * A curve's value at `t` seconds, holding the first key's value before it and\n * the last key's value after it. Between two keys it is a straight line, or,\n * given the keys' `slopes` ({@link curveSlopes}), the cubic Hermite through\n * them. Exported for the tests; not part of the package entry.\n */\nexport function sampleCurve(\n keys: IkiMotionCurve[\"keys\"],\n t: number,\n slopes?: readonly number[],\n): number {\n const first = keys[0];\n if (t <= first[0]) return first[1];\n const last = keys[keys.length - 1];\n if (t >= last[0]) return last[1];\n // first[0] < t < last[0], so the scan stops on a key after `t`; `<=` puts a\n // `t` exactly on a key at the start of its segment, where both forms are\n // exact.\n let i = 1;\n while (keys[i][0] <= t) i++;\n const [t0, v0] = keys[i - 1];\n const [t1, v1] = keys[i];\n const h = t1 - t0;\n const u = (t - t0) / h;\n if (!slopes) return lerp(v0, v1, u);\n // The Hermite basis regrouped: the eased move between the two values, plus\n // each key's slope term, which vanishes at both ends of the segment.\n return (\n lerp(v0, v1, smoothstep(u)) +\n h * u * (1 - u) * (slopes[i - 1] * (1 - u) - slopes[i] * u)\n );\n}\n\n/**\n * The clip's fade-in and fade-out weights at `t` seconds into it, each easing\n * along {@link smoothstep} and clamped to `[0, 1]`. A zero fade gives 1 — no\n * fade on that side. An absent one lasts `DEFAULT_FADE_SECONDS`, capped at\n * half the clip's duration: two absent fades never overlap, so a short clip\n * still reaches full weight, and, like a declared fade, each fits inside the\n * clip: the fade-out never starts before t = 0, so a replacing clip's first\n * frame (wOut = 1) is still the old pose. Exported for the tests; not part of\n * the package entry.\n */\nexport function fadeWeights(\n clip: IkiMotionClip,\n t: number,\n): { wIn: number; wOut: number } {\n const fallback = Math.min(DEFAULT_FADE_SECONDS, clip.duration / 2);\n const fadeIn = clip.fadeIn ?? fallback;\n const fadeOut = clip.fadeOut ?? fallback;\n return {\n wIn: fadeIn > 0 ? smoothstep(t / fadeIn) : 1,\n wOut: fadeOut > 0 ? smoothstep((clip.duration - t) / fadeOut) : 1,\n };\n}\n\n// --- Clip player -------------------------------------------------------------\n\n/** The one-shot slot: one playing clip, no queue. */\ninterface Slot {\n clip: IkiMotionClip;\n /** Seconds since the clip started. */\n t: number;\n /** The pose the clip fades in from: the replaced clip's last output. */\n from: Map<string, number>;\n /**\n * What the slot wrote on its last apply, clamped to each parameter's range;\n * `from` until the first apply, since that is still what is on screen.\n */\n last: Map<string, number>;\n}\n\n/**\n * Plays a model's motion clips into a per-update frame map. Internal to\n * {@link IkiMotion}, which owns the frame: the base rule below only holds\n * inside that frame, so this is not exported from the package entry.\n *\n * Two layers, written in this order on every {@link apply}:\n * - the Idle loop, when the model declares {@link IDLE_MOTION_GROUP}: its clips\n * back-to-back at full weight, wrapping from the last to the first;\n * - the one-shot slot over it, started by {@link play}. A clip blends between\n * the frame's base value and its own curves with its fade-in and fade-out;\n * a new `play` replaces the running clip and fades in from its last output.\n *\n * IkiMotion steps it once per update; this class has no timers, rAF, DOM, or\n * Date.now.\n */\nexport class ClipPlayer {\n /** True when the model declares the {@link IDLE_MOTION_GROUP} group. */\n readonly hasIdleLoop: boolean;\n /** Every curve parameter across all groups, deduplicated, insertion-ordered. */\n readonly parameterIds: readonly string[];\n private readonly motions: Record<string, IkiMotionClip[]>;\n private readonly params: Map<string, IkiParameter>;\n /** Key slopes of every `\"smooth\"` curve; a linear curve has no entry. */\n private readonly slopes: Map<IkiMotionCurve, readonly number[]>;\n\n private readonly idleClips: readonly IkiMotionClip[];\n private readonly idleLength: number;\n private idleIndex = 0;\n /** Seconds into the current Idle clip. */\n private idleTime = 0;\n\n private slot: Slot | undefined = undefined;\n\n constructor(\n motions: Record<string, IkiMotionClip[]> | undefined,\n parameters: IkiParameter[],\n ) {\n this.motions = motions ?? {};\n this.params = new Map(parameters.map((p) => [p.id, p]));\n // Own-property checks throughout: a group named after an Object.prototype\n // member (\"toString\") is not declared.\n this.hasIdleLoop = Object.hasOwn(this.motions, IDLE_MOTION_GROUP);\n this.idleClips = this.hasIdleLoop ? this.motions[IDLE_MOTION_GROUP] : [];\n this.idleLength = this.idleClips.reduce((sum, c) => sum + c.duration, 0);\n const curves = Object.values(this.motions).flatMap((clips) =>\n clips.flatMap((c) => c.curves),\n );\n this.parameterIds = [...new Set(curves.map((curve) => curve.parameter))];\n // Worked out once here, so a frame only evaluates the cubic.\n this.slopes = new Map(\n curves\n .filter((curve) => curve.interpolation !== \"linear\")\n .map((curve) => [curve, curveSlopes(curve.keys)]),\n );\n }\n\n /**\n * Start clip `index` of `group` at once, replacing any running one-shot.\n * Returns false, and changes nothing, for a group the model does not declare\n * or an index that is not an integer in range. Any group plays one-shot,\n * Idle included.\n */\n play(group: string, index: number): boolean {\n if (!Object.hasOwn(this.motions, group)) return false;\n const clips = this.motions[group];\n if (!Number.isInteger(index) || index < 0 || index >= clips.length) {\n return false;\n }\n // The new clip fades in from what the old one last put on screen. Until\n // the new one's first apply the screen still shows `from`, so that is its\n // last output too: a second play before the next apply inherits the same\n // pose instead of dropping the ids the first one never got to write.\n const from = this.slot?.last ?? new Map<string, number>();\n this.slot = { clip: clips[index], t: 0, from, last: from };\n return true;\n }\n\n /**\n * Advance `dtS` seconds and write into `frame`: the Idle loop layer, then\n * the one-shot slot over it.\n *\n * `frame` holds what earlier stages wrote this update. An id's base is its\n * frame value, else `rest(id)` — the parameter's resting value,\n * `clamp(default, min, max)`. The base is never the store's current value,\n * so a clip cannot accumulate across frames.\n */\n apply(\n dtS: number,\n frame: Map<string, number>,\n rest: (id: string) => number,\n ): void {\n if (this.hasIdleLoop) this.applyIdle(dtS, frame);\n if (this.slot) this.applySlot(this.slot, dtS, frame, rest);\n }\n\n /**\n * The Idle clips play as one continuous loop, so their fades are ignored:\n * fading each clip at its seams would dip the pose toward rest on every\n * clip boundary.\n */\n private applyIdle(dtS: number, frame: Map<string, number>): void {\n const clips = this.idleClips;\n let clip = clips[this.idleIndex];\n this.idleTime += dtS;\n if (this.idleTime >= clip.duration) {\n // A frame can cross many clips shorter than a frame. Whole passes of the\n // group land back at this same clip, so dropping them first leaves at\n // most one pass to walk, whatever dt is. The cap on the walk guards\n // float rounding: summing the durations one by one need not match the\n // precomputed total exactly.\n this.idleTime %= this.idleLength;\n for (\n let step = 0;\n step < clips.length && this.idleTime >= clip.duration;\n step++\n ) {\n this.idleTime -= clip.duration;\n this.idleIndex = (this.idleIndex + 1) % clips.length;\n clip = clips[this.idleIndex];\n }\n }\n for (const curve of clip.curves) {\n frame.set(curve.parameter, this.sample(curve, this.idleTime));\n }\n }\n\n private applySlot(\n slot: Slot,\n dtS: number,\n frame: Map<string, number>,\n rest: (id: string) => number,\n ): void {\n const { clip, from } = slot;\n // What earlier stages (and the Idle layer) wrote this update, else rest.\n const base = (id: string): number => frame.get(id) ?? rest(id);\n slot.t += dtS;\n\n if (slot.t >= clip.duration) {\n // One last write at base for every id the slot drove, then the slot is\n // gone: a parameter nothing else writes settles at its default instead\n // of holding the clip's final value.\n const ids = new Set(clip.curves.map((curve) => curve.parameter));\n for (const id of from.keys()) ids.add(id);\n for (const id of ids) frame.set(id, base(id));\n this.slot = undefined;\n return;\n }\n\n // Fade-in moves from the old pose to the new sample; fade-out pulls the\n // result to base. With an empty `from` this is lerp(base, s, wIn * wOut).\n const { wIn, wOut } = fadeWeights(clip, slot.t);\n const last = new Map<string, number>();\n const write = (id: string, sample: number | undefined): void => {\n const b = base(id);\n const f = from.get(id) ?? b;\n const value = lerp(b, lerp(f, sample ?? b, wIn), wOut);\n frame.set(id, value);\n last.set(id, this.displayed(id, value));\n };\n for (const curve of clip.curves) {\n write(curve.parameter, this.sample(curve, slot.t));\n }\n for (const id of from.keys()) if (!last.has(id)) write(id, undefined);\n slot.last = last;\n\n // From here on every value equals the no-`from` value, to rounding, and an\n // id only `from` held was just written at base, to rounding: drop them so\n // they are not written again.\n if (wIn >= 1) from.clear();\n }\n\n /** The curve at `t`, smooth unless it is marked `\"linear\"`. */\n private sample(curve: IkiMotionCurve, t: number): number {\n return sampleCurve(curve.keys, t, this.slopes.get(curve));\n }\n\n /**\n * The clip stage's output for an id, clamped to the parameter's range as\n * the store clamps every write. A replacing clip fades in from this, not\n * the raw value — a curve past the max would otherwise sit still on screen\n * until the fade got back inside the range.\n */\n private displayed(id: string, value: number): number {\n const param = this.params.get(id);\n return param ? clamp(value, param.min, param.max) : value;\n }\n}\n","import {\n DEFAULT_FADE_SECONDS,\n type IkiExpression,\n type IkiExpressionParameter,\n type IkiParameter,\n} from \"@ikijs/format\";\nimport { clamp, lerp, smoothstep } from \"./math\";\n\n/**\n * A parameter's value as a line in its base: `scale · base + offset`. Every\n * blend is one (add c is 1·base + c, multiply c is c·base, overwrite c is\n * 0·base + c) and so is leaving a parameter alone (1·base); a lerp between two\n * lines is a line too. So whatever mix of expressions is on screen, however\n * many were cut off mid-fade, is one line per parameter, and it still follows\n * the live base: a multiply on EyeOpen keeps the blink.\n */\ninterface Line {\n scale: number;\n offset: number;\n}\n\n/** The line of a parameter an expression leaves alone: the base itself. */\nconst BASE: Line = { scale: 1, offset: 0 };\n\nfunction lineOf({ value, blend = \"add\" }: IkiExpressionParameter): Line {\n switch (blend) {\n case \"add\":\n return { scale: 1, offset: value };\n case \"multiply\":\n return { scale: value, offset: 0 };\n case \"overwrite\":\n return { scale: 0, offset: value };\n }\n}\n\n/** The line's value over `base`. */\nfunction at({ scale, offset }: Line, base: number): number {\n return scale * base + offset;\n}\n\n/**\n * {@link lerp}, but exactly `b` at `t = 1` (lerp is exact only at 0): a\n * finished fade lands on its target, and an id it lets go of on base itself.\n */\nfunction mix(a: number, b: number, t: number): number {\n return t === 1 ? b : lerp(a, b, t);\n}\n\n/** What the player can fade to: an expression, or the base itself. */\ninterface Pose {\n /** Undefined for {@link RELEASE}. */\n expression: IkiExpression | undefined;\n /** The parameters it drives, by id. */\n lines: ReadonlyMap<string, Line>;\n}\n\n/** The pose a stop fades to: it drives nothing, so every id goes to base. */\nconst RELEASE: Pose = { expression: undefined, lines: new Map() };\n\n/**\n * The fade in progress: toward `pose`, from the pose on screen when it began.\n */\ninterface Fade {\n pose: Pose;\n /** How long it lasts, in seconds. */\n seconds: number;\n /** Seconds since it began. */\n elapsed: number;\n}\n\n/**\n * The fade's weight, eased along {@link smoothstep} from 0 to 1 over its\n * seconds; at or past its end exactly 1. A zero fade is at 1 the moment it\n * begins, with no division by zero: an expression with a zero `fadeIn` is\n * fully on as soon as it is played, so a stop before the next apply fades it\n * out from full.\n */\nfunction weight({ seconds, elapsed }: Fade): number {\n return elapsed >= seconds ? 1 : smoothstep(elapsed / seconds);\n}\n\n/** An id the player writes on every apply. */\ninterface Held {\n id: string;\n /**\n * Its base on the last apply, where a fold matches the screen (see\n * {@link ExpressionPlayer.begin}); NaN before the first apply.\n */\n base: number;\n}\n\n/**\n * Plays a model's expressions into a per-update frame map. Internal to\n * {@link IkiMotion}, which owns the frame: the base rule below only holds\n * inside that frame, so this is not exported from the package entry.\n *\n * One fade runs at a time, from the pose on screen when it began to its\n * target. {@link play} fades an expression in over its `fadeIn`; {@link stop}\n * fades back to base over the playing expression's `fadeOut`. Either one\n * interrupting a fade starts from where that fade got to, as a replacing\n * motion clip does, so the screen never jumps or dips toward base; unlike a\n * clip's, that starting pose keeps following the live base (see {@link Line}),\n * save a part of it the screen showed held at a range limit, which stays there.\n * Each target is taken over the base, never over what is on screen, so an\n * `add` never stacks on itself however often it is replayed.\n *\n * IkiMotion steps it once per update; this class has no timers, rAF, DOM, or\n * Date.now.\n */\nexport class ExpressionPlayer {\n /** Every expression parameter, deduplicated, insertion-ordered. */\n readonly parameterIds: readonly string[];\n private readonly poses: Map<string, Pose & { expression: IkiExpression }>;\n private readonly params: Map<string, IkiParameter>;\n\n /** Undefined while nothing is held. */\n private fade: Fade | undefined = undefined;\n /**\n * The pose on screen when {@link fade} began, a line per id; empty once the\n * fade has finished, since the screen is then its target alone.\n */\n private from = new Map<string, Line>();\n /** Every id `from` or the fade drives: what each apply writes. */\n private held: Held[] = [];\n\n constructor(\n expressions: IkiExpression[] | undefined,\n parameters: IkiParameter[],\n ) {\n const list = expressions ?? [];\n this.params = new Map(parameters.map((p) => [p.id, p]));\n this.poses = new Map(\n list.map((expression) => [\n expression.id,\n {\n expression,\n lines: new Map(\n expression.parameters.map((p) => [p.parameter, lineOf(p)]),\n ),\n },\n ]),\n );\n this.parameterIds = [\n ...new Set(list.flatMap((e) => e.parameters.map((p) => p.parameter))),\n ];\n }\n\n /**\n * Fade expression `id` in over its `fadeIn`, from what is on screen: the\n * base, or the output of the expression it replaces, or of a stop still\n * fading out. Returns false, and changes nothing, for an expression id the\n * model does not declare; playing the expression already fading in or held\n * changes nothing and returns true.\n */\n play(id: string): boolean {\n const pose = this.poses.get(id);\n if (!pose) return false;\n if (this.fade?.pose === pose) return true;\n this.begin(pose, pose.expression.fadeIn ?? DEFAULT_FADE_SECONDS);\n return true;\n }\n\n /**\n * Fade back to base over the playing expression's `fadeOut`, from what is\n * on screen. Does nothing when nothing is playing or a stop is already\n * fading out.\n */\n stop(): void {\n const playing = this.fade?.pose.expression;\n if (!playing) return;\n this.begin(RELEASE, playing.fadeOut ?? DEFAULT_FADE_SECONDS);\n }\n\n /**\n * Freeze what is on screen into {@link from}, at the weight the current\n * fade has reached, and start a fade from it toward `pose`. Folding keeps\n * this to one `from` and one fade however fast the plays come.\n *\n * {@link apply} clamps each end before it mixes, so each end folds in as\n * the screen showed it at the last apply's base ({@link pinned}): the new\n * fade starts on what was on screen, an end held at a range limit stays\n * there as the base moves, and the rest still follow the live base. Should\n * the base move so far that the old pose would have left the limit, the\n * start holds it instead: a little off, but continuous, and it fades out.\n */\n private begin(pose: Pose, seconds: number): void {\n if (this.fade) {\n const { lines } = this.fade.pose;\n const w = weight(this.fade);\n const from = new Map<string, Line>();\n for (const { id, base } of this.held) {\n const a = this.pinned(id, this.from.get(id) ?? BASE, base);\n const b = this.pinned(id, lines.get(id) ?? BASE, base);\n from.set(id, {\n scale: mix(a.scale, b.scale, w),\n offset: mix(a.offset, b.offset, w),\n });\n }\n this.from = from;\n }\n this.fade = { pose, seconds, elapsed: 0 };\n this.held = [...new Set([...this.from.keys(), ...pose.lines.keys()])].map(\n (id) => ({ id, base: NaN }),\n );\n }\n\n /**\n * Advance `dtS` seconds and write every held id into `frame`: the pose on\n * screen when the fade began, lerped toward the fade's target by its\n * weight, each end clamped to the parameter's range. An id the target does\n * not drive goes to base.\n *\n * `frame` holds what earlier stages wrote this update. A parameter id's base\n * is its frame value, else `rest(id)` — the parameter's resting value,\n * `clamp(default, min, max)`. The base is never the store's current value,\n * so an `add` cannot accumulate across frames.\n */\n apply(\n dtS: number,\n frame: Map<string, number>,\n rest: (id: string) => number,\n ): void {\n // IkiMotion calls this every frame for every model; most hold nothing.\n const fade = this.fade;\n if (!fade) return;\n fade.elapsed += dtS;\n const w = weight(fade);\n const { lines } = fade.pose;\n for (const held of this.held) {\n const { id } = held;\n const base = frame.get(id) ?? rest(id);\n held.base = base;\n const start = this.displayed(id, at(this.from.get(id) ?? BASE, base));\n const end = this.displayed(id, at(lines.get(id) ?? BASE, base));\n frame.set(id, mix(start, end, w));\n }\n if (w < 1) return;\n // The fade is done and the screen is its target alone. An id only `from`\n // drove was just written at base, exactly; dropping it now makes that its\n // last write, so a parameter nothing else writes rests at its default\n // instead of being held. A finished stop drives nothing, so it goes too.\n if (!fade.pose.expression) {\n this.fade = undefined;\n this.from.clear();\n this.held = [];\n } else if (this.from.size > 0) {\n this.from.clear();\n // Kept entries carry their last base into the next fold.\n this.held = this.held.filter(({ id }) => lines.has(id));\n }\n }\n\n /**\n * A value as the screen shows it: clamped to the parameter's range, as the\n * store clamps every write; an id the model does not declare as is. A fade\n * mixes these, so it leaves a value held past the max from the max at once\n * instead of sitting there until the mix gets back inside the range.\n */\n private displayed(id: string, value: number): number {\n const param = this.params.get(id);\n return param ? clamp(value, param.min, param.max) : value;\n }\n\n /**\n * `line`, or, where its value at `base` is past the parameter's range, the\n * constant line at the limit it crossed: the line as the screen shows it\n * there. An id the model does not declare pins nothing, and nor does a NaN\n * base (no apply yet), which compares false both ways.\n */\n private pinned(id: string, line: Line, base: number): Line {\n const param = this.params.get(id);\n if (!param) return line;\n const value = at(line, base);\n if (value > param.max) return { scale: 0, offset: param.max };\n if (value < param.min) return { scale: 0, offset: param.min };\n return line;\n }\n}\n","import {\n type IkiDeformer,\n type IkiMesh,\n type IkiModel,\n type IkiParameter,\n type IkiPart,\n type IkiWarpDeformer,\n StandardParameter as P,\n} from \"@ikijs/format\";\nimport type { Affine } from \"./affine\";\nimport { resolveDeformers } from \"./deform\";\nimport { type LandedPart, landPart, landedPart, staticDeformers } from \"./land\";\nimport { ParameterStore } from \"./parameter-store\";\nimport { deformWarpGrid } from \"./warp-grid\";\n\n/** A parameter setting to check the rig at; every other parameter rests at its default. */\nexport interface FoldPose {\n /** Its sorted `id=value` pairs joined by one space; `rest` when empty. */\n name: string;\n values: Record<string, number>;\n}\n\n/** Where and when a target comes nearest to folding over one class of poses. */\nexport interface FoldHit {\n /** Doubled signed area at the pose over the same at rest. */\n ratio: number;\n /** The warp grid's cell, or the part mesh's triangle (its index into `mesh.indices` / 3). */\n where: { col: number; row: number } | { triangle: number };\n pose: FoldPose;\n /** Where it sits at rest, model space, through the static matrix chain. */\n rest: { x: number; y: number };\n}\n\nexport interface FoldTarget {\n target: { kind: \"deformer\" | \"part\"; id: string };\n /** Read off `worst` alone; `ok` when it is absent. */\n kind: \"flip\" | \"collapse\" | \"ok\";\n /** Least ratio over the poses `expected` rejects (every pose without it). */\n worst?: FoldHit;\n /** Least ratio over the poses `expected` accepts. */\n expected?: FoldHit;\n}\n\nexport interface FoldOptions {\n /** The poses to check; `foldPoses(model)` when absent. */\n poses?: FoldPose[];\n /**\n * Whether `target` closes by design at `pose` (a mouth shut), which keeps a\n * fold there out of `worst`. `value(id)` is the parameter's effective value\n * at the pose: its override, else the clamped default — a pose carries only\n * overrides, so a closure at a default shows only through `value`.\n */\n expected?: (\n target: FoldTarget[\"target\"],\n pose: FoldPose,\n value: (id: string) => number,\n ) => boolean;\n}\n\nexport interface FoldReport {\n /** How many poses were checked. */\n poses: number;\n thresholds: { flip: 0; collapse: 0.1 };\n /** One per warp deformer, then one per mesh part, each in model order. */\n targets: FoldTarget[];\n /** The targets that are not `ok`, worst first. */\n offenders: FoldTarget[];\n}\n\nconst FLIP = 0;\nconst COLLAPSE = 0.1;\n\nconst ANGLES = [\n P.AngleX,\n P.AngleY,\n P.AngleZ,\n P.BodyAngleX,\n P.BodyAngleY,\n P.BodyAngleZ,\n];\n\n/** Crossed with every angle corner, each group's parameters at min then at max together. */\nconst CROSSES = [\n [P.EyeOpenLeft],\n [P.EyeOpenRight],\n [P.MouthOpen],\n [P.ArmLeft, P.ArmRight],\n [P.ElbowLeft, P.ElbowRight],\n];\n\n/**\n * The poses `checkFolds` checks by default: `rest`; every movable parameter\n * alone at its min and at its max; and, on a model declaring any head or body\n * angle, every min/max corner of those angles alone, then crossed with each\n * eye on its own, the mouth, the arms and the elbows (the last two paired)\n * shut/open — 2⁶ + 2⁶ · 2⁵ = 2112 corner poses at most — where moves no single extreme\n * shows stack up. Deduplicated by `name`.\n */\nexport function foldPoses(model: IkiModel): FoldPose[] {\n const byId = new Map(\n model.parameters.filter((p) => p.min !== p.max).map((p) => [p.id, p]),\n );\n const declared = (ids: string[]) => ids.flatMap((id) => byId.get(id) ?? []);\n\n const poses: FoldPose[] = [];\n const names = new Set<string>();\n const add = (values: Record<string, number>) => {\n const name = poseName(values);\n if (names.has(name)) return;\n names.add(name);\n poses.push({ name, values });\n };\n\n add({});\n for (const p of byId.values()) {\n add({ [p.id]: p.min });\n add({ [p.id]: p.max });\n }\n\n const angles = declared(ANGLES);\n if (angles.length === 0) return poses;\n const expand = (\n corners: Record<string, number>[],\n groups: IkiParameter[][],\n ) => {\n for (const group of groups) {\n corners = corners.flatMap((values) =>\n ([\"min\", \"max\"] as const).map((end) => {\n const next = { ...values };\n for (const p of group) next[p.id] = p[end];\n return next;\n }),\n );\n }\n return corners;\n };\n // The angle corners alone come first: the other parameters rest at their\n // defaults there, which no min/max cross reaches.\n const angleCorners = expand(\n [{}],\n angles.map((p) => [p]),\n );\n for (const values of angleCorners) add(values);\n const crosses = CROSSES.map(declared).filter((g) => g.length > 0);\n for (const values of expand(angleCorners, crosses)) add(values);\n return poses;\n}\n\nfunction poseName(values: Record<string, number>): string {\n const ids = Object.keys(values).sort();\n if (ids.length === 0) return \"rest\";\n return ids.map((id) => `${id}=${values[id]}`).join(\" \");\n}\n\n/**\n * Doubled signed area of each cell's four corner triangles — the corner, then\n * its two neighbours counter-clockwise (y up), as the auto-rig's body fold\n * refusal takes them — at index `cell * 4 + k`. Positive on a rest lattice.\n */\nfunction cornerAreas(\n points: ArrayLike<number>,\n cols: number,\n rows: number,\n): Float64Array {\n const stride = cols + 1;\n const out = new Float64Array(cols * rows * 4);\n for (let r = 0; r < rows; r++) {\n for (let c = 0; c < cols; c++) {\n const tl = r * stride + c;\n const [tr, bl, br] = [tl + 1, tl + stride, tl + stride + 1];\n const i = (r * cols + c) * 4;\n out[i] = doubledArea(points, bl, br, tl);\n out[i + 1] = doubledArea(points, br, tr, bl);\n out[i + 2] = doubledArea(points, tr, tl, br);\n out[i + 3] = doubledArea(points, tl, bl, tr);\n }\n }\n return out;\n}\n\nfunction doubledArea(\n points: ArrayLike<number>,\n p: number,\n q: number,\n s: number,\n): number {\n const ax = points[q * 2] - points[p * 2];\n const ay = points[q * 2 + 1] - points[p * 2 + 1];\n const bx = points[s * 2] - points[p * 2];\n const by = points[s * 2 + 1] - points[p * 2 + 1];\n return ax * by - ay * bx;\n}\n\n/** Doubled signed area of each of a mesh's triangles, at its triangle index. */\nfunction triangleAreas(\n points: ArrayLike<number>,\n indices: number[],\n): Float64Array {\n const out = new Float64Array(indices.length / 3);\n for (let t = 0; t < out.length; t++) {\n const i = t * 3;\n out[t] = doubledArea(points, indices[i], indices[i + 1], indices[i + 2]);\n }\n return out;\n}\n\n/** A target's least ratio so far over one class of poses. */\ninterface Least {\n ratio: number;\n /** Its index into the target's areas: `cell * 4 + corner`, or the triangle. */\n at: number;\n pose: FoldPose;\n}\n\n/** What a target keeps across the poses. */\ninterface Sweep {\n target: FoldTarget[\"target\"];\n restAreas: Float64Array;\n /** Rest areas below this have no ratio. */\n tiny: number;\n worst?: Least;\n expected?: Least;\n}\n\ninterface GridSweep extends Sweep {\n deformer: IkiWarpDeformer;\n}\n\ninterface PartSweep extends Sweep, LandedPart {\n indices: number[];\n}\n\n/**\n * Merges one pose's `areas` into `sweep`: each ratio to its rest area goes to\n * the class `expected` puts the pose in, which keeps its least.\n */\nfunction keepLeast(\n sweep: Sweep,\n areas: Float64Array,\n pose: FoldPose,\n expected: (target: FoldTarget[\"target\"]) => boolean,\n): void {\n const slot = expected(sweep.target) ? \"expected\" : \"worst\";\n for (let i = 0; i < areas.length; i++) {\n const rest = sweep.restAreas[i];\n if (Math.abs(rest) < sweep.tiny) continue;\n const ratio = areas[i] / rest;\n if (ratio < (sweep[slot]?.ratio ?? Infinity)) {\n sweep[slot] = { ratio, at: i, pose };\n }\n }\n}\n\n/** A mesh part's sweep: its landing, with the triangles' rest areas measured on its baseline. */\nfunction partSweep(\n part: IkiPart,\n mesh: IkiMesh,\n deformers: IkiDeformer[],\n worlds: Map<string, Affine>,\n store: ParameterStore,\n): PartSweep {\n const landing = landedPart(part, mesh.vertices, deformers, worlds, store);\n return {\n ...landing,\n target: { kind: \"part\", id: part.id },\n restAreas: triangleAreas(landing.restPoints, mesh.indices),\n tiny: 1e-9 * part.width * part.height,\n indices: mesh.indices,\n };\n}\n\n/**\n * Checks every warp deformer's grid cells and every mesh part's triangles for\n * folds over `options.poses` (`foldPoses(model)` by default) and reports, per\n * target, the least ratio of a triangle's doubled signed area at a pose to\n * the same at rest: `<= 0` a flip, `< 0.1` a collapse. Cells are measured on\n * the deformer's LOCAL grid, so a parent matrix's scale, which multiplies\n * every area alike, never reads as a fold. A part's triangles land as\n * drawPart lands them — its keyforms, its live transform, then its warp's\n * resolved grid or its matrix deformer's world — against its authored mesh on\n * the static matrix chain: a static scale or reflection cancels, a bound one\n * counts, and a vertex its warp grid pins to the edge shows already at\n * `rest` (a triangle wholly past the edge flattens, one across it thins).\n * Report-only: nothing is refused.\n */\nexport function checkFolds(\n model: IkiModel,\n options: FoldOptions = {},\n): FoldReport {\n const poses = options.poses ?? foldPoses(model);\n const deformers = model.deformers ?? [];\n const restStore = new ParameterStore(model.parameters);\n const { worlds } = resolveDeformers(staticDeformers(model), restStore);\n\n const gridSweeps: GridSweep[] = [];\n for (const d of deformers) {\n if (d.kind !== \"warp\") continue;\n const { cols, rows, points } = d.grid;\n // Row 0's x and column 0's y bound the lattice (the validator's own read).\n const width = points[cols * 2] - points[0];\n const height = points[1] - points[rows * (cols + 1) * 2 + 1];\n gridSweeps.push({\n deformer: d,\n target: { kind: \"deformer\", id: d.id },\n restAreas: cornerAreas(points, cols, rows),\n // The validator tolerates 1e-6 of jitter, which can zero a corner's area.\n tiny: 1e-9 * width * height,\n });\n }\n const partSweeps = model.parts.flatMap((part) =>\n part.mesh ? [partSweep(part, part.mesh, deformers, worlds, restStore)] : [],\n );\n\n for (const pose of poses) {\n const store = new ParameterStore(model.parameters);\n for (const [id, v] of Object.entries(pose.values)) store.set(id, v);\n const value = (id: string) => store.get(id);\n const expected = (target: FoldTarget[\"target\"]) =>\n options.expected?.(target, pose, value) === true;\n for (const sweep of gridSweeps) {\n const { cols, rows } = sweep.deformer.grid;\n const areas = cornerAreas(\n deformWarpGrid(sweep.deformer, store),\n cols,\n rows,\n );\n keepLeast(sweep, areas, pose, expected);\n }\n const resolved = resolveDeformers(deformers, store);\n for (const sweep of partSweeps) {\n const areas = triangleAreas(\n landPart(sweep, store, resolved),\n sweep.indices,\n );\n keepLeast(sweep, areas, pose, expected);\n }\n }\n\n const targets = [\n ...gridSweeps.map((sweep) => {\n const { parent } = sweep.deformer;\n const world = parent === undefined ? undefined : worlds.get(parent);\n return foldTarget(sweep, (least) =>\n cellHit(sweep.deformer, least, world),\n );\n }),\n ...partSweeps.map((sweep) =>\n foldTarget(sweep, (least) => triangleHit(sweep, least)),\n ),\n ];\n const offenders = targets\n .filter((t) => t.kind !== \"ok\")\n .sort((a, b) => a.worst!.ratio - b.worst!.ratio);\n return {\n poses: poses.length,\n thresholds: { flip: FLIP, collapse: COLLAPSE },\n targets,\n offenders,\n };\n}\n\n/** A sweep's two minima, each located by `hit`, and the kind they make. */\nfunction foldTarget(sweep: Sweep, hit: (least: Least) => FoldHit): FoldTarget {\n const worst = sweep.worst && hit(sweep.worst);\n const expected = sweep.expected && hit(sweep.expected);\n return { target: sweep.target, kind: classify(worst), worst, expected };\n}\n\n/** `least` located: its cell and that cell's rest centre through `parent`. */\nfunction cellHit(\n d: IkiWarpDeformer,\n least: Least,\n parent: Affine | undefined,\n): FoldHit {\n const { cols, points } = d.grid;\n const cell = Math.floor(least.at / 4);\n const col = cell % cols;\n const row = Math.floor(cell / cols);\n const stride = cols + 1;\n let x = 0;\n let y = 0;\n for (const i of [\n row * stride + col,\n row * stride + col + 1,\n (row + 1) * stride + col,\n (row + 1) * stride + col + 1,\n ]) {\n x += points[i * 2] / 4;\n y += points[i * 2 + 1] / 4;\n }\n const rest = parent\n ? {\n x: parent[0] * x + parent[2] * y + parent[4],\n y: parent[1] * x + parent[3] * y + parent[5],\n }\n : { x, y };\n return { ratio: least.ratio, where: { col, row }, pose: least.pose, rest };\n}\n\n/** `least` located: its triangle and that triangle's centroid on the static chain. */\nfunction triangleHit(sweep: PartSweep, least: Least): FoldHit {\n const { indices, restPoints } = sweep;\n let x = 0;\n let y = 0;\n for (let k = 0; k < 3; k++) {\n const i = indices[least.at * 3 + k];\n x += restPoints[i * 2] / 3;\n y += restPoints[i * 2 + 1] / 3;\n }\n return {\n ratio: least.ratio,\n where: { triangle: least.at },\n pose: least.pose,\n rest: { x, y },\n };\n}\n\nfunction classify(worst: FoldHit | undefined): FoldTarget[\"kind\"] {\n if (worst === undefined) return \"ok\";\n if (worst.ratio <= FLIP) return \"flip\";\n if (worst.ratio < COLLAPSE) return \"collapse\";\n return \"ok\";\n}\n","import type {\n IkiDeformer,\n IkiModel,\n IkiPart,\n IkiWarpDeformer,\n} from \"@ikijs/format\";\nimport { type Affine, multiply, rotate, scale, translate } from \"./affine\";\nimport {\n type ResolvedDeformers,\n type ResolvedTransform,\n evaluateTransform,\n} from \"./deform\";\nimport type { ParameterStore } from \"./parameter-store\";\nimport { applyWarps } from \"./warp\";\nimport { applyWarpToChild, transformGridPoints } from \"./warp-grid\";\n\n/**\n * The model's deformers with every binding and keyform removed: the rig no\n * parameter moves. Its matrix worlds place a rest location, and a part's\n * baseline, in model space.\n */\nexport function staticDeformers(model: IkiModel): IkiDeformer[] {\n return (model.deformers ?? []).map((d) =>\n d.kind === \"warp\"\n ? { ...d, warps: undefined, warp2d: undefined }\n : { ...d, bindings: undefined },\n );\n}\n\n/** A part's placement as `player.ts` drawPart builds it: translate · rotate · scale(size). */\nexport function placement(part: IkiPart, t: ResolvedTransform): Affine {\n return multiply(\n multiply(translate(t.x, t.y), rotate(t.rotation)),\n scale(part.width * t.scaleX, part.height * t.scaleY),\n );\n}\n\n/** A part's points set up to land at any pose, and their baseline. */\nexport interface LandedPart {\n part: IkiPart;\n /** The warp deformer it hangs from, which lands it instead of a matrix. */\n warpDeformer?: IkiWarpDeformer;\n /** The points as the renderer holds them: part-local, float32. */\n vertices: Float32Array;\n /** Per-pose scratch: the points after the part's keyforms, then where they land. */\n local: Float32Array;\n landed: Float32Array;\n /**\n * The baseline's points: `vertices` on the STATIC chain, model space — for\n * folds, the authored mesh. Not the rendered rest pose, which is `landPart`\n * at a resting store.\n */\n restPoints: Float64Array;\n}\n\n/**\n * A part's landing, its baseline set once: `vertices` (its mesh's, or any\n * part-local points) through the part's base transform and the static world\n * it hangs from — its matrix deformer's, or its warp's PARENT's (identity at\n * a root). The grid never enters it, so a vertex the grid pins to its edge is\n * measured, not cancelled.\n */\nexport function landedPart(\n part: IkiPart,\n vertices: number[],\n deformers: IkiDeformer[],\n worlds: Map<string, Affine>,\n store: ParameterStore,\n): LandedPart {\n // Found as drawPart finds it: a part hung from a warp is that warp's child.\n const warpDeformer = deformers.find(\n (d): d is IkiWarpDeformer => d.kind === \"warp\" && d.id === part.deformer,\n );\n const frame = warpDeformer ? warpDeformer.parent : part.deformer;\n const placed = placement(\n part,\n evaluateTransform(part.transform, undefined, store),\n );\n // Float64: a triangle authored degenerate stays exactly so, under folds'\n // `tiny`.\n const restPoints = transformGridPoints(\n vertices,\n frame === undefined ? placed : multiply(worlds.get(frame)!, placed),\n new Float64Array(vertices.length),\n );\n return {\n part,\n warpDeformer,\n vertices: Float32Array.from(vertices),\n local: new Float32Array(vertices.length),\n landed: new Float32Array(vertices.length),\n restPoints,\n };\n}\n\n/**\n * Where `landing`'s part lands at a pose, model space, by drawPart's three\n * branches: a warp child bound to its RAW rest grid and sampled on the\n * resolved one, a matrix child through its deformer's world, a free part by\n * its placement alone. `resolved` is the live rig at `store`'s pose, not the\n * static chain's worlds.\n */\nexport function landPart(\n landing: LandedPart,\n store: ParameterStore,\n { worlds, grids }: ResolvedDeformers,\n): Float32Array {\n const { part, warpDeformer, local, landed } = landing;\n applyWarps(landing.vertices, part.warps, store, local);\n const placed = placement(\n part,\n evaluateTransform(part.transform, part.bindings, store),\n );\n if (warpDeformer) {\n const grid = grids.get(warpDeformer.id)!;\n applyWarpToChild(local, placed, warpDeformer.grid, grid, landed);\n } else if (part.deformer !== undefined) {\n const world = worlds.get(part.deformer)!;\n transformGridPoints(local, multiply(world, placed), landed);\n } else {\n transformGridPoints(local, placed, landed);\n }\n return landed;\n}\n","import {\n type IkiDeformer,\n type IkiModel,\n type IkiParameter,\n type IkiPart,\n type IkiPhysics,\n physicsInputs,\n} from \"@ikijs/format\";\nimport { resolveDeformers } from \"./deform\";\nimport { FIXED_DT_S } from \"./frame-clock\";\nimport { landPart, landedPart, staticDeformers } from \"./land\";\nimport { ParameterStore } from \"./parameter-store\";\nimport {\n type Reading,\n anchorInputs,\n farEnd,\n idleRun,\n stepRun,\n} from \"./physics-runs\";\n\n/** How a driven output moves over one excitation window. */\nexport interface PhysicsResponse {\n /**\n * Its largest displacement from its resting value, as the store holds it\n * (clamped): signed in `step`, which has a direction; its size in `idle`,\n * whose sway goes both ways, so a sign there would carry nothing.\n */\n peak: number;\n /**\n * When it peaks, seconds into the window. Between two near-equal extremes\n * of the idle it may name either.\n */\n at: number;\n /**\n * The largest vertex move of any part, model px, with the output alone\n * (every other parameter resting) at the values the window reached.\n */\n displacementPx: number;\n}\n\n/** One output a physics rig drives: a spring's, or one chain segment's. */\nexport interface PhysicsTarget {\n rig:\n | { kind: \"spring\"; id: string }\n | { kind: \"chain\"; id: string; segment: number };\n /**\n * The spring's inputs, in rig order; for a chain, every parameter that turns\n * its anchor.\n */\n input: string[];\n /** The driven parameter. */\n output: string;\n /** What reads `output`: parts, then deformers, each in model order. */\n drives: { kind: \"part\" | \"deformer\"; id: string }[];\n kind: \"ok\" | \"frozen\" | \"unstable\";\n /** One phrase saying why, naming the window it came from; present when not `ok`. */\n why?: string;\n /**\n * An input stepped from rest to `values` and held: its displacement over\n * every value the run emitted, `final` the output at the window's end.\n */\n step: PhysicsResponse & { values: Record<string, number>; final: number };\n /** Every rig and chain together behind the procedural idle, displaced at every value it emitted. */\n idle: PhysicsResponse;\n}\n\nexport interface PhysicsReport {\n thresholds: { displacementPx: 1; pinnedFrames: 60 };\n /** One per `model.physics` rig, then one per chain segment, each in model order. */\n targets: PhysicsTarget[];\n /** The targets that are not `ok`, unstable first. */\n offenders: PhysicsTarget[];\n}\n\n/** Under 1 model px is sub-pixel in every render the loop looks at (0.51 render px each). */\nconst DISPLACEMENT_PX = 1;\n/** One second outside the range: longer than any transient overshoot clip. */\nconst PINNED_FRAMES = 60;\n/** Slack on the spring's stability limits. */\nconst TOLERANCE = 1e-9;\n/** The corners `createUnitQuad` uploads, which a part without a mesh draws. */\nconst UNIT_QUAD = [-0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5];\n\n/** A run's reading of one output, the window `why` names it by, and how far it moves the parts. */\ninterface Excitation {\n name: string;\n reading: Reading;\n displacementPx: number;\n}\n\n/** A step excitation and the setting it held. */\ninterface StepExcitation extends Excitation {\n values: Record<string, number>;\n}\n\n/**\n * Excites every physics rig through the real drivers (`PhysicsMotion`,\n * `HairChainMotion`, `IdleMotion`) on a synthetic 60 Hz clock, one FIXED_DT_S\n * sub-step per frame, and reports per driven output whether it moves the\n * parts (`ok`), cannot (`frozen`) or runs away (`unstable`).\n *\n * Step: a fresh store and a driver holding only that rig, seeded at rest,\n * then an input set to its far end — the end farther from its clamped\n * default, `max` on a tie — and held for 5 s. A spring steps each input that\n * has a range alone, in its own run. A chain steps each parameter that alone\n * turns its anchor (probed at its max, min and every warp keyform stop) in\n * its own run, at the probe value that turned it most. Either reports the run\n * moving the parts most among the runs that are not unstable. A lag input's\n * step peaks at once at the bound `−scale·weight` (less one sub-step) and its\n * `final` reads rest: the bound is what a one-frame step shows, a gradual\n * turn swings less. Idle: every rig and chain together behind `IdleMotion`\n * (seeded) for 30 s.\n *\n * `displacementPx` is the largest vertex move of any part with the output\n * alone at every distinct value the run emitted, step or idle, against the\n * parts landed at rest. `frozen` when nothing reads the output, no input of a\n * spring has a range, nothing turns a chain's anchor, or the step moves the\n * parts under 1 model px. `unstable`, before frozen, when a\n * spring's one-sub-step map has a spectral radius over 1 or sits on its\n * undamped boundary (springs only: a chain's update is nonlinear), when a\n * driver's finiteness guard fires, or when the raw output stays outside its\n * range for 60 consecutive frames, in any run. Deferred by the user: a chain\n * that grows yet stays finite and inside its range trips none of these and\n * is not flagged. Idle amplitude never flags. Report-only: nothing is refused.\n */\nexport function checkPhysics(model: IkiModel): PhysicsReport {\n const idle = idleRun(model);\n const displace = displacer(model);\n const idleExcitation = (output: IkiParameter): Excitation => {\n const reading = idle.get(output.id)!;\n return {\n name: \"the idle\",\n reading,\n displacementPx: displace(output, reading.values),\n };\n };\n const param = (id: string) => model.parameters.find((p) => p.id === id)!;\n\n const springs = (model.physics ?? []).map((rig) => {\n const inputs = physicsInputs(rig).map((i) => param(i.parameter));\n const ids = inputs.map((p) => p.id);\n const output = param(rig.output.parameter);\n const ranged = inputs.flatMap((input) => {\n const far = farEnd(input);\n return far === undefined ? [] : [{ [input.id]: far }];\n });\n // One unexcited run when nothing has a range, so mostMoving has a run.\n const settings = ranged.length === 0 ? [{}] : ranged;\n const steps = settings.map((values): StepExcitation => {\n const reading = stepRun(model, [rig], [], values).get(output.id)!;\n // A one-input rig has one run, so naming its setting would add nothing.\n const setting =\n inputs.length === 1\n ? []\n : Object.entries(values).map(([id, v]) => `${id}=${v}`);\n return {\n name: [\"the step\", ...setting].join(\" \"),\n reading,\n displacementPx: displace(output, reading.values),\n values,\n };\n });\n const atIdle = idleExcitation(output);\n const clean = steps.filter((s) => !unstableWhy(output, [s]));\n return target(model, {\n rig: { kind: \"spring\", id: rig.id },\n input: ids,\n output,\n step: mostMoving(clean.length > 0 ? clean : steps),\n idle: atIdle,\n unstable: springWhy(rig) ?? unstableWhy(output, [...steps, atIdle]),\n inert:\n ranged.length === 0\n ? `${ids.join(\", \")} ${ids.length === 1 ? \"has\" : \"have\"} no range`\n : undefined,\n });\n });\n\n const chains = (model.physicsChains ?? []).flatMap((chain) => {\n const candidates = anchorInputs(model, chain);\n const settings =\n candidates.length === 0\n ? [{}]\n : candidates.map((c) => ({ [c.parameter]: c.value }));\n const runs = settings.map((values) => ({\n values,\n readings: stepRun(model, [], [chain], values),\n }));\n return chain.segments.map((segment, i) => {\n const output = param(segment.output.parameter);\n const steps = runs.map(({ values, readings }): StepExcitation => {\n const reading = readings.get(output.id)!;\n const setting = Object.entries(values).map(([id, v]) => `${id}=${v}`);\n return {\n name: [\"the step\", ...setting].join(\" \"),\n reading,\n displacementPx: displace(output, reading.values),\n values,\n };\n });\n const atIdle = idleExcitation(output);\n const clean = steps.filter((s) => !unstableWhy(output, [s]));\n return target(model, {\n rig: { kind: \"chain\", id: chain.id, segment: i },\n input: candidates.map((c) => c.parameter),\n output,\n step: mostMoving(clean.length > 0 ? clean : steps),\n idle: atIdle,\n unstable: unstableWhy(output, [...steps, atIdle]),\n inert:\n candidates.length === 0\n ? `nothing turns anchor ${chain.anchorDeformer}`\n : undefined,\n });\n });\n });\n\n const targets = [...springs, ...chains];\n return {\n thresholds: {\n displacementPx: DISPLACEMENT_PX,\n pinnedFrames: PINNED_FRAMES,\n },\n targets,\n offenders: [\n ...targets.filter((t) => t.kind === \"unstable\"),\n ...targets.filter((t) => t.kind === \"frozen\"),\n ],\n };\n}\n\n/**\n * A target from its excitations: `unstable` with its reason, else `frozen`\n * when nothing reads the output, by the input-side reason `inert`, or under\n * 1 px.\n */\nfunction target(\n model: IkiModel,\n t: {\n rig: PhysicsTarget[\"rig\"];\n input: string[];\n output: IkiParameter;\n step: StepExcitation;\n idle: Excitation;\n unstable: string | undefined;\n inert: string | undefined;\n },\n): PhysicsTarget {\n const { step, idle, output } = t;\n const drives = drivesOf(model, output.id);\n // Floored, so a frozen 0.96 px never reads as 1.0.\n const px = Math.floor(step.displacementPx * 10) / 10;\n const still =\n step.displacementPx < DISPLACEMENT_PX\n ? `moves ${px.toFixed(1)} model px over ${step.name}`\n : undefined;\n const frozen = drives.length === 0 ? \"drives nothing\" : (t.inert ?? still);\n const { peak, at, final } = step.reading;\n return {\n rig: t.rig,\n input: t.input,\n output: output.id,\n drives,\n kind: t.unstable ? \"unstable\" : frozen ? \"frozen\" : \"ok\",\n why: t.unstable ?? frozen,\n step: {\n values: step.values,\n peak,\n at,\n final,\n displacementPx: step.displacementPx,\n },\n idle: {\n peak: Math.abs(idle.reading.peak),\n at: idle.reading.at,\n displacementPx: idle.displacementPx,\n },\n };\n}\n\n/** The excitation moving the parts most, ties by `|peak|`, the first on a full tie. */\nfunction mostMoving(steps: StepExcitation[]): StepExcitation {\n return steps.reduce((best, s) => {\n if (s.displacementPx !== best.displacementPx) {\n return s.displacementPx > best.displacementPx ? s : best;\n }\n return Math.abs(s.reading.peak) > Math.abs(best.reading.peak) ? s : best;\n });\n}\n\n/** The parts, then the deformers, that read `output`, each in model order. */\nfunction drivesOf(model: IkiModel, output: string): PhysicsTarget[\"drives\"] {\n const parts = model.parts.filter((p) =>\n [\n ...(p.bindings ?? []).map((b) => b.parameter),\n ...(p.warps ?? []).map((w) => w.parameter),\n ].includes(output),\n );\n const deformers = (model.deformers ?? []).filter((d) =>\n (d.kind === \"warp\"\n ? [\n ...(d.warps ?? []).map((w) => w.parameter),\n d.warp2d?.parameter,\n d.warp2d?.parameterY,\n ]\n : (d.bindings ?? []).map((b) => b.parameter)\n ).includes(output),\n );\n return [\n ...parts.map((p) => ({ kind: \"part\" as const, id: p.id })),\n ...deformers.map((d) => ({ kind: \"deformer\" as const, id: d.id })),\n ];\n}\n\n/**\n * The spectral radius of the map `PhysicsMotion.step` applies to the state\n * (x, v) each FIXED_DT_S sub-step — linear, constant coefficients:\n * `[[1 − h²k/m, h(1 − hc/m)], [−hk/m, 1 − hc/m]]` — by the closed form: a real\n * pair from trace and determinant, a complex pair's modulus `√det`. With it,\n * `k` = h²k/m, the term the undamped boundary reads.\n */\nfunction springStepRadius({ mass, stiffness, damping }: IkiPhysics): {\n radius: number;\n k: number;\n} {\n const k = (FIXED_DT_S * FIXED_DT_S * stiffness) / mass;\n const c = (FIXED_DT_S * damping) / mass;\n const trace = 2 - k - c;\n const det = 1 - c;\n const disc = trace * trace - 4 * det;\n const radius =\n disc >= 0 ? (Math.abs(trace) + Math.sqrt(disc)) / 2 : Math.sqrt(det);\n return { radius, k };\n}\n\n/**\n * Why a spring's constants make it unstable, if they do: a radius over 1, or\n * the undamped boundary `dt²k/m = 4`, where the radius is exactly 1 but the\n * matrix is defective (double eigenvalue −1) and the state grows linearly.\n */\nfunction springWhy(rig: IkiPhysics): string | undefined {\n const { radius, k } = springStepRadius(rig);\n if (radius > 1 + TOLERANCE) {\n // As many decimals as it takes to print the radius over 1.\n let digits = 2;\n while (Number(radius.toFixed(digits)) <= 1) digits++;\n return `spring step map radius ${radius.toFixed(digits)} over 1 at 1/60 s`;\n }\n if (rig.damping === 0 && k >= 4 - TOLERANCE) {\n return `spring on its undamped boundary, dt²k/m ${k.toFixed(2)}`;\n }\n return undefined;\n}\n\n/** Why `output` is unstable over `excitations`, if it is: a guard activation in any, else a pin. */\nfunction unstableWhy(\n output: IkiParameter,\n excitations: Excitation[],\n): string | undefined {\n for (const { name, reading } of excitations) {\n const n = reading.resets;\n if (n === 0) continue;\n return `finiteness guard reset it ${n} time${n === 1 ? \"\" : \"s\"} in ${name}`;\n }\n for (const { name, reading } of excitations) {\n const { frames, end } = reading.pinned;\n if (frames < PINNED_FRAMES) continue;\n return `pinned at ${output.id} ${end} ${output[end]} for ${frames} frames of ${name}`;\n }\n return undefined;\n}\n\n/**\n * The largest vertex move, model px, of any part with an output alone at\n * each of a list of values (every other parameter resting), against every\n * part landed at the resting store through the live deformers resolved at\n * rest — so a binding or keyform away from zero at rest is not motion. Every\n * part lands, so a deformer- or chain-driven part counts by the same path.\n */\nfunction displacer(\n model: IkiModel,\n): (output: IkiParameter, values: number[]) => number {\n const deformers = model.deformers ?? [];\n const store = new ParameterStore(model.parameters);\n // Only `landedPart`'s `restPoints` (folds' baseline) reads the static\n // worlds; this check lands its own baseline below.\n const { worlds } = resolveDeformers(staticDeformers(model), store);\n const landings = model.parts.map((part) =>\n landedPart(\n part,\n part.mesh?.vertices ?? UNIT_QUAD,\n deformers,\n worlds,\n store,\n ),\n );\n const atRest = resolveDeformers(deformers, store);\n // Copied out: landPart returns the landing's shared scratch.\n const baselines = landings.map((l) =>\n Float32Array.from(landPart(l, store, atRest)),\n );\n return (output, values) => {\n let most = 0;\n const affected = affectedParts(model, output.id);\n for (const value of values) {\n store.set(output.id, value);\n const resolved = resolveDeformers(deformers, store);\n landings.forEach((landing, i) => {\n if (!affected.has(landing.part)) return;\n const landed = landPart(landing, store, resolved);\n const base = baselines[i];\n for (let j = 0; j < landed.length; j += 2) {\n const dx = landed[j] - base[j];\n const dy = landed[j + 1] - base[j + 1];\n most = Math.max(most, dx * dx + dy * dy);\n }\n });\n }\n store.reset();\n return Math.sqrt(most);\n };\n}\n\n/**\n * The parts whose geometry can depend on `output`: those that read it\n * themselves, or hang from a deformer that reads it or has an ancestor that\n * does. The rest land exactly at rest, so landing them adds nothing.\n */\nfunction affectedParts(model: IkiModel, output: string): Set<IkiPart> {\n const deformers = new Map((model.deformers ?? []).map((d) => [d.id, d]));\n const reads = (d: IkiDeformer) =>\n (d.kind === \"warp\"\n ? [\n ...(d.warps ?? []).map((w) => w.parameter),\n d.warp2d?.parameter,\n d.warp2d?.parameterY,\n ]\n : (d.bindings ?? []).map((b) => b.parameter)\n ).includes(output);\n const hung = (id: string | undefined): boolean => {\n for (\n let d = id && deformers.get(id);\n d;\n d = d.parent && deformers.get(d.parent)\n ) {\n if (reads(d)) return true;\n }\n return false;\n };\n return new Set(\n model.parts.filter(\n (p) =>\n [\n ...(p.bindings ?? []).map((b) => b.parameter),\n ...(p.warps ?? []).map((w) => w.parameter),\n ].includes(output) || hung(p.deformer),\n ),\n );\n}\n","import type {\n IkiModel,\n IkiParameter,\n IkiPhysics,\n IkiPhysicsChain,\n} from \"@ikijs/format\";\nimport { resolveDeformers } from \"./deform\";\nimport { FIXED_DT_S } from \"./frame-clock\";\nimport { HairChainMotion } from \"./hair-chain-motion\";\nimport { IdleMotion } from \"./idle-motion\";\nimport { clamp } from \"./math\";\nimport { ParameterStore } from \"./parameter-store\";\nimport { PhysicsMotion } from \"./physics-motion\";\n\n// The excitation runs behind `checkPhysics`: the real drivers on a synthetic\n// 60 Hz clock, never a re-implemented integrator.\n\n/**\n * A hair over one sub-step: at exactly 1000/60 ms, float rounding leaves the\n * drivers' accumulator just short or just over, so about one frame in three\n * runs no sub-step (re-emitting the last value) and about as many run two\n * (emitting only the second) — and a skipped sub-step can be the peak.\n */\nconst FRAME_MS = FIXED_DT_S * 1000 * (1 + 1e-9);\n/** Frames after the seed frame: 5 s of step (the defaults settle in ~2 s), 30 s of idle. */\nconst STEP_FRAMES = 300;\nconst IDLE_FRAMES = 1800;\n/** Any constant keeps two checks equal; it only matters for a gaze- or eye-driven rig. */\nconst IDLE_SEED = 1;\n/** An anchor turn, or a lead over another, under this many radians is float noise (a uniform scale over a rotated anchor). */\nconst MIN_TURN = 1e-9;\n\n/** What a driver handed its sink for one output, read against the output's range and resting value. */\nexport interface Reading {\n /** The largest signed displacement of the clamped value from rest, and when, seconds in. */\n peak: number;\n at: number;\n /** The clamped value at the window's end. */\n final: number;\n /** Every distinct clamped value emitted except the resting one. */\n values: number[];\n /** The least and greatest clamped values emitted. */\n lo: number;\n hi: number;\n /** The longest run of frames with the raw value outside the range, and the bound it began past. */\n pinned: { frames: number; end: \"min\" | \"max\" };\n /** The driver's finiteness-guard activations for the output. */\n resets: number;\n}\n\n/**\n * Runs a `PhysicsMotion` over `rigs` and a `HairChainMotion` over `chains`,\n * both reading and writing `store`, for the seed frame and `frames` more —\n * one FIXED_DT_S sub-step each — calling `excite` ahead of them every frame;\n * reads what they hand the sink, per output.\n */\nfunction run(\n model: IkiModel,\n store: ParameterStore,\n rigs: IkiPhysics[],\n chains: IkiPhysicsChain[],\n frames: number,\n excite: (frame: number, nowMs: number) => void,\n): Map<string, Reading> {\n const raw = new Map<string, number[]>();\n const read = (id: string) => store.get(id);\n const sink = (id: string, value: number) => {\n let trace = raw.get(id);\n if (trace === undefined) raw.set(id, (trace = []));\n trace.push(value);\n store.set(id, value);\n };\n const { parameters } = model;\n const drivers = [\n new PhysicsMotion(rigs, parameters, read, sink),\n new HairChainMotion(chains, parameters, model.deformers ?? [], read, sink),\n ];\n for (let frame = 0; frame <= frames; frame++) {\n const nowMs = frame * FRAME_MS;\n excite(frame, nowMs);\n for (const driver of drivers) driver.update(nowMs);\n }\n const readings = new Map<string, Reading>();\n for (const driver of drivers) {\n driver.drivenParameterIds.forEach((id, i) => {\n const param = parameters.find((p) => p.id === id)!;\n readings.set(id, readTrace(raw.get(id)!, param, driver.resets[i]));\n });\n }\n return readings;\n}\n\n/** Reads `raw`, one sink value per frame from the seed frame on, against `param`. */\nfunction readTrace(\n raw: number[],\n param: IkiParameter,\n resets: number,\n): Reading {\n const rest = clamp(param.default, param.min, param.max);\n const reading: Reading = {\n peak: 0,\n at: 0,\n final: rest,\n values: [],\n lo: rest,\n hi: rest,\n pinned: { frames: 0, end: \"max\" },\n resets,\n };\n const seen = new Set([rest]);\n let outside = 0;\n let end: Reading[\"pinned\"][\"end\"] = \"max\";\n raw.forEach((value, frame) => {\n const held = clamp(value, param.min, param.max);\n if (Math.abs(held - rest) > Math.abs(reading.peak)) {\n reading.peak = held - rest;\n reading.at = frame * FIXED_DT_S;\n }\n if (!seen.has(held)) {\n seen.add(held);\n reading.values.push(held);\n }\n reading.lo = Math.min(reading.lo, held);\n reading.hi = Math.max(reading.hi, held);\n reading.final = held;\n if (value >= param.min && value <= param.max) {\n outside = 0;\n return;\n }\n const side = value < param.min ? \"min\" : \"max\";\n // Crossing to the other bound ends the run: a swing between the two is\n // not pinning.\n if (outside === 0 || side !== end) {\n outside = 0;\n end = side;\n }\n outside++;\n if (outside > reading.pinned.frames) {\n reading.pinned = { frames: outside, end };\n }\n });\n return reading;\n}\n\n/**\n * The end farther from the clamped default — the one `signedNormalized`\n * takes as its unit, `max` on a tie — or `undefined` for a zero-width range.\n */\nexport function farEnd(param: IkiParameter): number | undefined {\n if (param.min === param.max) return undefined;\n const rest = clamp(param.default, param.min, param.max);\n return param.max - rest >= rest - param.min ? param.max : param.min;\n}\n\n/**\n * The step run: `rigs` and `chains` from rest, `values` set after the seed\n * frame and held for the window, every other parameter resting.\n */\nexport function stepRun(\n model: IkiModel,\n rigs: IkiPhysics[],\n chains: IkiPhysicsChain[],\n values: Record<string, number>,\n): Map<string, Reading> {\n const store = new ParameterStore(model.parameters);\n return run(model, store, rigs, chains, STEP_FRAMES, (frame) => {\n if (frame !== 1) return;\n for (const [id, v] of Object.entries(values)) store.set(id, v);\n });\n}\n\n/**\n * The idle run: every rig and chain together behind the procedural\n * `IdleMotion` on a seeded rng, stepped idle → physics → chains each frame as\n * `IkiMotion` orders them. A declared `Idle` group is not played.\n */\nexport function idleRun(model: IkiModel): Map<string, Reading> {\n const store = new ParameterStore(model.parameters);\n const idle = new IdleMotion((id, v) => store.set(id, v), {\n rng: lcg(IDLE_SEED),\n });\n return run(\n model,\n store,\n model.physics ?? [],\n model.physicsChains ?? [],\n IDLE_FRAMES,\n (_, nowMs) => idle.update(nowMs),\n );\n}\n\n/** Numerical Recipes' 32-bit LCG, in [0, 1). */\nfunction lcg(seed: number): () => number {\n let state = seed >>> 0;\n return () => {\n state = (Math.imul(state, 1664525) + 1013904223) >>> 0;\n return state / 2 ** 32;\n };\n}\n\n/** A parameter that turns a chain's anchor, at the probe value that turns it most. */\nexport interface Candidate {\n parameter: string;\n value: number;\n}\n\n/**\n * Every parameter that alone changes `chain`'s anchor world rotation at one\n * of its probe values — its `max`, its `min` and every keyform stop of a warp\n * deformer keyed on it, all but the resting value — in model order. Both\n * ends and the stops, since a warp parent can turn the anchor at one end\n * alone or at an interior stop while its other end matches rest. A probe\n * turning it no more than `MIN_TURN` past an earlier one does not replace it,\n * so a symmetric rig steps to `max`, as `farEnd` does, and float noise never\n * decides a near-tie.\n */\nexport function anchorInputs(\n model: IkiModel,\n chain: IkiPhysicsChain,\n): Candidate[] {\n const store = new ParameterStore(model.parameters);\n const angle = () => {\n const { worlds } = resolveDeformers(model.deformers ?? [], store);\n const world = worlds.get(chain.anchorDeformer)!;\n return Math.atan2(world[1], world[0]);\n };\n const rest = angle();\n const found: Candidate[] = [];\n for (const p of model.parameters) {\n const probes = new Set(\n [p.max, p.min, ...stopsOf(model, p.id)].map((v) =>\n clamp(v, p.min, p.max),\n ),\n );\n probes.delete(store.get(p.id));\n let most = 0;\n let best: Candidate | undefined;\n for (const value of probes) {\n store.set(p.id, value);\n const d = angle() - rest;\n const turn = Math.abs(Math.atan2(Math.sin(d), Math.cos(d)));\n if (turn <= most + MIN_TURN) continue;\n [most, best] = [turn, { parameter: p.id, value }];\n }\n store.reset();\n if (best) found.push(best);\n }\n return found;\n}\n\n/** The sorted distinct keyform values of every deformer warp and `warp2d` axis keyed on `parameter`. */\nfunction stopsOf(model: IkiModel, parameter: string): number[] {\n const stops = new Set<number>();\n for (const d of model.deformers ?? []) {\n if (d.kind !== \"warp\") continue;\n for (const w of d.warps ?? []) {\n if (w.parameter !== parameter) continue;\n for (const k of w.keyforms) stops.add(k.value);\n }\n const { warp2d } = d;\n if (warp2d?.parameter === parameter) {\n for (const v of warp2d.valuesX) stops.add(v);\n }\n if (warp2d?.parameterY === parameter) {\n for (const v of warp2d.valuesY) stops.add(v);\n }\n }\n return [...stops].sort((a, b) => a - b);\n}\n","/**\n * The fold check `auto_rig_from_layers` and `render_poses` report: the\n * engine's `checkFolds` with the auto-rig's by-design closures set apart, and\n * the text lines both tools print it as.\n */\n\nimport { SHUT_BY } from \"@ikijs/editor\";\nimport {\n checkFolds,\n foldPoses,\n type FoldHit,\n type FoldPose,\n type FoldReport,\n type FoldTarget,\n} from \"@ikijs/engine\";\nimport type { IkiModel } from \"@ikijs/format\";\n\n/**\n * `checkFolds` over `foldPoses(model)` then one pose per `extraValues` set,\n * appended as given (a set equal to a default pose is checked twice), with\n * the auto-rig's by-design closures (`SHUT_BY`) kept out of `worst`.\n */\nexport function checkModelFolds(\n model: IkiModel,\n extraValues: Record<string, number>[] = [],\n): FoldReport {\n // An undeclared parameter reads 0 from the store, which is no closure.\n const declared = new Set(model.parameters.map((p) => p.id));\n return checkFolds(model, {\n poses: [...foldPoses(model), ...extraValues.map(foldPose)],\n // The effective value, not the pose's overrides: the auto-rig's mouth\n // rests shut at its default, so `rest` and the other parameters' singles\n // are shut-mouth poses too.\n expected: (target, _pose, value) => {\n if (target.kind !== \"part\") return false;\n const shutBy = SHUT_BY.get(target.id);\n return (\n shutBy !== undefined && declared.has(shutBy) && value(shutBy) === 0\n );\n },\n });\n}\n\n/**\n * `report` as text lines: one `FOLD` line per offender, worst first, or\n * `FOLDS: none over N poses`; then, when a by-design closure folds, one\n * `FOLDS expected:` line naming each such part, its ratio and the parameter\n * that shuts it. A `FOLD` line gives its rest point in model space and in\n * model px from the top-left of the model's `canvas` — the layer PNGs' own\n * pixels, the frame `RenderPlan.mouth` is in, not a render's.\n */\nexport function formatFoldReport(\n report: FoldReport,\n canvas: { width: number; height: number },\n): string[] {\n const lines =\n report.offenders.length === 0\n ? [`FOLDS: none over ${report.poses} poses`]\n : report.offenders.map((t) => offenderLine(t, t.worst!, canvas));\n\n // An expected hit that never came near folding is no closure to list.\n const closures = report.targets.flatMap((t) => {\n if (t.expected === undefined) return [];\n if (t.expected.ratio >= report.thresholds.collapse) return [];\n const shutBy = SHUT_BY.get(t.target.id);\n const at = shutBy === undefined ? \"\" : ` at ${shutBy}=0`;\n return [`${t.target.id} ${ratioText(t.expected.ratio)}${at}`];\n });\n if (closures.length > 0) {\n lines.push(\n `FOLDS expected: by-design closures, not findings — ${closures.join(\", \")}`,\n );\n }\n return lines;\n}\n\n/**\n * `values` named by the `FoldPose.name` contract, as the engine names its own\n * poses (its helper is not exported): sorted `id=value` pairs joined by one\n * space, `rest` when empty. Never a caller's PNG name, so a `FOLD` line keeps\n * settings a host can reproduce.\n */\nexport function foldPose(values: Record<string, number>): FoldPose {\n const ids = Object.keys(values).sort();\n const name =\n ids.length === 0\n ? \"rest\"\n : ids.map((id) => `${id}=${values[id]}`).join(\" \");\n return { name, values };\n}\n\nfunction offenderLine(\n t: FoldTarget,\n hit: FoldHit,\n canvas: { width: number; height: number },\n): string {\n const where =\n \"triangle\" in hit.where\n ? `triangle ${hit.where.triangle}`\n : `cell (${hit.where.col},${hit.where.row})`;\n const { x, y } = hit.rest;\n return (\n `FOLD ${t.kind} ${t.target.kind} ${t.target.id} ${where} ratio ${ratioText(hit.ratio)} ` +\n `pose [${hit.pose.name}] rest at (${x.toFixed(1)}, ${y.toFixed(1)}) model space, ` +\n `(${(canvas.width / 2 + x).toFixed(0)}, ${(canvas.height / 2 - y).toFixed(0)}) model px from the top-left`\n );\n}\n\n/** Two decimals, or two significant figures under 0.01, so a flip a hair\n * under 0 never reads `-0.00`. */\nfunction ratioText(ratio: number): string {\n if (ratio === 0) return \"0\";\n return Math.abs(ratio) < 0.01 ? ratio.toExponential(1) : ratio.toFixed(2);\n}\n","/**\n * The pose plan `render_poses` captures: the canvas framing, the crops and the\n * pose list, all decided from the model. It is the iki-character-loop's\n * render recipe, minus the page that ran it.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n IkiFormatError,\n StandardParameter,\n loadIkiModel,\n type IkiModel,\n} from \"@ikijs/format\";\nimport {\n checkPhysics,\n type FoldReport,\n type PhysicsReport,\n} from \"@ikijs/engine\";\nimport { checkModelFolds } from \"./fold-report\";\nimport {\n AutoRigInputError,\n confineToWorkingDirectory,\n resolveInputPath,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\nimport { NO_BROWSER_MESSAGE, findBrowser, withBrowser } from \"./render-browser\";\n\nexport interface RenderCrop {\n sx: number;\n sy: number;\n sw: number;\n sh: number;\n dw: number;\n dh: number;\n}\n\nexport interface RenderPose {\n name: string;\n values: Record<string, number>;\n /** Canvas px source and output size; absent = the whole canvas. */\n crop?: RenderCrop;\n}\n\nexport interface RenderPlan {\n canvas: { width: number; height: number };\n /** The player's view; absent = the model's own canvas. */\n view?: { x: number; y: number; width: number; height: number };\n fullBody: boolean;\n /** The mouth's centre in model px from the top-left. */\n mouth?: { cx: number; cy: number };\n poses: RenderPose[];\n}\n\n/** A pose the caller names, rendered in place of the model's own set. */\nexport interface RequestedPose {\n /** Written as `<outDir>/<name>.png`. */\n name: string;\n values: Record<string, number>;\n /** Model px from the top-left; absent = framed as the standard shots. */\n crop?: { x: number; y: number; w: number; h: number };\n}\n\n// The playground's view width for a full body, in model widths.\nconst FULL_BODY_VIEW_WIDTH = 2.5;\n// The model's square is drawn this many px wide, in the whole shot or a crop.\nexport const BUST_SIZE = 560;\n// A requested crop is drawn this many px wide, at its own aspect, and at\n// most this many tall: the page sizes a canvas to it.\nconst CROP_WIDTH = 720;\nconst CROP_MAX_HEIGHT = 8192;\n// The name becomes a file in outDir: no separator can climb out of it.\nconst POSE_NAME = /^[A-Za-z0-9_.-]+$/;\n\n/**\n * Bust-render px of vertical padding above a landscape model: the renderer\n * fits it into the square canvas and centres it. Zero for square and tall ones.\n */\nexport function bustPadY(width: number, height: number): number {\n return Math.max(0, (BUST_SIZE - (BUST_SIZE * height) / width) / 2);\n}\n\n/**\n * The model's own pose set, or `requested` alone when given. Throws\n * `AutoRigInputError` for a request it cannot render.\n */\nexport function planRenders(\n model: IkiModel,\n requested?: RequestedPose[],\n): RenderPlan {\n const { width: W, height: H } = model.canvas;\n const fullBody = H > W;\n const canvas = fullBody\n ? {\n width: FULL_BODY_VIEW_WIDTH * BUST_SIZE,\n height: Math.ceil((BUST_SIZE * H) / W),\n }\n : { width: BUST_SIZE, height: BUST_SIZE };\n const view = fullBody\n ? { x: 0, y: 0, width: FULL_BODY_VIEW_WIDTH * W, height: H }\n : undefined;\n\n // The model's square sits in the middle of the canvas.\n const x0 = (canvas.width - BUST_SIZE) / 2;\n const s = BUST_SIZE / W;\n const y0 = bustPadY(W, H);\n\n // The auto-rigger writes world-space part transforms and its deformers carry\n // no base transform, so the rest transform alone places the part.\n const mouthPart =\n model.parts.find((p) => p.id === \"mouth_inner\") ??\n model.parts.find((p) => p.id === \"mouth\");\n const mouth = mouthPart\n ? { cx: W / 2 + mouthPart.transform.x, cy: H / 2 - mouthPart.transform.y }\n : undefined;\n\n const squareCrop: RenderCrop | undefined = fullBody\n ? {\n sx: x0,\n sy: 0,\n sw: BUST_SIZE,\n sh: BUST_SIZE,\n dw: BUST_SIZE,\n dh: BUST_SIZE,\n }\n : undefined;\n const square = (name: string, values: Record<string, number> = {}) => ({\n name,\n values,\n crop: squareCrop,\n });\n const whole = (name: string, values: Record<string, number> = {}) => ({\n name,\n values,\n });\n\n if (requested) {\n if (requested.length === 0) throw new AutoRigInputError(\"poses is empty\");\n const poses = requested.map((pose, i): RenderPose => {\n checkRequest(requested, i);\n if (!pose.crop) return square(pose.name, pose.values);\n // Clamped to the canvas first, so a box grown past an edge still renders.\n const left = Math.max(pose.crop.x, 0);\n const top = Math.max(pose.crop.y, 0);\n const w = Math.min(pose.crop.x + pose.crop.w, W) - left;\n const h = Math.min(pose.crop.y + pose.crop.h, H) - top;\n // Negated so a NaN corner is refused too.\n if (!(w > 0 && h > 0)) {\n throw new AutoRigInputError(\n `poses[${i}].crop does not overlap the model's ${W}x${H} canvas`,\n );\n }\n // Refused here, not by the page after earlier poses were written.\n const dh = Math.round((CROP_WIDTH * h) / w);\n if (dh < 1 || dh > CROP_MAX_HEIGHT) {\n throw new AutoRigInputError(\n `poses[${i}].crop meets the canvas in ${w}x${h} model px, which ${CROP_WIDTH} px wide draws ${dh} px tall, outside 1..${CROP_MAX_HEIGHT}`,\n );\n }\n return {\n name: pose.name,\n values: pose.values,\n crop: {\n sx: x0 + left * s,\n sy: y0 + top * s,\n sw: w * s,\n sh: h * s,\n dw: CROP_WIDTH,\n dh,\n },\n };\n });\n return { canvas, view, fullBody, mouth, poses };\n }\n\n // The engine ignores an undeclared id, so this only keeps `stress` from\n // naming settings the rig lacks: every loop rig declares its other ids (the\n // composer requires brows), but the body angles only with a `body` layer.\n const bodyAngles = Object.fromEntries(\n [\n StandardParameter.BodyAngleX,\n StandardParameter.BodyAngleY,\n StandardParameter.BodyAngleZ,\n ]\n .filter((id) => model.parameters.some((p) => p.id === id))\n .map((id) => [id, -10]),\n );\n\n const poses: RenderPose[] = [\n square(\"rest\"),\n square(\"turn-m30\", { ParamAngleX: -30 }),\n square(\"turn-p30\", { ParamAngleX: 30 }),\n square(\"turn-15\", { ParamAngleX: 15 }),\n square(\"nod-15\", { ParamAngleY: 15 }),\n square(\"blink\", { ParamEyeLOpen: 0 }),\n square(\"blink-half\", { ParamEyeLOpen: 0.5 }),\n square(\"gaze\", { ParamEyeBallX: 1 }),\n square(\"combined\", { ParamAngleX: 30, ParamAngleY: 30, ParamAngleZ: 30 }),\n // Every head angle at its other extreme with the face moving too, where\n // moves that each look fine alone stack up into a fold.\n square(\"stress\", {\n ParamAngleX: -30,\n ParamAngleY: -30,\n ParamAngleZ: -30,\n ParamMouthOpenY: 1,\n ParamEyeLOpen: 0.5,\n ParamEyeROpen: 0.5,\n ParamBrowLY: -1,\n ParamBrowRY: 1,\n ParamBrowLAngle: 1,\n ParamBrowRAngle: -1,\n ...bodyAngles,\n }),\n ];\n\n if (mouth) {\n // 180 x 120 model px centred on the mouth, drawn x4 onto 720 x 480: a\n // small mouth is unreadable in the whole shot.\n const crop = {\n sx: x0 + (mouth.cx - 90) * s,\n sy: y0 + (mouth.cy - 60) * s,\n sw: 180 * s,\n sh: 120 * s,\n dw: 720,\n dh: 480,\n };\n for (const open of [0, 0.3, 0.6, 1]) {\n for (const [name, form] of [\n [\"m1\", -1],\n [\"0\", 0],\n [\"p1\", 1],\n ] as const) {\n poses.push({\n name: `mouth-open-${open}-form-${name}`,\n values: { ParamMouthOpenY: open, ParamMouthForm: form },\n crop,\n });\n }\n }\n poses.push(\n {\n name: \"mouth-laugh\",\n values: { ParamMouthOpenY: 0.8, ParamMouthForm: 1 },\n crop,\n },\n { name: \"mouth-surprised\", values: { ParamMouthOpenY: 0.9 }, crop },\n {\n name: \"mouth-turn-p30-half\",\n values: { ParamAngleX: 30, ParamMouthOpenY: 0.5 },\n crop,\n },\n );\n }\n\n if (fullBody) {\n poses.push(\n whole(\"full-rest\"),\n whole(\"full-turn-p30\", { ParamAngleX: 30 }),\n whole(\"full-body-x-m10\", { ParamBodyAngleX: -10 }),\n whole(\"full-body-x-p10\", { ParamBodyAngleX: 10 }),\n whole(\"full-body-y-m10\", { ParamBodyAngleY: -10 }),\n whole(\"full-body-y-p10\", { ParamBodyAngleY: 10 }),\n whole(\"full-body-z-m10\", { ParamBodyAngleZ: -10 }),\n whole(\"full-body-z-p10\", { ParamBodyAngleZ: 10 }),\n whole(\"full-arm-l-16\", { ParamArmL: 16 }),\n whole(\"full-arm-l-32\", { ParamArmL: 32 }),\n whole(\"full-arm-r-16\", { ParamArmR: 16 }),\n whole(\"full-arm-r-32\", { ParamArmR: 32 }),\n whole(\"full-elbow-l-m10\", { ParamElbowL: -10 }),\n whole(\"full-elbow-l-45\", { ParamElbowL: 45 }),\n whole(\"full-elbow-l-90\", { ParamElbowL: 90 }),\n whole(\"full-elbow-r-m10\", { ParamElbowR: -10 }),\n whole(\"full-elbow-r-45\", { ParamElbowR: 45 }),\n whole(\"full-elbow-r-90\", { ParamElbowR: 90 }),\n );\n if (model.parameters.some((p) => p.id === StandardParameter.ArmPoseRight)) {\n poses.push(\n whole(\"full-pose-l\", { ParamArmPoseL: 1 }),\n whole(\"full-pose-r\", { ParamArmPoseR: 1 }),\n whole(\"full-pose-r-angle-m15\", {\n ParamArmPoseR: 1,\n ParamArmPoseAngleR: -15,\n }),\n whole(\"full-pose-r-angle-p15\", {\n ParamArmPoseR: 1,\n ParamArmPoseAngleR: 15,\n }),\n whole(\"full-pose-r-half\", { ParamArmPoseR: 0.5 }),\n );\n }\n }\n\n return { canvas, view, fullBody, mouth, poses };\n}\n\n/** `requested[i]`'s name and values, as `planRenders` takes them. */\nfunction checkRequest(requested: RequestedPose[], i: number): void {\n const { name, values } = requested[i];\n if (!POSE_NAME.test(name)) {\n throw new AutoRigInputError(\n `poses[${i}].name must match ${POSE_NAME.source} (it names <outDir>/<name>.png): ${JSON.stringify(name)}`,\n );\n }\n const first = requested.findIndex(\n (p) => p.name.toLowerCase() === name.toLowerCase(),\n );\n if (first < i) {\n throw new AutoRigInputError(\n `poses[${i}].name ${JSON.stringify(name)} repeats poses[${first}].name ${JSON.stringify(requested[first].name)} (ignoring case: one file on a case-insensitive disk)`,\n );\n }\n for (const [id, value] of Object.entries(values)) {\n if (!Number.isFinite(value)) {\n throw new AutoRigInputError(\n `poses[${i}].values.${id} must be a finite number, got ${value}`,\n );\n }\n }\n}\n\nexport interface RenderPosesInput {\n /** The rigged `.iki` to render (resolved against cwd). */\n modelPath: string;\n /** Existing directory under cwd the pose PNGs are written into. */\n outDir: string;\n /** Rendered in place of the model's own set; each is also fold-checked. */\n poses?: RequestedPose[];\n}\n\nexport type RenderPosesResult =\n | {\n ok: true;\n outDir: string;\n canvas: RenderPlan[\"canvas\"];\n fullBody: boolean;\n mouth?: RenderPlan[\"mouth\"];\n /** Texture indices the engine could not load; the renders lack them. */\n failedTextures: number[];\n poses: { name: string; path: string }[];\n /** The model's own canvas, which `folds`' rest points are placed on in\n * the text (`canvas` is the render's). */\n modelCanvas: IkiModel[\"canvas\"];\n /** The model's folds, as `auto_rig_from_layers` reports them.\n * Report-only: a fold never fails the render. */\n folds: FoldReport;\n /** The model's own physics rigs (`poses` do not enter it), as\n * `auto_rig_from_layers` reports them. Report-only: it never fails\n * the render. */\n physics: PhysicsReport;\n }\n | { ok: false; error: string };\n\nconst PNG_PREFIX = \"data:image/png;base64,\";\nconst PAGE_SCRIPT_MS = 10_000;\nconst LOAD_MS = 60_000;\nconst CAPTURE_MS = 15_000;\n\nfunction readPageScript(): string {\n // Resolves from both src/ (vitest) and dist/: each sits one level under the package.\n const url = new URL(\"../dist/render-page.global.js\", import.meta.url);\n try {\n return readFileSync(url, \"utf8\");\n } catch (cause) {\n // A broken build or install, not caller input: it surfaces as a tool error.\n throw new Error(\n \"could not read the render page script; run `pnpm build` in packages/mcp\",\n { cause },\n );\n }\n}\n\n/**\n * Render the model's pose set into `outDir`. Only caller-input failures\n * (`AutoRigInputError`, `IkiFormatError`, and no installed browser) come back as\n * `{ ok: false, error }`; a browser or page failure throws.\n */\nexport async function renderPoses(\n input: RenderPosesInput,\n): Promise<RenderPosesResult> {\n try {\n const modelFile = confineToWorkingDirectory(\n process.cwd(),\n resolveInputPath(input.modelPath, \"model\"),\n \"model path\",\n input.modelPath,\n );\n const outDir = resolveOutputDir(input.outDir);\n const model = loadIkiModel(readFileSync(modelFile, \"utf8\"));\n const plan = planRenders(model, input.poses);\n const browser = findBrowser();\n if (!browser) return { ok: false, error: NO_BROWSER_MESSAGE };\n const pageScript = readPageScript();\n const folds = checkModelFolds(\n model,\n input.poses?.map((p) => p.values),\n );\n const physics = checkPhysics(model);\n\n const { failedTextures, poses } = await withBrowser(\n browser,\n async (evaluate) => {\n await evaluate(pageScript, PAGE_SCRIPT_MS);\n const loaded = (await evaluate(\n `window.__ikiRender.load(${JSON.stringify(model)}, ${JSON.stringify({ canvas: plan.canvas, view: plan.view })})`,\n LOAD_MS,\n )) as { failedTextures: number[] };\n const written: { name: string; path: string }[] = [];\n for (const pose of plan.poses) {\n const url = await evaluate(\n `window.__ikiRender.capture(${JSON.stringify(pose.values)}, ${JSON.stringify(pose.crop)})`,\n CAPTURE_MS,\n );\n if (typeof url !== \"string\" || !url.startsWith(PNG_PREFIX)) {\n throw new Error(`pose ${pose.name}: the page returned no PNG`);\n }\n const file = path.join(outDir, `${pose.name}.png`);\n writeFileAtomic(\n file,\n Buffer.from(url.slice(PNG_PREFIX.length), \"base64\"),\n );\n written.push({ name: pose.name, path: file });\n }\n return { failedTextures: loaded.failedTextures, poses: written };\n },\n );\n return {\n ok: true,\n outDir,\n canvas: plan.canvas,\n fullBody: plan.fullBody,\n mouth: plan.mouth,\n failedTextures,\n poses,\n modelCanvas: model.canvas,\n folds,\n physics,\n };\n } catch (error) {\n if (error instanceof AutoRigInputError || error instanceof IkiFormatError) {\n return { ok: false, error: error.message };\n }\n throw error;\n }\n}\n","/**\n * Resource guards + fail-fast path resolution and atomic writes for the Node\n * auto-rig tool.\n *\n * These constants bound an agent-supplied layer set so a malformed or oversized\n * request fails fast with a path-qualified message rather than exhausting memory\n * or producing a multi-MB MCP response. All guards REJECT (never downscale).\n *\n * `sharp` must stay confined to @ikijs/mcp — none of @ikijs/engine, @ikijs/editor,\n * or @ikijs/format may take a heavy Node image dependency.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\n/** Max number of input layers in one request. */\nexport const MAX_LAYERS = 64;\n/** Max per-side dimension (px) of any single input PNG. */\nexport const MAX_LAYER_DIM = 4096;\n/** Max per-side dimension (px) of the derived canvas. */\nexport const MAX_CANVAS_DIM = 4096;\n/** Max per-side length (px) of each packed atlas page. WebGL2 guarantees only\n * 2048, but 4096 or more is near-universal; the engine refuses a texture over\n * the device's own limit on either side and leaves its parts untextured. Both\n * sides within it also bound a page's area at 4096². */\nexport const MAX_ATLAS_SIDE = 4096;\n/** Decoded-pixel ceiling per input PNG, passed to sharp `limitInputPixels`. */\nexport const MAX_INPUT_PIXELS = 4096 * 4096;\n/** Aggregate decoded-pixel budget across ALL layers in one request. Layers\n * decode one at a time, so it bounds the request's total work, not its peak\n * memory. A full body's 21 layers at 1100 × 3650 decode 84.3 M px. */\nexport const MAX_TOTAL_PIXELS = 128 * 1024 * 1024;\n/** Max length (bytes) of the base64 atlas data URI embedded in the model,\n * summed over its pages. Sized for the loop's lossless re-rig of a full body:\n * measured on bob's layers, a lossless atlas costs 1.56 data-URI bytes per\n * crop px (1,677,898 B over 1,075,888 px), and a full body on a canvas up to\n * 4096 tall crops to at most ~5 M px, about 8 MB. */\nexport const MAX_OUTPUT_BYTES = 12 * 1024 * 1024;\n\n/**\n * Expected, caller-input-caused failure. The tool catches ONLY this class and\n * returns `{ ok: false, error }`; any other thrown Error (TypeError, invariant\n * break, programmer bug) propagates so the SDK handler surfaces `isError: true`.\n */\nexport class AutoRigInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AutoRigInputError\";\n }\n}\n\n/**\n * Reject an empty/whitespace or URL-looking caller-supplied path, shared by\n * {@link resolveInputPath} and {@link resolveInputDir}. `noun` and `kind`\n * shape the thrown message so each caller reports in its own vocabulary\n * (e.g. a directory input was never supposed to look like \"a file path\").\n */\nfunction rejectEmptyOrUrl(inputPath: string, noun: string, kind: string): void {\n if (typeof inputPath !== \"string\" || inputPath.trim() === \"\") {\n throw new AutoRigInputError(`${noun} is empty`);\n }\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(inputPath)) {\n throw new AutoRigInputError(\n `${noun} must be a ${kind}, not a URL: ${inputPath}`,\n );\n }\n}\n\n/**\n * Resolve a caller-supplied input file path against the MCP process cwd and\n * confirm it points at a readable file. Throws AutoRigInputError (path-qualified)\n * for empty/URL-looking strings, a missing file, or a directory.\n * `what` names the input in those messages (\"layer\" -> \"layer file not found\").\n *\n * READS ARE DELIBERATELY NOT CONFINED to the working directory, unlike\n * {@link resolveOutputPath}. The asymmetry is intentional, not an oversight: a\n * stray write destroys data, while a read only surfaces a PNG the agent already\n * named and the user's own account can already open. Confining reads would also\n * break the documented generate-a-character flow, which reads its part PNGs\n * from wherever the image generator dropped them (a downloads folder, a scratch\n * dir) while everything it writes — the composed layers, the model — stays\n * under the working directory. Revisit only if this server ever runs with wider\n * privileges than the person driving it. The same reasoning covers\n * {@link resolveInputDir}, its directory counterpart.\n *\n * Param is named `inputPath` (not `path`) to avoid shadowing the node:path import.\n */\nexport function resolveInputPath(inputPath: string, what = \"layer\"): string {\n rejectEmptyOrUrl(inputPath, `${what} path`, \"file path\");\n const resolved = path.resolve(process.cwd(), inputPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`${what} file not found: ${resolved}`);\n }\n if (stat.isDirectory()) {\n throw new AutoRigInputError(\n `${what} path is a directory, not a file: ${resolved}`,\n );\n }\n return resolved;\n}\n\n/** Directory counterpart to {@link resolveInputPath} — see its doc comment. */\nexport function resolveInputDir(dirPath: string): string {\n rejectEmptyOrUrl(dirPath, \"layers dir\", \"directory path\");\n const resolved = path.resolve(process.cwd(), dirPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`layers dir not found: ${resolved}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`layers path is not a directory: ${resolved}`);\n }\n return resolved;\n}\n\n/**\n * Confine an already-verified-to-exist directory to the MCP process working\n * directory, comparing REAL paths (statSync/writeFileSync follow symlinks, so\n * a lexical startsWith check can be bypassed by a symlinked dir under cwd).\n * Shared by {@link resolveOutputPath} and {@link resolveOutputDir} — both are\n * write-side boundaries where an unrestricted target is an\n * arbitrary-file-overwrite surface — and by `render_poses` for its model file,\n * whose first bytes a parse error would otherwise echo back. `label` and `original` shape the thrown\n * message (path-qualified with the caller's original, unresolved string).\n */\nexport function confineToWorkingDirectory(\n root: string,\n dir: string,\n label: string,\n original: string,\n): string {\n const realRoot = fs.realpathSync(root);\n const realDir = fs.realpathSync(dir);\n if (realDir !== realRoot && !realDir.startsWith(realRoot + path.sep)) {\n throw new AutoRigInputError(\n `${label} escapes the working directory: ${original}`,\n );\n }\n return realDir;\n}\n\n/**\n * Resolve a caller-supplied output path against the MCP process cwd. Throws\n * AutoRigInputError (path-qualified) if the parent directory does not exist —\n * the tool never creates directories (fail-fast).\n *\n * Writes are confined to the MCP process working directory: the path must end\n * in `.iki` AND resolve to a location under `process.cwd()`. The MCP server runs\n * with the user's own permissions on agent-supplied input, so an unrestricted\n * `outputPath` is an arbitrary-file-overwrite surface — absolute paths and `..`\n * traversal that escape the working directory are rejected. (Overwriting an\n * existing `.iki` UNDER the working directory is intentional: re-running the tool\n * regenerates the named model.)\n */\nexport function resolveOutputPath(outputPath: string): string {\n if (typeof outputPath !== \"string\" || outputPath.trim() === \"\") {\n throw new AutoRigInputError(\"output path is empty\");\n }\n if (!outputPath.toLowerCase().endsWith(\".iki\")) {\n throw new AutoRigInputError(`output path must end in .iki: ${outputPath}`);\n }\n const root = process.cwd();\n const resolved = path.resolve(root, outputPath);\n const dir = path.dirname(resolved);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(dir);\n } catch {\n throw new AutoRigInputError(`output directory does not exist: ${dir}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output parent is not a directory: ${dir}`);\n }\n const realDir = confineToWorkingDirectory(\n root,\n dir,\n \"output path\",\n outputPath,\n );\n return path.join(realDir, path.basename(resolved));\n}\n\n/**\n * Resolve a caller-supplied output DIRECTORY against the MCP process cwd.\n * Unlike {@link resolveOutputPath}, no filename is appended — the directory\n * itself must already exist (the tool never creates directories, fail-fast) —\n * and is confined via {@link confineToWorkingDirectory}. Returns the\n * realpath'd directory.\n */\nexport function resolveOutputDir(dirPath: string): string {\n if (typeof dirPath !== \"string\" || dirPath.trim() === \"\") {\n throw new AutoRigInputError(\"output dir is empty\");\n }\n const root = process.cwd();\n const resolved = path.resolve(root, dirPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`output dir not found: ${resolved}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output dir is not a directory: ${resolved}`);\n }\n return confineToWorkingDirectory(root, resolved, \"output dir\", dirPath);\n}\n\n/**\n * Write `data` to `outPath` atomically: write to a fresh temp file in the\n * same directory, then `renameSync` over the target. `rename` REPLACES the\n * destination directory entry rather than following it, so an existing\n * symlink at `outPath` cannot redirect the write outside the working tree.\n * Throws AutoRigInputError(\"write: …\") on failure.\n */\nexport function writeFileAtomic(\n outPath: string,\n data: string | Uint8Array,\n): void {\n const tmp = `${outPath}.${process.pid}.${Date.now()}.tmp`;\n try {\n fs.writeFileSync(tmp, data);\n try {\n fs.renameSync(tmp, outPath);\n } catch (e) {\n try {\n fs.rmSync(tmp, { force: true });\n } catch {\n // best-effort temp cleanup; surface the original rename error\n }\n throw e;\n }\n } catch (e) {\n throw new AutoRigInputError(\n `write: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n","/**\n * Browser discovery and a headless DevTools driver for `render_poses`: find a\n * system Chrome/Edge/Chromium, launch it, and evaluate scripts over the\n * DevTools protocol on Node's global `WebSocket`. No Playwright, no dependency.\n */\n\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { AutoRigInputError } from \"./limits\";\n\nexport const NO_BROWSER_MESSAGE =\n \"render_poses needs a Chromium-based browser and found none. Install Google Chrome, Microsoft Edge or Chromium, or set CHROME_PATH to its executable.\";\n\nconst DARWIN_CANDIDATES = [\n \"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\",\n \"/Applications/Chromium.app/Contents/MacOS/Chromium\",\n \"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge\",\n];\nconst LINUX_CANDIDATES = [\n \"/usr/bin/google-chrome\",\n \"/usr/bin/google-chrome-stable\",\n \"/usr/bin/chromium\",\n \"/usr/bin/chromium-browser\",\n \"/usr/bin/microsoft-edge\",\n \"/snap/bin/chromium\",\n];\nconst WIN32_ROOTS = [\"PROGRAMFILES\", \"PROGRAMFILES(X86)\", \"LOCALAPPDATA\"];\nconst WIN32_SUFFIXES = [\n [\"Google\", \"Chrome\", \"Application\", \"chrome.exe\"],\n [\"Microsoft\", \"Edge\", \"Application\", \"msedge.exe\"],\n];\n\nconst CLOSE_GRACE_MS = 2000;\nconst DEFAULT_TIMEOUT_MS = 30000;\nconst BROWSER_CLOSE_MS = 1000;\n\nfunction isExecutableFile(file: string): boolean {\n try {\n if (!fs.statSync(file).isFile()) return false;\n fs.accessSync(file, fs.constants.X_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nexport interface FindBrowserOptions {\n env: NodeJS.ProcessEnv;\n platform: NodeJS.Platform;\n isExecutable: (file: string) => boolean;\n}\n\n/** The browser to drive, or `undefined` when none is installed. */\nexport function findBrowser({\n env = process.env,\n platform = process.platform,\n isExecutable = isExecutableFile,\n}: Partial<FindBrowserOptions> = {}): string | undefined {\n const override = env.CHROME_PATH;\n if (override) {\n // A bad override must not fall through to spawn, where it fails obscurely.\n if (!isExecutable(override)) {\n throw new AutoRigInputError(\n `CHROME_PATH is not an executable file: ${override}`,\n );\n }\n return override;\n }\n let candidates: string[];\n if (platform === \"darwin\") candidates = DARWIN_CANDIDATES;\n else if (platform === \"win32\") {\n candidates = [];\n for (const suffix of WIN32_SUFFIXES) {\n for (const root of WIN32_ROOTS) {\n const base = env[root];\n if (base) candidates.push(path.win32.join(base, ...suffix));\n }\n }\n } else candidates = LINUX_CANDIDATES;\n return candidates.find((file) => isExecutable(file));\n}\n\nexport type Evaluate = (\n expression: string,\n timeoutMs: number,\n) => Promise<unknown>;\n\nexport interface Browser {\n openPage(): Promise<Evaluate>;\n close(): Promise<void>;\n}\n\ninterface RuntimeEvaluate {\n result: { value?: unknown };\n exceptionDetails?: {\n text: string;\n exception?: { description?: string; value?: unknown };\n };\n}\n\n/**\n * Race `promise` against a timer, clearing the timer either way. `detail`\n * adds context to the timeout message, read only when it fires.\n */\nfunction within<T>(\n promise: Promise<T>,\n ms: number,\n what: string,\n detail?: () => string,\n): Promise<T> {\n let timer: NodeJS.Timeout;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () =>\n reject(\n new Error(\n `${what} timed out after ${ms} ms${detail ? `: ${detail()}` : \"\"}`,\n ),\n ),\n ms,\n );\n });\n return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));\n}\n\ninterface CdpClient {\n send<T = unknown>(\n method: string,\n timeoutMs: number,\n params?: object,\n sessionId?: string,\n ): Promise<T>;\n}\n\nfunction connectCdp(url: string, timeoutMs: number): Promise<CdpClient> {\n const socket = new WebSocket(url);\n let nextId = 0;\n let socketClosed = false;\n const pending = new Map<\n number,\n { resolve: (v: unknown) => void; reject: (e: Error) => void }\n >();\n socket.addEventListener(\"message\", (event) => {\n const message = JSON.parse(String(event.data));\n const entry = pending.get(message.id);\n if (!entry) return; // a protocol event, not a reply\n pending.delete(message.id);\n if (message.error) {\n entry.reject(\n new Error(`${message.error.message} (${message.error.code})`),\n );\n } else entry.resolve(message.result);\n });\n socket.addEventListener(\"close\", () => {\n socketClosed = true;\n for (const entry of pending.values()) {\n entry.reject(new Error(\"DevTools connection closed\"));\n }\n pending.clear();\n });\n const opened = new Promise<CdpClient>((resolve, reject) => {\n socket.addEventListener(\"error\", () =>\n reject(new Error(\"DevTools connection failed\")),\n );\n socket.addEventListener(\"open\", () =>\n resolve({\n send<T>(\n method: string,\n callTimeoutMs: number,\n params?: object,\n sessionId?: string,\n ) {\n // send() on a closed socket is silent; fail now, not at the timeout.\n if (socketClosed) {\n return Promise.reject(new Error(\"DevTools connection closed\"));\n }\n const id = ++nextId;\n const reply = new Promise<T>((res, rej) => {\n pending.set(id, {\n resolve: res as (v: unknown) => void,\n reject: rej,\n });\n });\n socket.send(JSON.stringify({ id, method, params, sessionId }));\n return within(reply, callTimeoutMs, method).finally(() =>\n pending.delete(id),\n );\n },\n }),\n );\n });\n // Closing the socket on failure lets a hung connect not outlive the launch.\n return within(opened, timeoutMs, \"DevTools connection\").catch((error) => {\n socket.close();\n throw error;\n });\n}\n\nfunction startError(executable: string, error: NodeJS.ErrnoException): Error {\n return new Error(\n `could not start ${executable}: ${error.code ?? error.message}`,\n );\n}\n\n/** The DevTools websocket URL Chrome prints on stderr once it is ready. */\nfunction waitForDevTools(\n child: ChildProcess,\n closed: Promise<void>,\n getSpawnError: () => NodeJS.ErrnoException | undefined,\n executable: string,\n timeoutMs: number,\n): Promise<string> {\n let tail = \"\";\n return within(\n new Promise<string>((resolve, reject) => {\n // Keeps draining after the match so Chrome never blocks on a full pipe.\n child.stderr!.on(\"data\", (chunk) => {\n tail = (tail + chunk).slice(-2000);\n const match = /DevTools listening on (ws:\\/\\/\\S+)/.exec(tail);\n if (match) resolve(match[1]);\n });\n void closed.then(() => {\n const spawnError = getSpawnError();\n reject(\n spawnError\n ? startError(executable, spawnError)\n : new Error(\n `${executable} exited before DevTools was ready: ${tail.trim()}`,\n ),\n );\n });\n }),\n timeoutMs,\n \"browser startup\",\n () => tail.trim() || \"no output\",\n );\n}\n\nasync function openPage(cdp: CdpClient, timeoutMs: number): Promise<Evaluate> {\n const { targetId } = await cdp.send<{ targetId: string }>(\n \"Target.createTarget\",\n timeoutMs,\n { url: \"about:blank\" },\n );\n const { sessionId } = await cdp.send<{ sessionId: string }>(\n \"Target.attachToTarget\",\n timeoutMs,\n { targetId, flatten: true },\n );\n return async (expression, evalTimeoutMs) => {\n const { result, exceptionDetails } = await cdp.send<RuntimeEvaluate>(\n \"Runtime.evaluate\",\n evalTimeoutMs,\n { expression, awaitPromise: true, returnByValue: true },\n sessionId,\n );\n if (exceptionDetails) {\n // A thrown non-Error has no description; its value beats \"Uncaught\".\n const thrown = exceptionDetails.exception;\n throw new Error(\n thrown?.description ??\n (thrown && \"value\" in thrown\n ? String(thrown.value)\n : exceptionDetails.text),\n );\n }\n return result.value;\n };\n}\n\n/** Cleanup must not replace the result of a render that already finished. */\nfunction removeProfile(profile: string): void {\n try {\n fs.rmSync(profile, {\n recursive: true,\n force: true,\n maxRetries: 5,\n retryDelay: 100,\n });\n } catch (error) {\n console.error(`could not remove browser profile ${profile}:`, error);\n }\n}\n\n/**\n * Start `executable` headless and connect to it. `timeoutMs` bounds startup\n * and every DevTools call `openPage` makes; each evaluate has its own.\n */\nexport async function launchBrowser(\n executable: string,\n timeoutMs: number,\n): Promise<Browser> {\n if (typeof globalThis.WebSocket === \"undefined\") {\n throw new AutoRigInputError(\n \"render_poses needs Node 22 or newer (the global WebSocket is missing).\",\n );\n }\n const profile = fs.mkdtempSync(path.join(os.tmpdir(), \"iki-render-\"));\n let child: ChildProcess;\n try {\n child = spawn(\n executable,\n [\n \"--headless=new\",\n \"--remote-debugging-port=0\",\n `--user-data-dir=${profile}`,\n \"--no-first-run\",\n \"--no-default-browser-check\",\n // Output pixel sizes must equal the plan's, whatever the display.\n \"--force-device-scale-factor=1\",\n // WebGL without a GPU; recent Chrome no longer falls back by itself.\n \"--enable-unsafe-swiftshader\",\n \"about:blank\",\n ],\n { stdio: [\"ignore\", \"ignore\", \"pipe\"] },\n );\n } catch (error) {\n // Some failures (ENOEXEC, EINVAL on Windows) throw instead of emitting.\n fs.rmSync(profile, { recursive: true, force: true });\n throw startError(executable, error as NodeJS.ErrnoException);\n }\n // Both in the spawn tick: a failed spawn is an `error` event, not a throw,\n // and `close` fires even when no `exit` does.\n let spawnError: NodeJS.ErrnoException | undefined;\n child.on(\"error\", (error) => {\n spawnError = error;\n });\n let exited = false;\n const closed = new Promise<void>((resolve) => {\n child.on(\"close\", () => {\n exited = true;\n resolve();\n });\n });\n const settle = (ms: number) =>\n within(closed, ms, \"browser close\").catch(() => {});\n\n // The server can die mid-render (SIGTERM, host gone); 'exit' handlers run\n // synchronously, so the browser and its profile do not outlive it.\n const onProcessExit = () => {\n child.kill(\"SIGKILL\");\n removeProfile(profile);\n };\n process.once(\"exit\", onProcessExit);\n\n let shutdownPromise: Promise<void> | undefined;\n const shutdown = () =>\n (shutdownPromise ??= (async () => {\n if (!exited) {\n child.kill();\n await settle(CLOSE_GRACE_MS);\n if (!exited) {\n child.kill(\"SIGKILL\");\n await settle(CLOSE_GRACE_MS);\n }\n }\n process.removeListener(\"exit\", onProcessExit);\n removeProfile(profile);\n })());\n\n let cdp: CdpClient;\n try {\n const endpoint = await waitForDevTools(\n child,\n closed,\n () => spawnError,\n executable,\n timeoutMs,\n );\n cdp = await connectCdp(endpoint, timeoutMs);\n } catch (error) {\n await shutdown();\n throw error;\n }\n\n return {\n openPage: () => openPage(cdp, timeoutMs),\n async close() {\n if (!exited) {\n // Best effort: a polite close lets Chrome flush; kill follows anyway.\n await cdp.send(\"Browser.close\", BROWSER_CLOSE_MS).catch(() => {});\n }\n await shutdown();\n },\n };\n}\n\n/** Launch, open a page, run `fn`, and always close the browser. */\nexport async function withBrowser<T>(\n executable: string,\n fn: (evaluate: Evaluate) => Promise<T>,\n): Promise<T> {\n const browser = await launchBrowser(executable, DEFAULT_TIMEOUT_MS);\n try {\n return await fn(await browser.openPage());\n } finally {\n await browser.close();\n }\n}\n","/**\n * Node (sharp-backed) re-host of the browser-only pixel functions used by the\n * auto-rig import flow. Only the DECODE/ENCODE halves are re-hosted here — the\n * alpha-bbox scan itself is shared with the browser path via\n * @ikijs/editor, so the two cannot drift. Still a controlled duplicate of:\n * - crop ← examples/editor/src/auto-rig-image.ts\n * - atlas render + edge-extrude ← examples/editor/src/atlas-image.ts\n * The pure parts (packAtlas / uvRectFor / generateIkiFromLayerSet / role parsing\n * / bbox→model math) are reused from @ikijs/editor, not reimplemented here.\n *\n * `sharp` is a heavy native dependency and MUST stay confined to @ikijs/mcp — it\n * may never reach @ikijs/editor, @ikijs/engine, or @ikijs/format.\n */\n\nimport sharp from \"sharp\";\nimport type { AtlasLayout } from \"@ikijs/editor\";\nimport { detectAlphaBbox as scanAlphaBbox } from \"@ikijs/editor\";\nimport { AutoRigInputError, MAX_INPUT_PIXELS } from \"./limits\";\n\nexport interface DecodedPng {\n width: number;\n height: number;\n /** Straight-alpha RGBA bytes, stride-4 (parity with canvas getImageData). */\n rgba: Buffer;\n /** Whether the FILE carried an alpha channel, before `.ensureAlpha()` added\n * one. A generated part without it is opaque on a white background and needs\n * that white keyed out before it can layer (see ./compose). */\n hasAlpha: boolean;\n}\n\n/**\n * Decode a PNG file to straight-alpha RGBA bytes + dimensions.\n *\n * Decode is an input boundary: a missing/corrupt/unsupported file or a\n * limitInputPixels overflow surfaces as a path-qualified AutoRigInputError so\n * the tool returns { ok:false } rather than { isError:true }.\n *\n * `.ensureAlpha()` promotes RGB PNGs to RGBA so the alpha scan matches the\n * browser canvas getImageData path (which is always RGBA).\n */\nexport async function decodePng(filePath: string): Promise<DecodedPng> {\n try {\n const pipeline = sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS });\n const metadata = await pipeline.metadata();\n if (metadata.format !== \"png\") {\n throw new AutoRigInputError(\n `non-PNG image (${metadata.format ?? \"unknown\"}): ${filePath}`,\n );\n }\n const { data, info } = await pipeline\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return {\n width: info.width,\n height: info.height,\n rgba: data,\n hasAlpha: metadata.hasAlpha ?? false,\n };\n } catch (e) {\n if (e instanceof AutoRigInputError) throw e;\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);\n }\n}\n\n/**\n * Node-side wrapper over the shared scan in @ikijs/editor: same bbox rule\n * as the browser path by construction, with this package's error type for an\n * empty layer.\n */\nexport function detectAlphaBbox(\n rgba: Buffer,\n width: number,\n height: number,\n): { x: number; y: number; w: number; h: number } {\n const bbox = scanAlphaBbox(rgba, width, height);\n if (bbox === null) {\n throw new AutoRigInputError(\"layer is empty after alpha threshold\");\n }\n return bbox;\n}\n\n/**\n * Crop the already-decoded RGBA to bbox, returning a PNG buffer. One decode per\n * file: the crop is taken from the raw RGBA, not a re-read of the file. Parity\n * with cropBitmap in examples/editor/src/auto-rig-image.ts.\n */\nexport function cropToBuffer(\n rgba: Buffer,\n width: number,\n height: number,\n bbox: { x: number; y: number; w: number; h: number },\n): Promise<Buffer> {\n return sharp(rgba, { raw: { width, height, channels: 4 } })\n .extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h })\n .png()\n .toBuffer();\n}\n\n/**\n * Draw `svg` over the image at `filePath` and return the composited PNG bytes.\n * The debug half of ./measure-turn: the measurement is only believable once the\n * boxes are seen sitting on the irises. The caller has already decoded the file\n * through {@link decodePng}, so a failure here is an encode/environment fault,\n * not caller input, and propagates as itself.\n */\nexport function encodeOverlayPng(\n filePath: string,\n svg: string,\n): Promise<Buffer> {\n return sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS })\n .composite([{ input: Buffer.from(svg) }])\n .png()\n .toBuffer();\n}\n\nexport interface AtlasCrop {\n id: string;\n buffer: Buffer;\n width: number;\n height: number;\n}\n\n/**\n * Composite packed crops onto a transparent page and return a base64 PNG data\n * URI. Each crop's right + bottom edge pixels are extruded across the padding\n * gutter (replicating renderAtlas's right/bottom/corner drawImage extrudes in\n * examples/editor/src/atlas-image.ts) so LINEAR sampling at the inset UV never\n * reads a transparent neighbor texel. packAtlas reserves padding on the RIGHT\n * and BOTTOM only, so a one-sided `extend` matches its layout exactly.\n *\n * Crops are looked up BY placement.id (packAtlas sorts placements by id).\n * ASSUMES a non-empty layout (the empty case is handled by the caller).\n *\n * `quantizeColors` palette-quantizes the page PNG (libimagequant via sharp).\n * Flat-shaded character art keeps its look at 256 colours while the atlas\n * drops to roughly a quarter of its lossless size — the hero demo went from\n * 3.5MB to 0.9MB at a mean channel delta of 1.5/255 — which is what makes a\n * generated model shippable on a page. Omitted = lossless, as before. Soft\n * alpha is where it fails: a shaded nose's feather rims in borrowed palette\n * entries, so the auto-rig renders the nose on its own page without it.\n * Splitting it off also changes how page 0 re-quantizes, so the size effect\n * is content-dependent — on the playground hero the split model came to\n * 1.28MB, about the same as the all-quantized 1.29MB and well under the\n * 3.18MB lossless model.\n */\nexport async function renderAtlasToDataUri(\n crops: AtlasCrop[],\n layout: AtlasLayout,\n quantizeColors?: number,\n): Promise<string> {\n const byId = new Map<string, AtlasCrop>();\n for (const crop of crops) byId.set(crop.id, crop);\n\n const pad = layout.padding;\n\n const composites = await Promise.all(\n layout.placements.map(async (placement) => {\n const crop = byId.get(placement.id);\n if (crop === undefined) {\n throw new AutoRigInputError(\n `no crop for atlas placement \"${placement.id}\"`,\n );\n }\n // Replicate the right + bottom (+ corner) edge pixels into the gutter.\n const input =\n pad > 0\n ? await sharp(crop.buffer)\n .extend({ right: pad, bottom: pad, extendWith: \"copy\" })\n .png()\n .toBuffer()\n : crop.buffer;\n return { input, left: placement.x, top: placement.y };\n }),\n );\n\n const page = await sharp({\n create: {\n width: layout.pageWidth,\n height: layout.pageHeight,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n })\n .composite(composites)\n .png(\n quantizeColors === undefined\n ? {}\n : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 },\n )\n .toBuffer();\n\n return `data:image/png;base64,${page.toString(\"base64\")}`;\n}\n","/**\n * Compose AI-generated part PNGs into canvas-aligned, role-named layers for the\n * Iki auto-rig (`auto_rig_from_layers` / `@ikijs/editor` generateIkiFromLayerSet).\n * Each part is alpha-trimmed, resized to a target width, optionally mirrored,\n * and pasted at a chosen center on a shared transparent canvas, CANVAS wide and\n * `canvasHeight` tall (CANVAS unless a full body sets it) — the nose by its\n * dense core, the drawing inside a soft nose's feather.\n *\n * Ports the composer that shipped as a script in the Claude Code plugin, so a\n * plugin user gets it from the MCP server instead of an ad-hoc `sharp` install.\n * Composing is deterministic: same parts -> same layers, so re-run freely after\n * tuning `layout` (no image re-generation needed).\n *\n * The mouth has two routes. `mouth.png` (+ optional `mouth_open.png`) is a\n * closed drawing and an open one that cross-fade. `mouth_keyed.png` (the open\n * mouth, its inside flat #00FF00) + `mouth_interior.png` is the lip set: the\n * composer keys and splits it into `mouth_inner` / `lip_lower` / `lip_upper` on\n * one frame (./compose-lips), which the rig folds open like an eyelid, and the\n * interior's light paint into `mouth_tongue` / `mouth_teeth` clipped to it.\n *\n * `sharp` must stay confined to @ikijs/mcp; part decoding goes through\n * ./node-images, this package's single image-decode boundary.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport sharp from \"sharp\";\nimport {\n ALPHA_OPAQUE,\n isLipInsideRole,\n detectAlphaBbox as scanAlphaBbox,\n} from \"@ikijs/editor\";\nimport { cropToBuffer, decodePng } from \"./node-images\";\nimport { TRIM_THRESHOLD, boxWithoutStraySpecks, luma } from \"./trim\";\nimport { measureDir, type MeasureReport, type NoseSpeck } from \"./measure\";\nimport { denseCoreOf, isSpeckCore } from \"./measure-turn\";\nimport {\n ARM_WIDTH,\n armPlacement,\n forearmPosePlacement,\n forearmPoseWidth,\n} from \"./compose-arms\";\nimport {\n INTERIOR_SRC,\n KEYED_SRC,\n closedLips,\n keyBorderWhite,\n keyGreen,\n prepInterior,\n restShiftOf,\n splitLipSet,\n} from \"./compose-lips\";\nimport {\n AutoRigInputError,\n MAX_CANVAS_DIM,\n resolveInputDir,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\n\n/**\n * The layer canvas's width, and its default height, in px. The width is NOT an\n * input: the layout defaults below place parts against it (hair_front alone is\n * 660px wide, and sharp rejects a composite input larger than its\n * destination), so a different width would need its own layout. The height is\n * `canvasHeight`: the canvas grows downward from this square, so every default\n * keeps its place. The tuning surface is `layout` overrides.\n */\nexport const CANVAS = 1100;\n\n/** The layer canvas, in px: CANVAS wide and `canvasHeight` tall. */\ninterface Canvas {\n width: number;\n height: number;\n}\n\n/**\n * The canvas as error messages name it: \"1100\" when square, as every message\n * did before the height could grow, and \"1100x3650\" when tall.\n */\nfunction canvasName(canvas: Canvas): string {\n return canvas.width === canvas.height\n ? `${canvas.width}`\n : `${canvas.width}x${canvas.height}`;\n}\n\n// Iris width as a fraction of the sclera width. Anime irises fill most of the\n// eye opening and are clipped by the lids — the auto-rig clips iris->sclera at\n// runtime, so a large iris cannot spill. The first sample's 32% iris read as a\n// bead floating in white; the defaults below are the hero bob's, 50px in a\n// 98px opening (0.51). A caller retunes eye size through\n// `layout.eye_L/eye_R.w` and MUST move `layout.iris_L/iris_R.w` with it to keep\n// that ratio.\nconst EYE_W = 98;\nconst IRIS_W = 50;\n\n/** The eyewhite source that prepEyeSplit() splits into sclera + lash. */\nconst EYEWHITE_SRC = \"eyewhite.png\";\n/** Luminance below this (0..255) = a dark lash/outline pixel in the eyewhite. */\nconst EYE_LASH_LUMA = 120;\n// Of the eye's dark pixels, those in the TOP this-fraction are the upper lash,\n// an arc that folds DOWN over the eye on blink instead of a full ring that\n// shrinks in place; those below it are the lower lid's line and lashes.\nconst LASH_KEEP_FRACTION = 0.5;\n// A light pixel whose red exceeds its blue by this much is the lid's skin, not\n// the white. Measured on five drawn eyewhites: each sclera's median r - b sits\n// between -11 (mint's blue-white) and 0, and each lid band's 5th percentile\n// between 37 and 55 (silver-hood's band 242,208,191, mint's 231,196,184). A\n// cool shade painted on the white (the test fixture's 200,205,225) runs blue\n// over red, so it can never match.\nconst EYE_LID_WARMTH = 30;\n\ninterface RoleLayout {\n /** Part file name in the parts dir (the eye pair's two are split in memory). */\n src: string;\n /** Center in canvas px, origin top-left, y down. */\n cx: number;\n cy: number;\n /** Target width in px. */\n w: number;\n /**\n * Target height in px. Omitted, the height follows the part's own aspect\n * ratio — which is the right default for every role whose drawing already has\n * the proportions it should. It exists for the one that does not: an eyewhite\n * comes back flatter than the reference often enough that three generations\n * asking for \"taller\" landed at 0.47, while stretching a flat white lens ~15%\n * is invisible and free. Set it on the sclera and its lash together or the\n * fold tears — they share one frame.\n */\n h?: number;\n optional?: boolean;\n mirror?: boolean;\n noTrim?: boolean;\n}\n\n/**\n * The nose's layout. Its `w`, `h` and `cx` size and place its dense core\n * (`denseCoreOf`), not its whole trimmed part: a soft nose is mostly feather,\n * and sized by its extent it renders as a dot. A part with no core, or whose\n * core is a speck of it (`isSpeckCore`: a lone nostril mark or highlight,\n * which sized to `w` would blow the whole nose up), is sized and placed whole\n * instead, and the speck is warned about. Unlike every other role's, its `cy`\n * is optional. Set, it is the core's centre row; absent, the core's bottom row\n * — the tip — lands NOSE_TIP_AT of the way from the eye row down to the\n * mouth's.\n */\ninterface NoseLayout extends Omit<RoleLayout, \"cy\"> {\n cy?: number;\n}\n\n/**\n * An arm's layout. Its `cx`, `cy` and `w` are optional, each derived from the\n * placed body when unset (compose-arms.ts): `w` is ARM_WIDTH of the body's\n * width, and an unset `cx` or `cy` hangs the arm's shoulder pivot, the one\n * the rig turns it about, on the body box's shoulder corner on that axis. A\n * set one keeps every other role's meaning. The pose forearms share its shape\n * with their own derivation (compose-arms.ts): an unset `w` scales the\n * forearm's elbow end to the placed arm's elbow run, and an unset `cx` or\n * `cy` pins its elbow-end pivot on the arm's elbow.\n */\nexport interface ArmLayout extends Omit<RoleLayout, \"cx\" | \"cy\" | \"w\"> {\n cx?: number;\n cy?: number;\n w?: number;\n}\n\n/** A box in a part's own px, origin top-left. */\ninterface Box {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/**\n * Where a nose with no `cy` puts its tip, as a fraction of the way from the\n * eye row down to the mouth's. Bob's: tip row 554 between eye row 475 and\n * mouth row 594 (79/119 ≈ 0.66), so the default rows land bob's nose where his\n * own layout placed it.\n */\nconst NOSE_TIP_AT = 0.66;\n\n// ── DEFAULT LAYOUT (tune per character through `layout`) ──────────────────────\n// These defaults assume the standard framing the character skill prompts for\n// (a front-facing face centred across the canvas, in its top CANVAS rows).\n// They are canvas px from the top-left, so a taller canvas only adds room\n// below them. The face, eyes, irises,\n// lashes, brows, nose and mouth are the hero bob's own tuning; bob wears his\n// blush at its default placement, picked on his face (below). The features'\n// defaults are proportions of the face: resolveLayout carries them with the\n// face's cx, cy and w. The hair and\n// the torso depend on the hairstyle and on how the torso is framed, so they are\n// older defaults every character retunes from the report. If the rendered model is misaligned, tune cx/cy/w through the\n// `layout` override and re-run — composing is cheap and the parts do not need\n// regenerating.\n//\n// eyeSide reminder: eye_L = character's LEFT eye = screen RIGHT (larger cx).\n// Which way a source faces is fixed by the mirror flags below, and \"left eye\"\n// cannot say it — it reads as the viewer's left or the character's. So in\n// image terms: eyewhite.png is the eye on the SCREEN LEFT, its lash wing (outer\n// corner) at the image's left end and its lash-free tear duct at the right;\n// brow.png is the brow on the SCREEN RIGHT, its thick head at the image's left\n// end and its tail at the right; blush.png is the blush on the SCREEN LEFT,\n// its outer end (toward the face's edge) at the image's left end and its\n// inner end (toward the nose) at the right; arm.png is the arm on the SCREEN\n// LEFT (the character's right), hanging, its shoulder at the image's top and\n// its hand at the bottom; forearm_pose.png is that arm's forearm raised, on\n// the SCREEN LEFT too: standing up from its elbow, the open hand at the\n// image's top with the thumb at its right (toward the body), a rounded\n// closed elbow end at the bottom. A part drawn the other way round is\n// flipped for free with `mirrorParts`.\n// eye_* = the WHITE sclera (upper lashes recolored white) = the blink clip mask + fold.\n// iris_* = colored disc on top, clipped to the sclera, drives gaze.\n// lash_lower_* = the lower lid's dark line and lashes, ABOVE the iris (it\n// covers the iris's bottom edge, as the drawing does) and folding\n// with the white. Placed on the eye's frame, so it has no layout key.\n// lash_* = the dark upper lashes, a separate layer ABOVE the iris that folds\n// down to cover the closed-eye seam. eye_*, lash_lower_* and lash_* are\n// split from a single `eyewhite.png` (white almond + dark lashes) by\n// prepEyeSplit().\nconst DEFAULT_LAYOUT = {\n // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir\n // without them still composes (head-only character).\n hair_back: { src: \"hair_back.png\", cx: 550, cy: 523, w: 800, optional: true },\n // The bust's torso, cut off by a square canvas's bottom, so the character is\n // not a floating head; a full body on a tall canvas sets `layout.body`\n // itself. It rides the rig's `bodyWarp`, which the head hangs from.\n body: { src: \"body.png\", cx: 550, cy: 1017, w: 840, optional: true },\n // The arms, one part for both: arm_R (screen left) takes arm.png as drawn\n // and arm_L mirrors it, like the blush. They draw over the body and under\n // the face. They have no cx/cy/w defaults: each is derived from the placed\n // body (ArmLayout). OPTIONAL and opt-in: a parts dir without arm.png\n // composes as a bust does, and `skipped` never lists them.\n arm_L: { src: \"arm.png\", optional: true, mirror: true },\n arm_R: { src: \"arm.png\", optional: true, mirror: false },\n // The face is drawn without a neck, so its box is the skull and centres\n // above the eye row (bob's skull at 437 against his eyes' 475).\n face: { src: \"face.png\", cx: 550, cy: 437, w: 400 },\n // The cheek blush, one part for both cheeks: blush_R (screen left) takes it\n // as drawn and blush_L mirrors it, like the eyewhite. It draws over the face\n // and under the nose. Its box sits below each eye, centred 5 px outside the\n // eye's centre and 55 px under its row, above the nose tip: on bob's face,\n // which narrows fast below the eye row, a 2:1 blush there stays on the\n // cheek through the turn, where one 26 px further out reached the ears.\n // OPTIONAL: a parts dir without it composes, and nothing reports it missing.\n blush_L: { src: \"blush.png\", cx: 641, cy: 530, w: 56, optional: true, mirror: true }, // prettier-ignore\n blush_R: { src: \"blush.png\", cx: 459, cy: 530, w: 56, optional: true, mirror: false }, // prettier-ignore\n // The nose, drawn on its own (the face is drawn without one): the auto-rig\n // leads the head turn with it and keys the other features' slide on its\n // presence, so without it the features stay on the face plate. `w` is the\n // width of its dense core, and it has no `cy`: its row comes from the tip\n // rule (NOSE_TIP_AT), between the eyes and the mouth, so it follows them\n // when they are retuned. OPTIONAL: a parts dir without it composes.\n nose: { src: \"nose.png\", cx: 550, w: 20, optional: true },\n mouth: { src: \"mouth.png\", cx: 550, cy: 594, w: 76 },\n // Cross-fades with `mouth` on ParamMouthOpenY (opacity, not scaleY) once the\n // auto-rig sees both roles. Same cx/w as `mouth` so the lip width matches;\n // its top edge (not center) lines up with the closed mouth's top edge since\n // the mouth opens downward from a fixed upper lip — hence the +2 cy nudge\n // rather than sharing cy outright. Optional: composes fine without it.\n mouth_open: {\n src: \"mouth_open.png\",\n cx: 550,\n cy: 596,\n w: 76,\n optional: true,\n },\n // The lip set's ONE frame, mouth_open's place: the keyed mouth is split into\n // mouth_inner / lip_lower / lip_upper, the interior's light paint into\n // mouth_tongue / mouth_teeth, and all of them land here, so a retune moves\n // them together. The other four have no key of their own (LIP_FRAME).\n // OPTIONAL and opt-in: with mouth_keyed.png + mouth_interior.png it stands\n // in for mouth and mouth_open.\n mouth_inner: {\n src: KEYED_SRC,\n cx: 550,\n cy: 596,\n w: 76,\n optional: true,\n },\n // eye_* (sclera) and lash_* share the eyewhite's cropped frame via noTrim (so\n // they are NOT re-bboxed independently): the upper lash stays anchored ABOVE\n // the sclera center, so on blink it folds DOWN over the eye like the sample\n // model instead of the whole eye shrinking in place. Same cx/cy/w.\n eye_L: { src: \"eyewhite_sclera.png\", cx: 636, cy: 475, w: EYE_W, mirror: true, noTrim: true }, // prettier-ignore\n eye_R: { src: \"eyewhite_sclera.png\", cx: 464, cy: 475, w: EYE_W, mirror: false, noTrim: true }, // prettier-ignore\n // A little under the white's centre and toward the nose, as bob's sits.\n iris_L: { src: \"iris.png\", cx: 631, cy: 480, w: IRIS_W, mirror: false },\n iris_R: { src: \"iris.png\", cx: 469, cy: 480, w: IRIS_W, mirror: false },\n lash_L: {\n src: \"eyewhite_lash.png\",\n cx: 636,\n cy: 475,\n w: EYE_W,\n mirror: true,\n noTrim: true,\n },\n lash_R: { src: \"eyewhite_lash.png\", cx: 464, cy: 475, w: EYE_W, mirror: false, noTrim: true }, // prettier-ignore\n brow_L: { src: \"brow.png\", cx: 645, cy: 405, w: 105, mirror: false },\n brow_R: { src: \"brow.png\", cx: 455, cy: 405, w: 105, mirror: true },\n hair_front: { src: \"hair_front.png\", cx: 550, cy: 425, w: 660 },\n // The pose forearms, one drawing for both: forearm_pose_R (screen left)\n // takes forearm_pose.png as drawn and forearm_pose_L mirrors it, like the\n // arms. The rig draws them above the face and the hair, so they come last.\n // No cx/cy/w defaults: an unset `w` scales the forearm's elbow end to the\n // placed arm's elbow run, an unset `cx` or `cy` pins its elbow-end pivot\n // on the arm's elbow (ArmLayout). OPTIONAL and opt-in, like the arms.\n forearm_pose_L: { src: \"forearm_pose.png\", optional: true, mirror: true },\n forearm_pose_R: { src: \"forearm_pose.png\", optional: true, mirror: false },\n} satisfies Record<string, RoleLayout | NoseLayout | ArmLayout>;\n\nexport type Role = keyof typeof DEFAULT_LAYOUT;\n\n/** The lower lash of each eye, and the eye whose placement it takes. */\nconst LOWER_LASH = { lash_lower_L: \"eye_L\", lash_lower_R: \"eye_R\" } as const;\n/** The eyewhite's lower lid, split in memory like the sclera and lash. */\nconst LOWER_LASH_SRC = \"eyewhite_lash_lower.png\";\n\n/** The lip set's other layers, and the role whose frame they are cut on. */\nconst LIP_FRAME = {\n mouth_tongue: \"mouth_inner\",\n mouth_teeth: \"mouth_inner\",\n lip_lower: \"mouth_inner\",\n lip_upper: \"mouth_inner\",\n} as const;\n\n/** A role the composer writes a layer for. */\nexport type LayerRole = Role | keyof typeof LOWER_LASH | keyof typeof LIP_FRAME;\n\n/** The arm roles, placed off the body (ArmLayout). */\ntype ArmRole = \"arm_L\" | \"arm_R\";\n/** The pose forearm roles, placed off their arm's elbow (ArmLayout). */\ntype PoseRole = \"forearm_pose_L\" | \"forearm_pose_R\";\n\n/**\n * The merged layout, typed so a default other than the nose's, the arms' and\n * the pose forearms' that drops its `cy` fails to compile: `resolveLayout` builds it from\n * DEFAULT_LAYOUT.\n */\ntype ResolvedLayout = Record<\n Exclude<Role, \"nose\" | ArmRole | PoseRole>,\n RoleLayout\n> & {\n nose: NoseLayout;\n} & Record<ArmRole | PoseRole, ArmLayout>;\n\n/**\n * Draw order (back -> front): the roles of @ikijs/editor ROLE_TABLE the\n * composer writes, in its order — a test holds it to that subsequence.\n */\nexport const ORDER: LayerRole[] = [\n \"hair_back\",\n \"body\",\n \"arm_L\",\n \"arm_R\",\n \"face\",\n \"blush_L\",\n \"blush_R\",\n \"nose\",\n \"mouth\",\n \"mouth_open\",\n \"mouth_inner\",\n \"mouth_tongue\",\n \"mouth_teeth\",\n \"lip_lower\",\n \"lip_upper\",\n \"eye_L\",\n \"eye_R\",\n \"iris_L\",\n \"iris_R\",\n \"lash_lower_L\",\n \"lash_lower_R\",\n \"lash_L\",\n \"lash_R\",\n \"brow_L\",\n \"brow_R\",\n \"hair_front\",\n \"forearm_pose_L\",\n \"forearm_pose_R\",\n];\n\n/**\n * The part files a parts dir holds: every source the layout reads from disk,\n * and the eyewhite the eye pair is split from in memory.\n */\nconst PART_FILES = [\n ...new Set(\n Object.values(DEFAULT_LAYOUT)\n .map((cfg) => cfg.src)\n .filter((src) => !src.startsWith(\"eyewhite_\")),\n ),\n EYEWHITE_SRC,\n INTERIOR_SRC,\n];\n\n/** Per-role placement overrides; anything omitted keeps the default above. */\nexport type LayoutOverride = Partial<\n Record<Role, { cx?: number; cy?: number; w?: number; h?: number }>\n>;\n\nexport interface ComposeInput {\n /** Directory of the generated part PNGs (relative paths resolve against cwd). */\n partsDir: string;\n /**\n * Existing directory under cwd to write the role layers into. Callers reuse\n * one across runs (it must pre-exist), so the compose leaves it holding\n * exactly the roles it reports: the layer an earlier run wrote for any role\n * this run does not write — a skipped role, or an arm once arm.png is gone\n * — is removed rather than left for the next tool to pick up.\n */\n outDir: string;\n layout?: LayoutOverride;\n /**\n * Part files to flip left-right as they are read, e.g. `[\"eyewhite.png\"]`\n * for an eye drawn facing the other way. It flips the SOURCE, so every role\n * cut from it flips together — the eye pair's sclera and lash stay in one\n * frame, which a per-role flag would leave to the caller to keep in sync.\n */\n mirrorParts?: string[];\n /**\n * The canvas's height in px: an even integer in CANVAS..MAX_CANVAS_DIM,\n * CANVAS (a square bust canvas) when omitted, and every output at CANVAS is\n * byte-identical to an omitted one. The width stays CANVAS. The canvas grows\n * downward: every default and every override keeps its canvas px from the\n * top-left, so the head lands where it does on a bust and a full body gets\n * room below. Model space is centred on the canvas, so an odd height, which\n * would put the head on a half pixel, is refused.\n */\n canvasHeight?: number;\n}\n\nexport interface ComposedLayer {\n role: LayerRole;\n path: string;\n /** Size of the placed part itself (the file is always CANVAS x the canvas\n * height). */\n width: number;\n height: number;\n left: number;\n top: number;\n}\n\nexport type ComposeResult =\n | {\n ok: true;\n outDir: string;\n layers: ComposedLayer[];\n /**\n * Roles whose optional part was absent from the parts dir, and the lower\n * lashes when the eyewhite draws no dark lower lid. The arms and the\n * pose forearms are opt-in and never listed: a parts dir without\n * arm.png composes as a bust does, though an earlier compose's arm\n * layers are still removed. The lip roles are never listed either, and\n * with the lip set neither are `mouth` and `mouth_open`, which the set\n * stands in for.\n */\n skipped: LayerRole[];\n /** The rest pose, flattened: a pose forearm is invisible there, so it\n * never shows in this one, and the lip set shows closed, as the rig\n * draws the rest pose. */\n preview: string;\n /** Written only with a pose forearm: the switch at 1 as the rig draws\n * it — each arm with a pose forearm cropped to the rows above its\n * elbow (the hanging forearm hidden), the pose forearms over\n * everything. */\n previewPose?: string;\n measure: MeasureReport;\n }\n | { ok: false; error: string };\n\n/**\n * The roles drawn on the face, but the nose (resolveLayout places it on its\n * own). Their defaults are placed relative to the face's: a layout that moves\n * or scales the face carries them with it.\n */\nconst FACE_FEATURES = [\n \"blush_L\",\n \"blush_R\",\n \"mouth\",\n \"mouth_open\",\n \"mouth_inner\",\n \"eye_L\",\n \"eye_R\",\n \"iris_L\",\n \"iris_R\",\n \"lash_L\",\n \"lash_R\",\n \"brow_L\",\n \"brow_R\",\n] as const satisfies readonly Exclude<Role, \"nose\">[];\n\n/**\n * Merge caller overrides onto the defaults. Input boundary: an unknown role, a\n * non-finite centre or an out-of-range width or height fails fast,\n * path-qualified, before any decode. `w` is capped at the canvas's width and\n * `h` at its height, so a part sized whole can never exceed the canvas width\n * (a nose, sized by its core, is checked in partBuffer); `cx`/`cy` are\n * unbounded here because a part may legitimately hang off an edge —\n * assertOnCanvas() rejects the one that lands nowhere on it.\n *\n * The face's override applies first. Each feature's default is then moved\n * with the face's centre and scaled by its width against the default face's,\n * so the defaults are proportions of the face; a feature's own override still\n * names canvas px.\n */\nfunction resolveLayout(\n overrides: LayoutOverride | undefined,\n canvas: Canvas,\n): ResolvedLayout {\n const resolved: ResolvedLayout = { ...DEFAULT_LAYOUT };\n if (overrides === undefined) return resolved;\n const sets = new Map<\n Role,\n { cx?: number; cy?: number; w?: number; h?: number }\n >();\n for (const [role, override] of Object.entries(overrides)) {\n if (!Object.prototype.hasOwnProperty.call(DEFAULT_LAYOUT, role)) {\n throw new AutoRigInputError(\n `layout.${role}: unknown role — expected one of ${Object.keys(DEFAULT_LAYOUT).join(\", \")}`,\n );\n }\n if (override === undefined) continue;\n // Only the fields the override sets: spread over the entry, an explicit\n // undefined would erase the default it leaves alone.\n const set: { cx?: number; cy?: number; w?: number; h?: number } = {};\n for (const field of [\"cx\", \"cy\"] as const) {\n const value = override[field];\n if (value === undefined) continue;\n if (!Number.isFinite(value)) {\n throw new AutoRigInputError(\n `layout.${role}.${field} must be a finite number, got ${String(value)}`,\n );\n }\n set[field] = value;\n }\n for (const field of [\"w\", \"h\"] as const) {\n const value = override[field];\n if (value === undefined) continue;\n const max = field === \"w\" ? canvas.width : canvas.height;\n if (!Number.isInteger(value) || value < 1 || value > max) {\n throw new AutoRigInputError(\n `layout.${role}.${field} must be an integer in 1..${max}, got ${String(value)}`,\n );\n }\n set[field] = value;\n }\n sets.set(role as Role, set);\n }\n const face = { ...resolved.face, ...sets.get(\"face\") };\n resolved.face = face;\n const base = DEFAULT_LAYOUT.face;\n const scale = face.w / base.w;\n const x = (cx: number) => face.cx + (cx - base.cx) * scale;\n const w = (width: number) => Math.max(1, Math.round(width * scale));\n for (const role of FACE_FEATURES) {\n const d = DEFAULT_LAYOUT[role];\n const cy = face.cy + (d.cy - base.cy) * scale;\n resolved[role] = { ...d, cx: x(d.cx), cy, w: w(d.w), ...sets.get(role) };\n }\n // The nose has no default cy (the tip rule places it, off the eye and\n // mouth rows above), so it merges on its own.\n const nose = DEFAULT_LAYOUT.nose;\n resolved.nose = {\n ...nose,\n cx: x(nose.cx),\n w: w(nose.w),\n ...sets.get(\"nose\"),\n };\n for (const [role, set] of sets) {\n if (role === \"face\" || role === \"nose\") continue;\n if ((FACE_FEATURES as readonly Role[]).includes(role)) continue;\n mergeRole(resolved, role, set);\n }\n return resolved;\n}\n\n/**\n * Merge an override's set fields onto a role's resolved entry. Generic over\n * the role so one statement types for every kind of entry, the arms' among\n * them, whose cx/cy/w may stay unset.\n */\nfunction mergeRole<R extends Role>(\n resolved: ResolvedLayout,\n role: R,\n set: { cx?: number; cy?: number; w?: number; h?: number },\n): void {\n resolved[role] = { ...resolved[role], ...set };\n}\n\n/**\n * Input boundary for `canvasHeight`: an even integer in CANVAS..MAX_CANVAS_DIM,\n * CANVAS when omitted. Model space is centred on the canvas, so an odd height\n * would put the head on a half pixel.\n */\nfunction resolveCanvasHeight(value: number | undefined): number {\n if (value === undefined) return CANVAS;\n if (\n !Number.isInteger(value) ||\n value % 2 !== 0 ||\n value < CANVAS ||\n value > MAX_CANVAS_DIM\n ) {\n throw new AutoRigInputError(\n `canvasHeight must be an even integer in ${CANVAS}..${MAX_CANVAS_DIM}, got ${String(value)}`,\n );\n }\n return value;\n}\n\n/**\n * Input boundary for `mirrorParts`: a name that is not a part file (a typo, or\n * a role such as `eye_L`) would otherwise flip nothing and read as success.\n */\nfunction resolveMirrorParts(names: string[] | undefined): Set<string> {\n const mirrored = new Set<string>();\n for (const [i, name] of (names ?? []).entries()) {\n if (!PART_FILES.includes(name)) {\n throw new AutoRigInputError(\n `mirrorParts[${i}]: unknown part ${JSON.stringify(name)} — expected one of ${PART_FILES.join(\", \")}`,\n );\n }\n mirrored.add(name);\n }\n return mirrored;\n}\n\n/**\n * Some generated parts come back opaque on a white background (no alpha).\n * Key near-white pixels to transparent so they can layer cleanly.\n */\nfunction keyWhiteToAlpha(rgba: Buffer): Buffer {\n const keyed = Buffer.from(rgba);\n for (let i = 0; i < keyed.length; i += 4) {\n if (keyed[i] > 238 && keyed[i + 1] > 238 && keyed[i + 2] > 238) {\n keyed[i + 3] = 0;\n }\n }\n return keyed;\n}\n\n/** A PNG part's dense core (`null` when no pixel reaches the core's alpha)\n * and its own bounds, both in its own px. */\nasync function coreAndBoundsOf(\n png: Buffer,\n): Promise<{ core: Box | null; bounds: Box }> {\n const { data, info } = await sharp(png)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return {\n core: denseCoreOf(data, info.width, info.height),\n bounds: { x: 0, y: 0, w: info.width, h: info.height },\n };\n}\n\n/** Whether a part keeps a pixel the auto-rig counts as coverage. */\nasync function hasCoverage(png: Buffer): Promise<boolean> {\n const { data, info } = await sharp(png)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return scanAlphaBbox(data, info.width, info.height) !== null;\n}\n\n/** What a nose part's layout sizes, decided on the trimmed source part. */\ninterface NoseSizing {\n /** The box layout `w`/`h` size, in the trimmed source part's px (not the\n * resized part's). */\n box: Box;\n /** The whole part stood in for the core: it has none, or it is a speck. */\n whole: boolean;\n /** The core's and the part's sizes when a speck was the reason. */\n speck?: NoseSpeck;\n}\n\n/**\n * What a nose part's layout sizes: its dense core, in its own px — or its own\n * bounds, so it is sized and placed whole, when no pixel reaches the core's\n * alpha (a nose painted wholly translucent) or the core is a speck of those\n * bounds (`isSpeckCore`).\n */\nasync function noseSizingOf(png: Buffer): Promise<NoseSizing> {\n const { core, bounds } = await coreAndBoundsOf(png);\n if (core === null) return { box: bounds, whole: true };\n if (isSpeckCore(core, bounds)) {\n return {\n box: bounds,\n whole: true,\n speck: {\n core: { w: core.w, h: core.h },\n part: { w: bounds.w, h: bounds.h },\n },\n };\n }\n return { box: core, whole: false };\n}\n\n/** A part trimmed and flipped, not yet resized: a PNG and its size. */\ninterface Trimmed {\n data: Buffer;\n w: number;\n h: number;\n}\n\n/**\n * Trim/mirror a part, ready to be resized (`sizedPart`). `inMemory` carries\n * the eye pair's two split buffers and the lip set's keyed mouth; every other\n * role is read from the parts dir. `flipSource` is a `mirrorParts` entry for\n * the file the role is cut from. A pose forearm is measured between this and\n * the resize, to learn the width that fits it to its arm.\n * Missing optional part -> null; missing required part -> AutoRigInputError.\n */\nasync function trimmedPart(\n role: LayerRole,\n cfg: Omit<RoleLayout, \"cx\" | \"cy\" | \"w\">,\n partsDir: string,\n inMemory: Buffer | undefined,\n flipSource: boolean,\n): Promise<Trimmed | null> {\n let img: sharp.Sharp;\n if (inMemory !== undefined) {\n img = sharp(inMemory);\n } else {\n const srcPath = path.join(partsDir, cfg.src);\n if (!fs.existsSync(srcPath)) {\n // An optional role's part may be absent from the parts dir; the\n // auto-rig only requires face/eye_L/eye_R/mouth.\n if (cfg.optional) return null;\n // Name the role, not just the file: one source feeds two roles\n // (brow.png -> brow_L/brow_R), so the path alone does not say what broke.\n throw new AutoRigInputError(\n `missing part source for role \"${role}\": ${srcPath}` +\n (role === \"mouth\"\n ? \" — draw mouth.png (with mouth_open.png), or the lip set's mouth_keyed.png + mouth_interior.png\"\n : \"\"),\n );\n }\n const png = await decodePng(srcPath);\n // decodePng is the package's decode boundary: it caps the source at\n // MAX_INPUT_PIXELS and reports a bad/corrupt file as a path-qualified\n // AutoRigInputError, so the raw re-wrap below is already bounded.\n img = sharp(png.hasAlpha ? png.rgba : keyWhiteToAlpha(png.rgba), {\n raw: { width: png.width, height: png.height, channels: 4 },\n });\n }\n // noTrim parts (the eye and lash pairs) keep their shared pre-cropped frame so\n // sclera and lash stay aligned; everything else is alpha-trimmed to its own\n // bbox, less any stray speck beside the drawing.\n if (!cfg.noTrim) {\n // The rest of the pipeline reads this trimmed raw, so the source is\n // decoded and trimmed once. Only file sources and the keyed mouth are\n // trimmed (the eye pair's halves are noTrim), and the file sources are\n // raw already, so a part with no stray speck composes byte-identically.\n const kept = await img\n .trim({ threshold: TRIM_THRESHOLD })\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n const { width: keptW, height: keptH } = kept.info;\n img = sharp(kept.data, {\n raw: { width: keptW, height: keptH, channels: 4 },\n });\n const box = boxWithoutStraySpecks(kept.data, keptW, keptH);\n if (box !== null) img = img.extract(box);\n }\n // A flipped source under a mirrored role cancels out. sharp's flop() sets a\n // flag rather than toggling it, so the two cannot simply be applied in turn.\n if ((cfg.mirror ?? false) !== flipSource) img = img.flop();\n // Materialise the trimmed part BEFORE resizing: its size is bounded by the\n // source decode limit, so the size the resize WOULD produce can be checked\n // against the canvas while only the bounded buffer is allocated.\n const trimmed = await img.png().toBuffer({ resolveWithObject: true });\n return {\n data: trimmed.data,\n w: trimmed.info.width,\n h: trimmed.info.height,\n };\n}\n\n/**\n * Resize a trimmed part to its layout width. The nose is resized so its dense\n * core, not its whole part, comes out `w` wide (and `h` tall when set),\n * unless its whole part stood in for the core. Either way the nose's sizing\n * decision (`noseSizingOf`) always comes back as `nose`, and no other role\n * has one.\n */\nasync function sizedPart(\n role: LayerRole,\n cfg: Omit<RoleLayout, \"cx\" | \"cy\">,\n trimmed: Trimmed,\n canvas: Canvas,\n): Promise<{ buf: Buffer; w: number; h: number; nose?: NoseSizing }> {\n const { w: trimmedW, h: trimmedH } = trimmed;\n // What `w`/`h` size: the nose's dense core, measured on the trimmed, flipped\n // part — the whole part scales with it, feather and all — or that whole\n // part when it has no core or the core is a speck, and every other role's\n // whole part.\n const nose = role === \"nose\" ? await noseSizingOf(trimmed.data) : undefined;\n const sized = nose?.box ?? { x: 0, y: 0, w: trimmedW, h: trimmedH };\n const width = Math.round((trimmedW * cfg.w) / sized.w);\n const height =\n cfg.h === undefined\n ? Math.round((trimmedH * width) / trimmedW)\n : Math.round((trimmedH * cfg.h) / sized.h);\n // resolveLayout bounds w and an explicit h, so for a part sized whole only\n // the aspect-derived height can run past the canvas; a nose sized by its\n // core can overrun either dimension.\n if (width > canvas.width || height > canvas.height) {\n const field = width > canvas.width || cfg.h === undefined ? \"w\" : \"h\";\n throw new AutoRigInputError(\n `layout.${role}.${field}: resized part ${width}x${height} exceeds the ${canvasName(canvas)} canvas`,\n );\n }\n const resized = await sharp(trimmed.data)\n // Width alone keeps the source aspect. With h, fit:\"fill\" is the point —\n // stretch to the given box instead. Both options stay off the width-only\n // path: passing height:undefined alongside fit:\"fill\" makes sharp drop the\n // aspect it would otherwise preserve.\n .resize(cfg.h === undefined ? { width } : { width, height, fit: \"fill\" })\n .png()\n .toBuffer({ resolveWithObject: true });\n return {\n buf: resized.data,\n w: resized.info.width,\n h: resized.info.height,\n nose,\n };\n}\n\n/**\n * Trim/mirror a part and resize it to its layout width: `trimmedPart` then\n * `sizedPart`. Missing optional part -> null; missing required part ->\n * AutoRigInputError.\n */\nasync function partBuffer(\n role: LayerRole,\n cfg: Omit<RoleLayout, \"cx\" | \"cy\">,\n partsDir: string,\n inMemory: Buffer | undefined,\n flipSource: boolean,\n canvas: Canvas,\n): Promise<{ buf: Buffer; w: number; h: number; nose?: NoseSizing } | null> {\n const trimmed = await trimmedPart(role, cfg, partsDir, inMemory, flipSource);\n return trimmed === null ? null : sizedPart(role, cfg, trimmed, canvas);\n}\n\n/**\n * Refuse a placed part that lands nowhere on the canvas. Running off an edge is\n * legitimate — a bust's `body` is meant to be cut off by the canvas bottom — so\n * the test is INTERSECTION, not containment. A part that misses the canvas\n * entirely composes to a fully transparent layer that nothing downstream flags\n * (measureDir warns per measured layer, and an empty one has no geometry), so a\n * sign-flipped centre would otherwise read as success.\n */\nfunction assertOnCanvas(\n source: string,\n w: number,\n h: number,\n left: number,\n top: number,\n canvas: Canvas,\n): void {\n if (\n left + w <= 0 ||\n top + h <= 0 ||\n left >= canvas.width ||\n top >= canvas.height\n ) {\n throw new AutoRigInputError(\n `${source}: the placed part (${w}x${h} at ${left},${top}) falls entirely outside the ${canvasName(canvas)} canvas`,\n );\n }\n}\n\n/** Where a part lands, centred on its layout cx/cy. The nose has its own. */\nfunction placement(\n role: Exclude<Role, \"nose\" | ArmRole | PoseRole>,\n cfg: RoleLayout,\n w: number,\n h: number,\n canvas: Canvas,\n) {\n const left = Math.round(cfg.cx - w / 2);\n const top = Math.round(cfg.cy - h / 2);\n assertOnCanvas(`layout.${role}.cx/cy`, w, h, left, top, canvas);\n return { left, top };\n}\n\n/**\n * Where the nose lands: by the box it was sized by (`noseSizingOf`), in the\n * resized part's px — its dense core, or its whole bounds when those stood in.\n * `cx` centres the box's columns. A set `cy` centres its rows; absent, its\n * bottom row — the tip, the last row index at alpha ≥ 128 — lands on\n * round(E + NOSE_TIP_AT·(M − E)), E the eyes' mean row and M the mouth's. A\n * box's centre is `x + w/2`, as placement() takes it: pixel x covers\n * [x, x + 1).\n */\nfunction nosePlacement(\n layout: ResolvedLayout,\n mouthKey: \"mouth\" | \"mouth_inner\",\n box: Box,\n w: number,\n h: number,\n canvas: Canvas,\n) {\n const { cx, cy } = layout.nose;\n const left = Math.round(cx - (box.x + box.w / 2));\n let top: number;\n if (cy !== undefined) {\n top = Math.round(cy - (box.y + box.h / 2));\n } else {\n const eyeRow = (layout.eye_L.cy + layout.eye_R.cy) / 2;\n const tipRow = Math.round(\n eyeRow + NOSE_TIP_AT * (layout[mouthKey].cy - eyeRow),\n );\n top = tipRow - (box.y + box.h - 1);\n }\n assertOnCanvas(\n cy !== undefined\n ? \"layout.nose.cx/cy\"\n : `layout.nose.cx/cy (cy unset: its tip row comes from layout.eye_L/eye_R/${mouthKey}.cy)`,\n w,\n h,\n left,\n top,\n canvas,\n );\n return { left, top };\n}\n\nfunction blankCanvas(canvas: Canvas) {\n return sharp({\n create: {\n width: canvas.width,\n height: canvas.height,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n });\n}\n\n/**\n * The eyewhite's light ink drawn detached above its white, as a row-major\n * mask (1 = detached). Light ink is non-transparent at luma EYE_LASH_LUMA or\n * over. Its sets are 8-connected through visibly painted pixels only (alpha\n * ALPHA_OPAQUE or over), so a faint antialiased pixel between a crease and\n * the white does not join them. Each fainter pixel is fringe of the nearest\n * painted set it reaches through faint pixels whose alpha never rises on the\n * way (ties go to the set met first in row-major order, the higher one).\n * Antialiasing fades away from what it edges, so a translucent stroke past a\n * fainter halo does not become the fringe of the set the halo edges. Faint\n * ink that no painted set reaches this way forms sets of its own. So does a\n * noisy faint pixel brighter than every claimed neighbour and touching no\n * painted pixel: above the white's top, it is dropped. The white is the\n * largest painted set. Another set is detached above it when each of its own\n * pixels, fringe aside, lies above the white's topmost painted pixel in its\n * column, or, past either end of the white, above the top of that end's\n * column; it goes with its fringe. A crease often runs on past the eye's\n * corners, and judged only over the white, one pixel out there would keep\n * the whole crease. A shade painted on the white touches it, so it is part\n * of the white; a mark below the white, or beside an end and level with it,\n * is left.\n */\nfunction detachedAboveWhite(rgba: Buffer, W: number, H: number): Uint8Array {\n const n = W * H;\n // 2 = painted light ink, 1 = fainter light ink, 0 = neither.\n const ink = new Uint8Array(n);\n for (let p = 0; p < n; p++) {\n const alpha = rgba[p * 4 + 3];\n if (alpha > 0 && luma(rgba, p * 4) >= EYE_LASH_LUMA)\n ink[p] = alpha >= ALPHA_OPAQUE ? 2 : 1;\n }\n const label = new Int32Array(n).fill(-1);\n // A pixel is labelled as it is pushed, so it is pushed once and neither the\n // flood fill's stack nor the fringe's queue outgrows the image.\n const stack = new Int32Array(n);\n const near = (p: number, visit: (q: number) => void) => {\n const px = p % W;\n const py = (p - px) / W;\n for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {\n for (let x = Math.max(0, px - 1); x <= Math.min(W - 1, px + 1); x++) {\n visit(y * W + x);\n }\n }\n };\n const sizes: number[] = [];\n const fill = (start: number) => {\n const id = sizes.length;\n let size = 0;\n let depth = 0;\n label[start] = id;\n stack[depth++] = start;\n while (depth > 0) {\n const p = stack[--depth];\n size++;\n near(p, (q) => {\n if (ink[q] === ink[start] && label[q] === -1) {\n label[q] = id;\n stack[depth++] = q;\n }\n });\n }\n sizes.push(size);\n };\n for (let p = 0; p < n; p++) if (ink[p] === 2 && label[p] === -1) fill(p);\n const paintedSets = sizes.length;\n // The fringe: breadth-first from every painted pixel at once, each faint\n // pixel no more opaque than the one before taking the set that reaches it\n // first.\n let head = 0;\n let tail = 0;\n for (let p = 0; p < n; p++) if (ink[p] === 2) stack[tail++] = p;\n while (head < tail) {\n const p = stack[head++];\n near(p, (q) => {\n if (\n ink[q] === 1 &&\n label[q] === -1 &&\n rgba[q * 4 + 3] <= rgba[p * 4 + 3]\n ) {\n label[q] = label[p];\n stack[tail++] = q;\n }\n });\n }\n for (let p = 0; p < n; p++) if (ink[p] === 1 && label[p] === -1) fill(p);\n\n const detached = new Uint8Array(n);\n if (paintedSets === 0 || sizes.length < 2) return detached;\n let white = 0;\n for (let id = 1; id < paintedSets; id++) {\n if (sizes[id] > sizes[white]) white = id;\n }\n // A set's own pixels: a painted set's painted ones, a faint set's all.\n const own = (p: number) => ink[p] === 2 || label[p] >= paintedSets;\n // The white's topmost painted row per column (the scan is row-major, so\n // the first pixel met is the top).\n const whiteTop = new Int32Array(W).fill(-1);\n for (let p = 0; p < n; p++) {\n const x = p % W;\n if (label[p] === white && own(p) && whiteTop[x] === -1)\n whiteTop[x] = (p - x) / W;\n }\n // An 8-connected set covers one unbroken run of columns, so every column\n // the white misses lies past one of its ends and takes that end's top.\n let first = 0;\n while (whiteTop[first] === -1) first++;\n let last = W - 1;\n while (whiteTop[last] === -1) last--;\n whiteTop.fill(whiteTop[first], 0, first);\n whiteTop.fill(whiteTop[last], last + 1);\n const above = new Uint8Array(sizes.length).fill(1);\n for (let p = 0; p < n; p++) {\n const id = label[p];\n if (id === -1 || id === white || !own(p)) continue;\n const x = p % W;\n if ((p - x) / W >= whiteTop[x]) above[id] = 0;\n }\n for (let p = 0; p < n; p++) {\n const id = label[p];\n if (id !== -1 && id !== white && above[id]) detached[p] = 1;\n }\n return detached;\n}\n\n/**\n * Split eyewhite.png (white almond + dark lashes) into a sclera (the upper\n * lash recolored to white; the whole drawing's alpha = the blink clip-mask\n * shape), a dark UPPER-lash layer and a dark LOWER-lid layer. All are cropped\n * to the SAME eye bbox so they stay aligned (consumed with noTrim): the lash\n * arc keeps its position at the top of the sclera, so on blink it folds DOWN\n * over the eye rather than the eye shrinking in place.\n *\n * The lower lid's dark line and lashes stay in the sclera as drawn and are\n * copied into their own layer, which draws over the iris. Recolored white they\n * would show as white flicks wherever a lash hangs below the white, and left\n * in the sclera alone the iris would paint over the line. The sclera keeps\n * them so its alpha, which the rig measures the eye by, is the drawing's.\n * `lashLower` is null when the eyewhite draws no dark pixel below the upper\n * lash's fraction.\n *\n * A light mark drawn detached above the white, such as a double-eyelid crease,\n * is dropped from the sclera (`detachedAboveWhite`). The sclera is the iris's\n * clip, and at half blink the fold carries such a mark down into the iris's\n * path. The frame is still the source's alpha bbox, crease and all, so the\n * layout places the pair where it did before.\n *\n * The lid's skin drawn as a band over the lash is dropped from the sclera too.\n * It meets the white at the corners, so the detached rule keeps it as the\n * white's; left in the clip, the rig's `blinkFold` carries it over the iris's\n * rows at half blink, where the lash its `lashFold` folds does not cover it,\n * and a taller iris shows through it above the lash at rest. The cut takes\n * only warm skin (painted, light, red over blue by EYE_LID_WARMTH) above the\n * lowest dark row over the white, in the columns that have a lash there.\n * Its limits: a band drawn over a lash-free column (the tear duct, the\n * corners) stays, since there colour alone cannot tell it from the white's\n * own warm shading or caruncle; a lid as cool as the white is not told apart\n * from it; the band's antialiased edge\n * under alpha ALPHA_OPAQUE is not cut, so it stays in the clip as the white's\n * fringe, a faint outline of the band; and a sclera tinted warmer than the\n * rule everywhere has no white top, so it is left whole. The frame is\n * unchanged.\n *\n * Both come back as PNG buffers. The script this ports wrote them back into the\n * parts dir, but that dir is an INPUT here (reads are deliberately unconfined),\n * so the tool never writes there — only under the confined outDir.\n */\nasync function prepEyeSplit(\n partsDir: string,\n): Promise<{ sclera: Buffer; lash: Buffer; lashLower: Buffer | null }> {\n const srcPath = path.join(partsDir, EYEWHITE_SRC);\n if (!fs.existsSync(srcPath)) {\n throw new AutoRigInputError(`missing eyewhite source: ${srcPath}`);\n }\n const { width: W, height: H, rgba: data } = await decodePng(srcPath);\n\n // Eye content bbox (alpha) → the shared cropped frame for both outputs.\n let minX = W;\n let minY = H;\n let maxX = -1;\n let maxY = -1;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n if (data[(y * W + x) * 4 + 3] > 8) {\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n }\n }\n if (maxX < 0) {\n throw new AutoRigInputError(`eyewhite is fully transparent: ${srcPath}`);\n }\n // Dark pixels above this row are the upper lash; below it, the lower lid.\n const lashCutoffY = minY + LASH_KEEP_FRACTION * (maxY - minY + 1);\n const detached = detachedAboveWhite(data, W, H);\n const isDark = (i: number) =>\n data[i + 3] > 0 && luma(data, i) < EYE_LASH_LUMA;\n const isLight = (i: number) =>\n data[i + 3] >= ALPHA_OPAQUE && luma(data, i) >= EYE_LASH_LUMA;\n const isWarm = (i: number) => data[i] - data[i + 2] >= EYE_LID_WARMTH;\n // Each column's white top: its first painted, light, cool pixel that is not\n // a mark detached above the white (a cool crease would stop the cut).\n const whiteTop = new Int32Array(W).fill(-1);\n for (let x = 0; x < W; x++) {\n for (let y = 0; y < H; y++) {\n const i = (y * W + x) * 4;\n if (!detached[y * W + x] && isLight(i) && !isWarm(i)) {\n whiteTop[x] = y;\n break;\n }\n }\n }\n // The columns outside the outermost two with a white top take the nearer\n // one's. A column between them with no cool pixel stays -1 and is left\n // uncut, and with no white top anywhere nothing is cut.\n let first = 0;\n while (first < W && whiteTop[first] === -1) first++;\n if (first < W) {\n let last = W - 1;\n while (whiteTop[last] === -1) last--;\n whiteTop.fill(whiteTop[first], 0, first);\n whiteTop.fill(whiteTop[last], last + 1);\n }\n // The row the lid's skin is cut above: the lowest dark row over the white,\n // in a column with one only (-1: no cut). Any dark pixel counts, a lash\n // tail hanging past lashCutoffY too, so a misread keeps skin rather than\n // cutting under the lash. A lash-free column is never cut: there a lid band\n // and the white's own warm shading or caruncle sit on the white alike.\n const lidStop = new Int32Array(W).fill(-1);\n for (let x = 0; x < W; x++) {\n for (let y = whiteTop[x] - 1; y >= 0; y--) {\n if (isDark((y * W + x) * 4)) {\n lidStop[x] = y;\n break;\n }\n }\n }\n\n const sclera = Buffer.from(data);\n const lash = Buffer.from(data);\n const lashLower = Buffer.from(data);\n let lowerInk = false;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n const i = (y * W + x) * 4;\n const dark = isDark(i);\n const upper = y <= lashCutoffY;\n if (dark && upper) sclera[i] = sclera[i + 1] = sclera[i + 2] = 255; // dark -> white\n if (detached[y * W + x]) sclera[i + 3] = 0;\n if (y < lidStop[x] && isLight(i) && isWarm(i)) sclera[i + 3] = 0;\n if (!(dark && upper)) lash[i + 3] = 0;\n if (dark && !upper) lowerInk = true;\n else lashLower[i + 3] = 0;\n }\n }\n const region = {\n x: minX,\n y: minY,\n w: maxX - minX + 1,\n h: maxY - minY + 1,\n };\n return {\n sclera: await cropToBuffer(sclera, W, H, region),\n lash: await cropToBuffer(lash, W, H, region),\n lashLower: lowerInk ? await cropToBuffer(lashLower, W, H, region) : null,\n };\n}\n\n/** Whether any pixel is not fully opaque. An alpha channel alone proves\n * nothing: an image saved as RGBA can still be opaque on its white ground. */\nfunction hasTransparency(rgba: Buffer): boolean {\n for (let p = 3; p < rgba.length; p += 4) if (rgba[p] < 255) return true;\n return false;\n}\n\n/**\n * The lip set's two sources, keyed and prepared, or `undefined` for the legacy\n * mouth. Opt-in like the arms: both files present is the set, neither is the\n * legacy route, and one without the other, or either beside the legacy\n * drawings, is refused (auto_rig_from_layers refuses the mix; the composer\n * refuses it first, naming what to remove). Both are decoded here, at source\n * resolution, because the key reads the antialiasing of the source's own\n * pixels (./compose-lips); a part with no alpha has its white ground keyed\n * first.\n */\nasync function prepLipSources(\n partsDir: string,\n mirrored: Set<string>,\n): Promise<\n | {\n keyedPng: Buffer;\n interior: { png: Buffer; cavity: [number, number, number] };\n }\n | undefined\n> {\n const has = (name: string) => fs.existsSync(path.join(partsDir, name));\n const keyed = has(KEYED_SRC);\n const interior = has(INTERIOR_SRC);\n if (keyed && !interior) {\n throw new AutoRigInputError(\n `${KEYED_SRC} needs ${INTERIOR_SRC}: the composer fits the drawn interior into the keyed opening — draw it (billed)`,\n );\n }\n if (interior && !keyed) {\n throw new AutoRigInputError(\n `${INTERIOR_SRC} needs ${KEYED_SRC}: the composer cuts the lip set from the keyed open mouth and fits the interior into its opening — draw it (billed)`,\n );\n }\n if (!keyed) return undefined;\n const legacy = [\"mouth.png\", \"mouth_open.png\"].filter(has);\n if (legacy.length > 0) {\n throw new AutoRigInputError(\n `${KEYED_SRC}/${INTERIOR_SRC} cannot be composed beside mouth.png/mouth_open.png (the lip set replaces the mouth drawings, and auto_rig_from_layers refuses the mix) — remove ${legacy.join(\" and \")}`,\n );\n }\n\n const k = await decodePng(path.join(partsDir, KEYED_SRC));\n const keyedRgba = keyGreen(\n hasTransparency(k.rgba) ? k.rgba : keyWhiteToAlpha(k.rgba),\n k.width,\n k.height,\n );\n const i = await decodePng(path.join(partsDir, INTERIOR_SRC));\n const prepared = await prepInterior(\n hasTransparency(i.rgba)\n ? i.rgba\n : keyBorderWhite(i.rgba, i.width, i.height),\n i.width,\n i.height,\n );\n return {\n keyedPng: await sharp(keyedRgba, {\n raw: { width: k.width, height: k.height, channels: 4 },\n })\n .png()\n .toBuffer(),\n interior: mirrored.has(INTERIOR_SRC)\n ? { ...prepared, png: await sharp(prepared.png).flop().png().toBuffer() }\n : prepared,\n };\n}\n\n/**\n * Compose a parts directory into role-named layers plus a flattened preview,\n * then measure the result so the caller sees the geometry checks inline.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) →\n * `{ ok:false }`, matching autoRigFromLayers; any other throw propagates.\n */\nexport async function composeLayersFromParts(\n input: ComposeInput,\n): Promise<ComposeResult> {\n try {\n // Resolve the output dir FIRST (fail-fast): reject a missing or escaping\n // target before spending the decode budget on a run that cannot be written.\n const outDir = resolveOutputDir(input.outDir);\n const partsDir = resolveInputDir(input.partsDir);\n // resolveOutputDir already realpath's outDir; resolveInputDir does not (its\n // reads are deliberately unconfined), so realpath partsDir here too before\n // comparing — otherwise a symlink alias of the same directory would slip\n // past a lexical check. Composing a parts dir into itself would overwrite\n // originals like face.png/hair_front.png with resized, cropped layers, and\n // skipped-role cleanup would delete sources with no surviving part.\n if (fs.realpathSync(partsDir) === outDir) {\n throw new AutoRigInputError(\n `partsDir and outDir resolve to the same directory (${outDir}): composing would overwrite the source parts`,\n );\n }\n // Before anything decodes, like every other input check.\n const canvas: Canvas = {\n width: CANVAS,\n height: resolveCanvasHeight(input.canvasHeight),\n };\n const layout = resolveLayout(input.layout, canvas);\n const mirrored = resolveMirrorParts(input.mirrorParts);\n\n const split = await prepEyeSplit(partsDir);\n const splitSources = new Map<string, Buffer>([\n [\"eyewhite_sclera.png\", split.sclera],\n [\"eyewhite_lash.png\", split.lash],\n ]);\n if (split.lashLower !== null) {\n splitSources.set(LOWER_LASH_SRC, split.lashLower);\n }\n\n const lips = await prepLipSources(partsDir, mirrored);\n // The set's split, stashed where mouth_inner is placed for the two lip\n // layers cut on the same frame.\n let lipSplit:\n | {\n split: Awaited<ReturnType<typeof splitLipSet>>;\n w: number;\n h: number;\n left: number;\n top: number;\n }\n | undefined;\n\n // Place every role before writing any: a rejected placement must leave\n // outDir as the last compose left it, not half overwritten.\n const placed: {\n role: LayerRole;\n part: { buf: Buffer; w: number; h: number };\n left: number;\n top: number;\n /** An arm's, for a pose forearm to hang from: the rig's elbow pivot on\n * the canvas and the elbow seam's run, px. */\n elbow?: { x: number; y: number };\n elbowRun?: number;\n }[] = [];\n const skipped: LayerRole[] = [];\n // Compose's verdict on the nose's source part when its core was a speck,\n // for the report; otherwise the report judges the composed nose layer.\n let noseSpeck: NoseSpeck | undefined;\n for (const role of ORDER) {\n // With the lip set, mouth and mouth_open are neither placed nor listed in\n // `skipped`: the set stands in for them.\n if (lips !== undefined && (role === \"mouth\" || role === \"mouth_open\")) {\n continue;\n }\n if (role === \"mouth_inner\") {\n // Opt-in like the arms: without the lip set, nothing to place.\n if (lips === undefined) continue;\n const cfg = layout.mouth_inner;\n // Never null: the keyed part is in memory.\n const part = (await partBuffer(\n role,\n cfg,\n partsDir,\n lips.keyedPng,\n mirrored.has(KEYED_SRC),\n canvas,\n ))!;\n const split = await splitLipSet(\n part.buf,\n part.w,\n part.h,\n lips.interior,\n );\n const { left, top } = placement(role, cfg, part.w, part.h, canvas);\n lipSplit = { split, w: part.w, h: part.h, left, top };\n placed.push({\n role,\n part: { buf: split.inner, w: part.w, h: part.h },\n left,\n top,\n });\n continue;\n }\n if (\n role === \"mouth_tongue\" ||\n role === \"mouth_teeth\" ||\n role === \"lip_lower\" ||\n role === \"lip_upper\"\n ) {\n if (lipSplit === undefined) continue;\n const { split, w, h, left, top } = lipSplit;\n const buf = {\n mouth_tongue: split.tongue,\n mouth_teeth: split.teeth,\n lip_lower: split.lower,\n lip_upper: split.upper,\n }[role];\n // An interior with no light paint has no tongue or teeth to cut.\n if (isLipInsideRole(role) && !(await hasCoverage(buf))) {\n skipped.push(role);\n continue;\n }\n placed.push({ role, part: { buf, w, h }, left, top });\n continue;\n }\n // A lower lash is placed by its eye's layout, on the sclera's frame.\n const lower = role === \"lash_lower_L\" || role === \"lash_lower_R\";\n const key: Role = lower ? LOWER_LASH[role] : role;\n if (lower && split.lashLower === null) {\n skipped.push(role);\n continue;\n }\n if (key === \"arm_L\" || key === \"arm_R\") {\n const arm = layout[key];\n // Arms are opt-in: a parts dir without arm.png composes as a bust\n // does, the arms neither placed nor listed in `skipped`.\n if (!fs.existsSync(path.join(partsDir, arm.src))) continue;\n const body = placed.find((p) => p.role === \"body\");\n if (body === undefined) {\n throw new AutoRigInputError(\n \"arm.png: an arm needs body.png — the composer hangs each arm on the body's shoulder, and auto_rig_from_layers hangs it from the body\",\n );\n }\n const w = arm.w ?? Math.max(1, Math.round(ARM_WIDTH * body.part.w));\n // Never null: the part is there, checked above.\n const part = (await partBuffer(\n role,\n { ...arm, w },\n partsDir,\n undefined,\n mirrored.has(arm.src),\n canvas,\n ))!;\n const { left, top, elbow, elbowRun } = await armPlacement(\n key,\n arm,\n part,\n {\n left: body.left,\n top: body.top,\n w: body.part.w,\n h: body.part.h,\n },\n );\n const unset = ([\"cx\", \"cy\"] as const).filter(\n (field) => arm[field] === undefined,\n );\n assertOnCanvas(\n unset.length === 0\n ? `layout.${key}.cx/cy`\n : `layout.${key}.cx/cy (${unset.join(\"/\")} unset: its shoulder pivot hangs on the shoulder corner of layout.body's box)`,\n part.w,\n part.h,\n left,\n top,\n canvas,\n );\n placed.push({ role, part, left, top, elbow, elbowRun });\n continue;\n }\n if (key === \"forearm_pose_L\" || key === \"forearm_pose_R\") {\n const pose = layout[key];\n // Opt-in like the arms: neither placed nor listed in `skipped`.\n if (!fs.existsSync(path.join(partsDir, pose.src))) continue;\n const armRole = key === \"forearm_pose_L\" ? \"arm_L\" : \"arm_R\";\n const arm = placed.find((p) => p.role === armRole);\n if (arm?.elbow === undefined || arm.elbowRun === undefined) {\n throw new AutoRigInputError(\n \"forearm_pose.png: a pose forearm needs arm.png — the composer pins it on the arm's elbow, and auto_rig_from_layers hangs it from the arm\",\n );\n }\n // Never null: the part is there, checked above.\n const trimmed = (await trimmedPart(\n role,\n pose,\n partsDir,\n undefined,\n mirrored.has(pose.src),\n ))!;\n const w =\n pose.w ?? (await forearmPoseWidth(key, trimmed, arm.elbowRun));\n let part;\n try {\n part = await sizedPart(role, { ...pose, w }, trimmed, canvas);\n } catch (err) {\n // A derived w the user never set is not blamed on the layout key.\n if (pose.w === undefined && err instanceof AutoRigInputError) {\n throw new AutoRigInputError(\n err.message.replace(\n `layout.${role}.w:`,\n `layout.${role}.w (unset: scaled to ${armRole}'s elbow run):`,\n ),\n );\n }\n throw err;\n }\n const { left, top } = await forearmPosePlacement(\n key,\n pose,\n part,\n arm.elbow,\n );\n const unset = ([\"cx\", \"cy\"] as const).filter(\n (field) => pose[field] === undefined,\n );\n assertOnCanvas(\n unset.length === 0\n ? `layout.${key}.cx/cy`\n : `layout.${key}.cx/cy (${unset.join(\"/\")} unset: its elbow-end pivot hangs on the elbow of layout.${armRole}'s placed arm)`,\n part.w,\n part.h,\n left,\n top,\n canvas,\n );\n placed.push({ role, part, left, top });\n continue;\n }\n const cfg = lower ? { ...layout[key], src: LOWER_LASH_SRC } : layout[key];\n const inMemory = splitSources.get(cfg.src);\n const part = await partBuffer(\n role,\n cfg,\n partsDir,\n inMemory,\n // The split halves are cut from eyewhite.png, the file a caller names.\n mirrored.has(inMemory === undefined ? cfg.src : EYEWHITE_SRC),\n canvas,\n );\n // A lower lid too faint for the alpha the rig reads coverage at, or\n // that the resize erased, would be a layer it refuses as empty.\n if (part === null || (lower && !(await hasCoverage(part.buf)))) {\n skipped.push(role);\n continue;\n }\n // The nose is placed by the box it was sized by. A whole part that stood\n // in is placed by the resized part's own bounds. A core is measured\n // again on the resized part rather than scaled, since resampling moves\n // its edges and the tip rule lands its exact bottom row — and is not\n // judged again here: the source part's verdict decided how it was sized.\n let left: number;\n let top: number;\n if (key === \"nose\") {\n noseSpeck = part.nose?.speck;\n const { core, bounds } = await coreAndBoundsOf(part.buf);\n const box = part.nose?.whole ? bounds : (core ?? bounds);\n ({ left, top } = nosePlacement(\n layout,\n lips === undefined ? \"mouth\" : \"mouth_inner\",\n box,\n part.w,\n part.h,\n canvas,\n ));\n } else {\n ({ left, top } = placement(key, layout[key], part.w, part.h, canvas));\n }\n // The eye pair's halves are cut from one eyewhite into one frame. Set\n // apart, the blink fold tears — and a lash narrowed inside its sclera\n // still lies on it and inks its top row, so nothing in the composed\n // layers would show it. Compared as placed, not as set: an h equal to\n // the one the aspect gives lands on the same frame as leaving it unset.\n if (role === \"lash_L\" || role === \"lash_R\") {\n const eyeRole = role === \"lash_L\" ? \"eye_L\" : \"eye_R\";\n const eye = placed.find((p) => p.role === eyeRole);\n if (\n eye !== undefined &&\n (eye.left !== left ||\n eye.top !== top ||\n eye.part.w !== part.w ||\n eye.part.h !== part.h)\n ) {\n throw new AutoRigInputError(\n `layout.${role} places the lash at ${part.w}x${part.h} (${left},${top}), but layout.${eyeRole} ` +\n `places its sclera at ${eye.part.w}x${eye.part.h} (${eye.left},${eye.top}) — they are cut from one ` +\n `eyewhite into one frame, and the blink fold tears where they part. Set cx/cy/w/h the same on both.`,\n );\n }\n }\n placed.push({ role, part, left, top });\n }\n\n // Every layer is built, and the closed lip preview measured from them,\n // before the first sweep or write: a lip layer the canvas clips away is\n // refused with outDir as the last compose left it.\n const built = new Map<LayerRole, Buffer>();\n for (const { role, part, left, top } of placed) {\n // role layer: this part alone on a full canvas at its position.\n built.set(\n role,\n await blankCanvas(canvas)\n .composite([{ input: part.buf, left, top }])\n .png()\n .toBuffer(),\n );\n }\n // The preview shows the lip set shut by the field the rig's own\n // measurement of the written layers gives, as it draws the rest pose.\n const closed =\n lipSplit === undefined\n ? undefined\n : await closedLips(\n lipSplit.split.upper,\n lipSplit.split.lower,\n await restShiftOf(\n {\n mouth_inner: built.get(\"mouth_inner\")!,\n lip_lower: built.get(\"lip_lower\")!,\n lip_upper: built.get(\"lip_upper\")!,\n },\n canvas.width,\n canvas.height,\n ),\n lipSplit.left,\n lipSplit.top,\n );\n\n // Drop the layer an earlier compose into the same dir wrote for each role\n // this run does not write — a skipped one, or an arm once arm.png is\n // gone: left behind it would contradict the result, since measureDir\n // globs the directory (the report would still show a body) and the next\n // auto_rig_from_layers would rig the stale file into the model. Only the\n // fixed ORDER role names, under the confined outDir, are ever removed.\n for (const role of ORDER) {\n if (placed.some((p) => p.role === role)) continue;\n fs.rmSync(path.join(outDir, `${role}.png`), { force: true });\n }\n // The pose preview exists only with a pose forearm, so it is swept with\n // the layers: left behind it would show a forearm the layers no longer\n // hold.\n const posed = (role: LayerRole) =>\n role === \"forearm_pose_L\" || role === \"forearm_pose_R\";\n if (!placed.some((p) => posed(p.role))) {\n fs.rmSync(path.join(outDir, \"preview-pose.png\"), { force: true });\n }\n const layers: ComposedLayer[] = [];\n for (const { role, part, left, top } of placed) {\n const outPath = path.join(outDir, `${role}.png`);\n writeFileAtomic(outPath, built.get(role)!);\n layers.push({\n role,\n path: outPath,\n width: part.w,\n height: part.h,\n left,\n top,\n });\n }\n // What a role contributes to a rest-pose preview: the lips shut, the\n // interior and what it clips left out (shut, it has no height); null for\n // nothing.\n const restInput = (role: LayerRole, buf: Buffer): Buffer | null => {\n if (role === \"mouth_inner\" || isLipInsideRole(role)) return null;\n if (closed === undefined) return buf;\n if (role === \"lip_upper\") return closed.upper;\n if (role === \"lip_lower\") return closed.lower;\n return buf;\n };\n const preview: { input: Buffer; left: number; top: number }[] = [];\n for (const { role, part, left, top } of placed) {\n const input = restInput(role, part.buf);\n if (!posed(role) && input !== null) preview.push({ input, left, top });\n }\n\n // Flattened preview over a light bg so transparency reads clearly.\n const previewPng = await sharp({\n create: {\n width: canvas.width,\n height: canvas.height,\n channels: 4,\n background: { r: 245, g: 245, b: 248, alpha: 1 },\n },\n })\n .composite(preview)\n .png()\n .toBuffer();\n const previewPath = path.join(outDir, \"preview.png\");\n writeFileAtomic(previewPath, previewPng);\n\n // The switch at 1, as the rig draws it: an arm whose side has a pose\n // forearm keeps the rows above its elbow (the upper arm and the sleeve;\n // the hanging forearm hides), and the pose forearms, last in `placed`,\n // draw over everything.\n let previewPosePath: string | undefined;\n if (placed.some((p) => posed(p.role))) {\n const pose: { input: Buffer; left: number; top: number }[] = [];\n for (const { role, part, left, top, elbow } of placed) {\n const armPosed =\n elbow !== undefined &&\n placed.some(\n (p) =>\n p.role ===\n (role === \"arm_L\" ? \"forearm_pose_L\" : \"forearm_pose_R\"),\n );\n if (!armPosed) {\n const input = restInput(role, part.buf);\n if (input !== null) pose.push({ input, left, top });\n continue;\n }\n const rows = Math.min(part.h, Math.max(1, Math.round(elbow.y - top)));\n pose.push({\n input: await sharp(part.buf)\n .extract({ left: 0, top: 0, width: part.w, height: rows })\n .png()\n .toBuffer(),\n left,\n top,\n });\n }\n const posePng = await sharp({\n create: {\n width: canvas.width,\n height: canvas.height,\n channels: 4,\n background: { r: 245, g: 245, b: 248, alpha: 1 },\n },\n })\n .composite(pose)\n .png()\n .toBuffer();\n previewPosePath = path.join(outDir, \"preview-pose.png\");\n writeFileAtomic(previewPosePath, posePng);\n }\n\n return {\n ok: true,\n outDir,\n layers,\n skipped,\n preview: previewPath,\n ...(previewPosePath === undefined\n ? {}\n : { previewPose: previewPosePath }),\n measure: await measureDir(outDir, noseSpeck),\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n","/**\n * The trim the composer cuts every part by, shared with the lip set's interior:\n * the alpha a trim keeps, and the stray specks a background removal leaves\n * beside a drawing.\n */\n\nimport { ALPHA_OPAQUE } from \"@ikijs/editor\";\n\n/** The alpha a part's trim cuts at: what it keeps is over this. */\nexport const TRIM_THRESHOLD = 12;\n/** Of a part's kept pixels, the share under which a faint detached set is a stray speck. */\nexport const STRAY_SPECK_FRACTION = 0.01;\n\n/** Luma (0..255) of the RGBA pixel at byte offset `i`. */\nexport function luma(rgba: Buffer, i: number): number {\n return 0.299 * rgba[i] + 0.587 * rgba[i + 1] + 0.114 * rgba[i + 2];\n}\n\n/**\n * The box of a trimmed part without its stray specks, or null when no stray\n * speck lies outside its drawing. The part's kept pixels (alpha over\n * TRIM_THRESHOLD, the trim's own cut) form 8-connected sets; a stray speck is\n * a set that never reaches ALPHA_OPAQUE and holds under STRAY_SPECK_FRACTION of\n * them, the residue a background removal leaves beside a drawing. Kept, one\n * such speck widened a generated body's box by 70 px on one side and placed\n * the body 32 px off its centre. A drawn stroke reaches ALPHA_OPAQUE, so a\n * detached wisp or strand is never dropped, and a part painted wholly under\n * it (a soft blush) drops nothing.\n */\nexport function boxWithoutStraySpecks(\n rgba: Buffer,\n W: number,\n H: number,\n): { left: number; top: number; width: number; height: number } | null {\n const n = W * H;\n // The share is of the whole part, so count it before any set is judged.\n let kept = 0;\n for (let p = 0; p < n; p++) if (rgba[p * 4 + 3] > TRIM_THRESHOLD) kept++;\n // Each set is judged as its fill ends and only its box is kept, so memory\n // is a byte per pixel plus a stack grown to the deepest fill, not a label\n // per pixel and a record per set. A pixel is marked as it is pushed, so the\n // stack never outgrows the image.\n const visited = new Uint8Array(n);\n let stack = new Int32Array(1024);\n // [left, top, right, bottom] of the drawing's sets and of the stray ones.\n const drawing = [W, H, -1, -1];\n const strays = [W, H, -1, -1];\n let anyOpaque = false;\n for (let start = 0; start < n; start++) {\n if (visited[start] || rgba[start * 4 + 3] <= TRIM_THRESHOLD) continue;\n let setLeft = W;\n let setTop = H;\n let setRight = -1;\n let setBottom = -1;\n let size = 0;\n let opaque = false;\n let depth = 0;\n visited[start] = 1;\n stack[depth++] = start;\n while (depth > 0) {\n const p = stack[--depth];\n size++;\n if (rgba[p * 4 + 3] >= ALPHA_OPAQUE) opaque = true;\n const px = p % W;\n const py = (p - px) / W;\n setLeft = Math.min(setLeft, px);\n setTop = Math.min(setTop, py);\n setRight = Math.max(setRight, px);\n setBottom = Math.max(setBottom, py);\n for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {\n for (let x = Math.max(0, px - 1); x <= Math.min(W - 1, px + 1); x++) {\n const q = y * W + x;\n if (!visited[q] && rgba[q * 4 + 3] > TRIM_THRESHOLD) {\n visited[q] = 1;\n if (depth === stack.length) {\n const grown = new Int32Array(Math.min(n, stack.length * 2));\n grown.set(stack);\n stack = grown;\n }\n stack[depth++] = q;\n }\n }\n }\n }\n anyOpaque ||= opaque;\n const into =\n !opaque && size < kept * STRAY_SPECK_FRACTION ? strays : drawing;\n into[0] = Math.min(into[0], setLeft);\n into[1] = Math.min(into[1], setTop);\n into[2] = Math.max(into[2], setRight);\n into[3] = Math.max(into[3], setBottom);\n }\n if (!anyOpaque || strays[2] < 0) return null;\n const [left, top, right, bottom] = drawing;\n // A set's box reaches past the drawing's only where one of its pixels does,\n // and a speck inside the drawing's box moves nothing, so it is left be.\n if (\n strays[0] >= left &&\n strays[1] >= top &&\n strays[2] <= right &&\n strays[3] <= bottom\n )\n return null;\n return { left, top, width: right - left + 1, height: bottom - top + 1 };\n}\n","/**\n * Measure composed Iki role layers and flag the failure modes that have\n * actually shipped broken characters. Read-only: it never edits anything.\n *\n * Ports the geometry checks that shipped as a script in the Claude Code plugin,\n * so a plugin user gets them from the MCP server instead of an ad-hoc `sharp`\n * install. They exist because \"the eyes look too big\" is not actionable but\n * \"the iris is 33% of the sclera width, target 0.45-0.72\" is. Every check below\n * is one that cost a real regeneration or re-tune round to find by eye.\n *\n * `sharp` must stay confined to @ikijs/mcp; the decode goes through\n * ./node-images, this package's single image-decode boundary.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { decodePng, detectAlphaBbox } from \"./node-images\";\nimport { AutoRigInputError, MAX_LAYERS, resolveInputDir } from \"./limits\";\nimport { ARM_ROLES, armWarnings } from \"./measure-arms\";\nimport { POSE_ROLES, forearmPoseWarnings } from \"./measure-forearm-pose\";\nimport { isLipLayerRole, lipWarnings, type LipFacts } from \"./measure-lips\";\nimport { SPECK_CORE_FRACTION, denseCoreOf, isSpeckCore } from \"./measure-turn\";\n\n// Iris width as a fraction of sclera width. Below the floor the eye reads as a\n// bead floating in white — that is the failure this check was written for, and\n// it caught a model that shipped at 0.33. The ceiling was a guess and it was\n// too tight: measured on a real anime reference the iris runs about 0.70 of the\n// eye, with the white reduced to corner crescents, so 0.6 flagged the correct\n// value as a fault three rounds running.\nconst IRIS_RATIO_MIN = 0.45;\nconst IRIS_RATIO_MAX = 0.72;\n// A sclera flatter than this cannot hold a round iris: the iris overflows the\n// lids no matter how narrow it is.\nconst EYE_ASPECT_MIN = 0.5;\n// How far the iris centre may sit from the white's centre of mass. The two axes\n// are not the same problem. Sideways drift is always a fault — that is the bug\n// this check was written for, a lash that fell out of sync with its sclera by\n// 14px. Vertically the reference itself rides its iris HIGH, tucked under the\n// lash with roughly a sixth of the aperture showing as white below it, so a\n// deliberate lift of that order is correct and a 3px ceiling flagged it.\nconst IRIS_OFFSET_MAX_X = 3;\nconst IRIS_OFFSET_MAX_Y = 10;\n// A cropped part shows a long, nearly-continuous opaque run along one bbox edge,\n// and that straight seam appears the moment the head turns. A round part's edge\n// row is a short tangent run, so a fraction test alone flags every iris; both a\n// high fraction AND real length are required to separate the two. Observed:\n// genuine crops read 60-93%, circle tangents 8-14%.\nconst EDGE_SOLID_MAX = 0.5;\n/** Share of a lash's opaque pixels tolerated off its sclera. In sync there\n * are none — the sclera was recoloured from those very pixels. A real eye\n * measured 0 of 934 in sync, then 6-12 at a 1 px drift, 45-50 at 2 px and\n * 104-110 at 4 px, whichever way it drifted. */\nconst LASH_STRAY_TOL_FRAC = 0.02;\n/** How much further short of the outer corner than of the nose side an eye's\n * lash may stop, as a fraction of the eye width, before the eye reads as\n * drawn facing the other way. Three real eyewhites drawn reversed stopped\n * 4.0-6.1% further short there; one drawn the right way stops short at the\n * nose side instead, and one with a wing at each end at neither. */\nconst EYE_FACING_TOL_FRAC = 0.02;\nconst EDGE_RUN_MIN_PX = 40;\n// Longest straight \"art appears out of nothing\" run tolerated inside a part, as\n// a fraction of its width. A body generated with hair draped over the shoulders\n// had that hair cut flat by its own frame; the cut hid behind the head at rest\n// and opened into a seam on turn. Measured: that part ran 15% of its width,\n// a clean one 5%, so the boundary sits between them.\nconst FLAT_CUT_MAX_FRAC = 0.1;\n// ...and long in absolute terms. A mouth's upper lip is a naturally horizontal\n// run that clears the fraction test on a narrow part while being only ~15px.\nconst FLAT_CUT_MIN_PX = 40;\n// The cut is antialiased, so the transition is a soft cliff rather than\n// transparent-to-opaque; 8/200 finds nothing at all on real art.\nconst FLAT_CUT_ALPHA_ABOVE = 120;\nconst FLAT_CUT_ALPHA_BELOW = 140;\n\n/** Alpha-derived geometry of one layer, in canvas pixels. */\nexport interface LayerStats {\n w: number;\n h: number;\n /** Longest flat cut through the art, and the row it runs along (-1 if none). */\n flatCutRun: number;\n flatCutY: number;\n bboxCx: number;\n bboxCy: number;\n massCx: number;\n massCy: number;\n /** Distance from the layer's content to each canvas edge. */\n marginTop: number;\n marginBottom: number;\n marginLeft: number;\n marginRight: number;\n /** Fraction of each bbox edge that is opaque. */\n edgeTop: number;\n edgeBottom: number;\n edgeLeft: number;\n edgeRight: number;\n canvasW: number;\n canvasH: number;\n}\n\nexport interface MeasureReport {\n /** Measured stats by role (the layer's file name without `.png`). */\n layers: Record<string, LayerStats>;\n /** Roles whose PNG is fully transparent — nothing to measure. */\n empty: string[];\n warnings: string[];\n /**\n * The lip set's opening as the rig reads it, set whenever the three lip\n * layers are present and readable. The fold's dead zone `deadZone` is the\n * `MouthOpen` below which the slit between the lips has not opened, and\n * it varies with the drawing (0.03 on one opening, 0.26 on another), so a\n * half-open mouth that shows no slit is judged against it, not against a\n * fixed number.\n */\n lips?: LipFacts;\n}\n\nexport type MeasureResult =\n | ({ ok: true; layersDir: string; passed: boolean } & MeasureReport)\n | { ok: false; error: string };\n\nexport interface MeasureInput {\n /** Directory of role-named layer PNGs (relative paths resolve against cwd). */\n layersDir: string;\n}\n\n/**\n * Scan one layer PNG's alpha channel. Returns null for a fully transparent\n * layer. A decode failure surfaces as a path-qualified AutoRigInputError.\n */\nexport async function layerStats(filePath: string): Promise<LayerStats | null> {\n const { width: W, height: H, rgba } = await decodePng(filePath);\n const alpha = (x: number, y: number) => rgba[(y * W + x) * 4 + 3];\n\n let minX = W;\n let minY = H;\n let maxX = -1;\n let maxY = -1;\n let sumX = 0;\n let sumY = 0;\n let n = 0;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n if (alpha(x, y) > 8) {\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n sumX += x;\n sumY += y;\n n++;\n }\n }\n }\n if (maxX < 0) return null; // fully transparent\n\n const edge = (pts: number[]) =>\n pts.filter((v) => v > 200).length / pts.length;\n const top: number[] = [];\n const bottom: number[] = [];\n const left: number[] = [];\n const right: number[] = [];\n for (let x = minX; x <= maxX; x++) {\n top.push(alpha(x, minY));\n bottom.push(alpha(x, maxY));\n }\n for (let y = minY; y <= maxY; y++) {\n left.push(alpha(minX, y));\n right.push(alpha(maxX, y));\n }\n\n // Longest contiguous run of pixels where the art appears out of nothing along\n // one row — transparent above, opaque below. Organic art (hair, cloth) meets\n // its silhouette at an angle, so a long FLAT run like this means the source\n // image was cropped through the drawing. It is often interior to the bbox\n // (a hair strand cut short above a wider shoulder line), which is why the\n // bbox-edge test alone misses it, and it only becomes visible once the head\n // turns and uncovers the cut.\n let flatCutRun = 0;\n let flatCutY = -1;\n for (let y = minY + 1; y <= maxY; y++) {\n let run = 0;\n for (let x = minX; x <= maxX; x++) {\n if (\n alpha(x, y - 1) < FLAT_CUT_ALPHA_ABOVE &&\n alpha(x, y) > FLAT_CUT_ALPHA_BELOW\n ) {\n run++;\n if (run > flatCutRun) {\n flatCutRun = run;\n flatCutY = y;\n }\n } else {\n run = 0;\n }\n }\n }\n\n return {\n w: maxX - minX + 1,\n h: maxY - minY + 1,\n flatCutRun,\n flatCutY,\n bboxCx: (minX + maxX) / 2,\n bboxCy: (minY + maxY) / 2,\n massCx: sumX / n,\n massCy: sumY / n,\n marginTop: minY,\n marginBottom: H - 1 - maxY,\n marginLeft: minX,\n marginRight: W - 1 - maxX,\n edgeTop: edge(top),\n edgeBottom: edge(bottom),\n edgeLeft: edge(left),\n edgeRight: edge(right),\n canvasW: W,\n canvasH: H,\n };\n}\n\nconst pct = (v: number) => `${(v * 100).toFixed(0)}%`;\n\n/** An arm's seams show once it raises, every other part's on the head turn. A\n * pose forearm raises with its arm, and shows only once the switch is on. */\nconst isArm = (role: string) =>\n (ARM_ROLES as readonly string[]).includes(role) ||\n (POSE_ROLES as readonly string[]).includes(role);\n\n/** A nose's dense core that `isSpeckCore` judged a speck of its part, as sizes\n * in px: compose's verdict on the trimmed source part, or the composed\n * layer's against its crop. */\nexport interface NoseSpeck {\n core: { w: number; h: number };\n part: { w: number; h: number };\n}\n\n/**\n * The nose-speck warning. Each source says only what its own reader did:\n * `\"compose\"` judged the trimmed source part, before resampling, and composed\n * it whole; `\"layer\"` judged the layer file against its crop, which is what\n * `auto_rig_from_layers` reads. The remedy is the same either way.\n */\nfunction noseSpeckWarning(\n { core, part }: NoseSpeck,\n source: \"compose\" | \"layer\",\n): string {\n const [found, consequence] =\n source === \"compose\"\n ? [\n `the source part's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} trimmed part`,\n `compose_layers_from_parts sized and placed the whole part instead — layout.nose's w and h now size it, feather included`,\n ]\n : [\n `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,\n `auto_rig_from_layers turns and tilts the nose about its whole crop instead`,\n ];\n return (\n `nose: ${found} — under ${SPECK_CORE_FRACTION} of its width or height, a speck: a lone nostril ` +\n `mark or highlight at alpha >= 128, not the drawing, so ${consequence}. Regenerate the nose with ` +\n `its shading painted denser, so the drawing itself reaches alpha 128. Billed.`\n );\n}\n\n/**\n * Count the lash's opaque pixels, and those of them that land where its\n * sclera is transparent. Both are canvas-sized layers, so a pixel's position\n * is the same canvas point in each.\n */\nasync function lashOffSclera(\n eyePath: string,\n lashPath: string,\n): Promise<{ opaque: number; off: number }> {\n const eye = await decodePng(eyePath);\n const lash = await decodePng(lashPath);\n let opaque = 0;\n let off = 0;\n for (let y = 0; y < lash.height; y++) {\n for (let x = 0; x < lash.width; x++) {\n if (lash.rgba[(y * lash.width + x) * 4 + 3] < 128) continue;\n opaque++;\n const onEye = x < eye.width && y < eye.height;\n if (!onEye || eye.rgba[(y * eye.width + x) * 4 + 3] <= 8) off++;\n }\n }\n return { opaque, off };\n}\n\n/**\n * Measure every `*.png` in an already-resolved layers directory but the\n * `preview*.png` ones (`preview.png` is the composer's contact sheet, and a\n * caller's own previews sit beside it; none is a role) and run the geometry\n * checks.\n * `noseSpeck` is compose's own verdict on the nose's source part when that\n * part's core was a speck, and the nose check reports it as given. Left out —\n * compose found no speck, or `measure_layers` — that check judges the `nose`\n * layer file against its crop instead, as `auto_rig_from_layers` does.\n */\nexport async function measureDir(\n absDir: string,\n noseSpeck?: NoseSpeck,\n): Promise<MeasureReport> {\n const files = fs\n .readdirSync(absDir)\n .filter((f) => f.endsWith(\".png\") && !f.startsWith(\"preview\"))\n .sort();\n if (files.length === 0) {\n throw new AutoRigInputError(`no role layers in ${absDir}`);\n }\n // Same agent-supplied-input surface autoRigFromLayers bounds: a `layersDir`\n // pointed at an asset folder would decode every PNG in it before reporting.\n if (files.length > MAX_LAYERS) {\n throw new AutoRigInputError(\n `too many layers in ${absDir}: ${files.length} > ${MAX_LAYERS}`,\n );\n }\n\n const layers: Record<string, LayerStats> = {};\n const empty: string[] = [];\n for (const f of files) {\n const role = path.basename(f, \".png\");\n const m = await layerStats(path.join(absDir, f));\n if (!m) {\n empty.push(role);\n continue;\n }\n layers[role] = m;\n }\n\n const warnings: string[] = [];\n\n // 1. Art running to its own edge → a straight seam appears on head turn.\n // Two very different faults look identical in the flattened layer, and the\n // remedies cost differently, so tell them apart before prescribing one: a\n // part the CANVAS clipped has no margin left on that side (retune, free),\n // while a part placed with room whose own drawing runs to its frame does\n // (regenerate, billed). A real run lost a regeneration to this: the source\n // kept 44 px of margin and the default layout pushed it 70 px off-canvas,\n // so redrawing it reproduced the clip exactly.\n for (const [role, m] of Object.entries(layers)) {\n // A lip layer's straight edges are the split's cuts, not the art's; the\n // lip checks read what the rig does with them.\n if (isLipLayerRole(role)) continue;\n const edges: [string, number, number, number][] = [\n [\"top\", m.edgeTop, m.w, m.marginTop],\n [\"left\", m.edgeLeft, m.h, m.marginLeft],\n [\"right\", m.edgeRight, m.h, m.marginRight],\n ];\n // A bust's torso is meant to run off the bottom of a square canvas. A\n // full body stands on a taller one with its soles inside it, where two\n // soles' flat bottoms could trip the generic check, so a check of its own\n // replaces it: paint on the canvas's last row is feet cut off.\n if (role !== \"body\") {\n edges.push([\"bottom\", m.edgeBottom, m.w, m.marginBottom]);\n } else if (m.canvasH > m.canvasW && m.marginBottom === 0) {\n warnings.push(\n `body: its bottom row is the canvas's last — on a tall canvas that cuts the feet off. ` +\n `Free fix: raise canvasHeight (the canvas grows downward, nothing else moves) and ` +\n `remeasure; regenerate body.png only if the drawing itself stops short of the soles.`,\n );\n }\n for (const [side, v, span, margin] of edges) {\n if (v > EDGE_SOLID_MAX && v * span >= EDGE_RUN_MIN_PX) {\n const remedy =\n margin === 0\n ? // margin 0 is consistent with a clipped placement AND with art\n // already cropped flush that happens to sit on the boundary, and\n // the flattened layer cannot separate them — so name the free\n // move rather than the cause. If moving it inward leaves the\n // edge opaque, the drawing is the one at fault.\n `it sits flush against the canvas ${side}, which a clipped placement and already-cropped ` +\n `art both produce. Move it inward first — retune layout.${role}.cx/cy/w, free — and ` +\n `remeasure; regenerate only if the edge is still opaque with margin to spare.`\n : `its own drawing runs to the frame ${margin} px inside the canvas — regenerate that part ` +\n `with empty margin on that side. Billed.`;\n warnings.push(\n `${role}: ${pct(v)} of its ${side} edge is opaque — the art is cut off there, ` +\n `which shows as a straight seam ${isArm(role) ? \"once the arm raises\" : \"once the head turns\"}. ` +\n `Cause: ${remedy}`,\n );\n }\n }\n }\n\n // 1b. A straight cut through the drawing, wherever it falls in the bbox.\n for (const [role, m] of Object.entries(layers)) {\n // `body` bends as one drawing, so no pose opens a cut in it; its top is\n // deliberately cut flat where the jaw covers it, and stays under the jaw\n // because the head rides the body.\n if (role === \"body\" || isLipLayerRole(role)) continue;\n if (\n m.flatCutRun > FLAT_CUT_MAX_FRAC * m.w &&\n m.flatCutRun >= FLAT_CUT_MIN_PX\n ) {\n warnings.push(\n `${role}: ${m.flatCutRun}px of straight flat edge at y=${m.flatCutY} ` +\n `(${pct(m.flatCutRun / m.w)} of its width) — the source art is cut through there. ` +\n (isArm(role)\n ? `It hides at rest and opens into a seam once the arm raises. `\n : `It hides while the head faces front and opens into a seam on turn. `) +\n `Regenerate this part with the whole subject inside the frame.`,\n );\n }\n }\n\n // 1c. The arms: each needs a body, and its shoulder cap the torso under it.\n warnings.push(...(await armWarnings(absDir, layers)));\n\n // 1d. The pose forearms: each needs its arm, and its elbow end the arm's elbow.\n warnings.push(...(await forearmPoseWarnings(absDir, layers)));\n\n // 1e. The lip set: the fold's contract per column, the opening's size, the\n // line's weight, key green left, an interior with holes.\n const lip = await lipWarnings(absDir, layers);\n warnings.push(...lip.warnings);\n\n // 2/3/4. Eye stack geometry, per side.\n for (const side of [\"L\", \"R\"]) {\n const eye: LayerStats | undefined = layers[`eye_${side}`];\n const iris: LayerStats | undefined = layers[`iris_${side}`];\n const lash: LayerStats | undefined = layers[`lash_${side}`];\n if (!eye) continue;\n\n const aspect = eye.h / eye.w;\n if (aspect < EYE_ASPECT_MIN) {\n warnings.push(\n `eye_${side}: sclera aspect h/w=${aspect.toFixed(2)} is flatter than ${EYE_ASPECT_MIN} — ` +\n `a round iris cannot sit inside it. Free fix first: set layout.eye_${side}.h and ` +\n `layout.lash_${side}.h to ${Math.ceil(eye.w * EYE_ASPECT_MIN)} (both, or the fold tears) — ` +\n `stretching a flat white lens is invisible. Regenerate the eyewhite taller only if that ` +\n `distorts the lash.`,\n );\n }\n\n if (iris) {\n const ratio = iris.w / eye.w;\n if (ratio < IRIS_RATIO_MIN || ratio > IRIS_RATIO_MAX) {\n warnings.push(\n `iris_${side}: width is ${pct(ratio)} of the sclera (target ${IRIS_RATIO_MIN}-${IRIS_RATIO_MAX}) — ` +\n `retune layout.iris_${side}.w (keep it a fraction of the eye width), no regeneration needed.`,\n );\n }\n const dx = iris.bboxCx - eye.massCx;\n const dy = iris.bboxCy - eye.massCy;\n if (\n Math.abs(dx) > IRIS_OFFSET_MAX_X ||\n Math.abs(dy) > IRIS_OFFSET_MAX_Y\n ) {\n warnings.push(\n `iris_${side}: sits (${dx.toFixed(1)}, ${dy.toFixed(1)}) px from the white's centre of mass — ` +\n `retune layout.iris_${side}.cx/cy. The sclera's bbox centre is NOT its visual centre when the ` +\n `lash flick stretches the box.`,\n );\n }\n }\n\n // 5. The lash and the white are split from ONE source and pasted with the\n // same cx/cy/w, so their frames coincide even though the lash only inks the\n // upper part of it (its content sits higher — that is the fold working, not\n // a fault). In sync, the lash is ink the sclera was recoloured from, so\n // every opaque lash pixel lies on the sclera, and both ink the same top\n // row; a drift moves pixels off it, and a lash scaled down inside it (a w\n // or h out of sync) drops its top row — the seam the fold rides — either\n // way tearing the fold. Neither the ink centres nor the frame's sides can\n // stand in for that: a lash stops short of the tear duct (5b), so a\n // correctly composed eye's ink sits 3-5% of its width off the sclera's\n // centre, while a lash drifting in toward that bare end stays inside the\n // frame.\n //\n // 5b. Which way the eye was drawn. A lash runs out to the outer corner,\n // wing and all, and stops short of the tear duct at the inner one, so in\n // the frame it shares with the sclera it is the nose end that the lash\n // leaves bare. A lash that stops short of the OUTER end instead is an\n // eyewhite drawn facing the other way: the wings point in, and \"left eye\"\n // in a prompt cannot prevent it, since it reads as the viewer's left or\n // the character's. The ends are read, not the ink's centroid: a thin wing\n // widens the frame far more than it moves the centroid, which reads a\n // correctly drawn eye as reversed. Only a lash in sync is read — a drift\n // moves the ends too, and is check 5's to report, not the drawing's.\n if (lash) {\n const { opaque, off } = await lashOffSclera(\n path.join(absDir, `eye_${side}.png`),\n path.join(absDir, `lash_${side}.png`),\n );\n const dTop = lash.marginTop - eye.marginTop;\n const faults = [\n ...(off > opaque * LASH_STRAY_TOL_FRAC\n ? [`${off} of its ${opaque} opaque px lie off eye_${side}'s sclera`]\n : []),\n ...(Math.abs(dTop) > 0.5\n ? [`its top edge is ${dTop.toFixed(1)} px off the sclera's`]\n : []),\n ];\n if (faults.length > 0) {\n warnings.push(\n `lash_${side}: ${faults.join(\" and \")} — they are split from one source and MUST share ` +\n `cx/cy/w/h in layout, or the blink fold tears. Retune to match.`,\n );\n } else {\n // How far short of each side of the frame the lash stops.\n const bareLeft = lash.marginLeft - eye.marginLeft;\n const bareRight = lash.marginRight - eye.marginRight;\n // eye_R is the screen-left eye: its outer corner is its left end.\n const [bareOuter, bareInner] =\n side === \"R\" ? [bareLeft, bareRight] : [bareRight, bareLeft];\n if ((bareOuter - bareInner) / eye.w > EYE_FACING_TOL_FRAC) {\n warnings.push(\n `eye_${side}: its lash stops ${pct(bareOuter / eye.w)} of the eye width short of the outer corner ` +\n `and ${pct(bareInner / eye.w)} short of the nose side — the eyewhite is drawn facing the other way, ` +\n `lash wing at the inner corner. The composer reads eyewhite.png as the eye on the screen LEFT: lash ` +\n `wing at the image's left end, lash-free tear duct at its right. Free fix: compose again with ` +\n `mirrorParts: [\"eyewhite.png\"] — no regeneration.`,\n );\n }\n }\n }\n }\n\n // 6. A nose whose dense core is a speck of its part (`isSpeckCore`). A\n // speck compose found in the source part, before resampling, is reported\n // as given: a dot blurred under alpha 128 no longer shows in the file.\n // Otherwise the file is judged against its crop — what the rig reads —\n // which also catches a core that only resampling made a speck.\n if (noseSpeck !== undefined) {\n warnings.push(noseSpeckWarning(noseSpeck, \"compose\"));\n } else if (layers.nose !== undefined) {\n const nose = await decodePng(path.join(absDir, \"nose.png\"));\n const core = denseCoreOf(nose.rgba, nose.width, nose.height);\n if (core !== null) {\n const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);\n if (isSpeckCore(core, crop))\n warnings.push(noseSpeckWarning({ core, part: crop }, \"layer\"));\n }\n }\n\n // 7. Optional roles that change how finished the character reads.\n for (const [role, why] of [\n [\"body\", \"without it the character reads as a floating head on head-turn\"],\n [\"hair_back\", \"without it the silhouette is flat behind the face\"],\n [\n \"nose\",\n \"without it the head still turns on the default profile, but there is no nose to lead it, and no turn fit to the art (`turnTargets` is inert, no `turn` report)\",\n ],\n ]) {\n if (layers[role] === undefined) warnings.push(`${role}: missing — ${why}.`);\n }\n\n return {\n layers,\n empty,\n warnings,\n ...(lip.lips === undefined ? {} : { lips: lip.lips }),\n };\n}\n\n/**\n * Measure a caller-supplied layers directory.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) →\n * `{ ok:false }`, matching autoRigFromLayers; any other throw propagates.\n */\nexport async function measureLayers(\n input: MeasureInput,\n): Promise<MeasureResult> {\n try {\n const layersDir = resolveInputDir(input.layersDir);\n const report = await measureDir(layersDir);\n return {\n ok: true,\n layersDir,\n ...report,\n passed: report.warnings.length === 0,\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n\n/**\n * Render a measurement as plain text: the per-layer table first (numbers to\n * argue with), then the checks that fired. Takes the report itself rather than\n * a MeasureResult so a caller holding one inline (no `ok` to unwrap) can print\n * it too; a failed measurement has no report to render.\n */\nexport function formatMeasureReport(\n result: MeasureReport & { layersDir: string },\n): string {\n const lines = [\n `# layers (${result.layersDir})`,\n \"\",\n \"role size bbox-centre mass-centre margins t/b/l/r\",\n ];\n // Roles come off a sorted file listing, so sorting the two groups back\n // together restores that order.\n for (const role of [...Object.keys(result.layers), ...result.empty].sort()) {\n const m = result.layers[role];\n if (m === undefined) {\n lines.push(`${role.padEnd(13)} EMPTY (fully transparent)`);\n continue;\n }\n lines.push(\n `${role.padEnd(13)} ${`${m.w}x${m.h}`.padEnd(11)} ` +\n `${`${m.bboxCx.toFixed(0)},${m.bboxCy.toFixed(0)}`.padEnd(14)} ` +\n `${`${m.massCx.toFixed(0)},${m.massCy.toFixed(0)}`.padEnd(13)} ` +\n `${m.marginTop}/${m.marginBottom}/${m.marginLeft}/${m.marginRight}`,\n );\n }\n\n if (result.lips !== undefined) {\n const { opening, deadZone } = result.lips;\n lines.push(\n \"\",\n `lips: opening ${opening.width} px wide, ${opening.height} px tall at its centre under a ${opening.line} px line — no slit below MouthOpen ${deadZone.toFixed(2)}`,\n );\n }\n\n lines.push(\"\", \"# checks\", \"\");\n if (result.warnings.length === 0) {\n lines.push(\"all geometry checks passed\");\n } else {\n for (const w of result.warnings) lines.push(`- ${w}`);\n }\n return lines.join(\"\\n\");\n}\n","/**\n * The measure's arm checks. An arm hangs from the body's shoulder, and raising\n * it turns its shoulder cap about the rig's shoulder pivot, so the torso has\n * to reach under that cap or a gap opens beside the shoulder. The pivot is\n * the rig's own: `armGeometry`, run on the layer as `auto_rig_from_layers`\n * runs it, so the cap measured here is the one the rig turns.\n */\n\nimport path from \"node:path\";\nimport {\n LayerGeometryError,\n armGeometry,\n createLayerSetMeasurer,\n type ArmGeometry,\n type LayerInput,\n type LayerSetMeasurer,\n} from \"@ikijs/editor\";\nimport type { LayerStats } from \"./measure\";\nimport { decodePng } from \"./node-images\";\n\n/** The arm roles, screen right (`arm_L`) then screen left (`arm_R`). */\nexport const ARM_ROLES = [\"arm_L\", \"arm_R\"] as const;\n\n/** How far an arm's shoulder cap must reach under the torso's edge on the\n * shoulder pivot's row, as a share of its radius r_u. Our own value: a\n * raised arm turns its cap about the pivot, so a cap that barely meets the\n * torso's edge swings clear of it and bares the gap beside the shoulder. */\nexport const CAP_OVERLAP = 0.5;\n\n/** A px figure as the report prints it: pivots sit on half px. */\nexport const px = (v: number) => `${Number(v.toFixed(1))}`;\n\n/** Decode a role's layer in `absDir` and measure it on `measurer`. */\nexport async function measured(\n measurer: LayerSetMeasurer,\n absDir: string,\n role: string,\n): Promise<LayerInput> {\n const fileName = `${role}.png`;\n const { rgba } = await decodePng(path.join(absDir, fileName));\n // layerStats counts alpha > 8 and the measurer alpha >= 8, so a layer\n // measured non-empty is never empty here.\n return measurer.add({ role, fileName, rgba })!;\n}\n\n/**\n * Warn of an arm layer the rig refuses or would hang with a gap at the\n * shoulder: one without a body, one on another canvas than the body's, one\n * too short to place an elbow under its shoulder, and one whose shoulder cap\n * does not reach `CAP_OVERLAP` of its radius under the torso's edge.\n * `layers` holds the measured, non-empty layers of `absDir` by role.\n */\nexport async function armWarnings(\n absDir: string,\n layers: Record<string, LayerStats>,\n): Promise<string[]> {\n const warnings: string[] = [];\n const body = layers.body;\n // Opened for the first arm that reaches the overlap, so the body decodes once.\n let set: { measurer: LayerSetMeasurer; body: LayerInput } | undefined;\n\n for (const arm of ARM_ROLES) {\n const stats = layers[arm];\n if (stats === undefined) continue;\n if (body === undefined) {\n warnings.push(\n `${arm}: no body layer — an arm hangs from the body's shoulder, and auto_rig_from_layers refuses it.`,\n );\n continue;\n }\n // One measurer reads every buffer at one size, and a buffer of another\n // shape but the same area would pass its length check and be read with\n // the wrong stride.\n if (stats.canvasW !== body.canvasW || stats.canvasH !== body.canvasH) {\n warnings.push(\n `${arm}: its canvas ${stats.canvasW}x${stats.canvasH} differs from body's ` +\n `${body.canvasW}x${body.canvasH} — auto_rig_from_layers refuses layers of different ` +\n `sizes; recompose them together.`,\n );\n continue;\n }\n if (set === undefined) {\n const measurer = createLayerSetMeasurer({\n width: body.canvasW,\n height: body.canvasH,\n });\n set = { measurer, body: await measured(measurer, absDir, \"body\") };\n }\n\n let g: ArmGeometry;\n try {\n // The body box's centre, model x: the axis the rig reads an arm's side\n // off.\n g = armGeometry(\n await measured(set.measurer, absDir, arm),\n set.body.bbox.x + set.body.bbox.w / 2 - body.canvasW / 2,\n );\n } catch (err) {\n if (err instanceof LayerGeometryError) {\n warnings.push(\n `${arm}: ${err.message} — auto_rig_from_layers refuses it. Regenerate arm.png drawn ` +\n `hanging, shoulder at the top. Billed.`,\n );\n continue;\n }\n throw err;\n }\n const cap = capWarning(arm, g, set.body);\n if (cap !== undefined) warnings.push(cap);\n }\n return warnings;\n}\n\n/**\n * The shoulder cap against the torso's edge on the arm's side, on the canvas\n * row holding the shoulder pivot: the cap reaches r_u past the pivot, so it\n * overlaps the torso by r_u less the pivot's distance outside that edge.\n */\nfunction capWarning(\n arm: (typeof ARM_ROLES)[number],\n g: ArmGeometry,\n body: LayerInput,\n): string | undefined {\n // Model space is centred on the canvas, y up.\n const pivotX = g.shoulder.x + body.canvasW / 2;\n const row = Math.floor(body.canvasH / 2 - g.shoulder.y);\n const runs = body.rowRuns?.[row - body.bbox.y] ?? [];\n if (runs.length === 0) {\n return (\n `${arm}: the body has no paint on its shoulder pivot's row (y=${row}) — the torso shows a ` +\n `gap beside the shoulder once the arm raises. Retune layout.${arm}.cy onto the shoulder (free).`\n );\n }\n // The outermost run's end on the arm's side; a run's end column is exclusive.\n const edge = g.side === 1 ? runs[runs.length - 1] : runs[0];\n const overlap = g.shoulderRadius - g.side * (pivotX - edge);\n const need = CAP_OVERLAP * g.shoulderRadius;\n if (overlap >= need) return undefined;\n return (\n `${arm}: its shoulder cap reaches ${px(overlap)} px under the torso's edge on its pivot row ` +\n `(y=${row}), under half its radius (${px(need)} px) — a gap opens beside the shoulder once ` +\n `the arm raises. Move layout.${arm}.cx ${Math.ceil(need - overlap)} px toward the body (free).`\n );\n}\n","/**\n * The measure's pose forearm checks. A pose forearm hangs from its arm's\n * elbow and is swapped in for the hanging forearm, so it has to meet the arm\n * where the rig turns it: the rig puts its pivot on the arm's elbow and\n * `forearm_pose.png` is composed so that its elbow end lands there, at the\n * arm's elbow width. The geometry is the rig's own: `armGeometry` on the arm\n * and `forearmPoseGeometry` on the pose forearm, run on one measurer as\n * `auto_rig_from_layers` runs them. A pose forearm too far off in any of\n * pivot, width or length shows a broken joint once the switch is on; the\n * canvas-edge check is the generic one in `measureDir`.\n */\n\nimport {\n LayerGeometryError,\n armGeometry,\n createLayerSetMeasurer,\n forearmPoseGeometry,\n type ArmGeometry,\n type ForearmPoseGeometry,\n type LayerInput,\n type LayerSetMeasurer,\n} from \"@ikijs/editor\";\nimport type { LayerStats } from \"./measure\";\nimport { measured, px } from \"./measure-arms\";\n\n/** The pose forearm roles, each with the arm it hangs from. */\nexport const POSE_ROLES = [\"forearm_pose_L\", \"forearm_pose_R\"] as const;\nconst ARM_OF: Record<(typeof POSE_ROLES)[number], \"arm_L\" | \"arm_R\"> = {\n forearm_pose_L: \"arm_L\",\n forearm_pose_R: \"arm_R\",\n};\n\n/** How far off the arm's elbow the pose forearm's pivot may be, px. Our own\n * value: the composer pins it to within a pixel, so more is a layout `cx` /\n * `cy` that moved it. */\nexport const POSE_PIVOT_TOLERANCE = 2;\n/** How far the pose forearm's elbow end may differ from the arm's elbow run,\n * as a share of the run. Our own value: past it the joint shows a step in\n * the sleeve. */\nexport const POSE_WIDTH_TOLERANCE = 0.1;\n/** How far the pose forearm's length (pivot to its top painted row) may\n * differ from the hanging arm's (elbow to its last painted row), as a\n * share of it. Our own value, looser than the width's: a raised hand is\n * not a hanging one, but one twice as long is another arm. */\nexport const POSE_LENGTH_TOLERANCE = 0.15;\n\n/** Model y of the last painted row of a layer, y up. */\nfunction bottomRowY(layer: LayerInput): number {\n const painted =\n layer.rowRuns?.flatMap((runs, k) => (runs.length > 0 ? [k] : [])) ?? [];\n const k = painted.at(-1) ?? layer.bbox.h - 1;\n return layer.canvasH / 2 - (layer.bbox.y + k + 0.5);\n}\n\n/**\n * Warn of a pose forearm the rig refuses or would hang off its arm's elbow:\n * one without its arm, one on another canvas than its arm's, and one whose\n * pivot, elbow-end width or length is off the arm's. Each names its free\n * retune (`layout.forearm_pose_*`) or, where only a new drawing helps, the\n * regeneration. `layers` holds the measured, non-empty layers of `absDir` by\n * role.\n */\nexport async function forearmPoseWarnings(\n absDir: string,\n layers: Record<string, LayerStats>,\n): Promise<string[]> {\n const warnings: string[] = [];\n for (const pose of POSE_ROLES) {\n const stats = layers[pose];\n if (stats === undefined) continue;\n const arm = ARM_OF[pose];\n const armStats = layers[arm];\n if (armStats === undefined) {\n warnings.push(\n `${pose}: no ${arm} layer — a pose forearm hangs from its arm's elbow, and auto_rig_from_layers refuses it.`,\n );\n continue;\n }\n if (\n stats.canvasW !== armStats.canvasW ||\n stats.canvasH !== armStats.canvasH\n ) {\n warnings.push(\n `${pose}: its canvas ${stats.canvasW}x${stats.canvasH} differs from ${arm}'s ` +\n `${armStats.canvasW}x${armStats.canvasH} — auto_rig_from_layers refuses layers of different ` +\n `sizes; recompose them together.`,\n );\n continue;\n }\n // Without a body the arm is already warned of (armWarnings).\n if (layers.body === undefined) continue;\n\n const measurer: LayerSetMeasurer = createLayerSetMeasurer({\n width: stats.canvasW,\n height: stats.canvasH,\n });\n let a: ArmGeometry;\n let armLayer: LayerInput;\n try {\n armLayer = await measured(measurer, absDir, arm);\n // Only the elbow and the seam run are read, none of which depends on\n // the side, so the body is not decoded: the axis is the role's own, as\n // the composer passes it.\n a = armGeometry(armLayer, arm === \"arm_R\" ? Infinity : -Infinity);\n } catch (err) {\n // The arm's own warning says it.\n if (err instanceof LayerGeometryError) continue;\n throw err;\n }\n const b = forearmPoseGeometry(await measured(measurer, absDir, pose));\n warnings.push(...jointWarnings(pose, arm, stats, a, armLayer, b));\n }\n return warnings;\n}\n\nfunction jointWarnings(\n pose: (typeof POSE_ROLES)[number],\n arm: string,\n stats: LayerStats,\n a: ArmGeometry,\n armLayer: LayerInput,\n b: ForearmPoseGeometry,\n): string[] {\n const warnings: string[] = [];\n const key = `layout.${pose}`;\n\n // Pivot: model x grows right, y up; the layout's cy grows down. A layout\n // centre is the box's: the bbox's pixel centre (bboxCx) plus half a pixel.\n const dx = a.elbow.x - b.pivot.x;\n const dy = a.elbow.y - b.pivot.y;\n const off = Math.hypot(dx, dy);\n if (off > POSE_PIVOT_TOLERANCE) {\n warnings.push(\n `${pose}: its elbow end is ${px(off)} px off ${arm}'s elbow — the raised forearm detaches ` +\n `from the arm at the joint once it swaps in. Remove ${key}.cx/cy from the layout so it stays ` +\n `pinned on the elbow through later arm retunes (free), or set ${key}.cx to ` +\n `${Math.round(stats.bboxCx + 0.5 + dx)} and ${key}.cy to ${Math.round(stats.bboxCy + 0.5 - dy)} (free).`,\n );\n }\n\n // Width: B's elbow end against A's elbow run, by the w to set.\n const armRun = a.seamRun[1] - a.seamRun[0];\n const poseRun = 2 * b.radius;\n const widthRatio = poseRun / armRun;\n const widthBad = Math.abs(widthRatio - 1) > POSE_WIDTH_TOLERANCE;\n if (widthBad) {\n warnings.push(\n `${pose}: its elbow end is ${px(poseRun)} px wide, ${Math.round(Math.abs(widthRatio - 1) * 100)}% off ` +\n `${arm}'s elbow run (${px(armRun)} px) — the sleeve steps at the joint once it swaps in. ` +\n `Set ${key}.w to ${Math.round(stats.w / widthRatio)} (free).`,\n );\n }\n\n // Length: B from its pivot up to its hand, A from its elbow down to its\n // hand. A new w scales the width with it, so it only mends the length when\n // the width fits after.\n const armLen = a.elbow.y - bottomRowY(armLayer);\n const poseLen = b.top - b.pivot.y;\n const lengthRatio = poseLen / armLen;\n if (Math.abs(lengthRatio - 1) > POSE_LENGTH_TOLERANCE) {\n const fix = 1 / lengthRatio;\n const freeFix = Math.abs(widthRatio * fix - 1) <= POSE_WIDTH_TOLERANCE;\n warnings.push(\n `${pose}: its length from the elbow end to the hand is ${px(poseLen)} px against ${arm}'s ` +\n `${px(armLen)} px from its elbow to its hand — ` +\n (freeFix\n ? `the raised hand reaches the wrong height. Set ${key}.w to ${Math.round(stats.w * fix)} (free)` +\n (widthBad ? `, which fixes the width too.` : `.`)\n : `the raised hand reaches the wrong height, and no single w fits both its length and its width. ` +\n `Regenerate forearm_pose.png with the forearm and hand as long as the hanging arm's below its elbow. Billed.`),\n );\n }\n return warnings;\n}\n","/**\n * The measure's lip set checks. The rig folds the mouth open off the layers'\n * own alpha edges, per canvas column inside the opening (where `mouth_inner`\n * has a run): the interior's top must reach the line above it and the skin must\n * reach the interior, or a gap shows the face between them at rest. The\n * geometry is the rig's own: `mouthOpening`, run on the three layers as\n * `auto_rig_from_layers` runs it. The composer meets that contract by\n * construction; these checks are for a set it did not cut (hand-prepared\n * layers, a re-cut) and for the drawings the contract cannot save: a mouth too\n * small to fold, a line too thin to close on, green the key left, an interior\n * with holes. The lip layers' straight edges are the split's cuts, and so are\n * the inside layers' (`mouth_tongue`, `mouth_teeth`), so the generic edge and\n * flat-cut checks skip them all (`isLipLayerRole`). Of an inside layer the rig reads\n * only its box, so it is checked for the set it needs, its canvas and its box.\n */\n\nimport path from \"node:path\";\nimport {\n ALPHA_OPAQUE,\n LIP_INSIDE_ROLES,\n LIP_ROLES,\n LayerGeometryError,\n columnRuns,\n createLayerSetMeasurer,\n isLipInsideRole,\n mouthOpening,\n type LayerInput,\n type LipInsideRole,\n type LipRole,\n type Opening,\n} from \"@ikijs/editor\";\nimport type { LayerStats } from \"./measure\";\nimport { MIN_OPENING_WIDTH } from \"./compose-lips\";\nimport { decodePng } from \"./node-images\";\n\n/** A lip set's layer: one of its three, or an inside layer. */\nexport const isLipLayerRole = (role: string): role is LipRole | LipInsideRole =>\n (LIP_ROLES as readonly string[]).includes(role) || isLipInsideRole(role);\n\n/** The opening's height at its centre, rows, under which it is too small to\n * fold. Our own value, provisional. */\nconst MIN_OPENING_ROWS = 8;\n/** The line's height at the centre, rows, under which a closed mouth has no\n * line to close on (a hairline folds to nothing). Our own value, provisional. */\nconst MIN_LINE_ROWS = 2;\n/** Green excess `g - max(r, b)` above which an opaque lip pixel is key green\n * left over rather than art. Our own value, provisional. */\nconst GREEN_EXCESS = 40;\n/** The share of the opening's area that may be transparent inside\n * `mouth_inner`'s own span before the face shows through it. Our own value,\n * provisional. */\nconst INTERIOR_GAP_FRACTION = 0.05;\n\n/** What the report says of the opening, for judging a half-open mouth. */\nexport interface LipFacts {\n opening: { width: number; height: number; line: number };\n /** `MouthOpen` below which the slit has not opened: `v* = w' / (H + w')`. */\n deadZone: number;\n}\n\n/** A list of columns as the warning names it: the count and the first. */\nconst columns = (cols: number[]) =>\n `${cols.length} column${cols.length === 1 ? \"\" : \"s\"} (first at x=${cols[0]})`;\n\n/**\n * Warn of a lip set the rig refuses or would fold badly, and report the\n * opening it reads. `layers` holds the measured, non-empty layers of `absDir`\n * by role; a set with no lip layer is a legacy mouth and says nothing.\n */\nexport async function lipWarnings(\n absDir: string,\n layers: Record<string, LayerStats>,\n): Promise<{ warnings: string[]; lips?: LipFacts }> {\n const warnings: string[] = [];\n const present = LIP_ROLES.filter((role) => layers[role] !== undefined);\n const inside = LIP_INSIDE_ROLES.filter((role) => layers[role] !== undefined);\n if (present.length === 0) {\n if (inside.length > 0) {\n warnings.push(\n `${inside.join(\"/\")}: a lip set's inside layer with no lip set — auto_rig_from_layers refuses ` +\n `it (it is cut from the interior and clipped to it). Recompose from mouth_keyed.png + ` +\n `mouth_interior.png, or remove it.`,\n );\n }\n return { warnings };\n }\n\n const legacy = [\"mouth\", \"mouth_open\"].filter(\n (role) => layers[role] !== undefined,\n );\n if (legacy.length > 0) {\n warnings.push(\n `${present.join(\"/\")}: the lip set cannot be mixed with ${legacy.join(\"/\")} — auto_rig_from_layers ` +\n `refuses it. Remove one route: compose again with only mouth_keyed.png + mouth_interior.png, ` +\n `or without them.`,\n );\n }\n if (present.length < LIP_ROLES.length) {\n const missing = LIP_ROLES.filter((role) => layers[role] === undefined);\n warnings.push(\n `${present.join(\"/\")}: partial lip set, missing ${missing.join(\"/\")} — auto_rig_from_layers ` +\n `refuses it. Compose mouth_keyed.png + mouth_interior.png together, which cuts all three.`,\n );\n return { warnings };\n }\n\n const { mouth_inner: inner, lip_upper: upper } = layers;\n for (const role of [\"lip_lower\", \"lip_upper\", ...inside]) {\n const stats = layers[role];\n if (stats.canvasW !== inner.canvasW || stats.canvasH !== inner.canvasH) {\n warnings.push(\n `${role}: its canvas ${stats.canvasW}x${stats.canvasH} differs from mouth_inner's ` +\n `${inner.canvasW}x${inner.canvasH} — auto_rig_from_layers refuses layers of different ` +\n `sizes; recompose them together.`,\n );\n return { warnings };\n }\n }\n // Of an inside layer the rig reads only its box, and the cavity clips\n // whatever leaves its own: the measured alpha > 8 box (`bboxCx ± w/2`), in\n // pixel edges.\n const box = (m: LayerStats) => ({\n x0: m.bboxCx - m.w / 2,\n x1: m.bboxCx + m.w / 2,\n y0: m.bboxCy - m.h / 2,\n y1: m.bboxCy + m.h / 2,\n });\n const cavity = box(inner);\n for (const role of inside) {\n const b = box(layers[role]);\n if (\n b.x0 < cavity.x0 ||\n b.x1 > cavity.x1 ||\n b.y0 < cavity.y0 ||\n b.y1 > cavity.y1\n ) {\n warnings.push(\n `${role}: its box leaves mouth_inner's — the cavity clips it away there. Recompose from ` +\n `mouth_keyed.png + mouth_interior.png (free).`,\n );\n }\n }\n\n const measurer = createLayerSetMeasurer({\n width: inner.canvasW,\n height: inner.canvasH,\n });\n const set = new Map<string, LayerInput>();\n const green: string[] = [];\n for (const role of LIP_ROLES) {\n const fileName = `${role}.png`;\n const { rgba } = await decodePng(path.join(absDir, fileName));\n // Decoded here rather than through `measured`: the green scan below needs\n // the pixels. layerStats counts alpha > 8 and the measurer alpha >= 8, so\n // a layer measured non-empty is never empty here.\n set.set(role, measurer.add({ role, fileName, rgba })!);\n for (let i = 0; i < rgba.length; i += 4) {\n if (\n rgba[i + 3] >= ALPHA_OPAQUE &&\n rgba[i + 1] - Math.max(rgba[i], rgba[i + 2]) > GREEN_EXCESS\n ) {\n green.push(role);\n break;\n }\n }\n }\n let opening: Opening;\n try {\n opening = mouthOpening(set);\n } catch (err) {\n if (err instanceof LayerGeometryError) {\n warnings.push(err.message);\n return { warnings };\n }\n throw err;\n }\n\n const innerRuns = columnRuns(set.get(\"mouth_inner\")!);\n const noInterior: number[] = [];\n const gap: number[] = [];\n const noLine: number[] = [];\n const skinGap: number[] = [];\n let area = 0;\n let hollow = 0;\n for (let x = opening.x0; x <= opening.x1; x++) {\n const runs = innerRuns.get(x);\n if (runs === undefined) {\n noInterior.push(x);\n continue;\n }\n const span = runs[runs.length - 1][1] - runs[0][0];\n area += span;\n hollow += span - runs.reduce((n, r) => n + r[1] - r[0], 0);\n const c = opening.at(x);\n if (c.lineH <= 0) noLine.push(x);\n else if (c.Tu > c.T) gap.push(x);\n if (c.Bl < c.Bb) skinGap.push(x);\n }\n // The composer always cuts to the contract, so these come from a set it did\n // not cut: recomposing from the two sources is the free fix.\n const recompose = (file: string, ask: string) =>\n `Recompose from mouth_keyed.png + mouth_interior.png (free); if it persists, regenerate ${file} ${ask}. Billed.`;\n const regenKeyed = recompose(\n \"mouth_keyed.png\",\n \"with a closed outline and solid lips under it\",\n );\n if (noInterior.length > 0) {\n warnings.push(\n `mouth_inner: no interior in ${columns(noInterior)} of the opening — the fold has nothing to scale there. ${recompose(\"mouth_interior.png\", \"as one solid cavity\")}`,\n );\n }\n if (gap.length > 0) {\n warnings.push(\n `lip_upper: a gap between the line and the interior in ${columns(gap)} — the face shows through it ` +\n `at rest (the interior's top must reach the line's ink). ${regenKeyed}`,\n );\n }\n if (noLine.length > 0) {\n warnings.push(\n `lip_upper: no line above the interior in ${columns(noLine)} — nothing closes the mouth there. ${regenKeyed}`,\n );\n }\n if (skinGap.length > 0) {\n warnings.push(\n `lip_lower: a gap between the interior and the skin in ${columns(skinGap)} — the face shows through ` +\n `it once the mouth opens (the skin must reach the interior's bottom). ${regenKeyed}`,\n );\n }\n\n const width = opening.x1 - opening.x0 + 1;\n const centre = opening.at(opening.centre);\n if (width < MIN_OPENING_WIDTH * upper.w) {\n warnings.push(\n `mouth_inner: the opening is ${width} px wide, ${Math.round((100 * width) / upper.w)}% of lip_upper's ${upper.w} px ` +\n `(under ${Math.round(100 * MIN_OPENING_WIDTH)}%) — too narrow to fold; the slit stays a hairline. ` +\n `Regenerate mouth_keyed.png with the mouth open wider. Billed.`,\n );\n }\n if (centre.H < MIN_OPENING_ROWS) {\n // measure_layers sees only the layers, so a set layout.mouth_inner.h is\n // named in the message; a w past the canvas is not suggested at all.\n const w = Math.ceil((upper.w * MIN_OPENING_ROWS) / centre.H);\n const retune = w <= inner.canvasW ? w : null;\n warnings.push(\n `mouth_inner: the opening is ${centre.H} px tall at its centre (under ${MIN_OPENING_ROWS}) — too small to fold; ` +\n `the slit stays shut until MouthOpen is nearly 1. ` +\n (retune === null\n ? \"\"\n : `If the mouth is smaller than the reference's, set layout.mouth_inner.w to ${retune} ` +\n `(free; the whole set scales with it, so scale layout.mouth_inner.h too if it is set). Otherwise `) +\n `${retune === null ? \"R\" : \"r\"}egenerate mouth_keyed.png with the mouth open taller. Billed.`,\n );\n }\n if (opening.w < MIN_LINE_ROWS) {\n warnings.push(\n `lip_upper: the upper line is ${opening.w} px at the opening's centre (under ${MIN_LINE_ROWS}) — a hairline ` +\n `closes to nothing. Regenerate mouth_keyed.png ` +\n `with a bolder upper line, never thinner than the reference's mouth line. Billed.`,\n );\n }\n if (green.length > 0) {\n warnings.push(\n `${green.join(\"/\")}: opaque green left (key green, g exceeds r and b by over ${GREEN_EXCESS}) — it shows as a ` +\n `green fringe on the lips. Regenerate mouth_keyed.png with the green only inside the opening, or ` +\n `mouth_interior.png without green in it. Billed.`,\n );\n }\n if (area > 0 && hollow > INTERIOR_GAP_FRACTION * area) {\n warnings.push(\n `mouth_inner: ${Math.round((100 * hollow) / area)}% of the opening is transparent inside the interior's ` +\n `own span (over ${Math.round(100 * INTERIOR_GAP_FRACTION)}%) — the face shows through it. ` +\n `Regenerate mouth_interior.png as one solid cavity. Billed.`,\n );\n }\n\n return {\n warnings,\n lips: {\n opening: { width, height: centre.H, line: opening.w },\n deadZone: centre.overlap / (centre.H + centre.overlap),\n },\n };\n}\n","/**\n * The pixel work that turns a green-keyed open mouth plus a drawn interior\n * into the lip set the rig folds (`mouth_inner`, `lip_lower`, `lip_upper`),\n * with the interior's light paint as `mouth_tongue` and `mouth_teeth`.\n * Buffers in, buffers out: no file is read here, the composer hands over what\n * it decoded and gets PNGs back.\n *\n * The key (`keyGreen`) runs at SOURCE resolution. A model's \"flat #00FF00\" is\n * never that (bob's came back as (9, 245, 3)) and its line has less green than\n * red, so no formula of a pixel's own colour gives a half-mixed pixel half its\n * alpha. The fill's colour is therefore read off the art (the median of the\n * clearly green pixels), and each pixel near the fill is read against the far\n * end of ITS OWN ramp: the farthest pixel in reach that lies on the line from\n * the fill's colour through the pixel. The antialiasing becomes alpha, which\n * the premultiplied resize that follows carries cleanly.\n *\n * The split (`splitLipSet`) runs at the COMPOSED size. Every boundary it cuts\n * on is then an integer row of the pixels the rig reads, and its assertion\n * reads them through the rig's own `mouthOpening`, so what the composer checks\n * is what the rig will see. The interior is grown sideways only under ink and\n * never above its own column's hole top, which is what keeps the rig's\n * per-column contract (`Tu <= T <= lineTop`, `Bl >= Bb`) true by construction\n * rather than by luck of the art.\n *\n * The interior is split by lightness on the hole: a pixel at or over\n * CAVITY_LUMA (a tooth, the tongue) goes to `mouth_teeth` above its column's\n * hole middle and to `mouth_tongue` below it, and `mouth_inner` takes the\n * cavity's fill there, so the cavity is a dark fill with its own shading that\n * the rig clips the two to, the teeth riding the line and the tongue the\n * opening's bottom. Its edge is soft: a frame pixel beside the hole whose ink\n * is partial (alpha 128..254) was ink mixed with green, and the cavity takes\n * its share of it, `255 - alpha`, under ALPHA_OPAQUE, so no read of the\n * contract changes.\n *\n * The two columns beside the hole are grown into under the outline's side\n * wall. When the frame has ink above the first grown row the wall is the\n * line's own end, and it folds with the interior (its grown rows join\n * `mouth_inner`, not `lip_upper`), so the rig reads the line's bottom at the\n * interior's top there too and the closed line's ends are the drawn ends,\n * tapered. A column with no ink above its first grown row (an under-the-line\n * end) keeps every pixel in `lip_upper`; the rig still accepts it, its wall\n * past the opening thinned and, shut, shaped like a drawn flick.\n *\n * The preview (`closedLips`) shows the set as the rig draws it at rest: the\n * lips resampled through the lip meshes' own landed rows (`mouthRestShift`,\n * measured as the rig measures the final canvas layers), so the thinned line\n * and its tapered ends are in it, the interior left out (shut, it has zero\n * height).\n */\n\nimport sharp from \"sharp\";\nimport {\n ALPHA_OPAQUE,\n columnRuns,\n createLayerSetMeasurer,\n mouthOpening,\n mouthRestShift,\n type LayerInput,\n type Opening,\n} from \"@ikijs/editor\";\nimport { AutoRigInputError } from \"./limits\";\nimport { cropToBuffer } from \"./node-images\";\nimport { TRIM_THRESHOLD, boxWithoutStraySpecks, luma } from \"./trim\";\n\nexport const KEYED_SRC = \"mouth_keyed.png\";\nexport const INTERIOR_SRC = \"mouth_interior.png\";\n\n/** Green excess `(g - max(r, b)) / 255` at which a visible pixel is a fill\n * candidate; the fill is never full excess (bob's is 0.925). */\nconst KEY_CANDIDATE = 0.5;\n/** Levels (Euclidean) from the fill's median colour within which a pixel is\n * the fill. A ramp's last pixels past it are cut with the fill. */\nconst KEY_FILL_DIST = 20;\n/** Px (Chebyshev) from the fill within which a pixel may be a mix with it, and\n * within which the plateau of its ramp is sought. */\nconst KEY_REACH = 8;\n/** Levels a reference may sit off the segment from its colour to the fill's. */\nconst KEY_COLLINEAR = 12;\n/** A share of green under this is a stroke's own shading, not a mix: read as\n * zero, a true mix this small left opaque is 13 levels off at most. */\nconst KEY_MIN_SHARE = 0.05;\n/** Green outside the opening's region, as a share of the opening's, over\n * which the key is refused. */\nconst STRAY_KEY_FRACTION = 0.02;\n/** The opening's width, as a share of the frame's, under which it is too\n * small to fold. */\nexport const MIN_OPENING_WIDTH = 0.3;\n/** A second hole as a share of the largest, from which the opening is not\n * one region. */\nconst SECOND_HOLE_FRACTION = 0.05;\n/** A dark pixel (luma under this) under the opening belongs to its lower\n * outline band; skin is lighter. */\nconst BAND_LUMA = 150;\n/** The band's cap, in strokes: more is not an outline. */\nconst BAND_CAP = 3;\n/** Luma under which an interior's pixel is cavity rather than tooth or tongue:\n * the cavity's fill is read under it, and the hole's pixels at or over it are\n * cut into `mouth_teeth` / `mouth_tongue`. */\nexport const CAVITY_LUMA = 100;\n/** The lip rim's skin rule, the spike's: a pixel is skin at red, green and\n * blue over these floors, which a peach lip clears and a cavity's dark red or\n * a tongue's pink does not; but not a tooth, whose green and blue are over\n * these ceilings (near-white). */\nconst SKIN_MIN_R = 225;\nconst SKIN_MIN_G = 160;\nconst SKIN_MIN_B = 135;\nconst TEETH_MIN_G = 215;\nconst TEETH_MIN_B = 205;\nconst isSkin = (r: number, g: number, b: number): boolean =>\n r > SKIN_MIN_R &&\n g > SKIN_MIN_G &&\n b > SKIN_MIN_B &&\n !(g > TEETH_MIN_G && b > TEETH_MIN_B);\n\ninterface Components {\n /** Per pixel: its set's index, or -1 off the mask. */\n label: Int32Array;\n sizes: number[];\n /** Inclusive pixel boxes. */\n boxes: { x0: number; y0: number; x1: number; y1: number }[];\n}\n\n/** The sets of a mask, 4-connected, flood-filled on a stack that never\n * outgrows the image: a pixel is marked as it is pushed. */\nfunction components(mask: Uint8Array, W: number, H: number): Components {\n const n = W * H;\n const label = new Int32Array(n).fill(-1);\n const stack = new Int32Array(n);\n const sizes: number[] = [];\n const boxes: Components[\"boxes\"] = [];\n for (let start = 0; start < n; start++) {\n if (!mask[start] || label[start] >= 0) continue;\n const id = sizes.length;\n const box = { x0: W, y0: H, x1: -1, y1: -1 };\n let size = 0;\n let depth = 0;\n label[start] = id;\n stack[depth++] = start;\n while (depth > 0) {\n const p = stack[--depth];\n size++;\n const px = p % W;\n const py = (p - px) / W;\n box.x0 = Math.min(box.x0, px);\n box.x1 = Math.max(box.x1, px);\n box.y0 = Math.min(box.y0, py);\n box.y1 = Math.max(box.y1, py);\n for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {\n for (let x = Math.max(0, px - 1); x <= Math.min(W - 1, px + 1); x++) {\n if (x !== px && y !== py) continue;\n const q = y * W + x;\n if (mask[q] && label[q] < 0) {\n label[q] = id;\n stack[depth++] = q;\n }\n }\n }\n }\n sizes.push(size);\n boxes.push(box);\n }\n return { label, sizes, boxes };\n}\n\n/** The largest set's index, or -1 for none. */\nconst largest = (sizes: number[]): number =>\n sizes.reduce((best, s, i) => (best < 0 || s > sizes[best] ? i : best), -1);\n\n/**\n * Chebyshev dilation of `mask` by `reach`: done along the rows and then down\n * the columns, which is the same box as one pass over the square.\n */\nfunction dilate(mask: Uint8Array, W: number, H: number, reach: number) {\n const rows = new Uint8Array(W * H);\n const prefix = new Int32Array(Math.max(W, H) + 1);\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) prefix[x + 1] = prefix[x] + mask[y * W + x];\n for (let x = 0; x < W; x++) {\n rows[y * W + x] =\n prefix[Math.min(W, x + reach + 1)] - prefix[Math.max(0, x - reach)] > 0\n ? 1\n : 0;\n }\n }\n const out = new Uint8Array(W * H);\n for (let x = 0; x < W; x++) {\n for (let y = 0; y < H; y++) prefix[y + 1] = prefix[y] + rows[y * W + x];\n for (let y = 0; y < H; y++) {\n out[y * W + x] =\n prefix[Math.min(H, y + reach + 1)] - prefix[Math.max(0, y - reach)] > 0\n ? 1\n : 0;\n }\n }\n return out;\n}\n\n/**\n * The share of green in the pixel at byte offset `i`, read against the\n * foreground at `j`: where it lies on the segment from `j`'s colour to `g`,\n * clamped to 0..1. `j`'s colour must not be `g`'s.\n */\nfunction shareOf(rgba: Buffer, i: number, j: number, g: number[]): number {\n const dr = g[0] - rgba[j];\n const dg = g[1] - rgba[j + 1];\n const db = g[2] - rgba[j + 2];\n const t =\n ((rgba[i] - rgba[j]) * dr +\n (rgba[i + 1] - rgba[j + 1]) * dg +\n (rgba[i + 2] - rgba[j + 2]) * db) /\n (dr * dr + dg * dg + db * db);\n return Math.min(1, Math.max(0, t));\n}\n\n/**\n * Key the green out of a straight-alpha RGBA mouth, estimating each mixed\n * pixel's real alpha. See the header: the fill is the art's own green, a pixel\n * near it is read against the farthest pixel in reach on its own colour ramp,\n * and a share under KEY_MIN_SHARE is shading, not green. A pixel under alpha\n * 128 is a candidate for nothing and a reference for nobody (a PNG keeps RGB\n * under zero alpha, so invisible green must neither open a hole nor spoil the\n * region check), but green left faintly visible is cleared with the fill: it\n * would come out of the resize as a green fringe on the lip.\n */\nexport function keyGreen(rgba: Buffer, W: number, H: number): Buffer {\n const n = W * H;\n const noGreen = new AutoRigInputError(\n `${KEYED_SRC}: no green opening (#00FF00) to key — regenerate it with the inside of the open mouth painted ONE flat pure green`,\n );\n\n const hist = [\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n ];\n let candidates = 0;\n for (let p = 0; p < n; p++) {\n const i = p * 4;\n if (rgba[i + 3] < ALPHA_OPAQUE) continue;\n const excess = (rgba[i + 1] - Math.max(rgba[i], rgba[i + 2])) / 255;\n if (excess < KEY_CANDIDATE) continue;\n candidates++;\n for (let c = 0; c < 3; c++) hist[c][rgba[i + c]]++;\n }\n if (candidates === 0) throw noGreen;\n const median = (h: Uint32Array): number => {\n let seen = 0;\n for (let v = 0; v < 256; v++) {\n seen += h[v];\n if (seen * 2 >= candidates) return v;\n }\n return 255;\n };\n const G = [median(hist[0]), median(hist[1]), median(hist[2])];\n\n // The fill: visible pixels the art's key colour owns. `ref` is every visible\n // pixel that is not (the only ones a mixed pixel may read itself against).\n const out = Buffer.from(rgba);\n const fill = new Uint8Array(n);\n const ref = new Uint8Array(n);\n let fillCount = 0;\n for (let p = 0; p < n; p++) {\n const i = p * 4;\n if (rgba[i + 3] === 0) continue;\n const dr = rgba[i] - G[0];\n const dg = rgba[i + 1] - G[1];\n const db = rgba[i + 2] - G[2];\n const green = dr * dr + dg * dg + db * db <= KEY_FILL_DIST * KEY_FILL_DIST;\n if (rgba[i + 3] < ALPHA_OPAQUE) {\n if (green) out[i + 3] = 0;\n } else if (green) {\n fill[p] = 1;\n fillCount++;\n } else {\n ref[p] = 1;\n }\n }\n if (fillCount === 0) throw noGreen;\n\n const reach = dilate(fill, W, H, KEY_REACH);\n const collinear = KEY_COLLINEAR * KEY_COLLINEAR;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n const p = y * W + x;\n if (!reach[p] || fill[p] || out[p * 4 + 3] === 0) continue;\n const i = p * 4;\n // The pixel itself always qualifies, so there is no fallback.\n let best = i;\n let bestD2 =\n (rgba[i] - G[0]) ** 2 +\n (rgba[i + 1] - G[1]) ** 2 +\n (rgba[i + 2] - G[2]) ** 2;\n const y1 = Math.min(H - 1, y + KEY_REACH);\n const x1 = Math.min(W - 1, x + KEY_REACH);\n for (let qy = Math.max(0, y - KEY_REACH); qy <= y1; qy++) {\n for (let qx = Math.max(0, x - KEY_REACH); qx <= x1; qx++) {\n const q = qy * W + qx;\n if (q === p || !ref[q]) continue;\n const j = q * 4;\n const d2 =\n (rgba[j] - G[0]) ** 2 +\n (rgba[j + 1] - G[1]) ** 2 +\n (rgba[j + 2] - G[2]) ** 2;\n if (d2 <= bestD2) continue;\n const t = shareOf(rgba, i, j, G);\n const er = rgba[i] - rgba[j] - t * (G[0] - rgba[j]);\n const eg = rgba[i + 1] - rgba[j + 1] - t * (G[1] - rgba[j + 1]);\n const eb = rgba[i + 2] - rgba[j + 2] - t * (G[2] - rgba[j + 2]);\n if (er * er + eg * eg + eb * eb > collinear) continue;\n bestD2 = d2;\n best = j;\n }\n }\n const k = shareOf(rgba, i, best, G);\n if (k < KEY_MIN_SHARE) continue;\n rgba.copy(out, i, best, best + 3);\n out[i + 3] = Math.round(rgba[i + 3] * (1 - k));\n }\n }\n for (let p = 0; p < n; p++) if (fill[p]) out[p * 4 + 3] = 0;\n\n const { sizes } = components(fill, W, H);\n const main = largest(sizes);\n const strays = sizes.filter((_, i) => i !== main);\n const strayPx = strays.reduce((a, b) => a + b, 0);\n if (strayPx > STRAY_KEY_FRACTION * sizes[main]) {\n throw new AutoRigInputError(\n `${KEYED_SRC}: green outside the opening (${strayPx} px in ${strays.length} regions beside the opening's) — the key must be one flat region inside the outline; regenerate with no green elsewhere`,\n );\n }\n return out;\n}\n\n/** Levels (per channel) from the ground's median colour within which a pixel\n * is the ground. Near-white teeth (250, 248, 245) sit 5..10 off a pure white\n * ground, so a floor like the legacy parts' 238 would key them out. */\nconst GROUND_TOLERANCE = 4;\n/** A border whose median is light in every channel (over this) is a ground,\n * not the drawing: a darker or more saturated one means the drawing itself\n * reaches the edges. A mid-grey ground under it therefore passes through, read\n * as the drawing reaching the edges. */\nconst GROUND_LIGHT = 200;\n/** The floor of a light ground the interior is keyed against: a light ground\n * under it in some channel (cream, grey) is not white. */\nconst GROUND_MIN = 238;\n/** The share of the border a white ground must own: under it the ground has\n * heavy noise, a gradient or a checkerboard \"fake transparency\" along the\n * border itself (a checkerboard owns about half), and the key would leave a\n * rind of it round the drawing. A drawing may touch about a third of the\n * border and still pass. */\nconst GROUND_BORDER_SHARE = 0.65;\n\n/**\n * Key the white ground out of an interior that came without alpha: the pixels\n * 4-connected to the border within GROUND_TOLERANCE of the border's median\n * colour. The legacy parts' rule (every near-white pixel) would take the teeth\n * with it, and the teeth are what this part is for. A light ground that is\n * not white (cream, grey), or a white one with heavy noise or a gradient along\n * the border that leaves it owning under half of it, cannot be keyed cleanly\n * and is refused: stretched into the opening it would show as a box. A border\n * that is not light is the drawing itself reaching the edges (\"filling the\n * image\"): only the white connected to the border is keyed, the corners an oval\n * leaves.\n */\nexport function keyBorderWhite(rgba: Buffer, W: number, H: number): Buffer {\n const border: number[][] = [[], [], []];\n const edge = (p: number) => {\n for (let c = 0; c < 3; c++) border[c].push(rgba[p * 4 + c]);\n };\n for (let x = 0; x < W; x++) {\n edge(x);\n edge((H - 1) * W + x);\n }\n for (let y = 1; y < H - 1; y++) {\n edge(y * W);\n edge(y * W + W - 1);\n }\n const ground = border.map((v) => v.sort((a, b) => a - b)[v.length >> 1]);\n const light = ground.every((v) => v >= GROUND_LIGHT);\n if (light && ground.some((v) => v < GROUND_MIN)) {\n throw new AutoRigInputError(\n `${INTERIOR_SRC} came back opaque on a non-white ground — regenerate it with a transparent background. Billed.`,\n );\n }\n if (!light) ground.fill(255);\n\n const out = Buffer.from(rgba);\n const seen = new Uint8Array(W * H);\n const stack = new Int32Array(W * H);\n let depth = 0;\n const seed = (p: number) => {\n if (seen[p]) return;\n for (let c = 0; c < 3; c++) {\n if (Math.abs(rgba[p * 4 + c] - ground[c]) > GROUND_TOLERANCE) return;\n }\n seen[p] = 1;\n stack[depth++] = p;\n };\n for (let x = 0; x < W; x++) {\n seed(x);\n seed((H - 1) * W + x);\n }\n for (let y = 0; y < H; y++) {\n seed(y * W);\n seed(y * W + W - 1);\n }\n if (light && depth < GROUND_BORDER_SHARE * border[0].length) {\n throw new AutoRigInputError(\n `${INTERIOR_SRC} came back opaque on a white ground too noisy or shaded to key cleanly — regenerate it with a transparent background. Billed.`,\n );\n }\n while (depth > 0) {\n const p = stack[--depth];\n out[p * 4 + 3] = 0;\n const x = p % W;\n if (x > 0) seed(p - 1);\n if (x < W - 1) seed(p + 1);\n if (p >= W) seed(p - W);\n if (p < W * H - W) seed(p + W);\n }\n return out;\n}\n\n/** The box of the part's drawing: the composer's trim (stray specks aside),\n * or every pixel the trim keeps when no speck lies outside the drawing.\n * null when nothing is kept. */\nfunction drawingBox(rgba: Buffer, W: number, H: number) {\n const speckless = boxWithoutStraySpecks(rgba, W, H);\n if (speckless !== null) {\n return {\n x: speckless.left,\n y: speckless.top,\n w: speckless.width,\n h: speckless.height,\n };\n }\n let x0 = W;\n let y0 = H;\n let x1 = -1;\n let y1 = -1;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n if (rgba[(y * W + x) * 4 + 3] <= TRIM_THRESHOLD) continue;\n x0 = Math.min(x0, x);\n x1 = Math.max(x1, x);\n y0 = Math.min(y0, y);\n y1 = Math.max(y1, y);\n }\n }\n return x1 < 0 ? null : { x: x0, y: y0, w: x1 - x0 + 1, h: y1 - y0 + 1 };\n}\n\n/**\n * The drawn interior, ready to fit into the opening: trimmed, with the lip rim\n * a generator draws round the cavity removed (the skin-coloured sets touching\n * the trimmed border: the spike's interior prompt drew a peach lower lip\n * twice), and the cavity's colour read off what is left, for the flat fill the\n * split lays under it. The caller has keyed a white ground out of an interior\n * that came without alpha.\n */\nexport async function prepInterior(\n rgba: Buffer,\n W: number,\n H: number,\n): Promise<{ png: Buffer; cavity: [number, number, number] }> {\n const empty = new AutoRigInputError(\n `${INTERIOR_SRC}: nothing but lips/skin after trimming — regenerate it with the cavity, the teeth and the tongue only, NO lips`,\n );\n const first = drawingBox(rgba, W, H);\n if (first === null) throw empty;\n const cw = first.w;\n const ch = first.h;\n const crop = Buffer.alloc(cw * ch * 4);\n for (let y = 0; y < ch; y++) {\n const from = ((first.y + y) * W + first.x) * 4;\n rgba.copy(crop, y * cw * 4, from, from + cw * 4);\n }\n\n const skin = new Uint8Array(cw * ch);\n for (let p = 0; p < cw * ch; p++) {\n const i = p * 4;\n if (\n crop[i + 3] > TRIM_THRESHOLD &&\n isSkin(crop[i], crop[i + 1], crop[i + 2])\n )\n skin[p] = 1;\n }\n const { label, boxes } = components(skin, cw, ch);\n const rim = boxes.map(\n (b) => b.x0 === 0 || b.y0 === 0 || b.x1 === cw - 1 || b.y1 === ch - 1,\n );\n for (let p = 0; p < cw * ch; p++) {\n if (label[p] >= 0 && rim[label[p]]) crop[p * 4 + 3] = 0;\n }\n\n const box = drawingBox(crop, cw, ch);\n if (box === null) throw empty;\n\n // The cavity: the dark pixels' mean, or everything's when none is dark.\n const sum = [0, 0, 0];\n const all = [0, 0, 0];\n let dark = 0;\n let count = 0;\n for (let y = box.y; y < box.y + box.h; y++) {\n for (let x = box.x; x < box.x + box.w; x++) {\n const i = (y * cw + x) * 4;\n if (crop[i + 3] < ALPHA_OPAQUE) continue;\n count++;\n for (let c = 0; c < 3; c++) all[c] += crop[i + c];\n if (luma(crop, i) < CAVITY_LUMA) {\n dark++;\n for (let c = 0; c < 3; c++) sum[c] += crop[i + c];\n }\n }\n }\n if (count === 0) throw empty;\n const [from, over] = dark > 0 ? [sum, dark] : [all, count];\n const cavity = from.map((v) => Math.round(v / over)) as [\n number,\n number,\n number,\n ];\n return { png: await cropToBuffer(crop, cw, ch, box), cavity };\n}\n\nconst rawOf = async (png: Buffer) =>\n sharp(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });\n\nconst encode = (rgba: Buffer, w: number, h: number) =>\n sharp(rgba, { raw: { width: w, height: h, channels: 4 } })\n .png()\n .toBuffer();\n\n/**\n * The opening of a keyed frame: its transparent pixels the outside cannot\n * reach through transparent pixels (so its boundary is at or above\n * ALPHA_OPAQUE), as the largest set of them. Refuses a frame with no such hole,\n * one too narrow to fold, and one with a second hole of\n * SECOND_HOLE_FRACTION of the largest or more.\n */\nfunction enclosedHole(frame: Buffer, w: number, h: number) {\n const n = w * h;\n const alpha = (p: number) => frame[p * 4 + 3];\n const outside = new Uint8Array(n);\n const stack = new Int32Array(n);\n let depth = 0;\n const seed = (p: number) => {\n if (!outside[p] && alpha(p) < ALPHA_OPAQUE) {\n outside[p] = 1;\n stack[depth++] = p;\n }\n };\n for (let x = 0; x < w; x++) {\n seed(x);\n seed((h - 1) * w + x);\n }\n for (let y = 0; y < h; y++) {\n seed(y * w);\n seed(y * w + w - 1);\n }\n while (depth > 0) {\n const p = stack[--depth];\n const x = p % w;\n if (x > 0) seed(p - 1);\n if (x < w - 1) seed(p + 1);\n if (p >= w) seed(p - w);\n if (p < n - w) seed(p + w);\n }\n const mask = new Uint8Array(n);\n for (let p = 0; p < n; p++) {\n if (alpha(p) < ALPHA_OPAQUE && !outside[p]) mask[p] = 1;\n }\n const { label, sizes, boxes } = components(mask, w, h);\n const main = largest(sizes);\n if (main < 0) {\n throw new AutoRigInputError(\n `${KEYED_SRC}: the outline is not closed round the opening (the key reached the outside, or the line is broken or too thin at this size) — regenerate with ONE closed, bolder outline`,\n );\n }\n const box = boxes[main];\n const holeW = box.x1 - box.x0 + 1;\n if (holeW < MIN_OPENING_WIDTH * w) {\n throw new AutoRigInputError(\n `${KEYED_SRC}: the opening is only ${holeW} px wide of the mouth's ${w} — too small to fold; regenerate with the mouth open wider, or, if its outline is broken (only a small pocket of the opening was enclosed), with ONE closed, bolder outline`,\n );\n }\n const others = sizes.filter(\n (s, i) => i !== main && s >= SECOND_HOLE_FRACTION * sizes[main],\n );\n if (others.length > 0) {\n throw new AutoRigInputError(\n `${KEYED_SRC}: the opening is not one connected region (${others.length + 1} holes: teeth or tongue drawn into the green?) — regenerate with nothing drawn inside the green`,\n );\n }\n return { label, main, box };\n}\n\ntype LipRgba = { mouth_inner: Buffer; lip_lower: Buffer; lip_upper: Buffer };\n\n/** The three layers, raw RGBA on a `w` x `h` canvas, as the rig measures\n * them; null for a layer with no opaque pixel. */\nfunction measureLips(\n layers: LipRgba,\n w: number,\n h: number,\n): Map<string, LayerInput | null> {\n const measurer = createLayerSetMeasurer({ width: w, height: h });\n return new Map(\n Object.entries(layers).map(([role, rgba]) => [\n role,\n measurer.add({ role, fileName: `${role}.png`, rgba }),\n ]),\n );\n}\n\n/**\n * Read the three layers back through the rig's own `mouthOpening` and assert\n * the fold's contract on every column of the opening it reads. A violation is\n * an invariant of the split, not input, so it throws a plain Error naming the\n * column.\n */\nfunction assertFoldContract(layers: LipRgba, w: number, h: number): Opening {\n const byRole = new Map<string, LayerInput>();\n for (const [role, layer] of measureLips(layers, w, h)) {\n // The outline above the opening and the interior in it always exist; the\n // skin under it is the art's.\n if (layer === null && role === \"lip_lower\") {\n throw new AutoRigInputError(\n `${KEYED_SRC}: no lip_lower after the split — there is no skin under the opening; draw the lower lip under the outline`,\n );\n }\n byRole.set(role, layer!);\n }\n const opening = mouthOpening(byRole);\n const runs = columnRuns(byRole.get(\"mouth_inner\")!);\n for (let col = opening.x0; col <= opening.x1; col++) {\n const c = opening.at(col);\n const why = !runs.has(col)\n ? \"has no interior run\"\n : c.Tu > c.T\n ? `has a gap between the line and the interior (Tu ${c.Tu} > T ${c.T})`\n : c.T > c.lineTop || c.lineH <= 0\n ? `has no line above the interior (T ${c.T}, line top ${c.lineTop})`\n : c.Bl < c.Bb\n ? `has a gap between the interior and the skin (Bl ${c.Bl} < Bb ${c.Bb})`\n : null;\n if (why !== null) throw new Error(`splitLipSet: column ${col} ${why}`);\n }\n return opening;\n}\n\n/**\n * Split a keyed, trimmed and composed-size mouth frame into the lip set. Per\n * opening column (a column of the enclosed hole) `top` / `bot` are the hole's\n * first row and last row + 1:\n * lip_upper every pixel above `top`, every pixel of a column outside the\n * opening (the corner hooks) except a side wall's grown rows, the\n * hole's faint upper half;\n * mouth_inner the band (the ink from `bot` down while dark, at most\n * BAND_CAP strokes) over the interior over a flat cavity fill, on\n * the hole, the band and the first skin row `R`, grown once\n * sideways under ink and never above its own column's `top`\n * (the grown rows of a side column with ink above them are\n * `lip_upper`'s no longer: the wall folds with the interior);\n * lip_lower every row from `R` down (row `R` is in both: a one-row overlap,\n * not a gap);\n * mouth_teeth / mouth_tongue the hole's pixels whose colour in `mouth_inner`\n * is at or over CAVITY_LUMA, above / below the column's hole\n * middle, opaque; `mouth_inner` takes the cavity's fill there;\n * the rim a frame pixel outside `mouth_inner` beside the hole with alpha\n * 128..254: the cavity's fill at `255 - alpha` in `mouth_inner`.\n * A side column (beside the hole) whose frame has no ink above its first grown\n * row keeps those rows in `lip_upper` and out of `mouth_inner`'s fold.\n * The result is read back through the rig's own `mouthOpening` and the\n * contract asserted (`assertFoldContract`).\n */\nexport async function splitLipSet(\n keyedPng: Buffer,\n w: number,\n h: number,\n interior: { png: Buffer; cavity: [number, number, number] },\n): Promise<{\n inner: Buffer;\n lower: Buffer;\n upper: Buffer;\n tongue: Buffer;\n teeth: Buffer;\n opening: Opening;\n}> {\n const { data: frame, info } = await rawOf(keyedPng);\n if (info.width !== w || info.height !== h) {\n throw new Error(\n `splitLipSet: the frame is ${info.width}x${info.height}, not ${w}x${h}`,\n );\n }\n const n = w * h;\n const alpha = (p: number) => frame[p * 4 + 3];\n const { label, main, box: hb } = enclosedHole(frame, w, h);\n const holeW = hb.x1 - hb.x0 + 1;\n\n const top = new Int32Array(w).fill(-1);\n const bot = new Int32Array(w).fill(-1);\n for (let y = 0; y < h; y++) {\n for (let x = hb.x0; x <= hb.x1; x++) {\n if (label[y * w + x] !== main) continue;\n if (top[x] < 0) top[x] = y;\n bot[x] = y + 1;\n }\n }\n // The stroke: the opaque rows directly above the hole at its centre column.\n const centre = Math.round((hb.x0 + hb.x1) / 2);\n let stroke = 0;\n while (\n top[centre] - 1 - stroke >= 0 &&\n alpha((top[centre] - 1 - stroke) * w + centre) >= ALPHA_OPAQUE\n )\n stroke++;\n const bandCap = BAND_CAP * Math.max(1, stroke);\n\n // Per opening column: the band's end and the first skin row R (-1: none).\n const skinRow = new Int32Array(w).fill(-1);\n const inM = new Uint8Array(n);\n for (let x = hb.x0; x <= hb.x1; x++) {\n let y = bot[x];\n while (\n y < h &&\n y - bot[x] < bandCap &&\n alpha(y * w + x) >= ALPHA_OPAQUE &&\n luma(frame, (y * w + x) * 4) < BAND_LUMA\n )\n y++;\n for (let k = top[x]; k < y; k++) inM[k * w + x] = 1;\n let r = y;\n while (r < h && alpha(r * w + x) < ALPHA_OPAQUE) r++;\n if (r < h) {\n skinRow[x] = r;\n inM[r * w + x] = 1;\n }\n }\n\n // Grown once, from M as it was: sideways, under ink only, and in an opening\n // column never above its own hole top.\n const grown = Uint8Array.from(inM);\n for (let y = 0; y < h; y++) {\n for (let x = 0; x < w; x++) {\n const p = y * w + x;\n if (inM[p] || alpha(p) < ALPHA_OPAQUE) continue;\n if (top[x] >= 0 && y < top[x]) continue;\n if ((x > 0 && inM[p - 1]) || (x < w - 1 && inM[p + 1])) grown[p] = 1;\n }\n }\n\n // The columns beside the hole whose grown rows are the outline's side wall:\n // the frame is opaque on the row above the first one. Those rows fold with\n // the interior; a column with no ink above them keeps its pixels in the\n // line (an under-the-line end the rig still accepts, its wall thinned and,\n // shut, shaped like a drawn flick).\n const wall = new Uint8Array(w);\n for (const x of [hb.x0 - 1, hb.x1 + 1]) {\n if (x < 0 || x >= w) continue;\n let first = 0;\n while (first < h && !(grown[first * w + x] && !inM[first * w + x])) first++;\n if (first > 0 && first < h && alpha((first - 1) * w + x) >= ALPHA_OPAQUE)\n wall[x] = 1;\n }\n\n // The interior fitted to the hole's box grown one pixel each side.\n const gx = hb.x0 - 1;\n const gy = hb.y0 - 1;\n const gw = holeW + 2;\n const gh = hb.y1 - hb.y0 + 3;\n const { data: fitted } = await sharp(interior.png)\n .resize(gw, gh, { fit: \"fill\" })\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n\n const hole = (q: number) => label[q] === main;\n // Above its column's hole middle: the line's half of the opening, for the\n // faint pixels and for the light paint alike.\n const upperHalf = (x: number, y: number) => 2 * y < top[x] + bot[x];\n // The hole's faint pixels in its upper half are the line's antialiasing, the\n // lower half's the band's.\n const faintUpper = (p: number, x: number, y: number) =>\n y < bot[x] && hole(p) && upperHalf(x, y);\n const besideHole = (p: number, x: number, y: number) =>\n (x > 0 && hole(p - 1)) ||\n (x < w - 1 && hole(p + 1)) ||\n (y > 0 && hole(p - w)) ||\n (y < h - 1 && hole(p + w));\n\n const upper = Buffer.alloc(n * 4);\n const lower = Buffer.alloc(n * 4);\n const inner = Buffer.alloc(n * 4);\n const tongue = Buffer.alloc(n * 4);\n const teeth = Buffer.alloc(n * 4);\n const copy = (to: Buffer, p: number) =>\n frame.copy(to, p * 4, p * 4, p * 4 + 4);\n for (let y = 0; y < h; y++) {\n for (let x = 0; x < w; x++) {\n const p = y * w + x;\n const inOpening = top[x] >= 0;\n if (\n (!inOpening || y < top[x] || faintUpper(p, x, y)) &&\n !(wall[x] && grown[p])\n )\n copy(upper, p);\n if (inOpening && skinRow[x] >= 0 && y >= skinRow[x]) copy(lower, p);\n\n if (!grown[p]) {\n // The rim: the ink's partial alpha is its coverage, the rest the\n // opening's, which the cavity fills.\n const a = alpha(p);\n if (a >= ALPHA_OPAQUE && a < 255 && besideHole(p, x, y)) {\n inner.set(interior.cavity, p * 4);\n inner[p * 4 + 3] = 255 - a;\n }\n continue;\n }\n const out = [...interior.cavity];\n const ix = x - gx;\n const iy = y - gy;\n if (ix >= 0 && ix < gw && iy >= 0 && iy < gh) {\n const i = (iy * gw + ix) * 4;\n const a = fitted[i + 3] / 255;\n for (let c = 0; c < 3; c++) out[c] += (fitted[i + c] - out[c]) * a;\n }\n // The frame's own ink goes over it on the hole's rows (but not the faint\n // upper half, which is the line's), on the band and the skin row, and on\n // a side wall's rows.\n if ((inM[p] || wall[x]) && !faintUpper(p, x, y)) {\n const a = alpha(p) / 255;\n for (let c = 0; c < 3; c++) out[c] += (frame[p * 4 + c] - out[c]) * a;\n }\n inner[p * 4] = Math.round(out[0]);\n inner[p * 4 + 1] = Math.round(out[1]);\n inner[p * 4 + 2] = Math.round(out[2]);\n inner[p * 4 + 3] = 255;\n // The hole's light paint is a layer of its own, and the cavity is\n // repainted its fill under it.\n if (hole(p) && luma(inner, p * 4) >= CAVITY_LUMA) {\n const to = upperHalf(x, y) ? teeth : tongue;\n inner.copy(to, p * 4, p * 4, p * 4 + 4);\n inner.set(interior.cavity, p * 4);\n }\n }\n }\n\n const opening = assertFoldContract(\n { mouth_inner: inner, lip_lower: lower, lip_upper: upper },\n w,\n h,\n );\n const [innerPng, lowerPng, upperPng, tonguePng, teethPng] = await Promise.all(\n [inner, lower, upper, tongue, teeth].map((b) => encode(b, w, h)),\n );\n return {\n inner: innerPng,\n lower: lowerPng,\n upper: upperPng,\n tongue: tonguePng,\n teeth: teethPng,\n opening,\n };\n}\n\n/**\n * The rig's rest shift of the lips for the three canvas-sized layers: the\n * lip meshes' own field at MouthOpen 0 (`mouthRestShift`). Measured on the\n * canvas, not on the mouth-sized frame: `detectAlphaBbox` grows a box a pixel\n * each side and clamps it to the image, so a frame clamps where the canvas\n * does not, and the knot grid, which starts at the union's edge, lands\n * elsewhere. The measurement is the rig's own, of the same bytes.\n */\nexport async function restShiftOf(\n layers: { mouth_inner: Buffer; lip_lower: Buffer; lip_upper: Buffer },\n width: number,\n height: number,\n): Promise<ReturnType<typeof mouthRestShift>> {\n const [mouth_inner, lip_lower, lip_upper] = await Promise.all(\n [layers.mouth_inner, layers.lip_lower, layers.lip_upper].map(\n async (png) => (await rawOf(png)).data,\n ),\n );\n const byRole = new Map<string, LayerInput>();\n for (const [role, layer] of measureLips(\n { mouth_inner, lip_lower, lip_upper },\n width,\n height,\n )) {\n if (layer === null) {\n throw new AutoRigInputError(\n `layout.mouth_inner places the lip set so that ${role} falls off the canvas (nothing of it is left) — move it back on the canvas`,\n );\n }\n byRole.set(role, layer);\n }\n return mouthRestShift(byRole);\n}\n\n/**\n * The lips as the rig draws them at rest (MouthOpen 0), each column resampled\n * through the lip mesh's own landed rows: a source row lands at its centre\n * moved by the field there (`mouthRestShift`, the same knots, triangles and\n * stored offsets the rig has, so the preview is what the mesh draws; a\n * per-column fold is a pixel or more off on the lower lip, whose fold carries\n * integer-row reads). Only the rows whose centres the field answers land:\n * those inside the part's box, the layer's alpha box, so every row outside it\n * is transparent and contributes nothing, but for the one beyond each end,\n * landed a step past the edge row for the edge to blend into. The thin and\n * the squashes are positive scales, so the landed rows keep their order; each\n * destination row is blended linearly from the two consecutive landed rows\n * bracketing its centre, the way the GPU samples the mesh (rounding per row\n * would turn the smooth arc into a staircase the rig never draws),\n * premultiplied so an edge neither darkens nor lightens, and is transparent\n * when no pair brackets it. A constant field is a plain sub-pixel shift. The\n * flick's sideways pull is not previewed: the field is a column's dy alone.\n * `left` and `top` are the\n * frame's column and row on the canvas; +y is up and rows go down the image,\n * so a row lands at -dy. The interior is left out: shut, it has no height.\n */\nexport async function closedLips(\n upper: Buffer,\n lower: Buffer,\n shift: ReturnType<typeof mouthRestShift>,\n left: number,\n top: number,\n): Promise<{ upper: Buffer; lower: Buffer }> {\n const shut = async (png: Buffer, role: \"lip_upper\" | \"lip_lower\") => {\n const { data, info } = await rawOf(png);\n const { width: w, height: h } = info;\n const out = Buffer.alloc(w * h * 4);\n for (let x = 0; x < w; x++) {\n const px = (row: number, c: number) =>\n row < 0 || row >= h ? 0 : data[(row * w + x) * 4 + c];\n // [source row, its landed centre], in row order.\n const landed: [number, number][] = [];\n for (let row = 0; row < h; row++) {\n const dy = shift(role, left + x, top + row);\n if (dy !== undefined) landed.push([row, row + 0.5 - dy]);\n }\n // The rows just past the box (transparent), a landed step beyond its\n // edge rows: the edge rows blend into nothing over their outer half,\n // as a drawn edge does, rather than ending at their centres.\n if (landed.length > 1) {\n const [a, b] = landed;\n const [y, z] = landed.slice(-2);\n landed.unshift([a[0] - 1, 2 * a[1] - b[1]]);\n landed.push([z[0] + 1, 2 * z[1] - y[1]]);\n }\n let i = 0;\n for (let to = 0; to < h; to++) {\n const centre = to + 0.5;\n while (i + 1 < landed.length && landed[i + 1][1] < centre) i++;\n if (i + 1 >= landed.length || landed[i][1] > centre) continue;\n const [r0, y0] = landed[i];\n const [r1, y1] = landed[i + 1];\n const t = (centre - y0) / (y1 - y0);\n const a0 = px(r0, 3);\n const a1 = px(r1, 3);\n const a = (1 - t) * a0 + t * a1;\n if (a === 0) continue;\n const o = (to * w + x) * 4;\n for (let c = 0; c < 3; c++)\n out[o + c] = Math.round(\n ((1 - t) * a0 * px(r0, c) + t * a1 * px(r1, c)) / a,\n );\n out[o + 3] = Math.round(a);\n }\n }\n return encode(out, w, h);\n };\n const [u, l] = await Promise.all([\n shut(upper, \"lip_upper\"),\n shut(lower, \"lip_lower\"),\n ]);\n return { upper: u, lower: l };\n}\n","/**\n * Measure the head-turn cues in a PAIR of images of the same character — one\n * facing front, one turned — and report them as three ratios. It is how a\n * rigged turn gets compared to a reference turn without either image being\n * registered to the other: every number below is a front→turned CHANGE,\n * divided by something measured in the same image. That cancels crop and\n * position, not SCALE: the head span is sampled over a FIXED ±HEAD_BAND row\n * band, so a pair at different resolutions — or a character redrawn larger or\n * smaller between the two shots — would read as a turn that never happened.\n * The pair MUST already share framing and head size; this only checks it, it\n * does not correct for it. The check is a yaw does not change iris HEIGHT, so\n * a front/turned pair whose mean iris height differs is refused rather than\n * measured (see `measureTurnReference`).\n *\n * farEyeRatio how much the far eye narrows, over what it already was at\n * rest (a resting asymmetry in the art is divided out)\n * eyeShift how far the eye pair slides across the head, in units of\n * the FRONT head half-width (hh); negative = toward the\n * image's left\n * silhouetteRatio how much the head narrows, turned over front\n *\n * Read-only over two files; it edits nothing. Ported from the measurement\n * script this repo's turn work ran by hand, so the numbers a rig is tuned\n * against come out of the server every agent already has.\n *\n * `sharp` must stay confined to @ikijs/mcp; the decode and the debug-overlay\n * encode both go through ./node-images, this package's single image boundary.\n */\n\nimport path from \"node:path\";\nimport {\n ALPHA_OPAQUE,\n HEAD_BAND,\n foregroundSpan,\n headHalfOf,\n} from \"@ikijs/editor\";\nimport { decodePng, encodeOverlayPng } from \"./node-images\";\nimport {\n AutoRigInputError,\n resolveInputPath,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\n\n// Re-exported so compose.ts, measure.ts and the tests keep their imports.\nexport {\n SPECK_CORE_FRACTION,\n denseCoreOf,\n headHalfOf,\n isSpeckCore,\n} from \"@ikijs/editor\";\n\n/**\n * Hue/saturation window that selects the iris. Anime irises are a saturated\n * colour on a face that is not, which is what makes them findable at all; the\n * default window is violet-to-blue because that is what the characters this was\n * tuned on have. A character with, say, amber eyes passes its own window.\n */\nexport interface IrisColor {\n /** Inclusive hue bounds in degrees (0..360). */\n hueMin: number;\n hueMax: number;\n /** Minimum HSV saturation (0..1) — separates the iris from the skin. */\n satMin: number;\n}\n\nconst DEFAULT_IRIS: IrisColor = { hueMin: 230, hueMax: 300, satMin: 0.22 };\n\n// Value window, NOT a parameter: it excludes the specular highlight (near\n// white) and the pupil/lash ink (near black) whatever the iris hue is, so the\n// blob that survives is the coloured ring itself.\nconst IRIS_V_MIN = 0.18;\nconst IRIS_V_MAX = 0.95;\n// A blob whose surviving pixels average darker than this is lash ink or a\n// shadow that crept through the hue window, not an iris.\nconst IRIS_MEAN_V_MIN = 0.32;\n// The pupil and the specular highlight split the coloured ring into pieces; a\n// morphological CLOSE (dilate, then erode by the same radius) welds them back\n// into one component WITHOUT moving the blob's edges. A bare dilate would do\n// the welding too, but it adds its radius to every width, and that bias does\n// not cancel in far/near — it pushes the ratio toward 1 by an amount that\n// depends on how many pixels wide the iris happens to be.\nconst CLOSE_RADIUS = 3;\n// ...at the size it was tuned on; a smaller image gets a proportionally smaller\n// radius (at least 1 px), the way the area floor below is scaled.\nconst CLOSE_RADIUS_REFERENCE_PX = 1254;\n// An iris is small. Anything wider or taller than this fraction of the image is\n// hair, a collar, or the face itself leaking through the hue window.\nconst BLOB_MAX_FRAC = 0.12;\n// A KEYED head span this wide is not a head: the hue/sat/value backdrop rule\n// found no background at all, so the whole frame reads as foreground — a\n// backdrop that is not the lavender-grey it keys on (a plain screenshot, a\n// different key colour), not a character that fills the canvas edge to edge.\nconst KEYED_SPAN_MAX_FRAC = 0.95;\n// Area floor, scaled from the 300 px it was tuned at on a 1254² reference so\n// the same physical blob survives on a smaller render.\nconst MIN_AREA_REFERENCE_PIXELS = 1254 * 1254;\nconst MIN_AREA = 300;\n// Two irises sit apart but level. Below the dx floor is one iris found twice\n// (highlight vs ring), above the ceiling is an iris paired with a hair clip.\nconst PAIR_DX_MIN_FRAC = 0.08;\nconst PAIR_DX_MAX_FRAC = 0.35;\nconst PAIR_DY_MAX_FRAC = 0.05;\n/** Blobs kept as pair candidates, largest first — the pair search is O(n²). */\nconst MAX_CANDIDATES = 12;\n\n// --- Foreground (silhouette) rule -----------------------------------------\n// Two modes, chosen per image, because the two kinds of image this compares\n// carry their background differently and neither rule works on both.\n//\n// \"alpha\" an ENGINE RENDER: transparent backdrop. Foreground is alpha alone\n// — and nothing else. Its character pixels include near-black hair\n// ink and pale lavender highlights, both of which the keyed rule\n// below would eat, and the head would come back narrower than it is.\n// It is also the rule to follow when measuring the same silhouette\n// from the layer PNGs' own alpha, so the two are comparable.\n// \"keyed\" a fully opaque REFERENCE: no alpha to read, so the flat\n// lavender-grey backdrop is keyed out by colour instead, along with\n// a near-black frame/letterbox border.\nconst BG_HUE_MIN = 220;\nconst BG_HUE_MAX = 260;\nconst BG_SAT_MAX = 0.2;\nconst BG_V_MIN = 0.55;\nconst BG_V_BLACK = 0.03;\n\n/** Connected blob of iris-coloured pixels, in image px. */\nexport interface IrisBlob {\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n w: number;\n h: number;\n area: number;\n cx: number;\n cy: number;\n}\n\n/** One image's measurement. `irisL`/`irisR` are ordered by x in the IMAGE. */\nexport interface TurnImageMeasure {\n file: string;\n width: number;\n height: number;\n maskMode: \"alpha\" | \"keyed\";\n irisL: IrisBlob;\n irisR: IrisBlob;\n /** Mean row of the two iris centres. */\n eyeRow: number;\n /** Head silhouette span at the eye row. */\n head: { left: number; right: number; cx: number; half: number };\n /** Mean column of the two iris centres. */\n pairCx: number;\n eyeGap: number;\n}\n\nexport interface TurnMeasurement {\n front: TurnImageMeasure;\n turned: TurnImageMeasure;\n /** Turned far/near iris width over the same ratio at rest. */\n farEyeRatio: number;\n /** Front→turned slide of the eye pair across the head, in FRONT hh units. */\n eyeShift: number;\n /** Head half-width, turned over front. */\n silhouetteRatio: number;\n /** -1 = the head turned toward the image's left, +1 = toward its right. */\n turnSign: -1 | 1;\n /** Debug overlays written, when `debugDir` was given. */\n debug?: string[];\n}\n\nexport type MeasureTurnResult =\n | ({ ok: true } & TurnMeasurement)\n | { ok: false; error: string };\n\nexport interface MeasureTurnInput {\n /** Front-facing image (relative paths resolve against cwd). */\n front: string;\n /** The same character turned. */\n turned: string;\n /** Iris colour window override, merged over the violet default. */\n iris?: Partial<IrisColor>;\n /** Existing directory to write `<name>.debug.png` overlays into. */\n debugDir?: string;\n}\n\n/** HSV of an 8-bit RGB triple: hue in degrees, saturation and value in 0..1. */\nfunction rgbToHsv(r: number, g: number, b: number): [number, number, number] {\n r /= 255;\n g /= 255;\n b /= 255;\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const d = max - min;\n let h = 0;\n if (d > 0) {\n if (max === r) h = ((g - b) / d) % 6;\n else if (max === g) h = (b - r) / d + 2;\n else h = (r - g) / d + 4;\n h *= 60;\n if (h < 0) h += 360;\n }\n return [h, max === 0 ? 0 : d / max, max];\n}\n\n/** Grow `mask` by `r` px in every direction (square kernel). */\nfunction dilate(\n mask: Uint8Array,\n width: number,\n height: number,\n r: number,\n): Uint8Array {\n const out = new Uint8Array(width * height);\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n if (!mask[y * width + x]) continue;\n for (let dy = -r; dy <= r; dy++) {\n for (let dx = -r; dx <= r; dx++) {\n const yy = y + dy;\n const xx = x + dx;\n if (yy >= 0 && yy < height && xx >= 0 && xx < width)\n out[yy * width + xx] = 1;\n }\n }\n }\n }\n return out;\n}\n\n/** Shrink `mask` by `r` px in every direction; outside the image counts as\n * background. Erosion only ever clears pixels, so set ones are all it visits. */\nfunction erode(\n mask: Uint8Array,\n width: number,\n height: number,\n r: number,\n): Uint8Array {\n const out = new Uint8Array(width * height);\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n if (!mask[y * width + x]) continue;\n let keep = true;\n for (let dy = -r; dy <= r && keep; dy++) {\n for (let dx = -r; dx <= r; dx++) {\n const yy = y + dy;\n const xx = x + dx;\n if (\n yy < 0 ||\n yy >= height ||\n xx < 0 ||\n xx >= width ||\n !mask[yy * width + xx]\n ) {\n keep = false;\n break;\n }\n }\n }\n if (keep) out[y * width + x] = 1;\n }\n }\n return out;\n}\n\n/** Morphological close: weld pieces up to 2r apart, leaving the outer edges\n * where they were (a closed set never spills past the original's bbox). */\nfunction closeMask(\n mask: Uint8Array,\n width: number,\n height: number,\n r: number,\n): Uint8Array {\n return erode(dilate(mask, width, height, r), width, height, r);\n}\n\n/** 4-connected components of `mask` with at least `minArea` px, largest first. */\nfunction components(\n mask: Uint8Array,\n width: number,\n height: number,\n minArea: number,\n): IrisBlob[] {\n const seen = new Uint8Array(width * height);\n const out: IrisBlob[] = [];\n for (let i = 0; i < width * height; i++) {\n if (!mask[i] || seen[i]) continue;\n const stack = [i];\n seen[i] = 1;\n let x0 = width;\n let x1 = 0;\n let y0 = height;\n let y1 = 0;\n let n = 0;\n let sx = 0;\n let sy = 0;\n while (stack.length) {\n const p = stack.pop() as number;\n const x = p % width;\n const y = (p / width) | 0;\n n++;\n sx += x;\n sy += y;\n if (x < x0) x0 = x;\n if (x > x1) x1 = x;\n if (y < y0) y0 = y;\n if (y > y1) y1 = y;\n const neighbours: number[] = [];\n if (x > 0) neighbours.push(p - 1);\n if (x < width - 1) neighbours.push(p + 1);\n if (y > 0) neighbours.push(p - width);\n if (y < height - 1) neighbours.push(p + width);\n for (const q of neighbours) {\n if (seen[q] || !mask[q]) continue;\n seen[q] = 1;\n stack.push(q);\n }\n }\n if (n >= minArea) {\n out.push({\n x0,\n x1,\n y0,\n y1,\n w: x1 - x0 + 1,\n h: y1 - y0 + 1,\n area: n,\n cx: sx / n,\n cy: sy / n,\n });\n }\n }\n return out.sort((a, b) => b.area - a.area);\n}\n\n/** Merge a caller's partial iris window over the default, rejecting nonsense. */\nfunction resolveIris(override: Partial<IrisColor> | undefined): IrisColor {\n const iris = { ...DEFAULT_IRIS, ...override };\n if (iris.hueMin < 0 || iris.hueMax > 360 || iris.hueMin >= iris.hueMax) {\n throw new AutoRigInputError(\n `iris hue window must be 0 <= hueMin < hueMax <= 360, got ${iris.hueMin}..${iris.hueMax}`,\n );\n }\n if (iris.satMin < 0 || iris.satMin > 1) {\n throw new AutoRigInputError(\n `iris satMin must be within 0..1, got ${iris.satMin}`,\n );\n }\n return iris;\n}\n\n/**\n * Find the iris pair and the head silhouette in one image.\n *\n * Throws a path-qualified AutoRigInputError when no pair survives the filters\n * (the candidate count says whether the hue window found nothing at all or\n * found too much) or when the eye-row band holds no foreground.\n */\nasync function measureTurnImage(\n filePath: string,\n iris: IrisColor,\n): Promise<TurnImageMeasure> {\n const { width, height, rgba, hasAlpha } = await decodePng(filePath);\n const n = width * height;\n\n // An RGBA file whose alpha is entirely opaque is a reference that merely\n // carries a channel, not a render with a cut-out backdrop — key it by colour.\n let transparent = false;\n if (hasAlpha) {\n for (let i = 0; i < n; i++) {\n if (rgba[i * 4 + 3] < ALPHA_OPAQUE) {\n transparent = true;\n break;\n }\n }\n }\n const maskMode: \"alpha\" | \"keyed\" =\n hasAlpha && transparent ? \"alpha\" : \"keyed\";\n\n const irisMask = new Uint8Array(n);\n const fg = new Uint8Array(n);\n const value = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n if (rgba[i * 4 + 3] < ALPHA_OPAQUE) continue; // transparent = background\n const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);\n if (maskMode === \"alpha\") {\n fg[i] = 1;\n } else {\n const isBg =\n (hue >= BG_HUE_MIN &&\n hue <= BG_HUE_MAX &&\n s < BG_SAT_MAX &&\n v > BG_V_MIN) ||\n v < BG_V_BLACK;\n if (!isBg) fg[i] = 1;\n }\n if (\n hue >= iris.hueMin &&\n hue <= iris.hueMax &&\n s > iris.satMin &&\n v > IRIS_V_MIN &&\n v < IRIS_V_MAX\n ) {\n irisMask[i] = 1;\n value[i] = v;\n }\n }\n\n const minArea = Math.max(\n 1,\n Math.round((MIN_AREA * n) / MIN_AREA_REFERENCE_PIXELS),\n );\n const closeRadius = Math.max(\n 1,\n Math.round(\n (CLOSE_RADIUS * Math.max(width, height)) / CLOSE_RADIUS_REFERENCE_PX,\n ),\n );\n const meanValue = (b: IrisBlob): number => {\n let count = 0;\n let total = 0;\n for (let y = b.y0; y <= b.y1; y++) {\n for (let x = b.x0; x <= b.x1; x++) {\n const i = y * width + x;\n if (!irisMask[i]) continue;\n count++;\n total += value[i];\n }\n }\n return count ? total / count : 0;\n };\n const candidates = components(\n closeMask(irisMask, width, height, closeRadius),\n width,\n height,\n minArea,\n )\n .filter((b) => b.w < width * BLOB_MAX_FRAC && b.h < height * BLOB_MAX_FRAC)\n .filter((b) => meanValue(b) > IRIS_MEAN_V_MIN)\n .slice(0, MAX_CANDIDATES);\n\n let best: { score: number; pair: [IrisBlob, IrisBlob] } | null = null;\n for (let i = 0; i < candidates.length; i++) {\n for (let j = i + 1; j < candidates.length; j++) {\n const a = candidates[i];\n const b = candidates[j];\n const dx = Math.abs(a.cx - b.cx);\n const dy = Math.abs(a.cy - b.cy);\n if (dx < width * PAIR_DX_MIN_FRAC || dx > width * PAIR_DX_MAX_FRAC)\n continue;\n if (dy > height * PAIR_DY_MAX_FRAC) continue;\n const score = a.area + b.area;\n if (best === null || score > best.score) {\n const pair: [IrisBlob, IrisBlob] = a.cx <= b.cx ? [a, b] : [b, a];\n best = { score, pair };\n }\n }\n }\n if (best === null) {\n throw new AutoRigInputError(\n `no iris pair found in ${filePath} among ${candidates.length} candidate blobs ` +\n `(iris hue ${iris.hueMin}..${iris.hueMax}, sat > ${iris.satMin})`,\n );\n }\n\n const [irisL, irisR] = best.pair;\n const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);\n const { left, right } = foregroundSpan(\n fg,\n width,\n height,\n eyeRow - HEAD_BAND,\n eyeRow + HEAD_BAND,\n );\n // Every ratio divides by this half-width, so a band that keyed down to\n // nothing (or to a single column) must fail rather than report Infinity.\n if (right <= left) {\n throw new AutoRigInputError(\n `no head span at the eye row (y=${eyeRow}) in ${filePath}: the ${maskMode} foreground mask is empty there`,\n );\n }\n if (maskMode === \"keyed\" && right - left + 1 > width * KEYED_SPAN_MAX_FRAC) {\n throw new AutoRigInputError(\n `head span at the eye row (y=${eyeRow}) in ${filePath} covers ${right - left + 1}/${width} px: background not keyed / not an engine render`,\n );\n }\n\n return {\n file: filePath,\n width,\n height,\n maskMode,\n irisL,\n irisR,\n eyeRow,\n head: {\n left,\n right,\n cx: (left + right) / 2,\n half: headHalfOf({ left, right }),\n },\n pairCx: (irisL.cx + irisR.cx) / 2,\n eyeGap: irisR.cx - irisL.cx,\n };\n}\n\n/**\n * Iris widths split into far and near. FAR = the eye on the side the pair moved\n * TOWARD, which is the one rotating away from the viewer; `turnSign` says which\n * side that is. The measurement and the report must split them the same way, so\n * they share this.\n */\nfunction farNearWidths(\n m: TurnImageMeasure,\n turnSign: -1 | 1,\n): { far: number; near: number } {\n return turnSign < 0\n ? { far: m.irisL.w, near: m.irisR.w }\n : { far: m.irisR.w, near: m.irisL.w };\n}\n\n/** The overlay: iris boxes, head edges, head centre, pair centre. */\nfunction overlaySvg(m: TurnImageMeasure): string {\n const box = (b: IrisBlob, stroke: string) =>\n `<rect x=\"${b.x0}\" y=\"${b.y0}\" width=\"${b.w}\" height=\"${b.h}\" fill=\"none\" stroke=\"${stroke}\" stroke-width=\"3\"/>`;\n const tick = (x: number, half: number, stroke: string) =>\n `<line x1=\"${x}\" y1=\"${m.eyeRow - half}\" x2=\"${x}\" y2=\"${m.eyeRow + half}\" stroke=\"${stroke}\" stroke-width=\"3\"/>`;\n return (\n `<svg width=\"${m.width}\" height=\"${m.height}\">` +\n box(m.irisL, \"#ff0000\") +\n box(m.irisR, \"#00c000\") +\n tick(m.head.left, 40, \"#0000ff\") +\n tick(m.head.right, 40, \"#0000ff\") +\n tick(m.head.cx, 60, \"#ff8800\") +\n tick(m.pairCx, 60, \"#ff00ff\") +\n \"</svg>\"\n );\n}\n\n/** `label` prefixes the file name: the two inputs often share a basename\n * (`renders/head.png` + `ref/head.png`), and one would overwrite the other. */\nasync function writeOverlay(\n debugDir: string,\n label: \"front\" | \"turned\",\n m: TurnImageMeasure,\n): Promise<string> {\n const outPath = path.join(\n debugDir,\n `${label}-${path.basename(m.file, \".png\")}.debug.png`,\n );\n writeFileAtomic(outPath, await encodeOverlayPng(m.file, overlaySvg(m)));\n return outPath;\n}\n\n/** How far the front/turned mean iris heights may differ before the pair is\n * refused as not being at the same scale. A yaw foreshortens iris WIDTH, never\n * its height, so any difference here is framing/scale, not turn — 10% is\n * comfortably above the paint/detection noise a same-scale pair shows (the\n * fixtures in measure-turn.test.ts read within a percent) and comfortably\n * below a deliberate rescale. */\nconst IRIS_HEIGHT_SCALE_TOLERANCE = 0.1;\n\n/**\n * Measure a front/turned image pair and report the three turn ratios plus both\n * raw per-image measurements.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) →\n * `{ ok:false }`, matching measureLayers; any other throw propagates.\n */\nexport async function measureTurnReference(\n input: MeasureTurnInput,\n): Promise<MeasureTurnResult> {\n try {\n const iris = resolveIris(input.iris);\n const frontPath = resolveInputPath(input.front);\n const turnedPath = resolveInputPath(input.turned);\n // Resolve the debug dir before measuring (fail-fast): a missing or escaping\n // target should not cost two full decodes first.\n const debugDir =\n input.debugDir === undefined ? null : resolveOutputDir(input.debugDir);\n\n const front = await measureTurnImage(frontPath, iris);\n const turned = await measureTurnImage(turnedPath, iris);\n\n // A yaw does not change iris HEIGHT — only width, via foreshortening — so\n // a front/turned pair whose mean iris height differs is not at the same\n // scale/framing, and every ratio below would be measuring that instead of\n // the turn. Refuse it rather than silently reporting a scale change as one.\n const frontIrisH = (front.irisL.h + front.irisR.h) / 2;\n const turnedIrisH = (turned.irisL.h + turned.irisR.h) / 2;\n if (\n Math.abs(turnedIrisH - frontIrisH) / frontIrisH >\n IRIS_HEIGHT_SCALE_TOLERANCE\n ) {\n throw new AutoRigInputError(\n `front and turned images are not at the same scale: mean iris height ${frontIrisH.toFixed(1)}px front vs ${turnedIrisH.toFixed(1)}px turned, more than ${(IRIS_HEIGHT_SCALE_TOLERANCE * 100).toFixed(0)}% apart — a yaw does not change iris height, so the pair must share the same framing and head size`,\n );\n }\n\n // Where the eye pair sits on the head, per image; the CHANGE is the turn.\n const frontShift = front.pairCx - front.head.cx;\n const turnedShift = turned.pairCx - turned.head.cx;\n const shift = turnedShift - frontShift;\n // A pair that did not move has no far side, so there is no third value the\n // far/near rule below could use: treat a zero shift as a right turn, where\n // the ratio reads ~1 from either assignment anyway.\n const turnSign: -1 | 1 = shift < 0 ? -1 : 1;\n // Dividing the turned far/near by the same ratio at rest cancels a resting\n // asymmetry in the art, so what is left is the turn alone.\n const f = farNearWidths(front, turnSign);\n const t = farNearWidths(turned, turnSign);\n\n const debug =\n debugDir === null\n ? undefined\n : [\n await writeOverlay(debugDir, \"front\", front),\n await writeOverlay(debugDir, \"turned\", turned),\n ];\n\n return {\n ok: true,\n front,\n turned,\n farEyeRatio: t.far / t.near / (f.far / f.near),\n eyeShift: shift / front.head.half,\n silhouetteRatio: turned.head.half / front.head.half,\n turnSign,\n ...(debug === undefined ? {} : { debug }),\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n\nconst n1 = (v: number) => v.toFixed(1);\nconst n3 = (v: number) => v.toFixed(3);\n\n/** One image's raw block: what the ratios above were computed from. */\nfunction imageBlock(label: string, m: TurnImageMeasure): string[] {\n return [\n `# ${label} ${m.file} ${m.width}x${m.height} mask: ${m.maskMode}`,\n `iris widths ${m.irisL.w} / ${m.irisR.w} px centres ${n1(m.irisL.cx)} / ${n1(m.irisR.cx)} ` +\n `eye row ${m.eyeRow} gap ${n1(m.eyeGap)}`,\n `head ${m.head.left}..${m.head.right} centre ${n1(m.head.cx)} half ${n1(m.head.half)} ` +\n `pair centre ${n1(m.pairCx)}`,\n ];\n}\n\n/** Render a measurement as plain text: the three ratios with the raw numbers\n * behind each, then one block per image. */\nexport function formatTurnReport(result: TurnMeasurement): string {\n const { front, turned } = result;\n const f = farNearWidths(front, result.turnSign);\n const t = farNearWidths(turned, result.turnSign);\n const lines = [\n `farEyeRatio ${n3(result.farEyeRatio)} far/near iris width ${t.far}/${t.near} turned ` +\n `over ${f.far}/${f.near} front`,\n `eyeShift ${n3(result.eyeShift)} pair-vs-head centre ${n1(turned.pairCx - turned.head.cx)} px turned, ` +\n `${n1(front.pairCx - front.head.cx)} px front, over front head half ${n1(front.head.half)} px (hh)`,\n `silhouetteRatio ${n3(result.silhouetteRatio)} head half ${n1(turned.head.half)} px turned over ` +\n `${n1(front.head.half)} px front`,\n `turnSign ${result.turnSign} (the head turned toward the image's ${\n result.turnSign < 0 ? \"left\" : \"right\"\n })`,\n \"\",\n ...imageBlock(\"front\", front),\n \"\",\n ...imageBlock(\"turned\", turned),\n ];\n if (result.debug !== undefined) {\n lines.push(\"\", ...result.debug.map((p) => `debug overlay ${p}`));\n }\n return lines.join(\"\\n\");\n}\n","/**\n * Where the composer hangs an arm. One arm.png is the arm on the screen LEFT:\n * `arm_R` takes it as drawn and `arm_L` mirrored. Each of an arm's `cx` / `cy`\n * that the layout leaves unset is derived from the placed body's box: the\n * arm's shoulder pivot lands on the box's shoulder corner on that axis — the\n * box's left edge for `arm_R`, its right edge for `arm_L`, SHOULDER_DROP of\n * its height under its top. On a torso widest at its shoulders, the cap's\n * centre then sits on the torso's edge, overlapping it by the cap's radius.\n * An unset `w` is ARM_WIDTH of the body's width.\n *\n * The pivot is the rig's own: `armGeometry`, run on the resized part as\n * `auto_rig_from_layers` runs it on the composed layer, so the rig turns the\n * composed arm about the target to the pixel, with no second copy of its\n * shoulder rule here to keep in step.\n *\n * A pose forearm (`forearm_pose.png`: the screen-left forearm raised,\n * `forearm_pose_R` as drawn and `forearm_pose_L` mirrored) hangs from its\n * arm's elbow, so the composer puts its elbow end where the rig turns it. An\n * unset `w` scales it so its elbow-end width (2 r_e, measured on the trimmed\n * source) equals the placed arm's seam run, and an unset `cx` or `cy` pins\n * its elbow-end pivot (`forearmPoseGeometry`, measured on the resized part as\n * the shoulder is) on the arm's placed elbow. Both read the rig's geometry,\n * none of it copied here.\n */\n\nimport sharp from \"sharp\";\nimport {\n LayerGeometryError,\n armGeometry,\n createLayerSetMeasurer,\n forearmPoseGeometry,\n type ArmGeometry,\n type ForearmPoseGeometry,\n} from \"@ikijs/editor\";\nimport type { ArmLayout } from \"./compose\";\nimport { AutoRigInputError } from \"./limits\";\n\n/** An arm's default width, as a share of the placed body's width. Our own\n * value, provisional: to be picked by eye on the first full-body character. */\nexport const ARM_WIDTH = 0.4;\n/** How far under the body box's top its shoulder corners lie, as a share of\n * its height. Our own value, provisional: to be picked by eye on the first\n * full-body character. */\nexport const SHOULDER_DROP = 0.12;\n\n/** A placed part's box on the canvas, px. */\ninterface PlacedBox {\n left: number;\n top: number;\n w: number;\n h: number;\n}\n\n/**\n * Where an arm's resized part lands: by its rig shoulder pivot on the body\n * box's shoulder corner for each of `cx` / `cy` left unset, centred on a set\n * one as every other role's part is. An arm the rig would refuse as too short\n * is refused here, path-qualified.\n */\nexport async function armPlacement(\n role: \"arm_L\" | \"arm_R\",\n cfg: Pick<ArmLayout, \"cx\" | \"cy\">,\n part: { buf: Buffer; w: number; h: number },\n body: PlacedBox,\n): Promise<{\n left: number;\n top: number;\n /** The rig's elbow pivot on the canvas, px. */\n elbow: { x: number; y: number };\n /** The elbow seam's widest run, px: what a pose forearm's elbow end fits. */\n elbowRun: number;\n}> {\n const { data } = await sharp(part.buf)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n const layer = createLayerSetMeasurer({ width: part.w, height: part.h }).add({\n role,\n fileName: \"arm.png\",\n rgba: data,\n });\n if (layer === null) {\n throw new AutoRigInputError(\n `layout.${role}: arm.png is empty after alpha threshold once resized`,\n );\n }\n let g: ArmGeometry;\n try {\n // The axis keeps `side` the role's own all the same: arm_R on the screen\n // left, arm_L on the right.\n g = armGeometry(layer, role === \"arm_R\" ? Infinity : -Infinity);\n } catch (err) {\n if (err instanceof LayerGeometryError) {\n throw new AutoRigInputError(`layout.${role}: ${err.message}`);\n }\n throw err;\n }\n // Model space is centred on the measured canvas, here the part itself.\n const pivotX = g.shoulder.x + part.w / 2;\n const pivotY = part.h / 2 - g.shoulder.y;\n const cornerX = role === \"arm_R\" ? body.left : body.left + body.w;\n const cornerY = body.top + SHOULDER_DROP * body.h;\n const left = Math.round(\n cfg.cx === undefined ? cornerX - pivotX : cfg.cx - part.w / 2,\n );\n const top = Math.round(\n cfg.cy === undefined ? cornerY - pivotY : cfg.cy - part.h / 2,\n );\n return {\n left,\n top,\n elbow: {\n x: left + g.elbow.x + part.w / 2,\n y: top + part.h / 2 - g.elbow.y,\n },\n elbowRun: g.seamRun[1] - g.seamRun[0],\n };\n}\n\ntype PoseRole = \"forearm_pose_L\" | \"forearm_pose_R\";\n\n/** A pose forearm's geometry on a PNG of the given size, read as the rig\n * reads a layer; an empty one is refused path-qualified. */\nasync function poseGeometryOf(\n role: PoseRole,\n png: Buffer,\n size: { w: number; h: number },\n when: string,\n): Promise<ForearmPoseGeometry> {\n const { data } = await sharp(png)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n const layer = createLayerSetMeasurer({\n width: size.w,\n height: size.h,\n }).add({ role, fileName: \"forearm_pose.png\", rgba: data });\n if (layer === null) {\n throw new AutoRigInputError(\n `layout.${role}: forearm_pose.png is empty after alpha threshold${when}`,\n );\n }\n return forearmPoseGeometry(layer);\n}\n\n/**\n * The width that fits a pose forearm to its arm: the trimmed source scaled\n * so its elbow end's width (2 r_e) equals the arm's elbow run, at least 1.\n */\nexport async function forearmPoseWidth(\n role: PoseRole,\n trimmed: { data: Buffer; w: number; h: number },\n elbowRun: number,\n): Promise<number> {\n const g = await poseGeometryOf(role, trimmed.data, trimmed, \"\");\n return Math.max(1, Math.round((trimmed.w * elbowRun) / (2 * g.radius)));\n}\n\n/**\n * Where a pose forearm's resized part lands: its elbow-end pivot on the\n * arm's placed elbow for each of `cx` / `cy` left unset, centred on a set one\n * as every other role's part is.\n */\nexport async function forearmPosePlacement(\n role: PoseRole,\n cfg: Pick<ArmLayout, \"cx\" | \"cy\">,\n part: { buf: Buffer; w: number; h: number },\n elbow: { x: number; y: number },\n): Promise<{ left: number; top: number }> {\n const { pivot } = await poseGeometryOf(role, part.buf, part, \" once resized\");\n // Model space is centred on the canvas, here the part itself.\n const pivotX = pivot.x + part.w / 2;\n const pivotY = part.h / 2 - pivot.y;\n return {\n left: Math.round(\n cfg.cx === undefined ? elbow.x - pivotX : cfg.cx - part.w / 2,\n ),\n top: Math.round(\n cfg.cy === undefined ? elbow.y - pivotY : cfg.cy - part.h / 2,\n ),\n };\n}\n","/**\n * The text lines `auto_rig_from_layers` and `render_poses` print the engine's\n * `checkPhysics` report as, after the fold report.\n */\n\nimport type { PhysicsReport, PhysicsTarget } from \"@ikijs/engine\";\nimport { foldPose } from \"./fold-report\";\n\n/**\n * `report` as text lines: one `PHYSICS` line per target in the report's\n * order, or `PHYSICS: no rigs`. A line gives the target's kind, its rig (`id`,\n * or `id/segment [inputs]` for a chain segment), `input -> output`, the step's\n * setting with the output's peak, when, its final value and the largest part\n * move with what the output drives, then the idle's peak, when and move, and\n * ` — <why>` when the target is not `ok`.\n */\nexport function formatPhysicsReport(report: PhysicsReport): string[] {\n if (report.targets.length === 0) return [\"PHYSICS: no rigs\"];\n return report.targets.map(targetLine);\n}\n\nfunction targetLine(t: PhysicsTarget): string {\n const inputs = t.input.join(\", \");\n const rig =\n t.rig.kind === \"chain\"\n ? `${t.rig.id}/${t.rig.segment} [${inputs}]`\n : `${t.rig.id} ${inputs}`;\n const drives =\n t.drives.length === 0 ? \"\" : ` (${t.drives.map((d) => d.id).join(\", \")})`;\n const { step, idle } = t;\n return (\n `PHYSICS ${t.kind} ${rig} -> ${t.output}: ` +\n `step ${foldPose(step.values).name} peak ${step.peak.toFixed(2)} at ${step.at.toFixed(2)} s, ` +\n `final ${step.final.toFixed(2)}, moves ${pxText(step.displacementPx)} model px${drives}; ` +\n `idle peak ${idle.peak.toFixed(2)} at ${idle.at.toFixed(2)} s, ${pxText(idle.displacementPx)} model px` +\n (t.why === undefined ? \"\" : ` — ${t.why}`)\n );\n}\n\n/** One decimal, floored as the engine's frozen `why` is, so a frozen 0.96 px\n * never reads `1.0` on its own line. */\nfunction pxText(px: number): string {\n return (Math.floor(px * 10) / 10).toFixed(1);\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport type { PatchReport, RigPatch } from \"@ikijs/editor\";\nimport {\n validateIki,\n describeIki,\n describeIkiAt,\n listStandardParameters,\n describeRigPlan,\n formatRigPlanReport,\n autoRigFromLayers,\n} from \"./tools\";\nimport { composeLayersFromParts } from \"./compose\";\nimport { formatFoldReport } from \"./fold-report\";\nimport { formatPhysicsReport } from \"./physics-report\";\nimport { measureLayers, formatMeasureReport } from \"./measure\";\nimport { measureTurnReference, formatTurnReport } from \"./measure-turn\";\nimport { renderPoses } from \"./render-poses\";\n\n/** Injected by tsup (and vitest) from this package's package.json version. */\ndeclare const __MCP_VERSION__: string;\n\n/** One `PATCH` line per op `auto_rig_from_layers` replayed. */\nfunction formatPatchReports(reports: PatchReport[]): string[] {\n return reports.map((r) => {\n const at = Object.keys(r.at)\n .sort()\n .map((p) => `${p}=${r.at[p]}`)\n .join(\" \");\n const where =\n r.cols !== undefined && r.rows !== undefined\n ? `cols ${r.cols[0]}-${r.cols[1]}, rows ${r.rows[0]}-${r.rows[1]}`\n : \"vertices\";\n return `PATCH ${r.index} ${r.target} at ${at}: ${r.moved} of ${r.of} points (${where}), largest move ${r.maxPx} model px`;\n });\n}\n\nexport function createIkiMcpServer(): McpServer {\n const server = new McpServer({ name: \"iki\", version: __MCP_VERSION__ });\n\n server.registerTool(\n \"validate_iki\",\n {\n description:\n \"Validates a raw .iki model (object or JSON string); fail-fast — returns at most ONE error, so fix one, re-run.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = validateIki(model);\n const text = r.ok ? \"OK\" : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"describe_iki\",\n {\n description:\n \"Summarizes a valid model's canvas/params/parts/deformers and its expressions and motion clips (with the descriptions a host picks them by); returns an error for an invalid model. It is also the patch writer's view of a rigged model: each part's rest box in model px and in bust-render px, each part's warp stops, each warp2d's stops, and faceWidth, which is what an auto_rig_from_layers `patches` op is aimed with. Pass exactly one of model or modelPath; prefer modelPath for a written rig so a large model never crosses your context.\",\n inputSchema: {\n model: z\n .unknown()\n .optional()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n modelPath: z\n .string()\n .optional()\n .describe(\n \"Path to a written .iki model (relative to the working directory, inside it)\",\n ),\n },\n },\n async ({ model, modelPath }) => {\n try {\n if ((model === undefined) === (modelPath === undefined)) {\n const error = \"pass model or modelPath\";\n return {\n content: [{ type: \"text\", text: `INVALID: ${error}` }],\n structuredContent: { ok: false, error },\n };\n }\n const r =\n modelPath !== undefined\n ? describeIkiAt(modelPath)\n : describeIki(model);\n const text = r.ok\n ? JSON.stringify(r.summary, null, 2)\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"list_standard_parameters\",\n {\n description:\n \"Lists the recommended standard parameter ids a host can drive without per-model wiring.\",\n inputSchema: {},\n },\n async () => {\n const params = listStandardParameters();\n const text = params.map((p) => `${p.id} — ${p.description}`).join(\"\\n\");\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { parameters: params },\n };\n },\n );\n\n server.registerTool(\n \"describe_rig_plan\",\n {\n description:\n \"Lists the fields of the `rigPlan` input of auto_rig_from_layers: each one's path, default, range, recommended span, step, unit, the poses it shows at, the report reading that shows it and the `turnTargets` cue that fits it when given. The one source of those numbers.\",\n inputSchema: {},\n },\n async () => {\n const { fields } = describeRigPlan();\n const text = fields\n .map(\n (f) =>\n `${f.path} default ${f.default} range ${f.range[0]}..${f.range[1]} recommended ${f.recommended[0]}..${f.recommended[1]} step ${f.step} ${f.unit} — ${f.what}; shows at ${f.poses.map((p) => JSON.stringify(p)).join(\" \")}; cue ${f.cue ?? \"none\"}; fitted by ${f.fitBy ?? \"none\"}${f.provisional ? \"; provisional\" : \"\"}`,\n )\n .join(\"\\n\");\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { fields },\n };\n },\n );\n\n server.registerTool(\n \"auto_rig_from_layers\",\n {\n description:\n \"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, 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, 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 — a spring's, or each chain segment's — reading ok, frozen or unstable with the step and idle amplitudes, or `PHYSICS: no rigs`; report-only too. `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 — `PATCH <i> <target> at <Param=v …>: <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 — 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]…` and nothing is written; an op with a missing field or a field of the wrong type is the SDK's input validation error.\",\n inputSchema: {\n layers: z\n .array(\n z.object({\n fileName: z\n .string()\n .optional()\n .describe(\n \"Role-bearing filename; defaults to the basename of `path`.\",\n ),\n path: z\n .string()\n .describe(\"PNG file path (resolved against cwd).\"),\n }),\n )\n .describe(\"Full-canvas PNG layers; all must share the same size.\"),\n outputPath: z\n .string()\n .optional()\n .describe(\n \"Output .iki path (resolved against cwd; parent dir must exist).\",\n ),\n quantizeColors: z\n .number()\n .int()\n .min(2)\n .max(256)\n .optional()\n .describe(\n \"Palette-quantize the atlas PNG to this many colours (2..256). Flat-shaded art keeps its look at 256 and the model shrinks to about a quarter; omit for lossless. A `nose` layer stays lossless on a second atlas page of its own, since the palette rims a soft-shaded nose's feather; the nose's own lossless page adds a content-dependent amount, since splitting it off also changes how page 0 re-quantizes without it; the result's `atlasBytes` sums both pages.\",\n ),\n turnTargets: z\n .object({\n eyeShift: z.number().optional(),\n farEyeRatio: z.number().optional(),\n silhouetteRatio: z.number().optional(),\n noseShift: z.number().optional(),\n mouthShift: z.number().optional(),\n })\n .passthrough()\n .optional()\n .describe(\n \"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 — 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 — 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: …` 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.\",\n ),\n style: z\n .unknown()\n .optional()\n .describe(\n \"Removed in @ikijs/mcp 0.30.0: pass `rigPlan`. Any value here is refused with the field map.\",\n ),\n rigPlan: z\n .object({\n turn: z\n .object({\n amount: z.number().optional(),\n featureLead: z.number().optional(),\n eyeForeshorten: z.number().optional(),\n noseLead: z.number().optional(),\n })\n .passthrough()\n .optional(),\n hair: z\n .object({\n follow: z.number().optional(),\n outlineFollow: z.number().optional(),\n sway: z.number().optional(),\n })\n .passthrough()\n .optional(),\n eyes: z\n .object({ blink: z.number().optional() })\n .passthrough()\n .optional(),\n })\n .passthrough()\n .optional()\n .describe(\n \"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> …`; an object left out or `{}` is the profile. The result reports what the rig built with as `rigPlan` and a `RIGPLAN:` line.\",\n ),\n patches: z\n .array(\n z\n .object({\n target: z.string(),\n at: z.record(z.string(), z.number()),\n region: z\n .object({\n role: z.string(),\n // Not z.tuple: its JSON Schema is the array-form `items`\n // draft 2020-12 forbids. The rig checks the pair's order.\n x: z.array(z.number()).length(2),\n y: z.array(z.number()).length(2),\n })\n .passthrough(),\n by: z.object({ dx: z.number(), dy: z.number() }).passthrough(),\n falloff: z.number().optional(),\n why: z.string().optional(),\n })\n .passthrough(),\n )\n .optional()\n .describe(\n \"Displacements ADDED to EXISTING keyform stops of the freshly generated rig, each op `{ target, at, region, by, falloff?, why? }`. They are replayed on every rig of these inputs, over whatever the rig now bakes, so they hold through a layout or `rigPlan` retune; ops on one stop add up, whatever their order. `target` is a feature grid — `eyeWarp_L`, `eyeWarp_R`, `browWarp_L`, `browWarp_R`, `noseWarp`, `mouthWarp`, whose `at` names both `ParamAngleX` and `ParamAngleY`, each -30, 0 or 30, never both 0 — or a mesh part with warps (`face`, `hair_front`, …), whose `at` names exactly one parameter at one of that part's warp keyform values, never the parameter's default nor the stop where the rig shuts the part on purpose (`eye_*` and `lash_lower_*` at their `ParamEye*Open` 0, the lip set and its tongue and teeth at `ParamMouthOpenY` 0), which the fold check exempts, nor a `ParamAngleZ` or `ParamBodyAngleZ` stop (they roll the deformers the part hangs under, so a displacement there is turned off the screen axes). The rest pose is the drawn art and no patch changes it. `bodyWarp` and the matrix deformers are not targets, and a patch adds no stop and changes no parameter range. `region` `{ role, x: [from, to], y: [from, to] }` is a rectangle in fractions of the REST layer box (the opaque crop) of `role`, origin top-left, x right, y DOWN, and may reach past the box: the target's points whose REST position lies inside take the whole of `by`, those within `falloff` of it a smooth share, the rest nothing. `by` `{ dx, dy }` and `falloff` are in face widths (the `face` layer's crop width), on screen axes: +dx toward the viewer's right (a character's `_L` side), +dy DOWN. Between stops the engine blends linearly, so a fix at ParamAngleX -30 shows at half strength at -15 and none at rest. `why` is a note the rig ignores. An op this schema accepts but the rig refuses — an unknown key, target, role or stop, the rest stop or a shut stop, a region running backwards or catching none of the target's points — comes back as `INVALID: patches[i]…`, listing the keys, targets, stops or roles there are, or where the target's points lie in the role's box, and nothing is written; a missing field or one of the wrong type is refused by the schema itself, as the SDK's input validation error.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await autoRigFromLayers({\n ...args,\n // `.length(2)` makes each region span a pair, which its inferred\n // `number[]` cannot say.\n patches: args.patches as RigPatch[] | undefined,\n });\n const text = r.ok\n ? [\n r.path,\n formatRigPlanReport(r.rigPlan),\n ...formatPatchReports(r.patches ?? []),\n ...formatFoldReport(r.folds, r.canvas),\n ...formatPhysicsReport(r.physics),\n ].join(\"\\n\")\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"compose_layers_from_parts\",\n {\n description:\n \"Composes AI-generated part PNGs into canvas-aligned, role-named PNG layers on disk, ready for auto_rig_from_layers (the eyewhite split, alpha-trim/white-key, and placement pipeline the character-generation skill needs), with the same geometry report measure_layers returns standalone included inline. face, eyewhite, iris, brow, hair_front are required, with mouth.png — or the lip set's mouth_keyed.png (the open mouth, its inside painted flat #00FF00) + mouth_interior.png (the cavity, teeth and tongue alone), which the composer keys and splits into mouth_inner / lip_lower / lip_upper on one frame so auto_rig_from_layers folds the mouth open like the eyelid, the interior's light paint (luma 100 and over) written as mouth_tongue and mouth_teeth on the same frame, riding the opening's bottom and the upper line and clipped to the cavity (listed in `skipped` when the interior has none); the two routes cannot be mixed, one keyed file without the other is refused, and a key that fails (no green, green outside the opening, an outline not closed round it, more than one opening, no skin under the opening, an interior that is only lips, or one drawn opaque on a non-white or noisy ground) is refused naming the regeneration; with the lip set neither mouth nor mouth_open is written and preview.png shows the mouth closed, as the rig draws the rest pose. hair_back, body, mouth_open (legacy route only), blush (one blush.png makes the blush_L/blush_R pair) and nose are optional — without a nose layer the head still turns on the rig's default profile, but it has no nose to lead the turn, and `auto_rig_from_layers` fits no turn to the art (`turnTargets` is inert, no `turn` report). One arm.png — the arm on the screen LEFT, drawn hanging with its shoulder at the top — makes both arms of a full body: arm_R takes it as drawn and arm_L mirrored. The arms are opt-in: without arm.png the compose is a bust's and `skipped` never lists them. arm.png needs body.png, and each arm is hung on the body's shoulder by default (see `layout`). One forearm_pose.png — the arm's forearm raised, on the screen LEFT, standing up from its elbow with the hand at the top — makes both pose forearms (forearm_pose_R as drawn, forearm_pose_L mirrored): each is scaled so its elbow end is as wide as its arm's elbow run and pinned on that arm's elbow (see `layout`), and it needs arm.png. With one, preview-pose.png shows the switch at 1 as the rig draws it (the hanging forearms hidden below the elbow, the pose forearms over everything) while preview.png stays the rest pose; without one it is removed. The inline report carries the full-body checks too: a body whose feet a tall canvas's bottom cuts off, an arm without a body, an arm whose shoulder cap does not reach under the torso's edge, and a pose forearm without its arm or off its arm's elbow in pivot, width or length. A nose whose dense core is a speck — under a quarter of its trimmed part's width or height, such as a lone nostril mark or highlight — is sized and placed whole, and the inline report warns of it. A light mark drawn detached above the eye white, such as a double-eyelid crease, is dropped from the sclera (the iris's clip); dark strokes there stay lash ink. The eyewhite's dark lower lid — its line and lashes — becomes lash_lower_L/lash_lower_R, drawn over the iris; a white with none writes none and lists them in `skipped`.\",\n inputSchema: {\n partsDir: z\n .string()\n .describe(\n \"Directory of the source part PNGs (resolved against cwd).\",\n ),\n outDir: z\n .string()\n .describe(\n \"Existing directory to write the role layer PNGs + preview.png (and preview-pose.png when there is a forearm_pose.png) into (resolved against cwd; must already exist; confined to the working directory). Reused across runs: a role this run does not write — one it skips, or an arm or pose forearm once arm.png or forearm_pose.png is gone, preview-pose.png included — has its stale PNG from an earlier run deleted.\",\n ),\n layout: z\n .record(\n z.string(),\n z\n .object({\n cx: z.number(),\n cy: z.number(),\n w: z.number(),\n h: z.number(),\n })\n .partial(),\n )\n .optional()\n .describe(\n \"Per-role override merged over the built-in defaults, keyed by role — hair_back, body, arm_L, arm_R, face, blush_L, blush_R, nose, mouth, mouth_open, mouth_inner, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front, forearm_pose_L, forearm_pose_R — e.g. `{ eye_L: { cx: 660 } }`. `w` is an integer in 1..1100 (the canvas width) and `h` in 1..canvasHeight; omit `h` to keep the part's own aspect, set it to stretch. The defaults of the face's features — blush, nose, mouth, mouth_open, mouth_inner, eyes, irises, lashes, brows — are proportions of the face: an override of face.cx, face.cy or face.w carries them with it (scaled by the width; face.h stretches the face alone), while a feature's own override names canvas px. The nose is sized and placed by its dense core (its pixels at alpha >= 128, the drawing inside a soft nose's feather), not its whole part: `w`/`h` size the core, `cx` centres it, and a set `cy` centres its rows. A nose whose core is a speck — under a quarter of the trimmed part's width or height, such as a lone nostril mark or highlight — is sized and placed whole instead, and the report warns of it. Its `cy` defaults to unset, which lands the core's bottom row (the tip) 0.66 of the way from the eye row down to the mouth's, so the nose follows a retuned eye or mouth row. eye_L/lash_L and eye_R/lash_R are cut from one eyewhite into one frame, so each pair must land on the same frame — a pair set to land apart is rejected. lash_lower_L/lash_lower_R are cut from it too and have no key: they land on their eye's frame. mouth_inner is the lip set's one frame (mouth_open's place by default; lip_lower, lip_upper, mouth_tongue and mouth_teeth have no key and land on it, so a retune moves them together), and with the lip set the nose's tip rule reads layout.mouth_inner.cy. arm_L/arm_R have no cx/cy/w defaults: an unset `w` is 0.4 of the placed body's width, and an unset `cx` or `cy` hangs the arm's shoulder pivot — the one auto_rig_from_layers turns it about — on the body box's shoulder corner on that axis: its left edge for arm_R, its right edge for arm_L, 0.12 of its height under its top. A set one centres the arm as for every other role. forearm_pose_L/forearm_pose_R have no cx/cy/w defaults either: an unset `w` scales the forearm so its elbow end (the shoulder rule run from its bottom) is as wide as the placed arm's elbow run, and an unset `cx` or `cy` pins that elbow end's pivot on the arm's elbow — the one auto_rig_from_layers hangs it from.\",\n ),\n mirrorParts: z\n .array(z.string())\n .optional()\n .describe(\n \"Part files to flip left-right as they are read, e.g. `[\\\"eyewhite.png\\\"]`. The composer reads eyewhite.png as the eye on the screen LEFT (lash wing at the image's left end, lash-free tear duct at its right), brow.png as the brow on the screen RIGHT (thick head at the image's left end, tail at its right), blush.png as the blush on the screen LEFT (outer end, toward the face's edge, at the image's left end, inner end at its right), arm.png as the arm on the screen LEFT (the character's right, hanging, its shoulder at the image's top), and forearm_pose.png as the raised forearm on the screen LEFT (standing up from its elbow, the hand at the image's top, the thumb toward the body at the image's right); a part drawn the other way round is fixed here for free. It flips the source, so every role cut from it flips together and an eye's sclera and lash stay in one frame.\",\n ),\n canvasHeight: z\n .number()\n .optional()\n .describe(\n \"The canvas's height in px: an even integer in 1100..4096, default 1100 (a square bust canvas; at 1100 every output is byte-identical to leaving it out). The width stays 1100. The canvas grows downward: every default and every override keeps its canvas px from the top-left, so the head lands where it does on a bust and a full body gets room below. An odd height is refused — model space is centred on the canvas, so it would put the head on a half pixel — and it is checked before any part decodes.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await composeLayersFromParts(args);\n const text = r.ok\n ? [\n ...r.layers.map((l) => l.path),\n formatMeasureReport({ ...r.measure, layersDir: r.outDir }),\n ].join(\"\\n\")\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"measure_layers\",\n {\n description:\n \"Reports read-only geometry checks over an already-composed layers directory — the same checks compose_layers_from_parts returns inline (iris ratio/offset, eye aspect, cropped/cut edges, a nose whose dense core is a speck of its crop, missing optional roles, a body whose feet a tall canvas's bottom cuts off, an arm without a body, an arm whose shoulder cap does not reach under the torso's edge on its shoulder pivot's row, a pose forearm without its arm or whose elbow end is off its arm's elbow in pivot, width or length, and the lip set: a partial one or one beside mouth/mouth_open, the fold's contract per column of the opening, an opening too narrow or short, a line too thin, green left, an interior with holes, and of mouth_tongue/mouth_teeth: one with no lip set, one on another canvas, one whose box leaves mouth_inner's — with the opening's size and the MouthOpen below which no slit shows). Every preview*.png is skipped. Use to re-check a layers dir without recomposing. Its nose check reads the composed file against its crop, which is what auto_rig_from_layers acts on. Compose's inline report does the same unless the composer found the source part's core a speck, which it reports instead — so a speck that resampling erased from the layer shows there and not here.\",\n inputSchema: {\n layersDir: z\n .string()\n .describe(\n \"Directory of role-named layer PNGs (resolved against cwd).\",\n ),\n },\n },\n async ({ layersDir }) => {\n try {\n const r = await measureLayers({ layersDir });\n const text = r.ok ? formatMeasureReport(r) : `INVALID: ${r.error}`;\n // Spread into a fresh object: MeasureResult's ok:true arm is an\n // intersection with the MeasureReport interface, which TS won't accept\n // directly against the SDK's `Record<string, unknown>` structuredContent\n // — spreading drops that nominal interface identity, same value.\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { ...r },\n };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"measure_turn_reference\",\n {\n description:\n \"Measures how far a head turns between two images of the same character — a front view and a turned one, at the SAME scale — 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.\",\n inputSchema: {\n front: z\n .string()\n .describe(\"Front-facing PNG file path (resolved against cwd).\"),\n turned: z\n .string()\n .describe(\"The same character turned, as a PNG file path.\"),\n iris: z\n .object({\n hueMin: z.number().min(0).max(360),\n hueMax: z.number().min(0).max(360),\n satMin: z.number().min(0).max(1),\n })\n .partial()\n .optional()\n .describe(\n \"Iris colour window override merged over the violet default (hue 230..300, sat > 0.22) — set it for a character whose eyes are another colour.\",\n ),\n debugDir: z\n .string()\n .optional()\n .describe(\n \"Existing directory (resolved against cwd; confined to the working directory) to write `front-<name>.debug.png` / `turned-<name>.debug.png` overlays into, with the iris boxes and head edges drawn.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await measureTurnReference(args);\n const text = r.ok ? formatTurnReport(r) : `INVALID: ${r.error}`;\n // Spread into a fresh object: the ok:true arm is an intersection with\n // the TurnMeasurement interface, which TS won't accept directly against\n // the SDK's Record<string, unknown> structuredContent.\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { ...r },\n };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"render_poses\",\n {\n description:\n \"Renders a rigged .iki into the character loop's pose PNGs with the real engine, through the installed Chrome, Edge or Chromium run headless (set CHROME_PATH to pick one). The model decides the set: a bust gets 560x560 shots (rest, turns, nod, blinks, gaze, combined — ParamAngleX/Y/Z all at 30 — and stress: ParamAngleX/Y/Z all at -30, ParamMouthOpenY 1, both eyes at 0.5, the brows at opposite extremes (ParamBrowLY -1, ParamBrowRY 1, ParamBrowLAngle 1, ParamBrowRAngle -1) and each body angle the model declares at -10); a mouth adds 720x480 mouth crops; a full body (taller than wide) adds the full-canvas body, arm and elbow poses on a 1400-wide canvas, and a model with a pose forearm adds the full-pose-* shots. Given `poses` (see its field), the standard set is not rendered: only those poses are, each crop clamped to the model's canvas. Writes <pose>.png files into outDir, overwriting same-named files in place; returns the written paths one per line, then the model's fold report (the result's `folds`), checked by the engine over its own pose set plus any `poses`, each of which a `FOLD` line names by its settings, not its PNG name: a `FOLD` line per warp deformer or mesh part that flips (ratio <= 0) or collapses (under 0.1) at some pose — its cell or triangle, the ratio of its area there to at rest, the pose as its parameter settings (`rest` for none) and where it rests, in model space and in model px from the top-left (the layer PNGs' own pixels, not a render's) — or `FOLDS: none over N poses`, then a `FOLDS expected:` line naming the closures the rig draws on purpose (an eye or the mouth shut), each by part id, ratio and the parameter that shuts it. Report-only: a fold never fails the render. The `PHYSICS` lines follow the fold report (the result's `physics`), one per physics rig output of the model's own rigs — `poses` do not enter it — reading ok, frozen or unstable with the step and idle amplitudes, or `PHYSICS: no rigs`; report-only too. Fails with INVALID when no browser is found or an input is refused; a browser that cannot start is a tool error.\",\n inputSchema: {\n modelPath: z\n .string()\n .describe(\n \"Rigged .iki file path (resolved against cwd; must sit under the working directory).\",\n ),\n outDir: z\n .string()\n .describe(\n \"Existing directory to write the pose PNGs into (resolved against cwd; must already exist; confined to the working directory).\",\n ),\n poses: z\n .array(\n z.object({\n name: z.string(),\n values: z.record(z.string(), z.number()),\n crop: z\n .object({\n x: z.number(),\n y: z.number(),\n w: z.number(),\n h: z.number(),\n })\n .optional(),\n }),\n )\n .optional()\n .describe(\n \"Caller-named poses rendered INSTEAD of the standard set, each `{ name, values, crop? }`, in order. `name` becomes `<outDir>/<name>.png` and the result's pose name: letters, digits, `_`, `.` and `-` only, unique in the list ignoring case. `values` are parameter settings (every other parameter at its default; an id the model lacks is ignored). `crop` `{ x, y, w, h }` is a rectangle in model px from the top-left — the frame of describe_iki's boxes and of the `FOLD` lines — clamped to the model's canvas, then drawn 720 px wide at its own aspect; without one a pose is framed as the standard shots (560x560, the middle square on a full body). Each pose is also added to the fold sweep, after the engine's own poses. An empty list, a bad or repeated name, a non-finite value, or a crop that misses the canvas or would draw under 1 or over 8192 px tall comes back as `INVALID: poses…` and nothing is rendered.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await renderPoses(args);\n const text = r.ok\n ? [\n ...r.poses.map((p) => p.path),\n ...formatFoldReport(r.folds, r.modelCanvas),\n ...formatPhysicsReport(r.physics),\n ].join(\"\\n\")\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n return server;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,QAAQ,YAAY,MAAM,WAC1E,SAAS,cAAc,MACvB,I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M,EAAE,IAAI;AAAA,UAC5B,GAAG,iBAAiB,EAAE,OAAO,EAAE,WAAW;AAAA,UAC1C,GAAG,oBAAoB,EAAE,OAAO;AAAA,QAClC,EAAE,KAAK,IAAI,IACX,YAAY,EAAE,KAAK;AACvB,eAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,KAAK,CAAC,GAAG,mBAAmB,EAAE;AAAA,MACnE,SAAS,KAAK;AACZ,cAAM,QAAQ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC7D,eAAO;AAAA,UACL,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,qBAAqB,KAAK,GAAG,CAAC;AAAA,UAC9D,mBAAmB,EAAE,IAAI,OAAO,MAAM;AAAA,UACtC,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["import_node_fs","import_node_path","import_format","import_editor","xRight","yBottom","px","import_format","target","flat","import_format","import_format","import_format","import_format","P","target","import_format","px","target","import_node_fs","import_node_path","import_format","path","fs","import_node_fs","import_node_path","fs","path","os","poses","path","import_editor","sharp","scanAlphaBbox","placement","clamp","path","placement","import_node_fs","import_node_path","import_sharp","import_editor","import_editor","px","import_node_fs","import_node_path","import_node_path","import_editor","path","import_editor","k","import_node_path","import_editor","import_sharp","import_editor","px","from","sharp","z","path","import_node_path","import_editor","import_editor","dilate","components","path","run","fs","path","import_sharp","import_editor","sharp","scale","sharp","scanAlphaBbox","path","fs","placement","px","cfg","part","split","left","top","input","px"]}