Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Agents and scripts: the occurrence commands, Capture and Revert Position, Move Bodies and Sketches to Component and Paste New describe their exact parameters and reply (#13186) (#13231)

PeppaWutz3eacb3722e2d
diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs
index 70926ba17d..8d01286ff4 100644
--- a/crates/engine/src/cmd/component.rs
+++ b/crates/engine/src/cmd/component.rs
@@ -13,11 +13,13 @@ use solidcraft_doc::{Feature, FeatureKind, Mat, Occurrence};
use super::CommandSpec;
use crate::params::{bad, bool_, str_, string_list, vec3};
use crate::schema::component::{
- ActivateParams, ActivateResult, ChildEntry, CompactPlacement, ComponentNode, CreateParams, CreateResult, DeleteParams, DeleteResult,
- EditInPlaceParams, EditInPlaceResult, FinishEditParams, FinishEditResult, FromBodiesParams, FromBodiesResult, ListParams, ListResult,
- MoveFeaturesParams, MoveFeaturesResult, MoveSketchesToPartsParams, MoveSketchesToPartsResult, NamesOrCount, OccurrenceAlignParams,
- OccurrenceAlignResult, PlacementEntry, PlacementInfo, PropertiesParams, PropertiesResult, RenameParams, RenameResult, ReparentItemsParams,
- ReparentItemsResult, UnlockParams, UnlockResult,
+ ActivateParams, ActivateResult, CapturePositionParams, CapturePositionResult, ChildEntry, CompactPlacement, ComponentNode, CopyParams,
+ CopyResult, CreateParams, CreateResult, DeleteParams, DeleteResult, DragParams, DragResult, EditInPlaceParams, EditInPlaceResult,
+ FinishEditParams, FinishEditResult, FromBodiesParams, FromBodiesResult, GroundParams, GroundResult, ListParams, ListResult, MoveBodiesParams,
+ MoveBodiesResult, MoveFeaturesParams, MoveFeaturesResult, MoveParams, MoveResult, MoveSketchesParams, MoveSketchesResult,
+ MoveSketchesToPartsParams, MoveSketchesToPartsResult, NamesOrCount, OccurrenceAlignParams, OccurrenceAlignResult, OccurrencePropertiesParams,
+ OccurrencePropertiesResult, PasteNewParams, PasteNewResult, PlacementEntry, PlacementInfo, PropertiesParams, PropertiesResult, RenameParams,
+ RenameResult, ReparentItemsParams, ReparentItemsResult, RevertPositionParams, RevertPositionResult, UnlockParams, UnlockResult,
};
use crate::schema::{TypedContract, output_schema_for};
use crate::{Result, Session};
@@ -35,6 +37,16 @@ const FINISH_EDIT_CONTRACT: TypedContract<FinishEditParams> = TypedContract::new
const MOVE_FEATURES_CONTRACT: TypedContract<MoveFeaturesParams> = TypedContract::new();
const MOVE_SKETCHES_TO_PARTS_CONTRACT: TypedContract<MoveSketchesToPartsParams> = TypedContract::new();
const REPARENT_ITEMS_CONTRACT: TypedContract<ReparentItemsParams> = TypedContract::new();
+const CAPTURE_POSITION_CONTRACT: TypedContract<CapturePositionParams> = TypedContract::new();
+const COPY_CONTRACT: TypedContract<CopyParams> = TypedContract::new();
+const DRAG_CONTRACT: TypedContract<DragParams> = TypedContract::new();
+const GROUND_CONTRACT: TypedContract<GroundParams> = TypedContract::new();
+const MOVE_CONTRACT: TypedContract<MoveParams> = TypedContract::new();
+const MOVE_BODIES_CONTRACT: TypedContract<MoveBodiesParams> = TypedContract::new();
+const MOVE_SKETCHES_CONTRACT: TypedContract<MoveSketchesParams> = TypedContract::new();
+const OCCURRENCE_PROPERTIES_CONTRACT: TypedContract<OccurrencePropertiesParams> = TypedContract::new();
+const PASTE_NEW_CONTRACT: TypedContract<PasteNewParams> = TypedContract::new();
+const REVERT_POSITION_CONTRACT: TypedContract<RevertPositionParams> = TypedContract::new();
#[path = "component_align.rs"]
mod align;
@@ -133,8 +145,10 @@ pub static COMMANDS: &[CommandSpec] = &[
.contract(&PROPERTIES_CONTRACT)
.output(output_schema_for::<PropertiesResult>)
.params("component?: id or name (default active); descendants?: bool (default true); about?: [x, y, z] (mm). Measures the first placement, or all placements for root, including pending moves; material-aware mass and center of mass in world coordinates; volume, density, mass, center of mass and inertia_g_mm2 (the inertia tensor about the body's center of mass, world axes, from its tessellation) only for closed, consistently oriented bodies; total.open_bodies_skipped counts open bodies excluded from volume/mass totals; total.first_moment_g_mm (mass × center of mass), inertia_g_mm2 about the total center of mass, principal_moments_g_mm2 (smallest first) and principal_axes (unit, right-handed); with about, total.inertia_about {point, inertia_g_mm2}"),
- CommandSpec::new("occurrence.properties", "Occurrence Physical Properties", properties::occurrence)
+ CommandSpec::new("occurrence.properties", "Occurrence Physical Properties", crate::checked!("occurrence.properties", properties::occurrence))
.icon("measure").noundo()
+ .contract(&OCCURRENCE_PROPERTIES_CONTRACT)
+ .output(output_schema_for::<OccurrencePropertiesResult>)
.params("occurrence: id or name; path?: [occurrence ids] (required if nested under multiple instances); descendants?: bool (default true); about?: [x, y, z] (mm). Physical properties of this placement in world coordinates, including pending moves; volume, density, mass, center of mass and inertia_g_mm2 only for closed, consistently oriented bodies; total.open_bodies_skipped counts open bodies excluded from volume/mass totals; total inertia as in component.properties"),
CommandSpec::new("component.rename", "Rename Component", crate::checked!("component.rename", rename))
.icon("rename")
@@ -154,7 +168,11 @@ pub static COMMANDS: &[CommandSpec] = &[
"component: removes the rigid joints that hold its contents together (an imported assembly's rigid group), so its parts \
move and take joints one by one → joints (the ids removed)",
),
- CommandSpec::new("component.move_bodies", "Move Bodies to Component", move_bodies).icon("move").params(
+ CommandSpec::new("component.move_bodies", "Move Bodies to Component", crate::checked!("component.move_bodies", move_bodies))
+ .icon("move")
+ .contract(&MOVE_BODIES_CONTRACT)
+ .output(output_schema_for::<MoveBodiesResult>)
+ .params(
"bodies: [names], component; component_path?: its placement to place them by (default: its only one, else the active \
one; a component placed more than once gets them in every instance); from_path?: the placement of their component they \
move from (default: its only one, else its first, where its bodies have their own names)",
@@ -173,8 +191,10 @@ pub static COMMANDS: &[CommandSpec] = &[
A component that uses what isn't in it (another body, sketch or parameter) is refused, saying what. Returns \
`bodies` and `feature`, or the pasted components' `paths`",
),
- CommandSpec::new("component.move_sketches", "Move Sketches to Component", move_sketches)
+ CommandSpec::new("component.move_sketches", "Move Sketches to Component", crate::checked!("component.move_sketches", move_sketches))
.icon("move")
+ .contract(&MOVE_SKETCHES_CONTRACT)
+ .output(output_schema_for::<MoveSketchesResult>)
.params("sketches: [ids or names], component; the sketches keep their own coordinates (component.move_features keeps them where they are in the world), except that a sketch on an exactly attached face stays where it is on the face"),
CommandSpec::new(
"component.move_sketches.to_parts",
@@ -210,12 +230,26 @@ pub static COMMANDS: &[CommandSpec] = &[
nothing: placements move first (taking what they hold), then features (taking the bodies they made), then the bodies \
still elsewhere (a body transfer, which leaves its features behind)",
),
- CommandSpec::new("occurrence.copy", "Paste (Instance)", copy_occurrence).icon("copy")
+ CommandSpec::new("occurrence.copy", "Paste (Instance)", crate::checked!("occurrence.copy", copy_occurrence))
+ .icon("copy")
+ .contract(&COPY_CONTRACT)
+ .output(output_schema_for::<CopyResult>)
.params("component (or occurrence): what to place again; path?: validates selected occurrence; parent?: component (default: the same parent); translate?: [x,y,z]; in_place?: bool (default false: the selected transform within the parent; true: where the selected placement is in the world, translate in world axes; a parent placed more than once is placed by parent_path?, else the active placement, and every instance gets the copy). Copies the selected effective transform, including pending moves"),
- CommandSpec::new("component.paste_new", "Paste New", paste_new).icon("paste").params("component: independently copy its nested definition graph and history, materials and styles; occurrence?, path?: selected source placement; parent?: component the copy goes in (default: the source placement's; not the component or one inside it); in_place?, parent_path?: as occurrence.copy; translate?: [x,y,z]. Reassigned external bodies become base geometry; retained external links and omitted boundary joints are reported"),
- CommandSpec::new("occurrence.move", "Move Occurrence", move_occurrence).icon("move")
+ CommandSpec::new("component.paste_new", "Paste New", crate::checked!("component.paste_new", paste_new))
+ .icon("paste")
+ .contract(&PASTE_NEW_CONTRACT)
+ .output(output_schema_for::<PasteNewResult>)
+ .params("component: independently copy its nested definition graph and history, materials and styles; occurrence?, path?: selected source placement; parent?: component the copy goes in (default: the source placement's; not the component or one inside it); in_place?, parent_path?: as occurrence.copy; translate?: [x,y,z]. Reassigned external bodies become base geometry; retained external links and omitted boundary joints are reported"),
+ CommandSpec::new("occurrence.move", "Move Occurrence", crate::checked!("occurrence.move", move_occurrence))
+ .icon("move")
+ .contract(&MOVE_CONTRACT)
+ .output(output_schema_for::<MoveResult>)
.params("occurrence; path?: exact placement; space?: local|world (default local); translate?: [x,y,z]; axis?: [x,y,z], angle?: radians or \"30 deg\", origin?: [x,y,z]; matrix?: [12 or 16 numbers] (instead of translate/axis/angle/origin: a rigid move as a row-major 3x4 rotation-and-translation or 4x4 matrix, flat or as rows; one that is a rotation only up to rounding is orthonormalised, a scale, shear or mirror is refused); tolerance?: largest accepted |RᵀR − I| (default 1e-9, at most 1e-3); capture?: bool (default true; false keeps it pending until Capture Position); move_grounded?: bool (default false: a grounded occurrence refuses; true moves it and it stays grounded). Nested occurrence definitions remain shared. Replies {occurrence, transform, pending}; when joints hold it to something fixed and put it back, transform is where it is and the reply adds reverted: true and a warning naming the joint"),
- CommandSpec::new("occurrence.drag", "Drag Occurrence", drag::drag).icon("move").params(
+ CommandSpec::new("occurrence.drag", "Drag Occurrence", crate::checked!("occurrence.drag", drag::drag))
+ .icon("move")
+ .contract(&DRAG_CONTRACT)
+ .output(output_schema_for::<DragResult>)
+ .params(
"occurrence or path: exact placement; at: [x,y,z] world point on it; point: [x,y,z] where it goes. Moves the placement by \
point - at (with any chain of joints it is in that is joined to nothing grounded) and captures its position; other pending \
moves stay pending. Shared definitions move in all placements. Grounded parts and parts joints hold to something fixed are refused (joint.reach moves those)",
@@ -230,14 +264,29 @@ pub static COMMANDS: &[CommandSpec] = &[
world coordinates without changing shared component geometry; a placement inside a component placed more than once moves in \
every placement of it, and the reply's `shared` lists those paths",
),
- CommandSpec::new("occurrence.ground", "Ground", ground).icon("ground").params("occurrence; grounded?: bool (default toggles)"),
+ CommandSpec::new("occurrence.ground", "Ground", crate::checked!("occurrence.ground", ground))
+ .icon("ground")
+ .contract(&GROUND_CONTRACT)
+ .output(output_schema_for::<GroundResult>)
+ .params("occurrence; grounded?: bool (default toggles)"),
CommandSpec::new("occurrence.reparent", "Move to Component", reparent::reparent).icon("move").params(
"occurrence; path?: exact placement; parent: component id or name (0 or \"root\" for the design); parent_path?: the parent's \
placement to place it by (default: its only one, else the active one; every instance of the parent gets it). The placement \
keeps its world position; a move that would break a feature is refused",
),
- CommandSpec::new("component.capture_position", "Capture Position", capture).at("SOLID", "POSITION").icon("capture").params("keeps pending occurrence moves"),
- CommandSpec::new("component.revert_position", "Revert Position", revert).at("SOLID", "POSITION").icon("revert").noundo().params("occurrences?: [ids] (default all); drops selected pending occurrence moves"),
+ CommandSpec::new("component.capture_position", "Capture Position", crate::checked!("component.capture_position", capture))
+ .at("SOLID", "POSITION")
+ .icon("capture")
+ .contract(&CAPTURE_POSITION_CONTRACT)
+ .output(output_schema_for::<CapturePositionResult>)
+ .params("keeps pending occurrence moves"),
+ CommandSpec::new("component.revert_position", "Revert Position", crate::checked!("component.revert_position", revert))
+ .at("SOLID", "POSITION")
+ .icon("revert")
+ .noundo()
+ .contract(&REVERT_POSITION_CONTRACT)
+ .output(output_schema_for::<RevertPositionResult>)
+ .params("occurrences?: [ids] (default all); drops selected pending occurrence moves"),
];
const ALIGN_CONTRACT: TypedContract<OccurrenceAlignParams> = TypedContract::new();
@@ -269,7 +318,7 @@ fn translation(t: Vec3) -> Mat {
solidcraft_doc::rigid(t, Vec3::ZERO, Vec3::Z, 0.0)
}
-fn move_vector(p: &Value, key: &str, default: Vec3, coordinate: bool, cmd: &str) -> Result<Vec3> {
+pub(crate) fn move_vector(p: &Value, key: &str, default: Vec3, coordinate: bool, cmd: &str) -> Result<Vec3> {
let v = match p.get(key) {
None => default,
Some(value) => vec3(value).ok_or_else(|| bad(cmd, format!("{key} must contain three finite numbers")))?,
@@ -621,7 +670,7 @@ fn move_sketches(s: &mut Session, p: &Value) -> Result<Value> {
f.component = to;
}
}
- Ok(json!({"sketches": ids, "component": to}))
+ reply(MoveSketchesResult { sketches: ids, component: to, param_warnings: Vec::new() })
}
pub(super) fn copy_occurrence(s: &mut Session, p: &Value) -> Result<Value> {
@@ -655,7 +704,7 @@ pub(super) fn copy_occurrence(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "copy transform exceeds supported numeric range"));
}
let id = s.doc_mut().add_occurrence(comp, parent, m)?;
- Ok(json!({"occurrence": id, "component": comp}))
+ reply(CopyResult { occurrence: id, component: comp, param_warnings: Vec::new() })
}
fn paste_new(s: &mut Session, p: &Value) -> Result<Value> {
@@ -785,17 +834,7 @@ fn move_occurrence(s: &mut Session, p: &Value) -> Result<Value> {
delta
};
let cur = if let Some(value) = p.get("base_transform") {
- let base: Mat = serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "base_transform must be a 4x4 affine matrix"))?;
- if !valid_position(&base)
- || base[0][3].abs() > 1e-12
- || base[1][3].abs() > 1e-12
- || base[2][3].abs() > 1e-12
- || (base[3][3] - 1.0).abs() > 1e-12
- || solidcraft_doc::mat_inverse(&base).is_none()
- {
- return Err(bad(cmd, "base_transform must be finite, affine and invertible"));
- }
- base
+ base_transform(value).map_err(|message| bad(cmd, message))?
} else {
s.uncaptured_moves().get(&id).copied().unwrap_or(o.transform)
};
@@ -809,24 +848,47 @@ fn move_occurrence(s: &mut Session, p: &Value) -> Result<Value> {
x.transform = next;
}
if !s.doc.assembly.joints.is_empty() {
- return Ok(after_joints(s, p, id, next, cmd));
+ return reply(after_joints(s, p, id, next, cmd));
}
} else {
s.pending_moves.insert(id, next);
s.revision += 1;
}
- Ok(json!({"occurrence": id, "transform": next, "pending": !bool_(p, "capture").unwrap_or(true)}))
+ reply(MoveResult {
+ occurrence: id,
+ transform: next,
+ pending: !bool_(p, "capture").unwrap_or(true),
+ reverted: false,
+ warning: None,
+ param_warnings: Vec::new(),
+ })
+}
+
+/// A move's `base_transform`: a 4×4 matrix that is finite, affine and invertible, or what is
+/// wrong with it. The parameters contract reads it the same way.
+pub(crate) fn base_transform(value: &Value) -> std::result::Result<Mat, &'static str> {
+ let base: Mat = serde_json::from_value(value.clone()).map_err(|_| "base_transform must be a 4x4 affine matrix")?;
+ if !valid_position(&base)
+ || base[0][3].abs() > 1e-12
+ || base[1][3].abs() > 1e-12
+ || base[2][3].abs() > 1e-12
+ || (base[3][3] - 1.0).abs() > 1e-12
+ || solidcraft_doc::mat_inverse(&base).is_none()
+ {
+ return Err("base_transform must be finite, affine and invertible");
+ }
+ Ok(base)
}
/// The reply to a captured move once the joints are solved (#11723): a part its joints hold to
/// something fixed is put back by that solve, so the reply gives where it is now, says
/// `reverted`, and names the joint and what to change instead.
-fn after_joints(s: &mut Session, p: &Value, id: u64, moved: Mat, cmd: &str) -> Value {
+fn after_joints(s: &mut Session, p: &Value, id: u64, moved: Mat, cmd: &str) -> MoveResult {
s.refresh();
let now = s.doc.occurrences.iter().find(|o| o.id == id).map_or(moved, |o| o.transform);
let same = now.iter().flatten().zip(moved.iter().flatten()).all(|(a, b)| (a - b).abs() <= 1e-6);
if same {
- return json!({"occurrence": id, "transform": now, "pending": false});
+ return MoveResult { occurrence: id, transform: now, pending: false, reverted: false, warning: None, param_warnings: Vec::new() };
}
let name = s.doc.occurrences.iter().find(|o| o.id == id).map(|o| o.name.clone()).unwrap_or_default();
// The placement the caller named, else the first one: a part in a component placed more
@@ -855,7 +917,7 @@ fn after_joints(s: &mut Session, p: &Value, id: u64, moved: Mat, cmd: &str) -> V
"{why}The joints put {name} back where they hold it. To move it, change the joint (joint.edit for its offset or angle, \
joint.drive for a hinge or slider value), move what it is held to, or use joint.reach"
);
- json!({"occurrence": id, "transform": now, "pending": false, "reverted": true, "warning": warning})
+ MoveResult { occurrence: id, transform: now, pending: false, reverted: true, warning: Some(warning), param_warnings: Vec::new() }
}
fn ground(s: &mut Session, p: &Value) -> Result<Value> {
@@ -868,7 +930,7 @@ fn ground(s: &mut Session, p: &Value) -> Result<Value> {
let o = s.doc_mut().occurrences.iter_mut().find(|o| o.id == id).ok_or_else(|| bad(cmd, "occurrence"))?;
o.grounded = want.unwrap_or(!o.grounded);
let g = o.grounded;
- Ok(json!({"occurrence": id, "grounded": g}))
+ reply(GroundResult { occurrence: id, grounded: g, param_warnings: Vec::new() })
}
fn capture(s: &mut Session, _p: &Value) -> Result<Value> {
@@ -882,7 +944,7 @@ fn capture(s: &mut Session, _p: &Value) -> Result<Value> {
}
}
s.revision += 1;
- Ok(json!({ "captured": n }))
+ reply(CapturePositionResult { captured: n, param_warnings: Vec::new() })
}
fn revert(s: &mut Session, p: &Value) -> Result<Value> {
@@ -904,7 +966,7 @@ fn revert(s: &mut Session, p: &Value) -> Result<Value> {
}
let n = before - s.pending_moves.len();
s.revision += 1;
- Ok(json!({ "reverted": n }))
+ reply(RevertPositionResult { reverted: n, param_warnings: Vec::new() })
}
/// The active component's frame from world coordinates (for new features' geometry).
diff --git a/crates/engine/src/cmd/component_clone.rs b/crates/engine/src/cmd/component_clone.rs
index 0e0ab69285..5a352dac6f 100644
--- a/crates/engine/src/cmd/component_clone.rs
+++ b/crates/engine/src/cmd/component_clone.rs
@@ -4,8 +4,9 @@ use solidcraft_geom::prelude::*;
use std::collections::{BTreeMap, BTreeSet};
use crate::params::bad;
+use crate::schema::component::PasteNewResult;
use crate::{Result, Sel, Session};
-use serde_json::{Value, json};
+use serde_json::Value;
use solidcraft_doc::{Document, Feature, FeatureKind, Mat, Occurrence};
const CMD: &str = "component.paste_new";
@@ -793,7 +794,16 @@ pub(super) fn build(
}
}
scratch.selection = vec![Sel::Occurrence { path: clone_path }];
- let out = json!({"component":root,"occurrence":root_occurrence,"features":new_ids,"components":components.len(),"bodies":expected_count,"frozen_bodies":frozen,"notices":notices});
+ let out = super::component::reply(PasteNewResult {
+ component: root,
+ occurrence: root_occurrence,
+ features: new_ids,
+ components: components.len(),
+ bodies: expected_count,
+ frozen_bodies: frozen,
+ notices,
+ param_warnings: Vec::new(),
+ })?;
Ok((scratch, out))
}
diff --git a/crates/engine/src/cmd/component_drag.rs b/crates/engine/src/cmd/component_drag.rs
index 1815a79d86..f0c9467a8f 100644
--- a/crates/engine/src/cmd/component_drag.rs
+++ b/crates/engine/src/cmd/component_drag.rs
@@ -4,11 +4,12 @@
//! (`joint.reach` moves those as far as their joints allow). A chain of joints joined to nothing
//! fixed moves as one, so its joints stay as they are.
-use serde_json::{Value, json};
+use serde_json::Value;
use solidcraft_doc::{mat_inverse, mat_mul};
use super::{move_vector, occurrence, occurrence_path, translation, valid_position};
use crate::params::bad;
+use crate::schema::component::DragResult;
use crate::{EngineError, Result, Session};
#[cfg(test)]
@@ -158,5 +159,12 @@ pub(super) fn drag(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let continuous = p.get("continuous").and_then(Value::as_bool).unwrap_or(false);
- Ok(json!({"occurrence": path.last(), "path": path, "moved": moved, "translate": [t.x, t.y, t.z], "continuous": continuous}))
+ super::reply(DragResult {
+ occurrence: path.last().copied().unwrap_or_default(),
+ path,
+ moved,
+ translate: [t.x, t.y, t.z],
+ continuous,
+ param_warnings: Vec::new(),
+ })
}
diff --git a/crates/engine/src/cmd/component_properties.rs b/crates/engine/src/cmd/component_properties.rs
index 1ae78dca89..19773f1af4 100644
--- a/crates/engine/src/cmd/component_properties.rs
+++ b/crates/engine/src/cmd/component_properties.rs
@@ -2,14 +2,16 @@
use solidcraft_geom::prelude::*;
use std::collections::{BTreeMap, BTreeSet};
-use serde_json::{Value, json};
+use serde_json::Value;
use solidcore_record::Vec3;
use solidcraft_doc::{Document, Mat};
use solidcraft_geom::Aabb3;
use solidcraft_geom::inertia::{self, Tensor3};
use crate::params::bad;
-use crate::schema::component::{BodyProperties, BoundingBox, InertiaAbout, PhysicalProperties, PropertiesResult, TotalProperties};
+use crate::schema::component::{
+ BodyProperties, BoundingBox, InertiaAbout, OccurrencePropertiesResult, PhysicalProperties, PropertiesResult, TotalProperties,
+};
use crate::{Result, Session};
fn descendants(p: &Value, cmd: &str) -> Result<bool> {
@@ -104,10 +106,9 @@ pub(super) fn occurrence(s: &mut Session, p: &Value) -> Result<Value> {
_ => return Err(bad(cmd, "occurrence has multiple placements; supply its `path`")),
}
};
- let mut out = properties(s, &doc, &path, descendants(p, cmd)?, about(p, cmd)?, cmd)?;
- out["occurrence"] = json!(id);
- out["name"] = json!(doc.occurrences.iter().find(|o| o.id == id).map(|o| o.name.as_str()));
- Ok(out)
+ let properties = measure(s, &doc, &path, descendants(p, cmd)?, about(p, cmd)?, cmd)?;
+ let name = doc.occurrences.iter().find(|o| o.id == id).map(|o| o.name.clone());
+ super::reply(OccurrencePropertiesResult { occurrence: id, name, properties, param_warnings: Vec::new() })
}
/// The linear part of `m` is a rotation (no scale, shear or mirror), to rounding.
@@ -199,11 +200,6 @@ fn measure_placed(body: &solidcraft_doc::ModelBody, transform: Mat) -> Result<Pl
})
}
-/// [`measure`] as the JSON `occurrence.properties` adds its own keys to.
-fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool, about: Option<Vec3>, cmd: &str) -> Result<Value> {
- super::reply(measure(s, doc, selected, descendants, about, cmd)?)
-}
-
fn measure(s: &Session, doc: &Document, selected: &[u64], descendants: bool, about: Option<Vec3>, cmd: &str) -> Result<PhysicalProperties> {
let state = s.model.state();
let mut bodies = Vec::new();
diff --git a/crates/engine/src/cmd/component_transfer.rs b/crates/engine/src/cmd/component_transfer.rs
index e4dc022460..e56388b4f1 100644
--- a/crates/engine/src/cmd/component_transfer.rs
+++ b/crates/engine/src/cmd/component_transfer.rs
@@ -1,6 +1,6 @@
//! Atomic timeline ownership changes, preserving the selected world geometry.
use super::*;
-use crate::schema::component::{BodyComponent, FromBodiesResult};
+use crate::schema::component::{BodyComponent, FromBodiesResult, MoveBodiesResult};
use solidcraft_doc::BodyName;
use std::collections::{BTreeMap, BTreeSet};
@@ -188,7 +188,7 @@ fn move_at_boundary(s: &mut Session, p: &Value, allow_boundary: bool) -> Result<
features.push(transfer(&mut scratch, name, to, &frames, cmd)?);
}
finish(s, &mut scratch, &features, cmd)?;
- Ok(json!({"bodies":bodies,"component":to,"features":features}))
+ super::reply(MoveBodiesResult { bodies, component: to, features, param_warnings: Vec::new() })
}
#[cfg(test)]
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index e288b5c5a4..6481036a2d 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -86,6 +86,8 @@ mod script;
mod section;
pub mod settings;
pub(crate) use clipboard::{component_path_form, copy_keys};
+pub(crate) use component::matrix::{rigid as rigid_matrix, tolerance as matrix_tolerance};
+pub(crate) use component::{base_transform, move_vector};
pub(crate) use measure_sel::{measure_items, shape_of};
pub(crate) use measure_shape::Shape;
pub(crate) use script::step_params;
diff --git a/crates/engine/src/schema/component.rs b/crates/engine/src/schema/component.rs
index 28905a778f..38a21f6e45 100644
--- a/crates/engine/src/schema/component.rs
+++ b/crates/engine/src/schema/component.rs
@@ -1130,6 +1130,834 @@ pub struct UnlockResult {
pub param_warnings: Vec<String>,
}
+// ---------------------------------------------------------------------------------------------
+// The occurrence commands, Capture and Revert Position, Move Bodies and Sketches to Component and
+// Paste New (#13186).
+//
+// As above, each key reads as its handler reads it and fails with the handler's message; a key
+// the handler refuses when it is left out is optional in the type and required in the schema.
+// Some handlers read a key only in some cases (`occurrence.copy` reads `component` only without
+// `occurrence`, `occurrence.move` reads `tolerance` only with `matrix`, and so on): those
+// parameters types are read stage by stage in the handler's order, from only the keys the handler
+// reads in that case, so a call that works today gets no warning and a call that fails gets the
+// handler's message.
+// ---------------------------------------------------------------------------------------------
+
+/// The message of a handler's refusal, to give whole.
+fn refusal(e: crate::EngineError) -> String {
+ match e {
+ crate::EngineError::BadParams { msg, .. } => msg,
+ e => e.to_string(),
+ }
+}
+
+/// The keys of `value` that are in `keys`, as an object.
+fn only(value: &Value, keys: &[&str]) -> Value {
+ Value::Object(value.as_object().into_iter().flatten().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect())
+}
+
+/// `K` read from `value`: first from just the keys of each of `stages` in turn (the order the
+/// handler reads them in, so the first refusal is the handler's), then from all of it.
+fn staged<K: serde::de::DeserializeOwned, E: serde::de::Error>(value: &Value, stages: &[&[&str]]) -> Result<K, E> {
+ read_stages::<K, E>(value, stages)?;
+ serde_path_to_error::deserialize(value).map_err(|e| E::custom(located(&e)))
+}
+
+/// What [`staged`] reads first: just the keys of each of `stages` in turn, for the first refusal.
+fn read_stages<K: serde::de::DeserializeOwned, E: serde::de::Error>(value: &Value, stages: &[&[&str]]) -> Result<(), E> {
+ for stage in stages {
+ serde_path_to_error::deserialize::<_, K>(&only(value, stage)).map_err(|e| E::custom(located(&e)))?;
+ }
+ Ok(())
+}
+
+/// The keys of `value` without `keys`.
+fn without(mut value: Value, keys: &[&str]) -> Value {
+ if let Some(object) = value.as_object_mut() {
+ for key in keys {
+ object.remove(*key);
+ }
+ }
+ value
+}
+
+/// `key`'s value as `cmd::move_vector` reads it: `[x, y, z]` or `{x, y, z}` of numbers below 1e9
+/// in size, with its message `key must contain three finite numbers` for anything else, `null`
+/// included.
+fn move_point_key<'de, D: Deserializer<'de>>(d: D, key: &str, coordinate: bool) -> Result<Option<Point3>, D::Error> {
+ let mut one = serde_json::Map::new();
+ one.insert(key.to_string(), Value::deserialize(d)?);
+ crate::cmd::move_vector(&Value::Object(one), key, Vec3::ZERO, coordinate, "")
+ .map(|v| Some(Point3(v)))
+ .map_err(|e| D::Error::custom(whole(refusal(e))))
+}
+
+macro_rules! move_point {
+ ($name:ident, $key:literal, $coordinate:literal) => {
+ fn $name<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Point3>, D::Error> {
+ move_point_key(d, $key, $coordinate)
+ }
+ };
+}
+
+move_point!(translate_key, "translate", true);
+move_point!(axis_key, "axis", false);
+move_point!(origin_key, "origin", true);
+move_point!(at_key, "at", true);
+move_point!(point_key, "point", true);
+
+/// A placement path as `placing::parent_path` and `component.move_bodies` read `parent_path`,
+/// `component_path` and `from_path`: up to 64 occurrence ids (none is the design itself).
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct PlacementPath(pub Vec<u64>);
+
+impl<'de> Deserialize<'de> for PlacementPath {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ Value::deserialize(d)?
+ .as_array()
+ .filter(|a| a.len() <= 64)
+ .and_then(|a| a.iter().map(Value::as_u64).collect::<Option<Vec<_>>>())
+ .map(PlacementPath)
+ .ok_or_else(|| D::Error::custom("must list 0..64 occurrence ids"))
+ }
+}
+
+impl JsonSchema for PlacementPath {
+ fn schema_name() -> Cow<'static, str> {
+ "PlacementPath".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "An exact placement path: up to 64 occurrence ids from the root down; empty for the design itself.",
+ "type": "array",
+ "items": {"type": "integer", "minimum": 0, "maximum": u64::MAX},
+ "maxItems": 64
+ })
+ }
+}
+
+/// `component.revert_position`'s `occurrences`: 1 to 10000 occurrence ids.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct OccurrenceIds(pub Vec<u64>);
+
+impl<'de> Deserialize<'de> for OccurrenceIds {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ Value::deserialize(d)?
+ .as_array()
+ .filter(|a| !a.is_empty() && a.len() <= 10_000)
+ .and_then(|a| a.iter().map(Value::as_u64).collect::<Option<Vec<_>>>())
+ .map(OccurrenceIds)
+ .ok_or_else(|| D::Error::custom(whole("occurrences must list 1..10000 ids")))
+ }
+}
+
+impl JsonSchema for OccurrenceIds {
+ fn schema_name() -> Cow<'static, str> {
+ "OccurrenceIds".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "1 to 10000 occurrence ids.",
+ "type": "array",
+ "items": {"type": "integer", "minimum": 0, "maximum": u64::MAX},
+ "minItems": 1,
+ "maxItems": 10000
+ })
+ }
+}
+
+/// `occurrence.move`'s `angle`: a number (radians) or an angle expression, which the handler
+/// evaluates against the design's parameters.
+#[derive(Clone, Debug, PartialEq)]
+pub struct MoveAngle(pub Value);
+
+impl<'de> Deserialize<'de> for MoveAngle {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ v @ (Value::Number(_) | Value::String(_)) => Ok(MoveAngle(v)),
+ _ => Err(D::Error::custom(whole("angle must be a number or angle expression"))),
+ }
+ }
+}
+
+impl JsonSchema for MoveAngle {
+ fn schema_name() -> Cow<'static, str> {
+ "MoveAngle".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "An angle in radians (a number) or an angle expression such as \"30 deg\".", "type": ["number", "string"]})
+ }
+}
+
+/// Which frame `occurrence.move` reads its move in: `local` or `world`.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, JsonSchema)]
+#[serde(rename_all = "lowercase")]
+pub enum MoveSpace {
+ Local,
+ World,
+}
+
+fn move_space<'de, D: Deserializer<'de>>(d: D) -> Result<Option<MoveSpace>, D::Error> {
+ super::view_navigation::read_as(d, "space must be local or world")
+}
+
+/// `occurrence.move`'s `matrix`: 12 numbers (a row-major 3×4) or 16 (a 4×4), flat or as rows. The
+/// parameters read it with `tolerance` (`matrix::rigid`), which refuses what isn't a rigid move.
+#[derive(Clone, Debug, PartialEq)]
+pub struct MatrixParam(pub Value);
+
+impl<'de> Deserialize<'de> for MatrixParam {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ Value::deserialize(d).map(MatrixParam)
+ }
+}
+
+impl JsonSchema for MatrixParam {
+ fn schema_name() -> Cow<'static, str> {
+ "MoveMatrix".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ let row = json!({"type": "array", "items": {"type": "number"}, "minItems": 4, "maxItems": 4});
+ json_schema!({
+ "description": "A rigid move as a row-major 3x4 (12 numbers) or 4x4 (16 numbers) matrix, flat or as 3 or 4 rows of 4.",
+ "anyOf": [
+ {"type": "array", "items": {"type": "number"}, "minItems": 12, "maxItems": 12},
+ {"type": "array", "items": {"type": "number"}, "minItems": 16, "maxItems": 16},
+ {"type": "array", "items": row, "minItems": 3, "maxItems": 4}
+ ]
+ })
+ }
+}
+
+/// `occurrence.move`'s `tolerance`, read only with `matrix`: a number above 0 and at most 1e-3.
+#[derive(Clone, Debug, PartialEq)]
+pub struct MatrixTolerance(pub Value);
+
+impl<'de> Deserialize<'de> for MatrixTolerance {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ Value::deserialize(d).map(MatrixTolerance)
+ }
+}
+
+impl JsonSchema for MatrixTolerance {
+ fn schema_name() -> Cow<'static, str> {
+ "MatrixTolerance".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "A number above 0 and at most 0.001.", "type": "number", "exclusiveMinimum": 0, "maximum": 0.001})
+ }
+}
+
+/// `occurrence.move`'s `base_transform`: the 4×4 matrix a move starts from, as the Browser's
+/// drag passes it, in the layout of a placement's `transform` (4 columns of 4 numbers): finite,
+/// affine (the fourth number of the first three columns is 0, of the last 1) and invertible.
+#[derive(Clone, Debug, PartialEq)]
+pub struct BaseTransform(pub solidcraft_doc::Mat);
+
+impl<'de> Deserialize<'de> for BaseTransform {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ crate::cmd::base_transform(&Value::deserialize(d)?).map(BaseTransform).map_err(|message| D::Error::custom(whole(message)))
+ }
+}
+
+impl JsonSchema for BaseTransform {
+ fn schema_name() -> Cow<'static, str> {
+ "BaseTransform".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ let row = json!({"type": "array", "items": {"type": "number"}, "minItems": 4, "maxItems": 4});
+ json_schema!({
+ "description": "A 4x4 matrix as 4 columns of 4 numbers, as a placement's `transform` is given (the translation is the last column): finite, affine (the fourth number of the first three columns is 0, of the last column 1) and invertible.",
+ "type": "array",
+ "items": row,
+ "minItems": 4,
+ "maxItems": 4
+ })
+ }
+}
+
+macro_rules! wraps_keys {
+ ($params:ident, $keys:ident, $name:literal) => {
+ impl JsonSchema for $params {
+ fn schema_name() -> Cow<'static, str> {
+ $name.into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ $keys::json_schema(generator)
+ }
+ }
+ };
+}
+
+fn occurrence_required(schema: &mut Schema) {
+ require(schema, "occurrence");
+}
+
+fn component_and_bodies_required(schema: &mut Schema) {
+ require(schema, "component");
+ require(schema, "bodies");
+}
+
+fn component_and_sketches_required(schema: &mut Schema) {
+ require(schema, "component");
+ require(schema, "sketches");
+}
+
+fn occurrence_or_component_required(schema: &mut Schema) {
+ schema.insert("anyOf".into(), json!([{"required": ["occurrence"]}, {"required": ["component"]}]));
+}
+
+fn drag_schema(schema: &mut Schema) {
+ schema.insert("anyOf".into(), json!([{"required": ["occurrence"]}, {"required": ["path"]}]));
+ require(schema, "at");
+ require(schema, "point");
+}
+
+fn move_schema(schema: &mut Schema) {
+ require(schema, "occurrence");
+ schema.insert("allOf".into(), json!(["translate", "axis", "angle", "origin"].map(|key| json!({"not": {"required": ["matrix", key]}}))));
+}
+
+/// `sketches` as `string_list` reads it (one name or a list, with its messages), where `null`,
+/// `[]` and a missing key all get the handler's `` `sketches` must list sketches ``.
+fn sketch_names<'de, D: Deserializer<'de>>(d: D) -> Result<Option<super::config::NameList>, D::Error> {
+ let v = Value::deserialize(d)?;
+ let names = if v.is_null() { Default::default() } else { super::config::NameList::deserialize(v).map_err(D::Error::custom)? };
+ if names.0.is_empty() { Err(D::Error::custom(whole("`sketches` must list sketches"))) } else { Ok(Some(names)) }
+}
+
+fn sketch_names_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "The sketches, by id or name as text: one, or a list of 1 to 10000.",
+ "anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": params::MAX_STRING_LIST}]
+ })
+}
+
+/// Make every pending occurrence move the occurrence's placement. The exploded view is shown,
+/// never captured: it stays shown, and the design keeps its placements.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct CapturePositionParams {}
+
+/// What `component.capture_position` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct CapturePositionResult {
+ /// How many pending moves became the occurrences' placements.
+ pub captured: usize,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// Drop pending occurrence moves, putting the occurrences back where they were captured. Not an
+/// undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct RevertPositionParams {
+ /// The occurrences to put back, by id. Default: every one with a pending move.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OccurrenceIds")]
+ pub occurrences: Option<OccurrenceIds>,
+}
+
+/// What `component.revert_position` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct RevertPositionResult {
+ /// How many pending moves were dropped.
+ pub reverted: usize,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// Ground a placement, or let it go (a grounded part stays where it is when joints move
+/// things). Without `grounded` it toggles.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = occurrence_required)]
+pub struct GroundParams {
+ // Optional in the type and required in the schema (`occurrence_required`).
+ /// The occurrence, by id or name.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OccurrenceRef")]
+ pub occurrence: Option<OccurrenceRef>,
+ /// The occurrence's exact placement, as occurrence ids from the top of the design (1 to 64),
+ /// ending in `occurrence`. It is only checked.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OccurrencePath")]
+ pub path: Option<OccurrencePath>,
+ /// `true` grounds it, `false` frees it. Default: toggle.
+ #[serde(default)]
+ pub grounded: Option<bool>,
+}
+
+/// What `occurrence.ground` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct GroundResult {
+ /// The occurrence, by id.
+ pub occurrence: u64,
+ /// Whether it is grounded now.
+ pub grounded: bool,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// Place a component again (Paste as an instance): a new occurrence of the same component, which
+/// shares its contents, at the selected placement's transform (pending moves included) moved by
+/// `translate`. Give the `occurrence` to copy, or the `component`.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = occurrence_or_component_required)]
+pub struct CopyKeys {
+ // `occurrence` or `component` is needed: optional in the type and required in the schema
+ // (`occurrence_or_component_required`), so that the handler's message is what a caller sees.
+ /// The placement to copy, by id or name. When given, `component` is not read.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OccurrenceRef")]
+ pub occurrence: Option<OccurrenceRef>,
+ /// The component to place again, by id or name: its first placement is copied. Read only
+ /// without `occurrence`.
+ #[serde(default, deserialize_with = "component", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ComponentRef")]
+ pub component: Option<ComponentRef>,
+ /// The placement's exact path, as occurrence ids from the top of the design (1 to 64),
+ /// ending in the placement copied. Needed for a placement inside a component placed more
+ /// than once, with `in_place`.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OccurrencePath")]
+ pub path: Option<OccurrencePath>,
+ /// The component the copy goes in, by id or name. Default: the copied placement's parent.
+ #[serde(default, deserialize_with = "parent", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ComponentRef")]
+ pub parent: Option<ComponentRef>,
+ /// Move the copy by this much, in mm (up to 1e9). Default: no move.
+ #[serde(default, deserialize_with = "translate_key", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Point3")]
+ pub translate: Option<Point3>,
+ /// `false`: the copy has the selected transform within its parent. `true`: it sits where the
+ /// selected placement is in the world, and `translate` is along the world axes. Default:
+ /// `false`.
+ #[serde(default)]
+ pub in_place: Option<bool>,
+ /// With `in_place: true`: the placement of `parent` to place the copy by, as occurrence ids
+ /// from the top (up to 64; none is the design). A parent placed more than once puts the copy
+ /// in every instance. Default: the parent's only placement, else the active one. Read only
+ /// with `in_place: true`.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PlacementPath")]
+ pub parent_path: Option<PlacementPath>,
+}
+
+/// `occurrence.copy`'s parameters: [`CopyKeys`], with `component` read only without `occurrence`
+/// and `parent_path` only with `in_place: true`, as the handler reads them.
+#[derive(Debug)]
+pub struct CopyParams(pub CopyKeys);
+
+impl<'de> Deserialize<'de> for CopyParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let mut value = Value::deserialize(d)?;
+ if value.get("occurrence").is_some() {
+ value = without(value, &["component"]);
+ }
+ if value.get("in_place").and_then(Value::as_bool) != Some(true) {
+ value = without(value, &["parent_path"]);
+ }
+ staged(&value, &[&["occurrence", "component"], &["path"], &["parent"], &["translate"]]).map(CopyParams)
+ }
+}
+
+wraps_keys!(CopyParams, CopyKeys, "CopyParams");
+
+/// What `occurrence.copy` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct CopyResult {
+ /// The new placement, by id.
+ pub occurrence: u64,
+ /// The component it places, by id.
+ pub component: u64,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// Paste New: an independent copy of a component, with its nested components, features, bodies,
+/// materials, styles, joints and motion, placed at the source placement's transform (pending
+/// moves included) moved by `translate`. Unlike `occurrence.copy`, the copy shares nothing with
+/// the original. A body reassigned from outside becomes base geometry; links kept to outside
+/// things and joints omitted at the boundary are listed in `notices`.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = component_required)]
+pub struct PasteNewKeys {
+ // Optional in the type and required in the schema (`component_required`).
+ /// The component to copy, by id or name (not the design).
+ #[serde(default, deserialize_with = "component", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ComponentRef")]
+ pub component: Option<ComponentRef>,
+ /// The source placement, by id or name; it must place `component`. Default: the component's
+ /// first placement.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OccurrenceRef")]
+ pub occurrence: Option<OccurrenceRef>,
+ /// The source placement's exact path, as occurrence ids from the top of the design (1 to 64),
+ /// ending in the placement copied.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OccurrencePath")]
+ pub path: Option<OccurrencePath>,
+ /// The component the copy goes in, by id or name. Default: the source placement's parent. It
+ /// may not be the component or one inside it.
+ #[serde(default, deserialize_with = "parent", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ComponentRef")]
+ pub parent: Option<ComponentRef>,
+ /// Move the copy by this much, in mm (up to 1e9). Default: no move.
+ #[serde(default, deserialize_with = "translate_key", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Point3")]
+ pub translate: Option<Point3>,
+ /// `false`: the copy has the source transform within its parent. `true`: it sits where the
+ /// source placement is in the world, and `translate` is along the world axes. Default:
+ /// `false`.
+ #[serde(default)]
+ pub in_place: Option<bool>,
+ /// With `in_place: true`: the placement of `parent` to place the copy by, as occurrence ids
+ /// from the top (up to 64; none is the design). Read only with `in_place: true`.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PlacementPath")]
+ pub parent_path: Option<PlacementPath>,
+}
+
+/// `component.paste_new`'s parameters: [`PasteNewKeys`], with `parent_path` read only with
+/// `in_place: true`, as the handler reads it.
+#[derive(Debug)]
+pub struct PasteNewParams(pub PasteNewKeys);
+
+impl<'de> Deserialize<'de> for PasteNewParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let mut value = Value::deserialize(d)?;
+ if value.get("in_place").and_then(Value::as_bool) != Some(true) {
+ value = without(value, &["parent_path"]);
+ }
+ let first: &[&str] = if value.get("occurrence").is_some() { &["occurrence", "path"] } else { &["occurrence"] };
+ staged(&value, &[&["component"], first, &["translate"], &["parent"], &["path"]]).map(PasteNewParams)
+ }
+}
+
+wraps_keys!(PasteNewParams, PasteNewKeys, "PasteNewParams");
+
+/// What `component.paste_new` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct PasteNewResult {
+ /// The copy of the component, by id.
+ pub component: u64,
+ /// Its placement, by id.
+ pub occurrence: u64,
+ /// The new features, by id.
+ pub features: Vec<u64>,
+ /// How many components were made: the copy and what is inside it.
+ pub components: usize,
+ /// How many bodies the copy has.
+ pub bodies: usize,
+ /// The bodies copied as frozen geometry (their features stay with the original).
+ pub frozen_bodies: Vec<String>,
+ /// What was left behind or kept pointing outside the copy: links to bodies, sketches, planes,
+ /// parameters and features outside it, and joints and motion across its boundary.
+ pub notices: Vec<String>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// Move an occurrence: by `translate`, or turned by `angle` about `axis` through `origin`, or by
+/// a rigid `matrix` instead of those. Nested occurrences' definitions stay shared. A grounded
+/// occurrence refuses unless `move_grounded` is true. When joints hold it to something fixed and
+/// put it back, the reply says so (`reverted`).
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = move_schema)]
+pub struct MoveKeys {
+ // Optional in the type and required in the schema (`move_schema`).
+ /// The occurrence, by id or name.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OccurrenceRef")]
+ pub occurrence: Option<OccurrenceRef>,
+ /// The occurrence's exact placement, as occurrence ids from the top of the design (1 to 64),
+ /// ending in `occurrence`. Needed with `space: world` for a placement inside a component
+ /// placed more than once.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OccurrencePath")]
+ pub path: Option<OccurrencePath>,
+ /// The frame of the move: `local` is the parent's (the placement's own), `world` is world
+ /// coordinates. Default: `local`.
+ #[serde(default, deserialize_with = "move_space", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "MoveSpace")]
+ pub space: Option<MoveSpace>,
+ /// Move by this much, in mm. Default: no move. Not with `matrix`.
+ #[serde(default, deserialize_with = "translate_key", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Point3")]
+ pub translate: Option<Point3>,
+ /// The axis to turn about, not zero when `angle` is. Default: Z. Not with `matrix`.
+ #[serde(default, deserialize_with = "axis_key", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Point3")]
+ pub axis: Option<Point3>,
+ /// The turn about `axis`: radians, or an angle expression. Default: 0. Not with `matrix`.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "MoveAngle")]
+ pub angle: Option<MoveAngle>,
+ /// The point the turn is about, in mm. Default: the origin. Not with `matrix`.
+ #[serde(default, deserialize_with = "origin_key", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Point3")]
+ pub origin: Option<Point3>,
+ /// A rigid move instead of `translate`, `axis`, `angle` and `origin`: a rotation and a
+ /// translation. One that is a rotation only up to `tolerance` is made exact; a scale, shear or
+ /// mirror is refused.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "MatrixParam")]
+ pub matrix: Option<MatrixParam>,
+ /// With `matrix`: the largest accepted |RᵀR − I| per entry. Default: 1e-9. Read only with
+ /// `matrix`.
+ #[serde(default)]
+ pub tolerance: Option<MatrixTolerance>,
+ /// `true` makes the move the occurrence's placement now; `false` keeps it pending until
+ /// `component.capture_position`. Default: `true`.
+ #[serde(default)]
+ pub capture: Option<bool>,
+ /// `true` moves a grounded occurrence, which stays grounded. Default: `false`, which refuses.
+ #[serde(default)]
+ pub move_grounded: Option<bool>,
+ /// The transform the move starts from, in place of the occurrence's current one (what a drag
+ /// in the Browser passes).
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "BaseTransform")]
+ pub base_transform: Option<BaseTransform>,
+}
+
+/// `occurrence.move`'s parameters: [`MoveKeys`], read as the handler reads them: with `matrix`,
+/// `translate`, `axis`, `angle` and `origin` are refused and `tolerance` is read; without it,
+/// `tolerance` is not.
+#[derive(Debug)]
+pub struct MoveParams(pub MoveKeys);
+
+impl<'de> Deserialize<'de> for MoveParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let mut value = Value::deserialize(d)?;
+ if value.get("matrix").is_some() {
+ read_stages::<MoveKeys, D::Error>(&value, &[&["occurrence"]])?;
+ if let Some(key) = ["translate", "axis", "angle", "origin"].into_iter().find(|k| value.get(*k).is_some()) {
+ return Err(D::Error::custom(whole(format!("give either matrix or {key}, not both"))));
+ }
+ let tolerance = crate::cmd::matrix_tolerance(&value, "").map_err(|e| D::Error::custom(whole(refusal(e))))?;
+ crate::cmd::rigid_matrix(value.get("matrix").unwrap_or(&Value::Null), tolerance, "").map_err(|e| D::Error::custom(whole(refusal(e))))?;
+ return staged(&value, &[&["space"], &["path"]]).map(MoveParams);
+ }
+ value = without(value, &["tolerance"]);
+ staged(&value, &[&["occurrence"], &["translate"], &["axis"], &["angle"], &["origin"], &["space"], &["path"]]).map(MoveParams)
+ }
+}
+
+wraps_keys!(MoveParams, MoveKeys, "MoveParams");
+
+/// What `occurrence.move` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct MoveResult {
+ /// The occurrence, by id.
+ pub occurrence: u64,
+ /// Its placement in its parent now, as a 4×4 matrix (its pending one with `capture: false`).
+ pub transform: [[f64; 4]; 4],
+ /// Whether the move is pending, not captured.
+ pub pending: bool,
+ /// Present, and `true`, when joints hold the occurrence to something fixed and put it back:
+ /// `transform` is where it is.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub reverted: bool,
+ /// With `reverted`: the joint that holds it and what to change instead.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub warning: Option<String>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// Drag a placement by `point - at`, in world coordinates, and capture its position: the grabbed
+/// point `at` goes to `point`. Any chain of joints it is in that is joined to nothing grounded
+/// moves with it; other pending moves stay pending; shared definitions move in all their
+/// placements. Grounded parts and parts that joints hold to something fixed are refused
+/// (`joint.reach` moves those).
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = drag_schema)]
+pub struct DragKeys {
+ // `occurrence` or `path` is needed, and `at` and `point` both: optional in the type and
+ // required in the schema (`drag_schema`), so that the handler's message is what a caller sees.
+ /// The placement, by id or name. Without it, `path` names the placement.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OccurrenceRef")]
+ pub occurrence: Option<OccurrenceRef>,
+ /// The placement's exact path, as occurrence ids from the top of the design (1 to 64); with
+ /// `occurrence` it must end in it.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OccurrencePath")]
+ pub path: Option<OccurrencePath>,
+ /// The grabbed point on the placement, in world coordinates (mm).
+ #[serde(default, deserialize_with = "at_key", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Point3")]
+ pub at: Option<Point3>,
+ /// Where that point goes, in world coordinates (mm).
+ #[serde(default, deserialize_with = "point_key", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Point3")]
+ pub point: Option<Point3>,
+ /// Reply `continuous`, for a drag that goes on over several calls (the viewport's). It
+ /// changes nothing else. Default: `false`.
+ #[serde(default)]
+ pub continuous: Option<bool>,
+}
+
+/// `occurrence.drag`'s parameters: [`DragKeys`], read as the handler reads them: `path` stands
+/// for `occurrence` when it is missing, and `at` and `point` are asked for together.
+#[derive(Debug)]
+pub struct DragParams(pub DragKeys);
+
+impl<'de> Deserialize<'de> for DragParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let value = Value::deserialize(d)?;
+ if value.is_object() {
+ if value.get("occurrence").is_none() && value.get("path").is_none_or(|path| OccurrencePath::deserialize(path).is_err()) {
+ return Err(D::Error::custom(whole("give `occurrence` or `path` (1..64 occurrence ids)")));
+ }
+ read_stages::<DragKeys, D::Error>(&value, &[&["occurrence", "path"]])?;
+ if value.get("at").is_none() || value.get("point").is_none() {
+ return Err(D::Error::custom(whole("`at` and `point` must both be given")));
+ }
+ }
+ staged(&value, &[&["at"], &["point"]]).map(DragParams)
+ }
+}
+
+wraps_keys!(DragParams, DragKeys, "DragParams");
+
+/// What `occurrence.drag` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct DragResult {
+ /// The placement dragged, by id.
+ pub occurrence: u64,
+ /// Its exact path.
+ pub path: Vec<u64>,
+ /// The occurrences moved: it first, then those a chain of joints carries with it.
+ pub moved: Vec<u64>,
+ /// How far they moved, `point - at` (mm).
+ pub translate: [f64; 3],
+ /// What the call gave as `continuous`.
+ pub continuous: bool,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// Measure an occurrence where its placement puts it, in world coordinates, with what is inside
+/// it unless `descendants` is false: material-aware mass and centre of mass, and volume, density
+/// and inertia for closed, consistently oriented bodies, with totals and principal moments.
+/// Pending moves are included. The design is not changed.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = occurrence_required)]
+pub struct OccurrencePropertiesParams {
+ // Optional in the type and required in the schema (`occurrence_required`).
+ /// The occurrence, by id or name.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OccurrenceRef")]
+ pub occurrence: Option<OccurrenceRef>,
+ /// The occurrence's exact placement, as occurrence ids from the top of the design (1 to 64),
+ /// ending in `occurrence`. Needed when it is nested under several instances.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OccurrencePath")]
+ pub path: Option<OccurrencePath>,
+ /// Include the placements inside it. Default: `true`.
+ #[serde(default, deserialize_with = "descendants_flag", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "bool")]
+ pub descendants: Option<bool>,
+ /// A point in mm, also given the total inertia about it (`total.inertia_about`).
+ #[serde(default, deserialize_with = "about", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<Point3>")]
+ pub about: Option<Point3>,
+}
+
+/// What `occurrence.properties` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct OccurrencePropertiesResult {
+ /// The occurrence, by id.
+ pub occurrence: u64,
+ /// Its name.
+ pub name: Option<String>,
+ #[serde(flatten)]
+ pub properties: PhysicalProperties,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// Move bodies into another component, keeping them where they are in the world. All or
+/// nothing, one undo step; refused while the timeline is rolled back.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = component_and_bodies_required)]
+pub struct MoveBodiesParams {
+ // Optional in the type and required in the schema (`component_and_bodies_required`).
+ /// The bodies, by name.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "DefinitionBodies")]
+ pub bodies: Option<DefinitionBodies>,
+ /// The component they go to, by id or name.
+ #[serde(default, deserialize_with = "component", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ComponentRef")]
+ pub component: Option<ComponentRef>,
+ /// The placement of that component to place them by, as occurrence ids from the top (up to
+ /// 64). A component placed more than once gets them in every instance. Default: its only
+ /// placement, else the active one.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PlacementPath")]
+ pub component_path: Option<PlacementPath>,
+ /// The placement of their component they move from, as occurrence ids from the top (up to
+ /// 64). Default: its only placement, else its first, where its bodies have their own names.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PlacementPath")]
+ pub from_path: Option<PlacementPath>,
+}
+
+/// What `component.move_bodies` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct MoveBodiesResult {
+ /// The bodies that moved.
+ pub bodies: Vec<String>,
+ /// The component they went to, by id.
+ pub component: u64,
+ /// The Body Transfer features that moved them, by id, in the order of `bodies`.
+ pub features: Vec<u64>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// Move sketches into another component. They keep their own coordinates (`component.move_features`
+/// keeps them where they are in the world), except that a sketch on an exactly attached face
+/// stays where it is on the face.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = component_and_sketches_required)]
+pub struct MoveSketchesParams {
+ // Optional in the type and required in the schema (`component_and_sketches_required`): left
+ // out, `null` or empty, the handler refuses the call with its own message.
+ #[serde(default, deserialize_with = "sketch_names")]
+ #[schemars(schema_with = "sketch_names_schema")]
+ pub sketches: Option<super::config::NameList>,
+ /// The component they go to, by id or name.
+ #[serde(default, deserialize_with = "component", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ComponentRef")]
+ pub component: Option<ComponentRef>,
+}
+
+/// What `component.move_sketches` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct MoveSketchesResult {
+ /// The sketches that moved, by feature id.
+ pub sketches: Vec<u64>,
+ /// The component they went to, by id.
+ pub component: u64,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
#[cfg(test)]
#[path = "component_tests.rs"]
mod tests;
diff --git a/crates/engine/src/schema/component_tests.rs b/crates/engine/src/schema/component_tests.rs
index 9ec8eb131b..008e3febcf 100644
--- a/crates/engine/src/schema/component_tests.rs
+++ b/crates/engine/src/schema/component_tests.rs
@@ -4,9 +4,12 @@ use std::sync::Arc;
use serde_json::{Value, json};
use super::{
- ActivateParams, ActivateResult, CreateParams, CreateResult, DeleteParams, DeleteResult, EditInPlaceParams, FinishEditParams, FromBodiesParams,
- FromBodiesResult, ListParams, ListResult, MoveFeaturesParams, MoveSketchesToPartsParams, OccurrenceAlignParams, OccurrenceAlignResult,
- PropertiesParams, PropertiesResult, RenameParams, RenameResult, ReparentItemsParams, UnlockParams, UnlockResult,
+ ActivateParams, ActivateResult, CapturePositionParams, CapturePositionResult, CopyParams, CopyResult, CreateParams, CreateResult, DeleteParams,
+ DeleteResult, DragParams, DragResult, EditInPlaceParams, FinishEditParams, FromBodiesParams, FromBodiesResult, GroundParams, GroundResult,
+ ListParams, ListResult, MoveBodiesParams, MoveBodiesResult, MoveFeaturesParams, MoveParams, MoveResult, MoveSketchesParams, MoveSketchesResult,
+ MoveSketchesToPartsParams, OccurrenceAlignParams, OccurrenceAlignResult, OccurrencePropertiesParams, OccurrencePropertiesResult, PasteNewParams,
+ PasteNewResult, PropertiesParams, PropertiesResult, RenameParams, RenameResult, ReparentItemsParams, RevertPositionParams, RevertPositionResult,
+ UnlockParams, UnlockResult,
};
use crate::Session;
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
@@ -45,6 +48,19 @@ fn schemas_and_the_key_check_agree() {
assert_keys(input_schema_for::<RenameParams>(), &["component", "name"]);
assert_keys(input_schema_for::<DeleteParams>(), &["component"]);
assert_keys(input_schema_for::<UnlockParams>(), &["component"]);
+ assert_keys(input_schema_for::<CapturePositionParams>(), &[]);
+ assert_keys(input_schema_for::<RevertPositionParams>(), &["occurrences"]);
+ assert_keys(input_schema_for::<GroundParams>(), &["grounded", "occurrence", "path"]);
+ assert_keys(input_schema_for::<CopyParams>(), &["component", "in_place", "occurrence", "parent", "parent_path", "path", "translate"]);
+ assert_keys(input_schema_for::<PasteNewParams>(), &["component", "in_place", "occurrence", "parent", "parent_path", "path", "translate"]);
+ assert_keys(
+ input_schema_for::<MoveParams>(),
+ &["angle", "axis", "base_transform", "capture", "matrix", "move_grounded", "occurrence", "origin", "path", "space", "tolerance", "translate"],
+ );
+ assert_keys(input_schema_for::<DragParams>(), &["at", "continuous", "occurrence", "path", "point"]);
+ assert_keys(input_schema_for::<OccurrencePropertiesParams>(), &["about", "descendants", "occurrence", "path"]);
+ assert_keys(input_schema_for::<MoveBodiesParams>(), &["bodies", "component", "component_path", "from_path"]);
+ assert_keys(input_schema_for::<MoveSketchesParams>(), &["component", "sketches"]);
}
/// The calls these commands already refuse (the handlers' own messages), refused alike in strict.
@@ -508,3 +524,587 @@ fn sketches_moved_to_a_part_while_an_exploded_view_is_shown_save_what_they_save_
assert!(at.dist(assembled_at) < 1e-9, "{at:?} vs {assembled_at:?}");
assert!(plane.origin.dist(assembled_plane.origin) < 1e-9, "{plane:?} vs {assembled_plane:?}");
}
+
+// ---------------------------------------------------------------------------------------------
+// The occurrence commands, Capture and Revert Position, Move Bodies and Sketches to Component and
+// Paste New (#13186).
+// ---------------------------------------------------------------------------------------------
+
+/// Two ungrounded parts, `A` (with a box, `ABox`, and a sketch, `S`) and an empty `B`, in the
+/// design: the session at `level`, and the ids of their placements.
+fn two_parts(level: ParamCheck) -> (Session, u64, u64) {
+ let mut s = Session { param_check: level, ..Session::default() };
+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ let a = run("component.create", json!({"name": "A", "parent": 0, "grounded": false}))["occurrence"].as_u64().unwrap_or(0);
+ run("solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "ABox"}));
+ run("sketch.create", json!({"name": "S", "plane": "XY"}));
+ run("sketch.rectangle.two_point", json!({"p0": [1, 1], "p1": [3, 3]}));
+ run("sketch.finish", json!({}));
+ run("component.activate", json!({"component": 0}));
+ let b = run("component.create", json!({"name": "B", "parent": 0, "grounded": false, "activate": false}))["occurrence"].as_u64().unwrap_or(0);
+ (s, a, b)
+}
+
+/// Each case fails today (the handler's message, in Off) and fails the same in strict.
+fn strict_keeps(cases: impl Fn(u64, u64) -> Vec<(&'static str, Value)>) {
+ let (_, a, b) = two_parts(ParamCheck::Off);
+ for (id, p) in cases(a, b) {
+ let error = |level: ParamCheck| two_parts(level).0.execute(id, &p).err().map(|e| e.to_string());
+ let off = error(ParamCheck::Off);
+ assert!(off.is_some(), "{id} {p} should fail today");
+ assert_eq!(error(ParamCheck::Strict), off, "{id} {p}");
+ }
+}
+
+const FLAT_MATRIX: [i32; 12] = [1, 0, 0, 5, 0, 1, 0, 0, 0, 0, 1, 0];
+
+/// What the occurrence commands already refuse (their handlers' own messages), refused alike in
+/// strict, including the keys they read only in some cases.
+#[test]
+fn strict_keeps_todays_errors_of_the_occurrence_commands() {
+ strict_keeps(|a, b| {
+ let at = json!([0, 0, 0]);
+ vec![
+ ("component.revert_position", json!({"occurrences": null})),
+ ("component.revert_position", json!({"occurrences": "1"})),
+ ("component.revert_position", json!({"occurrences": []})),
+ ("component.revert_position", json!({"occurrences": [a, "x"]})),
+ ("component.revert_position", json!({"occurrences": vec![1; 10_001]})),
+ ("component.revert_position", json!({"occurrences": [999]})),
+ ("occurrence.ground", json!({})),
+ ("occurrence.ground", json!({"occurrence": null})),
+ ("occurrence.ground", json!({"occurrence": true})),
+ ("occurrence.ground", json!({"occurrence": "Nope"})),
+ ("occurrence.ground", json!({"occurrence": a, "path": null})),
+ ("occurrence.ground", json!({"occurrence": a, "path": "x"})),
+ ("occurrence.ground", json!({"occurrence": a, "path": []})),
+ ("occurrence.ground", json!({"occurrence": a, "path": vec![a; 65]})),
+ ("occurrence.copy", json!({})),
+ ("occurrence.copy", json!({"component": null})),
+ ("occurrence.copy", json!({"component": [1]})),
+ ("occurrence.copy", json!({"occurrence": null})),
+ ("occurrence.copy", json!({"occurrence": true, "component": "A"})),
+ ("occurrence.copy", json!({"occurrence": a, "path": null})),
+ ("occurrence.copy", json!({"occurrence": a, "path": []})),
+ ("occurrence.copy", json!({"occurrence": a, "parent": null})),
+ ("occurrence.copy", json!({"occurrence": a, "parent": true})),
+ ("occurrence.copy", json!({"occurrence": a, "parent": "Nope"})),
+ ("occurrence.copy", json!({"occurrence": a, "translate": [1, 2]})),
+ ("occurrence.copy", json!({"occurrence": a, "translate": null})),
+ ("occurrence.copy", json!({"occurrence": a, "translate": [1e9, 0, 0]})),
+ ("occurrence.copy", json!({"occurrence": a, "in_place": true, "parent_path": "x"})),
+ ("occurrence.copy", json!({"occurrence": a, "in_place": true, "parent_path": vec![1; 65]})),
+ ("component.paste_new", json!({})),
+ ("component.paste_new", json!({"component": null})),
+ ("component.paste_new", json!({"component": true})),
+ ("component.paste_new", json!({"component": 0})),
+ ("component.paste_new", json!({"component": "A", "occurrence": null})),
+ ("component.paste_new", json!({"component": "A", "occurrence": b})),
+ ("component.paste_new", json!({"component": "A", "occurrence": a, "path": []})),
+ ("component.paste_new", json!({"component": "A", "translate": [1]})),
+ ("component.paste_new", json!({"component": "A", "parent": true})),
+ ("component.paste_new", json!({"component": "A", "parent": "A"})),
+ ("component.paste_new", json!({"component": "A", "in_place": true, "parent_path": 5})),
+ ("occurrence.move", json!({})),
+ ("occurrence.move", json!({"occurrence": null})),
+ ("occurrence.move", json!({"occurrence": [1]})),
+ ("occurrence.move", json!({"occurrence": a, "translate": [1, 2]})),
+ ("occurrence.move", json!({"occurrence": a, "translate": null})),
+ ("occurrence.move", json!({"occurrence": a, "translate": [1e9, 0, 0]})),
+ ("occurrence.move", json!({"occurrence": a, "axis": "z"})),
+ ("occurrence.move", json!({"occurrence": a, "origin": [1, 2, "x"]})),
+ ("occurrence.move", json!({"occurrence": a, "angle": true})),
+ ("occurrence.move", json!({"occurrence": a, "angle": null})),
+ ("occurrence.move", json!({"occurrence": a, "angle": 1, "axis": [0, 0, 0]})),
+ ("occurrence.move", json!({"occurrence": a, "space": "up"})),
+ ("occurrence.move", json!({"occurrence": a, "space": "World"})),
+ ("occurrence.move", json!({"occurrence": a, "space": null})),
+ ("occurrence.move", json!({"occurrence": a, "path": []})),
+ ("occurrence.move", json!({"occurrence": a, "path": null})),
+ ("occurrence.move", json!({"occurrence": a, "base_transform": [[1]]})),
+ ("occurrence.move", json!({"occurrence": a, "base_transform": [[1, 0, 0, 5], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]})),
+ ("occurrence.move", json!({"occurrence": a, "base_transform": [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]]})),
+ ("occurrence.move", json!({"occurrence": a, "matrix": null})),
+ ("occurrence.move", json!({"occurrence": a, "matrix": [1, 2, 3]})),
+ ("occurrence.move", json!({"occurrence": a, "matrix": FLAT_MATRIX, "translate": [1, 0, 0]})),
+ ("occurrence.move", json!({"occurrence": a, "matrix": FLAT_MATRIX, "axis": null})),
+ ("occurrence.move", json!({"occurrence": a, "matrix": FLAT_MATRIX, "angle": 1})),
+ ("occurrence.move", json!({"occurrence": a, "matrix": FLAT_MATRIX, "origin": at})),
+ ("occurrence.move", json!({"occurrence": a, "matrix": FLAT_MATRIX, "tolerance": 0})),
+ ("occurrence.move", json!({"occurrence": a, "matrix": FLAT_MATRIX, "tolerance": "x"})),
+ ("occurrence.move", json!({"occurrence": a, "matrix": FLAT_MATRIX, "tolerance": 0.01})),
+ ("occurrence.move", json!({"occurrence": a, "matrix": [2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]})),
+ ("occurrence.move", json!({"occurrence": a, "matrix": [-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]})),
+ ("occurrence.move", json!({"occurrence": a, "matrix": [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1]})),
+ ("occurrence.drag", json!({})),
+ ("occurrence.drag", json!({"path": "x", "at": at, "point": at})),
+ ("occurrence.drag", json!({"path": [], "at": at, "point": at})),
+ ("occurrence.drag", json!({"occurrence": null, "at": at, "point": at})),
+ ("occurrence.drag", json!({"occurrence": a})),
+ ("occurrence.drag", json!({"occurrence": a, "at": at})),
+ ("occurrence.drag", json!({"occurrence": a, "point": at})),
+ ("occurrence.drag", json!({"occurrence": a, "at": 5})),
+ ("occurrence.drag", json!({"occurrence": a, "path": null, "at": at, "point": at})),
+ ("occurrence.drag", json!({"occurrence": a, "path": [], "at": at, "point": at})),
+ ("occurrence.drag", json!({"occurrence": a, "at": null, "point": at})),
+ ("occurrence.drag", json!({"occurrence": a, "at": at, "point": [1, 2]})),
+ ("occurrence.drag", json!({"occurrence": a, "at": [1e9, 0, 0], "point": at})),
+ ("occurrence.properties", json!({})),
+ ("occurrence.properties", json!({"occurrence": null})),
+ ("occurrence.properties", json!({"occurrence": false})),
+ ("occurrence.properties", json!({"occurrence": a, "path": []})),
+ ("occurrence.properties", json!({"occurrence": a, "path": null})),
+ ("occurrence.properties", json!({"occurrence": a, "descendants": "yes"})),
+ ("occurrence.properties", json!({"occurrence": a, "descendants": null})),
+ ("occurrence.properties", json!({"occurrence": a, "about": [1, 2]})),
+ ("occurrence.properties", json!({"occurrence": a, "about": "origin"})),
+ ("component.move_bodies", json!({})),
+ ("component.move_bodies", json!({"bodies": ["ABox"]})),
+ ("component.move_bodies", json!({"component": null, "bodies": ["ABox"]})),
+ ("component.move_bodies", json!({"component": "B"})),
+ ("component.move_bodies", json!({"component": "B", "bodies": null})),
+ ("component.move_bodies", json!({"component": "B", "bodies": "ABox"})),
+ ("component.move_bodies", json!({"component": "B", "bodies": [1]})),
+ ("component.move_bodies", json!({"component": "B", "bodies": []})),
+ ("component.move_bodies", json!({"component": "B", "bodies": ["ABox", "ABox"]})),
+ ("component.move_bodies", json!({"component": "B", "bodies": vec!["ABox"; 1001]})),
+ ("component.move_bodies", json!({"component": "B", "bodies": ["Nope"]})),
+ ("component.move_bodies", json!({"component": "Nope", "bodies": ["ABox"]})),
+ ("component.move_bodies", json!({"component": "B", "bodies": ["ABox"], "component_path": null})),
+ ("component.move_bodies", json!({"component": "B", "bodies": ["ABox"], "component_path": "x"})),
+ ("component.move_bodies", json!({"component": "B", "bodies": ["ABox"], "component_path": vec![b; 65]})),
+ ("component.move_bodies", json!({"component": "B", "bodies": ["ABox"], "from_path": [b, "x"]})),
+ ("component.move_sketches", json!({})),
+ ("component.move_sketches", json!({"sketches": ["S"]})),
+ ("component.move_sketches", json!({"component": null, "sketches": ["S"]})),
+ ("component.move_sketches", json!({"component": true, "sketches": ["S"]})),
+ ("component.move_sketches", json!({"component": "B"})),
+ ("component.move_sketches", json!({"component": "B", "sketches": null})),
+ ("component.move_sketches", json!({"component": "B", "sketches": []})),
+ ("component.move_sketches", json!({"component": "B", "sketches": 5})),
+ ("component.move_sketches", json!({"component": "B", "sketches": [1]})),
+ ("component.move_sketches", json!({"component": "B", "sketches": ["S", true]})),
+ ("component.move_sketches", json!({"component": "B", "sketches": vec!["S"; 10_001]})),
+ ("component.move_sketches", json!({"component": "B", "sketches": ["Nope"]})),
+ ]
+ });
+}
+
+/// The contracts say what the handlers need, in the schemas: required keys are required though the
+/// types leave them to the handlers' messages, and the ways a command can be called are open.
+#[test]
+fn the_schemas_take_what_the_occurrence_handlers_read() {
+ let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {
+ let schema = schema.as_value();
+ for (p, takes) in cases {
+ assert_eq!(conforms(schema, schema, p), *takes, "{p}");
+ }
+ };
+ let matrix: Vec<i32> = FLAT_MATRIX.to_vec();
+ takes(input_schema_for::<CapturePositionParams>(), &[(json!({}), true), (json!({"x": 1}), false)]);
+ takes(
+ input_schema_for::<RevertPositionParams>(),
+ &[(json!({}), true), (json!({"occurrences": [1, 2]}), true), (json!({"occurrences": []}), false), (json!({"occurrences": ["1"]}), false)],
+ );
+ takes(
+ input_schema_for::<GroundParams>(),
+ &[
+ (json!({"occurrence": 1}), true),
+ (json!({"occurrence": "A:1", "path": [1], "grounded": false}), true),
+ (json!({}), false),
+ (json!({"occurrence": 1, "path": []}), false),
+ (json!({"occurrence": true}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<CopyParams>(),
+ &[
+ (json!({"occurrence": 1}), true),
+ (json!({"component": "A"}), true),
+ (json!({"occurrence": 1, "translate": {"x": 1, "y": 2, "z": 3}, "in_place": true, "parent_path": [], "path": [1], "parent": 0}), true),
+ (json!({}), false),
+ (json!({"occurrence": 1, "translate": [1, 2]}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<PasteNewParams>(),
+ &[
+ (json!({"component": "A"}), true),
+ (
+ json!({"component": 1, "occurrence": 2, "path": [2], "parent": "B", "translate": [1, 2, 3], "in_place": true, "parent_path": [1]}),
+ true,
+ ),
+ (json!({"occurrence": 1}), false),
+ (json!({"component": "A", "translate": [1, 2]}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<MoveParams>(),
+ &[
+ (json!({"occurrence": 1}), true),
+ (json!({"occurrence": 1, "translate": [1, 2, 3], "axis": [0, 0, 1], "angle": "30 deg", "origin": [0, 0, 0], "space": "world"}), true),
+ (json!({"occurrence": 1, "angle": 0.5, "capture": false, "move_grounded": true, "path": [1]}), true),
+ (json!({"occurrence": 1, "matrix": matrix, "tolerance": 1e-6}), true),
+ (json!({"occurrence": 1, "matrix": [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]}), true),
+ (json!({"occurrence": 1, "base_transform": [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]}), true),
+ (json!({}), false),
+ (json!({"occurrence": 1, "matrix": FLAT_MATRIX, "translate": [1, 0, 0]}), false),
+ (json!({"occurrence": 1, "matrix": FLAT_MATRIX, "origin": [1, 0, 0]}), false),
+ (json!({"occurrence": 1, "matrix": [1, 2, 3]}), false),
+ (json!({"occurrence": 1, "space": "up"}), false),
+ (json!({"occurrence": 1, "angle": true}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<DragParams>(),
+ &[
+ (json!({"occurrence": 1, "at": [0, 0, 0], "point": [1, 0, 0]}), true),
+ (json!({"path": [1, 2], "at": {"x": 0, "y": 0, "z": 0}, "point": [1, 0, 0], "continuous": true}), true),
+ (json!({"at": [0, 0, 0], "point": [1, 0, 0]}), false),
+ (json!({"occurrence": 1, "at": [0, 0, 0]}), false),
+ (json!({"occurrence": 1, "point": [0, 0, 0]}), false),
+ (json!({"occurrence": 1, "path": [], "at": [0, 0, 0], "point": [1, 0, 0]}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<OccurrencePropertiesParams>(),
+ &[
+ (json!({"occurrence": 1}), true),
+ (json!({"occurrence": "A:1", "path": [1], "descendants": false, "about": [1, 2, 3]}), true),
+ (json!({"occurrence": 1, "about": null}), true),
+ (json!({}), false),
+ (json!({"occurrence": 1, "descendants": 1}), false),
+ (json!({"occurrence": 1, "about": [1, 2]}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<MoveBodiesParams>(),
+ &[
+ (json!({"component": "B", "bodies": ["A"]}), true),
+ (json!({"component": 2, "bodies": ["A", "B"], "component_path": [1], "from_path": []}), true),
+ (json!({"bodies": ["A"]}), false),
+ (json!({"component": "B"}), false),
+ (json!({"component": "B", "bodies": "A"}), false),
+ (json!({"component": "B", "bodies": ["A"], "from_path": vec![1; 65]}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<MoveSketchesParams>(),
+ &[
+ (json!({"component": "B", "sketches": ["S"]}), true),
+ (json!({"component": "B", "sketches": "S"}), true),
+ (json!({"component": 2, "sketches": ["S", "T"]}), true),
+ (json!({"sketches": ["S"]}), false),
+ (json!({"component": "B"}), false),
+ (json!({"component": "B", "sketches": []}), false),
+ (json!({"component": "B", "sketches": [1]}), false),
+ ],
+ );
+}
+
+/// The types read each key as its handler does: keys the handlers read only in some cases are
+/// read only in those, and a wrong key says what is wrong with it in the handler's words.
+#[test]
+fn the_check_reads_the_occurrence_keys_as_the_handlers_do() {
+ let issues = |id: &str, p: Value| crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect::<Vec<_>>();
+ let none = Vec::<String>::new();
+ // `occurrence.copy`: `component` only without `occurrence`, `parent_path` only with `in_place: true`.
+ assert_eq!(issues("occurrence.copy", json!({"occurrence": 1, "component": [1], "parent_path": "x"})), none);
+ assert_eq!(issues("occurrence.copy", json!({"component": [1]})), ["`component` must be a component id or name"]);
+ assert_eq!(issues("occurrence.copy", json!({"occurrence": null, "component": 1})), ["`occurrence` must be an id or name"]);
+ assert_eq!(issues("occurrence.copy", json!({"occurrence": 1, "in_place": false, "parent_path": "x"})), none);
+ assert_eq!(
+ issues("occurrence.copy", json!({"occurrence": 1, "in_place": true, "parent_path": "x"})),
+ ["`parent_path` must list 0..64 occurrence ids"]
+ );
+ assert_eq!(issues("occurrence.copy", json!({"occurrence": 1, "in_place": true, "parent_path": []})), none);
+ assert_eq!(issues("occurrence.copy", json!({"occurrence": 1, "path": []})), ["`path` must list 1..64 occurrence ids"]);
+ assert_eq!(issues("occurrence.copy", json!({"occurrence": 1, "translate": [1, 2]})), ["translate must contain three finite numbers"]);
+ assert_eq!(issues("occurrence.copy", json!({"occurrence": 1, "in_place": "yes"})).len(), 1);
+ assert_eq!(issues("occurrence.copy", json!({"occurence": 1})), ["unknown key `occurence`; did you mean `occurrence`?"]);
+ // `component.paste_new`: `parent_path` only with `in_place: true`.
+ assert_eq!(issues("component.paste_new", json!({"component": 1, "parent_path": 5})), none);
+ assert_eq!(
+ issues("component.paste_new", json!({"component": 1, "in_place": true, "parent_path": 5})),
+ ["`parent_path` must list 0..64 occurrence ids"]
+ );
+ assert_eq!(issues("component.paste_new", json!({"component": 1, "occurrence": 2, "path": [2], "translate": {"x": 1, "y": 2, "z": 3}})), none);
+ assert_eq!(issues("component.paste_new", json!({"component": 1, "path": []})), ["`path` must list 1..64 occurrence ids"]);
+ assert_eq!(issues("component.paste_new", json!({"component": 1, "parent": null})), ["`parent` must be a component id or name"]);
+ // `occurrence.move`: `tolerance` only with `matrix`, which takes the place of the move keys.
+ assert_eq!(issues("occurrence.move", json!({"occurrence": 1, "tolerance": "x"})), none);
+ assert_eq!(issues("occurrence.move", json!({"occurrence": 1, "matrix": FLAT_MATRIX, "tolerance": 1e-6})), none);
+ assert_eq!(
+ issues("occurrence.move", json!({"occurrence": 1, "matrix": FLAT_MATRIX, "tolerance": "x"})),
+ ["tolerance must be a number above 0 and at most 0.001"]
+ );
+ assert_eq!(
+ issues("occurrence.move", json!({"occurrence": 1, "matrix": FLAT_MATRIX, "translate": "x"})),
+ ["give either matrix or translate, not both"]
+ );
+ assert_eq!(
+ issues("occurrence.move", json!({"occurrence": 1, "matrix": FLAT_MATRIX, "origin": null})),
+ ["give either matrix or origin, not both"]
+ );
+ assert!(issues("occurrence.move", json!({"occurrence": 1, "matrix": [-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]}))[0].starts_with("matrix mirrors"));
+ assert_eq!(
+ issues("occurrence.move", json!({"occurrence": 1, "matrix": [1]})),
+ ["matrix must be 12 numbers (3x4, row by row) or 16 (4x4), flat or as rows"]
+ );
+ assert_eq!(issues("occurrence.move", json!({"occurrence": 1, "translate": [1, 2]})), ["translate must contain three finite numbers"]);
+ assert_eq!(issues("occurrence.move", json!({"occurrence": 1, "axis": null})), ["axis must contain three finite numbers"]);
+ assert_eq!(issues("occurrence.move", json!({"occurrence": 1, "origin": "x"})), ["origin must contain three finite numbers"]);
+ assert_eq!(issues("occurrence.move", json!({"occurrence": 1, "angle": null})), ["angle must be a number or angle expression"]);
+ assert_eq!(issues("occurrence.move", json!({"occurrence": 1, "angle": "30 deg", "axis": {"x": 0, "y": 1, "z": 0}})), none);
+ assert_eq!(issues("occurrence.move", json!({"occurrence": 1, "space": "World"})), ["space must be local or world"]);
+ assert_eq!(issues("occurrence.move", json!({"occurrence": 1, "base_transform": [[1]]})), ["base_transform must be a 4x4 affine matrix"]);
+ assert_eq!(
+ issues("occurrence.move", json!({"occurrence": 1, "base_transform": [[1, 0, 0, 2], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]})),
+ ["base_transform must be finite, affine and invertible"]
+ );
+ assert_eq!(issues("occurrence.move", json!({"occurrence": 1, "capture": "no"})).len(), 1);
+ assert_eq!(issues("occurrence.move", json!({"occurrence": 1, "translte": [1, 0, 0]})), ["unknown key `translte`; did you mean `translate`?"]);
+ // `occurrence.drag`: `path` stands in for `occurrence`, and `at` and `point` come together.
+ let at = json!([0, 0, 0]);
+ assert_eq!(issues("occurrence.drag", json!({"path": [1], "at": at, "point": at})), none);
+ assert_eq!(issues("occurrence.drag", json!({"at": at, "point": at})), ["give `occurrence` or `path` (1..64 occurrence ids)"]);
+ assert_eq!(issues("occurrence.drag", json!({"path": [], "at": at, "point": at})), ["give `occurrence` or `path` (1..64 occurrence ids)"]);
+ assert_eq!(issues("occurrence.drag", json!({"occurrence": 1, "path": [], "at": at, "point": at})), ["`path` must list 1..64 occurrence ids"]);
+ assert_eq!(issues("occurrence.drag", json!({"occurrence": 1, "at": at})), ["`at` and `point` must both be given"]);
+ assert_eq!(issues("occurrence.drag", json!({"occurrence": 1, "at": 5})), ["`at` and `point` must both be given"]);
+ assert_eq!(issues("occurrence.drag", json!({"occurrence": 1, "at": 5, "point": at})), ["at must contain three finite numbers"]);
+ assert_eq!(issues("occurrence.drag", json!({"occurrence": 1, "at": at, "point": [1]})), ["point must contain three finite numbers"]);
+ // The rest.
+ assert_eq!(issues("component.revert_position", json!({"occurrences": []})), ["occurrences must list 1..10000 ids"]);
+ assert_eq!(issues("component.revert_position", json!({"occurrences": null})), ["occurrences must list 1..10000 ids"]);
+ assert_eq!(issues("component.capture_position", json!({"capture": true})), ["unknown key `capture`"]);
+ assert_eq!(issues("occurrence.ground", json!({"occurrence": 1, "grounded": null})), none);
+ assert_eq!(issues("occurrence.ground", json!({"occurrence": 1, "path": []})), ["`path` must list 1..64 occurrence ids"]);
+ assert_eq!(issues("occurrence.properties", json!({"occurrence": 1, "about": [1]})), ["`about` must be a point [x, y, z] in mm"]);
+ assert_eq!(issues("occurrence.properties", json!({"occurrence": 1, "descendants": null})), ["`descendants` must be a boolean"]);
+ assert_eq!(issues("component.move_bodies", json!({"component": 1, "bodies": "A"})), ["bodies must be an array of body names"]);
+ assert_eq!(
+ issues("component.move_bodies", json!({"component": 1, "bodies": ["A"], "from_path": null})),
+ ["`from_path` must list 0..64 occurrence ids"]
+ );
+ assert_eq!(issues("component.move_sketches", json!({"component": 1, "sketches": 5})), ["`sketches` must be a list of names; it is 5"]);
+ assert_eq!(issues("component.move_sketches", json!({"component": 1, "sketches": ["S", 3]})), ["`sketches` must list names; the entry 2 is 3"]);
+ assert_eq!(issues("component.move_sketches", json!({"component": 1, "sketches": null})), ["`sketches` must list sketches"]);
+ assert_eq!(issues("component.move_sketches", json!({"component": 1, "sketches": "S"})), none);
+}
+
+/// A part set up with its placements: the design's grounded `Base`, a free `Plate` (a box, and
+/// the sketch `S`) and an empty free `Spare`.
+fn plates(s: &mut Session) -> (Value, Value, Value) {
+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ let base = run("component.create", json!({"name": "Base"}));
+ run("solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "BaseBox"}));
+ run("component.activate", json!({"component": 0}));
+ let plate = run("component.create", json!({"name": "Plate", "parent": 0, "grounded": false}));
+ run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "body_name": "PlateBox"}));
+ run("sketch.create", json!({"name": "S", "plane": "XY"}));
+ run("sketch.rectangle.two_point", json!({"p0": [21, 1], "p1": [23, 3]}));
+ run("sketch.finish", json!({}));
+ run("component.activate", json!({"component": 0}));
+ let spare = run("component.create", json!({"name": "Spare", "parent": 0, "grounded": false, "activate": false}));
+ (base, plate, spare)
+}
+
+/// Every command, in each form it takes, in Warn: the real reply matches its output schema and
+/// carries no `param_warnings` (Warn runs a call the contract refuses anyway, so the replies are
+/// also checked for warnings), and a key spelt wrongly on purpose is reported.
+#[test]
+fn replies_match_the_output_schemas_of_the_occurrence_commands() {
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let (base, plate, spare) = plates(&mut s);
+ let (base_at, pl, spare_at) = (base["occurrence"].clone(), plate["occurrence"].clone(), spare["occurrence"].clone());
+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+
+ // The placement's name, to give it by name.
+ let listed = run("component.list", json!({}));
+ let plate_name = listed["components"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .flat_map(|c| c["occurrences"].as_array().into_iter().flatten())
+ .find(|o| o["id"] == pl)
+ .map(|o| o["name"].clone())
+ .unwrap_or_default();
+ assert!(plate_name.is_string(), "{listed}");
+
+ // Move Occurrence, in each form.
+ let identity = json!([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]);
+ for p in [
+ json!({"occurrence": pl, "translate": [1, 0, 0]}),
+ json!({"occurrence": pl, "translate": {"x": 0, "y": 1, "z": 0}, "space": "local"}),
+ json!({"occurrence": pl, "space": "world", "path": [pl], "translate": [0, 0, 1]}),
+ json!({"occurrence": pl, "path": [pl], "translate": [0, 0, -1]}),
+ json!({"occurrence": pl, "axis": [0, 0, 1], "angle": "90 deg", "origin": [0, 0, 0]}),
+ json!({"occurrence": pl, "axis": {"x": 0, "y": 1, "z": 0}, "angle": 0.5, "origin": {"x": 1, "y": 1, "z": 1}}),
+ json!({"occurrence": pl, "angle": 0}),
+ json!({"occurrence": pl, "tolerance": "ignored without a matrix"}),
+ json!({"occurrence": pl, "matrix": FLAT_MATRIX}),
+ json!({"occurrence": pl, "matrix": FLAT_MATRIX, "tolerance": 1e-6, "space": "world", "path": [pl]}),
+ json!({"occurrence": pl, "matrix": [[1, 0, 0, 1], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]}),
+ json!({"occurrence": pl, "base_transform": identity, "translate": [3, 0, 0]}),
+ json!({"occurrence": pl, "capture": false, "translate": [0, 2, 0]}),
+ json!({"occurrence": base_at, "translate": [0, 0, 0], "move_grounded": true}),
+ ] {
+ let moved = run("occurrence.move", p.clone());
+ matches(output_schema_for::<MoveResult>(), "occurrence.move", &moved);
+ assert_eq!(moved["pending"], p.get("capture") == Some(&json!(false)), "{p}: {moved}");
+ }
+
+ // Capture and Revert Position.
+ let captured = run("component.capture_position", json!({}));
+ assert_eq!(captured["captured"], 1, "{captured}");
+ matches(output_schema_for::<CapturePositionResult>(), "component.capture_position", &captured);
+ let captured = run("component.capture_position", json!({}));
+ assert_eq!(captured["captured"], 0, "{captured}");
+ matches(output_schema_for::<CapturePositionResult>(), "component.capture_position", &captured);
+ run("occurrence.move", json!({"occurrence": pl, "capture": false, "translate": [0, 2, 0]}));
+ let reverted = run("component.revert_position", json!({"occurrences": [pl]}));
+ assert_eq!(reverted["reverted"], 1, "{reverted}");
+ matches(output_schema_for::<RevertPositionResult>(), "component.revert_position", &reverted);
+ run("occurrence.move", json!({"occurrence": pl, "capture": false, "translate": [0, 2, 0]}));
+ let reverted = run("component.revert_position", json!({}));
+ assert_eq!(reverted["reverted"], 1, "{reverted}");
+ matches(output_schema_for::<RevertPositionResult>(), "component.revert_position", &reverted);
+
+ // Ground.
+ for p in [
+ json!({"occurrence": pl}),
+ json!({"occurrence": pl, "grounded": true, "path": [pl]}),
+ json!({"occurrence": pl, "grounded": null}),
+ json!({"occurrence": pl, "grounded": false}),
+ ] {
+ let grounded = run("occurrence.ground", p.clone());
+ matches(output_schema_for::<GroundResult>(), "occurrence.ground", &grounded);
+ assert_eq!(grounded["occurrence"], pl);
+ }
+
+ // Copy (an instance), in each form. What the handler doesn't read for the form is no problem.
+ for p in [
+ json!({"component": "Plate"}),
+ json!({"component": plate["component"], "translate": [0, 30, 0], "parent": 0}),
+ json!({"occurrence": pl, "translate": [0, 40, 0]}),
+ json!({"occurrence": pl, "component": [1, 2], "parent_path": "ignored"}),
+ json!({"occurrence": plate_name, "path": [pl], "translate": {"x": 0, "y": 0, "z": 5}}),
+ json!({"occurrence": pl, "path": [pl], "in_place": true, "parent_path": [], "translate": [0, 0, 5]}),
+ json!({"occurrence": pl, "in_place": false, "parent_path": "ignored", "parent": 0}),
+ ] {
+ let copy = run("occurrence.copy", p.clone());
+ matches(output_schema_for::<CopyResult>(), "occurrence.copy", &copy);
+ assert_eq!(copy["component"], plate["component"], "{p}: {copy}");
+ }
+
+ // Paste New.
+ for p in [
+ json!({"component": "Plate"}),
+ json!({"component": plate["component"], "occurrence": pl, "translate": [0, 0, 60], "parent": 0}),
+ json!({"component": "Plate", "occurrence": pl, "path": [pl]}),
+ json!({"component": "Plate", "parent_path": "ignored"}),
+ json!({"component": "Plate", "in_place": true, "parent_path": [], "translate": {"x": 5, "y": 0, "z": 0}}),
+ ] {
+ let pasted = run("component.paste_new", p.clone());
+ matches(output_schema_for::<PasteNewResult>(), "component.paste_new", &pasted);
+ assert!(pasted["bodies"].as_u64().is_some_and(|n| n >= 1) && pasted["component"] != plate["component"], "{p}: {pasted}");
+ }
+
+ // Drag.
+ for p in [
+ json!({"occurrence": pl, "at": [25, 5, 5], "point": [25, 15, 5]}),
+ json!({"path": [pl], "at": {"x": 25, "y": 15, "z": 5}, "point": {"x": 25, "y": 5, "z": 5}, "continuous": true}),
+ json!({"occurrence": pl, "path": [pl], "at": [0, 0, 0], "point": [0, 0, 0]}),
+ ] {
+ let dragged = run("occurrence.drag", p.clone());
+ matches(output_schema_for::<DragResult>(), "occurrence.drag", &dragged);
+ assert_eq!(dragged["continuous"], p.get("continuous") == Some(&json!(true)), "{p}: {dragged}");
+ }
+
+ // Occurrence Physical Properties.
+ for p in [
+ json!({"occurrence": pl}),
+ json!({"occurrence": pl, "path": [pl], "descendants": false}),
+ json!({"occurrence": pl, "about": [1, 2, 3]}),
+ json!({"occurrence": plate_name, "about": {"x": 1, "y": 2, "z": 3}, "descendants": true}),
+ json!({"occurrence": base_at, "about": null}),
+ ] {
+ let measured = run("occurrence.properties", p.clone());
+ matches(output_schema_for::<OccurrencePropertiesResult>(), "occurrence.properties", &measured);
+ assert!(measured["name"].is_string() && measured["total"]["volume_mm3"].as_f64().is_some_and(|v| v > 0.0), "{p}: {measured}");
+ assert_eq!(measured["total"].get("inertia_about").is_some(), p.get("about").is_some_and(|a| !a.is_null()), "{p}: {measured}");
+ }
+
+ // Move Bodies to Component, and Move Sketches to Component.
+ let moved = run("component.move_bodies", json!({"bodies": ["BaseBox"], "component": "Spare"}));
+ assert_eq!(moved["features"].as_array().map(Vec::len), Some(1), "{moved}");
+ matches(output_schema_for::<MoveBodiesResult>(), "component.move_bodies", &moved);
+ let moved =
+ run("component.move_bodies", json!({"bodies": ["BaseBox"], "component": "Base", "component_path": [base_at], "from_path": [spare_at]}));
+ matches(output_schema_for::<MoveBodiesResult>(), "component.move_bodies", &moved);
+ let moved = run("component.move_sketches", json!({"sketches": ["S"], "component": "Spare"}));
+ assert_eq!(moved["component"], spare["component"], "{moved}");
+ matches(output_schema_for::<MoveSketchesResult>(), "component.move_sketches", &moved);
+ let moved = run("component.move_sketches", json!({"sketches": "S", "component": "Base"}));
+ matches(output_schema_for::<MoveSketchesResult>(), "component.move_sketches", &moved);
+
+ // Misspelt keys still run in Warn, say so, and the reply still matches.
+ run("occurrence.move", json!({"occurrence": pl, "capture": false, "translate": [0, 2, 0]}));
+ let cases: [(&str, Value, &str, schemars::Schema); 9] = [
+ ("component.capture_position", json!({"captrue": true}), "captrue", output_schema_for::<CapturePositionResult>()),
+ ("component.revert_position", json!({"occurence": [pl]}), "occurence", output_schema_for::<RevertPositionResult>()),
+ ("occurrence.copy", json!({"component": "Plate", "translat": [1, 0, 0]}), "translat", output_schema_for::<CopyResult>()),
+ ("component.paste_new", json!({"component": "Plate", "paretn": 0}), "paretn", output_schema_for::<PasteNewResult>()),
+ ("occurrence.move", json!({"occurrence": pl, "translte": [1, 0, 0]}), "translte", output_schema_for::<MoveResult>()),
+ (
+ "occurrence.drag",
+ json!({"occurrence": pl, "at": [0, 0, 0], "point": [1, 0, 0], "contiuous": true}),
+ "contiuous",
+ output_schema_for::<DragResult>(),
+ ),
+ ("occurrence.properties", json!({"occurrence": pl, "descendents": false}), "descendents", output_schema_for::<OccurrencePropertiesResult>()),
+ (
+ "component.move_bodies",
+ json!({"bodies": ["BaseBox"], "component": "Spare", "compnent_path": [spare_at]}),
+ "compnent_path",
+ output_schema_for::<MoveBodiesResult>(),
+ ),
+ (
+ "component.move_sketches",
+ json!({"sketches": ["S"], "component": "Plate", "componnt": 1}),
+ "componnt",
+ output_schema_for::<MoveSketchesResult>(),
+ ),
+ ];
+ for (id, p, key, schema) in cases {
+ let warned = run(id, p);
+ let warnings = warned["param_warnings"].as_array().cloned().unwrap_or_default();
+ assert!(warnings.len() == 1 && warnings[0].as_str().is_some_and(|w| w.contains(key)), "{id}: {warned}");
+ assert!(conforms(schema.as_value(), schema.as_value(), &warned), "{id}: {warned}");
+ }
+ // Last, as it toggles the placement's grounding.
+ let warned = run("occurrence.ground", json!({"occurrence": pl, "grouned": true}));
+ let schema = output_schema_for::<GroundResult>();
+ assert!(warned["param_warnings"].as_array().is_some_and(|w| w.len() == 1 && w[0].as_str().is_some_and(|w| w.contains("grouned"))), "{warned}");
+ assert!(conforms(schema.as_value(), schema.as_value(), &warned), "{warned}");
+}
+
+/// A move that joints undo replies with `reverted` and a `warning`, which the output schema
+/// describes.
+#[test]
+fn a_move_its_joints_undo_matches_the_output_schema() {
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ let base = run("component.create", json!({"name": "Base"}))["occurrence"].clone();
+ run("solid.box", json!({"length": 10, "width": 10, "height": 10}));
+ run("component.activate", json!({"component": 0}));
+ let plate = run("component.create", json!({"name": "Plate", "parent": 0, "grounded": false}))["occurrence"].clone();
+ run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0]}));
+ run("component.activate", json!({"component": 0}));
+ run("joint.as_built", json!({"type": "rigid", "a": base, "b": plate, "name": "Mount"}));
+ let moved = run("occurrence.move", json!({"occurrence": plate, "translate": [0, 0, 30]}));
+ assert_eq!(moved["reverted"], true, "{moved}");
+ assert!(moved["warning"].as_str().is_some_and(|w| w.contains("Mount")), "{moved}");
+ matches(output_schema_for::<MoveResult>(), "occurrence.move", &moved);
+}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index 3805c527a0..77637d29cb 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -2,11 +2,6 @@
# (coverage_tests.rs). This list only shrinks: when you give a command its contract and output
# type, remove its line. Never add one: a new command comes with both schemas. Sorted, one id
# per line.
-component.capture_position
-component.move_bodies
-component.move_sketches
-component.paste_new
-component.revert_position
doc.open
doc.recover
doc.recovery_discard
@@ -28,11 +23,6 @@ motion.plot
motion.trace
motion.trace.edit
motion.trace.keep
-occurrence.copy
-occurrence.drag
-occurrence.ground
-occurrence.move
-occurrence.properties
render.aging.describe
render.backends
render.cancel