rig-parts 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,7 +29,7 @@ pose that holds the hands apart, then given one hand-detailer pass; its generati
29
29
  record, See-through layers and licence are in
30
30
  <a href="https://github.com/rig-c/parts-examples">parts-examples</a>.
31
31
  See-through ran twice, once on the whole figure and once on a square head crop.
32
- Then one command: <code>rig-parts build --loop</code>. The proposer's bones, meshes,
32
+ Then one command: <code>rig-parts build --loop --lead-in 3</code>. The proposer's bones, meshes,
33
33
  regions and motion were used as proposed but for one correction, written in the
34
34
  config beside the values it replaced: the two outer skirt chains were moved out to
35
35
  0.8 of the skirt's half-width (the proposal's, within 90 px of the centre of a skirt
@@ -41,10 +41,13 @@ from the full run, because the twin tails leave the head crop sideways (a plan e
41
41
  <code>loop: idle 49 frame(s) at 12 fps, f0000 vs f0048 (t = 4s): max |d| 0 (0 required)</code><br/>
42
42
  <code>seam: setup pose at 654x1216, scale 0.9438: mean |d| 0.147 (&lt;= 1.0), 0 px over 40, 0.00 rig px (the count / s²; &lt;= 50), 0 px over 80 (reported)</code><br/>
43
43
  <code>pack: skeleton.png 1051x972, 23 region(s), 96.9% covered, padding 2, page edges free, shape polygon</code><br/>
44
- The loop is <code>rig-parts loop --palette</code>'s indexed APNG, 48 frames at
45
- 12 fps, 827,857 bytes, one 256-entry palette at a measured error of max 65, mean 0.879
46
- per channel over every frame (the lossless APNG beside it, the exactness record, is
47
- 5,832,634 bytes; the GIF, at the same error, 889,063). Frame 29 (2.417 s) is the
44
+ The loop is that build's indexed APNG, 48 frames at 12 fps, 727,486 bytes, one
45
+ 256-entry palette at a measured error of max 69, mean 0.630 per channel over every
46
+ frame (the lossless APNG beside it, the exactness record, is 5,148,992 bytes; the
47
+ GIF, at the same error, 781,526). The rig's hair, skirt, sleeves, bows and earrings
48
+ carry physics, which rigc's render starts from rest, so the idle is played three
49
+ periods ahead and the loop is the fourth: its last frame and the first differ by at
50
+ most 1 level (<code>--lead-in</code>). Frame 29 (2.417 s) is the
48
51
  closed eye: the blink holds for 0.084 s, one 12 fps frame rounded up; the painting is
49
52
  shown at half size, resampled and written by this package's PNG codec (nothing here
50
53
  encodes JPEG). <code>rig-parts sheet</code> made the contact sheet. Its
@@ -284,7 +287,7 @@ agent skill.
284
287
  | `rig --config --parts --out [--idle-keys ctl\|direct]` | author `rig.json` + `motion.json`, written only after rig-c's gate is green; each mesh is in the mode its config entry names — `grid` (the lattice, what `propose` writes), `contour` (the traced outline with declared interior points) or `auto` (the contour mesh at alpha 1 and above, reduced and locally refined by rig-c's `reduceMesh` under the author's declared bounds, written only when its motion against the unreduced source on the idle passes the author's `motion` bounds through rig-c's `compareMeshesInMotion`; [AUTHORING §3](docs/AUTHORING.md)); every chain link is turned along its chain and carries its `length`, so a physics constraint added later has a lever, with every offset under it in the turned frame so nothing moves; `--idle-keys` says whether the idle's keys on mesh-driving bones go through `<bone>_ctl` parents (default) or stay on the bones with `invariants.idleDrivesMeshes` declared; the config's `constraints` go to rigc as written, and a two-bone ik over keyed links needs `--idle-keys direct` (on `rig` or `build`) |
