From d61dff69a63f86e932bb1283166c4e9b54f474f1 Mon Sep 17 00:00:00 2001 From: Mateusz Sych <151755914+SychPL@users.noreply.github.com> Date: Sat, 24 Oct 2026 19:25:49 +0000 Subject: [PATCH] Exploded views export as an animation (#3713) (#3744) * claim: #3713 * Exploded views export as an animation (#3713) motion.export_animation takes an exploded view (view: id|name) as well as a study or a joint: the parts come apart at a steady pace from the assembled placement to where the view shows them, and back together with back: true (exploded at the middle frame). 41 frames by default, 81 with back. The home view frames the parts both assembled and exploded. As with explode.show, the design keeps its placements, its history and its saved state. explode.show and the export share the moves; moves a design file gives with no finite translation are left out. * Mechanisms skill: an exploded view's default frame count --------- Co-authored-by: MateuszSychXpl <151755914+MateuszSychXpl@users.noreply.github.com> --- ROADMAP.md | 2 +- crates/engine/src/cmd/motion.rs | 51 +++++++++---- crates/engine/src/cmd/motion_animation.rs | 89 ++++++++++++++++++----- crates/engine/src/cmd/motion_tests.rs | 88 ++++++++++++++++++++++ docs/book/src/guide/assemblies.md | 5 ++ skills/solidcraft-mechanisms/reference.md | 2 +- 6 files changed, 203 insertions(+), 34 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 33869bdc9..e976e5ae3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -58,7 +58,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings. | M6 | UI depth: selection feedback and origin (done), timeline editing (done: hover and selection highlight modifier faces, including fillets and chamfers; edit feature, history marker drag, dependency-checked single and multi-item reorder, suppress, rename, delete with dependents, re-resolved references; redefining selections refreshes persistent edge/face references while retaining feature identity and dimension names; responsive feature history with width-driven icons/names/title, snapping width resize, bottom/left/browser-stack docking, shared-column collapse, rollback bar, multi-selection and persistent folders), right-docked dialogs (done), live previews for every feature dialog (done), keyboard-first commands with on-canvas value boxes and sketch inline dimensions (done), drag manipulators with automatic join/cut (done: extrude incl. two sides, fillet, shell, hole depth, move, pattern spacing, revolve rotator, extrude taper), dark theme (done), right-click menu with Repeat (done), measure tool (done), section analysis (done), selection filter (done), drag-solve of sketch points (done); appearance controls now preserve body/face/component targeting, named transparent looks, reuse/search and override removal; preferences | in progress | 6 | | M7 | Thin extrude (walls along open or closed curves: centre, inside, outside or two sides; mitred corners, crossing walls joined; #721), sweep, loft (incl. to a point), rib and web (to next / depth), emboss (planar faces and exact radial emboss/deboss of bounded orthogonal profiles on complete exterior cylinders/sleeves), thread (cosmetic, and modelled M3–M20 outside and inside: the ISO profile screwed in as a faceted cut), coil (smooth B-spline helical walls), pipe, pattern on path, patterns of bodies and components, replace face (parallel), align, remove, feature copy/paste: done. Unique eligible cylindrical targets are inferred for new Emboss features. Left: general curved-face emboss and exact (unfaceted) modelled threads | in progress | 12 | | M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0, plus `crown`), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane, a face or sketch curves swept onto the surface, keeping a side or the picked regions; mutual trim of two surfaces, extended to meet and stitched, #767), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis, Surface Extrude/Revolve/Sweep/Loft from open and closed curves, Offset, Unstitch and Reverse Normal; the continuity-driven core (`kernel/src/bridge.rs`, G0–G3 Hermite rows) with **Blend** (`surface.blend`, #764: edge chains along one or several faces, closed rims paired seam to seam or from picked seams, a dialog), **Match** (`surface.match`), **Boundary** (`surface.boundary`, #763 — two sketch curves exact with G0–G3, three or four as the flat patch of their loop, and curve networks: Coons and Gordon surfaces through sketch, 3D-sketch or edge curves, a point for a three-sided side, G1/G2 against the faces along one direction's edges, joined into their body on request; G1/G2 on two sides that meet at a corner waits for the Gregory-type corner), **Fair** (`surface.fair`, CV fairing), **continuity analysis** (`inspect.continuity`, #770; a toolbar tool with edge markers and a legend, and curvature combs along face isocurves) and a multi-section **loft** with per-end continuity and crown, and guide rails on solid and surface lofts (one or two, scaling or stretching the sections between; #201). Also in the Class-A pass: G1…G4 blend curves in the sketch, chord and variable-radius fillets on curved edges (with honest refusals where the fit cannot hold), and a G2 corner patch where filleted edges meet (kernel; the command refuses until the patch's sections can be sewn to the blends' contacts). Left: bias/form-factor fillet sections (design recorded), a Gregory-type corner, surface Fillet between separate surface bodies (#769), Ruled (#762), Untrim (#761), curved-face Extend (#760), and every remaining #757–#772 item | deferred | — | -| M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), cams (`joint.cam`: a revolute cam drives a slider or revolute follower along a closed sketch profile or the cam's edges, knife, roller or flat followers, worked out again when the profile changes; drives, studies, closed loops, contact sets), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), motion analysis (joint values and a point's path charted over a study as value, velocity and acceleration; the parts that collide along a study, with the steps where they do), Exploded views (automatic or by hand, shown without changing placements); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link, Cam and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 | +| M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), cams (`joint.cam`: a revolute cam drives a slider or revolute follower along a closed sketch profile or the cam's edges, knife, roller or flat followers, worked out again when the profile changes; drives, studies, closed loops, contact sets), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), motion analysis (joint values and a point's path charted over a study as value, velocity and acceleration; the parts that collide along a study, with the steps where they do), Exploded views (automatic or by hand, shown without changing placements, and exported as an animation coming apart and back together); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link, Cam and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 | | M10 | Sheet metal: flange (base, edge, contour), hem, unfold/refold, convert, flat pattern + DXF, rules: done. PLASTIC enclosure subset: Boss, Rib, Web, Lip/Groove, Snap Fit, Rest, Plastic Rules (library, edit, assign; rule draft and clearance as feature defaults): done, tested against hand-computed geometry. UI: SHEET METAL and PLASTIC tabs with dialogs (live preview, Edit Feature, pre-selection) for Flange, Hem, Unfold/Refold, Convert, Sheet Metal Rules, Create Flat Pattern (flat view with bend lines, bend table CSV/JSON and DXF export with exact circle/arc/line cutouts), Boss, Lip/Groove, Snap Fit, Rest, Manage and Assign Plastic Rules; Fold (bend along a sketch line); flanges meeting at a corner closed at any angle with the rule's gap; edge flanges with their own angle and height per edge in one feature; corner reliefs (notch, round, rectangular, tear) chosen by the rule; Convert to Sheet Metal from a solid or shelled body by its bend edges (flat faces, sharp bends) | in progress | 36 | | M11 | 2D drawings | deferred | — | | M12 | Release: cross-platform packages, verification and deliberate publication implemented; original current-UI demo refreshed. Trusted distribution signing and broader performance work remain | in progress | 16 | diff --git a/crates/engine/src/cmd/motion.rs b/crates/engine/src/cmd/motion.rs index a4ac4531c..4bef2b70c 100644 --- a/crates/engine/src/cmd/motion.rs +++ b/crates/engine/src/cmd/motion.rs @@ -69,7 +69,16 @@ pub static COMMANDS: &[CommandSpec] = &[ .noundo() .params("study; samples? (default steps + 1); path? (.json or .csv) → occurrence positions per step (the design is not changed)"), CommandSpec::new("motion.export_animation", "Export Motion Animation", animation::export).icon("export").noundo().params( - "study: id|name, or joint: id|name with from and to (degrees for angles, mm for distances, or expressions) and index?; path: a .gif file, or a folder for PNG frames (frame-0001.png, frame-0002.png, …); samples? (frames, 2…1000; default the study's steps + 1, or 100); width?, height? (16…4096 pixels, default 800 × 500); camera?: {target, yaw, pitch, roll?, distance, fov?, up?} (ui.camera's reply; fields left out keep the default view: view.apply's camera, or the home view framing the model); fps? (1…50, default 20); grid?, axes? (default true: the ground grid and the origin's axes) - draws the study as it plays, or the joint as it is driven, with the headless renderer → path, format, frames, width, height, fps (GIF), bytes, renderer, stopped_at, stopped_by_loop, stopped_by_contact (the design is not changed)", + "study: id|name, or joint: id|name with from and to (degrees for angles, mm for distances, or expressions) and index?, or \ + view: id|name (an exploded view, coming apart from the assembled placement) with back? (default false; true: back together \ + too, exploded at the middle frame of an odd count); path: a .gif file, or a folder for PNG frames (frame-0001.png, \ + frame-0002.png, …); samples? (frames, 2…1000; default the study's steps + 1, 100 for a joint, 41 for a view or 81 with \ + back); width?, height? (16…4096 pixels, default 800 × 500); camera?: {target, yaw, pitch, roll?, distance, fov?, up?} \ + (ui.camera's reply; fields left out keep the default view: view.apply's camera, or the home view framing the model, for a \ + view both assembled and exploded); fps? (1…50, default 20); grid?, axes? (default true: the ground grid and the origin's \ + axes) - draws the study as it plays, the joint as it is driven or the view as it explodes, with the headless renderer → \ + path, format, frames, width, height, fps (GIF), bytes, renderer, stopped_at, stopped_by_loop, stopped_by_contact (the \ + design is not changed, nor its placements)", ), CommandSpec::new("motion.trace", "Motion Trace", trace).at("SOLID", "ASSEMBLE").icon("trace").noundo().params(concat!( trace_doc!(), @@ -87,7 +96,10 @@ pub static COMMANDS: &[CommandSpec] = &[ Edits a saved associative trace's driving conditions in one undo step", ), CommandSpec::new("motion.plot", "Plot Motion Study", analysis::plot).icon("graph").noundo().params(analysis::PLOT_DOC), - CommandSpec::new("motion.interference", "Motion Interference", analysis::interference).icon("interference").noundo().params(analysis::INTERFERENCE_DOC), + CommandSpec::new("motion.interference", "Motion Interference", analysis::interference) + .icon("interference") + .noundo() + .params(analysis::INTERFERENCE_DOC), CommandSpec::new("joint.sweep", "Sweep Joint", sweep::sweep).icon("interference").params(sweep::SWEEP_DOC), CommandSpec::new("motion.list", "List Motion Studies", list_studies).icon("list").noundo(), CommandSpec::new("motion.delete", "Delete Motion Study", delete_study).icon("delete").params("study"), @@ -1051,21 +1063,34 @@ fn explode_show(s: &mut Session, p: &Value) -> Result { } let i = view_index(s, p, cmd)?; let v = s.doc.assembly.exploded.get(i).cloned().ok_or_else(|| bad(cmd, "view"))?; - s.pending_moves.clear(); - for (o, t) in &v.moves { - let Some(occ) = s.doc.occurrences.iter().find(|x| x.id == *o) else { continue }; - let mut m = occ.transform; - if let Some(r) = m.get_mut(3) { - r[0] += t.x; - r[1] += t.y; - r[2] += t.z; - } - s.pending_moves.insert(*o, m); - } + s.pending_moves = exploded_at(&explode_moves(s, &v), 1.0); s.revision += 1; Ok(json!({"view": v.id, "name": v.name})) } +/// What exploded view `v` moves: (occurrence, its placement, the translation the view adds). Moves +/// of occurrences no longer in the design, or not finite (a hostile design file), are left out; +/// a later move of one occurrence replaces an earlier one. +fn explode_moves(s: &Session, v: &ExplodedView) -> Vec<(u64, Mat, Vec3)> { + let placed: std::collections::BTreeMap = s.doc.occurrences.iter().map(|o| (o.id, o.transform)).collect(); + v.moves.iter().filter(|(_, t)| t.len() < 1e7).filter_map(|(o, t)| Some((*o, *placed.get(o)?, *t))).collect() +} + +/// The pending moves that show `moves` `amount` of the way out: 0 assembled, 1 exploded. +fn exploded_at(moves: &[(u64, Mat, Vec3)], amount: f64) -> std::collections::BTreeMap { + let mut out = std::collections::BTreeMap::new(); + for (o, m, t) in moves { + let mut m = *m; + if let Some(r) = m.get_mut(3) { + r[0] += t.x * amount; + r[1] += t.y * amount; + r[2] += t.z * amount; + } + out.insert(*o, m); + } + out +} + fn explode_list(s: &mut Session, _p: &Value) -> Result { Ok(json!({"views": s.doc.assembly.exploded})) } diff --git a/crates/engine/src/cmd/motion_animation.rs b/crates/engine/src/cmd/motion_animation.rs index 53bd07951..4c820a433 100644 --- a/crates/engine/src/cmd/motion_animation.rs +++ b/crates/engine/src/cmd/motion_animation.rs @@ -1,16 +1,28 @@ -//! Motion animations (`motion.export_animation`): a study played, or one joint driven, drawn -//! frame by frame by the headless renderer the host installed ([`crate::capture`]) and written as -//! an animated GIF or a folder of PNG frames. Sampled on a copy, as a trace is: the design is not -//! changed. +//! Motion animations (`motion.export_animation`): a study played, one joint driven, or an exploded +//! view coming apart (and back together), drawn frame by frame by the headless renderer the host +//! installed ([`crate::capture`]) and written as an animated GIF or a folder of PNG frames. Sampled +//! on a copy, as a trace is: the design is not changed, nor its placements. + +use std::collections::BTreeSet; use serde_json::{Value, json}; +use solidcraft_doc::Mat; +use solidcraft_geom::Vec3; -use super::{drive_with_contact, motion_plan, sample_count}; +use super::{Plan, drive_with_contact, explode_moves, exploded_at, motion_plan, sample_count, view_index}; use crate::capture::{self, Renderer}; use crate::params::{bad, str_}; use crate::render::Camera; use crate::{Result, Session}; +/// What the frames show. +enum Motion { + /// A study played or a joint driven: the values driven, and what they are at each frame. + Drive(BTreeSet<(u64, usize)>, Plan), + /// An exploded view's moves coming apart, and back together when true. + Explode(Vec<(u64, Mat, Vec3)>, bool), +} + /// Most frames of one animation. const MAX_FRAMES: usize = 1000; /// Largest frame side, in pixels. @@ -57,14 +69,44 @@ pub(super) fn export_with(s: &Session, p: &Value, renderer: Option<&Renderer>) - None => 20.0, Some(v) => v.as_f64().filter(|n| n.is_finite() && (1.0..=50.0).contains(n)).ok_or_else(|| bad(cmd, "`fps` must be 1…50"))?, }; - let cam = camera(s, p.get("camera"), cmd)?; - let shown = |key: &str| match p.get(key) { - None => Ok(true), + let flag = |key: &str, default: bool| match p.get(key) { + None => Ok(default), Some(Value::Bool(b)) => Ok(*b), Some(_) => Err(bad(cmd, format!("`{key}` must be true or false"))), }; - let guides = crate::view::Guides { grid: shown("grid")?, axes: shown("axes")? }; - let (default, given, plan) = motion_plan(s, p, cmd)?; + let guides = crate::view::Guides { grid: flag("grid", true)?, axes: flag("axes", true)? }; + let (default, motion) = match (p.get("view"), p.get("study").or(p.get("joint"))) { + (Some(_), Some(_)) => return Err(bad(cmd, "give an exploded `view`, a `study` or a `joint`: one of them")), + (Some(_), None) => { + let back = flag("back", false)?; + let v = s.doc.assembly.exploded.get(view_index(s, p, cmd)?).ok_or_else(|| bad(cmd, "view"))?; + (if back { 81 } else { 41 }, Motion::Explode(explode_moves(s, v), back)) + } + (None, driven) => { + if driven.is_none() { + return Err(bad(cmd, "give a `study`, a `joint` with `from` and `to`, or an exploded `view`")); + } + if p.get("back").is_some() { + return Err(bad(cmd, "`back` goes with an exploded `view`")); + } + let (default, given, plan) = motion_plan(s, p, cmd)?; + (default, Motion::Drive(given, plan)) + } + }; + let home = || match &motion { + // Framing both ends: every frame lies between the parts assembled and exploded. + Motion::Explode(moves, _) => { + let mut t = s.scratch(); + t.pending_moves.clear(); + let assembled = crate::view::bounds(&t); + t.pending_moves = exploded_at(moves, 1.0); + let mut c = crate::view::home_camera(&t); + c.fit(&assembled.union(&crate::view::bounds(&t))); + c + } + Motion::Drive(..) => crate::view::home_camera(s), + }; + let cam = camera(s, home, p.get("camera"), cmd)?; // At least 4 frames fit even at the largest size. let max = MAX_FRAMES.min(if gif { MAX_GIF_PIXELS } else { MAX_PNG_PIXELS } / (width as usize * height as usize)); let n = sample_count(p, default.min(max), max, cmd).map_err(|_| bad(cmd, format!("`samples` must be 2…{max} for {width} × {height} frames")))?; @@ -83,15 +125,24 @@ pub(super) fn export_with(s: &Session, p: &Value, renderer: Option<&Renderer>) - } let mut t = s.scratch(); // From where the parts are placed: moves only shown (an exploded view, the pose an open - // Motion Study dialog shows) are not where the joints are solved. + // Motion Study dialog shows) are not where the joints are solved, nor the assembled placement. t.pending_moves.clear(); let (mut frames, mut bytes, mut drawn_by) = (Vec::new(), 0, ""); let mut stop = (Value::Null, Value::Null, Value::Null); for k in 0..n { - let want = plan(&t, k, n); - let (r, _) = drive_with_contact(&mut t, &want, &given)?; - if stop.0.is_null() && (r["stopped_by_loop"].is_object() || r["stopped_by_contact"].is_object()) { - stop = (json!(k), r["stopped_by_loop"].clone(), r["stopped_by_contact"].clone()); + match &motion { + Motion::Drive(given, plan) => { + let want = plan(&t, k, n); + let (r, _) = drive_with_contact(&mut t, &want, given)?; + if stop.0.is_null() && (r["stopped_by_loop"].is_object() || r["stopped_by_contact"].is_object()) { + stop = (json!(k), r["stopped_by_loop"].clone(), r["stopped_by_contact"].clone()); + } + } + // Shown as explode.show shows it, the way out at a steady pace (and back). + Motion::Explode(moves, back) => { + let u = k as f64 / (n - 1) as f64; + t.pending_moves = exploded_at(moves, if *back { 1.0 - (2.0 * u - 1.0).abs() } else { u }); + } } let scene = crate::view::scene_with_guides(&t, &cam, s.section, guides); let picture = capture::rgba_with(Some(renderer), &scene, &cam, width, height).map_err(|e| bad(cmd, e))?; @@ -125,10 +176,10 @@ pub(super) fn export_with(s: &Session, p: &Value, renderer: Option<&Renderer>) - Ok(out) } -/// The camera the frames are drawn from: the session's (`view.apply`), or the home view framing -/// the model, with the fields `given` sets (`ui.camera`'s reply sets them all). -fn camera(s: &Session, given: Option<&Value>, cmd: &str) -> Result { - let base = s.camera.unwrap_or_else(|| crate::view::home_camera(s)); +/// The camera the frames are drawn from: the session's (`view.apply`), or `home` framing the +/// model, with the fields `given` sets (`ui.camera`'s reply sets them all). +fn camera(s: &Session, home: impl FnOnce() -> Camera, given: Option<&Value>, cmd: &str) -> Result { + let base = s.camera.unwrap_or_else(home); let Some(given) = given else { return Ok(base) }; let fields = given.as_object().ok_or_else(|| bad(cmd, "`camera` must be an object, such as ui.camera's reply"))?; let mut v = serde_json::to_value(base).map_err(|e| bad(cmd, e.to_string()))?; diff --git a/crates/engine/src/cmd/motion_tests.rs b/crates/engine/src/cmd/motion_tests.rs index 1ceadf700..f4e88fb36 100644 --- a/crates/engine/src/cmd/motion_tests.rs +++ b/crates/engine/src/cmd/motion_tests.rs @@ -824,10 +824,78 @@ fn an_animation_is_drawn_from_the_camera_given() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn an_exploded_view_animates_apart_and_back_without_moving_the_design() { + let mut s = rail(); + run(&mut s, "explode.create", json!({"name": "Apart", "scale": 1})); + // Another view shown: the animation starts from the assembled placement all the same. + run(&mut s, "explode.create", json!({"name": "Up", "moves": [{"occurrence": "B", "translate": [0, 0, 50]}]})); + run(&mut s, "explode.show", json!({"view": "Up"})); + s.mark_saved(); + let (doc, pending, undo) = (s.doc.clone(), s.pending_moves.clone(), s.undo.len()); + // Each frame: the lowest x and z of each body drawn, rounded to a micrometre. + let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let record = { + let seen = seen.clone(); + move |scene: &crate::render::Scene, cam: &crate::render::Camera, w: u32, h: u32| { + let mut lows: Vec<[i64; 2]> = + scene.meshes.iter().map(|m| m.mesh.bounds().min).map(|v| [(v.x * 1e3).round() as i64, (v.z * 1e3).round() as i64]).collect(); + lows.sort(); + seen.lock().unwrap().push((lows, *cam)); + cpu(scene, cam, w, h) + } + }; + let dir = out_dir("explode"); + let gif = dir.join("apart.gif"); + let frames = |p: Value| { + let mut p = p; + p["path"] = json!(gif.to_string_lossy()); + p["width"] = json!(24); + p["height"] = json!(16); + let r = super::animation::export_with(&s, &p, Some(&record)).unwrap(); + let seen = std::mem::take(&mut *seen.lock().unwrap()); + assert_eq!(r["frames"].as_u64(), Some(seen.len() as u64), "{r}"); + assert_eq!(gif_frames(&std::fs::read(&gif).unwrap()), (24, 16, seen.len())); + seen + }; + let lows = |seen: &[(Vec<[i64; 2]>, crate::render::Camera)]| seen.iter().map(|(l, _)| l.clone()).collect::>(); + // A at x 0, B at x 20: each moves 10 mm out, at a steady pace. + let at = |x: i64| vec![[x * 1000, 0], [(20 - x) * 1000, 0]]; + let apart = frames(json!({"view": "Apart", "samples": 3})); + assert_eq!(lows(&apart), [at(0), at(-5), at(-10)]); + // Back together too: exploded at the middle frame, assembled at both ends. + let round = frames(json!({"view": "Apart", "back": true, "samples": 5})); + assert_eq!(lows(&round), [at(0), at(-5), at(-10), at(-5), at(0)]); + // One camera for the whole clip, framing the parts assembled and exploded alike. + assert!(round.iter().all(|(_, c)| *c == round[0].1)); + let mut framed = crate::render::Camera::default(); + framed.fit(&solidcraft_geom::Aabb3 { min: Vec3::new(-10.0, 0.0, 0.0), max: Vec3::new(40.0, 10.0, 10.0) }); + assert!(round[0].1.target.dist(framed.target) < 1e-9 && (round[0].1.distance - framed.distance).abs() < 1e-9, "{:?}", round[0].1); + // Without samples: 41 frames, or 81 with back (the middle one exploded). + assert_eq!(frames(json!({"view": "Apart"})).len(), 41); + let long = frames(json!({"view": "Up", "back": true})); + assert_eq!(long.len(), 81); + assert_eq!(long[40].0, [[0, 0], [20_000, 50_000]], "B up at the middle"); + assert_eq!((long[0].0.clone(), long[80].0.clone()), (vec![[0, 0], [20_000, 0]], vec![[0, 0], [20_000, 0]])); + // The design keeps its placements, the view shown, its history and its saved state. + assert_eq!((&*s.doc, &s.pending_moves, s.undo.len()), (&*doc, &pending, undo)); + // Through the registry too. + crate::capture::install_test_renderer(); + let r = run( + &mut s, + "motion.export_animation", + json!({"view": "Apart", "back": true, "path": gif.to_string_lossy(), "samples": 3, "width": 16, "height": 16}), + ); + assert_eq!(r["frames"], 3, "{r}"); + assert_eq!((&*s.doc, &s.pending_moves, s.undo.len(), s.is_dirty()), (&*doc, &pending, undo, false)); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn hostile_animation_params_are_refused() { let mut s = rail(); run(&mut s, "motion.study", json!({"name": "Push", "steps": 10, "keys": [{"joint": "Rail", "points": [[0, 10], [10, 0]]}]})); + run(&mut s, "explode.create", json!({"name": "Apart", "scale": 1})); let dir = out_dir("hostile"); let gif = dir.join("x.gif").to_string_lossy().to_string(); let base = json!({"study": "Push", "path": gif, "samples": 2, "width": 16, "height": 16}); @@ -873,6 +941,12 @@ fn hostile_animation_params_are_refused() { json!({"study": null}), json!({"study": "Nope"}), json!({"study": null, "joint": "Rail"}), + json!({"back": true}), + json!({"view": "Apart"}), + json!({"study": null, "view": "Nope"}), + json!({"study": null, "view": [1]}), + json!({"study": null, "view": "Apart", "back": "yes"}), + json!({"study": null, "view": "Apart", "joint": "Rail", "from": 0, "to": 1}), // 4096 × 4096 frames: a GIF holds four of them. json!({"width": 4096, "height": 4096, "samples": 5}), ] { @@ -891,6 +965,20 @@ fn hostile_animation_params_are_refused() { assert!(refused(json!({"path": root.join("in.gif").to_string_lossy()})).is_none()); }); assert!(root.join("in.gif").exists() && !dir.join("out").exists()); + // A design file's exploded view moving parts by no number, too far, or parts gone: those + // moves are left out, here and in explode.show. + let b = occ(&s, "B"); + let moves = vec![ + (b, Vec3::new(f64::NAN, 0.0, 0.0)), + (b, Vec3::new(0.0, f64::INFINITY, 0.0)), + (b, Vec3::new(1e300, 0.0, 0.0)), + (999, Vec3::new(1.0, 0.0, 0.0)), + ]; + s.doc_mut().assembly.exploded.push(solidcraft_doc::motion::ExplodedView { id: 900, name: "Bad".into(), moves }); + let p = json!({"view": "Bad", "path": gif, "samples": 2, "width": 16, "height": 16}); + super::animation::export_with(&s, &p, Some(&cpu)).unwrap(); + run(&mut s, "explode.show", json!({"view": "Bad"})); + assert!(s.pending_moves.is_empty(), "{:?}", s.pending_moves); let _ = std::fs::remove_dir_all(&dir); } diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index 7a02da209..0115cbe29 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -288,6 +288,11 @@ are drawn by the same renderer as `solidcraft-cli snapshot`, on a copy of the de changed. A GIF keeps one palette for all its frames, so colours don't flicker, and stores only what changed from one frame to the next. Frames are capped: at most 1000, and a GIF holds at most 2^26 pixels of frames (about 160 frames of 800 × 500). +An exploded view animates the same way: give its name or id as `view` (instead of a `study` or a +`joint`) and the parts come apart at a steady pace, from the assembled placement to where the view +shows them; `back: true` brings them back together, exploded at the middle frame. That takes 41 +frames by default, or 81 with `back`, and the home view frames the parts both assembled and +exploded. As with `explode.show`, the design keeps its placements. **Motion analysis.** The **Motion Study** dialog's **Study** box opens a saved study to edit, and by its timeline the dialog charts what the study does. diff --git a/skills/solidcraft-mechanisms/reference.md b/skills/solidcraft-mechanisms/reference.md index 1d59a920b..36a818bcc 100644 --- a/skills/solidcraft-mechanisms/reference.md +++ b/skills/solidcraft-mechanisms/reference.md @@ -154,6 +154,6 @@ The same pattern moved the solar wings of the SELENE rover (`Rover-v7.solidcraft ## Showing it moving -`motion.export_animation {"study":..., "path":"tour.gif"}` draws the whole motion as an animated GIF in one call, headless or bridged, and changes nothing: `{"joint":..., "from":0, "to":90, "path":...}` animates a drive instead. A path that does not end in `.gif` is a folder for PNG frames (`frame-0001.png`, ...). Pass `camera` (the reply of `ui.camera`, or any of its fields), `width`/`height` (default 800 x 500), `samples` (frames; default the study's steps + 1, or 100), `fps` (default 20), and `grid: false` / `axes: false` for a clean background. The reply is small: `frames`, `bytes`, and `stopped_at` with `stopped_by_loop`/`stopped_by_contact` where the motion first stopped short. +`motion.export_animation {"study":..., "path":"tour.gif"}` draws the whole motion as an animated GIF in one call, headless or bridged, and changes nothing: `{"joint":..., "from":0, "to":90, "path":...}` animates a drive instead, and `{"view":..., "back":true, "path":...}` an exploded view coming apart and back together (the placements stay as they are). A path that does not end in `.gif` is a folder for PNG frames (`frame-0001.png`, ...). Pass `camera` (the reply of `ui.camera`, or any of its fields), `width`/`height` (default 800 x 500), `samples` (frames; default the study's steps + 1, 100 for a joint, 41 for a view or 81 with `back`), `fps` (default 20), and `grid: false` / `axes: false` for a clean background. The reply is small: `frames`, `bytes`, and `stopped_at` with `stopped_by_loop`/`stopped_by_contact` where the motion first stopped short. Bridged to the app, `motion.play {"study":..., "step":s}` moves the user's viewport, and `screenshot` captures the window at that step.