Skip to main content

brep_render/engine_state/
component_move.rs

1use crate::geometry3d::{add3, cross3 as cross, sub3};
2use super::transform_gizmo::{
3    euler_xyz_deg_from_quat, normalize3, quat_from_axis_angle, quat_from_euler_xyz_deg, quat_mul,
4    parse_drag_delta, Quat, TransformDelta,
5};
6use super::*;
7
8// Component movement uses the shared gizmo at the member-bbox center. Fixed
9// components cannot arm it. A drag is solved LIVE: every drag frame asks the
10// kernel's dry-run drag solve (`assembly_drag_solve_impl`) where the mates put
11// the dragged members, and poses the member displays there display-only (the
12// document is untouched until release). A frame whose solve fails holds the
13// last good pose; a solve slower than the frame budget skips the next frames
14// in proportion, so a large assembly still follows the pointer. Release runs
15// one full solve at the final pointer pose and writes the solved poses of
16// every moved component in one batch (one undo step); the rerun then finds
17// them already solved.
18// Arming a component resets feature-transform and dimension gizmos because they
19// share one widget slot. All translation and rotation handles are shown together.
20// A GROUP (several components moved together) is one rigid body: one gizmo at
21// the union member-bbox center on world axes, the same delta composed onto
22// every member about that shared pivot, and one batched commit (one undo step).
23
24/// The component-Move controller state (one per engine, like [`TransformArm`]).
25pub struct ComponentMoveArm {
26    /// The ACOMP feature id the gizmo is armed for (`None` = disarmed) — the
27    /// FIRST member of a group.
28    pub(super) feature_id: Option<String>,
29    /// Every component the gizmo moves, `feature_id` first. One entry for the
30    /// single-component Move; two or more for a group move.
31    pub(super) group: Vec<String>,
32    /// Members that are FIXED and armed by "Unfix and Move": they stay fixed
33    /// until a drag commits, and the release writes `isFixed: false` in the
34    /// same batch as the new pose (one undo step). Disarming without a drag
35    /// changes nothing.
36    pub(super) unfix: Vec<String>,
37    /// Move Copy selects its members once the background scene rebuild lands.
38    select_after_run: bool,
39    /// The gizmo pivot — the component's (group's union) member-bbox center, re-synced after
40    /// every applied run so the gizmo follows a re-solved (snapped) component.
41    pub(super) anchor: [f64; 3],
42    /// The in-flight handle drag (grab snapshot + the pending composed pose).
43    pub(super) drag: Option<ComponentMoveDrag>,
44    /// Pre-drag copies of every display the live solve re-posed, keyed by
45    /// solid name — put back before a run's reconcile, on disarm, and when a
46    /// release writes nothing.
47    pub(super) live_originals: std::collections::HashMap<String, crate::scene::SolidDisplay>,
48    /// The pose each live-posed component's displays show now, by component:
49    /// a frame whose solve leaves it there re-poses nothing. (The drag solve
50    /// answers for every component it solved; on l500 three unmoved 100-part
51    /// modules were re-posed and re-uploaded every frame beside the dragged
52    /// one.)
53    pub(super) live_applied: std::collections::HashMap<String, ([f64; 3], [f64; 3])>,
54    /// The per-frame drag solve budget in milliseconds.
55    pub(super) budget_ms: f64,
56    /// Test hook: the cost every drag solve is charged instead of its
57    /// measured wall time (deterministic over-budget behaviour).
58    pub(super) solve_cost_override_ms: Option<f64>,
59    /// What the last typed move did (the panel's status line).
60    pub(super) typed: Option<TypedMove>,
61}
62
63/// The outcome of one typed move ([`EngineState::component_move_typed`]):
64/// the field, the value typed, how much of it the mates let through along
65/// that axis, and the constraints that stopped the rest.
66#[derive(Clone, Debug, PartialEq)]
67pub struct TypedMove {
68    /// `x`, `y`, `z` (mm along the gizmo's axes) or `rx`, `ry`, `rz` (degrees
69    /// about them).
70    pub field: String,
71    pub asked: f64,
72    pub applied: f64,
73    /// Constraint ids that refused the rest of the move (empty when it all
74    /// went through, or when none could be named).
75    pub blocking: Vec<String>,
76    /// Whether anything was written (one undo step).
77    pub written: bool,
78}
79
80impl TypedMove {
81    /// Whether the mates let the whole typed value through.
82    pub fn complete(&self) -> bool {
83        (self.applied - self.asked).abs() <= TYPED_TOLERANCE * self.asked.abs().max(1.0)
84    }
85
86    /// The panel's status line: what moved, of what was asked, and why not all.
87    pub fn summary(&self) -> String {
88        let (axis, unit, space) = typed_axis(&self.field).map(|(axis, rotate)| {
89            (["X", "Y", "Z"][axis], if rotate { "\u{00b0}" } else { " mm" }, if rotate { "about" } else { "along" })
90        }).unwrap_or(("?", "", "along"));
91        let shown = |value: f64| crate::formatting::compact_decimal(value, 4);
92        let limited = if self.blocking.is_empty() {
93            String::new()
94        } else {
95            format!(", limited by {}", self.blocking.join(", "))
96        };
97        if !self.written {
98            return match self.blocking.as_slice() {
99                [] => format!("Not moved {space} {axis}: the mates hold it here."),
100                held => format!("Not moved {space} {axis}: held by {}.", held.join(", ")),
101            };
102        }
103        if self.complete() {
104            return format!("Moved {}{unit} {space} {axis}.", shown(self.applied));
105        }
106        format!("Moved {} of {}{unit} {space} {axis}{limited}.", shown(self.applied), shown(self.asked))
107    }
108}
109
110/// A typed move counts as complete within this fraction of what was typed.
111const TYPED_TOLERANCE: f64 = 1e-6;
112
113/// `x|y|z|rx|ry|rz` → (axis index, is a rotation).
114fn typed_axis(field: &str) -> Option<(usize, bool)> {
115    match field {
116        "x" => Some((0, false)),
117        "y" => Some((1, false)),
118        "z" => Some((2, false)),
119        "rx" => Some((0, true)),
120        "ry" => Some((1, true)),
121        "rz" => Some((2, true)),
122        _ => None,
123    }
124}
125
126/// The per-frame drag solve budget: a solve slower than this skips the next
127/// frames in proportion (the display holds the last good pose meanwhile).
128pub(super) const DRAG_SOLVE_BUDGET_MS: f64 = 30.0;
129/// Never skip more than this many frames after one slow solve.
130const DRAG_SOLVE_MAX_SKIP: u32 = 10;
131
132impl Default for ComponentMoveArm {
133    fn default() -> Self {
134        Self {
135            feature_id: None,
136            group: Vec::new(),
137            unfix: Vec::new(),
138            select_after_run: false,
139            anchor: [0.0; 3],
140            drag: None,
141            live_originals: std::collections::HashMap::new(),
142            live_applied: std::collections::HashMap::new(),
143            budget_ms: DRAG_SOLVE_BUDGET_MS,
144            // The crate's unit tests charge every drag solve nothing, so a loaded machine's wall time never
145            // skips a frame a test then reads (a test of the over-budget path sets its own cost).
146            solve_cost_override_ms: if cfg!(test) { Some(0.0) } else { None },
147            typed: None,
148        }
149    }
150}
151
152/// The live solve's view of one drag: the last good solved poses, whether
153/// the latest frame's solve failed, and the frames still to skip.
154#[derive(Clone, Default, Debug)]
155pub(super) struct LiveSolve {
156    /// Component id → solved `(translate, rotate_deg)` from the last solve
157    /// that held (every component the solve moved, not only the dragged).
158    pub good: Option<std::collections::BTreeMap<String, ([f64; 3], [f64; 3])>>,
159    /// The latest attempted solve failed (the display holds `good`).
160    pub held: bool,
161    /// Frames to skip before the next solve (over-budget back-off).
162    pub skip: u32,
163    /// Solves run and frames skipped this drag (for the verifier).
164    pub solves: u32,
165    pub skipped: u32,
166}
167
168/// A grab snapshot: the handle, the grab screen point, the gizmo frame AT GRAB
169/// (the frozen frame every drag move resolves against — no error
170/// accumulation), every member's pose at grab (pivoting about the shared
171/// anchor), and the PENDING delta + frame the release commits.
172#[derive(Clone)]
173pub(super) struct ComponentMoveDrag {
174    handle: u32,
175    sx: f32,
176    sy: f32,
177    start: ComponentPose,
178    members: Vec<(String, ComponentPose)>,
179    pending: Option<(TransformDelta, ComponentPose)>,
180    live: LiveSolve,
181}
182
183/// A component pose as the gizmo tracks it: the ACOMP `transform` pair plus the
184/// gizmo anchor (bbox center) it pivots about.
185#[derive(Clone, Copy, PartialEq, Debug)]
186pub(super) struct ComponentPose {
187    pub translate: [f64; 3],
188    pub rotate_deg: [f64; 3],
189    pub anchor: [f64; 3],
190}
191
192impl EngineState {
193    /// Whether the component Move gizmo is armed (for any component).
194    pub fn component_move_armed(&self) -> bool {
195        self.component_move.feature_id.is_some()
196    }
197
198    /// The armed component feature id (empty when disarmed).
199    pub fn component_move_armed_feature(&self) -> String {
200        self.component_move.feature_id.clone().unwrap_or_default()
201    }
202
203    /// Every component the armed gizmo moves (empty when disarmed).
204    pub fn component_move_group(&self) -> Vec<String> {
205        self.component_move.group.clone()
206    }
207
208    /// The Move action for SEVERAL components (a multi-selection, or faces of
209    /// several occurrences): one gizmo that moves them together as a rigid
210    /// group. Duplicates count once. FIXED members are left out with one toast
211    /// naming them; the rest still arm. One movable member falls back to the
212    /// single-component [`Self::component_move_toggle`]; pressing Move again on
213    /// the armed group disarms it.
214    pub fn component_move_group_toggle(&mut self, ids: &[String]) {
215        let mut unique: Vec<String> = Vec::new();
216        for id in ids {
217            if !unique.contains(id) {
218                unique.push(id.clone());
219            }
220        }
221        if unique.len() <= 1 {
222            if let Some(id) = unique.first() {
223                self.component_move_toggle(id);
224            }
225            return;
226        }
227        let mut movable = Vec::new();
228        let mut fixed = Vec::new();
229        for id in unique {
230            match self.component_info(&id) {
231                None => self.push_notice(format!("'{id}' is not an assembly component")),
232                Some(info) if info.fixed => fixed.push(format!("{} ({id})", info.part_name)),
233                Some(_) => movable.push(id),
234            }
235        }
236        if !fixed.is_empty() {
237            let verb = if fixed.len() == 1 { "is" } else { "are" };
238            self.push_notice(format!(
239                "{} {verb} fixed — not moved (unfix to move)",
240                fixed.join(", ")
241            ));
242        }
243        match movable.len() {
244            0 => {}
245            1 => self.component_move_toggle(&movable[0]),
246            // The same set, in any order, toggles off.
247            _ if self.component_move.group.len() == movable.len()
248                && movable.iter().all(|id| self.component_move.group.contains(id)) =>
249            {
250                self.disarm_transform()
251            }
252            _ => self.component_move_arm_group(movable),
253        }
254    }
255
256    /// "Unfix and Move": like [`Self::component_move_group_toggle`], but FIXED
257    /// components join the move instead of being skipped. Nothing is unfixed
258    /// until a drag commits; the release then writes each fixed member's
259    /// `isFixed: false` together with its new pose, as one undo step. Pressing
260    /// it again on the same armed set disarms.
261    pub fn component_move_unfix_toggle(&mut self, ids: &[String]) {
262        let mut members: Vec<String> = Vec::new();
263        let mut unfix = Vec::new();
264        for id in ids {
265            if members.contains(id) {
266                continue;
267            }
268            match self.component_info(id) {
269                None => self.push_notice(format!("'{id}' is not an assembly component")),
270                Some(info) => {
271                    if info.fixed {
272                        unfix.push(id.clone());
273                    }
274                    members.push(id.clone());
275                }
276            }
277        }
278        if members.is_empty() {
279            return;
280        }
281        let same = self.component_move.group.len() == members.len()
282            && members.iter().all(|id| self.component_move.group.contains(id))
283            && self.component_move.unfix.len() == unfix.len();
284        if same {
285            self.disarm_transform();
286            return;
287        }
288        self.component_move_arm_group(members);
289        self.component_move.unfix = unfix;
290    }
291
292    /// The Move toggle (context bar / tree action): ARMS the full gizmo (all
293    /// handle sets) for `feature_id`, or DISARMS when it is already armed
294    /// (arming fresh replaces any other armed component). A FIXED component
295    /// refuses with a toast and never arms.
296    pub fn component_move_toggle(&mut self, feature_id: &str) {
297        let Some(info) = self.component_info(feature_id) else {
298            self.push_notice(format!("'{feature_id}' is not an assembly component"));
299            return;
300        };
301        if info.fixed {
302            self.push_notice(format!(
303                "{} ({feature_id}) is fixed — unfix it to move",
304                info.part_name
305            ));
306            return;
307        }
308        // Armed for exactly this component (not as one member of a group).
309        if self.component_move.group == [feature_id] {
310            self.disarm_transform();
311        } else {
312            self.component_move_arm_widget(feature_id);
313        }
314    }
315
316    /// The Move Copy action (context bar / tree action): append a SECOND
317    /// instance of `source_id`'s part — its `inputParams` cloned (same
318    /// `partName`, same pose, any other placement keys riding along) under a
319    /// fresh `ACOMP<n>` id and an explicit `isFixed: false` — then select it
320    /// and arm the full Move gizmo on it, so the user drags the copy off the
321    /// original. No new part is made: both instances reference one
322    /// parts-library entry. A FIXED source copies fine (the copy is free).
323    /// Returns the new feature id.
324    pub fn component_move_copy(&mut self, source_id: &str) -> Result<String, String> {
325        let Some(index) = self.history.index_of(source_id).filter(|&index| {
326            matches!(
327                self.history.feature_type(index).as_deref(),
328                Some("ACOMP") | Some("ASSEMBLY COMPONENT")
329            )
330        }) else {
331            let error = format!("'{source_id}' is not an assembly component");
332            self.push_notice(error.clone());
333            return Err(error);
334        };
335        let mut params = self
336            .history
337            .feature_params(index)
338            .unwrap_or_else(|| serde_json::json!({}));
339        let id = self.history.next_feature_id("ACOMP");
340        let Some(map) = params.as_object_mut() else {
341            return Err(format!("component '{source_id}': malformed inputParams"));
342        };
343        map.insert("id".into(), serde_json::Value::String(id.clone()));
344        map.insert("isFixed".into(), serde_json::Value::Bool(false));
345        let feature = serde_json::json!({
346            "type": "ACOMP",
347            "inputParams": params,
348            "persistentData": {}
349        });
350        self.add_feature(&feature.to_string())?;
351        // Select the copy so the context bar's actions (Move again, Delete, …)
352        // target the instance the gizmo sits on, not the original.
353        self.component_move_arm_widget(&id);
354        if self.run_pending() {
355            self.component_move.select_after_run = true;
356        } else {
357            self.select_component(&id);
358        }
359        Ok(id)
360    }
361
362    /// The `arm_transform` ROUTE for ACOMP features (history-panel expand):
363    /// a FIXED component silently stays armless (the explicit Move action is
364    /// the one that toasts).
365    pub(super) fn component_move_arm(&mut self, feature_id: &str) {
366        match self.component_info(feature_id) {
367            Some(info) if !info.fixed => self.component_move_arm_widget(feature_id),
368            _ => {}
369        }
370    }
371
372    /// Drop the component arm STATE only (the caller owns the widget slot) —
373    /// the exclusivity hook `arm_transform` / `arm_dimension` / `disarm_transform`
374    /// call before taking the slot for themselves.
375    pub(super) fn component_move_reset(&mut self) {
376        self.component_live_restore();
377        let budget_ms = self.component_move.budget_ms;
378        let solve_cost_override_ms = self.component_move.solve_cost_override_ms;
379        self.component_move =
380            ComponentMoveArm { budget_ms, solve_cost_override_ms, ..ComponentMoveArm::default() };
381    }
382
383    /// Arm for `feature_id`: claim the shared widget slot (clearing the
384    /// feature gizmo + dimension overlay), pin the anchor at the member-bbox
385    /// center, and feed the full handle set.
386    fn component_move_arm_widget(&mut self, feature_id: &str) {
387        self.component_move_arm_group(vec![feature_id.to_string()]);
388    }
389
390    /// Arm for every id of `group` (callers pass at least one, none fixed).
391    fn component_move_arm_group(&mut self, group: Vec<String>) {
392        // Claim the shared slot WITHOUT disarm_transform (which would also reset
393        // the component state we are about to set).
394        self.transform_gizmo.feature_id = None;
395        self.transform_gizmo.mode = GizmoMode::None;
396        self.transform_gizmo.drag = None;
397        self.clear_feature_dimension_overlay();
398
399        self.component_live_restore();
400        let anchor = self.component_group_anchor(&group);
401        self.component_move.feature_id = group.first().cloned();
402        self.component_move.group = group;
403        self.component_move.unfix.clear();
404        self.component_move.select_after_run = false;
405        self.component_move.anchor = anchor;
406        self.component_move.drag = None;
407        self.component_move.typed = None;
408        self.feed_component_widget();
409        self.dirty = true;
410    }
411
412    /// The pivot of `group`: the union member-bbox center (a lone component
413    /// without resident members falls back to its translate, as before).
414    fn component_group_anchor(&self, group: &[String]) -> [f64; 3] {
415        let mut bbox = crate::camera::Aabb::empty();
416        for id in group {
417            for solid in self.scene.solids() {
418                if super::components::owned_by(&solid.name, id) {
419                    bbox.union(&solid.bbox);
420                }
421            }
422        }
423        if !bbox.is_empty() {
424            return bbox.center();
425        }
426        group
427            .first()
428            .and_then(|id| self.component_info(id))
429            .map(|info| info.translate)
430            .unwrap_or([0.0; 3])
431    }
432
433    /// The gizmo frame at the armed pose: a single component's own rotated
434    /// basis; a group's WORLD axes (a group has no single orientation).
435    fn component_move_frame(&self) -> Option<ComponentPose> {
436        let anchor = self.component_move.anchor;
437        if self.component_move.group.len() > 1 {
438            return Some(ComponentPose { translate: anchor, rotate_deg: [0.0; 3], anchor });
439        }
440        let info = self.component_info(self.component_move.feature_id.as_deref()?)?;
441        Some(ComponentPose { translate: info.translate, rotate_deg: info.rotate_deg, anchor })
442    }
443
444    /// (Re)feed the widget gizmo at the armed component's current pose+anchor.
445    fn feed_component_widget(&mut self) {
446        let Some(pose) = self.component_move_frame() else {
447            return;
448        };
449        let json = component_frame_json(&pose);
450        let _ = self.widgets.set_transform_json(&json);
451    }
452
453    /// Post-run re-sync (the [`finish_apply`] hook, mirroring
454    /// `sync_transform_gizmo`): re-anchor at the possibly re-solved member bbox
455    /// and re-feed; auto-disarm when the component vanished or became fixed.
456    pub(super) fn component_move_sync(&mut self) {
457        if self.component_move.feature_id.is_none() {
458            return;
459        }
460        // A member that vanished or became fixed drops out; the gizmo
461        // disarms only when nothing movable is left.
462        let unfix = &self.component_move.unfix;
463        let group: Vec<String> = self
464            .component_move
465            .group
466            .iter()
467            .filter(|id| {
468                self.component_info(id)
469                    .is_some_and(|info| !info.fixed || unfix.contains(id))
470            })
471            .cloned()
472            .collect();
473        let Some(id) = group.first().cloned() else {
474            self.disarm_transform();
475            return;
476        };
477        // Earlier replies may arrive while a newer run is pending.
478        // Consume this once, only after the current scene is available.
479        if self.component_move.select_after_run && !self.run_pending() {
480            self.component_move.select_after_run = false;
481            self.select_component(&id);
482        }
483        self.component_move.anchor = self.component_group_anchor(&group);
484        self.component_move.feature_id = Some(id);
485        self.component_move.unfix.retain(|id| group.contains(id));
486        self.component_move.group = group;
487        self.feed_component_widget();
488        self.dirty = true;
489    }
490
491    /// Begin a component-gizmo drag at viewport px `(x, y)`; `true` when a
492    /// handle was grabbed (the viewport routes the drag here, not the camera).
493    pub fn component_press(&mut self, x: f64, y: f64) -> bool {
494        let Some(start) = self.component_move_frame() else {
495            return false;
496        };
497        let handle = self.transform_pick(x, y);
498        if handle == 0 {
499            return false;
500        }
501        let Some(members) = self.component_move_members() else {
502            return false;
503        };
504        // The dry-run solve needs the main-side session (once per applied
505        // run): no grab until its copy has landed from the runner.
506        if self.history_has_assembly() && !self.ensure_assembly_session() {
507            self.push_notice(format!("Move: {}", super::ASSEMBLY_SESSION_PENDING));
508            return false;
509        }
510        self.widgets.set_transform_active(handle);
511        self.component_move.live_applied.clear();
512        self.component_move.drag = Some(ComponentMoveDrag {
513            handle,
514            sx: x as f32,
515            sy: y as f32,
516            start,
517            members,
518            pending: None,
519            live: LiveSolve::default(),
520        });
521        // A drag supersedes the last typed move's status line.
522        self.component_move.typed = None;
523        self.dirty = true;
524        true
525    }
526
527    /// Every armed member at its current pose, pivoting about the shared
528    /// anchor (`None` when a member is gone).
529    fn component_move_members(&self) -> Option<Vec<(String, ComponentPose)>> {
530        self.component_move
531            .group
532            .iter()
533            .map(|id| {
534                let info = self.component_info(id)?;
535                let pose = ComponentPose {
536                    translate: info.translate,
537                    rotate_deg: info.rotate_deg,
538                    anchor: self.component_move.anchor,
539                };
540                Some((id.clone(), pose))
541            })
542            .collect()
543    }
544
545    /// A TYPED move of the armed component (or group): `value` mm along, or
546    /// degrees about, one of the gizmo's axes (`field` = `x|y|z|rx|ry|rz`) —
547    /// the same motion as dragging that arrow or ring by exactly `value`. It is
548    /// solved against the mates once and written through the drag release's
549    /// commit (one undo step, unfix, mechanical references). When the mates
550    /// allow only part of it, that part is applied and the report says how
551    /// much and which constraints stopped the rest; when they allow none, a
552    /// notice names them and nothing is written.
553    pub fn component_move_typed(&mut self, field: &str, value: f64) -> Result<TypedMove, String> {
554        let (axis, rotate) = typed_axis(field).ok_or_else(|| format!("unknown move field {field:?}"))?;
555        if !value.is_finite() {
556            return Err(format!("{value} is not a number"));
557        }
558        if self.component_move.drag.is_some() {
559            return Err("a drag is in progress".into());
560        }
561        let frame = self.component_move_frame().ok_or("nothing is armed to move")?;
562        let members = self.component_move_members().ok_or("an armed component is gone")?;
563        let mut unit = [0.0; 3];
564        unit[axis] = 1.0;
565        let direction = normalize3(quat_rotate(quat_from_euler_xyz_deg(frame.rotate_deg), unit));
566        let delta = if rotate {
567            TransformDelta::Rotate { axis: direction, radians: value.to_radians() }
568        } else {
569            TransformDelta::Translate([direction[0] * value, direction[1] * value, direction[2] * value])
570        };
571        if self.history_has_assembly() && !self.ensure_assembly_session() {
572            return Err(super::ASSEMBLY_SESSION_PENDING.into());
573        }
574        let (solved, blocking) = match self.component_solve_explained(&members, &delta, None, true) {
575            Ok(result) => result,
576            Err(error) => {
577                let report = TypedMove { field: field.into(), asked: value, applied: 0.0, blocking: Vec::new(), written: false };
578                self.push_notice(format!("Move: the mates cannot hold any pose for this move ({error})."));
579                self.component_move.typed = Some(report.clone());
580                return Ok(report);
581            }
582        };
583        let (primary, start) = members.first().cloned().ok_or("nothing is armed to move")?;
584        let landed = solved.get(&primary).copied().unwrap_or((start.translate, start.rotate_deg));
585        let applied = if rotate {
586            let q_start = quat_from_euler_xyz_deg(start.rotate_deg);
587            let q = quat_mul(quat_from_euler_xyz_deg(landed.1), [-q_start[0], -q_start[1], -q_start[2], q_start[3]]);
588            let along = q[0] * direction[0] + q[1] * direction[1] + q[2] * direction[2];
589            let mut degrees = (2.0 * along.atan2(q[3])).to_degrees();
590            if degrees > 180.0 {
591                degrees -= 360.0;
592            } else if degrees < -180.0 {
593                degrees += 360.0;
594            }
595            degrees
596        } else {
597            let moved = sub3(rigid_delta_point(&start, landed, start.anchor), start.anchor);
598            moved[0] * direction[0] + moved[1] * direction[1] + moved[2] * direction[2]
599        };
600        let stuck = applied.abs() <= TYPED_TOLERANCE * value.abs().max(1.0);
601        let written = !stuck && self.component_commit_solved(&members, &solved, frame.anchor);
602        if !written {
603            self.feed_component_widget();
604        }
605        let report = TypedMove { field: field.into(), asked: value, applied: if written { applied } else { 0.0 }, blocking, written };
606        if !written {
607            self.push_notice(format!("Move: {}", report.summary()));
608        }
609        self.component_move.typed = Some(report.clone());
610        self.dirty = true;
611        Ok(report)
612    }
613
614    /// The last typed move's report (the panel's status line).
615    pub fn component_move_typed_report(&self) -> Option<TypedMove> {
616        self.component_move.typed.clone()
617    }
618
619    /// Whether a component-gizmo drag is in flight.
620    pub fn component_move_dragging(&self) -> bool {
621        self.component_move.drag.is_some()
622    }
623
624    /// Continue the drag: resolve the world delta against the FROZEN grab frame,
625    /// compose the pending pose, solve it live (budget permitting) and pose the
626    /// member displays and the gizmo where the mates put them.
627    pub fn component_drag_to(&mut self, cx: f64, cy: f64) {
628        let Some(drag) = self.component_move.drag.clone() else {
629            return;
630        };
631        let cam = gizmo_camera(&self.camera);
632        let frame = component_frame_json(&drag.start);
633        let json = self.widgets.transform_drag_json_with_frame(
634            &cam,
635            &frame,
636            drag.handle,
637            drag.sx,
638            drag.sy,
639            cx as f32,
640            cy as f32,
641        );
642        let Some(delta) = parse_drag_delta(&json) else {
643            return;
644        };
645        let pending = compose_component_delta(&drag.start, &delta);
646        if let Some(live) = self.component_move.drag.as_mut() {
647            live.pending = Some((delta, pending));
648        }
649        let mut live = drag.live.clone();
650        if live.skip > 0 {
651            live.skip -= 1;
652            live.skipped += 1;
653        } else {
654            let started = now_ms();
655            let solved = self.component_drag_solve(&drag.members, &delta, live.good.as_ref());
656            let cost = self.component_move.solve_cost_override_ms.unwrap_or(now_ms() - started);
657            live.solves += 1;
658            match solved {
659                Ok(poses) => {
660                    live.good = Some(poses);
661                    live.held = false;
662                }
663                Err(_) => live.held = true,
664            }
665            let budget = self.component_move.budget_ms.max(1e-3);
666            if cost > budget {
667                live.skip = ((cost / budget).ceil() as u32).saturating_sub(1).min(DRAG_SOLVE_MAX_SKIP);
668            }
669        }
670        // The gizmo rides the primary member's live pose (the pending pose
671        // until a solve has held); the gold active-handle highlight survives
672        // (only a null feed clears it).
673        let frame = self.component_live_frame(&drag, &pending, &live);
674        let _ = self.widgets.set_transform_json(&component_frame_json(&frame));
675        self.component_live_pose_displays(&drag.members, &live);
676        if let Some(state) = self.component_move.drag.as_mut() {
677            state.live = live;
678        }
679        self.dirty = true;
680    }
681
682    /// One dry-run solve of the dragged members at `delta`: component id →
683    /// solved `(translate, rotate_deg)` for everything the mates moved. `good`
684    /// (the last good live poses) is where mechanical mates re-base. A
685    /// document without assembly state moves the members freely.
686    fn component_drag_solve(
687        &mut self,
688        members: &[(String, ComponentPose)],
689        delta: &TransformDelta,
690        good: Option<&std::collections::BTreeMap<String, ([f64; 3], [f64; 3])>>,
691    ) -> Result<std::collections::BTreeMap<String, ([f64; 3], [f64; 3])>, String> {
692        self.component_solve_explained(members, delta, good, false).map(|(poses, _)| poses)
693    }
694
695    /// [`Self::component_drag_solve`], and with `explain` the constraints that
696    /// refused the dragged members' target pose (the kernel's conflict search:
697    /// one solve per constraint, so only a typed move asks).
698    fn component_solve_explained(
699        &mut self,
700        members: &[(String, ComponentPose)],
701        delta: &TransformDelta,
702        good: Option<&std::collections::BTreeMap<String, ([f64; 3], [f64; 3])>>,
703        explain: bool,
704    ) -> Result<(std::collections::BTreeMap<String, ([f64; 3], [f64; 3])>, Vec<String>), String> {
705        let free: std::collections::BTreeMap<String, ([f64; 3], [f64; 3])> = members
706            .iter()
707            .map(|(id, start)| {
708                let pose = compose_component_delta(start, delta);
709                (id.clone(), (pose.translate, pose.rotate_deg))
710            })
711            .collect();
712        if !self.history_has_assembly() {
713            return Ok((free, Vec::new()));
714        }
715        let poses: serde_json::Map<String, serde_json::Value> = free
716            .iter()
717            .map(|(id, (translate, rotate_deg))| {
718                (id.clone(), serde_json::json!({ "translate": translate, "rotateEulerDeg": rotate_deg }))
719            })
720            .collect();
721        // The last good live poses: mechanical mates re-base there, so each
722        // frame couples only the motion since then.
723        let reference: serde_json::Map<String, serde_json::Value> = good
724            .into_iter()
725            .flatten()
726            .map(|(id, (translate, rotate_deg))| {
727                (id.clone(), serde_json::json!({ "translate": translate, "rotateEulerDeg": rotate_deg }))
728            })
729            .collect();
730        let request = serde_json::json!({
731            "poses": poses,
732            "unfix": self.component_move.unfix,
733            "reference": reference,
734            "explain": explain,
735        });
736        let reply = brep_kernel::assembly_drag_solve_impl(&request.to_string())?;
737        let reply: serde_json::Value = serde_json::from_str(&reply).map_err(|error| error.to_string())?;
738        let mut solved = std::collections::BTreeMap::new();
739        for (id, pose) in reply.get("poses").and_then(|poses| poses.as_object()).into_iter().flatten() {
740            let triple = |key: &str| -> Option<[f64; 3]> {
741                let values = pose.get(key)?.as_array()?;
742                Some([values.first()?.as_f64()?, values.get(1)?.as_f64()?, values.get(2)?.as_f64()?])
743            };
744            if let (Some(translate), Some(rotate_deg)) = (triple("translate"), triple("rotateEulerDeg")) {
745                solved.insert(id.clone(), (translate, rotate_deg));
746            }
747        }
748        let blocking = reply
749            .get("blocking")
750            .and_then(|ids| ids.as_array())
751            .into_iter()
752            .flatten()
753            .filter_map(|id| id.as_str().map(str::to_string))
754            .collect();
755        Ok((solved, blocking))
756    }
757
758    /// The gizmo frame for this drag frame: a group keeps its world-axis frame
759    /// at the anchor carried by the primary member's live delta; a single
760    /// component sits at its live pose.
761    fn component_live_frame(
762        &self,
763        drag: &ComponentMoveDrag,
764        pending: &ComponentPose,
765        live: &LiveSolve,
766    ) -> ComponentPose {
767        let Some((id, start)) = drag.members.first() else {
768            return *pending;
769        };
770        let Some(&(translate, rotate_deg)) = live.good.as_ref().and_then(|good| good.get(id)) else {
771            return *pending;
772        };
773        let anchor = rigid_delta_point(start, (translate, rotate_deg), start.anchor);
774        if drag.members.len() > 1 {
775            return ComponentPose { translate: anchor, rotate_deg: [0.0; 3], anchor };
776        }
777        ComponentPose { translate, rotate_deg, anchor }
778    }
779
780    /// Pose every display of every live-solved component at its solved pose
781    /// (display-only; the pre-drag copies are kept for the restore).
782    fn component_live_pose_displays(&mut self, members: &[(String, ComponentPose)], live: &LiveSolve) {
783        let Some(good) = live.good.as_ref() else {
784            return;
785        };
786        for (id, &solved) in good {
787            // The grab pose of a dragged member; the document pose otherwise.
788            let start = match members.iter().find(|(member, _)| member == id) {
789                Some((_, start)) => *start,
790                None => match self.component_info(id).map(|info| (info.translate, info.rotate_deg)).or_else(|| self.occurrence_world_pose(id)) {
791                    Some((translate, rotate_deg)) => ComponentPose { translate, rotate_deg, anchor: [0.0; 3] },
792                    None => continue,
793                },
794            };
795            // Already showing this pose (posed to it last frame, or never
796            // moved from where it started): nothing to re-pose or re-upload.
797            let shown = self
798                .component_move
799                .live_applied
800                .get(id)
801                .copied()
802                .unwrap_or((start.translate, start.rotate_deg));
803            if same_pose(shown, solved) {
804                continue;
805            }
806            self.component_move.live_applied.insert(id.clone(), solved);
807            // A flexible occurrence (`ACOMP1:ACOMP2`) poses its own solids;
808            // they come after their instance in the map, so its pose wins.
809            let names = if id.contains(':') {
810                let prefix = format!("{id}:");
811                self.scene.solids().iter().filter(|solid| solid.name.starts_with(&prefix)).map(|solid| solid.name.clone()).collect()
812            } else {
813                self.member_solid_names(id)
814            };
815            for name in names {
816                let Some(display) = self.scene.solid(&name) else { continue };
817                let original = self
818                    .component_move
819                    .live_originals
820                    .entry(name.clone())
821                    .or_insert_with(|| display.clone())
822                    .clone();
823                if let Some(display) = self.scene.solid_mut(&name) {
824                    *display = original;
825                    pose_display_rigid(display, &start, solved);
826                }
827            }
828        }
829        self.dirty = true;
830    }
831
832    /// A nested occurrence's world pose as `(translate, rotate_deg)`: its top
833    /// component's pose composed with the occurrence's SOLVED pose in it
834    /// (`nested_poses`). What a flexible occurrence's live drag pose starts
835    /// from. (The live display skipped occurrences, so a flexible
836    /// sub-assembly's parts moved rigidly with it during the drag and jumped
837    /// to their solved poses at release.)
838    fn occurrence_world_pose(&self, path: &str) -> Option<([f64; 3], [f64; 3])> {
839        let (top, rest) = path.split_once(':')?;
840        let record = self.assembly_components().iter().find(|record| record.id == top)?;
841        let local = record.nested_poses.get(rest)?;
842        let (a, b) = (&record.transform, local);
843        let world: [f64; 16] = std::array::from_fn(|k| (0..4).map(|m| a[(k / 4) * 4 + m] * b[m * 4 + k % 4]).sum());
844        let pose = brep_kernel::transform_to_pose_params(&brep_kernel::AffineTransform::new(world).ok()?);
845        let triple = |key: &str| -> Option<[f64; 3]> {
846            let values = pose.get(key)?.as_array()?;
847            Some([values.first()?.as_f64()?, values.get(1)?.as_f64()?, values.get(2)?.as_f64()?])
848        };
849        Some((triple("translate")?, triple("rotateEulerDeg")?))
850    }
851
852    /// Put every live-posed display back exactly (pre-drag pose).
853    pub(super) fn component_live_restore(&mut self) {
854        self.component_move.live_applied.clear();
855        let originals = std::mem::take(&mut self.component_move.live_originals);
856        if originals.is_empty() {
857            return;
858        }
859        for (name, original) in originals {
860            if let Some(display) = self.scene.solid_mut(&name) {
861                *display = original;
862            }
863        }
864        self.dirty = true;
865    }
866
867    /// End the drag: COMMIT the pending pose into each moved ACOMP's
868    /// `inputParams.transform` (one param write — or one batched write for a
869    /// group → one undo entry → one rerun whose constraint tail re-solves; the
870    /// post-run sync then re-glues the gizmo to wherever the solve left the
871    /// components). A grab that never moved commits nothing.
872    pub fn component_release(&mut self) {
873        let Some(drag) = self.component_move.drag.take() else {
874            return;
875        };
876        self.widgets.set_transform_active(0);
877        self.dirty = true;
878        let Some((delta, frame)) = drag.pending else {
879            self.component_live_restore();
880            return;
881        };
882        // The true solve at the final pointer pose; a failure keeps the last
883        // good live pose, and a drag that never held writes nothing (the
884        // pre-drag pose stands).
885        let solved = match self.component_drag_solve(&drag.members, &delta, drag.live.good.as_ref()) {
886            Ok(poses) => poses,
887            Err(_) => match drag.live.good.clone() {
888                Some(poses) => poses,
889                None => {
890                    self.component_live_restore();
891                    self.component_move.unfix.clear();
892                    self.feed_component_widget();
893                    return;
894                }
895            },
896        };
897        let solved = self.snap_dragged_poses(solved);
898        self.component_commit_solved(&drag.members, &solved, frame.anchor);
899    }
900
901    /// The released poses on the 0.001 drag grid, each number judged against
902    /// what the document stores, so a partner the mates left alone stays
903    /// unmoved. Only a drag comes through here; a typed move stays exact.
904    fn snap_dragged_poses(
905        &self,
906        solved: std::collections::BTreeMap<String, ([f64; 3], [f64; 3])>,
907    ) -> std::collections::BTreeMap<String, ([f64; 3], [f64; 3])> {
908        use crate::formatting::snap_drag_moved;
909        solved
910            .into_iter()
911            .map(|(id, (translate, rotate_deg))| {
912                let snapped = match self.component_info(&id) {
913                    Some(info) => (
914                        std::array::from_fn(|i| snap_drag_moved(info.translate[i], translate[i])),
915                        std::array::from_fn(|i| snap_drag_moved(info.rotate_deg[i], rotate_deg[i])),
916                    ),
917                    None => (translate, rotate_deg),
918                };
919                (id, snapped)
920            })
921            .collect()
922    }
923
924    /// Write the solved poses of a drag or a typed move: every component that
925    /// moved, a pending unfix, and the mechanical mates' references, in ONE
926    /// undo step (then one rerun). `fallback_anchor` places the gizmo when the
927    /// primary member has no solved pose. Returns whether anything was written.
928    fn component_commit_solved(
929        &mut self,
930        members: &[(String, ComponentPose)],
931        solved: &std::collections::BTreeMap<String, ([f64; 3], [f64; 3])>,
932        fallback_anchor: [f64; 3],
933    ) -> bool {
934        self.component_move.anchor = match members.first() {
935            Some((id, start)) => match solved.get(id) {
936                Some(&pose) => rigid_delta_point(start, pose, start.anchor),
937                None => fallback_anchor,
938            },
939            None => fallback_anchor,
940        };
941        let mut edits = Vec::new();
942        for (id, &(translate, rotate_deg)) in solved {
943            let Some(index) = self.history.index_of(id) else {
944                continue;
945            };
946            // Only what moved is written (a drag the mates fully undid, or a
947            // partner they left alone, changes nothing). A pending unfix
948            // always writes: the release frees the member.
949            let unfix = self.component_move.unfix.contains(id);
950            match self.component_info(id) {
951                Some(info) if !unfix && !pose_moved((info.translate, info.rotate_deg), (translate, rotate_deg)) => continue,
952                None => continue,
953                _ => {}
954            }
955            let pose = ComponentPose { translate, rotate_deg, anchor: [0.0; 3] };
956            let mut params = self
957                .history
958                .feature_params(index)
959                .unwrap_or_else(|| serde_json::json!({}));
960            if !params.get("transform").map(|t| t.is_object()).unwrap_or(false) {
961                if let Some(object) = params.as_object_mut() {
962                    object.insert("transform".into(), serde_json::json!({}));
963                }
964            }
965            if let Some(transform) = params.get_mut("transform").and_then(|t| t.as_object_mut()) {
966                transform.insert("translate".into(), serde_json::json!(pose.translate));
967                transform.insert("rotateEulerDeg".into(), serde_json::json!(pose.rotate_deg));
968            }
969            if self.component_move.unfix.contains(id) {
970                if let Some(object) = params.as_object_mut() {
971                    object.insert("isFixed".into(), serde_json::Value::Bool(false));
972                }
973            }
974            edits.push((id.clone(), params));
975        }
976        // The pending unfix is spent: from here the members are free.
977        self.component_move.unfix.clear();
978        if edits.is_empty() {
979            self.component_live_restore();
980            return false;
981        }
982        // Gears, racks and screws keep their phase across runs (their stored
983        // references): re-capture them at the released poses and write them in
984        // the SAME undo step as the poses, or the next run would read a
985        // multi-turn drag against the pre-drag references and wrap a spin.
986        // ONE UNDO STEP PER COMMIT. A param write coalesces on `param:{index}`,
987        // so two drags or typed values of the same component in a row would
988        // otherwise be one entry, and one undo would take back both (the
989        // feature transform gizmo ends its run on release for the same reason).
990        self.history.break_coalescing();
991        if let Some(block) = self.mechanical_block_at(solved) {
992            let resolved: Vec<(usize, serde_json::Value)> = edits
993                .iter()
994                .filter_map(|(id, params)| Some((self.history.index_of(id)?, params.clone())))
995                .collect();
996            // The checkpoint here snapshots the pre-drag document (poses AND
997            // references); the block follows without one.
998            self.history.set_many_feature_params(&resolved);
999            self.history.set_assembly_block(block, false);
1000            self.history.break_coalescing();
1001            let _ = self.rerun_history();
1002            return true;
1003        }
1004        match edits.as_slice() {
1005            [] => {}
1006            [(id, params)] => {
1007                let _ = self.update_feature_params(id, &params.to_string());
1008            }
1009            _ => {
1010                let _ = self.update_many_feature_params(&edits);
1011            }
1012        }
1013        self.history.break_coalescing();
1014        true
1015    }
1016
1017    /// The assembly block with every mechanical mate's references re-captured
1018    /// at `solved` (the released poses), or `None` when the document has no
1019    /// mechanical mate (nothing to refresh).
1020    fn mechanical_block_at(
1021        &mut self,
1022        solved: &std::collections::BTreeMap<String, ([f64; 3], [f64; 3])>,
1023    ) -> Option<serde_json::Value> {
1024        if !self.history_has_assembly() {
1025            return None;
1026        }
1027        let poses: serde_json::Map<String, serde_json::Value> = solved
1028            .iter()
1029            .map(|(id, (translate, rotate_deg))| {
1030                (id.clone(), serde_json::json!({ "translate": translate, "rotateEulerDeg": rotate_deg }))
1031            })
1032            .collect();
1033        let reply = brep_kernel::assembly_rebase_mechanical_impl(&serde_json::json!({ "poses": poses }).to_string()).ok()?;
1034        serde_json::from_str::<serde_json::Value>(&reply).ok().filter(|block| !block.is_null())
1035    }
1036
1037    /// The armed component gizmo's logical state for the verifier:
1038    /// `{armed, feature, group, unfix, anchor}`.
1039    pub fn component_move_json(&self) -> String {
1040        serde_json::json!({
1041            "armed": self.component_move_armed(),
1042            "feature": self.component_move_armed_feature(),
1043            "group": self.component_move.group,
1044            "unfix": self.component_move.unfix,
1045            "anchor": self.component_move.anchor,
1046            "typed": self.component_move.typed.as_ref().map(|typed| serde_json::json!({
1047                "field": typed.field,
1048                "asked": typed.asked,
1049                "applied": typed.applied,
1050                "blocking": typed.blocking,
1051                "written": typed.written,
1052                "summary": typed.summary(),
1053            })),
1054            "live": self.component_move.drag.as_ref().map(|drag| {
1055                let poses: serde_json::Map<String, serde_json::Value> = drag
1056                    .live
1057                    .good
1058                    .iter()
1059                    .flatten()
1060                    .map(|(id, (translate, rotate_deg))| {
1061                        (id.clone(), serde_json::json!({ "translate": translate, "rotateEulerDeg": rotate_deg }))
1062                    })
1063                    .collect();
1064                serde_json::json!({
1065                    "poses": poses,
1066                    "held": drag.live.held,
1067                    "solves": drag.live.solves,
1068                    "skipped": drag.live.skipped,
1069                })
1070            }),
1071        })
1072        .to_string()
1073    }
1074}
1075
1076/// The widget frame feed for a component pose: origin = the ANCHOR (bbox
1077/// center), axes = the pose's rotated basis (intrinsic XYZ, the kernel bake).
1078/// EVERY handle set is shown (center free-move ball + axis arrows + rotation
1079/// arcs) — move and rotate coexist, no mode switch.
1080fn component_frame_json(pose: &ComponentPose) -> String {
1081    let euler = [
1082        pose.rotate_deg[0].to_radians(),
1083        pose.rotate_deg[1].to_radians(),
1084        pose.rotate_deg[2].to_radians(),
1085    ];
1086    let x = normalize3(rotate_euler_xyz_f64([1.0, 0.0, 0.0], euler));
1087    let y = normalize3(rotate_euler_xyz_f64([0.0, 1.0, 0.0], euler));
1088    let z = normalize3(rotate_euler_xyz_f64([0.0, 0.0, 1.0], euler));
1089    serde_json::json!({
1090        "origin": pose.anchor,
1091        "x": x,
1092        "y": y,
1093        "z": z,
1094        "showCenter": true,
1095        "showAxes": true,
1096        "showRings": true,
1097    })
1098    .to_string()
1099}
1100
1101/// Translation shifts pose and anchor together. Rotation pivots about anchor C:
1102/// `R' = dR·R`, `translate' = C + dR·(translate − C)`.
1103pub(super) fn compose_component_delta(
1104    start: &ComponentPose,
1105    delta: &TransformDelta,
1106) -> ComponentPose {
1107    match delta {
1108        TransformDelta::Translate(d) => ComponentPose {
1109            translate: add3(start.translate, *d),
1110            rotate_deg: start.rotate_deg,
1111            anchor: add3(start.anchor, *d),
1112        },
1113        TransformDelta::Rotate { axis, radians } => {
1114            let dq = quat_from_axis_angle(*axis, *radians);
1115            let q0 = quat_from_euler_xyz_deg(start.rotate_deg);
1116            let rotate_deg = euler_xyz_deg_from_quat(quat_mul(dq, q0));
1117            let offset = sub3(start.translate, start.anchor);
1118            ComponentPose {
1119                translate: add3(start.anchor, quat_rotate(dq, offset)),
1120                rotate_deg,
1121                anchor: start.anchor,
1122            }
1123        }
1124    }
1125}
1126
1127/// Where a world point riding a component at `start` lands when the component
1128/// is at `to`: `p' = R_to·R_startᵀ·(p − t_start) + t_to`.
1129fn rigid_delta_point(start: &ComponentPose, to: ([f64; 3], [f64; 3]), point: [f64; 3]) -> [f64; 3] {
1130    let q_start = quat_from_euler_xyz_deg(start.rotate_deg);
1131    let q_to = quat_from_euler_xyz_deg(to.1);
1132    let q_delta = quat_mul(q_to, [-q_start[0], -q_start[1], -q_start[2], q_start[3]]);
1133    add3(to.0, quat_rotate(q_delta, sub3(point, start.translate)))
1134}
1135
1136/// Whether two `(translate, rotate_deg)` poses differ beyond solver noise: a
1137/// partner the drag did not move comes back from the solve within ~1e-7 mm
1138/// (measured on as1-ug-214), and writing that would rerun it for nothing.
1139fn pose_moved(a: ([f64; 3], [f64; 3]), b: ([f64; 3], [f64; 3])) -> bool {
1140    (0..3).any(|i| (a.0[i] - b.0[i]).abs() > 1e-6 || (a.1[i] - b.1[i]).abs() > 1e-6)
1141}
1142
1143/// Re-pose a display rigidly from the component pose `start` to `to`: the
1144/// mesh, edge polylines and vertices move, normals rotate, the bbox follows.
1145/// Two `(translate, rotate_deg)` poses within roundoff of each other.
1146fn same_pose(a: ([f64; 3], [f64; 3]), b: ([f64; 3], [f64; 3])) -> bool {
1147    (0..3).all(|k| (a.0[k] - b.0[k]).abs() <= 1e-9 && (a.1[k] - b.1[k]).abs() <= 1e-9)
1148}
1149
1150fn pose_display_rigid(display: &mut crate::scene::SolidDisplay, start: &ComponentPose, to: ([f64; 3], [f64; 3])) {
1151    // A rigid move keeps the shape: the renderer rewrites positions and
1152    // normals in the buffers it holds (`sync_scene`'s pose path) instead of
1153    // rebuilding the solid every drag frame.
1154    if display.shape_revision == 0 {
1155        display.shape_revision = display.revision;
1156    }
1157    // Moved by rewriting its positions, not through a pose matrix.
1158    display.pose = None;
1159    display.revision = crate::scene::next_revision();
1160    let q_start = quat_from_euler_xyz_deg(start.rotate_deg);
1161    let q_delta = quat_mul(quat_from_euler_xyz_deg(to.1), [-q_start[0], -q_start[1], -q_start[2], q_start[3]]);
1162    let pose = |p: [f64; 3]| add3(to.0, quat_rotate(q_delta, sub3(p, start.translate)));
1163    let mut bbox = crate::camera::Aabb::empty();
1164    for position in &mut display.mesh.positions {
1165        let posed = pose(position.map(f64::from));
1166        *position = posed.map(|v| v as f32);
1167        bbox.expand(posed);
1168    }
1169    for normal in &mut display.mesh.normals {
1170        *normal = quat_rotate(q_delta, normal.map(f64::from)).map(|v| v as f32);
1171    }
1172    for edge in &mut display.edges {
1173        for point in &mut edge.polyline {
1174            let posed = pose(point.map(f64::from));
1175            *point = posed.map(|v| v as f32);
1176            bbox.expand(posed);
1177        }
1178    }
1179    for vertex in &mut display.vertices {
1180        vertex.position = pose(vertex.position);
1181        bbox.expand(vertex.position);
1182    }
1183    if !bbox.is_empty() {
1184        display.bbox = bbox;
1185    }
1186}
1187
1188/// Milliseconds on a monotonic-enough clock (the browser has no `Instant`).
1189/// Shared with the motion-study bake (`simulation_play`), which slices its
1190/// solving under the same kind of per-frame budget.
1191#[cfg(not(target_arch = "wasm32"))]
1192pub(super) fn now_ms() -> f64 {
1193    static ORIGIN: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
1194    ORIGIN.get_or_init(std::time::Instant::now).elapsed().as_secs_f64() * 1000.0
1195}
1196
1197#[cfg(target_arch = "wasm32")]
1198pub(super) fn now_ms() -> f64 {
1199    js_sys::Date::now()
1200}
1201
1202/// Rotate `v` by quaternion `q`: `v + 2·(q.xyz × (q.xyz × v + w·v))`.
1203pub(super) fn quat_rotate(q: Quat, v: [f64; 3]) -> [f64; 3] {
1204    let u = [q[0], q[1], q[2]];
1205    let w = q[3];
1206    let t = cross(u, add3(cross(u, v), [w * v[0], w * v[1], w * v[2]]));
1207    [v[0] + 2.0 * t[0], v[1] + 2.0 * t[1], v[2] + 2.0 * t[2]]
1208}
1209