SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
fix: retain circular sketch pattern Quantity expressions (#4435) (#4607)
Reefwalker3ed1829cc721
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rsindex 803c619765..9ce48004cf 100644--- a/crates/doc/src/document.rs+++ b/crates/doc/src/document.rs@@ -3478,6 +3478,24 @@ impl Document {Ok(())}+ /// Resolve circular Quantity expressions before solving. Rebuilding the copies here also+ /// covers cold document evaluation and configuration changes, without an engine dependency.+ pub fn apply_pattern_quantities(&self, vals: &std::collections::BTreeMap<String, expr::Value>, sk: &mut Sketch) -> Result<()> {+ let counts: Vec<_> = sk+ .patterns+ .iter()+ .filter_map(|p| p.count_expression.as_ref().map(|e| (p.id.clone(), e)))+ .map(|(id, e)| {+ let n = crate::eval::val(vals, e, Kind::Unitless)?;+ Ok((id, solidcraft_sketch::SketchPattern::circular_quantity(n)?))+ })+ .collect::<Result<_>>()?;+ for (id, count) in counts {+ sk.resize_circular_pattern(&id, count)?;+ }+ Ok(())+ }+/// Move the points placed by parameters to where their expressions come to (in place). Such/// a point is fixed, so the solve keeps it there.pub fn apply_point_values(&self, vals: &std::collections::BTreeMap<String, expr::Value>, sk: &mut Sketch) -> Result<()> {@@ -3564,6 +3582,7 @@ impl Document {moved_from: Option<&Sketch>,analysis: solidcraft_sketch::Analysis,) -> Result<solidcraft_sketch::SolveReport> {+ self.apply_pattern_quantities(vals, sk)?;self.apply_dimension_values(vals, sk)?;let was = |sk: &Sketch| moved_from.and_then(|from| sk.positions_in(from));let offsets = !sk.offsets.is_empty() || !sk.freeform_offsets.is_empty();diff --git a/crates/doc/src/format/pending/sketch-circular-quantity-expression.rs b/crates/doc/src/format/pending/sketch-circular-quantity-expression.rsnew file mode 100644index 0000000000..62b120ed8a--- /dev/null+++ b/crates/doc/src/format/pending/sketch-circular-quantity-expression.rs@@ -0,0 +1,3 @@+//! Circular sketch patterns may retain a Quantity expression alongside their evaluated count.+//! Older designs have no expression and keep their fixed counts unchanged. The previous+//! release must request an update rather than discard the expression on save.diff --git a/crates/doc/src/params.rs b/crates/doc/src/params.rsindex 1ec392c431..5f4f0ddb54 100644--- a/crates/doc/src/params.rs+++ b/crates/doc/src/params.rs@@ -76,6 +76,9 @@ impl FeatureKind {ExprRole::Placement => placement.push(e.as_str()),});inputs.extend(placement);+ if let FeatureKind::Sketch { sketch, .. } = self {+ inputs.extend(sketch.patterns.iter().filter_map(|p| p.count_expression.as_deref()));+ }inputs}}@@ -694,6 +697,11 @@ impl Document {out.push(ParamUser::Dimension { feature: f.id, name: f.name.clone(), constraint: c.id.clone() });}}+ for pattern in &sketch.patterns {+ if pattern.count_expression.as_ref().is_some_and(|e| expr::references(e).iter().any(|r| r == name)) {+ out.push(ParamUser::Feature { feature: f.id, name: f.name.clone(), input: format!("{} Quantity", pattern.id) });+ }+ }for (what, e) in sketch.text_exprs() {if expr::references(e).iter().any(|r| r == name) {out.push(ParamUser::Feature { feature: f.id, name: f.name.clone(), input: what.to_string() });@@ -783,6 +791,13 @@ impl Document {n += 1;}}+ for e in sketch.patterns.iter_mut().filter_map(|p| p.count_expression.as_mut()) {+ let r = expr::rename_reference(e, old, new);+ if r != *e {+ *e = r;+ n += 1;+ }+ }for e in sketch.text_exprs_mut() {let r = expr::rename_reference(e, old, new);if r != *e {@@ -853,6 +868,7 @@ impl Document {if let FeatureKind::Sketch { sketch, .. } = &f.kind {names.extend(sketch.constraints.iter().filter_map(|c| c.param.clone()));names.extend(sketch.text_exprs().into_iter().flat_map(|(_, e)| expr::references(e)));+ names.extend(sketch.patterns.iter().filter_map(|p| p.count_expression.as_deref()).flat_map(expr::references));}out.extend(names.into_iter().map(|n| (format!("Feature:{}", f.name), n)));}diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rsindex 16f829edf1..0551783137 100644--- a/crates/engine/src/cmd/sketch.rs+++ b/crates/engine/src/cmd/sketch.rs@@ -278,6 +278,9 @@ pub(super) fn edit_solved<T>() -> Result<(T, Option<SolveReport>)> {let mut doc = (*s.doc).clone();let mut sk = doc.sketch(id)?.clone();+ if sk.patterns.iter().any(|p| p.count_expression.is_some()) {+ doc.apply_pattern_quantities(&doc.param_values().0, &mut sk)?;+ }super::sketch_project::refresh(s, &doc, id, &mut sk);// The stored sketch is solved for its stored values.let stored = sk.driving_values();diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rsindex b998d3c4d3..a70f51e8cf 100644--- a/crates/engine/src/cmd/sketch_modify.rs+++ b/crates/engine/src/cmd/sketch_modify.rs@@ -95,7 +95,7 @@ pub static COMMANDS: &[CommandSpec] = &[.at("SKETCH", "PATTERN").icon("sketch_circ_pattern").enabled(in_sketch)- .params(concat!("entities: [ids], center: [x,y] or point ref, count: 2…500, angle?: total deg (default 360); alignment?: left|center|right (default right); reversed?: bool (default false). Quantity includes the original. Center balances copies around it; reversed flips the direction and extra side for even totals. Partial arcs span angle with angle/(count-1) spacing; full turns use angle/count. Adds associative pattern constraints; a coordinate center creates a constrainable point. Returns pattern and center ids. pattern?: existing pattern id to edit (omitted values retained; surviving instance ids retained)", created_doc!())),+ .params(concat!("entities: [ids], center: [x,y] or point ref, count: 2…500 (number or unitless expression, retained through edits), angle?: total deg (default 360); alignment?: left|center|right (default right); reversed?: bool (default false). Quantity includes the original. Center balances copies around it; reversed flips the direction and extra side for even totals. Partial arcs span angle with angle/(count-1) spacing; full turns use angle/count. Adds associative pattern constraints; a coordinate center creates a constrainable point. Returns pattern and center ids. pattern?: existing pattern id to edit (omitted values retained; surviving instance ids retained)", created_doc!())),CommandSpec::new("sketch.pattern.rectangular", "Rectangular Pattern", pattern_rect).at("SKETCH", "PATTERN").icon("sketch_rect_pattern")diff --git a/crates/engine/src/cmd/sketch_pattern.rs b/crates/engine/src/cmd/sketch_pattern.rsindex bb9282796a..71f9c08cf5 100644--- a/crates/engine/src/cmd/sketch_pattern.rs+++ b/crates/engine/src/cmd/sketch_pattern.rs@@ -7,7 +7,7 @@ use crate::cmd::{alignment_param, reversed_param};pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result<Value> {let cmd = if circular { "sketch.pattern.circular" } else { "sketch.pattern.rectangular" };- let (out, info) = edit(s, p, cmd, true, |sk, _| {+ let (out, info) = edit(s, p, cmd, true, |sk, doc| {if sk.patterns.len() >= solidcraft_sketch::MAX_CONSTRAINTS {return Err(bad(cmd, "too many sketch patterns"));}@@ -25,7 +25,7 @@ pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result<Value> {}let defaults = match &old.kind {SketchPatternKind::Circular { center, count, angle, alignment, reversed } => {- json!({"entities":old.entities,"center":center,"count":count,"angle":angle,"alignment":alignment,"reversed":reversed})+ json!({"entities":old.entities,"center":center,"count":old.count_expression.as_ref().map_or_else(|| json!(count), |e| json!(e)),"angle":angle,"alignment":alignment,"reversed":reversed})}SketchPatternKind::Rectangular {dir,@@ -75,7 +75,23 @@ pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result<Value> {return Err(bad(cmd, "the pattern has deleted geometry or relations; undo the deletion before editing it"));}}+ let count_expression = if circular {+ match params.get("count") {+ Some(Value::String(expression)) => {+ let expression = expression.trim().to_string();+ let value = doc.eval(&expression, solidcraft_doc::expr::Kind::Unitless)?;+ params["count"] = json!(SketchPattern::circular_quantity(value)?);+ Some(expression)+ }+ _ => None,+ }+ } else {+ None+ };let n = count(¶ms, "count", cmd)?;+ if count_expression.is_some() && n < 2 {+ return Err(bad(cmd, "circular pattern Quantity must be 2…500"));+ }let (kind, center, slots) = if circular {let total = if params.get("angle").is_some() { num(¶ms, "angle").ok_or_else(|| bad(cmd, "`angle` must be finite"))? } else { 360.0 };if !(total.abs() > 1e-9 && total.abs() <= 360.0) {@@ -235,7 +251,7 @@ pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result<Value> {instances.push(instance);}let center_id = center.and_then(|i| sk.points.get(i)).map(|p| p.id.clone());- let pattern = SketchPattern { id: id.clone(), entities: entity_ids, kind, instances };+ let pattern = SketchPattern { id: id.clone(), entities: entity_ids, kind, count_expression, instances };if let Some(i) = old_index {sk.patterns.insert(i.min(sk.patterns.len()), pattern);} else {diff --git a/crates/engine/src/cmd/sketch_pattern_tests.rs b/crates/engine/src/cmd/sketch_pattern_tests.rsindex 0e3a15dfda..ef4e66f66d 100644--- a/crates/engine/src/cmd/sketch_pattern_tests.rs+++ b/crates/engine/src/cmd/sketch_pattern_tests.rs@@ -558,3 +558,101 @@ fn patterned_arc_ellipse_spline_and_conic_follow_seed_geometry_exactly() {assert!(solidcraft_doc::format::read(&s.doc.to_json()).is_ok());}}++#[test]+fn circular_quantity_expression_survives_parameter_edits_undo_and_reopen() {+ let mut s = new_sketch();+ run(&mut s, "parameters.add", json!({"name":"HoleAmount","expression":"5","unit":""}));+ run(&mut s, "sketch.circle.center", json!({"center":[20,0],"radius":2,"id":"seed"}));+ let out = run(&mut s, "sketch.pattern.circular", json!({"entities":["seed"],"center":"origin","count":"HoleAmount"}));+ let original = sketch(&s).patterns[0].instances.clone();+ assert_eq!(sketch(&s).curves.len(), 5);+ run(&mut s, "parameters.change", json!({"name":"HoleAmount","expression":"7"}));+ let expanded = sketch(&s);+ assert_eq!(expanded.curves.len(), 7);+ assert_eq!(expanded.patterns[0].count_expression.as_deref(), Some("HoleAmount"));+ for (before, after) in original.iter().zip(&expanded.patterns[0].instances) {+ assert_eq!(before.curves, after.curves);+ assert_eq!(before.points, after.points);+ assert_eq!(before.constraints, after.constraints);+ }+ let expected = Vec2::new(20.0 * (std::f64::consts::TAU / 7.0).cos(), 20.0 * (std::f64::consts::TAU / 7.0).sin());+ assert!(point(&expanded, &format!("{}.center", original[0].curves[0])).dist(expected) < 1e-6);+ run(&mut s, "edit.undo", json!({}));+ assert_eq!(sketch(&s).curves.len(), 5);+ run(&mut s, "edit.redo", json!({}));+ assert_eq!(sketch(&s).curves.len(), 7);+ run(&mut s, "parameters.rename", json!({"name":"HoleAmount","new_name":"holes"}));+ assert_eq!(sketch(&s).patterns[0].count_expression.as_deref(), Some("holes"));+ assert!(s.execute("parameters.delete", &json!({"name":"holes"})).is_err());+ let saved = s.doc.to_json();+ // A cold evaluation must rebuild from the expression even when no engine value-edit+ // command has materialized the new copies into the document yet.+ let mut cold_doc = (*s.doc).clone();+ cold_doc.change_param("holes", "9", None, None).unwrap();+ let mut cold =+ Session { doc: solidcraft_doc::format::read(&cold_doc.to_json()).unwrap().into(), active_sketch: s.active_sketch, ..Default::default() };+ cold.refresh();+ assert_eq!(sketch(&cold).curves.len(), 9);+ let mut reopened = Session { doc: solidcraft_doc::format::read(&saved).unwrap().into(), active_sketch: s.active_sketch, ..Default::default() };+ reopened.refresh();+ assert_eq!(sketch(&reopened).curves.len(), 7);+ run(&mut reopened, "parameters.change", json!({"name":"holes","expression":"3"}));+ assert_eq!(sketch(&reopened).curves.len(), 3);+ run(&mut reopened, "sketch.pattern.circular", json!({"pattern":out["pattern"],"reversed":true}));+ assert_eq!(sketch(&reopened).patterns[0].count_expression.as_deref(), Some("holes"));+ run(&mut reopened, "sketch.pattern.circular", json!({"pattern":out["pattern"],"count":4}));+ assert!(sketch(&reopened).patterns[0].count_expression.is_none());+ run(&mut reopened, "parameters.change", json!({"name":"holes","expression":"6"}));+ assert_eq!(sketch(&reopened).curves.len(), 4);+}++#[test]+fn circular_quantity_rejects_invalid_expressions_and_parameter_changes_atomically() {+ let mut s = new_sketch();+ run(&mut s, "parameters.add", json!({"name":"holes","expression":"5","unit":""}));+ run(&mut s, "sketch.circle.center", json!({"center":[20,0],"radius":2,"id":"seed"}));+ for expression in ["missing", "5 mm", "1", "0", "-3", "3.5", "501", "1e309"] {+ let before = s.doc.to_json();+ assert!(s.execute("sketch.pattern.circular", &json!({"entities":["seed"],"center":"origin","count":expression})).is_err(), "{expression}");+ assert_eq!(s.doc.to_json(), before);+ }+ run(&mut s, "sketch.pattern.circular", json!({"entities":["seed"],"center":"origin","count":"holes + 1e-10"}));+ for expression in ["1", "0", "-3", "3.5", "501", "5 mm", "1e309"] {+ let before = s.doc.to_json();+ assert!(s.execute("parameters.change", &json!({"name":"holes","expression":expression})).is_err(), "{expression}");+ assert_eq!(s.doc.to_json(), before, "rejected {expression} leaves the document unchanged");+ assert_eq!(sketch(&s).curves.len(), 5);+ }+}++#[test]+fn circular_quantity_changes_keep_partial_full_centered_and_reversed_placements() {+ for angle in [90.0_f64, -90.0, 360.0, -360.0] {+ for alignment in ["right", "left", "center"] {+ for reversed in [false, true] {+ let mut s = new_sketch();+ run(&mut s, "parameters.add", json!({"name":"holes","expression":"4","unit":""}));+ run(&mut s, "sketch.circle.center", json!({"center":[20,0],"radius":2,"id":"seed"}));+ run(+ &mut s,+ "sketch.pattern.circular",+ json!({"entities":["seed"],"center":"origin","count":"holes","angle":angle,"alignment":alignment,"reversed":reversed}),+ );+ for count in [6, 3] {+ run(&mut s, "parameters.change", json!({"name":"holes","expression":count}));+ let sk = sketch(&s);+ let solidcraft_sketch::SketchPatternKind::Circular { alignment, .. } = sk.patterns[0].kind else { panic!("circular pattern") };+ let step = angle / if angle.abs() == 360.0 { count as f64 } else { (count - 1) as f64 };+ for instance in &sk.patterns[0].instances {+ let a = (step * alignment.multiplier(instance.index[0], reversed)).to_radians();+ let expected = Vec2::new(20.0 * a.cos(), 20.0 * a.sin());+ assert!(point(&sk, &format!("{}.center", instance.curves[0])).dist(expected) < 1e-6);+ }+ sk.validate_patterns().unwrap();+ check_relations(&s);+ }+ }+ }+ }+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex edd100e8a8..1e82cdf186 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -761,6 +761,28 @@ impl Session {/// as before. Otherwise store each sketch whose values changed as solved, so the next edit/// continues from it (see `Model::adopt_solved_sketches`).pub(crate) fn settle_value_edit(&mut self, solved_before: &SketchValues) -> Result<()> {+ // Quantity changes alter topology, so store the regenerated instances in the same+ // transaction as the parameter edit. Later picks and undo must see those same ids.+ let mut updated: Vec<_> = self+ .doc+ .features+ .iter()+ .filter_map(|feature| match &feature.kind {+ solidcraft_doc::FeatureKind::Sketch { sketch, .. } if sketch.patterns.iter().any(|p| p.count_expression.is_some()) => {+ Some((feature.id, sketch.clone()))+ }+ _ => None,+ })+ .collect();+ if !updated.is_empty() {+ let (vals, _) = self.doc.param_values();+ for (_, sketch) in &mut updated {+ self.doc.apply_pattern_quantities(&vals, sketch)?;+ }+ }+ for (id, sketch) in updated {+ *self.doc_mut().sketch_mut(id)? = sketch;+ }self.refresh();for r in &self.model.results {let (Some(before), Some(k)) = (solved_before.get(&r.id), r.state.sketch(r.id)) else { continue };@@ -1214,5 +1236,14 @@ pub(crate) type SketchValues = std::collections::BTreeMap<u64, std::collections:/// The values of a sketch's driving dimensions that come from parameters: what a value edit/// changes in it (as opposed to geometry it projects or links from upstream).fn own_values(sk: &solidcraft_sketch::Sketch) -> std::collections::BTreeMap<String, f64> {- sk.constraints.iter().filter(|c| c.param.is_some() && !c.driven).filter_map(|c| Some((c.id.clone(), c.kind.value()?))).collect()+ let mut values: std::collections::BTreeMap<_, _> =+ sk.constraints.iter().filter(|c| c.param.is_some() && !c.driven).filter_map(|c| Some((c.id.clone(), c.kind.value()?))).collect();+ for pattern in &sk.patterns {+ if pattern.count_expression.is_some()+ && let solidcraft_sketch::SketchPatternKind::Circular { count, .. } = pattern.kind+ {+ values.insert(format!("pattern:{}:count", pattern.id), count as f64);+ }+ }+ values}diff --git a/crates/sketch/src/pattern.rs b/crates/sketch/src/pattern.rsindex 79cf990b1a..47a6b89fb3 100644--- a/crates/sketch/src/pattern.rs+++ b/crates/sketch/src/pattern.rs@@ -77,10 +77,22 @@ pub struct SketchPattern {pub id: String,pub entities: Vec<String>,pub kind: SketchPatternKind,+ /// Authored circular Quantity expression; absent for legacy and fixed-count patterns.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub count_expression: Option<String>,pub instances: Vec<PatternInstance>,}impl SketchPattern {+ /// Resolve an evaluated circular Quantity with the dialog's whole-number tolerance.+ pub fn circular_quantity(value: f64) -> Result<usize, SketchError> {+ let count = value.round();+ if !value.is_finite() || !(1.0..=500.0).contains(&value) || count < 2.0 || (value - count).abs() > 1e-9 {+ return Err(SketchError::Invalid("circular pattern Quantity must be a whole number from 2 to 500".into()));+ }+ Ok(count as usize)+ }+pub fn contains(&self, entity: &str) -> bool {self.entities.iter().any(|id| id == entity)|| self@@ -94,6 +106,122 @@ impl SketchPattern {}impl Sketch {+ /// Rebuild a circular pattern after its Quantity expression changes. Surviving slots keep+ /// their ids; new slots are copied from the authored seed. The caller owns the edit transaction.+ pub fn resize_circular_pattern(&mut self, id: &str, count: usize) -> Result<(), SketchError> {+ if !(2..=500).contains(&count) {+ return Err(SketchError::Invalid("circular pattern Quantity must be 2…500".into()));+ }+ self.validate_patterns()?;+ let index = self.patterns.iter().position(|p| p.id == id).ok_or_else(|| SketchError::Invalid("missing sketch pattern".into()))?;+ let mut pattern = self.patterns.remove(index);+ let SketchPatternKind::Circular { center, count: previous, angle, alignment, reversed } = &mut pattern.kind else {+ return Err(SketchError::Invalid("Quantity expression requires a circular pattern".into()));+ };+ if *previous == count {+ self.patterns.insert(index, pattern);+ return Ok(());+ }+ *previous = count;+ let (center_id, total, alignment, reversed) = (center.clone(), *angle, *alignment, *reversed);+ for instance in pattern.instances.iter().filter(|i| i.index[0] >= count) {+ let curves: Vec<_> = instance.curves.iter().filter_map(|id| self.curve_index(id)).collect();+ self.constraints.retain(|c| !instance.constraints.contains(&c.id));+ self.remove_curves(&curves);+ let points: Vec<_> = instance.points.iter().filter_map(|(_, id)| self.resolve_point(id)).collect();+ self.remove_points(&points);+ }+ pattern.instances.retain(|i| i.index[0] < count);+ let center = self.resolve_point(¢er_id).ok_or_else(|| SketchError::Invalid("missing pattern center".into()))?;+ let origin = self.point(center).ok_or_else(|| SketchError::Invalid("missing pattern center".into()))?;+ let step = total / if (total.abs() - 360.0).abs() < 1e-9 { count as f64 } else { (count - 1) as f64 };+ for slot in 1..count {+ let angle = (step * alignment.multiplier(slot, reversed)).to_radians();+ let (sin, cos) = angle.sin_cos();+ let transform = |p: Vec2| {+ let d = p - origin;+ origin + Vec2::new(d.x * cos - d.y * sin, d.x * sin + d.y * cos)+ };+ if let Some(instance) = pattern.instances.iter().find(|i| i.index == [slot, 0]) {+ for cid in &instance.constraints {+ if let Some(crate::ConstraintKind::PatternPoint { angle: value, .. }) =+ self.constraints.iter_mut().find(|c| c.id == *cid).map(|c| &mut c.kind)+ {+ *value = angle;+ }+ }+ for (seed, copy) in &instance.points {+ let p =+ self.resolve_point(seed).and_then(|p| self.point(p)).ok_or_else(|| SketchError::Invalid("missing pattern seed".into()))?;+ let q = self+ .resolve_point(copy)+ .and_then(|p| self.points.get_mut(p))+ .ok_or_else(|| SketchError::Invalid("missing pattern copy".into()))?;+ q.pos = transform(p);+ }+ continue;+ }+ let curves: Vec<_> = pattern.entities.iter().filter_map(|id| self.curve_index(id)).collect();+ let mut points = Vec::new();+ for id in &pattern.entities {+ if let Some(c) = self.curve_index(id).and_then(|i| self.curves.get(i)) {+ points.extend(c.kind.point_ids());+ } else if let Some(p) = self.resolve_point(id) {+ points.push(p);+ } else {+ return Err(SketchError::Invalid("missing pattern entity".into()));+ }+ }+ let mut map = Vec::new();+ for p in points {+ if map.iter().any(|(seed, _)| *seed == p) {+ continue;+ }+ let pos = self.point(p).ok_or_else(|| SketchError::Invalid("missing pattern point".into()))?;+ map.push((p, self.add_point(transform(pos), None)?));+ }+ if self.curves.len().saturating_add(curves.len()) > crate::MAX_CURVES {+ return Err(SketchError::TooLarge);+ }+ let mut made = Vec::new();+ for source in &curves {+ let mut copy = self.curves.get(*source).cloned().ok_or_else(|| SketchError::Invalid("missing pattern curve".into()))?;+ copy.kind.map_points(&|p| map.iter().find(|(seed, _)| *seed == p).map_or(p, |(_, q)| *q));+ let prefix = match copy.kind {+ CurveKind::Line { .. } => "l",+ CurveKind::Circle { .. } => "c",+ CurveKind::Arc { .. } => "a",+ CurveKind::Ellipse { .. } => "e",+ CurveKind::Spline { .. } => "s",+ CurveKind::Conic { .. } => "k",+ };+ copy.id = self.fresh(prefix)?;+ copy.link = None;+ copy.fixed = false;+ copy.centerline = false;+ made.push(copy.id.clone());+ self.curves.push(copy);+ }+ let mut constraints = Vec::new();+ for (p, q) in &map {+ constraints.push(self.add_constraint(+ crate::ConstraintKind::PatternPoint { p: *p, q: *q, center: Some(center), angle, offset: Vec2::ZERO, directions: [None; 2] },+ None,+ )?);+ }+ for (source, copy) in curves.iter().zip(&made) {+ if matches!(self.curves.get(*source).map(|c| &c.kind), Some(CurveKind::Circle { .. } | CurveKind::Ellipse { .. })) {+ let b = self.curve_index(copy).ok_or_else(|| SketchError::Invalid("missing pattern curve".into()))?;+ constraints.push(self.add_constraint(crate::ConstraintKind::PatternRadius { a: *source, b }, None)?);+ }+ }+ let points = map.iter().filter_map(|(p, q)| Some((self.points.get(*p)?.id.clone(), self.points.get(*q)?.id.clone()))).collect();+ pattern.instances.push(PatternInstance { index: [slot, 0], curves: made, points, constraints });+ }+ self.patterns.insert(index.min(self.patterns.len()), pattern);+ self.validate_patterns()+ }+/// Start an explicit Move/Scale of seed geometry with its copies already transformed./// Interactive drags instead leave the ordinary relations to the held-point solver,/// which also supports dragging an instance back through its seed.@@ -215,6 +343,11 @@ impl Sketch {}let mut ids = std::collections::BTreeSet::new();for pattern in &self.patterns {+ if pattern.count_expression.as_ref().is_some_and(|e| e.trim().is_empty() || e.len() > 4096)+ || (pattern.count_expression.is_some() && !matches!(pattern.kind, SketchPatternKind::Circular { .. }))+ {+ return Err(SketchError::Invalid("invalid circular pattern Quantity expression".into()));+ }if pattern.id.is_empty()|| pattern.id.len() > 512|| !ids.insert(&pattern.id)diff --git a/crates/ui-egui/src/sketch_modify_ui.rs b/crates/ui-egui/src/sketch_modify_ui.rsindex dcfba56361..be2263c98d 100644--- a/crates/ui-egui/src/sketch_modify_ui.rs+++ b/crates/ui-egui/src/sketch_modify_ui.rs@@ -236,7 +236,7 @@ pub fn edit_pattern(app: &mut SolveApp, id: &str) -> bool {let Some(pattern) = sk.patterns.iter().find(|p| p.id == id) else { return false };let kind = match &pattern.kind {SketchPatternKind::Circular { count, angle, alignment, reversed, .. } => Mod::PatternCirc {- count: count.to_string(),+ count: pattern.count_expression.clone().unwrap_or_else(|| count.to_string()),angle: format!("{angle} deg"),alignment: if *alignment == PatternAlignment::Left { PatternAlignment::Right } else { *alignment },reversed: *reversed ^ (*alignment == PatternAlignment::Left),@@ -665,7 +665,8 @@ fn picked_point(session: &solidcraft_engine::Session, inputs: &[SelInput], i: us}/// The command a sketch modify dialog makes. Scale, Move, and patterns send evaluated-/// numbers. Offset and Fillet retain expressions in persistent driving dimensions.+/// numbers, except circular Quantity, which keeps its authored expression. Offset and Fillet+/// retain expressions in persistent driving dimensions.pub fn commands(app: &SolveApp, k: &Mod, inputs: &[SelInput], extra: &Map<String, Value>) -> Result<Vec<(String, Value)>, String> {if inputs.iter().flat_map(|input| &input.items).any(|sel| matches!(sel, Sel::SketchPoint { .. }) && point_id(&app.session, sel).is_none()) {return Err("Select points of the sketch being edited".into());@@ -792,7 +793,7 @@ pub fn commands(app: &SolveApp, k: &Mod, inputs: &[SelInput], extra: &Map<Stringlet a = total_angle(app, "Total angle", angle)?;("sketch.pattern.circular",- json!({"entities": entities, "center": center, "count": n, "angle": a, "alignment": alignment, "reversed": reversed}),+ json!({"entities": entities, "center": center, "count": count.trim().parse::<u64>().map_or_else(|_| json!(count.trim()), |_| json!(n)), "angle": a, "alignment": alignment, "reversed": reversed}),)}Mod::Corner { chamfer: false, size, .. } => {diff --git a/crates/ui-egui/src/sketch_modify_ui_tests.rs b/crates/ui-egui/src/sketch_modify_ui_tests.rsindex 8e7276776e..840a165a5d 100644--- a/crates/ui-egui/src/sketch_modify_ui_tests.rs+++ b/crates/ui-egui/src/sketch_modify_ui_tests.rs@@ -604,8 +604,8 @@ fn an_axis_perpendicular_to_the_sketch_is_reported_not_silently_replaced() {}/// Upstream #218 is the same shape: `solid.pattern.circular` took expressions in its axis origin-/// and stored `[0, 0, 0]`. The sketch patterns read `count` and `angle` with `num`, which takes a-/// JSON number only, so the window evaluates every field itself.+/// and stored `[0, 0, 0]`. Rectangular sketch patterns still read `count` with `num`, which+/// takes a JSON number only, so the window evaluates their count fields itself.#[test]fn a_count_expression_is_evaluated_rather_than_sent_as_a_string() {let (mut h, id) = open("sketch.pattern.rectangular");@@ -777,3 +777,29 @@ fn a_missing_centre_a_short_count_and_a_bad_angle_are_all_refused() {let d = h.app.dialog.clone().unwrap();assert!(apply_commands(&h.app, &d).unwrap_err().contains("centre"));}++#[test]+fn circular_quantity_keeps_its_expression_when_reopened_and_follows_parameter_changes() {+ let mut h = Harness::new();+ h.app.run("parameters.add", json!({"name":"HoleAmount","expression":"5","unit":""})).unwrap();+ h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();+ h.app.run("sketch.circle.center", json!({"center":[20,0],"radius":2,"id":"seed"})).unwrap();+ h.app.start("sketch.pattern.circular");+ let d = h.app.dialog.as_mut().unwrap();+ d.inputs[0].items = vec![Sel::SketchCurve { id: "seed".into() }];+ d.inputs[1].items = vec![Sel::SketchPoint { id: "origin".into() }];+ if let Kind::SketchModify(Mod::PatternCirc { count, .. }) = &mut d.kind {+ *count = "HoleAmount".into();+ } else {+ panic!("expected circular pattern");+ }+ let commands = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap();+ assert_eq!(commands[0].1["count"], "HoleAmount");+ let out = h.app.run(&commands[0].0, commands[0].1.clone()).unwrap();+ h.app.dialog = None;+ h.app.run("parameters.change", json!({"name":"HoleAmount","expression":"7"})).unwrap();+ assert!(crate::sketch_modify_ui::edit_pattern(&mut h.app, out["pattern"].as_str().unwrap()));+ assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::SketchModify(Mod::PatternCirc { count, .. }) if count=="HoleAmount"));+ let sid = h.app.session.active_sketch.unwrap();+ assert_eq!(h.app.session.world_state().sketch(sid).unwrap().sketch.curves.len(), 7);+}diff --git a/docs/sketch-patterns.md b/docs/sketch-patterns.mdindex 1a0b7a4b36..9bae7df8a1 100644--- a/docs/sketch-patterns.md+++ b/docs/sketch-patterns.md@@ -31,6 +31,12 @@ them to its **Entities** input. Each tool previews the result before **OK**;Without Center, a positive angle proceeds counterclockwise from the original;Flip reverses it.+Circular **Quantity** accepts a unitless parameter or expression, such as `HoleAmount`+or `HoleAmount + 1`. The expression stays in the editor after applying and reopening;+changing its parameters updates the copies. It must evaluate to a whole number from+2 to 500. Enter a fixed number to replace the parameter link.+Existing fixed-count patterns keep their counts; enter a parameter name to link an older pattern.+Quantities include the original. Edit the original lines or their dimensionsto update their copies. Right-click a rectangular or circular pattern instanceand choose **Edit Sketch Pattern**, or double-click its pattern constraint badge,