rig-parts 2.64.0 → 2.65.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/docs/AUTHORING.md CHANGED
@@ -7220,13 +7220,16 @@ and stay absent).
7220
7220
  | <a id="SCENE_ACCEPT_KNOWN"></a>`SCENE_ACCEPT_KNOWN` | an `--accept` name, or one in a character's `accept`, is not a bar `check` holds a build to: a problem code (`CHECK_LOOP_CLOSES`) where the bar's name (`loop`) belongs, a misspelling, or `gate`, which is rig-c's and never accepted | one of the names the message lists |
7221
7221
  | <a id="SCENE_BUILD_FIELD_KNOWN"></a>`SCENE_BUILD_FIELD_KNOWN` | a build's `rig.json` or `motion.json` carries a key compose does not know how to prefix or place, or a root with a transform of its own | a rig `build` wrote; a rig written by something else is `check`'s to measure (§7, *Measuring a rig rig-parts did not assemble*), not compose's to merge |
7222
7222
  | <a id="SCENE_RIG_SCALE_AGREES"></a>`SCENE_RIG_SCALE_AGREES` | the characters' `parts.json` `scale_rig_per_source` differ (each named) | one `assemble.rig_scale` for every character; `characters[].scale` sizes a placed character, it does not make two `rig_scale`s one |
7223
- | <a id="SCENE_SCALE_EXACT"></a>`SCENE_SCALE_EXACT` | a character at a `scale` other than 1 carries something no per-character value can scale: a physics constraint with a nonzero `wind` or `gravity`, or a physics track keying `wind` or `gravity` with a nonzero value (Spine applies both through the skeleton's `referenceScale`, which the composed skeleton holds once for every character), a track whose `property` compose does not know to be a length or not, or a translate key whose `v` is neither a list of numbers nor a map of them | `scale` 1 for that character, or rebuild it at another `assemble.rig_scale` |
7223
+ | <a id="SCENE_SCALE_EXACT"></a>`SCENE_SCALE_EXACT` | a character at a `scale` other than 1 declares a numeric `with_idle` count or carries an input that compose cannot scale exactly. Examples include a physics constraint or track with nonzero `wind` or `gravity` (Spine uses one `referenceScale` for the composed skeleton), a track whose `property` compose does not know how to scale, and a translate key whose `v` is neither a list of numbers nor a map of them | use `scale` 1, or rebuild at another `assemble.rig_scale` to change the built size. To leave a physics-only clip out of the idle, declare `false`. The side clip must still pass the scale checks |
7224
7224
  | <a id="SCENE_DURATION_AGREES"></a>`SCENE_DURATION_AGREES` | with no `idle_repeats`, the characters' idles are of different durations (each named), or `scene.animations.idle.duration` differs from the composed idle | declare the same duration; compose preserves the original key timing |
7225
- | <a id="SCENE_REPEAT_COUNT"></a>`SCENE_REPEAT_COUNT` | a character declares an invalid `idle_repeats` value | declare a safe integer of 2 or more, or omit the field to use one source period |
7225
+ | <a id="SCENE_REPEAT_COUNT"></a>`SCENE_REPEAT_COUNT` | an invalid count in `characters[].idle_repeats`, `characters[].with_idle` or `scene.repeats` | use a safe integer of at least 2 for `idle_repeats` or `scene.repeats`, and a safe integer of at least 1 or literal `false` for `with_idle` |
7226
7226
  | <a id="SCENE_REPEAT_IDLE_REQUIRED"></a>`SCENE_REPEAT_IDLE_REQUIRED` | a character opts in but the scene declares no `animations.idle` | declare the scene idle and its duration |
7227
- | <a id="SCENE_REPEAT_DURATION"></a>`SCENE_REPEAT_DURATION` | in an opted-in scene, the declared idle duration differs from a character's source period times its playback count, including a count of one for a character without `idle_repeats` | use the exact finite, positive product for every character |
7227
+ | <a id="SCENE_REPEAT_DURATION"></a>`SCENE_REPEAT_DURATION` | the declared idle duration disagrees with a character’s source period times its playback count, or `scene.repeats` names a take without a positive authored duration or with animation keys ending off the period clock | use the exact finite, positive product for every character. Declare the whole take duration and make the latest effective scene animation key end exactly at duration divided by the scene repeat count |
7228
+ | <a id="SCENE_PHYSICS_CLIP_DECLARED"></a>`SCENE_PHYSICS_CLIP_DECLARED` | a character’s physics-only clip beside `idle` lacks a declaration. The refusal names the character, clip and distinct keyed constraint count | declare literal `false` in `with_idle` at any scale, or declare a whole-period count at scale 1 |
7229
+ | <a id="SCENE_PHYSICS_CLIP_ONLY"></a>`SCENE_PHYSICS_CLIP_ONLY` | a `with_idle` entry names `idle`, an absent clip, a clip with no physics keys or a clip with other timelines | use the source name of a physics-only clip beside `idle`. This applies to counts and to `false` |
7230
+ | <a id="SCENE_WITH_IDLE_DURATION"></a>`SCENE_WITH_IDLE_DURATION` | a numeric `with_idle` entry implies a duration different from the played idle. The refusal names the clip and the conflicting lengths. The diagnostic searches up to 10,000 copies of each source. Acceptance depends on exact duration equality regardless of that search bound | use the smallest exact pair of whole-period counts when the diagnostic finds one, retime the source clip supplied through `motion.animations_from`, adjust the source idle with `motion.duration`, or declare `false` |
7228
7231
  | <a id="SCENE_REPEAT_SOURCE_LOOP_CLOSES"></a>`SCENE_REPEAT_SOURCE_LOOP_CLOSES` | a repeated source idle has a loop flag other than `true`, or its original gated keyed poses at the start and stored end do not close or cannot be read | use a closed source idle with `loop: true` and correct the named pose channel |
7229
- | <a id="SCENE_REPEAT_KEY_SEAM"></a>`SCENE_REPEAT_KEY_SEAM` | a repeated source timeline cannot be spliced on its effective key clock, for example because of a setup gap, an unequal boundary state or left limit, or a reset at the boundary | author a timeline that starts at effective time zero and closes continuously, with any explicit reset strictly inside the source period and separate on Core's playback clock |
7232
+ | <a id="SCENE_REPEAT_KEY_SEAM"></a>`SCENE_REPEAT_KEY_SEAM` | a repeated source timeline cannot be spliced on its effective key clock, for example because of a setup gap, an unequal boundary state or left limit, a reset at the boundary or a period that collapses on the playback clock. Repeated scene animations also refuse timeline families without a defined splice | author a state timeline that starts at effective time zero and closes continuously, with any explicit reset strictly inside the source period and separate on Core's playback clock |
7230
7233
  | <a id="CE_COMPILE_ANIMATION_GROUP_UNKNOWN"></a>`CE_COMPILE_ANIMATION_GROUP_UNKNOWN` | a scene track names no own declared group, including inherited object names such as `constructor` | name an explicitly declared final group; prototype properties are not groups |
7231
7234
  | <a id="SCENE_ANIMATION_NAME_FREE"></a>`SCENE_ANIMATION_NAME_FREE` | a scene clip name already belongs to an imported character animation | choose a new name; only shared `idle` can be extended |
7232
7235
  | <a id="SCENE_DIAL_RANGE_DECLARED"></a>`SCENE_DIAL_RANGE_DECLARED` | a keyed slider has no readable explicit `from` and `max` bounds, or its bounds are reversed; the bone and slider are named | declare both finite bounds with `from <= max`; no limits are invented |
@@ -7234,8 +7237,8 @@ and stay absent).
7234
7237
  | <a id="SCENE_DIAL_KEY_DECLARED"></a>`SCENE_DIAL_KEY_DECLARED` | a scene key uses `derive` on a slider's input property, including one that also carries a raw `v`; derived slider inputs are not a supported scene dial dialect | declare an explicit numeric `v` for the named dial, within the named slider's own range; group member values are checked separately |
7235
7238
  | <a id="SCENE_ANIMATION_LOOP_CLOSES"></a>`SCENE_ANIMATION_LOOP_CLOSES` | the gated posed values at 0 and the scene clip's declared duration differ with physics omitted, for a new clip or an idle extension (physics-on frames are not measured by this check) | close the posed bone, slot, geometry, alpha, clip and draw-order values with physics omitted; comparison never wraps the endpoint to zero, and physics-on frame closure is not measured here |
7236
7239
  | <a id="SCENE_ANIMATION_POSE_READABLE"></a>`SCENE_ANIMATION_POSE_READABLE` | Core cannot read or pose the compiled scene clip for its endpoint comparison | correct the construct named by Core; unreadable poses never count as closed and no scene is emitted |
7237
- | <a id="SCENE_CAMERA_TRACK"></a>`SCENE_CAMERA_TRACK` | a camera track names an unknown take, has invalid keys or easing, or produces a nonfinite or collapsed view | correct the take name, key times, easing or camera values |
7238
- | <a id="SCENE_CAMERA_LOOP_CLOSES"></a>`SCENE_CAMERA_LOOP_CLOSES` | a looping take's camera pan or zoom differs at the unwrapped endpoints | give its first and last keys the same pan and zoom |
7240
+ | <a id="SCENE_CAMERA_TRACK"></a>`SCENE_CAMERA_TRACK` | a camera track names an unknown take, has invalid keys or easing, ends at the wrong time, or produces a nonfinite or collapsed view | correct the take name, key times, easing or camera values. End the keys exactly at the take duration, or at duration divided by the scene repeat count for a repeated take |
7241
+ | <a id="SCENE_CAMERA_LOOP_CLOSES"></a>`SCENE_CAMERA_LOOP_CLOSES` | a looping or repeated take's camera pan or zoom differs at the unwrapped endpoints of its authored keys | give its first and last keys the same pan and zoom |
7239
7242
  | <a id="SCENE_CAMERA_BACKDROP"></a>`SCENE_CAMERA_BACKDROP` | a camera backdrop does not resolve to its declared, measurable region behind the figures | select a plate that draws its bound region behind the figures throughout the keyed take |
7240
7243
  | <a id="SCENE_CAMERA_PLATE_EDGE"></a>`SCENE_CAMERA_PLATE_EDGE` | the camera view extends past the posed backdrop on the named frame | adjust the camera or plate motion, or extend the plate to cover the required view |
7241
7244
  | <a id="SCENE_CAMERA_PLATE_ALPHA"></a>`SCENE_CAMERA_PLATE_ALPHA` | the posed backdrop admits transparent coverage on the named camera frame | fill the transparent area or move the view into opaque art |
