rig-parts 1.55.1 → 1.55.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -463,6 +463,18 @@ bun run selftest # every gate's controls; with the examples fetched, bui
463
463
  bun run smoke # pack, install into an empty directory, run from the install (needs a network)
464
464
  ```
465
465
 
466
+ The generated `foot-ownership` suite can be run alone with
467
+ `bun run selftest -- --only foot-ownership` (exit 2 means a green partial run,
468
+ not a full-tree verdict). Issue #638's revised acceptance requires zero foreign-leg
469
+ components and reports historical own-cap components separately; it was changed
470
+ after measurement, and the historical case did not pass the original second-island
471
+ 1% bar. Issue #637 additionally preserves assigned own-cap connections under covers:
472
+ the generated default is now one connected component, retaining the historical
473
+ own-cap pixels and their bridge. The controls require both historical measurements
474
+ and current connected ownership, with no foreign-leg pixels.
475
+ [AUTHORING's limb section](docs/AUTHORING.md#limbs-cut-at-their-joints-limbs-issue-349)
476
+ records the generated default-cap case and its preservation controls.
477
+
466
478
  [CLAUDE.md](CLAUDE.md) is the doctrine, [CONTRIBUTING.md](CONTRIBUTING.md) the
467
479
  practice, [RELEASING.md](RELEASING.md) the cut, [docs/STABILITY.md](docs/STABILITY.md)
468
480
  the interface it holds.
package/docs/AUTHORING.md CHANGED
@@ -108,7 +108,7 @@ read by no CPU stage).
108
108
  | `assemble.extend_below_crop` | assemble | **proposed** with the plan: `{part, run, tag}` — a head-run part that reaches the bottom of the head crop is continued from a full-run layer, whole connected components |
109
109
  | `assemble.patches` | assemble; `meshes`/`regions` keys may name them too | **authored**, optional: `[{name, box, alpha, draw}]` — an extra part cut from the **painting** itself, for figure no See-through layer holds (a hem both runs dropped). `box` is `[x0, y0, x1, y1]` in **rig** pixels, `x1`/`y1` exclusive — the space of `parts.json` and `recomposite_rig.png`, where the hole is found; `alpha` is `"silhouette"` (the painting's figure silhouette inside the box, the one `--seam silhouette` uses) or `"box"` (the whole box); `draw` is `"back"`, `"front"` or `{"before": "<plan part>"}`. A patch is always a region: its bone is `regions.<name>`, in the one place every region's bone lives, and a `meshes` entry for it is refused. See §5 for how to place one |
110
110
  | `assemble.cuts` | assemble; `meshes`/`regions` keys may name the new parts too, and must (each is a part like any other) | **authored**, optional (issue #170): `[{from, into, polygon, draw, overlap, under, under_fill}]`, `under` and `under_fill` optional — a plan part's layer cut by a polygon the author draws: the pixels of plan part `from` whose **centre** lies inside `polygon` (even-odd; a centre exactly on an edge is outside) leave `from` and make the new part `into`, colour and alpha, so every pixel of the layer ends in exactly one of the two. `polygon` is `[[x, y], …]`, at least three points, non-negative integer **rig** pixels — the space of `parts.json` and of the patches' boxes. The file that shows the layer in those coordinates is `assemble`'s own `rig/parts/<from>.png`, placed at its `parts.json` `x`, `y` (the PNG's pixel `(i, j)` is rig pixel `(x + i, y + j)`), or `render/recomposite_rig.png`, the whole rig 1:1; the contact sheets (`sheet`) are scaled and carry no coordinates. `draw` is `"back"`, `"front"` or `{"before": "<plan part>"}`, as for a patch (to keep the setup pose, draw the piece immediately in front of `from` — `{"before": "<the plan part after from>"}`, or `"front"` when `from` is the last plan part; `{"before": "<from>"}` draws it behind `from`, which `under` refuses as `ASSEMBLE_UNDER_DRAW` because the fill would hide it). `from` must be a plan part (`CONFIG_NAME_RESOLVES`; a patch or another cut's piece is refused; a part a limb takes may be cut where no segment of the limb holds it, issue #564, §5 *Limbs*), `into` a new name (`CONFIG_PART_UNIQUE`), the polygon three or more integer points (`CONFIG_FIELD_TYPE`). The piece's `parts.json` record carries `from`'s `<run>:<tag>` and its own counts, each split from the layer's by where the pixel lies; it is a mesh or a region under its own name, and the coverage rule holds it like a plan part. What the config cannot know the stage refuses: a polygon point past the rig (`ASSEMBLE_CUT_INSIDE`), two cuts of one part sharing a pixel (`ASSEMBLE_CUT_OVERLAP`), a cut that takes none of the layer's opaque pixels or leaves `from` none (`ASSEMBLE_CUT_PIXELS`), a cut of a part a limb takes that takes a pixel a segment of the limb holds (`ASSEMBLE_CUT_CROSSES_LIMB`). `overlap` is required, a non-negative integer of rig pixels with no default (`CONFIG_FIELD_TYPE`): the **band** — the polygon's pixels within `overlap` px of its edge by Chebyshev distance (the polygon's mask less its erosion by a `2 * overlap + 1` square) — stays in `from` as well as going to the piece, so the piece's resampled edge has art under it; the counts stay a strict partition and the band is the base's extra copy, printed on the `cut:` line. At `0` the two abut and `check`'s seam bar judges the edge between them (`CHECK_SEAM_WITHIN_BAR`, §5). A band only covers the edge at rest: a piece that swings well clear of where it was painted shows the hole it leaves, and a thin piece's band shows a ghost of the piece. `under` (issue #193), optional, is the author's image of what lies under the piece: a PNG path relative to the config's directory (`CONFIG_FIELD_TYPE` unless a non-empty string), in rig pixels over the polygon's **bounding box** — the least and greatest polygon x and y, so the image is `max x − min x` by `max y − min y` and its pixel `(i, j)` is rig pixel `(min x + i, min y + j)`. Where the cut removed pixels from `from` — the piece's pixels (alpha above 0) less the band — `from` takes the image's pixel, colour and alpha wherever the image's alpha is at least the alpha the cut removed there (**filled**); elsewhere `from` stays empty there (**left empty**): a transparent pixel is the author's statement that nothing lies under it (the background, or a part drawn behind), and a less opaque one is not half-filled. The image is read nowhere else, so its pixels over the band, over the box outside the polygon or where the layer had no art never change `from`. The `cut:` line then ends `; under <n> px filled, <m> px left empty` (`n + m` is every removed pixel), so an unintended hole is a number in the log, not a guess; the filled pixels count in `from`'s `opaque_px` and `occluded_px` (the piece is drawn over them), never as visible or projected. The stage refuses: a file that is not there (`ASSEMBLE_UNDER_PRESENT`) or not a PNG (`ASSEMBLE_UNDER_DECODES`), an image not exactly the box's size (`ASSEMBLE_UNDER_SIZE`, both sizes given), an image that fills none of the removed pixels — all transparent there, or another file (`ASSEMBLE_UNDER_EMPTY`; to leave the whole hole, drop `under`), and a piece drawn behind `from` (`ASSEMBLE_UNDER_DRAW`: the fill would hide it; draw it `"front"` or `{"before": "<the plan part after from>"}`). Producing the image is the author's, by whatever means; absent, `from` keeps only its band. `under_fill` (issue #360), optional, is the one value `"colour"` (`CONFIG_FIELD_TYPE` on any other): the same pixels are filled and left empty, and a filled pixel takes the image's **colour** at the alpha the cut removed there instead of the image's alpha, so `from`'s alpha is the uncut layer's wherever the image fills and its silhouette does not grow — an opaque image over a soft edge leaves the edge soft. It applies to the part's hidden-art layer as well as to a file; a cut with neither is refused (`ASSEMBLE_UNDER_FILL_SOURCE`). The `cut:` line's filled count then says how many took the colour only: `; under 190 px filled (190 colour only, at the alpha the cut removed), 0 px left empty`. Absent, a filled pixel takes the image's colour and alpha, as above |
111
- | `assemble.alternates` | assemble, rig, check (`--set`, `--all-sets`) | **authored**, optional (issues #454, #465, #472, #473, #476): `[{name, source?, full?, head?, head_box?, parts?, hides?, cuts?, skeleton?, drawn?}]` — alternate painting sets assembled into `<out>/rig/parts/<set>_<part>.png` (`parts.json` `alternates`), attached on each covered slot in `rig.json` as `<set>_<part>` beside the base attachment, and indexed in `<out>/rig/sets.json` (`rig-parts-sets/1`: `sets.<set>.slots`, `.hides`, `.drawn` when present, and `.threshold: {yaw: 15, pitch: 12}` when the set replaces `face` on a rig with `turn` or `turn`/`tilt` slider animations). `source`, `full` and `head` may instead be given on the CLI with `--alt <name>=<source>:<full>[:<head>]`. `parts` lists the subset of parts the set replaces (default: every part not in `hides`); a **subset set** (issue #473, e.g. mouth visemes `a`, `i`, `u` with `"parts": ["mouth"]`) cuts only its covered parts from the alternate runs (refusing with `ASSEMBLE_ALT_INPUT_PRESENT` if a covered part's layer is missing or empty), writes only `{slot: "<set>_<slot>"}` in `sets.json` so `@rig-c/play`'s `setSet(name)` switches those slots while leaving every other slot on its base attachment (and `setSet(null)` restores the base pose), may be keyed on a slot attachment track in `motion.animations_from` as `{"t": …, "set": "<name>" \| null}` (`CONFIG_SET_COVERS_SLOT` if `"set"` is undeclared or does not cover the track's slot), and under `check --set <name>` counts `ANIMATIONS_DO_NOT_FOLD` only on its own covered slots; `hides` lists slots the set hides (`null` in `sets.json`). A **gesture subset set** (issue #476) covers a limb chain declared in `config.limbs.<limb>` (all of its segment `part`s; with `drawn` alone, cut at the base's joints posed to the set's own `drawn` angles by `poseBoneEntriesForDrawn`, each segment keeping the base's length; with `skeleton` (issue #539), cut at the skeleton's own joint positions by `placeBoneEntriesForSkeleton` — each covered bone the body-18 table names (`sleeve_*`, `arm_*0`/`arm_*1`, `leg_*0`/`leg_*1`) at its skeleton origin with the skeleton segment's own length and direction (`drawn` overriding the direction of a bone it names), and a covered bone the table does not name (a hand link `arm_r2`, a single `foot_r`) placed from its parent's new place — its base offset from the parent, stretched along the parent by the parent's length change and turned by its turn, so a link or a foot at the parent's end lands on the skeleton's end — with its base length and the drawn or base direction, so a foreshortened shin or forearm is cut where it is painted; naming the unsplit `from` layer, covering only some segments of the limb, or declaring polygon `cuts` on a limb set is refused with `CONFIG_LIMB_SET_JOINTS`) and carries `drawn` (or `skeleton`) for the covered bones only (giving `drawn` for an uncovered bone is refused with `CONFIG_SET_COVERS_BONE` / `RIG_SET_COVERS_BONE`; uncovered bones keep the base's `drawn`). A subset set's limb part takes no pixel that a base part drawn after it, which the set neither covers nor hides, covers at setup (issue #587): the set's attachment is drawn in the base slot's place, so that base part is drawn over it and what the set's painting shows there is that base part (shorts over a leg set's thigh top, which See-through synthesised in the set's leg layer); `assemble` clears those pixels — the base part's PNG at alpha above 8, at its `parts.json` x, y, on the shared canvas — from the set's part once its limbs are cut, before any count — its `merged_px` and its cap's record too (issue #603): a cap pixel it clears leaves the count it was in (`layer_px`, `image_px`, `upper_px`, `lower_px`, `lower_kept_px`) for the cap's `excluded_px`, written only when above 0, so every count is the written PNG's — and prints `LINT set "<set>" <part>: <n> px under <base part> excluded` per part and base part that took a pixel (n counts alpha above 8); a set that carries that base part itself (`"parts": ["thigh_l", "shin_l", "bottomwear"]`) excludes nothing and writes what it wrote before. A subset set that names one limb side of a layer more limbs take (issue #588: `"parts": ["thigh_r", "shin_r"]` where `leg_r` and `leg_l` both take the one `legs` layer) would put every pixel of that layer on its one limb, so each of its parts would hold a piece of both legs; when the set's layer holds more than one island (8-connected pixels with alpha above 8) of at least 1 % of its largest (issue #608: the ghost clean-up's own share; a smaller island is a speck, which goes with the island nearest it — the one holding the pixel centre nearest one of the speck's, none when two are equally near — and is never an island of its own), each segment part keeps the island its joints fall on — its bone's origin and the next segment's bone's origin, at the set's own bones, a joint on the island of a pixel whose square holds the point, and a joint on no island on the one island whose nearest pixel centre lies within the radius of the cap cut at that joint (`cap.radius`: an ankle just past the legwear's edge, on the shoe) — and drops the rest, once its limbs are cut and before the exclusion above, and `assemble` prints `LINT set "<set>" <part>: <layer part> holds <n> islands (8-connected, alpha above 8)[, and <s> speck(s) under 1 % of the largest (<f> px), each with the island nearest it], kept the one under <bone> [x, y] and <bone> [x, y][ (<e> px off it, within its cap's radius <r>)] (<k> px), dropped <m> (<d> px)` per part (k and d count the part's pixels above alpha 8, m the islands it lost one from, and `dropped none` when it lost none); a joint on no island with none or two within that radius, or with no cap cut at it (a limb's first joint), and a segment whose joints fall on two, are refused with `ASSEMBLE_ALT_LIMB_ISLAND` rather than guessed. A layer of one island — specks aside — may hold both legs over each other (a folded shin across the standing leg; issue #609): each of the set's segment parts then keeps the pixels nearer its own limb's segment line — the limb's polyline, its segments' bone origins and its last bone's end — than the other limb's, both in the set's pose, and gives the rest away, once its limbs are cut and before the exclusion above; a pixel whose two distances differ by 0.5 px or less (the overlap band: half a pixel, the reach by which a pixel centre is read as on a line) goes to the limb whose part there is drawn later in the base's draw order, and the `LINT set` line above counts what each part kept, gave and held in the band. The other limb stands where the set's `skeleton` places it — its keypoints place every limb bone of the body-18 table, the other leg's as well as the set's own (its `drawn` and `drawnLength` stay the covered bones') — and never at the base's place: a set that does not place it (a `drawn` set, which may not name a bone it does not cover, or a set with neither) is refused with `ASSEMBLE_ALT_LIMB_POSE` when its layer has art where the base draws that limb, and when it has none nothing says the layer holds it and the layer is cut as before; two limbs whose segment lines run closer than the limb's half-width over most of where their art can meet are refused with `ASSEMBLE_ALT_LIMB_OVERLAP`. A set that carries every limb of the layer is cut as before. `skeleton` (a pose file path relative to the config's directory, `{"width": W, "height": H, "points": {…}}` with all 18 body-18 keypoints on the canvas, validated by the same rules as `generation.control.skeleton`: `CONFIG_FILE_PRESENT`, `CONFIG_IS_JSON`, `CONFIG_FIELD_TYPE`, `CONFIG_KEY_KNOWN`, `CONFIG_KEY_UNIQUE`, `CONFIG_POSE_CANVAS`, `CONFIG_POSE_KEYPOINTS`, `CONFIG_POSE_IN_CANVAS`) or `drawn` (`{<bone>: <worldDegrees>}`, each bone resolved against `bones`, `CONFIG_NAME_RESOLVES`) declares the posed angles the alternate was painted at (issue #465); when `skeleton` is given, `assemble` derives `drawn` from its 18 keypoints (filtered to covered bones on a subset set, with `drawn` overriding any bone named in both), records both `skeleton` (scaled by `assemble.rig_scale` to rig px) and `drawn` in `parts.json` `alternates` — and, when the skeleton placed the set's limb bones (issue #539), `drawnLength` (`{<bone>: <ratio>}`, each covered table bone's skeleton segment length over its base length, 6 places) and `registration` (`{offset: [dx, dy], scale}`: the similarity without rotation, about the canvas origin, that maps the skeleton's torso — the mean of its shoulders `r_shoulder`/`l_shoulder` to the mean of its hips `r_hip`/`l_hip`, read where the base declares the bone rooted there, `sleeve_*0`/`arm_*0` and `leg_*0` — onto those base bones' origins, 6 places), both also written to `sets.json`; the set's painting must be registered, its torso within 1 rig px and 1 % in scale of the base's, or the set is refused by name before any joint is cut (`ASSEMBLE_ALT_SKELETON_REGISTERED`, with the offset and scale the painting would need) — and the `rig` stage writes `<set>_*` region and mesh attachments in the bone-local frame of `poseRigBonesForDrawn(bones, drawn)` (weighting limb segments directly from `skeleton`'s joint endpoints when `skeleton` is present) and emits `drawn` in `sets.json` so `rig-pose` and `check --set <name>` / `--all-sets` pose the bones at `drawn` without rotating the already-posed art a second time |
111
+ | `assemble.alternates` | assemble, rig, check (`--set`, `--all-sets`) | **authored**, optional (issues #454, #465, #472, #473, #476): `[{name, source?, full?, head?, head_box?, parts?, hides?, cuts?, skeleton?, drawn?}]` — alternate painting sets assembled into `<out>/rig/parts/<set>_<part>.png` (`parts.json` `alternates`), attached on each covered slot in `rig.json` as `<set>_<part>` beside the base attachment, and indexed in `<out>/rig/sets.json` (`rig-parts-sets/1`: `sets.<set>.slots`, `.hides`, `.drawn` when present, and `.threshold: {yaw: 15, pitch: 12}` when the set replaces `face` on a rig with `turn` or `turn`/`tilt` slider animations). `source`, `full` and `head` may instead be given on the CLI with `--alt <name>=<source>:<full>[:<head>]`. `parts` lists the subset of parts the set replaces (default: every part not in `hides`); a **subset set** (issue #473, e.g. mouth visemes `a`, `i`, `u` with `"parts": ["mouth"]`) cuts only its covered parts from the alternate runs (refusing with `ASSEMBLE_ALT_INPUT_PRESENT` if a covered part's layer is missing or empty), writes only `{slot: "<set>_<slot>"}` in `sets.json` so `@rig-c/play`'s `setSet(name)` switches those slots while leaving every other slot on its base attachment (and `setSet(null)` restores the base pose), may be keyed on a slot attachment track in `motion.animations_from` as `{"t": …, "set": "<name>" \| null}` (`CONFIG_SET_COVERS_SLOT` if `"set"` is undeclared or does not cover the track's slot), and under `check --set <name>` counts `ANIMATIONS_DO_NOT_FOLD` only on its own covered slots; `hides` lists slots the set hides (`null` in `sets.json`). A **gesture subset set** (issue #476) covers a limb chain declared in `config.limbs.<limb>` (all of its segment `part`s; with `drawn` alone, cut at the base's joints posed to the set's own `drawn` angles by `poseBoneEntriesForDrawn`, each segment keeping the base's length; with `skeleton` (issue #539), cut at the skeleton's own joint positions by `placeBoneEntriesForSkeleton` — each covered bone the body-18 table names (`sleeve_*`, `arm_*0`/`arm_*1`, `leg_*0`/`leg_*1`) at its skeleton origin with the skeleton segment's own length and direction (`drawn` overriding the direction of a bone it names), and a covered bone the table does not name (a hand link `arm_r2`, a single `foot_r`) placed from its parent's new place — its base offset from the parent, stretched along the parent by the parent's length change and turned by its turn, so a link or a foot at the parent's end lands on the skeleton's end — with its base length and the drawn or base direction, so a foreshortened shin or forearm is cut where it is painted; naming the unsplit `from` layer, covering only some segments of the limb, or declaring polygon `cuts` on a limb set is refused with `CONFIG_LIMB_SET_JOINTS`) and carries `drawn` (or `skeleton`) for the covered bones only (giving `drawn` for an uncovered bone is refused with `CONFIG_SET_COVERS_BONE` / `RIG_SET_COVERS_BONE`; uncovered bones keep the base's `drawn`). A subset set's limb part takes no pixel that a base part drawn after it, which the set neither covers nor hides, covers at setup (issue #587): the set's attachment is drawn in the base slot's place, so that base part is drawn over it and what the set's painting shows there is that base part (shorts over a leg set's thigh top, which See-through synthesised in the set's leg layer); `assemble` clears those pixels — the base part's PNG at alpha above 8, at its `parts.json` x, y, on the shared canvas — from the set's part once its limbs are cut, before any count — its `merged_px` and its cap's record too (issue #603): a cap pixel it clears leaves the count it was in (`layer_px`, `image_px`, `upper_px`, `lower_px`, `lower_kept_px`) for the cap's `excluded_px`, written only when above 0, so every count is the written PNG's — and prints `LINT set "<set>" <part>: <n> px under <base part> excluded` per part and base part that took a pixel (n counts alpha above 8); a set that carries that base part itself (`"parts": ["thigh_l", "shin_l", "bottomwear"]`) excludes nothing and writes what it wrote before. A subset set that names one limb side of a layer more limbs take (issue #588: `"parts": ["thigh_r", "shin_r"]` where `leg_r` and `leg_l` both take the one `legs` layer) would put every pixel of that layer on its one limb, so each of its parts would hold a piece of both legs; when the set's layer holds more than one island (8-connected pixels with alpha above 8) of at least 1 % of its largest (issue #608: the ghost clean-up's own share; a smaller island is a speck, which goes with the island nearest it — the one holding the pixel centre nearest one of the speck's, none when two are equally near — and is never an island of its own), each segment part keeps the island its joints fall on — its bone's origin and the next segment's bone's origin, at the set's own bones, a joint on the island of a pixel whose square holds the point, and a joint on no island on the one island whose nearest pixel centre lies within the radius of the cap cut at that joint (`cap.radius`: an ankle just past the legwear's edge, on the shoe) — and drops the rest, once its limbs are cut and before the exclusion above, and `assemble` prints `LINT set "<set>" <part>: <layer part> holds <n> islands (8-connected, alpha above 8)[, and <s> speck(s) under 1 % of the largest (<f> px), each with the island nearest it], kept the one under <bone> [x, y] and <bone> [x, y][ (<e> px off it, within its cap's radius <r>)] (<k> px), dropped <m> (<d> px)` per part (k and d count the part's pixels above alpha 8, m the islands it lost one from, and `dropped none` when it lost none); a joint on no island with none or two within that radius, or with no cap cut at it (a limb's first joint), and a segment whose joints fall on two, are refused with `ASSEMBLE_ALT_LIMB_ISLAND` rather than guessed. A layer of one island — specks aside — may hold both legs over each other (a folded shin across the standing leg; issue #609): each of the set's segment parts then keeps the pixels nearer its own limb's segment line — the polyline of only its segments taking that source, their bone origins and the last segment's supplied tip or following segment's joint (issue #638) — than the other limb's, both in the set's pose, and gives the rest away, once its limbs are cut and before the exclusion above; a pixel whose two distances differ by 0.5 px or less (the overlap band: half a pixel, the reach by which a pixel centre is read as on a line) goes to the limb whose part there is drawn later in the base's draw order, and the `LINT set` line above counts what each part kept, gave and held in the band. The other limb stands where the set's `skeleton` places it — its keypoints place every limb bone of the body-18 table, the other leg's as well as the set's own (its `drawn` and `drawnLength` stay the covered bones') — and never at the base's place: a set that does not place it (a `drawn` set, which may not name a bone it does not cover, or a set with neither) is refused with `ASSEMBLE_ALT_LIMB_POSE` when its layer has art where the base draws that limb, and when it has none nothing says the layer holds it and the layer is cut as before; two limbs whose segment lines run closer than the limb's half-width over most of where their art can meet are refused with `ASSEMBLE_ALT_LIMB_OVERLAP`. A set that carries every limb of the layer is cut as before. For a subset set, where a limb's own source layer holds art (`alpha > 8`) under another layer of that run drawn in front (`alpha > 8`, by the projection's plan/depth order), the limb keeps its own layer pixels through projection, limb cutting, island/nearest-line assignment, base-footprint exclusion, fringe clearing and seam correction (issue #637). Those pixels are occluded, never counted as painting projection; no base footprint or painting colour replaces them. After source-art island/nearest-line assignment, a source-transparent cap pixel is assigned before protection, in both doors: its centre is compared against only the segments taking the recipient's source, at the set's supplied bones (ankle-to-toe for a separate foot source), with the existing 0.5 px overlap band and base draw order. A missing last endpoint is refused with `ASSEMBLE_ALT_LIMB_POSE`; an actual following joint may supply that endpoint, never a guessed point. An unposed other limb with base art beneath these cap pixels is likewise refused; without such overlap the existing compatible path retains the cap without inventing the other limb's pose. A pixel cleared by this assignment is never restored. `CAP_FROM_UPPER` records a copy made before assignment and alone proves no ownership: only a retained copy is protected beneath the upper segment, which is drawn over it. The source-art island selection itself is unchanged. Other retained cap pixels (from the layer or a supplied cap image) are protected under an actual front layer even where the lower source is transparent. Protection follows each assigned piece through exclusion, fringe clearing and seam correction; it never restores a pixel ownership removed. Cap pixels removed during ownership leave their original counts for `excluded_px`, just as excluded pixels do, so the cap ledger describes the written PNG. Target assignment reconciles this ledger even when there are no source-transparent cap candidates and when a direct caller does not request cover protection. Unprotected source pixels still obey the base-footprint exclusion. Missing limb/cap art is never extended or guessed. Base builds and uncovered, unexcluded sets keep their existing bytes. `skeleton` (a pose file path relative to the config's directory, `{"width": W, "height": H, "points": {…}}` with all 18 body-18 keypoints on the canvas, validated by the same rules as `generation.control.skeleton`: `CONFIG_FILE_PRESENT`, `CONFIG_IS_JSON`, `CONFIG_FIELD_TYPE`, `CONFIG_KEY_KNOWN`, `CONFIG_KEY_UNIQUE`, `CONFIG_POSE_CANVAS`, `CONFIG_POSE_KEYPOINTS`, `CONFIG_POSE_IN_CANVAS`) or `drawn` (`{<bone>: <worldDegrees>}`, each bone resolved against `bones`, `CONFIG_NAME_RESOLVES`) declares the posed angles the alternate was painted at (issue #465); when `skeleton` is given, `assemble` derives `drawn` from its 18 keypoints (filtered to covered bones on a subset set, with `drawn` overriding any bone named in both), records both `skeleton` (scaled by `assemble.rig_scale` to rig px) and `drawn` in `parts.json` `alternates` — and, when the skeleton placed the set's limb bones (issue #539), `drawnLength` (`{<bone>: <ratio>}`, each covered table bone's skeleton segment length over its base length, 6 places) and `registration` (`{offset: [dx, dy], scale}`: the similarity without rotation, about the canvas origin, that maps the skeleton's torso — the mean of its shoulders `r_shoulder`/`l_shoulder` to the mean of its hips `r_hip`/`l_hip`, read where the base declares the bone rooted there, `sleeve_*0`/`arm_*0` and `leg_*0` — onto those base bones' origins, 6 places), both also written to `sets.json`; the set's painting must be registered, its torso within 1 rig px and 1 % in scale of the base's, or the set is refused by name before any joint is cut (`ASSEMBLE_ALT_SKELETON_REGISTERED`, with the offset and scale the painting would need) — and the `rig` stage writes `<set>_*` region and mesh attachments in the bone-local frame of `poseRigBonesForDrawn(bones, drawn)` (weighting limb segments directly from `skeleton`'s joint endpoints when `skeleton` is present) and emits `drawn` in `sets.json` so `rig-pose` and `check --set <name>` / `--all-sets` pose the bones at `drawn` without rotating the already-posed art a second time |
112
112
  | `assemble.head_face_underfill` | assemble, `assemble --propose-plan` | **authored**, optional (issue #492): `boolean` (`CONFIG_FIELD_TYPE` on any other). When both runs exist and `full:face` has at least `200` opaque run px (`PROPOSE_MIN_PX`), the stage maps `full:face` into the head canvas via `fullLayerToHead` and measures how much of its hole-filled silhouette (`alpha > 8`) is covered by `head:face` (`alpha > 8`). A head-run `face` covering less than `75 %` (`HEAD_FACE_COVERAGE_FLOOR`, measured `0.0 %..48.6 %` on hollow/omitted head runs vs `84.8 %..99.6 %` on clean head runs across the 4 public examples and 9-standee corpus) is refused with `SEETHROUGH_HEAD_RUN_HOLLOW` unless `head_face_underfill: true` is declared. When `head_face_underfill: true` is declared and `head:face` exists (`opaqueRunPx >= 200`), `fullLayerToHead(full:face)` is composited under `head:face` on the head canvas (`alpha = max(headAlpha, fullAlpha)`, RGB blended by `headAlpha / 255`) before `head:face` is placed in rig space (`underfill=<N>px(full:face)` on the `face` part log line and a `face: head_face_underfill composited …` note in `assemble --propose-plan`). The fill restores transparent pixels only and leaves the cut's own edge where it is — a hollow whose edge is not under hair stays visible, and that is the author's to fix at the cut. When `head:face` has fewer than `200` opaque pixels, `SEETHROUGH_HEAD_RUN_HOLLOW` still fires even under `head_face_underfill: true` because the head run omitted the face layer and cannot supply a jawline |
113
113
  | `limbs` | assemble (the cut and the caps), rig (through `regions`), check (`LIMB_ONE_BONE`) | **proposed** by `propose --keypoints` (issue #349), then checked: `{<limb>: {segments: [{part, from, bone}, {part, from, bone, joint, range?, cap?, edge?, cap_shape?, cut_band?}, …]}}`, the upper segment first. The rule is *Limbs: cut at their joints* below the table. `part` is a new part (`CONFIG_PART_NAME`, `CONFIG_PART_UNIQUE` against the plan, patches, cuts and every other limb part); `from` a plan part or a cut's piece (`CONFIG_NAME_RESOLVES`) — the layer the segment's pixels come from, which is cut into the limb parts and is not itself made: a `meshes` or `regions` entry for it is `CONFIG_NAME_RESOLVES`, and the segments of one limb that take one part are consecutive (`CONFIG_LIMB_FROM_RUN`); `bone` a declared bone, each segment's the child of the one before (`CONFIG_LIMB_BONES_CHAIN`); the upper segment names no `joint`, `range`, `cap`, `edge`, `cap_shape` or `cut_band` (`CONFIG_KEY_KNOWN`), every other names its `joint` (`CONFIG_FIELD_PRESENT`) — the joint is its bone's origin; `range` is `[min, max]` degrees from rest with `min <= 0 <= max` (`CONFIG_LIMB_RANGE`), which `assemble` writes into the lower part's `parts.json` record and `check` poses the joint at — its two ends and its middle — reading the seam there (`SEAM_OVER_RANGE`, issue #360; rig-c needs no rotation limit); `cap` a PNG path relative to the config's directory (`CONFIG_FIELD_TYPE`); `edge` `"feather"` (issue #360), the one value it takes, and `cap_shape` `"disc"` (issue #360) or `"ball"` (issue #579) (`CONFIG_FIELD_TYPE` on any other) — the cut's geometry at that joint, *Limbs: cut at their joints* below; absent, the cut is hard and the cap the layer's half-disc of half the limb's width; `cut_band` a whole number of px, 1 or more (`CONFIG_FIELD_TYPE`), on a segment that takes the segment above's part — between two layers nothing is cut, so a band there is `CONFIG_KEY_KNOWN` — places the cut within that many px of the joint line (issue #360, *Limbs: cut at their joints*); absent, the cut is the joint line. Each limb part is attached like any part — `regions.<part>`, which must be the segment's `bone` (`CONFIG_LIMB_BONE`), or a mesh, which `check` holds to that bone alone (`LIMB_ONE_BONE`). With `limbs`, `assemble` reads `bones` too (`CONFIG_FIELD_PRESENT` without it). Absent, nothing is cut at a joint and no byte of any output moves |
114
114
  | `bones` | rig; `propose --from-config` | **proposed** by `propose`, then corrected. A single bone `{name, parent, at, tip?}` or a chain `{chain, parent, points, tip, link_inherit?}` whose links are named `<chain>0 … <chain>n`. Parents come before children. In `rig.json` each link is **turned along its chain** — `rotation` is the direction from its origin to the next link's (the last link's to `tip`) and `length` that distance (issue #73), so a physics constraint added downstream finds a lever; under `--idle-keys ctl` the link's `<link>_ctl` carries the turn and the length and the link sits at local rotation 0 beneath it. A single bone with a `tip` is turned the same way, towards its tip, with that distance as its length (issue #239); a tip on the bone's own origin is refused (`RIG_TIP_DISTINCT`). The five face bones `eye_r`, `eye_l`, `brow_r`, `brow_l` and `mouth` (by name, when one has no tip of its own) are turned to the eye line — the line through the origins of `eye_r` and `eye_l` as `bones` writes them, read image-left to image-right, drawn when parts.json holds both an `eyewhite-r` and an `eyewhite-l` part — so the blink's `scaley` squashes across the eye line on a tilted head; move an eye bone and the line moves with it. With one eyewhite or none, or an eye bone missing, the rig stage's `face axis:` line says so and they keep the page's axes. A bone under a face bone keeps the face's axis. With the line, `rig.json` also declares `invariants.axes` — one entry, `"face"`, through `eye_r` and `eye_l`, holding the turned face bones (and their controls) — so rig-c's gate holds the build to the line; the line is the one rigc draws through the same two bones, so the tolerance is only the float floor — the largest gap the emitted (float32) bones have to it, rounded up to 6 places plus one 6-place unit — and the `face axis:` line prints it. With the line the rig stage also adds `head_up` (issue #250): a slotless bone under `head`, at head's origin, turned to the eye line + 90 degrees and as long as the eye midpoint lies from head's origin along that axis — the head's frame, which a rule that needs it reads; `head` keeps its own frame, so no key on it or under it changes meaning, and a config bone of that name is refused (`RIG_HEAD_UP_NAME_FREE`). A face bone with its own `tip` is held too (issue #258), in a second entry, `"face_tips"`, when its tip lies along the line within whole-pixel rounding — a tip written in whole pixels sits at most sqrt(2)/2 px off the point of the line it stands for, so its direction may sit up to asin((sqrt(2)/2) / length) degrees off — with its tolerance measured the same way; a tip further off is the bone's own axis, and the `face axis:` line names it with its gap and that bound. A failure is rig-c's `A51_BONES_LIE_ALONG_THEIR_DECLARED_AXIS` line, which names the bone and the fix (rig-c's `docs/AUTHORING.md` §3.7 and §5.2); with no line no entry is written and A51 reports SKIP. Every region on a turned bone is turned back, so the setup pose does not move. Any other single bone keeps world rotation 0; one whose parent is a link is turned back upright. A single bone may declare `inherit` (issue #348): what it takes from its parent's transform, one of rig-c's own mode names exactly as rig-c's table spells them — `normal`, `onlyTranslation`, `noRotationOrReflection`, `noScale`, `noScaleOrReflection` (rig-c's `RigBone.inherit`) — written to that bone in `rig.json` as declared; any other spelling, `"NoScale"` included (the runtime would fold its first letter; nothing here folds or maps), is refused (`CONFIG_BONE_INHERIT`), and a chain takes no `inherit` (`CONFIG_KEY_KNOWN`). A chain may instead declare `link_inherit` (issue #369), an object mapping its own expanded link names to those same modes, for example `"link_inherit": {"leg_r1": "noScale"}`. Only the named link changes; omitted links inherit normally. A key outside this chain is `CONFIG_NAME_RESOLVES`, with this chain's valid link names in the detail; a non-object or non-string mode is `CONFIG_FIELD_TYPE`, and another mode spelling is `CONFIG_BONE_INHERIT`. The mode is forwarded to the expanded link, or to its control under `--idle-keys ctl`, by the same rule as a single bone. This is an authored opt-in: `propose` does not add it. Its setup rotation is the turn from where rig-c's own poser puts the bone with no rotation of its own under that mode, so it still stands upright (or along its tip) at the setup pose. Where the idle gives the bone a `<bone>_ctl`, the mode goes on the control: the control is the bone the parent's rotation reaches, and the bone under it inherits normally, so the idle's keys moved onto the control still turn it. A foot that does not take its shin's rotation (`noRotationOrReflection` or `onlyTranslation`) keeps its shoe level while the leg is posed (`FEET_STAY_LEVEL`, §7); which mode is the author's. `noScale` keeps a shin or shoe's shape under a scaled parent but still takes the parent's rotation: a shoe that must also stay level needs a separate rotation constraint, for example a transform constraint from an unrotated bone. This does not change the proposed feet's existing inheritance or `FEET_STAY_LEVEL` default. An automatic mesh weighted through a bone with a mode other than `normal` gets no derived amplitude (its row names the bone) and no residual envelope (rig-c's `SKINNING_RANGE_UNSUPPORTED`). Absent, `rig.json` carries no `inherit` and no byte moves |
@@ -560,6 +560,32 @@ layers, as follows; every step is arithmetic on the declared bones and the layer
560
560
  part's Otsu luma split, or its uncrossed silhouette width, across the crossing) — so the covering
561
561
  limb's pixels stay on the covering limb and the seam follows the limb. Without `split`, the
562
562
  nearest-bone split stays and `propose`'s `LINT` names the crossing.
563
+ For a subset alternate set (issues #588, #609 and #638), ownership applies to every
564
+ segment source, including a separate `footwear` layer holding both shoes. With
565
+ separate islands, each segment keeps the island under its joints; with one shared
566
+ island, pixels go to the nearer line in the set's pose, using only the segments
567
+ that take that source. Footwear therefore reads each leg's ankle-to-toe segment,
568
+ not its thigh or shin. The toe comes from the foot bone's authored `tip`, placed
569
+ with that bone in the set; a missing endpoint on a shared one-island source is
570
+ `ASSEMBLE_ALT_LIMB_POSE`, never a guessed length or direction. The existing
571
+ overlap band and draw order settle near ties. A source already holding only
572
+ that side follows the existing path.
573
+ Issue #638's acceptance was **changed after measurement** (decision alternative 3):
574
+ foreign-leg components must be zero, with own-cap components counted separately.
575
+ That historical measurement did not satisfy the original second-island <=1% bar.
576
+ On the public generated default-cap control, explicit pre-#637 test settings
577
+ (`setCover: "painting"`, `setCapOwnership: "source"`, neither a CLI/config option)
578
+ retain the whole-limb-line mutant's islands `[97,16]` and the source-segment
579
+ line's `[104,16]`. All 16 pixels of the separate component are `CAP_FROM_UPPER`
580
+ copies from the same leg's shin, strictly owned by that foot's ankle-to-toe
581
+ segment. Issue #637 additionally preserves the assigned own-cap connection
582
+ through covering layers: the current default is one connected `[272]` component,
583
+ with the same 16 pixels and their 64-pixel bridge retained, and zero foreign-leg
584
+ pixels. Copy provenance alone grants no protection; target ownership is assigned
585
+ first, through the same source-segment helper as the ordinary source art. The
586
+ controls preserve the historical pixels byte for byte in the current default,
587
+ detect a planted foreign owner, causally remove each upper-source copy, and
588
+ reject deleting valid own-cap art. Neither change alters the cap's shape.
563
589
  - **The joint line.** Between two segments the joint is the lower bone's origin, and the line
564
590
  runs through it perpendicular to the limb's axis there — the sum of the upper bone's and the
565
591
  lower bone's unit directions, so on a bent limb the bisector. A pixel whose centre is past the
@@ -3250,7 +3276,7 @@ says why each requirement exists and what breaks without it.
3250
3276
  | <a id="ASSEMBLE_ALT_SKELETON"></a>`ASSEMBLE_ALT_SKELETON` | an alternate set's `skeleton` file (`assemble.alternates[i].skeleton`, issue #465) is not JSON or does not hold `{"width": W, "height": H, "points": {…the 18 body-18 keypoints}}` | that set's `skeleton` file |
3251
3277
  | <a id="ASSEMBLE_ALT_SKELETON_REGISTERED"></a>`ASSEMBLE_ALT_SKELETON_REGISTERED` | an alternate set whose `skeleton` places its limb bones (issue #539) is not registered on the base: the similarity without rotation that maps the skeleton's torso (the mean of its shoulders to the mean of its hips, where the base declares `sleeve_*0`/`arm_*0` and `leg_*0`) onto those base bones' origins is more than 1 rig px off (the offset's length) or more than 1 % off in scale; the detail gives the offset `[dx, dy]` rig px and the scale the painting would need (`p -> scale * p + offset`, about the canvas origin) and the bones read. Also when the base declares no bone at one end of the torso, or the skeleton's torso has no length. Refused before any joint is cut | the set's painting and skeleton, registered: the figure at the base figure's torso place and scale on the same canvas (`ASSEMBLE_ALT_CANVAS_SIZE` forbids another canvas); or, on a base with no torso bones, `drawn` in place of `skeleton` |
3252
3278
  | <a id="ASSEMBLE_ALT_LIMB_ISLAND"></a>`ASSEMBLE_ALT_LIMB_ISLAND` | a subset alternate set names one limb side of a layer more limbs take, the set's layer holds more than one island (8-connected, alpha above 8, at least 1 % of its largest — issue #608), and a segment's joint — its bone's origin, or the next segment's — lies on no island and none or two of them lie within the radius of the cap cut at that joint, or no cap is cut at it (a limb's first joint), or its joints lie on two, so no one island is the limb's to keep (issue #588; the detail gives every island's pixels and box, the joints, and for a joint off the art each island's distance and the radius) | the set's bones or `drawn`, a joint on its limb's art or within its cap's radius of it; one stroke of art from joint to joint; or a layer that holds the limb alone |
3253
- | <a id="ASSEMBLE_ALT_LIMB_POSE"></a>`ASSEMBLE_ALT_LIMB_POSE` | a subset alternate set names one limb side of a layer more limbs take, the set's layer holds one island (8-connected, alpha above 8, specks aside), it has art where the base build draws another limb of that layer (the detail gives the pixels and the base parts), and the set does not place that limb — no bone of it, nor an ancestor, is placed by the set's `skeleton` (the body-18 table's arm and leg bones) or named in its `drawn`; the pixels are split by the nearest segment line in the set's pose, and the other limb's place is never taken from the base's (issue #609) | a `skeleton` whose keypoints place the other limb (`drawn` may not name a bone the set does not cover, `CONFIG_SET_COVERS_BONE`); or a set that carries the other limb's parts too; or a layer that holds the set's limb alone |
3279
+ | <a id="ASSEMBLE_ALT_LIMB_POSE"></a>`ASSEMBLE_ALT_LIMB_POSE` | a subset alternate set names one limb side of a layer more limbs take, the set's layer holds one island (8-connected, alpha above 8, specks aside), it has art where the base build draws another limb of that layer (the detail gives the pixels and the base parts), and the set does not place that limb — no bone of it, nor an ancestor, is placed by the set's `skeleton` (the body-18 table's arm and leg bones) or named in its `drawn`; the pixels are split by the nearest segment line in the set's pose, and the other limb's place is never taken from the base's (issue #609). Also a source-transparent cap overlapping an unposed other limb's base art, or a cap target source segment with no supplied tip or following joint (issue #637) | a `skeleton` whose keypoints place the other limb (`drawn` may not name a bone the set does not cover, `CONFIG_SET_COVERS_BONE`); or a set that carries the other limb's parts too; or a layer that holds the set's limb alone |
3254
3280
  | <a id="ASSEMBLE_ALT_LIMB_OVERLAP"></a>`ASSEMBLE_ALT_LIMB_OVERLAP` | a subset alternate set's layer of one island holds its limb and another limb the set places, and in the set's pose the other limb's segment line runs within the limb's half-width (the least `cap.radius` of its joints) of the limb's, across it, at more than half of the readings 1 px apart along the limb's line where the other line passes within twice that — the limbs lie over each other, so no line between them says whose a pixel is (a crossing at angle θ reads cos θ / 2, under half; issue #609; the detail gives the readings, the half-width and the share); also when the limb has no joint to measure its half-width at | a layer that holds the set's limb alone; or a set that carries the other limb's parts too |
3255
3281
  | <a id="ASSEMBLE_COUNTS_ADD_UP"></a>`ASSEMBLE_COUNTS_ADD_UP` | a part's visible and occluded counts do not add up to its opaque pixels, or a projected pixel is not visible, or a cut part's pieces do not add up to it — an assembler bug, not an input problem | report it with the part named; nothing was written |
3256
3282
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-parts",
3
- "version": "1.55.1",
3
+ "version": "1.55.2",
4
4
  "description": "AI-authored 2D character parts from one anime painting and its See-through layer decomposition: measured parts, weighted-mesh rig specs, verified through rig-c before anything is written. A CLI for agents that cannot see the image.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/assemble.ts CHANGED
@@ -99,6 +99,7 @@
99
99
  *
100
100
  * Pure: no clock, no randomness, no file access. The CLI reads and writes.
101
101
  */
102
+ import { sourceLimbTarget, nearestTargetPart } from './limbownership.ts';
102
103
  import { type ArmSplit, type BoneEntry, type CharacterConfig, type ControlSkeleton, controlSkeletonOf, type Cut, type EarlyConfig, type Extend, type Limb, type Patch, type PlanEntry, type Run, type SeeThrough } from './config.ts';
103
104
  import { type Problem, refuseIfAny } from './errors.ts';
104
105
  import { figuresPhrase, implausibleRules, type Layer, type LayerFigures, layerFigures, type LayerSet, NEAR_WHITE_MIN, OPAQUE_ALPHA_ABOVE, ruleSummary } from './layers.ts';
@@ -349,7 +350,8 @@ export interface AssembleInput {
349
350
  /**
350
351
  * Issue #587: rig pixels taken out of named parts once the cuts and the limbs are made, before the fringe pass and
351
352
  * every figure a part's record holds — each entry clears `part`'s pixels (alpha, colour and region) where `mask` is
352
- * 1, and {@link AssembleResult.excluded} counts the ones above `OPAQUE_ALPHA_ABOVE` it took, in entry order (a pixel
353
+ * 1 (except owned source/cap art protected by issue #637). {@link AssembleResult.excluded} counts the ones
354
+ * above `OPAQUE_ALPHA_ABOVE` it took, in entry order (a pixel
353
355
  * an earlier entry cleared is not counted again). The set build passes {@link setExclusions}. An entry naming a part
354
356
  * this run did not make clears nothing and counts 0. Absent or empty: nothing changes. Issue #603: the part's
355
357
  * `merged_px` and, on a limb segment's part, its `cap` record are counted after it, so they add up to the PNG written
@@ -382,6 +384,10 @@ export interface AssembleInput {
382
384
  * once the limbs are cut and in place of the island rule, which needs two islands. Absent: nothing changes.
383
385
  */
384
386
  otherLimbs?: OtherLimbs;
387
+ /** Issue #637: preserve owned source/cap art under covers after limb assignment. Base builds omit it. */
388
+ limbUnderCover?: boolean;
389
+ /** Issue #637: `source` is the pre-fix test mutant that skips source-transparent cap ownership; stages use target. */
390
+ capOwnership?: 'target' | 'source';
385
391
  }
386
392
 
387
393
  /**
@@ -389,6 +395,8 @@ export interface AssembleInput {
389
395
  * hands them to {@link assemble}.
390
396
  */
391
397
  export interface OtherLimbs {
398
+ /** Issue #638's test-only pre-fix mutant; absent uses only segments taking the source. No CLI/config field. */
399
+ line?: 'whole-limb';
392
400
  /** The config's limbs, by name, that the set does not carry and that take one of `limbIslands`. */
393
401
  limbs: Readonly<Record<string, Limb>>;
394
402
  /**
@@ -827,8 +835,9 @@ function skeletonsTooClose(own: readonly LinePt[], other: readonly LinePt[], hal
827
835
  * Issue #609: on a layer of one island that the set's limbs take and `others`' limbs take too, give each pixel of the
828
836
  * set's limb parts to the limb whose segment line is nearest it, in the set's pose, and keep the set's.
829
837
  *
830
- * ⚖️ Invariant: a limb's segment line is its polyline ({@link limbPolyline}: its segments' bone origins, then the last
831
- * bone's end) at `places`, the set's own bones — the set's limb where the set cut it, the other limb where the set
838
+ * ⚖️ Invariant: a limb's segment line is the polyline of its segments taking this source ({@link limbPolyline}:
839
+ * those segments' bone origins, then the last bone's end or the next segment's joint) at `places`, the set's own
840
+ * bones — the set's limb where the set cut it, the other limb where the set
832
841
  * placed it (its skeleton's keypoints). A pixel of a part (alpha above 0, where the layer has art) is nearer the
833
842
  * other limb when its centre's distance to that limb's line is less than its distance to its own limb's by more than
834
843
  * {@link OVERLAP_BAND_PX}; within it, in the overlap band, it goes to the limb whose part there (the part of the
@@ -887,7 +896,26 @@ function splitOneIsland(
887
896
  refused = true;
888
897
  }
889
898
  if (refused || posed.length === 0) return;
890
- const polyOf = (l: string, all: Readonly<Record<string, Limb>>): Array<[number, number]> => limbPolyline(all[l], places);
899
+ // Issue #638: a separate footwear layer belongs to the ankle-to-toe segments, not to a nearby thigh or shin.
900
+ // The same source selection applies to every segment, without reading a part name or a layer tag.
901
+ const taking = (l: string, all: Readonly<Record<string, Limb>>): Limb => others.line === 'whole-limb'
902
+ ? all[l]
903
+ : { ...all[l], segments: all[l].segments.filter((sg) => sg.from === src) };
904
+ const polyOf = (l: string, all: Readonly<Record<string, Limb>>): Array<[number, number]> =>
905
+ others.line === 'whole-limb' ? limbPolyline(all[l], places) : sourceLimbTarget(all[l], src, places).line;
906
+ for (const [l, all] of [...ownNames.map((l) => [l, limbs] as const), ...posed.map((l) => [l, others.limbs] as const)]) {
907
+ const selected = taking(l, all);
908
+ const line = polyOf(l, all);
909
+ if (line.length <= selected.segments.length) {
910
+ const bone = selected.segments[selected.segments.length - 1].bone;
911
+ problems.push({
912
+ code: 'ASSEMBLE_ALT_LIMB_POSE',
913
+ object: `config.limbs.${l} (part "${src}", bone "${bone}")`,
914
+ detail: `takes this shared one-island source on a segment with no end: "${bone}" has no tip, so its origin alone cannot place the segment line; an explicit bone tip in the set's pose is required to assign the pixels, never another layer's segment line`,
915
+ });
916
+ }
917
+ }
918
+ if (problems.length > problemsBefore) return;
891
919
  // The too-close refusal, per own limb and other limb, on the own limb's half-width.
892
920
  for (const own of ownNames) {
893
921
  const radii = parts.filter((q) => q.limb === own && q.record.cap !== undefined).map((q) => (q.record.cap as CapRecord).radius);
@@ -914,7 +942,7 @@ function splitOneIsland(
914
942
  if (problems.length > problemsBefore) return;
915
943
  const drawAt = new Map(others.drawOrder.map((name, i) => [name, i]));
916
944
  // Each other limb's pieces, and the part each piece's segment is.
917
- const otherLines = posed.map((l) => ({ l, line: polyOf(l, others.limbs), segs: others.limbs[l].segments }));
945
+ const otherLines = posed.map((l) => ({ l, line: polyOf(l, others.limbs), segs: taking(l, others.limbs).segments }));
918
946
  for (const { q, i } of mine) {
919
947
  const piece = pieces[i];
920
948
  const ownLine = polyOf(q.limb, limbs);
@@ -971,6 +999,85 @@ function splitOneIsland(
971
999
  }
972
1000
  }
973
1001
 
1002
+ /**
1003
+ * Assign only live, source-transparent cap pixels after the existing source-art
1004
+ * assignment. Both the nearest-line and island doors leave such pixels without
1005
+ * a source verdict. Cap origin is provenance, never proof of ownership.
1006
+ */
1007
+ function assignCapOwnership(
1008
+ sources: readonly string[], limbs: Readonly<Record<string, Limb>>, bones: readonly BoneEntry[],
1009
+ parts: readonly LimbPart[], pieces: readonly Built[], sourceOf: (name: string) => Built | null,
1010
+ capFrom: ReadonlyArray<CapFrom | null>, W: number, H: number, others?: OtherLimbs,
1011
+ ): { counts: SplitCount[]; problems: Problem[] } {
1012
+ const counts: SplitCount[] = [], problems: Problem[] = [];
1013
+ if (others === undefined) return { counts, problems };
1014
+ const places = bonePlaces(bones);
1015
+ const drawAt = new Map(others.drawOrder.map((name, i) => [name, i]));
1016
+ parts.forEach((q, i) => {
1017
+ const from = capFrom[i], source = sourceOf(q.of), piece = pieces[i];
1018
+ if (from === null || source === null || !sources.includes(q.of)) return;
1019
+ const otherNames = Object.keys(others.limbs).filter((l) => others.limbs[l].segments.some((sg) => sg.from === q.of));
1020
+ if (otherNames.length === 0) return;
1021
+ const [bx, by, bw, bh] = from.box;
1022
+ const candidates: number[] = [];
1023
+ for (let y = Math.max(0, by); y < Math.min(H, by + bh); y++) for (let x = Math.max(0, bx); x < Math.min(W, bx + bw); x++) {
1024
+ const p = y * W + x;
1025
+ if (from.codes[(y - by) * bw + x - bx] !== 0 && piece.r.data[p * 4 + 3] > 0 && source.r.data[p * 4 + 3] === 0) candidates.push(p);
1026
+ }
1027
+ if (candidates.length === 0) return;
1028
+ const before = problems.length;
1029
+ const posed: string[] = [];
1030
+ for (const l of otherNames) {
1031
+ const unposed = others.unposed[l] ?? [];
1032
+ if (unposed.length === 0) { posed.push(l); continue; }
1033
+ // Same evidence boundary as #609: without a posed other limb, overlap
1034
+ // with its base art requires a pose. No overlap retains the compatible
1035
+ // path; the missing limb is never silently placed at its base bones.
1036
+ const on = candidates.filter((p) => piece.r.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE && others.baseArt[l]?.data[p] === 1).length;
1037
+ if (on > 0) problems.push({ code: 'ASSEMBLE_ALT_LIMB_POSE', object: `part "${q.part}" (config.limbs.${q.limb}, source-transparent cap, and config.limbs.${l})`,
1038
+ detail: `holds ${on} cap pixels where the base draws ${l}, but the set does not pose ${unposed.map((b) => `"${b}"`).join(', ')}; a supplied pose for the other limb is required to assign the cap by its target source segments, never its base place` });
1039
+ }
1040
+ if (problems.length > before || posed.length === 0) return;
1041
+ const own = sourceLimbTarget(limbs[q.limb], q.of, places);
1042
+ const other = posed.map((l) => ({ l, target: sourceLimbTarget(others.limbs[l], q.of, places) }));
1043
+ for (const { l, target } of [{ l: q.limb, target: own }, ...other]) {
1044
+ if (target.missingEndBone !== null) problems.push({ code: 'ASSEMBLE_ALT_LIMB_POSE', object: `config.limbs.${l} (part "${q.part}", source-transparent cap, bone "${target.missingEndBone}")`,
1045
+ detail: `takes "${q.of}" on a segment with no supplied end; an explicit bone tip or the following segment's joint in the set's pose is required to assign its cap, never an invented endpoint` });
1046
+ }
1047
+ if (problems.length > before) return;
1048
+ let kept = 0, bandKept = 0, bandGiven = 0;
1049
+ const given = new Map(posed.map((l) => [l, 0]));
1050
+ for (const p of candidates) {
1051
+ const x = p % W + 0.5, y = Math.floor(p / W) + 0.5;
1052
+ const dOwn = Math.sqrt(polylineDist2(own.line, x, y));
1053
+ let best: { l: string; distance: number; part: string } | null = null;
1054
+ for (const o of other) {
1055
+ const near = nearestTargetPart(o.target, x, y);
1056
+ if (best === null || near.distance < best.distance) best = { l: o.l, ...near };
1057
+ }
1058
+ if (best === null) continue;
1059
+ const inBand = Math.abs(best.distance - dOwn) <= OVERLAP_BAND_PX;
1060
+ const give = inBand ? (drawAt.get(best.part) ?? -1) > (drawAt.get(q.part) ?? -1) : best.distance < dOwn;
1061
+ const opaque = piece.r.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE;
1062
+ if (!give) {
1063
+ if (opaque) { kept++; if (inBand) bandKept++; }
1064
+ } else {
1065
+ if (opaque) { given.set(best.l, (given.get(best.l) ?? 0) + 1); if (inBand) bandGiven++; }
1066
+ piece.r.data.fill(0, p * 4, p * 4 + 4);
1067
+ if (piece.region !== null) piece.region.data[p] = 0;
1068
+ }
1069
+ }
1070
+ counts.push({ part: q.part, of: q.of, limb: q.limb, kept, given: posed.map((l) => ({ limb: l, px: given.get(l) ?? 0 })), bandKept, bandGiven });
1071
+ });
1072
+ return { counts, problems };
1073
+ }
1074
+
1075
+ /** Only actual cap reassignments are reported; source-art split counts remain their own stage's. */
1076
+ export function capOwnershipLines(set: string, counts: readonly SplitCount[]): string[] {
1077
+ return counts.filter((c) => c.given.some((g) => g.px > 0)).map((c) =>
1078
+ ` LINT set "${set}" ${c.part}: source-transparent cap assigned by target source segments at the set's bones: kept ${c.kept} px, ${c.given.map((g) => `gave ${g.px} px to ${g.limb}`).join(', ')}; overlap band ${OVERLAP_BAND_PX} px, ${c.bandKept} kept and ${c.bandGiven} given by draw order`);
1079
+ }
1080
+
974
1081
  /**
975
1082
  * One `LINT` line per {@link SplitCount} (issue #609), in `config.limbs` order: the part's pixels kept and given to each
976
1083
  * other limb, each with its share of the part's pixels before the split (3 places), and the overlap band's pixels and
@@ -2113,9 +2220,11 @@ export function pixelOwners(rigLayers: readonly Raster[], rank: readonly number[
2113
2220
  *
2114
2221
  * Both rules return `clear` (no layer in front of this one, by `frontOf`, is the owner) and `takenMask`, the
2115
2222
  * masks the part counts in `parts.json` are derived from; `takenMask` is a
2116
- * subset of the top-most set, and so of `clear`.
2223
+ * subset of the top-most set, and so of `clear`. Issue #637's optional `keep`
2224
+ * masks mark own-layer art under a subset set's actual cover (alpha above 8);
2225
+ * those pixels are occluded, outside every projection core, and never recoloured.
2117
2226
  */
2118
- export function projectSource(rigLayers: Raster[], srcr: Raster, frame: Frame, run: Run, rule: ProjectRule = DEFAULT_PROJECT_RULE, rank: readonly number[] | null = null): ProjectionStats[] {
2227
+ export function projectSource(rigLayers: Raster[], srcr: Raster, frame: Frame, run: Run, rule: ProjectRule = DEFAULT_PROJECT_RULE, rank: readonly number[] | null = null, keep: ReadonlyArray<Mask | null> | null = null): ProjectionStats[] {
2119
2228
  const { W, H } = frame;
2120
2229
  const owner = pixelOwners(rigLayers, rank);
2121
2230
  const inFront = (o: number, i: number): boolean => frontOf(o, i, rank);
@@ -2135,8 +2244,8 @@ export function projectSource(rigLayers: Raster[], srcr: Raster, frame: Frame, r
2135
2244
  const takenMask = newMask(W, H);
2136
2245
  let anyTop = false;
2137
2246
  for (let p = 0; p < W * H; p++) {
2138
- if (owner[p] === -1 || owner[p] === i || !inFront(owner[p], i)) clear.data[p] = 1;
2139
- if (owner[p] === i && r.data[p * 4 + 3] >= CORE_ALPHA) {
2247
+ if (keep?.[i]?.data[p] !== 1 && (owner[p] === -1 || owner[p] === i || !inFront(owner[p], i))) clear.data[p] = 1;
2248
+ if (keep?.[i]?.data[p] !== 1 && owner[p] === i && r.data[p * 4 + 3] >= CORE_ALPHA) {
2140
2249
  top.data[p] = 1;
2141
2250
  anyTop = true;
2142
2251
  }
@@ -2607,7 +2716,8 @@ function keepArtWhole(part: PlacedPart, cleared: Cleared[], holderAt: (q: number
2607
2716
 
2608
2717
  /**
2609
2718
  * Step 4b (issue #119), over every part in draw order, before the seam
2610
- * override. Modifies the part images in place and returns, per part, the
2719
+ * override. Issue #637's optional `keep` masks protect own-layer art under a set cover.
2720
+ * Modifies the part images in place and returns, per part, the
2611
2721
  * pixels it cleared, by holder.
2612
2722
  *
2613
2723
  * ⚖️ Invariant: a pixel is PUSHED BACK in a part when, over the stack as it
@@ -2653,7 +2763,7 @@ function keepArtWhole(part: PlacedPart, cleared: Cleared[], holderAt: (q: number
2653
2763
  * hold the pixel after it); and every pixel at alpha >= `CORE_ALPHA`, which
2654
2764
  * is the seam override's.
2655
2765
  */
2656
- export function pushBackFringe(parts: PlacedPart[], srcr: Raster, rule: SeamRule, silhouette: Mask | null, feathered: ReadonlyArray<Mask | null> | null = null): FringePushed[][] {
2766
+ export function pushBackFringe(parts: PlacedPart[], srcr: Raster, rule: SeamRule, silhouette: Mask | null, feathered: ReadonlyArray<Mask | null> | null = null, keep: ReadonlyArray<Mask | null> | null = null): FringePushed[][] {
2657
2767
  const { width: W } = srcr;
2658
2768
  const { holder, cand } = seamCandidates(parts, srcr, rule, silhouette);
2659
2769
  const at = (i: number, d: number): number => {
@@ -2671,7 +2781,7 @@ export function pushBackFringe(parts: PlacedPart[], srcr: Raster, rule: SeamRule
2671
2781
  // cover itself the loop below has nothing to clear, and the seam override acts on the pixel as before.
2672
2782
  if (cand[d] === 0 || !shows(d)) continue;
2673
2783
  for (let i = holder[d] + 1; i < parts.length; i++) {
2674
- if (feathered?.[i]?.data[d] === 1) continue;
2784
+ if (feathered?.[i]?.data[d] === 1 || keep?.[i]?.data[d] === 1) continue;
2675
2785
  const s = at(i, d);
2676
2786
  if (s < 0) continue;
2677
2787
  const img = parts[i].image.data;
@@ -2712,10 +2822,12 @@ export function pushBackFringe(parts: PlacedPart[], srcr: Raster, rule: SeamRule
2712
2822
  * characters — ORACLE_assemble.md.)
2713
2823
  * Each candidate is recoloured to the painting's colour in the TOP-MOST part
2714
2824
  * covering it, and only where that part's alpha is >= 250; alpha never
2715
- * changes. Candidates are chosen once, before any recolouring.
2825
+ * changes. Candidates are chosen once, before any recolouring. Issue #637's
2826
+ * optional `keep` masks, indexed by part in rig space, preserve own-layer art
2827
+ * under a subset set's actual cover instead of recolouring it to the painting.
2716
2828
  * (`assemble_parts.py` `main`, "5. seam override".)
2717
2829
  */
2718
- export function seamOverride(parts: PlacedPart[], srcr: Raster, rule: SeamRule, silhouette: Mask | null): void {
2830
+ export function seamOverride(parts: PlacedPart[], srcr: Raster, rule: SeamRule, silhouette: Mask | null, keep: ReadonlyArray<Mask | null> | null = null): void {
2719
2831
  const { width: W } = srcr;
2720
2832
  const { top, cand } = seamCandidates(parts, srcr, rule, silhouette);
2721
2833
  parts.forEach(({ record: p, image }, i) => {
@@ -2724,7 +2836,7 @@ export function seamOverride(parts: PlacedPart[], srcr: Raster, rule: SeamRule,
2724
2836
  for (let x = 0; x < p.w; x++) {
2725
2837
  const d = (p.y + y) * W + p.x + x;
2726
2838
  const s = (y * p.w + x) * 4;
2727
- if (cand[d] === 0 || top[d] !== i || image.data[s + 3] < CORE_ALPHA) continue;
2839
+ if (keep?.[i]?.data[d] === 1 || cand[d] === 0 || top[d] !== i || image.data[s + 3] < CORE_ALPHA) continue;
2728
2840
  image.data[s] = srcr.data[d * 4];
2729
2841
  image.data[s + 1] = srcr.data[d * 4 + 1];
2730
2842
  image.data[s + 2] = srcr.data[d * 4 + 2];
@@ -3375,7 +3487,7 @@ const CAP_FROM_LOWER = 4;
3375
3487
  const CAP_FROM_LOWER_KEPT = 5;
3376
3488
 
3377
3489
  /**
3378
- * Issue #603: the set exclusion cleared rig pixel `(x, y)` of a lower segment's part; when the cap wrote or kept it,
3490
+ * Issues #603/#637: ownership or set exclusion cleared rig pixel `(x, y)` of a lower segment's part; when the cap wrote or kept it,
3379
3491
  * move it from the count it was in to `excluded_px`, so the record's counts are the PNG's. A pixel off the cap's disc,
3380
3492
  * or one the cap counted missing (it wrote none), changes nothing.
3381
3493
  */
@@ -4101,6 +4213,8 @@ export interface AssembleResult {
4101
4213
  islands: IslandCount[];
4102
4214
  /** Issue #609: what each limb segment part cut from a `limbIslands` part of one island that `otherLimbs` take kept; empty otherwise. */
4103
4215
  splits: SplitCount[];
4216
+ /** Issue #637: source-transparent cap pixels assigned before preservation, in either source-art door. */
4217
+ capSplits: SplitCount[];
4104
4218
  }
4105
4219
 
4106
4220
  /** A hidden-art layer of a run (issue #359) and what read it: `cuts[i].under`, or a limb segment's cap; none is said. */
@@ -4297,6 +4411,13 @@ export function assemble(input: AssembleInput): AssembleResult {
4297
4411
  });
4298
4412
  refuseIfAny(hiddenProblems);
4299
4413
 
4414
+ // Issue #637: only subset limb sources, and only where a layer in front actually holds art.
4415
+ // Never extend an absent limb pixel or borrow a base layer's colour. The mask survives cuts by
4416
+ // the source key; only the resulting limb pieces read it, after #609 has assigned their pixels.
4417
+ const underCover = new Map<string, Mask>();
4418
+ const coverFootprints = new Map<string, Mask>();
4419
+ const limbSources = new Set(Object.values(input.limbs ?? {}).flatMap((l) => l.segments.map((sg) => sg.from)));
4420
+ const limbPlans = new Set([...limbSources, ...cuts.filter((c) => limbSources.has(c.into)).map((c) => c.from)]);
4300
4421
  const rig = new Map<string, Raster>();
4301
4422
  const stats = new Map<string, ProjectionStats>();
4302
4423
  const ghost: Record<string, number> = {};
@@ -4307,7 +4428,21 @@ export function assemble(input: AssembleInput): AssembleResult {
4307
4428
  const layers = runLayers(set, input.resolution);
4308
4429
  if (run === 'full') fullTags.push(...layers.filter((l) => l.opaqueRunPx > 0).map((l) => l.tag));
4309
4430
  const rigLayers = layers.map((l) => layerToRig(l.canvas, frame, run));
4310
- const st = projectSource(rigLayers, srcr, frame, run, projectRule, planRanks(layers.map((l) => l.tag), run, plan));
4431
+ const rank = planRanks(layers.map((l) => l.tag), run, plan);
4432
+ const keep = layers.map((l, i): Mask | null => {
4433
+ if (input.limbUnderCover !== true || !plan.some(([name, ru, tag]) => limbPlans.has(name) && ru === run && tag === l.tag)) return null;
4434
+ const mask = newMask(W, H);
4435
+ const cover = newMask(W, H);
4436
+ for (let p = 0; p < W * H; p++) {
4437
+ if (!rigLayers.some((r, j) => frontOf(j, i, rank) && r.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE)) continue;
4438
+ cover.data[p] = 1;
4439
+ if (rigLayers[i].data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE) mask.data[p] = 1;
4440
+ }
4441
+ underCover.set(`${run}:${l.tag}`, mask);
4442
+ coverFootprints.set(`${run}:${l.tag}`, cover);
4443
+ return mask;
4444
+ });
4445
+ const st = projectSource(rigLayers, srcr, frame, run, projectRule, rank, keep);
4311
4446
  layers.forEach((l, i) => {
4312
4447
  rig.set(`${run}:${l.tag}`, rigLayers[i]);
4313
4448
  stats.set(`${run}:${l.tag}`, st[i]);
@@ -4624,16 +4759,61 @@ export function assemble(input: AssembleInput): AssembleResult {
4624
4759
  ? { counts: [], splits: [], problems: [] }
4625
4760
  : keepJointIslands(input.limbIslands ?? [], input.limbs ?? {}, input.bones ?? [], lim.parts, limbPieces, limbSource, W, H, input.islandFloor ?? ISLAND_FLOOR_SHARE, input.otherLimbs);
4626
4761
  refuseIfAny(islandKept.problems);
4762
+ const capAssigned = input.capOwnership === 'source' ? { counts: [], problems: [] }
4763
+ : assignCapOwnership(input.limbIslands ?? [], input.limbs ?? {}, input.bones ?? [], lim.parts, limbPieces, limbSource, lim.capFrom, W, H, input.otherLimbs);
4764
+ refuseIfAny(capAssigned.problems);
4627
4765
 
4628
- // Issue #587: a set's limb part loses the pixels a base part it does not replace covers, before anything is counted.
4629
- // Issue #603: its merged_px and its cap record lose them too, so they count what its PNG holds.
4630
- const excluded: ExcludedCount[] = [];
4766
+
4767
+ // Issue #637: protection belongs to the assigned piece, never to a component guessed from
4768
+ // its size or colour. After target assignment, a retained upper-copy cap is the limb's connecting art beneath
4769
+ // its upper segment (limbOrder draws the upper over the lower). Other cap provenance is
4770
+ // protected only beneath an actual front layer, including where the lower source is
4771
+ // transparent. Source art still needs both its own alpha and that actual cover.
4772
+ // Read this after island/nearest-line assignment: a cleared pixel is never brought back.
4631
4773
  const recount = input.exclusionCounts !== 'before';
4774
+ // Assignment owns its bookkeeping even when cover preservation is not requested
4775
+ // (for example a direct assemble caller). Only the explicit historical mutant
4776
+ // with neither protection nor target assignment retains the old count path.
4777
+ if (recount && (input.limbUnderCover === true || input.capOwnership !== 'source')) {
4778
+ limbPieces.forEach((b, i) => {
4779
+ if (b.region !== null) b.merged = mergedIn(b, b.region);
4780
+ const cap = lim.parts[i].record.cap, from = lim.capFrom[i];
4781
+ if (cap === undefined || from === null) return;
4782
+ const [bx, by, bw, bh] = from.box;
4783
+ for (let y = Math.max(0, by); y < Math.min(H, by + bh); y++) for (let x = Math.max(0, bx); x < Math.min(W, bx + bw); x++) {
4784
+ if (b.r.data[(y * W + x) * 4 + 3] === 0) excludeCapPixel(cap, from, x, y);
4785
+ }
4786
+ });
4787
+ }
4788
+ const limbKeep = limbPieces.map((b, i): Mask | null => {
4789
+ if (input.limbUnderCover !== true) return null;
4790
+ const keep = newMask(W, H);
4791
+ const sourceKeep = underCover.get(b.key);
4792
+ if (sourceKeep !== undefined) keep.data.set(sourceKeep.data);
4793
+ const cap = lim.parts[i].record.cap;
4794
+ const from = lim.capFrom[i];
4795
+ if (cap === undefined || from === null) return keep;
4796
+ const [bx, by, bw, bh] = from.box;
4797
+ for (let y = Math.max(0, by); y < Math.min(H, by + bh); y++) {
4798
+ for (let x = Math.max(0, bx); x < Math.min(W, bx + bw); x++) {
4799
+ const code = from.codes[(y - by) * bw + x - bx];
4800
+ if (code === 0) continue;
4801
+ const p = y * W + x;
4802
+ if (b.r.data[p * 4 + 3] > 0 && (code === CAP_FROM_UPPER || coverFootprints.get(b.key)?.data[p] === 1)) keep.data[p] = 1;
4803
+ }
4804
+ }
4805
+ return keep;
4806
+ });
4807
+
4808
+ // Issue #587: unprotected pixels under base parts not replaced by the set still leave.
4809
+ // Issue #603: merged_px and cap counts lose exactly the pixels cleared from the PNG.
4810
+ const excluded: ExcludedCount[] = [];
4632
4811
  for (const ex of input.exclude ?? []) {
4633
4812
  const d = order.find((q) => !('patch' in q) && pieceAt(q).name === ex.part);
4634
4813
  const b = d === undefined || 'patch' in d ? null : pieceAt(d).b;
4635
4814
  const capOf = d !== undefined && 'limb' in d ? lim.parts[d.limb].record.cap : undefined;
4636
4815
  const from = d !== undefined && 'limb' in d ? lim.capFrom[d.limb] : null;
4816
+ const keep = d !== undefined && 'limb' in d ? limbKeep[d.limb] : null;
4637
4817
  let px = 0;
4638
4818
  if (b !== null) {
4639
4819
  if (b.region === null) {
@@ -4642,7 +4822,7 @@ export function assemble(input: AssembleInput): AssembleResult {
4642
4822
  }
4643
4823
  let mergedOut = 0;
4644
4824
  for (let p = 0; p < W * H; p++) {
4645
- if (ex.mask.data[p] === 0 || b.r.data[p * 4 + 3] === 0) continue;
4825
+ if (ex.mask.data[p] === 0 || b.r.data[p * 4 + 3] === 0 || keep?.data[p] === 1) continue;
4646
4826
  if (b.r.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE) px++;
4647
4827
  // merged_px counts the last merge's copied pixels and its ring inside the part's region (`mergedIn`).
4648
4828
  if (b.region.data[p] === 1) mergedOut += (b.trace.lastSel?.data[p] ?? 0) + (b.trace.lastRing?.data[p] ?? 0);
@@ -4664,7 +4844,8 @@ export function assemble(input: AssembleInput): AssembleResult {
4664
4844
  return { record: whole, image: b.r };
4665
4845
  });
4666
4846
  const featheredInOrder: Array<Mask | null> = order.map((d) => ('patch' in d ? null : (pieceAt(d).b.feathered ?? null)));
4667
- const pushedBy = pushBackFringe(stack, srcr, seamRule, seamRule === 'silhouette' ? silhouette : null, featheredInOrder);
4847
+ const keepInOrder = order.map((d) => ('limb' in d ? limbKeep[d.limb] : null));
4848
+ const pushedBy = pushBackFringe(stack, srcr, seamRule, seamRule === 'silhouette' ? silhouette : null, featheredInOrder, keepInOrder);
4668
4849
  // Issue #255: a part's drift refusals in a body, and who holds the body in the draw order (the push-back clears
4669
4850
  // only fringe below CORE_ALPHA, and the seam override only recolours, so the holders read here are final).
4670
4851
  const holderAt = new Int32Array(W * H).fill(-1);
@@ -4768,7 +4949,7 @@ export function assemble(input: AssembleInput): AssembleResult {
4768
4949
  refuseIfAny(empty);
4769
4950
  const placed: PlacedPart[] = order.map((d) => ('plan' in d ? planned[d.plan] : 'cut' in d ? cutPlaced[d.cut] : 'limb' in d ? limbPlaced[d.limb] : cut[d.patch]) as PlacedPart);
4770
4951
 
4771
- seamOverride(placed, srcr, seamRule, seamRule === 'silhouette' ? silhouette : null);
4952
+ seamOverride(placed, srcr, seamRule, seamRule === 'silhouette' ? silhouette : null, keepInOrder);
4772
4953
  const can = recomposite(placed, W, H);
4773
4954
  // Issue #242: on a scene painting the figure is read off the full run, and every recomposite figure inside it.
4774
4955
  const inside = input.scene === true ? sceneFigure([...rig.entries()].filter(([k]) => k.startsWith('full:')).map(([, r]) => r), W, H) : null;
@@ -4819,6 +5000,7 @@ export function assemble(input: AssembleInput): AssembleResult {
4819
5000
  excluded,
4820
5001
  islands: islandKept.counts,
4821
5002
  splits: islandKept.splits,
5003
+ capSplits: capAssigned.counts,
4822
5004
  };
4823
5005
  }
4824
5006
 
package/src/build.ts CHANGED
@@ -84,7 +84,7 @@ import { type AlternatePartsRecord, type PartRecord, readParts, type Recomposite
84
84
  import { encodePngBytes, readPng, writePng } from './raster/png.ts';
85
85
  import type { Raster } from './raster/types.ts';
86
86
  import { type Mask, newMask } from './raster/types.ts';
87
- import { type OtherLimbs, splitLines, type SplitCount } from './assemble.ts';
87
+ import { type OtherLimbs, splitLines, capOwnershipLines, type SplitCount } from './assemble.ts';
88
88
  import type { BoneEntry } from './config.ts';
89
89
  import { OPAQUE_ALPHA_ABOVE } from './layers.ts';
90
90
  import { readRequirements, type RequirementLine, summaryText } from './requirements.ts';
@@ -169,6 +169,10 @@ export interface AssembleStageInput {
169
169
  * `"none"` takes them, the rule before #587 — kept for the selftest's control that shows the count go red under it.
170
170
  */
171
171
  setExclusion?: 'base' | 'none';
172
+ /** Issue #637: the CLI protects assigned source/cap art under covers; painting is the unprotected test mutant only. */
173
+ setCover?: 'layer' | 'painting';
174
+ /** Issue #637: source is the skipped-cap ownership test mutant, never a CLI/config option. */
175
+ setCapOwnership?: 'target' | 'source';
172
176
  /**
173
177
  * What a subset set's limb parts keep of a layer of more than one island when the set names one limb side (issue
174
178
  * #588): `"joints"` (the default, the only one the CLI runs) the island the segment's joints fall on
@@ -180,9 +184,11 @@ export interface AssembleStageInput {
180
184
  * How a subset set's limb parts share a layer of one island with a limb the set does not carry (issue #609):
181
185
  * `"nearest"` (the default, the only one the CLI runs) by the nearest segment line in the set's pose, the other limb
182
186
  * placed by the set's skeleton ({@link OtherLimbs}); `"connectivity"` every pixel on the set's limb, the rule before
183
- * #609 — kept for the selftest's control that shows the second-limb share go red under it.
187
+ * #609 — kept for the selftest's control that shows the second-limb share go red under it. Issue #638's
188
+ * `"whole-limb"` mutant uses the pre-fix line, including segments taking other sources, to reproduce its measured
189
+ * default-cap case. Neither mutant is a CLI/config option or bypasses the rig-c gate.
184
190
  */
185
- setSplit?: 'nearest' | 'connectivity';
191
+ setSplit?: 'nearest' | 'connectivity' | 'whole-limb';
186
192
  }
187
193
 
188
194
  /** Where the assemble stage writes: `parts.json`, the directory of part PNGs, the recomposite, and its error map. */
@@ -338,7 +344,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
338
344
  }
339
345
 
340
346
  const altProblems: Problem[] = [];
341
- const altBuilt: Array<{ record: AlternatePartsRecord; images: Array<{ name: string; image: Raster }>; excluded: ExcludedCount[]; islands: IslandCount[]; splits: SplitCount[] }> = [];
347
+ const altBuilt: Array<{ record: AlternatePartsRecord; images: Array<{ name: string; image: Raster }>; excluded: ExcludedCount[]; islands: IslandCount[]; splits: SplitCount[]; capSplits: SplitCount[] }> = [];
342
348
  const baseSlots = result.parts.parts.map((p) => p.name);
343
349
  for (const alt of mergedAlts) {
344
350
  if (alt.source === undefined || alt.full === undefined) {
@@ -542,6 +548,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
542
548
  for (const b of Object.keys(limbDrawn)) setPlaced.add(b);
543
549
  }
544
550
  const altOthers = Object.keys(otherLimbs).length === 0 ? undefined : otherLimbsOf(otherLimbs, setPlaced, fields.bones ?? [], result.images, result.parts.rig_size, altSkeleton !== undefined ? 'skeleton' : alt.drawn !== undefined ? 'drawn' : 'none');
551
+ if (altOthers !== undefined && input.setSplit === 'whole-limb') altOthers.line = 'whole-limb';
545
552
  // Issue #587: a subset set's limb part takes nothing a base part it does not replace covers at setup.
546
553
  const [exW, exH] = result.parts.rig_size;
547
554
  const altExclude =
@@ -552,6 +559,8 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
552
559
  try {
553
560
  altRes = assemble({
554
561
  source: altSrc,
562
+ limbUnderCover: alt.parts !== undefined && input.setCover !== 'painting',
563
+ capOwnership: input.setCapOwnership ?? 'target',
555
564
  full: altRuns.full,
556
565
  head: altRuns.head,
557
566
  resolution: fields.resolution,
@@ -621,6 +630,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
621
630
  excluded: altRes.excluded,
622
631
  islands: altRes.islands,
623
632
  splits: altRes.splits,
633
+ capSplits: altRes.capSplits,
624
634
  });
625
635
  }
626
636
  refuseIfAny(altProblems);
@@ -685,7 +695,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
685
695
  // Issue #588: per subset set, one line per limb part cut from a layer of more than one island, then (issue #587) one
686
696
  // per limb part and base part over it that took a pixel. None otherwise.
687
697
  // Issue #609: then one per limb part cut from a layer of one island that also holds a limb the set does not carry.
688
- for (const b of altBuilt) for (const l of [...islandLines(b.record.name, b.islands), ...splitLines(b.record.name, b.splits), ...excludedLines(b.record.name, b.excluded)]) log(l);
698
+ for (const b of altBuilt) for (const l of [...islandLines(b.record.name, b.islands), ...splitLines(b.record.name, b.splits), ...capOwnershipLines(b.record.name, b.capSplits), ...excludedLines(b.record.name, b.excluded)]) log(l);
689
699
  log(`wrote ${outs.partsJson}, ${result.images.length} PNG(s) in ${outs.partsDir}, ${outs.recomposite}, ${outs.errorMap} (uncovered error px red, covered error px blue, the painting grey)${figurePath === null ? '' : `, ${figurePath} (the figure, white, the recomposite was read inside)`}`);
690
700
  return result;
691
701
  }
@@ -0,0 +1,37 @@
1
+ /** Shared source-segment geometry for subset ownership; no inferred endpoints. */
2
+ import type { Limb } from './config.ts';
3
+ import { type BonePlace, limbPolyline, polylineDist2 } from './limbs.ts';
4
+
5
+ export interface SourceLimbTarget {
6
+ segments: Limb['segments'];
7
+ line: Array<[number, number]>;
8
+ /** The last source segment has neither a supplied tip nor a following joint. */
9
+ missingEndBone: string | null;
10
+ }
11
+
12
+ /** Issue #638's source selection: only consecutive segments taking this source. */
13
+ export function sourceLimbTarget(limb: Limb, source: string, places: ReadonlyMap<string, BonePlace>): SourceLimbTarget {
14
+ const segments = limb.segments.filter((sg) => sg.from === source);
15
+ if (segments.length === 0) return { segments, line: [], missingEndBone: null };
16
+ const last = segments[segments.length - 1];
17
+ const line = limbPolyline({ ...limb, segments }, places);
18
+ if ((places.get(last.bone) as BonePlace).end === null) {
19
+ const next = limb.segments[limb.segments.indexOf(last) + 1];
20
+ if (next !== undefined) line.push((places.get(next.bone) as BonePlace).at);
21
+ }
22
+ return { segments, line, missingEndBone: line.length <= segments.length ? last.bone : null };
23
+ }
24
+
25
+ /** The nearest source segment and its part, with the same stable first-segment tie as #609. */
26
+ export function nearestTargetPart(target: SourceLimbTarget, x: number, y: number): { distance: number; part: string } {
27
+ let distance = Infinity;
28
+ let segment = 0;
29
+ for (let k = 0; k + 1 < target.line.length; k++) {
30
+ const d = polylineDist2([target.line[k], target.line[k + 1]], x, y);
31
+ if (d < distance) {
32
+ distance = d;
33
+ segment = k;
34
+ }
35
+ }
36
+ return { distance: Math.sqrt(distance), part: target.segments[segment].part };
37
+ }
package/src/parts.ts CHANGED
@@ -167,12 +167,12 @@ export interface CapRecord {
167
167
  short_px?: { left: number; right: number };
168
168
  /**
169
169
  * Issue #603, written only when above 0: the cap's pixels a subset set's
170
- * exclusion (issue #587) cleared — pixels a base part the set does not
171
- * replace covers at setup — each taken out of the count it was in
170
+ * exclusion (issue #587) or preceding ownership assignment (issue #637)
171
+ * cleared, each taken out of the count it was in
172
172
  * (`layer_px`, `image_px`, `upper_px`, `lower_px`, `lower_kept_px`), so
173
173
  * those counts are the written PNG's. The disc's pixels are then the
174
174
  * counts above, `upper_px`, the lower half's and `excluded_px` together.
175
- * A cap no exclusion touched writes no key.
175
+ * A cap neither step touched writes no key.
176
176
  */
177
177
  excluded_px?: number;
178
178
  /**