Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(assembly): turn the whole build per step (Flip, Tip, Spin), with turning paths that swing parts on their arc and atomic path saves

aashu166de8d3d581
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index dd26ec25f4..2fd3578347 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -72,7 +72,7 @@ pnpm --filter @carbon/erp test
| `productionQuantity` | Output: type (Production/Scrap/Rework), quantity, scrapReason |
| `jobOperationBatch` | Operation batch header (`BAT` sequence): process, work center, location, status (`Planned` = pre-floor, `Active` displayed "Released"). Members are `jobOperation` rows via nullable `jobOperationBatchId`. A Released batch's coalesced schedule slot is a `capacityReservation` row tagged `jobOperationBatchId` (spared by per-job regen deletes; visible in every snapshot regardless of the anchor job's status; deleted by a `jobOperationBatch` status trigger when the batch completes or is unreleased — the sparing rules make that trigger the only retirement path; dissolve self-heals via the FK's column-list SET NULL + the anchor job's next regen) |
| `procedure` / `procedureStep` / `procedureParameter` | Versioned work instructions |
-| `assemblyInstruction` / `assemblyInstructionStep` | 3D model-based assembly instructions (Draft/Published/Archived); steps carry `componentNodeIds` + `motion`/`camera` JSON for the viewer, `hiddenComponentNodeIds` (parts hidden on THAT step only — tooling/fixtures/installed parts in the way; never the step's own `componentNodeIds`, stripped by a DB trigger on every write; applied by the shared player in the ERP editor and MES playback, authored only in the ERP), a `buildWave` INTEGER (the step's longest-path level in the planner's precedence DAG — steps sharing a wave have no ordering constraint and can be built in parallel by different people/stations; NULL for cycle-affected or hand-authored steps; informational, `sortOrder` still governs playback), and `warnings.needsSupport` (a part in the step tips once placed — center of mass outside the support polygon of the parts below it — likely needs a fixture or a second hand; shown as a hand icon with a tooltip in the step list), and `warnings.plannedMotion` (the motion the step had before the author first drew a path in the editor — its presence marks the path as hand-drawn ("Custom path"), overrides `flagged`, and is what Reset restores; `updateAssemblyStepMotion` writes it on the first edit, a re-plan clears it by rewriting `warnings`) AND the typed-step fields mirrored from `jobOperationStep` (`type` `procedureStepType`, tiptap `description` with derived `instructionText`, `required`, UoM/min/max, `listValues`) for eventual copy into job operations. `motion`/`camera` are authored directly in the 3D viewer (drag the red waypoint path → relative `linear`/`L` motion, or `waypoints` once a waypoint is turned with the rotation rings; "Set view" captures the camera pose; a sub-assembly header's `motion` is the finished unit's own joining path, edited from the using step's Playback box — or the header's own panel when nothing uses it — and saved through the same motion route with the header id), autosaved via `updateAssemblyStepMotion` / the `steps/motion/$stepId` route — separate from the step form's `upsertAssemblyInstructionStep` (which rewrites `title`/typed fields). There is no numeric motion editor. **Step camera is a discriminated union**: a manual `{position,target,fov}` pose (applied verbatim), OR a planner hint `{source:"plan",direction}` — a mesh-precise view DIRECTION the Rust planner bakes per step (`crates/planner/src/view.rs` `best_view_direction`: sight lines against the real triangles of everything installed earlier, so it sees a hollow enclosure's open top where the viewer's AABB scoring can't). The viewer applies the hint with LIVE framing — target, standing distance, frustum fit at the real viewport aspect (`fitFraming`, `@carbon/viewer`). `null` = fully live AABB framing (fallback for hand-edited steps / old plans). Generated steps carry the plan hint (the TS-side camera bake was removed); re-motion refreshes it but never clobbers a manual pose. Playback visibility is presence-based (`@carbon/viewer` `visualForComponent`): a component exists on the canvas only once its step has run; components no step installs render like future-step ones (hidden during playback, future-components toggle while paused). Visibility has TWO independent axes — `futureMode` (not built yet) and `installedMode` (already built — `solid` default, so the historical rendering is unchanged; `ghost`/`hidden` let an operator see past an assembly that buries the active step's parts) — but the toolbar does NOT expose them as axes. It offers three NAMED views (`ASSEMBLY_VIEWS` / `VIEW_MODES` in `visibility.ts`): **Build** (installed solid — the historical default), **Focus** (installed ghosted, so you see past what is already fitted but keep its shape) and **Full** (everything solid). An "Isolate" view (installed hidden) was dropped: per-step `hiddenComponentNodeIds` cover removing the clutter an author chooses. The future side is hidden in all but Full: a step you are working is never helped by parts that are not on the bench yet. The same control renders in ERP and MES; nine combinations behind two icon triplets was the design that got rejected for being unreadable on a shop floor. The camera's AABB view-direction scoring honours both via `occluderWeight` — geometry the operator cannot see is never treated as an obstacle, or hiding it would clear the pixels while the framing still dodged it. AABB fallback motions for `"none"`-motion steps consider only PRIOR-step components as obstacles and fade in when no collision-free path exists or when the component interpenetrates a present component (mated parts — sliders on rails, fasteners in bores — never get fabricated paths; the planner is the only authority for those) |
+| `assemblyInstruction` / `assemblyInstructionStep` | 3D model-based assembly instructions (Draft/Published/Archived); steps carry `componentNodeIds` + `motion`/`camera` JSON for the viewer, `hiddenComponentNodeIds` (parts hidden on THAT step only — tooling/fixtures/installed parts in the way; never the step's own `componentNodeIds`, stripped by a DB trigger on every write; applied by the shared player in the ERP editor and MES playback, authored only in the ERP), `orientation` JSONB (the build's orientation from that step on — a unit quaternion, NULL = same as the previous step of the same build; written through `updateAssemblyStepMotion` by the Playback panel's five turn buttons — Flip over (180°), Tip toward you, Tip away from you, Spin left, Spin right (90° each), measured from the current view — in `ui/Assemblies/AssemblyOrientationRow.tsx`; a turn that lands back on the inherited orientation saves NULL. A turn that leaves the step turned also pins the current view as its `camera` when the step has no manual view (`isSavedView`, `@carbon/viewer`: a `{source:"plan"}` hint does not count), so playback lands on what the author saw; the Camera row (`AssemblyCameraRow`) uses the same check, so a plan hint reads "Automatic" and offers no Clear; a turn back keeps the pinned view and Reset only clears `orientation` — the Camera row's Clear returns to automatic framing; see `@carbon/viewer` `orientation.ts`), a `buildWave` INTEGER (the step's longest-path level in the planner's precedence DAG — steps sharing a wave have no ordering constraint and can be built in parallel by different people/stations; NULL for cycle-affected or hand-authored steps; informational, `sortOrder` still governs playback), and `warnings.needsSupport` (a part in the step tips once placed — center of mass outside the support polygon of the parts below it — likely needs a fixture or a second hand; shown as a hand icon with a tooltip in the step list), and `warnings.plannedMotion` (the motion the step had before the author first drew a path in the editor — its presence marks the path as hand-drawn ("Custom path"), overrides `flagged` (`isPlanFlagged` / `hasCustomMotion` in `@carbon/viewer` — server code imports them from the three-free `@carbon/viewer/steps` — are the one check, used by `toViewerStep`, the step list, the Properties panel and the MES `AssemblyView`), and is what Reset restores; `updateAssemblyStepMotion` writes it on the first edit, a re-plan clears it by rewriting `warnings`) AND the typed-step fields mirrored from `jobOperationStep` (`type` `procedureStepType`, tiptap `description` with derived `instructionText`, `required`, UoM/min/max, `listValues`) for eventual copy into job operations. `motion`/`camera` are authored directly in the 3D viewer (drag the red waypoint path → relative `linear`/`L` motion, or `waypoints` once a waypoint is turned with the rotation rings; "Set view" captures the camera pose; a sub-assembly header's `motion` is the finished unit's own joining path, edited from the using step's Playback box — or the header's own panel when nothing uses it — and saved through the same motion route with the header id), autosaved via `updateAssemblyStepMotion` / the `steps/motion/$stepId` route — separate from the step form's `upsertAssemblyInstructionStep` (which rewrites `title`/typed fields). There is no numeric motion editor. **Step camera is a discriminated union**: a manual `{position,target,fov}` pose (applied verbatim), OR a planner hint `{source:"plan",direction}` — a mesh-precise view DIRECTION the Rust planner bakes per step (`crates/planner/src/view.rs` `best_view_direction`: sight lines against the real triangles of everything installed earlier, so it sees a hollow enclosure's open top where the viewer's AABB scoring can't). The viewer applies the hint with LIVE framing — target, standing distance, frustum fit at the real viewport aspect (`fitFraming`, `@carbon/viewer`). `null` = fully live AABB framing (fallback for hand-edited steps / old plans). Generated steps carry the plan hint (the TS-side camera bake was removed); re-motion refreshes it but never clobbers a manual pose. Playback visibility is presence-based (`@carbon/viewer` `visualForComponent`): a component exists on the canvas only once its step has run; components no step installs render like future-step ones (hidden during playback, future-components toggle while paused). Visibility has TWO independent axes — `futureMode` (not built yet) and `installedMode` (already built — `solid` default, so the historical rendering is unchanged; `ghost`/`hidden` let an operator see past an assembly that buries the active step's parts) — but the toolbar does NOT expose them as axes. It offers three NAMED views (`ASSEMBLY_VIEWS` / `VIEW_MODES` in `visibility.ts`): **Build** (installed solid — the historical default), **Focus** (installed ghosted, so you see past what is already fitted but keep its shape) and **Full** (everything solid). An "Isolate" view (installed hidden) was dropped: per-step `hiddenComponentNodeIds` cover removing the clutter an author chooses. The future side is hidden in all but Full: a step you are working is never helped by parts that are not on the bench yet. The same control renders in ERP and MES; nine combinations behind two icon triplets was the design that got rejected for being unreadable on a shop floor. The camera's AABB view-direction scoring honours both via `occluderWeight` — geometry the operator cannot see is never treated as an obstacle, or hiding it would clear the pixels while the framing still dodged it. AABB fallback motions for `"none"`-motion steps consider only PRIOR-step components as obstacles and fade in when no collision-free path exists or when the component interpenetrates a present component (mated parts — sliders on rails, fasteners in bores — never get fabricated paths; the planner is the only authority for those) |
| `assemblyInstructionStepMaterial` | BOM parts consumed at a step (`stepId` → `itemId` + optional quantity; stored by itemId so links survive make-method re-versioning; picker limited to the item's make-method BOM; UNIQUE `(stepId, itemId)`). Auto-populated from `assemblyComponentMapping` via `syncAssemblyStepMaterialsFromMappings` — additive only (manual quantities/deletions survive), triggered on step generation, component add, mapping create, and "Match BOM" |
| `assemblyInstructionStepSlide` | Per-step reference slides (image XOR 3D model via `modelUploadId`, caption, `size`, `annotations` JSONB pins), mirroring `methodOperationStepSlide`; authored in the step editor's Details tab and copied to `jobOperationStepSlide` by the BOP sync / get-method. The former `assemblyInstructionStepRequirement` / `assemblyStandardNote` tables (fixtures/consumables/notes/media) were dropped — a step definition is parts + tools + slides |
| `assemblyInstructionStepTool` | Tools used at a step (`stepId` → `itemId` of a tool-type item + `quantity`, UNIQUE `(stepId, itemId)`) — `itemId` is the same target `jobOperationTool.toolId` references, so the BOP sync maps rows 1:1 |
@@ -114,7 +114,7 @@ pnpm --filter @carbon/erp test
- `updateAssemblyStepHiddenComponents` — autosave for a step's hidden list (route `x+/assembly+/$id.steps.hidden.$stepId.tsx`). The rule "a step never hides its own parts" lives in ONE place, the `assembly_step_strip_own_hidden_components` BEFORE trigger (migration `20260925063121`), which strips + dedupes on every insert/update of either array — no service strips it by hand.
- `getAssemblyInstruction(s)` / `upsertAssemblyInstructionStep` / `getAssemblyInstructionStepMaterials` — assembly instruction authoring; the step upsert derives `instructionText` from the tiptap `description` (viewer/MES consume the plain text)
- `getAssemblyInstructionVersions` / `copyAssemblyInstructionAsVersion` / `activateAssemblyInstructionVersion` — versioning (see the Assembly Instructions concept above). Routes: `x+/assembly+/$id.version.new.tsx` (copy → new Draft) and `x+/assembly+/$id.activate.tsx` (make active). Change-notice diffs of a `methodOperation` now surface its `assemblyInstructionId` (resolved to the instruction name), `inspectionDocumentId` (drawing/file name), and `operationType` via `stampOperationRefNames` + `ChangeNoticeDiffViewer` (items module)
-- `updateAssemblyStepMotion` — partial `motion`/`camera` patch for one step, used by the 3D path/camera editor's autosave (never touches `title`/typed fields); `camera: null` clears the pose (return to auto-framing). Deleting an instruction also drops the model's cached plan via `deleteAssemblyInstruction` → `invalidateAssemblyPlanCache`
+- `updateAssemblyStepMotion` — partial `motion`/`camera`/`orientation` patch for one step, used by the 3D path/camera editor's autosave and the orientation turn buttons (never touches `title`/typed fields); `camera: null` clears the pose (return to auto-framing), `orientation: null` makes the step inherit its build's orientation again, and `reset` puts back `warnings.plannedMotion` (the motion before the first hand-drawn path). It takes the Kysely handle (the route passes `getDatabaseClient()`) and writes every patch as ONE `UPDATE … WHERE id AND companyId` whose jsonb expressions read `motion`/`warnings` from the row being written: a path edit records `plannedMotion` from the old `motion` only when the marker is absent, Reset restores it (else `{"type":"none"}`) and drops the marker (`warnings` → NULL when nothing else is left), `flagged`/`blockedBy` are kept. A drag save and a Reset that land together therefore serialize on the row lock instead of losing the marker — never split it back into a read and a write. Returns `{ data, error }`. The editor route builds every post to it with `stepPatchFormData` (`ui/Assemblies/assembly-step-patch.ts`); `useStepMotionEditor` owns the path/camera edit session (one fetcher per row and column, so a Reset or Set view never aborts a drag save on another row) and `useBuildOrientation` owns the orientation fetcher and shows the pending orientation in the viewer before the save lands. The panel receives them as the grouped `motionEditing` / `camera` / `orientation` props. Deleting an instruction also drops the model's cached plan via `deleteAssemblyInstruction` → `invalidateAssemblyPlanCache`
- `generateAssemblyStepsFromPlan` — plan.json → draft steps via `buildAssemblyStepGroups` (`@carbon/viewer`): sequence order, consecutive identical components merged, subassembly `groups` one step (titled by the unit `name`), `mergedInto` components riding their host's step; planner-flagged components (blockedBy / failed verification) store motion "none" + `warnings: { flagged, blockedBy }` (the viewer fades them in — no fabricated paths); a **floater fold** using the plan's `contacts` graph merges a placed-but-detached part with the immediately-following step that attaches to it (collision precedence forces the part in first, so it would otherwise render as a lone floating island for one step) — the pair installs as one rigid step along the detached part's motion; skipped on older plans lacking `contacts`; `mode: "regenerate"` replaces existing steps, refused while any step is `planConfidence: "manual"` or status `Done`. Persists a human `title` on every step via `describeStep` (`@carbon/viewer`) — real editable data, not just a render-time fallback. Seeds each step's materials from the component→BOM mappings (best-effort): auto-runs `autoMatchAssemblyComponents` once when the model has no mappings yet, and returns `unmappedComponentCount` (distinct geometry groups with no BOM item) which the generate route surfaces as a "use Match BOM" nudge
- `syncAssemblyStepMaterialsFromMappings` — adds mapped BOM items (`assemblyComponentMapping`) to steps' materials from their `componentNodeIds` (quantity = instance count in the step); additive + best-effort, never updates or removes rows; scopable by `stepIds` / `geometryHashes` / `onlyComponentNodeIds`. Called from the step-components autosave route (newly added nodes only), the mapping-create route (that hash only), and the "Match BOM" route (full backfill)
- `getAssemblyUnits` / `upsertAssemblyUnit` / `deleteAssemblyUnit` — model-scoped "plan as one component" overrides (`assemblyUnit`: `componentNodeIds[]` + optional `itemId`), authored from the BOM tree
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index b850fc5a59..d54f602e02 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -1310,7 +1310,6 @@ const unitQuaternion = quaternion.refine(
{ message: "Rotation must be a unit quaternion" }
);
-/** A waypoint at the seated pose: no offset and no turn (either quaternion sign). */
function isSeatWaypoint(
waypoint: { offset: number[]; rotation: number[] } | undefined
): boolean {
@@ -1320,10 +1319,7 @@ function isSeatWaypoint(
return Math.hypot(ox, oy, oz) < 1e-3 && Math.abs(Math.abs(w) - 1) < 1e-6;
}
-/**
- * Insertion motion of a step's parts. Mirrors `Motion` in
- * `packages/viewer/src/types.ts`, the shared contract.
- */
+/** Mirrors `Motion` in `packages/viewer/src/types.ts` — keep them in sync. */
export const motionSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("linear"),
@@ -1363,8 +1359,7 @@ export const motionSchema = z.discriminatedUnion("type", [
)
.min(2)
}),
- // Editor-drawn path with rotation: poses relative to the seated pose. The
- // last waypoint is the seat itself (no offset, no turn).
+ // Editor-drawn path; poses are relative to the seated pose.
z.object({
type: z.literal("waypoints"),
waypoints: z
@@ -1392,6 +1387,12 @@ export const cameraSchema = z.union([
})
]);
+/**
+ * A step's build orientation: a unit quaternion turning the model frame into
+ * the bench frame. Mirrors `AssemblyStep.orientation` in `@carbon/viewer`.
+ */
+export const orientationSchema = unitQuaternion;
+
export const fastenerSchema = z.object({
spec: z.string().optional(),
count: z.number().int().positive().optional(),
@@ -1418,29 +1419,13 @@ export const stepPlanWarningsSchema = z.object({
/**
* The motion the step had before the author first drew a path (the
* planner's, or `none`). Present = the path is hand-drawn, which also
- * overrides `flagged`; Reset puts it back. A re-plan rewrites `warnings`,
+ * overrides `flagged` (`hasCustomMotion` / `isPlanFlagged` in
+ * `@carbon/viewer/steps`); Reset puts it back. A re-plan rewrites `warnings`,
* so it clears this together with the drawn path it replaces.
*/
plannedMotion: z.unknown().optional()
});
-/**
- * The step's motion was drawn by hand in the path editor (see `plannedMotion`).
- * The planner stores `none` on a flagged step, so a flagged step that moves was
- * drawn too — paths drawn before `plannedMotion` existed carry no marker.
- */
-export function hasCustomMotion(warnings: unknown, motion: unknown): boolean {
- const parsed = stepPlanWarningsSchema.safeParse(warnings).data;
- if (parsed?.plannedMotion !== undefined) return true;
- return (
- parsed?.flagged === true &&
- typeof motion === "object" &&
- motion !== null &&
- "type" in motion &&
- motion.type !== "none"
- );
-}
-
const jsonField = <T extends z.ZodTypeAny>(schema: T) =>
z.preprocess((raw) => {
if (typeof raw !== "string") return raw;
@@ -1615,7 +1600,9 @@ export const assemblyInstructionStepMotionValidator = z.object({
motion: jsonField(motionSchema.optional()),
// Put back the motion the step had before the author first drew a path.
reset: zfd.checkbox(),
- camera: jsonField(cameraSchema.nullable().optional())
+ camera: jsonField(cameraSchema.nullable().optional()),
+ // The build's orientation from this step on; `null` = same as the step before.
+ orientation: jsonField(orientationSchema.nullable().optional())
});
/**
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 38a4488e45..1395aa2840 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -40,6 +40,7 @@ import {
indexAssemblyGraph,
validateSubAssemblies
} from "@carbon/viewer";
+import { isPlanFlagged } from "@carbon/viewer/steps";
import { parseDate } from "@internationalized/date";
import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
import type { ExpressionBuilder } from "kysely";
@@ -100,15 +101,14 @@ import {
cameraSchema,
fastenerSchema,
getAssemblyModelState,
- hasCustomMotion,
isJobLocked,
isJobOrderStatusHidden,
JOB_LOCKED_STATUSES,
JOB_SUPPLY_STATUS_PRIORITY,
motionSchema,
+ orientationSchema,
PLANNING_EDITABLE_JOB_STATUSES,
PO_STATUS_PRIORITY,
- stepPlanWarningsSchema,
WEEKDAYS_MONDAY_FIRST
} from "./production.models";
import type {
@@ -7873,72 +7873,82 @@ export async function upsertAssemblyInstructionStep(
* Kept separate from `upsertAssemblyInstructionStep` (which always rewrites
* `title` and the typed-step fields) so the 3D editor can autosave a drag or a
* "Set view" click without touching the rest of the step. `camera: null` clears
- * the pose (return to auto-framing); omitting a field leaves it untouched.
+ * the pose (return to auto-framing); `orientation: null` makes the step keep the
+ * previous step's build orientation; omitting a field leaves it untouched.
+ *
+ * The first hand-drawn edit keeps the motion it replaces in
+ * `warnings.plannedMotion`; `reset` restores it and drops the marker. Both are
+ * ONE UPDATE that reads `motion`/`warnings` from the row it writes, so a drag
+ * save and a Reset reaching the server together cannot lose `plannedMotion`.
* @mcp update
*/
export async function updateAssemblyStepMotion(
- client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
data: {
id: string;
motion?: z.infer<typeof motionSchema>;
camera?: z.infer<typeof cameraSchema> | null;
+ orientation?: z.infer<typeof orientationSchema> | null;
/** Put back the motion the step had before its path was first drawn. */
reset?: boolean;
companyId: string;
updatedBy: string;
}
-) {
- let motionPatch: { motion?: Json; warnings?: Json | null } = {};
- if (data.reset || data.motion !== undefined) {
- const current = await client
- .from("assemblyInstructionStep")
- .select("motion, warnings")
- .eq("id", data.id)
- .eq("companyId", data.companyId)
- .single();
- if (current.error) return { data: null, error: current.error };
- // The first hand-drawn edit keeps the planner's motion in
- // `warnings.plannedMotion`; Reset restores it and drops the marker.
- const warnings =
- current.data.warnings &&
- typeof current.data.warnings === "object" &&
- !Array.isArray(current.data.warnings)
- ? (current.data.warnings as Record<string, Json | undefined>)
- : {};
- const { plannedMotion, ...rest } = warnings;
- if (data.reset) {
- motionPatch = {
- motion: plannedMotion ?? { type: "none" },
- warnings: Object.keys(rest).length > 0 ? (rest as Json) : null
- };
- } else {
- motionPatch = {
- motion: data.motion as Json,
- ...(plannedMotion === undefined
+): Promise<
+ { data: { id: string }; error: null } | { data: null; error: Error }
+> {
+ const flags = sql<Json>`CASE WHEN jsonb_typeof("warnings") = 'object' THEN "warnings" ELSE '{}'::jsonb END`;
+ const motionPatch = data.reset
+ ? {
+ motion: sql<Json>`COALESCE(NULLIF(${flags} -> 'plannedMotion', 'null'::jsonb), '{"type":"none"}'::jsonb)`,
+ warnings: sql<Json | null>`NULLIF(${flags} - 'plannedMotion', '{}'::jsonb)`
+ }
+ : data.motion !== undefined
+ ? {
+ motion: sql<Json>`${JSON.stringify(data.motion)}::jsonb`,
+ // `"motion"` is the pre-UPDATE value: the motion the drawn path replaces.
+ warnings: sql<Json | null>`CASE WHEN ${flags} ? 'plannedMotion' THEN "warnings" ELSE ${flags} || jsonb_build_object('plannedMotion', "motion") END`
+ }
+ : {};
+ try {
+ const row = await db
+ .updateTable("assemblyInstructionStep")
+ .set({
+ ...motionPatch,
+ ...(data.camera !== undefined
? {
- warnings: {
- ...rest,
- plannedMotion: current.data.motion
- } as Json
+ camera:
+ data.camera === null
+ ? null
+ : sql<Json>`${JSON.stringify(data.camera)}::jsonb`
}
- : {})
- };
- }
+ : {}),
+ ...(data.orientation !== undefined
+ ? {
+ orientation:
+ data.orientation === null
+ ? null
+ : sql<Json>`${JSON.stringify(data.orientation)}::jsonb`
+ }
+ : {}),
+ updatedBy: data.updatedBy,
+ updatedAt: datetime.timestamp()
+ })
+ .where("id", "=", data.id)
+ .where("companyId", "=", data.companyId)
+ .returning("id")
+ .executeTakeFirst();
+ if (!row) return { data: null, error: new Error("Step not found") };
+ return { data: row, error: null };
+ } catch (err) {
+ return {
+ data: null,
+ error:
+ err instanceof Error
+ ? err
+ : new Error(getErrorMessage(err, "Failed to update motion"))
+ };
}
- return client
- .from("assemblyInstructionStep")
- .update({
- ...motionPatch,
- ...(data.camera !== undefined
- ? { camera: data.camera as Json | null }
- : {}),
- updatedBy: data.updatedBy,
- updatedAt: new Date().toISOString()
- })
- .eq("id", data.id)
- .eq("companyId", data.companyId)
- .select("id")
- .single();
}
// Autosave target for the Details panel's Add/remove component controls: patches
@@ -10488,8 +10498,8 @@ export async function generateAssemblyStepsFromPlan(
export function toViewerStep(step: AssemblyInstructionStepRow): AssemblyStep {
const motion = motionSchema.safeParse(step.motion);
const camera = cameraSchema.safeParse(step.camera);
+ const orientation = orientationSchema.safeParse(step.orientation);
const fastener = fastenerSchema.safeParse(step.fastener);
- const planWarnings = stepPlanWarningsSchema.safeParse(step.warnings);
return {
id: step.id,
@@ -10502,15 +10512,10 @@ export function toViewerStep(step: AssemblyInstructionStepRow): AssemblyStep {
usedInStepId: step.usedInStepId ?? null,
motion: motion.success ? motion.data : { type: "none" },
camera: camera.success ? camera.data : null,
+ orientation: orientation.success ? orientation.data : null,
fastener: fastener.success ? fastener.data : null,
durationSeconds: step.durationSeconds,
- // A hand-drawn path overrides the planner's "no clear path" flag.
- flagged:
- planWarnings.success &&
- planWarnings.data.flagged === true &&
- !hasCustomMotion(step.warnings, step.motion)
- ? true
- : undefined
+ flagged: isPlanFlagged(step.warnings, step.motion) ? true : undefined
};
}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyCameraRow.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyCameraRow.tsx
new file mode 100644
index 0000000000..cf3dc100e5
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyCameraRow.tsx
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { Button, HStack, LabelWithHelp } from "@carbon/react";
+import { Trans } from "@lingui/react/macro";
+import PlaybackRow from "./AssemblyPlaybackRow";
+import type { CameraControls } from "./useStepMotionEditor";
+
+/**
+ * A planner hint (`{ source: "plan" }`) is not a saved view: it reads as
+ * Automatic and offers no Clear.
+ */
+export default function AssemblyCameraRow({
+ stepId,
+ hasSavedView,
+ isDisabled,
+ camera
+}: {
+ stepId: string;
+ hasSavedView: boolean;
+ isDisabled: boolean;
+ camera: CameraControls;
+}) {
+ return (
+ <PlaybackRow
+ label={
+ <LabelWithHelp termId="assembly-step-camera" variant="inline">
+ <Trans>Camera</Trans>
+ </LabelWithHelp>
+ }
+ value={
+ hasSavedView ? <Trans>Saved view</Trans> : <Trans>Automatic</Trans>
+ }
+ >
+ {!isDisabled && (
+ <HStack spacing={1}>
+ {hasSavedView && (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => camera.onClear(stepId)}
+ >
+ <Trans>Clear</Trans>
+ </Button>
+ )}
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={() => camera.onSet(stepId)}
+ >
+ <Trans>Use Current View</Trans>
+ </Button>
+ </HStack>
+ )}
+ </PlaybackRow>
+ );
+}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx
index e286489211..c65336cf08 100644
--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx
@@ -47,15 +47,17 @@ import {
buildSubAssemblyPlan,
describeStep,
groupComponentNodeIds,
+ hasCustomMotion,
+ isPlanFlagged,
+ isSavedView,
subAssemblyPartIds,
usableSubAssemblies
} from "@carbon/viewer";
import { Plural, Trans, useLingui } from "@lingui/react/macro";
-import { memo, useCallback, useEffect, useMemo, useState } from "react";
+import { memo, useCallback, useMemo, useState } from "react";
import {
LuBoxes,
LuCirclePlus,
- LuEyeOff,
LuMousePointerClick,
LuTriangleAlert,
LuX
@@ -69,7 +71,6 @@ import { path } from "~/utils/path";
import {
assemblyInstructionStepValidator,
fastenerSchema,
- hasCustomMotion,
stepPlanWarningsSchema
} from "../../production.models";
import type { FlattenedBomMaterial } from "../../production.service";
@@ -79,8 +80,11 @@ import type {
AssemblyStepSlide,
AssemblyStepTool
} from "../../types";
+import AssemblyCameraRow from "./AssemblyCameraRow";
+import AssemblyOrientationRow from "./AssemblyOrientationRow";
import PlaybackRow from "./AssemblyPlaybackRow";
import { ComponentColorSwatch } from "./AssemblyStepBom";
+import AssemblyStepHiddenComponents from "./AssemblyStepHiddenComponents";
import { SUB_ASSEMBLY_PARAM } from "./AssemblyStepList";
import AssemblyStepMaterials from "./AssemblyStepMaterials";
import AssemblyStepSlides from "./AssemblyStepSlides";
@@ -88,6 +92,8 @@ import { AssemblyStepStatus, normalizeStepStatus } from "./AssemblyStepStatus";
import AssemblyStepTools from "./AssemblyStepTools";
import SubAssemblyPathRow from "./AssemblySubAssemblyPathRow";
import AssemblySubAssemblyProperties from "./AssemblySubAssemblyProperties";
+import type { BuildOrientationControls } from "./useBuildOrientation";
+import type { CameraControls, MotionEditing } from "./useStepMotionEditor";
type AssemblyInstructionPropertiesProps = {
step: AssemblyInstructionStepRow | null;
@@ -110,17 +116,9 @@ type AssemblyInstructionPropertiesProps = {
onRemoveComponents: (nodeIds: string[]) => void;
hiddenNodeIds: string[];
onSetHiddenComponents: (nodeIds: string[]) => void;
- /** The active step's motion path is open in the 3D editor */
- isEditingMotion: boolean;
- /** The sub-assembly whose joining path is open in the 3D editor, if any */
- editingUnitId: string | null;
- /** Opens the editor on a step's motion, or on a sub-assembly it carries in */
- onEditMotion: (stepId: string, unitHeaderId?: string) => void;
- onStopEditMotion: () => void;
- /** Puts back the motion a step or sub-assembly had before its path was drawn */
- onResetMotion: (stepId: string) => void;
- onSetCamera: (stepId: string) => void;
- onClearCamera: (stepId: string) => void;
+ motionEditing: MotionEditing;
+ camera: CameraControls;
+ orientation: BuildOrientationControls;
/** Every step of the instruction, in play order — numbering and sub-assemblies */
viewerSteps: AssemblyStep[];
onSelectStep: (stepId: string) => void;
@@ -144,13 +142,9 @@ const AssemblyInstructionProperties = ({
onRemoveComponents,
hiddenNodeIds,
onSetHiddenComponents,
- isEditingMotion,
- editingUnitId,
- onEditMotion,
- onStopEditMotion,
- onResetMotion,
- onSetCamera,
- onClearCamera,
+ motionEditing,
+ camera,
+ orientation,
viewerSteps,
onSelectStep
}: AssemblyInstructionPropertiesProps) => {
@@ -281,12 +275,8 @@ const AssemblyInstructionProperties = ({
isDisabled={isDisabled}
itemMentions={itemMentions}
onSelectStep={onSelectStep}
- onSetCamera={onSetCamera}
- onClearCamera={onClearCamera}
- editingUnitId={editingUnitId}
- onEditMotion={onEditMotion}
- onStopEditMotion={onStopEditMotion}
- onResetMotion={onResetMotion}
+ camera={camera}
+ motionEditing={motionEditing}
/>
) : step ? (
<Tabs defaultValue="details" className="w-full px-4 pb-2 pt-3">
@@ -323,13 +313,9 @@ const AssemblyInstructionProperties = ({
onRemoveComponents={onRemoveComponents}
hiddenNodeIds={hiddenNodeIds}
onSetHiddenComponents={onSetHiddenComponents}
- isEditingMotion={isEditingMotion}
- editingUnitId={editingUnitId}
- onEditMotion={onEditMotion}
- onStopEditMotion={onStopEditMotion}
- onResetMotion={onResetMotion}
- onSetCamera={onSetCamera}
- onClearCamera={onClearCamera}
+ motionEditing={motionEditing}
+ camera={camera}
+ orientation={orientation}
viewerSteps={viewerSteps}
subPlan={subPlan}
titleOf={titleOf}
@@ -392,16 +378,10 @@ function getPlanFlag(
step: Pick<AssemblyInstructionStepRow, "warnings" | "motion">,
graphIndex: AssemblyGraphIndex | null
): { blockers: string[] } | null {
- const parsed = stepPlanWarningsSchema.safeParse(step.warnings);
- // A hand-drawn path overrides the planner's flag.
- if (
- !parsed.success ||
- parsed.data.flagged !== true ||
- hasCustomMotion(step.warnings, step.motion)
- ) {
- return null;
- }
- const blockers = (parsed.data.blockedBy ?? [])
+ if (!isPlanFlagged(step.warnings, step.motion)) return null;
+ const blockedBy =
+ stepPlanWarningsSchema.safeParse(step.warnings).data?.blockedBy ?? [];
+ const blockers = blockedBy
.map((nodeId) => graphIndex?.nodesById.get(nodeId)?.name)
.filter((name): name is string => Boolean(name));
return { blockers: [...new Set(blockers)] };
@@ -455,13 +435,9 @@ function StepForm({
onRemoveComponents,
hiddenNodeIds,
onSetHiddenComponents,
- isEditingMotion,
- editingUnitId,
- onEditMotion,
- onStopEditMotion,
- onResetMotion,
- onSetCamera,
- onClearCamera,
+ motionEditing,
+ camera,
+ orientation,
viewerSteps,
subPlan,
titleOf,
@@ -481,13 +457,9 @@ function StepForm({
onRemoveComponents: (nodeIds: string[]) => void;
hiddenNodeIds: string[];
onSetHiddenComponents: (nodeIds: string[]) => void;
- isEditingMotion: boolean;
- editingUnitId: string | null;
- onEditMotion: (stepId: string, unitHeaderId?: string) => void;
- onStopEditMotion: () => void;
- onResetMotion: (stepId: string) => void;
- onSetCamera: (stepId: string) => void;
- onClearCamera: (stepId: string) => void;
+ motionEditing: MotionEditing;
+ camera: CameraControls;
+ orientation: BuildOrientationControls;
viewerSteps: AssemblyStep[];
subPlan: Map<string, SubAssemblyInfo>;
titleOf: (stepId: string) => string;
@@ -527,7 +499,8 @@ function StepForm({
const cannotSave = isDisabled || !permissions.can("update", "production");
- const hasCamera = step.camera != null;
+ const hasSavedView = isSavedView(step.camera);
+ const isEditingMotion = motionEditing.isEditingStep;
// Title shown when the title field is left blank — derived from the components
// plus any stored fastener, matching how the step is titled elsewhere.
@@ -671,7 +644,7 @@ function StepForm({
onRemoveComponents={onRemoveComponents}
/>
- <StepHiddenComponentsEditor
+ <AssemblyStepHiddenComponents
hiddenNodeIds={hiddenNodeIds}
graphIndex={graphIndex}
isDisabled={isDisabled}
@@ -712,7 +685,7 @@ function StepForm({
<Button
variant="ghost"
size="sm"
- onClick={() => onResetMotion(step.id)}
+ onClick={() => motionEditing.onReset(step.id)}
>
<Trans>Reset</Trans>
</Button>
@@ -723,8 +696,8 @@ function StepForm({
isDisabled={componentNodeIds.length === 0}
onClick={() =>
isEditingMotion
- ? onStopEditMotion()
- : onEditMotion(step.id)
+ ? motionEditing.onStop()
+ : motionEditing.onEdit(step.id)
}
>
{isEditingMotion ? (
@@ -741,44 +714,26 @@ function StepForm({
key={header.id}
name={titleOf(header.id)}
hasPath={header.motion.type !== "none"}
- isEditing={editingUnitId === header.id}
+ isEditing={motionEditing.editingUnitId === header.id}
isDisabled={isDisabled}
- onEdit={() => onEditMotion(step.id, header.id)}
- onStopEdit={onStopEditMotion}
- onReset={() => onResetMotion(header.id)}
+ onEdit={() => motionEditing.onEdit(step.id, header.id)}
+ onStopEdit={motionEditing.onStop}
+ onReset={() => motionEditing.onReset(header.id)}
/>
))}
- <PlaybackRow
- label={
- <LabelWithHelp termId="assembly-step-camera" variant="inline">
- <Trans>Camera</Trans>
- </LabelWithHelp>
- }
- value={
- hasCamera ? <Trans>Saved view</Trans> : <Trans>Automatic</Trans>
- }
- >
- {!isDisabled && (
- <HStack spacing={1}>
- {hasCamera && (
- <Button
- variant="ghost"
- size="sm"
- onClick={() => onClearCamera(step.id)}
- >
- <Trans>Clear</Trans>
- </Button>
- )}
- <Button
- variant="secondary"
- size="sm"
- onClick={() => onSetCamera(step.id)}
- >
- <Trans>Use Current View</Trans>
- </Button>
- </HStack>
- )}
- </PlaybackRow>
+ <AssemblyCameraRow
+ stepId={step.id}
+ hasSavedView={hasSavedView}
+ isDisabled={isDisabled}
+ camera={camera}
+ />
+ <AssemblyOrientationRow
+ stepId={step.id}
+ viewerSteps={viewerSteps}
+ subPlan={subPlan}
+ isDisabled={isDisabled}
+ controls={orientation}
+ />
</div>
</VStack>
@@ -1083,146 +1038,3 @@ function StepComponentsEditor({
</VStack>
);
}
-
-/** Parts are hidden from the Components panel eye; here they can only be shown again. */
-function StepHiddenComponentsEditor({
- hiddenNodeIds,
- graphIndex,
- isDisabled,
- onSetHiddenComponents
-}: {
- hiddenNodeIds: string[];
- graphIndex: AssemblyGraphIndex | null;
- isDisabled: boolean;
- onSetHiddenComponents: (nodeIds: string[]) => void;
-}) {
- const { t } = useLingui();
- // "Show all" saves at once but stays undoable for SHOW_ALL_UNDO_MS, so a stray
- // click can't silently throw away a step's tuned hidden list.
- const [undoNodeIds, setUndoNodeIds] = useState<string[] | null>(null);
- useEffect(() => {
- if (!undoNodeIds) return;
- const timer = setTimeout(() => setUndoNodeIds(null), SHOW_ALL_UNDO_MS);
- return () => clearTimeout(timer);
- }, [undoNodeIds]);
- const isUndoPending = undoNodeIds !== null;
- const listedNodeIds = undoNodeIds ?? hiddenNodeIds;
-
- const groups = useMemo(
- () => (graphIndex ? groupComponentNodeIds(listedNodeIds, graphIndex) : []),
- [listedNodeIds, graphIndex]
- );
- const onShow = (nodeIds: string[]) => {
- const show = new Set(nodeIds);
- onSetHiddenComponents(hiddenNodeIds.filter((nodeId) => !show.has(nodeId)));
- };
-
- const onShowAll = () => {
- setUndoNodeIds(hiddenNodeIds);
- onSetHiddenComponents([]);
- };
-
- // Restore the shown parts, keeping anything hidden elsewhere in the meantime.
- const onHideAgain = () => {
- if (!undoNodeIds) return;
- onSetHiddenComponents([...new Set([...hiddenNodeIds, ...undoNodeIds])]);
- setUndoNodeIds(null);
- };
-
- return (
- <VStack spacing={2} className="w-full">
- <HStack className="w-full justify-between">
- <Subheading as="h4" variant="heavy">
- <LabelWithHelp
- termId="assembly-step-hidden-components"
- variant="inline"
- >
- <Trans>Hidden on this step</Trans>
- </LabelWithHelp>
- </Subheading>
- {groups.length === 0 ? (
- <span className="text-xs text-muted-foreground">
- <Trans>None</Trans>
- </span>
- ) : (
- !isDisabled &&
- (isUndoPending ? (
- <HideAgainButton onClick={onHideAgain} />
- ) : (
- <Button variant="secondary" size="sm" onClick={onShowAll}>
- <Trans>Show All</Trans>
- </Button>
- ))
- )}
- </HStack>
- {groups.length === 0 ? null : (
- <ul className="max-h-64 w-full divide-y divide-border overflow-y-auto rounded-lg border border-border scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
- {groups.map((group) => (
- <li
- key={group.key}
- className={cn(
- "flex w-full items-center gap-2 px-2 py-1.5 text-sm",
- isUndoPending && "opacity-50"
- )}
- >
- <ComponentColorSwatch color={group.color} />
- <span
- className="min-w-0 flex-1 truncate text-muted-foreground"
- title={group.name}
- >
- {group.name}
- </span>
- {group.count > 1 && (
- <Badge variant="secondary" className="tabular-nums">
- ×{group.count}
- </Badge>
- )}
- {!isDisabled && !isUndoPending && (
- <IconButton
- aria-label={t`Show ${group.name}`}
- icon={<LuEyeOff />}
- variant="ghost"
- size="sm"
- className="text-muted-foreground"
- onClick={() => onShow(group.nodeIds)}
- />
- )}
- </li>
- ))}
- </ul>
- )}
- </VStack>
- );
-}
-
-const SHOW_ALL_UNDO_MS = 4000;
-
-function HideAgainButton({ onClick }: { onClick: () => void }) {
- const [isDraining, setIsDraining] = useState(false);
- useEffect(() => {
- // Start full, then drain on the next frame so the width transition runs.
- const frame = requestAnimationFrame(() => setIsDraining(true));
- return () => cancelAnimationFrame(frame);
- }, []);
-
- return (
- <Button
- variant="secondary"
- size="sm"
- className="relative overflow-hidden"
- onClick={onClick}
- >
- <span
- aria-hidden
- className="pointer-events-none absolute inset-y-0 left-0 bg-primary/15"
- style={{
- width: isDraining ? "0%" : "100%",
- transition: `width ${SHOW_ALL_UNDO_MS}ms linear`
- }}
- />
- <span className="relative">
- <Trans>Hide Again</Trans>
- </span>
- </Button>
- );
-}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyOrientationRow.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyOrientationRow.tsx
new file mode 100644
index 0000000000..337b982135
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyOrientationRow.tsx
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import {
+ Button,
+ HStack,
+ IconButton,
+ LabelWithHelp,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@carbon/react";
+import type { AssemblyStep, BuildTurn, SubAssemblyInfo } from "@carbon/viewer";
+import {
+ describeOrientation,
+ IDENTITY_ORIENTATION,
+ resolveOrientations
+} from "@carbon/viewer";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useMemo } from "react";
+import {
+ LuArrowBigDown,
+ LuArrowBigUp,
+ LuFlipVertical2,
+ LuRotateCcw,
+ LuRotateCw
+} from "react-icons/lu";
+import PlaybackRow from "./AssemblyPlaybackRow";
+import type { BuildOrientationControls } from "./useBuildOrientation";
+
+export default function AssemblyOrientationRow({
+ stepId,
+ viewerSteps,
+ subPlan,
+ isDisabled,
+ controls
+}: {
+ stepId: string;
+ viewerSteps: AssemblyStep[];
+ subPlan: Map<string, SubAssemblyInfo>;
+ isDisabled: boolean;
+ controls: BuildOrientationControls;
+}) {
+ const { t } = useLingui();
+
+ const orientation = useMemo(() => {
+ const index = viewerSteps.findIndex((s) => s.id === stepId);
+ return index < 0 ? null : (resolveOrientations(viewerSteps)[index] ?? null);
+ }, [viewerSteps, stepId]);
+ const ownsOrientation = orientation?.sourceStepId === stepId;
+ const orientationSource =
+ orientation?.sourceStepId && !ownsOrientation
+ ? subPlan.get(orientation.sourceStepId)?.number
+ : undefined;
+ const pose = describeOrientation(
+ orientation?.orientation ?? IDENTITY_ORIENTATION
+ );
+ const turnButtons: { turn: BuildTurn; label: string; icon: JSX.Element }[] = [
+ { turn: "flip", label: t`Flip over`, icon: <LuFlipVertical2 /> },
+ { turn: "tipForward", label: t`Tip toward you`, icon: <LuArrowBigDown /> },
+ { turn: "tipBack", label: t`Tip away from you`, icon: <LuArrowBigUp /> },
+ { turn: "spinLeft", label: t`Spin left`, icon: <LuRotateCcw /> },
+ { turn: "spinRight", label: t`Spin right`, icon: <LuRotateCw /> }
+ ];
+
+ return (
+ <div>
+ <PlaybackRow
+ label={
+ <LabelWithHelp termId="assembly-build-orientation" variant="inline">
+ <Trans>Orientation</Trans>
+ </LabelWithHelp>
+ }
+ value={
+ orientationSource && pose !== "upright" ? (
+ pose === "upsideDown" ? (
+ <Trans>Upside down, from step {orientationSource}</Trans>
+ ) : (
+ <Trans>On its side, from step {orientationSource}</Trans>
+ )
+ ) : pose === "upsideDown" ? (
+ <Trans>Upside down</Trans>
+ ) : pose === "onSide" ? (
+ <Trans>On its side</Trans>
+ ) : (
+ <Trans>Upright</Trans>
+ )
+ }
+ >
+ {!isDisabled && ownsOrientation && (
+ <Button
+ variant="ghost"
+ size="sm"
+ isDisabled={controls.isSaving}
+ onClick={() => controls.onReset(stepId)}
+ >
+ <Trans>Reset</Trans>
+ </Button>
+ )}
+ </PlaybackRow>
+ {!isDisabled && (
+ <HStack spacing={1} className="px-2 pb-2">
+ {turnButtons.map(({ turn, label, icon }) => (
+ <Tooltip key={turn}>
+ <TooltipTrigger asChild>
+ <IconButton
+ aria-label={label}
+ icon={icon}
+ variant="ghost"
+ size="sm"
+ isDisabled={controls.isSaving}
+ onClick={() => controls.onTurn(stepId, turn)}
+ />
+ </TooltipTrigger>
+ <TooltipContent>{label}</TooltipContent>
+ </Tooltip>
+ ))}
+ </HStack>
+ )}
+ </div>
+ );
+}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepHiddenComponents.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepHiddenComponents.tsx
new file mode 100644
index 0000000000..51019c5343
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepHiddenComponents.tsx
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import {
+ Badge,
+ Button,
+ cn,
+ HStack,
+ IconButton,
+ LabelWithHelp,
+ Subheading,
+ VStack
+} from "@carbon/react";
+import type { AssemblyGraphIndex } from "@carbon/viewer";
+import { groupComponentNodeIds } from "@carbon/viewer";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useEffect, useMemo, useState } from "react";
+import { LuEyeOff } from "react-icons/lu";
+import { ComponentColorSwatch } from "./AssemblyStepBom";
+
+/** Parts are hidden from the Components panel eye; here they can only be shown again. */
+export default function AssemblyStepHiddenComponents({
+ hiddenNodeIds,
+ graphIndex,
+ isDisabled,
+ onSetHiddenComponents
+}: {
+ hiddenNodeIds: string[];
+ graphIndex: AssemblyGraphIndex | null;
+ isDisabled: boolean;
+ onSetHiddenComponents: (nodeIds: string[]) => void;
+}) {
+ const { t } = useLingui();
+ // "Show all" saves at once but stays undoable for SHOW_ALL_UNDO_MS, so a stray
+ // click can't silently throw away a step's tuned hidden list.
+ const [undoNodeIds, setUndoNodeIds] = useState<string[] | null>(null);
+ useEffect(() => {
+ if (!undoNodeIds) return;
+ const timer = setTimeout(() => setUndoNodeIds(null), SHOW_ALL_UNDO_MS);
+ return () => clearTimeout(timer);
+ }, [undoNodeIds]);
+ const isUndoPending = undoNodeIds !== null;
+ const listedNodeIds = undoNodeIds ?? hiddenNodeIds;
+
+ const groups = useMemo(
+ () => (graphIndex ? groupComponentNodeIds(listedNodeIds, graphIndex) : []),
+ [listedNodeIds, graphIndex]
+ );
+ const onShow = (nodeIds: string[]) => {
+ const show = new Set(nodeIds);
+ onSetHiddenComponents(hiddenNodeIds.filter((nodeId) => !show.has(nodeId)));
+ };
+
+ const onShowAll = () => {
+ setUndoNodeIds(hiddenNodeIds);
+ onSetHiddenComponents([]);
+ };
+
+ // Restore the shown parts, keeping anything hidden elsewhere in the meantime.
+ const onHideAgain = () => {
+ if (!undoNodeIds) return;
+ onSetHiddenComponents([...new Set([...hiddenNodeIds, ...undoNodeIds])]);
+ setUndoNodeIds(null);
+ };
+
+ return (
+ <VStack spacing={2} className="w-full">
+ <HStack className="w-full justify-between">
+ <Subheading as="h4" variant="heavy">
+ <LabelWithHelp
+ termId="assembly-step-hidden-components"
+ variant="inline"
+ >
+ <Trans>Hidden on this step</Trans>
+ </LabelWithHelp>
+ </Subheading>
+ {groups.length === 0 ? (
+ <span className="text-xs text-muted-foreground">
+ <Trans>None</Trans>
+ </span>
+ ) : (
+ !isDisabled &&
+ (isUndoPending ? (
+ <HideAgainButton onClick={onHideAgain} />
+ ) : (
+ <Button variant="secondary" size="sm" onClick={onShowAll}>
+ <Trans>Show All</Trans>
+ </Button>
+ ))
+ )}
+ </HStack>
+ {groups.length === 0 ? null : (
+ <ul className="max-h-64 w-full divide-y divide-border overflow-y-auto rounded-lg border border-border scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
+ {groups.map((group) => (
+ <li
+ key={group.key}
+ className={cn(
+ "flex w-full items-center gap-2 px-2 py-1.5 text-sm",
+ isUndoPending && "opacity-50"
+ )}
+ >
+ <ComponentColorSwatch color={group.color} />
+ <span
+ className="min-w-0 flex-1 truncate text-muted-foreground"
+ title={group.name}
+ >
+ {group.name}
+ </span>
+ {group.count > 1 && (
+ <Badge variant="secondary" className="tabular-nums">
+ ×{group.count}
+ </Badge>
+ )}
+ {!isDisabled && !isUndoPending && (
+ <IconButton
+ aria-label={t`Show ${group.name}`}
+ icon={<LuEyeOff />}
+ variant="ghost"
+ size="sm"
+ className="text-muted-foreground"
+ onClick={() => onShow(group.nodeIds)}
+ />
+ )}
+ </li>
+ ))}
+ </ul>
+ )}
+ </VStack>
+ );
+}
+
+const SHOW_ALL_UNDO_MS = 4000;
+
+function HideAgainButton({ onClick }: { onClick: () => void }) {
+ const [isDraining, setIsDraining] = useState(false);
+ useEffect(() => {
+ // Start full, then drain on the next frame so the width transition runs.
+ const frame = requestAnimationFrame(() => setIsDraining(true));
+ return () => cancelAnimationFrame(frame);
+ }, []);
+
+ return (
+ <Button
+ variant="secondary"
+ size="sm"
+ className="relative overflow-hidden"
+ onClick={onClick}
+ >
+ <span
+ aria-hidden
+ className="pointer-events-none absolute inset-y-0 left-0 bg-primary/15"
+ style={{
+ width: isDraining ? "0%" : "100%",
+ transition: `width ${SHOW_ALL_UNDO_MS}ms linear`
+ }}
+ />
+ <span className="relative">
+ <Trans>Hide Again</Trans>
+ </span>
+ </Button>
+ );
+}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepList.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepList.tsx
index 67b7801aa4..d4577992fa 100644
--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepList.tsx
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepList.tsx
@@ -27,6 +27,7 @@ import type { AssemblyStep, SubAssemblyInfo } from "@carbon/viewer";
import {
buildSubAssemblyPlan,
displayOrder,
+ isPlanFlagged,
subAssemblyPartIds,
validateSubAssemblies
} from "@carbon/viewer";
@@ -79,11 +80,7 @@ import { ProcedureStepTypeIcon } from "~/components/Icons";
import { ConfirmDelete } from "~/components/Modals";
import { usePermissions } from "~/hooks";
import { path } from "~/utils/path";
-import {
- assemblyStepStatuses,
- hasCustomMotion,
- stepPlanWarningsSchema
-} from "../../production.models";
+import { assemblyStepStatuses } from "../../production.models";
import type { AssemblyInstructionStepRow } from "../../types";
import type { AssemblyStepStatusValue } from "./AssemblyStepStatus";
import {
@@ -1002,10 +999,7 @@ function StepRow({
const stepType = step.type ?? "Task";
const needsSupport = (step.warnings as { needsSupport?: boolean } | null)
?.needsSupport;
- // A hand-drawn path overrides the planner's flag.
- const flagged =
- stepPlanWarningsSchema.safeParse(step.warnings).data?.flagged === true &&
- !hasCustomMotion(step.warnings, step.motion);
+ const flagged = isPlanFlagged(step.warnings, step.motion);
const isMember = info.headerId !== null;
const displayTitle = title || t`Untitled step`;
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblySubAssemblyPathRow.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblySubAssemblyPathRow.tsx
index 9441c5a701..824dd9ea50 100644
--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblySubAssemblyPathRow.tsx
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblySubAssemblyPathRow.tsx
@@ -6,10 +6,6 @@ import { Button, HStack, LabelWithHelp } from "@carbon/react";
import { Trans } from "@lingui/react/macro";
import PlaybackRow from "./AssemblyPlaybackRow";
-/**
- * The path a finished sub-assembly travels when it joins the build. Edited in
- * the 3D viewer like a step's motion; Reset returns it to the automatic glide.
- */
export default function SubAssemblyPathRow({
name,
hasPath,
@@ -30,8 +26,7 @@ export default function SubAssemblyPathRow({
return (
<PlaybackRow
label={
- // A long sub-assembly name ends in an ellipsis instead of running
- // under the buttons.
+ // Truncate a long name so it never runs under the buttons.
<LabelWithHelp
termId="assembly-sub-assembly-path"
variant="inline"
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblySubAssemblyProperties.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblySubAssemblyProperties.tsx
index cf35375318..03783274a5 100644
--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblySubAssemblyProperties.tsx
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblySubAssemblyProperties.tsx
@@ -11,7 +11,6 @@ import {
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuTrigger,
- HStack,
Label,
LabelWithHelp,
Subheading,
@@ -19,7 +18,7 @@ import {
} from "@carbon/react";
import { Editor } from "@carbon/react/Editor";
import type { AssemblyStep, SubAssemblyInfo } from "@carbon/viewer";
-import { usableSubAssemblies } from "@carbon/viewer";
+import { isSavedView, usableSubAssemblies } from "@carbon/viewer";
import { Trans, useLingui } from "@lingui/react/macro";
import { useMemo, useState } from "react";
import { LuChevronDown, LuTrash, LuUngroup } from "react-icons/lu";
@@ -29,9 +28,11 @@ import { useImageUpload, usePermissions } from "~/hooks";
import { path } from "~/utils/path";
import { assemblyInstructionStepValidator } from "../../production.models";
import type { AssemblyInstructionStepRow } from "../../types";
+import AssemblyCameraRow from "./AssemblyCameraRow";
import PlaybackRow from "./AssemblyPlaybackRow";
import { SUB_ASSEMBLY_PARAM } from "./AssemblyStepList";
import SubAssemblyPathRow from "./AssemblySubAssemblyPathRow";
+import type { CameraControls, MotionEditing } from "./useStepMotionEditor";
type AssemblySubAssemblyPropertiesProps = {
step: AssemblyInstructionStepRow;
@@ -42,12 +43,8 @@ type AssemblySubAssemblyPropertiesProps = {
isDisabled: boolean;
itemMentions: { id: string; label: string; helper?: string }[];
onSelectStep: (stepId: string) => void;
- onSetCamera: (stepId: string) => void;
- onClearCamera: (stepId: string) => void;
- editingUnitId: string | null;
- onEditMotion: (stepId: string, unitHeaderId?: string) => void;
- onStopEditMotion: () => void;
- onResetMotion: (stepId: string) => void;
+ camera: CameraControls;
+ motionEditing: MotionEditing;
};
/**
@@ -63,12 +60,8 @@ export default function AssemblySubAssemblyProperties({
isDisabled,
itemMentions,
onSelectStep,
- onSetCamera,
- onClearCamera,
- editingUnitId,
- onEditMotion,
- onStopEditMotion,
- onResetMotion
+ camera,
+ motionEditing
}: AssemblySubAssemblyPropertiesProps) {
const { id: instructionId } = useParams();
if (!instructionId) throw new Error("Could not find id");
@@ -145,7 +138,7 @@ export default function AssemblySubAssemblyProperties({
const hasOwnPath =
(viewerSteps.find((viewerStep) => viewerStep.id === step.id)?.motion.type ??
"none") !== "none";
- const hasCamera = step.camera != null;
+ const hasSavedView = isSavedView(step.camera);
const name = step.title || t`Sub-Assembly`;
return (
@@ -298,45 +291,20 @@ export default function AssemblySubAssemblyProperties({
<SubAssemblyPathRow
name={name}
hasPath={hasOwnPath}
- isEditing={editingUnitId === step.id}
+ isEditing={motionEditing.editingUnitId === step.id}
isDisabled={isDisabled}
- onEdit={() => onEditMotion(step.id, step.id)}
- onStopEdit={onStopEditMotion}
- onReset={() => onResetMotion(step.id)}
+ onEdit={() => motionEditing.onEdit(step.id, step.id)}
+ onStopEdit={motionEditing.onStop}
+ onReset={() => motionEditing.onReset(step.id)}
/>
)}
{!usedIn && (
- <PlaybackRow
- label={
- <LabelWithHelp termId="assembly-step-camera" variant="inline">
- <Trans>Camera</Trans>
- </LabelWithHelp>
- }
- value={
- hasCamera ? <Trans>Saved view</Trans> : <Trans>Automatic</Trans>
- }
- >
- {!isDisabled && (
- <HStack spacing={1}>
- {hasCamera && (
- <Button
- variant="ghost"
- size="sm"
- onClick={() => onClearCamera(step.id)}
- >
- <Trans>Clear</Trans>
- </Button>
- )}
- <Button
- variant="secondary"
- size="sm"
- onClick={() => onSetCamera(step.id)}
- >
- <Trans>Use Current View</Trans>
- </Button>
- </HStack>
- )}
- </PlaybackRow>
+ <AssemblyCameraRow
+ stepId={step.id}
+ hasSavedView={hasSavedView}
+ isDisabled={isDisabled}
+ camera={camera}
+ />
)}
</div>
</VStack>
diff --git a/apps/erp/app/modules/production/ui/Assemblies/assembly-step-patch.ts b/apps/erp/app/modules/production/ui/Assemblies/assembly-step-patch.ts
new file mode 100644
index 0000000000..2898c343a0
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/assembly-step-patch.ts
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type { CameraPose, Motion, Quat } from "@carbon/viewer";
+
+/**
+ * Body for `assemblyInstructionStepMotionValidator`: an `undefined` field is not
+ * sent, so the route leaves that column as it is; `null` clears it.
+ */
+export function stepPatchFormData(patch: {
+ motion?: Motion;
+ camera?: CameraPose | null;
+ orientation?: Quat | null;
+ reset?: boolean;
+}): FormData {
+ const formData = new FormData();
+ if (patch.reset) formData.set("reset", "on");
+ if (patch.motion !== undefined) {
+ formData.set("motion", JSON.stringify(patch.motion));
+ }
+ if (patch.camera !== undefined) {
+ formData.set("camera", JSON.stringify(patch.camera));
+ }
+ if (patch.orientation !== undefined) {
+ formData.set("orientation", JSON.stringify(patch.orientation));
+ }
+ return formData;
+}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/useBuildOrientation.ts b/apps/erp/app/modules/production/ui/Assemblies/useBuildOrientation.ts
new file mode 100644
index 0000000000..dc80eeb448
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/useBuildOrientation.ts
@@ -0,0 +1,127 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { toast } from "@carbon/react";
+import type {
+ AssemblyPlayerHandle,
+ AssemblyStep,
+ BuildTurn,
+ CameraPose,
+ Quat
+} from "@carbon/viewer";
+import {
+ isOrientation,
+ isSavedView,
+ resolveOrientations,
+ sameOrientation,
+ turnOrientation
+} from "@carbon/viewer";
+import { useLingui } from "@lingui/react/macro";
+import type { RefObject } from "react";
+import { useCallback, useMemo } from "react";
+import { useFetcher } from "react-router";
+import { path } from "~/utils/path";
+import { stepPatchFormData } from "./assembly-step-patch";
+
+export type BuildOrientationControls = {
+ /** Turns the build on a step, as seen from the current view */
+ onTurn: (stepId: string, turn: BuildTurn) => void;
+ /** The step keeps the previous step's build orientation again */
+ onReset: (stepId: string) => void;
+ isSaving: boolean;
+};
+
+/**
+ * Saves a step's build orientation on its own fetcher. While a save is in
+ * flight, the returned `viewerSteps` carry the orientation being saved, so the
+ * viewer and the panel show it before the loader catches up.
+ */
+export function useBuildOrientation({
+ id,
+ steps,
+ playerRef
+}: {
+ id: string;
+ steps: AssemblyStep[];
+ playerRef: RefObject<AssemblyPlayerHandle>;
+}) {
+ const { t } = useLingui();
+ const fetcher = useFetcher<{ success: boolean }>();
+
+ const pending = useMemo(() => {
+ const formData = fetcher.formData;
+ const stepId = formData?.get("stepId");
+ const raw = formData?.get("orientation");
+ if (typeof stepId !== "string" || typeof raw !== "string") return null;
+ const parsed: unknown = JSON.parse(raw);
+ return { stepId, orientation: isOrientation(parsed) ? parsed : null };
+ }, [fetcher.formData]);
+
+ const viewerSteps = useMemo(
+ () =>
+ pending
+ ? steps.map((step) =>
+ step.id === pending.stepId
+ ? { ...step, orientation: pending.orientation }
+ : step
+ )
+ : steps,
+ [steps, pending]
+ );
+
+ const save = useCallback(
+ (stepId: string, orientation: Quat | null, camera?: CameraPose) => {
+ const formData = stepPatchFormData({ orientation, camera });
+ // Read back by `pending` above; the route ignores it.
+ formData.set("stepId", stepId);
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.assemblyInstructionStepMotion(id, stepId)
+ });
+ },
+ [fetcher, id]
+ );
+
+ // A turn back onto the inherited orientation saves `null`. A turned step with
+ // no saved view (a plan hint doesn't count) also pins the current view, since
+ // the camera holds still while the build turns; a saved view is never replaced.
+ const onTurn = useCallback(
+ (stepId: string, turn: BuildTurn) => {
+ const pose = playerRef.current?.captureCameraPose();
+ if (!pose) {
+ toast.error(t`The model isn't ready yet`);
+ return;
+ }
+ const index = viewerSteps.findIndex((step) => step.id === stepId);
+ if (index < 0) return;
+ const current = resolveOrientations(viewerSteps)[index];
+ if (!current) return;
+ const next = turnOrientation(current.orientation, turn, pose);
+ const inherited = resolveOrientations(
+ viewerSteps.map((step) =>
+ step.id === stepId ? { ...step, orientation: null } : step
+ )
+ )[index];
+ const orientation =
+ inherited && sameOrientation(next, inherited.orientation) ? null : next;
+ const hasSavedView = isSavedView(viewerSteps[index]?.camera);
+ save(
+ stepId,
+ orientation,
+ orientation && !hasSavedView ? pose : undefined
+ );
+ },
+ [playerRef, viewerSteps, save, t]
+ );
+
+ const onReset = useCallback((stepId: string) => save(stepId, null), [save]);
+
+ const isSaving = fetcher.state !== "idle";
+ const orientation = useMemo<BuildOrientationControls>(
+ () => ({ onTurn, onReset, isSaving }),
+ [onTurn, onReset, isSaving]
+ );
+
+ return { viewerSteps, orientation };
+}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/useStepMotionEditor.ts b/apps/erp/app/modules/production/ui/Assemblies/useStepMotionEditor.ts
new file mode 100644
index 0000000000..52269eae39
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/useStepMotionEditor.ts
@@ -0,0 +1,201 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { toast } from "@carbon/react";
+import type {
+ AssemblyPlayerHandle,
+ AssemblyStep,
+ CameraPose,
+ Motion
+} from "@carbon/viewer";
+import { subAssemblyPartIds } from "@carbon/viewer";
+import { useLingui } from "@lingui/react/macro";
+import type { RefObject } from "react";
+import { useCallback, useMemo, useRef, useState } from "react";
+import { useSubmit } from "react-router";
+import { path } from "~/utils/path";
+import { stepPatchFormData } from "./assembly-step-patch";
+
+export type MotionEditing = {
+ /** The selected step's own motion path is open in the 3D editor */
+ isEditingStep: boolean;
+ /** The sub-assembly whose joining path is open in the 3D editor, if any */
+ editingUnitId: string | null;
+ /** Opens the editor on a step's motion, or on a sub-assembly it carries in */
+ onEdit: (stepId: string, unitHeaderId?: string) => void;
+ onStop: () => void;
+ /** Puts back the motion a step or sub-assembly had before its path was drawn */
+ onReset: (stepId: string) => void;
+};
+
+/** The Camera row's actions: pin the current view, or return to automatic. */
+export type CameraControls = {
+ onSet: (stepId: string) => void;
+ onClear: (stepId: string) => void;
+};
+
+/**
+ * The 3D viewer edits the selected step's motion path (drag waypoints) and
+ * captures its camera; both autosave through the step-motion route so they
+ * never round-trip the whole step form. `editMotion` is the controlled value
+ * the player renders while editing.
+ */
+export function useStepMotionEditor({
+ id,
+ viewerSteps,
+ playerRef,
+ selectedStepId,
+ setSelectedStepId
+}: {
+ id: string;
+ viewerSteps: AssemblyStep[];
+ playerRef: RefObject<AssemblyPlayerHandle>;
+ selectedStepId: string | null;
+ setSelectedStepId: (stepId: string) => void;
+}) {
+ const { t } = useLingui();
+ const submit = useSubmit();
+ const [editingStepId, setEditingStepId] = useState<string | null>(null);
+ // A sub-assembly header whose joining path is edited instead of the step's own.
+ const [editingUnitId, setEditingUnitId] = useState<string | null>(null);
+ const [draftMotion, setDraftMotion] = useState<Motion | null>(null);
+ const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const pendingMotion = useRef<{ targetId: string; motion: Motion } | null>(
+ null
+ );
+
+ const saveMotion = useCallback(
+ (
+ stepId: string,
+ body: { motion?: Motion; camera?: CameraPose | null; reset?: boolean }
+ ) => {
+ // One fetcher per row and column: a new submit on a fetcher aborts the
+ // one in flight, so a shared fetcher let a Reset or Set view cancel a
+ // drag save on another row. A newer save of the same column still
+ // replaces an older one (Reset writes `motion` too).
+ const column = body.camera !== undefined ? "camera" : "motion";
+ submit(stepPatchFormData(body), {
+ method: "post",
+ action: path.to.assemblyInstructionStepMotion(id, stepId),
+ navigate: false,
+ fetcherKey: `assembly-step-${column}-${stepId}`
+ });
+ },
+ [submit, id]
+ );
+
+ // The drag autosave waits 400 ms; leaving or switching an edit sends it now.
+ const flushMotionSave = useCallback(() => {
+ if (saveTimer.current) clearTimeout(saveTimer.current);
+ saveTimer.current = null;
+ const pending = pendingMotion.current;
+ pendingMotion.current = null;
+ if (pending) saveMotion(pending.targetId, { motion: pending.motion });
+ }, [saveMotion]);
+
+ // Selecting another step leaves the edit session; a drag still waiting to
+ // save is sent by its timer.
+ const leaveEdit = useCallback(() => {
+ setEditingStepId(null);
+ setEditingUnitId(null);
+ setDraftMotion(null);
+ }, []);
+
+ const onEdit = useCallback(
+ (stepId: string, unitHeaderId?: string) => {
+ flushMotionSave();
+ const edited = viewerSteps.find((s) => s.id === (unitHeaderId ?? stepId));
+ setSelectedStepId(stepId);
+ setEditingStepId(stepId);
+ setEditingUnitId(unitHeaderId ?? null);
+ setDraftMotion(edited?.motion ?? { type: "none" });
+ },
+ [viewerSteps, flushMotionSave, setSelectedStepId]
+ );
+
+ const onStop = useCallback(() => {
+ flushMotionSave();
+ leaveEdit();
+ }, [flushMotionSave, leaveEdit]);
+
+ const onMotionChange = useCallback(
+ (stepId: string, motion: Motion) => {
+ setDraftMotion(motion);
+ // A sub-assembly's path lives on its header row.
+ pendingMotion.current = { targetId: editingUnitId ?? stepId, motion };
+ if (saveTimer.current) clearTimeout(saveTimer.current);
+ saveTimer.current = setTimeout(flushMotionSave, 400);
+ },
+ [flushMotionSave, editingUnitId]
+ );
+
+ const onReset = useCallback(
+ (stepId: string) => {
+ // A drag still waiting to save on this row must not land after the reset.
+ if (pendingMotion.current?.targetId === stepId) {
+ if (saveTimer.current) clearTimeout(saveTimer.current);
+ saveTimer.current = null;
+ pendingMotion.current = null;
+ } else {
+ flushMotionSave();
+ }
+ saveMotion(stepId, { reset: true });
+ },
+ [saveMotion, flushMotionSave]
+ );
+
+ const onSetCamera = useCallback(
+ (stepId: string) => {
+ const pose = playerRef.current?.captureCameraPose();
+ if (!pose) {
+ toast.error(t`The model isn't ready yet`);
+ return;
+ }
+ saveMotion(stepId, { camera: pose });
+ },
+ [playerRef, saveMotion, t]
+ );
+
+ const onClearCamera = useCallback(
+ (stepId: string) => saveMotion(stepId, { camera: null }),
+ [saveMotion]
+ );
+
+ const isEditingSelected =
+ editingStepId !== null && selectedStepId === editingStepId;
+ const editingUnitPartIds = useMemo(
+ () =>
+ editingUnitId ? subAssemblyPartIds(viewerSteps, editingUnitId) : null,
+ [editingUnitId, viewerSteps]
+ );
+
+ const editMotion =
+ editingStepId && isEditingSelected && draftMotion
+ ? {
+ stepId: editingStepId,
+ motion: draftMotion,
+ ...(editingUnitPartIds ? { nodeIds: editingUnitPartIds } : {})
+ }
+ : null;
+
+ // Memoized: the panel is memoized and must not re-render on every drag frame.
+ const isEditingStep = isEditingSelected && editingUnitId === null;
+ const selectedUnitId = isEditingSelected ? editingUnitId : null;
+ const motionEditing = useMemo<MotionEditing>(
+ () => ({
+ isEditingStep,
+ editingUnitId: selectedUnitId,
+ onEdit,
+ onStop,
+ onReset
+ }),
+ [isEditingStep, selectedUnitId, onEdit, onStop, onReset]
+ );
+ const camera = useMemo<CameraControls>(
+ () => ({ onSet: onSetCamera, onClear: onClearCamera }),
+ [onSetCamera, onClearCamera]
+ );
+
+ return { editMotion, onMotionChange, leaveEdit, motionEditing, camera };
+}
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 6154f87ea3..22ca5d7a3d 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -663,7 +663,7 @@
{"name":"production_getAssemblyInstructions","classification":"READ","paramCount":5,"schema":"902de08eaf06","response":"845b5a451089","injectAuth":"companyId","permission":"production:view","paginates":true},
{"name":"production_getAssemblyInstructionsForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"c881f4ef7d23","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getAssemblyInstructionStepMaterials","classification":"READ","paramCount":1,"schema":"0f56299d6859","response":"89a5f52bebf8","injectAuth":"companyId","permission":"production:view","paginates":false},
- {"name":"production_getAssemblyInstructionSteps","classification":"READ","paramCount":1,"schema":"f9ddf194f67e","response":"5d620778dd6f","injectAuth":"companyId","permission":"production:view","paginates":false},
+ {"name":"production_getAssemblyInstructionSteps","classification":"READ","paramCount":1,"schema":"f9ddf194f67e","response":"65fd94da8279","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getAssemblyInstructionStepSlides","classification":"READ","paramCount":1,"schema":"0f56299d6859","response":"60aa9b57a118","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getAssemblyInstructionStepTools","classification":"READ","paramCount":1,"schema":"0f56299d6859","response":"d771814f7578","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getAssemblyInstructionVersions","classification":"READ","paramCount":2,"schema":"0c21424ecd86","response":"81c6e04c54bd","injectAuth":"companyId","permission":"production:view","paginates":false},
@@ -791,7 +791,7 @@
{"name":"production_setPeopleOvertimeBulk","classification":"WRITE","paramCount":6,"schema":"8f082483561d","response":"577d7088b794","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_syncAssemblyInstructionToOperation","classification":"DESTRUCTIVE","paramCount":2,"schema":"8160f8d92b1b","response":"4348d3bad80b","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},
{"name":"production_syncAssemblyStepMaterialsFromMappings","classification":"WRITE","paramCount":4,"schema":"7f7346bb3bd0","response":"5815c4dbf43d","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},
- {"name":"production_toViewerStep","classification":"WRITE","paramCount":1,"schema":"79b0e8edd0b6","response":"a15b53344e15","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_toViewerStep","classification":"WRITE","paramCount":1,"schema":"29ac1466e693","response":"af67df1e83ed","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_unassignPeopleWeek","classification":"DESTRUCTIVE","paramCount":4,"schema":"06ead5d3d9ce","response":"9658926b2cd2","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_ungroupAssemblySubAssembly","classification":"DESTRUCTIVE","paramCount":2,"schema":"4bb5885b787b","response":"none","injectAuth":"companyId+userId","permission":"production:update","paginates":false},
{"name":"production_unreleaseJobOperationBatch","classification":"WRITE","paramCount":1,"schema":"979f64cb9229","response":"9e056a59d695","injectAuth":"companyId+userId","permission":"production:update","paginates":false},
@@ -801,7 +801,7 @@
{"name":"production_updateAssemblyInstructionStepStatus","classification":"WRITE","paramCount":2,"schema":"9291eed55a4a","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_updateAssemblyStepComponents","classification":"WRITE","paramCount":2,"schema":"d7ea6b1800f7","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_updateAssemblyStepHiddenComponents","classification":"WRITE","paramCount":3,"schema":"3ac4e88c4df0","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
- {"name":"production_updateAssemblyStepMotion","classification":"WRITE","paramCount":4,"schema":"6c3d7338c096","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
+ {"name":"production_updateAssemblyStepMotion","classification":"WRITE","paramCount":5,"schema":"aa7dfb67132e","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_updateAssemblySubAssembly","classification":"WRITE","paramCount":4,"schema":"0f0cbf9e32e1","response":"none","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},
{"name":"production_updateJob","classification":"WRITE","paramCount":22,"schema":"fc37d97579b2","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_updateJobBatchNumber","classification":"WRITE","paramCount":2,"schema":"a4c2a31bb8a6","response":"f7a40899c090","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
diff --git a/apps/erp/app/routes/x+/assembly+/$id.steps.motion.$stepId.tsx b/apps/erp/app/routes/x+/assembly+/$id.steps.motion.$stepId.tsx
index c263314e06..fbad79ace8 100644
--- a/apps/erp/app/routes/x+/assembly+/$id.steps.motion.$stepId.tsx
+++ b/apps/erp/app/routes/x+/assembly+/$id.steps.motion.$stepId.tsx
@@ -16,12 +16,13 @@ import {
logAssemblyStep,
readAndLogFormData
} from "~/modules/production/assembly-debug.server";
+import { getDatabaseClient } from "~/services/database.server";
-// Autosave target for the 3D motion-path editor: patches only motion/camera on
-// a step (drag autosave + "Set view"/"Clear view"), leaving the rest untouched.
+// Autosave target for the 3D editor: patches only a step's motion, camera and
+// orientation, leaving the rest untouched.
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
update: "production"
});
@@ -44,10 +45,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- const update = await updateAssemblyStepMotion(client, {
+ const update = await updateAssemblyStepMotion(getDatabaseClient(), {
id: stepId,
motion: validation.data.motion,
camera: validation.data.camera,
+ orientation: validation.data.orientation,
reset: validation.data.reset,
companyId,
updatedBy: userId
@@ -56,6 +58,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
stepId,
motion: validation.data.motion,
hasCamera: validation.data.camera !== undefined,
+ hasOrientation: validation.data.orientation !== undefined,
error: update.error?.message ?? null,
updatedId: update.data?.id ?? null
});
diff --git a/apps/erp/app/routes/x+/assembly+/$id.tsx b/apps/erp/app/routes/x+/assembly+/$id.tsx
index 86723b6000..852fa36798 100644
--- a/apps/erp/app/routes/x+/assembly+/$id.tsx
+++ b/apps/erp/app/routes/x+/assembly+/$id.tsx
@@ -11,17 +11,11 @@ import {
Button,
ClientOnly,
Spinner,
- toast,
useInterval,
useMode
} from "@carbon/react";
import { redirect } from "@carbon/utils";
-import type {
- AssemblyGraph,
- AssemblyPlayerHandle,
- CameraPose,
- Motion
-} from "@carbon/viewer";
+import type { AssemblyGraph, AssemblyPlayerHandle } from "@carbon/viewer";
import {
AssemblyPlayer,
buildSubAssemblyPlan,
@@ -65,6 +59,8 @@ import AssemblyInstructionHeader from "~/modules/production/ui/Assemblies/Assemb
import AssemblyInstructionProperties from "~/modules/production/ui/Assemblies/AssemblyInstructionProperties";
import { SUB_ASSEMBLY_PARAM } from "~/modules/production/ui/Assemblies/AssemblyStepList";
import { ModelConvertProgress } from "~/modules/production/ui/Assemblies/ModelConvertProgress";
+import { useBuildOrientation } from "~/modules/production/ui/Assemblies/useBuildOrientation";
+import { useStepMotionEditor } from "~/modules/production/ui/Assemblies/useStepMotionEditor";
import { detailBreadcrumb, type Handle } from "~/utils/handle";
import { getPrivateUrl, path } from "~/utils/path";
@@ -319,7 +315,7 @@ export default function AssemblyInstructionRoute() {
}, [hiddenFetcher.state, hiddenFetcher.data]);
// The selected step shows its hidden draft before the autosave round-trips.
- const viewerSteps = useMemo(
+ const savedViewerSteps = useMemo(
() =>
steps.map((step) => {
const viewerStep = toViewerStep(step);
@@ -330,6 +326,21 @@ export default function AssemblyInstructionRoute() {
[steps, draftHiddenNodeIds, selectedStep]
);
+ const playerRef = useRef<AssemblyPlayerHandle>(null);
+ const { viewerSteps, orientation } = useBuildOrientation({
+ id,
+ steps: savedViewerSteps,
+ playerRef
+ });
+ const { editMotion, onMotionChange, leaveEdit, motionEditing, camera } =
+ useStepMotionEditor({
+ id,
+ viewerSteps,
+ playerRef,
+ selectedStepId: selectedStep?.id ?? null,
+ setSelectedStepId
+ });
+
const subPlan = useMemo(
() => buildSubAssemblyPlan(viewerSteps),
[viewerSteps]
@@ -447,10 +458,7 @@ export default function AssemblyInstructionRoute() {
setDraftComponentNodeIds(null);
setDraftHiddenNodeIds(null);
setIsAddingComponents(false);
- // Leave any open motion-path edit session when moving to another step.
- setEditingStepId(null);
- setEditingUnitId(null);
- setDraftMotion(null);
+ leaveEdit();
// Changing steps drops any isolate — the new step's parts should be visible.
setFocusedNodeIds([]);
// Selecting a step makes its components the active selection — red in the
@@ -464,7 +472,7 @@ export default function AssemblyInstructionRoute() {
setSelectedNodeIds(step.componentNodeIds ?? []);
}
},
- []
+ [leaveEdit]
);
// Opening a sub-assembly lands on its first step (the player only plays its
@@ -615,124 +623,6 @@ export default function AssemblyInstructionRoute() {
const cancelPlanFetcher = useFetcher<{ success: boolean }>();
const retryFetcher = useFetcher<{}>();
- // --- Motion path + camera editing (viewer-driven) ------------------------
- // The 3D viewer edits the active step's motion path (drag waypoints) and
- // captures its camera; both autosave via a dedicated partial-update route so
- // they never round-trip the whole step form. `draftMotion` is the controlled
- // value the viewer renders while editing.
- const playerRef = useRef<AssemblyPlayerHandle>(null);
- const motionFetcher = useFetcher<{ success: boolean }>();
- const [editingStepId, setEditingStepId] = useState<string | null>(null);
- // Editing the path of a sub-assembly the step carries in (saved on its
- // header row) instead of the step's own motion.
- const [editingUnitId, setEditingUnitId] = useState<string | null>(null);
- const [draftMotion, setDraftMotion] = useState<Motion | null>(null);
- const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
- const pendingMotion = useRef<{ targetId: string; motion: Motion } | null>(
- null
- );
-
- const saveMotion = useCallback(
- (
- stepId: string,
- body: { motion?: Motion; camera?: CameraPose | null; reset?: boolean }
- ) => {
- const formData = new FormData();
- if (body.reset) formData.set("reset", "on");
- if (body.motion !== undefined) {
- formData.set("motion", JSON.stringify(body.motion));
- }
- if (body.camera !== undefined) {
- formData.set("camera", JSON.stringify(body.camera));
- }
- motionFetcher.submit(formData, {
- method: "post",
- action: path.to.assemblyInstructionStepMotion(id, stepId)
- });
- },
- [motionFetcher, id]
- );
-
- // The drag autosave waits 400 ms; leaving or switching an edit sends it now.
- const flushMotionSave = useCallback(() => {
- if (saveTimer.current) clearTimeout(saveTimer.current);
- saveTimer.current = null;
- const pending = pendingMotion.current;
- pendingMotion.current = null;
- if (pending) saveMotion(pending.targetId, { motion: pending.motion });
- }, [saveMotion]);
-
- const onEditMotion = useCallback(
- (stepId: string, unitHeaderId?: string) => {
- flushMotionSave();
- const edited = viewerSteps.find((s) => s.id === (unitHeaderId ?? stepId));
- setSelectedStepId(stepId);
- setEditingStepId(stepId);
- setEditingUnitId(unitHeaderId ?? null);
- setDraftMotion(edited?.motion ?? { type: "none" });
- },
- [viewerSteps, flushMotionSave]
- );
-
- const onStopEditMotion = useCallback(() => {
- flushMotionSave();
- setEditingStepId(null);
- setEditingUnitId(null);
- setDraftMotion(null);
- }, [flushMotionSave]);
-
- const onMotionChange = useCallback(
- (stepId: string, motion: Motion) => {
- setDraftMotion(motion);
- // A sub-assembly's path lives on its header row.
- pendingMotion.current = { targetId: editingUnitId ?? stepId, motion };
- if (saveTimer.current) clearTimeout(saveTimer.current);
- saveTimer.current = setTimeout(flushMotionSave, 400);
- },
- [flushMotionSave, editingUnitId]
- );
-
- const onResetMotion = useCallback(
- (stepId: string) => {
- // A drag still waiting to save on this row must not land after the reset.
- if (pendingMotion.current?.targetId === stepId) {
- if (saveTimer.current) clearTimeout(saveTimer.current);
- saveTimer.current = null;
- pendingMotion.current = null;
- } else {
- flushMotionSave();
- }
- saveMotion(stepId, { reset: true });
- },
- [saveMotion, flushMotionSave]
- );
-
- const onSetCamera = useCallback(
- (stepId: string) => {
- const pose = playerRef.current?.captureCameraPose();
- if (!pose) {
- toast.error("The model isn't ready yet");
- return;
- }
- saveMotion(stepId, { camera: pose });
- },
- [saveMotion]
- );
-
- const onClearCamera = useCallback(
- (stepId: string) => saveMotion(stepId, { camera: null }),
- [saveMotion]
- );
-
- const isEditingSelected =
- editingStepId !== null && selectedStep?.id === editingStepId;
- const isEditingSelectedMotion = isEditingSelected && editingUnitId === null;
- const editingUnitPartIds = useMemo(
- () =>
- editingUnitId ? subAssemblyPartIds(viewerSteps, editingUnitId) : null,
- [editingUnitId, viewerSteps]
- );
-
return (
<PanelProvider key={id}>
<div className="flex flex-col h-[calc(100dvh-var(--topbar-height)-var(--content-inset))] overflow-hidden w-full">
@@ -821,17 +711,7 @@ export default function AssemblyInstructionRoute() {
highlightedNodeIds={selectedNodeIds}
focusedNodeIds={focusedNodeIds}
readOnly={isDisabled}
- editMotion={
- editingStepId && isEditingSelected && draftMotion
- ? {
- stepId: editingStepId,
- motion: draftMotion,
- ...(editingUnitPartIds
- ? { nodeIds: editingUnitPartIds }
- : {})
- }
- : null
- }
+ editMotion={editMotion}
onMotionChange={onMotionChange}
units={namedUnits}
suppressFallbackMotions={isPlanning}
@@ -903,13 +783,9 @@ export default function AssemblyInstructionRoute() {
onRemoveComponents={onRemoveComponents}
hiddenNodeIds={selectedHiddenNodeIds}
onSetHiddenComponents={onSetHiddenComponents}
- isEditingMotion={isEditingSelectedMotion}
- editingUnitId={isEditingSelected ? editingUnitId : null}
- onEditMotion={onEditMotion}
- onStopEditMotion={onStopEditMotion}
- onResetMotion={onResetMotion}
- onSetCamera={onSetCamera}
- onClearCamera={onClearCamera}
+ motionEditing={motionEditing}
+ camera={camera}
+ orientation={orientation}
stepMaterials={selectedStepMaterials}
stepSlides={selectedStepSlides}
stepTools={selectedStepTools}
diff --git a/apps/mes/app/components/AssemblyView.tsx b/apps/mes/app/components/AssemblyView.tsx
index 8b91e299cf..51eb6ef49b 100644
--- a/apps/mes/app/components/AssemblyView.tsx
+++ b/apps/mes/app/components/AssemblyView.tsx
@@ -52,6 +52,8 @@ import type { AssemblyStep, CameraPose, Fastener } from "@carbon/viewer";
import {
AssemblyPlayer,
buildSubAssemblyPlan,
+ isOrientation,
+ isPlanFlagged,
isPlayableMotion
} from "@carbon/viewer";
import { ModelPreview } from "@carbon/viewer/model-preview";
@@ -208,6 +210,8 @@ type AssemblyPlayback = {
isSubAssembly: boolean;
motion: Json;
camera: Json | null;
+ /** The build's orientation from this step on (unit quaternion) */
+ orientation: Json | null;
fastener: Json | null;
durationSeconds: number | null;
warnings: Json | null;
@@ -219,7 +223,6 @@ const SUB_ASSEMBLY_PARAM = "subAssembly";
// DB row → @carbon/viewer AssemblyStep.
function toViewerStep(step: AssemblyPlayback["steps"][number]): AssemblyStep {
- const warnings = step.warnings as { flagged?: boolean } | null;
return {
id: step.id,
title: step.title,
@@ -231,9 +234,11 @@ function toViewerStep(step: AssemblyPlayback["steps"][number]): AssemblyStep {
isSubAssembly: step.isSubAssembly,
motion: isPlayableMotion(step.motion) ? step.motion : { type: "none" },
camera: (step.camera as CameraPose | null) ?? null,
+ orientation: isOrientation(step.orientation) ? step.orientation : null,
fastener: (step.fastener as Fastener | null) ?? null,
durationSeconds: step.durationSeconds,
- flagged: warnings?.flagged === true ? true : undefined
+ // A hand-drawn path overrides the planner's flag, as in the ERP editor.
+ flagged: isPlanFlagged(step.warnings, step.motion) ? true : undefined
};
}
diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.ts
index d363ee2f42..7916d18fc1 100644
--- a/apps/mes/app/services/operations.service.ts
+++ b/apps/mes/app/services/operations.service.ts
@@ -661,7 +661,7 @@ export async function getAssemblyPlaybackByOperationId(
const steps = await client
.from("assemblyInstructionStep")
.select(
- "id, title, instructionText, componentNodeIds, hiddenComponentNodeIds, parentStepId, usedInStepId, isSubAssembly, motion, camera, fastener, durationSeconds, warnings"
+ "id, title, instructionText, componentNodeIds, hiddenComponentNodeIds, parentStepId, usedInStepId, isSubAssembly, motion, camera, orientation, fastener, durationSeconds, warnings"
)
.eq("assemblyInstructionId", instructionId)
.order("sortOrder", { ascending: true });
diff --git a/docs/content/docs/reference/assembly-instructions.mdx b/docs/content/docs/reference/assembly-instructions.mdx
index 8e5927576d..38cf371b75 100644
--- a/docs/content/docs/reference/assembly-instructions.mdx
+++ b/docs/content/docs/reference/assembly-instructions.mdx
@@ -64,7 +64,8 @@ The **Playback** box sets how the step plays:
<FieldTable>
<Field name="Motion">"Automatic" uses the path the planner found; "Custom path" means you drew it, and **"Reset"** puts the planner's path back. A drawn path also replaces "No clear path". **"Edit Path"** shows the path as red waypoints in the 3D view: drag one to reshape it, double-click the path to add one, and press Delete to remove the selected one. A see-through copy of the parts shows the selected waypoint's pose. Switch the viewer's **Move / Rotate** control to **Rotate** to get rotation rings on the selected waypoint: drag a ring to turn the part at that point (it snaps every 15°), so a part can be flipped on its way in. Switch back to **Move** to drag waypoints again. "No clear path" means the planner found none; hover the header note to see which parts block it.</Field>
- <Field name="Camera">"Automatic" frames the step's parts on its own. **"Use Current View"** saves the angle you are looking from; **"Clear"** goes back to automatic.</Field>
+ <Field name="Camera">"Automatic" frames the step's parts on its own; while the build is upright, a generated step looks from the angle the planner chose. **"Use Current View"** saves the angle you are looking from, and the row reads "Saved view"; **"Clear"** goes back to automatic. Clear shows only on a saved view.</Field>
+ <Field name="Orientation">Turns the whole build for this step, for example to flip it and fit parts on its underside. **"Flip over"** turns it upside down; **"Tip toward you"** and **"Tip away from you"** lay it on its side; **"Spin left"** and **"Spin right"** turn it on the bench. Flip over is a half turn and the others are quarter turns, each measured from the angle you are looking at. The view stays where it is while the build turns. If the step has no saved view, a turn that leaves the build turned also saves the view you are looking from, so the Camera row reads "Saved view" and playback shows the step from that angle; turning the build back keeps that view, and **"Clear"** on the Camera row returns it to automatic. The row says how the build sits ("Upright", "Upside down", "On its side"). Later steps of the same build keep it ("Upside down, from step 11") until a step turns it again, and playback turns the build over before that step's parts go in. A sub-assembly starts upright and keeps its own orientation. **"Reset"** gives the step the orientation of the step before it.</Field>
<Field name="Sub-assembly path">One row per sub-assembly the step fits. "Automatic" slides the finished unit in from beside the build. **"Edit Path"** draws the path the whole unit travels, with the same waypoints and rotation rings; **"Reset"** goes back to automatic.</Field>
</FieldTable>
@@ -121,6 +122,7 @@ On the shop floor the operation opens the [guided assembly view](/docs/reference
- Step status DB meaning: Todo = new manual step, Review = planner-generated, Done = author-validated. New steps default to Todo with `planConfidence` "manual".
- Sub-assemblies: a header row has `assemblyInstructionStep.isSubAssembly`; its steps have `parentStepId` = the header and are stored directly before it in `sortOrder`; the header's `usedInStepId` is the step that fits it (NULL = joins the main build at the header). Rules shared by ERP, the server, and playback: `validateSubAssemblies` in `packages/viewer/src/subassembly.ts`. Header rows are never copied to job steps. The header's `motion` is the unit's own path (`none` = glide in over 1.2 s, then ride the using step's motion); units with a path play one after another before the step's own parts. Paths drawn with a turned waypoint save as the relative `waypoints` motion type (poses turn about the moving set's seated bounds center); unturned paths still save as `linear`/`L`. The open sub-assembly is the `?subAssembly=` URL parameter.
- Hidden parts: `assemblyInstructionStep.hiddenComponentNodeIds`; a DB trigger strips the step's own components on every write.
+- Orientation: `assemblyInstructionStep.orientation` is a unit quaternion (model frame to bench frame); NULL = the previous step of the same build. Turns post to the step-motion route (`$id.steps.motion.$stepId.tsx`). A turn that lands on the inherited orientation saves NULL. The same post saves the current view as `camera` only when the step ends up turned and has no manual view (a planner `{ source: "plan" }` hint does not count).
- Flash strings: "Step not found"; "Sub-assembly not found"; "This step is already a sub-assembly"; "This step is already in a sub-assembly"; "A sub-assembly can't be inside another sub-assembly"; "A sub-assembly's steps must come directly before it"; "A sub-assembly can only be used after it is built"; "A sub-assembly can't be used by one of its own steps"; "Only draft instructions can be edited"; "Failed to update hidden components"; "Failed to update step status"; "Failed to update assembly instruction step"; "Steps already exist — delete them before generating from the plan"; "Some steps are locked — cannot regenerate"; "The geometry service is unavailable — motion planning can't run right now."; "Motion planning is already running"; "This instruction has no processed model"; "The model must finish converting before planning"; "This job is locked — steps can't be synced to it"; "The selected item has no 3D model. Upload a STEP file on the item's Model tab first."; "Made assembly instruction active"; "Failed to make assembly instruction active".
- Planner offline: "The geometry service is offline — motion planning is unavailable right now." Generate is disabled until it is back.
</AgentContext>
diff --git a/docs/content/src/glossary/terms.ts b/docs/content/src/glossary/terms.ts
index 136fe57840..1af4f9cb13 100644
--- a/docs/content/src/glossary/terms.ts
+++ b/docs/content/src/glossary/terms.ts
@@ -110,6 +110,11 @@ export const terms = {
definition: msg`The view a step plays from; without a saved view the step frames its own components.`,
href: "/docs/reference/assembly-instructions#playback-settings"
},
+ "assembly-build-orientation": {
+ term: msg`Orientation`,
+ definition: msg`How the whole build is turned on a step, such as flipped to fit parts on its underside. Later steps of the same build keep it until a step turns the build again.`,
+ href: "/docs/reference/assembly-instructions#playback-settings"
+ },
"assembly-sub-assembly": {
term: msg`Sub-assembly`,
definition: msg`Steps built on their own, then fitted as one piece: in the step that uses it, or, when nothing uses it, right after its own steps.`,
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 59290fbbe8..950fd1d5c5 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -58071,6 +58071,9 @@ export default {
{
$ref: "#/parameters/rowFilter.assemblyInstructionStep.isSubAssembly"
},
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStep.orientation"
+ },
{
$ref: "#/parameters/select"
},
@@ -58232,6 +58235,9 @@ export default {
{
$ref: "#/parameters/rowFilter.assemblyInstructionStep.isSubAssembly"
},
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStep.orientation"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -58347,6 +58353,9 @@ export default {
{
$ref: "#/parameters/rowFilter.assemblyInstructionStep.isSubAssembly"
},
+ {
+ $ref: "#/parameters/rowFilter.assemblyInstructionStep.orientation"
+ },
{
$ref: "#/parameters/body.assemblyInstructionStep"
},
@@ -62331,6 +62340,12 @@ export default {
{
$ref: "#/parameters/rowFilter.shipmentFixedAssetLine.updatedBy"
},
+ {
+ $ref: "#/parameters/rowFilter.shipmentFixedAssetLine.rentalAgreementLineId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.shipmentFixedAssetLine.meter"
+ },
{
$ref: "#/parameters/select"
},
@@ -62420,6 +62435,12 @@ export default {
{
$ref: "#/parameters/rowFilter.shipmentFixedAssetLine.updatedBy"
},
+ {
+ $ref: "#/parameters/rowFilter.shipmentFixedAssetLine.rentalAgreementLineId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.shipmentFixedAssetLine.meter"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -62463,6 +62484,12 @@ export default {
{
$ref: "#/parameters/rowFilter.shipmentFixedAssetLine.updatedBy"
},
+ {
+ $ref: "#/parameters/rowFilter.shipmentFixedAssetLine.rentalAgreementLineId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.shipmentFixedAssetLine.meter"
+ },
{
$ref: "#/parameters/body.shipmentFixedAssetLine"
},
@@ -100872,6 +100899,24 @@ export default {
{
$ref: "#/parameters/rowFilter.receiptFixedAssetLine.updatedBy"
},
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.rentalAgreementLineId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.meter"
+ },
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.takeOutOfService"
+ },
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.outOfServiceReason"
+ },
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.residualDestination"
+ },
{
$ref: "#/parameters/select"
},
@@ -100961,6 +101006,24 @@ export default {
{
$ref: "#/parameters/rowFilter.receiptFixedAssetLine.updatedBy"
},
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.rentalAgreementLineId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.meter"
+ },
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.takeOutOfService"
+ },
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.outOfServiceReason"
+ },
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.residualDestination"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -101004,6 +101067,24 @@ export default {
{
$ref: "#/parameters/rowFilter.receiptFixedAssetLine.updatedBy"
},
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.rentalAgreementLineId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.meter"
+ },
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.notes"
+ },
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.takeOutOfService"
+ },
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.outOfServiceReason"
+ },
+ {
+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.residualDestination"
+ },
{
$ref: "#/parameters/body.receiptFixedAssetLine"
},
@@ -118860,7 +118941,8 @@ export default {
"Inbound Transfer",
"Outbound Transfer",
"Manufacturing Consumption",
- "Manufacturing Output"
+ "Manufacturing Output",
+ "Rental Agreement"
],
format: 'public."receiptSourceDocument"',
type: "string"
@@ -120227,7 +120309,8 @@ export default {
"Inbound Transfer",
"Outbound Transfer",
"Manufacturing Consumption",
- "Manufacturing Output"
+ "Manufacturing Output",
+ "Rental Agreement"
],
format: 'public."receiptSourceDocument"',
type: "string"
@@ -140895,7 +140978,8 @@ export default {
"Purchase Invoice",
"Purchase Return Order",
"Inbound Transfer",
- "Outbound Transfer"
+ "Outbound Transfer",
+ "Rental Agreement"
],
format: 'public."shipmentSourceDocument"',
type: "string"
@@ -142064,6 +142148,9 @@ export default {
default: false,
format: "boolean",
type: "boolean"
+ },
+ orientation: {
+ format: "jsonb"
}
},
type: "object"
@@ -143725,7 +143812,6 @@ export default {
required: [
"id",
"shipmentId",
- "salesOrderLineId",
"shipped",
"companyId",
"createdBy",
@@ -143783,6 +143869,14 @@ export default {
updatedBy: {
format: "text",
type: "string"
+ },
+ rentalAgreementLineId: {
+ format: "text",
+ type: "string"
+ },
+ meter: {
+ format: "numeric",
+ type: "number"
}
},
type: "object"
@@ -162586,11 +162680,11 @@ export default {
required: [
"id",
"receiptId",
- "purchaseOrderLineId",
"received",
"companyId",
"createdBy",
- "createdAt"
+ "createdAt",
+ "takeOutOfService"
],
properties: {
id: {
@@ -162644,6 +162738,31 @@ export default {
updatedBy: {
format: "text",
type: "string"
+ },
+ rentalAgreementLineId: {
+ format: "text",
+ type: "string"
+ },
+ meter: {
+ format: "numeric",
+ type: "number"
+ },
+ notes: {
+ format: "text",
+ type: "string"
+ },
+ takeOutOfService: {
+ default: false,
+ format: "boolean",
+ type: "boolean"
+ },
+ outOfServiceReason: {
+ format: "text",
+ type: "string"
+ },
+ residualDestination: {
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -193673,6 +193792,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.assemblyInstructionStep.orientation": {
+ name: "orientation",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.receiptLine": {
name: "receiptLine",
description: "receiptLine",
@@ -195558,6 +195683,18 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.shipmentFixedAssetLine.rentalAgreementLineId": {
+ name: "rentalAgreementLineId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.shipmentFixedAssetLine.meter": {
+ name: "meter",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.customerContractInvoiceLine": {
name: "customerContractInvoiceLine",
description: "customerContractInvoiceLine",
@@ -216556,6 +216693,42 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.receiptFixedAssetLine.rentalAgreementLineId": {
+ name: "rentalAgreementLineId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.receiptFixedAssetLine.meter": {
+ name: "meter",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.receiptFixedAssetLine.notes": {
+ name: "notes",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.receiptFixedAssetLine.takeOutOfService": {
+ name: "takeOutOfService",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.receiptFixedAssetLine.outOfServiceReason": {
+ name: "outOfServiceReason",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.receiptFixedAssetLine.residualDestination": {
+ name: "residualDestination",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.kanban": {
name: "kanban",
description: "kanban",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 5dc5beb9f8..d495efffa8 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -3742,6 +3742,7 @@ export type Database = {
minValue: number | null
motion: Json
notes: Json | null
+ orientation: Json | null
parentStepId: string | null
planConfidence: string
required: boolean | null
@@ -3778,6 +3779,7 @@ export type Database = {
minValue?: number | null
motion?: Json
notes?: Json | null
+ orientation?: Json | null
parentStepId?: string | null
planConfidence?: string
required?: boolean | null
@@ -3814,6 +3816,7 @@ export type Database = {
minValue?: number | null
motion?: Json
notes?: Json | null
+ orientation?: Json | null
parentStepId?: string | null
planConfidence?: string
required?: boolean | null
diff --git a/packages/database/supabase/migrations/20261009110527_assembly-step-orientation.sql b/packages/database/supabase/migrations/20261009110527_assembly-step-orientation.sql
new file mode 100644
index 0000000000..bc24ce1fec
--- /dev/null
+++ b/packages/database/supabase/migrations/20261009110527_assembly-step-orientation.sql
@@ -0,0 +1,6 @@
+-- The build's orientation from this step on: a unit quaternion [x, y, z, w]
+-- that turns the model frame into the bench frame. Applied by the 3D player
+-- in the ERP editor and in MES. NULL = same as the previous step in the
+-- same build (main build or sub-assembly); a sub-assembly starts upright.
+ALTER TABLE "assemblyInstructionStep"
+ ADD COLUMN IF NOT EXISTS "orientation" JSONB;
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index b27e955cf0..2634ed99b1 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# Arbeitsgang hat keine Zeitstandards} other {# Arbeits
#. placeholder {0}: issues.length
msgid "{0, plural, one {# record needs attention} other {# records need attention}}"
-msgstr ""
+msgstr "{0, plural, one {# Datensatz benötigt Aufmerksamkeit} other {# Datensätze benötigen Aufmerksamkeit}}"
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
@@ -405,7 +405,7 @@ msgid "{count} units"
msgstr "{count} Einheiten"
msgid "{created} created, {updated} updated."
-msgstr ""
+msgstr "{created} erstellt, {updated} aktualisiert."
msgid "{days}d"
msgstr "{days}T"
@@ -432,7 +432,7 @@ msgid "{from}–{to} of {count} operations"
msgstr "{from}–{to} von {count} Arbeitsgängen"
msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"
-msgstr ""
+msgstr "{hidden, plural, one {Und # weiterer Datensatz.} other {Und # weitere Datensätze.}}"
msgid "{hiddenCount} more: {hiddenNames}"
msgstr "{hiddenCount} weitere: {hiddenNames}"
@@ -9495,6 +9495,9 @@ msgstr "Flotteneinheit"
msgid "Fleet Units"
msgstr "Flotteneinheiten"
+msgid "Flip over"
+msgstr "Umdrehen"
+
msgid "For <0/>"
msgstr "Für <0/>"
@@ -10228,6 +10231,9 @@ msgstr "Wie die Stichprobengröße entschieden wird — Alle inspizieren, Erste
msgid "How the unit price of each quantity was calculated."
msgstr "Wie der Einzelpreis jeder Menge berechnet wurde."
+msgid "How the whole build is turned on a step, such as flipped to fit parts on its underside. Later steps of the same build keep it until a step turns the build again."
+msgstr "Die Ausrichtung der gesamten Baugruppe bei einem Schritt, z. B. umgedreht, damit Teile an ihrer Unterseite passen. Spätere Schritte derselben Baugruppe behalten sie bei, bis ein Schritt die Baugruppe erneut dreht."
+
msgid "How this gauge is used — Standard (regular checks) or Master (calibrates other gauges)."
msgstr "Wie dieses Prüfmittel verwendet wird — Normal (regelmäßige Überprüfungen) oder Referenz (kalibriert andere Prüfmittel)."
@@ -11389,10 +11395,10 @@ msgstr "Nachname"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr ""
+msgstr "Letzte Übertragung {when} fehlgeschlagen: {0}"
msgid "Last push {when}:"
-msgstr ""
+msgstr "Letzte Übertragung {when}:"
msgid "Last Quarter"
msgstr "Letztes Quartal"
@@ -11401,7 +11407,7 @@ msgid "Last Run"
msgstr "Letzte Ausführung"
msgid "Last scheduled push {when}:"
-msgstr ""
+msgstr "Letzte geplante Übertragung {when}:"
msgid "Last synced: <0/>"
msgstr "Zuletzt synchronisiert: <0/>"
@@ -12551,7 +12557,7 @@ msgid "More overtime"
msgstr "Mehr Überstunden"
msgid "More records are waiting. Push again to continue."
-msgstr ""
+msgstr "Weitere Datensätze warten. Erneut übertragen, um fortzufahren."
msgid "Morning, {name}."
msgstr "Morgen, {name}."
@@ -12566,7 +12572,7 @@ msgid "Motion"
msgstr "Bewegung"
msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."
-msgstr ""
+msgstr "Mount hat {matches} Datensätze mit dieser Kennung. Löschen Sie die überzähligen in Mount oder führen Sie sie zusammen, und übertragen Sie dann erneut."
msgid "Move"
msgstr "Verschieben"
@@ -13284,7 +13290,7 @@ msgid "No comments yet. Be the first to add a comment."
msgstr "Noch keine Kommentare. Seien Sie der Erste, der einen Kommentar hinzufügt."
msgid "No companies match \"{query}\""
-msgstr ""
+msgstr "Keine Unternehmen gefunden für „{query}“"
msgid "No completed jobs within range"
msgstr "Keine fertiggestellten Fertigungsaufträge im Bereich"
@@ -14069,6 +14075,12 @@ msgstr "Verfügbar: {before} auf {after}"
msgid "On Hold"
msgstr "Angehalten"
+msgid "On its side"
+msgstr "Seitlich liegend"
+
+msgid "On its side, from step {orientationSource}"
+msgstr "Seitlich liegend, von Schritt {orientationSource}"
+
msgid "On Jobs"
msgstr "Auf Fertigungsaufträgen"
@@ -14590,6 +14602,9 @@ msgstr "Bestellungen"
msgid "Orders submitted"
msgstr "Bestellungen eingereicht"
+msgid "Orientation"
+msgstr "Ausrichtung"
+
msgid "Origin"
msgstr "Ursprung"
@@ -18255,7 +18270,7 @@ msgid "Search fields..."
msgstr "Felder durchsuchen..."
msgid "Search for a company"
-msgstr ""
+msgstr "Nach einem Unternehmen suchen"
msgid "Search for existing or create a new one"
msgstr "Suchen Sie nach einem vorhandenen oder erstellen Sie einen neuen"
@@ -19425,6 +19440,12 @@ msgstr "Spezifische Artikel"
msgid "Spend by supplier, item, or category — your biggest cost drivers"
msgstr "Ausgaben nach Lieferant, Artikel oder Kategorie – Ihre größten Kostenverursacher"
+msgid "Spin left"
+msgstr "Nach links drehen"
+
+msgid "Spin right"
+msgstr "Nach rechts drehen"
+
msgid "Split"
msgstr "Teilen"
@@ -19520,7 +19541,7 @@ msgid "Started"
msgstr "Gestartet"
msgid "Starting"
-msgstr ""
+msgstr "Wird gestartet"
msgid "Starting…"
msgstr "Wird gestartet…"
@@ -20894,6 +20915,9 @@ msgstr "Die Materialtypen, nach denen Sie Ihren Bestand organisieren"
msgid "The model is still loading."
msgstr "Das Modell wird noch geladen."
+msgid "The model isn't ready yet"
+msgstr "Das Modell ist noch nicht bereit"
+
msgid "The month your financial year begins; periods are numbered from this month."
msgstr "Der Monat, in dem Ihr Geschäftsjahr beginnt; Perioden werden von diesem Monat an nummeriert."
@@ -21047,16 +21071,16 @@ msgid "The purchase order"
msgstr "Die Bestellung"
msgid "The push to Mount did not start. Try again."
-msgstr ""
+msgstr "Die Übertragung an Mount konnte nicht gestartet werden. Versuchen Sie es erneut."
msgid "The push to Mount failed"
-msgstr ""
+msgstr "Übertragung an Mount fehlgeschlagen"
msgid "The push to Mount finished"
-msgstr ""
+msgstr "Übertragung an Mount abgeschlossen"
msgid "The push to Mount finished. Some records need attention"
-msgstr ""
+msgstr "Übertragung an Mount abgeschlossen. Einige Datensätze benötigen Aufmerksamkeit"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "Die Mengenestaffeln, zu denen diese Position bewertet ist; jede Spalte hat seinen eigenen Stückpreis für Käufer–Lieferant-Verhandlungen und für die Umwandlung in nachgelagerte Dokumente."
@@ -21892,6 +21916,12 @@ msgstr "Timer läuft"
msgid "Timezone"
msgstr "Zeitzone"
+msgid "Tip away from you"
+msgstr "Von sich weg kippen"
+
+msgid "Tip toward you"
+msgstr "Zu sich hin kippen"
+
msgid "Title"
msgstr "Titel"
@@ -22272,7 +22302,7 @@ msgid "Triggers"
msgstr "Auslöser"
msgid "Try a different name."
-msgstr ""
+msgstr "Versuchen Sie einen anderen Namen."
msgid "Tuesday"
msgstr "Dienstag"
@@ -22765,6 +22795,15 @@ msgstr "Wird hochgeladen…"
msgid "Upon clicking Convert, parts will be created with the following internal part numbers:"
msgstr "Beim Klicken auf Umwandeln werden Teile mit den folgenden internen Teilenummern erstellt:"
+msgid "Upright"
+msgstr "Aufrecht"
+
+msgid "Upside down"
+msgstr "Kopfüber"
+
+msgid "Upside down, from step {orientationSource}"
+msgstr "Kopfüber, von Schritt {orientationSource}"
+
msgid "URL"
msgstr "URL"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index f47799761c..012e256678 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -9495,6 +9495,9 @@ msgstr "Fleet Unit"
msgid "Fleet Units"
msgstr "Fleet Units"
+msgid "Flip over"
+msgstr "Flip over"
+
msgid "For <0/>"
msgstr "For <0/>"
@@ -10228,6 +10231,9 @@ msgstr "How the sample size is decided — Inspect All, Inspect First N, Percent
msgid "How the unit price of each quantity was calculated."
msgstr "How the unit price of each quantity was calculated."
+msgid "How the whole build is turned on a step, such as flipped to fit parts on its underside. Later steps of the same build keep it until a step turns the build again."
+msgstr "How the whole build is turned on a step, such as flipped to fit parts on its underside. Later steps of the same build keep it until a step turns the build again."
+
msgid "How this gauge is used — Standard (regular checks) or Master (calibrates other gauges)."
msgstr "How this gauge is used — Standard (regular checks) or Master (calibrates other gauges)."
@@ -14069,6 +14075,12 @@ msgstr "On hand {before} to {after}"
msgid "On Hold"
msgstr "On Hold"
+msgid "On its side"
+msgstr "On its side"
+
+msgid "On its side, from step {orientationSource}"
+msgstr "On its side, from step {orientationSource}"
+
msgid "On Jobs"
msgstr "On Jobs"
@@ -14590,6 +14602,9 @@ msgstr "Orders"
msgid "Orders submitted"
msgstr "Orders submitted"
+msgid "Orientation"
+msgstr "Orientation"
+
msgid "Origin"
msgstr "Origin"
@@ -19425,6 +19440,12 @@ msgstr "Specific Items"
msgid "Spend by supplier, item, or category — your biggest cost drivers"
msgstr "Spend by supplier, item, or category — your biggest cost drivers"
+msgid "Spin left"
+msgstr "Spin left"
+
+msgid "Spin right"
+msgstr "Spin right"
+
msgid "Split"
msgstr "Split"
@@ -20894,6 +20915,9 @@ msgstr "The material types you organize your stock by"
msgid "The model is still loading."
msgstr "The model is still loading."
+msgid "The model isn't ready yet"
+msgstr "The model isn't ready yet"
+
msgid "The month your financial year begins; periods are numbered from this month."
msgstr "The month your financial year begins; periods are numbered from this month."
@@ -21892,6 +21916,12 @@ msgstr "Timer running"
msgid "Timezone"
msgstr "Timezone"
+msgid "Tip away from you"
+msgstr "Tip away from you"
+
+msgid "Tip toward you"
+msgstr "Tip toward you"
+
msgid "Title"
msgstr "Title"
@@ -22765,6 +22795,15 @@ msgstr "Uploading…"
msgid "Upon clicking Convert, parts will be created with the following internal part numbers:"
msgstr "Upon clicking Convert, parts will be created with the following internal part numbers:"
+msgid "Upright"
+msgstr "Upright"
+
+msgid "Upside down"
+msgstr "Upside down"
+
+msgid "Upside down, from step {orientationSource}"
+msgstr "Upside down, from step {orientationSource}"
+
msgid "URL"
msgstr "URL"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index b3feecd335..c02ca18db8 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# operación no tiene estándares de tiempo} other {# o
#. placeholder {0}: issues.length
msgid "{0, plural, one {# record needs attention} other {# records need attention}}"
-msgstr ""
+msgstr "{0, plural, one {# registro requiere atención} other {# registros requieren atención}}"
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
@@ -405,7 +405,7 @@ msgid "{count} units"
msgstr "{count} unidades"
msgid "{created} created, {updated} updated."
-msgstr ""
+msgstr "{created} creados, {updated} actualizados."
msgid "{days}d"
msgstr "{days}d"
@@ -432,7 +432,7 @@ msgid "{from}–{to} of {count} operations"
msgstr "{from}–{to} de {count} operaciones"
msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"
-msgstr ""
+msgstr "{hidden, plural, one {Y # registro más.} other {Y # registros más.}}"
msgid "{hiddenCount} more: {hiddenNames}"
msgstr "{hiddenCount} más: {hiddenNames}"
@@ -9495,6 +9495,9 @@ msgstr "Unidad de flota"
msgid "Fleet Units"
msgstr "Unidades de flota"
+msgid "Flip over"
+msgstr "Dar la vuelta"
+
msgid "For <0/>"
msgstr "Para <0/>"
@@ -10228,6 +10231,9 @@ msgstr "Cómo se decide el tamaño de la muestra — Inspeccionar Todo, Inspecci
msgid "How the unit price of each quantity was calculated."
msgstr "Cómo se calculó el precio unitario de cada cantidad."
+msgid "How the whole build is turned on a step, such as flipped to fit parts on its underside. Later steps of the same build keep it until a step turns the build again."
+msgstr "Cómo se orienta todo el conjunto en un paso, por ejemplo, dado la vuelta para encajar piezas en su parte inferior. Los pasos posteriores del mismo conjunto mantienen esta orientación hasta que un paso vuelva a girar el conjunto."
+
msgid "How this gauge is used — Standard (regular checks) or Master (calibrates other gauges)."
msgstr "Cómo se utiliza este instrumento de medición — Estándar (verificaciones regulares) o Maestro (calibra otros instrumentos)."
@@ -11389,10 +11395,10 @@ msgstr "Apellido"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr ""
+msgstr "El último envío {when} falló: {0}"
msgid "Last push {when}:"
-msgstr ""
+msgstr "Último envío {when}:"
msgid "Last Quarter"
msgstr "Trimestre Anterior"
@@ -11401,7 +11407,7 @@ msgid "Last Run"
msgstr "Última ejecución"
msgid "Last scheduled push {when}:"
-msgstr ""
+msgstr "Último envío programado {when}:"
msgid "Last synced: <0/>"
msgstr "Última sincronización: <0/>"
@@ -12551,7 +12557,7 @@ msgid "More overtime"
msgstr "Más horas extra"
msgid "More records are waiting. Push again to continue."
-msgstr ""
+msgstr "Hay más registros pendientes. Vuelva a enviar para continuar."
msgid "Morning, {name}."
msgstr "Mañana, {name}."
@@ -12566,7 +12572,7 @@ msgid "Motion"
msgstr "Movimiento"
msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."
-msgstr ""
+msgstr "Mount tiene {matches} registros con este identificador. Elimine o combine los registros sobrantes en Mount y vuelva a enviar."
msgid "Move"
msgstr "Mover"
@@ -13284,7 +13290,7 @@ msgid "No comments yet. Be the first to add a comment."
msgstr "No hay comentarios aún. Sé el primero en agregar un comentario."
msgid "No companies match \"{query}\""
-msgstr ""
+msgstr "Ninguna empresa coincide con «{query}»"
msgid "No completed jobs within range"
msgstr "No hay órdenes de trabajo completadas dentro del rango"
@@ -14069,6 +14075,12 @@ msgstr "En existencia: de {before} a {after}"
msgid "On Hold"
msgstr "Suspendido"
+msgid "On its side"
+msgstr "De lado"
+
+msgid "On its side, from step {orientationSource}"
+msgstr "De lado, desde el paso {orientationSource}"
+
msgid "On Jobs"
msgstr "En órdenes de trabajo"
@@ -14590,6 +14602,9 @@ msgstr "Pedidos"
msgid "Orders submitted"
msgstr "Pedidos enviados"
+msgid "Orientation"
+msgstr "Orientación"
+
msgid "Origin"
msgstr "Origen"
@@ -18255,7 +18270,7 @@ msgid "Search fields..."
msgstr "Buscar campos..."
msgid "Search for a company"
-msgstr ""
+msgstr "Buscar una empresa"
msgid "Search for existing or create a new one"
msgstr "Buscar uno existente o crear uno nuevo"
@@ -19425,6 +19440,12 @@ msgstr "Artículos Específicos"
msgid "Spend by supplier, item, or category — your biggest cost drivers"
msgstr "Gasto por proveedor, artículo o categoría — sus mayores generadores de costos"
+msgid "Spin left"
+msgstr "Girar a la izquierda"
+
+msgid "Spin right"
+msgstr "Girar a la derecha"
+
msgid "Split"
msgstr "Dividir"
@@ -19520,7 +19541,7 @@ msgid "Started"
msgstr "Comenzó"
msgid "Starting"
-msgstr ""
+msgstr "Iniciando"
msgid "Starting…"
msgstr "Iniciando…"
@@ -20894,6 +20915,9 @@ msgstr "Los tipos de material por los que organizas tu inventario"
msgid "The model is still loading."
msgstr "El modelo aún se está cargando."
+msgid "The model isn't ready yet"
+msgstr "El modelo aún no está listo"
+
msgid "The month your financial year begins; periods are numbered from this month."
msgstr "El mes en que comienza su año fiscal; los períodos se numeran a partir de este mes."
@@ -21047,16 +21071,16 @@ msgid "The purchase order"
msgstr "La orden de compra"
msgid "The push to Mount did not start. Try again."
-msgstr ""
+msgstr "El envío a Mount no se inició. Inténtelo de nuevo."
msgid "The push to Mount failed"
-msgstr ""
+msgstr "El envío a Mount falló"
msgid "The push to Mount finished"
-msgstr ""
+msgstr "El envío a Mount finalizó"
msgid "The push to Mount finished. Some records need attention"
-msgstr ""
+msgstr "El envío a Mount finalizó. Algunos registros requieren atención"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "Los puntos de ruptura de cantidad a los que se cotiza esta línea; cada columna lleva su propio precio por unidad para la negociación comprador-proveedor y para la conversión a documentos posteriores."
@@ -21892,6 +21916,12 @@ msgstr "Temporizador en ejecución"
msgid "Timezone"
msgstr "Zona horaria"
+msgid "Tip away from you"
+msgstr "Inclinar alejándose"
+
+msgid "Tip toward you"
+msgstr "Inclinar acercándose"
+
msgid "Title"
msgstr "Título"
@@ -22272,7 +22302,7 @@ msgid "Triggers"
msgstr "Disparadores"
msgid "Try a different name."
-msgstr ""
+msgstr "Pruebe con otro nombre."
msgid "Tuesday"
msgstr "Martes"
@@ -22765,6 +22795,15 @@ msgstr "Cargando…"
msgid "Upon clicking Convert, parts will be created with the following internal part numbers:"
msgstr "Al hacer clic en Convertir, se crearán piezas con los siguientes números de pieza internos:"
+msgid "Upright"
+msgstr "Vertical"
+
+msgid "Upside down"
+msgstr "Boca abajo"
+
+msgid "Upside down, from step {orientationSource}"
+msgstr "Boca abajo, desde el paso {orientationSource}"
+
msgid "URL"
msgstr "URL"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 470fac2d0e..9aa68cac4d 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# opération n'a pas de normes de temps} other {# opér
#. placeholder {0}: issues.length
msgid "{0, plural, one {# record needs attention} other {# records need attention}}"
-msgstr ""
+msgstr "{0, plural, one {# enregistrement nécessite une attention} other {# enregistrements nécessitent une attention}}"
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
@@ -405,7 +405,7 @@ msgid "{count} units"
msgstr "{count} unités"
msgid "{created} created, {updated} updated."
-msgstr ""
+msgstr "{created} créé(s), {updated} mis à jour."
msgid "{days}d"
msgstr "{days}j"
@@ -432,7 +432,7 @@ msgid "{from}–{to} of {count} operations"
msgstr "{from}–{to} sur {count} opérations"
msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"
-msgstr ""
+msgstr "{hidden, plural, one {Et # enregistrement de plus.} other {Et # enregistrements de plus.}}"
msgid "{hiddenCount} more: {hiddenNames}"
msgstr "{hiddenCount} autres : {hiddenNames}"
@@ -9495,6 +9495,9 @@ msgstr "Unité de parc"
msgid "Fleet Units"
msgstr "Unités de parc"
+msgid "Flip over"
+msgstr "Retourner"
+
msgid "For <0/>"
msgstr "Pour <0/>"
@@ -10228,6 +10231,9 @@ msgstr "Comment la taille d'échantillon est décidée — Inspecter tout, Inspe
msgid "How the unit price of each quantity was calculated."
msgstr "Comment le prix unitaire de chaque quantité a été calculé."
+msgid "How the whole build is turned on a step, such as flipped to fit parts on its underside. Later steps of the same build keep it until a step turns the build again."
+msgstr "Orientation de l'ensemble complet à une étape, par exemple retourné pour poser des pièces sur sa face inférieure. Les étapes suivantes du même ensemble conservent cette orientation jusqu'à ce qu'une étape oriente à nouveau l'ensemble."
+
msgid "How this gauge is used — Standard (regular checks) or Master (calibrates other gauges)."
msgstr "Comment cet instrument de mesure est utilisé — Standard (contrôles réguliers) ou Maître (étalonner d'autres instruments)."
@@ -11389,10 +11395,10 @@ msgstr "Nom de famille"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr ""
+msgstr "Le dernier envoi {when} a échoué : {0}"
msgid "Last push {when}:"
-msgstr ""
+msgstr "Dernier envoi {when} :"
msgid "Last Quarter"
msgstr "Dernier trimestre"
@@ -11401,7 +11407,7 @@ msgid "Last Run"
msgstr "Dernière exécution"
msgid "Last scheduled push {when}:"
-msgstr ""
+msgstr "Dernier envoi planifié {when} :"
msgid "Last synced: <0/>"
msgstr "Dernière synchronisation : <0/>"
@@ -12551,7 +12557,7 @@ msgid "More overtime"
msgstr "Plus d'heures supplémentaires"
msgid "More records are waiting. Push again to continue."
-msgstr ""
+msgstr "D'autres enregistrements attendent. Relancez l'envoi pour continuer."
msgid "Morning, {name}."
msgstr "Bon matin, {name}."
@@ -12566,7 +12572,7 @@ msgid "Motion"
msgstr "Motion"
msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."
-msgstr ""
+msgstr "Mount contient {matches} enregistrements avec cet identifiant. Supprimez ou fusionnez les doublons dans Mount, puis relancez l'envoi."
msgid "Move"
msgstr "Déplacer"
@@ -13284,7 +13290,7 @@ msgid "No comments yet. Be the first to add a comment."
msgstr "Aucun commentaire pour le moment. Soyez le premier à ajouter un commentaire."
msgid "No companies match \"{query}\""
-msgstr ""
+msgstr "Aucune société ne correspond à « {query} »"
msgid "No completed jobs within range"
msgstr "Aucun ordre de fabrication terminé dans cette plage"
@@ -14069,6 +14075,12 @@ msgstr "En stock : de {before} à {after}"
msgid "On Hold"
msgstr "Suspendu"
+msgid "On its side"
+msgstr "Sur le côté"
+
+msgid "On its side, from step {orientationSource}"
+msgstr "Sur le côté, depuis l'étape {orientationSource}"
+
msgid "On Jobs"
msgstr "Sur ordres de fabrication"
@@ -14590,6 +14602,9 @@ msgstr "Commandes"
msgid "Orders submitted"
msgstr "Commandes soumises"
+msgid "Orientation"
+msgstr "Orientation"
+
msgid "Origin"
msgstr "Origine"
@@ -18255,7 +18270,7 @@ msgid "Search fields..."
msgstr "Rechercher des champs..."
msgid "Search for a company"
-msgstr ""
+msgstr "Rechercher une société"
msgid "Search for existing or create a new one"
msgstr "Rechercher un existant ou en créer un nouveau"
@@ -19425,6 +19440,12 @@ msgstr "Articles spécifiques"
msgid "Spend by supplier, item, or category — your biggest cost drivers"
msgstr "Dépenses par fournisseur, article ou catégorie — vos principaux moteurs de coûts"
+msgid "Spin left"
+msgstr "Tourner à gauche"
+
+msgid "Spin right"
+msgstr "Tourner à droite"
+
msgid "Split"
msgstr "Diviser"
@@ -19520,7 +19541,7 @@ msgid "Started"
msgstr "Commencé"
msgid "Starting"
-msgstr ""
+msgstr "Démarrage"
msgid "Starting…"
msgstr "Démarrage…"
@@ -20894,6 +20915,9 @@ msgstr "Les types de matériaux selon lesquels vous organisez votre stock"
msgid "The model is still loading."
msgstr "Le modèle est toujours en cours de chargement."
+msgid "The model isn't ready yet"
+msgstr "Le modèle n'est pas encore prêt"
+
msgid "The month your financial year begins; periods are numbered from this month."
msgstr "Le mois où votre exercice financier commence; les périodes sont numérotées à partir de ce mois."
@@ -21047,16 +21071,16 @@ msgid "The purchase order"
msgstr "Le bon de commande"
msgid "The push to Mount did not start. Try again."
-msgstr ""
+msgstr "L'envoi vers Mount n'a pas démarré. Réessayez."
msgid "The push to Mount failed"
-msgstr ""
+msgstr "L'envoi vers Mount a échoué"
msgid "The push to Mount finished"
-msgstr ""
+msgstr "L'envoi vers Mount est terminé"
msgid "The push to Mount finished. Some records need attention"
-msgstr ""
+msgstr "L'envoi vers Mount est terminé. Certains enregistrements nécessitent une attention"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "Les points d'arrêt de quantité à laquelle cette ligne est tarifée; chaque colonne porte son propre prix par unité pour la négociation acheteur-fournisseur et la conversion en documents aval."
@@ -21892,6 +21916,12 @@ msgstr "Minuterie en cours d'exécution"
msgid "Timezone"
msgstr "Fuseau horaire"
+msgid "Tip away from you"
+msgstr "Basculer en l'éloignant de vous"
+
+msgid "Tip toward you"
+msgstr "Basculer vers vous"
+
msgid "Title"
msgstr "Titre"
@@ -22272,7 +22302,7 @@ msgid "Triggers"
msgstr "Déclencheurs"
msgid "Try a different name."
-msgstr ""
+msgstr "Essayez un autre nom."
msgid "Tuesday"
msgstr "Mardi"
@@ -22765,6 +22795,15 @@ msgstr "Téléchargement en cours…"
msgid "Upon clicking Convert, parts will be created with the following internal part numbers:"
msgstr "En cliquant sur Convertir, les pièces seront créées avec les numéros de pièce internes suivants :"
+msgid "Upright"
+msgstr "Debout"
+
+msgid "Upside down"
+msgstr "À l'envers"
+
+msgid "Upside down, from step {orientationSource}"
+msgstr "À l'envers, depuis l'étape {orientationSource}"
+
msgid "URL"
msgstr "URL"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 4b76a58d77..2206996ec5 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# ऑपरेशन के लिए कोई सम
#. placeholder {0}: issues.length
msgid "{0, plural, one {# record needs attention} other {# records need attention}}"
-msgstr ""
+msgstr "{0, plural, one {# रिकॉर्ड पर ध्यान देने की ज़रूरत है} other {# रिकॉर्ड्स पर ध्यान देने की ज़रूरत है}}"
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
@@ -405,7 +405,7 @@ msgid "{count} units"
msgstr "{count} इकाइयाँ"
msgid "{created} created, {updated} updated."
-msgstr ""
+msgstr "{created} बनाए गए, {updated} अपडेट किए गए."
msgid "{days}d"
msgstr "{days}d"
@@ -432,7 +432,7 @@ msgid "{from}–{to} of {count} operations"
msgstr "{count} ऑपरेशन में से {from}–{to}"
msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"
-msgstr ""
+msgstr "{hidden, plural, one {और # रिकॉर्ड.} other {और # रिकॉर्ड्स.}}"
msgid "{hiddenCount} more: {hiddenNames}"
msgstr "और {hiddenCount}: {hiddenNames}"
@@ -9495,6 +9495,9 @@ msgstr "बेड़े की इकाई"
msgid "Fleet Units"
msgstr "फ्लीट इकाई"
+msgid "Flip over"
+msgstr "पलटें"
+
msgid "For <0/>"
msgstr "के लिए <0/>"
@@ -10228,6 +10231,9 @@ msgstr "नमूना आकार कैसे तय किया जात
msgid "How the unit price of each quantity was calculated."
msgstr "प्रत्येक मात्रा की इकाई मूल्य की गणना कैसे की गई।"
+msgid "How the whole build is turned on a step, such as flipped to fit parts on its underside. Later steps of the same build keep it until a step turns the build again."
+msgstr "किसी चरण में पूरी असेंबली को किस तरह घुमाया गया है, जैसे नीचे की ओर लगे पार्ट्स के लिए उसे पलटना। उसी असेंबली के बाद के चरण तब तक यही स्थिति रखते हैं, जब तक कोई चरण असेंबली को फिर से न घुमाए."
+
msgid "How this gauge is used — Standard (regular checks) or Master (calibrates other gauges)."
msgstr "यह गेज कैसे उपयोग किया जाता है — मानक (नियमित जांच) या मास्टर (अन्य गेज को कैलिब्रेट करता है)।"
@@ -11389,10 +11395,10 @@ msgstr "अंतिम नाम"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr ""
+msgstr "अंतिम पुश ({when}) विफल हुआ: {0}"
msgid "Last push {when}:"
-msgstr ""
+msgstr "अंतिम पुश ({when}):"
msgid "Last Quarter"
msgstr "पिछली तिमाही"
@@ -11401,7 +11407,7 @@ msgid "Last Run"
msgstr "अंतिम रन"
msgid "Last scheduled push {when}:"
-msgstr ""
+msgstr "अंतिम निर्धारित पुश ({when}):"
msgid "Last synced: <0/>"
msgstr "अंतिम सिंक: <0/>"
@@ -12551,7 +12557,7 @@ msgid "More overtime"
msgstr "अधिक ओवरटाइम"
msgid "More records are waiting. Push again to continue."
-msgstr ""
+msgstr "और रिकॉर्ड प्रतीक्षा में हैं। जारी रखने के लिए फिर से पुश करें."
msgid "Morning, {name}."
msgstr "सुबह, {name}।"
@@ -12566,7 +12572,7 @@ msgid "Motion"
msgstr "गति"
msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."
-msgstr ""
+msgstr "Mount में इस पहचानकर्ता वाले {matches} रिकॉर्ड हैं। Mount में अतिरिक्त रिकॉर्ड हटाएँ या मर्ज करें, फिर से पुश करें."
msgid "Move"
msgstr "स्थानांतरित करें"
@@ -13284,7 +13290,7 @@ msgid "No comments yet. Be the first to add a comment."
msgstr "अभी कोई टिप्पणी नहीं है। पहली टिप्पणी जोड़ने वाले बनें।"
msgid "No companies match \"{query}\""
-msgstr ""
+msgstr "कोई कंपनी “{query}” से मेल नहीं खाती"
msgid "No completed jobs within range"
msgstr "रेंज में कोई पूर्ण जॉब नहीं"
@@ -14069,6 +14075,12 @@ msgstr "हाथ में: {before} से {after}"
msgid "On Hold"
msgstr "होल्ड पर"
+msgid "On its side"
+msgstr "करवट पर"
+
+msgid "On its side, from step {orientationSource}"
+msgstr "चरण {orientationSource} से करवट पर"
+
msgid "On Jobs"
msgstr "जॉब पर"
@@ -14590,6 +14602,9 @@ msgstr "आदेश"
msgid "Orders submitted"
msgstr "ऑर्डर जमा किए गए"
+msgid "Orientation"
+msgstr "दिशा"
+
msgid "Origin"
msgstr "मूल"
@@ -18255,7 +18270,7 @@ msgid "Search fields..."
msgstr "फ़ील्ड खोजें..."
msgid "Search for a company"
-msgstr ""
+msgstr "कंपनी खोजें"
msgid "Search for existing or create a new one"
msgstr "मौजूदा को खोजें या नया बनाएं"
@@ -19425,6 +19440,12 @@ msgstr "विशिष्ट आइटम"
msgid "Spend by supplier, item, or category — your biggest cost drivers"
msgstr "आपूर्तिकर्ता, आइटम, या श्रेणी द्वारा व्यय — आपके सबसे बड़े लागत ड्राइवर"
+msgid "Spin left"
+msgstr "बाईं ओर घुमाएँ"
+
+msgid "Spin right"
+msgstr "दाईं ओर घुमाएँ"
+
msgid "Split"
msgstr "विभाजित करें"
@@ -19520,7 +19541,7 @@ msgid "Started"
msgstr "शुरू किया गया"
msgid "Starting"
-msgstr ""
+msgstr "शुरू हो रहा है"
msgid "Starting…"
msgstr "शुरू हो रहा है…"
@@ -20894,6 +20915,9 @@ msgstr "आप अपने स्टॉक को जिन सामग्र
msgid "The model is still loading."
msgstr "मॉडल अभी भी लोड हो रहा है।"
+msgid "The model isn't ready yet"
+msgstr "मॉडल अभी तैयार नहीं है"
+
msgid "The month your financial year begins; periods are numbered from this month."
msgstr "वह महीना जब आपका वित्तीय वर्ष शुरू होता है; अवधियों को इस महीने से गिना जाता है।"
@@ -21047,16 +21071,16 @@ msgid "The purchase order"
msgstr "क्रय आदेश"
msgid "The push to Mount did not start. Try again."
-msgstr ""
+msgstr "Mount पर पुश शुरू नहीं हो सका। फिर से कोशिश करें."
msgid "The push to Mount failed"
-msgstr ""
+msgstr "Mount पर पुश विफल रहा"
msgid "The push to Mount finished"
-msgstr ""
+msgstr "Mount पर पुश पूरा हुआ"
msgid "The push to Mount finished. Some records need attention"
-msgstr ""
+msgstr "Mount पर पुश पूरा हुआ। कुछ रिकॉर्ड पर ध्यान देने की ज़रूरत है"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "मात्रा विभाजन बिंदु जिन पर इस पंक्ति की कीमत है; प्रत्येक कॉलम क्रेता-आपूर्तिकर्ता बातचीत और डाउनस्ट्रीम दस्तावेजों में परिवर्तित करने के लिए अपनी स्वयं की प्रति-यूनिट कीमत रखता है।"
@@ -21892,6 +21916,12 @@ msgstr "टाइमर चल रहा है"
msgid "Timezone"
msgstr "समय क्षेत्र"
+msgid "Tip away from you"
+msgstr "अपनी ओर से दूर झुकाएँ"
+
+msgid "Tip toward you"
+msgstr "अपनी ओर झुकाएँ"
+
msgid "Title"
msgstr "शीर्षक"
@@ -22272,7 +22302,7 @@ msgid "Triggers"
msgstr "ट्रिगर"
msgid "Try a different name."
-msgstr ""
+msgstr "कोई दूसरा नाम आज़माएँ."
msgid "Tuesday"
msgstr "मंगलवार"
@@ -22765,6 +22795,15 @@ msgstr "अपलोड हो रहा है…"
msgid "Upon clicking Convert, parts will be created with the following internal part numbers:"
msgstr "परिवर्तित करें क्लिक करने पर, पार्ट्स निम्नलिखित आंतरिक पार्ट संख्या के साथ बनाए जाएंगे:"
+msgid "Upright"
+msgstr "सीधा"
+
+msgid "Upside down"
+msgstr "उल्टा"
+
+msgid "Upside down, from step {orientationSource}"
+msgstr "चरण {orientationSource} से उल्टा"
+
msgid "URL"
msgstr "यूआरएल"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index ca1779146f..8d1212e97c 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# operazione senza standard di tempo} other {# operazio
#. placeholder {0}: issues.length
msgid "{0, plural, one {# record needs attention} other {# records need attention}}"
-msgstr ""
+msgstr "{0, plural, one {# record richiede attenzione} other {# record richiedono attenzione}}"
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
@@ -405,7 +405,7 @@ msgid "{count} units"
msgstr "{count} unità"
msgid "{created} created, {updated} updated."
-msgstr ""
+msgstr "{created} creati, {updated} aggiornati."
msgid "{days}d"
msgstr "{days}g"
@@ -432,7 +432,7 @@ msgid "{from}–{to} of {count} operations"
msgstr "{from}–{to} di {count} operazioni"
msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"
-msgstr ""
+msgstr "{hidden, plural, one {E # altro record.} other {E altri # record.}}"
msgid "{hiddenCount} more: {hiddenNames}"
msgstr "{hiddenCount} altri: {hiddenNames}"
@@ -9495,6 +9495,9 @@ msgstr "Unità della flotta"
msgid "Fleet Units"
msgstr "Unità flotta"
+msgid "Flip over"
+msgstr "Capovolgi"
+
msgid "For <0/>"
msgstr "Per <0/>"
@@ -10228,6 +10231,9 @@ msgstr "Come viene decisa la dimensione del campione — Ispeziona Tutto, Ispezi
msgid "How the unit price of each quantity was calculated."
msgstr "Come il prezzo unitario di ogni quantità è stato calcolato."
+msgid "How the whole build is turned on a step, such as flipped to fit parts on its underside. Later steps of the same build keep it until a step turns the build again."
+msgstr "Come viene orientato l'intero assemblato in un passo, ad esempio capovolto per montare componenti sul lato inferiore. I passi successivi dello stesso assemblato mantengono questo orientamento finché un passo non ruota di nuovo l'assemblato."
+
msgid "How this gauge is used — Standard (regular checks) or Master (calibrates other gauges)."
msgstr "Come viene utilizzato questo strumento di misurazione: Standard (controlli regolari) o Master (calibra altri strumenti)."
@@ -11389,10 +11395,10 @@ msgstr "Cognome"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr ""
+msgstr "L'ultimo invio {when} non è riuscito: {0}"
msgid "Last push {when}:"
-msgstr ""
+msgstr "Ultimo invio {when}:"
msgid "Last Quarter"
msgstr "Ultimo Trimestre"
@@ -11401,7 +11407,7 @@ msgid "Last Run"
msgstr "Ultima esecuzione"
msgid "Last scheduled push {when}:"
-msgstr ""
+msgstr "Ultimo invio pianificato {when}:"
msgid "Last synced: <0/>"
msgstr "Ultimo sincronismo: <0/>"
@@ -12551,7 +12557,7 @@ msgid "More overtime"
msgstr "Più straordinario"
msgid "More records are waiting. Push again to continue."
-msgstr ""
+msgstr "Ci sono altri record in attesa. Invia di nuovo per continuare."
msgid "Morning, {name}."
msgstr "Mattino, {name}."
@@ -12566,7 +12572,7 @@ msgid "Motion"
msgstr "Movimento"
msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."
-msgstr ""
+msgstr "Mount ha {matches} record con questo identificativo. Elimina o unisci quelli in più in Mount, quindi invia di nuovo."
msgid "Move"
msgstr "Sposta"
@@ -13284,7 +13290,7 @@ msgid "No comments yet. Be the first to add a comment."
msgstr "Nessun commento ancora. Sii il primo ad aggiungere un commento."
msgid "No companies match \"{query}\""
-msgstr ""
+msgstr "Nessuna azienda corrisponde a «{query}»"
msgid "No completed jobs within range"
msgstr "Nessun ordine di produzione completato entro l'intervallo"
@@ -14069,6 +14075,12 @@ msgstr "Giacenza: da {before} a {after}"
msgid "On Hold"
msgstr "In Sospeso"
+msgid "On its side"
+msgstr "Sul fianco"
+
+msgid "On its side, from step {orientationSource}"
+msgstr "Sul fianco, dal passo {orientationSource}"
+
msgid "On Jobs"
msgstr "Su Ordini di produzione"
@@ -14590,6 +14602,9 @@ msgstr "Ordini"
msgid "Orders submitted"
msgstr "Ordini inviati"
+msgid "Orientation"
+msgstr "Orientamento"
+
msgid "Origin"
msgstr "Origine"
@@ -18255,7 +18270,7 @@ msgid "Search fields..."
msgstr "Cerca campi..."
msgid "Search for a company"
-msgstr ""
+msgstr "Cerca un'azienda"
msgid "Search for existing or create a new one"
msgstr "Cerca uno esistente o creane uno nuovo"
@@ -19425,6 +19440,12 @@ msgstr "Articoli Specifici"
msgid "Spend by supplier, item, or category — your biggest cost drivers"
msgstr "Spesa per fornitore, articolo o categoria — i tuoi principali driver di costo"
+msgid "Spin left"
+msgstr "Ruota a sinistra"
+
+msgid "Spin right"
+msgstr "Ruota a destra"
+
msgid "Split"
msgstr "Dividi"
@@ -19520,7 +19541,7 @@ msgid "Started"
msgstr "Iniziato"
msgid "Starting"
-msgstr ""
+msgstr "Avvio in corso"
msgid "Starting…"
msgstr "Avvio in corso…"
@@ -20894,6 +20915,9 @@ msgstr "I tipi di materiale in base ai quali organizzi il tuo stock"
msgid "The model is still loading."
msgstr "Il modello si sta ancora caricando."
+msgid "The model isn't ready yet"
+msgstr "Il modello non è ancora pronto"
+
msgid "The month your financial year begins; periods are numbered from this month."
msgstr "Il mese in cui inizia il vostro anno fiscale; i periodi sono numerati a partire da questo mese."
@@ -21047,16 +21071,16 @@ msgid "The purchase order"
msgstr "L'ordine di acquisto"
msgid "The push to Mount did not start. Try again."
-msgstr ""
+msgstr "L'invio a Mount non è stato avviato. Riprova."
msgid "The push to Mount failed"
-msgstr ""
+msgstr "L'invio a Mount non è riuscito"
msgid "The push to Mount finished"
-msgstr ""
+msgstr "L'invio a Mount è terminato"
msgid "The push to Mount finished. Some records need attention"
-msgstr ""
+msgstr "L'invio a Mount è terminato. Alcuni record richiedono attenzione"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "I punti di rottura della quantità a cui questa riga è quotata; ogni colonna ha il proprio prezzo unitario per la negoziazione acquirente-fornitore e per la conversione a documenti a valle."
@@ -21892,6 +21916,12 @@ msgstr "Timer in esecuzione"
msgid "Timezone"
msgstr "Fuso orario"
+msgid "Tip away from you"
+msgstr "Inclina lontano da te"
+
+msgid "Tip toward you"
+msgstr "Inclina verso di te"
+
msgid "Title"
msgstr "Titolo"
@@ -22272,7 +22302,7 @@ msgid "Triggers"
msgstr "Trigger"
msgid "Try a different name."
-msgstr ""
+msgstr "Prova un nome diverso."
msgid "Tuesday"
msgstr "Martedì"
@@ -22765,6 +22795,15 @@ msgstr "Caricamento in corso…"
msgid "Upon clicking Convert, parts will be created with the following internal part numbers:"
msgstr "Facendo clic su Converti, i componenti verranno creati con i seguenti numeri di parte interni:"
+msgid "Upright"
+msgstr "In piedi"
+
+msgid "Upside down"
+msgstr "Sottosopra"
+
+msgid "Upside down, from step {orientationSource}"
+msgstr "Sottosopra, dal passo {orientationSource}"
+
msgid "URL"
msgstr "URL"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index efef9940d5..0b459de346 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# 工程に標準時間がない} other {# 工程に標
#. placeholder {0}: issues.length
msgid "{0, plural, one {# record needs attention} other {# records need attention}}"
-msgstr ""
+msgstr "{0, plural, one {# 件のレコードに確認が必要です} other {# 件のレコードに確認が必要です}}"
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
@@ -405,7 +405,7 @@ msgid "{count} units"
msgstr "{count} 個"
msgid "{created} created, {updated} updated."
-msgstr ""
+msgstr "{created}件作成、{updated}件更新。"
msgid "{days}d"
msgstr "{days}日"
@@ -432,7 +432,7 @@ msgid "{from}–{to} of {count} operations"
msgstr "{from}–{to} / {count} 件の工程"
msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"
-msgstr ""
+msgstr "{hidden, plural, one {ほか # 件のレコードがあります。} other {ほか # 件のレコードがあります。}}"
msgid "{hiddenCount} more: {hiddenNames}"
msgstr "{hiddenCount} 件さらに表示: {hiddenNames}"
@@ -9495,6 +9495,9 @@ msgstr "フリートユニット"
msgid "Fleet Units"
msgstr "フリート個"
+msgid "Flip over"
+msgstr "裏返す"
+
msgid "For <0/>"
msgstr "用<0/>"
@@ -10228,6 +10231,9 @@ msgstr "サンプルサイズがどのように決定されるか—すべてを
msgid "How the unit price of each quantity was calculated."
msgstr "各数量の単価がどのように計算されたか。"
+msgid "How the whole build is turned on a step, such as flipped to fit parts on its underside. Later steps of the same build keep it until a step turns the build again."
+msgstr "ステップ内でアセンブリ全体の向きを変えます。たとえば、底面に部品を取り付けるために裏返す場合などです。同じアセンブリの後続ステップは、別のステップで向きが変わるまでこの向きを維持します。"
+
msgid "How this gauge is used — Standard (regular checks) or Master (calibrates other gauges)."
msgstr "この測定器の使用方法 — なみ検査(通常のチェック)または標準器(他の測定器を校正)"
@@ -11389,10 +11395,10 @@ msgstr "姓"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr ""
+msgstr "前回の{when}の送信は失敗しました: {0}"
msgid "Last push {when}:"
-msgstr ""
+msgstr "前回の送信 {when}:"
msgid "Last Quarter"
msgstr "前四半期"
@@ -11401,7 +11407,7 @@ msgid "Last Run"
msgstr "最終実行"
msgid "Last scheduled push {when}:"
-msgstr ""
+msgstr "前回のスケジュール送信 {when}:"
msgid "Last synced: <0/>"
msgstr "最後に同期: <0/>"
@@ -12551,7 +12557,7 @@ msgid "More overtime"
msgstr "残業を増やす"
msgid "More records are waiting. Push again to continue."
-msgstr ""
+msgstr "他にもレコードがあります。続けるには再度送信してください。"
msgid "Morning, {name}."
msgstr "朝、{name}さん。"
@@ -12566,7 +12572,7 @@ msgid "Motion"
msgstr "モーション"
msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."
-msgstr ""
+msgstr "Mountには、この識別子を持つレコードが{matches}件あります。Mountで余分なレコードを削除または統合してから、再度送信してください。"
msgid "Move"
msgstr "移動"
@@ -13284,7 +13290,7 @@ msgid "No comments yet. Be the first to add a comment."
msgstr "まだコメントがありません。最初のコメントを追加してください。"
msgid "No companies match \"{query}\""
-msgstr ""
+msgstr "「{query}」に一致する会社がありません"
msgid "No completed jobs within range"
msgstr "範囲内に完了した製造指図がありません"
@@ -14069,6 +14075,12 @@ msgstr "手持在庫: {before} から {after}"
msgid "On Hold"
msgstr "保留中"
+msgid "On its side"
+msgstr "横向き"
+
+msgid "On its side, from step {orientationSource}"
+msgstr "{orientationSource}のステップから横向き"
+
msgid "On Jobs"
msgstr "製造指図に対して"
@@ -14590,6 +14602,9 @@ msgstr "注文"
msgid "Orders submitted"
msgstr "注文が送信されました"
+msgid "Orientation"
+msgstr "向き"
+
msgid "Origin"
msgstr "オリジン"
@@ -18255,7 +18270,7 @@ msgid "Search fields..."
msgstr "フィールドを検索..."
msgid "Search for a company"
-msgstr ""
+msgstr "会社を検索"
msgid "Search for existing or create a new one"
msgstr "既存のものを検索するか、新しいものを作成してください"
@@ -19425,6 +19440,12 @@ msgstr "特定の品目"
msgid "Spend by supplier, item, or category — your biggest cost drivers"
msgstr "仕入先、品目、またはカテゴリ別の支出 — 最大の原価ドライバー"
+msgid "Spin left"
+msgstr "左に回転"
+
+msgid "Spin right"
+msgstr "右に回転"
+
msgid "Split"
msgstr "分割"
@@ -19520,7 +19541,7 @@ msgid "Started"
msgstr "開始"
msgid "Starting"
-msgstr ""
+msgstr "開始中"
msgid "Starting…"
msgstr "開始中…"
@@ -20894,6 +20915,9 @@ msgstr "あなたが在庫を整理する材料タイプ"
msgid "The model is still loading."
msgstr "モデルはまだ読み込み中です。"
+msgid "The model isn't ready yet"
+msgstr "モデルはまだ準備できていません"
+
msgid "The month your financial year begins; periods are numbered from this month."
msgstr "財務年度が開始される月。期間はこの月から番号が付けられます。"
@@ -21047,16 +21071,16 @@ msgid "The purchase order"
msgstr "発注書"
msgid "The push to Mount did not start. Try again."
-msgstr ""
+msgstr "Mountへの送信を開始できませんでした。もう一度お試しください。"
msgid "The push to Mount failed"
-msgstr ""
+msgstr "Mountへの送信に失敗しました"
msgid "The push to Mount finished"
-msgstr ""
+msgstr "Mountへの送信が完了しました"
msgid "The push to Mount finished. Some records need attention"
-msgstr ""
+msgstr "Mountへの送信が完了しました。一部のレコードに確認が必要です"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "この明細が価格設定される数量ブレークポイント。各列は買い手と仕入先の交渉および下流文書への変換用に、独自の単価を持ちます。"
@@ -21892,6 +21916,12 @@ msgstr "タイマー実行中"
msgid "Timezone"
msgstr "タイムゾーン"
+msgid "Tip away from you"
+msgstr "奥に傾ける"
+
+msgid "Tip toward you"
+msgstr "手前に傾ける"
+
msgid "Title"
msgstr "タイトル"
@@ -22272,7 +22302,7 @@ msgid "Triggers"
msgstr "トリガー"
msgid "Try a different name."
-msgstr ""
+msgstr "別の名前を試してください。"
msgid "Tuesday"
msgstr "火曜日"
@@ -22765,6 +22795,15 @@ msgstr "アップロード中…"
msgid "Upon clicking Convert, parts will be created with the following internal part numbers:"
msgstr "変換をクリックすると、以下の社内部品番号で部品が作成されます:"
+msgid "Upright"
+msgstr "正立"
+
+msgid "Upside down"
+msgstr "逆さま"
+
+msgid "Upside down, from step {orientationSource}"
+msgstr "{orientationSource}のステップから逆さま"
+
msgid "URL"
msgstr "URL"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 5d020c8b86..2fcae4e1af 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# 공정에 표준시간이 없습니다} other {# 공
#. placeholder {0}: issues.length
msgid "{0, plural, one {# record needs attention} other {# records need attention}}"
-msgstr ""
+msgstr "{0}개 레코드에 확인이 필요합니다"
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
@@ -405,7 +405,7 @@ msgid "{count} units"
msgstr "{count}개"
msgid "{created} created, {updated} updated."
-msgstr ""
+msgstr "{created}개 생성, {updated}개 업데이트."
msgid "{days}d"
msgstr "{days}일"
@@ -432,7 +432,7 @@ msgid "{from}–{to} of {count} operations"
msgstr "{from}–{to}/{count} 공정"
msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"
-msgstr ""
+msgstr "그 외 {hidden}개 레코드가 더 있습니다."
msgid "{hiddenCount} more: {hiddenNames}"
msgstr "{hiddenCount}개 추가: {hiddenNames}"
@@ -9495,6 +9495,9 @@ msgstr "플릿 단위"
msgid "Fleet Units"
msgstr "플릿 단위"
+msgid "Flip over"
+msgstr "뒤집기"
+
msgid "For <0/>"
msgstr "대상 <0/>"
@@ -10228,6 +10231,9 @@ msgstr "샘플 크기를 결정하는 방식 — 전수 검사, 처음 N개 검
msgid "How the unit price of each quantity was calculated."
msgstr "각 수량의 단가를 계산한 방법"
+msgid "How the whole build is turned on a step, such as flipped to fit parts on its underside. Later steps of the same build keep it until a step turns the build again."
+msgstr "단계에서 전체 빌드를 돌리는 방향입니다(예: 아랫면에 부품을 끼우기 위해 뒤집기). 같은 빌드의 이후 단계는 다른 단계에서 빌드를 다시 돌릴 때까지 이 방향을 유지합니다."
+
msgid "How this gauge is used — Standard (regular checks) or Master (calibrates other gauges)."
msgstr "이 계측기의 사용 방식 — 보통 검사(정기 점검) 또는 표준기(다른 계측기 교정)."
@@ -11389,10 +11395,10 @@ msgstr "성"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr ""
+msgstr "마지막 전송 {when} 실패: {0}"
msgid "Last push {when}:"
-msgstr ""
+msgstr "마지막 전송 {when}:"
msgid "Last Quarter"
msgstr "지난 분기"
@@ -11401,7 +11407,7 @@ msgid "Last Run"
msgstr "마지막 실행"
msgid "Last scheduled push {when}:"
-msgstr ""
+msgstr "마지막 예약 전송 {when}:"
msgid "Last synced: <0/>"
msgstr "마지막 동기화: <0/>"
@@ -12551,7 +12557,7 @@ msgid "More overtime"
msgstr "초과 근무 증가"
msgid "More records are waiting. Push again to continue."
-msgstr ""
+msgstr "전송 대기 중인 레코드가 더 있습니다. 계속하려면 다시 전송하세요."
msgid "Morning, {name}."
msgstr "{name}님, 아침이군요."
@@ -12566,7 +12572,7 @@ msgid "Motion"
msgstr "모션"
msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."
-msgstr ""
+msgstr "Mount에 이 식별자를 가진 레코드가 {matches}개 있습니다. Mount에서 초과 레코드를 삭제하거나 병합한 뒤 다시 전송하세요."
msgid "Move"
msgstr "이동"
@@ -13284,7 +13290,7 @@ msgid "No comments yet. Be the first to add a comment."
msgstr "아직 댓글이 없습니다. 첫 번째 댓글을 추가하세요."
msgid "No companies match \"{query}\""
-msgstr ""
+msgstr "“{query}”와 일치하는 회사가 없습니다"
msgid "No completed jobs within range"
msgstr "범위 내에 완료된 작업 지시가 없습니다"
@@ -14069,6 +14075,12 @@ msgstr "보유수량: {before}에서 {after}(으)로"
msgid "On Hold"
msgstr "보류"
+msgid "On its side"
+msgstr "옆으로 눕힘"
+
+msgid "On its side, from step {orientationSource}"
+msgstr "단계 {orientationSource}에서 옆으로 눕힘"
+
msgid "On Jobs"
msgstr "작업 지시에"
@@ -14590,6 +14602,9 @@ msgstr "주문"
msgid "Orders submitted"
msgstr "제출된 주문"
+msgid "Orientation"
+msgstr "방향"
+
msgid "Origin"
msgstr "출처"
@@ -18255,7 +18270,7 @@ msgid "Search fields..."
msgstr "필드 검색..."
msgid "Search for a company"
-msgstr ""
+msgstr "회사 검색"
msgid "Search for existing or create a new one"
msgstr "기존 항목을 검색하거나 새로 생성하세요"
@@ -19425,6 +19440,12 @@ msgstr "특정 품목"
msgid "Spend by supplier, item, or category — your biggest cost drivers"
msgstr "공급업체, 품목 또는 카테고리별 지출 — 주요 원가 요인"
+msgid "Spin left"
+msgstr "왼쪽으로 회전"
+
+msgid "Spin right"
+msgstr "오른쪽으로 회전"
+
msgid "Split"
msgstr "분할"
@@ -19520,7 +19541,7 @@ msgid "Started"
msgstr "시작됨"
msgid "Starting"
-msgstr ""
+msgstr "시작 중"
msgid "Starting…"
msgstr "시작 중…"
@@ -20894,6 +20915,9 @@ msgstr "재고를 분류하는 자재 유형"
msgid "The model is still loading."
msgstr "모델이 여전히 로드 중입니다."
+msgid "The model isn't ready yet"
+msgstr "모델이 아직 준비되지 않았습니다"
+
msgid "The month your financial year begins; periods are numbered from this month."
msgstr "귀사 회계연도가 시작되는 월입니다. 기간은 이 월부터 번호가 매겨집니다."
@@ -21047,16 +21071,16 @@ msgid "The purchase order"
msgstr "발주서"
msgid "The push to Mount did not start. Try again."
-msgstr ""
+msgstr "Mount로의 전송을 시작하지 못했습니다. 다시 시도하세요."
msgid "The push to Mount failed"
-msgstr ""
+msgstr "Mount로의 전송에 실패했습니다"
msgid "The push to Mount finished"
-msgstr ""
+msgstr "Mount로의 전송이 완료되었습니다"
msgid "The push to Mount finished. Some records need attention"
-msgstr ""
+msgstr "Mount로의 전송이 완료되었습니다. 일부 레코드에 확인이 필요합니다"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "이 라인의 가격 책정 수량 구간점; 각 열은 구매자-공급업체 협상 및 다운스트림 문서로 변환하기 위한 자체 단가를 포함합니다."
@@ -21892,6 +21916,12 @@ msgstr "타이머 실행 중"
msgid "Timezone"
msgstr "시간대"
+msgid "Tip away from you"
+msgstr "몸에서 멀어지는 방향으로 기울이기"
+
+msgid "Tip toward you"
+msgstr "몸 쪽으로 기울이기"
+
msgid "Title"
msgstr "제목"
@@ -22272,7 +22302,7 @@ msgid "Triggers"
msgstr "트리거"
msgid "Try a different name."
-msgstr ""
+msgstr "다른 이름을 입력하세요."
msgid "Tuesday"
msgstr "화요일"
@@ -22765,6 +22795,15 @@ msgstr "업로드 중…"
msgid "Upon clicking Convert, parts will be created with the following internal part numbers:"
msgstr "전환을 클릭하면 다음의 내부 부품 번호로 부품이 생성됩니다:"
+msgid "Upright"
+msgstr "똑바로 세움"
+
+msgid "Upside down"
+msgstr "거꾸로"
+
+msgid "Upside down, from step {orientationSource}"
+msgstr "단계 {orientationSource}에서 거꾸로"
+
msgid "URL"
msgstr "URL"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 5db53f233f..cf33450832 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# operacja nie ma standardów czasu} few {# operacje ni
#. placeholder {0}: issues.length
msgid "{0, plural, one {# record needs attention} other {# records need attention}}"
-msgstr ""
+msgstr "{0, plural, one {# rekord wymaga uwagi} few {# rekordy wymagają uwagi} many {# rekordów wymaga uwagi} other {# rekordu wymaga uwagi}}"
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
@@ -405,7 +405,7 @@ msgid "{count} units"
msgstr "{count} sztuk"
msgid "{created} created, {updated} updated."
-msgstr ""
+msgstr "Utworzono: {created}, zaktualizowano: {updated}."
msgid "{days}d"
msgstr "{days}d"
@@ -432,7 +432,7 @@ msgid "{from}–{to} of {count} operations"
msgstr "{from}–{to} z {count} operacji"
msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"
-msgstr ""
+msgstr "{hidden, plural, one {I jeszcze # rekord.} few {I jeszcze # rekordy.} many {I jeszcze # rekordów.} other {I jeszcze # rekordu.}}"
msgid "{hiddenCount} more: {hiddenNames}"
msgstr "{hiddenCount} więcej: {hiddenNames}"
@@ -9495,6 +9495,9 @@ msgstr "Sztuka floty"
msgid "Fleet Units"
msgstr "Sztuki floty"
+msgid "Flip over"
+msgstr "Przewróć"
+
msgid "For <0/>"
msgstr "Dla <0/>"
@@ -10228,6 +10231,9 @@ msgstr "Jak decyduje się o wielkości próbki — Sprawdzić Wszystko, Sprawdzi
msgid "How the unit price of each quantity was calculated."
msgstr "Jak obliczona została cena jednostkowa każdej ilości."
+msgid "How the whole build is turned on a step, such as flipped to fit parts on its underside. Later steps of the same build keep it until a step turns the build again."
+msgstr "Jak cały zespół jest obrócony w danym kroku, np. przewrócony, aby dopasować części od spodu. Kolejne kroki tego samego zespołu zachowują to ułożenie, dopóki któryś krok ponownie nie obróci zespołu."
+
msgid "How this gauge is used — Standard (regular checks) or Master (calibrates other gauges)."
msgstr "Jak ten przyrząd pomiarowy jest używany — Normalna (regularne sprawdzenia) czy Wzorzec (wzorcuje inne przyrządy pomiarowe)."
@@ -11389,10 +11395,10 @@ msgstr "Nazwisko"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr ""
+msgstr "Ostatnie wysłanie {when} nie powiodło się: {0}"
msgid "Last push {when}:"
-msgstr ""
+msgstr "Ostatnie wysłanie {when}:"
msgid "Last Quarter"
msgstr "Ostatni kwartał"
@@ -11401,7 +11407,7 @@ msgid "Last Run"
msgstr "Ostatnie uruchomienie"
msgid "Last scheduled push {when}:"
-msgstr ""
+msgstr "Ostatnie zaplanowane wysłanie {when}:"
msgid "Last synced: <0/>"
msgstr "Ostatnia synchronizacja: <0/>"
@@ -12551,7 +12557,7 @@ msgid "More overtime"
msgstr "Więcej nadgodzin"
msgid "More records are waiting. Push again to continue."
-msgstr ""
+msgstr "Czekają kolejne rekordy. Wyślij ponownie, aby kontynuować."
msgid "Morning, {name}."
msgstr "Poranek, {name}."
@@ -12566,7 +12572,7 @@ msgid "Motion"
msgstr "Ruch"
msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."
-msgstr ""
+msgstr "Rekordy z tym identyfikatorem w Mount: {matches}. Usuń lub scal nadmiarowe rekordy w Mount, a następnie wyślij ponownie."
msgid "Move"
msgstr "Przenieś"
@@ -13284,7 +13290,7 @@ msgid "No comments yet. Be the first to add a comment."
msgstr "Brak komentarzy. Bądź pierwszy i dodaj komentarz."
msgid "No companies match \"{query}\""
-msgstr ""
+msgstr "Brak firm pasujących do „{query}”"
msgid "No completed jobs within range"
msgstr "Nie znaleziono zakończonych zleceń produkcyjnych w danym zakresie"
@@ -14069,6 +14075,12 @@ msgstr "W magazynie: z {before} na {after}"
msgid "On Hold"
msgstr "Wstrzymane"
+msgid "On its side"
+msgstr "Na boku"
+
+msgid "On its side, from step {orientationSource}"
+msgstr "Na boku, od kroku {orientationSource}"
+
msgid "On Jobs"
msgstr "Na zleceniach produkcyjnych"
@@ -14590,6 +14602,9 @@ msgstr "Zamówienia"
msgid "Orders submitted"
msgstr "Zamówienia przesłane"
+msgid "Orientation"
+msgstr "Orientacja"
+
msgid "Origin"
msgstr "Pochodzenie"
@@ -18255,7 +18270,7 @@ msgid "Search fields..."
msgstr "Wyszukaj pola..."
msgid "Search for a company"
-msgstr ""
+msgstr "Szukaj firmy"
msgid "Search for existing or create a new one"
msgstr "Wyszukaj istniejący lub utwórz nowy"
@@ -19425,6 +19440,12 @@ msgstr "Określone artykuły"
msgid "Spend by supplier, item, or category — your biggest cost drivers"
msgstr "Wydatki według dostawcy, pozycji lub kategorii — Twoje największe czynniki kosztowe"
+msgid "Spin left"
+msgstr "Obróć w lewo"
+
+msgid "Spin right"
+msgstr "Obróć w prawo"
+
msgid "Split"
msgstr "Podziel"
@@ -19520,7 +19541,7 @@ msgid "Started"
msgstr "Rozpoczęto"
msgid "Starting"
-msgstr ""
+msgstr "Uruchamianie"
msgid "Starting…"
msgstr "Uruchamianie…"
@@ -20894,6 +20915,9 @@ msgstr "Typy materiałów, według których organizujesz swoje zapasy"
msgid "The model is still loading."
msgstr "Model jest wciąż ładowany."
+msgid "The model isn't ready yet"
+msgstr "Model nie jest jeszcze gotowy"
+
msgid "The month your financial year begins; periods are numbered from this month."
msgstr "Miesiąc, w którym rozpoczyna się Twój rok obrachunkowy; okresy są numerowane od tego miesiąca."
@@ -21047,16 +21071,16 @@ msgid "The purchase order"
msgstr "Zamówienie zakupu"
msgid "The push to Mount did not start. Try again."
-msgstr ""
+msgstr "Wysłanie do Mount nie zostało uruchomione. Spróbuj ponownie."
msgid "The push to Mount failed"
-msgstr ""
+msgstr "Wysłanie do Mount nie powiodło się"
msgid "The push to Mount finished"
-msgstr ""
+msgstr "Wysłanie do Mount zakończone"
msgid "The push to Mount finished. Some records need attention"
-msgstr ""
+msgstr "Wysłanie do Mount zakończone. Niektóre rekordy wymagają uwagi"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "Punkty graniczne ilości, przy których ta pozycja jest wyceniona; każda kolumna nosi własną cenę za sztukę do negocjacji kupiec–dostawca i do konwersji na dokumenty następujące."
@@ -21892,6 +21916,12 @@ msgstr "Czasomierz uruchomiony"
msgid "Timezone"
msgstr "Strefa czasowa"
+msgid "Tip away from you"
+msgstr "Przechyl od siebie"
+
+msgid "Tip toward you"
+msgstr "Przechyl do siebie"
+
msgid "Title"
msgstr "Tytuł"
@@ -22272,7 +22302,7 @@ msgid "Triggers"
msgstr "Wyzwalacze"
msgid "Try a different name."
-msgstr ""
+msgstr "Spróbuj innej nazwy."
msgid "Tuesday"
msgstr "Wtorek"
@@ -22765,6 +22795,15 @@ msgstr "Przesyłanie…"
msgid "Upon clicking Convert, parts will be created with the following internal part numbers:"
msgstr "Po kliknięciu Przekształć części zostaną utworzone z następującymi wewnętrznymi numerami części:"
+msgid "Upright"
+msgstr "W pionie"
+
+msgid "Upside down"
+msgstr "Do góry nogami"
+
+msgid "Upside down, from step {orientationSource}"
+msgstr "Do góry nogami, od kroku {orientationSource}"
+
msgid "URL"
msgstr "URL"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 50c575e658..babdfb07c4 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# operação não tem padrões de tempo} other {# opera
#. placeholder {0}: issues.length
msgid "{0, plural, one {# record needs attention} other {# records need attention}}"
-msgstr ""
+msgstr "{0, plural, one {# registro precisa de atenção} other {# registros precisam de atenção}}"
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
@@ -405,7 +405,7 @@ msgid "{count} units"
msgstr "{count} unidades"
msgid "{created} created, {updated} updated."
-msgstr ""
+msgstr "{created} criados, {updated} atualizados."
msgid "{days}d"
msgstr "{days}d"
@@ -432,7 +432,7 @@ msgid "{from}–{to} of {count} operations"
msgstr "{from}–{to} de {count} operações"
msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"
-msgstr ""
+msgstr "{hidden, plural, one {E mais # registro.} other {E mais # registros.}}"
msgid "{hiddenCount} more: {hiddenNames}"
msgstr "{hiddenCount} mais: {hiddenNames}"
@@ -9495,6 +9495,9 @@ msgstr "Unidade de frota"
msgid "Fleet Units"
msgstr "Unidades da Frota"
+msgid "Flip over"
+msgstr "Virar"
+
msgid "For <0/>"
msgstr "Para <0/>"
@@ -10228,6 +10231,9 @@ msgstr "Como o tamanho da amostra é decidido — Inspecionar Tudo, Inspecionar
msgid "How the unit price of each quantity was calculated."
msgstr "Como o preço unitário de cada quantidade foi calculado."
+msgid "How the whole build is turned on a step, such as flipped to fit parts on its underside. Later steps of the same build keep it until a step turns the build again."
+msgstr "Como o conjunto inteiro fica posicionado em uma etapa, por exemplo virado para encaixar peças na parte de baixo. As etapas seguintes do mesmo conjunto mantêm essa posição até que uma etapa gire o conjunto novamente."
+
msgid "How this gauge is used — Standard (regular checks) or Master (calibrates other gauges)."
msgstr "Como este instrumento de medição é usado — Normal (verificações regulares) ou Padrão (calibra outros instrumentos de medição)."
@@ -11389,10 +11395,10 @@ msgstr "Sobrenome"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr ""
+msgstr "Último envio {when} falhou: {0}"
msgid "Last push {when}:"
-msgstr ""
+msgstr "Último envio {when}:"
msgid "Last Quarter"
msgstr "Último Trimestre"
@@ -11401,7 +11407,7 @@ msgid "Last Run"
msgstr "Última execução"
msgid "Last scheduled push {when}:"
-msgstr ""
+msgstr "Último envio agendado {when}:"
msgid "Last synced: <0/>"
msgstr "Última sincronização: <0/>"
@@ -12551,7 +12557,7 @@ msgid "More overtime"
msgstr "Mais horas extras"
msgid "More records are waiting. Push again to continue."
-msgstr ""
+msgstr "Há mais registros aguardando. Envie novamente para continuar."
msgid "Morning, {name}."
msgstr "Bom dia, {name}."
@@ -12566,7 +12572,7 @@ msgid "Motion"
msgstr "Movimento"
msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."
-msgstr ""
+msgstr "O Mount tem {matches} registros com este identificador. Exclua ou mescle os registros extras no Mount e envie novamente."
msgid "Move"
msgstr "Mover"
@@ -13284,7 +13290,7 @@ msgid "No comments yet. Be the first to add a comment."
msgstr "Sem comentários ainda. Seja o primeiro a adicionar um comentário."
msgid "No companies match \"{query}\""
-msgstr ""
+msgstr "Nenhuma empresa corresponde a “{query}”"
msgid "No completed jobs within range"
msgstr "Nenhuma ordem de produção concluída dentro do intervalo"
@@ -14069,6 +14075,12 @@ msgstr "Em mão: de {before} para {after}"
msgid "On Hold"
msgstr "Suspenso"
+msgid "On its side"
+msgstr "De lado"
+
+msgid "On its side, from step {orientationSource}"
+msgstr "De lado, a partir da etapa {orientationSource}"
+
msgid "On Jobs"
msgstr "Em ordens de produção"
@@ -14590,6 +14602,9 @@ msgstr "Pedidos"
msgid "Orders submitted"
msgstr "Pedidos enviados"
+msgid "Orientation"
+msgstr "Orientação"
+
msgid "Origin"
msgstr "Origem"
@@ -18255,7 +18270,7 @@ msgid "Search fields..."
msgstr "Pesquisar campos..."
msgid "Search for a company"
-msgstr ""
+msgstr "Pesquisar uma empresa"
msgid "Search for existing or create a new one"
msgstr "Pesquisar um existente ou criar um novo"
@@ -19425,6 +19440,12 @@ msgstr "Itens Específicos"
msgid "Spend by supplier, item, or category — your biggest cost drivers"
msgstr "Gastos por fornecedor, item ou categoria — seus maiores impulsionadores de custo"
+msgid "Spin left"
+msgstr "Girar para a esquerda"
+
+msgid "Spin right"
+msgstr "Girar para a direita"
+
msgid "Split"
msgstr "Dividir"
@@ -19520,7 +19541,7 @@ msgid "Started"
msgstr "Iniciado"
msgid "Starting"
-msgstr ""
+msgstr "Iniciando"
msgid "Starting…"
msgstr "Iniciando…"
@@ -20894,6 +20915,9 @@ msgstr "Os tipos de material pelos quais você organiza seu estoque"
msgid "The model is still loading."
msgstr "O modelo ainda está carregando."
+msgid "The model isn't ready yet"
+msgstr "O modelo ainda não está pronto"
+
msgid "The month your financial year begins; periods are numbered from this month."
msgstr "O mês em que seu ano fiscal começa; os períodos são numerados a partir deste mês."
@@ -21047,16 +21071,16 @@ msgid "The purchase order"
msgstr "O pedido de compra"
msgid "The push to Mount did not start. Try again."
-msgstr ""
+msgstr "O envio ao Mount não foi iniciado. Tente novamente."
msgid "The push to Mount failed"
-msgstr ""
+msgstr "O envio ao Mount falhou"
msgid "The push to Mount finished"
-msgstr ""
+msgstr "O envio ao Mount foi concluído"
msgid "The push to Mount finished. Some records need attention"
-msgstr ""
+msgstr "O envio ao Mount foi concluído. Alguns registros precisam de atenção"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "Os pontos de ruptura de quantidade em que essa linha é precificada; cada coluna possui seu próprio preço por unidade para negociação comprador-fornecedor e conversão para documentos posteriores."
@@ -21892,6 +21916,12 @@ msgstr "Cronômetro em execução"
msgid "Timezone"
msgstr "Fuso Horário"
+msgid "Tip away from you"
+msgstr "Inclinar para longe de você"
+
+msgid "Tip toward you"
+msgstr "Inclinar em sua direção"
+
msgid "Title"
msgstr "Título"
@@ -22272,7 +22302,7 @@ msgid "Triggers"
msgstr "Acionadores"
msgid "Try a different name."
-msgstr ""
+msgstr "Tente um nome diferente."
msgid "Tuesday"
msgstr "Terça-feira"
@@ -22765,6 +22795,15 @@ msgstr "Enviando…"
msgid "Upon clicking Convert, parts will be created with the following internal part numbers:"
msgstr "Ao clicar em Converter, as peças serão criadas com os seguintes números de peça internos:"
+msgid "Upright"
+msgstr "Em pé"
+
+msgid "Upside down"
+msgstr "De cabeça para baixo"
+
+msgid "Upside down, from step {orientationSource}"
+msgstr "De cabeça para baixo, a partir da etapa {orientationSource}"
+
msgid "URL"
msgstr "URL"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 1a9795d34b..9d6f173640 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# операция не имеет временных
#. placeholder {0}: issues.length
msgid "{0, plural, one {# record needs attention} other {# records need attention}}"
-msgstr ""
+msgstr "{0, plural, one {# запись требует внимания} few {# записи требуют внимания} many {# записей требуют внимания} other {# записей требуют внимания}}"
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
@@ -405,7 +405,7 @@ msgid "{count} units"
msgstr "{count} единиц"
msgid "{created} created, {updated} updated."
-msgstr ""
+msgstr "Создано: {created}, обновлено: {updated}."
msgid "{days}d"
msgstr "{days}д"
@@ -432,7 +432,7 @@ msgid "{from}–{to} of {count} operations"
msgstr "{from}–{to} из {count} операций"
msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"
-msgstr ""
+msgstr "{hidden, plural, one {И ещё # запись.} few {И ещё # записи.} many {И ещё # записей.} other {И ещё # записей.}}"
msgid "{hiddenCount} more: {hiddenNames}"
msgstr "{hiddenCount} еще: {hiddenNames}"
@@ -9495,6 +9495,9 @@ msgstr "Единица парка"
msgid "Fleet Units"
msgstr "Единицы флота"
+msgid "Flip over"
+msgstr "Перевернуть"
+
msgid "For <0/>"
msgstr "На <0/>"
@@ -10228,6 +10231,9 @@ msgstr "Как определяется объем выборки — прове
msgid "How the unit price of each quantity was calculated."
msgstr "Как была рассчитана цена за единицу для каждого количества."
+msgid "How the whole build is turned on a step, such as flipped to fit parts on its underside. Later steps of the same build keep it until a step turns the build again."
+msgstr "Как вся сборка повернута на шаге, например перевернута, чтобы установить детали на её нижней стороне. Следующие шаги этой сборки сохраняют положение, пока какой-либо шаг снова не повернёт сборку."
+
msgid "How this gauge is used — Standard (regular checks) or Master (calibrates other gauges)."
msgstr "Как используется это средство измерения — Нормальный (регулярные проверки) или Эталон (калибрует другие средства измерения)."
@@ -11389,10 +11395,10 @@ msgstr "Фамилия"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr ""
+msgstr "Последняя отправка {when} завершилась ошибкой: {0}"
msgid "Last push {when}:"
-msgstr ""
+msgstr "Последняя отправка {when}:"
msgid "Last Quarter"
msgstr "Последний квартал"
@@ -11401,7 +11407,7 @@ msgid "Last Run"
msgstr "Последний запуск"
msgid "Last scheduled push {when}:"
-msgstr ""
+msgstr "Последняя плановая отправка {when}:"
msgid "Last synced: <0/>"
msgstr "Последняя синхронизация: <0/>"
@@ -12551,7 +12557,7 @@ msgid "More overtime"
msgstr "Больше переработки"
msgid "More records are waiting. Push again to continue."
-msgstr ""
+msgstr "Есть ещё записи в очереди. Отправьте снова, чтобы продолжить."
msgid "Morning, {name}."
msgstr "Доброе утро, {name}."
@@ -12566,7 +12572,7 @@ msgid "Motion"
msgstr "Движение"
msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."
-msgstr ""
+msgstr "В Mount есть {matches} записей с этим идентификатором. Удалите или объедините лишние записи в Mount, затем отправьте снова."
msgid "Move"
msgstr "Переместить"
@@ -13284,7 +13290,7 @@ msgid "No comments yet. Be the first to add a comment."
msgstr "Нет комментариев. Будьте первым, кто добавит комментарий."
msgid "No companies match \"{query}\""
-msgstr ""
+msgstr "Нет организаций, соответствующих «{query}»"
msgid "No completed jobs within range"
msgstr "Нет завершенных производственных заказов в диапазоне"
@@ -14069,6 +14075,12 @@ msgstr "На складе: с {before} до {after}"
msgid "On Hold"
msgstr "Приостановлено"
+msgid "On its side"
+msgstr "На боку"
+
+msgid "On its side, from step {orientationSource}"
+msgstr "На боку, как на шаге {orientationSource}"
+
msgid "On Jobs"
msgstr "На производственных заказах"
@@ -14590,6 +14602,9 @@ msgstr "Заказы"
msgid "Orders submitted"
msgstr "Заказы отправлены"
+msgid "Orientation"
+msgstr "Ориентация"
+
msgid "Origin"
msgstr "Источник"
@@ -18255,7 +18270,7 @@ msgid "Search fields..."
msgstr "Поиск полей..."
msgid "Search for a company"
-msgstr ""
+msgstr "Поиск организации"
msgid "Search for existing or create a new one"
msgstr "Поиск существующей или создание новой"
@@ -19425,6 +19440,12 @@ msgstr "Конкретные товары"
msgid "Spend by supplier, item, or category — your biggest cost drivers"
msgstr "Расходы по поставщику, номенклатуре или категории — ваши основные факторы затрат"
+msgid "Spin left"
+msgstr "Повернуть влево"
+
+msgid "Spin right"
+msgstr "Повернуть вправо"
+
msgid "Split"
msgstr "Разделить"
@@ -19520,7 +19541,7 @@ msgid "Started"
msgstr "Начал"
msgid "Starting"
-msgstr ""
+msgstr "Запуск"
msgid "Starting…"
msgstr "Начинаю…"
@@ -20894,6 +20915,9 @@ msgstr "Типы материалов, по которым вы организу
msgid "The model is still loading."
msgstr "Модель еще загружается."
+msgid "The model isn't ready yet"
+msgstr "Модель ещё не готова"
+
msgid "The month your financial year begins; periods are numbered from this month."
msgstr "Месяц начала финансового года; периоды нумеруются, начиная с этого месяца."
@@ -21047,16 +21071,16 @@ msgid "The purchase order"
msgstr "Заказ поставщику"
msgid "The push to Mount did not start. Try again."
-msgstr ""
+msgstr "Отправка в Mount не запустилась. Попробуйте ещё раз."
msgid "The push to Mount failed"
-msgstr ""
+msgstr "Отправка в Mount не удалась"
msgid "The push to Mount finished"
-msgstr ""
+msgstr "Отправка в Mount завершена"
msgid "The push to Mount finished. Some records need attention"
-msgstr ""
+msgstr "Отправка в Mount завершена. Некоторые записи требуют внимания"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "Точки разрыва по количеству, при которых рассчитывается цена этой строки; каждый столбец содержит свою цену за единицу для переговоров между закупщиком и поставщиком и для преобразования в последующие документы."
@@ -21892,6 +21916,12 @@ msgstr "Таймер запущен"
msgid "Timezone"
msgstr "Часовой пояс"
+msgid "Tip away from you"
+msgstr "Наклонить от себя"
+
+msgid "Tip toward you"
+msgstr "Наклонить к себе"
+
msgid "Title"
msgstr "Название"
@@ -22272,7 +22302,7 @@ msgid "Triggers"
msgstr "Триггеры"
msgid "Try a different name."
-msgstr ""
+msgstr "Попробуйте другое название."
msgid "Tuesday"
msgstr "Вторник"
@@ -22765,6 +22795,15 @@ msgstr "Загрузка…"
msgid "Upon clicking Convert, parts will be created with the following internal part numbers:"
msgstr "При нажатии кнопки «Преобразовать» будут созданы детали со следующими внутренними номерами деталей:"
+msgid "Upright"
+msgstr "Вертикально"
+
+msgid "Upside down"
+msgstr "Вверх ногами"
+
+msgid "Upside down, from step {orientationSource}"
+msgstr "Вверх ногами, как на шаге {orientationSource}"
+
msgid "URL"
msgstr "URL"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 3c9dec609c..07700fa373 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# operasyon için zaman standardı yok} other {# operas
#. placeholder {0}: issues.length
msgid "{0, plural, one {# record needs attention} other {# records need attention}}"
-msgstr ""
+msgstr "{0, plural, one {# kayıt dikkat gerektiriyor} other {# kayıt dikkat gerektiriyor}}"
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
@@ -405,7 +405,7 @@ msgid "{count} units"
msgstr "{count} adet"
msgid "{created} created, {updated} updated."
-msgstr ""
+msgstr "{created} oluşturuldu, {updated} güncellendi."
msgid "{days}d"
msgstr "{days}g"
@@ -432,7 +432,7 @@ msgid "{from}–{to} of {count} operations"
msgstr "{from}–{to} /{count} operasyon"
msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"
-msgstr ""
+msgstr "{hidden, plural, one {Ve # kayıt daha.} other {Ve # kayıt daha.}}"
msgid "{hiddenCount} more: {hiddenNames}"
msgstr "{hiddenCount} daha: {hiddenNames}"
@@ -9495,6 +9495,9 @@ msgstr "Filo Birimi"
msgid "Fleet Units"
msgstr "Filo Adetleri"
+msgid "Flip over"
+msgstr "Ters çevir"
+
msgid "For <0/>"
msgstr "İçin <0/>"
@@ -10228,6 +10231,9 @@ msgstr "Örneklem büyüklüğünün nasıl belirlendiği — Tümünü İncele,
msgid "How the unit price of each quantity was calculated."
msgstr "Her miktarın birim fiyatı nasıl hesaplandığı."
+msgid "How the whole build is turned on a step, such as flipped to fit parts on its underside. Later steps of the same build keep it until a step turns the build again."
+msgstr "Bir adımda tüm montajın nasıl çevrildiği; örneğin alt yüzeyine parça takmak için ters çevrilmesi. Aynı montajın sonraki adımları, bir adım montajı yeniden çevirene kadar bu konumu korur."
+
msgid "How this gauge is used — Standard (regular checks) or Master (calibrates other gauges)."
msgstr "Bu ölçüm aletinin nasıl kullanıldığı — Normal (düzenli kontroller) veya Mastar (diğer ölçüm aletlerini kalibre eder)."
@@ -11389,10 +11395,10 @@ msgstr "Soyadı"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr ""
+msgstr "{when} tarihindeki son gönderim başarısız oldu: {0}"
msgid "Last push {when}:"
-msgstr ""
+msgstr "{when} tarihli son gönderim:"
msgid "Last Quarter"
msgstr "Son Çeyrek"
@@ -11401,7 +11407,7 @@ msgid "Last Run"
msgstr "Son Çalıştırma"
msgid "Last scheduled push {when}:"
-msgstr ""
+msgstr "{when} tarihli son planlı gönderim:"
msgid "Last synced: <0/>"
msgstr "Son senkronizasyon: <0/>"
@@ -12551,7 +12557,7 @@ msgid "More overtime"
msgstr "Daha fazla fazla mesai"
msgid "More records are waiting. Push again to continue."
-msgstr ""
+msgstr "Bekleyen başka kayıtlar var. Devam etmek için yeniden gönderin."
msgid "Morning, {name}."
msgstr "Sabah, {name}."
@@ -12566,7 +12572,7 @@ msgid "Motion"
msgstr "Hareket"
msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."
-msgstr ""
+msgstr "Mount'ta bu tanımlayıcıya sahip {matches} kayıt var. Mount'taki fazla kayıtları sil veya birleştir, ardından yeniden gönder."
msgid "Move"
msgstr "Taşış"
@@ -13284,7 +13290,7 @@ msgid "No comments yet. Be the first to add a comment."
msgstr "Henüz yorum yok. İlk yorumu ekleyin."
msgid "No companies match \"{query}\""
-msgstr ""
+msgstr "“{query}” ile eşleşen şirket yok"
msgid "No completed jobs within range"
msgstr "Aralıkta tamamlanmış İş emri yok"
@@ -14069,6 +14075,12 @@ msgstr "Eldeki: {before} değerinden {after} değerine"
msgid "On Hold"
msgstr "Askıda"
+msgid "On its side"
+msgstr "Yana yatık"
+
+msgid "On its side, from step {orientationSource}"
+msgstr "Yana yatık, {orientationSource} adımından"
+
msgid "On Jobs"
msgstr "İş emirlerinde"
@@ -14590,6 +14602,9 @@ msgstr "Siparişler"
msgid "Orders submitted"
msgstr "Siparişler gönderildi"
+msgid "Orientation"
+msgstr "Yönlendirme"
+
msgid "Origin"
msgstr "Kaynak"
@@ -18255,7 +18270,7 @@ msgid "Search fields..."
msgstr "Alanları ara..."
msgid "Search for a company"
-msgstr ""
+msgstr "Şirket ara"
msgid "Search for existing or create a new one"
msgstr "Mevcut birini arayın veya yeni bir tane oluşturun"
@@ -19425,6 +19440,12 @@ msgstr "Belirli Ürünler"
msgid "Spend by supplier, item, or category — your biggest cost drivers"
msgstr "Tedarikçi, ürün veya kategoriye göre harcama — en büyük maliyet sürücüleriniz"
+msgid "Spin left"
+msgstr "Sola döndür"
+
+msgid "Spin right"
+msgstr "Sağa döndür"
+
msgid "Split"
msgstr "Bölünmüş"
@@ -19520,7 +19541,7 @@ msgid "Started"
msgstr "Başlangıç"
msgid "Starting"
-msgstr ""
+msgstr "Başlatılıyor"
msgid "Starting…"
msgstr "Başlanıyor…"
@@ -20894,6 +20915,9 @@ msgstr "Stok organizasyonunuz için kullandığınız malzeme türleri"
msgid "The model is still loading."
msgstr "Model yükleniyor."
+msgid "The model isn't ready yet"
+msgstr "Model henüz hazır değil"
+
msgid "The month your financial year begins; periods are numbered from this month."
msgstr "Mali yılınızın başladığı ay; dönemler bu aydan itibaren numaralandırılır."
@@ -21047,16 +21071,16 @@ msgid "The purchase order"
msgstr "Satın alma siparişi"
msgid "The push to Mount did not start. Try again."
-msgstr ""
+msgstr "Mount'a gönderim başlamadı. Yeniden deneyin."
msgid "The push to Mount failed"
-msgstr ""
+msgstr "Mount'a gönderim başarısız oldu"
msgid "The push to Mount finished"
-msgstr ""
+msgstr "Mount'a gönderim tamamlandı"
msgid "The push to Mount finished. Some records need attention"
-msgstr ""
+msgstr "Mount'a gönderim tamamlandı. Bazı kayıtlar dikkat gerektiriyor"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "Bu Satırın fiyatlandırıldığı Miktar kırılım noktaları; her sütun Satın almacı–Tedarikçi müzakereleri ve aşağı yönlü belgelere dönüştürme için kendi birim başına Fiyatını taşır."
@@ -21892,6 +21916,12 @@ msgstr "Zamanlayıcı çalışıyor"
msgid "Timezone"
msgstr "Saat Dilim"
+msgid "Tip away from you"
+msgstr "Sizden uzağa eğ"
+
+msgid "Tip toward you"
+msgstr "Size doğru eğ"
+
msgid "Title"
msgstr "Unvan"
@@ -22272,7 +22302,7 @@ msgid "Triggers"
msgstr "Tetikleyiciler"
msgid "Try a different name."
-msgstr ""
+msgstr "Farklı bir ad deneyin."
msgid "Tuesday"
msgstr "Salı"
@@ -22765,6 +22795,15 @@ msgstr "Yükleniyor…"
msgid "Upon clicking Convert, parts will be created with the following internal part numbers:"
msgstr "Dönüştür'e tıklanması durumunda parçalar aşağıdaki dahili parça numaralarıyla oluşturulacaktır:"
+msgid "Upright"
+msgstr "Dik"
+
+msgid "Upside down"
+msgstr "Baş aşağı"
+
+msgid "Upside down, from step {orientationSource}"
+msgstr "Baş aşağı, {orientationSource} adımından"
+
msgid "URL"
msgstr "URL"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 2403334049..6baa7da355 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# 道工序无工时定额} other {# 道工序无工时
#. placeholder {0}: issues.length
msgid "{0, plural, one {# record needs attention} other {# records need attention}}"
-msgstr ""
+msgstr "{0, plural, one {# 条记录需要处理} other {# 条记录需要处理}}"
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
@@ -405,7 +405,7 @@ msgid "{count} units"
msgstr "{count} 件"
msgid "{created} created, {updated} updated."
-msgstr ""
+msgstr "已创建 {created},已更新 {updated}。"
msgid "{days}d"
msgstr "{days}天"
@@ -432,7 +432,7 @@ msgid "{from}–{to} of {count} operations"
msgstr "第{from}–{to}个工序(共{count}个)"
msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"
-msgstr ""
+msgstr "{hidden, plural, one {还有 # 条记录。} other {还有 # 条记录。}}"
msgid "{hiddenCount} more: {hiddenNames}"
msgstr "还有{hiddenCount}个:{hiddenNames}"
@@ -9495,6 +9495,9 @@ msgstr "租赁单位"
msgid "Fleet Units"
msgstr "租赁设备"
+msgid "Flip over"
+msgstr "翻面"
+
msgid "For <0/>"
msgstr "对于 <0/>"
@@ -10228,6 +10231,9 @@ msgstr "样本量如何确定——检验全部、检验前N个、批次百分
msgid "How the unit price of each quantity was calculated."
msgstr "每个数量的单价是如何计算的。"
+msgid "How the whole build is turned on a step, such as flipped to fit parts on its underside. Later steps of the same build keep it until a step turns the build again."
+msgstr "在某一步骤中整个组件的转动方式,例如翻面以便将零件装在其底面。同一组件的后续步骤会保持该方向,直到某一步骤再次转动组件。"
+
msgid "How this gauge is used — Standard (regular checks) or Master (calibrates other gauges)."
msgstr "此量具的用途——正常检验(定期检查)或标准器(校准其他量具)。"
@@ -11389,10 +11395,10 @@ msgstr "姓氏"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr ""
+msgstr "上次推送 {when} 失败:{0}"
msgid "Last push {when}:"
-msgstr ""
+msgstr "上次推送 {when}:"
msgid "Last Quarter"
msgstr "上一季度"
@@ -11401,7 +11407,7 @@ msgid "Last Run"
msgstr "最后运行"
msgid "Last scheduled push {when}:"
-msgstr ""
+msgstr "上次定时推送 {when}:"
msgid "Last synced: <0/>"
msgstr "上次同步: <0/>"
@@ -12551,7 +12557,7 @@ msgid "More overtime"
msgstr "更多加班"
msgid "More records are waiting. Push again to continue."
-msgstr ""
+msgstr "仍有记录等待处理。请再次推送以继续。"
msgid "Morning, {name}."
msgstr "早上,{name}。"
@@ -12566,7 +12572,7 @@ msgid "Motion"
msgstr "运动"
msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."
-msgstr ""
+msgstr "Mount 中有 {matches} 条记录使用此标识。请在 Mount 中删除或合并多余记录,然后再次推送。"
msgid "Move"
msgstr "移动"
@@ -13284,7 +13290,7 @@ msgid "No comments yet. Be the first to add a comment."
msgstr "还没有评论。成为第一个添加评论的人。"
msgid "No companies match \"{query}\""
-msgstr ""
+msgstr "没有与“{query}”匹配的公司"
msgid "No completed jobs within range"
msgstr "范围内没有已完成的工单"
@@ -14069,6 +14075,12 @@ msgstr "现有:从 {before} 到 {after}"
msgid "On Hold"
msgstr "搁置"
+msgid "On its side"
+msgstr "侧放"
+
+msgid "On its side, from step {orientationSource}"
+msgstr "侧放,沿用步骤 {orientationSource}"
+
msgid "On Jobs"
msgstr "在工单上"
@@ -14590,6 +14602,9 @@ msgstr "订单"
msgid "Orders submitted"
msgstr "订单已提交"
+msgid "Orientation"
+msgstr "方向"
+
msgid "Origin"
msgstr "来源"
@@ -18255,7 +18270,7 @@ msgid "Search fields..."
msgstr "搜索字段..."
msgid "Search for a company"
-msgstr ""
+msgstr "搜索公司"
msgid "Search for existing or create a new one"
msgstr "搜索现有问题或创建新问题"
@@ -19425,6 +19440,12 @@ msgstr "特定物料"
msgid "Spend by supplier, item, or category — your biggest cost drivers"
msgstr "按供应商、项目或类别的支出 — 您最大的成本驱动因素"
+msgid "Spin left"
+msgstr "向左旋转"
+
+msgid "Spin right"
+msgstr "向右旋转"
+
msgid "Split"
msgstr "拆分"
@@ -19520,7 +19541,7 @@ msgid "Started"
msgstr "开始于"
msgid "Starting"
-msgstr ""
+msgstr "正在启动"
msgid "Starting…"
msgstr "正在启动…"
@@ -20894,6 +20915,9 @@ msgstr "您用来组织库存的原材料类型"
msgid "The model is still loading."
msgstr "模型正在加载。"
+msgid "The model isn't ready yet"
+msgstr "模型尚未就绪"
+
msgid "The month your financial year begins; periods are numbered from this month."
msgstr "财政年度开始的月份;期间从该月份开始编号。"
@@ -21047,16 +21071,16 @@ msgid "The purchase order"
msgstr "采购订单"
msgid "The push to Mount did not start. Try again."
-msgstr ""
+msgstr "未能开始推送至 Mount。请重试。"
msgid "The push to Mount failed"
-msgstr ""
+msgstr "推送至 Mount 失败"
msgid "The push to Mount finished"
-msgstr ""
+msgstr "推送至 Mount 已完成"
msgid "The push to Mount finished. Some records need attention"
-msgstr ""
+msgstr "推送至 Mount 已完成,部分记录需要处理"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "此行定价的数量断点;每一列都有自己的单位价格,用于采购方–供应商谈判和转换为下游文件。"
@@ -21892,6 +21916,12 @@ msgstr "计时器运行中"
msgid "Timezone"
msgstr "时区"
+msgid "Tip away from you"
+msgstr "向远离你的方向倾斜"
+
+msgid "Tip toward you"
+msgstr "向靠近你的方向倾斜"
+
msgid "Title"
msgstr "标题"
@@ -22272,7 +22302,7 @@ msgid "Triggers"
msgstr "触发器"
msgid "Try a different name."
-msgstr ""
+msgstr "请尝试其他名称。"
msgid "Tuesday"
msgstr "星期二"
@@ -22765,6 +22795,15 @@ msgstr "上传中…"
msgid "Upon clicking Convert, parts will be created with the following internal part numbers:"
msgstr "点击转换后,将使用以下内部零件编号创建零件:"
+msgid "Upright"
+msgstr "直立"
+
+msgid "Upside down"
+msgstr "倒置"
+
+msgid "Upside down, from step {orientationSource}"
+msgstr "倒置,沿用步骤 {orientationSource}"
+
msgid "URL"
msgstr "网址"
diff --git a/packages/viewer/AGENTS.md b/packages/viewer/AGENTS.md
index 67c5abda93..d181c0ea31 100644
--- a/packages/viewer/AGENTS.md
+++ b/packages/viewer/AGENTS.md
@@ -6,15 +6,16 @@
- **graph.json** (`AssemblyGraph`) — assembly tree written by the geometry service `/convert`; leaf nodes carry a stable `nodeId` (also baked into GLB node extras as `userData.nodeId`). All joins between steps, plans, and scene objects are by `nodeId`.
- **plan.json** (`AssemblyPlan`) — per-component insertion `Motion`, sequence, subassembly `groups`, and body-level `contacts`, written by the geometry service `/plan`. `CURRENT_PLAN_VERSION` (currently `3`) — stored plans below it are STALE and must be treated as absent so the pipeline re-plans.
-- **Step** (`AssemblyStep`) — one build instruction: `componentNodeIds`, a `Motion`, optional `camera`, `fastener`, per-step `hiddenComponentNodeIds`, and the sub-assembly fields `isSubAssembly` / `parentStepId` / `usedInStepId`. Built from a plan by `buildAssemblyStepGroups`.
-- **Sub-assemblies** (`subassembly.ts`) — a header step (`isSubAssembly`) groups the steps whose `parentStepId` points at it; those steps sit directly before it in play order and are BUILT ON THEIR OWN: while one is active the player isolates its sub-assembly's parts (focus-style, ancestors kept, not cleared by playback, framed on their own bounds). A header's `usedInStepId` names the later step that carries the finished unit in. A header whose `motion` is not `none` has a path of its own: the unit plays it (`buildStepClip`'s `units`, one after another in sub-assembly order) before the step's own parts move — a step with no animation of its own fades its parts in only after those units seat (`fadeProgress`). `buildCarryPlans` is THE per-step answer to which units fly, which glide, and whether an unused header joins on its own path. Otherwise it glides from beside the build (`CARRY_IN_GLIDE_SECONDS` / `buildStepClip`'s `glide.nodeIds`), then rides the step's insertion; without one the header itself is where the unit joins the main build, and a USED header plays nothing (0-length segment, skipped by prev/next). No nesting — a step USES a finished sub-assembly instead, so chains of any length work. `arrivalIndexByNode(steps, world)` is THE answer to "when does this part appear in the build on screen" and drives visibility; `validateSubAssemblies` is THE structural rule the ERP service and editor share. `scopeStepIds` limits the timeline to an opened sub-assembly.
-- **Motion** — discriminated union `linear | L | helix | path | waypoints | none`. `waypoints` is editor-authored: poses relative to the seated pose, turning about the moving set's seated bounds center (`seatedBoundsCenter`), so one motion fits a part, a rigid group or a sub-assembly. The path editor saves `linear`/`L` until a waypoint is turned (`editorWaypointsToMotion`); it has a Move / Rotate tool (`pathToolLabels` on the player, host-translated — no labels, no switch): Rotate shows drei `TransformControls` rings on the selected waypoint and stops the spheres dragging, because the rings' invisible free-rotation grip sits over the sphere. Insertion motion; the player derives removal (reverse) and start poses. `flagged`/`blockedBy` steps use `none` and fade in (no collision-free path exists — a synthesized path would clip through geometry).
+- **Step** (`AssemblyStep`) — one build instruction: `componentNodeIds`, a `Motion`, optional `camera`, `fastener`, per-step `hiddenComponentNodeIds`, an optional `orientation`, and the sub-assembly fields `isSubAssembly` / `parentStepId` / `usedInStepId`. Built from a plan by `buildAssemblyStepGroups`.
+- **Build orientation** (`orientation.ts`) — a step's `orientation` is a unit quaternion turning the model frame into the bench frame (both Z-up); it holds from that step on within its own build (`resolveOrientations`, keyed by `stepWorlds`: the main build and each sub-assembly keep separate chains, a sub-assembly starts upright). The player shows it as a CAMERA FRAME, never by turning the model — turning a root node would break everything that works in world space (`buildStepClip`, the path editor, box select). `useBuildFrame` owns the frame: `camera.up` = `upForOrientation(q)`, and a new orientation turns the camera, its target and up about the build's center (the framed bounds' center) by `next⁻¹ · applied` over `TURN_MS`, so on screen the build turns over in place (turning about the target swung an off-center build round in an arc). Playback and framing wait for the turn (`isTurning`), and grabbing the controls finishes it. When the center moves (entering or leaving a sub-assembly) the new frame SNAPS instead of turning about the other build's center, and unmounting hands the camera back upright, because the camera outlives a remounted scene. A turned step with no saved view keeps the camera's bench direction (`keptDirection`) rather than re-aiming — any geometry-scored framer undoes a spin, since a spin is just an orbit — and the editor's turn buttons save the current view with the orientation, so playback lands on what the author saw. `keptDirection` (where the camera looks from once the pending turn lands) is the current direction for every step's framing, so stepping back from a turned step to an upright one scores its candidates from the post-turn view, not the pre-turn one. A saved view (`captureCameraPose`; `isSavedView` tells it from a plan hint) is stored in the BENCH frame (`toBench` / `fromBench`, about the same center), so turning a step keeps its view and turns the build; a plan hint is used only on an upright build (it turns with the model); a turn on the active step never re-frames (orientation is not in `framingKey`); drei `GizmoHelper` writes `camera.up` on every frame of a viewcube tween and resets it when the tween ends, so the hook restores the build's up whenever no turn is playing; the framing effect takes the STEP's up, not the mid-turn `camera.up`. `turnOrientation` applies one editor turn (`flip` 180°, `tipForward`/`tipBack`/`spinLeft`/`spinRight` 90°) about a SQUARE bench axis picked from the view and snaps the result to the 24 right-angle orientations (axis by axis, never entry rounding); `describeOrientation` names the pose (upright / upside down / on its side) for the editor.
+- **Sub-assemblies** (`subassembly.ts`) — a header step (`isSubAssembly`) groups the steps whose `parentStepId` points at it; those steps sit directly before it in play order and are BUILT ON THEIR OWN: while one is active the player isolates its sub-assembly's parts (focus-style, ancestors kept, not cleared by playback, framed on their own bounds). A header's `usedInStepId` names the later step that carries the finished unit in. A header whose `motion` is not `none` has a path of its own: the unit plays it (`buildStepClip`'s `units`, one after another in sub-assembly order) before the step's own parts move — a step with no animation of its own fades its parts in only after those units seat (`fadeProgress`). One `stepClipTiming` per step feeds the timeline segment, the clip and the fade delay; while picking components it gives the units and the glide no time. `buildCarryPlans` is THE per-step answer to which units fly (`pathUnits`), which glide, what the step's own insertion moves (`ownMovingPartIds`) and whether the step is an unused header joining on its own path (`joinsOnOwnPath`: that path is the header's motion, so it has no insertion of its own); `carriesUnits` says whether a step brings any unit in. The clip, the fade, the path editor and the framing all read it. Each header's unit parts come from `buildSubAssemblyPlan` (`unitPartIds`). A unit whose header has no path of its own (`motion` `none`) glides from beside the build (`CARRY_IN_GLIDE_SECONDS` / `buildStepClip`'s `glide.nodeIds`), then rides the using step's insertion. A header nothing uses is where its unit joins the main build; a USED header plays nothing (0-length segment, skipped by prev/next). A step whose own insertion moves nothing (`stepClipTiming`'s `ownParts: false`, e.g. a header joining on its own path) gets a slot of just its units and the hold — the fixed `none` slot is for process-only steps and own parts that fade in. No nesting — a step USES a finished sub-assembly instead, so chains of any length work. `arrivalIndexByNode(steps, world)` is THE answer to "when does this part appear in the build on screen" and drives visibility; `validateSubAssemblies` is THE structural rule the ERP service and editor share. `scopeStepIds` limits the timeline to an opened sub-assembly.
+- **Motion** — discriminated union `linear | L | helix | path | waypoints | none`. `waypoints` is editor-authored: poses relative to the seated pose, turning about the moving set's seated bounds center, then shifting (`waypointMatrix`), so one motion fits a part, a rigid group or a sub-assembly. The player takes that center from graph.json's seated bounds for the clip (`buildStepClip`'s required `pivot`), the path editor and the framed start pose alike — the live nodes are mid-animation when framing runs. `resampleEased` keeps every input keyframe (at its eased time) besides its evenly spaced samples, so easing never cuts a turning leg's 15° samples short. The path editor saves `linear`/`L` until a waypoint is turned (`editorWaypointsToMotion`); it has a Move / Rotate tool (`pathToolLabels` on the player, host-translated — no labels, no switch): Rotate shows drei `TransformControls` rings on the selected waypoint and stops the spheres dragging, because the rings' invisible free-rotation grip sits over the sphere. Insertion motion; the player derives removal (reverse) and start poses. `flagged`/`blockedBy` steps use `none` and fade in (no collision-free path exists — a synthesized path would clip through geometry).
- **Artifact tiers** — a model renders from best-available: LOD GLB → optimised GLB → lossless GLB → raw WASM (in-browser occt-import-js) fallback.
## Always
- MUST key everything by `nodeId` — scene objects (`useAssembly` `nodesById`), plan components, and steps all join on it. Stale/unknown nodeIds (post re-upload) are skipped, never assumed.
-- MUST keep the three-free import path clean: server/Inngest code imports plan logic from `@carbon/viewer/steps` (re-exports `buildAssemblyStepGroups`, `assignStepPhases`, `indexAssemblyGraph`, `CURRENT_PLAN_VERSION`), NOT the barrel `.` — the barrel pulls in three.js/R3F.
+- MUST keep the three-free import path clean: server/Inngest code imports plan logic from `@carbon/viewer/steps` (re-exports `buildAssemblyStepGroups`, `assignStepPhases`, `indexAssemblyGraph`, `CURRENT_PLAN_VERSION`, the step flags), NOT the barrel `.` — the barrel pulls in three.js/R3F.
- MUST treat plans below `CURRENT_PLAN_VERSION` as absent (re-plan), never resurrect their motions.
- MUST keep this package free of `@carbon/react` router/i18n peers in the pure/motion/plan modules — `cn` is re-implemented locally in `utils.ts` for that reason. (`ModelPreview.tsx` is the one component that does import `@carbon/react`.)
- MUST prefer server artifacts over the raw tier — the raw WASM fallback renders only when there is no server GLB.
@@ -35,7 +36,7 @@
## Validation Commands
```bash
-pnpm --filter @carbon/viewer test # vitest — camera, fallback, graph, motion, plan, subassembly, visibility
+pnpm --filter @carbon/viewer test # vitest — camera, clip, display, fallback, graph, keyframes, orientation, path-editing, plan, quat, step-flags, subassembly, timing, validate-motion, visibility (shared helpers: src/test-utils.ts)
pnpm --filter @carbon/viewer typecheck # tsgo --noEmit
```
@@ -44,18 +45,18 @@ pnpm --filter @carbon/viewer typecheck # tsgo --noEmit
| Subpath | Provides |
|---------|----------|
| `.` | `AssemblyPlayer` (+ `AssemblyPlayerHandle`/`Props`), `AssemblyViewer`, `ModelCanvas`, all plan/motion/graph/camera/describe/visibility helpers and types |
-| `./steps` | Three-free plan→steps logic for server code: `buildAssemblyStepGroups`, `assignStepPhases`, `indexAssemblyGraph`, `CURRENT_PLAN_VERSION` |
+| `./steps` | Three-free plan→steps logic for server code: `buildAssemblyStepGroups`, `assignStepPhases`, `indexAssemblyGraph`, `CURRENT_PLAN_VERSION`, the sub-assembly structure helpers, and the step flags `isSavedView` / `hasCustomMotion` / `isPlanFlagged` (also on `.`) |
| `./canvas` | `ModelCanvas` — standalone static GLB viewer (orbit + view, no steps) |
| `./model-preview` | `ModelPreview` — progressive multi-tier preview (LOD → optimised → raw WASM), lazy-loads three.js on scroll-into-view |
| `./optimize-progress` | `OptimizeProgress` — optimise-status chip |
| `./use-optimized-model` | `useOptimizedModel` — TanStack Query polling of the model optimise lifecycle (shared by ERP `CadModel` + MES model tab) |
-Key non-exported building blocks: `useAssembly` (loads meshopt GLB + graph.json, indexes nodes by nodeId), `motion.ts` (`buildStepClip`, `motionToKeyframes`, `naturalizeMotion`), `fallback.ts` (`synthesizeFallbackMotion` — AABB escape for legacy `none` motions), `subassembly.ts` (`buildSubAssemblyPlan` / `arrivalIndexByNode` / `validateSubAssemblies` / `usableSubAssemblies` / `displayOrder` — also on `./steps`), `camera.ts` (`fitFraming` — live frustum fit around the planner's baked view direction), `raw/` (WASM fallback tier: `loadRawModel` via occt-import-js).
+Internal modules (no subpath of their own; some of their functions are re-exported from `.`): `useAssembly.ts` (loads meshopt GLB + graph.json, indexes nodes by nodeId), the motion modules — `timing.ts` (`stepClipTiming`, `motionDuration`), `validate-motion.ts` (`isPlayableMotion`, `isFiniteTuple` — shape checks on raw JSON), `keyframes.ts` (`motionToKeyframes`, `resampleEased`, `waypointMatrix`), `clip.ts` (`buildStepClip`), `display.ts` (`displayMotionForStep`, `naturalizeMotion`), `path-editing.ts` (motion ↔ editor waypoints) — plus `step-flags.ts` (`isSavedView` / `hasCustomMotion` / `isPlanFlagged`, three-free and zod-free), `quat.ts` (tuple ↔ three.js helpers, `sameOrientation`), `useBuildFrame.ts` (the build-orientation camera frame), `fallback.ts` (`synthesizeFallbackMotion` — AABB escape for legacy `none` motions), `subassembly.ts` (`buildSubAssemblyPlan` / `buildCarryPlans` / `arrivalIndexByNode` / `validateSubAssemblies` / `usableSubAssemblies` / `displayOrder`), `camera.ts` (`frameStepPose` — the pure per-step framing: direction choice, AABB scoring and frustum fit; `fitFraming` — the frustum fit itself), `raw/` (WASM fallback tier: `loadRawModel` via occt-import-js).
## Cross-References
- **Consumers**: ERP `apps/erp/app/components/CadModel.tsx`, `apps/erp/app/modules/production/ui/Assemblies/*`, route `apps/erp/app/routes/x+/assembly+/$id.tsx`; MES `apps/mes/app/components/AssemblyView.tsx` + `JobOperation`; Inngest `packages/jobs/src/inngest/functions/tasks/assembly-plan.ts` (imports `@carbon/viewer/steps`).
-- **Contracts**: `src/types.ts` is the contract itself (the `docs/specs/animated-work-instructions-contracts.md` it once mirrored no longer exists). The ERP mirrors `Motion` as zod in `motionSchema` (`apps/erp/app/modules/production/production.models.ts`); the MES checks raw rows with `isPlayableMotion`.
+- **Contracts**: `src/types.ts` is the contract itself (the `docs/specs/animated-work-instructions-contracts.md` it once mirrored no longer exists). The ERP mirrors `Motion` as zod in `motionSchema` (`apps/erp/app/modules/production/production.models.ts`); the MES checks raw rows with `isPlayableMotion` (`validate-motion.ts`), which checks every field keyframe generation reads.
- **Model paths / raw limits**: `@carbon/utils` (`modelPathOptimizeFormat`, `MODEL_RAW_KEEP_MAX_BYTES`).
</content>
</invoke>
diff --git a/packages/viewer/src/AssemblyPlayer.tsx b/packages/viewer/src/AssemblyPlayer.tsx
index 96a54eae9f..06fceaa221 100644
--- a/packages/viewer/src/AssemblyPlayer.tsx
+++ b/packages/viewer/src/AssemblyPlayer.tsx
@@ -24,7 +24,6 @@ import {
MeshStandardMaterial,
type Object3D,
PerspectiveCamera,
- Quaternion,
Vector3
} from "three";
import {
@@ -35,35 +34,39 @@ import {
} from "three-mesh-bvh";
import type { OrbitControls as OrbitControlsImpl } from "three-stdlib";
import { AssemblyViewer } from "./AssemblyViewer";
-import { fitFraming } from "./camera";
+import { type FramingOccluder, frameStepPose } from "./camera";
+import { buildStepClip } from "./clip";
import { describeStep, type NamedUnit } from "./describe";
+import { displayMotionForStep, naturalizeMotion } from "./display";
import { indexAssemblyGraph } from "./graph";
import { MotionPathEditor } from "./MotionPathEditor";
-import {
- buildStepClip,
- CARRY_IN_GLIDE_SECONDS,
- displayMotionForStep,
- fadeProgress,
- motionDuration,
- naturalizeMotion,
- seatedBoundsCenter,
- stepClipTiming
-} from "./motion";
+import { resolveOrientations, upForOrientation } from "./orientation";
+import { IDENTITY_QUAT, sameOrientation } from "./quat";
+import { isSavedView } from "./step-flags";
import {
arrivalIndexByNode,
buildCarryPlans,
buildSubAssemblyPlan,
- type PathUnit,
- worldOf
+ type CarryPlan,
+ carriesUnits,
+ stepWorlds
} from "./subassembly";
+import {
+ CARRY_IN_GLIDE_SECONDS,
+ fadeProgress,
+ type StepClipTiming,
+ stepClipTiming
+} from "./timing";
import type {
AssemblyGraph,
AssemblyStep,
CameraPose,
Motion,
+ Quat,
Vec3
} from "./types";
import { useAssembly } from "./useAssembly";
+import { useBuildFrame } from "./useBuildFrame";
import { cn } from "./utils";
import {
ASSEMBLY_VIEWS,
@@ -197,11 +200,7 @@ export type AssemblyPlayerProps = {
isolationLabel?: string | null;
/** Shown next to the isolation label while the active step carries a finished sub-assembly in. */
carryInLabel?: string | null;
- /**
- * Labels for the path editor's Move / Rotate switch (shown while a path is
- * being edited). The host translates them; without them the switch is hidden
- * and waypoints only move.
- */
+ /** Path editor Move / Rotate labels; without them the switch is hidden and waypoints only move. */
pathToolLabels?: { move: string; rotate: string } | null;
mode?: "dark" | "light";
className?: string;
@@ -278,16 +277,16 @@ export const AssemblyPlayer = forwardRef<
// Paused orbiting doesn't change modes (per-step framing already yields to
// the framing-key guard there).
const [cameraMode, setCameraMode] = useState<"auto" | "free">("auto");
- // Path editor tool: drag waypoints to move them, or turn the selected one
- // with rotation rings. Each edit session starts on Move.
- const [pathTool, setPathTool] = useState<PathTool>("move");
- const editKey = editMotion
- ? `${editMotion.stepId}|${editMotion.nodeIds?.[0] ?? "own"}`
- : null;
- // biome-ignore lint/correctness/useExhaustiveDependencies: editKey identifies the edit session; a new session resets the tool
- useEffect(() => {
- setPathTool("move");
- }, [editKey]);
+ // Each path-edit session starts on Move, even when the same path is reopened.
+ const editKey = editMotion ? editSessionKey(editMotion) : null;
+ const [toolChoice, setToolChoice] = useState<{
+ editKey: string | null;
+ tool: PathTool;
+ }>({ editKey: null, tool: "move" });
+ if (editKey === null && toolChoice.editKey !== null) {
+ setToolChoice({ editKey: null, tool: "move" });
+ }
+ const pathTool = toolChoice.editKey === editKey ? toolChoice.tool : "move";
// Stable identity — the scene re-subscribes its controls listener otherwise.
const handleFreeCamera = useCallback(() => setCameraMode("free"), []);
// Exposed as named views, not raw axes: six icon buttons made the reader
@@ -329,15 +328,15 @@ export const AssemblyPlayer = forwardRef<
[graph]
);
- const assemblyDiagonal = useMemo(() => {
- const bbox = graphIndex?.graph.root.bbox;
- if (!bbox) return 0;
- return Math.hypot(
- bbox.max[0] - bbox.min[0],
- bbox.max[1] - bbox.min[1],
- bbox.max[2] - bbox.min[2]
- );
- }, [graphIndex]);
+ const assemblyDiagonal = useMemo(
+ () =>
+ graphIndex
+ ? seatedBox([graphIndex.graph.root.nodeId], graphIndex.nodesById)
+ .getSize(new Vector3())
+ .length()
+ : 0,
+ [graphIndex]
+ );
const stepCount = steps.length;
const clampedIndex = Math.min(Math.max(activeStepIndex, 0), stepCount - 1);
@@ -385,36 +384,18 @@ export const AssemblyPlayer = forwardRef<
// header. Each part therefore arrives at a different step depending on which
// build is on screen — `arrivals` answers that per world.
const subPlan = useMemo(() => buildSubAssemblyPlan(steps), [steps]);
- const stepWorlds = useMemo(
- () => steps.map((step) => worldOf(steps, step.id)),
- [steps]
- );
+ const worlds = useMemo(() => stepWorlds(steps), [steps]);
const arrivals = useMemo(() => {
const byWorld = new Map<string | null, Map<string, number>>();
- for (const world of new Set(stepWorlds)) {
+ for (const world of new Set(worlds.values())) {
byWorld.set(world, arrivalIndexByNode(steps, world));
}
return byWorld;
- }, [steps, stepWorlds]);
- // How each step's carried-in sub-assemblies arrive: on their own path
- // (one after another, before the step's own parts) or gliding in beside
- // the build.
+ }, [steps, worlds]);
const carryPlans = useMemo(
() => buildCarryPlans(steps, subPlan),
[steps, subPlan]
);
- const carriedPartIds = useMemo(
- () => carryPlans.map((plan) => plan.carriedPartIds),
- [carryPlans]
- );
- const pathUnits = useMemo(
- () => carryPlans.map((plan) => plan.pathUnits),
- [carryPlans]
- );
- const glidingPartIds = useMemo(
- () => carryPlans.map((plan) => plan.glidingPartIds),
- [carryPlans]
- );
const scopeSet = useMemo(
() => (scopeStepIds ? new Set(scopeStepIds) : null),
[scopeStepIds]
@@ -447,6 +428,8 @@ export const AssemblyPlayer = forwardRef<
[playable]
);
+ const orientations = useMemo(() => resolveOrientations(steps), [steps]);
+
// Display-only motion adjustments — the stored data is untouched:
// 1. Non-flagged steps saved with motion "none" (legacy plans, manual
// steps) get an AABB-synthesized insertion so components never pop into
@@ -456,120 +439,88 @@ export const AssemblyPlayer = forwardRef<
// insertion reads clearly at assembly scale.
const displaySteps = useMemo(() => {
if (!graphIndex) return steps;
- const root = graphIndex.graph.root.bbox;
- const assemblyDiagonal = Math.hypot(
- root.max[0] - root.min[0],
- root.max[1] - root.min[1],
- root.max[2] - root.min[2]
- );
return steps.map((original, index) => {
- // A step that carries a finished sub-assembly in moves its own parts AND
- // the unit, so every per-step consumer (clip, fallback, framing, hidden
- // list) sees the whole moving set.
- const carried = carriedPartIds[index] ?? [];
+ const plan = carryPlans[index] ?? NO_CARRY;
let step = original;
- // A header whose unit joins on its own path: that path IS the header's
- // motion, and the unit plays it — the header has no insertion of its own.
- if (carryPlans[index]?.joinsOnOwnPath) {
+ if (plan.joinsOnOwnPath) {
step = { ...step, motion: { type: "none" } };
}
- // The step's own insertion moves its own parts plus the gliding units.
- const ownMoving = (glidingPartIds[index] ?? []).length
- ? [
+ const motionBasis = { ...step, componentNodeIds: plan.ownMovingPartIds };
+ // A step that carries a finished sub-assembly in moves its own parts AND
+ // the unit, so every per-step consumer (fallback occluders, framing,
+ // hidden list) sees the whole moving set.
+ if (carriesUnits(plan)) {
+ step = {
+ ...step,
+ componentNodeIds: [
...new Set([
...step.componentNodeIds,
- ...(glidingPartIds[index] ?? [])
+ ...plan.ownMovingPartIds,
+ ...plan.pathUnits.flatMap((unit) => unit.nodeIds)
])
]
- : step.componentNodeIds;
- const motionBasis = { ...step, componentNodeIds: ownMoving };
- if (carried.length > 0) {
- step = {
- ...step,
- componentNodeIds: [...new Set([...step.componentNodeIds, ...carried])]
};
}
// Fallback synthesis sees only the parts already in this step's build —
// what is actually on the canvas when it plays.
- const arrival = arrivals.get(stepWorlds[index] ?? null);
- const world = new Set<string>();
+ const arrival = arrivals.get(worlds.get(step.id) ?? null);
+ const present = new Set<string>();
for (const [nodeId, arrivedAt] of arrival ?? []) {
- if (arrivedAt < index) world.add(nodeId);
+ if (arrivedAt < index) present.add(nodeId);
}
const baseMotion = suppressFallbackMotions
? step.motion
- : displayMotionForStep(motionBasis, index, graphIndex, world);
+ : displayMotionForStep(motionBasis, index, graphIndex, present);
- let minBox: [number, number, number] | null = null;
- let maxBox: [number, number, number] | null = null;
- for (const nodeId of motionBasis.componentNodeIds) {
- const node = graphIndex.nodesById.get(nodeId);
- if (!node) continue;
- if (!minBox || !maxBox) {
- minBox = [...node.bbox.min];
- maxBox = [...node.bbox.max];
- } else {
- for (let axis = 0; axis < 3; axis++) {
- minBox[axis] = Math.min(
- minBox[axis] ?? 0,
- node.bbox.min[axis] ?? 0
- );
- maxBox[axis] = Math.max(
- maxBox[axis] ?? 0,
- node.bbox.max[axis] ?? 0
- );
- }
- }
- }
- if (!minBox || !maxBox) {
- return baseMotion === step.motion
- ? step
- : { ...step, motion: baseMotion };
- }
- const componentDiagonal = Math.hypot(
- maxBox[0] - minBox[0],
- maxBox[1] - minBox[1],
- maxBox[2] - minBox[2]
- );
- const motion = naturalizeMotion(
- baseMotion,
- componentDiagonal,
- assemblyDiagonal
+ const moving = seatedBox(
+ motionBasis.componentNodeIds,
+ graphIndex.nodesById
);
+ const motion = moving.isEmpty()
+ ? baseMotion
+ : naturalizeMotion(
+ baseMotion,
+ moving.getSize(new Vector3()).length(),
+ assemblyDiagonal
+ );
return motion === step.motion ? step : { ...step, motion };
});
}, [
steps,
graphIndex,
suppressFallbackMotions,
- carriedPartIds,
carryPlans,
- glidingPartIds,
arrivals,
- stepWorlds
+ worlds,
+ assemblyDiagonal
]);
// --- Continuous timeline ---------------------------------------------
// A carry-in step also spends the time bringing its units in: each unit's
- // own path, then the glide for the rest. Steps that don't play (a used
- // sub-assembly's header, or outside an opened sub-assembly) take no time.
- const segments = useMemo(
+ // own path, then the glide for the rest. Picking components keeps every
+ // part seated, so then the units and the glide take no time. Steps that
+ // don't play (a used sub-assembly's header, or outside an opened
+ // sub-assembly) take no time.
+ const timings = useMemo(
() =>
- displaySteps.map((step, index) =>
- playable[index]
- ? stepClipTiming(
- step,
- (glidingPartIds[index]?.length ?? 0) > 0
- ? CARRY_IN_GLIDE_SECONDS
- : 0,
- (pathUnits[index] ?? []).map((unit) =>
- motionDuration(unit.motion)
- )
- ).total
- : 0
- ),
- [displaySteps, playable, glidingPartIds, pathUnits]
+ displaySteps.map((step, index) => {
+ const plan = carryPlans[index] ?? NO_CARRY;
+ const carries = !componentPickerActive;
+ return stepClipTiming(step, {
+ glideSeconds:
+ carries && plan.glidingPartIds.length > 0
+ ? CARRY_IN_GLIDE_SECONDS
+ : 0,
+ units: carries ? plan.pathUnits.map((unit) => unit.motion) : [],
+ ownParts: plan.ownMovingPartIds.length > 0
+ });
+ }),
+ [displaySteps, carryPlans, componentPickerActive]
+ );
+ const segments = useMemo(
+ () => timings.map((timing, index) => (playable[index] ? timing.total : 0)),
+ [timings, playable]
);
const startTimes = useMemo(() => {
let elapsed = 0;
@@ -680,36 +631,33 @@ export const AssemblyPlayer = forwardRef<
const activeInfo = activeStep ? subPlan.get(activeStep.id) : undefined;
const isolatePartIds = activeInfo?.isolatePartIds ?? null;
- const activeCarried = carriedPartIds[clampedIndex] ?? NO_NODE_IDS;
- const activeGliding = glidingPartIds[clampedIndex] ?? NO_NODE_IDS;
- const activePathUnits = pathUnits[clampedIndex] ?? NO_PATH_UNITS;
- const activeArrivals = arrivals.get(stepWorlds[clampedIndex] ?? null) ?? null;
+ const activeCarry = carryPlans[clampedIndex] ?? NO_CARRY;
+ const activeGliding = activeCarry.glidingPartIds;
+ const activeArrivals =
+ arrivals.get((activeStep && worlds.get(activeStep.id)) ?? null) ?? null;
// An isolated sub-assembly frames on its own parts, not the whole model.
- const frameBounds = useMemo(() => {
- const root = graphIndex?.graph.root.bbox ?? null;
- if (!graphIndex || !isolatePartIds || isolatePartIds.length === 0) {
- return root;
- }
- return unionBounds(isolatePartIds, graphIndex.nodesById) ?? root;
+ const frameBox = useMemo(() => {
+ if (!graphIndex) return null;
+ const isolated = seatedBox(isolatePartIds ?? [], graphIndex.nodesById);
+ return isolated.isEmpty()
+ ? seatedBox([graphIndex.graph.root.nodeId], graphIndex.nodesById)
+ : isolated;
}, [graphIndex, isolatePartIds]);
// A carried unit with no path of its own glides in from beside the build
// that receives it.
const carryIn = useMemo(() => {
- if (!graphIndex || activeGliding.length === 0 || !frameBounds) return null;
- const unit = unionBounds(activeGliding, graphIndex.nodesById);
- if (!unit) return null;
- const diagonal = Math.hypot(
- frameBounds.max[0] - frameBounds.min[0],
- frameBounds.max[1] - frameBounds.min[1],
- frameBounds.max[2] - frameBounds.min[2]
- );
+ if (!graphIndex || activeGliding.length === 0 || !frameBox) return null;
+ const unit = seatedBox(activeGliding, graphIndex.nodesById);
+ if (unit.isEmpty()) return null;
const offset: Vec3 = [
- frameBounds.max[0] + diagonal * CARRY_IN_GAP_FRACTION - unit.min[0],
+ frameBox.max.x +
+ frameBox.getSize(new Vector3()).length() * CARRY_IN_GAP_FRACTION -
+ unit.min.x,
0,
0
];
return { nodeIds: activeGliding, offset };
- }, [graphIndex, activeGliding, frameBounds]);
+ }, [graphIndex, activeGliding, frameBox]);
const playablePosition = playableIndices.indexOf(clampedIndex);
const prevIndex = nextPlayable(clampedIndex, -1);
const nextIndex = nextPlayable(clampedIndex, 1);
@@ -747,11 +695,11 @@ export const AssemblyPlayer = forwardRef<
readOnly={readOnly}
onSelectComponents={onSelectComponents}
editMotion={editMotion ?? null}
- pathTool={pathToolLabels ? pathTool : "move"}
+ pathTool={pathTool}
onMotionChange={onMotionChange}
assemblyDiagonal={assemblyDiagonal}
capturePoseRef={capturePoseRef}
- assemblyBounds={frameBounds}
+ buildBox={frameBox}
leafBounds={graphIndex?.leaves ?? null}
seatedBoundsById={graphIndex?.nodesById ?? null}
segments={segments}
@@ -767,7 +715,11 @@ export const AssemblyPlayer = forwardRef<
installIndexByNode={activeArrivals}
isolateNodeIds={isolatePartIds}
carryIn={carryIn}
- pathUnits={activePathUnits}
+ carryPlan={activeCarry}
+ timing={timings[clampedIndex] ?? NO_TIMING}
+ orientation={
+ orientations[clampedIndex]?.orientation ?? IDENTITY_QUAT
+ }
/>
)}
</AssemblyViewer>
@@ -781,7 +733,7 @@ export const AssemblyPlayer = forwardRef<
key={tool}
type="button"
aria-pressed={pathTool === tool}
- onClick={() => setPathTool(tool)}
+ onClick={() => setToolChoice({ editKey, tool })}
className={cn(
"rounded-md px-2.5 py-1 transition-colors",
pathTool === tool
@@ -798,7 +750,7 @@ export const AssemblyPlayer = forwardRef<
<div className="pointer-events-none absolute left-1/2 top-3 z-10 flex -translate-x-1/2 items-center gap-2 whitespace-nowrap rounded-full border border-border bg-card px-3 py-1.5 text-xs font-medium text-foreground shadow-lg">
<BoxesIcon />
<span>{isolationLabel}</span>
- {carryInLabel && activeCarried.length > 0 && (
+ {carryInLabel && carriesUnits(activeCarry) && (
<>
<span aria-hidden className="h-3.5 w-px bg-border" />
<span className="text-muted-foreground">{carryInLabel}</span>
@@ -1144,7 +1096,7 @@ function AssemblyScene({
onMotionChange,
assemblyDiagonal,
capturePoseRef,
- assemblyBounds,
+ buildBox,
leafBounds,
seatedBoundsById,
segments,
@@ -1160,7 +1112,9 @@ function AssemblyScene({
installIndexByNode,
isolateNodeIds,
carryIn,
- pathUnits
+ carryPlan,
+ timing,
+ orientation
}: {
scene: Object3D;
nodesById: Map<string, Object3D>;
@@ -1183,8 +1137,11 @@ function AssemblyScene({
assemblyDiagonal: number;
/** The scene writes the live-camera reader here for the imperative handle */
capturePoseRef: React.MutableRefObject<(() => CameraPose | null) | null>;
- /** Seated world bounds from graph.json (stable under animation) */
- assemblyBounds: { min: number[]; max: number[] } | null;
+ /**
+ * Seated bounds of the build on screen, from graph.json (stable under
+ * animation): it sets the standing camera distance and the turn center.
+ */
+ buildBox: Box3 | null;
/** Seated per-leaf bounds for camera occlusion scoring */
leafBounds:
| { nodeId: string; bbox: { min: number[]; max: number[] } }[]
@@ -1229,8 +1186,11 @@ function AssemblyScene({
isolateNodeIds: string[] | null;
/** A finished sub-assembly carried in at the active step, gliding from `offset`. */
carryIn: { nodeIds: string[]; offset: Vec3 } | null;
- /** Carried sub-assemblies joining on their own path, in play order. */
- pathUnits: PathUnit[];
+ carryPlan: CarryPlan;
+ /** The active step's timing — the same one its timeline segment comes from. */
+ timing: StepClipTiming;
+ /** The active step's build orientation: shown as a camera frame. */
+ orientation: Quat;
}) {
const camera = useThree((state) => state.camera);
const controls = useThree(
@@ -1294,25 +1254,32 @@ function AssemblyScene({
editMotion && activeStep && editMotion.stepId === activeStep.id
);
- // Anchor for the editable path: center of the step's components' seated world
- // bounds — the visual center of the object at its final location. Node
- // origins won't do: CAD exports often pivot far from the geometry, which
- // would draw the locked endpoint away from the component. Components sit seated while
- // editing (the clip is skipped below), so world space IS the final pose.
- // The parts the edited path moves: a carried sub-assembly's when editing its
- // path, else the step's own (every part except the units on their own path).
+ // The center a moving set turns about and the path editor anchors on: the
+ // center of its SEATED bounds from graph.json. The clip, the editor and the
+ // framed start pose all use it — the live nodes can't be measured instead,
+ // because the framing runs while a step's parts sit at their start pose.
+ const pivotOf = useCallback(
+ (nodeIds: string[]): Vec3 | null => {
+ const box = seatedBox(nodeIds, seatedBoundsById, nodesById);
+ return box.isEmpty()
+ ? null
+ : (box.getCenter(new Vector3()).toArray() as Vec3);
+ },
+ [seatedBoundsById, nodesById]
+ );
+
const editedNodeIds = useMemo(() => {
if (!isEditingActive || !activeStep) return NO_NODE_IDS;
- if (editMotion?.nodeIds) return editMotion.nodeIds;
- const onPath = new Set(pathUnits.flatMap((unit) => unit.nodeIds));
- return activeStep.componentNodeIds.filter((nodeId) => !onPath.has(nodeId));
- }, [isEditingActive, activeStep, editMotion?.nodeIds, pathUnits]);
+ return editMotion?.nodeIds ?? carryPlan.ownMovingPartIds;
+ }, [
+ isEditingActive,
+ activeStep,
+ editMotion?.nodeIds,
+ carryPlan.ownMovingPartIds
+ ]);
const seatedCentroid = useMemo<Vec3 | null>(
- () =>
- editedNodeIds.length > 0
- ? seatedBoundsCenter(editedNodeIds, nodesById)
- : null,
- [editedNodeIds, nodesById]
+ () => (editedNodeIds.length > 0 ? pivotOf(editedNodeIds) : null),
+ [editedNodeIds, pivotOf]
);
const editedNodes = useMemo(
() =>
@@ -1614,6 +1581,26 @@ function AssemblyScene({
const applyVisualsRef = useRef(applyVisuals);
applyVisualsRef.current = applyVisuals;
+ // The framed build's bounds. Prefer the graph's seated bounds — measuring
+ // the scene mid-animation would inflate the box with displaced components.
+ const assemblyBox = useMemo(
+ () => buildBox ?? new Box3().setFromObject(scene),
+ [buildBox, scene]
+ );
+
+ // The build turns about the center of the bounds it is framed on. Called
+ // before the other frame loops: its turn plays first, and they wait for it.
+ const buildCenter = useMemo(
+ () => assemblyBox.getCenter(new Vector3()),
+ [assemblyBox]
+ );
+ const buildFrame = useBuildFrame({
+ camera,
+ controls,
+ orientation,
+ center: buildCenter
+ });
+
// --- Animation -----------------------------------------------------------
const mixer = useMemo(() => new AnimationMixer(scene), [scene]);
@@ -1642,13 +1629,18 @@ function AssemblyScene({
segmentsLiveRef.current = segments;
const carryInLiveRef = useRef(carryIn);
carryInLiveRef.current = carryIn;
- const pathUnitsLiveRef = useRef(pathUnits);
- pathUnitsLiveRef.current = pathUnits;
+ const carryPlanLiveRef = useRef(carryPlan);
+ carryPlanLiveRef.current = carryPlan;
+ const timingLiveRef = useRef(timing);
+ timingLiveRef.current = timing;
+ const pivotOfLiveRef = useRef(pivotOf);
+ pivotOfLiveRef.current = pivotOf;
// The carry-in glide and the units' paths are part of the signature so a
// change rebuilds the clip.
const carryInKey = carryIn
? JSON.stringify([carryIn.offset, carryIn.nodeIds.length])
: "";
+ const pathUnits = carryPlan.pathUnits;
const pathUnitsKey = pathUnits.length
? JSON.stringify(
pathUnits.map((unit) => [
@@ -1692,33 +1684,37 @@ function AssemblyScene({
if (isEditingActive) return;
// Carried-in sub-assemblies come first: each one with a path of its own
- // flies it, then the rest glide in from beside the build. Picking keeps
- // everything seated: a click must select what the BOM tree shows.
- const carry = componentPickerActive ? null : carryInLiveRef.current;
- const units = componentPickerActive ? [] : pathUnitsLiveRef.current;
- const timing = stepClipTiming(
- step,
- carry ? CARRY_IN_GLIDE_SECONDS : 0,
- units.map((unit) => motionDuration(unit.motion))
- );
- const clip = buildStepClip(step, nodesById, {
- duration: timing.motion,
- holdSeconds: timing.hold,
- units: units.map((unit, index) => ({
- nodeIds: unit.nodeIds,
- motion: unit.motion,
- seconds: timing.units[index] ?? 0
- })),
- ...(carry
- ? {
- glide: {
- offset: carry.offset,
- seconds: timing.glide,
- nodeIds: carry.nodeIds
+ // flies it, then the rest glide in from beside the build. The timing
+ // gives them no time while picking: a click must select what the BOM tree
+ // shows, so everything stays seated.
+ const timing = timingLiveRef.current;
+ const { pathUnits: units, ownMovingPartIds } = carryPlanLiveRef.current;
+ const carry = timing.glide > 0 ? carryInLiveRef.current : null;
+ const pivotOf = pivotOfLiveRef.current;
+ const clip = buildStepClip(
+ { ...step, componentNodeIds: ownMovingPartIds },
+ nodesById,
+ {
+ duration: timing.motion,
+ holdSeconds: timing.hold,
+ pivot: pivotOf(ownMovingPartIds),
+ units: units.slice(0, timing.units.length).map((unit, index) => ({
+ nodeIds: unit.nodeIds,
+ motion: unit.motion,
+ seconds: timing.units[index] ?? 0,
+ pivot: pivotOf(unit.nodeIds)
+ })),
+ ...(carry
+ ? {
+ glide: {
+ offset: carry.offset,
+ seconds: timing.glide,
+ nodeIds: carry.nodeIds
+ }
}
- }
- : {})
- });
+ : {})
+ }
+ );
if (!clip) {
// Nothing to animate (motion "none"), but a static selection must still
// land on "step completed": the seated fade below reads this timer, and
@@ -1833,12 +1829,9 @@ function AssemblyScene({
const overrides = overridesRef.current;
const entries: { mesh: Mesh; fade: Material | Material[] }[] = [];
const materials: Material[] = [];
- const carried = new Set([
- ...(carryIn?.nodeIds ?? []),
- ...pathUnits.flatMap((unit) => unit.nodeIds)
- ]);
- for (const nodeId of step.componentNodeIds) {
- if (carried.has(nodeId)) continue;
+ const gliding = new Set(carryPlan.glidingPartIds);
+ for (const nodeId of carryPlan.ownMovingPartIds) {
+ if (gliding.has(nodeId)) continue;
nodesById.get(nodeId)?.traverse((object) => {
if (!(object as Mesh).isMesh) return;
const mesh = object as Mesh;
@@ -1853,14 +1846,13 @@ function AssemblyScene({
}
if (entries.length === 0) return;
+ // The fade starts once the units have seated, and fits in what is left.
const segment = segments[activeStepIndex] ?? 0;
+ const delay = timing.unitsTotal;
const seconds =
- segment > 0 ? Math.min(FADE_SECONDS, segment) : FADE_SECONDS;
- const delay = stepClipTiming(
- step,
- carryIn ? CARRY_IN_GLIDE_SECONDS : 0,
- pathUnits.map((unit) => motionDuration(unit.motion))
- ).units.reduce((sum, unitSeconds) => sum + unitSeconds, 0);
+ segment > 0
+ ? Math.min(FADE_SECONDS, Math.max(segment - delay, 1e-3))
+ : FADE_SECONDS;
const progress = fadeProgress(
localElapsedRef.current,
delay,
@@ -1887,8 +1879,8 @@ function AssemblyScene({
nodesById,
segments,
editMotion,
- carryIn,
- pathUnits
+ carryPlan,
+ timing
]);
useFrame(() => {
@@ -1912,7 +1904,10 @@ function AssemblyScene({
// MES loop: freeze the animation while the operator manipulates the model
// (orbit/zoom/pan), so they can inspect it without the parts moving; it
// resumes the moment they let go. Only in loop mode — the editor is unaffected.
- const advancing = isPlaying && !(loop && orbitingRef.current);
+ // A step that turns the build holds its parts at the start until the build
+ // has turned over — at the bench you flip the frame, then fit the part.
+ const advancing =
+ isPlaying && !buildFrame.isTurning() && !(loop && orbitingRef.current);
if (advancing) {
mixer.update(delta);
localElapsedRef.current += delta;
@@ -1940,20 +1935,21 @@ function AssemblyScene({
// --- Camera ----------------------------------------------------------------
// Expose a live-camera reader for the "Set view" button (per-step camera).
+ // A saved view is where the viewer stands at the bench, so it is read in the
+ // bench frame: turning the build later keeps the view and turns the build.
useEffect(() => {
capturePoseRef.current = () => {
if (!controls) return null;
- const fov = camera instanceof PerspectiveCamera ? camera.fov : 45;
return {
- position: camera.position.toArray() as Vec3,
- target: controls.target.toArray() as Vec3,
- fov
+ position: buildFrame.toBench(camera.position.clone()).toArray() as Vec3,
+ target: buildFrame.toBench(controls.target.clone()).toArray() as Vec3,
+ fov: camera instanceof PerspectiveCamera ? camera.fov : 45
};
};
return () => {
capturePoseRef.current = null;
};
- }, [camera, controls, capturePoseRef]);
+ }, [camera, controls, capturePoseRef, buildFrame]);
const frameBox = useCallback(
(box: Box3) => {
@@ -1978,27 +1974,13 @@ function AssemblyScene({
[camera, controls]
);
- // The whole-assembly bounds set the standing camera distance: per-step
- // transitions keep this distance and only rotate, so the zoom never jumps
- // between steps. Prefer the graph's seated bounds — measuring the scene
- // mid-animation would inflate the box with displaced components.
- const getAssemblyBox = useCallback((): Box3 => {
- if (assemblyBounds) {
- return new Box3(
- new Vector3(...(assemblyBounds.min as [number, number, number])),
- new Vector3(...(assemblyBounds.max as [number, number, number]))
- );
- }
- return new Box3().setFromObject(scene);
- }, [assemblyBounds, scene]);
-
// Initial framing of the whole assembly
const framedSceneRef = useRef<Object3D | null>(null);
useEffect(() => {
if (!controls || framedSceneRef.current === scene) return;
framedSceneRef.current = scene;
- frameBox(getAssemblyBox());
- }, [scene, controls, frameBox, getAssemblyBox]);
+ frameBox(assemblyBox);
+ }, [scene, controls, frameBox, assemblyBox]);
// Smoothly approached camera pose (per-step rotation); cleared when the
// user grabs the controls so they can take over mid-transition
@@ -2046,6 +2028,8 @@ function AssemblyScene({
// and the distance eases, so the model never leaves the frame the way a
// straight-line position lerp can.
useFrame((_, delta) => {
+ // A turn to a new orientation plays first; framing waits for it.
+ if (buildFrame.isTurning()) return;
const desired = desiredPoseRef.current;
if (!desired || !controls) return;
const alpha = 1 - Math.exp(-delta * 4);
@@ -2087,9 +2071,9 @@ function AssemblyScene({
// the red tint (+ forced visibility) is the feedback. Auto-framing here
// yanked the view away every time a component was picked in the components panel.
- // Per-step camera: explicit pose wins; otherwise keep the standing
- // whole-assembly distance and rotate so the active component and its travel
- // face the camera — the zoom stays steady, only the view angle changes.
+ // Per-step camera: a saved view wins; otherwise keep the standing distance
+ // and turn toward the action (`frameStepPose`) — the zoom stays steady,
+ // only the view angle changes.
useEffect(() => {
const step = steps[activeStepIndex];
if (!step || !controls) return;
@@ -2111,254 +2095,95 @@ function AssemblyScene({
[...hiddenSet].sort().join(","),
carryInKey,
pathUnitsKey,
+ // Not the orientation: a turn plays under a still camera, and re-framing
+ // after it swings the camera along and visibly undoes the turn.
isolateNodeIds?.length ?? 0
].join("|");
if (framingKey === lastFramedKeyRef.current) return;
lastFramedKeyRef.current = framingKey;
- // Manual "Set view" pose — applied verbatim, fov included.
- if (step.camera && !("source" in step.camera)) {
+ // A saved view is applied verbatim, fov included. It is stored in the
+ // bench frame (see the capture above), so it stays put when the build
+ // turns; a plan hint is about the parts and stays in the model frame.
+ const savedView = step.camera;
+ if (isSavedView(savedView)) {
desiredPoseRef.current = {
- position: new Vector3(...step.camera.position),
- target: new Vector3(...step.camera.target)
+ position: buildFrame.fromBench(
+ new Vector3(...savedView.position),
+ orientation
+ ),
+ target: buildFrame.fromBench(
+ new Vector3(...savedView.target),
+ orientation
+ )
};
if (camera instanceof PerspectiveCamera) {
- camera.fov = step.camera.fov;
+ camera.fov = savedView.fov;
camera.updateProjectionMatrix();
}
return;
}
- // Planner-baked view direction: chosen at plan time with sight lines
- // against the real triangles of everything installed earlier — the AABB
- // scoring below can't tell a hollow container's open top from its wall.
- // Target, distance, and the frustum fit still happen live.
- const planDirection =
- step.camera && "source" in step.camera
- ? new Vector3(...step.camera.direction).normalize()
- : null;
-
- if (step.componentNodeIds.length === 0) return;
-
- const assemblyBox = getAssemblyBox().clone();
- if (assemblyBox.isEmpty()) return;
-
- const componentBox = new Box3();
- for (const nodeId of step.componentNodeIds) {
- const seated = seatedBoundsById?.get(nodeId);
- if (seated) {
- componentBox.expandByPoint(
- new Vector3(...(seated.bbox.min as [number, number, number]))
- );
- componentBox.expandByPoint(
- new Vector3(...(seated.bbox.max as [number, number, number]))
- );
+ // Where the camera looks from once any turn to this step's orientation
+ // has landed — the camera itself may still be in the previous frame.
+ const currentDirection = buildFrame.keptDirection(orientation);
+ if (!currentDirection) return;
+ const boxOf = (nodeIds: string[]) =>
+ seatedBox(nodeIds, seatedBoundsById, nodesById);
+ const stepComponents = new Set(step.componentNodeIds);
+ const occluders: FramingOccluder[] = [];
+ for (const leaf of leafBounds ?? []) {
+ if (stepComponents.has(leaf.nodeId) || hiddenSet.has(leaf.nodeId)) {
continue;
}
- const node = nodesById.get(nodeId);
- if (node) componentBox.expandByObject(node);
- }
- if (componentBox.isEmpty()) return;
- // A carried-in unit starts beside the build: keep that spot in frame too.
- const joinShift = carryIn ? new Vector3(...carryIn.offset) : null;
- assemblyBox.union(componentBox);
- if (joinShift) {
- assemblyBox.union(componentBox.clone().translate(joinShift));
- }
- // A unit on its own path starts wherever its path begins, turned as its
- // first waypoint turns it.
- for (const unit of pathUnits) {
- const unitBox = new Box3();
- for (const nodeId of unit.nodeIds) {
- const seated = seatedBoundsById?.get(nodeId);
- if (!seated) continue;
- unitBox.expandByPoint(
- new Vector3(...(seated.bbox.min as [number, number, number]))
- );
- unitBox.expandByPoint(
- new Vector3(...(seated.bbox.max as [number, number, number]))
- );
- }
- const startBox = unitBox.isEmpty()
- ? null
- : startPoseBounds(unitBox, unit.motion);
- if (startBox) assemblyBox.union(startBox);
- }
- const center = assemblyBox.getCenter(new Vector3());
- const radius = assemblyBox.getSize(new Vector3()).length() / 2;
- const fov = camera instanceof PerspectiveCamera ? camera.fov : 45;
- const distance = Math.max(
- (radius / Math.tan(((fov / 2) * Math.PI) / 180)) * 1.25,
- radius * 2
- );
- const componentCenter = componentBox.getCenter(new Vector3());
-
- // Aim mostly at the assembly (context) with a nudge toward the component
- const target = center.clone().lerp(componentCenter, 0.3);
-
- // Where the action happens: the seated body (corners, so a mostly-hidden
- // part scores worse than a clear one) plus the full travel — start,
- // midpoint, and seat.
- const motionDirection = insertionDirection(step.motion);
- const startOffset = insertionStartOffset(step.motion);
- const boxCorner = (box: Box3, i: number, offset: Vector3 | null) => {
- const corner = new Vector3(
- i & 1 ? box.max.x : box.min.x,
- i & 2 ? box.max.y : box.min.y,
- i & 4 ? box.max.z : box.min.z
- );
- return offset ? corner.add(offset) : corner;
- };
- const lookPoints = [componentCenter];
- for (let i = 0; i < 8; i++) {
- lookPoints.push(boxCorner(componentBox, i, null));
- if (joinShift) lookPoints.push(boxCorner(componentBox, i, joinShift));
- }
- if (startOffset) {
- lookPoints.push(
- componentCenter.clone().addScaledVector(startOffset, 0.5)
+ // Invisible geometry must not push the camera around.
+ const weight = occluderWeight(
+ stepIndexByNode.get(leaf.nodeId),
+ activeStepIndex,
+ futureMode,
+ installedMode
);
- lookPoints.push(componentCenter.clone().add(startOffset));
- }
-
- const up = camera.up.clone().normalize();
- let bestDirection: Vector3;
- if (planDirection && planDirection.lengthSq() > 1e-6) {
- bestDirection = planDirection;
- } else {
- // Live fallback (manual/edited steps, plans without directions):
- // AABB-scored candidates. Coarse — it can't see through hollow
- // geometry — which is exactly why generated steps carry a baked
- // direction instead.
- const stepComponents = new Set(step.componentNodeIds);
- const occluders: { min: Vector3; max: Vector3; weight: number }[] = [];
- for (const leaf of leafBounds ?? []) {
- if (stepComponents.has(leaf.nodeId)) continue;
- if (hiddenSet.has(leaf.nodeId)) continue;
- const leafStep = stepIndexByNode.get(leaf.nodeId);
- // Invisible geometry must not push the camera around.
- const weight = occluderWeight(
- leafStep,
- activeStepIndex,
- futureMode,
- installedMode
- );
- if (weight === null) continue;
- occluders.push({
- min: new Vector3(...(leaf.bbox.min as [number, number, number])),
- max: new Vector3(...(leaf.bbox.max as [number, number, number])),
- weight
- });
- }
-
- // Candidate view directions: elevation rings around the up axis, plus
- // the current view. Pick the one that sees the action with the fewest
- // components in the way, preferring lateral travel and small turns.
- let basisU = new Vector3().crossVectors(up, new Vector3(0, 0, 1));
- if (basisU.lengthSq() < 1e-6) {
- basisU = new Vector3().crossVectors(up, new Vector3(1, 0, 0));
- }
- basisU.normalize();
- const basisV = new Vector3().crossVectors(up, basisU).normalize();
-
- const currentDirection = camera.position
- .clone()
- .sub(controls.target)
- .normalize();
- const candidates: Vector3[] = [];
- if (currentDirection.lengthSq() > 1e-6) candidates.push(currentDirection);
- // Third, steeper ring: in dense machines the only clear sight line to a
- // buried part is often from high above.
- for (const elevation of [0.3, 0.55, 0.8]) {
- const horizontal = Math.sqrt(1 - elevation * elevation);
- for (let i = 0; i < 8; i++) {
- const azimuth = (i / 8) * Math.PI * 2;
- candidates.push(
- new Vector3()
- .addScaledVector(basisU, Math.cos(azimuth) * horizontal)
- .addScaledVector(basisV, Math.sin(azimuth) * horizontal)
- .addScaledVector(up, elevation)
- .normalize()
- );
- }
- }
-
- bestDirection = candidates[0] ?? new Vector3(1, 1, 1).normalize();
- let bestScore = Number.POSITIVE_INFINITY;
- for (const candidate of candidates) {
- const eye = target.clone().addScaledVector(candidate, distance);
- let score = 0;
- // How much is in the way of seeing the action?
- for (const point of lookPoints) {
- for (const occluder of occluders) {
- if (segmentIntersectsBox(eye, point, occluder.min, occluder.max)) {
- score += occluder.weight;
- }
- }
- }
- // Prefer travel running across the screen, not into it
- if (motionDirection) {
- score +=
- 4 * Math.max(0, Math.abs(candidate.dot(motionDirection)) - 0.6);
- }
- // Prefer small turns from the current view
- score += 1.75 * (1 - candidate.dot(currentDirection));
- if (score < bestScore) {
- bestScore = score;
- bestDirection = candidate;
- }
- }
- }
-
- // Guarantee the action is entirely in frame: pan the target (and only
- // grow the distance when the action genuinely can't fit) so the seated
- // body plus its travel-start copy sit inside the frustum.
- let right = new Vector3().crossVectors(up, bestDirection);
- if (right.lengthSq() < 1e-6) right = new Vector3(1, 0, 0);
- right.normalize();
- const trueUp = new Vector3().crossVectors(bestDirection, right).normalize();
- const actionPoints: Vector3[] = [];
- for (let i = 0; i < 8; i++) {
- actionPoints.push(boxCorner(componentBox, i, null));
- if (joinShift) actionPoints.push(boxCorner(componentBox, i, joinShift));
- if (startOffset)
- actionPoints.push(boxCorner(componentBox, i, startOffset));
+ if (weight === null) continue;
+ occluders.push({
+ min: new Vector3().fromArray(leaf.bbox.min),
+ max: new Vector3().fromArray(leaf.bbox.max),
+ weight
+ });
}
- const rel = new Vector3();
- const camPoints: Vec3[] = actionPoints.map((point) => {
- rel.copy(point).sub(target);
- return [rel.dot(right), rel.dot(trueUp), rel.dot(bestDirection)];
+ const pose = frameStepPose({
+ buildBox: assemblyBox,
+ ownBox: boxOf(carryPlan.ownMovingPartIds),
+ motion: step.motion,
+ pathUnits: carryPlan.pathUnits.map((unit) => ({
+ box: boxOf(unit.nodeIds),
+ motion: unit.motion
+ })),
+ glideStartBox: carryIn
+ ? boxOf(carryIn.nodeIds).translate(new Vector3(...carryIn.offset))
+ : null,
+ occluders,
+ // The step's own up — mid-turn, `camera.up` is still on its way there.
+ up: new Vector3(...upForOrientation(orientation)),
+ currentDirection,
+ turned: !sameOrientation(orientation, IDENTITY_QUAT),
+ planDirection:
+ step.camera && "source" in step.camera
+ ? new Vector3(...step.camera.direction)
+ : null,
+ fov: camera instanceof PerspectiveCamera ? camera.fov : 45,
+ aspect:
+ camera instanceof PerspectiveCamera && camera.aspect > 0
+ ? camera.aspect
+ : 16 / 9
});
- const aspect =
- camera instanceof PerspectiveCamera && camera.aspect > 0
- ? camera.aspect
- : 16 / 9;
- const tanHalfV = Math.tan(((fov / 2) * Math.PI) / 180);
- const fit = fitFraming(
- camPoints,
- tanHalfV * aspect,
- tanHalfV,
- 0.85,
- distance
- );
- const framedTarget = target
- .clone()
- .addScaledVector(right, fit.pan[0])
- .addScaledVector(trueUp, fit.pan[1]);
-
- desiredPoseRef.current = {
- position: framedTarget
- .clone()
- .addScaledVector(bestDirection, fit.distance),
- target: framedTarget
- };
+ if (pose) desiredPoseRef.current = pose;
}, [
steps,
activeStepIndex,
nodesById,
camera,
controls,
- getAssemblyBox,
+ assemblyBox,
leafBounds,
seatedBoundsById,
hiddenSet,
@@ -2368,9 +2193,11 @@ function AssemblyScene({
cameraMode,
carryIn,
carryInKey,
- pathUnits,
+ carryPlan,
pathUnitsKey,
- isolateNodeIds
+ isolateNodeIds,
+ orientation,
+ buildFrame
]);
// --- Selection -------------------------------------------------------------
@@ -2634,7 +2461,7 @@ function AssemblyScene({
/>
{isEditingActive && editMotion && onMotionChange && seatedCentroid && (
<MotionPathEditor
- key={`${editMotion.stepId}|${editMotion.nodeIds?.[0] ?? "own"}`}
+ key={editSessionKey(editMotion)}
motion={editMotion.motion}
seatedPosition={seatedCentroid}
scale={assemblyDiagonal}
@@ -2648,136 +2475,31 @@ function AssemblyScene({
}
/**
- * Does the open segment from `origin` to `end` pass through the AABB?
- * Slab clipping; ignores grazing contact right at the endpoint so a box
- * around the look-at point does not count as occluding itself.
+ * Seated world bounds of the nodes: graph.json's, which hold still while the
+ * parts animate; a node missing from the graph is measured live when its
+ * scene node is given. Empty when none resolve.
*/
-function segmentIntersectsBox(
- origin: Vector3,
- end: Vector3,
- min: Vector3,
- max: Vector3
-): boolean {
- let tMin = 0;
- let tMax = 0.98; // stop just short of the look-at point
- const axes = ["x", "y", "z"] as const;
- for (const axis of axes) {
- const delta = end[axis] - origin[axis];
- if (Math.abs(delta) < 1e-9) {
- if (origin[axis] < min[axis] || origin[axis] > max[axis]) return false;
+function seatedBox(
+ nodeIds: string[],
+ seatedBoundsById: ReadonlyMap<
+ string,
+ { bbox: { min: number[]; max: number[] } }
+ > | null,
+ nodesById?: Map<string, Object3D>
+): Box3 {
+ const box = new Box3();
+ const point = new Vector3();
+ for (const nodeId of nodeIds) {
+ const seated = seatedBoundsById?.get(nodeId);
+ if (seated) {
+ box.expandByPoint(point.fromArray(seated.bbox.min));
+ box.expandByPoint(point.fromArray(seated.bbox.max));
continue;
}
- let tNear = (min[axis] - origin[axis]) / delta;
- let tFar = (max[axis] - origin[axis]) / delta;
- if (tNear > tFar) [tNear, tFar] = [tFar, tNear];
- tMin = Math.max(tMin, tNear);
- tMax = Math.min(tMax, tFar);
- if (tMin > tMax) return false;
- }
- return true;
-}
-
-/**
- * Bounds of a set at the start of its motion: the seated box shifted by the
- * start offset, and for a `waypoints` motion first turned about its center as
- * the first waypoint turns it. Null when the motion has no start offset.
- */
-function startPoseBounds(
- seated: Box3,
- motion: AssemblyStep["motion"]
-): Box3 | null {
- const startOffset = insertionStartOffset(motion);
- if (!startOffset) return null;
- const first = motion.type === "waypoints" ? motion.waypoints[0] : undefined;
- if (!first) return seated.clone().translate(startOffset);
- const rotation = new Quaternion(...first.rotation).normalize();
- const center = seated.getCenter(new Vector3());
- const turned = new Box3();
- for (let i = 0; i < 8; i++) {
- turned.expandByPoint(
- new Vector3(
- i & 1 ? seated.max.x : seated.min.x,
- i & 2 ? seated.max.y : seated.min.y,
- i & 4 ? seated.max.z : seated.min.z
- )
- .sub(center)
- .applyQuaternion(rotation)
- .add(center)
- .add(startOffset)
- );
- }
- return turned;
-}
-
-/**
- * Where a component starts relative to its seated pose for the given insertion
- * motion. Null when the motion does not translate the component.
- */
-function insertionStartOffset(motion: AssemblyStep["motion"]): Vector3 | null {
- switch (motion.type) {
- case "linear": {
- const direction = new Vector3(...motion.direction).normalize();
- return direction.multiplyScalar(-motion.distance);
- }
- case "L": {
- const offset = new Vector3();
- for (const segment of motion.segments) {
- const direction = new Vector3(...segment.direction).normalize();
- offset.addScaledVector(direction, -segment.distance);
- }
- return offset;
- }
- case "helix": {
- const axis = new Vector3(...motion.axis).normalize();
- const travel = motion.approach + motion.pitch * motion.turns;
- return axis.multiplyScalar(-travel);
- }
- case "waypoints": {
- const first = motion.waypoints[0];
- return first ? new Vector3(...first.offset) : null;
- }
- default:
- return null;
- }
-}
-
-/**
- * The dominant travel direction of an insertion motion (used to pick a
- * camera angle where the motion reads laterally). Null for motions that
- * do not translate the component.
- */
-function insertionDirection(motion: AssemblyStep["motion"]): Vector3 | null {
- switch (motion.type) {
- case "linear":
- return new Vector3(...motion.direction).normalize();
- case "L": {
- let longest: Vector3 | null = null;
- let longestDistance = 0;
- for (const segment of motion.segments) {
- if (Math.abs(segment.distance) > longestDistance) {
- longestDistance = Math.abs(segment.distance);
- longest = new Vector3(...segment.direction);
- }
- }
- return longest ? longest.normalize() : null;
- }
- case "helix":
- return new Vector3(...motion.axis).normalize();
- case "waypoints": {
- // The longest leg, in travel order (start → seat).
- let longest: Vector3 | null = null;
- for (let i = 1; i < motion.waypoints.length; i++) {
- const from = motion.waypoints[i - 1];
- const to = motion.waypoints[i];
- if (!from || !to) continue;
- const leg = new Vector3(...to.offset).sub(new Vector3(...from.offset));
- if (leg.lengthSq() > (longest?.lengthSq() ?? 1e-12)) longest = leg;
- }
- return longest ? longest.normalize() : null;
- }
- default:
- return null;
+ const node = nodesById?.get(nodeId);
+ if (node) box.expandByObject(node);
}
+ return box;
}
function formatTime(seconds: number): string {
@@ -3158,31 +2880,19 @@ const CARRY_IN_GAP_FRACTION = 0.25;
/** Stable empty list, so memos keyed on "no ids" don't churn. */
const NO_NODE_IDS: string[] = [];
-type PathTool = "move" | "rotate";
+const NO_CARRY: CarryPlan = {
+ pathUnits: [],
+ glidingPartIds: [],
+ ownMovingPartIds: [],
+ joinsOnOwnPath: false
+};
-const NO_PATH_UNITS: PathUnit[] = [];
+const NO_TIMING: StepClipTiming = stepClipTiming({ motion: { type: "none" } });
-/** Seated world bounds of the given nodes, from graph.json; null when none resolve. */
-function unionBounds(
- nodeIds: string[],
- nodesById: ReadonlyMap<string, { bbox: { min: Vec3; max: Vec3 } }>
-): { min: Vec3; max: Vec3 } | null {
- let min: Vec3 | null = null;
- let max: Vec3 | null = null;
- for (const nodeId of nodeIds) {
- const node = nodesById.get(nodeId);
- if (!node) continue;
- if (!min || !max) {
- min = [...node.bbox.min];
- max = [...node.bbox.max];
- continue;
- }
- for (let axis = 0; axis < 3; axis++) {
- min[axis] = Math.min(min[axis] ?? 0, node.bbox.min[axis] ?? 0);
- max[axis] = Math.max(max[axis] ?? 0, node.bbox.max[axis] ?? 0);
- }
- }
- return min && max ? { min, max } : null;
+type PathTool = "move" | "rotate";
+
+function editSessionKey(edit: EditMotion): string {
+ return `${edit.stepId}|${edit.nodeIds?.[0] ?? "own"}`;
}
function BoxesIcon() {
diff --git a/packages/viewer/src/MotionPathEditor.tsx b/packages/viewer/src/MotionPathEditor.tsx
index ce5c5eaf9d..94272cead8 100644
--- a/packages/viewer/src/MotionPathEditor.tsx
+++ b/packages/viewer/src/MotionPathEditor.tsx
@@ -14,7 +14,6 @@ import {
} from "react";
import {
type Group,
- Matrix4,
type Mesh,
MeshBasicMaterial,
type Object3D,
@@ -23,7 +22,11 @@ import {
Vector3
} from "three";
import type { OrbitControls as OrbitControlsImpl } from "three-stdlib";
-import { editorWaypointsToMotion, motionToEditorWaypoints } from "./motion";
+import { waypointMatrix } from "./keyframes";
+import {
+ editorWaypointsToMotion,
+ motionToEditorWaypoints
+} from "./path-editing";
import type { Motion, Quat, Vec3 } from "./types";
/** Rotation rings snap to this step, so 90° and 180° turns are easy to hit. */
@@ -40,9 +43,8 @@ type Waypoint = { position: Vector3; rotation: Quaternion };
* Delete to remove it.
*
* A see-through copy of the moving parts shows the selected waypoint's pose.
- * With the Rotate tool, the selected waypoint gets rotation rings (snapping to
- * 15°) and the spheres stop dragging: the rings' free-rotation grip covers the
- * sphere, so allowing both made one drag move and spin the part at once.
+ * With the Rotate tool the spheres stop dragging: the rings' free-rotation grip
+ * covers the sphere, so one drag would both move and spin the part.
*
* Edits serialize back to a RELATIVE motion via `editorWaypointsToMotion` —
* `linear`/`L` while nothing is turned, `waypoints` once something is — so
@@ -213,16 +215,10 @@ export function MotionPathEditor({
};
}, [controls]);
- // Rotation rings act on a handle sitting at the selected waypoint; turning
- // the handle turns that waypoint.
+ // The rings and the see-through copy show the selected waypoint, else the start.
+ const shownIndex = selected !== null && selected !== lastIndex ? selected : 0;
const [ringHandle, setRingHandle] = useState<Group | null>(null);
- // With the Rotate tool the rings sit on the selected waypoint, else the start.
- const ringIndex =
- tool !== "rotate" || lastIndex < 1
- ? null
- : selected !== null && selected !== lastIndex
- ? selected
- : 0;
+ const ringIndex = tool === "rotate" && lastIndex >= 1 ? shownIndex : null;
const ringWaypoint = ringIndex !== null ? points[ringIndex] : undefined;
useEffect(() => {
if (!ringHandle || !ringWaypoint) return;
@@ -248,11 +244,7 @@ export function MotionPathEditor({
[points]
);
- // The see-through copy shows the selected waypoint, else the start.
- const ghostWaypoint =
- (selected !== null && selected !== lastIndex
- ? points[selected]
- : undefined) ?? points[0];
+ const ghostWaypoint = points[shownIndex] ?? points[0];
const showGhost = Boolean(ghostWaypoint) && points.length > 1;
return (
@@ -325,7 +317,6 @@ export function MotionPathEditor({
/**
* The moving parts drawn see-through at one waypoint's pose: turned about the
* seated center (`pivot`), then moved so that center sits on the waypoint.
- * Copies share the scene's geometry and never take part in picking.
*/
function MotionGhost({
nodes,
@@ -372,11 +363,13 @@ function MotionGhost({
useLayoutEffect(() => {
const group = groupRef.current;
if (!group) return;
- const [x, y, z] = pivot;
- group.matrix
- .makeTranslation(position.x, position.y, position.z)
- .multiply(new Matrix4().makeRotationFromQuaternion(rotation))
- .multiply(new Matrix4().makeTranslation(-x, -y, -z));
+ const center = new Vector3(...pivot);
+ waypointMatrix(
+ position.clone().sub(center),
+ rotation,
+ center,
+ group.matrix
+ );
group.matrixWorldNeedsUpdate = true;
}, [pivot, position, rotation]);
diff --git a/packages/viewer/src/camera.test.ts b/packages/viewer/src/camera.test.ts
index 55038275fc..b5b4ecc3f7 100644
--- a/packages/viewer/src/camera.test.ts
+++ b/packages/viewer/src/camera.test.ts
@@ -2,8 +2,9 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+import { Box3, Vector3 } from "three";
import { describe, expect, it } from "vitest";
-import { fitFraming } from "./camera";
+import { fitFraming, frameStepPose, type StepFramingInput } from "./camera";
import type { Vec3 } from "./types";
describe("fitFraming", () => {
@@ -91,3 +92,99 @@ describe("fitFraming", () => {
expect(contained(points, fit)).toBe(true);
});
});
+
+describe("frameStepPose", () => {
+ const box = (min: Vec3, max: Vec3) =>
+ new Box3(new Vector3(...min), new Vector3(...max));
+ const base = (overrides: Partial<StepFramingInput>): StepFramingInput => ({
+ buildBox: box([-100, -100, 0], [100, 100, 100]),
+ ownBox: box([-10, -10, 100], [10, 10, 120]),
+ motion: { type: "linear", direction: [0, 0, -1], distance: 50 },
+ pathUnits: [],
+ glideStartBox: null,
+ occluders: [],
+ up: new Vector3(0, 0, 1),
+ currentDirection: new Vector3(1, -1, 1).normalize(),
+ turned: false,
+ planDirection: null,
+ fov: 45,
+ aspect: 16 / 9,
+ ...overrides
+ });
+ const directionOf = (pose: { position: Vector3; target: Vector3 } | null) => {
+ if (!pose) throw new Error("expected a pose");
+ return pose.position.clone().sub(pose.target).normalize();
+ };
+
+ it("keeps the current direction on a turned build, ignoring the plan's", () => {
+ const current = new Vector3(-1, 0.2, -0.4).normalize();
+ const pose = frameStepPose(
+ base({
+ turned: true,
+ currentDirection: current,
+ planDirection: new Vector3(0, 0, 1)
+ })
+ );
+ expect(directionOf(pose).dot(current)).toBeCloseTo(1, 6);
+ });
+
+ it("takes the plan's direction on an upright build", () => {
+ const plan = new Vector3(0, -2, 1);
+ const pose = frameStepPose(base({ planDirection: plan }));
+ expect(directionOf(pose).dot(plan.clone().normalize())).toBeCloseTo(1, 6);
+ });
+
+ it("scores a clear side when there is no plan", () => {
+ // A wall right in front of the current view: the camera moves off it.
+ const current = new Vector3(0, -1, 0.3).normalize();
+ const pose = frameStepPose(
+ base({
+ currentDirection: current,
+ occluders: [
+ {
+ min: new Vector3(-300, -400, -300),
+ max: new Vector3(300, -300, 600),
+ weight: 1
+ }
+ ]
+ })
+ );
+ expect(directionOf(pose).dot(current)).toBeLessThan(0.99);
+ });
+
+ it("keeps a far unit's start inside the fitted frustum", () => {
+ const unitBox = box([60, 60, 0], [90, 90, 30]);
+ const input = base({
+ pathUnits: [
+ {
+ box: unitBox,
+ motion: { type: "linear", direction: [-1, 0, 0], distance: 900 }
+ }
+ ]
+ });
+ const pose = frameStepPose(input);
+ if (!pose) throw new Error("expected a pose");
+ const forward = pose.target.clone().sub(pose.position).normalize();
+ const right = new Vector3().crossVectors(forward, input.up).normalize();
+ const up = new Vector3().crossVectors(right, forward).normalize();
+ const tanV = Math.tan(((input.fov / 2) * Math.PI) / 180);
+ const tanH = tanV * input.aspect;
+ // The unit starts 900 mm out along -X.
+ const start = unitBox.clone().translate(new Vector3(900, 0, 0));
+ for (let i = 0; i < 8; i++) {
+ const corner = new Vector3(
+ i & 1 ? start.max.x : start.min.x,
+ i & 2 ? start.max.y : start.min.y,
+ i & 4 ? start.max.z : start.min.z
+ ).sub(pose.position);
+ const depth = corner.dot(forward);
+ expect(depth).toBeGreaterThan(0);
+ expect(Math.abs(corner.dot(right))).toBeLessThanOrEqual(tanH * depth);
+ expect(Math.abs(corner.dot(up))).toBeLessThanOrEqual(tanV * depth);
+ }
+ });
+
+ it("frames nothing for an empty build", () => {
+ expect(frameStepPose(base({ buildBox: new Box3() }))).toBeNull();
+ });
+});
diff --git a/packages/viewer/src/camera.ts b/packages/viewer/src/camera.ts
index c3fb2a23f7..c3e8b7fbd3 100644
--- a/packages/viewer/src/camera.ts
+++ b/packages/viewer/src/camera.ts
@@ -2,13 +2,16 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-import type { Vec3 } from "./types";
+import { Box3, Vector3 } from "three";
+import { waypointMatrix } from "./keyframes";
+import { toQuaternion } from "./quat";
+import type { Motion, Vec3 } from "./types";
-// Plain-array math so this stays importable server-side without pulling
-// three.js into the bundle. The per-step view DIRECTION is baked by the Rust
-// planner (mesh-precise sight lines, plan.json `viewDirection`); this module
-// is the live half of that split — fitting the frame at the real viewport
-// aspect once a direction is chosen (AssemblyPlayer's camera effect).
+// The per-step view DIRECTION is baked by the Rust planner (mesh-precise
+// sight lines, plan.json `viewDirection`); this module is the live half of
+// that split — choosing a direction when there is no baked one, and fitting
+// the frame at the real viewport aspect (AssemblyPlayer's camera effect).
+// Pure: no scene, no camera, no React.
export type FramingFit = {
/** Target shift along the camera's [right, up] axes (world units) */
@@ -74,3 +77,323 @@ export function fitFraming(
distance = Math.min(distance * 1.2, maxDistance);
}
}
+
+export type FramingOccluder = { min: Vector3; max: Vector3; weight: number };
+
+export type StepFramingInput = {
+ /** Seated bounds of the build the step happens in. */
+ buildBox: Box3;
+ /** What the step's own insertion moves, seated; empty when nothing. */
+ ownBox: Box3;
+ motion: Motion;
+ /** Carried units flying their own path: seated bounds and path. */
+ pathUnits: { box: Box3; motion: Motion }[];
+ /** A unit gliding in beside the build, where its glide starts. */
+ glideStartBox: Box3 | null;
+ /** Visible geometry that can block the view, for the live scoring. */
+ occluders: FramingOccluder[];
+ /** The bench's up in the model frame. */
+ up: Vector3;
+ /** Where the camera looks from now (target → eye, unit), in the step's frame. */
+ currentDirection: Vector3;
+ /**
+ * The build is turned: keep `currentDirection`. Re-aiming picks a side by
+ * geometry alone, which undoes a spin (a spin is just an orbit) and shows a
+ * pose the author never chose.
+ */
+ turned: boolean;
+ /**
+ * The planner's view direction. Only used on an upright build: it was picked
+ * for the upright model and turns with it.
+ */
+ planDirection: Vector3 | null;
+ /** Vertical field of view, degrees. */
+ fov: number;
+ aspect: number;
+};
+
+/**
+ * The camera pose for one step: the whole build in view at a steady standing
+ * distance, aimed a little toward the action (the step's own parts, seated and
+ * at their start, and each carried unit), from the chosen direction, panned —
+ * and only pushed back when it can't fit — so all of the action is in frame.
+ * Null when there is nothing to frame.
+ */
+export function frameStepPose(
+ input: StepFramingInput
+): { position: Vector3; target: Vector3 } | null {
+ const { motion, ownBox } = input;
+ const buildBox = input.buildBox.clone();
+ if (buildBox.isEmpty()) return null;
+
+ // The action, seated and at its start. Start poses turn about the same
+ // seated centers the clip uses.
+ const ownCenter = ownBox.isEmpty() ? null : ownBox.getCenter(new Vector3());
+ const startOffset = insertionStartOffset(motion);
+ const seatedBoxes = [ownBox];
+ const startBoxes: (Box3 | null)[] = [
+ ownCenter && startPoseBounds(ownBox, motion, ownCenter, startOffset),
+ input.glideStartBox
+ ];
+ for (const unit of input.pathUnits) {
+ if (unit.box.isEmpty()) continue;
+ seatedBoxes.push(unit.box);
+ startBoxes.push(
+ startPoseBounds(unit.box, unit.motion, unit.box.getCenter(new Vector3()))
+ );
+ }
+ const seatedAction = new Box3();
+ for (const box of seatedBoxes) seatedAction.union(box);
+ if (seatedAction.isEmpty()) return null;
+ const actionBoxes = [...seatedBoxes, ...startBoxes].filter(
+ (box): box is Box3 => box !== null && !box.isEmpty()
+ );
+ for (const box of actionBoxes) buildBox.union(box);
+
+ const center = buildBox.getCenter(new Vector3());
+ const radius = buildBox.getSize(new Vector3()).length() / 2;
+ const tanHalfV = Math.tan(((input.fov / 2) * Math.PI) / 180);
+ const distance = Math.max((radius / tanHalfV) * 1.25, radius * 2);
+ const actionCenter = seatedAction.getCenter(new Vector3());
+ // Aim mostly at the build (context) with a nudge toward the action.
+ const target = center.clone().lerp(actionCenter, 0.3);
+
+ // Every seated and start box (corners, so a mostly-hidden part scores worse
+ // than a clear one) plus the midpoint of the own insertion's travel.
+ const actionPoints = actionBoxes.flatMap(boxCorners);
+ const lookPoints = [actionCenter, ...actionPoints];
+ if (ownCenter && startOffset) {
+ lookPoints.push(ownCenter.clone().addScaledVector(startOffset, 0.5));
+ lookPoints.push(ownCenter.clone().add(startOffset));
+ }
+ const direction = chooseDirection(input, target, distance, lookPoints);
+
+ let right = new Vector3().crossVectors(input.up, direction);
+ if (right.lengthSq() < 1e-6) right = new Vector3(1, 0, 0);
+ right.normalize();
+ const trueUp = new Vector3().crossVectors(direction, right).normalize();
+ const rel = new Vector3();
+ const camPoints: Vec3[] = actionPoints.map((point) => {
+ rel.copy(point).sub(target);
+ return [rel.dot(right), rel.dot(trueUp), rel.dot(direction)];
+ });
+ const fit = fitFraming(
+ camPoints,
+ tanHalfV * input.aspect,
+ tanHalfV,
+ 0.85,
+ distance
+ );
+ const framedTarget = target
+ .clone()
+ .addScaledVector(right, fit.pan[0])
+ .addScaledVector(trueUp, fit.pan[1]);
+ return {
+ position: framedTarget.clone().addScaledVector(direction, fit.distance),
+ target: framedTarget
+ };
+}
+
+/**
+ * A turned build keeps the current direction; an upright one takes the
+ * planner's. Otherwise (manual or edited steps, plans without directions)
+ * AABB-scored candidates — coarse, since a box can't show a hollow part's open
+ * top, which is exactly why generated steps carry a baked direction.
+ */
+function chooseDirection(
+ input: StepFramingInput,
+ target: Vector3,
+ distance: number,
+ lookPoints: Vector3[]
+): Vector3 {
+ const { currentDirection, planDirection, up } = input;
+ const hasCurrent = currentDirection.lengthSq() > 1e-6;
+ if (input.turned && hasCurrent) return currentDirection.clone();
+ if (!input.turned && planDirection && planDirection.lengthSq() > 1e-6) {
+ return planDirection.clone().normalize();
+ }
+
+ // Elevation rings around the up axis, plus the current view. The third,
+ // steeper ring: in dense machines the only clear sight line to a buried
+ // part is often from high above.
+ let basisU = new Vector3().crossVectors(up, new Vector3(0, 0, 1));
+ if (basisU.lengthSq() < 1e-6) {
+ basisU = new Vector3().crossVectors(up, new Vector3(1, 0, 0));
+ }
+ basisU.normalize();
+ const basisV = new Vector3().crossVectors(up, basisU).normalize();
+ const candidates: Vector3[] = hasCurrent ? [currentDirection] : [];
+ for (const elevation of [0.3, 0.55, 0.8]) {
+ const horizontal = Math.sqrt(1 - elevation * elevation);
+ for (let i = 0; i < 8; i++) {
+ const azimuth = (i / 8) * Math.PI * 2;
+ candidates.push(
+ new Vector3()
+ .addScaledVector(basisU, Math.cos(azimuth) * horizontal)
+ .addScaledVector(basisV, Math.sin(azimuth) * horizontal)
+ .addScaledVector(up, elevation)
+ .normalize()
+ );
+ }
+ }
+
+ // Fewest components in the way of the action, travel across the screen
+ // rather than into it, and small turns from the current view.
+ const motionDirection = insertionDirection(input.motion);
+ let best = candidates[0] ?? new Vector3(1, 1, 1).normalize();
+ let bestScore = Number.POSITIVE_INFINITY;
+ for (const candidate of candidates) {
+ const eye = target.clone().addScaledVector(candidate, distance);
+ let score = 0;
+ for (const point of lookPoints) {
+ for (const occluder of input.occluders) {
+ if (segmentIntersectsBox(eye, point, occluder.min, occluder.max)) {
+ score += occluder.weight;
+ }
+ }
+ }
+ if (motionDirection) {
+ score += 4 * Math.max(0, Math.abs(candidate.dot(motionDirection)) - 0.6);
+ }
+ score += 1.75 * (1 - candidate.dot(currentDirection));
+ if (score < bestScore) {
+ bestScore = score;
+ best = candidate;
+ }
+ }
+ return best.clone();
+}
+
+/**
+ * Does the open segment from `origin` to `end` pass through the AABB?
+ * Slab clipping; ignores grazing contact right at the endpoint so a box
+ * around the look-at point does not count as occluding itself.
+ */
+function segmentIntersectsBox(
+ origin: Vector3,
+ end: Vector3,
+ min: Vector3,
+ max: Vector3
+): boolean {
+ let tMin = 0;
+ let tMax = 0.98; // stop just short of the look-at point
+ const axes = ["x", "y", "z"] as const;
+ for (const axis of axes) {
+ const delta = end[axis] - origin[axis];
+ if (Math.abs(delta) < 1e-9) {
+ if (origin[axis] < min[axis] || origin[axis] > max[axis]) return false;
+ continue;
+ }
+ let tNear = (min[axis] - origin[axis]) / delta;
+ let tFar = (max[axis] - origin[axis]) / delta;
+ if (tNear > tFar) [tNear, tFar] = [tFar, tNear];
+ tMin = Math.max(tMin, tNear);
+ tMax = Math.min(tMax, tFar);
+ if (tMin > tMax) return false;
+ }
+ return true;
+}
+
+/**
+ * Bounds of a set at the start of its motion: the seated box shifted by the
+ * start offset, and for a `waypoints` motion first turned about `pivot` as the
+ * first waypoint turns it. Null when the motion has no start offset.
+ */
+function startPoseBounds(
+ seated: Box3,
+ motion: Motion,
+ pivot: Vector3,
+ startOffset = insertionStartOffset(motion)
+): Box3 | null {
+ if (!startOffset) return null;
+ const first = motion.type === "waypoints" ? motion.waypoints[0] : undefined;
+ if (!first) return seated.clone().translate(startOffset);
+ return seated
+ .clone()
+ .applyMatrix4(
+ waypointMatrix(startOffset, toQuaternion(first.rotation), pivot)
+ );
+}
+
+function boxCorners(box: Box3): Vector3[] {
+ return Array.from(
+ { length: 8 },
+ (_, i) =>
+ new Vector3(
+ i & 1 ? box.max.x : box.min.x,
+ i & 2 ? box.max.y : box.min.y,
+ i & 4 ? box.max.z : box.min.z
+ )
+ );
+}
+
+/**
+ * Where a component starts relative to its seated pose for the given insertion
+ * motion. Null when the motion does not translate the component.
+ */
+function insertionStartOffset(motion: Motion): Vector3 | null {
+ switch (motion.type) {
+ case "linear": {
+ const direction = new Vector3(...motion.direction).normalize();
+ return direction.multiplyScalar(-motion.distance);
+ }
+ case "L": {
+ const offset = new Vector3();
+ for (const segment of motion.segments) {
+ const direction = new Vector3(...segment.direction).normalize();
+ offset.addScaledVector(direction, -segment.distance);
+ }
+ return offset;
+ }
+ case "helix": {
+ const axis = new Vector3(...motion.axis).normalize();
+ const travel = motion.approach + motion.pitch * motion.turns;
+ return axis.multiplyScalar(-travel);
+ }
+ case "waypoints": {
+ const first = motion.waypoints[0];
+ return first ? new Vector3(...first.offset) : null;
+ }
+ default:
+ return null;
+ }
+}
+
+/**
+ * The dominant travel direction of an insertion motion (used to pick a
+ * camera angle where the motion reads laterally). Null for motions that
+ * do not translate the component.
+ */
+function insertionDirection(motion: Motion): Vector3 | null {
+ switch (motion.type) {
+ case "linear":
+ return new Vector3(...motion.direction).normalize();
+ case "L": {
+ let longest: Vector3 | null = null;
+ let longestDistance = 0;
+ for (const segment of motion.segments) {
+ if (Math.abs(segment.distance) > longestDistance) {
+ longestDistance = Math.abs(segment.distance);
+ longest = new Vector3(...segment.direction);
+ }
+ }
+ return longest ? longest.normalize() : null;
+ }
+ case "helix":
+ return new Vector3(...motion.axis).normalize();
+ case "waypoints": {
+ // The longest leg, in travel order (start → seat).
+ let longest: Vector3 | null = null;
+ for (let i = 1; i < motion.waypoints.length; i++) {
+ const from = motion.waypoints[i - 1];
+ const to = motion.waypoints[i];
+ if (!from || !to) continue;
+ const leg = new Vector3(...to.offset).sub(new Vector3(...from.offset));
+ if (leg.lengthSq() > (longest?.lengthSq() ?? 1e-12)) longest = leg;
+ }
+ return longest ? longest.normalize() : null;
+ }
+ default:
+ return null;
+ }
+}
diff --git a/packages/viewer/src/clip.test.ts b/packages/viewer/src/clip.test.ts
new file mode 100644
index 0000000000..2068c59a32
--- /dev/null
+++ b/packages/viewer/src/clip.test.ts
@@ -0,0 +1,466 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import {
+ type AnimationClip,
+ AnimationMixer,
+ Group,
+ Matrix4,
+ Object3D,
+ Quaternion,
+ Vector3
+} from "three";
+import { describe, expect, it } from "vitest";
+import { buildStepClip } from "./clip";
+import { expectVectorClose, makeStep } from "./test-utils";
+import type { Motion } from "./types";
+
+describe("buildStepClip", () => {
+ function makeAssembly() {
+ const root = new Group();
+ const parent = new Group();
+ parent.position.set(5, 0, 0);
+ root.add(parent);
+ const component = new Object3D();
+ component.position.set(1, 2, 3);
+ component.userData.nodeId = "node-a";
+ parent.add(component);
+ root.updateMatrixWorld(true);
+ return {
+ root,
+ component,
+ parent,
+ nodesById: new Map([["node-a", component]])
+ };
+ }
+
+ it("returns null for none motions and for steps with no resolvable components", () => {
+ const { nodesById } = makeAssembly();
+ expect(
+ buildStepClip(makeStep({ type: "none" }, ["node-a"]), nodesById, {
+ pivot: null
+ })
+ ).toBeNull();
+ expect(
+ buildStepClip(
+ makeStep({ type: "linear", direction: [1, 0, 0], distance: 10 }, []),
+ nodesById,
+ { pivot: null }
+ )
+ ).toBeNull();
+ expect(
+ buildStepClip(
+ makeStep({ type: "linear", direction: [1, 0, 0], distance: 10 }, [
+ "missing-node"
+ ]),
+ nodesById,
+ { pivot: null }
+ )
+ ).toBeNull();
+ });
+
+ it("builds uuid-bound position/quaternion tracks in parent-local space with a seated hold", () => {
+ const { component, nodesById } = makeAssembly();
+ const step = makeStep(
+ { type: "linear", direction: [1, 0, 0], distance: 10 },
+ ["node-a"]
+ );
+ const clip = buildStepClip(step, nodesById, {
+ pivot: null,
+ duration: 2,
+ holdSeconds: 0.5
+ });
+ expect(clip).not.toBeNull();
+ if (!clip) return;
+
+ expect(clip.name).toBe("step:step-1");
+ expect(clip.duration).toBeCloseTo(2.5);
+ expect(clip.tracks.length).toBe(2);
+ const [positionTrack, quaternionTrack] = clip.tracks;
+ if (!positionTrack || !quaternionTrack) throw new Error("expected tracks");
+ expect(positionTrack.name).toBe(`${component.uuid}.position`);
+ expect(quaternionTrack.name).toBe(`${component.uuid}.quaternion`);
+
+ // World start [6,2,3] - [10,0,0] = [-4,2,3] → parent-local [-9,2,3]
+ expectVectorClose([...positionTrack.values.slice(0, 3)], [-9, 2, 3]);
+ // Seated keyframe and hold keyframe both equal the component's local pose
+ expectVectorClose([...positionTrack.values.slice(-6, -3)], [1, 2, 3]);
+ expectVectorClose([...positionTrack.values.slice(-3)], [1, 2, 3]);
+ // Hold keyframe extends the timeline
+ const times = positionTrack.times;
+ expect(times[times.length - 1]).toBeCloseTo(2.5);
+ expect(times[times.length - 2]).toBeCloseTo(2);
+ });
+
+ it("glides a carried-in unit from beside the build, then inserts", () => {
+ const { nodesById } = makeAssembly();
+ const motion: Motion = {
+ type: "linear",
+ direction: [1, 0, 0],
+ distance: 10
+ };
+ const clip = buildStepClip(makeStep(motion, ["node-a"]), nodesById, {
+ pivot: null,
+ duration: 2,
+ holdSeconds: 0.5,
+ glide: { offset: [0, 100, 0], seconds: 1.2 }
+ });
+ if (!clip) throw new Error("expected clip");
+ expect(clip.duration).toBeCloseTo(1.2 + 2 + 0.5);
+
+ const [positionTrack] = clip.tracks;
+ if (!positionTrack) throw new Error("expected tracks");
+ const values = [...positionTrack.values];
+ const times = [...positionTrack.times];
+ // Seated world [6,2,3] + offset [0,100,0] → parent-local [1,102,3]
+ expectVectorClose(values.slice(0, 3), [1, 102, 3]);
+ // Glide ends at the linear insertion start: world [-4,2,3] → local [-9,2,3]
+ const glideEnd = times.findIndex((time) => Math.abs(time - 1.2) < 1e-5);
+ expect(glideEnd).toBeGreaterThan(0);
+ expectVectorClose(values.slice(glideEnd * 3, glideEnd * 3 + 3), [-9, 2, 3]);
+ // Still ends seated, with the hold
+ expectVectorClose(values.slice(-6, -3), [1, 2, 3]);
+ expect(times[times.length - 2]).toBeCloseTo(3.2);
+ for (let i = 1; i < times.length; i++) {
+ expect(times[i]).toBeGreaterThan(
+ times[i - 1] ?? Number.POSITIVE_INFINITY
+ );
+ }
+ });
+
+ it("glides a none-motion carry-in step straight to the seat", () => {
+ const { nodesById } = makeAssembly();
+ const clip = buildStepClip(
+ makeStep({ type: "none" }, ["node-a"]),
+ nodesById,
+ {
+ pivot: null,
+ holdSeconds: 0,
+ glide: { offset: [50, 0, 0], seconds: 1.2 }
+ }
+ );
+ if (!clip) throw new Error("expected clip");
+ expect(clip.duration).toBeCloseTo(1.2);
+ const [positionTrack] = clip.tracks;
+ if (!positionTrack) throw new Error("expected tracks");
+ const values = [...positionTrack.values];
+ expectVectorClose(values.slice(0, 3), [51, 2, 3]);
+ expectVectorClose(values.slice(-3), [1, 2, 3]);
+ });
+
+ it("glides only the carried unit; the step's own parts wait at their start", () => {
+ const { nodesById } = makeAssembly();
+ const motion: Motion = {
+ type: "linear",
+ direction: [1, 0, 0],
+ distance: 10
+ };
+ const clip = buildStepClip(makeStep(motion, ["node-a"]), nodesById, {
+ pivot: null,
+ duration: 2,
+ holdSeconds: 0,
+ glide: { offset: [0, 100, 0], seconds: 1.2, nodeIds: ["other"] }
+ });
+ if (!clip) throw new Error("expected clip");
+ const [positionTrack] = clip.tracks;
+ if (!positionTrack) throw new Error("expected tracks");
+ const values = [...positionTrack.values];
+ const times = [...positionTrack.times];
+ // Not carried: sits at its insertion start (local [-9,2,3]) through the glide.
+ expectVectorClose(values.slice(0, 3), [-9, 2, 3]);
+ const glideEnd = times.findIndex((time) => Math.abs(time - 1.2) < 1e-5);
+ expectVectorClose(values.slice(glideEnd * 3, glideEnd * 3 + 3), [-9, 2, 3]);
+ expectVectorClose(values.slice(-3), [1, 2, 3]);
+ });
+
+ it("converts world-space motion into the local space of a rotated parent", () => {
+ const root = new Group();
+ const parent = new Group();
+ parent.rotation.z = Math.PI / 2;
+ root.add(parent);
+ const component = new Object3D();
+ component.userData.nodeId = "node-b";
+ parent.add(component);
+ root.updateMatrixWorld(true);
+ const nodesById = new Map([["node-b", component]]);
+
+ const step = makeStep(
+ { type: "linear", direction: [0, 1, 0], distance: 10 },
+ ["node-b"]
+ );
+ const clip = buildStepClip(step, nodesById, {
+ pivot: null,
+ holdSeconds: 0
+ });
+ if (!clip) throw new Error("expected clip");
+
+ const expectedStart = new Vector3(0, -10, 0).applyMatrix4(
+ new Matrix4().copy(parent.matrixWorld).invert()
+ );
+ const [positionTrack, quaternionTrack] = clip.tracks;
+ if (!positionTrack || !quaternionTrack) throw new Error("expected tracks");
+ expectVectorClose(
+ [...positionTrack.values.slice(0, 3)],
+ expectedStart.toArray()
+ );
+ expectVectorClose([...positionTrack.values.slice(-3)], [0, 0, 0]);
+
+ const localQuaternion = new Quaternion().copy(component.quaternion);
+ expectVectorClose(
+ [...quaternionTrack.values.slice(-4)],
+ [
+ localQuaternion.x,
+ localQuaternion.y,
+ localQuaternion.z,
+ localQuaternion.w
+ ]
+ );
+ });
+
+ it("clamps the default duration to 1-4 s based on travel distance", () => {
+ const { nodesById } = makeAssembly();
+ const short = buildStepClip(
+ makeStep({ type: "linear", direction: [1, 0, 0], distance: 1 }, [
+ "node-a"
+ ]),
+ nodesById,
+ { pivot: null, holdSeconds: 0 }
+ );
+ const long = buildStepClip(
+ makeStep({ type: "linear", direction: [1, 0, 0], distance: 6000 }, [
+ "node-a"
+ ]),
+ nodesById,
+ { pivot: null, holdSeconds: 0 }
+ );
+ expect(short?.duration).toBeCloseTo(1);
+ expect(long?.duration).toBeCloseTo(4);
+ });
+
+ it("drives nodes through an AnimationMixer via uuid-bound tracks", () => {
+ const { root, component, nodesById } = makeAssembly();
+ const step = makeStep(
+ { type: "linear", direction: [1, 0, 0], distance: 10 },
+ ["node-a"]
+ );
+ const clip = buildStepClip(step, nodesById, {
+ pivot: null,
+ duration: 2,
+ holdSeconds: 0
+ });
+ if (!clip) throw new Error("expected clip");
+
+ const mixer = new AnimationMixer(root);
+ mixer.clipAction(clip).play();
+
+ mixer.update(0); // t = 0 → displaced start pose (local [-9, 2, 3])
+ expect(component.position.x).toBeCloseTo(-9);
+ mixer.update(1); // t = 1 → halfway back to seated
+ expect(component.position.x).toBeCloseTo(-4);
+ expect(component.position.y).toBeCloseTo(2);
+ expect(component.position.z).toBeCloseTo(3);
+ });
+});
+
+describe("buildStepClip with sub-assembly units", () => {
+ function makeParts() {
+ const root = new Group();
+ const own = new Object3D();
+ own.position.set(0, 0, 0);
+ const unitA = new Object3D();
+ unitA.position.set(100, 0, 0);
+ const unitB = new Object3D();
+ unitB.position.set(200, 0, 0);
+ root.add(own, unitA, unitB);
+ root.updateMatrixWorld(true);
+ return {
+ own,
+ unitA,
+ unitB,
+ nodesById: new Map<string, Object3D>([
+ ["own", own],
+ ["unit-a", unitA],
+ ["unit-b", unitB]
+ ])
+ };
+ }
+ const drop: Motion = { type: "linear", direction: [0, 0, -1], distance: 10 };
+ const trackFor = (clip: AnimationClip, node: Object3D) => {
+ const track = clip.tracks.find(
+ (candidate) => candidate.name === `${node.uuid}.position`
+ );
+ if (!track) throw new Error("expected a track");
+ return { times: [...track.times], values: [...track.values] };
+ };
+ const valueAt = (
+ track: { times: number[]; values: number[] },
+ time: number
+ ) => {
+ const index = track.times.findIndex((t) => Math.abs(t - time) < 1e-6);
+ expect(index).toBeGreaterThanOrEqual(0);
+ return track.values.slice(index * 3, index * 3 + 3);
+ };
+
+ it("flies the unit in first; the step's own part waits, then inserts", () => {
+ const { own, unitA, nodesById } = makeParts();
+ const clip = buildStepClip(makeStep(drop, ["own"]), nodesById, {
+ pivot: null,
+ duration: 2,
+ holdSeconds: 0.5,
+ units: [{ nodeIds: ["unit-a"], motion: drop, seconds: 1, pivot: null }]
+ });
+ if (!clip) throw new Error("expected clip");
+ expect(clip.duration).toBeCloseTo(1 + 2 + 0.5);
+
+ const unit = trackFor(clip, unitA);
+ expectVectorClose(unit.values.slice(0, 3), [100, 0, 10]);
+ expectVectorClose(valueAt(unit, 1), [100, 0, 0]);
+ expectVectorClose(unit.values.slice(-3), [100, 0, 0]);
+ expect(unit.times[unit.times.length - 1]).toBeCloseTo(3.5);
+
+ const part = trackFor(clip, own);
+ // Waits at its insertion start until the unit has seated…
+ expectVectorClose(part.values.slice(0, 3), [0, 0, 10]);
+ expectVectorClose(valueAt(part, 1), [0, 0, 10]);
+ // …then inserts and holds.
+ expectVectorClose(valueAt(part, 3), [0, 0, 0]);
+ });
+
+ it("plays several units one after another", () => {
+ const { unitB, nodesById } = makeParts();
+ const clip = buildStepClip(makeStep({ type: "none" }, []), nodesById, {
+ pivot: null,
+ holdSeconds: 0,
+ units: [
+ { nodeIds: ["unit-a"], motion: drop, seconds: 1, pivot: null },
+ { nodeIds: ["unit-b"], motion: drop, seconds: 1.5, pivot: null }
+ ]
+ });
+ if (!clip) throw new Error("expected clip");
+ expect(clip.duration).toBeCloseTo(2.5);
+ const second = trackFor(clip, unitB);
+ expectVectorClose(valueAt(second, 1), [200, 0, 10]);
+ expectVectorClose(second.values.slice(-3), [200, 0, 0]);
+ });
+
+ it("turns a unit about the pivot it is given", () => {
+ const { unitA, nodesById } = makeParts();
+ const halfTurn: Motion = {
+ type: "waypoints",
+ waypoints: [
+ { offset: [0, 0, 0], rotation: [0, 0, 1, 0] },
+ { offset: [0, 0, 0], rotation: [0, 0, 0, 1] }
+ ]
+ };
+ const clip = buildStepClip(makeStep({ type: "none" }, []), nodesById, {
+ pivot: null,
+ holdSeconds: 0,
+ units: [
+ { nodeIds: ["unit-a"], motion: halfTurn, seconds: 1, pivot: [0, 0, 0] }
+ ]
+ });
+ if (!clip) throw new Error("expected clip");
+ // 180° about the origin swings the unit from +X to -X.
+ expectVectorClose(trackFor(clip, unitA).values.slice(0, 3), [-100, 0, 0]);
+ });
+
+ it("moves a node listed in two units with the first one only", () => {
+ const { unitA, nodesById } = makeParts();
+ const clip = buildStepClip(makeStep({ type: "none" }, []), nodesById, {
+ pivot: null,
+ holdSeconds: 0,
+ units: [
+ { nodeIds: ["unit-a"], motion: drop, seconds: 1, pivot: null },
+ {
+ nodeIds: ["unit-a", "unit-b"],
+ motion: drop,
+ seconds: 1,
+ pivot: null
+ }
+ ]
+ });
+ if (!clip) throw new Error("expected clip");
+ const tracks = clip.tracks.filter(
+ (track) => track.name === `${unitA.uuid}.position`
+ );
+ expect(tracks).toHaveLength(1);
+ // Seated by the end of the first unit's second, not delayed into the second's.
+ expectVectorClose(valueAt(trackFor(clip, unitA), 1), [100, 0, 0]);
+ });
+
+ it("builds a clip for a unit joining at a step with no parts of its own", () => {
+ const { nodesById } = makeParts();
+ expect(
+ buildStepClip(makeStep({ type: "none" }, []), nodesById, {
+ pivot: null,
+ units: [{ nodeIds: ["unit-a"], motion: drop, seconds: 1, pivot: null }]
+ })
+ ).not.toBeNull();
+ // A unit with no path of its own adds nothing.
+ expect(
+ buildStepClip(makeStep({ type: "none" }, []), nodesById, {
+ pivot: null,
+ units: [
+ {
+ nodeIds: ["unit-a"],
+ motion: { type: "none" },
+ seconds: 0,
+ pivot: null
+ }
+ ]
+ })
+ ).toBeNull();
+ });
+});
+
+describe("buildStepClip with a turning waypoints path", () => {
+ // Three 180° legs about Z, turning in place about the origin.
+ const threeHalfTurns: Motion = {
+ type: "waypoints",
+ waypoints: [
+ { offset: [0, 0, 0], rotation: [0, 0, -1, 0] },
+ { offset: [0, 0, 0], rotation: [0, 0, 0, -1] },
+ { offset: [0, 0, 0], rotation: [0, 0, 1, 0] },
+ { offset: [0, 0, 0], rotation: [0, 0, 0, 1] }
+ ]
+ };
+ // A first leg that only shifts, then a half turn in place: the turn's
+ // keyframes are far closer together in time than the shift's.
+ const shiftThenTurn: Motion = {
+ type: "waypoints",
+ waypoints: [
+ { offset: [0, 0, 400], rotation: [0, 0, 1, 0] },
+ { offset: [0, 0, 0], rotation: [0, 0, 1, 0] },
+ { offset: [0, 0, 0], rotation: [0, 0, 0, 1] }
+ ]
+ };
+
+ it.each([
+ ["three half turns", threeHalfTurns],
+ ["a shift, then a half turn", shiftThenTurn]
+ ])("keeps a part 100 mm from the pivot on its arc (%s)", (_, motion) => {
+ const root = new Group();
+ const part = new Object3D();
+ part.position.set(100, 0, 0);
+ root.add(part);
+ root.updateMatrixWorld(true);
+ const clip = buildStepClip(
+ makeStep(motion, ["part"]),
+ new Map([["part", part]]),
+ { pivot: [0, 0, 0], holdSeconds: 0 }
+ );
+ const track = clip?.tracks.find(
+ (candidate) => candidate.name === `${part.uuid}.position`
+ );
+ if (!track) throw new Error("expected a position track");
+ // The track moves in a straight line between keys: each chord's midpoint
+ // must stay near the arc, not cut inside it.
+ const values = [...track.values];
+ for (let i = 0; i + 1 < track.times.length; i++) {
+ const [ax = 0, ay = 0] = values.slice(i * 3, i * 3 + 2);
+ const [bx = 0, by = 0] = values.slice((i + 1) * 3, (i + 1) * 3 + 2);
+ expect(Math.hypot((ax + bx) / 2, (ay + by) / 2)).toBeGreaterThan(99);
+ }
+ });
+});
diff --git a/packages/viewer/src/clip.ts b/packages/viewer/src/clip.ts
new file mode 100644
index 0000000000..0cd847a458
--- /dev/null
+++ b/packages/viewer/src/clip.ts
@@ -0,0 +1,303 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import {
+ AnimationClip,
+ Matrix4,
+ type Object3D,
+ Quaternion,
+ QuaternionKeyframeTrack,
+ Vector3,
+ VectorKeyframeTrack
+} from "three";
+import {
+ EASE_SAMPLES,
+ easeInOutCubic,
+ type MotionKeyframeOptions,
+ type MotionKeyframes,
+ motionToKeyframes,
+ type Pose,
+ resampleEased
+} from "./keyframes";
+import { toQuat, toVector3 } from "./quat";
+import { DEFAULT_HOLD_SECONDS, motionDuration } from "./timing";
+import type { AssemblyStep, Motion, Vec3 } from "./types";
+
+export type StepClipOptions = Omit<MotionKeyframeOptions, "pivot"> & {
+ /**
+ * Seated center of what the step's own insertion moves — a `waypoints`
+ * motion turns the set about it. Null when none of its parts resolve.
+ */
+ pivot: Vec3 | null;
+ /** Seconds to hold the seated pose at the end of each loop. */
+ holdSeconds?: number;
+ /**
+ * A step that carries a finished sub-assembly in: prepend a straight glide
+ * from seat + `offset` (beside the build) to where the insertion starts.
+ * Never clamped like the insertion travel is — it starts far by design.
+ * With `nodeIds`, only those nodes glide; the step's other parts wait at
+ * their insertion start until the glide ends.
+ */
+ glide?: { offset: Vec3; seconds: number; nodeIds?: string[] };
+ /**
+ * Finished sub-assemblies that join on their own path. They play one after
+ * another before the step's own parts move (and before any `glide`); each
+ * travels as one rigid unit, turning about its own seated center.
+ */
+ units?: StepClipUnit[];
+};
+
+export type StepClipUnit = {
+ nodeIds: string[];
+ motion: Motion;
+ seconds: number;
+ /** The unit's seated center, which a `waypoints` motion turns about. */
+ pivot: Vec3 | null;
+};
+
+type ClipSegment = StepClipUnit & { glide?: StepClipOptions["glide"] };
+
+/**
+ * Tracks are bound by node uuid so duplicate node names cannot collide, and
+ * keyframes are converted into each node's parent-local space. Nodes must
+ * currently sit at their seated pose.
+ *
+ * `step.componentNodeIds` are the parts the step's own insertion moves — the
+ * units' parts belong in `units`. Each unit first travels its own path, one
+ * after another, while the step's own parts wait at their start. With
+ * `glide`, the own parts then glide from seat + offset to their insertion
+ * start (a `none` motion glides straight to the seat).
+ *
+ * A node listed in more than one segment moves with the first one only: two
+ * tracks on one node would fight over it.
+ *
+ * Returns `null` when nothing moves: a `none` motion without a glide or units,
+ * or no component that resolves to a node.
+ */
+export function buildStepClip(
+ step: AssemblyStep,
+ nodesById: Map<string, Object3D>,
+ options: StepClipOptions
+): AnimationClip | null {
+ const { glide } = options;
+ const segments: ClipSegment[] = (options.units ?? []).filter(
+ (unit) => unit.nodeIds.length > 0 && unit.motion.type !== "none"
+ );
+ if (
+ step.componentNodeIds.length > 0 &&
+ (step.motion.type !== "none" || glide)
+ ) {
+ segments.push({
+ nodeIds: step.componentNodeIds,
+ motion: step.motion,
+ seconds:
+ step.motion.type === "none"
+ ? 0
+ : (options.duration ?? motionDuration(step.motion)),
+ pivot: options.pivot,
+ glide
+ });
+ }
+ if (segments.length === 0) return null;
+
+ const clipLength =
+ segments.reduce(
+ (sum, segment) => sum + segment.seconds + (segment.glide?.seconds ?? 0),
+ 0
+ ) + (options.holdSeconds ?? DEFAULT_HOLD_SECONDS);
+ const tracks: (VectorKeyframeTrack | QuaternionKeyframeTrack)[] = [];
+
+ const claimed = new Set<string>();
+ let start = 0;
+ for (const segment of segments) {
+ const { motion, glide: segmentGlide } = segment;
+ const pivot = segment.pivot ?? undefined;
+ for (const nodeId of segment.nodeIds) {
+ if (claimed.has(nodeId)) continue;
+ claimed.add(nodeId);
+ const node = nodesById.get(nodeId);
+ if (!node) continue;
+ const { seatedPose, worldScale } = worldPoseOf(node);
+ // A `none` motion only plays with a glide: the insertion is the seat itself.
+ const raw =
+ motion.type === "none"
+ ? {
+ times: [0],
+ positions: [...seatedPose.position],
+ quaternions: [...seatedPose.quaternion]
+ }
+ : motionToKeyframes(motion, seatedPose, {
+ samplesPerTurn: options.samplesPerTurn,
+ duration: segment.seconds,
+ pivot
+ });
+ if (!raw) continue;
+ const insertion = isEasedMotion(motion) ? resampleEased(raw) : raw;
+ const keyframes = segmentGlide
+ ? prependGlide(
+ insertion,
+ !segmentGlide.nodeIds || segmentGlide.nodeIds.includes(nodeId)
+ ? segmentGlide.offset
+ : null,
+ seatedPose,
+ segmentGlide.seconds
+ )
+ : insertion;
+ tracks.push(
+ ...nodeTracks(
+ node,
+ delayKeyframes(keyframes, start),
+ worldScale,
+ clipLength
+ )
+ );
+ }
+ start += segment.seconds + (segmentGlide?.seconds ?? 0);
+ }
+
+ if (tracks.length === 0) return null;
+ return new AnimationClip(`step:${step.id}`, clipLength, tracks);
+}
+
+/**
+ * Ease the straight and editor-drawn approaches (accelerate off the start,
+ * settle into the seat). Helix threads at a constant rate (mechanically
+ * correct) and planner paths carry their own timing.
+ */
+function isEasedMotion(motion: Motion): boolean {
+ return (
+ motion.type === "linear" ||
+ motion.type === "L" ||
+ motion.type === "waypoints"
+ );
+}
+
+function worldPoseOf(node: Object3D): {
+ seatedPose: Pose;
+ worldScale: Vector3;
+} {
+ node.updateWorldMatrix(true, false);
+ const worldPosition = new Vector3();
+ const worldQuaternion = new Quaternion();
+ const worldScale = new Vector3();
+ node.matrixWorld.decompose(worldPosition, worldQuaternion, worldScale);
+ return {
+ seatedPose: {
+ position: worldPosition.toArray() as Vec3,
+ quaternion: toQuat(worldQuaternion)
+ },
+ worldScale
+ };
+}
+
+function delayKeyframes(
+ keyframes: MotionKeyframes,
+ seconds: number
+): MotionKeyframes {
+ if (seconds <= 0 || keyframes.times.length === 0) return keyframes;
+ return {
+ times: [0, ...keyframes.times.map((time) => time + seconds)],
+ positions: [...keyframes.positions.slice(0, 3), ...keyframes.positions],
+ quaternions: [
+ ...keyframes.quaternions.slice(0, 4),
+ ...keyframes.quaternions
+ ]
+ };
+}
+
+/**
+ * World-space keyframes → uuid-bound tracks in the node's parent-local space,
+ * holding the last (seated) pose until `clipLength` so the loop pauses there.
+ */
+function nodeTracks(
+ node: Object3D,
+ keyframes: MotionKeyframes,
+ worldScale: Vector3,
+ clipLength: number
+): (VectorKeyframeTrack | QuaternionKeyframeTrack)[] {
+ const parentWorldInverse = node.parent
+ ? node.parent.matrixWorld.clone().invert()
+ : new Matrix4();
+
+ const times: number[] = [];
+ const positions: number[] = [];
+ const quaternions: number[] = [];
+ const worldMatrix = new Matrix4();
+ const localMatrix = new Matrix4();
+ const position = new Vector3();
+ const quaternion = new Quaternion();
+ const localPosition = new Vector3();
+ const localQuaternion = new Quaternion();
+ const localScale = new Vector3();
+
+ const frameCount = keyframes.times.length;
+ for (let i = 0; i < frameCount; i++) {
+ const time = keyframes.times[i];
+ if (time === undefined) continue;
+ position.fromArray(keyframes.positions, i * 3);
+ quaternion.fromArray(keyframes.quaternions, i * 4);
+ worldMatrix.compose(position, quaternion, worldScale);
+ localMatrix.multiplyMatrices(parentWorldInverse, worldMatrix);
+ localMatrix.decompose(localPosition, localQuaternion, localScale);
+ times.push(time);
+ positions.push(localPosition.x, localPosition.y, localPosition.z);
+ quaternions.push(
+ localQuaternion.x,
+ localQuaternion.y,
+ localQuaternion.z,
+ localQuaternion.w
+ );
+ }
+
+ const lastTime = times[times.length - 1];
+ if (lastTime !== undefined && lastTime < clipLength - 1e-9) {
+ times.push(clipLength);
+ positions.push(...positions.slice(-3));
+ quaternions.push(...quaternions.slice(-4));
+ }
+
+ return [
+ new VectorKeyframeTrack(`${node.uuid}.position`, times, positions),
+ new QuaternionKeyframeTrack(`${node.uuid}.quaternion`, times, quaternions)
+ ];
+}
+
+/**
+ * Prepends an eased straight glide from seat + `offset` to the insertion's
+ * first pose, and shifts the insertion to start when the glide ends. The part
+ * holds the insertion's starting orientation while it glides (the carry is a
+ * pure translation), so a helix that starts unscrewed doesn't snap. A `null`
+ * offset holds the part at its insertion start for the glide's duration.
+ */
+function prependGlide(
+ insertion: MotionKeyframes,
+ offset: Vec3 | null,
+ seatedPose: Pose,
+ seconds: number
+): MotionKeyframes {
+ const end = new Vector3().fromArray(insertion.positions, 0);
+ const start = offset
+ ? toVector3(seatedPose.position).add(toVector3(offset))
+ : end.clone();
+ const quaternion = new Quaternion().fromArray(insertion.quaternions, 0);
+
+ const times: number[] = [];
+ const positions: number[] = [];
+ const quaternions: number[] = [];
+ const point = new Vector3();
+ for (let j = 0; j <= EASE_SAMPLES; j++) {
+ const u = j / EASE_SAMPLES;
+ point.copy(start).lerp(end, easeInOutCubic(u));
+ times.push(u * seconds);
+ positions.push(point.x, point.y, point.z);
+ quaternions.push(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
+ }
+ // The insertion's first frame is where the glide ended — skip the duplicate.
+ for (let i = 1; i < insertion.times.length; i++) {
+ times.push(seconds + (insertion.times[i] ?? 0));
+ positions.push(...insertion.positions.slice(i * 3, i * 3 + 3));
+ quaternions.push(...insertion.quaternions.slice(i * 4, i * 4 + 4));
+ }
+ return { times, positions, quaternions };
+}
diff --git a/packages/viewer/src/display.test.ts b/packages/viewer/src/display.test.ts
new file mode 100644
index 0000000000..cf06094fa7
--- /dev/null
+++ b/packages/viewer/src/display.test.ts
@@ -0,0 +1,231 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { describe, expect, it } from "vitest";
+import { displayMotionForStep, naturalizeMotion } from "./display";
+import { indexAssemblyGraph } from "./graph";
+import type { AssemblyStep, Motion } from "./types";
+
+describe("naturalizeMotion", () => {
+ const lift = {
+ type: "linear",
+ direction: [0, 0, -1] as [number, number, number],
+ distance: 15
+ } as const;
+
+ it("floors small-component travel to a readable distance", () => {
+ // 20mm bolt in a 1000mm assembly travels at least 2.5x its size
+ const result = naturalizeMotion(lift, 20, 1000);
+ expect(result.type).toBe("linear");
+ if (result.type === "linear") {
+ expect(result.distance).toBe(50);
+ }
+ });
+
+ it("caps a long travel to a few of the part's own body-lengths", () => {
+ // 20mm part flying in 500mm → ceiling 3*20 + 5 = 65
+ const long = { ...lift, distance: 500 };
+ const result = naturalizeMotion(long, 20, 1000);
+ if (result.type === "linear") {
+ expect(result.distance).toBe(65);
+ } else {
+ throw new Error("expected linear motion");
+ }
+ });
+
+ it("caps a large part at the assembly-wide ceiling, not the raw travel", () => {
+ // 400mm part (not small), 2000mm travel. Per-part ceiling is 3*400+5=1205,
+ // but the assembly cap 0.35*1000=350 governs — nothing flies in from
+ // further than a third of the whole assembly, however large the part.
+ const long = { ...lift, distance: 2000 };
+ const result = naturalizeMotion(long, 400, 1000);
+ if (result.type === "linear") {
+ expect(result.distance).toBe(350);
+ } else {
+ throw new Error("expected linear motion");
+ }
+ });
+
+ it("keeps a large flat part's drop within the assembly (seal fly-out)", () => {
+ // 166mm diagonal, 288mm L-travel, 196mm assembly: the per-part ceiling
+ // alone (3*166+5=503) would let it fly in from 1.5x the whole assembly.
+ const seal: Motion = {
+ type: "L",
+ segments: [
+ { direction: [1, 0, 0], distance: 122 },
+ { direction: [0, 0, -1], distance: 166 }
+ ]
+ };
+ const result = naturalizeMotion(seal, 166, 196);
+ if (result.type !== "L") throw new Error("expected L motion");
+ const total = result.segments.reduce(
+ (sum, s) => sum + Math.abs(s.distance),
+ 0
+ );
+ expect(total).toBeCloseTo(196 * 0.35, 1); // ~68.6mm, a natural drop
+ });
+
+ it("leaves an in-band travel unchanged", () => {
+ const inBand = { ...lift, distance: 55 }; // within [50, 65] for a 20mm part
+ expect(naturalizeMotion(inBand, 20, 1000)).toBe(inBand);
+ });
+
+ it("floors then scales L segments proportionally", () => {
+ const motion: Motion = {
+ type: "L",
+ segments: [
+ { direction: [1, 0, 0], distance: 6 },
+ { direction: [0, 0, -1], distance: 4 }
+ ]
+ };
+ const result = naturalizeMotion(motion, 20, 1000); // total 10 → floor 50
+ if (result.type === "L") {
+ const total = result.segments.reduce((sum, s) => sum + s.distance, 0);
+ expect(total).toBeCloseTo(50);
+ expect(
+ result.segments[0]!.distance / result.segments[1]!.distance
+ ).toBeCloseTo(6 / 4);
+ } else {
+ throw new Error("expected L motion");
+ }
+ });
+
+ it("caps an over-long L total to the ceiling", () => {
+ const motion: Motion = {
+ type: "L",
+ segments: [
+ { direction: [1, 0, 0], distance: 180 },
+ { direction: [0, 0, -1], distance: 120 }
+ ]
+ };
+ const result = naturalizeMotion(motion, 20, 1000); // total 300 → ceiling 65
+ if (result.type === "L") {
+ const total = result.segments.reduce((sum, s) => sum + s.distance, 0);
+ expect(total).toBeCloseTo(65);
+ expect(
+ result.segments[0]!.distance / result.segments[1]!.distance
+ ).toBeCloseTo(180 / 120);
+ } else {
+ throw new Error("expected L motion");
+ }
+ });
+
+ it("does not touch none motions", () => {
+ const none = { type: "none" } as const;
+ expect(naturalizeMotion(none, 20, 1000)).toBe(none);
+ });
+});
+
+describe("displayMotionForStep", () => {
+ const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+ const graphIndex = indexAssemblyGraph({
+ version: 1,
+ unit: "mm",
+ sourceUnit: "mm",
+ componentCount: 2,
+ root: {
+ nodeId: "root",
+ name: "Assembly",
+ isAssembly: true,
+ geometryHash: null,
+ transform: IDENTITY,
+ bbox: { min: [-50, -50, 0], max: [50, 50, 20] },
+ volume: null,
+ color: null,
+ children: [
+ {
+ nodeId: "base",
+ name: "base",
+ isAssembly: false,
+ geometryHash: "hash-base",
+ transform: IDENTITY,
+ bbox: { min: [-50, -50, 0], max: [50, 50, 10] },
+ volume: 1000,
+ color: null,
+ children: []
+ },
+ {
+ nodeId: "top",
+ name: "top",
+ isAssembly: false,
+ geometryHash: "hash-top",
+ transform: IDENTITY,
+ bbox: { min: [-10, -10, 10], max: [10, 10, 20] },
+ volume: 1000,
+ color: null,
+ children: []
+ }
+ ]
+ }
+ });
+
+ const step = (
+ overrides: Partial<
+ Pick<AssemblyStep, "motion" | "componentNodeIds" | "flagged">
+ >
+ ) => ({
+ motion: { type: "none" } as Motion,
+ componentNodeIds: ["top"],
+ ...overrides
+ });
+
+ const present = new Set(["base"]);
+
+ it("keeps motion none for flagged steps — no fabricated fallback", () => {
+ expect(
+ displayMotionForStep(step({ flagged: true }), 1, graphIndex, present)
+ ).toEqual({ type: "none" });
+ });
+
+ it("synthesizes a fallback for unflagged none-motion steps after the base", () => {
+ const motion = displayMotionForStep(step({}), 1, graphIndex, present);
+ expect(motion.type).toBe("linear");
+ });
+
+ it("keeps the base step still", () => {
+ expect(displayMotionForStep(step({}), 0, graphIndex, present)).toEqual({
+ type: "none"
+ });
+ });
+
+ it("passes stored motions through untouched", () => {
+ const stored: Motion = {
+ type: "linear",
+ direction: [0, 0, -1],
+ distance: 5
+ };
+ expect(
+ displayMotionForStep(step({ motion: stored }), 1, graphIndex, present)
+ ).toBe(stored);
+ });
+
+ it("only treats present components as obstacles", () => {
+ // A canopy leaf over "top" that is NOT in the present set must not
+ // redirect the fallback.
+ const canopyIndex = indexAssemblyGraph({
+ ...graphIndex.graph,
+ root: {
+ ...graphIndex.graph.root,
+ children: [
+ ...graphIndex.graph.root.children,
+ {
+ nodeId: "canopy",
+ name: "canopy",
+ isAssembly: false,
+ geometryHash: "hash-canopy",
+ transform: IDENTITY,
+ bbox: { min: [-50, -50, 30], max: [50, 50, 40] },
+ volume: 1000,
+ color: null,
+ children: []
+ }
+ ]
+ }
+ });
+ const motion = displayMotionForStep(step({}), 1, canopyIndex, present);
+ // Insertion still approaches from above: the absent canopy doesn't block
+ if (motion.type !== "linear") throw new Error("expected linear");
+ expect(motion.direction[2]).toBe(-1);
+ });
+});
diff --git a/packages/viewer/src/display.ts b/packages/viewer/src/display.ts
new file mode 100644
index 0000000000..eeffcc247f
--- /dev/null
+++ b/packages/viewer/src/display.ts
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { synthesizeFallbackMotion } from "./fallback";
+import type { AssemblyGraphIndex } from "./graph";
+import type { AssemblyStep, Motion } from "./types";
+
+/**
+ * Display-only motion adjustments for playback. The stored plan is never
+ * changed: these only decide how a step's motion is shown.
+ */
+
+/**
+ * The motion a step should display. Flagged steps (the planner proved no
+ * collision-free path exists) keep motion "none" — the player fades their
+ * components in at the seated pose rather than animating a fabricated
+ * fly-through. Other non-first steps stored with "none" (legacy plans,
+ * manually authored steps) get the AABB fallback so components never pop into
+ * place; the fallback's obstacle world is `presentNodeIds`, the components
+ * already installed by EARLIER steps — later-step and never-installed
+ * components are not on the canvas. When no collision-free fallback exists the
+ * step keeps "none" and fades in. The first step is the base: placed, not
+ * inserted.
+ */
+export function displayMotionForStep(
+ step: Pick<AssemblyStep, "motion" | "componentNodeIds" | "flagged">,
+ index: number,
+ graphIndex: AssemblyGraphIndex | null,
+ presentNodeIds: ReadonlySet<string>
+): Motion {
+ if (
+ index === 0 ||
+ step.flagged ||
+ step.motion.type !== "none" ||
+ step.componentNodeIds.length === 0 ||
+ !graphIndex
+ ) {
+ return step.motion;
+ }
+ const fallback = synthesizeFallbackMotion(
+ graphIndex,
+ step.componentNodeIds,
+ presentNodeIds
+ );
+ return fallback && fallback.type !== "none" ? fallback : step.motion;
+}
+
+/** Components smaller than this fraction of the assembly count as "small". */
+const SMALL_COMPONENT_FRACTION = 0.15;
+/** Small components travel at least this many times their own size. */
+const SMALL_COMPONENT_TRAVEL_FACTOR = 2.5;
+/** No component travels more than this many times its own size, +margin. */
+const NATURAL_TRAVEL_FACTOR = 3;
+/** Additive slack (mm) on the travel ceiling so a seat still fully clears. */
+const NATURAL_TRAVEL_MARGIN_MM = 5;
+/**
+ * Hard ceiling as a fraction of the whole assembly. A big flat part (a gasket,
+ * a lid) has a huge diagonal, so the per-part ceiling alone would let its
+ * planner detour fly in from off-screen.
+ */
+const ASSEMBLY_TRAVEL_FRACTION = 0.35;
+
+/**
+ * Shapes a component's insertion travel into a natural band for playback so it
+ * neither pops (too short) nor flies in from across the assembly (too long).
+ * Safe because playback hides future-step parts and a part seats against the
+ * already-placed parts around it, not along its short approach.
+ */
+export function naturalizeMotion(
+ motion: Motion,
+ componentDiagonal: number,
+ assemblyDiagonal: number
+): Motion {
+ if (componentDiagonal <= 0 || assemblyDiagonal <= 0) return motion;
+
+ const isSmall =
+ componentDiagonal < assemblyDiagonal * SMALL_COMPONENT_FRACTION;
+ const floor = isSmall ? componentDiagonal * SMALL_COMPONENT_TRAVEL_FACTOR : 0;
+ // Per-part ceiling, then the assembly-wide cap; never below the floor so a
+ // borderline-small part keeps its readable minimum travel.
+ const ceiling = Math.max(
+ floor,
+ Math.min(
+ componentDiagonal * NATURAL_TRAVEL_FACTOR + NATURAL_TRAVEL_MARGIN_MM,
+ assemblyDiagonal * ASSEMBLY_TRAVEL_FRACTION
+ )
+ );
+ const clamp = (t: number) => Math.min(Math.max(t, floor), ceiling);
+
+ switch (motion.type) {
+ case "linear": {
+ const distance = clamp(motion.distance);
+ return distance === motion.distance ? motion : { ...motion, distance };
+ }
+ case "L": {
+ const total = motion.segments.reduce(
+ (sum, segment) => sum + Math.abs(segment.distance),
+ 0
+ );
+ if (total <= 0) return motion;
+ const target = clamp(total);
+ if (target === total) return motion;
+ const scale = target / total;
+ return {
+ ...motion,
+ segments: motion.segments.map((segment) => ({
+ ...segment,
+ distance: segment.distance * scale
+ }))
+ };
+ }
+ default:
+ return motion;
+ }
+}
diff --git a/packages/viewer/src/index.ts b/packages/viewer/src/index.ts
index 622680a523..a6b656de54 100644
--- a/packages/viewer/src/index.ts
+++ b/packages/viewer/src/index.ts
@@ -12,7 +12,9 @@ export {
} from "./AssemblyPlayer";
export { AssemblyViewer, type AssemblyViewerProps } from "./AssemblyViewer";
export { type FramingFit, fitFraming } from "./camera";
+export { buildStepClip, type StepClipOptions } from "./clip";
export { describeStep, type NamedUnit } from "./describe";
+export { displayMotionForStep, naturalizeMotion } from "./display";
export { synthesizeFallbackMotion } from "./fallback";
export {
type AssemblyGraphIndex,
@@ -20,25 +22,27 @@ export {
groupComponentNodeIds,
indexAssemblyGraph
} from "./graph";
+export {
+ type MotionKeyframeOptions,
+ type MotionKeyframes,
+ motionToKeyframes,
+ type Pose
+} from "./keyframes";
export {
ModelCanvas,
type ModelCanvasProps,
type ModelMetrics
} from "./ModelCanvas";
export {
- buildStepClip,
- displayMotionForStep,
- isPlayableMotion,
- type MotionKeyframeOptions,
- type MotionKeyframes,
- motionDuration,
- motionToKeyframes,
- motionTravelDistance,
- naturalizeMotion,
- type Pose,
- type StepClipOptions,
- stepClipTiming
-} from "./motion";
+ type BuildTurn,
+ describeOrientation,
+ isOrientation,
+ type OrientationPose,
+ type ResolvedOrientation,
+ resolveOrientations,
+ turnOrientation,
+ upForOrientation
+} from "./orientation";
export {
type AssemblyPlan,
type AssemblyPlanComponent,
@@ -50,6 +54,8 @@ export {
planMotionForComponents,
type StepPhase
} from "./plan";
+export { IDENTITY_QUAT as IDENTITY_ORIENTATION, sameOrientation } from "./quat";
+export { hasCustomMotion, isPlanFlagged, isSavedView } from "./step-flags";
export {
arrivalIndexByNode,
buildSubAssemblyPlan,
@@ -63,6 +69,11 @@ export {
usableSubAssemblies,
validateSubAssemblies
} from "./subassembly";
+export {
+ motionDuration,
+ motionTravelDistance,
+ stepClipTiming
+} from "./timing";
export type {
AssemblyGraph,
AssemblyGraphNode,
@@ -80,6 +91,7 @@ export type {
Vec3
} from "./types";
export { type UseAssemblyResult, useAssembly } from "./useAssembly";
+export { isPlayableMotion } from "./validate-motion";
export {
ASSEMBLY_VIEWS,
type ComponentVisual,
diff --git a/packages/viewer/src/keyframes.test.ts b/packages/viewer/src/keyframes.test.ts
new file mode 100644
index 0000000000..6aeb024280
--- /dev/null
+++ b/packages/viewer/src/keyframes.test.ts
@@ -0,0 +1,338 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { Quaternion, Vector3 } from "three";
+import { describe, expect, it } from "vitest";
+import {
+ type MotionKeyframes,
+ motionToKeyframes,
+ type Pose,
+ resampleEased,
+ waypointMatrix
+} from "./keyframes";
+import {
+ expectMonotonicTimes,
+ expectVectorClose,
+ IDENTITY_POSE,
+ lastIndex,
+ positionAt,
+ quaternionAt
+} from "./test-utils";
+import type { Motion, Vec3 } from "./types";
+
+describe("motionToKeyframes", () => {
+ it("returns null for none motions", () => {
+ expect(motionToKeyframes({ type: "none" }, IDENTITY_POSE)).toBeNull();
+ });
+
+ it("linear: starts displaced against the insertion direction and ends at the final pose", () => {
+ const basePose: Pose = {
+ position: [10, 20, 30],
+ quaternion: [0, 0, 0, 1]
+ };
+ const keyframes = motionToKeyframes(
+ { type: "linear", direction: [0, 0, -1], distance: 80 },
+ basePose,
+ { duration: 2 }
+ );
+ expect(keyframes).not.toBeNull();
+ if (!keyframes) return;
+
+ expectMonotonicTimes(keyframes);
+ expect(keyframes.times).toEqual([0, 2]);
+ expectVectorClose(positionAt(keyframes, 0), [10, 20, 110]);
+ expectVectorClose(
+ positionAt(keyframes, lastIndex(keyframes)),
+ [10, 20, 30]
+ );
+ expectVectorClose(quaternionAt(keyframes, 0), [0, 0, 0, 1]);
+ expectVectorClose(
+ quaternionAt(keyframes, lastIndex(keyframes)),
+ [0, 0, 0, 1]
+ );
+ });
+
+ it("linear: normalizes the direction vector", () => {
+ const keyframes = motionToKeyframes(
+ { type: "linear", direction: [0, 0, -10], distance: 80 },
+ IDENTITY_POSE
+ );
+ if (!keyframes) throw new Error("expected keyframes");
+ expectVectorClose(positionAt(keyframes, 0), [0, 0, 80]);
+ });
+
+ it("L: walks segments backwards from the final pose with proportional times", () => {
+ const keyframes = motionToKeyframes(
+ {
+ type: "L",
+ segments: [
+ { direction: [1, 0, 0], distance: 60 },
+ { direction: [0, 0, -1], distance: 20 }
+ ]
+ },
+ IDENTITY_POSE,
+ { duration: 2 }
+ );
+ if (!keyframes) throw new Error("expected keyframes");
+
+ expectMonotonicTimes(keyframes);
+ expect(keyframes.times.length).toBe(3);
+ // 60 of 80 mm in segment 1 → 75% of the duration
+ expect(keyframes.times[1]).toBeCloseTo(1.5);
+ expect(keyframes.times[2]).toBeCloseTo(2);
+ expectVectorClose(positionAt(keyframes, 0), [-60, 0, 20]);
+ expectVectorClose(positionAt(keyframes, 1), [0, 0, 20]);
+ expectVectorClose(positionAt(keyframes, 2), [0, 0, 0]);
+ });
+
+ it("helix: retracts by approach + pitch*turns and ends seated at the final pose", () => {
+ const basePose: Pose = {
+ position: [10, 20, 5],
+ quaternion: [0, 0, 0, 1]
+ };
+ const motion: Motion = {
+ type: "helix",
+ axis: [0, 0, -1],
+ origin: [10, 20, 5], // through the component center so rotation keeps position
+ pitch: 0.8,
+ turns: 6,
+ approach: 30
+ };
+ const keyframes = motionToKeyframes(motion, basePose, {
+ samplesPerTurn: 4
+ });
+ if (!keyframes) throw new Error("expected keyframes");
+
+ expectMonotonicTimes(keyframes);
+ // 1 approach start + 1 threading start + turns * samplesPerTurn samples
+ expect(keyframes.times.length).toBe(2 + 6 * 4);
+ expect(keyframes.quaternions.length).toBe((2 + 6 * 4) * 4);
+
+ // Start fully retracted along the axis: approach + pitch*turns = 34.8 mm
+ expectVectorClose(positionAt(keyframes, 0), [10, 20, 5 + 34.8]);
+ // Threading start: approach consumed, thread advance remaining
+ expectVectorClose(positionAt(keyframes, 1), [10, 20, 5 + 4.8]);
+ // Seated
+ const last = lastIndex(keyframes);
+ expectVectorClose(positionAt(keyframes, last), [10, 20, 5]);
+ expectVectorClose(quaternionAt(keyframes, last), [0, 0, 0, 1]);
+
+ // Rotation actually happens between thread samples (quarter turns)
+ const intermediate = quaternionAt(keyframes, 2);
+ const final = quaternionAt(keyframes, last);
+ const dot = intermediate.reduce(
+ (sum, value, index) => sum + value * (final[index] ?? Number.NaN),
+ 0
+ );
+ expect(Math.abs(dot)).toBeLessThan(0.999);
+ });
+
+ it("helix: ends exactly at the final pose even when origin is off-axis from the component", () => {
+ const basePose: Pose = {
+ position: [10, 0, 0],
+ quaternion: [0, 0, 0, 1]
+ };
+ const keyframes = motionToKeyframes(
+ {
+ type: "helix",
+ axis: [0, 0, 1],
+ origin: [0, 0, 0],
+ pitch: 1,
+ turns: 2.5,
+ approach: 10
+ },
+ basePose
+ );
+ if (!keyframes) throw new Error("expected keyframes");
+ const last = lastIndex(keyframes);
+ expectVectorClose(positionAt(keyframes, last), [10, 0, 0]);
+ expectVectorClose(quaternionAt(keyframes, last), [0, 0, 0, 1]);
+ expectMonotonicTimes(keyframes);
+ });
+
+ it("path: passes absolute world poses through, scaling t by duration", () => {
+ const keyframes = motionToKeyframes(
+ {
+ type: "path",
+ keyframes: [
+ { t: 0, position: [0, 0, 100], quaternion: [0, 0, 0, 1] },
+ { t: 0.5, position: [0, 50, 50], quaternion: [0, 0, 0, 1] },
+ { t: 1, position: [0, 0, 0], quaternion: [0, 0, 0, 1] }
+ ]
+ },
+ IDENTITY_POSE,
+ { duration: 2 }
+ );
+ if (!keyframes) throw new Error("expected keyframes");
+ expect(keyframes.times).toEqual([0, 1, 2]);
+ expectVectorClose(positionAt(keyframes, 0), [0, 0, 100]);
+ expectVectorClose(positionAt(keyframes, 1), [0, 50, 50]);
+ expectVectorClose(positionAt(keyframes, 2), [0, 0, 0]);
+ });
+
+ it("path: rejects non-monotonic times", () => {
+ expect(() =>
+ motionToKeyframes(
+ {
+ type: "path",
+ keyframes: [
+ { t: 0, position: [0, 0, 100], quaternion: [0, 0, 0, 1] },
+ { t: 0.5, position: [0, 0, 50], quaternion: [0, 0, 0, 1] },
+ { t: 0.5, position: [0, 0, 0], quaternion: [0, 0, 0, 1] }
+ ]
+ },
+ IDENTITY_POSE
+ )
+ ).toThrow(/strictly increasing/);
+ });
+
+ it("path: rejects a last keyframe that is not the final pose", () => {
+ expect(() =>
+ motionToKeyframes(
+ {
+ type: "path",
+ keyframes: [
+ { t: 0, position: [0, 0, 100], quaternion: [0, 0, 0, 1] },
+ { t: 1, position: [0, 0, 5], quaternion: [0, 0, 0, 1] }
+ ]
+ },
+ IDENTITY_POSE
+ )
+ ).toThrow(/final pose/);
+ });
+
+ it("path: requires t to span 0..1 and at least 2 keyframes", () => {
+ expect(() =>
+ motionToKeyframes(
+ {
+ type: "path",
+ keyframes: [{ t: 0, position: [0, 0, 0], quaternion: [0, 0, 0, 1] }]
+ },
+ IDENTITY_POSE
+ )
+ ).toThrow(/at least 2/);
+ expect(() =>
+ motionToKeyframes(
+ {
+ type: "path",
+ keyframes: [
+ { t: 0.1, position: [0, 0, 100], quaternion: [0, 0, 0, 1] },
+ { t: 1, position: [0, 0, 0], quaternion: [0, 0, 0, 1] }
+ ]
+ },
+ IDENTITY_POSE
+ )
+ ).toThrow(/span/);
+ });
+});
+
+describe("resampleEased", () => {
+ const straight: MotionKeyframes = {
+ times: [0, 2],
+ positions: [0, 0, 0, 0, 0, 100],
+ quaternions: [0, 0, 0, 1, 0, 0, 0, 1]
+ };
+
+ it("preserves both endpoints and the total duration exactly", () => {
+ const eased = resampleEased(straight);
+ expectVectorClose(positionAt(eased, 0), [0, 0, 0]);
+ expectVectorClose(positionAt(eased, lastIndex(eased)), [0, 0, 100]);
+ expect(eased.times[0]).toBe(0);
+ expect(eased.times[eased.times.length - 1]).toBeCloseTo(2);
+ expectMonotonicTimes(eased);
+ });
+
+ it("accelerates off the start and decelerates into the seat", () => {
+ const eased = resampleEased(straight);
+ // 21 samples → index 5 is u=0.25 (time 0.5), index 15 is u=0.75 (time 1.5)
+ expect(eased.times.length).toBe(21);
+ const early = positionAt(eased, 5)[2] ?? Number.NaN;
+ const late = positionAt(eased, 15)[2] ?? Number.NaN;
+ // slow start: quarter of the way in time, far less than a quarter of the way
+ expect(early).toBeLessThan(10); // easeInOutCubic(0.25)=0.0625 → ~6.25
+ // gentle settle: three quarters through time, most of the distance covered
+ expect(late).toBeGreaterThan(90); // easeInOutCubic(0.75)=0.9375 → ~93.75
+ // symmetric ease keeps the midpoint at the midpoint
+ expect(positionAt(eased, 10)[2] ?? Number.NaN).toBeCloseTo(50);
+ });
+
+ it("leaves a degenerate path unchanged", () => {
+ const single: MotionKeyframes = {
+ times: [0],
+ positions: [1, 2, 3],
+ quaternions: [0, 0, 0, 1]
+ };
+ expect(resampleEased(single)).toBe(single);
+ const zero: MotionKeyframes = {
+ times: [0, 0],
+ positions: [0, 0, 0, 0, 0, 0],
+ quaternions: [0, 0, 0, 1, 0, 0, 0, 1]
+ };
+ expect(resampleEased(zero)).toBe(zero);
+ });
+});
+
+describe("waypoints motion", () => {
+ const halfTurnZ: [number, number, number, number] = [0, 0, 1, 0];
+
+ it("turns the set about its pivot, then shifts it, and ends seated", () => {
+ const motion: Motion = {
+ type: "waypoints",
+ waypoints: [
+ { offset: [0, 0, 50], rotation: halfTurnZ },
+ { offset: [0, 0, 0], rotation: [0, 0, 0, 1] }
+ ]
+ };
+ // Part sits 10 mm along +X from the set's center at the origin.
+ const keyframes = motionToKeyframes(
+ motion,
+ { position: [10, 0, 0], quaternion: [0, 0, 0, 1] },
+ { duration: 2, pivot: [0, 0, 0] }
+ );
+ if (!keyframes) throw new Error("expected keyframes");
+ // 180° about Z swings the part to -X, then the offset lifts it.
+ expectVectorClose(positionAt(keyframes, 0), [-10, 0, 50]);
+ expectVectorClose(quaternionAt(keyframes, 0), [0, 0, 1, 0]);
+ const last = lastIndex(keyframes);
+ expectVectorClose(positionAt(keyframes, last), [10, 0, 0]);
+ expectVectorClose(quaternionAt(keyframes, last), [0, 0, 0, 1]);
+ expect(keyframes.times[last]).toBeCloseTo(2);
+ });
+
+ it("waypointMatrix turns about the pivot, then shifts", () => {
+ const turn = new Quaternion(...halfTurnZ);
+ const offset = new Vector3(0, 0, 50);
+ const point = (pivot: Vec3) =>
+ new Vector3(10, 0, 0)
+ .applyMatrix4(waypointMatrix(offset, turn, new Vector3(...pivot)))
+ .toArray();
+ expectVectorClose(point([0, 0, 0]), [-10, 0, 50]);
+ expectVectorClose(point([5, 0, 0]), [0, 0, 50]);
+ });
+
+ it("swings a part round the pivot through a turn, never across it", () => {
+ const halfTurnInPlace: Motion = {
+ type: "waypoints",
+ waypoints: [
+ { offset: [0, 0, 0], rotation: halfTurnZ },
+ { offset: [0, 0, 0], rotation: [0, 0, 0, 1] }
+ ]
+ };
+ const keyframes = motionToKeyframes(
+ halfTurnInPlace,
+ { position: [10, 0, 0], quaternion: [0, 0, 0, 1] },
+ { duration: 2, pivot: [0, 0, 0] }
+ );
+ if (!keyframes) throw new Error("expected keyframes");
+ // The track moves in a straight line between keyframes: each midpoint
+ // must stay near the 10 mm arc (two keyframes alone would pass through
+ // the pivot at mid-turn).
+ for (let i = 0; i < lastIndex(keyframes); i++) {
+ const [ax = 0, ay = 0, az = 0] = positionAt(keyframes, i);
+ const [bx = 0, by = 0, bz = 0] = positionAt(keyframes, i + 1);
+ const radius = Math.hypot((ax + bx) / 2, (ay + by) / 2, (az + bz) / 2);
+ expect(radius).toBeGreaterThan(9.5);
+ }
+ });
+});
diff --git a/packages/viewer/src/keyframes.ts b/packages/viewer/src/keyframes.ts
new file mode 100644
index 0000000000..8fa04866b9
--- /dev/null
+++ b/packages/viewer/src/keyframes.ts
@@ -0,0 +1,389 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { Matrix4, Quaternion, Vector3 } from "three";
+import { toQuaternion, toVector3 } from "./quat";
+import { motionDuration, waypointLegTravel } from "./timing";
+import type { Motion, Quat, Vec3 } from "./types";
+
+/**
+ * Pure keyframe construction for step motions. No WebGL — everything here is
+ * unit-testable in node.
+ *
+ * Motion JSON describes the INSERTION of a component: keyframes start at the
+ * displaced (pre-insertion) pose and end at the component's final (seated) pose.
+ * All poses produced by `motionToKeyframes` are world-space; `buildStepClip`
+ * converts them into each node's parent-local space for animation.
+ */
+
+/** A world-space pose: position + quaternion ([x, y, z, w]) */
+export type Pose = {
+ position: Vec3;
+ quaternion: Quat;
+};
+
+export type MotionKeyframes = {
+ /** Seconds, monotonically non-decreasing, starting at 0 */
+ times: number[];
+ /** Flat [x, y, z] per keyframe, world space */
+ positions: number[];
+ /** Flat [x, y, z, w] per keyframe, world space */
+ quaternions: number[];
+};
+
+export type MotionKeyframeOptions = {
+ /** Total animation duration in seconds. Defaults to `motionDuration(motion)`. */
+ duration?: number;
+ /** Helix sampling density (quaternion slerp needs <180° between samples). */
+ samplesPerTurn?: number;
+ /**
+ * Seated center of the whole moving set (one part, a rigid group, or a
+ * sub-assembly). A `waypoints` motion turns the set about it. Defaults to the
+ * part's own seated position.
+ */
+ pivot?: Vec3;
+};
+
+const DEFAULT_SAMPLES_PER_TURN = 4;
+/** A turning waypoint leg gets one keyframe per this much rotation (15°). */
+const WAYPOINT_TURN_STEP = Math.PI / 12;
+/** Sub-samples per motion when re-timing a straight path through ease-in-out. */
+export const EASE_SAMPLES = 20;
+
+export function easeInOutCubic(t: number): number {
+ return t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2;
+}
+
+/**
+ * A `waypoints` pose as a world transform of the seated set: turn about the
+ * pivot (the set's seated center), then shift by `offset`.
+ */
+export function waypointMatrix(
+ offset: Vector3,
+ rotation: Quaternion,
+ pivot: Vector3,
+ target: Matrix4 = new Matrix4()
+): Matrix4 {
+ const translation = pivot
+ .clone()
+ .applyQuaternion(rotation)
+ .negate()
+ .add(pivot)
+ .add(offset);
+ return target.makeRotationFromQuaternion(rotation).setPosition(translation);
+}
+
+function easeInOutCubicInverse(y: number): number {
+ return y < 0.5 ? Math.cbrt(y / 4) : 1 - Math.cbrt(2 * (1 - y)) / 2;
+}
+
+/**
+ * Re-times a piecewise-linear keyframe path through an ease-in-out velocity
+ * profile. The geometric path, both endpoints and the total duration are kept;
+ * only WHEN the part is at each point changes.
+ *
+ * Every input keyframe stays a keyframe (at its eased time), besides
+ * `EASE_SAMPLES` evenly spaced ones for the velocity profile. Uniform samples
+ * alone skip keyframes where the ease runs fast, and the track then cuts
+ * straight across a turning waypoint leg's arc.
+ */
+export function resampleEased(kf: MotionKeyframes): MotionKeyframes {
+ const n = kf.times.length;
+ const total = kf.times[n - 1] ?? 0;
+ if (n < 2 || total <= 0) return kf;
+
+ const fractions = new Set<number>();
+ for (let j = 0; j <= EASE_SAMPLES; j++) fractions.add(j / EASE_SAMPLES);
+ for (const time of kf.times) {
+ fractions.add(
+ easeInOutCubicInverse(Math.min(Math.max(time / total, 0), 1))
+ );
+ }
+ const sorted = [...fractions].sort((a, b) => a - b);
+ const samples = sorted.filter(
+ (u, index) => index === 0 || u - (sorted[index - 1] ?? 0) > 1e-9
+ );
+
+ const times: number[] = [];
+ const positions: number[] = [];
+ const quaternions: number[] = [];
+ const a = new Vector3();
+ const b = new Vector3();
+ const qa = new Quaternion();
+ const qb = new Quaternion();
+
+ let i = 0;
+ for (const u of samples) {
+ const s = easeInOutCubic(u) * total; // eased sample point along the path
+ while (i < n - 1 && (kf.times[i + 1] ?? total) < s) i++;
+ const t0 = kf.times[i] ?? 0;
+ const t1 = kf.times[i + 1] ?? total;
+ const span = t1 - t0;
+ const f = span > 1e-9 ? Math.min(Math.max((s - t0) / span, 0), 1) : 0;
+ a.fromArray(kf.positions, i * 3);
+ b.fromArray(kf.positions, (i + 1) * 3);
+ a.lerp(b, f);
+ qa.fromArray(kf.quaternions, i * 4);
+ qb.fromArray(kf.quaternions, (i + 1) * 4);
+ qa.slerp(qb, f);
+ times.push(u * total);
+ positions.push(a.x, a.y, a.z);
+ quaternions.push(qa.x, qa.y, qa.z, qa.w);
+ }
+ return { times, positions, quaternions };
+}
+
+/**
+ * Builds world-space insertion keyframes for a component whose final (seated)
+ * world pose is `basePose`. The last keyframe always equals `basePose`.
+ * Returns `null` for `none` motions.
+ */
+export function motionToKeyframes(
+ motion: Motion,
+ basePose: Pose,
+ options: MotionKeyframeOptions = {}
+): MotionKeyframes | null {
+ const duration = options.duration ?? motionDuration(motion);
+ const finalPosition = toVector3(basePose.position);
+ const finalQuaternion = toQuaternion(basePose.quaternion);
+
+ switch (motion.type) {
+ case "none":
+ return null;
+
+ case "linear": {
+ const direction = toVector3(motion.direction).normalize();
+ const start = finalPosition
+ .clone()
+ .addScaledVector(direction, -motion.distance);
+ return fromPoses(
+ [0, duration],
+ [
+ { position: start, quaternion: finalQuaternion },
+ { position: finalPosition, quaternion: finalQuaternion }
+ ]
+ );
+ }
+
+ case "L": {
+ // Walk backwards from the final pose through the segments (insertion
+ // order means the last segment ends at the final pose).
+ const positions: Vector3[] = [finalPosition.clone()];
+ for (let i = motion.segments.length - 1; i >= 0; i--) {
+ const segment = motion.segments[i];
+ const previous = positions[0];
+ if (!segment || !previous) continue;
+ const direction = toVector3(segment.direction).normalize();
+ positions.unshift(
+ previous.clone().addScaledVector(direction, -segment.distance)
+ );
+ }
+ const distances = motion.segments.map((s) => Math.abs(s.distance));
+ const total = distances.reduce((sum, d) => sum + d, 0);
+ const times: number[] = [0];
+ let elapsed = 0;
+ for (const distance of distances) {
+ elapsed += total > 0 ? (distance / total) * duration : 0;
+ times.push(elapsed);
+ }
+ if (total === 0) times[times.length - 1] = duration;
+ return fromPoses(
+ times,
+ positions.map((position) => ({
+ position,
+ quaternion: finalQuaternion
+ }))
+ );
+ }
+
+ case "helix": {
+ const axis = toVector3(motion.axis).normalize();
+ const origin = toVector3(motion.origin);
+ const samplesPerTurn = options.samplesPerTurn ?? DEFAULT_SAMPLES_PER_TURN;
+ const totalAngle = Math.PI * 2 * motion.turns;
+ const threadAdvance = motion.pitch * motion.turns;
+ const threadSamples = Math.max(
+ 1,
+ Math.ceil(motion.turns * samplesPerTurn)
+ );
+
+ // Pose at the given remaining (un-inserted) thread fraction. r = 1 is
+ // the start of threading, r = 0 is seated. The screw transform rotates
+ // the final pose backwards about `axis` through `origin` and retracts
+ // it along the axis.
+ const threadPoseAt = (
+ r: number
+ ): { position: Vector3; quaternion: Quaternion } => {
+ const unscrew = new Quaternion().setFromAxisAngle(
+ axis,
+ -totalAngle * r
+ );
+ const position = finalPosition
+ .clone()
+ .sub(origin)
+ .applyQuaternion(unscrew)
+ .add(origin)
+ .addScaledVector(axis, -threadAdvance * r);
+ const quaternion = unscrew.clone().multiply(finalQuaternion);
+ return { position, quaternion };
+ };
+
+ const approachWeight = Math.abs(motion.approach);
+ const threadWeight =
+ Math.abs(threadAdvance) > 0
+ ? Math.abs(threadAdvance)
+ : motion.turns > 0
+ ? 1
+ : 0;
+ const totalWeight = approachWeight + threadWeight;
+ const approachTime =
+ totalWeight > 0 ? (approachWeight / totalWeight) * duration : 0;
+
+ const times: number[] = [];
+ const poses: { position: Vector3; quaternion: Quaternion }[] = [];
+
+ const threadStart = threadPoseAt(1);
+ if (motion.approach !== 0) {
+ times.push(0);
+ poses.push({
+ position: threadStart.position
+ .clone()
+ .addScaledVector(axis, -motion.approach),
+ quaternion: threadStart.quaternion
+ });
+ }
+ times.push(approachTime);
+ poses.push(threadStart);
+ for (let i = 1; i <= threadSamples; i++) {
+ const progress = i / threadSamples;
+ times.push(approachTime + (duration - approachTime) * progress);
+ poses.push(threadPoseAt(1 - progress));
+ }
+ return fromPoses(times, poses);
+ }
+
+ case "path": {
+ const keyframes = motion.keyframes;
+ const first = keyframes[0];
+ const last = keyframes[keyframes.length - 1];
+ if (keyframes.length < 2 || !first || !last) {
+ throw new Error("path motion requires at least 2 keyframes");
+ }
+ for (let i = 1; i < keyframes.length; i++) {
+ const current = keyframes[i];
+ const previous = keyframes[i - 1];
+ if (!current || !previous) continue;
+ if (current.t <= previous.t) {
+ throw new Error(
+ "path motion keyframe times must be strictly increasing"
+ );
+ }
+ }
+ if (first.t !== 0 || last.t !== 1) {
+ throw new Error("path motion keyframes must span t = 0 to t = 1");
+ }
+ const epsilon = 1e-3;
+ if (
+ toVector3(last.position).distanceTo(finalPosition) > epsilon ||
+ Math.abs(toQuaternion(last.quaternion).dot(finalQuaternion)) <
+ 1 - epsilon
+ ) {
+ throw new Error(
+ "path motion's last keyframe must equal the component's final pose"
+ );
+ }
+ return fromPoses(
+ keyframes.map((keyframe) => keyframe.t * duration),
+ keyframes.map((keyframe) => ({
+ position: toVector3(keyframe.position),
+ quaternion: toQuaternion(keyframe.quaternion)
+ }))
+ );
+ }
+
+ case "waypoints": {
+ const waypoints = motion.waypoints;
+ const first = waypoints[0];
+ if (waypoints.length < 2 || !first) {
+ throw new Error("waypoints motion requires at least 2 waypoints");
+ }
+ const pivot = options.pivot ? toVector3(options.pivot) : finalPosition;
+ const matrix = new Matrix4();
+ const poseAt = (rotation: Quaternion, offset: Vector3) => ({
+ position: finalPosition
+ .clone()
+ .applyMatrix4(waypointMatrix(offset, rotation, pivot, matrix)),
+ quaternion: rotation.clone().multiply(finalQuaternion)
+ });
+ const legs = waypoints
+ .slice(1)
+ .map((waypoint, index) =>
+ waypointLegTravel(waypoints[index] ?? waypoint, waypoint)
+ );
+ const total = legs.reduce((sum, leg) => sum + leg, 0);
+
+ const times: number[] = [0];
+ const poses = [
+ poseAt(toQuaternion(first.rotation), toVector3(first.offset))
+ ];
+ let elapsed = 0;
+ // Keyframe tracks move position in a straight line, so a turning leg is
+ // sampled: between samples a part far from the pivot would cut across
+ // the arc instead of swinging round it with the rest of the set.
+ for (let leg = 0; leg < legs.length; leg++) {
+ const from = waypoints[leg];
+ const to = waypoints[leg + 1];
+ if (!from || !to) continue;
+ const fromRotation = toQuaternion(from.rotation);
+ const toRotation = toQuaternion(to.rotation);
+ const fromOffset = toVector3(from.offset);
+ const toOffset = toVector3(to.offset);
+ const legSeconds =
+ total > 0
+ ? ((legs[leg] ?? 0) / total) * duration
+ : duration / legs.length;
+ const samples = Math.max(
+ 1,
+ Math.ceil(fromRotation.angleTo(toRotation) / WAYPOINT_TURN_STEP)
+ );
+ for (let i = 1; i <= samples; i++) {
+ const f = i / samples;
+ times.push(elapsed + legSeconds * f);
+ poses.push(
+ poseAt(
+ fromRotation.clone().slerp(toRotation, f),
+ fromOffset.clone().lerp(toOffset, f)
+ )
+ );
+ }
+ elapsed += legSeconds;
+ }
+ // The last waypoint is the seat: land on it exactly.
+ times[times.length - 1] = duration;
+ poses[poses.length - 1] = {
+ position: finalPosition,
+ quaternion: finalQuaternion
+ };
+ return fromPoses(times, poses);
+ }
+ }
+}
+
+function fromPoses(
+ times: number[],
+ poses: { position: Vector3; quaternion: Quaternion }[]
+): MotionKeyframes {
+ const positions: number[] = [];
+ const quaternions: number[] = [];
+ for (const pose of poses) {
+ positions.push(pose.position.x, pose.position.y, pose.position.z);
+ quaternions.push(
+ pose.quaternion.x,
+ pose.quaternion.y,
+ pose.quaternion.z,
+ pose.quaternion.w
+ );
+ }
+ return { times, positions, quaternions };
+}
diff --git a/packages/viewer/src/motion.test.ts b/packages/viewer/src/motion.test.ts
deleted file mode 100644
index 1258e14c58..0000000000
--- a/packages/viewer/src/motion.test.ts
+++ /dev/null
@@ -1,1208 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
-// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-
-import {
- type AnimationClip,
- AnimationMixer,
- Group,
- Matrix4,
- Object3D,
- Quaternion,
- Vector3
-} from "three";
-import { describe, expect, it } from "vitest";
-import { indexAssemblyGraph } from "./graph";
-import {
- buildStepClip,
- DEFAULT_WAYPOINT_DISTANCE,
- displayMotionForStep,
- editorWaypointsToMotion,
- fadeProgress,
- isPlayableMotion,
- type MotionKeyframes,
- motionDuration,
- motionToEditorWaypoints,
- motionToKeyframes,
- motionToWaypoints,
- motionTravelDistance,
- naturalizeMotion,
- type Pose,
- resampleEased,
- stepClipTiming,
- waypointsToMotion
-} from "./motion";
-import type { AssemblyStep, Motion, Vec3 } from "./types";
-
-const IDENTITY_POSE: Pose = {
- position: [0, 0, 0],
- quaternion: [0, 0, 0, 1]
-};
-
-function positionAt(keyframes: MotionKeyframes, index: number): number[] {
- return keyframes.positions.slice(index * 3, index * 3 + 3);
-}
-
-function quaternionAt(keyframes: MotionKeyframes, index: number): number[] {
- return keyframes.quaternions.slice(index * 4, index * 4 + 4);
-}
-
-function lastIndex(keyframes: MotionKeyframes): number {
- return keyframes.times.length - 1;
-}
-
-function expectVectorClose(actual: number[], expected: number[]) {
- expect(actual.length).toBe(expected.length);
- actual.forEach((value, index) => {
- expect(value).toBeCloseTo(expected[index] ?? Number.NaN, 6);
- });
-}
-
-function expectMonotonicTimes(keyframes: MotionKeyframes) {
- expect(keyframes.times[0]).toBe(0);
- for (let i = 1; i < keyframes.times.length; i++) {
- expect(keyframes.times[i]).toBeGreaterThan(
- keyframes.times[i - 1] ?? Number.POSITIVE_INFINITY
- );
- }
-}
-
-function makeStep(motion: Motion, componentNodeIds: string[]): AssemblyStep {
- return {
- id: "step-1",
- title: null,
- instructionText: null,
- componentNodeIds,
- motion,
- camera: null,
- fastener: null
- };
-}
-
-describe("motionTravelDistance", () => {
- it("computes travel for each motion type", () => {
- expect(
- motionTravelDistance({
- type: "linear",
- direction: [0, 0, -1],
- distance: 80
- })
- ).toBe(80);
- expect(
- motionTravelDistance({
- type: "L",
- segments: [
- { direction: [1, 0, 0], distance: 60 },
- { direction: [0, 0, -1], distance: 20 }
- ]
- })
- ).toBe(80);
- expect(
- motionTravelDistance({
- type: "helix",
- axis: [0, 0, -1],
- origin: [0, 0, 0],
- pitch: 0.8,
- turns: 6,
- approach: 30
- })
- ).toBeCloseTo(34.8);
- expect(motionTravelDistance({ type: "none" })).toBe(0);
- });
-});
-
-describe("motionDuration", () => {
- it("scales with travel distance and clamps to 1-4 s", () => {
- expect(
- motionDuration({ type: "linear", direction: [0, 0, 1], distance: 6 })
- ).toBe(1);
- expect(
- motionDuration({ type: "linear", direction: [0, 0, 1], distance: 120 })
- ).toBeCloseTo(2);
- expect(
- motionDuration({ type: "linear", direction: [0, 0, 1], distance: 6000 })
- ).toBe(4);
- expect(motionDuration({ type: "none" })).toBe(0);
- });
-});
-
-describe("motionToKeyframes", () => {
- it("returns null for none motions", () => {
- expect(motionToKeyframes({ type: "none" }, IDENTITY_POSE)).toBeNull();
- });
-
- it("linear: starts displaced against the insertion direction and ends at the final pose", () => {
- const basePose: Pose = {
- position: [10, 20, 30],
- quaternion: [0, 0, 0, 1]
- };
- const keyframes = motionToKeyframes(
- { type: "linear", direction: [0, 0, -1], distance: 80 },
- basePose,
- { duration: 2 }
- );
- expect(keyframes).not.toBeNull();
- if (!keyframes) return;
-
- expectMonotonicTimes(keyframes);
- expect(keyframes.times).toEqual([0, 2]);
- expectVectorClose(positionAt(keyframes, 0), [10, 20, 110]);
- expectVectorClose(
- positionAt(keyframes, lastIndex(keyframes)),
- [10, 20, 30]
- );
- expectVectorClose(quaternionAt(keyframes, 0), [0, 0, 0, 1]);
- expectVectorClose(
- quaternionAt(keyframes, lastIndex(keyframes)),
- [0, 0, 0, 1]
- );
- });
-
- it("linear: normalizes the direction vector", () => {
- const keyframes = motionToKeyframes(
- { type: "linear", direction: [0, 0, -10], distance: 80 },
- IDENTITY_POSE
- );
- if (!keyframes) throw new Error("expected keyframes");
- expectVectorClose(positionAt(keyframes, 0), [0, 0, 80]);
- });
-
- it("L: walks segments backwards from the final pose with proportional times", () => {
- const keyframes = motionToKeyframes(
- {
- type: "L",
- segments: [
- { direction: [1, 0, 0], distance: 60 },
- { direction: [0, 0, -1], distance: 20 }
- ]
- },
- IDENTITY_POSE,
- { duration: 2 }
- );
- if (!keyframes) throw new Error("expected keyframes");
-
- expectMonotonicTimes(keyframes);
- expect(keyframes.times.length).toBe(3);
- // 60 of 80 mm in segment 1 → 75% of the duration
- expect(keyframes.times[1]).toBeCloseTo(1.5);
- expect(keyframes.times[2]).toBeCloseTo(2);
- expectVectorClose(positionAt(keyframes, 0), [-60, 0, 20]);
- expectVectorClose(positionAt(keyframes, 1), [0, 0, 20]);
- expectVectorClose(positionAt(keyframes, 2), [0, 0, 0]);
- });
-
- it("helix: retracts by approach + pitch*turns and ends seated at the final pose", () => {
- const basePose: Pose = {
- position: [10, 20, 5],
- quaternion: [0, 0, 0, 1]
- };
- const motion: Motion = {
- type: "helix",
- axis: [0, 0, -1],
- origin: [10, 20, 5], // through the component center so rotation keeps position
- pitch: 0.8,
- turns: 6,
- approach: 30
- };
- const keyframes = motionToKeyframes(motion, basePose, {
- samplesPerTurn: 4
- });
- if (!keyframes) throw new Error("expected keyframes");
-
- expectMonotonicTimes(keyframes);
- // 1 approach start + 1 threading start + turns * samplesPerTurn samples
- expect(keyframes.times.length).toBe(2 + 6 * 4);
- expect(keyframes.quaternions.length).toBe((2 + 6 * 4) * 4);
-
- // Start fully retracted along the axis: approach + pitch*turns = 34.8 mm
- expectVectorClose(positionAt(keyframes, 0), [10, 20, 5 + 34.8]);
- // Threading start: approach consumed, thread advance remaining
- expectVectorClose(positionAt(keyframes, 1), [10, 20, 5 + 4.8]);
- // Seated
- const last = lastIndex(keyframes);
- expectVectorClose(positionAt(keyframes, last), [10, 20, 5]);
- expectVectorClose(quaternionAt(keyframes, last), [0, 0, 0, 1]);
-
- // Rotation actually happens between thread samples (quarter turns)
- const intermediate = quaternionAt(keyframes, 2);
- const final = quaternionAt(keyframes, last);
- const dot = intermediate.reduce(
- (sum, value, index) => sum + value * (final[index] ?? Number.NaN),
- 0
- );
- expect(Math.abs(dot)).toBeLessThan(0.999);
- });
-
- it("helix: ends exactly at the final pose even when origin is off-axis from the component", () => {
- const basePose: Pose = {
- position: [10, 0, 0],
- quaternion: [0, 0, 0, 1]
- };
- const keyframes = motionToKeyframes(
- {
- type: "helix",
- axis: [0, 0, 1],
- origin: [0, 0, 0],
- pitch: 1,
- turns: 2.5,
- approach: 10
- },
- basePose
- );
- if (!keyframes) throw new Error("expected keyframes");
- const last = lastIndex(keyframes);
- expectVectorClose(positionAt(keyframes, last), [10, 0, 0]);
- expectVectorClose(quaternionAt(keyframes, last), [0, 0, 0, 1]);
- expectMonotonicTimes(keyframes);
- });
-
- it("path: passes absolute world poses through, scaling t by duration", () => {
- const keyframes = motionToKeyframes(
- {
- type: "path",
- keyframes: [
- { t: 0, position: [0, 0, 100], quaternion: [0, 0, 0, 1] },
- { t: 0.5, position: [0, 50, 50], quaternion: [0, 0, 0, 1] },
- { t: 1, position: [0, 0, 0], quaternion: [0, 0, 0, 1] }
- ]
- },
- IDENTITY_POSE,
- { duration: 2 }
- );
- if (!keyframes) throw new Error("expected keyframes");
- expect(keyframes.times).toEqual([0, 1, 2]);
- expectVectorClose(positionAt(keyframes, 0), [0, 0, 100]);
- expectVectorClose(positionAt(keyframes, 1), [0, 50, 50]);
- expectVectorClose(positionAt(keyframes, 2), [0, 0, 0]);
- });
-
- it("path: rejects non-monotonic times", () => {
- expect(() =>
- motionToKeyframes(
- {
- type: "path",
- keyframes: [
- { t: 0, position: [0, 0, 100], quaternion: [0, 0, 0, 1] },
- { t: 0.5, position: [0, 0, 50], quaternion: [0, 0, 0, 1] },
- { t: 0.5, position: [0, 0, 0], quaternion: [0, 0, 0, 1] }
- ]
- },
- IDENTITY_POSE
- )
- ).toThrow(/strictly increasing/);
- });
-
- it("path: rejects a last keyframe that is not the final pose", () => {
- expect(() =>
- motionToKeyframes(
- {
- type: "path",
- keyframes: [
- { t: 0, position: [0, 0, 100], quaternion: [0, 0, 0, 1] },
- { t: 1, position: [0, 0, 5], quaternion: [0, 0, 0, 1] }
- ]
- },
- IDENTITY_POSE
- )
- ).toThrow(/final pose/);
- });
-
- it("path: requires t to span 0..1 and at least 2 keyframes", () => {
- expect(() =>
- motionToKeyframes(
- {
- type: "path",
- keyframes: [{ t: 0, position: [0, 0, 0], quaternion: [0, 0, 0, 1] }]
- },
- IDENTITY_POSE
- )
- ).toThrow(/at least 2/);
- expect(() =>
- motionToKeyframes(
- {
- type: "path",
- keyframes: [
- { t: 0.1, position: [0, 0, 100], quaternion: [0, 0, 0, 1] },
- { t: 1, position: [0, 0, 0], quaternion: [0, 0, 0, 1] }
- ]
- },
- IDENTITY_POSE
- )
- ).toThrow(/span/);
- });
-});
-
-describe("buildStepClip", () => {
- function makeAssembly() {
- const root = new Group();
- const parent = new Group();
- parent.position.set(5, 0, 0);
- root.add(parent);
- const component = new Object3D();
- component.position.set(1, 2, 3);
- component.userData.nodeId = "node-a";
- parent.add(component);
- root.updateMatrixWorld(true);
- return {
- root,
- component,
- parent,
- nodesById: new Map([["node-a", component]])
- };
- }
-
- it("returns null for none motions and for steps with no resolvable components", () => {
- const { nodesById } = makeAssembly();
- expect(
- buildStepClip(makeStep({ type: "none" }, ["node-a"]), nodesById)
- ).toBeNull();
- expect(
- buildStepClip(
- makeStep({ type: "linear", direction: [1, 0, 0], distance: 10 }, []),
- nodesById
- )
- ).toBeNull();
- expect(
- buildStepClip(
- makeStep({ type: "linear", direction: [1, 0, 0], distance: 10 }, [
- "missing-node"
- ]),
- nodesById
- )
- ).toBeNull();
- });
-
- it("builds uuid-bound position/quaternion tracks in parent-local space with a seated hold", () => {
- const { component, nodesById } = makeAssembly();
- const step = makeStep(
- { type: "linear", direction: [1, 0, 0], distance: 10 },
- ["node-a"]
- );
- const clip = buildStepClip(step, nodesById, {
- duration: 2,
- holdSeconds: 0.5
- });
- expect(clip).not.toBeNull();
- if (!clip) return;
-
- expect(clip.name).toBe("step:step-1");
- expect(clip.duration).toBeCloseTo(2.5);
- expect(clip.tracks.length).toBe(2);
- const [positionTrack, quaternionTrack] = clip.tracks;
- if (!positionTrack || !quaternionTrack) throw new Error("expected tracks");
- expect(positionTrack.name).toBe(`${component.uuid}.position`);
- expect(quaternionTrack.name).toBe(`${component.uuid}.quaternion`);
-
- // World start [6,2,3] - [10,0,0] = [-4,2,3] → parent-local [-9,2,3]
- expectVectorClose([...positionTrack.values.slice(0, 3)], [-9, 2, 3]);
- // Seated keyframe and hold keyframe both equal the component's local pose
- expectVectorClose([...positionTrack.values.slice(-6, -3)], [1, 2, 3]);
- expectVectorClose([...positionTrack.values.slice(-3)], [1, 2, 3]);
- // Hold keyframe extends the timeline
- const times = positionTrack.times;
- expect(times[times.length - 1]).toBeCloseTo(2.5);
- expect(times[times.length - 2]).toBeCloseTo(2);
- });
-
- it("glides a carried-in unit from beside the build, then inserts", () => {
- const { nodesById } = makeAssembly();
- const motion: Motion = {
- type: "linear",
- direction: [1, 0, 0],
- distance: 10
- };
- const clip = buildStepClip(makeStep(motion, ["node-a"]), nodesById, {
- duration: 2,
- holdSeconds: 0.5,
- glide: { offset: [0, 100, 0], seconds: 1.2 }
- });
- if (!clip) throw new Error("expected clip");
- expect(clip.duration).toBeCloseTo(1.2 + 2 + 0.5);
-
- const [positionTrack] = clip.tracks;
- if (!positionTrack) throw new Error("expected tracks");
- const values = [...positionTrack.values];
- const times = [...positionTrack.times];
- // Seated world [6,2,3] + offset [0,100,0] → parent-local [1,102,3]
- expectVectorClose(values.slice(0, 3), [1, 102, 3]);
- // Glide ends at the linear insertion start: world [-4,2,3] → local [-9,2,3]
- const glideEnd = times.findIndex((time) => Math.abs(time - 1.2) < 1e-5);
- expect(glideEnd).toBeGreaterThan(0);
- expectVectorClose(values.slice(glideEnd * 3, glideEnd * 3 + 3), [-9, 2, 3]);
- // Still ends seated, with the hold
- expectVectorClose(values.slice(-6, -3), [1, 2, 3]);
- expect(times[times.length - 2]).toBeCloseTo(3.2);
- for (let i = 1; i < times.length; i++) {
- expect(times[i]).toBeGreaterThan(
- times[i - 1] ?? Number.POSITIVE_INFINITY
- );
- }
- });
-
- it("glides a none-motion carry-in step straight to the seat", () => {
- const { nodesById } = makeAssembly();
- const clip = buildStepClip(
- makeStep({ type: "none" }, ["node-a"]),
- nodesById,
- {
- holdSeconds: 0,
- glide: { offset: [50, 0, 0], seconds: 1.2 }
- }
- );
- if (!clip) throw new Error("expected clip");
- expect(clip.duration).toBeCloseTo(1.2);
- const [positionTrack] = clip.tracks;
- if (!positionTrack) throw new Error("expected tracks");
- const values = [...positionTrack.values];
- expectVectorClose(values.slice(0, 3), [51, 2, 3]);
- expectVectorClose(values.slice(-3), [1, 2, 3]);
- });
-
- it("glides only the carried unit; the step's own parts wait at their start", () => {
- const { nodesById } = makeAssembly();
- const motion: Motion = {
- type: "linear",
- direction: [1, 0, 0],
- distance: 10
- };
- const clip = buildStepClip(makeStep(motion, ["node-a"]), nodesById, {
- duration: 2,
- holdSeconds: 0,
- glide: { offset: [0, 100, 0], seconds: 1.2, nodeIds: ["other"] }
- });
- if (!clip) throw new Error("expected clip");
- const [positionTrack] = clip.tracks;
- if (!positionTrack) throw new Error("expected tracks");
- const values = [...positionTrack.values];
- const times = [...positionTrack.times];
- // Not carried: sits at its insertion start (local [-9,2,3]) through the glide.
- expectVectorClose(values.slice(0, 3), [-9, 2, 3]);
- const glideEnd = times.findIndex((time) => Math.abs(time - 1.2) < 1e-5);
- expectVectorClose(values.slice(glideEnd * 3, glideEnd * 3 + 3), [-9, 2, 3]);
- expectVectorClose(values.slice(-3), [1, 2, 3]);
- });
-
- it("converts world-space motion into the local space of a rotated parent", () => {
- const root = new Group();
- const parent = new Group();
- parent.rotation.z = Math.PI / 2;
- root.add(parent);
- const component = new Object3D();
- component.userData.nodeId = "node-b";
- parent.add(component);
- root.updateMatrixWorld(true);
- const nodesById = new Map([["node-b", component]]);
-
- const step = makeStep(
- { type: "linear", direction: [0, 1, 0], distance: 10 },
- ["node-b"]
- );
- const clip = buildStepClip(step, nodesById, { holdSeconds: 0 });
- if (!clip) throw new Error("expected clip");
-
- const expectedStart = new Vector3(0, -10, 0).applyMatrix4(
- new Matrix4().copy(parent.matrixWorld).invert()
- );
- const [positionTrack, quaternionTrack] = clip.tracks;
- if (!positionTrack || !quaternionTrack) throw new Error("expected tracks");
- expectVectorClose(
- [...positionTrack.values.slice(0, 3)],
- expectedStart.toArray()
- );
- expectVectorClose([...positionTrack.values.slice(-3)], [0, 0, 0]);
-
- const localQuaternion = new Quaternion().copy(component.quaternion);
- expectVectorClose(
- [...quaternionTrack.values.slice(-4)],
- [
- localQuaternion.x,
- localQuaternion.y,
- localQuaternion.z,
- localQuaternion.w
- ]
- );
- });
-
- it("clamps the default duration to 1-4 s based on travel distance", () => {
- const { nodesById } = makeAssembly();
- const short = buildStepClip(
- makeStep({ type: "linear", direction: [1, 0, 0], distance: 1 }, [
- "node-a"
- ]),
- nodesById,
- { holdSeconds: 0 }
- );
- const long = buildStepClip(
- makeStep({ type: "linear", direction: [1, 0, 0], distance: 6000 }, [
- "node-a"
- ]),
- nodesById,
- { holdSeconds: 0 }
- );
- expect(short?.duration).toBeCloseTo(1);
- expect(long?.duration).toBeCloseTo(4);
- });
-
- it("drives nodes through an AnimationMixer via uuid-bound tracks", () => {
- const { root, component, nodesById } = makeAssembly();
- const step = makeStep(
- { type: "linear", direction: [1, 0, 0], distance: 10 },
- ["node-a"]
- );
- const clip = buildStepClip(step, nodesById, {
- duration: 2,
- holdSeconds: 0
- });
- if (!clip) throw new Error("expected clip");
-
- const mixer = new AnimationMixer(root);
- mixer.clipAction(clip).play();
-
- mixer.update(0); // t = 0 → displaced start pose (local [-9, 2, 3])
- expect(component.position.x).toBeCloseTo(-9);
- mixer.update(1); // t = 1 → halfway back to seated
- expect(component.position.x).toBeCloseTo(-4);
- expect(component.position.y).toBeCloseTo(2);
- expect(component.position.z).toBeCloseTo(3);
- });
-});
-
-describe("resampleEased", () => {
- const straight: MotionKeyframes = {
- times: [0, 2],
- positions: [0, 0, 0, 0, 0, 100],
- quaternions: [0, 0, 0, 1, 0, 0, 0, 1]
- };
-
- it("preserves both endpoints and the total duration exactly", () => {
- const eased = resampleEased(straight);
- expectVectorClose(positionAt(eased, 0), [0, 0, 0]);
- expectVectorClose(positionAt(eased, lastIndex(eased)), [0, 0, 100]);
- expect(eased.times[0]).toBe(0);
- expect(eased.times[eased.times.length - 1]).toBeCloseTo(2);
- expectMonotonicTimes(eased);
- });
-
- it("accelerates off the start and decelerates into the seat", () => {
- const eased = resampleEased(straight);
- // 21 samples → index 5 is u=0.25 (time 0.5), index 15 is u=0.75 (time 1.5)
- expect(eased.times.length).toBe(21);
- const early = positionAt(eased, 5)[2] ?? Number.NaN;
- const late = positionAt(eased, 15)[2] ?? Number.NaN;
- // slow start: quarter of the way in time, far less than a quarter of the way
- expect(early).toBeLessThan(10); // easeInOutCubic(0.25)=0.0625 → ~6.25
- // gentle settle: three quarters through time, most of the distance covered
- expect(late).toBeGreaterThan(90); // easeInOutCubic(0.75)=0.9375 → ~93.75
- // symmetric ease keeps the midpoint at the midpoint
- expect(positionAt(eased, 10)[2] ?? Number.NaN).toBeCloseTo(50);
- });
-
- it("leaves a degenerate path unchanged", () => {
- const single: MotionKeyframes = {
- times: [0],
- positions: [1, 2, 3],
- quaternions: [0, 0, 0, 1]
- };
- expect(resampleEased(single)).toBe(single);
- const zero: MotionKeyframes = {
- times: [0, 0],
- positions: [0, 0, 0, 0, 0, 0],
- quaternions: [0, 0, 0, 1, 0, 0, 0, 1]
- };
- expect(resampleEased(zero)).toBe(zero);
- });
-});
-
-describe("naturalizeMotion", () => {
- const lift = {
- type: "linear",
- direction: [0, 0, -1] as [number, number, number],
- distance: 15
- } as const;
-
- it("floors small-component travel to a readable distance", () => {
- // 20mm bolt in a 1000mm assembly travels at least 2.5x its size
- const result = naturalizeMotion(lift, 20, 1000);
- expect(result.type).toBe("linear");
- if (result.type === "linear") {
- expect(result.distance).toBe(50);
- }
- });
-
- it("caps a long travel to a few of the part's own body-lengths", () => {
- // 20mm part flying in 500mm → ceiling 3*20 + 5 = 65
- const long = { ...lift, distance: 500 };
- const result = naturalizeMotion(long, 20, 1000);
- if (result.type === "linear") {
- expect(result.distance).toBe(65);
- } else {
- throw new Error("expected linear motion");
- }
- });
-
- it("caps a large part at the assembly-wide ceiling, not the raw travel", () => {
- // 400mm part (not small), 2000mm travel. Per-part ceiling is 3*400+5=1205,
- // but the assembly cap 0.35*1000=350 governs — nothing flies in from
- // further than a third of the whole assembly, however large the part.
- const long = { ...lift, distance: 2000 };
- const result = naturalizeMotion(long, 400, 1000);
- if (result.type === "linear") {
- expect(result.distance).toBe(350);
- } else {
- throw new Error("expected linear motion");
- }
- });
-
- it("keeps a large flat part's drop within the assembly (seal fly-out)", () => {
- // The SA BCU seal: 166mm diagonal, 288mm L-travel, 196mm assembly. Without
- // the assembly cap its ceiling is 3*166+5=503, so 288mm passed through and
- // it flew in from 1.5x the whole assembly.
- const seal: Motion = {
- type: "L",
- segments: [
- { direction: [1, 0, 0], distance: 122 },
- { direction: [0, 0, -1], distance: 166 }
- ]
- };
- const result = naturalizeMotion(seal, 166, 196);
- if (result.type !== "L") throw new Error("expected L motion");
- const total = result.segments.reduce(
- (sum, s) => sum + Math.abs(s.distance),
- 0
- );
- expect(total).toBeCloseTo(196 * 0.35, 1); // ~68.6mm, a natural drop
- });
-
- it("leaves an in-band travel unchanged", () => {
- const inBand = { ...lift, distance: 55 }; // within [50, 65] for a 20mm part
- expect(naturalizeMotion(inBand, 20, 1000)).toBe(inBand);
- });
-
- it("floors then scales L segments proportionally", () => {
- const motion: Motion = {
- type: "L",
- segments: [
- { direction: [1, 0, 0], distance: 6 },
- { direction: [0, 0, -1], distance: 4 }
- ]
- };
- const result = naturalizeMotion(motion, 20, 1000); // total 10 → floor 50
- if (result.type === "L") {
- const total = result.segments.reduce((sum, s) => sum + s.distance, 0);
- expect(total).toBeCloseTo(50);
- expect(
- result.segments[0]!.distance / result.segments[1]!.distance
- ).toBeCloseTo(6 / 4);
- } else {
- throw new Error("expected L motion");
- }
- });
-
- it("caps an over-long L total to the ceiling", () => {
- const motion: Motion = {
- type: "L",
- segments: [
- { direction: [1, 0, 0], distance: 180 },
- { direction: [0, 0, -1], distance: 120 }
- ]
- };
- const result = naturalizeMotion(motion, 20, 1000); // total 300 → ceiling 65
- if (result.type === "L") {
- const total = result.segments.reduce((sum, s) => sum + s.distance, 0);
- expect(total).toBeCloseTo(65);
- expect(
- result.segments[0]!.distance / result.segments[1]!.distance
- ).toBeCloseTo(180 / 120);
- } else {
- throw new Error("expected L motion");
- }
- });
-
- it("does not touch none motions", () => {
- const none = { type: "none" } as const;
- expect(naturalizeMotion(none, 20, 1000)).toBe(none);
- });
-});
-
-describe("displayMotionForStep", () => {
- const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
- const graphIndex = indexAssemblyGraph({
- version: 1,
- unit: "mm",
- sourceUnit: "mm",
- componentCount: 2,
- root: {
- nodeId: "root",
- name: "Assembly",
- isAssembly: true,
- geometryHash: null,
- transform: IDENTITY,
- bbox: { min: [-50, -50, 0], max: [50, 50, 20] },
- volume: null,
- color: null,
- children: [
- {
- nodeId: "base",
- name: "base",
- isAssembly: false,
- geometryHash: "hash-base",
- transform: IDENTITY,
- bbox: { min: [-50, -50, 0], max: [50, 50, 10] },
- volume: 1000,
- color: null,
- children: []
- },
- {
- nodeId: "top",
- name: "top",
- isAssembly: false,
- geometryHash: "hash-top",
- transform: IDENTITY,
- bbox: { min: [-10, -10, 10], max: [10, 10, 20] },
- volume: 1000,
- color: null,
- children: []
- }
- ]
- }
- });
-
- const step = (
- overrides: Partial<
- Pick<AssemblyStep, "motion" | "componentNodeIds" | "flagged">
- >
- ) => ({
- motion: { type: "none" } as Motion,
- componentNodeIds: ["top"],
- ...overrides
- });
-
- const present = new Set(["base"]);
-
- it("keeps motion none for flagged steps — no fabricated fallback", () => {
- expect(
- displayMotionForStep(step({ flagged: true }), 1, graphIndex, present)
- ).toEqual({ type: "none" });
- });
-
- it("synthesizes a fallback for unflagged none-motion steps after the base", () => {
- const motion = displayMotionForStep(step({}), 1, graphIndex, present);
- expect(motion.type).toBe("linear");
- });
-
- it("keeps the base step still", () => {
- expect(displayMotionForStep(step({}), 0, graphIndex, present)).toEqual({
- type: "none"
- });
- });
-
- it("passes stored motions through untouched", () => {
- const stored: Motion = {
- type: "linear",
- direction: [0, 0, -1],
- distance: 5
- };
- expect(
- displayMotionForStep(step({ motion: stored }), 1, graphIndex, present)
- ).toBe(stored);
- });
-
- it("only treats present components as obstacles", () => {
- // "base" fully covers the region above "top"… here instead: a canopy leaf
- // over "top" that is NOT in the present set must not redirect the fallback
- const canopyIndex = indexAssemblyGraph({
- ...graphIndex.graph,
- root: {
- ...graphIndex.graph.root,
- children: [
- ...graphIndex.graph.root.children,
- {
- nodeId: "canopy",
- name: "canopy",
- isAssembly: false,
- geometryHash: "hash-canopy",
- transform: IDENTITY,
- bbox: { min: [-50, -50, 30], max: [50, 50, 40] },
- volume: 1000,
- color: null,
- children: []
- }
- ]
- }
- });
- const motion = displayMotionForStep(step({}), 1, canopyIndex, present);
- // Insertion still approaches from above: the absent canopy doesn't block
- if (motion.type !== "linear") throw new Error("expected linear");
- expect(motion.direction[2]).toBe(-1);
- });
-});
-
-describe("motionToWaypoints / waypointsToMotion", () => {
- const seated: Vec3 = [10, 5, -2];
-
- function expectVec3Close(actual: Vec3, expected: Vec3) {
- actual.forEach((value, index) => {
- expect(value).toBeCloseTo(expected[index] ?? Number.NaN, 6);
- });
- }
-
- it("samples a linear motion to a start + seated waypoint", () => {
- const motion: Motion = {
- type: "linear",
- direction: [0, 1, 0],
- distance: 20
- };
- const waypoints = motionToWaypoints(motion, seated);
- expect(waypoints).toHaveLength(2);
- expectVec3Close(waypoints[0]!, [10, -15, -2]); // seated - dir*distance
- expectVec3Close(waypoints[1]!, seated); // last === seated
- });
-
- it("round-trips a linear motion exactly", () => {
- const motion: Motion = {
- type: "linear",
- direction: [0, 0, 1],
- distance: 12
- };
- const back = waypointsToMotion(motionToWaypoints(motion, seated), seated);
- expect(back.type).toBe("linear");
- if (back.type === "linear") {
- expectVec3Close(back.direction, [0, 0, 1]);
- expect(back.distance).toBeCloseTo(12, 6);
- }
- });
-
- it("round-trips an L motion, preserving segment order and directions", () => {
- const motion: Motion = {
- type: "L",
- segments: [
- { direction: [1, 0, 0], distance: 8 },
- { direction: [0, 1, 0], distance: 5 }
- ]
- };
- const back = waypointsToMotion(motionToWaypoints(motion, seated), seated);
- expect(back.type).toBe("L");
- if (back.type === "L") {
- expect(back.segments).toHaveLength(2);
- expectVec3Close(back.segments[0]!.direction, [1, 0, 0]);
- expect(back.segments[0]!.distance).toBeCloseTo(8, 6);
- expectVec3Close(back.segments[1]!.direction, [0, 1, 0]);
- expect(back.segments[1]!.distance).toBeCloseTo(5, 6);
- }
- });
-
- it("forces the last waypoint to the seated position", () => {
- const back = waypointsToMotion(
- [
- [0, 0, 0],
- [99, 99, 99]
- ],
- seated
- );
- // The seated end is pinned, so travel is start -> seated.
- expect(back.type).toBe("linear");
- if (back.type === "linear") {
- expect(back.distance).toBeCloseTo(
- Math.hypot(seated[0], seated[1], seated[2]),
- 6
- );
- }
- });
-
- it("synthesizes a default straight path for a none motion", () => {
- const waypoints = motionToWaypoints({ type: "none" }, seated);
- expect(waypoints).toHaveLength(2);
- expectVec3Close(waypoints[0]!, [
- seated[0],
- seated[1] + DEFAULT_WAYPOINT_DISTANCE,
- seated[2]
- ]);
- expectVec3Close(waypoints[1]!, seated);
- });
-
- it("collapses degenerate (coincident) waypoints to none", () => {
- expect(waypointsToMotion([seated, seated], seated)).toEqual({
- type: "none"
- });
- });
-
- it("drops a zero-length middle segment (3 pts, collinear) to linear", () => {
- const back = waypointsToMotion([[0, 0, 0], [0, 0, 0], seated], seated);
- expect(back.type).toBe("linear");
- });
-});
-
-describe("stepClipTiming", () => {
- const linear: Motion = { type: "linear", direction: [0, 0, 1], distance: 60 };
- const seconds = motionDuration(linear);
-
- it("plays the natural animation when no duration is authored", () => {
- expect(stepClipTiming({ motion: linear })).toEqual({
- total: seconds + 0.6,
- units: [],
- glide: 0,
- motion: seconds,
- hold: 0.6
- });
- });
-
- it("adds a carry-in glide before the insertion", () => {
- const timing = stepClipTiming({ motion: linear }, 1.2);
- expect(timing.total).toBeCloseTo(1.2 + seconds + 0.6);
- expect(timing.glide).toBe(1.2);
- });
-
- it("gives a process-only step a fixed slot plus any glide", () => {
- expect(stepClipTiming({ motion: { type: "none" } }).total).toBe(2);
- expect(stepClipTiming({ motion: { type: "none" } }, 1.2).total).toBe(3.2);
- });
-
- it("speeds glide, insertion and hold up to fit a shorter authored duration", () => {
- const natural = 1.2 + seconds + 0.6;
- const timing = stepClipTiming(
- { motion: linear, durationSeconds: natural / 2 },
- 1.2
- );
- expect(timing.total).toBe(natural / 2);
- expect(timing.glide + timing.motion + timing.hold).toBeCloseTo(natural / 2);
- expect(timing.glide).toBeCloseTo(0.6);
- });
-
- it("keeps the natural animation inside a longer authored duration", () => {
- const timing = stepClipTiming({ motion: linear, durationSeconds: 30 });
- expect(timing.total).toBe(30);
- expect(timing.motion).toBe(seconds);
- });
-});
-
-describe("waypoints motion", () => {
- const halfTurnZ: [number, number, number, number] = [0, 0, 1, 0];
-
- it("turns the set about its pivot, then shifts it, and ends seated", () => {
- const motion: Motion = {
- type: "waypoints",
- waypoints: [
- { offset: [0, 0, 50], rotation: halfTurnZ },
- { offset: [0, 0, 0], rotation: [0, 0, 0, 1] }
- ]
- };
- // Part sits 10 mm along +X from the set's center at the origin.
- const keyframes = motionToKeyframes(
- motion,
- { position: [10, 0, 0], quaternion: [0, 0, 0, 1] },
- { duration: 2, pivot: [0, 0, 0] }
- );
- if (!keyframes) throw new Error("expected keyframes");
- // 180° about Z swings the part to -X, then the offset lifts it.
- expectVectorClose(positionAt(keyframes, 0), [-10, 0, 50]);
- expectVectorClose(quaternionAt(keyframes, 0), [0, 0, 1, 0]);
- const last = lastIndex(keyframes);
- expectVectorClose(positionAt(keyframes, last), [10, 0, 0]);
- expectVectorClose(quaternionAt(keyframes, last), [0, 0, 0, 1]);
- expect(keyframes.times[last]).toBeCloseTo(2);
- });
-
- it("gives a turn in place readable time", () => {
- const turnInPlace: Motion = {
- type: "waypoints",
- waypoints: [
- { offset: [0, 0, 0], rotation: [0, 0, Math.SQRT1_2, Math.SQRT1_2] },
- { offset: [0, 0, 0], rotation: [0, 0, 0, 1] }
- ]
- };
- expect(motionTravelDistance(turnInPlace)).toBeGreaterThan(0);
- expect(motionDuration(turnInPlace)).toBeGreaterThanOrEqual(1);
- expect(motionDuration(turnInPlace)).toBeLessThanOrEqual(4);
- });
-
- it("round-trips through the editor and keeps unturned paths linear / L", () => {
- const seated: Vec3 = [1, 2, 3];
- expect(
- editorWaypointsToMotion(
- [
- { position: [1, 2, 53], rotation: [0, 0, 0, 1] },
- { position: seated, rotation: [0, 0, 0, 1] }
- ],
- seated
- ).type
- ).toBe("linear");
- expect(
- editorWaypointsToMotion(
- [
- { position: [1, 52, 53], rotation: [0, 0, 0, 1] },
- { position: [1, 2, 53], rotation: [0, 0, 0, 1] },
- { position: seated, rotation: [0, 0, 0, 1] }
- ],
- seated
- ).type
- ).toBe("L");
-
- const turned = [
- { position: [1, 2, 53] as Vec3, rotation: halfTurnZ },
- {
- position: seated,
- rotation: [0, 0, 0, 1] as [number, number, number, number]
- }
- ];
- const motion = editorWaypointsToMotion(turned, seated);
- expect(motion.type).toBe("waypoints");
- const back = motionToEditorWaypoints(motion, seated);
- expect(back.length).toBe(2);
- expectVectorClose(back[0]?.position ?? [], [1, 2, 53]);
- expectVectorClose(back[0]?.rotation ?? [], halfTurnZ);
- expectVectorClose(back[1]?.position ?? [], seated);
- });
-});
-
-describe("buildStepClip with sub-assembly units", () => {
- function makeParts() {
- const root = new Group();
- const own = new Object3D();
- own.position.set(0, 0, 0);
- const unitA = new Object3D();
- unitA.position.set(100, 0, 0);
- const unitB = new Object3D();
- unitB.position.set(200, 0, 0);
- root.add(own, unitA, unitB);
- root.updateMatrixWorld(true);
- return {
- own,
- unitA,
- unitB,
- nodesById: new Map<string, Object3D>([
- ["own", own],
- ["unit-a", unitA],
- ["unit-b", unitB]
- ])
- };
- }
- const drop: Motion = { type: "linear", direction: [0, 0, -1], distance: 10 };
- const trackFor = (clip: AnimationClip, node: Object3D) => {
- const track = clip.tracks.find(
- (candidate) => candidate.name === `${node.uuid}.position`
- );
- if (!track) throw new Error("expected a track");
- return { times: [...track.times], values: [...track.values] };
- };
- const valueAt = (
- track: { times: number[]; values: number[] },
- time: number
- ) => {
- const index = track.times.findIndex((t) => Math.abs(t - time) < 1e-6);
- expect(index).toBeGreaterThanOrEqual(0);
- return track.values.slice(index * 3, index * 3 + 3);
- };
-
- it("flies the unit in first; the step's own part waits, then inserts", () => {
- const { own, unitA, nodesById } = makeParts();
- const clip = buildStepClip(makeStep(drop, ["own"]), nodesById, {
- duration: 2,
- holdSeconds: 0.5,
- units: [{ nodeIds: ["unit-a"], motion: drop, seconds: 1 }]
- });
- if (!clip) throw new Error("expected clip");
- expect(clip.duration).toBeCloseTo(1 + 2 + 0.5);
-
- const unit = trackFor(clip, unitA);
- expectVectorClose(unit.values.slice(0, 3), [100, 0, 10]);
- expectVectorClose(valueAt(unit, 1), [100, 0, 0]);
- expectVectorClose(unit.values.slice(-3), [100, 0, 0]);
- expect(unit.times[unit.times.length - 1]).toBeCloseTo(3.5);
-
- const part = trackFor(clip, own);
- // Waits at its insertion start until the unit has seated…
- expectVectorClose(part.values.slice(0, 3), [0, 0, 10]);
- expectVectorClose(valueAt(part, 1), [0, 0, 10]);
- // …then inserts and holds.
- expectVectorClose(valueAt(part, 3), [0, 0, 0]);
- });
-
- it("plays several units one after another", () => {
- const { unitB, nodesById } = makeParts();
- const clip = buildStepClip(makeStep({ type: "none" }, []), nodesById, {
- holdSeconds: 0,
- units: [
- { nodeIds: ["unit-a"], motion: drop, seconds: 1 },
- { nodeIds: ["unit-b"], motion: drop, seconds: 1.5 }
- ]
- });
- if (!clip) throw new Error("expected clip");
- expect(clip.duration).toBeCloseTo(2.5);
- const second = trackFor(clip, unitB);
- expectVectorClose(valueAt(second, 1), [200, 0, 10]);
- expectVectorClose(second.values.slice(-3), [200, 0, 0]);
- });
-
- it("builds a clip for a unit joining at a step with no parts of its own", () => {
- const { nodesById } = makeParts();
- expect(
- buildStepClip(makeStep({ type: "none" }, []), nodesById, {
- units: [{ nodeIds: ["unit-a"], motion: drop, seconds: 1 }]
- })
- ).not.toBeNull();
- // A unit with no path of its own adds nothing.
- expect(
- buildStepClip(makeStep({ type: "none" }, []), nodesById, {
- units: [{ nodeIds: ["unit-a"], motion: { type: "none" }, seconds: 0 }]
- })
- ).toBeNull();
- });
-
- it("scales the unit time with an authored duration", () => {
- const natural = stepClipTiming({ motion: drop }, 0, [2]);
- const fitted = stepClipTiming(
- { motion: drop, durationSeconds: natural.total / 2 },
- 0,
- [2]
- );
- expect(fitted.units[0]).toBeCloseTo(1);
- expect(fitted.total).toBeCloseTo(natural.total / 2);
- });
-});
-
-describe("fadeProgress", () => {
- it("waits for the units, then fades in over its own time", () => {
- expect(fadeProgress(0.5, 2, 1.2, false)).toBe(0);
- expect(fadeProgress(2, 2, 1.2, false)).toBe(0);
- expect(fadeProgress(2.6, 2, 1.2, false)).toBeCloseTo(0.5);
- expect(fadeProgress(5, 2, 1.2, false)).toBe(1);
- });
-
- it("is fully in once the step has finished, whatever the clock says", () => {
- expect(fadeProgress(0, 2, 1.2, true)).toBe(1);
- });
-
- it("starts at once with no units", () => {
- expect(fadeProgress(0.6, 0, 1.2, false)).toBeCloseTo(0.5);
- });
-});
-
-describe("isPlayableMotion", () => {
- it("accepts the motion types the player animates", () => {
- expect(isPlayableMotion({ type: "none" })).toBe(true);
- expect(
- isPlayableMotion({ type: "linear", direction: [0, 0, 1], distance: 5 })
- ).toBe(true);
- expect(
- isPlayableMotion({
- type: "waypoints",
- waypoints: [
- { offset: [0, 0, 5], rotation: [0, 0, 0, 1] },
- { offset: [0, 0, 0], rotation: [0, 0, 0, 1] }
- ]
- })
- ).toBe(true);
- });
-
- it("rejects what would throw or is unknown", () => {
- expect(isPlayableMotion(null)).toBe(false);
- expect(isPlayableMotion({ type: "teleport" })).toBe(false);
- expect(
- isPlayableMotion({
- type: "waypoints",
- waypoints: [{ offset: [0, 0, 0], rotation: [0, 0, 0, 1] }]
- })
- ).toBe(false);
- expect(isPlayableMotion({ type: "path", keyframes: [] })).toBe(false);
- });
-});
diff --git a/packages/viewer/src/motion.ts b/packages/viewer/src/motion.ts
deleted file mode 100644
index 301542f060..0000000000
--- a/packages/viewer/src/motion.ts
+++ /dev/null
@@ -1,1109 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
-// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-
-import {
- AnimationClip,
- Box3,
- Matrix4,
- type Object3D,
- Quaternion,
- QuaternionKeyframeTrack,
- Vector3,
- VectorKeyframeTrack
-} from "three";
-import { synthesizeFallbackMotion } from "./fallback";
-import type { AssemblyGraphIndex } from "./graph";
-import type {
- AssemblyStep,
- Motion,
- Quat,
- Vec3,
- WaypointsMotion
-} from "./types";
-
-/**
- * Pure keyframe construction for step motions. No WebGL — everything here is
- * unit-testable in node.
- *
- * Motion JSON describes the INSERTION of a component: keyframes start at the
- * displaced (pre-insertion) pose and end at the component's final (seated) pose.
- * All poses produced by `motionToKeyframes` are world-space; `buildStepClip`
- * converts them into each node's parent-local space for animation.
- */
-
-/** A world-space pose: position + quaternion ([x, y, z, w]) */
-export type Pose = {
- position: Vec3;
- quaternion: Quat;
-};
-
-export type MotionKeyframes = {
- /** Seconds, monotonically non-decreasing, starting at 0 */
- times: number[];
- /** Flat [x, y, z] per keyframe, world space */
- positions: number[];
- /** Flat [x, y, z, w] per keyframe, world space */
- quaternions: number[];
-};
-
-export type MotionKeyframeOptions = {
- /** Total animation duration in seconds. Defaults to `motionDuration(motion)`. */
- duration?: number;
- /** Helix sampling density (quaternion slerp needs <180° between samples). */
- samplesPerTurn?: number;
- /**
- * Seated center of the whole moving set (one part, a rigid group, or a
- * sub-assembly). A `waypoints` motion turns the set about it. Defaults to the
- * part's own seated position.
- */
- pivot?: Vec3;
-};
-
-export type StepClipOptions = MotionKeyframeOptions & {
- /** Seconds to hold the seated pose at the end of each loop. */
- holdSeconds?: number;
- /**
- * A step that carries a finished sub-assembly in: prepend a straight glide
- * from seat + `offset` (beside the build) to where the insertion starts.
- * Never clamped like the insertion travel is — it starts far by design.
- * With `nodeIds`, only those nodes glide; the step's other parts wait at
- * their insertion start until the glide ends.
- */
- glide?: { offset: Vec3; seconds: number; nodeIds?: string[] };
- /**
- * Finished sub-assemblies that join on their own path. They play one after
- * another before the step's own parts move (and before any `glide`); each
- * travels as one rigid unit, turning about its own seated center.
- */
- units?: StepClipUnit[];
-};
-
-export type StepClipUnit = {
- nodeIds: string[];
- motion: Motion;
- seconds: number;
-};
-
-/** Seconds a carried-in sub-assembly takes to glide to its insertion start. */
-export const CARRY_IN_GLIDE_SECONDS = 1.2;
-
-const INSERTION_SPEED_MM_PER_S = 60;
-const MIN_DURATION_S = 1;
-const MAX_DURATION_S = 4;
-const DEFAULT_SAMPLES_PER_TURN = 4;
-export const DEFAULT_HOLD_SECONDS = 0.6;
-/** Coincident-waypoint threshold (mm) and the fallback travel for `none`. */
-const WAYPOINT_EPSILON = 1e-3;
-export const DEFAULT_WAYPOINT_DISTANCE = 50;
-/** Timeline length of a process-only (none-motion) step without an explicit duration */
-const NONE_STEP_SECONDS = 2;
-
-/**
- * How a step spends its slot on the continuous timeline (`total`): the
- * sub-assemblies that join on their own path (`unitSeconds`, one after
- * another), a carried-in sub-assembly's glide, the insertion, then the seated
- * hold. The slot is the explicit `durationSeconds` when set, otherwise the
- * natural length (a fixed slot for process-only steps). An authored duration
- * shorter than the animation speeds everything up to fit, so the step never
- * ends mid-travel and snaps its parts to their seat.
- */
-export function stepClipTiming(
- step: Pick<AssemblyStep, "motion" | "durationSeconds">,
- glideSeconds = 0,
- unitSeconds: number[] = []
-): {
- total: number;
- units: number[];
- glide: number;
- motion: number;
- hold: number;
-} {
- const unitsTotal = unitSeconds.reduce((sum, seconds) => sum + seconds, 0);
- const motion = step.motion.type === "none" ? 0 : motionDuration(step.motion);
- const natural = unitsTotal + glideSeconds + motion + DEFAULT_HOLD_SECONDS;
- const total =
- step.durationSeconds && step.durationSeconds > 0
- ? step.durationSeconds
- : step.motion.type === "none"
- ? unitsTotal + glideSeconds + NONE_STEP_SECONDS
- : natural;
- const fit = Math.min(1, total / natural);
- return {
- total,
- units: unitSeconds.map((seconds) => seconds * fit),
- glide: glideSeconds * fit,
- motion: motion * fit,
- hold: DEFAULT_HOLD_SECONDS * fit
- };
-}
-
-/**
- * Opacity of a seated fade-in at `elapsed` seconds into the step: 0 until
- * `delay` (the step's units on their own path are still arriving), then up to
- * 1 over `seconds`. A finished step — including one shown statically, at its
- * end — is fully in.
- */
-export function fadeProgress(
- elapsed: number,
- delay: number,
- seconds: number,
- finished: boolean
-): number {
- if (finished) return 1;
- return Math.min(Math.max((elapsed - delay) / seconds, 0), 1);
-}
-
-const PLAYABLE_MOTION_TYPES = new Set([
- "linear",
- "L",
- "helix",
- "path",
- "waypoints",
- "none"
-]);
-
-/**
- * A stored motion the player can animate without throwing. Callers that read
- * raw JSON (the MES) play anything else as `none`. Keyframed motions need at
- * least two poses — `motionToKeyframes` throws on fewer.
- */
-export function isPlayableMotion(value: unknown): value is Motion {
- if (!value || typeof value !== "object") return false;
- const motion = value as {
- type?: unknown;
- waypoints?: unknown;
- keyframes?: unknown;
- };
- if (typeof motion.type !== "string") return false;
- if (!PLAYABLE_MOTION_TYPES.has(motion.type)) return false;
- if (motion.type === "waypoints") {
- return Array.isArray(motion.waypoints) && motion.waypoints.length >= 2;
- }
- if (motion.type === "path") {
- return Array.isArray(motion.keyframes) && motion.keyframes.length >= 2;
- }
- return true;
-}
-
-/** Total travel distance (mm) implied by a motion. */
-export function motionTravelDistance(motion: Motion): number {
- switch (motion.type) {
- case "linear":
- return Math.abs(motion.distance);
- case "L":
- return motion.segments.reduce(
- (sum, segment) => sum + Math.abs(segment.distance),
- 0
- );
- case "helix":
- return Math.abs(motion.approach) + Math.abs(motion.pitch * motion.turns);
- case "path": {
- let total = 0;
- for (let i = 1; i < motion.keyframes.length; i++) {
- const current = motion.keyframes[i];
- const previous = motion.keyframes[i - 1];
- if (!current || !previous) continue;
- total += toVector3(current.position).distanceTo(
- toVector3(previous.position)
- );
- }
- return total;
- }
- case "waypoints": {
- let total = 0;
- for (let i = 1; i < motion.waypoints.length; i++) {
- const current = motion.waypoints[i];
- const previous = motion.waypoints[i - 1];
- if (!current || !previous) continue;
- total += waypointLegTravel(previous, current);
- }
- return total;
- }
- case "none":
- return 0;
- }
-}
-
-/** Turning counts as travel so a flip in place still takes readable time. */
-const TURN_MM_PER_RADIAN = 30;
-
-function waypointLegTravel(
- from: WaypointsMotion["waypoints"][number],
- to: WaypointsMotion["waypoints"][number]
-): number {
- const distance = toVector3(from.offset).distanceTo(toVector3(to.offset));
- const angle = toQuaternion(from.rotation).angleTo(toQuaternion(to.rotation));
- return distance + angle * TURN_MM_PER_RADIAN;
-}
-
-/** Animation duration (s) scaled to travel distance, clamped to 1–4 s. */
-export function motionDuration(motion: Motion): number {
- if (motion.type === "none") return 0;
- const travel = motionTravelDistance(motion);
- return Math.min(
- MAX_DURATION_S,
- Math.max(MIN_DURATION_S, travel / INSERTION_SPEED_MM_PER_S)
- );
-}
-
-/**
- * The motion a step should display. Flagged steps (the planner proved no
- * collision-free path exists) keep motion "none" — the player fades their
- * components in at the seated pose rather than animating a fabricated
- * fly-through. Other non-first steps stored with "none" (legacy plans,
- * manually authored steps) get the AABB fallback so components never pop into
- * place; the fallback's obstacle world is `presentNodeIds`, the components
- * already installed by EARLIER steps — later-step and never-installed
- * components are not on the canvas. When no collision-free fallback exists the
- * step keeps "none" and fades in. The first step is the base: placed, not
- * inserted.
- */
-export function displayMotionForStep(
- step: Pick<AssemblyStep, "motion" | "componentNodeIds" | "flagged">,
- index: number,
- graphIndex: AssemblyGraphIndex | null,
- presentNodeIds: ReadonlySet<string>
-): Motion {
- if (
- index === 0 ||
- step.flagged ||
- step.motion.type !== "none" ||
- step.componentNodeIds.length === 0 ||
- !graphIndex
- ) {
- return step.motion;
- }
- const fallback = synthesizeFallbackMotion(
- graphIndex,
- step.componentNodeIds,
- presentNodeIds
- );
- return fallback && fallback.type !== "none" ? fallback : step.motion;
-}
-
-/** Components smaller than this fraction of the assembly count as "small". */
-const SMALL_COMPONENT_FRACTION = 0.15;
-/** Small components travel at least this many times their own size. */
-const SMALL_COMPONENT_TRAVEL_FACTOR = 2.5;
-/** No component travels more than this many times its own size, +margin. */
-const NATURAL_TRAVEL_FACTOR = 3;
-/** Additive slack (mm) on the travel ceiling so a seat still fully clears. */
-const NATURAL_TRAVEL_MARGIN_MM = 5;
-/**
- * Hard ceiling as a fraction of the whole assembly: nothing animates in from
- * further than this, however large the part. A big FLAT part (a gasket, a lid)
- * has a huge diagonal but should still just drop a short way onto its seat —
- * the per-part `NATURAL_TRAVEL_FACTOR × diagonal` ceiling is meaningless for it
- * (3× a 166 mm seal = 500 mm), so its planner collision path (an L-shaped
- * detour around the box, ~1.5× the assembly) reads as flying in from off-screen.
- */
-const ASSEMBLY_TRAVEL_FRACTION = 0.35;
-
-/**
- * Shapes a component's insertion travel into a natural band for playback so it
- * neither pops (too short) nor flies in from across the assembly (too long).
- *
- * Display-only: the stored plan keeps the geometric (collision-minimum) travel;
- * this only shortens/lengthens where the part *starts* its animated approach.
- * Safe because playback hides future-step parts and a part seats against the
- * already-placed parts below/beside it, not along its short approach.
- *
- * - Ceiling (all parts): `d · NATURAL_TRAVEL_FACTOR + margin` — a long
- * collision path (slider, deep mate, a graze past a distant neighbor) is
- * trimmed to a few of the part's own body-lengths.
- * - Floor (small parts only, < SMALL_COMPONENT_FRACTION of the assembly): keeps
- * bolts/washers/pins traveling `d · SMALL_COMPONENT_TRAVEL_FACTOR` so they
- * still read at assembly scale.
- *
- * Returns the motion unchanged when it's non-translating or already in band.
- */
-export function naturalizeMotion(
- motion: Motion,
- componentDiagonal: number,
- assemblyDiagonal: number
-): Motion {
- if (componentDiagonal <= 0 || assemblyDiagonal <= 0) return motion;
-
- const isSmall =
- componentDiagonal < assemblyDiagonal * SMALL_COMPONENT_FRACTION;
- const floor = isSmall ? componentDiagonal * SMALL_COMPONENT_TRAVEL_FACTOR : 0;
- // Per-part ceiling, then the assembly-wide cap; never below the floor so a
- // borderline-small part keeps its readable minimum travel.
- const ceiling = Math.max(
- floor,
- Math.min(
- componentDiagonal * NATURAL_TRAVEL_FACTOR + NATURAL_TRAVEL_MARGIN_MM,
- assemblyDiagonal * ASSEMBLY_TRAVEL_FRACTION
- )
- );
- const clamp = (t: number) => Math.min(Math.max(t, floor), ceiling);
-
- switch (motion.type) {
- case "linear": {
- const distance = clamp(motion.distance);
- return distance === motion.distance ? motion : { ...motion, distance };
- }
- case "L": {
- const total = motion.segments.reduce(
- (sum, segment) => sum + Math.abs(segment.distance),
- 0
- );
- if (total <= 0) return motion;
- const target = clamp(total);
- if (target === total) return motion;
- const scale = target / total;
- return {
- ...motion,
- segments: motion.segments.map((segment) => ({
- ...segment,
- distance: segment.distance * scale
- }))
- };
- }
- default:
- return motion;
- }
-}
-
-/**
- * Builds world-space insertion keyframes for a component whose final (seated)
- * world pose is `basePose`. The last keyframe always equals `basePose`.
- * Returns `null` for `none` motions.
- */
-/** Sub-samples per motion when re-timing a straight path through ease-in-out. */
-const EASE_SAMPLES = 20;
-
-/** Ease-in-out cubic: slow start, quick middle, gentle settle. */
-function easeInOutCubic(t: number): number {
- return t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2;
-}
-
-/**
- * Re-times a piecewise-linear keyframe path through an ease-in-out velocity
- * profile so an insertion accelerates off the start and decelerates into its
- * seat instead of moving at constant speed. Preserves the geometric path and
- * both endpoints exactly (only WHEN the part is at each point changes); total
- * duration is unchanged. Playback-only — the stored motion and the editable
- * waypoints keep the raw path.
- */
-export function resampleEased(kf: MotionKeyframes): MotionKeyframes {
- const n = kf.times.length;
- const total = kf.times[n - 1] ?? 0;
- if (n < 2 || total <= 0) return kf;
-
- const times: number[] = [];
- const positions: number[] = [];
- const quaternions: number[] = [];
- const a = new Vector3();
- const b = new Vector3();
- const qa = new Quaternion();
- const qb = new Quaternion();
-
- for (let j = 0; j <= EASE_SAMPLES; j++) {
- const u = j / EASE_SAMPLES;
- const s = easeInOutCubic(u) * total; // eased sample point along the path
- let i = 0;
- while (i < n - 1 && (kf.times[i + 1] ?? total) < s) i++;
- const t0 = kf.times[i] ?? 0;
- const t1 = kf.times[i + 1] ?? total;
- const span = t1 - t0;
- const f = span > 1e-9 ? (s - t0) / span : 0;
- a.fromArray(kf.positions, i * 3);
- b.fromArray(kf.positions, (i + 1) * 3);
- a.lerp(b, f);
- qa.fromArray(kf.quaternions, i * 4);
- qb.fromArray(kf.quaternions, (i + 1) * 4);
- qa.slerp(qb, f);
- times.push(u * total);
- positions.push(a.x, a.y, a.z);
- quaternions.push(qa.x, qa.y, qa.z, qa.w);
- }
- return { times, positions, quaternions };
-}
-
-export function motionToKeyframes(
- motion: Motion,
- basePose: Pose,
- options: MotionKeyframeOptions = {}
-): MotionKeyframes | null {
- const duration = options.duration ?? motionDuration(motion);
- const finalPosition = toVector3(basePose.position);
- const finalQuaternion = toQuaternion(basePose.quaternion);
-
- switch (motion.type) {
- case "none":
- return null;
-
- case "linear": {
- const direction = toVector3(motion.direction).normalize();
- const start = finalPosition
- .clone()
- .addScaledVector(direction, -motion.distance);
- return fromPoses(
- [0, duration],
- [
- { position: start, quaternion: finalQuaternion },
- { position: finalPosition, quaternion: finalQuaternion }
- ]
- );
- }
-
- case "L": {
- // Walk backwards from the final pose through the segments (insertion
- // order means the last segment ends at the final pose).
- const positions: Vector3[] = [finalPosition.clone()];
- for (let i = motion.segments.length - 1; i >= 0; i--) {
- const segment = motion.segments[i];
- const previous = positions[0];
- if (!segment || !previous) continue;
- const direction = toVector3(segment.direction).normalize();
- positions.unshift(
- previous.clone().addScaledVector(direction, -segment.distance)
- );
- }
- const distances = motion.segments.map((s) => Math.abs(s.distance));
- const total = distances.reduce((sum, d) => sum + d, 0);
- const times: number[] = [0];
- let elapsed = 0;
- for (const distance of distances) {
- elapsed += total > 0 ? (distance / total) * duration : 0;
- times.push(elapsed);
- }
- if (total === 0) times[times.length - 1] = duration;
- return fromPoses(
- times,
- positions.map((position) => ({
- position,
- quaternion: finalQuaternion
- }))
- );
- }
-
- case "helix": {
- const axis = toVector3(motion.axis).normalize();
- const origin = toVector3(motion.origin);
- const samplesPerTurn = options.samplesPerTurn ?? DEFAULT_SAMPLES_PER_TURN;
- const totalAngle = Math.PI * 2 * motion.turns;
- const threadAdvance = motion.pitch * motion.turns;
- const threadSamples = Math.max(
- 1,
- Math.ceil(motion.turns * samplesPerTurn)
- );
-
- // Pose at the given remaining (un-inserted) thread fraction. r = 1 is
- // the start of threading, r = 0 is seated. The screw transform rotates
- // the final pose backwards about `axis` through `origin` and retracts
- // it along the axis.
- const threadPoseAt = (
- r: number
- ): { position: Vector3; quaternion: Quaternion } => {
- const unscrew = new Quaternion().setFromAxisAngle(
- axis,
- -totalAngle * r
- );
- const position = finalPosition
- .clone()
- .sub(origin)
- .applyQuaternion(unscrew)
- .add(origin)
- .addScaledVector(axis, -threadAdvance * r);
- const quaternion = unscrew.clone().multiply(finalQuaternion);
- return { position, quaternion };
- };
-
- const approachWeight = Math.abs(motion.approach);
- const threadWeight =
- Math.abs(threadAdvance) > 0
- ? Math.abs(threadAdvance)
- : motion.turns > 0
- ? 1
- : 0;
- const totalWeight = approachWeight + threadWeight;
- const approachTime =
- totalWeight > 0 ? (approachWeight / totalWeight) * duration : 0;
-
- const times: number[] = [];
- const poses: { position: Vector3; quaternion: Quaternion }[] = [];
-
- const threadStart = threadPoseAt(1);
- if (motion.approach !== 0) {
- times.push(0);
- poses.push({
- position: threadStart.position
- .clone()
- .addScaledVector(axis, -motion.approach),
- quaternion: threadStart.quaternion
- });
- }
- times.push(approachTime);
- poses.push(threadStart);
- for (let i = 1; i <= threadSamples; i++) {
- const progress = i / threadSamples;
- times.push(approachTime + (duration - approachTime) * progress);
- poses.push(threadPoseAt(1 - progress));
- }
- return fromPoses(times, poses);
- }
-
- case "path": {
- const keyframes = motion.keyframes;
- const first = keyframes[0];
- const last = keyframes[keyframes.length - 1];
- if (keyframes.length < 2 || !first || !last) {
- throw new Error("path motion requires at least 2 keyframes");
- }
- for (let i = 1; i < keyframes.length; i++) {
- const current = keyframes[i];
- const previous = keyframes[i - 1];
- if (!current || !previous) continue;
- if (current.t <= previous.t) {
- throw new Error(
- "path motion keyframe times must be strictly increasing"
- );
- }
- }
- if (first.t !== 0 || last.t !== 1) {
- throw new Error("path motion keyframes must span t = 0 to t = 1");
- }
- const epsilon = 1e-3;
- if (
- toVector3(last.position).distanceTo(finalPosition) > epsilon ||
- Math.abs(toQuaternion(last.quaternion).dot(finalQuaternion)) <
- 1 - epsilon
- ) {
- throw new Error(
- "path motion's last keyframe must equal the component's final pose"
- );
- }
- return fromPoses(
- keyframes.map((keyframe) => keyframe.t * duration),
- keyframes.map((keyframe) => ({
- position: toVector3(keyframe.position),
- quaternion: toQuaternion(keyframe.quaternion)
- }))
- );
- }
-
- case "waypoints": {
- const waypoints = motion.waypoints;
- if (waypoints.length < 2) {
- throw new Error("waypoints motion requires at least 2 waypoints");
- }
- // Each waypoint turns the whole set about its seated center, then shifts
- // it: a part away from the center swings around it with the rest.
- const pivot = options.pivot ? toVector3(options.pivot) : finalPosition;
- const arm = finalPosition.clone().sub(pivot);
- const poses = waypoints.map((waypoint, index) => {
- if (index === waypoints.length - 1) {
- return { position: finalPosition, quaternion: finalQuaternion };
- }
- const rotation = toQuaternion(waypoint.rotation);
- return {
- position: pivot
- .clone()
- .add(toVector3(waypoint.offset))
- .add(arm.clone().applyQuaternion(rotation)),
- quaternion: rotation.clone().multiply(finalQuaternion)
- };
- });
- const legs = waypoints
- .slice(1)
- .map((waypoint, index) =>
- waypointLegTravel(waypoints[index] ?? waypoint, waypoint)
- );
- const total = legs.reduce((sum, leg) => sum + leg, 0);
- const times: number[] = [0];
- let elapsed = 0;
- for (const leg of legs) {
- elapsed +=
- total > 0 ? (leg / total) * duration : duration / legs.length;
- times.push(elapsed);
- }
- times[times.length - 1] = duration;
- return fromPoses(times, poses);
- }
- }
-}
-
-/**
- * Builds a looping insertion AnimationClip for one step, with position and
- * quaternion tracks for each of the step's components. Tracks are bound by node
- * uuid so duplicate node names cannot collide. World-space keyframes are
- * converted into each node's parent-local space, so nested assembly
- * transforms are respected. Nodes are assumed to currently sit at their
- * final (seated) pose — or at their staging spot for a step built aside, which
- * is the pose the insertion then ends at.
- *
- * With `units`, each finished sub-assembly first travels its own path, one
- * after another, while the step's own parts wait at their start. With `glide`,
- * every node then glides from seat + offset to its insertion start (a `none`
- * motion glides straight to the seat).
- *
- * Returns `null` when nothing moves: a `none` motion without a glide or units,
- * or no component that resolves to a node.
- */
-export function buildStepClip(
- step: AssemblyStep,
- nodesById: Map<string, Object3D>,
- options: StepClipOptions = {}
-): AnimationClip | null {
- const { glide } = options;
- const units = (options.units ?? []).filter(
- (unit) => unit.nodeIds.length > 0 && unit.motion.type !== "none"
- );
- const unitNodeIds = new Set(units.flatMap((unit) => unit.nodeIds));
- const ownNodeIds = step.componentNodeIds.filter(
- (nodeId) => !unitNodeIds.has(nodeId)
- );
- const ownMoves =
- ownNodeIds.length > 0 && (step.motion.type !== "none" || Boolean(glide));
- if (!ownMoves && units.length === 0) return null;
-
- const duration =
- step.motion.type === "none"
- ? 0
- : (options.duration ?? motionDuration(step.motion));
- const glideSeconds = glide ? glide.seconds : 0;
- const holdSeconds = options.holdSeconds ?? DEFAULT_HOLD_SECONDS;
- const unitsSeconds = units.reduce((sum, unit) => sum + unit.seconds, 0);
- const clipLength =
- unitsSeconds + (ownMoves ? glideSeconds + duration : 0) + holdSeconds;
- const tracks: (VectorKeyframeTrack | QuaternionKeyframeTrack)[] = [];
-
- let unitStart = 0;
- for (const unit of units) {
- const pivot =
- unit.motion.type === "waypoints"
- ? (seatedBoundsCenter(unit.nodeIds, nodesById) ?? undefined)
- : undefined;
- for (const nodeId of unit.nodeIds) {
- const node = nodesById.get(nodeId);
- if (!node) continue;
- const { seatedPose, worldScale } = worldPoseOf(node);
- const raw = motionToKeyframes(unit.motion, seatedPose, {
- duration: unit.seconds,
- pivot
- });
- if (!raw) continue;
- const keyframes = delayKeyframes(
- isEasedMotion(unit.motion) ? resampleEased(raw) : raw,
- unitStart
- );
- tracks.push(...nodeTracks(node, keyframes, worldScale, clipLength));
- }
- unitStart += unit.seconds;
- }
-
- if (ownMoves) {
- const pivot =
- step.motion.type === "waypoints"
- ? (seatedBoundsCenter(ownNodeIds, nodesById) ?? undefined)
- : undefined;
- for (const nodeId of ownNodeIds) {
- const node = nodesById.get(nodeId);
- if (!node) continue;
- const { seatedPose, worldScale } = worldPoseOf(node);
- // A `none` motion only happens with a glide: the insertion is the seat itself.
- const rawKeyframes =
- step.motion.type === "none"
- ? {
- times: [0],
- positions: [...seatedPose.position],
- quaternions: [...seatedPose.quaternion]
- }
- : motionToKeyframes(step.motion, seatedPose, {
- ...options,
- duration,
- pivot
- });
- if (!rawKeyframes) continue;
- // Ease the straight and editor-drawn approaches (accelerate off the
- // start, settle into the seat). Helix threads at a constant rate
- // (mechanically correct) and planner paths carry their own timing.
- const insertion = isEasedMotion(step.motion)
- ? resampleEased(rawKeyframes)
- : rawKeyframes;
- const glides =
- glide && (!glide.nodeIds || glide.nodeIds.includes(nodeId));
- const keyframes = glide
- ? prependGlide(
- insertion,
- glides ? glide.offset : null,
- seatedPose,
- glide.seconds
- )
- : insertion;
- tracks.push(
- ...nodeTracks(
- node,
- delayKeyframes(keyframes, unitsSeconds),
- worldScale,
- clipLength
- )
- );
- }
- }
-
- if (tracks.length === 0) return null;
- return new AnimationClip(`step:${step.id}`, clipLength, tracks);
-}
-
-function worldPoseOf(node: Object3D): {
- seatedPose: Pose;
- worldScale: Vector3;
-} {
- node.updateWorldMatrix(true, false);
- const worldPosition = new Vector3();
- const worldQuaternion = new Quaternion();
- const worldScale = new Vector3();
- node.matrixWorld.decompose(worldPosition, worldQuaternion, worldScale);
- return {
- seatedPose: {
- position: worldPosition.toArray() as Vec3,
- quaternion: toQuat(worldQuaternion)
- },
- worldScale
- };
-}
-
-/** Holds the first pose for `seconds`, then plays the keyframes. */
-function delayKeyframes(
- keyframes: MotionKeyframes,
- seconds: number
-): MotionKeyframes {
- if (seconds <= 0 || keyframes.times.length === 0) return keyframes;
- return {
- times: [0, ...keyframes.times.map((time) => time + seconds)],
- positions: [...keyframes.positions.slice(0, 3), ...keyframes.positions],
- quaternions: [
- ...keyframes.quaternions.slice(0, 4),
- ...keyframes.quaternions
- ]
- };
-}
-
-/**
- * World-space keyframes → uuid-bound tracks in the node's parent-local space,
- * holding the last (seated) pose until `clipLength` so the loop pauses there.
- */
-function nodeTracks(
- node: Object3D,
- keyframes: MotionKeyframes,
- worldScale: Vector3,
- clipLength: number
-): (VectorKeyframeTrack | QuaternionKeyframeTrack)[] {
- const parentWorldInverse = node.parent
- ? node.parent.matrixWorld.clone().invert()
- : new Matrix4();
-
- const times: number[] = [];
- const positions: number[] = [];
- const quaternions: number[] = [];
- const worldMatrix = new Matrix4();
- const localMatrix = new Matrix4();
- const localPosition = new Vector3();
- const localQuaternion = new Quaternion();
- const localScale = new Vector3();
-
- const frameCount = keyframes.times.length;
- for (let i = 0; i < frameCount; i++) {
- const time = keyframes.times[i];
- if (time === undefined) continue;
- const position = new Vector3().fromArray(keyframes.positions, i * 3);
- const quaternion = new Quaternion().fromArray(keyframes.quaternions, i * 4);
- worldMatrix.compose(position, quaternion, worldScale);
- localMatrix.multiplyMatrices(parentWorldInverse, worldMatrix);
- localMatrix.decompose(localPosition, localQuaternion, localScale);
- times.push(time);
- positions.push(localPosition.x, localPosition.y, localPosition.z);
- quaternions.push(
- localQuaternion.x,
- localQuaternion.y,
- localQuaternion.z,
- localQuaternion.w
- );
- }
-
- // Hold the seated pose so LoopRepeat pauses before restarting.
- const lastTime = times[times.length - 1];
- if (lastTime !== undefined && lastTime < clipLength - 1e-9) {
- times.push(clipLength);
- positions.push(...positions.slice(-3));
- quaternions.push(...quaternions.slice(-4));
- }
-
- return [
- new VectorKeyframeTrack(`${node.uuid}.position`, times, positions),
- new QuaternionKeyframeTrack(`${node.uuid}.quaternion`, times, quaternions)
- ];
-}
-
-/**
- * Prepends an eased straight glide from seat + `offset` to the insertion's
- * first pose, and shifts the insertion to start when the glide ends. The part
- * holds the insertion's starting orientation while it glides (the carry is a
- * pure translation), so a helix that starts unscrewed doesn't snap. A `null`
- * offset holds the part at its insertion start for the glide's duration.
- */
-function prependGlide(
- insertion: MotionKeyframes,
- offset: Vec3 | null,
- seatedPose: Pose,
- seconds: number
-): MotionKeyframes {
- const end = new Vector3().fromArray(insertion.positions, 0);
- const start = offset
- ? toVector3(seatedPose.position).add(toVector3(offset))
- : end.clone();
- const quaternion = new Quaternion().fromArray(insertion.quaternions, 0);
-
- const times: number[] = [];
- const positions: number[] = [];
- const quaternions: number[] = [];
- const point = new Vector3();
- for (let j = 0; j <= EASE_SAMPLES; j++) {
- const u = j / EASE_SAMPLES;
- point.copy(start).lerp(end, easeInOutCubic(u));
- times.push(u * seconds);
- positions.push(point.x, point.y, point.z);
- quaternions.push(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
- }
- // The insertion's first frame is where the glide ended — skip the duplicate.
- for (let i = 1; i < insertion.times.length; i++) {
- times.push(seconds + (insertion.times[i] ?? 0));
- positions.push(...insertion.positions.slice(i * 3, i * 3 + 3));
- quaternions.push(...insertion.quaternions.slice(i * 4, i * 4 + 4));
- }
- return { times, positions, quaternions };
-}
-
-/**
- * World-space waypoints describing a step's insertion travel, for the visual
- * path editor. The LAST waypoint is the seated reference position; earlier
- * waypoints are where the component(s) travel FROM. Relative motions
- * (linear/L/helix) are anchored to `seatedPosition`; a `path` motion's absolute
- * keyframe positions are used directly. `none` — or any motion that can't be
- * sampled — yields a straight default offset so there is always a path to drag.
- *
- * For a multi-component (rigid group) step, pass the centroid of the components' seated
- * positions: the shared relative motion renders as one path anchored there.
- */
-export function motionToWaypoints(
- motion: Motion,
- seatedPosition: Vec3,
- options: { defaultDistance?: number } = {}
-): Vec3[] {
- if (motion.type !== "none") {
- try {
- const keyframes = motionToKeyframes(motion, {
- position: seatedPosition,
- quaternion: [0, 0, 0, 1]
- });
- if (keyframes) {
- const points = dedupePositions(keyframes.positions);
- if (points.length >= 2) return points;
- }
- } catch {
- // Unsamplable (e.g. an absolute path whose seated pose differs) — fall
- // through to the default straight offset below.
- }
- }
- const distance =
- options.defaultDistance && options.defaultDistance > 0
- ? options.defaultDistance
- : DEFAULT_WAYPOINT_DISTANCE;
- const start = toVector3(seatedPosition).add(new Vector3(0, distance, 0));
- return [start.toArray() as Vec3, seatedPosition];
-}
-
-/**
- * Converts dragged world-space waypoints back into a RELATIVE motion — 2
- * waypoints → `linear`, 3+ → `L` (multi-segment). Relative (not absolute
- * `path`) so it applies to every component in a rigid-group step. Pure translation:
- * components keep their seated orientation. The last waypoint is forced to the
- * seated position; zero-length segments are dropped; degenerate input collapses
- * to `none`. Directions/distances match `motionToKeyframes`' reconstruction, so
- * `motionToWaypoints` → `waypointsToMotion` round-trips exactly for linear/L.
- */
-export function waypointsToMotion(
- waypoints: Vec3[],
- seatedPosition: Vec3
-): Motion {
- const points = waypoints.map(toVector3);
- if (points.length > 0) points[points.length - 1] = toVector3(seatedPosition);
-
- const segments: { direction: Vec3; distance: number }[] = [];
- for (let i = 1; i < points.length; i++) {
- const from = points[i - 1];
- const to = points[i];
- if (!from || !to) continue;
- const delta = to.clone().sub(from);
- const distance = delta.length();
- if (distance < WAYPOINT_EPSILON) continue;
- segments.push({
- direction: delta.divideScalar(distance).toArray() as Vec3,
- distance
- });
- }
-
- const first = segments[0];
- if (!first) return { type: "none" };
- if (segments.length === 1) {
- return {
- type: "linear",
- direction: first.direction,
- distance: first.distance
- };
- }
- return { type: "L", segments };
-}
-
-/**
- * One editable waypoint: where the moving set's seated center travels through
- * (world space) and how it is turned there, relative to its seated pose.
- */
-export type EditorWaypoint = { position: Vec3; rotation: Quat };
-
-const IDENTITY_QUAT: Quat = [0, 0, 0, 1];
-
-/**
- * Editor waypoints for any motion. A `waypoints` motion keeps its rotations;
- * every other motion goes through `motionToWaypoints` with no rotation.
- */
-export function motionToEditorWaypoints(
- motion: Motion,
- seatedPosition: Vec3,
- options: { defaultDistance?: number } = {}
-): EditorWaypoint[] {
- if (motion.type === "waypoints" && motion.waypoints.length >= 2) {
- const seated = toVector3(seatedPosition);
- return motion.waypoints.map((waypoint) => ({
- position: seated
- .clone()
- .add(toVector3(waypoint.offset))
- .toArray() as Vec3,
- rotation: waypoint.rotation
- }));
- }
- return motionToWaypoints(motion, seatedPosition, options).map((position) => ({
- position,
- rotation: IDENTITY_QUAT
- }));
-}
-
-/**
- * Edited waypoints back to a motion. With no rotation anywhere it is the same
- * `linear` / `L` / `none` the editor has always saved; any turned waypoint
- * makes it a relative `waypoints` motion. The last waypoint is forced to the
- * seat, unturned.
- */
-export function editorWaypointsToMotion(
- waypoints: EditorWaypoint[],
- seatedPosition: Vec3
-): Motion {
- const rotated = waypoints
- .slice(0, -1)
- .some((waypoint) => !isIdentityRotation(waypoint.rotation));
- if (!rotated) {
- return waypointsToMotion(
- waypoints.map((waypoint) => waypoint.position),
- seatedPosition
- );
- }
- const seated = toVector3(seatedPosition);
- return {
- type: "waypoints",
- waypoints: waypoints.map((waypoint, index) =>
- index === waypoints.length - 1
- ? { offset: [0, 0, 0], rotation: IDENTITY_QUAT }
- : {
- offset: toVector3(waypoint.position).sub(seated).toArray() as Vec3,
- rotation: toQuat(toQuaternion(waypoint.rotation))
- }
- )
- };
-}
-
-function isIdentityRotation(rotation: Quat): boolean {
- return Math.abs(toQuaternion(rotation).w) >= 1 - 1e-6;
-}
-
-function isEasedMotion(motion: Motion): boolean {
- return (
- motion.type === "linear" ||
- motion.type === "L" ||
- motion.type === "waypoints"
- );
-}
-
-/**
- * Center of the nodes' seated world bounds — the visual middle of the set,
- * which a `waypoints` motion turns about. Node origins won't do: CAD exports
- * often pivot far from the geometry. The editor anchors its path here too.
- */
-export function seatedBoundsCenter(
- nodeIds: string[],
- nodesById: Map<string, Object3D>
-): Vec3 | null {
- const box = new Box3();
- for (const nodeId of nodeIds) {
- const node = nodesById.get(nodeId);
- if (!node) continue;
- node.updateWorldMatrix(true, false);
- box.expandByObject(node);
- }
- if (box.isEmpty()) return null;
- return box.getCenter(new Vector3()).toArray() as Vec3;
-}
-
-/** Flat [x,y,z,…] → Vec3[], dropping consecutive coincident points. */
-function dedupePositions(flat: number[]): Vec3[] {
- const points: Vec3[] = [];
- for (let i = 0; i + 2 < flat.length; i += 3) {
- const point: Vec3 = [flat[i] ?? 0, flat[i + 1] ?? 0, flat[i + 2] ?? 0];
- const previous = points[points.length - 1];
- if (
- previous &&
- Math.hypot(
- point[0] - previous[0],
- point[1] - previous[1],
- point[2] - previous[2]
- ) < WAYPOINT_EPSILON
- ) {
- continue;
- }
- points.push(point);
- }
- return points;
-}
-
-function toVector3(value: Vec3): Vector3 {
- return new Vector3(value[0], value[1], value[2]);
-}
-
-function toQuaternion(value: Quat): Quaternion {
- return new Quaternion(value[0], value[1], value[2], value[3]).normalize();
-}
-
-function toQuat(quaternion: Quaternion): Quat {
- return [quaternion.x, quaternion.y, quaternion.z, quaternion.w];
-}
-
-function fromPoses(
- times: number[],
- poses: { position: Vector3; quaternion: Quaternion }[]
-): MotionKeyframes {
- const positions: number[] = [];
- const quaternions: number[] = [];
- for (const pose of poses) {
- positions.push(pose.position.x, pose.position.y, pose.position.z);
- quaternions.push(
- pose.quaternion.x,
- pose.quaternion.y,
- pose.quaternion.z,
- pose.quaternion.w
- );
- }
- return { times, positions, quaternions };
-}
diff --git a/packages/viewer/src/orientation.test.ts b/packages/viewer/src/orientation.test.ts
new file mode 100644
index 0000000000..76f57eb7cf
--- /dev/null
+++ b/packages/viewer/src/orientation.test.ts
@@ -0,0 +1,209 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { Quaternion, Vector3 } from "three";
+import { describe, expect, it } from "vitest";
+import {
+ describeOrientation,
+ isOrientation,
+ resolveOrientations,
+ turnOrientation
+} from "./orientation";
+import { IDENTITY_QUAT, sameOrientation } from "./quat";
+import type { AssemblyStep, Quat, Vec3 } from "./types";
+
+type Row = Pick<
+ AssemblyStep,
+ | "id"
+ | "componentNodeIds"
+ | "parentStepId"
+ | "usedInStepId"
+ | "isSubAssembly"
+ | "orientation"
+>;
+
+const step = (id: string, extra: Partial<Row> = {}): Row => ({
+ id,
+ componentNodeIds: [id],
+ ...extra
+});
+
+// 180° about X: the build upside down.
+const FLIPPED: Quat = [1, 0, 0, 0];
+
+const benchUpOfModelTop = (q: Quat): Vec3 =>
+ new Vector3(0, 0, 1)
+ .applyQuaternion(new Quaternion(...q))
+ .toArray()
+ .map((n) => Math.round(n * 1e6) / 1e6 + 0) as Vec3;
+
+describe("resolveOrientations", () => {
+ it("carries a turn forward through its build", () => {
+ const resolved = resolveOrientations([
+ step("base"),
+ step("flip", { orientation: FLIPPED }),
+ step("cover")
+ ]);
+ expect(resolved.map((r) => r.sourceStepId)).toEqual([null, "flip", "flip"]);
+ expect(resolved[0]?.orientation).toEqual(IDENTITY_QUAT);
+ expect(resolved[2]?.orientation).toEqual(FLIPPED);
+ });
+
+ it("starts a sub-assembly upright, even after the main build flips", () => {
+ const resolved = resolveOrientations([
+ step("flip", { orientation: FLIPPED }),
+ step("member", { parentStepId: "unit" }),
+ step("unit", { isSubAssembly: true, componentNodeIds: [] }),
+ step("after")
+ ]);
+ expect(resolved[1]).toEqual({
+ orientation: IDENTITY_QUAT,
+ sourceStepId: null
+ });
+ // The header joins the main build, so it plays in the main build's turn.
+ expect(resolved[2]?.sourceStepId).toBe("flip");
+ expect(resolved[3]?.sourceStepId).toBe("flip");
+ });
+
+ it("keeps a sub-assembly's turn out of the main build", () => {
+ const resolved = resolveOrientations([
+ step("first", { parentStepId: "unit", orientation: FLIPPED }),
+ step("second", { parentStepId: "unit" }),
+ step("unit", { isSubAssembly: true, componentNodeIds: [] }),
+ step("main")
+ ]);
+ expect(resolved[1]?.sourceStepId).toBe("first");
+ expect(resolved[3]).toEqual({
+ orientation: IDENTITY_QUAT,
+ sourceStepId: null
+ });
+ });
+
+ it("ignores a malformed stored value", () => {
+ const resolved = resolveOrientations([
+ step("bad", { orientation: [0, 0, 0, 2] })
+ ]);
+ expect(resolved[0]?.sourceStepId).toBeNull();
+ });
+});
+
+describe("turnOrientation", () => {
+ // Camera in front of the build (CAD front is -Y), level with it.
+ const front = { position: [0, -10, 0] as Vec3, target: [0, 0, 0] as Vec3 };
+
+ it("tipping forward rolls the top toward the viewer", () => {
+ const tipped = turnOrientation(IDENTITY_QUAT, "tipForward", front);
+ expect(benchUpOfModelTop(tipped)).toEqual([0, -1, 0]);
+ });
+
+ it("tipping back rolls the top away from the viewer", () => {
+ const tipped = turnOrientation(IDENTITY_QUAT, "tipBack", front);
+ expect(benchUpOfModelTop(tipped)).toEqual([0, 1, 0]);
+ });
+
+ it("two tips forward turn the build upside down", () => {
+ const once = turnOrientation(IDENTITY_QUAT, "tipForward", front);
+ const twice = turnOrientation(once, "tipForward", front);
+ expect(benchUpOfModelTop(twice)).toEqual([0, 0, -1]);
+ });
+
+ it("a turn and its opposite cancel out", () => {
+ const left = turnOrientation(IDENTITY_QUAT, "spinLeft", front);
+ const back = turnOrientation(left, "spinRight", front);
+ expect(sameOrientation(back, IDENTITY_QUAT)).toBe(true);
+ });
+
+ it("spinning right moves the front to the viewer's right", () => {
+ // From the front, the viewer's right is +X.
+ const turned = turnOrientation(IDENTITY_QUAT, "spinRight", front);
+ const frontFace = new Vector3(0, -1, 0)
+ .applyQuaternion(new Quaternion(...turned))
+ .toArray()
+ .map((n) => Math.round(n * 1e6) / 1e6 + 0);
+ expect(frontFace).toEqual([1, 0, 0]);
+ });
+
+ it("tips toward a camera at the side, not the CAD front", () => {
+ const side = { position: [10, 0, 5] as Vec3, target: [0, 0, 0] as Vec3 };
+ const tipped = turnOrientation(IDENTITY_QUAT, "tipForward", side);
+ expect(benchUpOfModelTop(tipped)).toEqual([1, 0, 0]);
+ });
+
+ it("tips toward the viewer of an already flipped build", () => {
+ const tipped = turnOrientation(FLIPPED, "tipForward", front);
+ // What faces up now (the model's underside) rolls toward the viewer, so
+ // the model's top, facing the bench, rolls away from it.
+ expect(benchUpOfModelTop(tipped)).toEqual([0, 1, 0]);
+ });
+});
+
+describe("turnOrientation from a slanted view", () => {
+ // A typical editor view: front-right, above the bench.
+ const slanted = { position: [6, -10, 7] as Vec3, target: [0, 0, 0] as Vec3 };
+
+ it("tips about the nearest square axis, so the result is a clean 90°", () => {
+ const tipped = turnOrientation(IDENTITY_QUAT, "tipForward", slanted);
+ // The camera is mostly in front (-Y), so the top rolls toward -Y.
+ expect(benchUpOfModelTop(tipped)).toEqual([0, -1, 0]);
+ });
+
+ it("flips upside down in one turn", () => {
+ const flipped = turnOrientation(IDENTITY_QUAT, "flip", slanted);
+ expect(benchUpOfModelTop(flipped)).toEqual([0, 0, -1]);
+ expect(describeOrientation(flipped)).toBe("upsideDown");
+ });
+
+ it("two tips equal one flip", () => {
+ const once = turnOrientation(IDENTITY_QUAT, "tipForward", slanted);
+ const twice = turnOrientation(once, "tipForward", slanted);
+ const flipped = turnOrientation(IDENTITY_QUAT, "flip", slanted);
+ expect(sameOrientation(twice, flipped)).toBe(true);
+ });
+});
+
+describe("describeOrientation", () => {
+ it("names the pose by where the top points", () => {
+ expect(describeOrientation(IDENTITY_QUAT)).toBe("upright");
+ expect(describeOrientation(FLIPPED)).toBe("upsideDown");
+ const side = new Quaternion().setFromAxisAngle(
+ new Vector3(1, 0, 0),
+ Math.PI / 2
+ );
+ expect(describeOrientation([side.x, side.y, side.z, side.w])).toBe(
+ "onSide"
+ );
+ });
+});
+
+describe("turnOrientation snapping", () => {
+ const front = { position: [0, -100, 0] as Vec3, target: [0, 0, 0] as Vec3 };
+ const aboutZ = (angle: number): Quat => {
+ const q = new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), angle);
+ return [q.x, q.y, q.z, q.w];
+ };
+
+ it("always returns a real rotation, even from a 45° start", () => {
+ const turned = turnOrientation(aboutZ(Math.PI / 4), "spinRight", front);
+ expect(isOrientation(turned)).toBe(true);
+ expect(benchUpOfModelTop(turned)).toEqual([0, 0, 1]);
+ });
+
+ it("lands a nearly right-angle start exactly on a right angle", () => {
+ const turned = turnOrientation(
+ aboutZ(Math.PI / 2 + Math.PI / 180),
+ "spinLeft",
+ front
+ );
+ expect(sameOrientation(turned, IDENTITY_QUAT)).toBe(true);
+ });
+});
+
+describe("isOrientation", () => {
+ it("accepts a unit quaternion and rejects the rest", () => {
+ expect(isOrientation([0, 0, 0, 1])).toBe(true);
+ expect(isOrientation([0, 0, 0, 2])).toBe(false);
+ expect(isOrientation([1, 2, 3])).toBe(false);
+ expect(isOrientation(null)).toBe(false);
+ });
+});
diff --git a/packages/viewer/src/orientation.ts b/packages/viewer/src/orientation.ts
new file mode 100644
index 0000000000..deaff4cd73
--- /dev/null
+++ b/packages/viewer/src/orientation.ts
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { Matrix4, Quaternion, Vector3 } from "three";
+import { IDENTITY_QUAT, toQuat, toQuaternion } from "./quat";
+import { stepWorlds } from "./subassembly";
+import type { AssemblyStep, Quat, Vec3 } from "./types";
+import { isFiniteTuple } from "./validate-motion";
+
+/**
+ * Build orientation: how the whole build is turned on a step (flipped to fit
+ * parts on its underside, laid on its side). A unit quaternion that turns the
+ * model frame into the bench frame; both are Z-up. A step's `orientation`
+ * holds from that step on, within its own build — the main build and each
+ * sub-assembly keep separate chains, and a sub-assembly starts upright.
+ *
+ * The player shows it by rolling and orbiting the camera, never by turning the
+ * model: motion, the path editor and box select all work in world space.
+ */
+
+/** Turns relative to the current view: `flip` is 180°, the others 90°. */
+export type BuildTurn =
+ | "flip"
+ | "tipForward"
+ | "tipBack"
+ | "spinLeft"
+ | "spinRight";
+
+const BENCH_UP = new Vector3(0, 0, 1);
+
+export function isOrientation(value: unknown): value is Quat {
+ return (
+ isFiniteTuple(value, 4) &&
+ Math.abs(Math.hypot(...(value as number[])) - 1) < 1e-3
+ );
+}
+
+/**
+ * Snaps to the nearest of the 24 right-angle orientations, so repeated 90°
+ * turns never drift and a turn and its opposite compare equal.
+ */
+function snapOrientation(q: Quat): Quat {
+ const rotation = toQuaternion(q);
+ // Snap where the model's X and Y axes point to the nearest bench axes (two
+ // different ones), then derive Z — rounding matrix entries one by one can
+ // yield something that is not a rotation at all.
+ const x = nearestAxis(new Vector3(1, 0, 0).applyQuaternion(rotation));
+ const y = nearestAxis(new Vector3(0, 1, 0).applyQuaternion(rotation), x);
+ const z = new Vector3().crossVectors(x, y);
+ const matrix = new Matrix4().makeBasis(x, y, z);
+ return toQuat(new Quaternion().setFromRotationMatrix(matrix));
+}
+
+export type OrientationPose = "upright" | "upsideDown" | "onSide";
+
+export function describeOrientation(q: Quat): OrientationPose {
+ const top = BENCH_UP.clone().applyQuaternion(toQuaternion(q)).z;
+ if (top > 0.5) return "upright";
+ if (top < -0.5) return "upsideDown";
+ return "onSide";
+}
+
+/** The bench's up direction in the model frame — what `camera.up` becomes. */
+export function upForOrientation(q: Quat): Vec3 {
+ return BENCH_UP.clone()
+ .applyQuaternion(toQuaternion(q).invert())
+ .toArray() as Vec3;
+}
+
+export type ResolvedOrientation = {
+ orientation: Quat;
+ /** The step that set it; `null` = no step of this build turned it yet. */
+ sourceStepId: string | null;
+};
+
+/**
+ * Each step's orientation, in step order: its own, else the last one set
+ * earlier in the same build (see `stepWorlds`), else upright.
+ */
+export function resolveOrientations(
+ steps: Pick<
+ AssemblyStep,
+ | "id"
+ | "componentNodeIds"
+ | "parentStepId"
+ | "usedInStepId"
+ | "isSubAssembly"
+ | "orientation"
+ >[]
+): ResolvedOrientation[] {
+ const worlds = stepWorlds(steps);
+ const current = new Map<string | null, ResolvedOrientation>();
+ return steps.map((step) => {
+ const world = worlds.get(step.id) ?? null;
+ if (isOrientation(step.orientation)) {
+ current.set(world, {
+ orientation: step.orientation,
+ sourceStepId: step.id
+ });
+ }
+ return (
+ current.get(world) ?? {
+ orientation: IDENTITY_QUAT,
+ sourceStepId: null
+ }
+ );
+ });
+}
+
+/**
+ * `current` turned as seen from `view` — a bench-frame camera pose, as the
+ * player's `captureCameraPose` returns it. Spinning turns the build about the
+ * bench's up axis; tipping and flipping roll it about the bench axis that runs
+ * most nearly left-right on screen, so a turn is always a clean right angle
+ * even from a slanted view.
+ */
+export function turnOrientation(
+ current: Quat,
+ turn: BuildTurn,
+ view: { position: Vec3; target: Vec3 }
+): Quat {
+ const orientation = toQuaternion(current);
+ // Where the camera stands, flattened onto the bench.
+ const toCamera = new Vector3(...view.position)
+ .sub(new Vector3(...view.target))
+ .setZ(0);
+ // Looking straight down there is no "toward the viewer": use the CAD front.
+ const facing =
+ toCamera.lengthSq() < 1e-12 ? new Vector3(0, -1, 0) : toCamera.normalize();
+
+ const axis =
+ turn === "spinLeft" || turn === "spinRight"
+ ? BENCH_UP.clone()
+ : nearestAxis(new Vector3().crossVectors(BENCH_UP, facing));
+ const angle =
+ turn === "flip"
+ ? Math.PI
+ : turn === "spinRight" || turn === "tipForward"
+ ? Math.PI / 2
+ : -Math.PI / 2;
+
+ const rotation = new Quaternion().setFromAxisAngle(axis, angle);
+ return snapOrientation(toQuat(rotation.multiply(orientation).normalize()));
+}
+
+/** The bench axis (±X, ±Y, ±Z) closest to `v`, skipping `exclude`'s axis. */
+function nearestAxis(v: Vector3, exclude?: Vector3): Vector3 {
+ const components = [v.x, v.y, v.z];
+ let best = -1;
+ for (let i = 0; i < 3; i++) {
+ if (exclude && Math.abs(exclude.getComponent(i)) > 0.5) continue;
+ if (
+ best < 0 ||
+ Math.abs(components[i] ?? 0) > Math.abs(components[best] ?? 0)
+ ) {
+ best = i;
+ }
+ }
+ const axis = new Vector3();
+ axis.setComponent(best, Math.sign(components[best] ?? 0) || 1);
+ return axis;
+}
diff --git a/packages/viewer/src/path-editing.test.ts b/packages/viewer/src/path-editing.test.ts
new file mode 100644
index 0000000000..1ce6b4c0aa
--- /dev/null
+++ b/packages/viewer/src/path-editing.test.ts
@@ -0,0 +1,164 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { describe, expect, it } from "vitest";
+import {
+ DEFAULT_WAYPOINT_DISTANCE,
+ editorWaypointsToMotion,
+ motionToEditorWaypoints,
+ motionToWaypoints,
+ waypointsToMotion
+} from "./path-editing";
+import { expectVectorClose } from "./test-utils";
+import type { Motion, Vec3 } from "./types";
+
+describe("motionToWaypoints / waypointsToMotion", () => {
+ const seated: Vec3 = [10, 5, -2];
+
+ function expectVec3Close(actual: Vec3, expected: Vec3) {
+ actual.forEach((value, index) => {
+ expect(value).toBeCloseTo(expected[index] ?? Number.NaN, 6);
+ });
+ }
+
+ it("samples a linear motion to a start + seated waypoint", () => {
+ const motion: Motion = {
+ type: "linear",
+ direction: [0, 1, 0],
+ distance: 20
+ };
+ const waypoints = motionToWaypoints(motion, seated);
+ expect(waypoints).toHaveLength(2);
+ expectVec3Close(waypoints[0]!, [10, -15, -2]); // seated - dir*distance
+ expectVec3Close(waypoints[1]!, seated); // last === seated
+ });
+
+ it("round-trips a linear motion exactly", () => {
+ const motion: Motion = {
+ type: "linear",
+ direction: [0, 0, 1],
+ distance: 12
+ };
+ const back = waypointsToMotion(motionToWaypoints(motion, seated), seated);
+ expect(back.type).toBe("linear");
+ if (back.type === "linear") {
+ expectVec3Close(back.direction, [0, 0, 1]);
+ expect(back.distance).toBeCloseTo(12, 6);
+ }
+ });
+
+ it("round-trips an L motion, preserving segment order and directions", () => {
+ const motion: Motion = {
+ type: "L",
+ segments: [
+ { direction: [1, 0, 0], distance: 8 },
+ { direction: [0, 1, 0], distance: 5 }
+ ]
+ };
+ const back = waypointsToMotion(motionToWaypoints(motion, seated), seated);
+ expect(back.type).toBe("L");
+ if (back.type === "L") {
+ expect(back.segments).toHaveLength(2);
+ expectVec3Close(back.segments[0]!.direction, [1, 0, 0]);
+ expect(back.segments[0]!.distance).toBeCloseTo(8, 6);
+ expectVec3Close(back.segments[1]!.direction, [0, 1, 0]);
+ expect(back.segments[1]!.distance).toBeCloseTo(5, 6);
+ }
+ });
+
+ it("forces the last waypoint to the seated position", () => {
+ const back = waypointsToMotion(
+ [
+ [0, 0, 0],
+ [99, 99, 99]
+ ],
+ seated
+ );
+ // The seated end is pinned, so travel is start -> seated.
+ expect(back.type).toBe("linear");
+ if (back.type === "linear") {
+ expect(back.distance).toBeCloseTo(
+ Math.hypot(seated[0], seated[1], seated[2]),
+ 6
+ );
+ }
+ });
+
+ it("synthesizes a default straight path for a none motion", () => {
+ const waypoints = motionToWaypoints({ type: "none" }, seated);
+ expect(waypoints).toHaveLength(2);
+ expectVec3Close(waypoints[0]!, [
+ seated[0],
+ seated[1] + DEFAULT_WAYPOINT_DISTANCE,
+ seated[2]
+ ]);
+ expectVec3Close(waypoints[1]!, seated);
+ });
+
+ it("collapses degenerate (coincident) waypoints to none", () => {
+ expect(waypointsToMotion([seated, seated], seated)).toEqual({
+ type: "none"
+ });
+ });
+
+ it("drops a zero-length middle segment (3 pts, collinear) to linear", () => {
+ const back = waypointsToMotion([[0, 0, 0], [0, 0, 0], seated], seated);
+ expect(back.type).toBe("linear");
+ });
+});
+
+describe("editor waypoints", () => {
+ const halfTurnZ: [number, number, number, number] = [0, 0, 1, 0];
+
+ it("round-trips through the editor and keeps unturned paths linear / L", () => {
+ const seated: Vec3 = [1, 2, 3];
+ expect(
+ editorWaypointsToMotion(
+ [
+ { position: [1, 2, 53], rotation: [0, 0, 0, 1] },
+ { position: seated, rotation: [0, 0, 0, 1] }
+ ],
+ seated
+ ).type
+ ).toBe("linear");
+ expect(
+ editorWaypointsToMotion(
+ [
+ { position: [1, 52, 53], rotation: [0, 0, 0, 1] },
+ { position: [1, 2, 53], rotation: [0, 0, 0, 1] },
+ { position: seated, rotation: [0, 0, 0, 1] }
+ ],
+ seated
+ ).type
+ ).toBe("L");
+
+ const turned = [
+ { position: [1, 2, 53] as Vec3, rotation: halfTurnZ },
+ {
+ position: seated,
+ rotation: [0, 0, 0, 1] as [number, number, number, number]
+ }
+ ];
+ const motion = editorWaypointsToMotion(turned, seated);
+ expect(motion.type).toBe("waypoints");
+ const back = motionToEditorWaypoints(motion, seated);
+ expect(back.length).toBe(2);
+ expectVectorClose(back[0]?.position ?? [], [1, 2, 53]);
+ expectVectorClose(back[0]?.rotation ?? [], halfTurnZ);
+ expectVectorClose(back[1]?.position ?? [], seated);
+ });
+
+ it("keeps a turn stored as a non-unit quaternion", () => {
+ const seated: Vec3 = [0, 0, 0];
+ expect(
+ editorWaypointsToMotion(
+ [
+ { position: [0, 0, 50], rotation: [0.1, 0, 0, 1.5] },
+ { position: seated, rotation: [0, 0, 0, 1] }
+ ],
+ seated
+ ).type
+ ).toBe("waypoints");
+ });
+});
diff --git a/packages/viewer/src/path-editing.ts b/packages/viewer/src/path-editing.ts
new file mode 100644
index 0000000000..42d8d1b64a
--- /dev/null
+++ b/packages/viewer/src/path-editing.ts
@@ -0,0 +1,180 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { Vector3 } from "three";
+import { motionToKeyframes } from "./keyframes";
+import {
+ IDENTITY_QUAT,
+ sameOrientation,
+ toQuat,
+ toQuaternion,
+ toVector3
+} from "./quat";
+import type { Motion, Quat, Vec3 } from "./types";
+
+/** Coincident-waypoint threshold (mm). */
+const WAYPOINT_EPSILON = 1e-3;
+/** Travel of the straight default path drawn for a `none` motion. */
+export const DEFAULT_WAYPOINT_DISTANCE = 50;
+
+/**
+ * World-space waypoints describing a step's insertion travel, for the visual
+ * path editor. The LAST waypoint is the seated reference position; earlier
+ * waypoints are where the component(s) travel FROM. Relative motions
+ * (linear/L/helix) are anchored to `seatedPosition`; a `path` motion's absolute
+ * keyframe positions are used directly. `none` — or any motion that can't be
+ * sampled — yields a straight default offset so there is always a path to drag.
+ *
+ * For a multi-component (rigid group) step, pass the centroid of the components' seated
+ * positions: the shared relative motion renders as one path anchored there.
+ */
+export function motionToWaypoints(
+ motion: Motion,
+ seatedPosition: Vec3,
+ options: { defaultDistance?: number } = {}
+): Vec3[] {
+ if (motion.type !== "none") {
+ try {
+ const keyframes = motionToKeyframes(motion, {
+ position: seatedPosition,
+ quaternion: IDENTITY_QUAT
+ });
+ if (keyframes) {
+ const points = dedupePositions(keyframes.positions);
+ if (points.length >= 2) return points;
+ }
+ } catch {
+ // Unsamplable (e.g. an absolute path whose seated pose differs) — fall
+ // through to the default straight offset below.
+ }
+ }
+ const distance =
+ options.defaultDistance && options.defaultDistance > 0
+ ? options.defaultDistance
+ : DEFAULT_WAYPOINT_DISTANCE;
+ const start = toVector3(seatedPosition).add(new Vector3(0, distance, 0));
+ return [start.toArray() as Vec3, seatedPosition];
+}
+
+/**
+ * Converts dragged world-space waypoints back into a RELATIVE motion — 2
+ * waypoints → `linear`, 3+ → `L` (multi-segment). Relative (not absolute
+ * `path`) so it applies to every component in a rigid-group step. Pure translation:
+ * components keep their seated orientation. The last waypoint is forced to the
+ * seated position; zero-length segments are dropped; degenerate input collapses
+ * to `none`. Directions/distances match `motionToKeyframes`' reconstruction, so
+ * `motionToWaypoints` → `waypointsToMotion` round-trips exactly for linear/L.
+ */
+export function waypointsToMotion(
+ waypoints: Vec3[],
+ seatedPosition: Vec3
+): Motion {
+ const points = waypoints.map(toVector3);
+ if (points.length > 0) points[points.length - 1] = toVector3(seatedPosition);
+
+ const segments: { direction: Vec3; distance: number }[] = [];
+ for (let i = 1; i < points.length; i++) {
+ const from = points[i - 1];
+ const to = points[i];
+ if (!from || !to) continue;
+ const delta = to.clone().sub(from);
+ const distance = delta.length();
+ if (distance < WAYPOINT_EPSILON) continue;
+ segments.push({
+ direction: delta.divideScalar(distance).toArray() as Vec3,
+ distance
+ });
+ }
+
+ const first = segments[0];
+ if (!first) return { type: "none" };
+ if (segments.length === 1) {
+ return {
+ type: "linear",
+ direction: first.direction,
+ distance: first.distance
+ };
+ }
+ return { type: "L", segments };
+}
+
+/**
+ * One editable waypoint: where the moving set's seated center travels through
+ * (world space) and how it is turned there, relative to its seated pose.
+ */
+export type EditorWaypoint = { position: Vec3; rotation: Quat };
+
+export function motionToEditorWaypoints(
+ motion: Motion,
+ seatedPosition: Vec3,
+ options: { defaultDistance?: number } = {}
+): EditorWaypoint[] {
+ if (motion.type === "waypoints" && motion.waypoints.length >= 2) {
+ const seated = toVector3(seatedPosition);
+ return motion.waypoints.map((waypoint) => ({
+ position: seated
+ .clone()
+ .add(toVector3(waypoint.offset))
+ .toArray() as Vec3,
+ rotation: waypoint.rotation
+ }));
+ }
+ return motionToWaypoints(motion, seatedPosition, options).map((position) => ({
+ position,
+ rotation: IDENTITY_QUAT
+ }));
+}
+
+/**
+ * With no turned waypoint this is `waypointsToMotion`'s `linear` / `L` / `none`;
+ * any turn makes it a relative `waypoints` motion. The last waypoint is forced
+ * to the seat, unturned.
+ */
+export function editorWaypointsToMotion(
+ waypoints: EditorWaypoint[],
+ seatedPosition: Vec3
+): Motion {
+ const rotated = waypoints
+ .slice(0, -1)
+ .some((waypoint) => !sameOrientation(waypoint.rotation, IDENTITY_QUAT));
+ if (!rotated) {
+ return waypointsToMotion(
+ waypoints.map((waypoint) => waypoint.position),
+ seatedPosition
+ );
+ }
+ const seated = toVector3(seatedPosition);
+ return {
+ type: "waypoints",
+ waypoints: waypoints.map((waypoint, index) =>
+ index === waypoints.length - 1
+ ? { offset: [0, 0, 0], rotation: IDENTITY_QUAT }
+ : {
+ offset: toVector3(waypoint.position).sub(seated).toArray() as Vec3,
+ rotation: toQuat(toQuaternion(waypoint.rotation))
+ }
+ )
+ };
+}
+
+/** Flat [x,y,z,…] → Vec3[], dropping consecutive coincident points. */
+function dedupePositions(flat: number[]): Vec3[] {
+ const points: Vec3[] = [];
+ for (let i = 0; i + 2 < flat.length; i += 3) {
+ const point: Vec3 = [flat[i] ?? 0, flat[i + 1] ?? 0, flat[i + 2] ?? 0];
+ const previous = points[points.length - 1];
+ if (
+ previous &&
+ Math.hypot(
+ point[0] - previous[0],
+ point[1] - previous[1],
+ point[2] - previous[2]
+ ) < WAYPOINT_EPSILON
+ ) {
+ continue;
+ }
+ points.push(point);
+ }
+ return points;
+}
diff --git a/packages/viewer/src/quat.test.ts b/packages/viewer/src/quat.test.ts
new file mode 100644
index 0000000000..1abd689e5b
--- /dev/null
+++ b/packages/viewer/src/quat.test.ts
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { describe, expect, it } from "vitest";
+import { IDENTITY_QUAT, sameOrientation } from "./quat";
+
+describe("sameOrientation", () => {
+ it("treats q and -q as the same rotation", () => {
+ expect(sameOrientation([0, 0, 1, 0], [0, 0, -1, 0])).toBe(true);
+ expect(sameOrientation(IDENTITY_QUAT, [0, 0, 0, -1])).toBe(true);
+ });
+
+ it("compares rotations, not raw tuples", () => {
+ // A non-unit tuple whose raw dot with identity is 1.5: a turn of ~7.6°.
+ expect(sameOrientation([0.1, 0, 0, 1.5], IDENTITY_QUAT)).toBe(false);
+ // The same rotation scaled is still the same rotation.
+ expect(sameOrientation([0, 0, 0, 2], IDENTITY_QUAT)).toBe(true);
+ expect(sameOrientation([0, 0, 2, 0], [0, 0, 1, 0])).toBe(true);
+ });
+
+ it("matches nothing for a zero quaternion", () => {
+ expect(sameOrientation([0, 0, 0, 0], IDENTITY_QUAT)).toBe(false);
+ });
+
+ it("tells a quarter turn apart", () => {
+ const quarterZ: [number, number, number, number] = [
+ 0,
+ 0,
+ Math.SQRT1_2,
+ Math.SQRT1_2
+ ];
+ expect(sameOrientation(quarterZ, IDENTITY_QUAT)).toBe(false);
+ });
+});
diff --git a/packages/viewer/src/quat.ts b/packages/viewer/src/quat.ts
new file mode 100644
index 0000000000..79c00d54ed
--- /dev/null
+++ b/packages/viewer/src/quat.ts
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { Quaternion, Vector3 } from "three";
+import type { Quat, Vec3 } from "./types";
+
+export const IDENTITY_QUAT: Quat = [0, 0, 0, 1];
+
+export function toVector3(value: Vec3): Vector3 {
+ return new Vector3(value[0], value[1], value[2]);
+}
+
+/** Normalized, so a slightly-off stored quaternion still turns cleanly. */
+export function toQuaternion(value: Quat): Quaternion {
+ return new Quaternion(value[0], value[1], value[2], value[3]).normalize();
+}
+
+export function toQuat(quaternion: Quaternion): Quat {
+ return [quaternion.x, quaternion.y, quaternion.z, quaternion.w];
+}
+
+/** `q` and `-q` match, as do scaled copies; a zero quaternion matches nothing. */
+export function sameOrientation(a: Quat, b: Quat): boolean {
+ const norms = Math.hypot(...a) * Math.hypot(...b);
+ if (!(norms > 0)) return false;
+ const dot = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
+ return Math.abs(dot) / norms > 1 - 1e-6;
+}
diff --git a/packages/viewer/src/step-flags.test.ts b/packages/viewer/src/step-flags.test.ts
new file mode 100644
index 0000000000..9d61bde07a
--- /dev/null
+++ b/packages/viewer/src/step-flags.test.ts
@@ -0,0 +1,69 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { describe, expect, it } from "vitest";
+import { hasCustomMotion, isPlanFlagged, isSavedView } from "./step-flags";
+
+describe("isSavedView", () => {
+ it("is true for a manual pose", () => {
+ expect(
+ isSavedView({ position: [1, 2, 3], target: [0, 0, 0], fov: 45 })
+ ).toBe(true);
+ });
+
+ it("is false for a planner hint, null and malformed values", () => {
+ expect(isSavedView({ source: "plan", direction: [0, 0, 1] })).toBe(false);
+ expect(
+ isSavedView({ source: "plan", position: [1, 2, 3], target: [0, 0, 0] })
+ ).toBe(false);
+ expect(isSavedView(null)).toBe(false);
+ expect(isSavedView(undefined)).toBe(false);
+ expect(isSavedView("view")).toBe(false);
+ expect(isSavedView({ position: [1, 2, 3] })).toBe(false);
+ expect(isSavedView({ position: "a", target: [0, 0, 0] })).toBe(false);
+ });
+});
+
+describe("hasCustomMotion / isPlanFlagged", () => {
+ const moving = { type: "linear", direction: [0, 0, 1], distance: 10 };
+ const none = { type: "none" };
+
+ it("treats a plannedMotion marker as hand-drawn, even unflagged", () => {
+ expect(hasCustomMotion({ plannedMotion: none }, moving)).toBe(true);
+ expect(hasCustomMotion({ plannedMotion: null }, none)).toBe(true);
+ expect(isPlanFlagged({ flagged: true, plannedMotion: none }, none)).toBe(
+ false
+ );
+ });
+
+ it("treats a flagged step that moves as hand-drawn", () => {
+ expect(hasCustomMotion({ flagged: true }, moving)).toBe(true);
+ expect(isPlanFlagged({ flagged: true }, moving)).toBe(false);
+ });
+
+ it("flags a flagged step that does not move", () => {
+ expect(hasCustomMotion({ flagged: true }, none)).toBe(false);
+ expect(isPlanFlagged({ flagged: true }, none)).toBe(true);
+ expect(isPlanFlagged({ flagged: true }, null)).toBe(true);
+ expect(isPlanFlagged({ flagged: true }, { distance: 3 })).toBe(true);
+ });
+
+ it("is neither for an unflagged planner motion", () => {
+ expect(hasCustomMotion({}, moving)).toBe(false);
+ expect(hasCustomMotion({ flagged: false }, moving)).toBe(false);
+ expect(isPlanFlagged({ flagged: false }, none)).toBe(false);
+ });
+
+ it("treats non-object warnings as empty", () => {
+ for (const warnings of [null, undefined, "flagged", 7, true]) {
+ expect(hasCustomMotion(warnings, moving)).toBe(false);
+ expect(isPlanFlagged(warnings, none)).toBe(false);
+ }
+ });
+
+ it("only counts flagged === true", () => {
+ expect(isPlanFlagged({ flagged: "true" }, none)).toBe(false);
+ expect(hasCustomMotion({ flagged: 1 }, moving)).toBe(false);
+ });
+});
diff --git a/packages/viewer/src/step-flags.ts b/packages/viewer/src/step-flags.ts
new file mode 100644
index 0000000000..9fb6504fb1
--- /dev/null
+++ b/packages/viewer/src/step-flags.ts
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+/**
+ * Plain checks on a step's stored `camera` and `warnings`, shared by the
+ * player, the ERP editor and server code. Three-free and zod-free, so it is
+ * safe on the `./steps` entry point.
+ */
+
+function asRecord(value: unknown): Record<string, unknown> {
+ return typeof value === "object" && value !== null
+ ? (value as Record<string, unknown>)
+ : {};
+}
+
+/**
+ * A view the author saved (`{ position, target, fov }`), applied as-is — not a
+ * planner hint (`{ source: "plan", direction }`), which only aims live framing.
+ */
+export function isSavedView(
+ camera: unknown
+): camera is { position: unknown[]; target: unknown[] } {
+ if (typeof camera !== "object" || camera === null) return false;
+ if ("source" in camera) return false;
+ const pose = camera as Record<string, unknown>;
+ return Array.isArray(pose.position) && Array.isArray(pose.target);
+}
+
+/**
+ * The step's motion was drawn by hand in the path editor
+ * (`warnings.plannedMotion` is present). The planner stores `none` on a
+ * flagged step, so a flagged step that moves was drawn too — paths drawn
+ * before `plannedMotion` existed carry no marker.
+ */
+export function hasCustomMotion(warnings: unknown, motion: unknown): boolean {
+ const flags = asRecord(warnings);
+ if (flags.plannedMotion !== undefined) return true;
+ return (
+ flags.flagged === true &&
+ typeof motion === "object" &&
+ motion !== null &&
+ "type" in motion &&
+ motion.type !== "none"
+ );
+}
+
+/**
+ * The planner found no clear path for the step's parts (`flagged`) and the
+ * author has not drawn one by hand, which overrides the flag.
+ */
+export function isPlanFlagged(warnings: unknown, motion: unknown): boolean {
+ return (
+ asRecord(warnings).flagged === true && !hasCustomMotion(warnings, motion)
+ );
+}
diff --git a/packages/viewer/src/steps.ts b/packages/viewer/src/steps.ts
index 3a714b75a9..d5e3649575 100644
--- a/packages/viewer/src/steps.ts
+++ b/packages/viewer/src/steps.ts
@@ -13,6 +13,7 @@ import {
buildAssemblyStepGroups,
CURRENT_PLAN_VERSION
} from "./plan";
+import { hasCustomMotion, isPlanFlagged, isSavedView } from "./step-flags";
import {
buildSubAssemblyPlan,
displayOrder,
@@ -28,7 +29,10 @@ export {
buildSubAssemblyPlan,
CURRENT_PLAN_VERSION,
displayOrder,
+ hasCustomMotion,
indexAssemblyGraph,
+ isPlanFlagged,
+ isSavedView,
isSubAssemblyHeader,
subAssemblyPartIds,
usableSubAssemblies,
diff --git a/packages/viewer/src/subassembly.test.ts b/packages/viewer/src/subassembly.test.ts
index eb34556823..9bc4abfb88 100644
--- a/packages/viewer/src/subassembly.test.ts
+++ b/packages/viewer/src/subassembly.test.ts
@@ -7,11 +7,12 @@ import {
arrivalIndexByNode,
buildCarryPlans,
buildSubAssemblyPlan,
+ carriesUnits,
displayOrder,
+ stepWorlds,
subAssemblyPartIds,
usableSubAssemblies,
- validateSubAssemblies,
- worldOf
+ validateSubAssemblies
} from "./subassembly";
import type { AssemblyStep, Motion } from "./types";
@@ -119,14 +120,27 @@ describe("buildSubAssemblyPlan", () => {
expect(plan.get("sole")?.isolatePartIds).toBeNull();
expect(plan.get("heel")?.isolatePartIds).toBeNull();
});
+
+ it("gives each header its finished unit's parts", () => {
+ expect(plan.get("heel")?.unitPartIds?.sort()).toEqual(
+ ["battery", "idler", "pinion", "plate", "shell"].sort()
+ );
+ expect(plan.get("drive")?.unitPartIds?.sort()).toEqual(
+ ["idler", "pinion", "plate"].sort()
+ );
+ expect(plan.get("fit")?.unitPartIds).toBeNull();
+ });
});
-describe("worldOf / arrivalIndexByNode", () => {
+describe("stepWorlds / arrivalIndexByNode", () => {
it("places each step in its build", () => {
- expect(worldOf(example, "pinion")).toBe("drive");
- expect(worldOf(example, "fit")).toBe("heel");
- expect(worldOf(example, "sole")).toBeNull();
- expect(worldOf(example, "heel")).toBeNull();
+ const worlds = stepWorlds(example);
+ expect(worlds.get("pinion")).toBe("drive");
+ expect(worlds.get("fit")).toBe("heel");
+ expect(worlds.get("sole")).toBeNull();
+ expect(worlds.get("heel")).toBeNull();
+ expect(worlds.get("drive")).toBeNull();
+ expect(worlds.size).toBe(example.length);
});
it("main build: a sub-assembly's parts arrive when its unit joins", () => {
@@ -256,6 +270,10 @@ describe("buildCarryPlans", () => {
expect(plans.fit?.glidingPartIds.sort()).toEqual(
["idler", "pinion", "plate"].sort()
);
+ // The step's own insertion carries the gliding unit with its own part.
+ expect(plans.fit?.ownMovingPartIds.sort()).toEqual(
+ ["battery", "idler", "pinion", "plate"].sort()
+ );
expect(plans.heel?.joinsOnOwnPath).toBe(false);
});
@@ -269,9 +287,7 @@ describe("buildCarryPlans", () => {
}
]);
expect(plans.fit?.glidingPartIds).toEqual([]);
- expect(plans.fit?.carriedPartIds.sort()).toEqual(
- ["idler", "pinion", "plate"].sort()
- );
+ expect(plans.fit?.ownMovingPartIds).toEqual(["battery"]);
// Its header is used, so it is not where the unit joins.
expect(plans.drive?.joinsOnOwnPath).toBe(false);
});
@@ -279,6 +295,7 @@ describe("buildCarryPlans", () => {
it("an unused header with a path joins on it", () => {
const plans = plansFor({ heel: drop });
expect(plans.heel?.joinsOnOwnPath).toBe(true);
+ expect(plans.heel && carriesUnits(plans.heel)).toBe(true);
expect(plans.heel?.pathUnits.map((unit) => unit.headerId)).toEqual([
"heel"
]);
@@ -286,11 +303,58 @@ describe("buildCarryPlans", () => {
});
it("steps that carry nothing in have an empty plan", () => {
- expect(plansFor({ drive: drop }).sole).toEqual({
- carriedPartIds: [],
+ const sole = plansFor({ drive: drop }).sole;
+ expect(sole).toEqual({
pathUnits: [],
glidingPartIds: [],
+ ownMovingPartIds: ["sole"],
joinsOnOwnPath: false
});
+ expect(sole && carriesUnits(sole)).toBe(false);
+ });
+
+ // A chain: Drive Train is used inside Heel Module, and Heel Module is
+ // itself used by the main build's "upper" step.
+ const chain = example.map((row) =>
+ row.id === "heel" ? { ...row, usedInStepId: "upper" } : row
+ );
+ const chainPlansFor = (paths: Record<string, Motion>) => {
+ const rows = chain.map((row) => ({
+ ...row,
+ motion: paths[row.id] ?? ({ type: "none" } as Motion)
+ }));
+ const plans = buildCarryPlans(rows, buildSubAssemblyPlan(rows));
+ return Object.fromEntries(rows.map((row, i) => [row.id, plans[i]]));
+ };
+ const heelParts = ["battery", "idler", "pinion", "plate", "shell"];
+
+ it("chain: both units fly their own path, each at the step that uses it", () => {
+ const plans = chainPlansFor({ drive: drop, heel: drop });
+ expect(plans.fit?.pathUnits.map((unit) => unit.headerId)).toEqual([
+ "drive"
+ ]);
+ expect(plans.fit?.ownMovingPartIds).toEqual(["battery"]);
+ // The outer unit flies with the inner one inside it.
+ expect(plans.upper?.pathUnits.map((unit) => unit.headerId)).toEqual([
+ "heel"
+ ]);
+ expect(plans.upper?.pathUnits[0]?.nodeIds.sort()).toEqual(heelParts);
+ expect(plans.upper?.glidingPartIds).toEqual([]);
+ expect(plans.upper?.ownMovingPartIds).toEqual(["upper"]);
+ // Used headers play nothing of their own.
+ expect(plans.heel?.pathUnits).toEqual([]);
+ expect(plans.drive?.pathUnits).toEqual([]);
+ });
+
+ it("chain: an outer unit with no path glides, inner unit and all", () => {
+ const plans = chainPlansFor({ drive: drop });
+ expect(plans.fit?.pathUnits.map((unit) => unit.headerId)).toEqual([
+ "drive"
+ ]);
+ expect(plans.upper?.pathUnits).toEqual([]);
+ expect(plans.upper?.glidingPartIds.sort()).toEqual(heelParts);
+ expect(plans.upper?.ownMovingPartIds.sort()).toEqual(
+ [...heelParts, "upper"].sort()
+ );
});
});
diff --git a/packages/viewer/src/subassembly.ts b/packages/viewer/src/subassembly.ts
index d3ab82bf5e..0668102d86 100644
--- a/packages/viewer/src/subassembly.ts
+++ b/packages/viewer/src/subassembly.ts
@@ -33,6 +33,8 @@ export type SubAssemblyInfo = {
plays: boolean;
/** Members: every part of their sub-assembly (shown on its own). Otherwise null. */
isolatePartIds: string[] | null;
+ /** Headers: every part of the finished unit. Otherwise null. */
+ unitPartIds: string[] | null;
/** Headers whose finished parts arrive at this step. */
carriesIn: string[];
};
@@ -70,14 +72,21 @@ export function subAssemblyPartIds(
}
/**
- * The build a step happens in: its sub-assembly's header id, or `null` for the
- * main build. Headers themselves are main-build steps (an unused one is where
- * its unit joins the main build).
+ * The build each step happens in, keyed by step id: its sub-assembly's header
+ * id, or `null` for the main build. Headers themselves are main-build steps
+ * (an unused one is where its unit joins the main build).
*/
-export function worldOf(steps: StructureStep[], stepId: string): string | null {
- const step = steps.find((s) => s.id === stepId);
- if (!step?.parentStepId || isSubAssemblyHeader(step)) return null;
- const header = steps.find((s) => s.id === step.parentStepId);
+export function stepWorlds(steps: StructureStep[]): Map<string, string | null> {
+ const byId = new Map(steps.map((step) => [step.id, step]));
+ return new Map(steps.map((step) => [step.id, worldIn(byId, step)]));
+}
+
+function worldIn(
+ byId: ReadonlyMap<string, StructureStep>,
+ step: StructureStep
+): string | null {
+ if (!step.parentStepId || isSubAssemblyHeader(step)) return null;
+ const header = byId.get(step.parentStepId);
return header && isSubAssemblyHeader(header) ? header.id : null;
}
@@ -94,9 +103,7 @@ export function arrivalIndexByNode(
): Map<string, number> {
const indexById = new Map(steps.map((step, index) => [step.id, index]));
const byId = new Map(steps.map((step) => [step.id, step]));
- const worlds = new Map(
- steps.map((step) => [step.id, worldOf(steps, step.id)])
- );
+ const worlds = stepWorlds(steps);
const arrival = new Map<string, number>();
steps.forEach((installer) => {
@@ -193,6 +200,7 @@ export function buildSubAssemblyPlan(
number: depth === 0 ? String(top) : `${top}.${child}`,
plays: !(isHeader && step.usedInStepId),
isolatePartIds: depth === 1 && headerId ? partsOf(headerId) : null,
+ unitPartIds: isHeader ? partsOf(step.id) : null,
carriesIn
});
}
@@ -202,24 +210,33 @@ export function buildSubAssemblyPlan(
/** A finished sub-assembly that joins on a path of its own (its header's motion). */
export type PathUnit = { headerId: string; nodeIds: string[]; motion: Motion };
-/** How the finished sub-assemblies a step carries in arrive. */
+/**
+ * How a step's parts move. The finished sub-assemblies it carries in either
+ * fly their own path (`pathUnits`) or glide in beside the build; everything
+ * else rides the step's own insertion.
+ */
export type CarryPlan = {
- carriedPartIds: string[];
- /** The ones with a path of their own, in sub-assembly order: they fly in first. */
+ /** The units with a path of their own, in sub-assembly order: they fly in first. */
pathUnits: PathUnit[];
/** Carried parts with no path of their own: they glide in beside the build. */
glidingPartIds: string[];
+ /** What the step's own insertion moves: its own parts plus the gliding units. */
+ ownMovingPartIds: string[];
/**
- * The step is an unused header whose unit joins on its own path. That path
- * IS the header's motion, so the header has no insertion of its own.
+ * An unused header whose unit joins the main build on its own path: that
+ * path IS the header's motion, so the header has no insertion of its own.
*/
joinsOnOwnPath: boolean;
};
+export function carriesUnits(plan: CarryPlan): boolean {
+ return plan.pathUnits.length > 0 || plan.glidingPartIds.length > 0;
+}
+
/**
- * Per step (same order as `steps`): which finished sub-assemblies arrive and
- * how. A header whose `motion` is not `none` has a path of its own; the rest
- * keep the glide from beside the build.
+ * Per step (same order as `steps`), from the plan `buildSubAssemblyPlan`
+ * made for the same steps. A header whose `motion` is not `none` has a path
+ * of its own; the rest keep the glide from beside the build.
*/
export function buildCarryPlans(
steps: (StructureStep & Pick<AssemblyStep, "motion">)[],
@@ -227,24 +244,25 @@ export function buildCarryPlans(
): CarryPlan[] {
const byId = new Map(steps.map((step) => [step.id, step]));
return steps.map((step) => {
- const headers = subPlan.get(step.id)?.carriesIn ?? [];
- const carried = new Set<string>();
- const onPath = new Set<string>();
const pathUnits: PathUnit[] = [];
- for (const headerId of headers) {
- const nodeIds = subAssemblyPartIds(steps, headerId);
- for (const id of nodeIds) carried.add(id);
+ const gliding = new Set<string>();
+ for (const headerId of subPlan.get(step.id)?.carriesIn ?? []) {
+ const nodeIds = subPlan.get(headerId)?.unitPartIds ?? [];
const header = byId.get(headerId);
if (header && header.motion.type !== "none") {
pathUnits.push({ headerId, nodeIds, motion: header.motion });
- for (const id of nodeIds) onPath.add(id);
+ } else {
+ for (const id of nodeIds) gliding.add(id);
}
}
- const carriedPartIds = [...carried];
+ const onPath = new Set(pathUnits.flatMap((unit) => unit.nodeIds));
+ for (const id of onPath) gliding.delete(id);
+ const own = new Set([...step.componentNodeIds, ...gliding]);
+ for (const id of onPath) own.delete(id);
return {
- carriedPartIds,
pathUnits,
- glidingPartIds: carriedPartIds.filter((id) => !onPath.has(id)),
+ glidingPartIds: [...gliding],
+ ownMovingPartIds: [...own],
joinsOnOwnPath: pathUnits.some((unit) => unit.headerId === step.id)
};
});
diff --git a/packages/viewer/src/test-utils.ts b/packages/viewer/src/test-utils.ts
new file mode 100644
index 0000000000..ecb25af9ee
--- /dev/null
+++ b/packages/viewer/src/test-utils.ts
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { expect } from "vitest";
+import type { MotionKeyframes, Pose } from "./keyframes";
+import type { AssemblyStep, Motion } from "./types";
+
+export const IDENTITY_POSE: Pose = {
+ position: [0, 0, 0],
+ quaternion: [0, 0, 0, 1]
+};
+
+export function positionAt(
+ keyframes: MotionKeyframes,
+ index: number
+): number[] {
+ return keyframes.positions.slice(index * 3, index * 3 + 3);
+}
+
+export function quaternionAt(
+ keyframes: MotionKeyframes,
+ index: number
+): number[] {
+ return keyframes.quaternions.slice(index * 4, index * 4 + 4);
+}
+
+export function lastIndex(keyframes: MotionKeyframes): number {
+ return keyframes.times.length - 1;
+}
+
+export function expectVectorClose(actual: number[], expected: number[]) {
+ expect(actual.length).toBe(expected.length);
+ actual.forEach((value, index) => {
+ expect(value).toBeCloseTo(expected[index] ?? Number.NaN, 6);
+ });
+}
+
+export function expectMonotonicTimes(keyframes: MotionKeyframes) {
+ expect(keyframes.times[0]).toBe(0);
+ for (let i = 1; i < keyframes.times.length; i++) {
+ expect(keyframes.times[i]).toBeGreaterThan(
+ keyframes.times[i - 1] ?? Number.POSITIVE_INFINITY
+ );
+ }
+}
+
+export function makeStep(
+ motion: Motion,
+ componentNodeIds: string[]
+): AssemblyStep {
+ return {
+ id: "step-1",
+ title: null,
+ instructionText: null,
+ componentNodeIds,
+ motion,
+ camera: null,
+ fastener: null
+ };
+}
diff --git a/packages/viewer/src/timing.test.ts b/packages/viewer/src/timing.test.ts
new file mode 100644
index 0000000000..3da5dcd4b6
--- /dev/null
+++ b/packages/viewer/src/timing.test.ts
@@ -0,0 +1,192 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { describe, expect, it } from "vitest";
+import {
+ fadeProgress,
+ motionDuration,
+ motionTravelDistance,
+ stepClipTiming
+} from "./timing";
+import type { Motion } from "./types";
+
+describe("motionTravelDistance", () => {
+ it("computes travel for each motion type", () => {
+ expect(
+ motionTravelDistance({
+ type: "linear",
+ direction: [0, 0, -1],
+ distance: 80
+ })
+ ).toBe(80);
+ expect(
+ motionTravelDistance({
+ type: "L",
+ segments: [
+ { direction: [1, 0, 0], distance: 60 },
+ { direction: [0, 0, -1], distance: 20 }
+ ]
+ })
+ ).toBe(80);
+ expect(
+ motionTravelDistance({
+ type: "helix",
+ axis: [0, 0, -1],
+ origin: [0, 0, 0],
+ pitch: 0.8,
+ turns: 6,
+ approach: 30
+ })
+ ).toBeCloseTo(34.8);
+ expect(motionTravelDistance({ type: "none" })).toBe(0);
+ });
+});
+
+describe("motionDuration", () => {
+ it("scales with travel distance and clamps to 1-4 s", () => {
+ expect(
+ motionDuration({ type: "linear", direction: [0, 0, 1], distance: 6 })
+ ).toBe(1);
+ expect(
+ motionDuration({ type: "linear", direction: [0, 0, 1], distance: 120 })
+ ).toBeCloseTo(2);
+ expect(
+ motionDuration({ type: "linear", direction: [0, 0, 1], distance: 6000 })
+ ).toBe(4);
+ expect(motionDuration({ type: "none" })).toBe(0);
+ });
+});
+
+describe("stepClipTiming", () => {
+ const linear: Motion = { type: "linear", direction: [0, 0, 1], distance: 60 };
+ const seconds = motionDuration(linear);
+
+ it("plays the natural animation when no duration is authored", () => {
+ expect(stepClipTiming({ motion: linear })).toEqual({
+ total: seconds + 0.6,
+ units: [],
+ unitsTotal: 0,
+ glide: 0,
+ motion: seconds,
+ hold: 0.6
+ });
+ });
+
+ it("adds a carry-in glide before the insertion", () => {
+ const timing = stepClipTiming({ motion: linear }, { glideSeconds: 1.2 });
+ expect(timing.total).toBeCloseTo(1.2 + seconds + 0.6);
+ expect(timing.glide).toBe(1.2);
+ });
+
+ it("gives a process-only step a fixed slot plus any glide", () => {
+ expect(stepClipTiming({ motion: { type: "none" } }).total).toBe(2);
+ expect(
+ stepClipTiming({ motion: { type: "none" } }, { glideSeconds: 1.2 }).total
+ ).toBe(3.2);
+ });
+
+ it("gives a step that only brings a unit in its units and the hold", () => {
+ const unit: Motion = {
+ type: "linear",
+ direction: [0, 0, -1],
+ distance: 60
+ };
+ // An unused header joining on its own path: nothing of its own moves or fades.
+ const header = stepClipTiming(
+ { motion: { type: "none" } },
+ { units: [unit], ownParts: false }
+ );
+ expect(header.total).toBeCloseTo(motionDuration(unit) + 0.6);
+ expect(header.hold).toBeCloseTo(0.6);
+ // A stored motion with nothing of its own to move adds no time.
+ expect(
+ stepClipTiming({ motion: linear }, { units: [unit], ownParts: false })
+ .total
+ ).toBeCloseTo(motionDuration(unit) + 0.6);
+ // Own parts that fade in after the unit keep the fixed slot.
+ expect(
+ stepClipTiming({ motion: { type: "none" } }, { units: [unit] }).total
+ ).toBeCloseTo(motionDuration(unit) + 2);
+ // Nothing to bring in and nothing to move: a process-only step.
+ expect(
+ stepClipTiming({ motion: { type: "none" } }, { ownParts: false }).total
+ ).toBe(2);
+ });
+
+ it("speeds glide, insertion and hold up to fit a shorter authored duration", () => {
+ const natural = 1.2 + seconds + 0.6;
+ const timing = stepClipTiming(
+ { motion: linear, durationSeconds: natural / 2 },
+ { glideSeconds: 1.2 }
+ );
+ expect(timing.total).toBe(natural / 2);
+ expect(timing.glide + timing.motion + timing.hold).toBeCloseTo(natural / 2);
+ expect(timing.glide).toBeCloseTo(0.6);
+ });
+
+ it("keeps the natural animation inside a longer authored duration", () => {
+ const timing = stepClipTiming({ motion: linear, durationSeconds: 30 });
+ expect(timing.total).toBe(30);
+ expect(timing.motion).toBe(seconds);
+ });
+
+ it("times each unit by its own path and scales it with an authored duration", () => {
+ // 120 mm at 60 mm/s: a 2 s path.
+ const unit: Motion = {
+ type: "linear",
+ direction: [0, 0, -1],
+ distance: 120
+ };
+ const drop: Motion = {
+ type: "linear",
+ direction: [0, 0, -1],
+ distance: 10
+ };
+ const natural = stepClipTiming({ motion: drop }, { units: [unit] });
+ expect(natural.units).toEqual([2]);
+ expect(natural.unitsTotal).toBe(2);
+ const fitted = stepClipTiming(
+ { motion: drop, durationSeconds: natural.total / 2 },
+ { units: [unit] }
+ );
+ expect(fitted.units[0]).toBeCloseTo(1);
+ expect(fitted.unitsTotal).toBeCloseTo(1);
+ expect(fitted.total).toBeCloseTo(natural.total / 2);
+ });
+});
+
+describe("fadeProgress", () => {
+ it("waits for the units, then fades in over its own time", () => {
+ expect(fadeProgress(0.5, 2, 1.2, false)).toBe(0);
+ expect(fadeProgress(2, 2, 1.2, false)).toBe(0);
+ expect(fadeProgress(2.6, 2, 1.2, false)).toBeCloseTo(0.5);
+ expect(fadeProgress(5, 2, 1.2, false)).toBe(1);
+ });
+
+ it("is fully in once the step has finished, whatever the clock says", () => {
+ expect(fadeProgress(0, 2, 1.2, true)).toBe(1);
+ });
+
+ it("starts at once with no units", () => {
+ expect(fadeProgress(0.6, 0, 1.2, false)).toBeCloseTo(0.5);
+ });
+});
+
+describe("waypoints motion timing", () => {
+ const halfTurnZ: [number, number, number, number] = [0, 0, 1, 0];
+
+ it("gives a turn in place readable time", () => {
+ const halfTurnInPlace: Motion = {
+ type: "waypoints",
+ waypoints: [
+ { offset: [0, 0, 0], rotation: halfTurnZ },
+ { offset: [0, 0, 0], rotation: [0, 0, 0, 1] }
+ ]
+ };
+ // 30 mm of travel per radian turned, played at 60 mm/s: π/2 s, above the
+ // 1 s floor a turn counted as no travel would get.
+ expect(motionTravelDistance(halfTurnInPlace)).toBeCloseTo(Math.PI * 30);
+ expect(motionDuration(halfTurnInPlace)).toBeCloseTo(Math.PI / 2);
+ });
+});
diff --git a/packages/viewer/src/timing.ts b/packages/viewer/src/timing.ts
new file mode 100644
index 0000000000..dbe4ee060a
--- /dev/null
+++ b/packages/viewer/src/timing.ts
@@ -0,0 +1,144 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { toQuaternion, toVector3 } from "./quat";
+import type { AssemblyStep, Motion, WaypointsMotion } from "./types";
+
+export const CARRY_IN_GLIDE_SECONDS = 1.2;
+export const DEFAULT_HOLD_SECONDS = 0.6;
+
+const INSERTION_SPEED_MM_PER_S = 60;
+const MIN_DURATION_S = 1;
+const MAX_DURATION_S = 4;
+/** Timeline length of a process-only (none-motion) step without an explicit duration */
+const NONE_STEP_SECONDS = 2;
+/** Turning counts as travel so a flip in place still takes readable time. */
+const TURN_MM_PER_RADIAN = 30;
+
+export type StepClipTiming = {
+ total: number;
+ /** Each unit's own path, in play order. */
+ units: number[];
+ unitsTotal: number;
+ glide: number;
+ motion: number;
+ hold: number;
+};
+
+/**
+ * How a step spends its slot on the continuous timeline (`total`): the
+ * sub-assemblies that join on their own path (`units`, one after another), a
+ * carried-in sub-assembly's glide, the insertion, then the seated hold. The
+ * slot is the explicit `durationSeconds` when set, otherwise the natural length
+ * (a fixed slot for process-only steps). An authored duration shorter than the
+ * animation speeds everything up to fit, so the step never ends mid-travel and
+ * snaps its parts to their seat.
+ *
+ * `ownParts: false` — the step's own insertion moves nothing (an unused header
+ * whose unit joins on its own path, or a step that only brings a unit in): its
+ * motion is ignored, and with units its slot is just the units and the hold.
+ */
+export function stepClipTiming(
+ step: Pick<AssemblyStep, "motion" | "durationSeconds">,
+ {
+ glideSeconds = 0,
+ units = [],
+ ownParts = true
+ }: { glideSeconds?: number; units?: Motion[]; ownParts?: boolean } = {}
+): StepClipTiming {
+ const unitSeconds = units.map(motionDuration);
+ const naturalUnits = unitSeconds.reduce((sum, seconds) => sum + seconds, 0);
+ const moves = ownParts && step.motion.type !== "none";
+ const motion = moves ? motionDuration(step.motion) : 0;
+ const natural = naturalUnits + glideSeconds + motion + DEFAULT_HOLD_SECONDS;
+ const total =
+ step.durationSeconds && step.durationSeconds > 0
+ ? step.durationSeconds
+ : moves || (!ownParts && units.length > 0)
+ ? natural
+ : naturalUnits + glideSeconds + NONE_STEP_SECONDS;
+ const fit = Math.min(1, total / natural);
+ return {
+ total,
+ units: unitSeconds.map((seconds) => seconds * fit),
+ unitsTotal: naturalUnits * fit,
+ glide: glideSeconds * fit,
+ motion: motion * fit,
+ hold: DEFAULT_HOLD_SECONDS * fit
+ };
+}
+
+/**
+ * Opacity of a seated fade-in at `elapsed` seconds into the step: 0 until
+ * `delay` (the step's units on their own path are still arriving), then up to
+ * 1 over `seconds`. A finished step — including one shown statically, at its
+ * end — is fully in.
+ */
+export function fadeProgress(
+ elapsed: number,
+ delay: number,
+ seconds: number,
+ finished: boolean
+): number {
+ if (finished) return 1;
+ return Math.min(Math.max((elapsed - delay) / seconds, 0), 1);
+}
+
+/** Total travel distance (mm) implied by a motion. */
+export function motionTravelDistance(motion: Motion): number {
+ switch (motion.type) {
+ case "linear":
+ return Math.abs(motion.distance);
+ case "L":
+ return motion.segments.reduce(
+ (sum, segment) => sum + Math.abs(segment.distance),
+ 0
+ );
+ case "helix":
+ return Math.abs(motion.approach) + Math.abs(motion.pitch * motion.turns);
+ case "path": {
+ let total = 0;
+ for (let i = 1; i < motion.keyframes.length; i++) {
+ const current = motion.keyframes[i];
+ const previous = motion.keyframes[i - 1];
+ if (!current || !previous) continue;
+ total += toVector3(current.position).distanceTo(
+ toVector3(previous.position)
+ );
+ }
+ return total;
+ }
+ case "waypoints": {
+ let total = 0;
+ for (let i = 1; i < motion.waypoints.length; i++) {
+ const current = motion.waypoints[i];
+ const previous = motion.waypoints[i - 1];
+ if (!current || !previous) continue;
+ total += waypointLegTravel(previous, current);
+ }
+ return total;
+ }
+ case "none":
+ return 0;
+ }
+}
+
+export function waypointLegTravel(
+ from: WaypointsMotion["waypoints"][number],
+ to: WaypointsMotion["waypoints"][number]
+): number {
+ const distance = toVector3(from.offset).distanceTo(toVector3(to.offset));
+ const angle = toQuaternion(from.rotation).angleTo(toQuaternion(to.rotation));
+ return distance + angle * TURN_MM_PER_RADIAN;
+}
+
+/** Animation duration (s) scaled to travel distance, clamped to 1–4 s. */
+export function motionDuration(motion: Motion): number {
+ if (motion.type === "none") return 0;
+ const travel = motionTravelDistance(motion);
+ return Math.min(
+ MAX_DURATION_S,
+ Math.max(MIN_DURATION_S, travel / INSERTION_SPEED_MM_PER_S)
+ );
+}
diff --git a/packages/viewer/src/types.ts b/packages/viewer/src/types.ts
index 7c4a630c37..f9a166b91e 100644
--- a/packages/viewer/src/types.ts
+++ b/packages/viewer/src/types.ts
@@ -147,6 +147,12 @@ export type AssemblyStep = {
* `null`/absent = it joins the main build at the header itself.
*/
usedInStepId?: string | null;
+ /**
+ * The build's orientation from this step on (see `orientation.ts`): a unit
+ * quaternion turning the model frame into the bench frame. `null`/absent =
+ * the same as the previous step in this build.
+ */
+ orientation?: Quat | null;
};
/** One node of the assembly tree in graph.json. */
diff --git a/packages/viewer/src/useBuildFrame.ts b/packages/viewer/src/useBuildFrame.ts
new file mode 100644
index 0000000000..3c3a4e5759
--- /dev/null
+++ b/packages/viewer/src/useBuildFrame.ts
@@ -0,0 +1,210 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { useFrame } from "@react-three/fiber";
+import { useCallback, useEffect, useMemo, useRef } from "react";
+import { type Camera, Quaternion, Vector3 } from "three";
+import type { OrbitControls as OrbitControlsImpl } from "three-stdlib";
+import { easeInOutCubic } from "./keyframes";
+import { upForOrientation } from "./orientation";
+import { sameOrientation, toQuat, toQuaternion } from "./quat";
+import type { Quat } from "./types";
+
+const TURN_MS = 900;
+
+const IDENTITY = new Quaternion();
+// Reused every frame so the turn allocates nothing.
+const SCRATCH_DELTA = new Quaternion();
+const SCRATCH_STEP = new Quaternion();
+
+export type BuildFrame = {
+ /** A turn to a new orientation is playing: playback and framing wait for it. */
+ isTurning: () => boolean;
+ /** A model-frame point as seen on the bench (where the viewer stands), in place. */
+ toBench: (point: Vector3) => Vector3;
+ /** A bench-frame point in the model frame of a build turned by `orientation`, in place. */
+ fromBench: (point: Vector3, orientation: Quat) => Vector3;
+ /**
+ * The camera's current bench direction (target → eye, unit), in the model
+ * frame of `orientation`: where it looks from once a turn to it lands.
+ * Null before the controls exist.
+ */
+ keptDirection: (orientation: Quat) => Vector3 | null;
+};
+
+/**
+ * The build's orientation as a CAMERA FRAME, never a turned model (motion, the
+ * path editor and box select all work in world space). A new orientation turns
+ * the camera, its target and up about the build's center by `next⁻¹ · applied`
+ * — the center, not the camera target, so an off-center build turns in place
+ * instead of swinging round in an arc.
+ *
+ * Call it before any other `useFrame` that moves the camera: the turn step must
+ * run first, and the others check `isTurning()`.
+ */
+export function useBuildFrame({
+ camera,
+ controls,
+ orientation,
+ center
+}: {
+ camera: Camera;
+ controls: OrbitControlsImpl | null;
+ orientation: Quat;
+ /** The center of the bounds the build is framed on — what it turns about. */
+ center: Vector3;
+}): BuildFrame {
+ const frameRef = useRef<{
+ applied: Quaternion;
+ from: Quaternion;
+ to: Quaternion;
+ start: number;
+ } | null>(null);
+ const pivotRef = useRef(new Vector3());
+ // The up `applied` implies, recomputed only when `applied` changes.
+ const upRef = useRef({ applied: new Quaternion(), up: new Vector3(0, 0, 1) });
+
+ // Moves the frame from `applied` to `next`, keeping the camera fixed in the
+ // bench frame.
+ const applyFrame = useCallback(
+ (next: Quaternion) => {
+ const frame = frameRef.current;
+ if (!frame || !controls) return;
+ const delta = SCRATCH_DELTA.copy(next).invert().multiply(frame.applied);
+ turnAbout(camera.position, delta, pivotRef.current);
+ turnAbout(controls.target, delta, pivotRef.current);
+ camera.up.applyQuaternion(delta).normalize();
+ frame.applied.copy(next);
+ controls.update();
+ },
+ [camera, controls]
+ );
+
+ useEffect(() => {
+ if (!controls) return;
+ const next = toQuaternion(orientation);
+ const frame = frameRef.current;
+ if (!frame) {
+ // First frame: start already turned, no animation.
+ camera.up.set(0, 0, 1);
+ pivotRef.current.copy(center);
+ frameRef.current = {
+ applied: new Quaternion(),
+ from: next.clone(),
+ to: next.clone(),
+ start: 0
+ };
+ applyFrame(next);
+ return;
+ }
+ if (!center.equals(pivotRef.current)) {
+ // Entering or leaving a sub-assembly moves the center: a turn would
+ // swing about the other build's center, so the new frame lands at once.
+ pivotRef.current.copy(center);
+ applyFrame(next);
+ frame.from.copy(next);
+ frame.to.copy(next);
+ return;
+ }
+ if (sameOrientation(toQuat(frame.to), orientation)) return;
+ frame.from.copy(frame.applied);
+ frame.to.copy(next);
+ frame.start = performance.now();
+ }, [orientation, center, controls, camera, applyFrame]);
+
+ // The camera outlives a remounted scene (`key={scene.uuid}`): hand it back
+ // upright, so the next mount starts from the model frame.
+ useEffect(
+ () => () => {
+ if (!frameRef.current) return;
+ applyFrame(IDENTITY);
+ frameRef.current = null;
+ },
+ [applyFrame]
+ );
+
+ // Grabbing the view mid-turn finishes the turn at once.
+ useEffect(() => {
+ if (!controls) return;
+ const finishTurn = () => {
+ const frame = frameRef.current;
+ if (frame && !frame.applied.equals(frame.to)) applyFrame(frame.to);
+ };
+ controls.addEventListener("start", finishTurn);
+ return () => controls.removeEventListener("start", finishTurn);
+ }, [controls, applyFrame]);
+
+ useFrame(() => {
+ const frame = frameRef.current;
+ if (!frame || !controls) return;
+ if (!frame.applied.equals(frame.to)) {
+ const t = Math.min((performance.now() - frame.start) / TURN_MS, 1);
+ applyFrame(
+ t < 1
+ ? SCRATCH_STEP.slerpQuaternions(
+ frame.from,
+ frame.to,
+ easeInOutCubic(t)
+ )
+ : frame.to
+ );
+ return;
+ }
+ // drei's GizmoHelper writes `camera.up` on every frame of a viewcube
+ // tween and resets it when the tween ends: keep the build turned.
+ const cached = upRef.current;
+ if (!cached.applied.equals(frame.applied)) {
+ cached.up.fromArray(upForOrientation(toQuat(frame.applied)));
+ cached.applied.copy(frame.applied);
+ }
+ if (camera.up.distanceToSquared(cached.up) > 1e-6) {
+ camera.up.copy(cached.up);
+ controls.update();
+ }
+ });
+
+ const isTurning = useCallback(() => {
+ const frame = frameRef.current;
+ return frame !== null && !frame.applied.equals(frame.to);
+ }, []);
+ const toBench = useCallback(
+ (point: Vector3) =>
+ turnAbout(point, frameRef.current?.applied ?? IDENTITY, pivotRef.current),
+ []
+ );
+ const fromBench = useCallback(
+ (point: Vector3, target: Quat) =>
+ turnAbout(point, toQuaternion(target).invert(), pivotRef.current),
+ []
+ );
+ const keptDirection = useCallback(
+ (target: Quat) => {
+ if (!controls) return null;
+ return camera.position
+ .clone()
+ .sub(controls.target)
+ .applyQuaternion(
+ toQuaternion(target)
+ .invert()
+ .multiply(frameRef.current?.applied ?? IDENTITY)
+ )
+ .normalize();
+ },
+ [camera, controls]
+ );
+
+ return useMemo(
+ () => ({ isTurning, toBench, fromBench, keptDirection }),
+ [isTurning, toBench, fromBench, keptDirection]
+ );
+}
+
+/** Mutates `point`. */
+function turnAbout(
+ point: Vector3,
+ rotation: Quaternion,
+ pivot: Vector3
+): Vector3 {
+ return point.sub(pivot).applyQuaternion(rotation).add(pivot);
+}
diff --git a/packages/viewer/src/validate-motion.test.ts b/packages/viewer/src/validate-motion.test.ts
new file mode 100644
index 0000000000..f180996ebf
--- /dev/null
+++ b/packages/viewer/src/validate-motion.test.ts
@@ -0,0 +1,151 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { describe, expect, it } from "vitest";
+import { motionToKeyframes } from "./keyframes";
+import { IDENTITY_POSE } from "./test-utils";
+import type { Motion } from "./types";
+import { isPlayableMotion } from "./validate-motion";
+
+describe("isPlayableMotion", () => {
+ it("accepts the motion types the player animates", () => {
+ expect(isPlayableMotion({ type: "none" })).toBe(true);
+ expect(
+ isPlayableMotion({ type: "linear", direction: [0, 0, 1], distance: 5 })
+ ).toBe(true);
+ expect(
+ isPlayableMotion({
+ type: "waypoints",
+ waypoints: [
+ { offset: [0, 0, 5], rotation: [0, 0, 0, 1] },
+ { offset: [0, 0, 0], rotation: [0, 0, 0, 1] }
+ ]
+ })
+ ).toBe(true);
+ });
+
+ it("rejects what would throw or is unknown", () => {
+ expect(isPlayableMotion(null)).toBe(false);
+ expect(isPlayableMotion({ type: "teleport" })).toBe(false);
+ expect(
+ isPlayableMotion({
+ type: "waypoints",
+ waypoints: [{ offset: [0, 0, 0], rotation: [0, 0, 0, 1] }]
+ })
+ ).toBe(false);
+ expect(isPlayableMotion({ type: "path", keyframes: [] })).toBe(false);
+ });
+
+ const key = (t: number) => ({
+ t,
+ position: [0, 0, 0],
+ quaternion: [0, 0, 0, 1]
+ });
+
+ it("rejects fields keyframe generation would turn into NaN", () => {
+ expect(isPlayableMotion({ type: "linear", direction: [0, 0, 1] })).toBe(
+ false
+ );
+ expect(
+ isPlayableMotion({ type: "linear", direction: [0, 1], distance: 5 })
+ ).toBe(false);
+ expect(
+ isPlayableMotion({
+ type: "linear",
+ direction: [0, 0, Number.NaN],
+ distance: 5
+ })
+ ).toBe(false);
+ expect(
+ isPlayableMotion({
+ type: "L",
+ segments: [{ direction: [0, 0, 1], distance: "5" }]
+ })
+ ).toBe(false);
+ expect(
+ isPlayableMotion({
+ type: "helix",
+ axis: [0, 0, 1],
+ origin: [0, 0, 0],
+ pitch: 1,
+ turns: 2
+ })
+ ).toBe(false);
+ expect(
+ isPlayableMotion({
+ type: "waypoints",
+ waypoints: [
+ { offset: [0, 0, 5], rotation: [0, 0, 1] },
+ { offset: [0, 0, 0], rotation: [0, 0, 0, 1] }
+ ]
+ })
+ ).toBe(false);
+ expect(
+ isPlayableMotion({
+ type: "waypoints",
+ waypoints: [{ offset: [0, 0, 5] }, { offset: [0, 0, 0] }]
+ })
+ ).toBe(false);
+ });
+
+ it("rejects path keyframes that don't run 0 → 1 in order", () => {
+ expect(
+ isPlayableMotion({ type: "path", keyframes: [key(0), key(0.5)] })
+ ).toBe(false);
+ expect(
+ isPlayableMotion({ type: "path", keyframes: [key(0.1), key(1)] })
+ ).toBe(false);
+ expect(
+ isPlayableMotion({
+ type: "path",
+ keyframes: [key(0), key(0.6), key(0.4), key(1)]
+ })
+ ).toBe(false);
+ expect(
+ isPlayableMotion({
+ type: "path",
+ keyframes: [
+ key(0),
+ { t: 1, position: [0, 0], quaternion: [0, 0, 0, 1] }
+ ]
+ })
+ ).toBe(false);
+ });
+
+ it("everything it accepts turns into keyframes", () => {
+ const accepted: Motion[] = [
+ { type: "linear", direction: [0, 0, 1], distance: 5 },
+ { type: "L", segments: [] },
+ {
+ type: "helix",
+ axis: [0, 0, 1],
+ origin: [0, 0, 0],
+ pitch: 1,
+ turns: 2,
+ approach: 3
+ },
+ {
+ type: "path",
+ keyframes: [
+ { t: 0, position: [0, 0, 5], quaternion: [0, 0, 0, 1] },
+ { t: 1, position: [0, 0, 0], quaternion: [0, 0, 0, 1] }
+ ]
+ },
+ {
+ type: "waypoints",
+ waypoints: [
+ { offset: [0, 0, 5], rotation: [0, 0, 0, 0] },
+ { offset: [0, 0, 0], rotation: [0, 0, 0, 1] }
+ ]
+ }
+ ];
+ for (const motion of accepted) {
+ expect(isPlayableMotion(motion)).toBe(true);
+ const keyframes = motionToKeyframes(motion, IDENTITY_POSE);
+ expect(keyframes?.times.every(Number.isFinite)).toBe(true);
+ expect(keyframes?.positions.every(Number.isFinite)).toBe(true);
+ expect(keyframes?.quaternions.every(Number.isFinite)).toBe(true);
+ }
+ });
+});
diff --git a/packages/viewer/src/validate-motion.ts b/packages/viewer/src/validate-motion.ts
new file mode 100644
index 0000000000..38c5011179
--- /dev/null
+++ b/packages/viewer/src/validate-motion.ts
@@ -0,0 +1,79 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type { Motion } from "./types";
+
+const isFiniteNumber = (value: unknown): value is number =>
+ typeof value === "number" && Number.isFinite(value);
+
+export const isFiniteTuple = (value: unknown, length: number): boolean =>
+ Array.isArray(value) &&
+ value.length === length &&
+ value.every(isFiniteNumber);
+
+const isVec3 = (value: unknown) => isFiniteTuple(value, 3);
+const isQuat = (value: unknown) => isFiniteTuple(value, 4);
+
+/**
+ * A stored motion the player can animate without throwing or producing NaN.
+ * It cannot check that a `path` motion's last keyframe equals the part's seated
+ * pose, which only the scene knows.
+ */
+export function isPlayableMotion(value: unknown): value is Motion {
+ if (!value || typeof value !== "object") return false;
+ const motion = value as Record<string, unknown>;
+ switch (motion.type) {
+ case "none":
+ return true;
+ case "linear":
+ return isVec3(motion.direction) && isFiniteNumber(motion.distance);
+ case "L":
+ return (
+ Array.isArray(motion.segments) &&
+ motion.segments.every(
+ (segment: { direction?: unknown; distance?: unknown } | null) =>
+ !!segment &&
+ isVec3(segment.direction) &&
+ isFiniteNumber(segment.distance)
+ )
+ );
+ case "helix":
+ return (
+ isVec3(motion.axis) &&
+ isVec3(motion.origin) &&
+ isFiniteNumber(motion.pitch) &&
+ isFiniteNumber(motion.turns) &&
+ isFiniteNumber(motion.approach)
+ );
+ case "path": {
+ const keyframes = motion.keyframes;
+ if (!Array.isArray(keyframes) || keyframes.length < 2) return false;
+ const valid = keyframes.every(
+ (
+ keyframe: { t?: unknown; position?: unknown; quaternion?: unknown },
+ index
+ ) =>
+ !!keyframe &&
+ isFiniteNumber(keyframe.t) &&
+ isVec3(keyframe.position) &&
+ isQuat(keyframe.quaternion) &&
+ (index === 0 || keyframe.t > keyframes[index - 1].t)
+ );
+ return (
+ valid && keyframes[0].t === 0 && keyframes[keyframes.length - 1].t === 1
+ );
+ }
+ case "waypoints":
+ return (
+ Array.isArray(motion.waypoints) &&
+ motion.waypoints.length >= 2 &&
+ motion.waypoints.every(
+ (waypoint: { offset?: unknown; rotation?: unknown } | null) =>
+ !!waypoint && isVec3(waypoint.offset) && isQuat(waypoint.rotation)
+ )
+ );
+ default:
+ return false;
+ }
+}