@@ -8072,8 +8075,10 @@ the composed idle under `<out>/check/`, at the viewport used for the shipped fra
8072
8075
  | `characters[].canvas_clip` | optional literal `true` for intentional overflow (issue #1491). The placed part bounds must be finite, extend past at least one canvas edge and overlap the canvas with positive width and height. Omitting the key requires containment, with flush edges allowed. Every explicit value other than `true` is `SCENE_FIELD_TYPE` |
8073
8076
  | `characters[].placement_pivot` | optional literal `true` (issue #1498). Generates an identity `<id>:placement` under `root` and requires a scene-authored `translate`, `translatex` or `translatey` key on it. Every explicit value other than `true` is `SCENE_FIELD_TYPE` |
8074
8077
  | `characters[].idle_repeats` | optional safe integer of 2 or more (issue #1511). Counts total plays of this character's source idle within an explicit `scene.animations.idle`. Its declared duration must equal `idle_repeats * source idle duration` exactly. In the same scene, each character without the key must fill the duration once. In `scene.json`, `characters[].idle_duration` gives the source period, `characters[].idle_repeats` appears on opted-in rows, and top-level `idle_duration` gives the scene period |
8078
+ | `characters[].with_idle` | map from each source physics-only clip beside `idle` to a safe integer of at least 1 or literal `false` (issue #1615). A count requires character scale 1 and folds whole periods into the played idle. `false` leaves that clip out of the idle at any character scale. Both retain the prefixed side clip, which must pass the character's scale checks. See [Physics clips and scene repeats](#physics-clips-and-scene-repeats-issue-1615) |
8075
8079
  | `characters[].accept` | optional, a list of bar names: the bars this character's own check may have failed and still be composed (issue #203). `compose --accept <bar>[,<bar>…]` is the same list for every character; the two are joined, so the command line applies to every character and a character's list adds to it. Each name is one of the bars `check`'s summary names, less the gate — `loop`, `seam`, `BREATH_VISIBLE`, `BLINK_NO_HOLE`, `CHAIN_LAG`, `TIP_OVER_ROOT`, `STILL_REGIONS_DARK`, `TEXTURE_STRETCH`, `ANIMATIONS_DO_NOT_FOLD` (issue #320), `STRESS_OFF_CHAIN` (issue #347), `SEAM_OVER_MOTION` (the body-root bar, issue #686); anything else is `SCENE_ACCEPT_KNOWN`. When `check/check.json` declares `spec: "rig-parts-check/1"`, `compose` reads its `bar_outcomes` for the bars whose outcome status is `FAIL` in the report's order (issue #1373); without that spec it keeps the legacy `barsNotMet` reading. A build is taken when every bar its `check.json` failed is named; its gate red, a declared requirement not PASS, or a bar not named is `SCENE_BUILD_GREEN` as before. **It is for looking, not for shipping:** the `[compose]` line says which failing bars were accepted, `scene.json` records them as the character's `accepted`, the composed rig's own check measures them again and reports them as it finds them, and the run exits 1 even when that check is PASS (a composed rig has no `parts.json`, so the seam and four judgement lines say SKIP there). A list that accepts nothing — every build green — composes to the bytes a scene without one writes |
8076
- | `animations` | optional map by scene clip name, each value a rigc `MotionAnimation` (`duration`, `tracks`, optional `loop`, `note`, and core timeline collections). Names resolve against the final scene without another prefix or unit conversion: `root`, `plate`, declared named plate bones and `<id>:<bone>`, including generated dials. Keying `root` moves the whole scene. A new name adds a clip. `idle` appends tracks and timelines once to the composed idle, preserving character metadata and physics constraints. Its duration must exactly equal the composed idle (`SCENE_DURATION_AGREES`, or `SCENE_REPEAT_DURATION` when a character opts in to repetition). Imported animation names are reserved (`SCENE_ANIMATION_NAME_FREE`). Absent declaration preserves legacy bytes and output paths (issue #1346) |
8080
+ | `animations` | optional map by scene clip name, each value a rigc `MotionAnimation` (`duration`, `tracks`, optional `loop`, `note`, and core timeline collections). Names resolve against the final scene without another prefix or unit conversion: `root`, `plate`, declared named plate bones and `<id>:<bone>`, including generated dials. Keying `root` moves the whole scene. A new name adds a clip. `idle` appends the resulting tracks and timelines to the composed idle, preserving character metadata and physics constraints. Its duration must exactly equal the composed idle (`SCENE_DURATION_AGREES`, or `SCENE_REPEAT_DURATION` when a character opts in to repetition). Imported animation names are reserved (`SCENE_ANIMATION_NAME_FREE`). See `repeats` for period-authored tracks and deforms |
8081
+ | `repeats` | optional map from authored take names to safe integers of at least 2 (issue #1615). Repeats the scene-authored tracks, deforms and camera keys on a single period clock. `animations.<take>.duration` is the whole take duration. See [Physics clips and scene repeats](#physics-clips-and-scene-repeats-issue-1615) |
8077
8082
  | `camera` | optional keyed view over composed animation names. See [Keyed scene camera](#keyed-scene-camera-issue-1596) for the camera clock, coverage requirements and opt-in report version |
8078
8083
  | `order` | the draw order, back to front: a character id (its slots not named elsewhere, in its own order) or one `<id>:<slot>`. Every slot of every character is drawn exactly once. Interleaving is written by naming slots: `["a", "b:arm_l", "b"]` draws `b`'s left arm between `a` and the rest of `b` |
8079
8084
 
@@ -8242,9 +8247,9 @@ What is composed:
8242
8247
  declares it.
8243
8248
  - **Every animation beside a character's idle** — what `motion.animations_from`
8244
8249
  wrote into its `motion.json` (§3) — rides along as `<id>:<name>` after the idle,
8245
- its tracks' bones, groups, physics constraints and easings prefixed as the idle's are and every other
8246
- value as written; the scene schedules none of them, they are the consumer's to
8247
- play. Each is read with the idle's own key lists, so a key compose does not know
8250
+ with its tracks' names prefixed and its length retained. A numeric `with_idle`
8251
+ declaration also folds that physics-only clip into the played idle. Each side
8252
+ clip is read with the idle's own key lists, so a key compose does not know
8248
8253
  how to prefix is `SCENE_BUILD_FIELD_KNOWN`, as it is on the idle, and a track of
8249
8254
  one that keys `root` is `SCENE_ROOT_SHARED` (issues #183, #1485).
8250
8255
  - **Turn producer output** (issue #1344) is admitted explicitly: yaw/pitch
@@ -8394,6 +8399,111 @@ Both files must remain under `check/idle_frames/` for readers to verify the
8394
8399
  seam evidence after the run. This refusal clears `rig/`, `check/`, `scene.json` and
8395
8400
  `compose-run.json` under `--out` before the gate.
8396
8401
 
8402
+ #### Physics clips and scene repeats (issue #1615)
8403
+
8404
+ A physics-only side clip typically enters a character build through
8405
+ `motion.animations_from`. It has at least one track, every track targets a
8406
+ physics constraint alone, and it has no other populated timeline collections.
8407
+ Declare each such clip by its source name in `characters[].with_idle`. A count
8408
+ copies that many whole periods into the composed `idle` with the character's
8409
+ prefix. Literal `false` plays the idle without that clip. The standalone
8410
+ `<id>:<clip>` ships in either case, and the character's row in `scene.json`
8411
+ echoes the declaration. A single-animation player plays the folded keys by
8412
+ selecting `idle`.
8413
+
8414
+ Literal `false` is accepted at any character scale. The side clip still passes
8415
+ through the character's scale checks, which refuse nonzero `wind` or `gravity`
8416
+ at scales other than 1. A numeric declaration requires character scale 1 and
8417
+ an exact match between the source clip period times its count and the played
8418
+ idle duration. A count of 1 can fold an equal-duration clip without authoring
8419
+ `scene.animations.idle`.
8420
+ Use `idle_repeats` and an explicit scene idle duration when the character idle
8421
+ also needs to fill multiple periods. The counts for the idle and the physics
8422
+ clip may differ as long as their products agree exactly.
8423
+
8424
+ Set `scene.repeats.<take>` to author the scene animation and any camera track
8425
+ for that take over a shared period. Give `scene.animations.<take>.duration`
8426
+ the positive whole take length and divide it by the scene repeat count to get
8427
+ the authored period. The latest effective animation key across tracks and
8428
+ deforms, if present, and the final camera key, if present, must end exactly
8429
+ there. A state channel that has already closed may hold to the splice.
8430
+ The splice repeats tracks and deforms. Populated `ik`, `transform`,
8431
+ `sequence`, `drawOrder` and `events` collections are refused. A repeated camera
8432
+ must close on its authored period even for a non-looping take.
8433
+
8434
+ The splice requires the held end key state to equal the start state and
8435
+ checks the left limit at the boundary. It shares equivalent boundary keys,
8436
+ offsets absolute curve times and keeps resets strictly inside each physics
8437
+ period. Compose's pose loop check omits physics. The splice checks keyed
8438
+ physics inputs, while Core's render loop-seam measurement reads the resulting
8439
+ physics-on frames.
8440
+
8441
+ On a frame-aligned tiled camera with a backdrop that follows the same period,
8442
+ `pan`, `zoom`, `view` and `backdrop_quad` repeat at the same phase. The player's
8443
+ coverage guard compares the view with the backdrop quad, so the repeated rows
8444
+ yield the same guard verdict. `figures` contains bounds measured from each
8445
+ frame's pose, with physics stepping through the whole take.
8446
+
8447
+ ##### Compose the generated fixture
8448
+
8449
+ From the repository root, generate the fixture, compose its tiled scene and
8450
+ single-period reference, then render only `idle` with Core 3.11.0.
8451
+
8452
+ ```sh
8453
+ bun fixtures/scene.ts scratch/fixture
8454
+ bun cli.ts compose --scene scratch/fixture/scene.json --out scratch/folded
8455
+ bun cli.ts compose --scene scratch/fixture/period.json --out scratch/period
8456
+ bunx --no-install rigc render --candidate scratch/folded/check/build --animation idle --fps 12 --loop-seam --out scratch/physics-on
8457
+ bunx --no-install rigc render --candidate scratch/folded/check/build --animation idle --fps 12 --physics off --out scratch/physics-off
8458
+ ```
8459
+
8460
+ Both compose runs reported `PASS` on Linux. In
8461
+ `scratch/folded/rig/motion.json`, the 3 s `idle` contains `wind` and `mix`
8462
+ tracks targeting `figure:hem_spring`, with five keys each from 0 to 3 s.
8463
+ The prefixed side clip is retained. Select `idle` when opening the packed
8464
+ model in a single-animation player.
8465
+
8466
+ Core's `loop-seam.json` records an unjudged seam at warmup 0, with 183
8467
+ differing pixels and a maximum RGBA channel delta of 95. At 0.75 s, the
8468
+ 256 × 204 `f0009.png` differs by 253 pixels between the physics-on and
8469
+ physics-off renders, with a maximum RGBA channel delta of 128. To compare
8470
+ the two frames, use the frame-set directory named in each `frames.json`.
8471
+
8472
+ ```sh
8473
+ bun - <<'TS'
8474
+ import { readPng } from './src/raster/png.ts';
8475
+
8476
+ async function frame(root: string) {
8477
+ const { sets } = await Bun.file(`${root}/frames.json`).json();
8478
+ return readPng(`${root}/${sets[0].dir}/f0009.png`);
8479
+ }
8480
+
8481
+ const on = await frame('scratch/physics-on');
8482
+ const off = await frame('scratch/physics-off');
8483
+ if (on.width !== off.width || on.height !== off.height) {
8484
+ throw new Error('Frame dimensions differ');
8485
+ }
8486
+ let pixels = 0;
8487
+ let maxDelta = 0;
8488
+ for (let i = 0; i < on.data.length; i += 4) {
8489
+ let pixelDelta = 0;
8490
+ for (let channel = 0; channel < 4; channel++) {
8491
+ pixelDelta = Math.max(pixelDelta, Math.abs(on.data[i + channel] - off.data[i + channel]));
8492
+ }
8493
+ if (pixelDelta > 0) pixels++;
8494
+ maxDelta = Math.max(maxDelta, pixelDelta);
8495
+ }
8496
+ console.log({ width: on.width, height: on.height, pixels, maxDelta });
8497
+ TS
8498
+ ```
8499
+
8500
+ The `scene.json` reports contain 13 period rows and 37 tiled rows in
8501
+ `camera.tracks.idle.frames`. Comparing each tiled row with its period phase
8502
+ (the terminal row uses the period endpoint) found zero mismatches in `pan`,
8503
+ `zoom`, `view` and `backdrop_quad`, with the same coverage guard verdict.
8504
+ Figure rows differed from the reference phase on 36 of 37 frames, with
8505
+ zero outside the view.
8506
+
8397
8507
  #### Keyed scene camera (issue #1596)
8398
8508
 
8399
8509
  A camera projects an already posed scene into the fixed canvas. It follows the
@@ -8418,7 +8528,8 @@ The example object is the value of `camera`. `backdrop` names one scene plate
8418
8528
  behind the characters. A track names a final composed animation, including
8419
8529
  `idle` or a prefixed clip. A take without a track uses the existing view.
8420
8530
  Times are seconds, strictly increasing from zero through the declared
8421
- duration. Pan offsets the view center from the stage center in canvas pixels,
8531
+ duration. For a take listed in `scene.repeats`, author the camera through
8532
+ duration divided by its repeat count. Pan offsets the view center from the stage center in canvas pixels,
8422
8533
  with positive X right and positive Y down. Zoom is positive and finite.
8423
8534
  Zoom 1 shows a stage-sized window. Zoom 2 halves its visible width and height
8424
8535
  about the panned center. The first and last pan and zoom must agree on a
package/docs/STABILITY.md CHANGED
@@ -1198,6 +1198,7 @@ execution in historical evidence is inferred from a current export.
1198
1198
  | compose output profiles | `compose` | Issue #1610 adds `--no-extremes` to omit only the extremes diagnostic renders, and `--output-profile preview` to also omit `check/idle_frames/`, `check/contact.png` and `check/motion_heat.png`. Preview takes precedence when both flags are given. Preview uses the stock idle render and existing readers. Before preview success, Parts removes the idle render directory, including Core's temporary contact sheet, skips copying the sheet to the check root, and skips generating heat. Each omission has a diagnostic `SKIP` line naming its selected flag. The gate, camera binding and check requirements still apply. Success prints `compose: PREVIEW — checks met; …` or `compose: NO EXTREMES — checks met; …`, respectively, and writes `output_profile` as `"preview"` or `"no-extremes"`. Default compose keeps its existing file bytes (with the nested Core receipt clock comparison described above), output paths and `compose: PASS — …` line. `COMPOSE_PREVIEW_REQUIRED_CHECK` refuses a valid loop seam pair in preview with `found=preview, required=default or no-extremes`, because the `loop_seam` record in `check.json` binds the paths and hashes of first and wrap PNGs that must remain under `check/idle_frames/`. Compose clears its owned outputs before this refusal. See [Compose output profiles](AUTHORING.md#compose-output-profiles-issue-1610). |
1199
1199
  | 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`); `pack_mode` records `page_size` only when `--page-size <px>` is given (issue #1352, additive; without `--page-size`, rigc's default 2048 px page and padding 2 on each side bound any plate or region side to at most 2044 px before `CE_ATLAS_REGION_EXCEEDS_PAGE`) |
1200
1200
  | keyed scene camera | `compose` | optional `camera` in `spine-parts-scene/1` (issue #1596). A camera scene writes `spine-parts-scene-report/2` at the existing `scene.json` path with its keyed camera, sampled coverage and framing verdict, and packed model SHA-256. Report /1 and the existing output inventory and bytes are preserved for scenes without a camera, subject to the existing Core receipt clocks. The camera path uses Core animation easing and the posed backdrop at each sampled frame. Rig, motion and stock check outputs retain their existing semantics. The compose input receipt stays `rig-compose-run/1`. See [Keyed scene camera](AUTHORING.md#keyed-scene-camera-issue-1596) |
1201
+ | physics clips and scene repeats | `compose` | Issue #1615 adds `characters[].with_idle` and top-level `repeats` to `spine-parts-scene/1`. Each physics-only side clip requires literal `false` at any character scale or a safe integer count of at least 1 at scale 1. Numeric declarations fold whole periods into `idle` with exact duration equality. Both values retain `<id>:<clip>` subject to the character's scale checks, and the character report row echoes `with_idle` when declared. A scene repeat count is a safe integer of at least 2 on an authored take. Its duration remains the whole take length. Its tracks, deforms and camera keys use the exact duration divided by the count as their period. Repeated camera keys are expanded in report /2, with coverage on the full take clock and per-frame figure measurements. See [Physics clips and scene repeats](AUTHORING.md#physics-clips-and-scene-repeats-issue-1615) |
1201
1202
  | `idle.png`, `idle-indexed.png`, `idle.gif` | `loop`, `build --loop` | APNG and GIF encodings of the rendered idle |
1202
1203
  | `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), `inputs` on `assemble` (issues #1316, #1554, additive: one `{role, path, sha256}` entry for each of `--source`, `--full` and `--head` that was given, in that order, with `path` relative to `--out` by the per-platform link rule — naming `<dir>/layers.json` when given a directory — and `sha256` of the file `path` names), 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 |
1203
1204
  | 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 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-parts",
3
- "version": "2.64.0",
3
+ "version": "2.65.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
  "exports": {
package/src/scene.ts CHANGED
@@ -82,6 +82,9 @@
82
82
  * `generated`, `unknown`) is copied into `scene.json` and nothing reads it.
83
83
  * - **The idle**: one `idle` holding every character's tracks. It can play
84
84
  * whole source periods per character when the scene declares `idle_repeats`.
85
+ * A physics-only clip needs a `with_idle` count at scale 1 or an explicit
86
+ * `false` at any scale that the character supports.
87
+ * `scene.repeats` splices scene-authored animation and camera keys.
85
88
  * - **A failing bar, by name (issue #203).** A build whose own check is not
86
89
  * green is refused (`SCENE_BUILD_GREEN`) unless every bar it failed is named
87
90
  * in `compose --accept` or the character's `accept` — the two lists are
@@ -123,8 +126,8 @@ import { clearComposeRun, COMPOSE_RUN_FILE, COMPOSE_RUN_SPEC, type ComposeRun, t
123
126
  import { readRequirements, type RequirementsFile } from './requirements.ts';
124
127
  import { OFFSET_PLACES, rigJsonText, type RigSpec } from './rig.ts';
125
128
  import { pyRound } from './round.ts';
126
- import { mergeSceneAnimations, readSceneAnimations, readSceneCamera, resolveSceneCamera, sceneBoneContext, sceneClipLoopProblems, sceneRepeatSourceLoopProblems, type ResolvedSceneCamera, type ResolvedSceneCameraTrack, type SceneAnimations, type SceneCamera, type SceneCameraSample, type ScenePlacementPivot } from './sceneclips.ts';
127
- import { repeatSceneKeys } from './scenerepeat.ts';
129
+ import { mergeSceneAnimations, readSceneAnimations, readSceneCamera, repeatSceneAnimations, resolveSceneCamera, sceneBoneContext, sceneClipLoopProblems, sceneRepeatCurveProblems, sceneRepeatSourceLoopProblems, type ResolvedSceneCamera, type ResolvedSceneCameraTrack, type SceneAnimations, type SceneCamera, type SceneCameraSample, type ScenePlacementPivot } from './sceneclips.ts';
130
+ import { repeatSceneKeys, type SceneRepeatSeam } from './scenerepeat.ts';
128
131
 
129
132
  /** The scene file's `spec`. */
130
133
  export const SCENE_SPEC = 'spine-parts-scene/1';
@@ -183,6 +186,8 @@ export interface SceneCharacter {
183
186
  placement_pivot?: true;
184
187
  /** Total number of source idle periods within the declared scene idle. */
185
188
  idle_repeats?: number;
189
+ /** Physics-only clips carried into idle by whole periods, or explicitly left beside it. */
190
+ with_idle?: Record<string, number | false>;
186
191
  /** The bars this character's own check may have failed and still be taken (issue #203), as the file lists them; empty when it lists none. */
187
192
  accept: string[];
188
193
  }
@@ -215,6 +220,7 @@ export interface SceneFile {
215
220
  plate: ScenePlate | null;
216
221
  plates?: NamedScenePlate[];
217
222
  animations?: SceneAnimations;
223
+ repeats?: Record<string, number>;
218
224
  camera?: SceneCamera;
219
225
  characters: SceneCharacter[];
220
226
  order: string[];
@@ -300,7 +306,9 @@ export function loadScene(path: string): SceneFile {
300
306
  if (!keys.includes(k) && !freeKey(k, v)) fail('SCENE_KEY_KNOWN', `${where}.${k}`, `is a key ${SCENE_SPEC} does not read; it reads ${keys.join(', ')} (and "note", "…_note" strings and "x-…" records, which nothing reads)`);
301
307
  }
302
308
  };
303
- known(fields, 'scene', ['spec', 'canvas', 'plate', 'plates', 'characters', 'order', 'animations']);
309
+ const sceneKeys = ['spec', 'canvas', 'plate', 'plates', 'characters', 'order', 'animations'];
310
+ if ('repeats' in o) sceneKeys.push('repeats');
311
+ known(fields, 'scene', sceneKeys);
304
312
  if (o.spec !== SCENE_SPEC) fail('SCENE_SPEC', 'scene.spec', `is ${show(o.spec)}; "${SCENE_SPEC}" is required`);
305
313
 
306
314
  // canvas
@@ -388,6 +396,7 @@ export function loadScene(path: string): SceneFile {
388
396
  const keys = ['id', 'build', 'offset', 'scale', 'accept', 'canvas_clip'];
389
397
  if ('placement_pivot' in c) keys.push('placement_pivot'); // Keep the default unknown-key diagnostic byte-stable.
390
398
  if ('idle_repeats' in c) keys.push('idle_repeats');
399
+ if ('with_idle' in c) keys.push('with_idle');
391
400
  known(c, where, keys);
392
401
  let ok = true;
393
402
  for (const k of ['id', 'build', 'offset']) {
@@ -439,6 +448,23 @@ export function loadScene(path: string): SceneFile {
439
448
  fail('SCENE_REPEAT_COUNT', `${where}.idle_repeats`, `is ${show(repeats)}. Declare a safe integer of 2 or more, or omit the field to use one source period`);
440
449
  ok = false;
441
450
  }
451
+ let withIdle: SceneCharacter['with_idle'];
452
+ if ('with_idle' in c) {
453
+ if (!isRecord(c.with_idle)) {
454
+ fail('SCENE_FIELD_TYPE', `${where}.with_idle`, `is ${show(c.with_idle)}. An object mapping physics-only clip names to repeat counts or false is required`);
455
+ ok = false;
456
+ } else {
457
+ const entries: Array<[string, number | false]> = [];
458
+ for (const [clip, count] of Object.entries(c.with_idle)) {
459
+ if (count === false || (typeof count === 'number' && Number.isSafeInteger(count) && count >= 1)) entries.push([clip, count]);
460
+ else {
461
+ fail('SCENE_REPEAT_COUNT', `${where}.with_idle[${show(clip)}]`, `is ${show(count)}. A safe integer of 1 or more, or false, is required`);
462
+ ok = false;
463
+ }
464
+ }
465
+ withIdle = Object.fromEntries(entries);
466
+ }
467
+ }
442
468
  const acc = c.accept;
443
469
  if ('accept' in c) {
444
470
  if (!(Array.isArray(acc) && acc.every((v) => typeof v === 'string'))) {
@@ -460,6 +486,7 @@ export function loadScene(path: string): SceneFile {
460
486
  ...(c.canvas_clip === true ? { canvas_clip: true } : {}),
461
487
  ...(c.placement_pivot === true ? { placement_pivot: true } : {}),
462
488
  ...(typeof repeats === 'number' ? { idle_repeats: repeats } : {}),
489
+ ...(withIdle === undefined ? {} : { with_idle: withIdle }),
463
490
  });
464
491
  });
465
492
  }
@@ -490,13 +517,26 @@ export function loadScene(path: string): SceneFile {
490
517
  problems.push(...err.problems);
491
518
  }
492
519
  }
520
+ let repeats: SceneFile['repeats'];
521
+ if ('repeats' in o) {
522
+ if (!isRecord(o.repeats)) fail('SCENE_FIELD_TYPE', 'scene.repeats', `is ${show(o.repeats)}. An object mapping take names to repeat counts is required`);
523
+ else {
524
+ const entries: Array<[string, number]> = [];
525
+ for (const [take, count] of Object.entries(o.repeats)) {
526
+ if (typeof count === 'number' && Number.isSafeInteger(count) && count >= 2) entries.push([take, count]);
527
+ else fail('SCENE_REPEAT_COUNT', `scene.repeats[${show(take)}]`, `is ${show(count)}. A safe integer of 2 or more is required`);
528
+ }
529
+ repeats = Object.fromEntries(entries);
530
+ }
531
+ }
493
532
  if (!(isRecord(o.animations) && Object.hasOwn(o.animations, 'idle'))) {
494
533
  for (const c of characters) if (c.idle_repeats !== undefined) {
495
534
  fail('SCENE_REPEAT_IDLE_REQUIRED', 'scene.animations.idle', `is absent for character ${show(c.id)} with idle_repeats ${c.idle_repeats}. Declare the scene idle and its duration`);
496
535
  }
497
536
  }
498
537
  refuseIfAny(problems);
499
- return { path: at, sha256, canvas, plate, ...('plates' in o ? { plates } : {}), ...(animations === undefined ? {} : { animations }), ...(camera === undefined ? {} : { camera }), characters, order };
538
+ return { path: at, sha256, canvas, plate, ...('plates' in o ? { plates } : {}), ...(animations === undefined ? {} : { animations }),
539
+ ...(repeats === undefined ? {} : { repeats }), ...(camera === undefined ? {} : { camera }), characters, order };
500
540
  }
501
541
 
502
542
  // ---------------------------------------------------------------------------
@@ -549,6 +589,45 @@ function animationsOf(motion: MotionSpec): Record<string, SceneAnimation> {
549
589
  return motion.animations as unknown as Record<string, SceneAnimation>;
550
590
  }
551
591
 
592
+ function physicsClipTargets(clip: SceneAnimation): ReadonlySet<string> | undefined {
593
+ if (clip.tracks.length === 0 || Object.entries(clip).some(([key, value]) =>
594
+ !['duration', 'loop', 'note', 'tracks'].includes(key) && value !== undefined && !(Array.isArray(value) && value.length === 0))) return undefined;
595
+ const targets = new Set<string>();
596
+ for (const track of clip.tracks) {
597
+ if (typeof track.physics !== 'string' || track.physics === '' ||
598
+ ['bone', 'group', 'slot', 'path', 'slider'].some(key => Object.hasOwn(track, key))) return undefined;
599
+ targets.add(track.physics);
600
+ }
601
+ return targets;
602
+ }
603
+
604
+ /** Maximum copies of each source searched for a diagnostic hint. Acceptance compares the declared counts directly. */
605
+ const WITH_IDLE_DIAGNOSTIC_COPY_LIMIT = 10_000;
606
+
607
+ function compareRepeatDurations(left: number, right: number): -1 | 0 | 1 {
608
+ return left === right ? 0 : left < right ? -1 : 1;
609
+ }
610
+
611
+ function idleRepeatAdvice(idlePeriod: number, clipPeriod: number): string {
612
+ if (Number.isFinite(idlePeriod) && idlePeriod > 0 && Number.isFinite(clipPeriod) && clipPeriod > 0) {
613
+ let idleCount = 1;
614
+ let clipCount = 1;
615
+ while (idleCount <= WITH_IDLE_DIAGNOSTIC_COPY_LIMIT && clipCount <= WITH_IDLE_DIAGNOSTIC_COPY_LIMIT) {
616
+ const idleDuration = idleCount * idlePeriod;
617
+ const clipDuration = clipCount * clipPeriod;
618
+ if (!Number.isFinite(idleDuration) || !Number.isFinite(clipDuration)) break;
619
+ // Only the smaller product can catch the other, so the first match has the least idle count and then clip count.
620
+ const order = compareRepeatDurations(idleDuration, clipDuration);
621
+ if (order === 0) return `Smallest exact counts: idle ${idleCount}, clip ${clipCount} (${idleDuration} s).`;
622
+ if (order < 0) idleCount++;
623
+ else clipCount++;
624
+ }
625
+ }
626
+ const limit = String(WITH_IDLE_DIAGNOSTIC_COPY_LIMIT).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
627
+ return `No pair within ${limit} copies of each for source idle ${idlePeriod} s and source clip ${clipPeriod} s. ` +
628
+ 'Retime the clip at its source in motion.animations_from, change the source idle\'s motion.duration, or declare false.';
629
+ }
630
+
552
631
  function readJson(path: string, what: string, problems: Problem[], consumed: (bytes: Uint8Array) => void): unknown {
553
632
  if (!existsSync(path)) {
554
633
  problems.push({ code: 'SCENE_BUILD_PRESENT', object: path, detail: `no such file; ${what}` });
@@ -1296,6 +1375,7 @@ export interface SceneCharacterReport {
1296
1375
  constraints: number;
1297
1376
  idle_duration: number;
1298
1377
  idle_repeats?: number;
1378
+ with_idle?: Record<string, number | false>;
1299
1379
  /** The bars the character's own check failed that `--accept` or its `accept` took (issue #203); written only when there are any, so a scene of green builds writes the bytes it wrote before the field existed. */
1300
1380
  accepted?: string[];
1301
1381
  }
@@ -1327,6 +1407,8 @@ export interface ComposedScene {
1327
1407
  report: SceneReport;
1328
1408
  /** Opt-in declaration retained for pre-emission pose measurement; never serialized. */
1329
1409
  sceneAnimations?: SceneAnimations;
1410
+ /** Compiled timeline addresses checked at the final gate; never serialized. */
1411
+ repeatSeams: SceneRepeatSeam[];
1330
1412
  sceneCamera?: ResolvedSceneCamera;
1331
1413
  }
1332
1414
 
@@ -1406,6 +1488,11 @@ function measureSceneCamera(build: string, composed: ComposedScene, camera: Reso
1406
1488
  // Keep authored ticks exact, including keys on that grid. Both the camera
1407
1489
  // and the packed pose read the same phase at their own clock precision.
1408
1490
  const times = authoredTimes.map(time => time === track.duration ? compiledDuration : time / track.duration * compiledDuration);
1491
+ const { period } = track;
1492
+ const periodTicks = period === undefined ? 0 : Math.round(period * IDLE_FPS);
1493
+ const totalTicks = Math.round(track.duration * IDLE_FPS);
1494
+ const samplePeriod = periodTicks > 0 && periodTicks / IDLE_FPS === period && totalTicks / IDLE_FPS === track.duration &&
1495
+ totalTicks % periodTicks === 0 ? track.samplePeriod : undefined;
1409
1496
  const frames: CameraFrameReport[] = [];
1410
1497
  // The track remains unwrapped through the closing pose, with one
1411
1498
  // physics clock stepping the entire schedule, including a short end step.
@@ -1415,7 +1502,12 @@ function measureSceneCamera(build: string, composed: ComposedScene, camera: Reso
1415
1502
  object = `${field} frame ${index} (t=${time} s, authored ${authored} s)`;
1416
1503
  const fail = (code: string, detail: string): void => { problems.push({ code, object, detail }); };
1417
1504
  let sample: SceneCameraSample;
1418
- try { sample = track.sample(authored); }
1505
+ try {
1506
+ // The player still reads the global i/fps grid. Exact frame phase
1507
+ // avoids subtracting two rounded global times on each tiled copy.
1508
+ sample = samplePeriod === undefined ? track.sample(authored) :
1509
+ samplePeriod(index === times.length - 1 ? periodTicks / IDLE_FPS : (index % periodTicks) / IDLE_FPS);
1510
+ }
1419
1511
  catch (err) {
1420
1512
  if (!(err instanceof PartsError)) throw err;
1421
1513
  for (const problem of err.problems) fail(problem.code, problem.detail);
@@ -1599,6 +1691,10 @@ export function composeScene(
1599
1691
  const hasRepeats = scene.characters.some(c => c.idle_repeats !== undefined);
1600
1692
  const clip = scene.animations?.idle;
1601
1693
  const idleDuration = hasRepeats ? clip?.duration ?? 0 : durations[0];
1694
+ const sceneIdleRepeat = scene.repeats !== undefined && Object.hasOwn(scene.repeats, 'idle') ? scene.repeats.idle : undefined;
1695
+ const sceneIdleClock = sceneIdleRepeat === undefined ? 'scene.animations.idle.duration' : `scene.animations.idle.duration for scene.repeats["idle"]: ${sceneIdleRepeat}`;
1696
+ const idleClockFields: string[] = [];
1697
+ const importedIdleMismatches: Array<{ field: string; found: number; problem: Problem }> = [];
1602
1698
  if (hasRepeats) scene.characters.forEach((c, i) => {
1603
1699
  if (clip === undefined) {
1604
1700
  if (c.idle_repeats !== undefined) fail('SCENE_REPEAT_IDLE_REQUIRED', 'scene.animations.idle', `is absent for character ${show(c.id)} with idle_repeats ${c.idle_repeats}. Declare the scene idle and its duration`);
@@ -1608,8 +1704,13 @@ export function composeScene(
1608
1704
  if (idle === undefined) return;
1609
1705
  const count = c.idle_repeats ?? 1;
1610
1706
  const period = idle.duration;
1611
- if (!Number.isFinite(period) || period <= 0 || !Number.isFinite(idleDuration) || idleDuration <= 0 || idleDuration !== count * period) {
1612
- fail('SCENE_REPEAT_DURATION', 'scene.animations.idle.duration', `is ${idleDuration} s for character ${show(c.id)}. Its ${period} s idle repeated ${count} times requires exactly ${count * period} s (tolerance 0 s)`);
1707
+ const field = `scene.characters[${i}].idle_repeats`;
1708
+ if (c.idle_repeats !== undefined) idleClockFields.push(`${field} for character ${show(c.id)} implies ${count * period} s (${count} × ${period} s)`);
1709
+ if (!Number.isFinite(period) || period <= 0 || !Number.isFinite(idleDuration) || idleDuration <= 0 || compareRepeatDurations(idleDuration, count * period) !== 0) {
1710
+ const problem = { code: 'SCENE_REPEAT_DURATION', object: 'scene.animations.idle.duration',
1711
+ detail: `is ${idleDuration} s for character ${show(c.id)}. Its ${period} s idle repeated ${count} times requires exactly ${count * period} s (tolerance 0 s)` };
1712
+ problems.push(problem);
1713
+ importedIdleMismatches.push({ field, found: count * period, problem });
1613
1714
  }
1614
1715
  if (c.idle_repeats !== undefined && idle.loop !== true) {
1615
1716
  fail('SCENE_REPEAT_SOURCE_LOOP_CLOSES', `scene.characters[${i}] motion.json animations.idle`, `loop is ${show(idle.loop)}; repeating requires a closed source idle with loop: true`);
@@ -1619,6 +1720,61 @@ export function composeScene(
1619
1720
  fail('SCENE_DURATION_AGREES', 'scene.characters', `have idles of ${ready.map((b, i) => `"${b.id}" ${durations[i]} s`).join(', ')}; one idle holds every character's tracks, so one duration is required — rebuild with one motion.duration`);
1620
1721
  }
1621
1722
 
1723
+ const foldedClips = new Map<string, Map<string, SceneAnimation>>();
1724
+ const withIdleClockFields: string[] = [];
1725
+ for (const [i, c] of scene.characters.entries()) {
1726
+ const character = `scene.characters[${i}]`;
1727
+ const declarations = c.with_idle ?? {};
1728
+ if (c.scale !== 1 && Object.values(declarations).some(count => typeof count === 'number')) {
1729
+ fail('SCENE_SCALE_EXACT', `${character}.with_idle`, `character ${show(c.id)} has scale ${c.scale}. with_idle applies at scale 1 only`);
1730
+ }
1731
+ const b = byId.get(c.id);
1732
+ if (b === undefined) continue;
1733
+ const animations = animationsOf(b.motion);
1734
+ const clips = new Map<string, SceneAnimation>();
1735
+ for (const [name, source] of Object.entries(animations)) {
1736
+ if (name === 'idle') continue;
1737
+ const targets = physicsClipTargets(source);
1738
+ if (targets !== undefined && !Object.hasOwn(declarations, name)) {
1739
+ const count = targets.size;
1740
+ const advice = c.scale === 1
1741
+ ? 'Declare its whole-period repeat count to carry it into idle or false to play idle without it'
1742
+ : `At scale ${c.scale}, declare false to play idle without it. A repeat count applies at scale 1 only`;
1743
+ fail('SCENE_PHYSICS_CLIP_DECLARED', `${character}.with_idle[${JSON.stringify(name)}]`,
1744
+ `character ${show(c.id)} carries physics-only clip ${show(name)} keying ${count} physics constraint${count === 1 ? '' : 's'}. ${advice}`);
1745
+ }
1746
+ }
1747
+ for (const [name, count] of Object.entries(declarations)) {
1748
+ const object = `${character}.with_idle[${JSON.stringify(name)}]`;
1749
+ const source = name !== 'idle' && Object.hasOwn(animations, name) ? animations[name] : undefined;
1750
+ if (source === undefined || physicsClipTargets(source) === undefined) {
1751
+ fail('SCENE_PHYSICS_CLIP_ONLY', object, `character ${show(c.id)} ${source === undefined ? 'has no clip beside idle named' : 'has a clip with other timelines or no physics keys named'} ${show(name)}. Name a clip beside idle with only physics-constraint tracks`);
1752
+ continue;
1753
+ }
1754
+ if (count === false || c.scale !== 1) continue;
1755
+ const period = source.duration;
1756
+ const foldedDuration = count * period;
1757
+ if (Number.isFinite(foldedDuration)) withIdleClockFields.push(`${object} for character ${show(c.id)} implies ${foldedDuration} s (${count} × ${period} s)`);
1758
+ const sourceIdle = animations.idle.duration;
1759
+ if (!Number.isFinite(foldedDuration) || foldedDuration <= 0 || compareRepeatDurations(idleDuration, foldedDuration) !== 0) {
1760
+ const idleField = c.idle_repeats === undefined ? `character ${show(c.id)}'s source idle` : `${character}.idle_repeats: ${c.idle_repeats} (implies ${c.idle_repeats * sourceIdle} s)`;
1761
+ const sceneField = clip === undefined ? '' : ` ${sceneIdleClock} declares ${clip.duration} s.`;
1762
+ fail('SCENE_WITH_IDLE_DURATION', object, `character ${show(c.id)} clip ${show(name)} at ${count} × ${period} s implies ${foldedDuration} s. The played idle is ${idleDuration} s with ${idleField}.${sceneField} ${idleRepeatAdvice(sourceIdle, period)}`);
1763
+ continue;
1764
+ }
1765
+ clips.set(name, source);
1766
+ }
1767
+ foldedClips.set(c.id, clips);
1768
+ }
1769
+ for (const mismatch of importedIdleMismatches) {
1770
+ const opts = [
1771
+ ...(sceneIdleRepeat === undefined ? [] : [`${sceneIdleClock} declares ${idleDuration} s`]),
1772
+ ...withIdleClockFields,
1773
+ ];
1774
+ if (opts.length > 0) mismatch.problem.detail += `. ${mismatch.field} implies ${mismatch.found} s. ${opts.join('. ')}.`;
1775
+ }
1776
+ idleClockFields.push(...withIdleClockFields);
1777
+
1622
1778
  // ---- placed bounds --------------------------------------------------------
1623
1779
  const rows: SceneCharacterReport[] = [];
1624
1780
  scene.characters.forEach((c, i) => {
@@ -1679,6 +1835,7 @@ export function composeScene(
1679
1835
  constraints: b.rig.constraints?.length ?? 0,
1680
1836
  idle_duration: b.motion.animations.idle.duration,
1681
1837
  ...(c.idle_repeats === undefined ? {} : { idle_repeats: c.idle_repeats }),
1838
+ ...(c.with_idle === undefined ? {} : { with_idle: { ...c.with_idle } }),
1682
1839
  ...(b.accepted.length === 0 ? {} : { accepted: [...b.accepted] }),
1683
1840
  });
1684
1841
  });
@@ -2083,8 +2240,9 @@ export function composeScene(
2083
2240
  const groups: MotionSpec['groups'] = {};
2084
2241
  const tracks: MotionSpec['animations']['idle']['tracks'] = [];
2085
2242
  const idleDeform: SceneDeform[] = [];
2086
- // Every animation beside a character's idle rides along under its character's prefix (issue #183), its tracks
2087
- // prefixed as the idle's are and nothing else changed: the scene plays the idle, and schedules none of these.
2243
+ const repeatSeams: SceneRepeatSeam[] = [];
2244
+ // Every animation beside a character's idle rides along under its character's prefix (issue #183).
2245
+ // A with_idle count also folds the declared physics clip into the composed idle (#1615).
2088
2246
  const beside: Record<string, SceneAnimation> = {};
2089
2247
  const notes = new Set(ready.map((b) => b.motion.animations.idle.note));
2090
2248
  for (const [i, c] of scene.characters.entries()) {
@@ -2092,7 +2250,7 @@ export function composeScene(
2092
2250
  const id = c.id;
2093
2251
  for (const [k, v] of Object.entries(b.motion.easings)) easings[prefixed(id, k)] = v;
2094
2252
  for (const [k, v] of Object.entries(b.motion.groups)) groups[prefixed(id, k)] = v.map((n) => P(id, n));
2095
- const prefixTrack = (t: MotionSpec['animations']['idle']['tracks'][number], repeatedIdle = false): MotionSpec['animations']['idle']['tracks'][number] => {
2253
+ const prefixTrack = (t: MotionSpec['animations']['idle']['tracks'][number], literalStepped = false): MotionSpec['animations']['idle']['tracks'][number] => {
2096
2254
  const tr = { ...t } as Record<string, unknown>;
2097
2255
  if (typeof tr.bone === 'string') tr.bone = P(id, tr.bone);
2098
2256
  if (typeof tr.group === 'string') tr.group = prefixed(id, tr.group);
@@ -2100,7 +2258,7 @@ export function composeScene(
2100
2258
  const memberMap = (v: Record<string, unknown>): Record<string, unknown> => Object.fromEntries(Object.entries(v).map(([n, value]) => [P(id, n), value]));
2101
2259
  tr.keys = (t.keys as unknown as Array<Record<string, unknown>>).map((k) => ({
2102
2260
  ...k,
2103
- ...(typeof k.ease === 'string' && !(repeatedIdle && k.ease === 'stepped') ? { ease: prefixed(id, k.ease) } : {}),
2261
+ ...(typeof k.ease === 'string' && !(literalStepped && k.ease === 'stepped') ? { ease: prefixed(id, k.ease) } : {}),
2104
2262
  ...(isRecord(k.v) ? { v: memberMap(k.v) } : {}),
2105
2263
  ...(isRecord(k.derive) ? { derive: { ...k.derive, ...(isRecord(k.derive.depth) ? { depth: memberMap(k.derive.depth) } : {}) } } : {}),
2106
2264
  }));
@@ -2124,7 +2282,18 @@ export function composeScene(
2124
2282
  }
2125
2283
  for (const t of idle.tracks) tracks.push(scaledTrack(prefixTrack(t, repeats !== undefined), c.scale));
2126
2284
  idleDeform.push(...(deforms(idle, repeats !== undefined).deform ?? []));
2127
- for (const [n, a] of Object.entries(animations)) if (n !== 'idle') beside[prefixed(id, n)] = { ...a, tracks: a.tracks.map((t) => scaledTrack(prefixTrack(t), c.scale)), ...deforms(a) };
2285
+ for (const [n, a] of Object.entries(animations)) if (n !== 'idle') {
2286
+ const source = foldedClips.get(id)?.get(n);
2287
+ const count = c.with_idle?.[n];
2288
+ const declared = c.with_idle !== undefined && Object.hasOwn(c.with_idle, n);
2289
+ beside[prefixed(id, n)] = { ...a, tracks: a.tracks.map(t => scaledTrack(prefixTrack(t, declared), c.scale)), ...deforms(a) };
2290
+ if (source === undefined || typeof count !== 'number') continue;
2291
+ const object = `scene.characters[${i}].with_idle[${JSON.stringify(n)}]`;
2292
+ const folded = repeatSceneKeys(source, count, idleDuration, b.motion.groups, object, undefined, {
2293
+ take: 'idle', into: repeatSeams, mapTarget: name => prefixed(id, name),
2294
+ });
2295
+ for (const t of folded.tracks) tracks.push(prefixTrack(t, true));
2296
+ }
2128
2297
  }
2129
2298
  const note = notes.size === 1 ? [...notes][0] : ready.map((b) => `${b.id}: ${b.motion.animations.idle.note}`).join(' | ');
2130
2299
  const motion: MotionSpec = { spec: 'rigc-motion/1', archetype: name, cut: name, easings, groups, animations: { idle: { duration: idleDuration, loop: true, note, tracks, ...(idleDeform.length === 0 ? {} : { deform: idleDeform }) }, ...beside } };
@@ -2150,8 +2319,23 @@ export function composeScene(
2150
2319
  }
2151
2320
  refuseIfAny(problems);
2152
2321
  }
2153
- if (scene.animations !== undefined || pivots.size > 0) mergeSceneAnimations(rig, motion, scene.animations ?? {}, [...pivots.values()]);
2154
- const sceneCamera = scene.camera === undefined ? undefined : resolveSceneCamera(scene.camera, motion);
2322
+ let sceneAnimations = scene.animations;
2323
+ let sceneCamera: ResolvedSceneCamera | undefined;
2324
+ try {
2325
+ if (scene.repeats !== undefined) {
2326
+ const repeated = repeatSceneAnimations(scene.animations, motion.groups, scene.repeats, repeatSeams);
2327
+ if (scene.animations !== undefined) sceneAnimations = repeated;
2328
+ }
2329
+ if (sceneAnimations !== undefined || pivots.size > 0) mergeSceneAnimations(rig, motion, sceneAnimations ?? {}, [...pivots.values()]);
2330
+ if (scene.camera !== undefined) sceneCamera = resolveSceneCamera(scene.camera, motion, scene.repeats);
2331
+ } catch (err) {
2332
+ if (!(err instanceof PartsError) || sceneIdleRepeat === undefined || idleClockFields.length === 0) throw err;
2333
+ throw new PartsError(err.problems.map(problem => {
2334
+ if (!['SCENE_REPEAT_DURATION', 'SCENE_CAMERA_TRACK', 'SCENE_DURATION_AGREES'].includes(problem.code) ||
2335
+ !['scene.animations.idle', 'scene.animations["idle"]', 'scene.camera.tracks["idle"]', 'scene.repeats["idle"]'].some(field => problem.object.startsWith(field))) return problem;
2336
+ return { ...problem, detail: `${problem.detail} ${idleClockFields.join('. ')}.` };
2337
+ }));
2338
+ }
2155
2339
  if (sceneCamera !== undefined) {
2156
2340
  for (const [name, track] of sceneCamera.tracks) for (const key of track.keys) {
2157
2341
  if (cameraViewport(stage, key) === null) fail('SCENE_CAMERA_TRACK', `scene.camera.tracks[${show(name)}]`,
@@ -2175,7 +2359,7 @@ export function composeScene(
2175
2359
  order: { declared: [...scene.order], slots: slots.map((s) => s.name), judged_by: 'nothing' },
2176
2360
  idle_duration: idleDuration,
2177
2361
  };
2178
- return { rig, motion, images, report, ...(scene.animations === undefined ? {} : { sceneAnimations: scene.animations }), ...(sceneCamera === undefined ? {} : { sceneCamera }) };
2362
+ return { rig, motion, images, report, repeatSeams, ...(sceneAnimations === undefined ? {} : { sceneAnimations }), ...(sceneCamera === undefined ? {} : { sceneCamera }) };
2179
2363
  }
2180
2364
 
2181
2365
  // ---------------------------------------------------------------------------
@@ -2513,6 +2697,9 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
2513
2697
  for (const c of r.characters) {
2514
2698
  const clipped = c.clipped_bounds === undefined ? '' : `; clipped bounds [${c.clipped_bounds.join(', ')}]`;
2515
2699
  say(` ${c.id}: ${c.build} at offset [${c.offset.join(', ')}], scale ${c.scale ?? 1}, bounds [${c.bounds.join(', ')}], shift [${c.shift.join(', ')}] on ${c.shifted.bones.length} first-level bone(s), ${c.shifted.root_regions.length} region(s) on root and ${c.shifted.root_weights} weight(s) bound to root; ${c.bones} bone(s), ${c.slots} slot(s), ${c.tracks} track(s), ${c.constraints} constraint(s), rig_scale ${c.rig_scale}, idle ${c.idle_duration} s${c.accepted === undefined ? '' : `; its own check FAILED ${c.accepted.join(', ')}, accepted — the scene is for looking, not shipping`}${clipped}`);
2700
+ for (const [clip, count] of Object.entries(c.with_idle ?? {})) {
2701
+ say(` ${prefixed(c.id, clip)} ${count === false ? 'plays beside idle only (with_idle: false)' : `carried into idle for ${count} source period${count === 1 ? '' : 's'} and retained beside it`}`);
2702
+ }
2516
2703
  }
2517
2704
  say(` order (declared, judged by nothing): ${r.order.declared.join(', ')} -> ${r.order.slots.length} slot(s), back to front`);
2518
2705
  const texts: Array<[string, string]> = [
@@ -2523,13 +2710,15 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
2523
2710
  const gated: { camera?: CameraEvidence } = {};
2524
2711
  let gate: ReturnType<typeof gateThroughRigc>;
2525
2712
  try {
2526
- const clips = composed.sceneAnimations;
2527
- const readLoop = (build: string): void => {
2528
- if (clips === undefined) return;
2529
- refuseIfAny(sceneClipLoopProblems(readFileSync(join(build, 'skeleton.model.json'), 'utf8'), clips, r.characters.some(c => c.idle_repeats !== undefined)));
2713
+ const { sceneAnimations: clips, repeatSeams } = composed;
2714
+ const checkMotion = (build: string): void => {
2715
+ if (clips === undefined && repeatSeams.length === 0) return;
2716
+ const modelText = readFileSync(join(build, CAMERA_MODEL), 'utf8');
2717
+ refuseIfAny(sceneRepeatCurveProblems(modelText, repeatSeams));
2718
+ if (clips !== undefined) refuseIfAny(sceneClipLoopProblems(modelText, clips, r.characters.some(c => c.idle_repeats !== undefined)));
2530
2719
  };
2531
2720
  if (camera === undefined) {
2532
- gate = gateThroughRigc(composed.images, texts, run.rig, run.scratch, mode, clips === undefined ? undefined : readLoop);
2721
+ gate = gateThroughRigc(composed.images, texts, run.rig, run.scratch, mode, clips === undefined && repeatSeams.length === 0 ? undefined : checkMotion);
2533
2722
  } else {
2534
2723
  // Core binds the model to skeleton.json, whose image path is relative
2535
2724
  // to the build. Mirror check's rig/ and check/build/ in gate scratch.
@@ -2539,7 +2728,7 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
2539
2728
  try {
2540
2729
  const packed: RigcRunner = args => run.rig(args.map((arg, i) => args[i - 1] === '--out' ? build : arg));
2541
2730
  gate = gateThroughRigc(composed.images, texts, packed, scratch, mode, () => {
2542
- readLoop(build);
2731
+ checkMotion(build);
2543
2732
  gated.camera = measureSceneCamera(build, composed, camera);
2544
2733
  });
2545
2734
  } finally {
package/src/sceneclips.ts CHANGED
@@ -2,10 +2,11 @@
2
2
  import { bezierForChannel, f32 } from '@rig-c/core/compile';
3
3
  import { CompileError } from '@rig-c/core/errors';
4
4
  import { parseMotionSpec, type MotionSpec as CoreMotion } from '@rig-c/core/motion';
5
- import { bezierPolyline, CORE_DOCUMENT_SPEC, CoreInputError, poseRawAnimation, readModel, type RawPose } from '@rig-c/core/core';
5
+ import { bezierPolyline, CORE_DOCUMENT_SPEC, CoreInputError, poseRawAnimation, readModel, type CompiledDocument, type RawPose } from '@rig-c/core/core';
6
6
  import { PartsError, refuseIfAny, type Problem } from './errors.ts';
7
7
  import type { MotionSpec } from './motion.ts';
8
8
  import type { RigSpec } from './rig.ts';
9
+ import { repeatSceneKeys, repeatSceneTimeline, type SceneRepeatSeam } from './scenerepeat.ts';
9
10
 
10
11
  export type SceneAnimations = CoreMotion['animations'];
11
12
 
@@ -30,6 +31,9 @@ export interface ResolvedSceneCameraTrack {
30
31
  keys: Omit<SceneCameraKey, 'ease'>[];
31
32
  duration: number;
32
33
  loop: boolean;
34
+ /** The source clock for exact per-period coverage phases. */
35
+ period?: number;
36
+ samplePeriod?(time: number): SceneCameraSample;
33
37
  /** Sample on the authored clock, including the unwrapped terminal time. */
34
38
  sample(time: number): SceneCameraSample;
35
39
  }
@@ -198,7 +202,7 @@ function cameraLoopProblem(first: SceneCameraSample, last: SceneCameraSample, du
198
202
  }
199
203
 
200
204
  /** Resolve only declared tracks, against the final take and easing names. */
201
- export function resolveSceneCamera(camera: SceneCamera, motion: MotionSpec): ResolvedSceneCamera {
205
+ export function resolveSceneCamera(camera: SceneCamera, motion: MotionSpec, repeats?: Readonly<Record<string, number>>): ResolvedSceneCamera {
202
206
  const problems: Problem[] = [];
203
207
  const tracks = new Map<string, ResolvedSceneCameraTrack>();
204
208
  for (const [name, authored] of Object.entries(camera.tracks)) {
@@ -210,14 +214,21 @@ export function resolveSceneCamera(camera: SceneCamera, motion: MotionSpec): Res
210
214
  }
211
215
  const { duration } = take;
212
216
  const loop = take.loop === true;
217
+ const count = repeats !== undefined && Object.hasOwn(repeats, name) ? repeats[name] : undefined;
218
+ const period = count === undefined ? duration : duration / count;
219
+ const closedPeriod = loop || count !== undefined;
213
220
  const first = authored[0], last = authored.at(-1);
214
- if (last === undefined || last.t !== duration) {
215
- problems.push({ code: CAMERA_TRACK, object, detail: `ends at ${last === undefined ? 'no key' : `${last.t} s`}. Take ${JSON.stringify(name)} declares ${duration} s and the terminal key must match exactly` });
221
+ if (last === undefined || last.t !== period) {
222
+ const found = last === undefined ? 'no key' : `${last.t} s`;
223
+ const detail = count === undefined
224
+ ? `Take ${JSON.stringify(name)} declares ${duration} s and the terminal key must match exactly`
225
+ : `Take ${JSON.stringify(name)} declares ${duration} s and scene.repeats[${JSON.stringify(name)}] is ${count}. The terminal key must match the ${period} s period exactly`;
226
+ problems.push({ code: CAMERA_TRACK, object, detail: `ends at ${found}. ${detail}` });
216
227
  continue;
217
228
  }
218
229
  const before = problems.length;
219
- if (loop) {
220
- const problem = cameraLoopProblem(first, last, duration, object, 'Authored');
230
+ if (closedPeriod) {
231
+ const problem = cameraLoopProblem(first, last, period, object, 'Authored');
221
232
  if (problem !== null) problems.push(problem);
222
233
  }
223
234
 
@@ -256,14 +267,22 @@ export function resolveSceneCamera(camera: SceneCamera, motion: MotionSpec): Res
256
267
  let coreStart: SceneCameraSample | undefined, coreEnd: SceneCameraSample | undefined;
257
268
  if (eased) {
258
269
  try {
259
- coreSample = cameraCoreSampler(keys, times, duration, object);
270
+ coreSample = cameraCoreSampler(keys, times, period, object);
260
271
  const storedEnd = Math.fround(times[times.length - 1]);
261
272
  coreStart = coreSample(0);
262
273
  coreEnd = coreSample(storedEnd);
263
- if (loop) {
274
+ if (closedPeriod) {
264
275
  const problem = cameraLoopProblem(coreStart, coreEnd, storedEnd, object, 'Core-evaluated');
265
276
  if (problem !== null) problems.push(problem);
266
277
  }
278
+ if (count !== undefined && problems.length === before) {
279
+ const penultimate = keys.length - 2;
280
+ const curve = keys[penultimate]?.curve;
281
+ if (Array.isArray(curve)) {
282
+ const problem = curveSeamProblem(curve, times[penultimate], times[times.length - 1], storedEnd, object);
283
+ if (problem !== null) problems.push(problem);
284
+ }
285
+ }
267
286
  } catch (err) {
268
287
  if (err instanceof PartsError) problems.push(...err.problems);
269
288
  else if (err instanceof CoreInputError) problems.push({ code: CAMERA_TRACK, object, detail: err.message });
@@ -273,32 +292,55 @@ export function resolveSceneCamera(camera: SceneCamera, motion: MotionSpec): Res
273
292
  }
274
293
  const easedStart = keys[0].curve !== undefined;
275
294
  const easedEnd = keys.at(-2)?.curve !== undefined;
276
- const easedSeam = loop && (easedStart || easedEnd);
277
- tracks.set(name, {
278
- keys, duration, loop,
279
- sample(time) {
280
- if (!Number.isFinite(time) || time < 0 || time > duration) {
281
- throw new PartsError([{ code: CAMERA_TRACK, object, detail: `cannot sample t=${time} s. Authored time in [0, ${duration}] s is required` }]);
282
- }
283
- // At a curved loop seam use both unwrapped Core reads. The linear-only
284
- // seam uses both authored values, so the two ends share a precision.
285
- const endpoint = time === 0 && (easedSeam || easedStart) ? coreStart
286
- : time === duration && (easedSeam || easedEnd) ? coreEnd : undefined;
287
- if (endpoint !== undefined) return { pan: [...endpoint.pan], zoom: endpoint.zoom };
288
- let low = 0, high = keys.length - 1;
289
- while (low < high) {
290
- const mid = Math.ceil((low + high) / 2);
291
- if (keys[mid].t <= time) low = mid;
292
- else high = mid - 1;
293
- }
294
- const from = keys[low], to = keys[low + 1];
295
- if (from.curve !== undefined && coreSample !== undefined) return coreSample(time);
296
- if (from.t === time || to === undefined) return checkCameraSample([...from.pan], from.zoom, time, object);
297
- const phase = (time - from.t) / (to.t - from.t);
298
- const mix = (a: number, b: number): number => a + (b - a) * phase;
299
- return checkCameraSample([mix(from.pan[0], to.pan[0]), mix(from.pan[1], to.pan[1])], 1 / mix(1 / from.zoom, 1 / to.zoom), time, object);
300
- },
301
- });
295
+ const easedSeam = closedPeriod && (easedStart || easedEnd);
296
+ const checkTime = (time: number, end: number): void => {
297
+ if (!Number.isFinite(time) || time < 0 || time > end) {
298
+ throw new PartsError([{ code: CAMERA_TRACK, object, detail: `cannot sample t=${time} s. Authored time in [0, ${end}] s is required` }]);
299
+ }
300
+ };
301
+ const samplePeriod = (time: number): SceneCameraSample => {
302
+ checkTime(time, period);
303
+ // At a curved loop seam use both unwrapped Core reads. The linear-only
304
+ // seam uses both authored values, so the two ends share a precision.
305
+ const endpoint = time === 0 && (easedSeam || easedStart) ? coreStart
306
+ : time === period && (easedSeam || easedEnd) ? coreEnd : undefined;
307
+ if (endpoint !== undefined) return { pan: [...endpoint.pan], zoom: endpoint.zoom };
308
+ let low = 0, high = keys.length - 1;
309
+ while (low < high) {
310
+ const mid = Math.ceil((low + high) / 2);
311
+ if (keys[mid].t <= time) low = mid;
312
+ else high = mid - 1;
313
+ }
314
+ const from = keys[low], to = keys[low + 1];
315
+ if (from.curve !== undefined && coreSample !== undefined) return coreSample(time);
316
+ if (from.t === time || to === undefined) return checkCameraSample([...from.pan], from.zoom, time, object);
317
+ const phase = (time - from.t) / (to.t - from.t);
318
+ const mix = (a: number, b: number): number => a + (b - a) * phase;
319
+ return checkCameraSample([mix(from.pan[0], to.pan[0]), mix(from.pan[1], to.pan[1])], 1 / mix(1 / from.zoom, 1 / to.zoom), time, object);
320
+ };
321
+ if (count === undefined) {
322
+ tracks.set(name, { keys, duration, loop, sample: samplePeriod });
323
+ } else if (problems.length === before) {
324
+ try {
325
+ tracks.set(name, {
326
+ keys: repeatSceneTimeline(keys, count, period, duration, object), duration, loop,
327
+ period, samplePeriod,
328
+ sample(time) {
329
+ checkTime(time, duration);
330
+ if (time === duration) return samplePeriod(period);
331
+ // Locate the splice by its emitted clock, including a quotient
332
+ // that may round to an adjacent integer at a boundary.
333
+ let copy = Math.min(Math.floor(time / period), count - 1);
334
+ if (copy * period > time) copy--;
335
+ else if (copy + 1 < count && (copy + 1) * period <= time) copy++;
336
+ return samplePeriod(Math.min(time - copy * period, period));
337
+ },
338
+ });
339
+ } catch (err) {
340
+ if (!(err instanceof PartsError)) throw err;
341
+ problems.push(...err.problems);
342
+ }
343
+ }
302
344
  }
303
345
  refuseIfAny(problems);
304
346
  return { backdrop: camera.backdrop, tracks };
@@ -355,6 +397,40 @@ export function readSceneAnimations(raw: unknown, where: string): SceneAnimation
355
397
  }
356
398
  }
357
399
 
400
+ /** Expand scene-authored keys on the composed clock before merging timelines. */
401
+ export function repeatSceneAnimations(clips: SceneAnimations | undefined, groups: Readonly<Record<string, string[]>>,
402
+ repeats?: Readonly<Record<string, number>>, repeatSeams?: SceneRepeatSeam[]): SceneAnimations {
403
+ const authored = clips ?? {};
404
+ if (repeats === undefined) return authored;
405
+ const problems: Problem[] = [];
406
+ const expanded = { ...authored };
407
+ for (const [name, count] of Object.entries(repeats)) {
408
+ const field = `scene.repeats[${JSON.stringify(name)}]`;
409
+ const object = `scene.animations.${name}`;
410
+ const clip = Object.hasOwn(authored, name) ? authored[name] : undefined;
411
+ if (clip === undefined || !(clip.duration > 0)) {
412
+ problems.push({ code: 'SCENE_REPEAT_DURATION', object: field,
413
+ detail: `is ${count} and ${object}.duration is ${clip === undefined ? 'absent' : `${clip.duration} s`}. Declare a positive whole take duration` });
414
+ continue;
415
+ }
416
+ const before = problems.length;
417
+ for (const family of ['ik', 'transform', 'sequence', 'drawOrder', 'events'] as const) {
418
+ if ((clip[family]?.length ?? 0) > 0) problems.push({ code: 'SCENE_REPEAT_KEY_SEAM', object: `${object}.${family}`,
419
+ detail: `${field} is ${count}. This declaration splices scene tracks, deforms and camera keys; this timeline has no defined repeat splice` });
420
+ }
421
+ if (problems.length !== before) continue;
422
+ try {
423
+ const capture = repeatSeams === undefined ? undefined : { take: name, into: repeatSeams };
424
+ expanded[name] = repeatSceneKeys({ ...clip, duration: clip.duration / count }, count, clip.duration, groups, object, field, capture);
425
+ } catch (err) {
426
+ if (!(err instanceof PartsError)) throw err;
427
+ problems.push(...err.problems);
428
+ }
429
+ }
430
+ refuseIfAny(problems);
431
+ return expanded;
432
+ }
433
+
358
434
  /** Core slider source properties and the bone timeline channels that feed them. */
359
435
  function sliderInputChannel(source: unknown, property: string): number | null {
360
436
  switch (source) {
@@ -531,6 +607,87 @@ function storedIdleLoopDifference(modelText: string): { difference: string | nul
531
607
  interface StoredCurveKey { time: number; curve?: number[] | 'stepped' }
532
608
  interface StoredTrackTarget { name: string; timelines: Array<{ name: string; keys: StoredCurveKey[] }> }
533
609
 
610
+ function curveSeamProblem(curve: number[], start: number, end: number, duration: number, object: string): Problem | null {
611
+ for (let i = 0; i < curve.length; i += 4) {
612
+ const points = bezierPolyline(start, 0, curve[i], 0, curve[i + 2], 0, end, 0);
613
+ const overlap = points.find((n, j) => j % 2 === 0 && n >= duration);
614
+ if (overlap !== undefined) return { code: 'SCENE_REPEAT_KEY_SEAM', object,
615
+ detail: `Bezier channel ${i / 4} has a stored time sample ${overlap} s at or past the closing key ${duration} s. The source channel must splice without changing its keyed motion` };
616
+ }
617
+ return null;
618
+ }
619
+
620
+ type CompiledSceneAnimation = CompiledDocument['animations'][number];
621
+ interface CompiledSeamKey {
622
+ time: number;
623
+ stated: number | { time: number };
624
+ curve: number[] | 'linear' | 'stepped';
625
+ }
626
+
627
+ function compiledSeamKeys(animation: CompiledSceneAnimation, address: SceneRepeatSeam['timeline']): readonly CompiledSeamKey[] | null | undefined {
628
+ const { timelines, constraints } = animation;
629
+ if (address.family === 'deform') {
630
+ return timelines.attachments.find(a => a.skin === address.skin && a.slot === address.slot && a.attachment === address.attachment)?.deform;
631
+ }
632
+ const { family, target, property } = address;
633
+ if (family === 'path') {
634
+ const track = constraints.path.find(t => t.name === target);
635
+ return property === 'position' || property === 'spacing' || property === 'mix' ? track?.[property] : undefined;
636
+ }
637
+ if (family === 'slider') {
638
+ const track = constraints.slider.find(t => t.name === target);
639
+ return property === 'time' || property === 'mix' ? track?.[property] : undefined;
640
+ }
641
+ const bone = family === 'bone' || family === 'group'
642
+ ? timelines.bones.find(t => t.name === target)?.timelines.find(t => t.kind === property)?.keys : undefined;
643
+ const slot = family === 'slot' || family === 'group'
644
+ ? timelines.slots.find(t => t.name === target)?.timelines.find(t => t.kind === property)?.keys : undefined;
645
+ const physics = family === 'physics' || family === 'group'
646
+ ? constraints.physicsKeyed?.find(t => t.name === target && t.kind === property)?.keys : undefined;
647
+ const matches = [bone, slot, physics].filter(keys => keys !== undefined);
648
+ return matches.length === 1 ? matches[0] : undefined;
649
+ }
650
+
651
+ /** Read the final Core model so both raw curves and expanded named easings use
652
+ * the actual stored handles. Key ordinals identify the splice after quantizing
653
+ * the clock; a different timeline can have a key at the same time.
654
+ */
655
+ export function sceneRepeatCurveProblems(modelText: string, seams: readonly SceneRepeatSeam[]): Problem[] {
656
+ if (seams.length === 0) return [];
657
+ let doc: CompiledDocument;
658
+ try { doc = readModel(modelText, 'composed repeat model'); }
659
+ catch (err) {
660
+ if (!(err instanceof CoreInputError)) throw err;
661
+ return [{ code: 'SCENE_REPEAT_KEY_SEAM', object: seams[0].object, detail: err.message }];
662
+ }
663
+ const problems: Problem[] = [];
664
+ const statedTime = (key: CompiledSeamKey): number => typeof key.stated === 'number' ? key.stated : key.stated.time;
665
+ for (const { take, object, timeline, stride, count } of seams) {
666
+ const animation = doc.animations.find(a => a.name === take);
667
+ const keys = animation === undefined ? undefined : compiledSeamKeys(animation, timeline);
668
+ const timelineName = timeline.family === 'deform' ? `deform ${timeline.skin}/${timeline.slot}/${timeline.attachment}`
669
+ : `${timeline.family} ${JSON.stringify(timeline.target)} ${timeline.property}`;
670
+ const where = `${object} (${timelineName} in take ${JSON.stringify(take)})`;
671
+ const expected = stride * count + 1;
672
+ if (keys?.length !== expected) {
673
+ problems.push({ code: 'SCENE_REPEAT_KEY_SEAM', object: where,
674
+ detail: `compiled timeline has ${keys === undefined || keys === null ? 'no uniquely resolved key list' : `${keys.length} keys`}. The splice requires ${expected} keys to locate its closing segments` });
675
+ continue;
676
+ }
677
+ for (let copy = 1; copy <= count; copy++) {
678
+ const i = copy * stride;
679
+ const before = keys[i - 1], end = keys[i];
680
+ if (!Array.isArray(before.curve)) continue;
681
+ const problem = curveSeamProblem(before.curve, statedTime(before), statedTime(end), end.time, where);
682
+ if (problem !== null) {
683
+ problems.push(problem);
684
+ break;
685
+ }
686
+ }
687
+ }
688
+ return problems;
689
+ }
690
+
534
691
  /** At a splice, Core's sampled Bezier must reach the closing key from the left.
535
692
  * Check the stored polyline, including curves generated from named easings.
536
693
  */
@@ -548,17 +705,10 @@ function sourceCurveSeamProblems(modelText: string, duration: number, object: st
548
705
  const check = (keys: StoredCurveKey[], timeline: string, deform = false): void => {
549
706
  const before = keys.at(-2), end = keys.at(-1);
550
707
  if (end === undefined || Math.fround(end.time) !== duration || !Array.isArray(before?.curve)) return;
551
- const curve = before.curve;
552
- for (let i = 0; i < curve.length; i += 4) {
553
- // Only the time axis is needed. Core's deform polyline uses the stored
554
- // float for the leading key time; bone and physics curves use its name.
555
- const points = bezierPolyline(deform ? Math.fround(before.time) : before.time, 0, curve[i], 0, curve[i + 2], 0, end.time, 0);
556
- const overlap = points.find((n, j) => j % 2 === 0 && n >= duration);
557
- if (overlap === undefined) continue;
558
- problems.push({ code: 'SCENE_REPEAT_KEY_SEAM', object: `${object}.${timeline}`,
559
- detail: `Bezier channel ${i / 4} has a stored time sample ${overlap} s at or past the closing key ${duration} s. The source channel must splice without changing its keyed motion` });
560
- break;
561
- }
708
+ // Core's deform polyline uses the stored float for the leading key time;
709
+ // bone and physics curves use its name.
710
+ const problem = curveSeamProblem(before.curve, deform ? Math.fround(before.time) : before.time, end.time, duration, `${object}.${timeline}`);
711
+ if (problem !== null) problems.push(problem);
562
712
  };
563
713
  for (const [family, targets] of [['bone', idle.bones], ['slot', idle.slots], ['physics', idle.constraints.physics]] as const) {
564
714
  for (const target of targets) for (const track of target.timelines) check(track.keys, `${family} ${JSON.stringify(target.name)} ${track.name}`);
@@ -1,4 +1,4 @@
1
- /** Periodic splicing for the imported character idle only. */
1
+ /** Periodic splicing for character motion, scene motion and camera keys. */
2
2
  import { isDeepStrictEqual } from 'node:util';
3
3
  import { PartsError } from './errors.ts';
4
4
 
@@ -10,8 +10,26 @@ interface Key {
10
10
 
11
11
  interface Idle {
12
12
  duration: number;
13
- tracks: Array<{ property: string; bone?: string; group?: string; physics?: string; lag?: number; stagger?: number; keys: Key[] }>;
14
- deform?: Array<{ slot: string; attachment: string; keys: Key[] }>;
13
+ tracks: Array<{ property: string; bone?: string; slot?: string; group?: string; physics?: string; path?: string; slider?: string; lag?: number; stagger?: number; keys: Key[] }>;
14
+ deform?: Array<{ skin?: string; slot: string; attachment: string; keys: Key[] }>;
15
+ }
16
+
17
+ type TrackFamily = 'bone' | 'slot' | 'physics' | 'path' | 'slider' | 'group';
18
+
19
+ export interface SceneRepeatSeam {
20
+ take: string;
21
+ object: string;
22
+ timeline: { family: TrackFamily; target: string; property: string }
23
+ | { family: 'deform'; skin: string; slot: string; attachment: string };
24
+ /** The closing key of copy i is at i * stride, including the final key. */
25
+ stride: number;
26
+ count: number;
27
+ }
28
+
29
+ interface SceneRepeatSeamCapture {
30
+ take: string;
31
+ into: SceneRepeatSeam[];
32
+ mapTarget?: (name: string) => string;
15
33
  }
16
34
 
17
35
  function refuse(object: string, detail: string): never {
@@ -42,7 +60,7 @@ function atOffset<K extends Key>(key: K, offset: number, time = key.t + offset):
42
60
  }
43
61
 
44
62
  function repeatTimeline<K extends Key>(keys: K[], count: number, period: number, duration: number, object: string,
45
- clocks: ReadonlyArray<{ target: string; shift: number }>, property?: string): K[] {
63
+ clocks: ReadonlyArray<{ target: string; shift: number }>, property?: string, captureCurveSeam?: (stride: number) => void): K[] {
46
64
  const first = keys[0], last = keys[keys.length - 1], before = keys[keys.length - 2];
47
65
  if (first === undefined) refuse(object, 'has no source keys');
48
66
  const startState = state(first), endState = state(last);
@@ -85,27 +103,77 @@ function repeatTimeline<K extends Key>(keys: K[], count: number, period: number,
85
103
  out.push(atOffset(keys[j], k * period, terminal));
86
104
  }
87
105
  }
106
+ if (sharesKey && before !== undefined && (Array.isArray(before.curve) || (typeof before.ease === 'string' && before.ease !== 'stepped'))) {
107
+ captureCurveSeam?.(stride);
108
+ }
88
109
  return out;
89
110
  }
90
111
 
91
- export function repeatSceneKeys<T extends Idle>(idle: T, count: number, duration: number, groups: Readonly<Record<string, string[]>>, object: string): T {
92
- const period = idle.duration;
112
+ function checkRepeatClock(count: number, period: number, duration: number, object: string): void {
93
113
  if (!Number.isFinite(Math.fround(duration)) || Math.fround(period) === 0 || Math.fround((count - 1) * period) === Math.fround(duration)) {
94
114
  refuse(object, `the source period ${period} s cannot separate ${count} copies on the float32 playback clock at ${duration} s`);
95
115
  }
116
+ }
117
+
118
+ export function repeatSceneTimeline<K extends Key>(keys: K[], count: number, period: number, duration: number, object: string): K[] {
119
+ checkRepeatClock(count, period, duration, object);
120
+ return repeatTimeline(keys, count, period, duration, object, [{ target: object, shift: 0 }]);
121
+ }
122
+
123
+ export function repeatSceneKeys<T extends Idle>(idle: T, count: number, duration: number, groups: Readonly<Record<string, string[]>>, object: string,
124
+ sceneRepeatField?: string, capture?: SceneRepeatSeamCapture): T {
125
+ const period = idle.duration;
126
+ checkRepeatClock(count, period, duration, object);
127
+ const recordSeam = (timeline: SceneRepeatSeam['timeline'], where: string, stride: number): void => {
128
+ if (capture !== undefined) capture.into.push({ take: capture.take, object: where, timeline, stride, count });
129
+ };
130
+ const trackClocks = (track: Idle['tracks'][number], where: string) => {
131
+ const sceneTarget = sceneRepeatField === undefined ? undefined : track.slot ?? track.path ?? track.slider;
132
+ const targets = track.group === undefined ? [track.bone ?? track.physics ?? sceneTarget ?? track.property]
133
+ : Object.hasOwn(groups, track.group) ? groups[track.group] : [];
134
+ if (targets.length === 0) refuse(where, `group ${JSON.stringify(track.group)} has no resolved members`);
135
+ return targets.map((name, index) => ({ name, target: JSON.stringify(name), shift: (track.lag ?? 0) + (track.stagger ?? 0) * index }));
136
+ };
137
+ if (sceneRepeatField !== undefined) {
138
+ // A clip's end is the latest effective key across its timelines. Closed
139
+ // state channels can hold through a gap, and resets must stay interior.
140
+ let end = -Infinity;
141
+ for (const [i, track] of idle.tracks.entries()) {
142
+ const key = track.keys.at(-1);
143
+ if (key === undefined) continue;
144
+ for (const { shift } of trackClocks(track, `${object}.tracks[${i}]`)) end = Math.max(end, key.t + shift);
145
+ }
146
+ for (const deform of idle.deform ?? []) {
147
+ const key = deform.keys.at(-1);
148
+ if (key !== undefined) end = Math.max(end, key.t);
149
+ }
150
+ if (end !== -Infinity && end !== period) throw new PartsError([{
151
+ code: 'SCENE_REPEAT_DURATION', object,
152
+ detail: `keys end at ${end} s. ${object}.duration declares ${duration} s and ${sceneRepeatField} is ${count}. The terminal time must match the ${period} s period exactly`,
153
+ }]);
154
+ }
96
155
  return {
97
156
  ...idle,
98
157
  duration,
99
158
  tracks: idle.tracks.map((track, i) => {
100
159
  const where = `${object}.tracks[${i}]`;
101
- const targets = track.group === undefined ? [track.bone ?? track.physics ?? track.property] : Object.hasOwn(groups, track.group) ? groups[track.group] : [];
102
- if (targets.length === 0) refuse(where, `group ${JSON.stringify(track.group)} has no resolved members`);
103
- const clocks = targets.map((target, index) => ({ target: JSON.stringify(target), shift: (track.lag ?? 0) + (track.stagger ?? 0) * index }));
104
- return { ...track, keys: repeatTimeline(track.keys, count, period, duration, where, clocks, track.property) };
160
+ const clocks = trackClocks(track, where);
161
+ const record = capture === undefined ? undefined : (stride: number): void => {
162
+ const family = (['bone', 'slot', 'physics', 'path', 'slider', 'group'] as const).find(field => track[field] !== undefined);
163
+ if (family === undefined) return; // Core refuses a track with no target before the seam check.
164
+ for (const { name } of clocks) {
165
+ recordSeam({ family, target: capture.mapTarget?.(name) ?? name, property: track.property }, where, stride);
166
+ }
167
+ };
168
+ return { ...track, keys: repeatTimeline(track.keys, count, period, duration, where, clocks, track.property, record) };
105
169
  }),
106
- ...(idle.deform === undefined ? {} : { deform: idle.deform.map((deform, i) => ({
107
- ...deform,
108
- keys: repeatTimeline(deform.keys, count, period, duration, `${object}.deform[${i}]`, [{ target: `${deform.slot}/${deform.attachment}`, shift: 0 }]),
109
- })) }),
170
+ ...(idle.deform === undefined ? {} : { deform: idle.deform.map((deform, i) => {
171
+ const where = `${object}.deform[${i}]`;
172
+ const clocks = [{ target: `${deform.slot}/${deform.attachment}`, shift: 0 }];
173
+ const record = capture === undefined ? undefined : (stride: number): void => {
174
+ recordSeam({ family: 'deform', skin: deform.skin ?? 'default', slot: deform.slot, attachment: deform.attachment }, where, stride);
175
+ };
176
+ return { ...deform, keys: repeatTimeline(deform.keys, count, period, duration, where, clocks, undefined, record) };
177
+ }) }),
110
178
  };
111
179
  }