Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
Meta Vens
7f6e0ce7c1 Merge cut/vili-request-marks: a request's marks and inPlace are kept in the job record and never reach the worker (Soul s1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 03:40:30 +01:00
Meta Vens
d1fcb03858 README: FBX export is live, and marks and inPlace are the caller's, kept in the record
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 03:23:42 +01:00
Meta Vens
6976520e52 Vili keeps a request's marks and inPlace in the job record, never gives them to the worker, and refuses malformed ones first
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 03:23:42 +01:00
Meta Vens
386c4d6691 Tests: a request's marks and inPlace are kept in the record, never reach the worker, and malformed ones are refused first
Red at base: the fields are not yet read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 03:19:17 +01:00
Meta Vens
3066c375d6 Merge cut/vili-loop-export: Vili exports a seam-matched loop window on request (Soul s1 fixed, s2 holds)
The worker picks the pose- and velocity-matched window from the generated
joints; the FBX is that window; the record keeps request.loop, worker.loops
and the constraints as sent. Constraints given more than once are refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:09:35 +01:00
Meta Vens
67979a78d2 vili-daemon.mjs and its test: back to LF line endings
The earlier fixes in this batch (16e585d, d35b9e2, bdee73c) staged both files with CRLF by a tool slip; this commit
changes no line but the endings, so the batch's net diff on them is its real lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:50:30 +01:00
Meta Vens
bdee73c028 Tests pin each window refusal: a negative first, first equal to last, a fractional last, extra or misnamed --frames arguments
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:32:27 +01:00
Meta Vens
d35b9e2c31 A sample's file and window pair by its own index, not by sorting the file names as text
motion_100.bvh sorted before motion_11.bvh, so past 100 samples a clip was exported over another sample's window.
The index is read from the file name and orders the samples and names the clips.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:32:26 +01:00
Meta Vens
16e585d0b9 Constraints given twice are a 400, so the record names the one input the worker read
The worker reads one path; with inline constraints and constraints_path both sent, the daemon preferred the path
but the record kept the inline list. Two inputs are now refused before anything is written, in the daemon's
fixed-text 400 shape, echoing nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:32:26 +01:00
Meta Vens
0426a7ce3a loop_windows moves beside loop_window and takes the model; a test pins it on a real take with the two skeletons
The worker's window path loaded the 8B model at import, so no test reached it and swapped atan2 arguments or
the 30-joint skeleton went unnoticed. loop_windows(output, model) needs only model.output_skeleton and
model.fps. The test uses a committed 240-frame somaskel77 take (fixtures/take.npz, joints from a live Vili BVH
by forward kinematics) and stand-ins that carry the 77- and 30-joint skeletons' names and parents.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:32:25 +01:00
Meta Vens
d275f00aeb README: loop on the generate request, and what the FBX window is
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 09:05:56 +01:00
Meta Vens
447bf09ddf loop: the worker picks the seamless window, the daemon forwards loops[k] to Blender, the record keeps it
Worker: with loop true the answer gains loops (one {first, last, poseCost, velocityCost}
per sample) from loop_window over Kimodo's somaskel77 posed joints and compute_global_heading.
Daemon: loop must be a boolean and needs fbx (400 'Invalid fbx request.'); sample k is
exported with '--frames first+1 last+1'; an answer without a window for a sample fails
'fbx-export-failed (no loop window)'; the record keeps request.loop and, when inline,
the constraints as sent. The daemon never computes a window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 08:59:03 +01:00
Meta Vens
928eb15592 test_bvh_to_fbx: the BVH builder's newlines are escapes, not line breaks
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 08:56:14 +01:00
Meta Vens
303cb28683 bvh-to-fbx.py applies a --frames range it is handed and chooses none
Optional '--frames A B' after the clip name sets the scene's frame range to A..B
(Blender frames, from 1); outside the take, or malformed, it exits 4 or 3 and writes
nothing. Without it the whole take, as before. The test's BVH builder is shared.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 08:55:43 +01:00
Meta Vens
f5fa841d58 loop_window: the lowest-cost seam of a generated take, pose and velocity matched
Numpy only; the resident worker is its one caller. Hips-relative, heading-normalised
poses; cost is pose RMS plus 0.1 s of velocity RMS; ties go to the longer window,
then the earlier. Tests: a periodic stride between rests, the stated cost against a
frame-by-frame oracle, heading, ties, minimum length.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 08:54:53 +01:00
Meta Vens
3499d86b2b Map: the RPS slot clips r1 (takes, pace, slide, loop seams, countdown contacts)
Imagination pass for motion-pipeline:cut_spec:cut-rps-slot-clips.r1: 19 live
takes; the brisk mope covers the walk-off in 11.4 s, no celebrating take
reaches walking pace without a speed-up, and no countdown take shows three
separate fist-into-palm hits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 07:24:52 +01:00
Meta Vens
a496fbc42c Map: SOMA avatar against the live export (r3 body facts and rationale)
Imagination pass for motion-pipeline:cut_spec:cut-soma-humanoid-avatar.r3:
the live rest FBX imports as a valid Humanoid with the finger table shifted
to *2/*3/*4, the bone map converges from code in two passes, clips reimport
through DependsOnArtifact, and exit travel comes from root motion read by the
duel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 04:08:29 +01:00
Meta Vens
51eb113d57 Merge fix/vili-runner-build: daemon tests run their stub Blender from the checkout, not noexec /tmp (Soul s4)
Idunn's node-build runner mounts /tmp noexec, so test-daemon failed 20 of 137 and
the 2026-10-25 deploy failed in Sealing. The stub now lives under the gitignored
.vili/test-scratch. The whole recipe passes by hand in the runner's shape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 02:49:11 +01:00
11 changed files with 678 additions and 37 deletions

View file

@ -8,11 +8,11 @@ Linux. It runs on Yggdrasil as an Idunn target (see Front Door).
## Front Door
- **Value:** a supervised path from a text prompt to generated body motion. The daemon spawns one resident Kimodo worker, caps its threads, and returns motion artifacts (`motion.npz` and BVH; FBX for Unity is planned, see below) for a job.
- **Value:** a supervised path from a text prompt to generated body motion. The daemon spawns one resident Kimodo worker, caps its threads, and returns motion artifacts (`motion.npz`, BVH, and an FBX for Unity, see FBX Export) for a job.
- **Problem:** Personas and games need generated motion, but cold per-request model loads cost minutes. One daemon owns job identity, worker lifecycle, the thread budget and artifact references, so callers touch no model state.
- **Entry points:** `scripts/vili-daemon.mjs` (the daemon; `npm start`, `npm test`), `scripts/idunn-entry.mjs` (the process Idunn runs), `deployment/idunn/recipe.toml` (the sealed release), `scripts/kimodo-resident-worker.py` (the worker it spawns), `scripts/kimodo-text-encode.py` (the one-shot encoder child), `POST /motion/generate` (see Motion Generation), `docs/verse-service-contract.md` and `docs/motion-pipeline-target.md`.
- **Live:** the Idunn target `vili` on Yggdrasil at `http://10.77.0.1:8824` (WireGuard only), CPU only, running the revision deployed before the FBX export: `POST /motion/generate` (`motion.npz` and optional BVH on the SOMA skeleton; no FBX), `GET /health`, `GET /operator-state`, and the CultCache service store.
- **Planned:** FBX export, which is in this tree and not yet deployed: `"fbx": true` on `POST /motion/generate` (a Unity-ready FBX per clip), `POST /motion/rest-fbx` (the avatar's rest pose) and `GET /motion/artifacts/{jobId}/{name}` (the FBX and BVH bytes), from `scripts/bvh-to-fbx.py` in the release's own Blender 5.2.2 (see FBX Export). They answer only after the next `idunn up`. Also planned: worker intake closed to local callers only, publication to Odin, and a Thing 2 operator surface. The text-prompt-to-Unity-clip path with no hand steps is `docs/motion-pipeline-target.md`.
- **Live:** the Idunn target `vili` on Yggdrasil at `http://10.77.0.1:8824` (WireGuard only), CPU only: `POST /motion/generate` (`motion.npz`, optional BVH on the SOMA skeleton, and with `"fbx": true` a Unity-ready FBX per clip, which the live unit exported for the H3-s2 take), `POST /motion/rest-fbx` (the avatar's rest pose), `GET /motion/artifacts/{jobId}/{name}` (the FBX and BVH bytes), `GET /health`, `GET /operator-state`, and the CultCache service store. The fields added since that export (`loop`, `marks`, `inPlace`) answer on the live unit once a deploy carries them; the job record's `request` shows which ones it kept.
- **Planned:** worker intake closed to local callers only, publication to Odin, and a Thing 2 operator surface. The text-prompt-to-Unity-clip path with no hand steps is `docs/motion-pipeline-target.md`.
## Authority
@ -132,6 +132,8 @@ Supported request fields:
- `cfg`, `cfgType` / `cfg_type`, `cfgWeight` / `cfg_weight`
- `bvh`, `bvhStandardTpose` / `bvh_standard_tpose`
- `fbx` and `clipName` (see FBX Export)
- `loop` (a boolean, valid only with `fbx: true`; see FBX Export)
- `marks` and `inPlace` (see FBX Export): the caller's own, kept in the job record and never given to the worker
- `noPostprocess` / `no_postprocess`
- `saveExampleDir` / `save_example_dir`
- `timeoutMs`, `workerTimeoutMs`, `exportTimeoutMs` (at most 120000)
@ -144,8 +146,6 @@ exports CSV when that model is resident.
## FBX Export
Planned until the next deploy: the live unit does not have these routes or the `fbx` field yet.
`"fbx": true` makes the job's BVH an FBX for Unity, beside it: `motion.fbx`, or `motion/motion_NN.fbx` for several
samples. It implies `bvh` and `bvhStandardTpose`; an explicit `bvhStandardTpose: false` is a 400. `clipName`
(`^[A-Za-z0-9_-]{1,64}$`, default the job id; sample N of several is `<clipName>_NN`) names the armature, the action
@ -166,6 +166,20 @@ timeout, and its output in `<state>/logs/export.log`. It is killed with the work
SIGTERM. A failed export fails the job (`fbx-export-refused` or `fbx-export-failed (...)`, 502) and the answer never
carries Blender's output.
`"loop": true` (with `fbx: true`; otherwise a 400, as is a non-boolean) exports the take's lowest-cost loop window instead
of the whole take. The worker chooses it (`scripts/loop_window.py`) from Kimodo's own posed joints: every joint relative
to its Hips and turned by its own heading (`compute_global_heading`), and the seam from frame `b` back to frame `a`
costs the pose RMS plus 0.1 s times the velocity RMS (central differences, in m and m/s), over `b - a >= ceil(F / 2)`.
The lowest cost wins; a tie goes to the longer window, then the earlier. The worker's answer carries `loops`, one
`{first, last, poseCost, velocityCost}` per sample (BVH frame indices, `last` inclusive), and the daemon hands
sample k's window to `bvh-to-fbx.py` as `--frames <first+1> <last+1>` (Blender counts from 1); the daemon never
computes a window, and an answer without one for a sample fails the job (`fbx-export-failed (no loop window)`).
The BVH and NPZ stay the whole generated take. The job record keeps `request.loop`, `worker.loops` and the clip's
`frames` as Blender reports them, and keeps inline `constraints` as sent (a path otherwise), so a committed record
reproduces its clip. Without `loop` the FBX is the whole take, as before.
`marks` (absent, or at most 32 objects, each exactly `{name, frame}`: `name` matches `^[A-Za-z0-9_-]{1,64}$`, `frame` an integer in `[0, 2^31)` in the take's own frame indices, frame 0 being BVH frame 0) and `inPlace` (absent or a boolean: the caller plays the take in place, so its consumer keeps the root travel in the pose) are the caller's. Vili keeps them verbatim in `request.marks` and `request.inPlace` of the job record and the answer (`marks` omitted when absent or empty, `inPlace` only when true), interprets neither, and never gives either to the worker, so the same request yields the same motion. Anything else is a 400 `Invalid marks request.` before a job directory, a file or a spawn.
One BVH gives the same FBX bytes on one host body (a fixed hash seed and a fixed time stamp); FBX bytes differ
between glibc versions in the last float digits, so the BVH is the cross-body reproducibility unit.

View file

@ -7,6 +7,50 @@ cuts not yet mapped. The target's rationale is `docs/motion-pipeline-target.md`.
## Body facts
### The SOMA avatar against the live export, 2026-10-25
Imagination (imagination-soma-avatar-r3, session sp-reentry-2026-10-21), for
`motion-pipeline:cut_spec:cut-soma-humanoid-avatar.r3` at StreamPixels main `f3280e0`. The live unit is release
`5bcd6700...` from Vili main `51eb113`, reached at `http://10.77.0.1:8824` over WireGuard; its `/health` reports
Blender 5.2.2 LTS and 8 threads. Unity ran on Starfire (2021.3.45f2, batchmode with graphics, one job at a time,
waiting out Soul's runs on `F:\ws\sp-a3b-r7`) in a lean copy of `apps/overlay-unity` (5.5 GB, Library caches left
out) and a 1 GB mini project with no Library, both in the session scratchpad. No repo was changed.
| Probe | Result |
|---|---|
| Rest FBX | `POST /motion/rest-fbx` twice (jobs `rest-1792894213349-4a1879dc`, `rest-1792897207052-c83d9a2d`): `SOMA77_Rest.fbx` 457,852 bytes, sha256 `3a608c93767696220d95534ec6c3b2a619419a13424b71b2af542be43de12f3a` both times. The route serves the FBX only; `SOMA77_Rest.bvh` is a 404. |
| Motion FBX | `POST /motion/generate` with `{"prompt":"A person walks forward happily, pumping both fists in the air to celebrate.","duration":3,"seed":7,"fbx":true,"clipName":...}` took 60 s wall. Three runs gave one BVH (`e2d29634...`, the same bytes as the 2026-10-24 probe) and NPZ (`bf7def08...`). With `clipName` `fixture-celebrate-walk` (job `vili-1792897178490-8de9b8cc`) the FBX is 949,468 bytes, sha256 `e362ad34c0bfae2a4bfcdb41c15783d191c35c4e736d598c6328497efe2e7d3f`. A mope walk ('A person walks forward slowly and sadly, head hanging down and shoulders slumped.', 3 s, seed 7, `probe-mope`) was generated for comparison. |
| Humanoid validation | `ApplyToRest` (table and skeleton set by an editor method, then `SaveAndReimport`): `isValid True`, `isHuman True`, 55 human bones, 79 skeleton entries, `humanScale 0.991`. Hips y 1.000, Head y 1.598, toe 0.011, root scale 1. |
| Finger map | `LeftHandIndex1` unmapped, `LeftHandIndex2 -> Left Index Proximal`, `Index4 -> Distal`, `Thumb1 -> Thumb Proximal`, `RightHandPinky2 -> Right Little Proximal`; `Chest -> UpperChest`; `Neck2` and `Root` unmapped. The table fixes the auto-map's off-by-one. |
| T-pose | Upper arm and forearm directions are (-1, 0, 0) and (1, 0, 0), elevation 0.0 degrees. Thigh is 1.1 degrees off vertical and shin 4.7. Unity accepts it with no Enforce T-Pose: no correction. |
| Reproducing the `.meta` from code | From a Generic import, the first `ApplyToRest` writes 33,313 bytes and the second 33,321; the third equals the second. The two passes differ only in the last float digits of eight skeleton rotations (`z: 0` against `z: -0`, `0.7071068` against `0.70710677`), because the first pass reads the transforms of the Generic import and the second those of the Humanoid one. A fresh copy driven to the fixed point equals the committed `.meta` except its `guid` line. |
| Automatic clip import | An `AssetPostprocessor` scoped to `Assets/Motion/Vili/` sets Human, CopyFromOther and the rest's avatar in `OnPreprocessModel`, calls `context.DependsOnArtifact(rest)`, and sets clip settings in `OnPreprocessAnimation`. `ApplyToRest` alone re-imported both clips through that dependency. Clips: `humanMotion True`, length 2.9667 s, `hasRootCurves True`, `averageSpeed` (0.006, 0, 0.863) celebrate and (0.028, 0, 0.930) mope. |
| Fresh clone, no Library | The mini project held the scripts, the rest with its `.meta`, the celebrate clip with its `.meta` and the mope clip with no `.meta`. Import order was mope (the avatar was not loadable yet: the hook bailed with a warning), then the rest, then celebrate (its `.meta` names the avatar), then mope again through the artifact dependency. All three ended Human from the SOMA avatar with the same `averageSpeed`. The committed `.meta` files were left byte-identical, and the new mope `.meta` equals the lean copy's except for its `guid`. So the first pass on a dropped-in clip legitimately finds no avatar; the hook must not log an error there. |
| The duel's scale | The staged LHMP duelist: `Base NormalAvatar`, `humanScale 0.633`, lossy scale 11.616, so root motion moves 7.354 world units per SOMA metre. LHMP's `Walk` is an in-place loop (`averageSpeed` 0, loop-blend XZ, Y and rotation all baked). The live duel walks out 136.3 units in 12.17 s at 11.21 u/s. Winner and Loser today are `Walk_09_Happy_Dance_Loop` and `Crying`. |
| Foot contact and slide | The method was `AnimationDuelSceneTests.SoleStride`'s skinned-sole contact (within 12 percent of the foot's height range), with the duelist's Walk state overridden by each clip at 60 Hz, giving the mean slide over contact frames in SOMA m/s (units divided by 7.354). The current LHMP Walk in place at its stride (11.24 u/s) slides 0.203. The celebrate clip slides 0.907 with root motion and 0.389 with root motion plus Foot IK on the state; in place it slides 0.595 at its sole stride (5.90 u/s) and 0.606 at the speed derived from `averageSpeed` (6.34 u/s), and 0.716 in place with Foot IK. The mope clip slides 1.175 with root motion, 0.672 with root motion plus Foot IK, and 0.929 and 0.691 in place without and with IK, at a stride of 4.25 to 6.80. On SOMA's own avatar (toe-base joints), the celebrate clip slides 0.065 with root motion and 0.50 in place; the mope clip slides 0.42 either way, which is Kimodo's own shuffle. |
| Root speed profile | Celebrate root velocity on LHMP runs from 0.85 to 7.46 to 10.76 u/s (p10, p50, p90), because the gait lurches with the fist pumps. Mope's runs from 6.32 to 6.87 to 7.33, which is steady. Over 2.97 s, root motion carries the duelist 18.66 u (celebrate) and 20.28 u (mope): 14 and 15 percent of the 136 u exit. |
### The RPS slot clips against live takes, 2026-10-25
Imagination (imagination-rps-clips, session sp-reentry-2026-10-21), for
`motion-pipeline:cut_spec:cut-rps-slot-clips.r1` at StreamPixels main `84d7499`. Takes came from the live unit
(release `5bcd6700...`, 8 threads) by `POST /motion/generate` with `fbx: true`, a fixed `clipName` per slot, a seed and a
duration, and `GET /motion/artifacts/<jobId>/motion.fbx`: 19 takes, 21 to 80 s wall each. Each was imported through the
avatar cut's hook in a lean copy of `apps/overlay-unity` (Library caches left out) and played on the scene's
`Challenger Character` (LHMP, 7.354 u per SOMA m) at 60 Hz, Unity 2021.3.45f2 batchmode with graphics. Slide is the
`SoleStride` stance rule (sole within 12 percent of its height range) applied to the sole's world horizontal speed while the
body is placed by its own root delta, mean and median over stance frames, in SOMA m/s. The takes and their records are
kept in the session scratchpad folder `imagination-rps-clips\takes`. No repo was changed.
| Probe | Result |
|---|---|
| Root delta with root motion off | With `applyRootMotion` false and no `OnAnimatorMove` handler, `animator.deltaPosition` reads 0 every frame (two clips, 960 frames each). With an `[ExecuteAlways]` `OnAnimatorMove` handler on the duelist it reads the clip's travel (148.48 u over 16 s, equal to the handler's sum), in EditMode under `Animator.Update`, and the transform moves 0.0000. So the beat needs a tap on the duelist's GameObject; `AnimationDuel` cannot read the delta itself. |
| Countdown, 7 takes, 4 s | Prompt a, "A person stands still, holds out the open left hand palm up in front of the chest, and pounds the right fist down into the left palm three times, then holds the fist on the palm.", seeds 1 to 3: the hand-curve distance stays at 0.71 m or more except in the first and last 0.25 s (0.43 and 0.48 m at most there); the hands wave apart. Prompt c, "A person raises the right fist and brings it down hard onto the open left palm, three times in a row, then keeps the fist resting on the palm.", seeds 1 and 2: the same, minima 0.67 to 1.08 m. Prompt b, "A person counts one, two, three by bumping the right fist into the open left palm three times at a steady beat, and keeps the fist pressed in the palm after the third bump.": seed 2 meets once (1.450 s, 0.181 m); seed 1 (job `vili-1792907818564-564416e8`, sha256 `01a37f765a0e8627717d64694e08a594f1c44d29f87b7bdaa7cb77645958fd41`) has three contacts by the test's rule, at 0.958, 1.208 and 1.775 s (0.155, 0.160, 0.175 m), but the distance between them peaks at only 0.171 and 0.176 m: one press held from 0.96 to 1.78 s, not three pounds. On the duelist the retargeted wrists at those frames are 2.56 to 2.84 u apart (arm 3.67 u). |
| Raised arms and the icon | Across all seven countdown takes the higher hand stays 6.4 to 8.8 u below the head's top. A weapon pass at the held third hit was run but is not usable: renderer bounds of freshly instantiated weapon prefabs read stale in batchmode (223 of 588 mounts at one identical +103.8 u). |
| Winner, 6 takes, 8 s | "A person walks forward briskly while celebrating, pumping both fists in the air." seeds 1 to 3: 0.26, 0.37, 0.59 m/s. "A happy person struts forward quickly with a victorious bounce, raising both arms in triumph as they walk." seeds 1 to 3: 0.60, 0.66, 0.95 m/s. Best by pace and slide: seed 3 (job `vili-1792908162029-5dea0ac1`, sha256 `bd579f0b54621ca698e7c3b5efad5a54d260d5260118b8e095eae02dec298c09`): 7.02 u/s, 90.9 u by 12.17 s, root speed p10/p50/p90 -0.27/8.70/13.20 u/s, lateral drift 11.6 u in 16 s; slide with Foot IK mean 0.521 median 0.086, without IK 2.087 and 1.479; with loop pose and IK 0.773 and 0.100; seam pose cost 0.054 (muscle RMS plus step RMS, 0 to 7.97 s; no better window). |
| Loser, 6 takes, 8 s | "A person walks forward briskly but dejectedly, head hanging down and shoulders slumped." seeds 1 to 3: 1.26, 1.15, 1.44 m/s. "A disappointed person walks away quickly, head down, shaking their head, arms hanging limply." seeds 1 to 3 turn round and walk backward in the clip's frame (-0.93 to -1.08 m/s): unusable. Best: seed 3 of the first (job `vili-1792908307335-991264b1`, sha256 `009b7240f92f14c27a941d547572ccd56163d22ee11cd6736f3429d545fe5944`): 10.60 u/s, 136.3 u in 11.40 s, lateral 20.9 u in 16 s; slide with loop pose and IK mean 0.557 median 0.143 (seam frames 0.075), with IK only 0.982 and 0.184 (seams 0.646), without IK 2.357 and 2.013; seam cost 0.033, the lowest of all takes. |
| Timing | The countdown slot is unchanged, so `RpsRoundTimeoutSeconds` (8) holds as before (5 + 1.5 + 0.4). Staging: run-in up to about 4.1 s for the widest name plus an exit of 136 to 198 u at 10.6 to 11.2 u/s (12 to 18.7 s), with the 3 s outro gone: at most about 23 s against `RpsStagingTimeoutSeconds` 40. |
### FBX export on Yggdrasil, 2026-10-24
Imagination (imagination-vili-fbx-r3, session sp-reentry-2026-10-21), for
@ -445,6 +489,69 @@ no seed in the record, so no artifact could be reproduced. The daemon now mints
(`crypto.randomInt(0, 2**31)`) and records it for every job, FBX or not
(`artifact-provenance`).
### The avatar cut, r3
r2 was mapped at StreamPixels `84bdd34` against a Raven-era export. r3 maps it to the live Yggdrasil route and
changes four things, each because a probe above disagreed with r2:
- **The `.meta` is a fixed point, not a single pass.** One `ApplyToRest` from a fresh import does not reproduce
the committed bytes; two do, and every pass after that is a no-op. So `ApplyToRest` repeats until the `.meta` stops
changing (at most three passes), and tests pin both ends: it is a no-op on the committed `.meta`, and a fresh copy
converges to it. Rounding the skeleton was rejected because it hides the source of the drift instead of removing it.
- **Provenance lives in the owner, not in a JSON sidecar.** r2 committed `*.provenance.json` beside each FBX. The
only reader would be a test, and a JSON file a test reads is load-bearing. `SomaHumanoid` holds the rest's sha256,
job and Vili release as constants, and the test fixture's request and sha256 sit in the test. Per-clip provenance
for real clips is the RPS clip cut's to place.
- **The hook warns, then the dependency finishes the job.** r2 had the clip hook log an error when the avatar
could not be loaded. On a fresh clone that is the normal first pass for a clip without a `.meta`, and an error
log fails any EditMode test that sees it. `DependsOnArtifact` re-imports the clip once the rest lands, so the
hook logs a warning and returns, and a test asserts the end state of every model under `Assets/Motion/Vili`.
- **The fixture is the live celebrate walk**, not `rps_probe_fist`, which came from Raven and no longer exists.
**How the Winner and Loser exits should travel.** The travel comes from the clip's own root motion, read by the
duel and placed by the beat. The Animator should not move the transform, and the speed should not be a constant.
- *Against a constant speed:* the celebrate gait's root speed spans 0.85 to 10.76 u/s, so no single speed tracks
its feet. In place it slides 0.60 m/s at the best constant, against 0.39 with root motion and Foot IK. For the
steady mope the two are equal (0.69 against 0.67), so root motion costs nothing there.
- *Against the Animator owning position:* today `RpsDuelBeat.WalkFrame` is the one writer of where the duelists
stand, and `Phase.WalkOut` ends when both reach the entrance distance. With `applyRootMotion` on, the Animator
would become a second writer during the exit. The beat could then neither keep a duelist on its line nor know
when the exit is done.
- *So:* `AnimationDuel.OnAnimatorMove` forwards each side's `animator.deltaPosition`, projected on its exit
direction, to the beat. The beat advances that side's own distance and places it, and the exit ends when both
are past the entrance. Winner and Loser get Foot IK in `Battle.controller`. This is the run-in rule
(`rps:ruling:rps-run-speed-from-the-clip`: speed comes from the clip's own contact) carried over to a clip whose
speed varies within the stride. It belongs to the RPS slot-clips cut, not to this one.
- *The open product question* is the exit's length. A 3 s take covers 14 to 15 percent of the 136 u exit, and at
the takes' own pace the walk-off would last about 20 s against 12 s today
(`motion-pipeline:question:rps-exit-pace`).
- *Slide is the clip-selection criterion.* Even the best retargeted take slides about twice as much as LHMP's own
walk (0.39 against 0.20 m/s). The mope take slides 0.42 m/s on its own avatar before any retarget. Takes for the
slot clips should be chosen on measured slide, by the `SoleStride` rule, across seeds.
### The RPS slot clips, r1
- **The exit reads the clip; the beat still places.** `rps-duelists-exit-celebrating-moping` makes the Winner and Loser
motions the exit, so the plain walk, its `WalkSpeed`, the `Walk` slot and state and the 3 s outro all lose their
reason to exist and are deleted. Each tick the beat asks how far each side's clip carried it along its way out
(`IRpsDuelWorld.Travelled`), adds that to the side's own distance and places it on its line. The Animator never moves
a duelist (`applyRootMotion` stays false); its delta reaches the beat through a tap on the duelist, because the probe
shows the delta is 0 without an `OnAnimatorMove` handler. A lerp at a constant would slide the lurching celebrate gait
(its root speed spans -0.27 to 13.2 u/s).
- **Loop, not length.** Kimodo's takes are 8 s and the exit is 12 to 19 s, so the exit clips loop. Loop pose is on for
both: it cut the loser's seam slide from 0.646 to 0.075 m/s and cost the winner little in median (0.086 to 0.100).
Which clips loop is a committed set inside the SOMA hook, so the hook stays the one writer of import settings.
- **Pace is a fork for the winner only.** The mope take meets the ruled pace on its own (1.44 m/s, 11.4 s). No
celebrating take walked faster than 0.95 m/s, so the spec plays it at 1.6 (`motion-pipeline:question:rps-winner-pace`).
- **The countdown is not in this cut.** No take shows three distinct hits; the one that passes the contact rule is a held
press (`motion-pipeline:question:rps-countdown-take`). The exits do not depend on it, so they go first and the countdown
waits for a constrained take. `rps-icon-offhead-gear-raised-arm` stays with the countdown: the hands stay 6.4 u or more
below the head's top in every take, but the weapon reach is unmeasured.
- **No exit ceiling.** A clip with no forward travel would never finish the exit. That is an asset fault, so the editor
test pins it (looping, forward `averageSpeed`), and the director's staging timeout remains the runtime guard. A
ceiling in the beat would pool a duelist in view and add a second rule for when the exit ends.
### Earlier decisions
- **Blender stays; the FBX SDK does not come in.** Skipping Blender would save
@ -471,15 +578,13 @@ no seed in the record, so no artifact could be reproduced. The daemon now mints
## Cuts not yet mapped
`cut-vili-admission` is merged (`c5cf445`), and `cut-vili-fbx-export` r3 is mapped (its spec is in
the mind). One line each for the rest:
`cut-vili-admission` (`c5cf445`) and `cut-vili-fbx-export` (`51eb113`, live as release `5bcd6700...`) are merged,
and `cut-soma-humanoid-avatar` r3 is mapped (its spec is in the mind). One line each for the rest:
- **Raven teardown** (the list under "What retires on Raven"), and Self supersedes the Raven
rulings with it. Waits on nothing now that admission is live.
- **`cut-soma-humanoid-avatar` r3**, its rest FBX taken from `POST /motion/rest-fbx` on Yggdrasil
instead of Raven. Waits on the FBX cut.
- **RPS slot clips** (`motion-pipeline:follow_up:rps-slot-clips-from-vili`; Winner and Loser travel,
`rps:ruling:rps-duelists-exit-celebrating-moping`). Waits on the avatar cut.
- **RPS slot clips**: the exits are mapped (`motion-pipeline:cut_spec:cut-rps-slot-clips.r1`, blocked on
`rps-countdown-take` and `rps-winner-pace`). The countdown waits for a constrained take.
- **Vili intake closed** (`motion-pipeline:follow_up:vili-worker-intake-local-callers` and
`vili-caller-read-paths-2`). Independent of the FBX cut.
- **Vili publishes to Odin over CultMesh**, as StreamPixels' service does. Waits on nothing.

View file

@ -1,6 +1,9 @@
# Converts one Kimodo standard-T-pose BVH to one FBX. Blender converts formats and nothing else: no retarget, no
# rename, no key reduction, no resample, no root-motion bake. Run by the daemon (scripts/vili-daemon.mjs exportClip):
# blender -b --factory-startup --python-use-system-env --python-exit-code 1 --python bvh-to-fbx.py -- <bvh> <fbx> <clipName>
# rename, no key reduction, no resample, no root-motion bake. It applies the frame range it is handed and chooses
# none: the whole take unless the daemon passes --frames. Run by the daemon (scripts/vili-daemon.mjs exportClip):
# blender -b --factory-startup --python-use-system-env --python-exit-code 1 --python bvh-to-fbx.py -- <bvh> <fbx> <clipName> [--frames <A> <B>]
# Frames are Blender's, counted from 1: the BVH's frame k is Blender's k + 1. Exit 3 is an argument or a hash seed it
# will not take, exit 4 a range outside the take.
# with PYTHONHASHSEED=0 in the environment. The settings are Blender API parameters, cross-checked against the
# 'unity' preset of wifimetas/kimodo-mcp blender_export.py (Apache-2.0, 83b5361); no code is copied.
import datetime
@ -15,7 +18,9 @@ import bpy
if sys.flags.hash_randomization != 0:
sys.exit(3)
bvh, fbx, clip = sys.argv[sys.argv.index("--") + 1:]
bvh, fbx, clip, *window = sys.argv[sys.argv.index("--") + 1:]
if window and not (len(window) == 3 and window[0] == "--frames" and all(arg.isdigit() for arg in window[1:])):
sys.exit(3)
bpy.ops.wm.read_factory_settings(use_empty=True)
scene = bpy.context.scene
@ -38,6 +43,10 @@ action = armature.animation_data.action
# The FBX take takes the scene's name.
armature.name = armature.data.name = action.name = scene.name = clip
first, last = (int(frame) for frame in action.frame_range)
if window:
first, last = int(window[1]), int(window[2])
if not (int(action.frame_range[0]) <= first < last <= int(action.frame_range[1])):
sys.exit(4)
scene.frame_start, scene.frame_end = first, last
bpy.ops.object.select_all(action="DESELECT")

View file

@ -1,7 +1,7 @@
// Stands in for kimodo-resident-worker.py in the daemon's tests. It binds port 0, prints the ready line the
// daemon waits for, and answers /health and /generate with what the daemon gave it. The --model value picks a
// misbehaviour: crash-before-ready, hang-before-ready, sick, slow-health, stubborn, fail-generate,
// refuse-generate, drop-generate, slow-generate, writer (appends to <output>.writes every 50 ms, never answers, ignores SIGTERM), slow-to-stop (no answer; prints a line and exits 1.5 s after SIGTERM), chatty (prints a line the moment it is healthy), encoder (a grandchild, then no answer), graceful (exits 0.5 s after SIGTERM), die-after-ready, bvh-outside (lists a BVH outside the job's directory), bvh-link (lists a symlink as its BVH), bvh-fifo (lists a FIFO as its BVH), plant-link (a normal answer with a file symlink and a directory symlink planted beside the BVH). A request with bvh writes <output>.bvh (motion/motion_NN.bvh for several samples) and lists it. Any other value is just the model the worker serves.
// refuse-generate, drop-generate, slow-generate, writer (appends to <output>.writes every 50 ms, never answers, ignores SIGTERM), slow-to-stop (no answer; prints a line and exits 1.5 s after SIGTERM), chatty (prints a line the moment it is healthy), encoder (a grandchild, then no answer), graceful (exits 0.5 s after SIGTERM), die-after-ready, bvh-outside (lists a BVH outside the job's directory), bvh-link (lists a symlink as its BVH), bvh-fifo (lists a FIFO as its BVH), plant-link (a normal answer with a file symlink and a directory symlink planted beside the BVH), no-loops (a normal answer that leaves out the loops a loop request asked for), bad-loops, negative-loops, empty-loops, fractional-last-loops (loops whose window is not a frame range: a fractional first, a negative first, first equal to last, a fractional last), short-loops (one window fewer than samples). A loop request is answered with loops, sample k as {first 3 + k, last 223 + k}. A request with bvh writes <output>.bvh (motion/motion_NN.bvh for several samples) and lists it. Any other value is just the model the worker serves.
import http from "node:http";
import os from "node:os";
import path from "node:path";
@ -14,6 +14,12 @@ const flag = (name) => {
return index < 0 ? undefined : argv[index + 1];
};
const model = flag("--model");
const BAD_WINDOWS = {
"bad-loops": { first: 5.5, last: 9 },
"negative-loops": { first: -1, last: 9 },
"empty-loops": { first: 7, last: 7 },
"fractional-last-loops": { first: 5, last: 9.5 },
};
const spawnLog = path.join(process.env.VILI_EMBEDDINGS_DIR, "stub-spawns.log");
let requests = 0;
let healthCalls = 0;
@ -117,6 +123,10 @@ if (model === "hang-before-ready") {
seed: payload.seed,
metaSeed: payload.meta?.seed,
bvh: payload.bvh,
...(payload.loop && model !== "no-loops" ? {
loops: Array.from({ length: payload.numSamples - (model === "short-loops" ? 1 : 0) }, (_, k) => (BAD_WINDOWS[model]
?? { first: 3 + k, last: 223 + k, poseCost: 0.03, velocityCost: 0.2 })),
} : {}),
bvhStandardTpose: payload.bvhStandardTpose,
model: model || "stub-model",
pid: process.pid,

BIN
scripts/fixtures/take.npz Normal file

Binary file not shown.

View file

@ -28,6 +28,7 @@ from kimodo.scripts.generate import (
)
from kimodo.tools import save_json, seed_everything
import loop_window
import text_encoding
@ -319,6 +320,7 @@ def generate(payload):
request_bool(payload, "bvh"),
request_bool(payload, "bvhStandardTpose") or request_bool(payload, "bvh_standard_tpose"),
)
loops = loop_window.loop_windows(output, model) if request_bool(payload, "loop") else None
if request_bool(payload, "saveExampleDir") or request_bool(payload, "save_example_dir"):
files.extend(save_example_dirs(output_base, texts, num_frames, num_samples, constraints_path))
generation_count += 1
@ -347,6 +349,7 @@ def generate(payload):
"constraints": constraints_path,
"seed": seed,
"files": files,
**({"loops": loops} if loops is not None else {}),
"encoder": encoder_record,
"worker": worker_identity,
"timing": {

60
scripts/loop_window.py Normal file
View file

@ -0,0 +1,60 @@
"""The frame window of a generated take that loops with the smallest seam. Called by the resident worker, nowhere else.
A seam is the jump from frame b back to frame a. Its cost is the pose difference plus 0.1 s times the velocity
difference (Kovar, Gleicher and Pighin 2002, motion-graph transitions), both as RMS over joints, with each frame
taken relative to its own Hips and turned to face a fixed way, so where the take wanders and which way it faces
do not count. loop_window is numpy only; loop_windows needs torch and kimodo's heading, and no model weights.
"""
import math
import numpy as np
import torch
from kimodo.constraints import compute_global_heading
VELOCITY_WEIGHT_SECONDS = 0.1
def loop_window(joints, heading, fps, min_frames, hips=0):
"""joints [F, J, 3] world positions, heading [F] radians about Y (Kimodo's hip-vector angle), the joint index of
Hips. Returns (first, last, pose_cost, velocity_cost): frame indices into the take, last inclusive, last - first
at least min_frames, the pair with the lowest cost. A tie goes to the longer window, then to the earlier first."""
joints = np.asarray(joints, dtype=np.float64)
heading = np.asarray(heading, dtype=np.float64)
frames = joints.shape[0]
if joints.ndim != 3 or joints.shape[2] != 3 or heading.shape != (frames,) or not 1 <= min_frames < frames:
raise ValueError("loop_window: shapes or min_frames out of range")
relative = joints - joints[:, hips:hips + 1]
cos, sin = np.cos(-heading), np.sin(-heading)
x, z = relative[..., 0], relative[..., 2]
pose = relative.copy()
pose[..., 0] = x * cos[:, None] + z * sin[:, None]
pose[..., 2] = -x * sin[:, None] + z * cos[:, None]
velocity = np.gradient(pose, axis=0) * fps # central differences, one-sided at the two ends
firsts, lasts = np.triu_indices(frames, k=min_frames)
pose_cost = np.empty(len(firsts))
velocity_cost = np.empty(len(firsts))
for first in range(frames - min_frames): # one row of seams at a time: memory stays O(frames * joints)
row = slice(*np.searchsorted(firsts, [first, first + 1]))
later = lasts[row]
pose_cost[row] = np.sqrt(((pose[later] - pose[first]) ** 2).sum(-1).mean(-1))
velocity_cost[row] = np.sqrt(((velocity[later] - velocity[first]) ** 2).sum(-1).mean(-1))
cost = pose_cost + VELOCITY_WEIGHT_SECONDS * velocity_cost
best = np.flatnonzero(cost == cost.min())
pick = best[np.lexsort((firsts[best], -(lasts[best] - firsts[best])))[0]]
return int(firsts[pick]), int(lasts[pick]), float(pose_cost[pick]), float(velocity_cost[pick])
def loop_windows(output, model):
"""One loop window per sample of a Kimodo output, as the worker answers them: {first, last, poseCost, velocityCost},
frame indices into the take, last inclusive. The joints are posed_joints, always in model.output_skeleton (the
somaskel77, not model.skeleton), and the heading is Kimodo's own from those joints."""
skeleton = model.output_skeleton
hips = skeleton.bone_index["Hips"]
windows = []
for joints in output["posed_joints"]:
heading = compute_global_heading(torch.from_numpy(joints[None]), skeleton)[0]
angle = torch.atan2(heading[:, 1], heading[:, 0]).numpy()
first, last, pose_cost, velocity_cost = loop_window(joints, angle, model.fps, math.ceil(len(joints) / 2), hips)
windows.append({"first": first, "last": last, "poseCost": pose_cost, "velocityCost": velocity_cost})
return windows

View file

@ -1441,6 +1441,191 @@ test("fbx refusals happen before anything is written or spawned", async () => {
}
});
test("loop asks for the seamless window, and the window is the FBX's frame range", async () => {
const daemon = await startDaemon();
try {
const constraints = [{ type: "root2d", frame_indices: [0, 10], smooth_root_2d: [[0, 0], [0, 0.5]] }];
const answer = await generate(daemon, exportRequest({ clipName: "walk", seed: 7, loop: true, constraints }));
assert.equal(answer.status, 200);
const job = answer.body;
assert.equal(job.request.loop, true);
assert.deepEqual(job.worker.loops, [{ first: 3, last: 223, poseCost: 0.03, velocityCost: 0.2 }]);
assert.deepEqual(job.request.constraints, constraints, "the record keeps inline constraints as sent");
assert.deepEqual(JSON.parse(readFileSync(path.join(job.artifactDir, "constraints.json"), "utf8")), constraints);
assert.equal(JSON.parse(readFileSync(path.join(job.artifactDir, "request.json"), "utf8")).loop, true, "the worker is asked for the loop");
assert.equal(job.worker.constraints, path.join(job.artifactDir, "constraints.json"), "the worker still gets the path");
const [run] = exportStarts(daemon);
assert.deepEqual(run.argv.slice(run.argv.indexOf("--") + 3), ["walk", "--frames", "4", "224"], "Blender's frames count from 1");
assert.deepEqual(job.export.clips.map((clip) => clip.frames), [[1, 60]], "the clip's frames are what Blender reports");
const several = await generate(daemon, exportRequest({ clipName: "pair", numSamples: 2, loop: true }));
assert.equal(several.status, 200);
assert.deepEqual(several.body.worker.loops.map((loop) => [loop.first, loop.last]), [[3, 223], [4, 224]]);
const frames = Object.fromEntries(exportStarts(daemon).slice(1).map((start) => {
const [, , clip, ...rest] = start.argv.slice(start.argv.indexOf("--") + 1);
return [clip, rest];
}));
assert.deepEqual(frames, { pair_00: ["--frames", "4", "224"], pair_01: ["--frames", "5", "225"] }, "each sample is exported over its own window");
const plain = await generate(daemon, exportRequest({ clipName: "plain" }));
assert.equal(plain.status, 200);
assert.equal(plain.body.worker.loops, undefined);
assert.equal(plain.body.request.loop, undefined);
assert.equal(JSON.parse(readFileSync(path.join(plain.body.artifactDir, "request.json"), "utf8")).loop, undefined);
assert.equal(exportStarts(daemon).at(-1).argv.at(-1), "plain", "no window, no --frames");
const kept = await generate(daemon, exportRequest({ constraints_path: "/some/where.json", constraints: undefined }));
assert.equal(kept.body.request.constraints, "/some/where.json", "a path stays a path");
} finally {
await daemon.stop();
}
});
test("past 100 samples each clip is exported over the window of its own sample", async () => {
const daemon = await startDaemon();
try {
const answer = await generate(daemon, exportRequest({ clipName: "m", loop: true, numSamples: 101, exportTimeoutMs: 60000 }));
assert.equal(answer.status, 200);
const starts = exportStarts(daemon);
assert.equal(answer.body.export.clips.length, 101);
answer.body.export.clips.forEach((clip, i) => {
const sample = Number(/motion_(\d+)\.fbx$/.exec(clip.file)[1]);
const argv = starts[i].argv.slice(starts[i].argv.indexOf("--") + 1);
assert.equal(argv[2], `m_${String(sample).padStart(2, "0")}`, `${clip.file} is named for its sample`);
assert.deepEqual(argv.slice(3), ["--frames", String(4 + sample), String(224 + sample)], `${clip.file} gets its own sample's window`);
});
assert.ok(answer.body.export.clips.some((clip) => clip.file.endsWith("motion_100.fbx")));
} finally {
await daemon.stop();
}
});
test("constraints given twice are refused before anything is written or spawned", async () => {
const daemon = await startDaemon();
try {
const inline = [{ type: "root2d" }];
for (const bad of [
{ constraints: inline, constraints_path: "/canary/a.json" },
{ constraints: inline, constraintsPath: "/canary/a.json" },
{ constraints: "/canary/a.json", constraints_path: "/canary/b.json" },
{ constraints_path: "/canary/a.json", constraintsPath: "/canary/b.json" },
]) {
const answer = await generate(daemon, exportRequest(bad));
assert.equal(answer.status, 400, JSON.stringify(bad));
assert.deepEqual(answer.body, { ok: false, error: "Invalid constraints request." });
assert.ok(!answer.raw.includes("canary"), "the refusal repeated the input");
}
assert.equal(existsSync(path.join(daemon.stateRoot, "artifacts")), false, "no artifact directory was made");
assert.deepEqual(jobFiles(daemon), []);
assert.deepEqual(daemon.spawns(), [], "no worker was started");
assert.equal((await generate(daemon, exportRequest({ constraints_path: "/some/where.json" }))).status, 200, "one input is fine");
} finally {
await daemon.stop();
}
});
test("loop is a boolean and needs fbx, refused before anything is written or spawned", async () => {
const daemon = await startDaemon();
try {
for (const bad of [{ fbx: false, loop: true }, { fbx: undefined, loop: true }, { loop: "yes canary" }, { loop: 1 }, { loop: null }, { loop: "true" }]) {
const answer = await generate(daemon, exportRequest(bad));
assert.equal(answer.status, 400, JSON.stringify(bad));
assert.deepEqual(answer.body, { ok: false, error: "Invalid fbx request." });
assert.ok(!answer.raw.includes("canary"), "the refusal repeated the input");
}
assert.equal(existsSync(path.join(daemon.stateRoot, "artifacts")), false, "no artifact directory was made");
assert.deepEqual(jobFiles(daemon), []);
assert.deepEqual(daemon.spawns(), [], "no worker was started");
assert.equal(exportStarts(daemon).length, 0);
assert.equal((await generate(daemon, exportRequest({ loop: false }))).status, 200, "loop false is no loop");
assert.equal((await generate(daemon, { prompt: "a person waves", duration: 2, loop: false })).status, 200);
} finally {
await daemon.stop();
}
});
test("marks and inPlace are kept in the record and never reach the worker", async () => {
const daemon = await startDaemon();
try {
const marks = [{ name: "RpsHit", frame: 38 }, { name: "RpsHit", frame: 53 }, { name: "RpsHit", frame: 68 }];
const marked = await generate(daemon, exportRequest({ clipName: "cd", seed: 7, marks, inPlace: true }));
assert.equal(marked.status, 200);
assert.deepEqual(marked.body.request.marks, marks);
assert.equal(marked.body.request.inPlace, true);
const record = JSON.parse(readFileSync(path.join(daemon.stateRoot, "jobs", `${marked.body.jobId}.json`), "utf8"));
assert.deepEqual(record.request.marks, marks, "the stored record keeps them too");
const sent = JSON.parse(readFileSync(path.join(marked.body.artifactDir, "request.json"), "utf8"));
assert.ok(!("marks" in sent) && !("inPlace" in sent), "the worker request carries neither");
const meta = readFileSync(path.join(marked.body.artifactDir, "meta.json"), "utf8");
assert.ok(!meta.includes("RpsHit") && !meta.includes("inPlace"), "meta.json carries neither");
const plain = await generate(daemon, exportRequest({ clipName: "cd", seed: 7 }));
assert.equal(plain.status, 200);
assert.ok(!("marks" in plain.body.request) && !("inPlace" in plain.body.request), "no marks, no keys");
const hash = (job, name) => job.files.find((file) => file.name === name).sha256;
for (const name of ["motion.bvh", "motion.fbx"]) assert.equal(hash(marked.body, name), hash(plain.body, name), `${name} is the same motion`);
const empty = await generate(daemon, exportRequest({ marks: [], inPlace: false }));
assert.equal(empty.status, 200);
assert.ok(!("marks" in empty.body.request) && !("inPlace" in empty.body.request), "empty marks and inPlace false are not recorded");
const bare = await generate(daemon, { prompt: "a person waves", duration: 2, marks: [{ name: "a", frame: 0 }], inPlace: true });
assert.equal(bare.status, 200, "without fbx");
assert.deepEqual(bare.body.request.marks, [{ name: "a", frame: 0 }]);
assert.equal(bare.body.request.inPlace, true);
const batch = await generate(daemon, { texts: ["a person waves", "a person sits"], durations: [1, 1], marks: [{ name: "b", frame: 2147483647 }] });
assert.equal(batch.status, 200, "a batch");
assert.deepEqual(batch.body.request.marks, [{ name: "b", frame: 2147483647 }]);
const many = Array.from({ length: 32 }, (_, i) => ({ name: `m${i}`, frame: i }));
assert.equal((await generate(daemon, exportRequest({ marks: many }))).status, 200, "32 marks is the limit, not past it");
} finally {
await daemon.stop();
}
});
test("malformed marks or inPlace are refused before anything is written or spawned", async () => {
const daemon = await startDaemon();
try {
const mark = (extra) => ({ name: "a", frame: 1, ...extra });
for (const bad of [
{ marks: "x canary" }, { marks: {} }, { marks: null }, { marks: [null] }, { marks: ["a"] },
{ marks: [mark({ name: "a b canary" })] }, { marks: [mark({ name: "" })] }, { marks: [mark({ name: 5 })] },
{ marks: [{ frame: 1 }] }, { marks: [{ name: "a" }] },
{ marks: [mark({ frame: -1 })] }, { marks: [mark({ frame: 1.5 })] }, { marks: [mark({ frame: "1" })] },
{ marks: [mark({ frame: 2147483648 })] }, { marks: [mark({ frame: null })] },
{ marks: [mark({ extra: 0 })] },
{ marks: Array.from({ length: 33 }, (_, i) => ({ name: `m${i}`, frame: i })) },
{ inPlace: "true" }, { inPlace: 1 }, { inPlace: null }, { inPlace: {} },
]) {
const answer = await generate(daemon, exportRequest(bad));
assert.equal(answer.status, 400, JSON.stringify(bad));
assert.deepEqual(answer.body, { ok: false, error: "Invalid marks request." });
assert.ok(!answer.raw.includes("canary"), "the refusal repeated the input");
}
assert.equal(existsSync(path.join(daemon.stateRoot, "artifacts")), false, "no artifact directory was made");
assert.deepEqual(jobFiles(daemon), []);
assert.deepEqual(daemon.spawns(), [], "no worker was started");
assert.equal(exportStarts(daemon).length, 0);
} finally {
await daemon.stop();
}
});
test("a loop request whose answer has no usable window for a sample fails without exporting that sample", async () => {
for (const [model, exported] of [["no-loops", 0], ["bad-loops", 0], ["negative-loops", 0], ["empty-loops", 0], ["fractional-last-loops", 0], ["short-loops", 1]]) {
const daemon = await startDaemon();
try {
const answer = await generate(daemon, exportRequest({ model, loop: true, numSamples: 2 }));
assert.equal(answer.status, 502, model);
assert.equal(answer.body.ok, false);
assert.equal(answer.body.error, "fbx-export-failed (no loop window)");
assert.equal(exportStarts(daemon).length, exported, `${model}: only a sample with a window is exported`);
assert.equal(answer.body.export.clips.length, exported);
} finally {
await daemon.stop();
}
}
});
test("the BVH is never given to Blender unless it is a regular file inside the job's directory", async () => {
const daemon = await startDaemon();
try {

View file

@ -155,6 +155,21 @@ class BvhToFbx(unittest.TestCase):
line = next(line for line in run.stdout.splitlines() if line.startswith("INSPECT "))
return json.loads(line[len("INSPECT "):])
def walk(self, name, frames):
"""A BVH of the rest pose's skeleton whose Hips travel one metre, accelerating, and whose Spine1 is turned."""
text = self.rest.read_text()
header = text[:text.index("MOTION")]
channels = sum(int(n) for n in re.findall(r"CHANNELS\s+(\d+)", header))
rows = []
for frame in range(frames):
row = ["0"] * channels
row[8] = repr(100.0 * (frame / (frames - 1)) ** 2) # Hips Zposition, cm: one metre, accelerating
row[12], row[13], row[14] = "30", "20", "40" # Spine1 Z, Y, X rotation: the Euler order matters
rows.append(" ".join(row))
bvh = self.dir / f"{name}.bvh"
bvh.write_text(f"{header}MOTION\nFrames: {frames}\nFrame Time: 0.0333333\n" + "\n".join(rows) + "\n")
return bvh
def test_rest_pose_keeps_the_bvh_joint_names_and_height(self):
fbx = self.dir / "rest.fbx"
run = convert(self.rest, fbx, "SOMA77_Rest")
@ -189,18 +204,8 @@ class BvhToFbx(unittest.TestCase):
self.assertFalse(target.exists())
def test_a_clip_keeps_its_travel_timing_pose_and_name(self):
text = self.rest.read_text()
header = text[:text.index("MOTION")]
channels = sum(int(n) for n in re.findall(r"CHANNELS\s+(\d+)", header))
frames = 31
rows = []
for frame in range(frames):
row = ["0"] * channels
row[8] = repr(100.0 * (frame / (frames - 1)) ** 2) # Hips Zposition, cm: one metre, accelerating
row[12], row[13], row[14] = "30", "20", "40" # Spine1 Z, Y, X rotation: the Euler order matters
rows.append(" ".join(row))
bvh = self.dir / "walk.bvh"
bvh.write_text(f"{header}MOTION\nFrames: {frames}\nFrame Time: 0.0333333\n" + "\n".join(rows) + "\n")
bvh = self.walk("walk", frames)
fbx = self.dir / "walk.fbx"
run = convert(bvh, fbx, "walk")
self.assertEqual(run.returncode, 0, run.stderr[-2000:])
@ -222,6 +227,32 @@ class BvhToFbx(unittest.TestCase):
for got, want in zip(seen["head_from_hips"], seen["reference_head_from_hips"]):
self.assertAlmostEqual(got, want, delta=0.002, msg="the rotated pose is Blender's own native reading of the BVH")
def test_frames_exports_that_range_and_nothing_else(self):
bvh = self.walk("long", 61)
fbx = self.dir / "window.fbx"
run = blender("--python", str(SCRIPT), "--", str(bvh), str(fbx), "window", "--frames", "5", "40")
self.assertEqual(run.returncode, 0, run.stderr[-2000:])
self.assertEqual(result(run), {"bones": 78, "frames": [5, 40], "fps": 30})
seen = self.inspect(fbx, bvh)
# The BVH's frame k is Blender's k + 1, so frames 5..40 are BVH rows 4..39 and Hips z is 100 (k/60)^2 cm.
self.assertAlmostEqual(seen["hips_travel"], (39 ** 2 - 4 ** 2) / 60 ** 2, delta=0.002, msg=json.dumps(seen))
self.assertEqual(set(fbx_key_counts(fbx)), {36}, "one key per frame of the window")
whole = self.dir / "whole.fbx"
self.assertEqual(result(convert(bvh, whole, "whole"))["frames"], [1, 61], "without --frames the take is whole")
def test_frames_outside_the_take_or_malformed_exit_without_a_file(self):
bvh = self.walk("short", 31)
for index, (arguments, exit_code) in enumerate((
(("--frames", "0", "10"), 4), (("--frames", "5", "32"), 4), (("--frames", "10", "10"), 4),
(("--frames", "20", "10"), 4),
(("--frames", "5"), 3), (("--frames", "a", "9"), 3), (("--frames", "-1", "9"), 3),
(("--frames", "4", "20", "9"), 3), (("--range", "4", "20"), 3), (("4", "20"), 3),
)):
fbx = self.dir / f"refused{index}.fbx"
run = blender("--python", str(SCRIPT), "--", str(bvh), str(fbx), "refused", *arguments)
self.assertEqual(run.returncode, exit_code, arguments)
self.assertFalse(fbx.exists(), arguments)
if __name__ == "__main__":
unittest.main()

189
scripts/test_loop_window.py Normal file
View file

@ -0,0 +1,189 @@
"""python3 -m unittest scripts/test_loop_window.py (numpy, torch and kimodo; no model weights)"""
import math
import pathlib
import sys
import unittest
import numpy as np
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from loop_window import loop_window, loop_windows # noqa: E402
from types import SimpleNamespace # noqa: E402
FPS = 30
def turn(points, angle):
"""Rotate points [..., 3] about Y by angle, so that +Z turns toward +X (Kimodo's heading: 0 faces +Z)."""
x, z = points[..., 0], points[..., 2]
out = points.copy()
out[..., 0] = x * math.cos(angle) + z * math.sin(angle)
out[..., 2] = -x * math.sin(angle) + z * math.cos(angle)
return out
def stride(frames=240, period=37, start=40, end=200):
"""A stride cycle between two different rests. Hips travels; every other joint swings."""
rng = np.random.default_rng(3)
rest_a, rest_b = rng.normal(size=(2, 6, 3)) * 0.3
phase, direction = rng.uniform(0, 6.28, 6), rng.normal(size=(6, 3))
out = np.zeros((frames, 7, 3))
for f in range(frames):
weight = min(1.0, f / start, (frames - 1 - f) / (frames - 1 - end))
rest = rest_a if f < frames // 2 else rest_b
cycle = 0.2 * np.sin(2 * math.pi * f / period + phase)[:, None] * direction
out[f, 1:] = weight * (rest_a + cycle) + (1 - weight) * rest
out[f, 0] = (0.03 * f, 0.9, 0.0) # Hips
out[f, 1:] += out[f, 0]
return out
def reference(joints, heading, fps, min_frames):
"""The cost written out frame by frame and joint by joint, to check the vectorised search against."""
frames, count = joints.shape[0], joints.shape[1]
pose = np.zeros((frames, count, 3))
for f in range(frames):
pose[f] = turn(joints[f] - joints[f, 0], -heading[f])
velocity = np.zeros_like(pose)
for f in range(frames):
lo, hi = max(f - 1, 0), min(f + 1, frames - 1)
velocity[f] = (pose[hi] - pose[lo]) / (hi - lo) * fps
best = None
for a in range(frames):
for b in range(a + min_frames, frames):
p = math.sqrt(sum(np.sum((pose[b, j] - pose[a, j]) ** 2) for j in range(count)) / count)
v = math.sqrt(sum(np.sum((velocity[b, j] - velocity[a, j]) ** 2) for j in range(count)) / count)
cost = p + 0.1 * v
key = (cost, -(b - a), a)
if best is None or key < best[0]:
best = (key, a, b, p, v)
return best[1:]
def wandering(frames=44, count=4, seed=0):
"""A smooth, unrepeating motion that turns as it goes, so the best window is unique and pose, velocity and
heading each move it."""
rng = np.random.default_rng(seed)
time = np.arange(frames)
joints = sum(rng.normal(size=(1, count, 3)) * 0.3 * np.sin(time[:, None, None] * rng.uniform(0.05, 0.5) + rng.uniform(0, 6.28))
for _ in range(4))
heading = sum(0.4 * np.sin(time * rng.uniform(0.03, 0.2) + rng.uniform(0, 6.28)) for _ in range(2))
return joints, heading
class LoopWindow(unittest.TestCase):
def test_a_periodic_motion_between_rest_ramps(self):
joints = stride()
first, last, pose_cost, _ = loop_window(joints, np.zeros(240), FPS, 120)
self.assertGreaterEqual(first, 40)
self.assertLessEqual(last, 200)
self.assertEqual((last - first) % 37, 0, (first, last))
self.assertGreaterEqual(last - first, 120)
self.assertLess(pose_cost, 1e-3)
self.assertNotEqual((first, last), (0, 239), "the whole take is not the answer")
def test_the_search_is_the_stated_cost(self):
joints, heading = wandering()
want_first, want_last, want_pose, want_velocity = reference(joints, heading, FPS, 22)
got = loop_window(joints, heading, FPS, 22)
self.assertEqual(got[:2], (want_first, want_last))
self.assertAlmostEqual(got[2], want_pose, places=9)
self.assertAlmostEqual(got[3], want_velocity, places=9)
# The velocity term decides here: matching poses alone would pick another window.
pose_only = min(
((np.sqrt(((turn(joints[b] - joints[b, 0], -heading[b]) - turn(joints[a] - joints[a, 0], -heading[a])) ** 2).sum(-1).mean()), a, b)
for a in range(44) for b in range(a + 22, 44)))
self.assertNotEqual(pose_only[1:], (want_first, want_last))
def test_heading_is_normalised_away(self):
joints, heading = wandering()
upright = np.stack([turn(joints[f] - joints[f, :1], -heading[f]) + joints[f, :1] for f in range(44)])
turned = np.stack([turn(upright[f] - upright[f, :1], heading[f]) + upright[f, :1] for f in range(44)])
want = loop_window(upright, np.zeros(44), FPS, 22)
got = loop_window(turned, heading, FPS, 22)
self.assertEqual(got[:2], want[:2])
self.assertAlmostEqual(got[2], want[2], places=9)
self.assertNotEqual(loop_window(turned, np.zeros(44), FPS, 22)[:2], want[:2], "the turning would otherwise change the answer")
def test_a_tie_goes_to_the_longer_window_then_the_earlier(self):
cycle = np.array([[0, 0, 0], [0.5, 0.2, 0.1], [0.2, 0.7, 0.3], [0.4, 0.1, 0.9]], dtype=float)
joints = np.stack([np.stack([np.zeros(3), cycle[f % 4]]) for f in range(30)])
# Exact repeats every 4 frames: every a, b with b - a a multiple of 4 inside 1..28 costs zero.
self.assertEqual(loop_window(joints, np.zeros(30), FPS, 15)[:2], (1, 25))
still = np.zeros((30, 3, 3))
self.assertEqual(loop_window(still, np.zeros(30), FPS, 15)[:2], (0, 29))
def test_no_window_is_shorter_than_the_minimum(self):
joints, heading = wandering(frames=31)
for minimum in (5, 16, 25):
first, last, _, _ = loop_window(joints, heading, FPS, minimum)
self.assertGreaterEqual(last - first, minimum)
self.assertEqual(loop_window(joints, heading, FPS, 30)[:2], (0, 30))
def test_hips_is_the_joint_it_is_told(self):
joints, heading = wandering()
moved = joints[:, [2, 0, 1, 3]]
self.assertEqual(loop_window(moved, heading, FPS, 22, hips=1), loop_window(joints, heading, FPS, 22, hips=0))
def test_shapes_and_minimum_are_checked_without_echoing_them(self):
joints, heading = wandering()
for bad in ((joints, heading[:-1], 22), (joints, heading, 0), (joints, heading, 4321), (joints[..., :2], heading, 22)):
with self.assertRaises(ValueError) as caught:
loop_window(bad[0], bad[1], FPS, bad[2])
self.assertNotIn("4321", str(caught.exception))
class StandInSkeleton:
"""What kimodo's heading and the worker read of a skeleton: the names and parents of the real one, its Hips index
and the [right, left] hip joints (RightLeg, LeftLeg) that heading is taken from."""
def __init__(self, names, parents):
self.bone_order_names = [str(name) for name in names]
self.bone_index = {name: index for index, name in enumerate(self.bone_order_names)}
self.bone_parents = {name: (None if parent < 0 else self.bone_order_names[parent]) for name, parent in zip(self.bone_order_names, parents)}
self.hip_joint_idx = [self.bone_index["RightLeg"], self.bone_index["LeftLeg"]]
class WorkerLoopWindowsTest(unittest.TestCase):
"""loop_windows on a real generated take (the somaskel77 joints of a live Vili take, 240 frames at 30 fps), with
stand-ins for the model's two skeletons: the 77-joint output skeleton and the 30-joint one the model also carries."""
@classmethod
def setUpClass(cls):
data = np.load(pathlib.Path(__file__).resolve().parent / "fixtures" / "take.npz")
cls.joints = data["joints"]
cls.model = SimpleNamespace(
output_skeleton=StandInSkeleton(data["names77"], data["parents77"]),
skeleton=StandInSkeleton(data["names30"], data["parents30"]),
fps=FPS,
)
def window(self, joints):
(answer,) = loop_windows({"posed_joints": [joints]}, self.model)
return answer["first"], answer["last"]
def test_the_real_take_gets_the_window_of_its_own_heading_in_the_output_skeleton(self):
self.assertEqual(self.joints.shape, (240, 77, 3))
self.assertEqual(self.model.output_skeleton.hip_joint_idx, [72, 67])
self.assertEqual(self.model.skeleton.hip_joint_idx, [26, 22])
self.assertEqual(self.window(self.joints), (35, 222))
# The 30-joint skeleton's hip indices read the wrong joints of a 77-joint take and move the window.
wrong = SimpleNamespace(output_skeleton=self.model.skeleton, fps=FPS)
self.assertNotEqual(loop_windows({"posed_joints": [self.joints]}, wrong)[0]["first"], 35)
def test_turning_the_body_about_its_hips_by_a_smooth_angle_leaves_the_window(self):
turned = np.stack([
turn(self.joints[f] - self.joints[f, 0], 0.8 * math.sin(0.05 * f)) + self.joints[f, 0] for f in range(len(self.joints))
]).astype(np.float32)
self.assertEqual(self.window(turned), (35, 222))
def test_each_sample_gets_its_own_window_with_its_costs(self):
still = np.repeat(self.joints[:1], 240, axis=0)
answers = loop_windows({"posed_joints": [self.joints, still]}, self.model)
self.assertEqual([(a["first"], a["last"]) for a in answers], [(35, 222), (0, 239)])
self.assertEqual(set(answers[0]), {"first", "last", "poseCost", "velocityCost"})
self.assertAlmostEqual(answers[1]["poseCost"], 0.0, places=6)
if __name__ == "__main__":
unittest.main()

View file

@ -592,8 +592,9 @@ async function readInside(file, directory) {
// the BVH and writes a private FBX in a directory made for this export alone, and the FBX is then created beside the
// BVH exclusively, so nothing planted at either path is read, written through or replaced. The FBX counts only if
// Blender exits 0, prints its result line and its file exists. A failure names the exit or the signal and never
// Blender's output.
async function exportClip(bvh, fbx, clipName, timeoutMs, artifactDir) {
// Blender's output. A window {first, last} (BVH frame indices, last inclusive) is handed to Blender as the frame
// range to export, in Blender's frames, which count from 1; the daemon never chooses one.
async function exportClip(bvh, fbx, clipName, timeoutMs, artifactDir, window = null) {
const input = await readInside(bvh, artifactDir);
if (input === null) return { error: "fbx-export-refused" };
guard();
@ -606,6 +607,7 @@ async function exportClip(bvh, fbx, clipName, timeoutMs, artifactDir) {
const run = await runBlender([
"-b", "--factory-startup", "--python-use-system-env", "--python-exit-code", "1",
"--python", exportScript, "--", privateBvh, privateFbx, clipName,
...(window ? ["--frames", String(window.first + 1), String(window.last + 1)] : []),
], timeoutMs);
let info = null;
if (run.code === 0 && run.result !== null) {
@ -648,19 +650,28 @@ async function sweepWork() {
// Every BVH the worker listed becomes an FBX, or the job fails. A listed BVH must be a regular file inside the job's
// artifact directory, and that is decided when its export begins (exportClip), never earlier. Sample N of several is
// <clipName>_NN.
async function exportListed(listed, artifactDir, clipName, timeoutMs) {
// <clipName>_NN, N being its own index. With loops (the worker's answer, an array when the request asked for a loop,
// else undefined), sample k is exported over loops[k], and a job whose answer has no usable window for a sample fails.
async function exportListed(listed, artifactDir, clipName, timeoutMs, loops = undefined) {
const bvhs = [];
for (const file of Array.isArray(listed) ? listed : []) {
if (typeof file !== "string" || !file.endsWith(".bvh")) continue;
bvhs.push(path.resolve(artifactDir, file));
}
if (bvhs.length === 0) return { clips: [], error: "fbx-export-failed (no bvh)" };
bvhs.sort();
// A sample's own index is in its file name (motion_NN.bvh, more digits past 99), so the order and the window come
// from that number and never from sorting the names as text.
const sampleOf = (bvh) => Number(/_(\d+)\.bvh$/.exec(bvh)?.[1] ?? 0);
bvhs.sort((a, b) => sampleOf(a) - sampleOf(b) || (a < b ? -1 : a > b ? 1 : 0));
const clips = [];
for (const [index, bvh] of bvhs.entries()) {
for (const bvh of bvhs) {
const index = sampleOf(bvh);
const name = bvhs.length === 1 ? clipName : `${clipName}_${String(index).padStart(2, "0")}`;
const done = await exportClip(bvh, `${bvh.slice(0, -".bvh".length)}.fbx`, name, timeoutMs, artifactDir);
const window = loops === undefined ? null : loops[index];
if (window !== null && !(Number.isInteger(window?.first) && Number.isInteger(window?.last) && window.first >= 0 && window.last > window.first)) {
return { clips, error: "fbx-export-failed (no loop window)" };
}
const done = await exportClip(bvh, `${bvh.slice(0, -".bvh".length)}.fbx`, name, timeoutMs, artifactDir, window);
if (done.error) return { clips, error: done.error };
clips.push({ ...done.clip, file: path.relative(artifactDir, done.clip.file).split(path.sep).join("/") });
}
@ -864,11 +875,24 @@ async function generate(request, response) {
// One export plan: fbx implies the BVH and its standard T-pose, which the FBX is made from.
const fbx = boolValue(body.fbx);
const askedTpose = firstDefined(body.bvhStandardTpose, body.bvh_standard_tpose);
if (fbx && ((askedTpose !== undefined && !boolValue(askedTpose))
|| (body.clipName !== undefined && !(typeof body.clipName === "string" && CLIP_NAME.test(body.clipName))))) {
const loop = body.loop === true;
if ((body.loop !== undefined && typeof body.loop !== "boolean") || (loop && !fbx)
|| (fbx && ((askedTpose !== undefined && !boolValue(askedTpose))
|| (body.clipName !== undefined && !(typeof body.clipName === "string" && CLIP_NAME.test(body.clipName)))))) {
json(response, 400, { ok: false, error: "Invalid fbx request." });
return;
}
// The caller's own marks (named take frames) and whether it plays the take in place: kept in the record for the
// caller, interpreted by nobody here, never given to the worker.
const marks = body.marks === undefined ? [] : body.marks;
const markOk = (mark) => mark !== null && typeof mark === "object" && !Array.isArray(mark)
&& Object.keys(mark).length === 2 && typeof mark.name === "string" && CLIP_NAME.test(mark.name)
&& Number.isInteger(mark.frame) && mark.frame >= 0 && mark.frame < 2 ** 31;
if (!Array.isArray(marks) || marks.length > 32 || !marks.every(markOk)
|| (body.inPlace !== undefined && typeof body.inPlace !== "boolean")) {
json(response, 400, { ok: false, error: "Invalid marks request." });
return;
}
if (fbx && !blenderReady()) {
json(response, 503, { ok: false, code: "blender-unavailable" });
return;
@ -878,6 +902,13 @@ async function generate(request, response) {
bvhStandardTpose: fbx || boolValue(askedTpose),
};
// One way to give constraints: the worker reads exactly one path, so two inputs would leave the record naming
// constraints that did not make the clip.
if ([body.constraints, body.constraints_path, body.constraintsPath].filter((given) => given !== undefined).length > 1) {
json(response, 400, { ok: false, error: "Invalid constraints request." });
return;
}
const bodyMeta = typeof body.meta === "object" && body.meta ? body.meta : {};
const askedSeed = firstDefined(body.seed, bodyMeta.seed);
if (askedSeed !== undefined && !(Number.isInteger(askedSeed) && askedSeed >= 0 && askedSeed < SEED_LIMIT)) {
@ -934,10 +965,13 @@ async function generate(request, response) {
numSamples,
diffusion_steps: diffusionSteps,
numTransitionFrames: firstDefined(body.numTransitionFrames, body.num_transition_frames),
constraints: constraintsPath,
constraints: body.constraints !== undefined && typeof body.constraints !== "string" ? body.constraints : constraintsPath,
seed,
fbx: fbx || undefined,
loop: loop || undefined,
clipName,
marks: marks.length > 0 ? marks.map(({ name, frame }) => ({ name, frame })) : undefined,
inPlace: body.inPlace === true || undefined,
cfg: body.cfg,
cfgType: firstDefined(body.cfgType, body.cfg_type),
cfgWeight: firstDefined(body.cfgWeight, body.cfg_weight),
@ -967,6 +1001,7 @@ async function generate(request, response) {
numTransitionFrames: firstDefined(body.numTransitionFrames, body.num_transition_frames),
constraints: constraintsPath,
seed,
loop: loop || undefined,
cfg: body.cfg,
cfgType: firstDefined(body.cfgType, body.cfg_type),
cfgWeight: firstDefined(body.cfgWeight, body.cfg_weight),
@ -993,7 +1028,7 @@ async function generate(request, response) {
let exported = null;
if (fbx && result.ok) {
const timeoutMs = Math.min(EXPORT_TIMEOUT_MS, Math.max(1, Number(firstDefined(body.exportTimeoutMs, EXPORT_TIMEOUT_MS)) || EXPORT_TIMEOUT_MS));
exported = await exportListed(result.body?.files, artifactDir, clipName, timeoutMs);
exported = await exportListed(result.body?.files, artifactDir, clipName, timeoutMs, loop ? (Array.isArray(result.body?.loops) ? result.body.loops : []) : undefined);
if (exported.error) result = { ok: false, error: exported.error, body: result.body };
}