Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: sample interior clip poses in the Three.js physical audit (#12264)

[._.]/ Adam Eivy557deb224385
diff --git a/client/src/pages/ThreejsModelDetail.jsx b/client/src/pages/ThreejsModelDetail.jsx
index ef6676658e..4fe2b14d17 100644
--- a/client/src/pages/ThreejsModelDetail.jsx
+++ b/client/src/pages/ThreejsModelDetail.jsx
@@ -50,7 +50,7 @@ const countSeverities = (findings) => findings.reduce((counts, finding) => {
* severity-styled finding list. Shared so a second gate cannot drift into a
* different look for the same data.
*/
-function GatePanel({ title, findings, cleanLabel, footer }) {
+function GatePanel({ title, findings, cleanLabel, footer, children = null }) {
const counts = countSeverities(findings);
return (
<section className="rounded-xl border border-port-border bg-port-card p-4">
@@ -75,6 +75,7 @@ function GatePanel({ title, findings, cleanLabel, footer }) {
))}
</ul>
)}
+ {children}
<p className="mt-3 flex items-start gap-1.5 text-[11px] leading-relaxed text-gray-500">
<Info className="mt-0.5 h-3 w-3 shrink-0" />
<span>{footer}</span>
@@ -83,6 +84,39 @@ function GatePanel({ title, findings, cleanLabel, footer }) {
);
}
+const formatSeconds = (times) => times.map((time) => `${time}s`).join(', ');
+
+/**
+ * Which clip times the physical audit measured, and which its pose budget left
+ * out — so a clean panel over an animated model says how much of the motion it
+ * actually covers.
+ */
+function PoseCoverageList({ coverage }) {
+ return (
+ <div className="mt-3 text-[11px] leading-relaxed text-gray-500">
+ <p className="mb-1">
+ {coverage.status === 'partial'
+ ? `Clip poses checked (the ${coverage.budget}-pose budget ran out):`
+ : 'Clip poses checked:'}
+ </p>
+ <ul className="space-y-0.5">
+ {coverage.clips.map((clip) => (
+ <li key={clip.clipId} className="break-words">
+ <span className="text-gray-400">{clip.clipName}</span>
+ {' — '}
+ {clip.sampledTimes.length > 0 ? formatSeconds(clip.sampledTimes) : 'none'}
+ {clip.omittedCount > 0 && (
+ <span className="text-port-warning">
+ {`; ${clip.omittedCount} omitted (${formatSeconds(clip.omittedTimes)}${clip.omittedCount > clip.omittedTimes.length ? ', …' : ''})`}
+ </span>
+ )}
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
+
/**
* The chosen subject family's checklist, with each required component marked
* resolved or unresolved by the coverage pass, plus the axes and orbit views
@@ -389,6 +423,13 @@ export default function ThreejsModelDetail() {
const unmeasuredAttachments = Array.isArray(record.physicalAudit?.unmeasuredAttachments)
? record.physicalAudit.unmeasuredAttachments
: [];
+ // Interior clip poses were first sampled with `poseCoverage`; an audit stored
+ // before then measured an animated model only at clip and sequence
+ // boundaries, which is reported as a gap rather than read as full coverage.
+ const poseCoverage = Array.isArray(record.physicalAudit?.poseCoverage?.clips)
+ ? record.physicalAudit.poseCoverage
+ : null;
+ const poseCoverageUnrecorded = !poseCoverage && listThreejsClips(record.spec).length > 0;
const physicalAuditFindings = Array.isArray(record.physicalAudit?.findings)
? [
...record.physicalAudit.findings,
@@ -397,6 +438,11 @@ export default function ThreejsModelDetail() {
severity: 'note',
message: `Attachment "${entry.partId}" could not be checked against ${entry.anchorSocket ? `socket "${entry.anchorSocket}"` : `"${entry.anchorPartId}"`} because ${entry.reason}.`,
})),
+ ...(poseCoverageUnrecorded ? [{
+ code: 'clip-poses-unrecorded',
+ severity: 'note',
+ message: 'This audit predates interior clip-pose sampling: attachments were measured only at clip and sequence boundaries, so a part could leave its anchor mid-motion unreported. Regenerate to measure the clips mid-motion.',
+ }] : []),
]
: null;
const materialFindings = Array.isArray(record.materialPlausibility?.findings)
@@ -632,7 +678,9 @@ export default function ThreejsModelDetail() {
? ' Refining without your own feedback will also target physical conformance defects.'
: ''
}`}
- />
+ >
+ {poseCoverage?.clips.length > 0 && <PoseCoverageList coverage={poseCoverage} />}
+ </GatePanel>
)}
{materialFindings && (
diff --git a/client/src/pages/ThreejsModelDetail.test.jsx b/client/src/pages/ThreejsModelDetail.test.jsx
index 65ecb84fca..e153adea59 100644
--- a/client/src/pages/ThreejsModelDetail.test.jsx
+++ b/client/src/pages/ThreejsModelDetail.test.jsx
@@ -685,6 +685,58 @@ describe('ThreejsModelDetail unmeasured attachments', () => {
});
});
+// Interior clip poses are only as covered as the audit says: the panel names the
+// times it measured and the ones the budget left out, and an audit stored before
+// that report existed is never presented as having measured the motion.
+describe('ThreejsModelDetail clip pose coverage', () => {
+ beforeEach(resetMocks);
+
+ const animatedSpec = {
+ ...baseRecord.spec,
+ animation: {
+ cues: [],
+ clips: [{
+ id: 'swing',
+ name: 'Swing',
+ durationSeconds: 2,
+ sequences: [{ id: 'turn', name: 'Turn', partId: 'arm', startSeconds: 0, endSeconds: 2, channels: { rotationDegrees: { from: [0, 0, 0], to: [0, 0, 360] } } }],
+ }],
+ },
+ };
+ const cleanAudit = { errorCount: 0, warningCount: 0, noteCount: 0, findings: [], unmeasuredAttachments: [] };
+
+ it('lists the measured and omitted clip times', async () => {
+ getThreejsModel.mockResolvedValue({
+ ...baseRecord,
+ spec: animatedSpec,
+ physicalAudit: {
+ ...cleanAudit,
+ poseCoverage: {
+ status: 'partial',
+ measuresAttachments: true,
+ budget: 48,
+ clips: [{ clipId: 'swing', clipName: 'Swing', sampledTimes: [0, 1, 2], omittedCount: 2, omittedTimes: [0.5, 1.5] }],
+ },
+ },
+ });
+ renderDetail();
+
+ await waitFor(() => expect(screen.getByText('Physical audit')).toBeInTheDocument());
+ expect(screen.getByText('Clip poses checked (the 48-pose budget ran out):')).toBeInTheDocument();
+ expect(screen.getByText(/0s, 1s, 2s/)).toBeInTheDocument();
+ expect(screen.getByText('; 2 omitted (0.5s, 1.5s)')).toBeInTheDocument();
+ });
+
+ it('reads an animated record audited before coverage reporting as unmeasured mid-motion', async () => {
+ getThreejsModel.mockResolvedValue({ ...baseRecord, spec: animatedSpec, physicalAudit: cleanAudit });
+ renderDetail();
+
+ await waitFor(() => expect(screen.getByText('Physical audit')).toBeInTheDocument());
+ expect(screen.getByText(/This audit predates interior clip-pose sampling/)).toBeInTheDocument();
+ expect(screen.queryByText('Assembly satisfies physical attachment, exposure, and coplanarity rules')).not.toBeInTheDocument();
+ });
+});
+
describe('ThreejsModelDetail rig readiness fallbacks', () => {
beforeEach(resetMocks);
diff --git a/server/lib/README.md b/server/lib/README.md
index aa74d56c3f..d4ff710c5f 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -406,11 +406,12 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `pngMetadata.js` | `extractGenerationMetadataEntries` shares the bounded projection between PNG text chunks and video container tags. `extractPngGenerationMetadataFile` seeks past pixel data for bounded disk-file metadata extraction. Bounded PNG `tEXt`/`zTXt`/`iTXt` extraction for Stable Diffusion-compatible provenance plus normalization of prompt, negative prompt, sampler, steps, CFG, seed, size, model, and model hash fields; `GENERATION_METADATA_LIMITS` shares the projection bounds with catalog sync validation. Pure. |
| `threejsModel.js` | Validated declarative procedural-model schema plus deterministic standalone Three.js factory export for the Three.js Models workspace. Also the cross-section gate: `evaluateThreejsFlatness(spec)` counts distinct vertex planes per axis — relative to the mesh's own size, with a rotation-invariant zero-volume check behind it — and treats an `extrude` with no bevel thickness as the two-plane slab it is to report when the majority of identity-priority features are built only from flat parts — a model that reads right head-on and like cardboard when orbited. `buildThreejsFlatnessFeedback(flatness)` turns that into default refinement feedback; `listSpecNames(names)` is the shared capped name-list formatter both gates use in finding messages. Also the material-plausibility gate: `evaluateThreejsMaterialPlausibility(spec)` keys a bounded per-family prior table (metal, wood, plastic, glass, fabric, ceramic, rubber, stone, leather, paper) off tokens in each material's id and reports channels whose values the named substance does not support — metalness 0.9 oak, transmission 1.0 steel — skipping any id that names no family or two, and any channel the material's `type` never forwards to Three.js. Advisory only: it never clamps, because a stylized model may legitimately break every prior. `buildThreejsMaterialFeedback(plausibility)` turns that into default refinement feedback. The same pass emits a `reflective-material-without-environment` note when a spec authors reflective channels (metalness above 0.6, or any transmission/clearcoat/iridescence) while `environment.preset` is `none` — those channels read off an environment, so in that scene their values cannot be judged at all. Attachments are declared in two forms — the original anchor-less `attachmentPartIds` and the anchored `attachments: [{ partId, anchorPartId | anchorSocket, maxOffset }]` — and `resolveThreejsAttachments(articulation)` merges them into one canonical list (an anchored entry wins over a bare id) so every gate reads the same set; `isThreejsAttachmentAnchored(attachment)` is the shared anchored/unanchored predicate and `DEFAULT_ATTACHMENT_MAX_OFFSET` the default tolerance. The spec-level refinement rejects an anchor that does not resolve, one that is the attachment itself, an anchor chain that cycles, and the model root (the sole top-level part) — which carries no relationship to any body part. The spec carries an optional `environment` block (see `threejsModelEnvironment.js`), and `buildThreejsFactorySource()` stamps its render profile onto `root.userData.sculptRuntime.render` and exports it as `renderProfile`, so a consumer wiring their own `WebGLRenderer` reproduces the model instead of a differently tone-mapped approximation. |
| `threejsModelAnimation.js` | `summarizeThreejsAnimation(spec)` — clip inventory *and* playback gate over an already-validated Three.js spec: `{ animated, clipCount, cueCount, sequenceCount, movingPartCount, longestClipSeconds, findings, warningCount, clips }`. The schema proves a declared `animation` block is well *formed* (sequences on real parts, inside their clip, never two on one channel at once, never a cue without motion); this reports what the model *declared* — one entry per clip with its role, duration, sequence and distinct-cue counts — plus the ways a well-formed clip still plays badly: a clip authored against a pose the assembly does not build (`clip-start-pose-mismatch`), a handover between sequences that do not meet (`clip-sequence-jump`), a `loop: true` clip that does not return to where it began, a one-shot `idle`, an unfired cue, a long dead tail, and an articulation graph with no clip at all. Advisory warnings only — a static assembly is a complete answer. `buildThreejsAnimationFeedback(animation)` turns those findings into default refinement feedback. A spec with no `animation` key summarizes as not animated — never as evaluated-and-empty. |
+| `threejsModelClipPose.js` | `evaluateThreejsModelClipPose(clip, timeSeconds)` — server copy of the declarative clip pose evaluator (owner per part+channel, step `visible`, the four easing curves), mirroring `client/src/lib/threejsAnimation.js` and the emitted `THREEJS_PLAYER_SOURCE` so the gates measure the pose the preview and the export show; its test executes all three against one clip. |
| `threejsModelCoverage.js` | `evaluateThreejsPartCoverage(spec, { family })` — structural assembly gate over an already-validated Three.js spec: flags promised features fused onto the same part set, geometry claimed by no detail, and details nothing was built for (folded minor relief stays a `note`). With a subject family it also warns on a required component the spec never mentions at all — the one check that can fault a spec for what it failed to *promise*. `buildThreejsCoverageFeedback(coverage)` turns the error findings (plus any family gap) into default refinement feedback. |
| `threejsModelEnvironment.js` | The image-based-lighting and render-profile half of the procedural sculpt contract, kept **dependency-free** so the client suite can import it to assert parity with `client/src/lib/threejsEnvironment.js` (`threejsModel.js` pulls in zod, which the client CI job does not install). `THREEJS_ENVIRONMENT_PRESETS` (`none`/`neutral`/`studio`) is the bounded preset list the spec schema builds its enum from; `resolveThreejsEnvironment(spec)` normalizes a spec's `{ preset, intensity }` block, reading an absent, partial, or unrecognized one as `DEFAULT_THREEJS_ENVIRONMENT` per field — a record stored before the block shipped has no key and was rendered with no environment, so `none` is the honest reading of it. `THREEJS_RENDER_PROFILE` is the output-colour-space / tone-mapping / exposure contract `buildThreejsFactorySource()` stamps onto every export. |
| `threejsModelFamilies.js` | Curated subject-family checklists for Three.js generation. `THREEJS_MODEL_FAMILY_OPTIONS` / `THREEJS_MODEL_FAMILY_IDS` drive the picker and route validation; `buildThreejsFamilyChecklist(id)` returns the prompt block spliced into generation (`''` for the default `general`, so an un-narrowed subject keeps the unchanged general-purpose prompt); `findMissingFamilyComponents(spec, id)` reports which required components the spec never mentions. |
| `threejsModelPenetration.js` | `evaluateThreejsPenetration(spec)` — cross-part penetration gate over an already-validated Three.js spec, the one check that compares two parts to each other. Rebuilds each part's world placement (the same `THREE.Euler` 'XYZ' composition the preview applies), derives an analytic solid per geometry type, and samples one part's interior against another's to flag a part entirely buried inside an unrelated one (`error`) or unrelated parts occupying substantially the same space (`warning`). Parts in the same subtree and declared `attachmentPartIds` are exempt — embedding is what those relationships are *for* — and a shallow or transparent-container overlap is reported as an undecided `note`, never as a defect. `buildThreejsPenetrationFeedback(penetration)` turns the errors and warnings (never the undecided notes) into default refinement feedback. |
-| `threejsModelPhysicalAudit.js` | `evaluateThreejsPhysicalAudit(spec)` — pure bounds and pose audit gate over an already-validated Three.js spec: inspects static resting poses and animated clip poses to detect floating parts (`floating-part`), swallowed geometry (`buried-geometry`), z-fighting coplanar surfaces (`coplanar-surface`), unprovenanced appearing geometry (`unprovenanced-transition`), non-uniform parent scale cascading into descendants (`nonuniform-parent-scale`), attachments declared with nothing to hang from (`unanchored-attachment`, warning), and attachments measured further from their declared anchor than `maxOffset` allows (`attachment-far-from-anchor`, error — the spec asserted the relationship itself), across the resting pose and the sampled clip poses so a clip that carries an attachment away from its anchor is caught too. Named left/right pairs are additionally audited for handedness in the resting pose — measured in the frame of the pair’s nearest common ancestor, since the lateral plane a pair mirrors across is the one their shared parent defines and not world `x = 0` — which no bounds check can see — a limb mirrored by a 180° yaw about the vertical axis rather than a lateral reflection (`bilateral-chirality`), by a negated scale component (`bilateral-mirror-scale`), or not mirrored at all so both halves sit on one side of the lateral plane (`bilateral-pair-same-side`), all warnings. An attachment whose anchor geometry could not be measured is listed in `unmeasuredAttachments` rather than counted as passing. `buildThreejsPhysicalAuditFeedback(physicalAudit)` turns actionable findings into default refinement feedback. |
+| `threejsModelPhysicalAudit.js` | `evaluateThreejsPhysicalAudit(spec)` — pure bounds and pose audit gate over an already-validated Three.js spec: inspects static resting poses and animated clip poses to detect floating parts (`floating-part`), swallowed geometry (`buried-geometry`), z-fighting coplanar surfaces (`coplanar-surface`), unprovenanced appearing geometry (`unprovenanced-transition`), non-uniform parent scale cascading into descendants (`nonuniform-parent-scale`), attachments declared with nothing to hang from (`unanchored-attachment`, warning), and attachments measured further from their declared anchor than `maxOffset` allows (`attachment-far-from-anchor`, error — the spec asserted the relationship itself), across the resting pose and the sampled clip poses so a clip that carries an attachment away from its anchor is caught too — interior times (each sequence midpoint, plus a subdivision per 90° of large rotations) as well as boundaries, under a 48-pose budget dealt round-robin across clips; `poseCoverage` records which clip times were measured and which the budget omitted, and an omission is a `clip-poses-unsampled` note rather than a clean pass. Named left/right pairs are additionally audited for handedness in the resting pose — measured in the frame of the pair’s nearest common ancestor, since the lateral plane a pair mirrors across is the one their shared parent defines and not world `x = 0` — which no bounds check can see — a limb mirrored by a 180° yaw about the vertical axis rather than a lateral reflection (`bilateral-chirality`), by a negated scale component (`bilateral-mirror-scale`), or not mirrored at all so both halves sit on one side of the lateral plane (`bilateral-pair-same-side`), all warnings. An attachment whose anchor geometry could not be measured is listed in `unmeasuredAttachments` rather than counted as passing. `buildThreejsPhysicalAuditFeedback(physicalAudit)` turns actionable findings into default refinement feedback. |
| `threejsModelPlayerSource.js` | `THREEJS_PLAYER_SOURCE` — the fixed clip-player source `buildThreejsFactorySource` emits into every exported Three.js module, giving a standalone consumer `createSculptAnimationPlayer(root, { onCue })` (plus `evaluateSculptClipPose` / `collectSculptCues`) over the node map and validated `animation` block the factory already carries. A STRING constant, not generated text: nothing provider-authored is interpolated into it, so the export stays data-plus-PortOS-code. It takes `update(deltaSeconds)` from the host render loop rather than owning one, scrubs silently and fires cues only on playback (mirroring the preview), and clones a shared material before driving `opacity`. Semantics mirror `client/src/lib/threejsAnimation.js` — change one and change the other. |
| `threejsModelRig.js` | `evaluateThreejsRigReadiness(spec)` — honest rig-readiness report over an already-validated Three.js spec: `{ articulationReady, reasons, jointCount, socketCount, attachmentCount, anchoredAttachmentCount, unanchoredAttachmentCount, rootJointId, subjectType }`. The schema proves the optional `articulation` graph is well *formed* (one root, no cycles or forward refs, joints and pivots pointed at real parts/sockets); this reports whether it is *useful* (more than a lone root, every child joint carrying a pivot axis, every declared attachment naming what it hangs from) and names the reason when it is not. It reports rather than rejects, and never claims skinning: PortOS generates static assemblies and declared articulation intent, not skeletons or bind poses. |
| `threejsTransform.js` | Affine transform primitives shared by every server-side gate that reconstructs where a Three.js scene-spec part sits in the world — `rotationMatrix` (row-major 3×3 matching `THREE.Euler` order `XYZ`, the composition the preview canvas and exported factory both apply), `scaleLinear`, `multiplyLinear`, `applyLinear`, `applyTransform`, `composeTransform(parent, { position, rotationDegrees, scale })`, `vectorLength`, `degreesToRadians`, `IDENTITY_LINEAR` / `IDENTITY_TRANSFORM`. One owner for math `threejsModel.js`, `threejsModelPenetration.js` and `threejsModelPhysicalAudit.js` each used to spell separately. A non-finite rotation component reads as `0` degrees and a non-finite scale component as `1`, matching what the renderer does with a malformed stored spec — feeding `null`/`NaN` through instead produced `NaN` bounds that the audits read as "no overlap" and "no defect". |
diff --git a/server/lib/index.js b/server/lib/index.js
index 61be47efaa..9bb45d901f 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -92,6 +92,7 @@ export * from './sharedSchemas.js';
export * from './threadRefKinds.js';
export * from './threejsModel.js';
export * from './threejsModelAnimation.js';
+export * from './threejsModelClipPose.js';
export * from './threejsModelCoverage.js';
export * from './threejsModelEnvironment.js';
export * from './threejsModelFamilies.js';
diff --git a/server/lib/threejsModelClipPose.js b/server/lib/threejsModelClipPose.js
new file mode 100644
index 0000000000..0a6a5ed8c5
--- /dev/null
+++ b/server/lib/threejsModelClipPose.js
@@ -0,0 +1,88 @@
+/**
+ * Server-side pose evaluator for the declarative clip contract in
+ * `threejsModel.js`, used by the gates that measure a clip mid-motion
+ * (`threejsModelPhysicalAudit.js`).
+ *
+ * The semantics MIRROR the preview evaluator (`client/src/lib/threejsAnimation.js`)
+ * and the player emitted into an exported factory (`threejsModelPlayerSource.js`):
+ * per part+channel the owning sequence is the window containing the instant, else
+ * the most recent window behind it (its `to` holds), else the next window ahead
+ * (its `from` has not moved yet); `visible` is a step that takes `to` only once
+ * the window completes; easing names resolve to the same four curves. A gate
+ * that sampled any other pose would report defects the user can never see, or
+ * pass ones they can. `threejsModelClipPose.test.js` executes all three against
+ * the same clip so they cannot drift apart silently.
+ *
+ * Server code cannot import the client module, and the player is a fixed source
+ * string, so this is the third copy rather than a shared one.
+ */
+
+const CLIP_CHANNELS = ['position', 'rotationDegrees', 'scale', 'opacity', 'visible'];
+
+const EASING_CURVES = Object.freeze({
+ linear: (t) => t,
+ easeIn: (t) => t * t,
+ easeOut: (t) => t * (2 - t),
+ easeInOut: (t) => t * t * (3 - (2 * t)),
+});
+
+const clamp01 = (value) => (value < 0 ? 0 : value > 1 ? 1 : value);
+
+const interpolate = ({ from, to }, progress) => (
+ Array.isArray(from) && Array.isArray(to)
+ ? from.map((value, axis) => value + ((to[axis] - value) * progress))
+ : from + ((to - from) * progress)
+);
+
+const channelValue = (sequence, range, channel, time) => {
+ const span = sequence.endSeconds - sequence.startSeconds;
+ const progress = clamp01(span > 0 ? (time - sequence.startSeconds) / span : 1);
+ if (channel === 'visible') return progress >= 1 ? range.to : range.from;
+ const curve = EASING_CURVES[sequence.easing] || EASING_CURVES.linear;
+ return interpolate(range, curve(progress));
+};
+
+const rankAt = (sequence, time) => {
+ if (time >= sequence.startSeconds && time <= sequence.endSeconds) return 2;
+ return sequence.endSeconds < time ? 1 : 0;
+};
+
+const outranks = (candidate, current, time) => {
+ const candidateRank = rankAt(candidate, time);
+ const currentRank = rankAt(current, time);
+ if (candidateRank !== currentRank) return candidateRank > currentRank;
+ if (candidateRank === 2) return candidate.startSeconds > current.startSeconds;
+ if (candidateRank === 1) return candidate.endSeconds > current.endSeconds;
+ return candidate.startSeconds < current.startSeconds;
+};
+
+/**
+ * Pose for every part a clip drives at an absolute time.
+ *
+ * @param {object|null} clip a validated clip, or null
+ * @param {number} timeSeconds absolute seconds from the clip's start
+ * @returns {object} null-prototype map of partId → `{ position?, rotationDegrees?, scale?, opacity?, visible? }`;
+ * a part no sequence drives is absent, which reads as "the authored pose".
+ */
+export function evaluateThreejsModelClipPose(clip, timeSeconds) {
+ const pose = Object.create(null);
+ const sequences = Array.isArray(clip?.sequences) ? clip.sequences : [];
+ const time = Number.isFinite(timeSeconds) ? timeSeconds : 0;
+ const owners = new Map();
+ for (const sequence of sequences) {
+ for (const channel of CLIP_CHANNELS) {
+ const range = sequence.channels?.[channel];
+ if (!range) continue;
+ const key = `${sequence.partId}|${channel}`;
+ const current = owners.get(key);
+ if (!current || outranks(sequence, current.sequence, time)) {
+ owners.set(key, { sequence, range, channel });
+ }
+ }
+ }
+ for (const { sequence, range, channel } of owners.values()) {
+ const partPose = pose[sequence.partId] || (pose[sequence.partId] = {});
+ partPose[channel] = channelValue(sequence, range, channel, time);
+ }
+ return pose;
+}
diff --git a/server/lib/threejsModelClipPose.test.js b/server/lib/threejsModelClipPose.test.js
new file mode 100644
index 0000000000..a753558219
--- /dev/null
+++ b/server/lib/threejsModelClipPose.test.js
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest';
+import { evaluateThreejsClipPose as evaluatePreviewPose } from '../../client/src/lib/threejsAnimation.js';
+import { evaluateThreejsModelClipPose } from './threejsModelClipPose.js';
+import { THREEJS_PLAYER_SOURCE } from './threejsModelPlayerSource.js';
+
+// The audit only means something if it measures the pose the user sees, so the
+// server evaluator is pinned against BOTH other copies — the preview's and the
+// one shipped inside an exported factory — over every semantic they share:
+// each easing curve, the step `visible`, a gap between two windows on one
+// channel (the earlier `to` holds), the time before a part's first window (its
+// `from` holds), and sequences declared out of time order.
+const importEmittedPlayer = () => import(`data:text/javascript;base64,${Buffer.from(
+ `const spec = { parts: [] }; const rotation = () => [0, 0, 0];\n${THREEJS_PLAYER_SOURCE}`,
+).toString('base64')}`);
+
+const clip = {
+ id: 'parity',
+ name: 'Parity',
+ durationSeconds: 4,
+ loop: false,
+ sequences: [
+ { id: 'late', name: 'Late', partId: 'arm', startSeconds: 2.5, endSeconds: 4, easing: 'easeOut', channels: { rotationDegrees: { from: [0, 90, 0], to: [0, 360, 0] } } },
+ { id: 'early', name: 'Early', partId: 'arm', startSeconds: 0.5, endSeconds: 1.5, easing: 'easeIn', channels: { rotationDegrees: { from: [0, 0, 0], to: [0, 90, 0] } } },
+ { id: 'lift', name: 'Lift', partId: 'lid', startSeconds: 0, endSeconds: 2, easing: 'easeInOut', channels: { position: { from: [0, 0, 0], to: [0, 2, 0] }, opacity: { from: 1, to: 0.25 } } },
+ { id: 'show', name: 'Show', partId: 'prop', startSeconds: 1, endSeconds: 3, easing: 'linear', channels: { visible: { from: false, to: true }, scale: { from: [1, 1, 1], to: [2, 1, 1] } } },
+ ],
+};
+
+describe('evaluateThreejsModelClipPose', () => {
+ it('poses a clip exactly as the preview and the exported player do', async () => {
+ const { evaluateSculptClipPose } = await importEmittedPlayer();
+ for (let step = 0; step <= 32; step += 1) {
+ const time = step * 0.125;
+ const server = { ...evaluateThreejsModelClipPose(clip, time) };
+ expect(server).toEqual({ ...evaluatePreviewPose(clip, time).pose });
+ expect(server).toEqual({ ...evaluateSculptClipPose(clip, time) });
+ }
+ // Spot-check the semantics the parity rests on, so three copies that drifted
+ // together cannot pass by agreeing with each other.
+ expect(evaluateThreejsModelClipPose(clip, 0).arm.rotationDegrees).toEqual([0, 0, 0]);
+ expect(evaluateThreejsModelClipPose(clip, 2).arm.rotationDegrees).toEqual([0, 90, 0]);
+ expect(evaluateThreejsModelClipPose(clip, 2).prop.visible).toBe(false);
+ expect(evaluateThreejsModelClipPose(clip, 3).prop.visible).toBe(true);
+ });
+});
diff --git a/server/lib/threejsModelPhysicalAudit.js b/server/lib/threejsModelPhysicalAudit.js
index df1a8128a7..fa4ed5a6e3 100644
--- a/server/lib/threejsModelPhysicalAudit.js
+++ b/server/lib/threejsModelPhysicalAudit.js
@@ -41,6 +41,7 @@ import {
listSpecNames,
resolveThreejsAttachments,
} from './threejsModel.js';
+import { evaluateThreejsModelClipPose } from './threejsModelClipPose.js';
import {
applyTransform,
composeTransform,
@@ -51,7 +52,21 @@ import {
const EPSILON = 1e-4;
const COPLANAR_TOLERANCE = 1e-3;
const TOUCH_TOLERANCE = 0.02;
-const MAX_AUDIT_POSES = 16;
+// Clip poses measured per audit, shared by every clip. Boundaries alone miss
+// motion that leaves and comes back inside one window — an arm turned through
+// 360° is back at rest at both ends — so each sequence also contributes interior
+// samples. The budget is dealt round-robin across clips, so a sequence-heavy
+// first clip cannot starve a later one, and every sample that does not fit is
+// reported rather than dropped. 48 keeps the walk bounded (12 clips is the
+// schema maximum, four poses each) while covering a typical model completely.
+const MAX_CLIP_AUDIT_POSES = 48;
+// A rotating sequence gets one interior sample per this many degrees of turn,
+// up to MAX_INTERIOR_SEGMENTS segments; every sequence gets at least its midpoint.
+const MAX_ROTATION_STEP_DEGREES = 90;
+const MAX_INTERIOR_SEGMENTS = 8;
+// Omitted times are listed for the reader up to this many per clip; the count
+// is always exact.
+const MAX_LISTED_OMITTED_TIMES = 24;
// One percent anisotropy is small enough to ignore authoring noise while still
// catching the intentional shape-squashing that distorts a child hierarchy.
const NONUNIFORM_SCALE_TOLERANCE = 0.01;
@@ -196,77 +211,91 @@ function faceAreaOverlap2D(minA1, maxA1, minA2, maxA2, minB1, maxB1, minB2, maxB
const isTransparent = (material) => Boolean(material)
&& ((material.transparent === true && (material.opacity ?? 1) < 1) || (material.transmission ?? 0) > 0);
+// The clip pose is the one the preview and the exported player show
+// (`threejsModelClipPose.js`); a part no sequence drives keeps its authored pose.
function getPoseStateResolver(clip, timeSeconds) {
- const sequences = Array.isArray(clip?.sequences) ? clip.sequences : [];
-
- const getChannelValue = (sequence, channel, t) => {
- const range = sequence.channels?.[channel];
- if (!range) return null;
- if (channel === 'visible' || channel === 'opacity') {
- if (t >= sequence.endSeconds) return range.to;
- if (t < sequence.startSeconds) return range.from;
- if (channel === 'visible') return range.to;
- }
- if (t <= sequence.startSeconds) return range.from;
- if (t >= sequence.endSeconds) return range.to;
-
- const duration = sequence.endSeconds - sequence.startSeconds;
- const progress = duration > 0 ? (t - sequence.startSeconds) / duration : 1;
- let eased = progress;
- if (sequence.easing === 'easeIn') eased = progress * progress;
- else if (sequence.easing === 'easeOut') eased = progress * (2 - progress);
- else if (sequence.easing === 'easeInOut') eased = progress < 0.5 ? 2 * progress * progress : -1 + ((4 - (2 * progress)) * progress);
-
- if (Array.isArray(range.from) && Array.isArray(range.to)) {
- return range.from.map((v, i) => v + ((range.to[i] - v) * eased));
- }
- if (typeof range.from === 'number' && typeof range.to === 'number') {
- return range.from + ((range.to - range.from) * eased);
- }
- return range.to;
+ const pose = evaluateThreejsModelClipPose(clip, timeSeconds);
+ return (part) => {
+ const driven = pose[part.id] || {};
+ return {
+ position: driven.position ?? part.position ?? [0, 0, 0],
+ rotationDegrees: driven.rotationDegrees ?? part.rotationDegrees ?? [0, 0, 0],
+ scale: driven.scale ?? part.scale ?? [1, 1, 1],
+ visible: driven.visible ?? (part.visible !== false),
+ opacity: driven.opacity ?? part.opacity ?? 1,
+ };
};
+}
+
+const roundTime = (value) => Number(value.toFixed(4));
+
+const formatTimes = (times) => times.map((time) => `${time}s`).join(', ');
- const partSequences = new Map();
- for (const seq of sequences) {
- if (!seq.partId) continue;
- const list = partSequences.get(seq.partId) || [];
- list.push(seq);
- partSequences.set(seq.partId, list);
+const sequenceSegments = (sequence) => {
+ const range = sequence.channels?.rotationDegrees;
+ const turn = range && Array.isArray(range.from) && Array.isArray(range.to)
+ ? Math.max(...range.from.map((value, axis) => Math.abs((range.to[axis] ?? value) - value)))
+ : 0;
+ return Math.min(MAX_INTERIOR_SEGMENTS, Math.max(2, Math.ceil(turn / MAX_ROTATION_STEP_DEGREES)));
+};
+
+/**
+ * Every pose time worth measuring in one clip, highest priority first: the clip
+ * boundaries, then each sequence's midpoint, then sequence boundaries, then the
+ * extra subdivisions of large rotations. Priority only matters when the budget
+ * runs out, and then it decides which poses are reported as omitted.
+ */
+const planClipSampleTimes = (clip) => {
+ const sequences = (Array.isArray(clip.sequences) ? clip.sequences : [])
+ .filter((sequence) => Number.isFinite(sequence.startSeconds) && Number.isFinite(sequence.endSeconds))
+ .sort((a, b) => (a.startSeconds - b.startSeconds) || (a.endSeconds - b.endSeconds));
+ const tiers = [
+ [0, Number.isFinite(clip.durationSeconds) ? clip.durationSeconds : 0],
+ sequences.map((sequence) => (sequence.startSeconds + sequence.endSeconds) / 2),
+ sequences.flatMap((sequence) => [sequence.startSeconds, sequence.endSeconds]),
+ sequences.flatMap((sequence) => {
+ const segments = sequenceSegments(sequence);
+ const span = sequence.endSeconds - sequence.startSeconds;
+ return Array.from({ length: segments - 1 }, (_, index) => sequence.startSeconds + ((span * (index + 1)) / segments));
+ }),
+ ];
+ const ordered = [];
+ const seen = new Set();
+ for (const time of tiers.flat()) {
+ const rounded = roundTime(time);
+ if (seen.has(rounded)) continue;
+ seen.add(rounded);
+ ordered.push(rounded);
}
+ return ordered;
+};
- return (part) => {
- const seqs = partSequences.get(part.id) || [];
- let pos = part.position || [0, 0, 0];
- let rot = part.rotationDegrees || [0, 0, 0];
- let sca = part.scale || [1, 1, 1];
- let vis = part.visible !== false;
- let opac = part.opacity ?? 1;
-
- for (const channel of ['position', 'rotationDegrees', 'scale', 'visible', 'opacity']) {
- const drivingSeqs = seqs.filter((s) => s.channels?.[channel] && s.startSeconds <= timeSeconds);
- if (drivingSeqs.length > 0) {
- drivingSeqs.sort((a, b) => a.startSeconds - b.startSeconds);
- const active = drivingSeqs[drivingSeqs.length - 1];
- const val = getChannelValue(active, channel, timeSeconds);
- if (val !== null) {
- if (channel === 'position') pos = val;
- else if (channel === 'rotationDegrees') rot = val;
- else if (channel === 'scale') sca = val;
- else if (channel === 'visible') vis = Boolean(val);
- else if (channel === 'opacity') opac = Number(val);
- }
- }
- }
- return { position: pos, rotationDegrees: rot, scale: sca, visible: vis, opacity: opac };
- };
-}
+// Round-robin, in clip declaration order: deterministic, and no clip gets a
+// second pose until every clip with candidates left has had another one.
+const allocateClipPoseBudget = (candidateLists, budget) => {
+ const quotas = candidateLists.map(() => 0);
+ let remaining = budget;
+ let progressed = true;
+ while (remaining > 0 && progressed) {
+ progressed = false;
+ candidateLists.forEach((candidates, index) => {
+ if (remaining <= 0 || quotas[index] >= candidates.length) return;
+ quotas[index] += 1;
+ remaining -= 1;
+ progressed = true;
+ });
+ }
+ return quotas;
+};
function collectPoseVolumes(spec, getPartState) {
const volumes = [];
// Every part, not only the ones that carry geometry: a socket hangs off its
// parent part's world transform, and that parent is routinely a bare group.
const transformsByPartId = new Map();
- const walk = (part, parentTransform, ancestorIds) => {
+ // A hidden parent hides its whole subtree in Three.js, so visibility is
+ // inherited down the walk; opacity lives on each part's own material and is not.
+ const walk = (part, parentTransform, ancestorIds, parentVisible) => {
const state = getPartState ? getPartState(part) : {
position: part.position,
rotationDegrees: part.rotationDegrees,
@@ -277,6 +306,7 @@ function collectPoseVolumes(spec, getPartState) {
const transform = composeTransform(parentTransform, state);
transformsByPartId.set(part.id, transform);
+ const visible = parentVisible && state.visible !== false;
const localBounds = getLocalBounds(part.geometry);
if (localBounds) {
@@ -288,19 +318,19 @@ function collectPoseVolumes(spec, getPartState) {
materialId: part.material || null,
explodeWithParent: part.explodeWithParent === true,
ancestorIds,
- visible: state.visible,
+ visible,
opacity: state.opacity,
worldBounds,
});
}
for (const child of part.children || []) {
- walk(child, transform, [...ancestorIds, part.id]);
+ walk(child, transform, [...ancestorIds, part.id], visible);
}
};
for (const part of spec?.parts || []) {
- walk(part, IDENTITY_TRANSFORM, []);
+ walk(part, IDENTITY_TRANSFORM, [], true);
}
return { volumes, transformsByPartId };
@@ -494,7 +524,7 @@ function measureAttachmentAnchors({
if (distance <= attachment.maxOffset) continue;
const scope = clipName
- ? `In clip "${clipName}", part ${label(attachment.partId)}`
+ ? `In clip "${clipName}" at ${formatOffset(metadata.timeSeconds ?? 0)}s, part ${label(attachment.partId)}`
: `Part ${label(attachment.partId)}`;
findings.push({
code: 'attachment-far-from-anchor',
@@ -978,9 +1008,11 @@ export function evaluateThreejsPhysicalAudit(spec) {
// 2. Animated Clips & Pose Evaluation
const clips = Array.isArray(spec.animation?.clips) ? spec.animation.clips : [];
- let remainingBudget = MAX_AUDIT_POSES - 1;
+ const candidateTimes = clips.map(planClipSampleTimes);
+ const quotas = allocateClipPoseBudget(candidateTimes, MAX_CLIP_AUDIT_POSES);
+ const clipCoverage = [];
- for (const clip of clips) {
+ clips.forEach((clip, clipIndex) => {
const sequences = Array.isArray(clip.sequences) ? clip.sequences : [];
for (const part of parts) {
@@ -999,17 +1031,32 @@ export function evaluateThreejsPhysicalAudit(spec) {
}
}
- if (remainingBudget <= 0) continue;
-
- const sampleTimes = new Set([0, clip.durationSeconds || 0]);
- for (const seq of sequences) {
- if (Number.isFinite(seq.startSeconds)) sampleTimes.add(seq.startSeconds);
- if (Number.isFinite(seq.endSeconds)) sampleTimes.add(seq.endSeconds);
- }
-
- const timesToTest = [...sampleTimes].sort((a, b) => a - b).slice(0, remainingBudget);
- remainingBudget -= timesToTest.length;
+ const candidates = candidateTimes[clipIndex];
+ const timesToTest = candidates.slice(0, quotas[clipIndex]).sort((a, b) => a - b);
+ const omittedTimes = candidates.slice(quotas[clipIndex]).sort((a, b) => a - b);
evaluatedPoseCount += timesToTest.length;
+ clipCoverage.push({
+ clipId: clip.id,
+ clipName: clip.name || clip.id,
+ sampledTimes: timesToTest,
+ omittedCount: omittedTimes.length,
+ omittedTimes: omittedTimes.slice(0, MAX_LISTED_OMITTED_TIMES),
+ });
+ // Only the attachment measurement walks the sampled poses, so a pose left
+ // out of the budget is a gap in that check alone — and it is said so,
+ // rather than letting the clean count imply every moment was measured.
+ if (omittedTimes.length > 0 && anchoredAttachments.length > 0) {
+ const listed = omittedTimes.slice(0, MAX_LISTED_OMITTED_TIMES);
+ addFinding({
+ code: 'clip-poses-unsampled',
+ severity: 'note',
+ partIds: [],
+ clipId: clip.id,
+ omittedTimes: listed,
+ omittedCount: omittedTimes.length,
+ message: `In clip "${clip.name || clip.id}", attachments were checked at ${timesToTest.length} of ${candidates.length} sampled pose(s); the audit's ${MAX_CLIP_AUDIT_POSES}-pose budget across ${clips.length} clip(s) left ${formatTimes(listed)}${omittedTimes.length > listed.length ? ` and ${omittedTimes.length - listed.length} more` : ''} unmeasured, so an attachment could leave its anchor there unreported.`,
+ });
+ }
// A clip can carry an attachment away from its anchor without ever breaking
// the resting pose, so the same measurement runs over the sampled poses —
@@ -1074,7 +1121,7 @@ export function evaluateThreejsPhysicalAudit(spec) {
}
}
}
- }
+ });
for (const [partId, finding] of strongestAnimatedScaleFindings) {
const staticFinding = staticScaleFindings.get(partId);
@@ -1100,6 +1147,18 @@ export function evaluateThreejsPhysicalAudit(spec) {
// measured was not checked, and reporting it as passing is the failure this
// gate exists to avoid.
unmeasuredAttachments,
+ // Which clip times the pose walk measured and which the budget left out.
+ // `complete`/`partial` describe the attachment check over clip motion;
+ // a record written before this field existed carries none, which readers
+ // treat as "interior clip poses never measured", not as complete.
+ poseCoverage: {
+ status: clips.length === 0
+ ? 'static'
+ : clipCoverage.some((entry) => entry.omittedCount > 0) ? 'partial' : 'complete',
+ measuresAttachments: anchoredAttachments.length > 0,
+ budget: MAX_CLIP_AUDIT_POSES,
+ clips: clipCoverage,
+ },
};
}
@@ -1113,7 +1172,10 @@ export function evaluateThreejsPhysicalAudit(spec) {
export function buildThreejsPhysicalAuditFeedback(physicalAudit) {
const actionable = (physicalAudit?.findings || []).filter((f) => f.severity === 'error' || f.severity === 'warning');
const unmeasured = Array.isArray(physicalAudit?.unmeasuredAttachments) ? physicalAudit.unmeasuredAttachments : [];
- if (actionable.length === 0 && unmeasured.length === 0) return '';
+ // A clip pose the budget left out is, like an unmeasured anchor, an
+ // attachment relationship nothing verified — so it is fed back too.
+ const unsampled = (physicalAudit?.findings || []).filter((f) => f.code === 'clip-poses-unsampled');
+ if (actionable.length === 0 && unmeasured.length === 0 && unsampled.length === 0) return '';
const hasNonuniformParentScale = actionable.some((finding) => finding.code === 'nonuniform-parent-scale');
const hasBilateralChirality = actionable.some((finding) => (
finding.code === 'bilateral-chirality'
@@ -1134,6 +1196,7 @@ export function buildThreejsPhysicalAuditFeedback(physicalAudit) {
'The previous pass failed physical conformance audits:',
...actionable.map((finding, index) => `${index + 1}. ${finding.message}`),
...unmeasured.map((entry) => `Attachment "${entry.partId}" could not be checked against ${entry.anchorSocket ? `socket "${entry.anchorSocket}"` : `"${entry.anchorPartId}"`} because ${entry.reason} — give both the attachment and its anchor real geometry so the relationship can be verified.`),
+ ...unsampled.map((finding) => `${finding.message} Keep every carried part on its anchor throughout each motion, not only where a sequence starts and ends.`),
...(hasNonuniformParentScale ? [
'For non-uniform parent scale findings, size each part through its own geometry dimensions (for example, box width/height/depth or sphere radius) and keep containers near-uniform instead of squashing a parent that owns other components.',
] : []),
diff --git a/server/lib/threejsModelPhysicalAudit.test.js b/server/lib/threejsModelPhysicalAudit.test.js
index 1f3016866e..207ef91941 100644
--- a/server/lib/threejsModelPhysicalAudit.test.js
+++ b/server/lib/threejsModelPhysicalAudit.test.js
@@ -3,6 +3,7 @@ import {
buildThreejsPhysicalAuditFeedback,
evaluateThreejsPhysicalAudit,
} from './threejsModelPhysicalAudit.js';
+import { threejsSculptSpecSchema } from './threejsModel.js';
describe('threejsModelPhysicalAudit', () => {
it('returns clean result for null/empty spec', () => {
@@ -1184,3 +1185,121 @@ describe('swept-path curvature', () => {
});
});
+
+// Through the real schema, as the generation path sees it: an arm turned a full
+// circle is back where it started at both ends of its window, so a walk that
+// samples only boundaries reports the prop riding its grip as clean while the
+// preview shows it 3.9 units away at the half-turn.
+describe('threejsModelPhysicalAudit interior clip poses', () => {
+ const box = (id, size, overrides = {}) => ({
+ id,
+ name: id,
+ geometry: { type: 'box', width: size[0], height: size[1], depth: size[2] },
+ material: 'shell',
+ ...overrides,
+ });
+
+ const swingClip = (id = 'swing', easing = 'easeInOut') => ({
+ id,
+ name: id,
+ durationSeconds: 2,
+ sequences: [{
+ id: `${id}-turn`,
+ name: 'Turn the arm',
+ partId: 'arm',
+ startSeconds: 0,
+ endSeconds: 2,
+ easing,
+ channels: { rotationDegrees: { from: [0, 0, 0], to: [0, 0, 360] } },
+ }],
+ });
+
+ // A filler clip whose 30 short windows are each a distinct pose time, so it
+ // alone has more candidate poses than the whole budget.
+ const busyClip = {
+ id: 'busy',
+ name: 'Busy',
+ durationSeconds: 3.2,
+ sequences: Array.from({ length: 30 }, (_, index) => ({
+ id: `nudge-${index}`,
+ name: `Nudge ${index}`,
+ partId: 'torso',
+ startSeconds: index * 0.1,
+ endSeconds: (index * 0.1) + 0.05,
+ channels: { position: { from: [0, 1, 0], to: [0, 1.001, 0] } },
+ })),
+ };
+
+ const gripSpec = (clips) => threejsSculptSpecSchema.parse({
+ schemaVersion: 1,
+ name: 'Example Figure',
+ summary: 'Placeholder figure holding a prop in a rotating grip.',
+ subjectType: 'character',
+ camera: { position: [4, 3, 5] },
+ materials: { shell: { color: '#556677' } },
+ lights: [{ type: 'directional', intensity: 2 }],
+ parts: [
+ box('torso', [1, 1, 1], { position: [0, 1, 0] }),
+ box('arm', [0.2, 2, 0.2], { position: [0, 2, 0] }),
+ // Fixed in the world where the grip is at rest — it never moves with the arm.
+ box('prop', [0.2, 0.2, 0.2], { position: [0, 3.95, 0] }),
+ ],
+ sockets: [{ name: 'grip', parentPartId: 'arm', position: [0, 1.95, 0] }],
+ articulation: {
+ joints: [
+ { id: 'rootJoint', partId: 'torso', parentJointId: null, pivotSocket: null },
+ { id: 'armJoint', partId: 'arm', parentJointId: 'rootJoint', pivotSocket: null },
+ ],
+ attachments: [{ partId: 'prop', anchorPartId: null, anchorSocket: 'grip', maxOffset: 0.25 }],
+ },
+ animation: { cues: [], clips },
+ detailInventory: [{
+ feature: 'Held prop',
+ evidence: 'Visible in the reference image.',
+ implementationPartIds: ['prop'],
+ priority: 'identity',
+ }],
+ });
+
+ const farFindings = (audit) => audit.findings.filter((f) => f.code === 'attachment-far-from-anchor');
+
+ it('catches an attachment that leaves its socket only between sequence boundaries', () => {
+ const audit = evaluateThreejsPhysicalAudit(gripSpec([swingClip()]));
+ const [finding] = farFindings(audit);
+ expect(finding).toMatchObject({ clipId: 'swing', timeSeconds: 1, anchorSocket: 'grip' });
+ expect(finding.distance).toBeGreaterThan(3.5);
+ expect(finding.message).toContain('In clip "swing" at 1s');
+ expect(audit.poseCoverage).toMatchObject({ status: 'complete', measuresAttachments: true });
+ expect(audit.poseCoverage.clips[0].sampledTimes).toEqual([0, 0.5, 1, 1.5, 2]);
+ expect(buildThreejsPhysicalAuditFeedback(audit)).toContain('In clip "swing" at 1s');
+ });
+
+ it('cannot let an earlier sequence-heavy clip silently starve a later one', () => {
+ const run = () => evaluateThreejsPhysicalAudit(gripSpec([busyClip, swingClip('late-swing', 'linear')]));
+ const audit = run();
+ expect(run()).toEqual(audit);
+
+ expect(farFindings(audit).map((f) => f.clipId)).toEqual(['late-swing']);
+ expect(audit.poseCoverage.status).toBe('partial');
+ const [busy, late] = audit.poseCoverage.clips;
+ expect(late).toMatchObject({ clipId: 'late-swing', omittedCount: 0 });
+ expect(busy.sampledTimes.length + late.sampledTimes.length).toBe(audit.poseCoverage.budget);
+ expect(busy.omittedCount).toBeGreaterThan(0);
+ expect(audit.evaluatedPoseCount).toBe(audit.poseCoverage.budget + 1);
+
+ // The exhausted budget is a stated gap, never a clean result.
+ const gap = audit.findings.find((f) => f.code === 'clip-poses-unsampled');
+ expect(gap).toMatchObject({ severity: 'note', clipId: 'busy', omittedCount: busy.omittedCount });
+ expect(gap.message).toContain(`${busy.omittedTimes[0]}s`);
+ expect(buildThreejsPhysicalAuditFeedback(audit)).toContain('In clip "Busy", attachments were checked at');
+ });
+
+ it('reports a static assembly as having no clip poses to sample', () => {
+ const spec = gripSpec([swingClip()]);
+ delete spec.animation;
+ const audit = evaluateThreejsPhysicalAudit(spec);
+ expect(audit.evaluatedPoseCount).toBe(1);
+ expect(farFindings(audit)).toEqual([]);
+ expect(audit.poseCoverage).toMatchObject({ status: 'static', clips: [] });
+ });
+});
diff --git a/server/services/threejsModels/index.js b/server/services/threejsModels/index.js
index 3b8e36d076..aeec552662 100644
--- a/server/services/threejsModels/index.js
+++ b/server/services/threejsModels/index.js
@@ -180,6 +180,9 @@ async function executeGeneration({
if (physicalAudit.errorCount > 0 || physicalAudit.warningCount > 0) {
console.warn(`⚠️ Three.js model ${id} physical audit: ${physicalAudit.errorCount} error, ${physicalAudit.warningCount} warning finding(s) across ${physicalAudit.evaluatedPoseCount} pose(s)`);
}
+ if (physicalAudit.poseCoverage?.status === 'partial' && physicalAudit.poseCoverage.measuresAttachments) {
+ console.warn(`⚠️ Three.js model ${id} physical audit: clip pose budget of ${physicalAudit.poseCoverage.budget} exhausted, some clip poses were not measured`);
+ }
if (materialPlausibility.warningCount > 0) {
console.warn(`⚠️ Three.js model ${id} material plausibility: ${materialPlausibility.warningCount} of ${materialPlausibility.matchedMaterialCount} recognized material(s) carry values their substance does not support`);
}