285
288
  | `check --rig --out [--parts] [--source] [--requirements]` | build packed, gated under `spine-html`, render the idle, measure seam, loop and the six judgement lines (mesh texture stretch among them, from the idle's `render --geometry`), and report the recomposite's holes from `parts.json`; on a rig spec with no `parts.json` or no `idle` (a merged rig, issue #77) the gate still runs and every line that needs the missing input says SKIP by name; `--source <painting.png>` adds `SETUP_POSE_VS_SOURCE`, the setup pose against the painting by assemble's recomposite figures; `--requirements <scene.json>` measures what a scene declares of the motion — a contact, a follow fraction, an aim, a joint range, a mesh's stretch, the seam between two parts over the motion — each against the author's own bar, from rig-c's posed frames, one line each, PASS, FAIL or NOT MEASURABLE (AUTHORING §7, *Declared requirements*) |
286
289
  | `loop --frames <dir> --out <file.gif \| file.png> [--palette]` | encode a rendered idle as a looping GIF, lossless APNG, or indexed APNG (`--palette`) |
287
- | `build --config --source --full --head --out [--seam] [--project] [--loop] [--requirements] [--idle-keys ctl\|direct]` | assemble, rig and check in one process, stopping at the first refusal; `--requirements` is forwarded to check, `--idle-keys` to rig |
290
+ | `build --config --source --full --head --out [--seam] [--project] [--loop] [--lead-in <periods>] [--requirements] [--idle-keys ctl\|direct]` | assemble, rig and check in one process, stopping at the first refusal; `--requirements` is forwarded to check, `--idle-keys` to rig; `--lead-in` (with `--loop`) encodes the loop from the last of n + 1 idle periods played back to back, for a rig whose physics does not end where the render starts it |
288
291
  | `compose --scene <scene.json> --out [--requirements] [--accept]` | bind several characters' green builds into one rig (or, under `--accept`, builds failing only the bars named — for looking, not shipping): every name prefixed `<id>:` under one shared root, each character's offset added at its first-level bones, an optional background plate (its provenance recorded, judged by nothing) drawn first, and the draw order between the characters' slots as the scene file declares it — nothing inferred, nothing scaled; gated through rig-c as `rig` is, then checked ([AUTHORING §7](docs/AUTHORING.md), *Composing several characters*) |
289
292
 
290
293
  `rig-parts --help` has every flag. Exit codes: 0 done, 1 input refused (every
@@ -334,8 +337,10 @@ These are limits of the approach, stated so nobody reads more into a green run:
334
337
 
335
338
  This package makes no expression and no jiggle, but the rig it writes is the material for
336
339
  both, and the config has a field for each; `examples/demo` and `examples/scarf` carry a worked
337
- set of each (issue #224: a tilt, two looks, a smile, a startle, a wave or a bow and a hop,
338
- with physics on the hair, the skirt, the sleeves and the scarf ends). [docs/AUTHORING.md](docs/AUTHORING.md) has a recipe
340
+ set of each (issue #224: a hop, a head tilt, a wave or a bow, and physics on the hair, the
341
+ skirt, the sleeves and the scarf ends; also two head turns, a smile and a startle, which at
342
+ full-body size read as small moves of the head and face rather than as expressions —
343
+ one image per slot leaves the face only what its bones can do). [docs/AUTHORING.md](docs/AUTHORING.md) has a recipe
339
344
  for each — a config fragment, the `check` lines it passes with, and its limit:
340
345
 
341
346
  - [**Expressions and other named animations**](docs/AUTHORING.md#recipe-expressions-and-other-named-animations):
package/cli.ts CHANGED
@@ -417,7 +417,7 @@ usage:
417
417
  --head <dir|psd> --out <dir> [--seam near-white|silhouette]
418
418
  [--project core|visible] [--page-edges pot|free]
419
419
  [--pack-shape rect|polygon] [--loop] [--requirements <file.json>]
420
- [--idle-keys ctl|direct]
420
+ [--idle-keys ctl|direct] [--lead-in <periods>]
421
421
  assemble, then rig, then check, in one process, each stage's own lines
422
422
  printed under [assemble], [rig] and [check]; the first stage that refuses
423
423
  stops the build with its own FAIL lines. The config must already carry
@@ -428,7 +428,9 @@ usage:
428
428
  rig/ (rig), check/ (check, with the packed build in check/build/), and with
429
429
  --loop idle.png (lossless APNG), idle-indexed.png (indexed APNG) and
430
430
  idle.gif from check/idle_frames/, then one loop: line with the three sizes
431
- and the two palette errors. The paths it writes are cleared first. A
431
+ and the two palette errors. --lead-in <n> (with --loop) encodes them
432
+ instead from the last of n + 1 idle periods played back to back, for a
433
+ rig whose physics does not end where rigc's render starts it. The paths it writes are cleared first. A
432
434
  green build ends with the pack line beside the spineboy yardstick and the
433
435
  three artifact paths — skeleton .json, .atlas and the packed page: the
434
436
  packed atlas is the result, the loose parts are the intermediate it was
@@ -574,7 +576,7 @@ const TAKES = {
574
576
  'comfy seethrough': { valued: ['--image', '--out', '--resolution', '--steps', '--seed', '--prefix', '--host', '--wait', '--timeout', '--poll'], switches: ['--offload', '--lama', '--nf4'] },
575
577
  'comfy paint': { valued: ['--config', '--out', '--seeds', '--seed0', '--host', '--wait', '--timeout', '--poll'], switches: [] },
576
578
  inputs: { valued: ['--source', '--config', '--out'], switches: [] },
577
- build: { valued: ['--config', '--source', '--full', '--head', '--out', '--seam', '--project', '--page-edges', '--pack-shape', '--requirements', '--idle-keys'], switches: ['--loop'] },
579
+ build: { valued: ['--config', '--source', '--full', '--head', '--out', '--seam', '--project', '--page-edges', '--pack-shape', '--requirements', '--idle-keys', '--lead-in'], switches: ['--loop'] },
578
580
  compose: { valued: ['--scene', '--out', '--requirements', '--accept'], switches: [] },
579
581
  } as const satisfies Record<string, { valued: readonly string[]; switches: readonly string[] }>;
580
582
 
@@ -1171,6 +1173,9 @@ function cmdBuild(args: string[]): number {
1171
1173
  if (!isPackShape(shape)) return usage(shape);
1172
1174
  const keys = idleKeysOf(flags.get('--idle-keys'));
1173
1175
  if (!isIdleKeys(keys)) return usage(keys);
1176
+ const leadText = flags.get('--lead-in');
1177
+ if (leadText !== undefined && !/^[1-9][0-9]*$/.test(leadText)) return usage(`--lead-in ${leadText}; a whole number of idle periods, 1 or more, is required`);
1178
+ if (leadText !== undefined && !loop) return usage('--lead-in needs --loop; it says which frames the loop is encoded from');
1174
1179
  const [config, source, full, head, out] = ['--config', '--source', '--full', '--head', '--out'].map((f) => flags.get(f) as string);
1175
1180
  let bin: string;
1176
1181
  try {
@@ -1181,7 +1186,7 @@ function cmdBuild(args: string[]): number {
1181
1186
  const scratch = mkdtempSync(join(tmpdir(), 'rig-parts-build-'));
1182
1187
  try {
1183
1188
  const r = build(
1184
- { config, source, full, head, out, seam: seam as SeamRule, project: project as ProjectRule, loop, pageEdges: edges, packShape: shape, ...(flags.has('--requirements') ? { requirements: flags.get('--requirements') as string } : {}), idleKeys: keys },
1189
+ { config, source, full, head, out, seam: seam as SeamRule, project: project as ProjectRule, loop, pageEdges: edges, packShape: shape, ...(flags.has('--requirements') ? { requirements: flags.get('--requirements') as string } : {}), idleKeys: keys, ...(leadText === undefined ? {} : { leadIn: Number(leadText) }) },
1185
1190
  { rig: rigcRunner(bin), check: rigcRunner(bin), checkBin: bin, scratch: join(scratch, 'rig-gate') },
1186
1191
  console.log,
1187
1192
  );
package/docs/AUTHORING.md CHANGED
@@ -91,7 +91,7 @@ read by no CPU stage).
91
91
  | `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 |
92
92
  | `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 |
93
93
  | `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` 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), `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`). `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 |
94
- | `bones` | rig; `propose --from-config` | **proposed** by `propose`, then corrected. A single bone `{name, parent, at, tip?}` or a chain `{chain, parent, points, tip}` 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 is never turned; one whose parent is a link is turned back upright |
94
+ | `bones` | rig; `propose --from-config` | **proposed** by `propose`, then corrected. A single bone `{name, parent, at, tip?}` or a chain `{chain, parent, points, tip}` 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. 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 |
95
95
  | `meshes.<part>` | rig | **proposed**, then corrected. Exactly one of `grid` (the lattice: cell size, px — what `propose` writes), `contour` (the outline mode, authored; the next row and "A contour mesh" below) or `auto` (the automatic mode, authored; "An automatic mesh" below) — two, or none, is `CONFIG_MESH_MODE`. In every mode: `r` (added to every distance before weighting: `w = 1/(d + r)²`), `segments` (a chain name, a bone name with a `tip`, or `[bone, [x0,y0], [x1,y1]]`), and, **authored**, optional, `exponent` (issue #161): a number above 0 that replaces the 2 in that rule, `w = 1/(d + r)^exponent` — a larger one hands each vertex more fully to its nearest bone; absent is 2 and changes no byte, a value that is not a number above 0 is `CONFIG_FIELD_TYPE` at `meshes.<part>.exponent`, and a declared one is echoed as `exponent` in the mesh's `mesh_report.json` row; the exponent is the distance rule's, so declared beside `rule: "heat"` it is refused (`CONFIG_FIELD_TYPE` at `meshes.<part>.exponent`). The segment list is the one authored decision about a layer: which bones may pull it. The slot's bone is the first segment's. Optional `rule` (issue #161): `"distance"` — the rule above, and what an absent `rule` means (every byte is the same) — or `"heat"`, bone heat over the part's own silhouette, in every mode: the lattice's art (alpha above 8) with holes filled, or for `contour` and `auto` the silhouette their outline is traced from (that mode's art — alpha above 8 for `contour`, alpha 1 and above for `auto` — less any island a declared `stray` left out, holes filled, grown by its `margin`); each bound bone's sources are the silhouette pixels whose centre lies within 0.75 px of its segment (a pixel two bones reach goes to the nearer, a tie to the first listed), held at 1 for that bone and 0 for the others; the field is solved by row-major Gauss–Seidel over-relaxation to a sweep change under 1e-7 within 20000 sweeps; a vertex reads the nearest silhouette pixel and takes the same cap and floor (and `regions`) as the distance rule; `r` is not read. The mesh's `mesh_report.json` row gains `heat` (the constants, each bone's sources and sweeps, the residual). Any other value is `CONFIG_FIELD_TYPE`; a bound bone with no source pixel is `RIG_HEAT_BONE_SOURCE`, an island no bone has a source in `RIG_HEAT_ISLAND_SOURCE`, a solve past its sweep bound `RIG_HEAT_CONVERGED` — none is weighted 0 |
96
96
  | `meshes.<part>.contour` | rig | **authored**, optional (issue #84): `{tolerance, margin, spacing, budget?, stray?, regions?}`. `tolerance` — rig-c's Douglas–Peucker tolerance on the traced outline, px, 0 or more; `margin` — how far the silhouette grows before it is traced, px: 0, or 1 or more (a pixel joins when its centre lies within `margin` of an art pixel's centre; a value above 0 and below 1 adds nothing and is refused, `CONFIG_FIELD_TYPE`); `spacing` — the background interior spacing, px, above 0; `budget` — the most vertices the mesh may have (refused above it, nothing thinned); `stray` — the largest island, in art pixels, that may be left out of the mesh (absent: none is); `regions` — local deformation regions, each `{name, shape, bone, spacing, band}` with `shape` `"circle"` (`cx, cy, r`) or `"polygon"` (`points`, 3 or more): `bone` is the region's control bone (any bone `bones` declares), `spacing` the interior spacing inside the region and its band, `band` the width the bone's weight falls across. Every length and position is **rig px**, like every other in the config; the part image is the rig less `(x − 4, y − 4)` (its box less the pad), a translation, so a length is the same number in both. A region's `cx`, `cy`, `r`, `band` and `points` are multiples of 1/256 px (`CONFIG_FIELD_TYPE` otherwise); region names are unique per mesh (`CONFIG_REGION_NAME_UNIQUE`). The alpha threshold is not a field: art is alpha above 8, the lattice's and `check`'s |
97
97
  | `meshes.<part>.ribs` | rig | **authored**, optional (issue #188), in the `contour` and `auto` modes: `{<chain>: {stations}, …}`, each key a chain this mesh's `segments` name. Each link of the chain gets a row of vertices across the part at its origin and at `stations` points evenly between its origin and its end (`stations`, a whole number, 0 or more, required; a chain of L links carries L × (stations + 1) ribs), each rib a row of vertices across the part, kept as a row of locked edges; the rule is "Ribs along a chain" under "A contour mesh". Absent places none and changes no byte. Refused: a lattice mesh with ribs (`CONFIG_RIBS_MODE` — its vertices are its grid's corners), a key that is not one of the mesh's chains (`CONFIG_NAME_RESOLVES`), an object naming no chain or a `stations` that is not a whole number from 0 (`CONFIG_FIELD_TYPE`); at the rig stage `CONTOUR_RIB_ART`, `CONTOUR_RIB_LINK`, `CONTOUR_RIB_CROSSING`, `CONTOUR_RIB_EDGE` (the contour refusals). The mesh's `mesh_report.json` row gains `ribs` — the declaration, the ribs placed and the vertices they hold — and its contour report (the source's, in `auto`) lists each rib's vertices |
@@ -200,6 +200,8 @@ What a joint with a position places, as given — no ratio is applied over it:
200
200
  | `chest` | its rule, half way from neck to hip, taken along the line between the placed ends | the rule as before when neither end is a joint |
201
201
  | `sleeve_<s>` | `<s>_shoulder` → `<s>_elbow` (two links), tip at `<s>_wrist`, with the two-blob rule's first two amplitudes and its chest stub laid along the upper arm — when every handwear part over 500 px holds one such wrist within 15 px of its art (the larger of the x and y gaps, the LINT's own tolerance), or is bound one by `--wrist-snap` (below) | the sleeve rule places every sleeve chain, and each arm joint's note says why: for a wrist on no part, `… lies on the art of no handwear part within 15 px, so it does not say which sleeve it ends; the nearest is <part>, <d> px from its art by the larger of the x and y gaps (--wrist-snap <d> would bind it)` — `(beyond --wrist-snap <px>)` when the flag was given and fell short, and `the nearest are <a> and <b>, each <d> px …, so no tolerance says which` when two parts tie |
202
202
  | `eye_<s>`, `head`, the face box | not moved: they are measured off the parts | the note prints the eye joint's distance from the eye bone, with no bar |
203
+ | `leg_<s>` or `leg` (issue #241) | on a `legwear` part over 500 px: `<s>_hip` → `<s>_knee` (two links), tip at `<s>_ankle`, parent `hip`, the part meshed on the chain and a `hip` stub laid along the thigh — when every such part holds the ankle of a leg whose three joints are given, within 15 px of its art. A part holding both ankles gets a chain per leg only when its art breaks along the line from `r_knee` to `l_knee` and along the line from `r_ankle` to `l_ankle` (the legs painted apart); otherwise one chain, `leg`, through the midpoints of the two hips, the two knees and the two ankles. No idle track: the chain is drafted whatever the pose, and whether the legs move is the scene's. A note on the part says which and why | no leg with all three joints: no chain, and the part is the trunk rule's region with the note it always had, byte for byte. A complete leg whose ankle lies on no legwear part, or on two: no chain, and a note `<parts>: no leg chain — <why>; the trunk rule places it` |
204
+ | the trunk parts' segments (issue #243) | on the `neck` (head run), `topwear` and `bottomwear` meshes, each `[bone, from, to]` segment the rule drafts down the screen is laid along neck → hip, the line the chest is placed on — `neck` + 18 px along it to `chest`; a topwear part's `chest` segment from its art's nearest reach toward the neck end to 20 px short of `hip`, and its `hip` segment from there to 100 px past `hip`; a bottomwear part's `chest` segment from 30 px short of `chest` to 20 px short of `hip` — and the bottomwear waist segment runs across that line, 5 px past `hip`, over 0.09 to 0.91 of the art's width across it. The `head` segment on the neck mesh and the one-blob sleeve rule's chest segment are not moved. A note, `trunk segments (<parts>): laid along neck -> hip …`, gives the line's angle | neither end a joint: the vertical draft, byte for byte. Neck and hip on one point: no line, the vertical draft, and a note says so. An upright line over boxes tight on their art writes the vertical draft's bytes |
203
205
 
204
206
  **`--wrist-snap <px>`** (issue #199), with `--keypoints` only, declares a tolerance
205
207
  for a wrist that lies on no handwear part within the built-in 15 px — hands folded
@@ -229,8 +231,8 @@ silently:
229
231
  The `assemble.cuts` entry (§3; §5, *Cutting a piece out of a layer*) splits the part; the
230
232
  proposer does not.
231
233
 
232
- Every other joint (`nose`, knees, ankles, ears; the eyes with no eyewhite) is named
233
- with its state in one note: no bone is authored from it. Every joint the proposer
234
+ Every other joint (`nose`, ears, the knees and ankles no leg chain used; the eyes
235
+ with no eyewhite) is named with its state in one note: no bone is authored from it. Every joint the proposer
234
236
  could use gets its own note — `used as given for bone X`, `used as the producer's
235
237
  estimate for bone X`, or `missing: the rule "…" placed bone X instead` — after every
236
238
  note the rules wrote. LINT then reads the torso by the relations the joints declare:
@@ -1242,7 +1244,7 @@ proposal in as the steps above say (`RL01`); every step must exit 0.
1242
1244
  | `check` (inside `build`) | the gate lines verbatim, the pack line, `loop:` (and `loop physics:` when the rig declares a physics constraint, §7), `seam:`, the six judgement lines, `RECOMPOSITE_HOLES` and, under `--source`, `SETUP_POSE_VS_SOURCE` (§7), `check.json`; the last line says how many of the nine bars measured and names the ones that said SKIP | `check: PASS; 9 of 9 bar(s) measured, 0 skipped` on the examples, and a judgement line SKIP only where the character lacks what it reads; on a rig spec with no `parts.json` or no `idle` (a merged rig, §7 *Measuring a rig rig-parts did not assemble*), PASS with the skipped bars named | `CHECK_SEAM_WITHIN_BAR` or `CHECK_LOOP_CLOSES` (§6) |
1243
1245
  | `check --requirements` (and `build --requirements`) | after the lines above, one line per declared requirement, `NAME: PASS`, `FAIL` or `NOT MEASURABLE — …` with its figures, the bar as declared and the worst frame; then `requirements: N declared — M measured (P PASS, F FAIL), K NOT MEASURABLE; not declared: <kinds>`; `check.json`'s `requirements` block; the renders under `requirements/` (§7, *Declared requirements*) | every line PASS and `0 NOT MEASURABLE`; a follow's `released_copy` says whether rigc's consumer-driven door was taken on the throwaway copy | `CHECK_REQUIREMENT_MET` (a figure past its bar; the line names the frame) or `CHECK_REQUIREMENT_MEASURABLE` (the quantity is undefined in the frames: a tip or an axis on a bone of length 0, an aim with no line, a follow no frame of which reaches its least drive); the last line then reads `check: FAIL — B bar(s) not met, R declared requirement(s) not PASS` |
1244
1246
  | `compose` | the `[compose]` lines: one per character (its offset, its scale, its placed bounds, the shift and how many first-level bones, regions on `root` and weights bound to `root` it moved, its bone, slot, track and constraint counts, its `rig_scale` and idle), the declared order and the slot count it expands to, rigc's gate lines; then the `[check]` lines as for `check`, and `scene.json` | both gate summaries `0 failed`, `check: PASS` with the bars that measured and the ones that said SKIP named — on a composed rig `4 of 9`: the gate, the loop, `CHAIN_LAG` and `TEXTURE_STRETCH` (there is no `parts.json`; each character's own `build` measured all nine). `scene.json`'s `order.slots` is the order the compiled skeleton draws | a `SCENE_*` refusal (§6, *compose*) — the scene file, a build, or the order; `COMPOSE_RIGC_GREEN` — rigc's own line, quoted |
1245
- | `loop` (inside `build --loop`, or `loop --frames … --out …`) | the dropped-duplicate line, each file's line, then `loop: idle.png N B (lossless); idle-indexed.png N B (max …, mean …); idle.gif N B (max …, mean …)` | `f0048.png equals f0000.png byte for byte, so it is dropped` | `LOOP_ENCODE` (§6) |
1247
+ | `loop` (inside `build --loop`, or `loop --frames … --out …`) | the dropped-duplicate line (under `build --lead-in`, the lead-in line in its place: the frames kept and the jump at the wrap), each file's line, then `loop: idle.png N B (lossless); idle-indexed.png N B (max …, mean …); idle.gif N B (max …, mean …)` | `f0048.png equals f0000.png byte for byte, so it is dropped` | `LOOP_ENCODE` (§6) |
1246
1248
 
1247
1249
  `loop` writes three files from one frame set, and they are not interchangeable.
1248
1250
  `idle.png` (`loop --out x.png`) is the lossless APNG: every frame decodes to the
@@ -1253,10 +1255,26 @@ entry, no dithering, filter None) — and is the small file to show. `idle.gif`
1253
1255
  (`loop --out x.gif`) is the same median cut in a GIF. The indexed APNG and the GIF
1254
1256
  print their palette error, per channel over R, G and B of every frame (and alpha's
1255
1257
  max for the APNG); a figure is a measurement of the file, not a bar. On the demo
1256
- (the README's animation since issue #227: `build --loop`, default flags, rig-c 2.33.0):
1257
- 5,832,634 B lossless, 827,857 B indexed and 889,063 B GIF, both palette files at
1258
- max 65, mean 0.879 — the two share one quantiser, so their error is the same by
1259
- construction and the size is the difference. On reference-demo with `--seam silhouette`
1258
+ (the README's animation since issue #224's follow-up: `build --loop --lead-in 3`, rig-c
1259
+ 2.33.0): 5,148,992 B lossless, 727,486 B indexed and 781,526 B GIF, both palette files
1260
+ at max 69, mean 0.630 — the two share one quantiser, so their error is the same by
1261
+ construction and the size is the difference. From issue #227 until then, `build --loop`
1262
+ with default flags, before the demo carried physics: 5,832,634, 827,857 and 889,063 B
1263
+ at max 65, mean 0.879.
1264
+
1265
+ **`build --loop --lead-in <n>`** is for a rig with physics. rigc's render resets every
1266
+ physics constraint at frame 0, so such an idle does not end where it starts: on the demo
1267
+ (issue #224's strands, the tails at inertia 0.8) frame 0 and frame 48 differ by max |d|
1268
+ 132, 626 px over 40, and
1269
+ the plain loop keeps all 49 frames and jumps at the wrap. With `--lead-in n` the build
1270
+ renders the idle played n + 1 times back to back (`idle_lead_in`, the build's other
1271
+ animations kept so the viewport is fitted as for the idle frames), keeps the last
1272
+ period, drops its end frame (the next period's first) and prints how far that end frame
1273
+ is from the first kept one — the jump the loop will show. The settling is the rig's, not
1274
+ a constant: on the demo, `--lead-in 1` and `2` each still read max |d| 117, 305 px over 40, and `3` reads max 1, 0 px over 40. The idle
1275
+ must repeat without an invented value — every track keyed from 0 to the duration, ending
1276
+ where it starts — or the build refuses it (`LOOP_LEAD_IN_IDLE`). `check` and its bars
1277
+ read `check/idle_frames/` as before; only the loop files move. On reference-demo with `--seam silhouette`
1260
1278
  (the README's animation until issue #227, rig-c 2.1.3, and 2.10.1 to the byte):
1261
1279
  13,645,503 B lossless, 1,706,719 B indexed and 1,812,288 B GIF at max 57, mean 1.601;
1262
1280
  with `--pack-shape rect` the same build writes 13,645,350, 1,706,520 and 1,812,238 B,
@@ -1510,7 +1528,7 @@ it was cut from, so two records may share one, and names that part in `cut_from`
1510
1528
  or before its base comes first, and only `cut_from` says which of the two the cut made.
1511
1529
  The reader refuses a `cut_from` that names no part of the file, the piece itself, another
1512
1530
  piece, or a part on another layer (`PARTS_CUT_FROM_KNOWN`). A `parts.json` written before
1513
- 1.5.6 has no `cut_from` and still reads; `propose` alone refuses it when two of its parts
1531
+ 1.6.0 has no `cut_from` and still reads; `propose` alone refuses it when two of its parts
1514
1532
  share a layer (`PROPOSE_CUT_FROM_RECORDED`): re-run assemble. **A patch is 100 % source**: every pixel is the
1515
1533
  painting's, so it is all visible and all taken — `visible_px`, `projected_core_px`
1516
1534
  and `source_px_taken` equal `opaque_px`, and `occluded_px`,
@@ -1700,7 +1718,7 @@ See-through with another seed.
1700
1718
  | `HEADBOX_FACE_PRESENT`, `HEADBOX_RUN_SQUARE`, `HEADBOX_CANVAS_SIZE`, `HEADBOX_FITS_CANVAS` | the full run has no face or is not square; `--canvas` is not a positive size; or the painting cannot hold the proposed box at its size — its shorter side is the bound (shrinking it would cut the head) | `--full`, `--canvas`, or the painting |
1701
1719
  | `PROPOSE_SOURCE_PRESENT`, `PROPOSE_PNG_PRESENT`, `PROPOSE_PNG_MATCHES_BOX` | the painting or a part PNG is missing, or a PNG is not its box | `--source`, `--parts` (re-run assemble) |
1702
1720
  | `PROPOSE_FACE_PRESENT` | no part comes from a `face` layer, and the face-less fallback cannot derive a face box either: it needs the head run's `neck` and at least one head-run `front hair`/`back hair` part whose top is above the neck's, and the message names the half that is missing. With both, `propose` does not refuse — it derives the box and says so in its first note (§5) | `assemble.plan`: take the face, or the head run's hair and neck |
1703
- | `PROPOSE_CUT_FROM_RECORDED` | two parts share one layer and none of them records `cut_from`: a `parts.json` an `assemble` before 1.5.6 wrote with `assemble.cuts`. The records are in draw order, so which is the plan part and which the piece cannot be read off the file; the message names the parts and the layer. Every other reader still takes the file | `--parts`: re-run assemble (1.5.6+) to record `cut_from` |
1721
+ | `PROPOSE_CUT_FROM_RECORDED` | two parts share one layer and none of them records `cut_from`: a `parts.json` an `assemble` before 1.6.0 wrote with `assemble.cuts`. The records are in draw order, so which is the plan part and which the piece cannot be read off the file; the message names the parts and the layer. Every other reader still takes the file | `--parts`: re-run assemble (1.6.0+) to record `cut_from` |
1704
1722
  | `PROPOSE_ACCESSORY_BODY` | an accessory has nothing above its pendant rows to hang its bone on | that part's plan entry, or author its bones by hand |
1705
1723
  | `KEYPOINTS_FILE_PRESENT`, `KEYPOINTS_IS_JSON`, `KEYPOINTS_KEY_KNOWN`, `KEYPOINTS_FIELD_PRESENT`, `KEYPOINTS_FIELD_TYPE` | the `--keypoints` file is absent, not JSON, has a key this reader does not know, lacks one of `spec`, `space`, `width`, `height`, `source`, `people`, or holds a value of the wrong type (a size that is not a whole positive px count, an empty `source`, no people) | the keypoint file (§3, *A posed figure*) |
1706
1724
  | `KEYPOINTS_SPEC_KNOWN`, `KEYPOINTS_SPACE_STATED` | the file is not `spine-parts-keypoints/1`, or states a space other than painting-px, origin top-left, y down | convert the file to that space; it is not read as if it were in it |
@@ -1748,6 +1766,7 @@ See-through with another seed.
1748
1766
  | `CHECK_TEXTURE_STRETCH` | a mesh triangle's edge, in some idle frame, is more than 1.926544 times its rest length or less than 1/1.926544 of it (the mesh, triangle, its three vertices, the edge and the frame are named); or a rest edge has length 0 | the chain tracks' `amps` on the bones that mesh is weighted to (the stretch grows with them), or the mesh's `segments` — a vertex blending two bones that swing against each other |
1749
1767
  | `CHECK_SEAM_FRAME_SIZE`, `FRAMES_SIDECAR`, `CHECK_GEOMETRY_FILE` | rigc's render is not what its `frames.json` says, or its `geometry.json` is not a whole `rigc-geometry/1` export of the frames beside it (a frame count, a mesh whose vertex count differs from its rest entry; for the face half, another viewport than `frames.json`'s, other frame indices, the head bone or a feature's bone missing from a frame, a non-finite transform or time) | a rigc problem; report it |
1750
1768
  | `LOOP_ENCODE` | the loop encoder refused a frame (translucent pixel in a GIF, a size change) | the frames; for a translucent frame write the lossless or the indexed APNG, which keep alpha |
1769
+ | `LOOP_LEAD_IN_IDLE` | `build --lead-in`: the idle cannot be repeated without inventing a value (a track not keyed from 0 to the duration, or ending where it does not start; a field besides `duration`, `loop`, `note`, `tracks`), the motion already has an `idle_lead_in`, or the render did not write whole periods | the refusal names the track or field; the demo's idle, as the rig stage writes it, repeats as written |
1751
1770
  | `CHECK_PACK_LINE_READS` | rigc printed a `pack:` line that is not `pack: <page> <W>x<H>, <N> region(s), <P>% covered, padding <D>`, then `, page edges free` or nothing, then `, shape rect`, `, shape polygon` or nothing (rig-c 2.1 prints the shape; 1.5–2.0 printed none, read as `rect`); an unknown shape is this refusal; the line is quoted | a rigc this package does not know the output of; report it, with `rigc --version` |
1752
1771
  | `CHECK_PACK_PAGE_EDGES` | the pack line disagrees with the `--page-edges` the build was run with — its `, page edges free` clause is there under `pot` or missing under `free`, or a `pot` page is not a power of two on both edges | a rigc problem; report it, with `rigc --version` |
1753
1772
  | `CHECK_PACK_SHAPE` | the pack line disagrees with the `--pack-shape` the build was run with — it ends `, shape rect` under `polygon` or `, shape polygon` under `rect`, or it has no shape clause (the 1.5–2.0 form, read as `rect`) under `polygon` | a rigc older than 2.1.0 on `PATH`: rigc 2.0.3 takes `--pack-shape` without a word, packs by rectangles and prints the form with no shape clause, so this refusal is what catches it — `bun install` (this package depends on rig-c ^2.20.4); otherwise a rigc problem, report it with `rigc --version` |
package/docs/STABILITY.md CHANGED
@@ -57,7 +57,7 @@ defaults are the help's too, and none is guessed from the art.
57
57
  | `rig` | `--config`, `--parts`, `--out`; optional `--idle-keys` (ctl, direct), `--page-edges` (pot, free), `--pack-shape` (rect, polygon) |
58
58
  | `check` | `--rig`, `--out`; optional `--parts`, `--source`, `--page-edges`, `--pack-shape`, `--requirements`, `--seam-pairs`, `--keep-stills` |
59
59
  | `loop` | `--frames`, `--out`; optional `--palette` |
60
- | `build` | `--config`, `--source`, `--full`, `--head`, `--out`; optional `--seam`, `--project`, `--page-edges`, `--pack-shape`, `--loop`, `--requirements`, `--idle-keys` |
60
+ | `build` | `--config`, `--source`, `--full`, `--head`, `--out`; optional `--seam`, `--project`, `--page-edges`, `--pack-shape`, `--loop`, `--lead-in`, `--requirements`, `--idle-keys` |
61
61
  | `compose` | `--scene`, `--out`; optional `--requirements`, `--accept` |
62
62
  | (none) | `--version`, `--help` |
63
63
  <!-- /stable:commands -->
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-parts",
3
- "version": "1.6.0",
3
+ "version": "1.7.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": {
@@ -60,7 +60,7 @@
60
60
  },
61
61
  "dependencies": {
62
62
  "ag-psd": "^31.0.2",
63
- "rig-c": "^2.33.0"
63
+ "rig-c": "^2.40.0"
64
64
  },
65
65
  "devDependencies": {
66
66
  "@esotericsoftware/spine-core": "4.3.13",
package/src/build.ts CHANGED
@@ -70,7 +70,7 @@ import {
70
70
  splitSchedule,
71
71
  untestedIntervals,
72
72
  } from './autoreplay.ts';
73
- import { BARS, besideIdleLine, causeLines, REQUIREMENTS_DIR, type CheckReport, type PackLine, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, JUDGEMENT_LINES, type JudgementLine, packedBuildArgs, packedBuildLabel, type PackMode, type PackShape, type PageEdges, readFrameSet, REPORTED_LINES, type ReportedLine, type RigcRunner, runCheck, SEAM_DIR, SEAM_MEAN_BAR, seamPairText, seamRigPxText, SOURCE_LINE, SEAM_PX_BAR, SEAM_PX_LEVEL, SEAM_PX_LEVEL_HIGH, SPINEBOY_YARDSTICK, STILL_DIR } from './check.ts';
73
+ import { BARS, besideIdleLine, buildGateLines, causeLines, IDLE_FPS, IDLE_MAX_PX, maxRgbDiff, REQUIREMENTS_DIR, type CheckReport, type PackLine, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, JUDGEMENT_LINES, type JudgementLine, packedBuildArgs, packedBuildLabel, type PackMode, type PackShape, type PageEdges, readFrameSet, rigcFailed, REPORTED_LINES, type ReportedLine, type RigcRunner, runCheck, SEAM_DIR, SEAM_MEAN_BAR, seamPairText, seamRigPxText, SOURCE_LINE, SEAM_PX_BAR, SEAM_PX_LEVEL, SEAM_PX_LEVEL_HIGH, SPINEBOY_YARDSTICK, STILL_DIR } from './check.ts';
74
74
  import { type Cut, loadConfig, loadConfigAndAnimations, loadEarlyConfig } from './config.ts';
75
75
  import { PartsError, type Problem, problemLine, refuseIfAny } from './errors.ts';
76
76
  import type { MeshQualityReport, MotionSchedule } from 'rig-c/mesh';
@@ -82,7 +82,8 @@ import { type PartRecord, readParts, writeParts } from './parts.ts';
82
82
  import { encodePngBytes, readPng, writePng } from './raster/png.ts';
83
83
  import type { Raster } from './raster/types.ts';
84
84
  import { readRequirements, type RequirementLine, summaryText } from './requirements.ts';
85
- import { type AutoMeshReport, buildRig, DEFAULT_IDLE_KEYS, type IdleKeys, type MeshReport, type RigCommand, rigJsonText, type RigOutput, type RigSpec, type StrayCleared } from './rig.ts';
85
+ import { type AutoMeshReport, buildRig, DEFAULT_IDLE_KEYS, type FaceAxis, type IdleKeys, type MeshReport, type RigCommand, rigJsonText, type RigOutput, type RigSpec, type StrayCleared } from './rig.ts';
86
+ import { pyRound } from './round.ts';
86
87
 
87
88
  /** Where a stage's lines go. The commands hand it `console.log`; `build` hands it a prefixing wrapper. */
88
89
  export type Log = (line: string) => void;
@@ -819,6 +820,7 @@ export function rigStage(input: RigStageInput, rigc: RigcRunner, scratch: string
819
820
  ` bones ${rig.rig.bones.length} (${rig.controls.length} control) slots ${rig.rig.slots.length} meshes ${rig.meshReport.length} regions ${regions} vertices ${vertices}; idle ${rig.motion.animations.idle.duration} s, ${tracks.length} track(s), ${keys} key(s)`,
820
821
  );
821
822
  if (from !== null) log(` animations beside the idle, from ${from.file} as written: ${Object.keys(from.table).join(', ') || 'none'}`);
823
+ log(faceAxisLine(rig.faceAxis));
822
824
  log(
823
825
  rig.idleKeys === 'ctl'
824
826
  ? ` idle keys ctl: ${rig.meshKeyed.length} mesh-driving bone(s) keyed by the idle, each keyed through a same-origin <bone>_ctl parent`
@@ -941,6 +943,24 @@ export function barsSummary(r: CheckReport): string {
941
943
  return `${measured.length} of ${BARS.length} bar(s) measured, ${skipped.length} skipped${skipped.length === 0 ? '' : ` (${skipped.map((s) => s.bar).join(', ')})`}`;
942
944
  }
943
945
 
946
+ /**
947
+ * The rig stage's face-axis line (issue #239): the eye line's angle, the parts it runs between and the face bones
948
+ * turned to it, or why there is no line and the face bones keep the page's axes — the note a one-eyed painting gets.
949
+ * With a line it also names the `invariants.axes` entry written for rigc's A51, its tolerance, or why none was.
950
+ */
951
+ export function faceAxisLine(f: FaceAxis): string {
952
+ const own = f.ownTip.length === 0 ? '' : `; ${f.ownTip.join(', ')} ${f.ownTip.length === 1 ? 'takes its' : 'take their'} own tip`;
953
+ if (f.degrees === null) return ` face axis: none — ${f.none}; ${f.ownTip.length === 0 ? 'the face bones keep' : 'the other face bones keep'} the page's axes${own}`;
954
+ const turned = f.turned.length === 0 ? 'no face bone to turn' : `${f.turned.join(', ')} turned to it`;
955
+ const held =
956
+ f.axis !== null
957
+ ? `; invariants.axes "${f.axis.name}" holds ${f.axis.bones.join(', ')} to the line through ${f.axis.through.join(' -> ')}, tolerance ${f.axis.tolerance} degrees (rigc's A51)`
958
+ : f.noAxis !== null
959
+ ? `; no invariants.axes entry: ${f.noAxis}`
960
+ : '';
961
+ return ` face axis: ${pyRound(f.degrees, 6)} degrees, the line through the eye bones eye_r and eye_l (on ${f.parts[0]} and ${f.parts[1]}); ${turned}${own}${held}`;
962
+ }
963
+
944
964
  /** A judgement line as the console prints it: its name, its status, then its figures and bars as check.json holds them (a SKIP prints its reason). */
945
965
  export function judgementLine(name: string, line: JudgementLine | ReportedLine): string {
946
966
  if (line.status === 'SKIP') return `${name}: SKIP — ${String(line.reason)}`;
@@ -1027,19 +1047,141 @@ export interface LoopResult {
1027
1047
  error: PaletteError | null;
1028
1048
  }
1029
1049
 
1050
+ /**
1051
+ * The idle `build --loop --lead-in <n>` renders (issue #224's follow-up):
1052
+ * `idle` played n + 1 times back to back, of which the loop keeps the last
1053
+ * period. rigc's render resets physics at frame 0, so an idle whose rig
1054
+ * carries a physics constraint does not end where it starts; played on, a
1055
+ * spring the idle drives settles into the idle's period, and the last period
1056
+ * of the run is that steady state.
1057
+ */
1058
+ export const LEAD_IN_ANIMATION = 'idle_lead_in';
1059
+
1060
+ /** Which frames of a lead-in run the loop keeps: the last of `periods + 1` periods. */
1061
+ export interface LoopWindow {
1062
+ periods: number;
1063
+ }
1064
+
1065
+ const LEAD_IN_ANIMATION_KEYS = ['duration', 'loop', 'note', 'tracks'];
1066
+
1067
+ /**
1068
+ * `motion` with {@link LEAD_IN_ANIMATION} added: every idle track's keys
1069
+ * repeated `periods + 1` times, each copy shifted by one idle duration, its
1070
+ * Bezier `curve` times with it, and the key at the end of a copy dropped for
1071
+ * the next copy's first key at the same time. Refused by name
1072
+ * (`LOOP_LEAD_IN_IDLE`), every problem at once, when the motion has no idle,
1073
+ * already has an animation of that name, or the idle is not a loop this can
1074
+ * repeat without inventing a value: a field besides duration, loop, note and
1075
+ * tracks; a track whose keys do not start at 0 and end at the duration; or one
1076
+ * whose last value is not its first.
1077
+ */
1078
+ export function repeatIdle(motion: Record<string, unknown>, periods: number): Record<string, unknown> {
1079
+ const problems: Problem[] = [];
1080
+ const fail = (object: string, detail: string): void => {
1081
+ problems.push({ code: 'LOOP_LEAD_IN_IDLE', object, detail });
1082
+ };
1083
+ const anims = motion.animations;
1084
+ const table = typeof anims === 'object' && anims !== null && !Array.isArray(anims) ? (anims as Record<string, unknown>) : null;
1085
+ const idle = table?.idle;
1086
+ if (table === null || typeof idle !== 'object' || idle === null || Array.isArray(idle)) {
1087
+ fail('motion.json animations.idle', 'is absent; the lead-in repeats the idle');
1088
+ refuseIfAny(problems);
1089
+ }
1090
+ const t = table as Record<string, unknown>;
1091
+ const a = idle as Record<string, unknown>;
1092
+ if (LEAD_IN_ANIMATION in t) fail(`motion.json animations.${LEAD_IN_ANIMATION}`, 'exists; the lead-in writes an animation of that name and never replaces one');
1093
+ for (const k of Object.keys(a)) if (!LEAD_IN_ANIMATION_KEYS.includes(k)) fail(`motion.json animations.idle.${k}`, `is a field the lead-in does not repeat; the idle it repeats holds ${LEAD_IN_ANIMATION_KEYS.join(', ')}`);
1094
+ const d = a.duration;
1095
+ if (typeof d !== 'number' || !(d > 0)) fail('motion.json animations.idle.duration', `is ${JSON.stringify(d)}; a positive number is required`);
1096
+ const tracks = Array.isArray(a.tracks) ? a.tracks : [];
1097
+ const duration = d as number;
1098
+ const out: unknown[] = [];
1099
+ tracks.forEach((track, i) => {
1100
+ const tr = track as Record<string, unknown>;
1101
+ const keys = Array.isArray(tr.keys) ? (tr.keys as Array<Record<string, unknown>>) : [];
1102
+ const at = `motion.json animations.idle.tracks[${i}]`;
1103
+ const first = keys[0];
1104
+ const last = keys[keys.length - 1];
1105
+ if (first === undefined || first.t !== 0 || last.t !== duration) {
1106
+ fail(at, `keys run from ${String(first?.t)} to ${String(last?.t)}; a track the lead-in repeats starts at 0 and ends at the duration ${duration}`);
1107
+ return;
1108
+ }
1109
+ if (JSON.stringify(first.v) !== JSON.stringify(last.v)) {
1110
+ fail(at, `ends at ${JSON.stringify(last.v)} and starts at ${JSON.stringify(first.v)}; repeated, the idle would jump where one copy meets the next`);
1111
+ return;
1112
+ }
1113
+ const repeated: Array<Record<string, unknown>> = [];
1114
+ for (let r = 0; r <= periods; r++) {
1115
+ const shift = r * duration;
1116
+ keys.forEach((k, j) => {
1117
+ if (r < periods && j === keys.length - 1) return;
1118
+ const moved: Record<string, unknown> = { ...k, t: (k.t as number) + shift };
1119
+ if (Array.isArray(k.curve)) moved.curve = (k.curve as number[]).map((c, n) => (n % 2 === 0 ? c + shift : c));
1120
+ repeated.push(moved);
1121
+ });
1122
+ }
1123
+ out.push({ ...tr, keys: repeated });
1124
+ });
1125
+ refuseIfAny(problems);
1126
+ return { ...motion, animations: { ...t, [LEAD_IN_ANIMATION]: { duration: duration * (periods + 1), loop: false, tracks: out } } };
1127
+ }
1128
+
1129
+ /**
1130
+ * Render {@link LEAD_IN_ANIMATION} of the rig in `rigDir` as `check` renders
1131
+ * the idle (the packed build, `IDLE_FPS`, `IDLE_MAX_PX`), every other
1132
+ * animation kept so the viewport is fitted as for the idle frames. Writes
1133
+ * under `dir` and returns the frame set's directory.
1134
+ */
1135
+ export function leadInFrames(rigDir: string, dir: string, periods: number, rigc: RigcRunner, mode: PackMode): string {
1136
+ const rig = JSON.parse(readFileSync(join(rigDir, 'rig.json'), 'utf8')) as Record<string, unknown>;
1137
+ const motion = repeatIdle(JSON.parse(readFileSync(join(rigDir, 'motion.json'), 'utf8')) as Record<string, unknown>, periods);
1138
+ const images = typeof rig.images === 'string' ? resolve(rigDir, rig.images) : rig.images;
1139
+ mkdirSync(dir, { recursive: true });
1140
+ writeFileSync(join(dir, 'rig.json'), JSON.stringify({ ...rig, images }));
1141
+ writeFileSync(join(dir, 'motion.json'), JSON.stringify(motion));
1142
+ const what = `the idle played ${periods + 1} times (${LEAD_IN_ANIMATION})`;
1143
+ const b = rigc(['build', '--rig', join(dir, 'rig.json'), '--motion', join(dir, 'motion.json'), '--out', join(dir, 'build'), ...packedBuildArgs(mode)]);
1144
+ if (b.status !== 0) refuseIfAny(rigcFailed(`${packedBuildLabel(mode)} (${what})`, b, buildGateLines(b.out)));
1145
+ const r = rigc(['render', '--candidate', join(dir, 'build'), '--animation', LEAD_IN_ANIMATION, '--fps', String(IDLE_FPS), '--max', String(IDLE_MAX_PX), '--out', join(dir, 'frames')]);
1146
+ if (r.status !== 0) refuseIfAny(rigcFailed(`render --animation ${LEAD_IN_ANIMATION} (${what})`, r, r.out.split('\n').filter((l) => l.includes('FAIL') || l.includes('rigc:'))));
1147
+ return join(dir, 'frames');
1148
+ }
1149
+
1150
+ /** Pixels whose largest RGB channel difference between `a` and `b` is above `level`. */
1151
+ function pixelsOver(a: Raster, b: Raster, level: number): number {
1152
+ let n = 0;
1153
+ for (let p = 0; p < a.width * a.height; p++) {
1154
+ let m = 0;
1155
+ for (let c = 0; c < 3; c++) m = Math.max(m, Math.abs(a.data[p * 4 + c] - b.data[p * 4 + c]));
1156
+ if (m > level) n++;
1157
+ }
1158
+ return n;
1159
+ }
1160
+
1030
1161
  /**
1031
1162
  * Encode a rigc frame set as a looping APNG, indexed APNG or GIF and write it.
1032
1163
  * An encoder refusal is a PartsError coded `LOOP_ENCODE`, so it prints like
1033
1164
  * every other.
1034
1165
  */
1035
- export function loopStage(frames: string, out: string, format: LoopFormat, log: Log): LoopResult {
1166
+ export function loopStage(frames: string, out: string, format: LoopFormat, log: Log, window?: LoopWindow): LoopResult {
1036
1167
  const set = readFrameSet(frames);
1037
1168
  const images = set.frames.map((fr) => fr.image);
1038
1169
  log(`rig-parts loop: ${set.dir} -> ${out}`);
1039
1170
  log(` ${images.length} frame(s) ${images[0]?.width ?? 0}x${images[0]?.height ?? 0} at ${set.fps} fps (from frames.json), animation ${set.animation ?? '(none)'}`);
1040
1171
  let used = images;
1041
1172
  const lastName = set.frames[set.frames.length - 1]?.name ?? '';
1042
- if (images.length > 1 && sameRgba(images[0].data, images[images.length - 1].data)) {
1173
+ if (window !== undefined) {
1174
+ const per = (images.length - 1) / (window.periods + 1);
1175
+ if (!Number.isInteger(per) || per < 1) {
1176
+ throw new PartsError([{ code: 'LOOP_LEAD_IN_IDLE', object: set.dir, detail: `holds ${images.length} frame(s), which is not ${window.periods + 1} whole period(s) and the end frame; the lead-in keeps the last period` }]);
1177
+ }
1178
+ const start = window.periods * per;
1179
+ const end = start + per;
1180
+ const jump = maxRgbDiff(images[start], images[end]);
1181
+ used = images.slice(start, end);
1182
+ const name = (i: number): string => set.frames[i].name.replace('.png', '');
1183
+ log(` lead-in: ${window.periods} period(s) of the idle played ahead, physics running; ${name(start)}–${name(end - 1)} kept (${per} frame(s), the last period); ${name(end)}, one period after ${name(start)}, differs from it by max |d| ${jump.max}, ${pixelsOver(images[start], images[end], 40)} px over 40 — the jump at the wrap`);
1184
+ } else if (images.length > 1 && sameRgba(images[0].data, images[images.length - 1].data)) {
1043
1185
  used = images.slice(0, -1);
1044
1186
  log(` ${lastName} equals f0000.png byte for byte, so it is dropped: the loop wraps onto frame 0, and showing it twice would hold that pose for two ticks`);
1045
1187
  } else if (images.length > 1) {
@@ -1103,6 +1245,12 @@ export interface BuildInput {
1103
1245
  requirements?: string;
1104
1246
  /** `--idle-keys`, forwarded to the rig stage as `rig` takes it (issue #95); {@link DEFAULT_IDLE_KEYS} when absent. */
1105
1247
  idleKeys?: IdleKeys;
1248
+ /**
1249
+ * `--lead-in <n>`, with `loop` only: the loop is encoded from the last of n + 1
1250
+ * idle periods played back to back ({@link leadInFrames}) instead of from
1251
+ * `check/idle_frames/`; absent, the loop is as before.
1252
+ */
1253
+ leadIn?: number;
1106
1254
  }
1107
1255
 
1108
1256
  /**
@@ -1116,7 +1264,7 @@ export interface BuildRunners {
1116
1264
  check: RigcRunner;
1117
1265
  /** Where the check's rigc binary is, for its header line. */
1118
1266
  checkBin: string;
1119
- /** A directory the rig stage may stage its gate in; emptied before and after. */
1267
+ /** A directory the rig stage may stage its gate in, and the loop its lead-in render after it; emptied before and after each. */
1120
1268
  scratch: string;
1121
1269
  }
1122
1270
 
@@ -1178,7 +1326,7 @@ export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResu
1178
1326
  for (const p of BUILD_OWNS) rmSync(join(out, p), { recursive: true, force: true });
1179
1327
  // The idle-keys value is named only when it is not the default, so a build without the flag, or with the default, prints the line it printed before issue #95.
1180
1328
  const idleKeys = input.idleKeys ?? DEFAULT_IDLE_KEYS;
1181
- log(`rig-parts build: ${input.config} -> ${out}, seam rule ${input.seam}, projection rule ${input.project}, page edges ${input.pageEdges}, pack shape ${input.packShape ?? DEFAULT_PACK_SHAPE}${idleKeys === DEFAULT_IDLE_KEYS ? '' : `, idle keys ${idleKeys}`}${input.loop ? ', with the idle loop' : ''}`);
1329
+ log(`rig-parts build: ${input.config} -> ${out}, seam rule ${input.seam}, projection rule ${input.project}, page edges ${input.pageEdges}, pack shape ${input.packShape ?? DEFAULT_PACK_SHAPE}${idleKeys === DEFAULT_IDLE_KEYS ? '' : `, idle keys ${idleKeys}`}${input.loop ? `, with the idle loop${input.leadIn === undefined ? '' : ` after a lead-in of ${input.leadIn} period(s)`}` : ''}`);
1182
1330
 
1183
1331
  try {
1184
1332
  // build runs rig next, which needs the whole config, so the full loader is
@@ -1215,12 +1363,15 @@ export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResu
1215
1363
  }
1216
1364
 
1217
1365
  if (input.loop) {
1218
- const frames = join(out, 'check', 'idle_frames');
1219
1366
  try {
1220
1367
  const say = prefixed('loop');
1221
- const lossless = loopStage(frames, join(out, 'idle.png'), 'apng', say);
1222
- const indexed = loopStage(frames, join(out, 'idle-indexed.png'), 'indexed', say);
1223
- const gif = loopStage(frames, join(out, 'idle.gif'), 'gif', say);
1368
+ const window = input.leadIn === undefined ? undefined : { periods: input.leadIn };
1369
+ if (window !== undefined) rmSync(run.scratch, { recursive: true, force: true });
1370
+ const frames = window === undefined ? join(out, 'check', 'idle_frames') : leadInFrames(join(out, 'rig'), run.scratch, window.periods, run.check, { pageEdges: input.pageEdges, packShape: input.packShape ?? DEFAULT_PACK_SHAPE });
1371
+ const lossless = loopStage(frames, join(out, 'idle.png'), 'apng', say, window);
1372
+ const indexed = loopStage(frames, join(out, 'idle-indexed.png'), 'indexed', say, window);
1373
+ const gif = loopStage(frames, join(out, 'idle.gif'), 'gif', say, window);
1374
+ if (window !== undefined) rmSync(run.scratch, { recursive: true, force: true });
1224
1375
  const fig = (e: PaletteError | null): string => (e === null ? 'lossless' : `max ${e.max}, mean ${e.mean.toFixed(3)}`);
1225
1376
  say(`loop: idle.png ${lossless.bytes} B (${fig(lossless.error)}); idle-indexed.png ${indexed.bytes} B (${fig(indexed.error)}); idle.gif ${gif.bytes} B (${fig(gif.error)}) — palette error per channel over all frames`);
1226
1377
  } catch (err) {
package/src/parts.ts CHANGED
@@ -40,7 +40,7 @@
40
40
  * cut from, which shares its `from`. The record is in draw order, and a piece
41
41
  * drawn `"back"` comes before its base, so order cannot say which of two parts
42
42
  * sharing a layer is the piece; this field does. A `parts.json` written before
43
- * 1.5.6 has none, and still reads.
43
+ * 1.6.0 has none, and still reads.
44
44
  *
45
45
  * ⭐ **A patch is 100 % source.** Every pixel of a `painting:` part is the
46
46
  * painting's own, so it is all visible (the painting shows it; nothing of it
@@ -81,7 +81,7 @@ export interface PartRecord {
81
81
  /**
82
82
  * Written only on a piece an `assemble.cuts` entry made (issue #230): the
83
83
  * name of the plan part it was cut from, which has the same `from`. Absent
84
- * on every other part, and in a `parts.json` written before 1.5.6.
84
+ * on every other part, and in a `parts.json` written before 1.6.0.
85
85
  */
86
86
  cut_from?: string;
87
87
  x: number;