diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index c4ee4039b..66ef524c5 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -3666,6 +3666,7 @@ impl Document { /// parameters (in place). pub fn apply_dimension_values(&self, vals: &std::collections::BTreeMap, sk: &mut Sketch) -> Result<()> { self.apply_point_values(vals, sk)?; + self.apply_pattern_values(vals, sk)?; for c in &mut sk.constraints { if let Some(p) = &c.param { let kind = if c.kind.is_angle() { Kind::Angle } else { Kind::Length }; @@ -3697,6 +3698,43 @@ impl Document { Ok(()) } + /// Evaluate the retained pattern inputs before solving its associative relations. + pub fn apply_pattern_values(&self, vals: &std::collections::BTreeMap, sk: &mut Sketch) -> Result<()> { + use solidcraft_sketch::SketchPatternKind; + self.apply_pattern_quantities(vals, sk)?; + for index in 0..sk.patterns.len() { + let Some(pattern) = sk.patterns.get(index) else { continue }; + let mut kind = pattern.kind.clone(); + for (key, expression) in &pattern.expressions { + let unit = match key.as_str() { + "count" | "count2" => Kind::Unitless, + "spacing" | "spacing2" => Kind::Length, + "angle" => Kind::Angle, + _ => return Err(DocError::Invalid(format!("unknown sketch pattern input `{key}`"))), + }; + let value = crate::eval::val(vals, expression, unit).map_err(|e| DocError::Expr(format!("pattern {} `{key}`: {e}", pattern.id)))?; + let count = || -> Result { + if !(1.0..=500.0).contains(&value) || value.fract() != 0.0 { + return Err(DocError::Invalid(format!("pattern `{key}` must be a positive integer from 1 to 500"))); + } + Ok(value as usize) + }; + match (&mut kind, key.as_str()) { + (SketchPatternKind::Circular { count: n, .. } | SketchPatternKind::Rectangular { count: n, .. }, "count") => *n = count()?, + (SketchPatternKind::Rectangular { count2, .. }, "count2") => *count2 = count()?, + (SketchPatternKind::Rectangular { spacing, .. }, "spacing") => *spacing = value, + (SketchPatternKind::Rectangular { spacing2, .. }, "spacing2") => *spacing2 = value, + (SketchPatternKind::Circular { angle, .. }, "angle") => *angle = value.to_degrees(), + _ => return Err(DocError::Invalid(format!("invalid sketch pattern input `{key}`"))), + } + } + if kind != pattern.kind { + sk.update_pattern(index, kind)?; + } + } + 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, sk: &mut Sketch) -> Result<()> { @@ -3792,7 +3830,6 @@ impl Document { moved_from: Option<&Sketch>, analysis: solidcraft_sketch::Analysis, ) -> Result { - 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/eval.rs b/crates/doc/src/eval.rs index 0a217381a..4bac408da 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1196,6 +1196,7 @@ fn param_names(f: &Feature) -> Vec { let mut names: Vec = f.kind.expressions().iter().flat_map(|e| expr::references(e)).collect(); if let FeatureKind::Sketch { sketch, .. } = &f.kind { names.extend(sketch.constraints.iter().filter_map(|c| c.param.clone())); + names.extend(sketch.patterns.iter().flat_map(|p| p.expressions.values()).flat_map(|e| expr::references(e))); names.extend(sketch.text_exprs().into_iter().flat_map(|(_, e)| expr::references(e))); names.extend(sketch.text_word_exprs().into_iter().flat_map(|e| crate::text_params::references(e))); } @@ -1343,13 +1344,28 @@ fn feature_json(f: &Feature, steps: &StepDigests) -> String { /// constraints' values. Nothing else: what evaluation derives for its own copy (an offset's /// upgraded topology, refreshed links) stays out of the stored sketch. A `solved` that does not /// match `stored` entity for entity is not adopted. -fn adopt_solution(stored: &mut solidcraft_sketch::Sketch, solved: &solidcraft_sketch::Sketch) { +fn adopt_solution(stored: &mut solidcraft_sketch::Sketch, solved: &solidcraft_sketch::Sketch) -> bool { + if stored.patterns != solved.patterns { + // Rebuild authored copies without storing topology derived from links or offsets. + let mut updated = stored.clone(); + for pattern in &solved.patterns { + let Some(index) = updated.patterns.iter().position(|p| p.id == pattern.id) else { return false }; + if updated.update_pattern(index, pattern.kind.clone()).is_err() { + return false; + } + } + if updated.patterns != solved.patterns || !adopt_solution(&mut updated, solved) { + return false; + } + *stored = updated; + return true; + } if stored.points.len() != solved.points.len() || stored.curves.len() != solved.curves.len() || stored.constraints.len() != solved.constraints.len() || stored.constraints.iter().zip(&solved.constraints).any(|(a, b)| a.id != b.id) { - return; + return false; } for (p, q) in stored.points.iter_mut().zip(&solved.points) { p.pos = q.pos; @@ -1371,6 +1387,7 @@ fn adopt_solution(stored: &mut solidcraft_sketch::Sketch, solved: &solidcraft_sk c.kind.set_value(v); } } + true } /// The values features are evaluated with: the parameters, and the design's length unit. @@ -1877,6 +1894,7 @@ impl Model { s.report.keeps_orientation() && doc.sketch(s.feature).is_ok_and(|stored| { stored.driving_values() != s.sketch.driving_values() + || stored.patterns != s.sketch.patterns || s.sketch.points.iter().zip(&stored.points).any(|(p, q)| p.link.is_some() && p.id == q.id && p.pos != q.pos) }) }) diff --git a/crates/doc/src/format/pending/sketch-pattern-expressions.rs b/crates/doc/src/format/pending/sketch-pattern-expressions.rs new file mode 100644 index 000000000..88898d229 --- /dev/null +++ b/crates/doc/src/format/pending/sketch-pattern-expressions.rs @@ -0,0 +1,2 @@ +//! Sketch patterns retain count, spacing and angle expressions alongside evaluated settings. +//! Missing expressions preserve the numeric settings of older designs without rewriting them. diff --git a/crates/doc/src/params.rs b/crates/doc/src/params.rs index 0fd89aa2e..ab4f0a249 100644 --- a/crates/doc/src/params.rs +++ b/crates/doc/src/params.rs @@ -78,6 +78,7 @@ impl FeatureKind { inputs.extend(placement); if let FeatureKind::Sketch { sketch, .. } = self { inputs.extend(sketch.patterns.iter().filter_map(|p| p.count_expression.as_deref())); + inputs.extend(sketch.patterns.iter().flat_map(|p| p.expressions.values().map(String::as_str))); } inputs } @@ -738,7 +739,9 @@ impl Document { out.push(ParamUser::Feature { feature: f.id, name: f.name.clone(), input: format!("{} Quantity", pattern.id) }); } } - for (what, e) in sketch.text_exprs() { + for (what, e) in + sketch.text_exprs().into_iter().chain(sketch.patterns.iter().flat_map(|p| p.expressions.iter().map(|(k, e)| (k.as_str(), e)))) + { if expr::references(e).iter().any(|r| r == name) { out.push(ParamUser::Feature { feature: f.id, name: f.name.clone(), input: what.to_string() }); } @@ -857,7 +860,7 @@ impl Document { n += 1; } } - for e in sketch.patterns.iter_mut().filter_map(|p| p.count_expression.as_mut()) { + for e in sketch.patterns.iter_mut().flat_map(|p| p.count_expression.iter_mut().chain(p.expressions.values_mut())) { let r = expr::rename_reference(e, old, new); if r != *e { *e = r; @@ -964,6 +967,7 @@ impl Document { let mut names: BTreeSet = f.param_names.iter().filter(|n| !n.is_empty()).cloned().collect(); if let FeatureKind::Sketch { sketch, .. } = &f.kind { names.extend(sketch.constraints.iter().filter_map(|c| c.param.clone())); + names.extend(sketch.patterns.iter().flat_map(|p| p.expressions.values()).flat_map(|e| expr::references(e))); 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)); names.extend(sketch.text_word_exprs().into_iter().flat_map(|e| crate::text_params::references(e))); @@ -1007,6 +1011,7 @@ impl Document { hit |= f.kind.expressions().iter().any(|e| expr::references(e).iter().any(|r| affected.contains(r))); if let FeatureKind::Sketch { sketch, .. } = &f.kind { hit |= sketch.constraints.iter().any(|c| c.param.as_ref().is_some_and(|p| affected.contains(p))); + hit |= sketch.patterns.iter().flat_map(|p| p.expressions.values()).any(|e| expr::references(e).iter().any(|r| affected.contains(r))); hit |= sketch.text_exprs().iter().any(|(_, e)| expr::references(e).iter().any(|r| affected.contains(r))); hit |= sketch.text_word_exprs().iter().any(|e| crate::text_params::references(e).iter().any(|r| affected.contains(r))); } diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 7afd70afb..a0caae9b5 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -283,8 +283,8 @@ pub(super) fn edit_solved( ) -> Result<(T, Option)> { 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)?; + if sk.patterns.iter().any(|p| p.count_expression.is_some() || !p.expressions.is_empty()) { + doc.apply_pattern_values(&doc.param_values().0, &mut sk)?; } // The next frame of a live gesture on this sketch, nothing else run since the last one: its // links are as that frame projected them, from a model that hasn't changed (#3222). diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index d5a7a0741..eea628a75 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -95,12 +95,12 @@ 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 (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!())), + .params(concat!("entities: [ids], center: [x,y] or point ref, count: 2…500 (number or unitless expression, retained through edits), angle?: total deg, number or expression (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") .enabled(in_sketch) - .params(concat!("entities: [ids], count, spacing; count2?, spacing2?; direction?, direction2?: sketch line ids (live references); dir?, dir2?: [x,y] vectors (defaults: sketch x, perpendicular to direction 1); alignment?, alignment2?: left|center|right (default right). Signed spacings reverse each direction. reversed?, reversed2?: bool (default false); reverses placement and the extra side of even centered totals. Quantities include the original. Adds associative pattern constraints. Returns pattern id. pattern?: existing pattern id to edit (omitted values retained; surviving instance ids retained)", created_doc!())), + .params(concat!("entities: [ids], count, spacing; count2?, spacing2?; counts: positive integer numbers or expressions, at most 500 instances total; spacings: length numbers or expressions; direction?, direction2?: sketch line ids (live references); dir?, dir2?: [x,y] vectors (defaults: sketch x, perpendicular to direction 1); alignment?, alignment2?: left|center|right (default right). Signed spacings reverse each direction. reversed?, reversed2?: bool (default false); reverses placement and the extra side of even centered totals. Quantities include the original. Adds associative pattern constraints. Returns pattern id. pattern?: existing pattern id to edit (omitted values retained; surviving instance ids retained)", created_doc!())), ]; const TOL: f64 = 1e-7; @@ -2520,14 +2520,6 @@ fn mirror(s: &mut Session, p: &Value) -> Result { Ok(json!({"curves": out.0, "constraints": out.1, "sketch": info})) } -fn count(p: &Value, k: &str, cmd: &str) -> Result { - let n = num(p, k).ok_or_else(|| bad(cmd, format!("`{k}` must be a number")))?; - if !(1.0..=MAX_COPIES as f64).contains(&n) || n.fract() != 0.0 { - return Err(bad(cmd, format!("`{k}` must be 1…{MAX_COPIES}"))); - } - Ok(n as usize) -} - fn point_or_ref(sk: &Sketch, p: &Value, k: &str, cmd: &str) -> Result { match p.get(k) { Some(Value::String(r)) => sk.resolve_point(r).and_then(|i| sk.point(i)).ok_or_else(|| bad(cmd, format!("unknown point `{r}`"))), diff --git a/crates/engine/src/cmd/sketch_pattern.rs b/crates/engine/src/cmd/sketch_pattern.rs index 71f9c08cf..d90c23a10 100644 --- a/crates/engine/src/cmd/sketch_pattern.rs +++ b/crates/engine/src/cmd/sketch_pattern.rs @@ -1,6 +1,6 @@ //! Associative sketch patterns. Editing retains ids at surviving instance indices. -use solidcraft_sketch::{PatternInstance, SketchPattern, SketchPatternKind}; +use solidcraft_sketch::{SketchPattern, SketchPatternKind}; use super::*; use crate::cmd::{alignment_param, reversed_param}; @@ -50,6 +50,30 @@ pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result { } } } + let mut expressions = old.as_ref().map(|old| old.expressions.clone()).unwrap_or_default(); + for key in ["count", "count2", "spacing", "spacing2", "angle"] { + if p.get(key).is_some() { + expressions.remove(key); + } + if let Some(Value::String(e)) = p.get(key) { + expressions.insert(key.into(), e.clone()); + } + } + for (key, expression) in &expressions { + let kind = match key.as_str() { + "count" | "count2" => solidcraft_doc::expr::Kind::Unitless, + "angle" => solidcraft_doc::expr::Kind::Angle, + _ => solidcraft_doc::expr::Kind::Length, + }; + let value = doc.eval(expression, kind).map_err(|e| bad(cmd, format!("`{key}`: {e}")))?; + params[key] = json!(if key == "angle" { value.to_degrees() } else { value }); + } + if !circular + && params.get("spacing2").is_none() + && let Some(e) = expressions.get("spacing").cloned() + { + expressions.insert("spacing2".into(), e); + } let (mut cs, mut ps) = entities(sk, ¶ms, cmd)?; cs.sort_unstable(); cs.dedup(); @@ -76,23 +100,18 @@ pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result { } } 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, + let expression = + expressions.remove("count").or_else(|| old.as_ref().and_then(|p| p.count_expression.clone()).filter(|_| p.get("count").is_none())); + if let Some(expression) = &expression { + let value = doc.eval(expression, solidcraft_doc::expr::Kind::Unitless)?; + params["count"] = json!(SketchPattern::circular_quantity(value).map_err(|e| bad(cmd, format!("`count`: {e}")))?); } + expression } 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 (kind, center) = 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) { return Err(bad(cmd, "`angle` must be nonzero and at most 360 degrees")); @@ -108,15 +127,9 @@ pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result { None => return Err(bad(cmd, "missing `center`")), }; let id = sk.points.get(center).ok_or_else(|| bad(cmd, "missing center point"))?.id.clone(); - let full = (total.abs() - 360.0).abs() < 1e-9; - let step = total / if full { n as f64 } else { (n.max(2) - 1) as f64 }; let alignment = alignment_param(¶ms, "alignment", cmd)?; let reversed = reversed_param(¶ms, "reversed", cmd)?; - ( - SketchPatternKind::Circular { center: id, count: n, angle: total, alignment, reversed }, - Some(center), - (1..n).map(|i| ([i, 0], (step * alignment.multiplier(i, reversed)).to_radians(), Vec2::ZERO)).collect::>(), - ) + (SketchPatternKind::Circular { center: id, count: n, angle: total, alignment, reversed }, Some(center)) } else { let spacing = num(¶ms, "spacing").ok_or_else(|| bad(cmd, "`spacing` must be finite"))?; let count2 = if params.get("count2").is_some() { count(¶ms, "count2", cmd)? } else { 1 }; @@ -144,19 +157,6 @@ pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result { let alignment2 = alignment_param(¶ms, "alignment2", cmd)?; let reversed = reversed_param(¶ms, "reversed", cmd)?; let reversed2 = reversed_param(¶ms, "reversed2", cmd)?; - let first = line_direction(sk, direction.as_deref()).unwrap_or(dir); - let second = line_direction(sk, direction2.as_deref()).or(dir2).unwrap_or_else(|| first.perp()); - let slots = (0..n) - .flat_map(|i| { - (0..count2).filter_map(move |j| { - (i != 0 || j != 0).then_some(( - [i, j], - 0.0, - first * (spacing * alignment.multiplier(i, reversed)) + second * (spacing2 * alignment2.multiplier(j, reversed2)), - )) - }) - }) - .collect(); ( SketchPatternKind::Rectangular { dir, @@ -173,7 +173,6 @@ pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result { reversed2, }, None, - slots, ) }; let id = match &old { @@ -181,82 +180,20 @@ pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result { None => sk.fresh("pat")?, }; let center_id = center.and_then(|i| sk.points.get(i)).map(|p| p.id.clone()); - let mut existing = old.map(|old| old.instances).unwrap_or_default(); - // Remove retired instances first: all following indices are resolved by stable id. - for instance in existing.iter().filter(|instance| !slots.iter().any(|(index, _, _)| *index == instance.index)) { - let curves: Vec<_> = instance.curves.iter().filter_map(|id| sk.curve_index(id)).collect(); - sk.constraints.retain(|c| !instance.constraints.contains(&c.id)); - sk.remove_curves(&curves); - let points: Vec<_> = instance.points.iter().filter_map(|(_, id)| sk.resolve_point(id)).collect(); - sk.remove_points(&points); - } - let mut instances = Vec::new(); - let center = center_id.as_ref().and_then(|id| sk.resolve_point(id)); - if center_id.is_some() && center.is_none() { - return Err(bad(cmd, "the center belongs to an instance removed by this edit")); - } - if !circular { - // A direction can have belonged to an instance retired above. Resolve it again - // before creating relations so an edit never silently substitutes a vector. - direction_ref(sk, ¶ms, "direction", cmd)?; - direction_ref(sk, ¶ms, "direction2", cmd)?; - } - let mut curves = Vec::new(); - let mut constraints = Vec::new(); - for (index, angle, offset) in slots { - let (base_offset, directions) = linear_displacement(sk, &kind, index, offset); - let c = center.and_then(|i| sk.point(i)).unwrap_or(Vec2::ZERO); - let transform = |p| rotate(c, angle)(p) + offset; - let instance = if let Some(i) = existing.iter().position(|instance| instance.index == index) { - let instance = existing.remove(i); - for cid in &instance.constraints { - if let Some(constraint) = sk.constraints.iter_mut().find(|constraint| constraint.id == *cid) - && let ConstraintKind::PatternPoint { center: slot, angle: a, offset: off, directions: dirs, .. } = &mut constraint.kind - { - *slot = center; - *a = angle; - *off = base_offset; - *dirs = directions; - } - } - for (seed, copy) in &instance.points { - let pos = sk.resolve_point(seed).and_then(|i| sk.point(i)).ok_or_else(|| bad(cmd, "missing seed point"))?; - if let Some(point) = sk.resolve_point(copy).and_then(|i| sk.points.get_mut(i)) { - point.pos = transform(pos); - } - } - instance - } else { - let cs: Vec<_> = entity_ids.iter().filter_map(|id| sk.curve_index(id)).collect(); - let ps: Vec<_> = entity_ids.iter().filter(|id| sk.curve_index(id).is_none()).filter_map(|id| sk.resolve_point(id)).collect(); - let (made, map) = copy_through(sk, &cs, &ps, &transform, false, &|_| false, 1.0)?; - let mut cons = Vec::new(); - for (p, q) in &map { - cons.push(add_c(sk, ConstraintKind::PatternPoint { p: *p, q: *q, center, angle, offset: base_offset, directions })?); - } - for (a, b) in cs.iter().zip(&made) { - if matches!(sk.curves.get(*a).map(|c| &c.kind), Some(CurveKind::Circle { .. } | CurveKind::Ellipse { .. })) { - cons.push(add_c(sk, ConstraintKind::PatternRadius { a: *a, b: *b })?); - } - } - PatternInstance { - index, - curves: ids_of(sk, &made), - points: map.iter().filter_map(|(p, q)| Some((sk.points.get(*p)?.id.clone(), sk.points.get(*q)?.id.clone()))).collect(), - constraints: cons, - } - }; - curves.extend(instance.curves.iter().cloned()); - constraints.extend(instance.constraints.iter().cloned()); - 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, count_expression, instances }; - if let Some(i) = old_index { - sk.patterns.insert(i.min(sk.patterns.len()), pattern); - } else { - sk.patterns.push(pattern); - } + let index = old_index.unwrap_or(sk.patterns.len()); + let pattern = SketchPattern { + id: id.clone(), + entities: entity_ids, + kind: kind.clone(), + instances: old.map(|old| old.instances).unwrap_or_default(), + expressions, + count_expression, + }; + sk.patterns.insert(index.min(sk.patterns.len()), pattern); + sk.update_pattern(index, kind)?; + let pattern = sk.patterns.get(index).ok_or_else(|| bad(cmd, "missing sketch pattern"))?; + let curves: Vec<_> = pattern.instances.iter().flat_map(|i| i.curves.iter().cloned()).collect(); + let constraints: Vec<_> = pattern.instances.iter().flat_map(|i| i.constraints.iter().cloned()).collect(); Ok(json!({"pattern":id,"center":center_id,"curves":curves,"constraints":constraints})) })?; let mut out = out; @@ -266,6 +203,14 @@ pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result { Ok(out) } +fn count(p: &Value, k: &str, cmd: &str) -> Result { + let n = num(p, k).ok_or_else(|| bad(cmd, format!("`{k}` must be a number or expression")))?; + if !(1.0..=MAX_COPIES as f64).contains(&n) || n.fract() != 0.0 { + return Err(bad(cmd, format!("`{k}` must be a positive integer from 1 to {MAX_COPIES}"))); + } + Ok(n as usize) +} + fn direction_ref(sk: &Sketch, p: &Value, key: &str, cmd: &str) -> Result> { match p.get(key) { None | Some(Value::Null) => Ok(None), @@ -278,30 +223,3 @@ fn line_direction(sk: &Sketch, id: Option<&str>) -> Option { let Shape::Line { a, b } = sk.shape(sk.curve_index(id?)?)? else { return None }; (b - a).normalized() } - -/// Keep sampled vector directions compatible with older designs, while picked lines are -/// solver references. The default second direction follows the first line's perpendicular. -fn linear_displacement(sk: &Sketch, kind: &SketchPatternKind, [i, j]: [usize; 2], fallback: Vec2) -> (Vec2, [Option<(usize, Vec2)>; 2]) { - let SketchPatternKind::Rectangular { dir, dir2, direction, direction2, spacing, spacing2, alignment, alignment2, reversed, reversed2, .. } = kind - else { - return (fallback, [None; 2]); - }; - let mut offset = Vec2::ZERO; - let mut directions = [None; 2]; - let d1 = *spacing * alignment.multiplier(i, *reversed); - let d2 = *spacing2 * alignment2.multiplier(j, *reversed2); - if let Some(l) = direction.as_ref().and_then(|id| sk.curve_index(id)) { - directions[0] = Some((l, Vec2::new(d1, if dir2.is_none() && direction2.is_none() { d2 } else { 0.0 }))); - } else { - offset += *dir * d1; - if dir2.is_none() && direction2.is_none() { - offset += dir.perp() * d2; - } - } - if let Some(l) = direction2.as_ref().and_then(|id| sk.curve_index(id)) { - directions[1] = Some((l, Vec2::new(d2, 0.0))); - } else if let Some(dir2) = dir2 { - offset += *dir2 * d2; - } - (offset, directions) -} diff --git a/crates/engine/src/cmd/sketch_pattern_tests.rs b/crates/engine/src/cmd/sketch_pattern_tests.rs index a4017c372..68d8a6cd4 100644 --- a/crates/engine/src/cmd/sketch_pattern_tests.rs +++ b/crates/engine/src/cmd/sketch_pattern_tests.rs @@ -678,3 +678,80 @@ fn a_pattern_too_large_to_solve_says_why() { .to_string(); assert!(e.contains("unknowns") && e.contains(&solidcraft_sketch::MAX_COMPONENT_VARS.to_string()) && !e.contains("conflicts with"), "{e}"); } + +#[test] +fn rectangular_pattern_expressions_follow_parameters_and_survive_reopening() { + let mut s = new_sketch(); + for (name, expression, unit) in [("pitch", "30", "mm"), ("copies", "3", "")] { + run(&mut s, "parameters.add", json!({"name":name,"expression":expression,"unit":unit})); + } + run(&mut s, "sketch.circle.center", json!({"id":"seed","center":[5,5],"radius":1})); + let out = run( + &mut s, + "sketch.pattern.rectangular", + json!({"entities":["seed"],"count":"copies","spacing":"pitch","count2":"2","spacing2":"pitch / 2"}), + ); + let first = ids(&out["curves"])[0].clone(); + assert!(!s.doc.param_users("pitch").is_empty()); + run(&mut s, "sketch.finish", json!({})); + let mut s = Session { doc: solidcraft_doc::format::read(&s.doc.to_json()).unwrap().into(), ..Default::default() }; + s.refresh(); + run(&mut s, "parameters.change", json!({"name":"pitch","expression":"40"})); + run(&mut s, "parameters.change", json!({"name":"copies","expression":"4"})); + let state = s.world_state(); + let sk = &state.sketch(1).unwrap().sketch; + assert_eq!(sk.patterns[0].instances.len(), 7); + assert_eq!(sk.patterns[0].instances[0].curves[0], first); + assert!(point(sk, &format!("{first}.center")).dist(Vec2::new(5., 25.)) < 1e-6); + let last = &sk.patterns[0].instances.last().unwrap().curves[0]; + assert!(point(sk, &format!("{last}.center")).dist(Vec2::new(125., 25.)) < 1e-6); + run(&mut s, "parameters.change", json!({"name":"copies","expression":"2"})); + assert_eq!(s.world_state().sketch(1).unwrap().sketch.patterns[0].instances.len(), 3); + run(&mut s, "parameters.change", json!({"name":"pitch","new_name":"step"})); + assert_eq!(serde_json::to_value(&s.doc.sketch(1).unwrap().patterns[0]).unwrap()["expressions"]["spacing"], "step"); + assert!(s.execute("parameters.change", &json!({"delete":"step"})).is_err()); +} + +#[test] +fn circular_pattern_expressions_validate_inputs_and_keep_numeric_compatibility() { + let mut s = new_sketch(); + for (name, expression, unit) in [("turn", "90", "deg"), ("copies", "3", "")] { + run(&mut s, "parameters.add", json!({"name":name,"expression":expression,"unit":unit})); + } + run(&mut s, "sketch.circle.center", json!({"id":"seed","center":[20,0],"radius":1})); + let out = run(&mut s, "sketch.pattern.circular", json!({"entities":["seed"],"center":"origin","count":"copies","angle":"turn"})); + run(&mut s, "parameters.change", json!({"name":"turn","expression":"180"})); + run(&mut s, "parameters.change", json!({"name":"copies","expression":"4"})); + let sk = sketch(&s); + let last = &sk.patterns[0].instances.last().unwrap().curves[0]; + assert!(point(&sk, &format!("{last}.center")).dist(Vec2::new(-20., 0.)) < 1e-6); + for expression in ["2.5", "501", "0", "-1"] { + let error = s.execute("parameters.change", &json!({"name":"copies","expression":expression})).unwrap_err().to_string(); + assert!(error.contains("whole number"), "{error}"); + } + for (key, value, message) in [("count", json!("2.5"), "count"), ("count", json!("501"), "count"), ("angle", json!("missing + 1"), "missing")] { + let mut p = json!({"pattern":out["pattern"]}); + p[key] = value; + let error = s.execute("sketch.pattern.circular", &p).unwrap_err().to_string(); + assert!(error.contains(message), "{error}"); + } + let error = s.execute("sketch.pattern.rectangular", &json!({"entities":["seed"],"count":2,"spacing":"unknown_pitch"})).unwrap_err().to_string(); + assert!(error.contains("spacing") && error.contains("unknown_pitch"), "{error}"); + run(&mut s, "sketch.pattern.circular", json!({"pattern":out["pattern"],"count":3,"angle":90})); + assert!(serde_json::to_value(&sketch(&s).patterns[0]).unwrap().get("expressions").is_none()); + let legacy = s.doc.to_json(); + // Numeric patterns omit the optional expression field, just as older files do. + assert!(!s.doc.to_json().contains("\"expressions\"")); + let reopened = solidcraft_doc::format::read(&legacy).unwrap(); + assert_eq!(reopened.sketch(1).unwrap().patterns[0].instances.len(), 2); + // A design with plain numbers saves back unchanged and evaluates to the same copies. + assert_eq!(reopened.to_json(), legacy); + let before = sketch(&s); + let mut s = Session { doc: reopened.into(), ..Default::default() }; + s.refresh(); + let state = s.world_state(); + let after = &state.sketch(1).unwrap().sketch; + for (a, b) in before.points.iter().zip(&after.points) { + assert!(a.id == b.id && a.pos.dist(b.pos) < 1e-9, "{} moved", a.id); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2b40b3d1c..ed747e44e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -891,7 +891,9 @@ impl Session { .features .iter() .filter_map(|feature| match &feature.kind { - solidcraft_doc::FeatureKind::Sketch { sketch, .. } if sketch.patterns.iter().any(|p| p.count_expression.is_some()) => { + solidcraft_doc::FeatureKind::Sketch { sketch, .. } + if sketch.patterns.iter().any(|p| p.count_expression.is_some() || !p.expressions.is_empty()) => + { Some((feature.id, sketch.clone())) } _ => None, @@ -900,7 +902,7 @@ impl Session { if !updated.is_empty() { let (vals, _) = self.doc.param_values(); for (_, sketch) in &mut updated { - self.doc.apply_pattern_quantities(&vals, sketch)?; + self.doc.apply_pattern_values(&vals, sketch)?; } } for (id, sketch) in updated { @@ -1405,11 +1407,18 @@ pub(crate) type SketchValues = std::collections::BTreeMap std::collections::BTreeMap { 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); + for p in &sk.patterns { + use solidcraft_sketch::SketchPatternKind; + let inputs = match p.kind { + SketchPatternKind::Circular { count, angle, .. } => vec![("count", count as f64), ("angle", angle)], + SketchPatternKind::Rectangular { count, spacing, count2, spacing2, .. } => { + vec![("count", count as f64), ("spacing", spacing), ("count2", count2 as f64), ("spacing2", spacing2)] + } + }; + for (key, value) in inputs { + if p.expressions.contains_key(key) || (key == "count" && p.count_expression.is_some()) { + values.insert(format!("{}.{}", p.id, key), value); + } } } values diff --git a/crates/sketch/src/pattern.rs b/crates/sketch/src/pattern.rs index 47a6b89fb..5ac99d578 100644 --- a/crates/sketch/src/pattern.rs +++ b/crates/sketch/src/pattern.rs @@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize}; use solidcraft_geom::Vec2; -use crate::{CurveKind, Sketch, SketchError}; +use crate::{ConstraintKind, Curve, CurveKind, Sketch, SketchError}; /// Placement relative to the original, along a pattern direction's oriented line. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -81,6 +81,8 @@ pub struct SketchPattern { #[serde(default, skip_serializing_if = "Option::is_none")] pub count_expression: Option, pub instances: Vec, + #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub expressions: std::collections::BTreeMap, } impl SketchPattern { @@ -106,120 +108,150 @@ 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. + /// Rebuild a circular Quantity while retaining surviving copy ids. 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 { + let mut kind = self.patterns.get(index).ok_or_else(|| SketchError::Invalid("missing sketch pattern".into()))?.kind.clone(); + let SketchPatternKind::Circular { count: previous, .. } = &mut 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) { + self.update_pattern(index, kind) + } + + /// Rebuild a pattern after its driving expressions change, retaining surviving copy ids. + pub fn update_pattern(&mut self, index: usize, kind: SketchPatternKind) -> Result<(), SketchError> { + let old = self.patterns.get(index).cloned().ok_or_else(|| SketchError::Invalid("missing sketch pattern".into()))?; + let check_count = |n: usize| { + if !(1..=500).contains(&n) { Err(SketchError::Invalid("pattern count must be a positive integer from 1 to 500".into())) } else { Ok(()) } + }; + match &kind { + SketchPatternKind::Circular { count, angle, .. } => { + check_count(*count)?; + if !angle.is_finite() || angle.abs() <= 1e-9 || angle.abs() > 360.0 { + return Err(SketchError::Invalid("pattern angle must be nonzero and at most 360 degrees".into())); + } + } + SketchPatternKind::Rectangular { count, count2, spacing, spacing2, .. } => { + check_count(*count)?; + check_count(*count2)?; + if count.checked_mul(*count2).is_none_or(|n| n > 500) { + return Err(SketchError::Invalid("pattern counts must make at most 500 instances total".into())); + } + if ![spacing, spacing2].iter().all(|v| v.is_finite() && v.abs() <= crate::MAX_COORD) { + return Err(SketchError::Invalid("pattern spacing must be finite and in range".into())); + } + } + } + self.patterns.remove(index); + let entity_ids = old.entities.clone(); + let (center, slots) = match &kind { + SketchPatternKind::Circular { center, count, angle, alignment, reversed } => { + let center = self.resolve_point(center).ok_or_else(|| SketchError::Invalid("missing pattern center".into()))?; + let full = (angle.abs() - 360.0).abs() < 1e-9; + let step = angle / if full { *count as f64 } else { (count.max(&2) - 1) as f64 }; + ( + Some(center), + (1..*count).map(|i| ([i, 0], (step * alignment.multiplier(i, *reversed)).to_radians(), Vec2::ZERO)).collect::>(), + ) + } + SketchPatternKind::Rectangular { count, count2, .. } => { + (None, (0..*count).flat_map(|i| (0..*count2).filter_map(move |j| (i != 0 || j != 0).then_some(([i, j], 0.0, Vec2::ZERO)))).collect()) + } + }; + let center_id = center.and_then(|i| self.points.get(i)).map(|p| p.id.clone()); + let mut existing = old.instances.clone(); + // Remove retired instances first: all following indices are resolved by stable id. + for instance in existing.iter().filter(|instance| !slots.iter().any(|(index, _, _)| *index == instance.index)) { 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]) { + if let SketchPatternKind::Rectangular { direction, direction2, .. } = &kind { + for id in direction.iter().chain(direction2) { + if self.curve_index(id).is_none() { + return Err(SketchError::Invalid("the direction belongs to an instance removed by this edit".into())); + } + } + } + let mut instances = Vec::new(); + let center = center_id.as_ref().and_then(|id| self.resolve_point(id)); + if center_id.is_some() && center.is_none() { + return Err(SketchError::Invalid("the center belongs to an instance removed by this edit".into())); + } + for (index, angle, offset) in slots { + let (base_offset, directions) = linear_displacement(self, &kind, index, offset); + let c = center.and_then(|i| self.point(i)).unwrap_or(Vec2::ZERO); + let mut displacement = base_offset; + for (line, distance) in directions.into_iter().flatten() { + if let Some(crate::Shape::Line { a, b }) = self.shape(line) + && let Some(u) = (b - a).normalized() + { + displacement += u * distance.x + u.perp() * distance.y; + } + } + let transform = |p| rotate(c, angle)(p) + displacement; + let instance = if let Some(i) = existing.iter().position(|instance| instance.index == index) { + let instance = existing.remove(i); 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) + if let Some(constraint) = self.constraints.iter_mut().find(|constraint| constraint.id == *cid) + && let ConstraintKind::PatternPoint { center: slot, angle: a, offset: off, directions: dirs, .. } = &mut constraint.kind { - *value = angle; + *slot = center; + *a = angle; + *off = base_offset; + *dirs = directions; } } 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); + let pos = + self.resolve_point(seed).and_then(|i| self.point(i)).ok_or_else(|| SketchError::Invalid("missing seed point".into()))?; + if let Some(point) = self.resolve_point(copy).and_then(|i| self.points.get_mut(i)) { + let at = transform(pos); + if !crate::model::in_range(at) { + return Err(SketchError::Invalid("pattern point is out of range".into())); + } + point.pos = at; + } } - 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())); + instance + } else { + let cs: Vec<_> = entity_ids.iter().filter_map(|id| self.curve_index(id)).collect(); + let ps: Vec<_> = entity_ids.iter().filter(|id| self.curve_index(id).is_none()).filter_map(|id| self.resolve_point(id)).collect(); + let (made, map) = copy_through(self, &cs, &ps, &transform)?; + let mut cons = Vec::new(); + for (p, q) in &map { + cons.push( + self.add_constraint(ConstraintKind::PatternPoint { p: *p, q: *q, center, angle, offset: base_offset, directions }, None)?, + ); } - } - let mut map = Vec::new(); - for p in points { - if map.iter().any(|(seed, _)| *seed == p) { - continue; + for (a, b) in cs.iter().zip(&made) { + if matches!(self.curves.get(*a).map(|c| &c.kind), Some(CurveKind::Circle { .. } | CurveKind::Ellipse { .. })) { + cons.push(self.add_constraint(ConstraintKind::PatternRadius { a: *a, b: *b }, None)?); + } } - 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)?); + PatternInstance { + index, + curves: made.iter().filter_map(|i| self.curves.get(*i).map(|c| c.id.clone())).collect(), + points: map.iter().filter_map(|(p, q)| Some((self.points.get(*p)?.id.clone(), self.points.get(*q)?.id.clone()))).collect(), + constraints: cons, } - } - 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 }); + }; + instances.push(instance); } - self.patterns.insert(index.min(self.patterns.len()), pattern); - self.validate_patterns() + + self.patterns.insert(index.min(self.patterns.len()), SketchPattern { kind, instances, ..old }); + self.follow_pattern_seeds(); + Ok(()) } /// Start an explicit Move/Scale of seed geometry with its copies already transformed. @@ -343,6 +375,15 @@ impl Sketch { } let mut ids = std::collections::BTreeSet::new(); for pattern in &self.patterns { + if pattern.expressions.len() > 5 + || pattern.expressions.iter().any(|(key, expression)| { + !matches!(key.as_str(), "count" | "count2" | "spacing" | "spacing2" | "angle") + || expression.trim().is_empty() + || expression.len() > 4096 + }) + { + return Err(SketchError::Invalid("invalid sketch pattern expression".into())); + } 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 { .. })) { @@ -424,3 +465,99 @@ impl Sketch { Ok(()) } } + +/// Keep sampled vector directions compatible with older designs, while picked lines are +/// solver references. The default second direction follows the first line's perpendicular. +fn linear_displacement(sk: &Sketch, kind: &SketchPatternKind, [i, j]: [usize; 2], fallback: Vec2) -> (Vec2, [Option<(usize, Vec2)>; 2]) { + let SketchPatternKind::Rectangular { dir, dir2, direction, direction2, spacing, spacing2, alignment, alignment2, reversed, reversed2, .. } = kind + else { + return (fallback, [None; 2]); + }; + let mut offset = Vec2::ZERO; + let mut directions = [None; 2]; + let d1 = *spacing * alignment.multiplier(i, *reversed); + let d2 = *spacing2 * alignment2.multiplier(j, *reversed2); + if let Some(l) = direction.as_ref().and_then(|id| sk.curve_index(id)) { + directions[0] = Some((l, Vec2::new(d1, if dir2.is_none() && direction2.is_none() { d2 } else { 0.0 }))); + } else { + offset += *dir * d1; + if dir2.is_none() && direction2.is_none() { + offset += dir.perp() * d2; + } + } + if let Some(l) = direction2.as_ref().and_then(|id| sk.curve_index(id)) { + directions[1] = Some((l, Vec2::new(d2, 0.0))); + } else if let Some(dir2) = dir2 { + offset += *dir2 * d2; + } + (offset, directions) +} + +fn involved_points(sk: &Sketch, cs: &[usize], ps: &[usize]) -> Vec { + let mut v: Vec = Vec::new(); + for c in cs { + if let Some(k) = sk.curves.get(*c).map(|c| &c.kind) { + v.extend(k.point_ids()); + } + } + v.extend(ps); + let mut out = Vec::new(); + for q in v { + if !out.contains(&q) { + out.push(q); + } + } + out +} + +/// Copy seed curves and their points, returning curves and the original-to-copy point map. +fn copy_through(sk: &mut Sketch, cs: &[usize], ps: &[usize], f: &dyn Fn(Vec2) -> Vec2) -> Result<(Vec, Vec<(usize, usize)>), SketchError> { + if sk.curves.len().saturating_add(cs.len()) > crate::MAX_CURVES { + return Err(crate::SketchError::TooLarge); + } + let pts = involved_points(sk, cs, ps); + let mut map: Vec<(usize, usize)> = Vec::new(); + for q in &pts { + let pos = sk.point(*q).unwrap_or_default(); + let n = sk.add_point(f(pos), None)?; + map.push((*q, n)); + } + let m = |q: usize| map.iter().find(|x| x.0 == q).map(|x| x.1).unwrap_or(q); + let mut made = Vec::new(); + for c in cs { + let Some(cu) = sk.curves.get(*c).cloned() else { continue }; + let mut kind = cu.kind.clone(); + kind.map_points(&m); + let prefix = match &kind { + CurveKind::Ellipse { .. } => "e", + CurveKind::Spline { .. } => "s", + CurveKind::Conic { .. } => "k", + CurveKind::Line { .. } => "l", + CurveKind::Circle { .. } => "c", + CurveKind::Arc { .. } => "a", + }; + let id = sk.fresh(prefix)?; + // Copies retain the seed line's extent. + let infinite = cu.infinite && matches!(kind, CurveKind::Line { .. }); + sk.curves.push(Curve { + id, + kind, + construction: cu.construction, + reversed: cu.reversed, + link: None, + centerline: false, + fixed: false, + infinite, + }); + made.push(sk.curves.len() - 1); + } + Ok((made, map)) +} + +fn rotate(c: Vec2, ang: f64) -> impl Fn(Vec2) -> Vec2 { + move |q: Vec2| { + let d = q - c; + let (s, co) = ang.sin_cos(); + c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co) + } +} diff --git a/crates/ui-egui/src/dialogs_sketch_tests.rs b/crates/ui-egui/src/dialogs_sketch_tests.rs index fe4154511..c59348271 100644 --- a/crates/ui-egui/src/dialogs_sketch_tests.rs +++ b/crates/ui-egui/src/dialogs_sketch_tests.rs @@ -228,7 +228,7 @@ fn circular_pattern_quantity_arrows_step_the_count_within_its_limits_and_keep_pa assert_eq!(count(&h), "6"); h.step(&json!({"click":{"handle":"dialog:Quantity up"}})).unwrap(); assert_eq!(count(&h), "7"); - assert_eq!((sent(&h), previewed(&h)), (json!(7), json!(7)), "the preview follows the arrow as it follows typing"); + assert_eq!((sent(&h), previewed(&h)), (json!("7"), json!("7")), "the preview follows the arrow as it follows typing"); h.step(&json!({"click":{"handle":"dialog:Quantity down"}})).unwrap(); h.step(&json!({"click":{"handle":"dialog:Quantity down"}})).unwrap(); assert_eq!(count(&h), "5"); @@ -281,3 +281,43 @@ fn rectangular_pattern_quantity_arrows_keep_both_directions_within_the_copy_limi h.step(&json!({"click":{"handle":"dialog:Quantity down"}})).unwrap(); assert_eq!(counts(&h), ("249".into(), "2".into())); } + +#[test] +fn sketch_pattern_dialog_preserves_expression_text_when_applying_and_editing() { + let mut h = fixture(); + h.app.run("parameters.add", json!({"name":"pitch","expression":"30","unit":"mm"})).unwrap(); + for command in ["sketch.pattern.rectangular", "sketch.pattern.circular"] { + let mut d = picked(&h, command); + match &mut d.kind { + Kind::SketchModify(Mod::PatternRect { count, spacing, .. }) => { + *count = "1 + 2".into(); + *spacing = "pitch".into(); + } + Kind::SketchModify(Mod::PatternCirc { count, angle, .. }) => { + *count = "1 + 2".into(); + *angle = "45 deg + 45 deg".into(); + } + _ => panic!("expected a sketch pattern dialog"), + } + let cmds = apply_commands(&h.app, &d).unwrap(); + assert_eq!(cmds[0].1["count"], "1 + 2"); + let (key, expression) = if command.ends_with("rectangular") { ("spacing", "pitch") } else { ("angle", "45 deg + 45 deg") }; + assert_eq!(cmds[0].1[key], expression); + let result = h.app.run(command, cmds[0].1.clone()).unwrap(); + if command.ends_with("rectangular") { + h.app.run("parameters.change", json!({"name":"pitch","expression":"40"})).unwrap(); + } + assert!(crate::sketch_modify_ui::edit_pattern(&mut h.app, result["pattern"].as_str().unwrap())); + match &h.app.dialog.as_ref().unwrap().kind { + Kind::SketchModify(Mod::PatternRect { count, spacing, .. }) => { + assert_eq!(count, "1 + 2"); + assert_eq!(spacing, expression); + } + Kind::SketchModify(Mod::PatternCirc { count, angle, .. }) => { + assert_eq!(count, "1 + 2"); + assert_eq!(angle, expression); + } + _ => panic!("expected a sketch pattern dialog"), + } + } +} diff --git a/crates/ui-egui/src/sketch_modify_ui.rs b/crates/ui-egui/src/sketch_modify_ui.rs index 93d5a81dc..9e8e8a81a 100644 --- a/crates/ui-egui/src/sketch_modify_ui.rs +++ b/crates/ui-egui/src/sketch_modify_ui.rs @@ -251,18 +251,19 @@ pub fn edit_pattern(app: &mut SolveApp, id: &str) -> bool { let state = app.session.world_state(); let Some(sk) = state.sketch(sid).map(|s| &s.sketch) else { return false }; let Some(pattern) = sk.patterns.iter().find(|p| p.id == id) else { return false }; + let input = |key: &str, fallback: String| pattern.expressions.get(key).cloned().unwrap_or(fallback); let kind = match &pattern.kind { SketchPatternKind::Circular { count, angle, alignment, reversed, .. } => Mod::PatternCirc { - count: pattern.count_expression.clone().unwrap_or_else(|| count.to_string()), - angle: format!("{angle} deg"), + count: pattern.count_expression.clone().unwrap_or_else(|| input("count", count.to_string())), + angle: input("angle", format!("{angle} deg")), alignment: if *alignment == PatternAlignment::Left { PatternAlignment::Right } else { *alignment }, reversed: *reversed ^ (*alignment == PatternAlignment::Left), }, SketchPatternKind::Rectangular { count, spacing, count2, spacing2, alignment, alignment2, reversed, reversed2, .. } => Mod::PatternRect { - count: count.to_string(), - spacing: format!("{spacing} mm"), - count2: count2.to_string(), - spacing2: format!("{spacing2} mm"), + count: input("count", count.to_string()), + spacing: input("spacing", format!("{spacing} mm")), + count2: input("count2", count2.to_string()), + spacing2: input("spacing2", format!("{spacing2} mm")), alignment: if *alignment == PatternAlignment::Left { PatternAlignment::Right } else { *alignment }, alignment2: if *alignment2 == PatternAlignment::Left { PatternAlignment::Right } else { *alignment2 }, reversed: *reversed ^ (*alignment == PatternAlignment::Left), @@ -609,14 +610,7 @@ fn signed_length(app: &SolveApp, label: &str, text: &str, flip: bool) -> Result< Ok(if flip { -v } else { v }) } -/// A typed count as the command wants it: the field evaluated against the document's -/// parameters, then a whole number the engine accepts. -/// -/// The sketch patterns read `count` and `angle` with `num`, which takes a JSON number and -/// nothing else. An expression string would be refused outright for `count`, and silently -/// replaced by the 360 degree default for `angle`. That silent substitution is the defect -/// upstream #218 reports for `solid.pattern.circular`'s axis origin. The window therefore -/// evaluates every value here and sends numbers. +/// Validate a typed count before sending its expression to the command. fn whole(app: &SolveApp, label: &str, text: &str) -> Result { let v = app.session.doc.eval(text.trim(), ValueKind::Unitless).map_err(|e| format!("{label}: {e}"))?; if !v.is_finite() || !(1.0..=MAX_COPIES).contains(&v) || (v - v.round()).abs() > 1e-9 { @@ -791,7 +785,7 @@ pub fn commands(app: &SolveApp, k: &Mod, inputs: &[SelInput], extra: &Map MAX_COPIES as u64 { return Err(format!("Quantity and Quantity 2 together must make at most {MAX_COPIES:.0} instances")); } - let mut p = json!({"entities": entities, "count": n1, "spacing": s1, "count2": n2, "spacing2": s2, "alignment": alignment, "alignment2": alignment2, "reversed": reversed, "reversed2": reversed2}); + let mut p = json!({"entities": entities, "count": count, "spacing": spacing, "count2": count2, "spacing2": spacing2, "alignment": alignment, "alignment2": alignment2, "reversed": reversed, "reversed2": reversed2}); // A picked direction that has no component in the sketch plane is reported rather // than quietly replaced by the default. for (index, vector_key, line_key) in [(1, "dir", "direction"), (2, "dir2", "direction2")] { @@ -826,10 +820,10 @@ pub fn commands(app: &SolveApp, k: &Mod, inputs: &[SelInput], extra: &Map().map_or_else(|_| json!(count.trim()), |_| json!(n)), "angle": a, "alignment": alignment, "reversed": reversed}), + json!({"entities": entities, "center": center, "count": count, "angle": angle, "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.rs index 854ce6fd6..3a04a73b5 100644 --- a/crates/ui-egui/src/sketch_modify_ui_tests.rs +++ b/crates/ui-egui/src/sketch_modify_ui_tests.rs @@ -523,7 +523,7 @@ fn rectangular_sections_flip_and_center_independently_and_restore_even_counts_wh assert_eq!(commands[0].1["alignment"], "center"); assert_eq!(commands[0].1["alignment2"], "right"); assert_eq!(commands[0].1["reversed2"], true); - assert_eq!(commands[0].1["count"], 4); + assert_eq!(commands[0].1["count"], "4"); h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap(); h.settle(); assert!(h.app.dialog.is_none()); @@ -556,10 +556,10 @@ fn typed_counts_and_spacings_reach_the_command_with_the_second_direction() { assert_eq!(cmds.len(), 1); assert_eq!(cmds[0].0, "sketch.pattern.rectangular"); // The click tool could only ever send a count of 3 and no second count at all. - assert_eq!(cmds[0].1["count"], json!(5)); - assert_eq!(cmds[0].1["spacing"], json!(20.0)); - assert_eq!(cmds[0].1["count2"], json!(2)); - assert_eq!(cmds[0].1["spacing2"], json!(15.0)); + assert_eq!(cmds[0].1["count"], json!("5")); + assert_eq!(cmds[0].1["spacing"], json!("20")); + assert_eq!(cmds[0].1["count2"], json!("2")); + assert_eq!(cmds[0].1["spacing2"], json!("15 mm")); assert!(cmds[0].1.get("dir").is_none(), "an unpicked direction leaves the command's own default"); } @@ -624,18 +624,16 @@ fn an_axis_perpendicular_to_the_sketch_is_reported_not_silently_replaced() { assert!(e.contains("sketch plane"), "{e}"); } -/// Upstream #218 is the same shape: `solid.pattern.circular` took expressions in its axis origin -/// 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. +/// Count expressions stay linked to parameters when sent to the command. #[test] -fn a_count_expression_is_evaluated_rather_than_sent_as_a_string() { +fn a_count_expression_reaches_the_command_as_text() { let (mut h, id) = open("sketch.pattern.rectangular"); h.app.run("parameters.add", json!({"name": "n", "expression": "4", "unit": ""})).unwrap(); h.app.dialog.as_mut().unwrap().inputs[0].items = vec![Sel::SketchCurve { id, sketch: None }]; rect(&mut h, "n", "10", "1", "10"); let d = h.app.dialog.clone().unwrap(); let cmds = apply_commands(&h.app, &d).unwrap(); - assert_eq!(cmds[0].1["count"], json!(4)); + assert_eq!(cmds[0].1["count"], json!("n")); } #[test] @@ -726,12 +724,12 @@ fn the_typed_count_and_total_angle_reach_the_command() { assert_eq!(cmds.len(), 1); assert_eq!(cmds[0].0, "sketch.pattern.circular"); // The click flow could only ever send a count of 6, and never any angle. - assert_eq!(cmds[0].1["count"], json!(4)); - assert_eq!(cmds[0].1["angle"], json!(180.0)); + assert_eq!(cmds[0].1["count"], json!("4")); + assert_eq!(cmds[0].1["angle"], json!("180")); assert_eq!(cmds[0].1["center"], json!(centre), "the bare point id the command resolves"); circ(&mut h, "4", "90 deg"); let d = h.app.dialog.clone().unwrap(); - assert_eq!(apply_commands(&h.app, &d).unwrap()[0].1["angle"], json!(90.0)); + assert_eq!(apply_commands(&h.app, &d).unwrap()[0].1["angle"], json!("90 deg")); } #[test] @@ -744,8 +742,8 @@ fn circular_flip_and_center_buttons_apply_and_reopen_the_saved_placement() { h.step(&json!({"click":{"handle":"dialog:Alignment:Flip direction"}})).unwrap(); let d = h.app.dialog.clone().unwrap(); let params = &apply_commands(&h.app, &d).unwrap()[0].1; - assert_eq!(params["count"], json!(6)); - assert_eq!(params["angle"], json!(90.)); + assert_eq!(params["count"], json!("6")); + assert_eq!(params["angle"], json!("90 deg")); assert_eq!(params["alignment"], json!("center")); assert_eq!(params["reversed"], json!(true)); h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap(); @@ -769,17 +767,14 @@ fn circular_flip_and_center_buttons_apply_and_reopen_the_saved_placement() { assert_eq!(params["reversed"], json!(true)); } -/// The same lesson as upstream #218: `num` reads a JSON number only, and `sketch.pattern.circular` -/// falls back to a full turn when `angle` is anything else. An expression has to be evaluated -/// here or it disappears in silence. +/// Angle expressions stay linked to parameters when sent to the command. #[test] -fn an_angle_expression_is_evaluated_rather_than_sent_as_a_string() { +fn an_angle_expression_reaches_the_command_as_text() { let (mut h, _) = open_circ(); h.app.run("parameters.add", json!({"name": "sweep", "expression": "120", "unit": "deg"})).unwrap(); circ(&mut h, "3", "sweep"); let d = h.app.dialog.clone().unwrap(); - let angle = apply_commands(&h.app, &d).unwrap()[0].1["angle"].as_f64().expect("a number, not the text `sweep`"); - assert!((angle - 120.0).abs() < 1e-9, "{angle}"); + assert_eq!(apply_commands(&h.app, &d).unwrap()[0].1["angle"], "sweep"); } #[test]