@rig-c/parts 2.39.0 → 2.40.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/cli.ts CHANGED
@@ -74,7 +74,7 @@ const HELP = `rig-parts ${version()} — Spine-ready parts from one painting and
74
74
 
75
75
  usage:
76
76
  rig-parts diff-components --stack <png> --painting <png> --parts <parts.json> --floor <px>
77
- [--threshold <channel>] [--figure <binary-png>] (--out <json> | --verify <json>)
77
+ [--threshold <channel>] [--figure <binary-png>] [--owners] (--out <json> | --verify <json>)
78
78
  Exhaustive native difference inventory; default max RGB channel > 40.
79
79
 
80
80
 
@@ -1079,7 +1079,15 @@ function usage(message: string): number {
1079
1079
  }
1080
1080
 
1081
1081
  function cmdDiffComponents(args: string[]): number {
1082
+ const switches: readonly string[] = TAKES['diff-components'].switches;
1083
+ const seen = new Set<string>();
1082
1084
  for (let i = 0; i < args.length; i += 2) {
1085
+ if (switches.includes(args[i])) {
1086
+ if (seen.has(args[i])) return usage(`${args[i]} is given twice`);
1087
+ seen.add(args[i]);
1088
+ i--;
1089
+ continue;
1090
+ }
1083
1091
  if (!takesValued('diff-components', args[i])) return usage(notTaken('diff-components', args[i]));
1084
1092
  if (args[i + 1] === undefined || args[i + 1].startsWith('--')) return usage(`diff-components ${args[i]} requires a value`);
1085
1093
  }
@@ -1175,7 +1183,7 @@ function printLayerTable(set: LayerSet): void {
1175
1183
  */
1176
1184
  const TAKES = {
1177
1185
  'check-parts': { valued: ['--parts', '--out'], switches: ['--json'] },
1178
- 'diff-components': { valued: ['--stack', '--painting', '--parts', '--figure', '--floor', '--threshold', '--out', '--verify'], switches: [] },
1186
+ 'diff-components': { valued: ['--stack', '--painting', '--parts', '--figure', '--floor', '--threshold', '--out', '--verify'], switches: ['--owners'] },
1179
1187
  'depth-bind': { valued: ['--map', '--input', '--part'], switches: [] },
1180
1188
  'depth-prepare': { valued: ['--parts', '--config', '--out'], switches: [] },
1181
1189
  'depth-apply': { valued: ['--parts', '--manifest', '--config', '--rig-config', '--out'], switches: [] },
@@ -1792,7 +1800,7 @@ function cmdPropose(args: string[]): number {
1792
1800
  if (target !== null) for (const line of configWriteLines(target, staged.changes)) console.error(line);
1793
1801
  }
1794
1802
  console.log(`wrote proposal.json (${prop.bones.length} bone entries, ${Object.keys(prop.meshes).length} meshes) and render/landmarks.png (+_head) under ${out}`);
1795
- for (const n of prop.notes) console.log(`note: ${n}`);
1803
+ for (const n of prop.notes) console.log(n.startsWith('WARN PROPOSE_TORSO_ISLAND_LEFT_OUT:') ? n : `note: ${n}`);
1796
1804
  if (leftBehind.unread !== null) console.log(`note: the keyed chains were not read after the recipe (issue #572): ${leftBehind.unread}`);
1797
1805
  printLint(P, prop, joints, [...draftLint, ...leftBehind.findings]);
1798
1806
  console.log(basisLine(bfile, out));
package/docs/AUTHORING.md CHANGED
@@ -181,7 +181,7 @@ read by no CPU stage).
181
181
  | `constraints` | rig (handed to rig-c as `rig.json`'s `constraints`); `compare` and the coverage lines (roles) | **authored**, optional; `propose` writes none, but with `--cloth` (issue #364), where it writes the recipe's physics and swing transforms (*Recipe: cloth and hair that answer the world*, below). A list of constraints in **rig-c's own rig-spec shape** (`RigConstraint`: `ik`, `transform`, `path`, `physics`, `slider` — rig-c's `src/rig.ts` documents every field), in the order rigc applies them. The loader checks only what this package owns: each entry is an object with a `type` rigc names (`CONFIG_CONSTRAINT_TYPE_KNOWN`) and a non-empty `name`, unique within its kind as rigc finds constraints (`CONFIG_CONSTRAINT_NAME_UNIQUE`; an ik and a transform may share one); every bone it names — `bones`, an ik's `target`, a transform's `source`, a physics or slider constraint's `bone` — is a bone `bones` declares, a chain link as `<chain><i>` (`CONFIG_NAME_RESOLVES`); the bone a constraint follows does not sit under a bone it drives (`CONFIG_CONSTRAINT_TARGET_DETACHED`). Every other field (`mix`, `softness`, `properties`, a path's `slot`, a slider's `animation`) and every value is rigc's to accept or refuse at the rig stage's gate, in rigc's words (`RIG_RIGC_GREEN`) — an ik's `bones` as a shape too: from rig-c 2.15.0 rigc refuses an ik over more than two bones, or over a pair whose second bone is not the first's child (issue #103; this loader refused both itself until then). A note and an `x-` record may ride on an entry; the rig stage leaves them out of what it hands rigc. Under the default `--idle-keys ctl` a two-bone ik whose child link the idle keys is split by that link's control, and rigc refuses the pair: run `rig --idle-keys direct` or `build --idle-keys direct` (the rig stage adds that sentence, naming the flag on the command that ran, to rigc's line; `build` forwards it to its rig stage, issue #95). Each bone a constraint follows is declared to rigc as `invariants.detached` from every bone it drives, which rigc's gate rule `A25` checks |
182
182
  | `stops` | rig (handed to rig-c as `rig.json`'s `stops`, and moves slots, mesh weights and child bones on stopped links onto `<link>_d`); `propose --from-config` (`LINT stop on <chain> …`) | **authored**, optional (issues #404, #447): `[{chain, links?, against, at, inward, outward, lower?: {inward, outward}}]` — rig-c's leg stops (`RigStop`, rig-c 2.56.0, `@rig-c/core/stop`). `chain` is a chain `bones` declares (`CONFIG_NAME_RESOLVES`, `RIG_NAME_RESOLVES`); `links`, optional, is a non-empty list of links of that chain (`CONFIG_NAME_RESOLVES`, `CONFIG_FIELD_TYPE`), or absent for every link of `chain` in chain order; `against` is a bone `bones` declares, a chain link as `<chain><i>` (`CONFIG_NAME_RESOLVES`, `RIG_NAME_RESOLVES`); `at` is `[x, y]` in `against`'s local space, as rig-c's stop takes it (`CONFIG_FIELD_TYPE`): since each chain link (`leg_r0`, `leg_r1`) is turned to point along its segment (`+x` from origin to next link or tip, `+y` 90° counter-clockwise in Spine world), `at: [d, n]` sits `d` px from `against`'s origin toward its end and `n` px perpendicular to it; `inward`, `outward` and `lower.inward`, `lower.outward` are finite numbers (`CONFIG_FIELD_TYPE`). Every other stop rule — non-negative bounds, each stopped link written by a constraint, `against` not under the stopped chain, the aim not degenerate, `\|rest\| + outward <= 180°` (`RIG_STOP_BOUNDS`) — is rigc's to accept or refuse at the rig stage's gate, in rigc's words (`RIG_RIGC_GREEN`). **Rising-limb / prone geometry (issue #447):** rig-c's `expandStops` aims `<chain>_rest` from `links[0]`'s setup origin at `<chain>_touch` (`at` in `against`'s local frame) and clamps `<link>_d` inside `[rest − inward, rest + outward]`; Spine wraps rotation at `±180°`, so `\|rest\| + outward <= 180°` is required (`RIG_STOP_BOUNDS`). Whenever `<chain>_touch` lies **above** `links[0]`'s root in rig pixels (`ty < y0`, i.e. higher Spine `y` — e.g. stopping a hanging cloth chain against a rising shin `leg_<s1>` in a prone or kneeling pose where the knee sits below `links[0]` and the ankle above it, so positive `at[0]` walks upward along the shin past `links[0]`'s root), `rest` lands in the upper half-plane (`\|rest\| > 90°`) and `\|rest\| + outward` exceeds `180°`. Stop against the descending thigh (`leg_<s0>`), set `links` to start at a link whose root sits above `<chain>_touch`, or omit the stop when the rising shin sits outside the hanging chain's sweep; `propose --from-config` prints `LINT stop on <chain> …` with the exact coordinates and angles when `<chain>_touch` lies above `links[0]`'s root or `\|rest\| + outward > 180°`. For every stopped link `<link>`, the rig stage moves any slot on `<link>`, any mesh weight on `<link>`, and any bone whose parent is `<link>` (a branched cloth tree's branches hanging from `<trunk_last>`, before `--idle-keys ctl` adds `<bone>_ctl` and before `turn` adds `turn_<part>_<bone>`) onto `<link>_d`, the drawn link bone rig-c's `expandStops` creates at `<link>`'s setup frame to carry the clamped rotation. Absent, `rig.json` carries no `stops` and no byte of any output moves |
183
183
  | `turn` | rig (adds the turn control or 2.5D head-turn producer) | **proposed** only with `propose --full`/`--head` (issue #251), then corrected, or **authored** for 2.5D depth-sampled head turns (issue #763): `{pivot?, depths?, deform?, band?, radius?, surface?: {radius?}, head?: {pivot?, radius?}, roles?, counter?, grid?, unitDepths?, body?}`. When `roles` is declared (`{<part>: "surface" \| "unit" \| "rear"}`, issue #763; `CONFIG_TURN_ROLE_UNKNOWN`, `CONFIG_TURN_SURFACE_REQUIRED`, `RIG_TURN_SURFACE_MESH_BINDINGS`, `CONFIG_TURN_UNIT_MESH_BONES`), the rig stage runs the 2.5D depth-sampled head-turn producer: it edge-extends each turn-bound part's depth sheet across its transparent border and semi-transparent fringe from the nearest fully opaque (`alpha === 255`) texel before `PAD = 4` clamping (`padTurnDepthSheet`, `DEPTH_SILHOUETTE_SIZE_MISMATCH`), keeps authored `"surface"` meshes and their skinning (#795), sampling each vertex at its weighted setup position on its own extended sheet and emitting one inverse-setup-bone offset per influence (`D = -(pivot + z - zRef) * sin(angle)`, on x for yaw and y for pitch, with no narrowing or 2D spin); shared frames moved by another turn role are refused (`RIG_TURN_SURFACE_MESH_BINDINGS`), as are alternate drawings without their own depth sampling frame (`RIG_TURN_SURFACE_MESH_ATTACHMENT`). It promotes `"surface"` regions to `generator: {kind: "grid", cols, rows, depth}` (`grid`: `[cols, rows]` or `{<part>: [cols, rows]}`, default `[13, 16]`, bounded at `<= 2,400` triangles per slot and `<= 4,000` total, `RIG_TURN_GRID_BUDGET`, `RIG_TURN_SURFACE_DEPTH_REQUIRED`, `RIG_TURN_SHARED_DEPTH_SCALE`), emits `faceshift` and `rear_shift` under `head` (`CONFIG_TURN_HEAD_BONE`, `RIG_TURN_HEAD_BONE`), `<part>_surface` and `<part>_unit` under `faceshift`, and `yaw_dial` and `pitch_dial` under `root` (`CONFIG_TURN_BONE_FREE`, `RIG_TURN_NAME_FREE`), re-parents `"unit"` region bones and `"rear"` bones and mesh weights to `faceshift` and `rear_shift` (while `"unit"` mesh parts receive their own `<part>_unit` carrier under `faceshift`, rebind direct `"head"` weights to `<part>_unit`, reparent bound chain roots to `<part>_unit` while keeping chain skinning weights intact, and key `<part>_unit` in `turn_units`, #790), samples each `"unit"` bone's depth from the `"surface"` depth sheet at its rest position (or reads `unitDepths.<part>`, `RIG_TURN_UNIT_DEPTH_REQUIRED`), enforces ear occlusion (`ear_r`/`ear_l` drawn before the `face` surface in `assemble.plan`, `CONFIG_TURN_EAR_DRAW_ORDER`, and behind the cheek surface, `RIG_TURN_EAR_DEPTH_BEHIND_CHEEK`), and writes `turn` and `tilt` `derive` tracks (`pivot` default `55` rig px, `counter` default `0.1` in `[0, 1]`, `CONFIG_TURN_COUNTER_RANGE`). `depths` holds, per part, the See-through layer's `depth_median` the part came from (larger = further back), read from the run the part was assembled from; a `painting:` patch has none and is not carried. A rider (issue #271) — a part from an `eyewhite`, `irides`, `eyelash`, `eyebrow`, `nose` or `mouth` layer — is drafted at the `face` part's depth, 0.001 nearer when parts.json draws it after the face and 0.001 further when before: See-through makes no depth of its own for the eye group (it cuts them from one depth map of the combined eyes) and clamps nose and mouth to the face's median − 0.001, and the two runs' own medians for these layers disagreed by up to 0.47 and swapped their order against the face. Every other layer — ears, headwear and earwear included — keeps its own median, unless it rides another part's bone. With no `face` part, or more than one, the riders keep their own and a note says so. A rider by bone (issue #535) — a part every *ownable* bone of which (a chain link, or a bone no other bone hangs from; `head`, `chest` and any bone with a child are shared and never count on their own) is *hosted* by another carried part, the host of a bone being the carried part that binds it (its region's bone; a mesh's `segments`, `contour` and `auto` regions' bones) with the most `opaque_px`, the earlier in parts.json on a tie, and which hosts no bone itself — is drafted at its host's depth, 0.001 nearer when drawn after the host and 0.001 further when before, and a note names the host, the bones and its own median: a pin, clip or ornament on the back hair's links travels with the back hair, not with its own layer's depth. `propose` reads the proposal's own `bones`, `meshes` and `regions`; the face riders are read by their tag first and never by their bones. A part bound to two hosts' bones rides neither and a note says so. In the rig stage, an authored depth on a rider by bone whose fraction differs from its host's by more than 0.1 of the dial (`TURN_RIDER_APART`, a share of `pivot − nearest`) is refused (`CONFIG_TURN_RIDER_DEPTH`); the host is read off `parts.json`'s `opaque_px`, so the config loader cannot see it. One note lists each part's depth and where it came from; a carrier the other run places more than 10 % of `pivot − nearest` away gets a note naming both values and the run read — the two runs are not reconciled. `pivot` is the depth that stays put; `propose` drafts the mean of the parts' depths weighted by `opaque_px`, the one depth at which the painted pixels' centroid does not slide under the dial. The rig stage adds a bone `turn` under `root` at its origin that nothing keys — its local x is the dial, in rig px — and carries each part by `(pivot − depth) / (pivot − nearest depth)` of it: the nearest part all of it, a part behind the pivot the other way, a part at the pivot not at all. Each part rides leaf twins (`turn_<part>_<bone>`, an identity child of every bone its slot and weights bind) moved by one `transform` constraint (`turn_<part>`, after the config's own); the idle's keys, the `<bone>_ctl` controls and a physics constraint stay on the bones, and the dial moves none of them. Optional `deform` (`Partial<FaceDeformFractions>`, issue #436) overrides the Set B ×2.5 face surface deformation table (`FACE_DEFORM_FRACTIONS`, checked against `FACE_DEFORM_RANGES` by `CONFIG_TURN_DEFORM_RANGE`); when `applyFaceSurfaceDeform` runs on a rig whose `motion` carries `tilt` or `turn` slider `derive` keys, it requires `config.turn` (`CONFIG_TURN_REQUIRED`, issue #478; `propose --full`/`--head` drafts it), promotes `face` on `head` (or `turn_face_head` when `turn` is declared) to the uneven 5×5 grid mesh, keys `face`, `hair_front` and `hair_back` deform timelines and ear/topknot tracks from `evalPitchFaceSurface` and `evalYawFaceSurface`, and samples the same deform field across each `features` member's rest span (`featRx = (24 / 106) · W`, `featRy = (12 / 128) · H`) with its depth fraction `z / zRef` as the field's angle input and chord foreshortening (`scalex` narrowing on the leading side and widening on the trailing side, `scaley` on pitch) so every feature's bounding box stays inside the deformed face plate across the rated band (issue #468). On yaw (`issue #479`), `evalYawFaceSurface` evaluates a **cylinder projection** (`cylinderYawDx`: `Δx(x, θ, R) = R · (sin(clamp(arcsin(clamp(x / R, −1, 1)) − θ, −π/2, π/2)) − clamp(x / R, −1, 1))`) of radius `R` (`turnSurfaceRadius`: `turn.surface.radius ?? turn.radius ?? turn.head.radius`, positive rig px checked by `CONFIG_FIELD_TYPE`, defaulting to half the face plate's opaque width `W / 2`) tapered by a cubic Hermite outline weight (`wOutline = 1` for `\|ux\| <= 0.7`, reaching `0` at `\|ux\| = 1.0`) so features slide across a fixed outline (`iris` shift within `±2%` of `cylinderYawDx`), the trailing cheek strip widens (`>= 1.54×` at `±15°`), and the leading jaw edge holds fixed (`0 px` shift) unless explicit horizontal `turn.deform` overrides (`turn_mid_x`, `turn_lead_compress_x`, `turn_trail_shift_x`) request the flat yaw table. On yaw (`issue #478`), `applyFaceSurfaceDeform` also derives a **head-only pivot** (`headTurnPivot`: `turn.head.pivot` when authored, otherwise the `opaque_px`-weighted mean of `depths[part]` across the head parts `DEFAULT_HEAD_TURN_PARTS` — `face`, `hair_front`, `hair_back`, `ear_r`, `ear_l`, `hairpin` — from `parts.json`, falling back to `turn.pivot`) so a forward torso or arm in `turn.depths` does not pull the head's rotation axis in front of `face`: `hair_back` (`depth_median > headPivot`, negative `headTurnFraction`) and `hairpin` behind `headPivot` translate opposite to the face's turn (`dx = s · turn_face_center_x · W · (headPivot − depth) / (headPivot − nearestHeadDepth)`), emerging on the trailing side to compensate for the leading-cheek foreshortening and keeping the combined head silhouette width near-constant across `±15°` without any same-sign `turn_hair_back_cheek_x` term. Optional `band` (`number` or `{yaw?, pitch?}`, positive degrees, issue #472) declares the rig's rated face turn band (default `FACE_RATED_BAND`: `yaw <= 15°`, `pitch <= 12°`); declaring a `turn.band` or a `motion.animations_from` `turn`/`tilt` `derive.degrees` above `±15°` yaw or `±12°` pitch without an `assemble.alternates` entry that replaces `face` is refused (`CONFIG_FACE_BAND_EXCEEDED`), and on a single-plate rig `applyFaceSurfaceDeform` adds self-targeting transform constraints `yaw_clamp` (`[-15, 15]`) and `pitch_clamp` (`[-12, 12]`) ahead of the slider constraints so driving `yaw` or `pitch` beyond the rated band clamps at the boundary. At rest: with `turn` declared, no pixel differs by more than 1 level at dial 0 (not byte-identical; the cause is float noise in the identity child bones, and the constraints add nothing); without `turn`, byte-identical. Neither `pivot` nor `depths` has a default (`CONFIG_FIELD_PRESENT`); `pivot` and `head.pivot` must lie behind the nearest part (`CONFIG_TURN_PIVOT_BEHIND_NEAREST`). Absent, no control is added and no byte of any output moves |
184
- | `scene` | assemble (the recomposite, its holes and the figure's mask); check, through `parts.json`'s `scene` block (`RECOMPOSITE_HOLES`, the seam) | **authored**, optional; `propose` writes none (issue #242). `{}` declares the painting a scene: the figure and its surroundings in one image, See-through's full run holding only the figure. With it, `assemble` reads the recomposite figures, the hole list and the `uncovered:` lines inside the figure — the rig pixels where any full-run layer's alpha is above 8 (`OPAQUE_ALPHA_ABOVE`, the cut every layer's painted pixels are read by) — each line starting `inside the figure (config.scene: …, <n> of <m> rig px)`; writes that figure as `figure_rig.png` (white on black) beside the recomposite (and the same bytes beside `parts.json` when standalone `assemble` writes it to another directory, issue #1177), and a `scene` block in `parts.json`; flags error pixels on the error map inside it only (outside, the painting grey); and `check` leaves out of the seam every frame pixel whose composite sample reaches the painting's outermost row or column, saying how many (`seam_border` in `check.json`, and on the seam line). It takes no field: the figure and its threshold are derived. A key in it other than a record or an annotation is `CONFIG_KEY_KNOWN`. Absent, no byte of any output moves |
184
+ | `scene` | assemble (the recomposite, its holes and the figure's mask); check, through `parts.json`'s `scene` block (`RECOMPOSITE_HOLES`, the seam) | **authored**, optional; `propose` writes none (issue #242). `{}` declares the painting a scene: the figure and its surroundings in one image, See-through's full run holding only the figure. With it, `assemble` reads the recomposite figures, the hole list and the `uncovered:` lines inside the figure — the rig pixels where any full-run layer's alpha is above 8 (`OPAQUE_ALPHA_ABOVE`, the cut every layer's painted pixels are read by) — each line starting `inside the figure (config.scene: …, <n> of <m> rig px)`; writes that figure as `figure_rig.png` (white on black) beside the recomposite (and the same bytes beside `parts.json` when standalone `assemble` writes it to another directory, issue #1177), and a `scene` block in `parts.json`; flags error pixels on the error map inside it only (outside, the painting grey); and `check` leaves out of the seam every frame pixel whose composite sample reaches the painting's outermost row or column, saying how many (`seam_border` in `check.json`, and on the seam line). When `assemble` writes `figure_rig.png`, it also prints `figure mask (figure_rig.png):` and one `figure rim full:<tag>` row per full-run layer with a nonzero count, naming the union `alpha >= 250` core, the outer `alpha 9..127` soft rim in the 4-connected exterior of that core and its pixels more than 40 (`ERROR_LIMIT`) off the painting in the rig, and the mask pixels outside every emitted part at `alpha > 8`: when a soft rim over a contrasting ground or an outside-all-parts island is present, declare `setup_painting.figure_mask` for an independent figure domain, or retouch against the painting only inside the `alpha >= 250` core (issue #1297). It takes no field: the figure and its threshold are derived. A key in it other than a record or an annotation is `CONFIG_KEY_KNOWN`. Absent, no byte of any output moves |
185
185
  | `cloth` | `propose --cloth` only; no other stage reads it, so it moves no byte of any build | **authored**, optional (issue #364): one recipe per tag, `{"bottomwear": {…}, "back hair": {…}, "front hair": {…}}`, each `{chains, links, wind, gravity, split?, length_ratio?, strength?, damping?, alternate_damping?, translate?, swing?, part?, influence?}`. `influence` (issue #518) — `{across, max, shape, radius?}`: the parts this recipe meshes are drafted in the influence mode (`meshes.<part>.influence` above) at their lattice's cell, with `across`, `max` and `shape` as declared (each required — the reading behind the radius did not vary them) and `radius` as declared or, absent, drafted as the farthest vertex's distance plus 3 cells (the `influence.radius` row); without it the parts keep their lattice. `chains` — trees across the piece (for `back hair`, per side of the eye axis), a whole number, 1 or more; `links` — links from root to tip on every path, 1 or more; `split` — `{at, into}`: the first `at` links are the trunk, which forks into `into` (2 or more) branches; `at` below `links` (`CONFIG_CLOTH_SPLIT_BEFORE_TIP`); `length_ratio` — a path's last link over its first, above 0, default 0.5; `strength` — `{trunk, branch, edge}`, each above 0 and below the spring's stability bound (`CONFIG_CLOTH_SPRING_STABLE`), default 100 / 100 / 50; `damping` — in [0, 1], absent: rig-c's default; `alternate_damping` — the odd trees' damping, in [0, 1], beside `damping` and different from it (`CONFIG_CLOTH_ALTERNATE_DIFFERS`); `wind`, `gravity` — `[root, tip]`, each 0 or more, tip at or above root (`CONFIG_CLOTH_RESPONSE_GROWS_TO_TIP`); `translate` — the x and y mix of a dangling end's flutter, above 0 and at most 1; `swing` — `bottomwear` only, `{scales}`, one positive scale per tree (`CONFIG_CLOTH_SWING_SCALE_PER_TREE`); `part` — `bottomwear` only (`CONFIG_CLOTH_PART_ON_BOTTOMWEAR`), a non-empty part or cut-piece name: the `topwear` part that holds a skirt See-through returned inside it (a dress), or its skirt piece cut by `assemble.cuts`, which takes the skirt's trees (issue #402, *A skirt inside topwear* below; the part is checked by `propose`, `PROPOSE_CLOTH_PART`). The two defaults are the recipe's own, measured on its synthetic fixture (the recipe below). The recipe below says what each field drafts. The config written: `propose --cloth <config.json> --write-config <out.json>` (issue #537) writes this config's own text back with the sections the recipe drafts spliced in — `meshes.<part>` and `regions.<part>`, and `bones`, `constraints` and `motion.tracks` entry by entry by name (issue #552) — and every other byte as read; `--from <previous config>` (issue #571) takes an entry equal to the previous recipe's draft as the recipe's (*The config written*, under the recipe below) |
186
186
  | `proposed_rig_scale` | assemble, rig, build, `propose --from-config`/`--compare` | **proposed** by `propose` (issue #354): `parts.json`'s `scale_rig_per_source`, the `assemble.rig_scale` the rig sections (`bones`, `meshes`, `limbs`, `motion`) were drafted at. Held equal to `assemble.rig_scale` when present (`CONFIG_PROPOSED_RIG_SCALE`; 0, negative or not a number: `CONFIG_FIELD_TYPE`). Absent on a hand-authored config, where no byte of any output moves |
187
187
  | `motion_seams` | propose, assemble, check | Optional `[{part, neighbour}]`, using output part names. Each unordered pair is declared once; self-pairs, unknown names, wrong shapes and unknown fields refuse (`CONFIG_MOTION_SEAM`, `PARTS_MOTION_SEAM`, `CHECK_MOTION_SEAM_DECLARATION`). Empty adds no pair. Assemble copies the declaration into `parts.json`; check merges it with existing pairs and never regenerates a removed declaration. It uses the existing non-root WARN floor and changes no bar or exit status. See *Explicit motion seam observations* below. |
@@ -189,10 +189,24 @@ read by no CPU stage).
189
189
 
190
190
  ### Drafting the chest carrier
191
191
 
192
+ `propose` drafts the chest carrier's largest art island as a contour.
193
+
192
194
  The drafted contour torso also uses mesh-draft's existing dust rule. Extra islands
193
195
  of at most 4 pixels and at most 0.1% of the part's art set `contour.stray` to the
194
196
  largest dust island. The proposal note names the islands and pixels left out.
195
- A real extra piece is refused by `PROPOSE_TORSO_ISLANDS` and must be separated.
197
+
198
+ A non-dust extra island is accepted for omission only when its art-pixel count
199
+ is strictly below the drafted `contour.spacing` squared (`spacing²`). Each such
200
+ island produces a `PROPOSE_TORSO_ISLAND_LEFT_OUT` warning with its art-pixel count
201
+ and bounding box in rig pixels. When islands are omitted, `contour.stray` is set
202
+ to the largest omitted island's art-pixel count, including dust. The `spacing²`
203
+ threshold is a derived sampling-cell area policy; an area below it does not prove
204
+ that no vertex can lie inside the small island.
205
+
206
+ Equal-largest island ties and any non-dust extra island with an art-pixel count
207
+ greater than or equal to `spacing²` are refused by `PROPOSE_TORSO_ISLANDS`.
208
+ The refusal detail includes the threshold; separate the extra pieces before
209
+ drafting. A chest carrier with no art is also refused by that code.
196
210
 
197
211
  `propose --bust-landmarks <landmarks.json>` reads an object with `apex_r` and `apex_l`,
198
212
  and optional `cleavage`, each a finite `[x, y]` in rig pixels (crop origin at top left,
@@ -3560,7 +3574,8 @@ world units. Other proposal modes (`--keypoints`, `--compare`, `--grid-rule`,
3560
3574
 
3561
3575
  | rule | means | change |
3562
3576
  | --- | --- | --- |
3563
- | <a id="PROPOSE_TORSO_ISLANDS"></a>`PROPOSE_TORSO_ISLANDS` | the chest carrier has no art, tied largest islands, or an extra island exceeding the existing mesh-draft dust limits | separate real pieces so the torso has one largest art island and only dust beside it |
3577
+ | <a id="PROPOSE_TORSO_ISLAND_LEFT_OUT"></a>`PROPOSE_TORSO_ISLAND_LEFT_OUT` | WARN: a non-dust island smaller than one drafted sampling cell is omitted; names its art px and rig-pixel box | inspect the omitted art; separate it if it needs its own mesh; `contour.stray` records the largest omitted island |
3578
+ | <a id="PROPOSE_TORSO_ISLANDS"></a>`PROPOSE_TORSO_ISLANDS` | the chest carrier has no art, equal-largest island ties, or a non-dust extra island with an art-pixel count greater than or equal to the drafted `contour.spacing` squared; the detail includes the threshold | supply art with one uniquely largest island; separate non-dust extra pieces at or above the threshold; dust keeps its existing rule, and smaller non-dust islands are omitted with `PROPOSE_TORSO_ISLAND_LEFT_OUT` |
3564
3579
  | <a id="PROPOSE_BUST_INPUT"></a>`PROPOSE_BUST_INPUT` | a chest torso has neither a bust declaration nor an omission reason, a bust landmark is missing, malformed or unknown, the omission reason is blank or conflicts with landmarks, the midline has no unique crossing inside the apex segment, or the chest carrier is absent or ambiguous, or its recipe declares an incompatible influence mode | give finite rig-pixel apex_r/apex_l and optional cleavage, or a non-blank omission reason; separate overlapping chest-holding topwear |
3565
3580
  | <a id="PROPOSE_NECK_BODY_TURN"></a>`PROPOSE_NECK_BODY_TURN` | no authored sampled body turn | follow this recipe and supply the named input; the refusal writes no config |
3566
3581
  | <a id="PROPOSE_NECK_PLAN"></a>`PROPOSE_NECK_PLAN` | no unique neck plan row | follow this recipe and supply the named input; the refusal writes no config |
@@ -5727,7 +5742,7 @@ recorded transform. The record fields and sampling formula are specified in
5727
5742
  | <a id="PARTS_PAINTING_REFERENCE_WRITE"></a>`PARTS_PAINTING_REFERENCE_WRITE` | Reference publication failed | Preserve existing files and retry with the same sealed inputs |
5728
5743
  | <a id="DIFF_COMPONENTS_INPUT"></a>`DIFF_COMPONENTS_INPUT` | `diff-components` needs readable PNG stack/painting/part images, a writable `--out` target when writing, explicit parts, positive integer floor, a finite threshold in [0,255], matching native dimensions and valid coverage/domain inputs; flags must be unique and known, with nonempty values | Supply the named missing or invalid input; no resampling or inferred figure is performed |
5729
5744
  | <a id="DIFF_COMPONENTS_BINDING"></a>`DIFF_COMPONENTS_BINDING` | The shipped report reader found a stack or painting SHA-256 different from the supplied bytes; found and required digests are printed | Regenerate against the bytes being reviewed |
5730
- | <a id="DIFF_COMPONENTS_REPORT"></a>`DIFF_COMPONENTS_REPORT` | Invalid report JSON/spec, or its exhaustive inventory, definition, paths, domain or coverage differs from remeasurement; capped inventories are refused | Regenerate the complete versioned report against the same input paths, bytes, parts and figure domain |
5745
+ | <a id="DIFF_COMPONENTS_REPORT"></a>`DIFF_COMPONENTS_REPORT` | Invalid report JSON/spec (`rig-parts-diff-components/1` or `rig-parts-diff-components/2` is required, or the spec requested by a narrow reader), or its exhaustive inventory, definition, paths, domain, coverage or topmost `owners` (on `/2`) differs from remeasurement; capped inventories are refused | Regenerate the complete versioned report against the same input paths, bytes, parts and figure domain |
5731
5746
  | <a id="ASSEMBLE_PINHOLES"></a>`ASSEMBLE_PINHOLES` | the requirements file declares `pinholes.required: true` and the flat parts stack holds a pinhole: an 8-connected opening (alpha 0 on every part, enclosed by the parts' alpha above 0) whose every pixel the painting shows as figure. One refusal per pinhole, largest first, naming its box, its px and the parts bordering it; nothing is written (issue #944, [Pinholes at rest](#pinholes-at-rest-issue-944)) | `assemble.plan` / `assemble.take` / the head pass: take the pinhole's pixels from a layer that holds them ([Source before scissors](#source-before-scissors)); where no layer holds them, the defect is the input's. Without the declaration the bar reports SKIP |
5732
5747
  | <a id="ASSEMBLE_PATCH_BOX_INSIDE"></a>`ASSEMBLE_PATCH_BOX_INSIDE` | a patch's box reaches past the rig (the painting times `rig_scale`; the detail gives the size) | that patch's `box` — it is in rig pixels, not painting pixels |
5733
5748
  | <a id="ASSEMBLE_PATCH_OPAQUE"></a>`ASSEMBLE_PATCH_OPAQUE` | a patch takes no pixel: a `"silhouette"` patch whose box holds none of the figure | move the box onto the figure, or `"alpha": "box"` |
@@ -8519,7 +8534,7 @@ references remain active declarations. See [the input contract and refusals](AUT
8519
8534
  ### Whole-figure difference inventory
8520
8535
 
8521
8536
  `rig-parts diff-components --stack stack.png --painting painting.png --parts parts.json --floor 2 --out diff-components.json`
8522
- writes `rig-parts-diff-components/1`. Supply the assembled stack and the painting
8537
+ writes `rig-parts-diff-components/1` by default. Pass `--owners` during retouch rounds that need the topmost owning part for each differing component (replacing hand-written scripts that recomputed per-pixel draw-order ownership): with `--owners`, the command writes `rig-parts-diff-components/2` and adds `owners` to every component. Without `--owners`, output bytes stay `rig-parts-diff-components/1` with no `owners` field. Supply the assembled stack and the painting
8523
8538
  **already in the same native canvas** (for a scaled assembly, use its rig-sized
8524
8539
  painting). Parts are read in manifest order from the `parts/` sibling directory.
8525
8540
  No registration or resampling occurs. For scene assemblies pass
@@ -8539,8 +8554,12 @@ SHA-256 of the binary figure domain (`null` for the whole canvas).
8539
8554
  PNG buffer decoded for measurement. `components` is uncapped and ordered by
8540
8555
  first pixel in row-major scan order. Each entry records `id` (`p<first pixel
8541
8556
  index>-n<pixel count>`), `px`, `box: {x,y,w,h}`, `coverage`, `uncovered_px` and
8542
- `borders`. Coverage is `covered`, `uncovered` or `mixed`: a whole-error component
8543
- can cross a part's edge, so a boolean would lose pixels. Borders use the existing
8557
+ `borders` (plus `owners` before `borders` in `rig-parts-diff-components/2` under `--owners`). Coverage is `covered`, `uncovered` or `mixed`: a whole-error component
8558
+ can cross a part's edge, so a boolean would lose pixels. Under `--owners`, `owners` lists each topmost part
8559
+ (in `parts.json` draw order, back to front) with alpha above the coverage cut (`COVERED_ALPHA`, >128)
8560
+ drawing the component's covered pixels, as `{part, px}`; an uncovered pixel names no owner, so an
8561
+ uncovered component has `owners: []` and the sum of `owners[].px` plus `uncovered_px` equals `px`.
8562
+ Borders use the existing
8544
8563
  hole convention: part pixels above the coverage cut touching a component in
8545
8564
  their 3x3 neighbourhood, counted once per part pixel, sorted by count then
8546
8565
  manifest order. A covered component may therefore name its own covering part.
@@ -8551,7 +8570,7 @@ Listed `px` plus `below_floor.px` equals `error_px`; listed `uncovered_px` plus
8551
8570
  `parts.json.recomposite` block, including `holes_listed: 5`, is unchanged.
8552
8571
 
8553
8572
  Replace `--out` with `--verify diff-components.json` to use the shipped reader.
8554
- Use the same paths and floor/threshold flags. It collects both source-binding mismatches before refusing. With matching bindings,
8573
+ Use the same paths and floor/threshold flags. `--verify` accepts both `rig-parts-diff-components/1` and `rig-parts-diff-components/2` reports (pass `--owners` with `--verify` or `readDiffComponents(text, input, [DIFF_COMPONENTS_SPEC])` when a caller requires a single spec version; a `/1`-only reader refuses a `/2` report by name with `DIFF_COMPONENTS_REPORT`). It collects both source-binding mismatches before refusing. With matching bindings,
8555
8574
  it recomputes every field against the supplied parts and domain, refusing
8556
8575
  missing, capped or altered components, stale coverage and definition drift. Every
8557
8576
  changed, missing or extra inventory field names its path, the value found and the
package/docs/STABILITY.md CHANGED
@@ -245,7 +245,7 @@ defaults are the help's too, and none is guessed from the art.
245
245
  <!-- stable:commands -->
246
246
  | command | flags |
247
247
  | --- | --- |
248
- | `diff-components` | `--stack`, `--painting`, `--parts`, `--floor`; optional `--threshold`, `--figure`; exactly one of `--out`, `--verify` (issue #1005; exhaustive native error inventory, with byte-bound reader) |
248
+ | `diff-components` | `--stack`, `--painting`, `--parts`, `--floor`; optional `--threshold`, `--figure`, `--owners`; exactly one of `--out`, `--verify` (issues #1005, #1291; exhaustive native error inventory, `rig-parts-diff-components/1` by default and `rig-parts-diff-components/2` with `--owners`, and byte-bound reader for both) |
249
249
  | `depth-prepare` | `--parts`, `--config`, `--out` (issue #897; separate numeric-depth recipe) |
250
250
  | `depth-bind` | `--map`, `--input`, `--part` (issue #1284; exclusive receipt creation from current file bytes) |
251
251
  | `depth-apply` | `--parts`, `--manifest`, `--config`, `--rig-config`, `--out` (issue #897; original character config is read-only) |
@@ -701,6 +701,7 @@ execution in historical evidence is inferred from a current export.
701
701
  | the scene report | `compose` | spec `spine-parts-scene-report/1`; the plate block carries `sha256` of the plate PNG's bytes after `size` (issue #1183, additive under *What "stable" means here*: a new report key in a minor version, so the spec stays `/1`) |
702
702
  | `idle.png`, `idle-indexed.png`, `idle.gif` | `loop`, `build --loop` | APNG and GIF encodings of the rendered idle |
703
703
  | `run.json` | `rig`, `assemble` | spec `rig-run/1` (issue #1165, additive): `spec`, `package` (`name`, `version`), `command` (`"rig"` or `"assemble"`), `started_at` and `finished_at` (UTC ISO-8601 millisecond timestamps ending in `Z`, read in the CLI layer), `config` (`path` relative to `--out`, `sha256` of the config file on disk), and `outputs` (`path` relative to `--out`, `sha256` of each written output file on disk, sorted by `path` in code-unit order and excluding `run.json` itself); written only after the command's gate is green |
704
+ | the difference inventory (`--out`) | `diff-components` | spec `rig-parts-diff-components/1` by default (issue #1005: `stack`, `painting`, `definition`, `error_px`, `uncovered_error_px`, `components` — each `id`, `px`, `box`, `coverage`, `uncovered_px`, `borders` — and `below_floor`, byte-identical to 2.38.1), and spec `rig-parts-diff-components/2` under `--owners` (issue #1291: adds `owners` — each `{part, px}`, the topmost `parts.json` part above `COVERED_ALPHA` per covered pixel, back to front — before `borders` on every component); `--verify` verifies both `/1` and `/2` reports (with `--owners`, `/2` is required), while a `/1`-only reader (`readDiffComponents(text, input, [DIFF_COMPONENTS_SPEC])`) refuses `/2` by name |
704
705
 
705
706
  Issue #705 pins setup-seam acceptance to one source-relative scale1 union U of the authored stage and all actual drawn base/checked-set still vertices. U is snapped relative to the source origin, including odd-width half phase.
706
707
  The existing seam fields and pair pictures use that grid; source/blink and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rig-c/parts",
3
- "version": "2.39.0",
3
+ "version": "2.40.0",
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
@@ -3640,6 +3640,163 @@ export function holeKindsLine(k: HoleKinds, scene: string | null = null): string
3640
3640
  );
3641
3641
  }
3642
3642
 
3643
+ /** One full-run layer's outer soft rim in `figure_rig.png` (issue #1297). */
3644
+ export interface FigureRimLayer {
3645
+ /** The full-run layer tag. */
3646
+ tag: string;
3647
+ /** The plan part that takes `full:<tag>` directly, or null when no plan row does. */
3648
+ part: string | null;
3649
+ /** Layer pixels at alpha `OPAQUE_ALPHA_ABOVE + 1 .. COVERED_ALPHA - 1` (9..127) in the 4-connected exterior of the union `alpha >= CORE_ALPHA` core. */
3650
+ rimPx: number;
3651
+ /** Those rim pixels whose max absolute RGB channel difference from the painting in the rig is above `ERROR_LIMIT`. */
3652
+ farPx: number;
3653
+ /** Total pixels of this full-run layer on the rig grid with alpha above `OPAQUE_ALPHA_ABOVE`. */
3654
+ maskPx: number;
3655
+ }
3656
+
3657
+ /**
3658
+ * What `figure_rig.png` holds beyond the union `alpha >= CORE_ALPHA` core and
3659
+ * beyond the emitted parts' support (issue #1297).
3660
+ */
3661
+ export interface FigureMaskReading {
3662
+ /** Total pixels in `figure_rig.png` (`inside[p] === 1`, union of full-run layers at alpha above `OPAQUE_ALPHA_ABOVE`). */
3663
+ figurePx: number;
3664
+ /** Total pixels in the union of full-run layers at alpha >= `CORE_ALPHA` (250). */
3665
+ corePx: number;
3666
+ /** Union of full-run layer rim pixels (alpha 9..127 in the 4-connected exterior of the union alpha >= 250 core). */
3667
+ rimPx: number;
3668
+ /** Union of full-run layer far-rim pixels (rim pixels with max-channel RGB difference from the painting in the rig > `ERROR_LIMIT`). */
3669
+ farPx: number;
3670
+ /** Full-run layers with `rimPx > 0`, largest `rimPx` first (then `farPx`, then `tag`). */
3671
+ layers: FigureRimLayer[];
3672
+ /** Figure-mask pixels that no emitted part carries at alpha above `OPAQUE_ALPHA_ABOVE` (8), 8-connected. */
3673
+ outsideParts: HoleKindSummary;
3674
+ /** Pixels in both the union rim and `outsideParts`. */
3675
+ alsoInRimPx: number;
3676
+ /** Pixels in the union rim or `outsideParts` (overlap counted once). */
3677
+ rimOrOutsidePx: number;
3678
+ }
3679
+
3680
+ /**
3681
+ * Measure the figure mask's outer soft rim (`alpha 9..127` in the 4-connected
3682
+ * exterior of the union `alpha >= CORE_ALPHA` core), its far-rim subset (`max`
3683
+ * RGB channel difference from `srcr` > `ERROR_LIMIT`), and the mask pixels
3684
+ * outside every emitted part at `alpha > OPAQUE_ALPHA_ABOVE` (issue #1297).
3685
+ */
3686
+ export function measureFigureMask(
3687
+ inside: Uint8Array,
3688
+ fullRig: ReadonlyArray<{ tag: string; rig: Raster }>,
3689
+ srcr: Raster,
3690
+ parts: readonly PlacedPart[],
3691
+ plan: readonly PlanEntry[],
3692
+ ): FigureMaskReading {
3693
+ const { width: W, height: H } = srcr;
3694
+ const n = W * H;
3695
+ let figurePx = 0;
3696
+ for (let p = 0; p < n; p++) figurePx += inside[p];
3697
+ const core = newMask(W, H);
3698
+ for (const { rig } of fullRig) {
3699
+ for (let p = 0; p < n; p++) {
3700
+ if (rig.data[p * 4 + 3] >= CORE_ALPHA) core.data[p] = 1;
3701
+ }
3702
+ }
3703
+ let corePx = 0;
3704
+ for (let p = 0; p < n; p++) corePx += core.data[p];
3705
+ const filledCore = fillHoles(core);
3706
+ const unionRim = new Uint8Array(n);
3707
+ const unionFar = new Uint8Array(n);
3708
+ const layers: FigureRimLayer[] = [];
3709
+ for (const { tag, rig } of fullRig) {
3710
+ let rimPx = 0;
3711
+ let farPx = 0;
3712
+ let maskPx = 0;
3713
+ for (let p = 0; p < n; p++) {
3714
+ const a = rig.data[p * 4 + 3];
3715
+ if (a > OPAQUE_ALPHA_ABOVE) maskPx++;
3716
+ if (filledCore.data[p] === 0 && a > OPAQUE_ALPHA_ABOVE && a < COVERED_ALPHA) {
3717
+ rimPx++;
3718
+ unionRim[p] = 1;
3719
+ if (maxDiff(rig.data, p * 4, srcr.data, p * 4) > ERROR_LIMIT) {
3720
+ farPx++;
3721
+ unionFar[p] = 1;
3722
+ }
3723
+ }
3724
+ }
3725
+ if (rimPx > 0) {
3726
+ const part = plan.find(([, run, t]) => run === 'full' && t === tag)?.[0] ?? null;
3727
+ layers.push({ tag, part, rimPx, farPx, maskPx });
3728
+ }
3729
+ }
3730
+ layers.sort((a, b) => b.rimPx - a.rimPx || b.farPx - a.farPx || (a.tag < b.tag ? -1 : a.tag > b.tag ? 1 : 0));
3731
+ let rimPx = 0;
3732
+ let farPx = 0;
3733
+ for (let p = 0; p < n; p++) {
3734
+ rimPx += unionRim[p];
3735
+ farPx += unionFar[p];
3736
+ }
3737
+ const partSupport = new Uint8Array(n);
3738
+ for (const { image, record } of parts) {
3739
+ for (let y = 0; y < record.h; y++) {
3740
+ const ry = record.y + y;
3741
+ if (ry < 0 || ry >= H) continue;
3742
+ for (let x = 0; x < record.w; x++) {
3743
+ const rx = record.x + x;
3744
+ if (rx < 0 || rx >= W) continue;
3745
+ if (image.data[(y * record.w + x) * 4 + 3] > OPAQUE_ALPHA_ABOVE) partSupport[ry * W + rx] = 1;
3746
+ }
3747
+ }
3748
+ }
3749
+ const outsideMask = newMask(W, H);
3750
+ let alsoInRimPx = 0;
3751
+ let rimOrOutsidePx = 0;
3752
+ for (let p = 0; p < n; p++) {
3753
+ const out = inside[p] === 1 && partSupport[p] === 0;
3754
+ if (out) {
3755
+ outsideMask.data[p] = 1;
3756
+ if (unionRim[p] === 1) alsoInRimPx++;
3757
+ }
3758
+ if (unionRim[p] === 1 || out) rimOrOutsidePx++;
3759
+ }
3760
+ return {
3761
+ figurePx,
3762
+ corePx,
3763
+ rimPx,
3764
+ farPx,
3765
+ layers,
3766
+ outsideParts: summarizeKindMask(outsideMask),
3767
+ alsoInRimPx,
3768
+ rimOrOutsidePx,
3769
+ };
3770
+ }
3771
+
3772
+ /**
3773
+ * The measurement line and per-layer rows when `assemble` writes
3774
+ * `figure_rig.png` (issue #1297): the union `alpha >= CORE_ALPHA` core, the
3775
+ * outer `alpha 9..127` soft rim and its pixels more than `ERROR_LIMIT` off the
3776
+ * painting in the rig, the mask pixels outside every emitted part at
3777
+ * `alpha > OPAQUE_ALPHA_ABOVE`, and one row per full-run layer with a nonzero
3778
+ * rim count.
3779
+ */
3780
+ export function figureMaskLines(m: FigureMaskReading, scene: string | null = null): string[] {
3781
+ const outside =
3782
+ m.outsideParts.px === 0 || m.outsideParts.largest === null
3783
+ ? '0 px'
3784
+ : `${m.outsideParts.px} px in ${m.outsideParts.count} component(s) (8-connected, largest ${m.outsideParts.largest.px} px at ${m.outsideParts.largest.x},${m.outsideParts.largest.y} ${m.outsideParts.largest.w}x${m.outsideParts.largest.h})`;
3785
+ const head =
3786
+ `${scene === null ? '' : `${scene}: `}figure mask (${FIGURE_MASK_FILE}): ` +
3787
+ `core (alpha >= ${CORE_ALPHA}) ${m.corePx} px; ` +
3788
+ `soft rim (alpha ${OPAQUE_ALPHA_ABOVE + 1}..${COVERED_ALPHA - 1} in the 4-connected exterior of the union alpha >= ${CORE_ALPHA} core): union ${m.rimPx} px, far (max channel > ${ERROR_LIMIT} from the painting in the rig) ${m.farPx} px; ` +
3789
+ `outside all parts (no part at alpha > ${OPAQUE_ALPHA_ABOVE}): ${outside} (${m.alsoInRimPx} px also in rim, rim or outside ${m.rimOrOutsidePx} px); ` +
3790
+ `measurement, no declared limit`;
3791
+ return [
3792
+ head,
3793
+ ...m.layers.map(
3794
+ (l) =>
3795
+ ` figure rim full:${l.tag} (${l.part === null ? 'no full-run plan part' : `part "${l.part}"`}): rim ${l.rimPx} px, far ${l.farPx} px (of ${l.maskPx} layer mask px)`,
3796
+ ),
3797
+ ];
3798
+ }
3799
+
3643
3800
  /** The `parts.json` `recomposite` block: the four figures, the limits they were measured at, and the listed holes. */
3644
3801
  export function recompositeRecord(f: RecompositeFigures): RecompositeRecord {
3645
3802
  return {
@@ -4868,6 +5025,8 @@ export interface AssembleResult {
4868
5025
  errorMap: Raster;
4869
5026
  /** Under `config.scene` (issue #242), the figure the recomposite was read inside ({@link figureImage}); null otherwise. */
4870
5027
  figure: Raster | null;
5028
+ /** Under `config.scene` (issue #1297), the figure mask's soft rim and outside-all-parts counts; absent otherwise. */
5029
+ figureMask?: FigureMaskReading;
4871
5030
  figures: RecompositeFigures;
4872
5031
  /** What each `assemble.cuts` entry took, counted when it was made (`cutLines`); empty without cuts. */
4873
5032
  cuts: CutCount[];
@@ -6569,8 +6728,10 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6569
6728
  for (const group of [built, pieces, cutSources, limbPieces]) for (const b of group) if (b !== null) b.writers = undefined;
6570
6729
  const can = recomposite(placed, W, H);
6571
6730
  // Issue #242: on a scene painting the figure is read off the full run, and every recomposite figure inside it.
6572
- const inside = input.scene === true ? sceneFigure([...rig.entries()].filter(([k]) => k.startsWith('full:')).map(([, r]) => r), W, H) : null;
6731
+ const fullRigAll = [...rig.entries()].filter(([k]) => k.startsWith('full:')).map(([k, r]) => ({ tag: k.slice('full:'.length), rig: r }));
6732
+ const inside = input.scene === true ? sceneFigure(fullRigAll.map((l) => l.rig), W, H) : null;
6573
6733
  const sceneRecord: SceneRecord | null = inside === null ? null : { figure_alpha_above: OPAQUE_ALPHA_ABOVE, figure_px: inside.reduce((a, b) => a + b, 0), figure_mask: FIGURE_MASK_FILE };
6734
+ const figureMask = inside === null ? undefined : measureFigureMask(inside, fullRigAll, srcr, placed, plan);
6574
6735
  const figures = measureRecomposite(can, srcr, placed, inside);
6575
6736
  const covered = coveredMask(placed, W, H);
6576
6737
  const err = errorMask(can, srcr, inside);
@@ -6627,6 +6788,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6627
6788
  recomposite: can,
6628
6789
  errorMap: recompositeErrorMap(can, srcr, placed, inside),
6629
6790
  figure: inside === null ? null : figureImage(inside, W, H),
6791
+ ...(figureMask === undefined ? {} : { figureMask }),
6630
6792
  figures,
6631
6793
  cuts: cutCounts,
6632
6794
  cutMaterial: [...cutMaterial, ...lim.material],
package/src/build.ts CHANGED
@@ -69,7 +69,7 @@ import { createHash } from 'node:crypto';
69
69
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
70
70
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
71
71
  import { type AnimFrame, EncodeError, encodeApng, encodeIndexedApng, INDEXED_DEFAULTS } from './apng.ts';
72
- import { assemble, type AssembleResult, boxOf, cutLines, edgeSplitLines, ERROR_LIMIT, type ExcludedCount, excludedLines, setExclusions, islandLines, setIslandSources, type IslandCount, hiddenLines, SINGLE_RUN_FACE_TAGS, singleRunHeadBox, softOcclusionLine, driftLine, limbLines, FIGURE_MASK_FILE, figuresLine, groundWarning, holeKindsLine, holeLines, measurePinholes, measureRecomposite, pinholeProblems, pinholesLine, type ProjectRule, recomposite, recompositeRecord, scenePhrase, type SeamRule, sourceInRig, stageFields, uncoveredLine, underBox } from './assemble.ts';
72
+ import { assemble, type AssembleResult, boxOf, cutLines, edgeSplitLines, ERROR_LIMIT, type ExcludedCount, excludedLines, setExclusions, islandLines, setIslandSources, type IslandCount, hiddenLines, SINGLE_RUN_FACE_TAGS, singleRunHeadBox, softOcclusionLine, driftLine, limbLines, FIGURE_MASK_FILE, figureMaskLines, figuresLine, groundWarning, holeKindsLine, holeLines, measurePinholes, measureRecomposite, pinholeProblems, pinholesLine, type ProjectRule, recomposite, recompositeRecord, scenePhrase, type SeamRule, sourceInRig, stageFields, uncoveredLine, underBox } from './assemble.ts';
73
73
  import { allocationClause, type Reducer, stageBClause, unboundedClause } from './automesh.ts';
74
74
  import { residualClause } from './autoenvelope.ts';
75
75
  import { type AutoMotionCase, failingRows, idleSchedule, localRow, motionClause, motionDeformation, motionDocument, motionInput, motionRowText, motionStimulus, motionVerdict, noStimulusProblem, prepareComparison, type ReplayCandidate, runComparison, runPreparedComparison, sourceSelfFailure, stimulusMotion, withStimulus } from './automotion.ts';
@@ -1210,6 +1210,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
1210
1210
  for (const l of holeLines(result.figures, scene)) log(l);
1211
1211
  if (result.figures.uncoveredErrorPx > 0) log(holeKindsLine(result.holeKinds, scene));
1212
1212
  for (const u of result.uncovered) log(uncoveredLine(u, scene));
1213
+ if (result.figureMask !== undefined) for (const l of figureMaskLines(result.figureMask, scene)) log(l);
1213
1214
  log(pinholesLine(pinholes, altBuilt.map((b) => b.record.name)));
1214
1215
  for (const d of result.drift) log(driftLine(d));
1215
1216
  for (const d of result.softOcclusion ?? []) log(softOcclusionLine(d));
@@ -10,6 +10,8 @@ import { decodePngBytes } from './raster/png.ts';
10
10
  import { newMask, type Raster } from './raster/types.ts';
11
11
 
12
12
  export const DIFF_COMPONENTS_SPEC = 'rig-parts-diff-components/1';
13
+ export const DIFF_COMPONENTS_OWNERS_SPEC = 'rig-parts-diff-components/2';
14
+ export type DiffComponentsSpec = typeof DIFF_COMPONENTS_SPEC | typeof DIFF_COMPONENTS_OWNERS_SPEC;
13
15
  export interface DiffBytes { path: string; bytes: Uint8Array }
14
16
  export interface DiffInputs {
15
17
  stack: DiffBytes;
@@ -24,10 +26,11 @@ export interface DiffComponent {
24
26
  box: { x: number; y: number; w: number; h: number };
25
27
  coverage: 'covered' | 'uncovered' | 'mixed';
26
28
  uncovered_px: number;
29
+ owners?: { part: string; px: number }[];
27
30
  borders: { part: string; px: number }[];
28
31
  }
29
32
  export interface DiffComponentsReport {
30
- spec: typeof DIFF_COMPONENTS_SPEC;
33
+ spec: DiffComponentsSpec;
31
34
  stack: { path: string; sha256: string };
32
35
  painting: { path: string; sha256: string };
33
36
  definition: {
@@ -63,7 +66,7 @@ function diffPng(bytes: Uint8Array, label: string): Raster {
63
66
  }
64
67
 
65
68
  /** Hash and decode each source from the same buffer. No alignment or resampling. */
66
- export function measureDiffComponents(input: DiffInputs, floor: number, threshold = ERROR_LIMIT): DiffComponentsReport {
69
+ export function measureDiffComponents(input: DiffInputs, floor: number, threshold = ERROR_LIMIT, withOwners = false): DiffComponentsReport {
67
70
  diffDefinition(floor, threshold);
68
71
  const stack = diffPng(input.stack.bytes, input.stack.path);
69
72
  const painting = diffPng(input.painting.bytes, input.painting.path);
@@ -74,9 +77,12 @@ export function measureDiffComponents(input: DiffInputs, floor: number, threshol
74
77
  if (input.inside.length !== W * H || bad >= 0) inputFailure('inside', `has ${input.inside.length} pixels, first nonbinary value ${bad < 0 ? 'none' : `${input.inside[bad]} at index ${bad}`}; ${W * H} binary 0/1 pixels in the painting's native frame are required`);
75
78
  }
76
79
  const names = new Set<string>();
77
- for (const { record: p, image } of input.parts) {
80
+ const topmost = new Int32Array(W * H).fill(-1);
81
+ for (let i = 0; i < input.parts.length; i++) {
82
+ const { record: p, image } = input.parts[i];
78
83
  if (!p.name || names.has(p.name) || ![p.x, p.y, p.w, p.h].every(Number.isSafeInteger) || p.x < 0 || p.y < 0 || p.w < 1 || p.h < 1 || p.x + p.w > W || p.y + p.h > H || image.width !== p.w || image.height !== p.h || image.data.length < p.w * p.h * 4) inputFailure(`part "${p.name}"`, `box ${p.x},${p.y} ${p.w}x${p.h}, image ${image.width}x${image.height} with ${image.data.length} RGBA bytes, duplicate name ${names.has(p.name)}; a unique nonempty name and an integer in-canvas matching box with four RGBA bytes per pixel are required on ${W}x${H}`);
79
84
  names.add(p.name);
85
+ for (let y = 0; y < p.h; y++) for (let x = 0; x < p.w; x++) if (image.data[(y * p.w + x) * 4 + 3] > COVERED_ALPHA) topmost[(p.y + y) * W + p.x + x] = i;
80
86
  }
81
87
  const covered = coveredMask(input.parts, W, H);
82
88
  const err = errorMask(stack, painting, input.inside, threshold);
@@ -96,12 +102,22 @@ export function measureDiffComponents(input: DiffInputs, floor: number, threshol
96
102
  for (const s of cc.stats.slice(1).filter(s => s.area > 0).sort((a,b) => first[a.label] - first[b.label])) {
97
103
  const u = uncovered[s.label];
98
104
  if (s.area < floor) { below.count++; below.px += s.area; below.uncovered_px += u; continue; }
105
+ let owners: { part: string; px: number }[] | undefined;
106
+ if (withOwners) {
107
+ const counts = new Int32Array(input.parts.length);
108
+ for (let y = s.top; y < s.top + s.height; y++) for (let x = s.left; x < s.left + s.width; x++) {
109
+ const p = y * W + x;
110
+ if (cc.labels[p] === s.label && topmost[p] >= 0) counts[topmost[p]]++;
111
+ }
112
+ owners = [];
113
+ for (let i = 0; i < input.parts.length; i++) if (counts[i] > 0) owners.push({ part: input.parts[i].record.name, px: counts[i] });
114
+ }
99
115
  components.push({ id: `p${first[s.label]}-n${s.area}`, px: s.area,
100
116
  box: { x: s.left, y: s.top, w: s.width, h: s.height },
101
117
  coverage: u === 0 ? 'covered' : u === s.area ? 'uncovered' : 'mixed', uncovered_px: u,
102
- borders: holeBorders(input.parts, cc, s, W, H, COVERED_ALPHA) });
118
+ ...(owners === undefined ? {} : { owners }), borders: holeBorders(input.parts, cc, s, W, H, COVERED_ALPHA) });
103
119
  }
104
- return { spec: DIFF_COMPONENTS_SPEC,
120
+ return { spec: withOwners ? DIFF_COMPONENTS_OWNERS_SPEC : DIFF_COMPONENTS_SPEC,
105
121
  stack: { path: input.stack.path, sha256: sha(input.stack.bytes) },
106
122
  painting: { path: input.painting.path, sha256: sha(input.painting.bytes) },
107
123
  definition: { metric: 'max-absolute-rgb-channel', threshold, comparison: '>', connectivity: 8, floor_px: floor,
@@ -110,8 +126,8 @@ export function measureDiffComponents(input: DiffInputs, floor: number, threshol
110
126
  error_px: errorPx, uncovered_error_px: uncoveredPx, components, below_floor: below };
111
127
  }
112
128
  export function serializeDiffComponents(report: DiffComponentsReport): string { return JSON.stringify(report, null, 2) + '\n'; }
113
- export function writeDiffComponents(path: string, input: DiffInputs, floor: number, threshold = ERROR_LIMIT): DiffComponentsReport {
114
- const report = measureDiffComponents(input, floor, threshold);
129
+ export function writeDiffComponents(path: string, input: DiffInputs, floor: number, threshold = ERROR_LIMIT, withOwners = false): DiffComponentsReport {
130
+ const report = measureDiffComponents(input, floor, threshold, withOwners);
115
131
  try { writeFileSync(path, serializeDiffComponents(report)); }
116
132
  catch (err) { inputFailure(path, `cannot write report: ${JSON.stringify(err instanceof Error ? err.message : err)}; a writable output file path is required`); }
117
133
  return report;
@@ -119,11 +135,11 @@ export function writeDiffComponents(path: string, input: DiffInputs, floor: numb
119
135
  const object = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
120
136
  const shown = (v: unknown): string => v === undefined ? 'missing' : Array.isArray(v) ? `array with ${v.length} entries` : typeof v === 'number' && !Number.isFinite(v) ? String(v) : JSON.stringify(v);
121
137
  /** Recompute the inventory against the supplied bytes and coverage/domain. A capped or edited report is refused. */
122
- export function readDiffComponents(text: string, input: DiffInputs): DiffComponentsReport {
138
+ export function readDiffComponents(text: string, input: DiffInputs, allowedSpecs: readonly DiffComponentsSpec[] = [DIFF_COMPONENTS_SPEC, DIFF_COMPONENTS_OWNERS_SPEC]): DiffComponentsReport {
123
139
  let raw: unknown;
124
140
  try { raw = JSON.parse(text); } catch (err) { return reportFailure(`cannot parse JSON: ${JSON.stringify(err instanceof Error ? err.message : err)}; valid JSON is required`); }
125
141
  if (!object(raw)) return reportFailure(`found ${shown(raw)}; a ${DIFF_COMPONENTS_SPEC} report object is required`);
126
- if (raw.spec !== DIFF_COMPONENTS_SPEC) return reportFailure(`spec is ${shown(raw.spec)}; ${DIFF_COMPONENTS_SPEC} is required`);
142
+ if (!allowedSpecs.includes(raw.spec as DiffComponentsSpec)) return reportFailure(`spec is ${shown(raw.spec)}; ${allowedSpecs.join(' or ')} is required`);
127
143
  if (!object(raw.stack) || !object(raw.painting) || !object(raw.definition)) return reportFailure(`stack=${shown(raw.stack)}, painting=${shown(raw.painting)}, definition=${shown(raw.definition)}; all three objects are required`);
128
144
  const bindings: Problem[] = [];
129
145
  for (const key of ['stack', 'painting'] as const) {
@@ -135,7 +151,7 @@ export function readDiffComponents(text: string, input: DiffInputs): DiffCompone
135
151
  if (bindings.length > 0) throw new PartsError(bindings);
136
152
  const floor = raw.definition.floor_px, threshold = raw.definition.threshold;
137
153
  if (typeof floor !== 'number' || typeof threshold !== 'number') return reportFailure(`definition floor_px=${shown(floor)}, threshold=${shown(threshold)}; both must be numbers`);
138
- const expected = measureDiffComponents(input, floor, threshold);
154
+ const expected = measureDiffComponents(input, floor, threshold, raw.spec === DIFF_COMPONENTS_OWNERS_SPEC);
139
155
  const differences: Problem[] = [];
140
156
  const fail = (path: string, found: unknown, required: unknown): void => {
141
157
  differences.push({ code: 'DIFF_COMPONENTS_REPORT', object: path,
@@ -164,9 +180,11 @@ export function readDiffComponents(text: string, input: DiffInputs): DiffCompone
164
180
  export function diffComponentsCommand(args: string[]): void {
165
181
  const allowed = ['--stack', '--painting', '--parts', '--figure', '--floor', '--threshold', '--out', '--verify'];
166
182
  const flags = new Map<string,string>();
183
+ let withOwners = false;
167
184
  for (let i = 0; i < args.length; i += 2) {
168
185
  const key = args[i], value = args[i + 1];
169
- if (!allowed.includes(key) || flags.has(key) || value === undefined || value.startsWith('--')) inputFailure('arguments', `requires unique ${allowed.join(', ')} flags with values; found ${key}`);
186
+ if (key === '--owners' && !withOwners) { withOwners = true; i--; continue; }
187
+ if (!allowed.includes(key) || flags.has(key) || value === undefined || value.startsWith('--')) inputFailure('arguments', `requires unique ${allowed.join(', ')} flags with values (and optional --owners); found ${key}`);
170
188
  if (value.length === 0) inputFailure(key, 'is ""; a nonempty value is required');
171
189
  flags.set(key, value);
172
190
  }
@@ -202,7 +220,7 @@ export function diffComponentsCommand(args: string[]): void {
202
220
  const input = { stack, painting, parts: placed, inside };
203
221
  if (flags.has('--verify')) {
204
222
  const path = flags.get('--verify')!;
205
- const report = readDiffComponents(new TextDecoder().decode(bytes(path).bytes), input);
223
+ const report = readDiffComponents(new TextDecoder().decode(bytes(path).bytes), input, withOwners ? [DIFF_COMPONENTS_OWNERS_SPEC] : [DIFF_COMPONENTS_SPEC, DIFF_COMPONENTS_OWNERS_SPEC]);
206
224
  if (report.definition.floor_px !== floor || report.definition.threshold !== threshold) inputFailure('definition', `report floor_px=${report.definition.floor_px}, threshold=${report.definition.threshold}; caller floor_px=${floor}, threshold=${threshold} are required`);
207
- } else writeDiffComponents(flags.get('--out')!, input, floor, threshold);
225
+ } else writeDiffComponents(flags.get('--out')!, input, floor, threshold, withOwners);
208
226
  }
package/src/propose.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { dustOf } from './mesh.ts';
1
+ import { ART_ALPHA, dustOf, isDust } from './mesh.ts';
2
2
  import { explicitWeightRows, regionBone, type RegionSpec } from './config.ts';
3
3
  /**
4
4
  * The propose stage: bone origins, mesh candidate lists, regions and a default
@@ -145,7 +145,7 @@ import { connectedComponents } from './raster/components.ts';
145
145
  import { dilate, morphGradient } from './raster/morph.ts';
146
146
  import { readPng } from './raster/png.ts';
147
147
  import { resize } from './raster/resize.ts';
148
- import { type Mask, newMask, newRaster, type Raster } from './raster/types.ts';
148
+ import { alphaAbove, type Mask, newMask, newRaster, type Raster } from './raster/types.ts';
149
149
  import { npMean, npMedian, npPercentile, pyFixed, pyInt, pyIntList, pyRepr, pyRound, pyStrList } from './pyfmt.ts';
150
150
  import type { JointState, RigJoint, RigJoints } from './keypoints.ts';
151
151
  import { IDLE_FPS } from './motion.ts';
@@ -3489,10 +3489,31 @@ export function proposeWithBasis(
3489
3489
  torsoImage = { ...torsoImage, data };
3490
3490
  }
3491
3491
  const dust = dustOf(torsoImage);
3492
+ let torsoStray: number | undefined;
3492
3493
  if ('keep' in dust) {
3493
- throw new PartsError([{ code: 'PROPOSE_TORSO_ISLANDS', object: `chest carrier "${torsoName}"`, detail: `${dust.keep}. Separate the real pieces before drafting a contour torso` }]);
3494
+ const cellArea = fig.grid * fig.grid;
3495
+ const components = connectedComponents(alphaAbove(torsoImage, ART_ALPHA), 4);
3496
+ const islands = components.stats.slice(1).sort((a, b) => b.area - a.area || a.label - b.label);
3497
+ const art = islands.reduce((sum, island) => sum + island.area, 0);
3498
+ const extra = islands.slice(1);
3499
+ // One drafted sampling cell supplies the area policy, not a geometric claim that a smaller island
3500
+ // cannot contain a sample point. Dust retains its independent, existing limits.
3501
+ if (islands.length === 0 || islands[0].area === islands[1]?.area ||
3502
+ extra.some(island => !isDust(island.area, art) && island.area >= cellArea)) {
3503
+ throw new PartsError([{ code: 'PROPOSE_TORSO_ISLANDS', object: `chest carrier "${torsoName}"`, detail: `${dust.keep}. Non-dust islands must hold fewer than spacing squared = ${fig.grid} * ${fig.grid} = ${cellArea} art px. Separate the real pieces before drafting a contour torso` }]);
3504
+ }
3505
+ torsoStray = extra[0]?.area;
3506
+ for (const island of extra) {
3507
+ if (isDust(island.area, art)) continue;
3508
+ const code = 'PROPOSE_TORSO_ISLAND_LEFT_OUT';
3509
+ notes.push(`WARN ${code}: chest carrier "${torsoName}" — ${island.area} art px at box [${source.x + island.left}, ${source.y + island.top}, ${island.width}, ${island.height}] rig px left out of the contour; below spacing squared ${fig.grid} * ${fig.grid} = ${cellArea} art px; contour.stray=${torsoStray}`);
3510
+ }
3511
+ const small = extra.filter(island => isDust(island.area, art));
3512
+ if (small.length > 0) notes.push(`${torsoName}: contour dust rule leaves out ${small.length} island(s), ${small.reduce((sum, island) => sum + island.area, 0)} px; contour.stray=${torsoStray}`);
3513
+ } else {
3514
+ torsoStray = dust.stray;
3515
+ if (dust.stray !== undefined) notes.push(`${torsoName}: contour dust rule leaves out ${dust.dust.length} island(s), ${dust.dust.reduce((sum, pixels) => sum + pixels, 0)} px; contour.stray=${dust.stray}`);
3494
3516
  }
3495
- if (dust.stray !== undefined) notes.push(`${torsoName}: contour dust rule leaves out ${dust.dust.length} island(s), ${dust.dust.reduce((sum, pixels) => sum + pixels, 0)} px; contour.stray=${dust.stray}`);
3496
3517
  const [, radius] = gridR(source);
3497
3518
  const segments: Segment[] = lattice !== undefined && 'grid' in lattice ? lattice.segments : [['chest', rnd(neckAt), rnd(hip)]];
3498
3519
  // Same figure formulas as mesh-draft's figureRules (issue #265). Importing meshdraft here would cycle through propose.
@@ -3502,7 +3523,7 @@ export function proposeWithBasis(
3502
3523
  margin: tolerance,
3503
3524
  spacing: fig.grid,
3504
3525
  maxEdge: fig.grid,
3505
- ...(dust.stray === undefined ? {} : { stray: dust.stray }),
3526
+ ...(torsoStray === undefined ? {} : { stray: torsoStray }),
3506
3527
  };
3507
3528
  if (bust.noBust !== undefined) {
3508
3529
  notes.push(`${torsoName}: contour bust omitted for the declared reason: ${bust.noBust}`);