diff --git a/assets/locales/pending/ellipse-axes.json b/assets/locales/pending/ellipse-axes.json new file mode 100644 index 000000000..017530aff --- /dev/null +++ b/assets/locales/pending/ellipse-axes.json @@ -0,0 +1,38 @@ +{ + "en": { + "prefs.sketch.ellipse_axes": "Draw ellipses with their axes", + "prefs.sketch.ellipse_axes_note": "The major and minor axes as construction lines, so the half-axes and axes can be dimensioned. Off: the ellipse alone, and D on it gives its minor radius wherever the value is pulled, drawn and labelled R as before." + }, + "ar": { + "prefs.sketch.ellipse_axes": "رسم القطوع الناقصة مع محاورها", + "prefs.sketch.ellipse_axes_note": "المحوران الأكبر والأصغر كخطوط مساعدة، لتحديد أبعاد أنصاف المحاور والمحاور. عند الإيقاف: القطع الناقص وحده، ويعطي D عليه نصف قطره الأصغر أينما سُحبت القيمة، مرسومًا ومُعلَّمًا بـ R كما في السابق." + }, + "de": { + "prefs.sketch.ellipse_axes": "Ellipsen mit ihren Achsen zeichnen", + "prefs.sketch.ellipse_axes_note": "Haupt- und Nebenachse als Konstruktionslinien, damit Halbachsen und Achsen bemaßt werden können. Aus: nur die Ellipse, und D darauf ergibt ihren Nebenradius, wohin der Wert auch gezogen wird, gezeichnet und mit R beschriftet wie bisher." + }, + "he": { + "prefs.sketch.ellipse_axes": "שרטוט אליפסות עם הצירים שלהן", + "prefs.sketch.ellipse_axes_note": "הציר הראשי והציר המשני כקווי עזר, כדי שאפשר יהיה לתת מידות לחצאי הצירים ולצירים. כבוי: האליפסה בלבד, ו-D עליה נותן את הרדיוס המשני שלה בכל מקום שאליו נגרר הערך, משורטט ומסומן R כמו קודם." + }, + "ja": { + "prefs.sketch.ellipse_axes": "楕円を軸と一緒に描く", + "prefs.sketch.ellipse_axes_note": "長軸と短軸をコンストラクション線として描き、半軸と軸に寸法を付けられるようにします。オフ: 楕円のみを描き、D で短半径を寸法にします。値をどこへ引いても、これまでどおり R 付きで描かれます。" + }, + "ko": { + "prefs.sketch.ellipse_axes": "타원을 축과 함께 그리기", + "prefs.sketch.ellipse_axes_note": "장축과 단축을 구성선으로 그려 반축과 축에 치수를 지정할 수 있습니다. 끄면: 타원만 그리며, D는 값을 어디로 끌든 단반경을 주며, 이전처럼 R로 표시되어 그려집니다." + }, + "pl": { + "prefs.sketch.ellipse_axes": "Rysuj elipsy z osiami", + "prefs.sketch.ellipse_axes_note": "Oś wielka i mała jako linie konstrukcyjne, aby można było wymiarować półosie i osie. Wyłączone: sama elipsa, a D na niej daje promień małej półosi, gdziekolwiek przeciągnąć wartość, rysowany i oznaczony R jak dotąd." + }, + "vi": { + "prefs.sketch.ellipse_axes": "Vẽ hình elip kèm các trục", + "prefs.sketch.ellipse_axes_note": "Trục lớn và trục nhỏ dưới dạng đường gióng dựng hình, để có thể ghi kích thước bán trục và trục. Tắt: chỉ vẽ hình elip, và D trên nó cho bán kính nhỏ dù kéo giá trị đến đâu, được vẽ và ghi nhãn R như trước." + }, + "zh": { + "prefs.sketch.ellipse_axes": "绘制椭圆时带上轴线", + "prefs.sketch.ellipse_axes_note": "将长轴和短轴绘制为构造线,以便标注半轴和轴。关闭:仅绘制椭圆,对其按 D 得到短半径,无论将数值拖到何处,都像以前一样绘制并标注 R。" + } +} diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 205189bcd..a08861b42 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -141,7 +141,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .params(concat!("p0, p1: overall ends, width", connect_doc!(), created_doc!())), CommandSpec::new("sketch.point", "Point", draw_point).at("SKETCH", "CREATE").icon("point").enabled(in_sketch).params(concat!("point: [x,y] (each a number or an expression over the design's parameters: the point is then fixed where it comes to and follows them) or a snap: \"mid:\" (held at the line's midpoint), \"on::x,y\" (on the curve near x,y), {vertex: [x,y,z]} or {on_edge: [x,y,z]} of the model; id?", connect_doc!(), created_doc!())), CommandSpec::new("sketch.dimension", "Sketch Dimension", dimension).at("SKETCH", "CREATE").icon("dimension").key("D").enabled(in_sketch).params( - "entities: [refs] (a line midpoint is \"mid:line_id\"; a model edge or vertex, {edge: [x,y,z], body?} or {vertex: [x,y,z], body?}, is projected into the sketch first and measured there: a point against the projected edge measures the distance to it), type?: auto|distance|horizontal|distance_x|vertical|distance_y|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override), or `name = expression` (e.g. \"width = 40\"; also `#name = expression`), which adds the user parameter `name` with that expression and dimensions with `name` (refused when the name is taken or reserved; the reply's `defined` names it); text_at?: [x, y]. Two points, two midpoints or a line off the axes: with auto, text_at inside the box they span (as opposite corners) or in its outer corners is the distance between them, above or below the box horizontal, beside it vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A point and a circle or arc: the distance from the point to its edge (or how far within it a point inside lies). Two circles or arcs: the gap between their edges (or how far they overlap when they cross, or the narrowest gap between them when one lies inside the other), or the centre-to-centre distance when they are the two caps of a slot. An arc and one of its end points: the arc's length (type arc_length does it from the arc alone). A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled", + "entities: [refs] (a line midpoint is \"mid:line_id\"; a model edge or vertex, {edge: [x,y,z], body?} or {vertex: [x,y,z], body?}, is projected into the sketch first and measured there: a point against the projected edge measures the distance to it), type?: auto|distance|horizontal|distance_x|vertical|distance_y|length|radius|diameter|major|minor|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override), or `name = expression` (e.g. \"width = 40\"; also `#name = expression`), which adds the user parameter `name` with that expression and dimensions with `name` (refused when the name is taken or reserved; the reply's `defined` names it); text_at?: [x, y]. Two points, two midpoints or a line off the axes: with auto, text_at inside the box they span (as opposite corners) or in its outer corners is the distance between them, above or below the box horizontal, beside it vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A point and a circle or arc: the distance from the point to its edge (or how far within it a point inside lies). Two circles or arcs: the gap between their edges (or how far they overlap when they cross, or the narrowest gap between them when one lies inside the other), or the centre-to-centre distance when they are the two caps of a slot. An ellipse: a half-axis, the distance from the centre to an axis end (major or minor; with auto, text_at pulled across the major axis gives the major half-axis, pulled out past an end of it the minor one, the minor without text_at; previous_axis?: major|minor, the half-axis an earlier placement chose, kept while text_at is near the boundary between them; the reply's axis names the one chosen; with auto, when a driving dimension already holds one half-axis (or its whole axis), the other one, wherever text_at is; without its major axis line the major half-axis goes to the ellipse's own major end, without its minor axis line the minor half-axis is the minor radius); any other type, radius among them, the minor radius; an ellipse's axis line with auto: its length, the whole axis, wherever text_at is; half_axes?: bool (default true; false: with auto, the minor radius wherever text_at is, as before half-axes, which the Dimension tool sends with Draw ellipses with their axes off). An arc and one of its end points: the arc's length (type arc_length does it from the arc alone). A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled", ), CommandSpec::new("sketch.constraint.horizontal_vertical", "Horizontal/Vertical", c_horizontal_vertical) .at("SKETCH", "CONSTRAINTS") @@ -2929,6 +2929,13 @@ fn dimension(s: &mut Session, p: &Value) -> Result { None => (None, value), }; let scale_sketch = bool_(p, "scale_sketch").unwrap_or(false); + let previous_axis = str_(p, "previous_axis").map(str::to_ascii_lowercase); + let half_axes = match p.get("half_axes") { + None | Some(Value::Null) => true, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad(cmd, "`half_axes` must be true or false")), + }; + let mut axis = None; let mut scaled = None; let mut before = None; let (mut residual, mut new_id) = (None, String::new()); @@ -2969,7 +2976,10 @@ fn dimension(s: &mut Session, p: &Value) -> Result { } ((None, Some(c)), None) if is_line(c) => { let (a, b) = line_pts(sk, c).unwrap_or_default(); - match auto_orientation(&ty, a, b, text_at) { + // An ellipse's axis is a construction axis, not a free line: its length, the + // whole axis, wherever the text is. + let ty = if ty == "auto" && sk.is_ellipse_axis(c) { "length" } else { ty.as_str() }; + match auto_orientation(ty, a, b, text_at) { "angle" => { let angle = (b - a).angle(); (ConstraintKind::LineAngle { l: c, value: angle }, angle) @@ -2992,9 +3002,27 @@ fn dimension(s: &mut Session, p: &Value) -> Result { let Some(CurveKind::Ellipse { c: cp, m, r }) = sk.curves.get(c).map(|x| x.kind.clone()) else { return Err(bad(cmd, "ellipse")); }; - if ty == "major" { - let d = sk.point(cp).zip(sk.point(m)).map(|(a, b)| a.dist(b)).unwrap_or(0.0); - (ConstraintKind::Distance { p: cp, q: m, value: d }, d) + // A half-axis, chosen by where the text is: the distance from the centre to an + // axis end (the ellipse's own major end when its major axis is gone), or the + // minor radius when its minor axis is gone or it never had one. + if matches!(ty.as_str(), "major" | "minor") || (ty == "auto" && half_axes) { + let (major, minor) = sk.ellipse_axis_lines(c).unwrap_or((None, None)); + let ends = (m, major.map(|(_, m2)| m2), minor.map(|(_, n1, n2)| [n1, n2])); + // With one half-axis already held, the other is the only one left to guess. + let ty = match (ty.as_str(), half_axes_held(sk, c, cp, m, major, minor)) { + ("auto", (true, false)) => "minor".to_string(), + ("auto", (false, true)) => "major".to_string(), + _ => ty.clone(), + }; + let (which, end) = ellipse_half_axis(sk, cp, ends, r, &ty, text_at, previous_axis.as_deref()); + axis = Some(which); + match end { + Some(end) => { + let d = sk.point(cp).zip(sk.point(end)).map(|(a, b)| a.dist(b)).unwrap_or(0.0); + (ConstraintKind::Distance { p: cp, q: end, value: d }, d) + } + None => (ConstraintKind::Radius { c, value: r }, r), + } } else { (ConstraintKind::Radius { c, value: r }, r) } @@ -3193,7 +3221,11 @@ fn dimension(s: &mut Session, p: &Value) -> Result { // Report what the dimension measures once the sketch is solved, not the geometry before. let current = solved_measure(s, p, cmd).unwrap_or(current); if driven { - return Ok(json!({"param": Value::Null, "driven": true, "type": kind_name, "measured": current.0, "unit": current.1, "sketch": info})); + let mut out = json!({"param": Value::Null, "driven": true, "type": kind_name, "measured": current.0, "unit": current.1, "sketch": info}); + if let Some(axis) = axis { + out["axis"] = json!(axis); + } + return Ok(out); } // A dimension the sketch already determines cannot drive it: it is refused, or with // `if_redundant: "driven"` placed as a driven (reference) dimension instead. @@ -3223,6 +3255,9 @@ fn dimension(s: &mut Session, p: &Value) -> Result { if let Some(factor) = scaled { out["scaled"] = json!(round6(factor)); } + if let Some(axis) = axis { + out["axis"] = json!(axis); + } if let Some((name, _)) = defines { out["defined"] = json!(name); } @@ -3263,6 +3298,107 @@ fn auto_orientation(ty: &str, a: Vec2, b: Vec2, text_at: Option) -> &str { } } +/// Inside this band around the boundary between the two half-axes (the ratio of how far the +/// text is pulled across the major axis to how far past its end, both scaled by the half-axes), +/// a dimension being placed keeps the half-axis it had, so the preview does not flip back and +/// forth while the pointer crosses slowly. +const HALF_AXIS_DEAD_ZONE: f64 = 1.25; + +/// Whether a driving dimension already holds ellipse `e`'s major and its minor half-axis: a +/// half-axis to an axis end (or the minor radius), or the whole axis, along its line or between +/// its ends. +fn half_axes_held(sk: &Sketch, e: usize, c: usize, m: usize, major: Option<(usize, usize)>, minor: Option<(usize, usize, usize)>) -> (bool, bool) { + let pair = |p: usize, q: usize, a: usize, b: usize| (p == a && q == b) || (p == b && q == a); + let mut held = (false, false); + for k in sk.constraints.iter().filter(|k| !k.driven) { + match k.kind { + ConstraintKind::Distance { p, q, .. } => { + let minor_end = |x: usize| minor.is_some_and(|(_, n1, n2)| x == n1 || x == n2); + if pair(p, q, c, m) || major.is_some_and(|(_, m2)| pair(p, q, c, m2) || pair(p, q, m, m2)) { + held.0 = true; + } else if minor.is_some_and(|(_, n1, n2)| pair(p, q, n1, n2)) || (p == c && minor_end(q)) || (q == c && minor_end(p)) { + held.1 = true; + } + } + ConstraintKind::Length { l, .. } => { + held.0 |= major.is_some_and(|(line, _)| line == l); + held.1 |= minor.is_some_and(|(line, ..)| line == l); + } + ConstraintKind::Radius { c: on, .. } => held.1 |= on == e, + // A horizontal (vertical) distance across an axis holds its length when the axis + // lies that way, the distance then being the length; across a slanted axis it is only + // a projection. + ConstraintKind::DistanceX { p, q, value } | ConstraintKind::DistanceY { p, q, value } => { + let length = sk.point(p).zip(sk.point(q)).map(|(a, b)| a.dist(b)); + if !length.is_some_and(|l| (value.abs() - l).abs() <= 1e-9 * l.max(1.0)) { + continue; + } + if pair(p, q, c, m) || major.is_some_and(|(_, m2)| pair(p, q, c, m2) || pair(p, q, m, m2)) { + held.0 = true; + } else if minor.is_some_and(|(_, n1, n2)| pair(p, q, n1, n2) || pair(p, q, c, n1) || pair(p, q, c, n2)) { + held.1 = true; + } + } + _ => {} + } + } + held +} + +/// Which half-axis of an ellipse a dimension measures, and the axis end it goes to. `ends` is +/// what it has of its axes: the major end (always its own), the point opposite it, the minor +/// axis's ends. The choice does not depend on them; the major half-axis goes to the major end +/// when the point opposite is missing, and the minor one has no end (the minor radius) when its +/// axis line is. +/// With `auto` and `text_at` it follows the rule for a line, in the ellipse's own frame: text +/// pulled across the major axis measures along it (the major half-axis), text pulled out past +/// an end of the major axis measures across it (the minor one). The end is the one on the +/// text's side. Without `text_at` it is the minor half-axis, as it always was. +fn ellipse_half_axis( + sk: &Sketch, + c: usize, + ends: (usize, Option, Option<[usize; 2]>), + minor: f64, + ty: &str, + text_at: Option, + previous: Option<&str>, +) -> (&'static str, Option) { + let (m, m2, minor_ends) = ends; + let (pc, pm) = (sk.point(c).unwrap_or_default(), sk.point(m).unwrap_or_default()); + let d = pm - pc; + let major = d.len(); + let rel = text_at.map(|t| t - pc); + let along = rel.map(|v| v.dot(d) / (major * major)).filter(|v| v.is_finite()).unwrap_or(0.0); + let across = rel.map(|v| d.cross(v) / (major * minor)).filter(|v| v.is_finite()).unwrap_or(0.0); + let which = match ty { + "major" => "major", + "minor" => "minor", + _ => { + let (x, y) = (along.abs(), across.abs()); + match previous { + Some(keep @ ("major" | "minor")) if y < x * HALF_AXIS_DEAD_ZONE && x < y * HALF_AXIS_DEAD_ZONE => { + if keep == "major" { + "major" + } else { + "minor" + } + } + _ if y > x => "major", + _ => "minor", + } + } + }; + if which == "major" { + (which, Some(if along < 0.0 { m2.unwrap_or(m) } else { m })) + } else { + let end = minor_ends.map(|[n1, n2]| { + let side = sk.point(n1).map(|q| d.cross(q - pc)).unwrap_or(1.0); + if across * side < 0.0 { n2 } else { n1 } + }); + (which, end) + } +} + /// Keep a dimension's text where it was placed (`at`, sketch coordinates), relative to the /// dimension so it follows the geometry. fn place_text(sk: &mut Sketch, id: &str, at: Option) { diff --git a/crates/engine/src/cmd/sketch_corner_tests.rs b/crates/engine/src/cmd/sketch_corner_tests.rs index b2e86e8a1..cf894ded7 100644 --- a/crates/engine/src/cmd/sketch_corner_tests.rs +++ b/crates/engine/src/cmd/sketch_corner_tests.rs @@ -204,6 +204,26 @@ fn a_fillet_where_a_line_runs_on_smoothly_from_an_arc_is_refused() { assert_eq!(sk(&s).curves.len(), n); } +/// An ellipse's construction axes take no part in a corner: a line drawn from the major end +/// meets the major axis there, and Fillet or Chamfer at that point, or on that pair, is refused +/// instead of rounding the line into the axis. +#[test] +fn an_ellipse_s_axis_is_not_a_side_of_a_corner() { + let mut s = new_sketch(); + let r = run(&mut s, "sketch.ellipse", json!({"center": [0, 0], "major": [20, 0], "minor_radius": 8})); + let major = r["created"]["curves"][1].as_str().unwrap().to_string(); + let l = curves(&run(&mut s, "sketch.line", json!({"points": [format!("{major}.end"), [20, 15]], "infer": false, "connect": false})))[0].clone(); + let before = sk(&s); + for (cmd, size) in [("sketch.fillet", "radius"), ("sketch.chamfer.equal_distance", "distance")] { + for corner in [json!({"point": format!("{l}.start")}), json!({"a": l, "b": major})] { + let mut p = corner; + p[size] = json!(2); + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}: {:?}", sk(&s).curves); + assert_eq!(sk(&s), before, "{cmd} {p}"); + } + } +} + /// The ids of the constraints driven by the model parameter `name`. fn driven_by(s: &Session, name: &str) -> Vec { sk(s).constraints.iter().filter(|c| c.param.as_deref() == Some(name)).map(|c| c.id.clone()).collect() diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs index d231b6c12..95cf36cc4 100644 --- a/crates/engine/src/cmd/sketch_create.rs +++ b/crates/engine/src/cmd/sketch_create.rs @@ -68,7 +68,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .enabled(in_sketch) .params(concat!("center, start: centre arc start, end: direction of the centre arc end (counter-clockwise) or sweep: degrees (0 < sweep < 360), width; returns centre_arc", created_doc!())), CommandSpec::new("sketch.ellipse", "Ellipse", ellipse).at("SKETCH", "CREATE").icon("ellipse").enabled(in_sketch).params(concat!( - "center, major: end of the major axis [x,y], minor: a point the ellipse passes through on the minor side [x,y] | minor_radius", + "center, major: end of the major axis [x,y], minor: a point the ellipse passes through on the minor side [x,y] | minor_radius. Also adds its major and minor axes as construction lines through the centre (their ends: the major end and the point opposite it, and the two ends of the minor axis on the ellipse), held by midpoint, perpendicular and point-on-curve constraints, so a half-axis is the distance from the centre to an axis end and an axis line's length is a full axis; axes?: bool (default true; false: the ellipse alone, as the Ellipse tool draws it with Draw ellipses with their axes off)", created_doc!() )), CommandSpec::new("sketch.spline.fit_point", "Fit Point Spline", spline_fit) @@ -626,12 +626,38 @@ fn ellipse(s: &mut Session, p: &Value) -> Result { if !(r > 1e-9 && r < 1e8) { return Err(bad(cmd, "the minor radius must be positive")); } + let axes = match p.get("axes") { + None | Some(Value::Null) => true, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad(cmd, "`axes` must be true or false")), + }; let (out, info) = edit(s, p, cmd, false, |sk, _| { let ci = sk.add_point(c, None)?; let mi = sk.add_point(m, None)?; let e = sk.add_curve(CurveKind::Ellipse { c: ci, m: mi, r }, None)?; mark_construction(sk, &[e], p); - Ok((ids_of(sk, &[e]), Vec::new())) + if !axes { + return Ok((ids_of(sk, &[e]), Vec::new())); + } + // Its major and minor axes, construction lines through the centre that bisects both: + // the major one ends at the major end, the minor one is perpendicular to it and ends + // on the ellipse. Six new coordinates, six equations: the ellipse keeps its 5 degrees + // of freedom, and each half-axis is a plain distance from the centre to an end. + let n = u.perp() * r; + let (m2, n1, n2) = (sk.add_point(c * 2.0 - m, None)?, sk.add_point(c + n, None)?, sk.add_point(c - n, None)?); + let (major, minor) = (sk.add_line_pts(m2, mi, None)?, sk.add_line_pts(n2, n1, None)?); + for l in [major, minor] { + if let Some(cu) = sk.curves.get_mut(l) { + cu.construction = true; + } + } + let cons = vec![ + add_c(sk, ConstraintKind::Midpoint { p: ci, l: major })?, + add_c(sk, ConstraintKind::Midpoint { p: ci, l: minor })?, + add_c(sk, ConstraintKind::Perpendicular { a: minor, b: major })?, + add_c(sk, ConstraintKind::PointOnCurve { p: n1, c: e })?, + ]; + Ok((ids_of(sk, &[e]), cons)) })?; Ok(result(out, info)) } diff --git a/crates/engine/src/cmd/sketch_drag.rs b/crates/engine/src/cmd/sketch_drag.rs index 78e822577..8a24a2928 100644 --- a/crates/engine/src/cmd/sketch_drag.rs +++ b/crates/engine/src/cmd/sketch_drag.rs @@ -787,8 +787,21 @@ fn plan(sk: &Sketch, e: Ent, from: Vec2, to: Vec2) -> Option<(Path, Hold)> { Path::ConicRho { c, from: rho, to: to_rho } } k => { - // Lines and splines slide with the cursor. + // Lines and splines slide with the cursor. An ellipse's construction axis + // takes the ellipse and the other axis along, keeping their sizes, as a + // rectangle's diagonal does through the corners it shares with the edges. let mut ids = k.point_ids(); + // Whichever axes are left: one may have been deleted. + if let Some((e, major, minor)) = (0..sk.curves.len()).find_map(|e| { + let (major, minor) = sk.ellipse_axis_lines(e)?; + (major.is_some_and(|(l, _)| l == c) || minor.is_some_and(|(l, ..)| l == c)).then_some((e, major, minor)) + }) && let Some(kind) = sk.curves.get(e).map(|x| &x.kind) + { + ids.extend(kind.point_ids()); + ids.extend(major.map(|(_, q)| q)); + ids.extend(minor.into_iter().flat_map(|(_, n1, n2)| [n1, n2])); + hold.radii.push(e); + } ids.sort_unstable(); ids.dedup(); let pts = ids.iter().filter(|q| free(q)).filter_map(|&q| Some((q, sk.point(q)?))).collect(); @@ -802,8 +815,9 @@ fn plan(sk: &Sketch, e: Ent, from: Vec2, to: Vec2) -> Option<(Path, Hold)> { } /// A selection dragged by one of its entities (`e`, the rest `with`): every free point of all of -/// them slides by `d` and the solves hold them all (circles and ellipses keep their radii), so -/// the selection moves as one instead of its free ends trailing behind the grabbed entity. +/// them slides by `d` and the solves hold them all (circles and ellipses keep their radii, an +/// ellipse's axis brings its ellipse), so the selection moves as one instead of its free ends +/// trailing behind the grabbed entity. fn plan_group(sk: &Sketch, e: Ent, with: &[Ent], d: Vec2) -> Option<(Path, Hold)> { let mut hold = Hold::default(); for e in std::iter::once(&e).chain(with) { @@ -815,6 +829,16 @@ fn plan_group(sk: &Sketch, e: Ent, with: &[Ent], d: Vec2) -> Option<(Path, Hold) if matches!(kind, CurveKind::Circle { .. } | CurveKind::Ellipse { .. }) { hold.radii.push(c); } + // An ellipse's axis takes the ellipse and the other axis along, as it does dragged + // alone (see `plan`). + if let Some(e) = sk.ellipse_of_axis(c) + && let (Some(kind), Some((major, minor))) = (sk.curves.get(e).map(|x| &x.kind), sk.ellipse_axis_lines(e)) + { + hold.points.extend(kind.point_ids()); + hold.points.extend(major.map(|(_, q)| q)); + hold.points.extend(minor.into_iter().flat_map(|(_, n1, n2)| [n1, n2])); + hold.radii.push(e); + } } } } diff --git a/crates/engine/src/cmd/sketch_drag_live_tests.rs b/crates/engine/src/cmd/sketch_drag_live_tests.rs index d3df28daa..628a091b0 100644 --- a/crates/engine/src/cmd/sketch_drag_live_tests.rs +++ b/crates/engine/src/cmd/sketch_drag_live_tests.rs @@ -386,6 +386,30 @@ fn a_drag_with_the_rest_of_a_selection_moves_it_as_one() { } } +/// A selection dragged by an ellipse's axis takes the ellipse and its other axis along, as the +/// axis dragged alone does: the whole ellipse slides by the cursor's move, keeping its size. +#[test] +fn a_selection_dragged_by_an_ellipse_axis_takes_the_ellipse_along() { + for live in [false, true] { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + let r = run(&mut s, "sketch.ellipse", json!({"center": [0, 0], "major": [20, 0], "minor_radius": 8})); + let e = r["curves"][0].as_str().expect("the ellipse").to_string(); + run(&mut s, "sketch.line", json!({"points": [[40, -10], [40, 10]], "connect": false})); + let sk = s.doc.sketch(s.active_sketch.expect("sketch mode")).expect("the sketch"); + let Some((Some((major, _)), _)) = sk.ellipse_axis_lines(sk.curve_index(&e).expect("the ellipse")) else { panic!("its axes") }; + let axis = sk.curves[major].id.clone(); + let line = sk.curves.last().expect("the line").id.clone(); + run(&mut s, "sketch.drag", json!({"entity": axis, "with": [line], "from": [10, 0], "to": [10, 15], "live": live})); + let sk = s.doc.sketch(s.active_sketch.expect("sketch mode")).expect("the sketch"); + let ei = sk.curve_index(&e).expect("the ellipse"); + let solidcraft_sketch::CurveKind::Ellipse { c, m, .. } = sk.curves[ei].kind else { panic!("an ellipse") }; + let v = solidcore_record::Vec2::new; + assert!(sk.point(c).expect("its centre").dist(v(0.0, 15.0)) < 1e-6, "live {live}: the centre follows: {:?}", sk.point(c)); + assert!(sk.point(m).expect("its major end").dist(v(20.0, 15.0)) < 1e-6, "live {live}: the major end follows: {:?}", sk.point(m)); + } +} + /// A 5 x 5 square drawn on the top face of a 30 x 20 x 10 box, the face's edges projected into /// its sketch; returns the session and a corner of the square (its id and where it is). fn on_a_face() -> (Session, String, solidcore_record::Vec2) { diff --git a/crates/engine/src/cmd/sketch_freeform.rs b/crates/engine/src/cmd/sketch_freeform.rs index 03710ddc2..d64aa80f9 100644 --- a/crates/engine/src/cmd/sketch_freeform.rs +++ b/crates/engine/src/cmd/sketch_freeform.rs @@ -58,8 +58,12 @@ fn cuts(sk: &Sketch, ci: usize, segs: &[Seg2], only_freeform: bool) -> Vec<(f64, let (t, u) = ((c - a).cross(s) / den, (c - a).cross(r) / den); ((-1e-9..=1.0 + 1e-9).contains(&t) && (-1e-9..=1.0 + 1e-9).contains(&u)).then(|| a + r * t) }; + // An ellipse's own axes end on it and cut it nowhere, as a Center Rectangle's diagonals end + // at its corners. + let (major, minor) = sk.ellipse_axis_lines(ci).unwrap_or((None, None)); + let own_axes = [major.map(|(l, _)| l), minor.map(|(l, ..)| l)]; for (oi, curve) in sk.curves.iter().enumerate() { - if oi == ci || (only_freeform && !curve.kind.is_freeform()) { + if oi == ci || (only_freeform && !curve.kind.is_freeform()) || own_axes.contains(&Some(oi)) { continue; } let other = sk.polyline(oi); diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index 5ce6f355e..00c3189e4 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -25,7 +25,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SKETCH", "MODIFY") .icon("sketch_fillet") .enabled(in_sketch) - .params(concat!("point: corner shared by two curves (\"l1.end\") | points: [corners] (all rounded alike: one radius, the rest equal; a corner is a point reference or {a, b}, the two curves meeting there) | a, b: two lines or arcs meeting at a corner (two lines that share no end are first brought to where they meet: the nearer end of a line that stops short moves there, and a line that runs past is cut there, losing its shorter piece); radius: expr. A corner that dimensions or constraints measure to stays as a virtual sharp corner on both curves' extensions (`virtual_corners`; the moved ones in `moved_to_virtual_corner`)", created_doc!())), + .params(concat!("point: corner shared by two curves (\"l1.end\") | points: [corners] (all rounded alike: one radius, the rest equal; a corner is a point reference or {a, b}, the two curves meeting there) | a, b: two lines or arcs meeting at a corner (two lines that share no end are first brought to where they meet: the nearer end of a line that stops short moves there, and a line that runs past is cut there, losing its shorter piece); radius: expr. A corner that dimensions or constraints measure to stays as a virtual sharp corner on both curves' extensions (`virtual_corners`; the moved ones in `moved_to_virtual_corner`). An ellipse's axis line is never a side of a corner (also for the chamfers)", created_doc!())), CommandSpec::new("sketch.chamfer.equal_distance", "Equal Distance Chamfer", chamfer_equal) .at("SKETCH", "MODIFY") .icon("sketch_chamfer") @@ -1780,7 +1780,10 @@ fn corner(sk: &Sketch, p: &Value, cmd: &str) -> Result<(usize, usize, usize, usi }; let (la, lb) = if let Some(r) = str_(p, "point") { let q = sk.resolve_point(r).ok_or_else(|| bad(cmd, format!("unknown point `{r}`")))?; - let lines: Vec = (0..sk.curves.len()).filter(|i| ends(*i).is_some_and(|(a, b)| a == q || b == q) && !sk.is_linked_curve(*i)).collect(); + // An ellipse's construction axis is never a side: it would round a line into the axis. + let lines: Vec = (0..sk.curves.len()) + .filter(|i| ends(*i).is_some_and(|(a, b)| a == q || b == q) && !sk.is_linked_curve(*i) && !sk.is_ellipse_axis(*i)) + .collect(); // A construction line ending there too (a diagonal that centres something) is not one of // the corner's sides: it keeps its end on the virtual sharp corner (#1026). let sides: Vec = @@ -1792,6 +1795,9 @@ fn corner(sk: &Sketch, p: &Value, cmd: &str) -> Result<(usize, usize, usize, usi } else { let a = str_(p, "a").and_then(|i| sk.curve_index(i)).ok_or_else(|| bad(cmd, "`a` must be a line"))?; let b = str_(p, "b").and_then(|i| sk.curve_index(i)).ok_or_else(|| bad(cmd, "`b` must be a line"))?; + if sk.is_ellipse_axis(a) || sk.is_ellipse_axis(b) { + return Err(bad(cmd, "an ellipse's axis is not a side of a corner")); + } (a, b) }; let (a0, a1) = ends(la).ok_or_else(|| bad(cmd, "fillets and chamfers work on two lines"))?; @@ -2087,7 +2093,9 @@ fn round_corner(sk: &mut Sketch, p: &Value, r: f64, cmd: &str) -> Result = (0..sk.curves.len()).filter(|i| ends(*i).is_some_and(|(a, b)| a == q || b == q) && !sk.is_linked_curve(*i)).collect(); + let cs: Vec = (0..sk.curves.len()) + .filter(|i| ends(*i).is_some_and(|(a, b)| a == q || b == q) && !sk.is_linked_curve(*i) && !sk.is_ellipse_axis(*i)) + .collect(); match cs[..] { [a, b] => (a, b, q), _ => return Ok(None), @@ -2097,6 +2105,9 @@ fn round_corner(sk: &mut Sketch, p: &Value, r: f64, cmd: &str) -> Result Result<(Vec, Vec Ok((cs, ps)) } +/// `cs` with the ellipse of every axis line in it and the axis lines of every ellipse in it: an +/// ellipse, or one of its axes, moved, turned or scaled takes the rest along, as a drag does, +/// instead of leaving the axes behind its centre or pulling an axis off the ellipse. +fn with_ellipse_axes(sk: &Sketch, cs: &mut Vec) { + let ellipses: Vec = cs.iter().filter_map(|&l| sk.ellipse_of_axis(l)).collect(); + for e in ellipses { + if !cs.contains(&e) { + cs.push(e); + } + } + let axes: Vec = cs + .iter() + .filter_map(|&e| sk.ellipse_axis_lines(e)) + .flat_map(|(major, minor)| major.map(|(l, _)| l).into_iter().chain(minor.map(|(l, ..)| l))) + .collect(); + for l in axes { + if !cs.contains(&l) { + cs.push(l); + } + } +} + /// Points used by curves plus lone points, in a stable order. fn involved_points(sk: &Sketch, cs: &[usize], ps: &[usize]) -> Vec { let mut v: Vec = Vec::new(); @@ -3513,6 +3546,7 @@ fn move_copy(s: &mut Session, p: &Value) -> Result { } return Ok(ids); } + with_ellipse_axes(sk, &mut cs); transform_in_place(sk, &cs, &ps, &f, 1.0, cmd)?; if rotate_constraints { let moved = involved_points(sk, &cs, &ps); @@ -3539,7 +3573,8 @@ fn transform(s: &mut Session, p: &Value) -> Result { }; let t = if p.get("translate").is_some() { req_vec2(cmd, p, "translate")? } else { Vec2::ZERO }; let (out, info) = edit(s, p, cmd, false, |sk, doc| { - let (cs, ps) = entities(sk, p, cmd)?; + let (mut cs, ps) = entities(sk, p, cmd)?; + with_ellipse_axes(sk, &mut cs); let c = if p.get("center").is_some() { point_or_ref(sk, p, "center", cmd)? } else { Vec2::ZERO }; let rot = rotate(c, ang); let f = move |q: Vec2| rot(c + (q - c) * k) + t; @@ -3612,7 +3647,8 @@ fn scale(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.scale"; let k = num(p, "factor").filter(|k| *k > 1e-9 && *k < 1e6).ok_or_else(|| bad(cmd, "`factor` must be a positive number"))?; let (out, info) = edit(s, p, cmd, false, |sk, _| { - let (cs, ps) = entities(sk, p, cmd)?; + let (mut cs, ps) = entities(sk, p, cmd)?; + with_ellipse_axes(sk, &mut cs); let b = if p.get("base").is_some() { point_or_ref(sk, p, "base", cmd)? } else { Vec2::ZERO }; let f = move |q: Vec2| b + (q - b) * k; transform_in_place(sk, &cs, &ps, &f, k, cmd)?; diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index 6b67b6893..ecbc0de59 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -142,7 +142,7 @@ fn explicit_ellipse_break_keeps_closed_profile() { let out = run(&mut s, "sketch.break", json!({"curve": id, "points": [[10,0], [0,4], [10,0]]})); assert_eq!(ids(&out["curves"]).len(), 4, "{out}"); let after = sketch(&s); - assert!(after.curves.iter().all(|c| matches!(c.kind, CurveKind::Conic { .. }))); + assert!(after.curves.iter().filter(|c| !c.construction).all(|c| matches!(c.kind, CurveKind::Conic { .. }))); assert_eq!(profiles(&s).len(), 1); assert!((profiles(&s)[0] - area).abs() < 1e-6); run(&mut s, "edit.undo", json!({})); @@ -174,6 +174,83 @@ fn explicit_break_rejects_bad_points_atomically_and_merges_duplicates() { } } +/// An axis line moved, turned or scaled on its own takes its ellipse and the other axis along, +/// as a drag of the same line does, instead of pulling away from the ellipse. +#[test] +fn an_ellipse_axis_moved_turned_or_scaled_alone_takes_its_ellipse_along() { + for (cmd, params, centre, major) in [ + ("sketch.move", json!({"translate": [0, 30]}), Vec2::new(0.0, 30.0), Vec2::new(20.0, 30.0)), + ("sketch.move", json!({"angle": 90, "center": [0, 0]}), Vec2::ZERO, Vec2::new(0.0, 20.0)), + ("sketch.scale", json!({"base": [0, 0], "factor": 2}), Vec2::ZERO, Vec2::new(40.0, 0.0)), + ("sketch.transform", json!({"translate": [5, 0]}), Vec2::new(5.0, 0.0), Vec2::new(25.0, 0.0)), + ] { + for which in ["major", "minor"] { + let mut s = new_sketch(); + let e = ids(&run(&mut s, "sketch.ellipse", json!({"center": [0, 0], "major": [20, 0], "minor_radius": 8}))["curves"])[0].clone(); + let sk = sketch(&s); + let Some((Some((major_line, _)), Some((minor_line, ..)))) = sk.ellipse_axis_lines(sk.curve_index(&e).unwrap()) else { + panic!("its axes") + }; + let axis = sk.curves[if which == "major" { major_line } else { minor_line }].id.clone(); + let mut p = params.clone(); + p["entities"] = json!([axis]); + let r = run(&mut s, cmd, p); + assert_eq!(r["sketch"]["solved"], json!(true), "{cmd} {params} {which}: {r}"); + let sk = sketch(&s); + let ei = sk.curve_index(&e).unwrap(); + let CurveKind::Ellipse { c, m, .. } = sk.curves[ei].kind else { panic!("an ellipse") }; + assert!(sk.point(c).unwrap().dist(centre) < 1e-6, "{cmd} {params} {which}: the ellipse's centre follows: {:?}", sk.point(c)); + assert!(sk.point(m).unwrap().dist(major) < 1e-6, "{cmd} {params} {which}: its major end follows: {:?}", sk.point(m)); + assert!(sk.ellipse_axis_lines(ei).is_some_and(|(a, b)| a.is_some() && b.is_some()), "{cmd} {params} {which}: still its axes"); + assert!(ids(&r["curves"]).contains(&e), "{cmd} {params} {which}: the reply lists the ellipse: {r}"); + } + } +} + +/// An ellipse moved, turned or scaled on its own takes its axes along, as a drag does: they +/// stay its axes and nothing is left failing. +#[test] +fn an_ellipse_moved_turned_or_scaled_alone_takes_its_axes_along() { + // With the minor axis deleted, the major axis that is left still goes along. + let mut s = new_sketch(); + let e = ids(&run(&mut s, "sketch.ellipse", json!({"center": [0, 0], "major": [20, 0], "minor_radius": 8}))["curves"])[0].clone(); + let minor = sketch(&s).curves.iter().rev().find(|c| matches!(c.kind, CurveKind::Line { .. })).unwrap().id.clone(); + run(&mut s, "sketch.delete", json!({"entities": [minor]})); + let r = run(&mut s, "sketch.move", json!({"entities": [e], "translate": [0, 30]})); + assert_eq!(r["sketch"]["solved"], json!(true), "{r}"); + let sk = sketch(&s); + let (major, _) = sk.ellipse_axis_lines(sk.curve_index(&e).unwrap()).and_then(|(major, _)| major).expect("its major axis"); + let CurveKind::Line { a, b } = sk.curves[major].kind else { panic!("a line") }; + assert!(sk.point(a).unwrap().dist(Vec2::new(-20.0, 30.0)) < 1e-6 && sk.point(b).unwrap().dist(Vec2::new(20.0, 30.0)) < 1e-6); + assert!(ids(&r["curves"]).contains(&sk.curves[major].id), "the reply lists the axis moved: {r}"); + for (cmd, params, centre, major) in [ + ("sketch.move", json!({"translate": [0, 30]}), Vec2::new(0.0, 30.0), Vec2::new(20.0, 30.0)), + ("sketch.move", json!({"angle": 90, "center": [0, 0]}), Vec2::ZERO, Vec2::new(0.0, 20.0)), + ("sketch.scale", json!({"base": [0, 0], "factor": 2}), Vec2::ZERO, Vec2::new(40.0, 0.0)), + ("sketch.transform", json!({"translate": [5, 0]}), Vec2::new(5.0, 0.0), Vec2::new(25.0, 0.0)), + ] { + let mut s = new_sketch(); + let e = ids(&run(&mut s, "sketch.ellipse", json!({"center": [0, 0], "major": [20, 0], "minor_radius": 8}))["curves"])[0].clone(); + let mut p = params.clone(); + p["entities"] = json!([e]); + let r = run(&mut s, cmd, p); + assert_eq!(r["sketch"]["solved"], json!(true), "{cmd} {params}: {r}"); + let sk = sketch(&s); + let ei = sk.curve_index(&e).unwrap(); + let Some((Some((major_line, opposite)), Some((minor_line, n1, n2)))) = sk.ellipse_axis_lines(ei) else { + panic!("{cmd} {params}: still its axes") + }; + let CurveKind::Ellipse { m, .. } = sk.curves[ei].kind else { panic!("an ellipse") }; + let ends: Vec = [m, opposite, n1, n2].iter().map(|q| sk.point(*q).unwrap()).collect(); + assert!(ends[0].dist(major) < 1e-6 && ends[1].dist(centre * 2.0 - major) < 1e-6, "{cmd} {params}: the major axis follows: {ends:?}"); + assert!(((ends[2] + ends[3]) * 0.5).dist(centre) < 1e-6, "{cmd} {params}: the minor axis follows: {ends:?}"); + let listed = ids(&r["curves"]); + for l in [major_line, minor_line] { + assert!(listed.contains(&sk.curves[l].id), "{cmd} {params}: the reply lists the axis lines: {r}"); + } + } +} + #[test] fn analytic_trim_and_break_use_freeform_cutters() { let mut s = new_sketch(); @@ -190,11 +267,95 @@ fn analytic_trim_and_break_use_freeform_cutters() { let mut s = new_sketch(); let circle = ids(&run(&mut s, "sketch.circle.center", json!({"center": [0,0], "radius": 5}))["curves"])[0].clone(); run(&mut s, "sketch.ellipse", json!({"center": [0,0], "major": [8,0], "minor": [0,3]})); - run(&mut s, "sketch.trim", json!({"curve": circle, "at": [5,0]})); + // Picked 15 degrees round from where the major axis crosses the circle: the piece from the + // axis to the ellipse's crossing goes, the rest stays. Its construction axes cut too (see + // the next test). + run(&mut s, "sketch.trim", json!({"curve": circle, "at": [4.8296,1.2941]})); let sk = sketch(&s); let ci = sk.curve_index(&circle).unwrap(); - assert!(matches!(sk.curves[ci].kind, CurveKind::Arc { .. })); - assert!(sk.shape(ci).unwrap().dist(Vec2::new(-5.0, 0.0)) < 1e-6); + let CurveKind::Arc { a, b, .. } = sk.curves[ci].kind else { panic!("{:?}", sk.curves[ci].kind) }; + let crossing = Vec2::new((25.0f64 - 351.0 / 55.0).sqrt(), (351.0f64 / 55.0).sqrt()); + let mut ends = [sk.point(a).unwrap(), sk.point(b).unwrap()]; + ends.sort_by(|p, q| p.y.total_cmp(&q.y)); + assert!(ends[0].dist(Vec2::new(5.0, 0.0)) < 1e-6 && ends[1].dist(crossing) < 1e-6, "{ends:?}"); + let shape = sk.shape(ci).unwrap(); + assert!(shape.dist(Vec2::new(-5.0, 0.0)) < 1e-6 && shape.dist(Vec2::new(4.8296, -1.2941)) < 1e-3); + assert!(shape.dist(Vec2::new(4.8296, 1.2941)) > 0.5); +} + +/// An ellipse's own axes do not cut it (they end on it, where a Center Rectangle's diagonals end +/// at its corners): a lone ellipse trims away whole, its axes staying as when it is deleted, and +/// a trim of its outline stops where a line crosses, not at an axis end. +#[test] +fn an_ellipse_s_own_axes_do_not_cut_it() { + let mut s = new_sketch(); + let e = ids(&run(&mut s, "sketch.ellipse", json!({"center": [0, 0], "major": [20, 0], "minor_radius": 8}))["curves"])[0].clone(); + run(&mut s, "sketch.trim", json!({"curve": e, "at": [0, 8]})); + let sk = sketch(&s); + assert!(sk.curves.iter().all(|c| c.construction), "the whole ellipse goes: {:?}", sk.curves); + assert_eq!(sk.curves.len(), 2, "its two axes stay"); + + let mut s = new_sketch(); + let e = ids(&run(&mut s, "sketch.ellipse", json!({"center": [0, 0], "major": [20, 0], "minor_radius": 8}))["curves"])[0].clone(); + run(&mut s, "sketch.line", json!({"points": [[10, -10], [10, 10]], "connect": false})); + // Clicked 10 degrees round from the major end: the cap right of the line goes, from one + // crossing to the other, past the major end. + let at = Vec2::new(20.0 * 10f64.to_radians().cos(), 8.0 * 10f64.to_radians().sin()); + run(&mut s, "sketch.trim", json!({"curve": e, "at": [at.x, at.y]})); + let sk = sketch(&s); + let left: Vec = + (0..sk.curves.len()).filter(|i| !sk.curves[*i].construction && !matches!(sk.curves[*i].kind, CurveKind::Line { .. })).collect(); + // What is left of the ellipse comes back as conic pieces; the trim must leave some. + assert!(!left.is_empty(), "part of the ellipse is left: {:?}", sk.curves); + for i in left { + let right = sk.polyline(i).iter().map(|q| q.x).fold(f64::MIN, f64::max); + assert!(right < 10.0 + 1e-6, "{}: what is left stays left of the line, reaching x = {right}", sk.curves[i].id); + } +} + +/// An ellipse's construction axes cut a trim, as a Center Rectangle's construction diagonals +/// do: a line inside the ellipse trims back to the minor axis, one inside the rectangle to the +/// diagonals. +#[test] +fn an_ellipse_s_axes_cut_as_a_center_rectangle_s_diagonals_do() { + // What is left of the line at y = 1, as x ranges. + let lines = |s: &Session| { + let sk = sketch(s); + let mut ends: Vec<[f64; 2]> = sk + .curves + .iter() + .filter_map(|c| match c.kind { + CurveKind::Line { a, b } => { + let (a, b) = (sk.point(a).unwrap(), sk.point(b).unwrap()); + (close(a.y, 1.0) && close(b.y, 1.0)).then(|| [a.x.min(b.x), a.x.max(b.x)]) + } + _ => None, + }) + .collect(); + ends.sort_by(|x, y| x[0].total_cmp(&y[0])); + ends + }; + let mut s = new_sketch(); + run(&mut s, "sketch.ellipse", json!({"center": [0, 0], "major": [20, 0], "minor_radius": 8})); + let line = ids(&run(&mut s, "sketch.line", json!({"points": [[-3, 1], [3, 1]], "connect": false}))["curves"])[0].clone(); + run(&mut s, "sketch.trim", json!({"curve": line, "at": [1, 1]})); + let ends = lines(&s); + assert!(ends.len() == 1 && close(ends[0][0], -3.0) && close(ends[0][1], 0.0), "{ends:?}"); + + // Extend stops at them too: a line inside the ellipse reaches the minor axis, not the outline. + let mut s = new_sketch(); + run(&mut s, "sketch.ellipse", json!({"center": [0, 0], "major": [20, 0], "minor_radius": 8})); + let line = ids(&run(&mut s, "sketch.line", json!({"points": [[-6, 1], [-3, 1]], "connect": false}))["curves"])[0].clone(); + run(&mut s, "sketch.extend", json!({"curve": line, "at": [-3, 1]})); + let ends = lines(&s); + assert!(ends.len() == 1 && close(ends[0][0], -6.0) && close(ends[0][1], 0.0), "{ends:?}"); + + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.center", json!({"center": [0, 0], "corner": [20, 8]})); + let line = ids(&run(&mut s, "sketch.line", json!({"points": [[-3, 1], [3, 1]], "connect": false}))["curves"])[0].clone(); + run(&mut s, "sketch.trim", json!({"curve": line, "at": [1, 1]})); + let ends = lines(&s); + assert!(ends.len() == 2 && close(ends[0][1], -2.5) && close(ends[1][0], 2.5), "{ends:?}"); } /// #10851: an endpoint's tangent must stay with the arc piece that owns that endpoint, @@ -2064,6 +2225,164 @@ fn ellipse_radii_dimensions() { assert!((a - std::f64::consts::PI * 60.0).abs() < 1e-6, "{a}"); } +/// An ellipse comes with its major and minor axes as construction lines through its centre. +/// They add no freedom (the ellipse keeps 5 degrees), follow its size, and stay when the +/// ellipse is deleted, as a Center Rectangle's construction diagonals stay with its edges gone. +#[test] +fn an_ellipse_comes_with_its_axes_as_construction_lines() { + let axes = |s: &Session| { + let sk = sketch(s); + let mut lengths: Vec = sk + .curves + .iter() + .filter_map(|c| match c.kind { + CurveKind::Line { a, b } if c.construction => Some(sk.point(a).unwrap().dist(sk.point(b).unwrap())), + _ => None, + }) + .collect(); + lengths.sort_by(f64::total_cmp); + lengths + }; + let mut s = new_sketch(); + let out = run(&mut s, "sketch.ellipse", json!({"center": [5, 3], "major": [25, 3], "minor_radius": 8})); + let e = ids(&out["curves"])[0].clone(); + assert_eq!(out["created"]["curves"].as_array().map(Vec::len), Some(3), "{out}"); + assert_eq!(run(&mut s, "sketch.inspect", json!({}))["dof"], json!(5)); + let lengths = axes(&s); + assert!(lengths.len() == 2 && close(lengths[0], 16.0) && close(lengths[1], 40.0), "{lengths:?}"); + assert!(profiles(&s).len() == 1 && close(profiles(&s)[0], std::f64::consts::PI * 160.0), "{:?}", profiles(&s)); + // Dragging either axis moves the ellipse and its axes as one, sizes kept, as dragging a + // Center Rectangle's diagonal moves the rectangle. + let half_axes = |s: &Session| { + let sk = sketch(s); + let Some(CurveKind::Ellipse { c, m, r }) = sk.curves.iter().map(|x| x.kind.clone()).find(|k| matches!(k, CurveKind::Ellipse { .. })) else { + panic!("the ellipse") + }; + (sk.point(c).unwrap(), sk.point(c).unwrap().dist(sk.point(m).unwrap()), r) + }; + let (centre, ..) = half_axes(&s); + let (major, minor) = { + let sk = sketch(&s); + let mut lines: Vec<(f64, String)> = sk + .curves + .iter() + .filter_map(|c| match c.kind { + CurveKind::Line { a, b } => Some((sk.point(a).unwrap().dist(sk.point(b).unwrap()), c.id.clone())), + _ => None, + }) + .collect(); + lines.sort_by(|x, y| y.0.total_cmp(&x.0)); + (lines[0].1.clone(), lines[1].1.clone()) + }; + let mut moved = centre; + for (line, by) in [(&major, Vec2::new(4.0, 6.0)), (&minor, Vec2::new(-3.0, 2.0))] { + let from = moved + if *line == major { Vec2::new(-12.0, 0.0) } else { Vec2::new(0.0, 4.0) }; + run(&mut s, "sketch.drag", json!({"entity": line, "from": [from.x, from.y], "to": [from.x + by.x, from.y + by.y]})); + run(&mut s, "sketch.drag_end", json!({})); + moved += by; + let (at, a, b) = half_axes(&s); + assert!(at.dist(moved) < 1e-6 && close(a, 20.0) && close(b, 8.0), "dragging {line}: centre {at:?}, half-axes {a} {b}"); + let lengths = axes(&s); + assert!(close(lengths[0], 16.0) && close(lengths[1], 40.0), "dragging {line}: {lengths:?}"); + } + // Dragging the outline still sets the minor half-axis, the axes following it. + run(&mut s, "sketch.drag", json!({"entity": &e, "from": [moved.x, moved.y + 8.0], "to": [moved.x, moved.y + 10.0]})); + run(&mut s, "sketch.drag_end", json!({})); + let (at, a, b) = half_axes(&s); + assert!(at.dist(moved) < 1e-6 && close(a, 20.0) && close(b, 10.0), "dragging the outline: centre {at:?}, half-axes {a} {b}"); + let lengths = axes(&s); + assert!(close(lengths[0], 20.0) && close(lengths[1], 40.0), "dragging the outline: {lengths:?}"); + // Sizing the ellipse resizes its axes, and they stay through its centre. + run(&mut s, "sketch.dimension", json!({"entities": [&e], "type": "major", "value": 30})); + run(&mut s, "sketch.dimension", json!({"entities": [&e], "type": "minor", "value": 10})); + let lengths = axes(&s); + assert!(close(lengths[0], 20.0) && close(lengths[1], 60.0), "{lengths:?}"); + assert!(close(profiles(&s)[0], std::f64::consts::PI * 300.0), "{:?}", profiles(&s)); + // A double-click on the ellipse or on either axis selects all three, as one on a Center + // Rectangle's edge or diagonal selects its edges and both diagonals. + let curves: Vec = sketch(&s).curves.iter().map(|c| c.id.clone()).collect(); + for id in &curves { + let mut chain = ids(&run(&mut s, "sketch.chain", json!({"curve": id}))["curves"]); + chain.sort(); + assert_eq!(chain, curves, "double-click on {id}"); + } + // Deleting it leaves the two axes, still construction and still perpendicular, and still + // bisected by the centre, which stays as a Center Rectangle's centre does. + run(&mut s, "sketch.delete", json!({"entities": [&e]})); + let sk = sketch(&s); + assert_eq!(sk.curves.len(), 2); + assert!(sk.curves.iter().all(|c| c.construction && matches!(c.kind, CurveKind::Line { .. }))); + assert!(sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Perpendicular { .. }))); + let centres: Vec = + sk.constraints.iter().filter_map(|c| if let ConstraintKind::Midpoint { p, .. } = c.kind { Some(p) } else { None }).collect(); + assert!(centres.len() == 2 && centres[0] == centres[1], "both axes keep their midpoint on the centre: {:?}", sk.constraints); + // The same as a Center Rectangle whose edges are deleted: its diagonals stay. + let mut s = new_sketch(); + let edges = ids(&run(&mut s, "sketch.rectangle.center", json!({"center": [0, 0], "corner": [20, 10]}))["curves"]); + assert_eq!(ids(&run(&mut s, "sketch.chain", json!({"curve": &edges[0]}))["curves"]).len(), 6); + run(&mut s, "sketch.delete", json!({"entities": edges})); + let sk = sketch(&s); + assert!(sk.curves.len() == 2 && sk.curves.iter().all(|c| c.construction), "{:?}", sk.curves); + // With axes: false (the Sketch preference off), the ellipse alone, as before its axes. + let mut s = new_sketch(); + let r = run(&mut s, "sketch.ellipse", json!({"center": [0, 0], "major": [20, 0], "minor_radius": 8, "axes": false})); + let sk = sketch(&s); + assert!(sk.curves.len() == 1 && sk.constraints.is_empty(), "{r}"); + assert_eq!(r["sketch"]["dof"], json!(5)); + let refused = s.execute("sketch.ellipse", &json!({"center": [0, 0], "major": [20, 0], "minor_radius": 8, "axes": "false"})); + assert!(refused.is_err_and(|e| e.to_string().contains("true or false"))); +} + +/// An ellipse with its axes, the minor one (or the major one) then deleted: the ids of the +/// ellipse and of the axis left. +fn ellipse_with_one_axis(s: &mut Session, keep_major: bool) -> (String, String) { + let e = ids(&run(s, "sketch.ellipse", json!({"center": [0, 0], "major": [20, 0], "minor_radius": 8}))["curves"])[0].clone(); + let sk = sketch(s); + let mut lines: Vec<(f64, String)> = sk + .curves + .iter() + .filter_map(|c| match c.kind { + CurveKind::Line { a, b } => Some((sk.point(a).unwrap().dist(sk.point(b).unwrap()), c.id.clone())), + _ => None, + }) + .collect(); + lines.sort_by(|x, y| y.0.total_cmp(&x.0)); + let (kept, gone) = if keep_major { (&lines[0].1, &lines[1].1) } else { (&lines[1].1, &lines[0].1) }; + run(s, "sketch.delete", json!({"entities": [gone]})); + (e, kept.clone()) +} + +/// With one of its axes deleted, dragging the other still moves the ellipse with it, sizes kept. +#[test] +fn an_ellipse_s_remaining_axis_drags_it_along() { + for (keep_major, from) in [(true, Vec2::new(-12.0, 0.0)), (false, Vec2::new(0.0, 4.0))] { + let mut s = new_sketch(); + let (_, axis) = ellipse_with_one_axis(&mut s, keep_major); + run(&mut s, "sketch.drag", json!({"entity": &axis, "from": [from.x, from.y], "to": [from.x + 4.0, from.y + 6.0]})); + run(&mut s, "sketch.drag_end", json!({})); + let sk = sketch(&s); + let Some(CurveKind::Ellipse { c, m, r }) = sk.curves.iter().map(|x| x.kind.clone()).find(|k| matches!(k, CurveKind::Ellipse { .. })) else { + panic!("the ellipse: {:?}", sk.curves) + }; + let (at, a) = (sk.point(c).unwrap(), sk.point(c).unwrap().dist(sk.point(m).unwrap())); + assert!(at.dist(Vec2::new(4.0, 6.0)) < 1e-6 && close(a, 20.0) && close(r, 8.0), "major kept {keep_major}: centre {at:?}, half-axes {a} {r}"); + } +} + +/// With one of its axes deleted, a double-click on the ellipse or the other axis selects both. +#[test] +fn an_ellipse_and_its_remaining_axis_are_one_chain() { + let mut s = new_sketch(); + let (e, major) = ellipse_with_one_axis(&mut s, true); + let mut both = vec![e.clone(), major.clone()]; + both.sort(); + for id in [&e, &major] { + let mut chain = ids(&run(&mut s, "sketch.chain", json!({"curve": id}))["curves"]); + chain.sort(); + assert_eq!(chain, both, "double-click on {id}"); + } +} + /// #1026: a construction diagonal ending at a rectangle's corner is not one of the corner's /// sides. The corner is rounded, and the diagonal keeps its end on the virtual sharp corner. #[test] @@ -2390,7 +2709,8 @@ fn certified_offset_delete_output_undo_reopen_and_refuse_dependent_source() { run(&mut s, "sketch.delete", json!({"entities":[node]})); assert!(sketch(&s).freeform_offsets.is_empty()); assert!(sketch(&s).curve_index(&id).is_none()); - assert_eq!(sketch(&s).points.len(), 3, "all private derived nodes must be removed"); + // The origin, the ellipse's centre and major end, and its three other axis ends. + assert_eq!(sketch(&s).points.len(), 6, "all private derived nodes must be removed"); } #[test] diff --git a/crates/engine/src/cmd/sketch_ux_tests.rs b/crates/engine/src/cmd/sketch_ux_tests.rs index ae40e4477..8d94f52b8 100644 --- a/crates/engine/src/cmd/sketch_ux_tests.rs +++ b/crates/engine/src/cmd/sketch_ux_tests.rs @@ -161,7 +161,8 @@ fn fixing_curves_holds_their_points_and_radius() { assert_eq!(r["result"]["changed"], 4); assert_eq!(dof(&mut s), free - 17); let si = run(&mut s, "sketch.inspect", json!({})); - assert!(si["curves"].as_array().is_some_and(|c| c.iter().all(|c| c["fixed"] == true)), "{si}"); + // The ellipse's construction axes were not picked. + assert!(si["curves"].as_array().is_some_and(|c| c.iter().filter(|c| c["construction"] != true).all(|c| c["fixed"] == true)), "{si}"); // A fixed circle keeps centre and radius; a dimension on it conflicts. run(&mut s, "sketch.move_point", json!({"point": "c1.center", "to": [0, 0]})); assert_eq!(pt(&s, "c1.center"), solidcore_record::Vec2::new(10.0, 10.0)); @@ -1513,6 +1514,301 @@ fn auto_dimension_orientation_follows_where_its_text_is_placed() { assert!(((end.x - start.x).abs() - 24.0).abs() < 1e-6 && ((end.y - start.y).abs() - 40.0).abs() < 1e-6, "{start:?} {end:?}"); } +/// An ellipse with half-axes 20 and 8, turned by 45 degrees when asked: its id, and its +/// construction axis lines, major first. +fn ellipse_with_axes(s: &mut Session, turn: bool) -> (String, String, String) { + let at = |x: f64, y: f64| if turn { [std::f64::consts::FRAC_1_SQRT_2 * (x - y), std::f64::consts::FRAC_1_SQRT_2 * (x + y)] } else { [x, y] }; + let e = run(s, "sketch.ellipse", json!({"center": [0, 0], "major": at(20.0, 0.0), "minor_radius": 8}))["curves"][0] + .as_str() + .expect("the ellipse") + .to_string(); + let sk = sketch(s); + let mut lines: Vec<(f64, String)> = sk + .curves + .iter() + .filter_map(|c| match c.kind { + solidcraft_sketch::CurveKind::Line { a, b } if c.construction => Some((sk.point(a)?.dist(sk.point(b)?), c.id.clone())), + _ => None, + }) + .collect(); + lines.sort_by(|x, y| y.0.total_cmp(&x.0)); + let [(_, major), (_, minor)] = <[(f64, String); 2]>::try_from(lines).expect("two axis lines"); + (e, major, minor) +} + +/// D on an ellipse's outline gives a half-axis, the distance from the centre to an axis end, +/// chosen as a line chooses horizontal or vertical, in the ellipse's own frame: text pulled +/// across the major axis measures along it, text pulled out past an end of it measures across +/// it. Near the boundary a placement keeps the half-axis it had. D on an axis line gives the +/// whole axis. An ellipse without axes keeps its minor radius. +#[test] +fn an_ellipse_half_axis_dimension_follows_where_its_text_is_pulled() { + use solidcraft_sketch::ConstraintKind; + let dimension = |turn: bool, extra: Value| { + let mut s = new_sketch(); + let (e, ..) = ellipse_with_axes(&mut s, turn); + let mut p = json!({"entities": [e]}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + let r = run(&mut s, "sketch.dimension", p); + let sk = sketch(&s); + let kind = sk.constraints.iter().find(|c| c.kind.is_dimension()).map(|c| c.kind.clone()).expect("a dimension"); + let ConstraintKind::Distance { p, q, .. } = kind else { return ("radius".to_string(), 0.0, r) }; + let (pc, end) = (sk.point(p).expect("centre"), sk.point(q).expect("axis end")); + assert!(pc.len() < 1e-9, "measured from the centre: {pc:?}"); + let which = if (pc.dist(end) - 20.0).abs() < 1e-6 { "major" } else { "minor" }; + assert_eq!(r["axis"], json!(which), "{r}"); + // The end on the text's side. + let side = extra.get("text_at").and_then(Value::as_array).map(|t| (t[0].as_f64().unwrap_or(0.0), t[1].as_f64().unwrap_or(0.0))); + (which.to_string(), side.map_or(1.0, |(x, y)| end.x * x + end.y * y), r) + }; + let turned = |x: f64, y: f64, turn: bool| { + if turn { [std::f64::consts::FRAC_1_SQRT_2 * (x - y), std::f64::consts::FRAC_1_SQRT_2 * (x + y)] } else { [x, y] } + }; + for turn in [false, true] { + for ((x, y), expected) in [ + ((3.0, 16.0), "major"), + ((-4.0, -14.0), "major"), + ((18.0, 12.0), "major"), + ((30.0, 3.0), "minor"), + ((-28.0, -2.0), "minor"), + ((24.0, 6.0), "minor"), + ] { + let (which, side, r) = dimension(turn, json!({"text_at": turned(x, y, turn)})); + assert_eq!(which, expected, "turned {turn}, text at ({x}, {y}): {r}"); + assert!(side > 0.0, "turned {turn}, text at ({x}, {y}): the end on the other side"); + } + // Near the boundary (0.5 of the major half-axis along, 0.55 or 0.45 of the minor + // across) the half-axis a placement had is kept, from either side; well past it, it is not. + let near = json!(turned(10.0, 4.4, turn)); + assert_eq!(dimension(turn, json!({"text_at": near})).0, "major"); + assert_eq!(dimension(turn, json!({"text_at": near, "previous_axis": "minor"})).0, "minor"); + let near = json!(turned(10.0, 3.6, turn)); + assert_eq!(dimension(turn, json!({"text_at": near})).0, "minor"); + assert_eq!(dimension(turn, json!({"text_at": near, "previous_axis": "major"})).0, "major"); + assert_eq!(dimension(turn, json!({"text_at": turned(16.0, 4.0, turn), "previous_axis": "major"})).0, "minor"); + } + // An explicit type wins; with no text, the minor half-axis; radius, and any other type, + // stays the minor radius as on an ellipse without axes. + assert_eq!(dimension(false, json!({"type": "major", "text_at": [30, 3]})).0, "major"); + assert_eq!(dimension(false, json!({"type": "minor", "text_at": [3, 16]})).0, "minor"); + assert_eq!(dimension(false, json!({})).0, "minor"); + assert_eq!(dimension(false, json!({"type": "radius", "text_at": [3, 16]})).0, "radius"); + assert_eq!(dimension(false, json!({"type": "diameter", "text_at": [3, 16]})).0, "radius"); + assert_eq!(dimension(false, json!({"type": "horizontal", "text_at": [3, 16]})).0, "radius"); + // With half_axes false (Draw ellipses with their axes off), auto is the minor radius + // wherever the text is, as before half-axes; an explicit type still gives its half-axis. + for at in [[3.0, 16.0], [30.0, 3.0]] { + assert_eq!(dimension(false, json!({"half_axes": false, "text_at": at})).0, "radius", "text at {at:?}"); + } + assert_eq!(dimension(false, json!({"half_axes": false, "type": "major"})).0, "major"); + let mut s = new_sketch(); + let (e, ..) = ellipse_with_axes(&mut s, false); + assert!(s.execute("sketch.dimension", &json!({"entities": [e], "half_axes": "no"})).is_err()); + // An axis line is a line: its length is the whole axis. + let mut s = new_sketch(); + let (_, major, minor) = ellipse_with_axes(&mut s, true); + assert_eq!(run(&mut s, "sketch.dimension", json!({"entities": [major]}))["measured"], json!(40.0)); + assert_eq!(run(&mut s, "sketch.dimension", json!({"entities": [minor]}))["measured"], json!(16.0)); + // Also with the text beside or above the box a turned axis spans, where a free line gives + // its horizontal or vertical distance; and it holds that half-axis, so D on the outline + // then gives the other one. + for (axis, at, whole) in [("major", [30.0, 0.0], 40.0), ("major", [0.0, -30.0], 40.0), ("minor", [20.0, 0.0], 16.0), ("minor", [0.0, 20.0], 16.0)] + { + let mut s = new_sketch(); + let (e, major, minor) = ellipse_with_axes(&mut s, true); + let line = if axis == "major" { major } else { minor }; + let r = run(&mut s, "sketch.dimension", json!({"entities": [line], "text_at": at})); + assert!(r["measured"].as_f64().is_some_and(|v| (v - whole).abs() < 1e-6), "{axis} axis, text at {at:?}: {r}"); + let r = run(&mut s, "sketch.dimension", json!({"entities": [e], "text_at": [3, 16]})); + assert_ne!(r["axis"], json!(axis), "{axis} axis, text at {at:?}: {r}"); + } + // With one axis deleted the half-axis is still chosen by where the text is, as if the axis + // were there: the major half-axis to the major end, the minor one to what is left of its axis + // or, with that gone, as the minor radius. + let placed = |gone: &str, extra: Value| { + let mut s = new_sketch(); + let (e, major, minor) = ellipse_with_axes(&mut s, true); + run(&mut s, "sketch.delete", json!({"entities": [if gone == "major" { major } else { minor }]})); + let mut p = json!({"entities": [e]}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + let r = run(&mut s, "sketch.dimension", p); + let sk = sketch(&s); + let kind = sk.constraints.iter().find(|c| c.kind.is_dimension()).map(|c| c.kind.clone()).expect("a dimension"); + // Where the dimension ends: the axis end it measures to, none for a radius. + let end = match kind { + ConstraintKind::Distance { q, .. } => sk.point(q), + ConstraintKind::Radius { .. } => None, + other => panic!("a half-axis, not {other:?}"), + }; + (r, end) + }; + for gone in ["major", "minor"] { + for ((x, y), expected) in [((3.0, 16.0), "major"), ((-4.0, -14.0), "major"), ((30.0, 3.0), "minor"), ((-28.0, -2.0), "minor")] { + let at = [std::f64::consts::FRAC_1_SQRT_2 * (x - y), std::f64::consts::FRAC_1_SQRT_2 * (x + y)]; + let (r, end) = placed(gone, json!({"text_at": at})); + assert_eq!(r["axis"], json!(expected), "{gone} axis deleted, text at ({x}, {y}): {r}"); + let want = if expected == "major" { 20.0 } else { 8.0 }; + assert!(r["measured"].as_f64().is_some_and(|v| (v - want).abs() < 1e-6), "{gone} axis deleted, text at ({x}, {y}): {r}"); + // To the axis end on the text's side while there is one: the major end from either + // side once the point opposite is gone, a radius once the minor axis is. + match (gone, expected) { + ("minor", "minor") => assert!(end.is_none(), "the minor radius: {r}"), + ("major", "major") => { + let m = solidcore_record::Vec2::new(20.0, 20.0) * std::f64::consts::FRAC_1_SQRT_2; + assert!(end.is_some_and(|q| q.dist(m) < 1e-6), "the major end: {r}") + } + _ => assert!( + end.is_some_and(|q| q.x * at[0] + q.y * at[1] > 0.0), + "{gone} axis deleted, text at ({x}, {y}): the end on the other side" + ), + } + } + } + // With the major axis deleted and no text, the minor half-axis to its axis end, named in + // the reply as with both axes. + let (r, end) = placed("major", json!({})); + assert_eq!((r["axis"].clone(), r["type"].clone()), (json!("minor"), json!("LinearDimension")), "{r}"); + assert!(end.is_some_and(|q| (q.len() - 8.0).abs() < 1e-6), "{r}"); + // Without its axes (an older design, or both deleted) the half-axis is still chosen by + // where the text is: the major one to the ellipse's own major end, the minor one as its + // minor radius; with no text, the minor radius as before. + for ((x, y), expected, want) in [((3.0, 16.0), "major", 20.0), ((-4.0, -14.0), "major", 20.0), ((30.0, 3.0), "minor", 8.0)] { + let mut s = new_sketch(); + let (e, major, minor) = ellipse_with_axes(&mut s, false); + run(&mut s, "sketch.delete", json!({"entities": [major, minor]})); + let r = run(&mut s, "sketch.dimension", json!({"entities": [e], "text_at": [x, y]})); + assert_eq!(r["axis"], json!(expected), "text at ({x}, {y}): {r}"); + assert!(r["measured"].as_f64().is_some_and(|v| (v - want).abs() < 1e-6), "text at ({x}, {y}): {r}"); + } + let mut s = new_sketch(); + let (e, major, minor) = ellipse_with_axes(&mut s, false); + run(&mut s, "sketch.delete", json!({"entities": [major, minor]})); + run(&mut s, "sketch.dimension", json!({"entities": [e]})); + assert!(sketch(&s).constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Radius { .. }))); + // The mirror of an ellipse has no axes (Mirror copies no midpoints): D on it reaches the + // major half-axis as well. + let mut s = new_sketch(); + let (e, major, minor) = ellipse_with_axes(&mut s, false); + run(&mut s, "sketch.delete", json!({"entities": [minor]})); + let line = run(&mut s, "sketch.line", json!({"points": [[40, -30], [40, 30]], "connect": false}))["curves"][0].as_str().unwrap().to_string(); + let copy = run(&mut s, "sketch.mirror", json!({"entities": [e, major], "line": line}))["curves"][0].as_str().unwrap().to_string(); + let sk = sketch(&s); + assert!(sk.ellipse_axis_lines(sk.curve_index(©).unwrap()).is_none(), "the mirror has no axes"); + let r = run(&mut s, "sketch.dimension", json!({"entities": [copy], "text_at": [77, 16]})); + assert_eq!((r["axis"].clone(), r["measured"].clone()), (json!("major"), json!(20.0)), "{r}"); +} + +/// With one half-axis already dimensioned, D on the outline gives the other one wherever the +/// text is pulled: guessing the one that is already there would only be refused. Either order, +/// with both axes, with one deleted and with none. +#[test] +fn an_ellipse_s_second_half_axis_is_the_one_not_yet_dimensioned() { + for gone in [&[][..], &["major"][..], &["minor"][..], &["major", "minor"][..]] { + for (first, at, second) in [("major", [3.0, 16.0], "minor"), ("minor", [30.0, 3.0], "major")] { + let mut s = new_sketch(); + let (e, major, minor) = ellipse_with_axes(&mut s, false); + let deleted: Vec = gone.iter().map(|g| if *g == "major" { major.clone() } else { minor.clone() }).collect(); + if !deleted.is_empty() { + run(&mut s, "sketch.delete", json!({"entities": deleted})); + } + let r = run(&mut s, "sketch.dimension", json!({"entities": [e], "text_at": at})); + assert_eq!(r["axis"], json!(first), "{gone:?}: {r}"); + let r = run(&mut s, "sketch.dimension", json!({"entities": [e], "text_at": at})); + assert_eq!(r["axis"], json!(second), "{gone:?}, {first} first, then text at {at:?} again: {r}"); + assert!(r["param"].is_string(), "{gone:?}: the second one drives: {r}"); + } + } + // The whole axis held counts too: as a distance between its ends, or as its line's length + // with the other axis deleted. + for axis in ["major", "minor"] { + let mut s = new_sketch(); + let (e, major, minor) = ellipse_with_axes(&mut s, false); + let line = if axis == "major" { &major } else { &minor }; + run(&mut s, "sketch.dimension", json!({"entities": [format!("{line}.start"), format!("{line}.end")], "type": "distance"})); + let at = if axis == "major" { [3.0, 16.0] } else { [30.0, 3.0] }; + let r = run(&mut s, "sketch.dimension", json!({"entities": [e], "text_at": at})); + assert_ne!(r["axis"], json!(axis), "{axis} held between its ends: {r}"); + let mut s = new_sketch(); + let (e, major, minor) = ellipse_with_axes(&mut s, false); + let (line, other) = if axis == "major" { (major, minor) } else { (minor, major) }; + run(&mut s, "sketch.delete", json!({"entities": [other]})); + run(&mut s, "sketch.dimension", json!({"entities": [line]})); + let r = run(&mut s, "sketch.dimension", json!({"entities": [e], "text_at": at})); + assert_ne!(r["axis"], json!(axis), "{axis} held by its line, the other axis deleted: {r}"); + } +} + +/// A horizontal dimension across a level major axis is its length, so D on the outline then +/// gives the minor half-axis; across a slanted axis it is only a projection, and the major +/// half-axis is still free to take. +#[test] +fn a_horizontal_dimension_across_a_level_major_axis_counts_as_holding_it() { + for turn in [false, true] { + let mut s = new_sketch(); + let (e, major, _) = ellipse_with_axes(&mut s, turn); + run(&mut s, "sketch.dimension", json!({"entities": [format!("{major}.start"), format!("{major}.end")], "type": "horizontal"})); + let at = if turn { [std::f64::consts::FRAC_1_SQRT_2 * (3.0 - 16.0), std::f64::consts::FRAC_1_SQRT_2 * (3.0 + 16.0)] } else { [3.0, 16.0] }; + let r = run(&mut s, "sketch.dimension", json!({"entities": [e], "text_at": at})); + let want = if turn { "major" } else { "minor" }; + assert_eq!(r["axis"], json!(want), "turned {turn}: {r}"); + assert!(r["param"].is_string(), "turned {turn}: it drives: {r}"); + } +} + +/// The same for the minor axis: a vertical dimension across its ends holds it while it stands +/// upright, so D with the text out past the major axis's end then gives the major half-axis. +#[test] +fn a_vertical_dimension_across_an_upright_minor_axis_counts_as_holding_it() { + for turn in [false, true] { + let mut s = new_sketch(); + let (e, _, minor) = ellipse_with_axes(&mut s, turn); + run(&mut s, "sketch.dimension", json!({"entities": [format!("{minor}.start"), format!("{minor}.end")], "type": "vertical"})); + let at = if turn { [std::f64::consts::FRAC_1_SQRT_2 * (30.0 - 3.0), std::f64::consts::FRAC_1_SQRT_2 * (30.0 + 3.0)] } else { [30.0, 3.0] }; + let r = run(&mut s, "sketch.dimension", json!({"entities": [e], "text_at": at})); + let want = if turn { "minor" } else { "major" }; + assert_eq!(r["axis"], json!(want), "turned {turn}: {r}"); + assert!(r["param"].is_string(), "turned {turn}: it drives: {r}"); + } +} + +/// A half-axis and its whole axis are one dimension: whichever comes second is determined by +/// the first, so the Dimension tool's `if_redundant: "driven"` adds it as a reference, and +/// without it the command refuses it. Both orders, both axes. After the whole axis, D on the +/// outline with no type gives the other half-axis, the one not yet held; the same half-axis +/// is asked for by its type. +#[test] +fn an_ellipse_half_axis_and_its_whole_axis_determine_each_other() { + for (axis, text_at) in [("major", [3.0, 16.0]), ("minor", [30.0, 3.0])] { + for half_first in [true, false] { + let mut s = new_sketch(); + let (e, major, minor) = ellipse_with_axes(&mut s, false); + let line = if axis == "major" { major } else { minor }; + let half = json!({"entities": [e], "text_at": text_at, "type": axis}); + let whole = json!({"entities": [line]}); + if !half_first { + let mut t = new_sketch(); + let (e, major, minor) = ellipse_with_axes(&mut t, false); + run(&mut t, "sketch.dimension", json!({"entities": [if axis == "major" { major } else { minor }]})); + let r = run(&mut t, "sketch.dimension", json!({"entities": [e], "text_at": text_at})); + assert_ne!(r["axis"], json!(axis), "{axis}: after the whole axis, the other half-axis: {r}"); + } + let (first, second) = if half_first { (half, whole) } else { (whole, half) }; + let r = run(&mut s, "sketch.dimension", first); + assert!(r["param"].is_string(), "{axis}: the first one drives: {r}"); + let refused = s.execute("sketch.dimension", &second).expect_err("the second one is determined").to_string(); + assert!(refused.contains("already determined"), "{axis}: {refused}"); + let mut second = second; + second["if_redundant"] = json!("driven"); + let r = run(&mut s, "sketch.dimension", second); + assert_eq!((r["redundant"].clone(), r["driven"].clone()), (json!(true), json!(true)), "{axis}, half first {half_first}: {r}"); + } + } +} + /// A two-link arm (B, elbow E, hand H) hanging off a rigid triangle A B C that only the cluster /// decomposition places: pinned at F by two of its corners and held at G by the third. Every /// line is dimensioned. Without decomposition budget the elbow's seed has nothing to build on. diff --git a/crates/sketch/src/dims.rs b/crates/sketch/src/dims.rs index 427570ffc..ea6c635bc 100644 --- a/crates/sketch/src/dims.rs +++ b/crates/sketch/src/dims.rs @@ -27,6 +27,11 @@ pub enum DimFrame { Angular { vertex: Vec2, d0: Vec2, sweep: f64 }, /// Length along an arc around `center` from angle `start` by `sweep`. ArcLength { center: Vec2, radius: f64, start: f64, sweep: f64 }, + /// An ellipse's minor half-axis: `len` from `center` along the unit `dir` or against it, + /// drawn as a linear dimension to the minor axis end on the text's side, as the distance + /// to that end is when the ellipse has its axes. The text is stored from `center`, as a + /// radius's is, so a radius placed before it was drawn this way keeps its text. + HalfAxis { center: Vec2, dir: Vec2, len: f64 }, } /// A drawn dimension (sketch coordinates). @@ -126,6 +131,10 @@ pub fn dim_frame(sk: &Sketch, k: &ConstraintKind) -> Option { DimFrame::Linear { p0, p1, dir: u } } Radius { c, .. } | Diameter { c, .. } => { + if let (Radius { .. }, CurveKind::Ellipse { c: centre, m, r }) = (k, &sk.curves.get(c)?.kind) { + let center = sk.point(*centre)?; + return Some(DimFrame::HalfAxis { center, dir: unit(sk.point(*m)? - center, Vec2::X).perp(), len: *r }); + } let (radius, arc) = match sk.curves.get(c)?.kind { CurveKind::Ellipse { r, .. } => (r, None), CurveKind::Arc { .. } => match sk.segs(c).first()? { @@ -172,9 +181,18 @@ pub fn encode_text(f: &DimFrame, at: Vec2) -> Vec2 { } DimFrame::Radial { center, .. } | DimFrame::ArcLength { center, .. } => at - center, DimFrame::Angular { vertex, .. } => at - vertex, + DimFrame::HalfAxis { center, .. } => at - center, } } +/// The linear frame a [`DimFrame::HalfAxis`] is drawn as for the stored text `t`: to the end +/// on the text's side, with `t` re-expressed for that frame. +fn half_axis_side(center: Vec2, dir: Vec2, len: f64, t: Vec2) -> (DimFrame, Vec2) { + let dir = if t.dot(dir) < 0.0 { -dir } else { dir }; + let linear = DimFrame::Linear { p0: center, p1: center + dir * len, dir }; + (linear, encode_text(&linear, center + t)) +} + /// Per point: the centre of the connected geometry it belongs to (points joined by curves), /// which a dimension's default place keeps away from. pub fn chain_centres(sk: &Sketch) -> Vec { @@ -214,6 +232,8 @@ pub fn default_text(f: &DimFrame, away: Vec2, px: f64) -> Option { pub fn default_text_offset(f: &DimFrame, px: f64) -> Vec2 { match *f { DimFrame::Linear { .. } => Vec2::new(0.0, 22.0 * px), + // Where a linear dimension to the minor axis end puts it. + DimFrame::HalfAxis { dir, len, .. } => dir * (len * 0.5) + dir.perp() * (22.0 * px), DimFrame::Radial { radius, .. } => Vec2::new(1.0, 1.0) * ((radius + 18.0 * px) * std::f64::consts::FRAC_1_SQRT_2), DimFrame::Angular { d0, sweep, .. } => Vec2::from_angle(d0.angle() + sweep * 0.5) * (48.0 * px), DimFrame::ArcLength { radius, start, sweep, .. } => Vec2::from_angle(start + sweep * 0.5) * (radius + 20.0 * px), @@ -293,6 +313,11 @@ pub fn dim_layout_reaching(f: &DimFrame, text: Option, px: f64, half: Vec2 let over = 4.0 * px; let mut out = DimLayout::default(); match *f { + DimFrame::HalfAxis { center, dir, len } => { + let t = text.unwrap_or_else(|| default_text_offset(f, px)); + let (linear, t) = half_axis_side(center, dir, len, t); + return dim_layout_reaching(&linear, Some(t), px, half, reach); + } DimFrame::Linear { p0, p1, dir } => { let n = dir.perp(); let m = (p0 + p1) * 0.5; @@ -465,6 +490,42 @@ mod tests { assert!(close(dim_layout(&r, Some(encode_text(&r, at)), 0.1, Vec2::ZERO).text, at)); } + #[test] + fn an_ellipse_s_minor_radius_is_drawn_as_the_distance_to_its_axis_end() { + // A turned ellipse whose minor axis line was deleted: its minor radius is drawn as the + // distance from the centre to the minor axis end would be, on whichever side the text is. + let mut sk = Sketch::new(); + let major = Vec2::new(1.0, 1.0) * (20.0 * std::f64::consts::FRAC_1_SQRT_2); + let c = sk.add_point(Vec2::ZERO, None).unwrap_or(0); + let m = sk.add_point(major, None).unwrap_or(0); + let e = sk.add_curve(CurveKind::Ellipse { c, m, r: 8.0 }, None).unwrap_or(0); + let f = + dim_frame(&sk, &ConstraintKind::Radius { c: e, value: 8.0 }).unwrap_or(DimFrame::Linear { p0: Vec2::ZERO, p1: Vec2::ZERO, dir: Vec2::X }); + assert!(matches!(f, DimFrame::HalfAxis { .. }), "{f:?}"); + // Its text is stored from the centre, as it was while it was drawn as a radius, so a + // design saved then keeps the text where it was placed. + let at = Vec2::new(3.0, 17.0); + let radial = DimFrame::Radial { center: Vec2::ZERO, radius: 8.0, diameter: false, arc: None }; + assert!(close(encode_text(&f, at), encode_text(&radial, at))); + assert!(close(dim_layout(&f, Some(encode_text(&radial, at)), 0.1, Vec2::ZERO).text, at)); + let minor = Vec2::new(-1.0, 1.0) * (8.0 * std::f64::consts::FRAC_1_SQRT_2); + for end in [minor, minor * -1.0] { + let to_end = DimFrame::Linear { p0: Vec2::ZERO, p1: end, dir: end * (1.0 / 8.0) }; + for at in [end * 1.6 + major * 0.2, end * 0.5 - major * 0.9] { + let half = dim_layout(&f, Some(encode_text(&f, at)), 0.1, Vec2::new(2.0, 1.0)); + let axis = dim_layout(&to_end, Some(encode_text(&to_end, at)), 0.1, Vec2::new(2.0, 1.0)); + let same = |a: &[Vec2], b: &[Vec2]| a.len() == b.len() && a.iter().zip(b).all(|(p, q)| close(*p, *q)); + assert!(close(half.text, at) && close(half.text, axis.text), "{at:?}"); + assert!( + half.lines.len() == axis.lines.len() && half.lines.iter().zip(&axis.lines).all(|(a, b)| same(a, b)), + "{at:?}: {half:?} {axis:?}" + ); + let tips = |l: &DimLayout| l.arrows.iter().map(|a| a.0).collect::>(); + assert!(same(&tips(&half), &tips(&axis)), "{at:?}"); + } + } + } + #[test] fn diameter_has_arrows_on_both_sides() { let r = DimFrame::Radial { center: Vec2::ZERO, radius: 10.0, diameter: true, arc: None }; diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index 18a238df1..91f795554 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -1278,8 +1278,88 @@ impl Sketch { out } + /// The construction axes `sketch.ellipse` draws with an ellipse, or what is left of them when + /// one was deleted: the major axis line (from the point opposite the major end to the major + /// end) with the point opposite the major end, and the minor axis line (held on the ellipse + /// at one end) with that end, then the one opposite; both are bisected by the centre. None + /// for an ellipse with neither (one from an older design, or whose axes were deleted). + /// + /// The axes are read from the constraints alone, with no mark in the design: any line the + /// centre bisects through the major end, and any other with an end held on the ellipse, + /// first in curve order, counts, construction or not (a diameter drawn that way before the + /// minor axis is taken for it). Deleting the midpoint or point-on-curve constraint makes + /// it an ellipse without that axis. Each call scans the constraints once, and again per line + /// the centre bisects; `chain`, a line drag and a move ask it for the ellipses they meet. + #[allow(clippy::type_complexity)] + pub fn ellipse_axis_lines(&self, e: usize) -> Option<(Option<(usize, usize)>, Option<(usize, usize, usize)>)> { + let Some(CurveKind::Ellipse { c, m, .. }) = self.curves.get(e).map(|x| &x.kind) else { return None }; + let line = |l: usize| match self.curves.get(l).map(|x| &x.kind) { + Some(CurveKind::Line { a, b }) => Some((*a, *b)), + _ => None, + }; + // The lines the centre bisects, in curve order: one pass over the constraints, so a + // large sketch does not pay curves times constraints per ellipse. + let mut held: Vec = self + .constraints + .iter() + .filter_map(|k| match k.kind { + ConstraintKind::Midpoint { p, l } if !k.driven && p == *c => Some(l), + _ => None, + }) + .collect(); + held.sort_unstable(); + held.dedup(); + let on = + |q: usize| self.constraints.iter().any(|k| !k.driven && matches!(k.kind, ConstraintKind::PointOnCurve { p, c: on } if p == q && on == e)); + let major = held.iter().find_map(|&l| match line(l) { + Some((a, b)) if a == *m || b == *m => Some((l, if a == *m { b } else { a })), + _ => None, + }); + let minor = held.iter().copied().filter(|l| major.is_none_or(|(major, _)| *l != major)).find_map(|l| { + let (a, b) = line(l)?; + if on(a) { + Some((l, a, b)) + } else if on(b) { + Some((l, b, a)) + } else { + None + } + }); + (major.is_some() || minor.is_some()).then_some((major, minor)) + } + + /// The ellipse whose axis line `l` is (see [`Sketch::ellipse_axis_lines`]), if any. + pub fn ellipse_of_axis(&self, l: usize) -> Option { + if !matches!(self.curves.get(l).map(|x| &x.kind), Some(CurveKind::Line { .. })) { + return None; + } + (0..self.curves.len()).find(|&e| { + self.ellipse_axis_lines(e) + .is_some_and(|(major, minor)| major.is_some_and(|(line, _)| line == l) || minor.is_some_and(|(line, ..)| line == l)) + }) + } + + /// Whether line `l` is one of an ellipse's axes (see [`Sketch::ellipse_axis_lines`]). + pub fn is_ellipse_axis(&self, l: usize) -> bool { + // An axis is bisected by its ellipse's centre: only the ellipses centred on a point that + // bisects `l` are asked. + let centres: Vec = self + .constraints + .iter() + .filter_map(|k| match k.kind { + ConstraintKind::Midpoint { p, l: m } if !k.driven && m == l => Some(p), + _ => None, + }) + .collect(); + (0..self.curves.len()) + .filter(|&e| matches!(self.curves.get(e).map(|x| &x.kind), Some(CurveKind::Ellipse { c, .. }) if centres.contains(c))) + .filter_map(|e| self.ellipse_axis_lines(e)) + .any(|(major, minor)| major.is_some_and(|(line, _)| line == l) || minor.is_some_and(|(line, ..)| line == l)) + } + /// The curves joined end to end with curve `ci` (through shared or coincident end points), - /// `ci` first, then the others in sketch order: what a double-click selects. + /// `ci` first, then the others in sketch order: what a double-click selects. An ellipse and + /// its construction axes count as joined, as a rectangle's edges and its diagonals are. pub fn chain(&self, ci: usize) -> Vec { if ci >= self.curves.len() { return Vec::new(); @@ -1293,6 +1373,13 @@ impl Sketch { } let ends: Vec> = self.curves.iter().map(|c| c.kind.ends().map(|(a, b)| vec![find(&mut root, a), find(&mut root, b)]).unwrap_or_default()).collect(); + // Each ellipse with whichever of its axes are left (one may have been deleted). + let ellipses: Vec> = (0..self.curves.len()) + .filter_map(|e| { + let (major, minor) = self.ellipse_axis_lines(e)?; + Some(std::iter::once(e).chain(major.map(|(l, _)| l)).chain(minor.map(|(l, ..)| l)).collect()) + }) + .collect(); let mut seen = vec![false; self.curves.len()]; let mut stack = vec![ci]; let mut out = Vec::new(); @@ -1310,6 +1397,11 @@ impl Sketch { stack.push(j); } } + for group in &ellipses { + if group.contains(&i) { + stack.extend(group); + } + } } let first = out.first().copied(); out.sort_unstable(); @@ -1657,7 +1749,8 @@ impl Sketch { } /// Remove curves (by index) and then any points no longer used by a curve (except the - /// origin and free points), and constraints that referred to removed entities. + /// origin and free points, and a removed ellipse's centre while one of its axes stays, as a + /// Center Rectangle's centre stays), and constraints that referred to removed entities. pub fn remove_curves(&mut self, which: &[usize]) { let mut owned: Vec = Vec::new(); for (i, c) in self.curves.iter().enumerate() { @@ -1665,6 +1758,17 @@ impl Sketch { owned.extend(c.kind.point_ids()); } } + // An ellipse going while one of its axes stays leaves its centre, which still bisects + // them, as a Center Rectangle's centre stays with its edges gone. + let centres: Vec = which + .iter() + .filter_map(|&e| { + let CurveKind::Ellipse { c, .. } = self.curves.get(e)?.kind else { return None }; + let (major, minor) = self.ellipse_axis_lines(e)?; + [major.map(|(l, _)| l), minor.map(|(l, ..)| l)].into_iter().flatten().any(|l| !which.contains(&l)).then_some(c) + }) + .collect(); + owned.retain(|p| !centres.contains(p)); let on_ends = self.points_on_ends_of(which); self.drop_curves(which); for (p, q) in on_ends { diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 8e42ca344..eb8c664a4 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -3489,7 +3489,7 @@ pub(crate) fn occurrence_triad(app: &mut SolveApp, ui: &mut egui::Ui, painter: & /// value edits it in place without editing the sketch (`crate::dim_view::model_double_click`). pub fn dims_overlay(app: &SolveApp, ctx: &egui::Context) { use solidcore_record::Vec2; - use solidcraft_engine::sketch::{DimFrame, chain_centres, default_text, dim_frame, dim_layout_reaching, dim_reach}; + use solidcraft_engine::sketch::{DimFrame, chain_centres, default_text, dim_layout_reaching, dim_reach}; crate::dim_view::set_model_drawn(Vec::new()); let Some(rect) = app.viewport.rect else { return }; if app.session.visibility.shown_dimensions.is_empty() { @@ -3515,10 +3515,10 @@ pub fn dims_overlay(app: &SolveApp, ctx: &egui::Context) { let n = centres.len().max(1) as f64; let middle = centres.iter().fold(Vec2::ZERO, |a, p| a + *p) * (1.0 / n); for c in &sk.constraints { - let Some(frame) = dim_frame(sk, &c.kind) else { continue }; + let Some(frame) = crate::dim_view::shown_frame(app.preferences.ellipse_axes, sk, &c.kind) else { continue }; let anchor = match frame { DimFrame::Linear { p0, p1, .. } => (p0 + p1) * 0.5, - DimFrame::Radial { center, .. } | DimFrame::ArcLength { center, .. } => center, + DimFrame::Radial { center, .. } | DimFrame::ArcLength { center, .. } | DimFrame::HalfAxis { center, .. } => center, DimFrame::Angular { vertex, .. } => vertex, }; let (Some(a), Some(b)) = (to(anchor), to(anchor + Vec2::X)) else { continue }; @@ -3529,7 +3529,7 @@ pub fn dims_overlay(app: &SolveApp, ctx: &egui::Context) { let expr = c.param.as_ref().and_then(|p| app.session.doc.param(p)).map(|p| p.expr.as_str()); let col = if c.driven { tk.dimension_driven } else { tk.dimension }; let galley = painter.layout_no_wrap( - crate::dim_view::label(&c.kind, expr, c.driven, &app.session.doc.units, app.preferences.length_decimals), + crate::dim_view::frame_label(&frame, &c.kind, expr, c.driven, &app.session.doc.units, app.preferences.length_decimals), FontId::proportional(tk.font_caption), col, ); diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index d00e87ae0..dfaef0ac2 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -1306,7 +1306,9 @@ fn sketch_entity_items(app: &SolveApp) -> Vec { v.push(act("ui.copy", "Copy", "copy").key("Ctrl+C")); v.push(act("ui.paste", "Paste", "paste").key("Ctrl+V").on(crate::edit_clipboard::can_paste_sketch(app))); v.push(act("ui.delete", "Delete", "delete").key("Del")); - v.push(cmd(app, "sketch.dimension", "Sketch Dimension").with(json!({ "entities": ents })).on(ents.len() <= 2)); + let mut dimension = json!({ "entities": ents }); + crate::dim_view::ellipse_as_before(app.preferences.ellipse_axes, &mut dimension); + v.push(cmd(app, "sketch.dimension", "Sketch Dimension").with(dimension).on(ents.len() <= 2)); // One arc alone: Sketch Dimension gives its radius, this its length along the curve (#6039). if let [arc] = ents.as_slice() && ss.sketch.curve_index(arc).and_then(|i| ss.sketch.curves.get(i)).is_some_and(|c| matches!(c.kind, CurveKind::Arc { .. })) diff --git a/crates/ui-egui/src/dim_view.rs b/crates/ui-egui/src/dim_view.rs index ecb6727bb..c499ed3ba 100644 --- a/crates/ui-egui/src/dim_view.rs +++ b/crates/ui-egui/src/dim_view.rs @@ -107,6 +107,8 @@ struct DimensionDraft { /// A dimension that would over-constrain the sketch, placed as a driven (reference) one: /// it has no parameter and no value to edit (#320). driven: bool, + /// Draw ellipses with their axes, when the draft was made (see [`ellipse_as_before`]). + half_axes: bool, } impl DimensionDraft { @@ -123,11 +125,15 @@ impl DimensionDraft { if let Some(at) = self.at { params["text_at"] = json!([at.x, at.y]); } + previous_axis(self.sketch, &self.entities, &mut params); + ellipse_as_before(self.half_axes, &mut params); params } fn evaluate(&self, app: &SolveApp, expr: &str) -> Result { let mut scratch = app.session.scratch(); - let result = scratch.execute("sketch.dimension", &self.params(expr)).map_err(|e| shown_error("sketch.dimension", &e.to_string()))?; + let params = self.params(expr); + let result = scratch.execute("sketch.dimension", ¶ms).map_err(|e| shown_error("sketch.dimension", &e.to_string()))?; + remember_axis(self.sketch, &self.entities, ¶ms, &result); let param = result.get("param").and_then(serde_json::Value::as_str).ok_or("The dimension value is unavailable")?; let state = crate::open_meshing::session_world(&scratch); let solved = state.sketch(self.sketch).ok_or("The dimension sketch is unavailable")?; @@ -156,6 +162,47 @@ pub fn cancel() { EDIT.with(|edit| *edit.borrow_mut() = None); PLACEMENT.with(|preview| *preview.borrow_mut() = None); window::forget(); + AXIS.with(|axis| *axis.borrow_mut() = None); +} + +/// With Draw ellipses with their axes off, D on an ellipse gives its minor radius wherever +/// the text is, as before half-axes (`sketch.dimension`'s `half_axes`). +pub(crate) fn ellipse_as_before(half_axes: bool, params: &mut serde_json::Value) { + if !half_axes { + params["half_axes"] = json!(false); + } +} + +/// How a dimension is drawn: with Draw ellipses with their axes off, a radius on an ellipse +/// is drawn as a radius, as before, instead of to its minor axis end. +pub(crate) fn shown_frame(half_axes: bool, sk: &solidcraft_engine::sketch::Sketch, k: &ConstraintKind) -> Option { + match dim_frame(sk, k)? { + DimFrame::HalfAxis { center, len, .. } if !half_axes => Some(DimFrame::Radial { center, radius: len, diameter: false, arc: None }), + frame => Some(frame), + } +} + +/// Near the boundary between an ellipse's two half-axes, a dimension being placed keeps the +/// one it had (`sketch.dimension`'s `previous_axis`), so the preview does not flip. +fn previous_axis(sketch: u64, entities: &[String], params: &mut serde_json::Value) { + AXIS.with(|axis| { + if let Some((in_sketch, picked, axis)) = axis.borrow().as_ref() + && *in_sketch == sketch + && picked.as_slice() == entities + { + params["previous_axis"] = json!(axis); + } + }); +} + +/// Only a draft whose text was placed chose its half-axis; one without text is the minor one +/// by default and would bias the first placement. +fn remember_axis(sketch: u64, entities: &[String], params: &serde_json::Value, result: &serde_json::Value) { + if params.get("text_at").is_some() + && let Some(chosen) = result.get("axis").and_then(serde_json::Value::as_str) + { + AXIS.with(|axis| *axis.borrow_mut() = Some((sketch, entities.to_vec(), chosen.to_string()))); + } } /// Infer the measured value through the same command as scripts, without creating a real @@ -165,7 +212,11 @@ pub fn begin_dimension(app: &mut SolveApp, entities: Vec, at: Vec2) -> R let (param, expr, draft) = dimension_draft(app, entities, Some(at))?; if draft.driven { PLACEMENT.with(|preview| *preview.borrow_mut() = None); - app.run("sketch.dimension", json!({"entities": entities_value(&draft.entities), "text_at": [at.x, at.y], "driven": true}))?; + let mut params = json!({"entities": entities_value(&draft.entities), "text_at": [at.x, at.y], "driven": true}); + previous_axis(draft.sketch, &draft.entities, &mut params); + ellipse_as_before(draft.half_axes, &mut params); + AXIS.with(|axis| *axis.borrow_mut() = None); + app.run("sketch.dimension", params)?; app.set_status(crate::i18n::tr("sketch.dimension_added_driven"), false); return Ok(()); } @@ -315,7 +366,10 @@ fn draft_of(app: &SolveApp, sketch: u64, entities: &[String], at: Option, if let Some(at) = at { params["text_at"] = json!([at.x, at.y]); } + previous_axis(sketch, entities, &mut params); + ellipse_as_before(app.preferences.ellipse_axes, &mut params); let result = scratch.execute("sketch.dimension", ¶ms).map_err(|e| e.to_string())?; + remember_axis(sketch, entities, ¶ms, &result); let (param, expr) = if driven { let before = app.session.doc.sketch(sketch).ok().map(|sk| sk.constraints.iter().map(|c| c.id.clone()).collect::>()).unwrap_or_default(); @@ -340,6 +394,7 @@ fn draft_of(app: &SolveApp, sketch: u64, entities: &[String], at: Option, preview_doc: scratch.doc.clone(), error: None, driven, + half_axes: app.preferences.ellipse_axes, }; if !draft.preview.sketch(sketch).is_some_and(|solved| solved.report.ok()) { return Err("That dimension conflicts with the sketch constraints".into()); @@ -397,6 +452,9 @@ thread_local! { static DRAG: RefCell> = const { RefCell::new(None) }; static EDIT: RefCell> = const { RefCell::new(None) }; static PLACEMENT: RefCell> = const { RefCell::new(None) }; + /// The half-axis of an ellipse the last placed draft for these picks in this sketch + /// measured (see `previous_axis`). + static AXIS: RefCell, String)>> = const { RefCell::new(None) }; /// Value texts of finished sketches' shown dimensions (Show Dimensions), as the model view /// drew them last frame: sketch, constraint id, parameter (None: driven), text box. static MODEL: RefCell> = const { RefCell::new(Vec::new()) }; @@ -644,9 +702,19 @@ pub fn drag_end() { DRAG.with(|g| *g.borrow_mut() = None); } +/// [`label`] for a dimension drawn as `frame`: an ellipse's minor half-axis is a length, as +/// it is measured to its axis end, so it has no R. +pub fn frame_label(frame: &DimFrame, k: &ConstraintKind, expr: Option<&str>, driven: bool, units: &str, decimals: u8) -> String { + label_marked(k, !matches!(frame, DimFrame::HalfAxis { .. }), expr, driven, units, decimals) +} + /// The text shown for a dimension: the value (R / Ø for radius and diameter, degrees for /// angles), "fx: value" when an expression drives it, in parentheses when driven. pub fn label(k: &ConstraintKind, expr: Option<&str>, driven: bool, units: &str, decimals: u8) -> String { + label_marked(k, true, expr, driven, units, decimals) +} + +fn label_marked(k: &ConstraintKind, radius_mark: bool, expr: Option<&str>, driven: bool, units: &str, decimals: u8) -> String { let v = k.value().unwrap_or(0.0); // Retain deliberately authored trailing zeros in a four-place inch literal too. let authored_four = units == "in" @@ -660,7 +728,7 @@ pub fn label(k: &ConstraintKind, expr: Option<&str>, driven: bool, units: &str, // A length says its unit, as the value inputs and the pointer's coordinates do (#1155). let num = if k.is_angle() { format!("{:.1}°", v.to_degrees()) } else { format!("{} {units}", crate::prefs::length_number(v, units, decimals)) }; let num = match k { - ConstraintKind::Radius { .. } => format!("R{num}"), + ConstraintKind::Radius { .. } if radius_mark => format!("R{num}"), ConstraintKind::Diameter { .. } | ConstraintKind::LinearDiameter { .. } => format!("Ø{num}"), _ => num, }; @@ -764,10 +832,13 @@ pub fn show(app: &mut SolveApp, ui: &egui::Ui, painter: &egui::Painter, proj: &P let sk = &source.sketch; let centres = if is_draft { draft_centres.as_ref().unwrap_or(¢res) } else { ¢res }; let to = |p: Vec2| proj.to_screen(source.plane.to_world(p)); - let Some(frame) = dim_frame(sk, &c.kind) else { continue }; + // A draft is drawn as it will be added: with the preference it was made with. + let half_axes = + if is_draft { draft.as_ref().map_or(app.preferences.ellipse_axes, |(_, d)| d.half_axes) } else { app.preferences.ellipse_axes }; + let Some(frame) = shown_frame(half_axes, sk, &c.kind) else { continue }; let anchor = match frame { DimFrame::Linear { p0, p1, .. } => (p0 + p1) * 0.5, - DimFrame::Radial { center, .. } | DimFrame::ArcLength { center, .. } => center, + DimFrame::Radial { center, .. } | DimFrame::ArcLength { center, .. } | DimFrame::HalfAxis { center, .. } => center, DimFrame::Angular { vertex, .. } => vertex, }; // Millimetres per pixel at the dimension. @@ -789,8 +860,11 @@ pub fn show(app: &mut SolveApp, ui: &egui::Ui, painter: &egui::Painter, proj: &P } else { tk.dimension }; - let galley = - painter.layout_no_wrap(label(&c.kind, expr, c.driven, &app.session.doc.units, app.preferences.length_decimals), font.clone(), col); + let galley = painter.layout_no_wrap( + frame_label(&frame, &c.kind, expr, c.driven, &app.session.doc.units, app.preferences.length_decimals), + font.clone(), + col, + ); let size = galley.size() + vec2(6.0, 2.0); let half = Vec2::new(f64::from(size.x) * 0.5 * px, f64::from(size.y) * 0.5 * px); // Unplaced linear dimensions sit outside the shape they measure. @@ -1138,6 +1212,7 @@ fn settle(app: &mut SolveApp, mut e: Edit, done: Option, escaped: bool) { /// The Dimension tool starts over (its picks became a dimension, or were cancelled). fn clear_picks(app: &mut SolveApp) { + AXIS.with(|axis| *axis.borrow_mut() = None); if let Some(tool) = app.tool.as_mut().filter(|t| t.kind == crate::tools::Kind::Dimension) { tool.picks.clear(); tool.point_picks.clear(); @@ -1450,6 +1525,176 @@ mod tests { cancel(); } + /// Placing an ellipse's half-axis: near the boundary between the major and the minor + /// half-axis the preview keeps the one it had, from either side, so it does not flip. + #[test] + fn an_ellipse_half_axis_preview_keeps_its_axis_near_the_boundary() { + cancel(); + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.ellipse", json!({"center":[0,0],"major":[20,0],"minor_radius":8})).unwrap(); + h.call("ui.view", json!({"view":"top"})); + h.step(&json!({"start":"sketch.dimension"})).unwrap(); + h.step(&json!({"click":{"sketch":[14.142,-5.657]}})).unwrap(); + h.frames(4); + h.step(&json!({"key":"Tab"})).unwrap(); + // Across the major axis, then on the boundary: the major half-axis; past its end, then + // on the boundary again: the minor one. + for (at, half) in [([3., 16.], 20.), ([10., 3.6], 20.), ([16., 4.], 8.), ([10., 4.4], 8.)] { + h.step(&json!({"move":{"sketch":at}})).unwrap(); + h.settle(); + let (param, draft) = placement_preview(&h.app).expect("an ellipse has a dimension preview"); + let sk = &draft.preview.sketch(draft.sketch).unwrap().sketch; + let c = sk.constraints.iter().find(|c| c.param.as_deref() == Some(¶m)).unwrap(); + assert!(matches!(c.kind, ConstraintKind::Distance {value,..} if (value-half).abs()<1e-6), "text at {at:?}: {:?}", c.kind); + } + h.step(&json!({"key":"Escape"})).unwrap(); + h.step(&json!({"key":"Escape"})).unwrap(); + cancel(); + } + + /// With the minor axis line deleted, D past the major end gives the minor half-axis, and + /// the view paints it as a length, without R. + #[test] + fn an_ellipse_s_minor_half_axis_without_its_axis_is_painted_without_r() { + cancel(); + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + let r = h.app.run("sketch.ellipse", json!({"center":[0,0],"major":[20,0],"minor_radius":8})).unwrap(); + let minor = r["created"]["curves"][2].as_str().unwrap().to_string(); + h.app.run("sketch.delete", json!({"entities":[minor]})).unwrap(); + h.app.run("sketch.dimension", json!({"entities":["e1"],"text_at":[30,3]})).unwrap(); + h.call("ui.view", json!({"view":"top"})); + h.frames(4); + let mut texts = Vec::new(); + for clipped in &h.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |shape| { + if let Shape::Text(t) = shape { + texts.push(t.galley.text().to_string()); + } + }); + } + assert!(texts.iter().any(|t| t == "8.00 mm"), "{texts:?}"); + assert!(!texts.iter().any(|t| t.starts_with("R8")), "{texts:?}"); + cancel(); + } + + /// With Draw ellipses with their axes off, D on an ellipse gives its minor radius wherever + /// the text is pulled, as before half-axes, drawn and labelled as a radius (R); on an + /// ellipse drawn with its axes too. + #[test] + fn an_ellipse_gives_its_minor_radius_with_the_axes_preference_off() { + cancel(); + let mut h = crate::scenario::Harness::new(); + h.app.preferences.ellipse_axes = false; + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.ellipse", json!({"center":[0,0],"major":[20,0],"minor_radius":8,"axes":true})).unwrap(); + h.call("ui.view", json!({"view":"top"})); + h.step(&json!({"start":"sketch.dimension"})).unwrap(); + h.step(&json!({"click":{"sketch":[14.142,-5.657]}})).unwrap(); + h.frames(4); + h.step(&json!({"key":"Tab"})).unwrap(); + // Across the major axis, where the half-axes give the major one. + for at in [[3., 16.], [30., 3.]] { + h.step(&json!({"move":{"sketch":at}})).unwrap(); + h.settle(); + let (param, draft) = placement_preview(&h.app).expect("an ellipse has a dimension preview"); + let sk = &draft.preview.sketch(draft.sketch).unwrap().sketch; + let c = sk.constraints.iter().find(|c| c.param.as_deref() == Some(¶m)).unwrap(); + assert!(matches!(c.kind, ConstraintKind::Radius { value, .. } if (value - 8.).abs() < 1e-6), "text at {at:?}: {:?}", c.kind); + } + h.step(&json!({"click":{"sketch":[30,3]}})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + h.settle(); + let sk = h.app.session.doc.sketch(h.app.session.active_sketch.unwrap()).unwrap(); + assert!(sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Radius { .. })), "{:?}", sk.constraints); + h.frames(4); + let mut texts = Vec::new(); + for clipped in &h.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |shape| { + if let Shape::Text(t) = shape { + texts.push(t.galley.text().to_string()); + } + }); + } + assert!(texts.iter().any(|t| t == "R8.00 mm"), "{texts:?}"); + cancel(); + } + + /// The preview's half-axis of an ellipse at a pointer position. + fn previewed_half_axis(h: &mut crate::scenario::Harness, at: [f64; 2]) -> f64 { + h.step(&json!({"move":{"sketch":at}})).unwrap(); + h.settle(); + let (id, draft) = placement_preview(&h.app).expect("an ellipse has a dimension preview"); + let sk = &draft.preview.sketch(draft.sketch).unwrap().sketch; + let c = sk.constraints.iter().find(|c| c.param.as_deref() == Some(&id) || c.id == id).unwrap(); + let ConstraintKind::Distance { value, .. } = c.kind else { panic!("text at {at:?}: {:?}", c.kind) }; + value + } + + /// An ellipse's half-axis placement starts from where its text is: neither the draft made + /// before the text was placed (the minor half-axis by default) nor the dimension placed + /// before it biases which half-axis it takes near the boundary. (That dimension is undone + /// first: while it holds the major half-axis, D gives the minor one wherever the text is.) + #[test] + fn an_ellipse_half_axis_placement_starts_from_where_its_text_is() { + cancel(); + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.ellipse", json!({"center":[0,0],"major":[20,0],"minor_radius":8})).unwrap(); + h.call("ui.view", json!({"view":"top"})); + h.step(&json!({"start":"sketch.dimension"})).unwrap(); + // Picked near the boundary on the major side, the text first where it was picked, then + // near the boundary again: the major. + h.step(&json!({"click":{"sketch":[13.383,-5.945]}})).unwrap(); + h.frames(4); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!((previewed_half_axis(&mut h, [10., 4.4]) - 20.).abs() < 1e-6); + h.step(&json!({"click":{"sketch":[10,4.4]}})).unwrap(); + assert!(editing()); + h.step(&json!({"text":"20"})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + h.settle(); + assert!(!editing()); + h.app.run("edit.undo", json!({})).unwrap(); + h.settle(); + // The next one on the same ellipse, picked near the boundary on the minor side, the + // text where it was picked: the minor. + h.step(&json!({"click":{"sketch":[14.863,-5.353]}})).unwrap(); + h.frames(4); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!((previewed_half_axis(&mut h, [14.863, -5.353]) - 8.).abs() < 1e-6); + h.step(&json!({"key":"Escape"})).unwrap(); + h.step(&json!({"key":"Escape"})).unwrap(); + cancel(); + } + + /// On an ellipse already sized, a half-axis is placed as a driven dimension at once on + /// the click: it is the half-axis the preview showed, near the boundary too. + #[test] + fn a_driven_ellipse_half_axis_is_the_one_its_preview_showed() { + cancel(); + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + let out = h.app.run("sketch.ellipse", json!({"center":[0,0],"major":[20,0],"minor_radius":8})).unwrap(); + let e = out["curves"][0].as_str().unwrap().to_string(); + for ty in ["major", "minor"] { + h.app.run("sketch.dimension", json!({"entities":[e],"type":ty})).unwrap(); + } + h.call("ui.view", json!({"view":"top"})); + h.step(&json!({"start":"sketch.dimension"})).unwrap(); + h.step(&json!({"click":{"sketch":[13.383,-5.945]}})).unwrap(); + assert!((previewed_half_axis(&mut h, [3., 16.]) - 20.).abs() < 1e-6); + assert!((previewed_half_axis(&mut h, [10., 3.6]) - 20.).abs() < 1e-6); + h.step(&json!({"click":{"sketch":[10,3.6]}})).unwrap(); + h.settle(); + let sk = h.app.session.doc.sketch(h.app.session.active_sketch.unwrap()).unwrap(); + let driven: Vec<_> = sk.constraints.iter().filter(|c| c.driven).map(|c| c.kind.clone()).collect(); + assert!(matches!(driven.as_slice(), [ConstraintKind::Distance { value, .. }] if (value - 20.).abs() < 1e-6), "{driven:?}"); + h.step(&json!({"key":"Escape"})).unwrap(); + cancel(); + } + /// Two dimensions whose texts were placed on the same spot: the later one steps to the /// next row instead of sitting on the first (#44). #[test] @@ -1513,6 +1758,11 @@ mod tests { let radius = ConstraintKind::Radius { c: 0, value: 1.2345 * 25.4 }; assert_eq!(label(&radius, Some("1.2345 in"), false, "in", 2), "R1.2345 in"); assert_eq!(label(&radius, Some("width / 2"), true, "in", 2), "(fx: R1.2345 in)"); + // An ellipse's minor half-axis is a length to its axis end: no R. + let half_axis = DimFrame::HalfAxis { center: Vec2::ZERO, dir: Vec2::Y, len: 8.0 }; + let minor = ConstraintKind::Radius { c: 0, value: 8.0 }; + assert_eq!(frame_label(&half_axis, &minor, None, false, "mm", 2), "8.00 mm"); + assert_eq!(frame_label(&half_axis, &minor, Some("width / 2"), true, "mm", 2), "(fx: 8.00 mm)"); let diameter = ConstraintKind::Diameter { c: 0, value: 0.001 * 25.4 }; assert_eq!(label(&diameter, None, false, "in", 2), "Ø0.001 in"); assert_eq!(crate::prefs::length_number(25.4 * (1.0 + 1e-12), "in", 2), "1.000"); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 2ae94ecf0..a97d1e824 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -1603,6 +1603,10 @@ preference_settings! { /// less than `sketch_tools::MIN_GLYPH_SPAN_PX` (#10518). Off: glyphs stay at a fixed screen /// size at every zoom, as before. hide_constraint_glyphs_zoomed_out: bool = true, PAGE_SKETCH; + /// The Ellipse tool draws the major and minor axes as construction lines with the ellipse, so + /// its half-axes and axes can be dimensioned. Off: the ellipse alone, and D on it gives its + /// minor radius, labelled R, as before. + ellipse_axes: bool = true, PAGE_SKETCH; /// Drive Joints shows the moved parts' old place as a ghost (its Show ghost box, #5905). drive_joints_ghost: bool = true, PAGE_TOOLS => check_tr("prefs.design_tools.ghost"); /// Plugin ids turned off (Preferences › Plugins). An installed plugin whose id is absent is on. @@ -6255,6 +6259,29 @@ mod tests { } } + /// The Ellipse tool draws its axes with "Draw ellipses with their axes" on (the default), + /// and the ellipse alone, as before, with it off. + #[test] + fn the_ellipse_tool_draws_its_axes_as_the_preference_says() { + for (on, curves) in [(None, 3), (Some(false), 1), (Some(true), 3)] { + let mut h = crate::scenario::Harness::new(); + if let Some(on) = on { + set(&mut h.app, &serde_json::json!({"ellipse_axes": on})).unwrap(); + } + assert_eq!(h.app.preferences.ellipse_axes, on.unwrap_or(true)); + h.app.run("sketch.create", serde_json::json!({"plane": "XY"})).unwrap(); + h.call("ui.view", serde_json::json!({"view": "top"})); + h.step(&serde_json::json!({"start": "sketch.ellipse"})).unwrap(); + for at in [[0.0, 0.0], [20.0, 0.0], [0.0, 8.0]] { + h.step(&serde_json::json!({"click": {"sketch": at}})).unwrap(); + } + h.settle(); + let sid = h.app.session.active_sketch.unwrap(); + let sk = h.app.session.model.state().sketch(sid).unwrap().sketch.clone(); + assert_eq!(sk.curves.len(), curves, "preference {on:?}: {:?}", sk.curves); + } + } + fn hole_preset_row(name: &str) -> serde_json::Value { serde_json::json!({ "name": name, "style": "counterbore", "extent": "distance", diff --git a/crates/ui-egui/src/prefs/sketch.rs b/crates/ui-egui/src/prefs/sketch.rs index d8e88e0f3..7f1c1c52b 100644 --- a/crates/ui-egui/src/prefs/sketch.rs +++ b/crates/ui-egui/src/prefs/sketch.rs @@ -90,6 +90,7 @@ fn drawing(app: &mut SolveApp, ui: &mut egui::Ui) { "prefs.line_hover_tangent_arc", "prefs.sketch.center_arc", "prefs.sketch_construction_lines", + "prefs.sketch.ellipse_axes", "prefs.sketch.auto_dimensions", "prefs.sketch.auto_locate", ]; @@ -127,6 +128,7 @@ fn drawing(app: &mut SolveApp, ui: &mut egui::Ui) { &mut app.preferences.center_arc_follows_cursor, ); check(ui, "sketch_construction_lines", "prefs.sketch_construction_lines", None, &mut app.preferences.sketch_construction_lines); + check(ui, "ellipse_axes", "prefs.sketch.ellipse_axes", Some("prefs.sketch.ellipse_axes_note"), &mut app.preferences.ellipse_axes); check( ui, "sketch_auto_dimensions", diff --git a/crates/ui-egui/src/sketch_corner_ui_tests.rs b/crates/ui-egui/src/sketch_corner_ui_tests.rs index 4e30d253e..40c105386 100644 --- a/crates/ui-egui/src/sketch_corner_ui_tests.rs +++ b/crates/ui-egui/src/sketch_corner_ui_tests.rs @@ -173,15 +173,17 @@ fn clicked_extend_endpoint_reaches_exact_ellipse_and_preserves_support() { h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); h.app.run("sketch.ellipse", json!({"center":[20,0],"major":[30,0],"minor_radius":5})).unwrap(); h.app.run("sketch.constraint.fix", json!({"entity":"e1"})).unwrap(); - h.app.run("sketch.line", json!({"points":[[0,3],[5,3]],"connect":false,"infer":false})).unwrap(); + // The ellipse's construction axes come first, so the line's id is read from the reply. + let line = + h.app.run("sketch.line", json!({"points":[[0,3],[5,3]],"connect":false,"infer":false})).unwrap()["curves"][0].as_str().unwrap().to_string(); h.frames(2); h.step(&json!({"start":"sketch.extend"})).unwrap(); h.step(&json!({"click":{"world":[5,3,0]}})).unwrap(); let st = h.app.session.world_state().unwrap(); let ss = st.sketch(h.app.session.active_sketch.unwrap()).unwrap(); - let end = ss.sketch.point(ss.sketch.resolve_point("l1.end").unwrap()).unwrap(); + let end = ss.sketch.point(ss.sketch.resolve_point(&format!("{line}.end")).unwrap()).unwrap(); assert!(end.dist(Vec2::new(12.0, 3.0)) < 1e-7, "clicked endpoint must extend: {end:?}, {:?}", h.app.status); - assert_eq!(ss.sketch.point(ss.sketch.resolve_point("l1.start").unwrap()), Some(Vec2::new(0.0, 3.0))); + assert_eq!(ss.sketch.point(ss.sketch.resolve_point(&format!("{line}.start")).unwrap()), Some(Vec2::new(0.0, 3.0))); } #[test] @@ -1030,3 +1032,25 @@ fn line_arc_fillet_preview_and_apply_work_in_both_pick_orders() { })); } } + +/// An ellipse's axis is never a side of a Fillet or Chamfer corner (the engine refuses it), so a +/// line drawn from the major end is no corner the picker offers. +#[test] +fn an_ellipse_axis_end_is_no_corner_to_pick() { + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + let e = h.app.run("sketch.ellipse", json!({"center":[0,0],"major":[20,0],"minor_radius":8})).unwrap()["curves"][0].as_str().unwrap().to_string(); + let major_end = { + let st = h.app.session.model.state(); + let sk = &st.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; + let CurveKind::Ellipse { m, .. } = sk.curves[sk.curve_index(&e).unwrap()].kind else { panic!("an ellipse") }; + sk.points[m].id.clone() + }; + h.app.run("sketch.line", json!({"points":[major_end, [40,10]],"connect":false,"infer":false})).unwrap(); + let st = h.app.session.model.state(); + let sk = &st.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; + let pi = sk.resolve_point(&major_end).unwrap(); + for arcs_ok in [true, false] { + assert_eq!(crate::sketch_tools::corner_curves(sk, pi, arcs_ok), None, "the axis and the line are no corner (arcs_ok {arcs_ok})"); + } +} diff --git a/crates/ui-egui/src/sketch_dims_tests.rs b/crates/ui-egui/src/sketch_dims_tests.rs index 4f5b7d18c..f1b338339 100644 --- a/crates/ui-egui/src/sketch_dims_tests.rs +++ b/crates/ui-egui/src/sketch_dims_tests.rs @@ -193,8 +193,11 @@ fn an_ellipse_takes_a_typed_major_and_minor_radius() { h.step(&json!({"key": "Enter"})).unwrap(); let state = h.app.session.world_state().unwrap(); let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; - assert_eq!(sk.curves.len(), 1, "{:?}", h.app.status); - let CurveKind::Ellipse { c, m, r } = sk.curves[0].kind.clone() else { panic!("{:?}", sk.curves[0].kind) }; + // The ellipse and its two axes (the default ellipse_axes preference). + assert_eq!(sk.curves.len(), 3, "{:?}", h.app.status); + let Some(CurveKind::Ellipse { c, m, r }) = sk.curves.iter().map(|k| k.kind.clone()).find(|k| matches!(k, CurveKind::Ellipse { .. })) else { + panic!("{:?}", sk.curves) + }; let (c, m) = (sk.point(c).unwrap(), sk.point(m).unwrap()); // From the centre (the origin) toward the cursor at (20, 10). let dir = solidcore_record::Vec2::new(20.0, 10.0).normalized().unwrap(); diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index 1c5d056df..4a1beece6 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -981,12 +981,17 @@ fn sketch_entity(app: &SolveApp, hits: &[Hit]) -> Option<(String, bool)> { } /// The two editable curves that meet at sketch point `pi`, in curve order, which is the order -/// the corner commands resolve them in from a `point` parameter. Construction curves are -/// ignored when more than two meet. Each side must be a line, or an arc for a fillet. +/// the corner commands resolve them in from a `point` parameter. An ellipse's axis is never a +/// side (the engine refuses it), and construction curves are ignored when more than two meet. +/// Each side must be a line, or an arc for a fillet. pub(crate) fn corner_curves(sk: &solidcraft_engine::sketch::Sketch, pi: usize, arcs_ok: bool) -> Option<(usize, usize)> { use solidcraft_engine::sketch::CurveKind; - let candidates = - sk.curves.iter().enumerate().filter(|(ci, c)| !sk.is_linked_curve(*ci) && c.kind.ends().is_some_and(|(a, b)| a == pi || b == pi)); + let candidates = sk + .curves + .iter() + .enumerate() + // The cheap end test first: the axis test scans the constraints. + .filter(|(ci, c)| c.kind.ends().is_some_and(|(a, b)| a == pi || b == pi) && !sk.is_linked_curve(*ci) && !sk.is_ellipse_axis(*ci)); let mut curves: Vec<_> = candidates.clone().take(3).collect(); // Center rectangles have construction diagonals at their corners. Match the engine's // corner selection: when more than two curves meet, use the profile sides. @@ -1397,7 +1402,7 @@ fn run_points(app: &mut SolveApp, t: &Tool) -> bool { let params = match (t.cmd, p.as_slice()) { ("sketch.line.midpoint", [m, e]) => json!({"mid": arg(m), "end": xy(e.0)}), ("sketch.arc.tangent", [s, e]) => json!({"start": arg(s), "end": xy(e.0)}), - ("sketch.ellipse", [c, m, q]) => json!({"center": xy(c.0), "major": xy(m.0), "minor": xy(q.0)}), + ("sketch.ellipse", [c, m, q]) => json!({"center": xy(c.0), "major": xy(m.0), "minor": xy(q.0), "axes": app.preferences.ellipse_axes}), ("sketch.conic", [a, b, x]) => { // The typed Rho box, or the parabola the command defaults to. let rho = crate::sketch_dims::locked_value(app, t, "Rho").unwrap_or(0.5); diff --git a/crates/ui-egui/src/sketch_transform_ui.rs b/crates/ui-egui/src/sketch_transform_ui.rs index acadf7a48..ac4e3d582 100644 --- a/crates/ui-egui/src/sketch_transform_ui.rs +++ b/crates/ui-egui/src/sketch_transform_ui.rs @@ -80,9 +80,18 @@ fn picked_box(app: &SolveApp, d: &crate::dialogs::Dialog) -> Option<(Vec> = Vec::new(); let mut points: Vec = Vec::new(); + let mut drawn: Vec = Vec::new(); for id in crate::sketch_modify_ui::entity_ids(&app.session, &d.inputs, 0) { if let Some(i) = sk.curve_index(&id) { - lines.push(sk.polyline(i)); + // An ellipse's axes go with it when OK applies (`sketch.transform`), so they are + // drawn with it. + let (major, minor) = sk.ellipse_axis_lines(i).unwrap_or((None, None)); + for c in std::iter::once(i).chain(major.map(|(l, _)| l)).chain(minor.map(|(l, ..)| l)) { + if !drawn.contains(&c) { + drawn.push(c); + lines.push(sk.polyline(c)); + } + } } else if let Some(p) = sk.resolve_point(&id).and_then(|i| sk.point(i)) { points.push(p); } @@ -270,4 +279,38 @@ mod tests { assert_eq!(plain(1.23456), "1.235"); assert_eq!(plain(-0.0001), "0"); } + + /// An ellipse picked alone is drawn where OK would leave it with its axes, as OK moves, + /// turns and scales them with it. + #[test] + fn an_ellipse_picked_alone_is_previewed_with_its_axes() { + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", serde_json::json!({"plane": "XY"})).unwrap(); + h.app.run("sketch.ellipse", serde_json::json!({"center": [0, 0], "major": [20, 0], "minor_radius": 8})).unwrap(); + h.call("ui.view", serde_json::json!({"view": "top"})); + h.settle(); + h.step(&serde_json::json!({"click": {"sketch": [10.0, 6.928]}})).unwrap(); + h.step(&serde_json::json!({"start": "sketch.transform"})).unwrap(); + h.frames(3); + let d = h.app.dialog.as_ref().expect("the Transform window"); + let (lines, middle, size) = picked_box(&h.app, d).expect("a box round the ellipse"); + assert_eq!(lines.len(), 3, "the ellipse and its two axes"); + assert!( + middle[0].abs() < 1e-6 && middle[1].abs() < 1e-6 && (size[0] - 40.0).abs() < 1e-3 && (size[1] - 16.0).abs() < 1e-3, + "{middle:?} {size:?}" + ); + // With its minor axis deleted, the major one that is left. + h.step(&serde_json::json!({"key": "Escape"})).unwrap(); + let sk = h.app.session.doc.sketch(h.app.session.active_sketch.unwrap()).unwrap(); + let minor = sk.curves.iter().rev().find(|c| c.construction).unwrap().id.clone(); + h.app.run("sketch.delete", serde_json::json!({"entities": [minor]})).unwrap(); + h.settle(); + h.step(&serde_json::json!({"click": {"sketch": [10.0, 6.928]}})).unwrap(); + h.step(&serde_json::json!({"start": "sketch.transform"})).unwrap(); + h.frames(3); + let d = h.app.dialog.as_ref().expect("the Transform window"); + let (lines, _, size) = picked_box(&h.app, d).expect("a box round the ellipse"); + assert_eq!(lines.len(), 2, "the ellipse and its major axis"); + assert!((size[0] - 40.0).abs() < 1e-3, "{size:?}"); + } } diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md index a9cec30da..3ec998333 100644 --- a/docs/book/src/guide/sketching.md +++ b/docs/book/src/guide/sketching.md @@ -343,7 +343,16 @@ The solver is SolidCraft's own (damped Gauss–Newton with degree-of-freedom ana coincident, horizontal/vertical, parallel, perpendicular, tangent, equal, concentric, collinear, midpoint, symmetry, fix, curvature (G2) and polygon. **Sketch Dimension** (D) adds linear, aligned, horizontal, vertical, point-to-line, line-to-circle, point-to-circle, circle-to-circle, -radius, diameter, arc length and angle dimensions. For an arc's length, click the arc and then one of its end points. Each is a parameter +radius, diameter, arc length and angle dimensions. For an arc's length, click the arc and then one of its end points. +An ellipse is drawn with its major and minor axes as construction lines through its centre +(Preferences › Sketch › Draw ellipses with their axes; turned off, the ellipse is drawn alone, +and D on an ellipse gives its minor radius wherever the value is pulled, as before). +As with a Center Rectangle's diagonals, trim, extend and break stop at them, and they stay when the +ellipse is deleted. +Click the ellipse and pull the value across its major axis for the major half-axis, or out past an +end of the major axis for the minor half-axis, also on an ellipse whose axis lines were deleted; +once one half-axis has a dimension, the next click on the ellipse gives the other; +click an axis line for the whole axis. Each is a parameter (`d1`, `d2`, …), so it can hold an expression. **Concentric** accepts two circles or arcs, or a circle or arc and a sketch point (including the diff --git a/docs/design/preferences/pages/sketch.md b/docs/design/preferences/pages/sketch.md index cab8f1ff3..73b7bde38 100644 --- a/docs/design/preferences/pages/sketch.md +++ b/docs/design/preferences/pages/sketch.md @@ -25,6 +25,7 @@ Two columns of checkboxes. | Rest on a line's last point to switch to a tangent arc | Checkbox | `Prefs.line_hover_tangent_arc` | `false` | Existing `prefs.line_hover_tangent_arc_note`: leaving, returning to and resting on the last point toggles line / tangent arc. | none | Retained newer control; immediately after press-and-drag, before centre-point arc. | | Centre-point arc follows the cursor | Checkbox | `Prefs.center_arc_follows_cursor` | `true` | none | none | | | Extended construction line tools | Checkbox | `Prefs.sketch_construction_lines` | `true` | none | none | | +| Draw ellipses with their axes | Checkbox | `Prefs.ellipse_axes` | `true` | "The major and minor axes as construction lines, so the half-axes and axes can be dimensioned. Off: the ellipse alone, and D on it gives its minor radius wherever the value is pulled, drawn and labelled R as before." | none | New in #9292; not in `PROFILE_KEYS` (that list is the frozen pre-split baseline). | | Dimension new shapes fully | Checkbox | `Prefs.sketch_auto_dimensions` | `false` | "Typed values plus every dimension that fixes the shape." | none | | | Place from the sketch origin | Checkbox (dimmed on the board while the one above is off) | `Prefs.sketch_auto_locate` | `false` | "With full dimensions." | none | Dimmed unless "Dimension new shapes fully" is on. | | Shortcut again switches mode | Checkbox | `Prefs.shortcut_cycles_modes` | `false` | "Off: it starts the tool again." | none | |