diff --git a/assets/icons/ui/design/palette.toml b/assets/icons/ui/design/palette.toml
index 00674439b..c23f252be 100644
--- a/assets/icons/ui/design/palette.toml
+++ b/assets/icons/ui/design/palette.toml
@@ -188,7 +188,7 @@ surface = [
sketch = [
"arc3", "arc_center", "arc_slot", "arc_slot_center", "arc_tangent",
"blend", "circle", "circle2", "circle3", "circle_tt",
- "circle_ttt", "conic", "constrainer", "dimension", "ellipse",
+ "circle_ttt", "conic", "constrainer", "dimension", "ellipse", "equation_curve",
"extend", "finish", "fit_section", "include",
"intersect", "intersection_curve", "iso_curve", "line", "line_mid",
"offset", "offset_two_sides", "offset_symmetric", "point", "polygon", "polygon_circumscribed", "polygon_edge",
diff --git a/assets/icons/ui/design/requested_icons.txt b/assets/icons/ui/design/requested_icons.txt
index ddb72f14d..038e79783 100644
--- a/assets/icons/ui/design/requested_icons.txt
+++ b/assets/icons/ui/design/requested_icons.txt
@@ -95,6 +95,7 @@ edit false
ellipse false
emboss false
environment_map false
+equation_curve false
error false
explode false
export false
diff --git a/assets/icons/ui/design/svg/model/equation_curve.svg b/assets/icons/ui/design/svg/model/equation_curve.svg
new file mode 100644
index 000000000..b9ca6f134
--- /dev/null
+++ b/assets/icons/ui/design/svg/model/equation_curve.svg
@@ -0,0 +1,9 @@
+
diff --git a/assets/locales/pending/sketch-equation-curve.json b/assets/locales/pending/sketch-equation-curve.json
new file mode 100644
index 000000000..53ba7a77e
--- /dev/null
+++ b/assets/locales/pending/sketch-equation-curve.json
@@ -0,0 +1,114 @@
+{
+ "en": {
+ "cmd.sketch_equation_curve": "Equation Curve",
+ "cmd.sketch_equation_curve_edit": "Edit Equation Curve",
+ "help.sketch.equation_curve": "Draws a curve from formulas: x(t) and y(t), or y = f(x), over a range. The formulas can use parameters and the curve follows them: use it for a sine wave, a spiral or a gear tooth's involute.",
+ "ui.heading_equation_curve": "EQUATION CURVE",
+ "ui.equation_form": "Form",
+ "ui.equation_parametric": "Parametric",
+ "ui.equation_explicit": "Explicit",
+ "ui.equation_end": "End",
+ "ui.equation_note": "The variable is a plain number: sin(t) takes it in radians. A result without a unit is in the design's unit.",
+ "ui.equation_x_of_t": "x(t)",
+ "ui.equation_y_of_t": "y(t)",
+ "ui.equation_y_of_x": "y(x)"
+ },
+ "ja": {
+ "cmd.sketch_equation_curve": "方程式曲線",
+ "cmd.sketch_equation_curve_edit": "方程式曲線を編集",
+ "help.sketch.equation_curve": "x(t) と y(t)、または y = f(x) の式から、範囲を指定して曲線を描きます。式にはパラメーターを使え、曲線はその変更に追従します。正弦波、らせん、歯車のインボリュートなどに使います。",
+ "ui.heading_equation_curve": "方程式曲線",
+ "ui.equation_form": "形式",
+ "ui.equation_parametric": "パラメトリック",
+ "ui.equation_explicit": "陽関数",
+ "ui.equation_end": "終了",
+ "ui.equation_note": "変数は単位のない数値です。sin(t) はラジアンとして扱います。単位のない結果はデザインの単位になります。",
+ "ui.equation_x_of_t": "x(t)",
+ "ui.equation_y_of_t": "y(t)",
+ "ui.equation_y_of_x": "y(x)"
+ },
+ "zh": {
+ "cmd.sketch_equation_curve": "方程曲线",
+ "cmd.sketch_equation_curve_edit": "编辑方程曲线",
+ "help.sketch.equation_curve": "在一个范围内按公式绘制曲线:x(t) 和 y(t),或 y = f(x)。公式可以使用参数,曲线随参数变化。适用于正弦波、螺旋线或齿轮的渐开线。",
+ "ui.heading_equation_curve": "方程曲线",
+ "ui.equation_form": "形式",
+ "ui.equation_parametric": "参数式",
+ "ui.equation_explicit": "显式",
+ "ui.equation_end": "结束",
+ "ui.equation_note": "变量是不带单位的数:sin(t) 按弧度计算。不带单位的结果采用设计的单位。",
+ "ui.equation_x_of_t": "x(t)",
+ "ui.equation_y_of_t": "y(t)",
+ "ui.equation_y_of_x": "y(x)"
+ },
+ "ar": {
+ "cmd.sketch_equation_curve": "منحنى معادلة",
+ "cmd.sketch_equation_curve_edit": "تحرير منحنى المعادلة",
+ "help.sketch.equation_curve": "يرسم منحنى من صيغ على مدى: x(t) و y(t)، أو y = f(x). يمكن أن تستخدم الصيغ المعلمات فيتبعها المنحنى: استخدمه لموجة جيبية أو لولب أو منحنى انفلات لسن ترس.",
+ "ui.heading_equation_curve": "منحنى معادلة",
+ "ui.equation_form": "الشكل",
+ "ui.equation_parametric": "بارامتري",
+ "ui.equation_explicit": "صريح",
+ "ui.equation_end": "النهاية",
+ "ui.equation_note": "المتغير رقم بلا وحدة: تأخذه sin(t) بالراديان. والنتيجة التي بلا وحدة تكون بوحدة التصميم.",
+ "ui.equation_x_of_t": "x(t)",
+ "ui.equation_y_of_t": "y(t)",
+ "ui.equation_y_of_x": "y(x)"
+ },
+ "he": {
+ "cmd.sketch_equation_curve": "עקומת משוואה",
+ "cmd.sketch_equation_curve_edit": "עריכת עקומת משוואה",
+ "help.sketch.equation_curve": "משרטט עקומה מנוסחאות על פני טווח: x(t) ו־y(t), או y = f(x). הנוסחאות יכולות להשתמש בפרמטרים והעקומה עוקבת אחריהם: לגל סינוס, לספירלה או לאבולבנטה של שן גלגל שיניים.",
+ "ui.heading_equation_curve": "עקומת משוואה",
+ "ui.equation_form": "צורה",
+ "ui.equation_parametric": "פרמטרית",
+ "ui.equation_explicit": "מפורשת",
+ "ui.equation_end": "סוף",
+ "ui.equation_note": "המשתנה הוא מספר ללא יחידה: sin(t) מקבלת אותו ברדיאנים. תוצאה ללא יחידה היא ביחידה של התכנון.",
+ "ui.equation_x_of_t": "x(t)",
+ "ui.equation_y_of_t": "y(t)",
+ "ui.equation_y_of_x": "y(x)"
+ },
+ "vi": {
+ "cmd.sketch_equation_curve": "Đường cong phương trình",
+ "cmd.sketch_equation_curve_edit": "Sửa đường cong phương trình",
+ "help.sketch.equation_curve": "Vẽ một đường cong từ công thức trên một khoảng: x(t) và y(t), hoặc y = f(x). Công thức có thể dùng tham số và đường cong thay đổi theo: dùng cho sóng sin, đường xoắn ốc hay đường thân khai của răng bánh răng.",
+ "ui.heading_equation_curve": "ĐƯỜNG CONG PHƯƠNG TRÌNH",
+ "ui.equation_form": "Dạng",
+ "ui.equation_parametric": "Tham số",
+ "ui.equation_explicit": "Tường minh",
+ "ui.equation_end": "Kết thúc",
+ "ui.equation_note": "Biến là một số không có đơn vị: sin(t) hiểu nó theo radian. Kết quả không có đơn vị dùng đơn vị của thiết kế.",
+ "ui.equation_x_of_t": "x(t)",
+ "ui.equation_y_of_t": "y(t)",
+ "ui.equation_y_of_x": "y(x)"
+ },
+ "de": {
+ "cmd.sketch_equation_curve": "Gleichungskurve",
+ "cmd.sketch_equation_curve_edit": "Gleichungskurve bearbeiten",
+ "help.sketch.equation_curve": "Zeichnet eine Kurve aus Formeln über einen Bereich: x(t) und y(t) oder y = f(x). Die Formeln können Parameter verwenden, und die Kurve folgt ihnen: für eine Sinuswelle, eine Spirale oder die Evolvente eines Zahnrads.",
+ "ui.heading_equation_curve": "GLEICHUNGSKURVE",
+ "ui.equation_form": "Form",
+ "ui.equation_parametric": "Parametrisch",
+ "ui.equation_explicit": "Explizit",
+ "ui.equation_end": "Ende",
+ "ui.equation_note": "Die Variable ist eine Zahl ohne Einheit: sin(t) liest sie im Bogenmaß. Ein Ergebnis ohne Einheit ist in der Einheit der Konstruktion.",
+ "ui.equation_x_of_t": "x(t)",
+ "ui.equation_y_of_t": "y(t)",
+ "ui.equation_y_of_x": "y(x)"
+ },
+ "ko": {
+ "cmd.sketch_equation_curve": "방정식 곡선",
+ "cmd.sketch_equation_curve_edit": "방정식 곡선 편집",
+ "help.sketch.equation_curve": "범위에 걸쳐 수식으로 곡선을 그립니다: x(t)와 y(t), 또는 y = f(x). 수식에 매개변수를 쓸 수 있으며 곡선이 그 값을 따라갑니다. 사인파, 나선, 기어 이의 인벌류트에 사용합니다.",
+ "ui.heading_equation_curve": "방정식 곡선",
+ "ui.equation_form": "형식",
+ "ui.equation_parametric": "매개변수식",
+ "ui.equation_explicit": "명시적",
+ "ui.equation_end": "끝",
+ "ui.equation_note": "변수는 단위가 없는 수입니다. sin(t)는 라디안으로 읽습니다. 단위가 없는 결과는 디자인 단위입니다.",
+ "ui.equation_x_of_t": "x(t)",
+ "ui.equation_y_of_t": "y(t)",
+ "ui.equation_y_of_x": "y(x)"
+ }
+}
\ No newline at end of file
diff --git a/attribution/pending/sketch-equation-curve.md b/attribution/pending/sketch-equation-curve.md
new file mode 100644
index 000000000..7aed13129
--- /dev/null
+++ b/attribution/pending/sketch-equation-curve.md
@@ -0,0 +1 @@
+| assets/icons/ui/design/svg/model/equation_curve.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 |
diff --git a/crates/doc/src/clipboard.rs b/crates/doc/src/clipboard.rs
index e7dee1829..83cb3b733 100644
--- a/crates/doc/src/clipboard.rs
+++ b/crates/doc/src/clipboard.rs
@@ -253,6 +253,12 @@ impl crate::Feature {
for e in sketch.text_exprs_mut() {
*e = clone_expression(e, parameters);
}
+ // An equation curve's variable is its own: a parameter of that name is not renamed in it.
+ for (variable, e) in sketch.equation_exprs_mut() {
+ let others: BTreeMap =
+ parameters.iter().filter(|(old, _)| old.as_str() != variable).map(|(o, n)| (o.clone(), n.clone())).collect();
+ *e = clone_expression(e, &others);
+ }
for link in &mut sketch.links {
remap_link(&mut link.source, ids, names, bodies, 0);
for n in link.face_name.iter_mut().chain(&mut link.edge_name) {
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index ddb2da037..9f06500ee 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -3889,10 +3889,11 @@ impl Document {
}
}
- /// Apply parameter values to every dimension in a sketch, and to its points placed by
- /// parameters (in place).
+ /// Apply parameter values to every dimension in a sketch, to its points placed by parameters
+ /// and to its equation curves (in place).
pub fn apply_dimension_values(&self, vals: &std::collections::BTreeMap, sk: &mut Sketch) -> Result<()> {
self.apply_point_values(vals, sk)?;
+ self.apply_equation_values(vals, sk)?;
self.apply_pattern_values(vals, sk)?;
for c in &mut sk.constraints {
if let Some(p) = &c.param {
diff --git a/crates/doc/src/format/pending/sketch-equation-curves.rs b/crates/doc/src/format/pending/sketch-equation-curves.rs
new file mode 100644
index 000000000..d63484aa9
--- /dev/null
+++ b/crates/doc/src/format/pending/sketch-equation-curves.rs
@@ -0,0 +1,5 @@
+//! A sketch saves its equation curves (#8352) in `equations`: for each, the fit point spline it
+//! places, its formulas (x(t) and y(t), or y = f(x) without `x`), the range of the variable and
+//! the tolerance its points were chosen for. An older design has none, and its sketches mean
+//! what they meant. The last release refuses a design that has them (it asks for an update)
+//! instead of opening the splines as plain fixed splines that no longer follow their formulas.
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 09b933615..0a750d01b 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -71,6 +71,7 @@ pub mod render_settings;
pub mod render_surface;
pub use project3d::iso_grid;
pub mod sheet;
+pub mod sketch_equation;
pub mod text_params;
pub use assembly::{
diff --git a/crates/doc/src/params.rs b/crates/doc/src/params.rs
index 6def88716..eaff09f51 100644
--- a/crates/doc/src/params.rs
+++ b/crates/doc/src/params.rs
@@ -896,6 +896,18 @@ impl Document {
n += 1;
}
}
+ // An equation curve's variable hides a parameter of its name: such a parameter is
+ // not what its formulas refer to.
+ for (variable, e) in sketch.equation_exprs_mut() {
+ if variable == old {
+ continue;
+ }
+ let r = expr::rename_reference(e, old, new);
+ if r != *e {
+ *e = r;
+ n += 1;
+ }
+ }
for e in sketch.text_word_exprs_mut() {
let r = crate::text_params::rename_reference(e, old, new);
if r != *e {
diff --git a/crates/doc/src/sketch_equation.rs b/crates/doc/src/sketch_equation.rs
new file mode 100644
index 000000000..dcfdbcbbc
--- /dev/null
+++ b/crates/doc/src/sketch_equation.rs
@@ -0,0 +1,363 @@
+//! Equation curves (#8352): the points of a sketch curve worked out from its formulas over the
+//! design's parameters. The formulas are evaluated at evenly spaced values of the curve's
+//! variable; the sketch draws a cubic fit spline through those points. How many points: as many
+//! as it takes for the spline to stay within the curve's tolerance of the formulas, checked
+//! between the points, up to the most a spline takes. When the parameters change, the same
+//! number of points is placed again (`Document::apply_equation_values`), before every solve.
+
+use std::collections::BTreeMap;
+
+use solidcraft_geom::Vec2;
+use solidcraft_sketch::{EquationCurve, MAX_COORD, MAX_EQUATION_TEXT, MAX_SPLINE_POINTS, Sketch, fit_beziers_mode};
+
+use crate::expr::{self, Defaults, Kind, Value};
+use crate::{DocError, Result};
+
+/// The tolerance a new equation curve gets (mm).
+pub const DEFAULT_TOLERANCE: f64 = 0.01;
+/// The tightest and loosest tolerances (mm).
+pub const MIN_TOLERANCE: f64 = 1e-4;
+pub const MAX_TOLERANCE: f64 = 10.0;
+/// The fewest points a fit starts from.
+const FIRST_COUNT: usize = 9;
+/// The widest range of the variable.
+const MAX_RANGE: f64 = 1e6;
+/// How many times the point count is raised before the fit gives up.
+const MAX_ROUNDS: usize = 12;
+
+/// An equation curve's points and how well the spline through them follows the formulas.
+#[derive(Clone, Debug, PartialEq)]
+pub struct EquationFit {
+ /// The spline's points in order; a closed curve's last point is its first one again.
+ pub points: Vec,
+ /// The curve ends where it starts: the spline closes smoothly there.
+ pub closed: bool,
+ /// The largest distance (mm) found between the spline and the formulas.
+ pub deviation: f64,
+}
+
+/// How bare numbers read in the formulas: angles in radians (the variable is a plain number,
+/// `sin(t)` its sine), lengths in the design's unit.
+fn defaults(vals: &BTreeMap) -> Defaults {
+ let len = vals.get(crate::eval::DESIGN_LEN).map(|v| v.v).filter(|v| v.is_finite() && *v > 0.0).unwrap_or(1.0);
+ Defaults { len, ang: 1.0 }
+}
+
+fn checked_text<'a>(what: &str, e: &'a str) -> Result<&'a str> {
+ let e = e.trim();
+ if e.is_empty() {
+ return Err(DocError::Invalid(format!("{what} is empty")));
+ }
+ if e.chars().count() > MAX_EQUATION_TEXT {
+ return Err(DocError::Invalid(format!("{what} is longer than {MAX_EQUATION_TEXT} characters")));
+ }
+ Ok(e)
+}
+
+/// A formula's value (mm) where the variable is `at`. The variable hides a parameter of its name.
+fn formula(vals: &BTreeMap, e: &str, variable: &str, at: f64, d: Defaults) -> Result {
+ let lookup = |n: &str| {
+ if n == variable { Ok(Value::num(at)) } else { vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))) }
+ };
+ let v = expr::eval_with_defaults(e, &lookup, d)?.to_kind_in(Kind::Length, d)?;
+ if v.is_finite() && v.abs() < MAX_COORD { Ok(v) } else { Err(DocError::Expr("the curve goes out of range".into())) }
+}
+
+/// Where the variable starts or ends, as the plain number the formulas see: a number, an angle
+/// (in radians) or a length (in the design's unit).
+fn range_end(vals: &BTreeMap, e: &str, d: Defaults) -> Result {
+ let v = expr::eval_with_defaults(e, &|n| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))), d)?;
+ let out = match v.kind() {
+ Some(Kind::Unitless | Kind::Angle) => v.v,
+ Some(Kind::Length) => v.v / d.len,
+ None => return Err(DocError::Expr(format!("expected a number, an angle or a length, got {}", v.describe()))),
+ };
+ if out.is_finite() { Ok(out) } else { Err(DocError::Expr("not a finite number".into())) }
+}
+
+/// The variable's range, checked.
+fn range(vals: &BTreeMap, eq: &EquationCurve, d: Defaults) -> Result<(f64, f64)> {
+ let a = range_end(vals, checked_text("the start", &eq.start)?, d).map_err(|e| DocError::Expr(format!("start: {e}")))?;
+ let b = range_end(vals, checked_text("the end", &eq.end)?, d).map_err(|e| DocError::Expr(format!("end: {e}")))?;
+ if (b - a).abs() <= 1e-12 * a.abs().max(b.abs()).max(1.0) {
+ return Err(DocError::Invalid("the start and the end of the range must differ".into()));
+ }
+ if (b - a).abs() > MAX_RANGE {
+ return Err(DocError::Invalid(format!("the range is wider than {MAX_RANGE}")));
+ }
+ Ok((a, b))
+}
+
+/// The curve's point where the variable is `at`.
+fn point_at(vals: &BTreeMap, eq: &EquationCurve, at: f64, d: Defaults) -> Result {
+ let variable = eq.variable();
+ let x = match &eq.x {
+ Some(e) => formula(vals, e, variable, at, d).map_err(|e| DocError::Expr(format!("x: {e}")))?,
+ // The explicit form: x is the variable, in the design's unit.
+ None => {
+ let x = at * d.len;
+ if !(x.is_finite() && x.abs() < MAX_COORD) {
+ return Err(DocError::Expr("the curve goes out of range".into()));
+ }
+ x
+ }
+ };
+ let y = formula(vals, &eq.y, variable, at, d).map_err(|e| DocError::Expr(format!("y: {e}")))?;
+ Ok(Vec2::new(x, y))
+}
+
+/// The formulas' points at `count` evenly spaced values of the variable, from start to end.
+fn samples(vals: &BTreeMap, eq: &EquationCurve, (a, b): (f64, f64), count: usize, d: Defaults) -> Result> {
+ let last = count.saturating_sub(1).max(1) as f64;
+ (0..count)
+ .map(|i| {
+ let at = a + (b - a) * (i as f64 / last);
+ point_at(vals, eq, at, d).map_err(|e| DocError::Expr(format!("at {} = {}: {e}", eq.variable(), short(at))))
+ })
+ .collect()
+}
+
+/// A number short enough for a message.
+fn short(v: f64) -> String {
+ let s = format!("{v:.6}");
+ s.trim_end_matches('0').trim_end_matches('.').to_string()
+}
+
+/// The size of the curve: the larger side of its box (for closing tolerances).
+fn extent(points: &[Vec2]) -> f64 {
+ let (mut lo, mut hi) = (Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY));
+ for p in points {
+ lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y));
+ hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y));
+ }
+ (hi.x - lo.x).max(hi.y - lo.y).max(0.0)
+}
+
+/// Does a curve through these samples end where it starts?
+fn closes(points: &[Vec2]) -> bool {
+ match (points.first(), points.last()) {
+ (Some(a), Some(b)) => points.len() >= 4 && a.dist(*b) <= 1e-7 * extent(points).max(1.0),
+ _ => false,
+ }
+}
+
+/// Refuse samples a spline cannot pass through: two in a row on the same spot, or all of them.
+fn check_samples(points: &[Vec2], closed: bool) -> Result<()> {
+ let size = extent(points);
+ if size <= 1e-9 {
+ return Err(DocError::Invalid("the formulas give the same point all along the range".into()));
+ }
+ let spans = if closed { points.len().saturating_sub(1) } else { points.len() };
+ for w in points.windows(2).take(spans) {
+ if let [p, q] = w
+ && p.dist(*q) <= 1e-9 * size.max(1.0)
+ {
+ return Err(DocError::Invalid("the curve stands still between two of its points: narrow the range or use fewer points".into()));
+ }
+ }
+ Ok(())
+}
+
+/// Distance from `q` to the cubic Bézier `b`, sampled finely.
+fn bezier_distance(b: &[Vec2; 4], q: Vec2) -> f64 {
+ const STEPS: usize = 32;
+ let at = |t: f64| {
+ let s = 1.0 - t;
+ b[0] * (s * s * s) + b[1] * (3.0 * t * s * s) + b[2] * (3.0 * t * t * s) + b[3] * (t * t * t)
+ };
+ let mut best = f64::INFINITY;
+ let mut prev = at(0.0);
+ for i in 1..=STEPS {
+ let next = at(i as f64 / STEPS as f64);
+ let d = next - prev;
+ let l2 = d.len2();
+ let t = if l2 > 0.0 { ((q - prev).dot(d) / l2).clamp(0.0, 1.0) } else { 0.0 };
+ best = best.min(q.dist(prev + d * t));
+ prev = next;
+ }
+ best
+}
+
+/// How far the spline through `points` strays from the formulas: the largest distance from the
+/// formulas' points a quarter, a half and three quarters of the way between two samples to the
+/// spline's piece between them.
+fn deviation(vals: &BTreeMap, eq: &EquationCurve, (a, b): (f64, f64), points: &[Vec2], closed: bool, d: Defaults) -> Result {
+ let pieces = fit_beziers_mode(points, closed).map_err(|e| DocError::Invalid(e.to_string()))?;
+ let step = (b - a) / points.len().saturating_sub(1).max(1) as f64;
+ let mut worst: f64 = 0.0;
+ for (i, piece) in pieces.iter().enumerate() {
+ for k in [0.25, 0.5, 0.75] {
+ let q = point_at(vals, eq, a + step * (i as f64 + k), d)?;
+ worst = worst.max(bezier_distance(piece, q));
+ }
+ }
+ Ok(worst)
+}
+
+/// Check an equation's text and tolerance before any evaluation.
+pub fn check(eq: &EquationCurve) -> Result<()> {
+ if let Some(x) = &eq.x {
+ checked_text("x(t)", x)?;
+ }
+ checked_text(if eq.x.is_some() { "y(t)" } else { "y(x)" }, &eq.y)?;
+ checked_text("the start", &eq.start)?;
+ checked_text("the end", &eq.end)?;
+ if !(eq.tolerance.is_finite() && (MIN_TOLERANCE..=MAX_TOLERANCE).contains(&eq.tolerance)) {
+ return Err(DocError::Invalid(format!("the tolerance must be from {MIN_TOLERANCE} mm to {MAX_TOLERANCE} mm")));
+ }
+ Ok(())
+}
+
+/// The points of `count` samples (a closed curve's last one is its first), whether it closes,
+/// and how far the spline through them strays.
+pub fn sample(vals: &BTreeMap, eq: &EquationCurve, count: usize, closed: Option) -> Result {
+ check(eq)?;
+ if !(2..=MAX_SPLINE_POINTS).contains(&count) {
+ return Err(DocError::Invalid(format!("an equation curve takes 2 to {MAX_SPLINE_POINTS} points")));
+ }
+ let d = defaults(vals);
+ let span = range(vals, eq, d)?;
+ let mut points = samples(vals, eq, span, count, d)?;
+ let closed = closed.unwrap_or_else(|| closes(&points)) && count >= 4;
+ if closed
+ && let Some(first) = points.first().copied()
+ && let Some(last) = points.last_mut()
+ {
+ *last = first;
+ }
+ check_samples(&points, closed)?;
+ let deviation = deviation(vals, eq, span, &points, closed, d)?;
+ Ok(EquationFit { points, closed, deviation })
+}
+
+/// The points of an equation curve, as few as keep the spline within its tolerance of the
+/// formulas. Refused when even the most points a spline takes are not close enough.
+pub fn fit(vals: &BTreeMap, eq: &EquationCurve) -> Result {
+ let mut count = FIRST_COUNT;
+ for _ in 0..MAX_ROUNDS {
+ let fit = sample(vals, eq, count, None)?;
+ if fit.deviation <= eq.tolerance {
+ return Ok(fit);
+ }
+ if count >= MAX_SPLINE_POINTS {
+ return Err(DocError::Invalid(format!(
+ "even {MAX_SPLINE_POINTS} points stray {} mm from the formulas, more than the tolerance of {} mm: raise the tolerance or narrow the range",
+ short(fit.deviation),
+ short(eq.tolerance)
+ )));
+ }
+ // A cubic fit's error falls with the fourth power of the spacing: aim a little past
+ // what that asks for, at least half as many points again.
+ let ratio = (fit.deviation / eq.tolerance).powf(0.25) * 1.2;
+ let next = (count as f64 * ratio.max(1.5)).ceil();
+ count = if next.is_finite() && next < MAX_SPLINE_POINTS as f64 { next as usize } else { MAX_SPLINE_POINTS };
+ }
+ Err(DocError::Invalid("the equation curve's points could not be fitted".into()))
+}
+
+impl crate::Document {
+ /// Place the points of the sketch's equation curves where their formulas put them now (in
+ /// place), with the number of points each has. Their points are fixed, so the solve keeps
+ /// them there. A curve that is gone or is no longer a fit point spline is left as it is.
+ pub fn apply_equation_values(&self, vals: &BTreeMap, sk: &mut Sketch) -> Result<()> {
+ for k in 0..sk.equations.len() {
+ let Some(eq) = sk.equations.get(k).cloned() else { continue };
+ let Some(ci) = sk.curve_index(&eq.curve) else { continue };
+ let Some(solidcraft_sketch::CurveKind::Spline { pts, control: false, periodic, .. }) = sk.curves.get(ci).map(|c| &c.kind) else {
+ continue;
+ };
+ let (count, closed) = (pts.len(), *periodic);
+ let fit = sample(vals, &eq, count, Some(closed)).map_err(|e| DocError::Expr(format!("equation curve {}: {e}", eq.curve)))?;
+ sk.place_equation_points(ci, &fit.points)?;
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn eq(x: Option<&str>, y: &str, start: &str, end: &str) -> EquationCurve {
+ EquationCurve {
+ curve: String::new(),
+ x: x.map(str::to_string),
+ y: y.into(),
+ start: start.into(),
+ end: end.into(),
+ tolerance: DEFAULT_TOLERANCE,
+ }
+ }
+
+ #[test]
+ fn a_circle_closes_and_stays_within_the_tolerance() {
+ let vals = BTreeMap::new();
+ let fit = fit(&vals, &eq(Some("10 * cos(t)"), "10 * sin(t)", "0", "2 * pi")).unwrap();
+ assert!(fit.closed);
+ assert!(fit.deviation <= DEFAULT_TOLERANCE, "{}", fit.deviation);
+ for p in &fit.points {
+ assert!((p.len() - 10.0).abs() < 1e-9, "{p:?}");
+ }
+ assert_eq!(fit.points.first(), fit.points.last());
+ }
+
+ #[test]
+ fn the_variable_hides_a_parameter_and_parameters_drive_the_curve() {
+ let mut vals = BTreeMap::new();
+ vals.insert("t".to_string(), Value::length(1000.0));
+ vals.insert("amp".to_string(), Value::length(5.0));
+ let fit = fit(&vals, &eq(None, "amp * sin(x / 10)", "0 mm", "100 mm")).unwrap();
+ assert!(!fit.closed);
+ let (first, last) = (fit.points[0], *fit.points.last().unwrap());
+ assert!((first - Vec2::new(0.0, 0.0)).len() < 1e-9, "{first:?}");
+ assert!((last.x - 100.0).abs() < 1e-9 && (last.y - 5.0 * 10f64.sin()).abs() < 1e-9, "{last:?}");
+ assert!(fit.points.iter().all(|p| p.y.abs() <= 5.0 + 1e-9));
+ }
+
+ #[test]
+ fn a_design_in_inches_reads_bare_numbers_in_inches() {
+ let mut vals = BTreeMap::new();
+ vals.insert(crate::eval::DESIGN_LEN.to_string(), Value::num(25.4));
+ let fit = fit(&vals, &eq(Some("t"), "2", "0", "1")).unwrap();
+ let last = *fit.points.last().unwrap();
+ assert!((last - Vec2::new(25.4, 50.8)).len() < 1e-9, "{last:?}");
+ }
+
+ #[test]
+ fn more_points_where_the_tolerance_is_tighter() {
+ let vals = BTreeMap::new();
+ let mut e = eq(Some("t * cos(t)"), "t * sin(t)", "0", "6 * pi");
+ e.tolerance = 0.1;
+ let loose = fit(&vals, &e).unwrap();
+ e.tolerance = 0.005;
+ let tight = fit(&vals, &e).unwrap();
+ assert!(tight.points.len() > loose.points.len(), "{} vs {}", tight.points.len(), loose.points.len());
+ assert!(tight.deviation <= 0.005 && loose.deviation <= 0.1);
+ }
+
+ #[test]
+ fn hostile_formulas_and_ranges_are_refused() {
+ let vals = BTreeMap::new();
+ for (x, y, a, b, tol) in [
+ (Some("t"), "sqrt(t)", "-1", "1", DEFAULT_TOLERANCE),
+ (Some("t"), "1 / t", "-1", "1", DEFAULT_TOLERANCE),
+ (Some("t"), "t", "0", "0", DEFAULT_TOLERANCE),
+ (Some("t"), "t", "0", "1e300", DEFAULT_TOLERANCE),
+ (Some("t"), "t", "0", "nan", DEFAULT_TOLERANCE),
+ (Some("t * 1 deg"), "t", "0", "1", DEFAULT_TOLERANCE),
+ (Some("1e300 * t"), "t", "0", "1", DEFAULT_TOLERANCE),
+ (Some("5"), "5", "0", "1", DEFAULT_TOLERANCE),
+ (Some(""), "t", "0", "1", DEFAULT_TOLERANCE),
+ (Some("t"), "t", "0", "1", f64::NAN),
+ (Some("t"), "t", "0", "1", 0.0),
+ (Some("t"), "unknown_name * t", "0", "1", DEFAULT_TOLERANCE),
+ (Some("t"), "sin(1e5 * t)", "0", "1000", 1e-4),
+ ] {
+ let mut e = eq(x, y, a, b);
+ e.tolerance = tol;
+ assert!(fit(&vals, &e).is_err(), "{x:?} {y} {a}..{b} {tol}");
+ }
+ let long = "t + ".repeat(400) + "t";
+ assert!(fit(&vals, &eq(Some(&long), "t", "0", "1")).is_err());
+ }
+}
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index 894ddc769..fe99d0957 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -94,6 +94,7 @@ pub mod sketch_clipboard;
mod sketch_constraints;
mod sketch_create;
mod sketch_ends;
+mod sketch_equation;
mod sketch_freeform;
mod sketch_import;
mod sketch_inspect;
@@ -286,6 +287,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> {
let mut v: Vec<&'static CommandSpec> = Vec::new();
v.extend(sketch::COMMANDS.iter());
v.extend(sketch_create::COMMANDS.iter());
+ v.extend(sketch_equation::COMMANDS.iter());
v.extend(sketch_constraints::COMMANDS.iter());
v.extend(sketch_import::COMMANDS.iter());
v.extend(sketch_inspect::COMMANDS.iter());
diff --git a/crates/engine/src/cmd/sketch_equation.rs b/crates/engine/src/cmd/sketch_equation.rs
new file mode 100644
index 000000000..5aac5da3e
--- /dev/null
+++ b/crates/engine/src/cmd/sketch_equation.rs
@@ -0,0 +1,159 @@
+//! Equation curves (#8352): a sketch curve drawn from formulas, x(t) and y(t) over a range of t
+//! or y = f(x) over a range of x, in the design's expression language and parameters. The curve
+//! is a fit point spline through points worked out from the formulas, as many as keep it within
+//! a tolerance of them; it keeps its formulas, so it follows the parameters and can be edited.
+
+use serde_json::{Value, json};
+use solidcraft_doc::sketch_equation::{self, DEFAULT_TOLERANCE, EquationFit};
+use solidcraft_sketch::{EquationCurve, Sketch};
+
+use super::sketch::{edit, mark_construction};
+use super::{CommandSpec, in_sketch};
+use crate::params::bad;
+use crate::schema::sketch_equation::{EquationCurveParams, EquationCurveResult, EquationEditParams, EquationEditResult};
+use crate::schema::{TypedContract, output_schema_for};
+use crate::{Result, Session};
+
+#[cfg(test)]
+#[path = "sketch_equation_tests.rs"]
+mod tests;
+
+const CREATE_CONTRACT: TypedContract = TypedContract::new();
+const EDIT_CONTRACT: TypedContract = TypedContract::new();
+
+pub static COMMANDS: &[CommandSpec] = &[
+ CommandSpec::new("sketch.equation_curve", "Equation Curve", crate::checked!("sketch.equation_curve", create))
+ .at("SKETCH", "CREATE")
+ .icon("equation_curve")
+ .enabled(in_sketch)
+ .contract(&CREATE_CONTRACT)
+ .output(output_schema_for::)
+ .params(concat!(
+ "x: x(t), y: y(t): formulas of t in the design's expression language and parameters (\"r * (cos(t) + t * sin(t))\"); or explicit: true and y: f(x) alone (no x); \
+ start, end: the range of t (or of x): a number or an expression (\"2 * pi\", \"360 deg\" is 2·pi, a length is in the design's unit); \
+ tolerance?: mm (default 0.01): how far the curve may stray from the formulas (0.0001 to 10); construction?: bool. \
+ The variable is a plain number: sin(t) reads it in radians; a result without a unit is in the design's length unit. \
+ Makes a fit point spline through fixed points, as many as the tolerance needs (up to 500), closed smoothly when it ends where it starts; \
+ the points are placed again from the formulas whenever the parameters change. Returns curve, points (how many), closed, deviation (mm)",
+ created_doc!()
+ )),
+ CommandSpec::new("sketch.equation_curve.edit", "Edit Equation Curve", crate::checked!("sketch.equation_curve.edit", edit_curve))
+ .icon("equation_curve")
+ .enabled(in_sketch)
+ .contract(&EDIT_CONTRACT)
+ .output(output_schema_for::)
+ .params(
+ "curve: an equation curve's id; x?, y?, explicit?, start?, end?, tolerance?: as in sketch.equation_curve, each kept when left out (explicit: true drops x; false needs x). \
+ The points are chosen again for the new formulas; the curve's start point (and the end point of an open curve) keeps its id, so geometry joined there stays joined. Returns curve, points, closed, deviation",
+ ),
+];
+
+/// A formula or range parameter: a string (an expression) or a number.
+fn text(p: &Value, cmd: &str, key: &str) -> Result