SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Sketch: hovering over a large sketch no longer slows down (#9614)
kaltenbrunnermarkusaee947f0f970
diff --git a/crates/doc/src/profile_refs.rs b/crates/doc/src/profile_refs.rsindex ccd4335b01..461703c1da 100644--- a/crates/doc/src/profile_refs.rs+++ b/crates/doc/src/profile_refs.rs@@ -278,7 +278,7 @@ fn selection_indices(ss: &SolvedSketch, selection: &ProfileSel, mut notes: Optio.profiles.iter().enumerate()- .filter(|(_, profile)| profile.region.contains(*point))+ .filter(|(_, profile)| profile.contains(*point)).min_by(|(_, a), (_, b)| a.area.total_cmp(&b.area)).ok_or_else(|| DocError::Unknown(format!("profile at {:?} in {}", [point.x, point.y], ss.name)))?;indices.push(index);diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rsindex f4cb2e3841..b5085c01cb 100644--- a/crates/engine/src/cmd/mod.rs+++ b/crates/engine/src/cmd/mod.rs@@ -57,7 +57,7 @@ pub use sketch_construction::{};pub use sketch_create::{tangent_arc_preview, tangent_arc_starts_at};pub use sketch_import::drawing_import_command;-pub use sketch_modify::{extend_arc_preview, extend_preview, trim_piece};+pub use sketch_modify::{TrimHover, extend_arc_preview, extend_end_at, extend_preview, trim_hover, trim_piece};pub use view_dxf::sketch::exportable as view_dxf_exportable;pub(crate) use view_navigation::camera_form;pub use view_navigation::standard_view;diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rsindex b0c459b093..d11f630041 100644--- a/crates/engine/src/cmd/sketch_modify.rs+++ b/crates/engine/src/cmd/sketch_modify.rs@@ -375,9 +375,18 @@ fn rebind_endpoint_tangencies(sk: &mut Sketch, ci: usize, pieces: &[usize], tang}}-/// The cut parameters bracketing `tq` on curve `ci`: (before, after) with their cutter curves.-fn bracket(sk: &Sketch, ci: usize, tq: f64) -> (Vec<(f64, Vec2, usize)>, bool) {- let Some(sh) = sk.shape(ci) else { return (Vec::new(), false) };+/// The cuts on a curve a trim chooses between, made once for any number of trim points+/// ([`TrimCuts::around`]): crossings and touching ends, in order along the curve, the curve's own+/// ends left out.+#[derive(Clone, Debug, Default)]+struct TrimCuts {+ cuts: Vec<(f64, Vec2, usize)>,+ /// A whole circle: the cuts wrap round.+ full: bool,+}++fn trim_cuts(sk: &Sketch, ci: usize) -> TrimCuts {+ let Some(sh) = sk.shape(ci) else { return TrimCuts::default() };let (t0, t1) = sh.range();let full = sh.is_full();let span = t1 - t0;@@ -390,51 +399,90 @@ fn bracket(sk: &Sketch, ci: usize, tq: f64) -> (Vec<(f64, Vec2, usize)>, bool) {.filter(|(t, _, _)| full || (*t > t0 + 1e-9 * span && *t < t1 - 1e-9 * span && ends.iter().all(|e| e.dist(sh.point(*t)) >= TOL * 10.0))).collect();cuts.sort_by(|a, b| a.0.total_cmp(&b.0));- if full {- if cuts.len() < 2 {- return (Vec::new(), true);+ TrimCuts { cuts, full }+}++impl TrimCuts {+ /// The cuts bracketing parameter `tq`: (before, after) with their cutter curves, and whether+ /// the curve is a whole circle.+ fn around(&self, tq: f64) -> (Vec<(f64, Vec2, usize)>, bool) {+ let cuts = &self.cuts;+ if self.full {+ if cuts.len() < 2 {+ return (Vec::new(), true);+ }+ // Cuts around tq on the circle (wrapping).+ let after = cuts.iter().position(|c| c.0 > tq).unwrap_or(0);+ let before = (after + cuts.len() - 1) % cuts.len();+ let mut two = vec![cuts[before], cuts[after]];+ two.sort_by(|a, b| a.0.total_cmp(&b.0));+ return (two, true);}- // Cuts around tq on the circle (wrapping).- let after = cuts.iter().position(|c| c.0 > tq).unwrap_or(0);- let before = (after + cuts.len() - 1) % cuts.len();- let mut two = vec![cuts[before], cuts[after]];- two.sort_by(|a, b| a.0.total_cmp(&b.0));- return (two, true);+ let before = cuts.iter().rev().find(|c| c.0 < tq).copied();+ let after = cuts.iter().find(|c| c.0 > tq).copied();+ (before.into_iter().chain(after).collect(), false)}- let before = cuts.iter().rev().find(|c| c.0 < tq).copied();- let after = cuts.iter().find(|c| c.0 > tq).copied();- (before.into_iter().chain(after).collect(), false)}-/// The piece of `curve` a trim at `at` takes away, as points along it, for the Trim tool to show-/// under the cursor (#3052): the part between the crossings either side of `at`, as `sketch.trim`-/// cuts it, or the whole curve where nothing crosses it. `None` where trim works otherwise (a-/// free-form or infinite curve) or the curve isn't in the sketch: the tool shows the curve.-pub fn trim_piece(sk: &Sketch, curve: &str, at: Vec2) -> Option<Vec<Vec2>> {+/// The cut parameters bracketing `tq` on curve `ci`: (before, after) with their cutter curves.+fn bracket(sk: &Sketch, ci: usize, tq: f64) -> (Vec<(f64, Vec2, usize)>, bool) {+ trim_cuts(sk, ci).around(tq)+}++/// What the Trim tool's hover needs of one curve, made once per sketch state: the curve and the+/// cuts on it. Finding the cuts intersects the curve with every other one (free-form ones by+/// their polylines), while the piece under the cursor ([`TrimHover::piece`]) only looks the+/// cursor up among them, so the hover keeps this while the sketch is unchanged and asks it on+/// each mouse move.+#[derive(Clone, Debug)]+pub struct TrimHover {+ sh: Shape,+ cuts: TrimCuts,+}++/// The [`TrimHover`] of `curve`. `None` where trim works otherwise (a free-form or infinite+/// curve) or the curve isn't in the sketch: the tool shows the curve.+pub fn trim_hover(sk: &Sketch, curve: &str) -> Option<TrimHover> {let ci = sk.curve_index(curve)?;let c = sk.curves.get(ci)?;if c.infinite || c.kind.is_freeform() {return None;}let sh = sk.shape(ci)?;- let tq = sh.param(sh.project(at));- let (t0, t1) = sh.range();- let (cuts, full) = bracket(sk, ci, tq);- let (a, b) = match (cuts.as_slice(), full) {- ([], _) => (t0, t1),- // A whole circle: the arc between the two crossings round `at`.- ([x, y], true) => {- if tq > x.0 && tq < y.0 {- (x.0, y.0)- } else {- (y.0, x.0 + TAU)+ Some(TrimHover { sh, cuts: trim_cuts(sk, ci) })+}++impl TrimHover {+ /// The piece a trim at `at` takes away, as [`trim_piece`] answers it.+ pub fn piece(&self, at: Vec2) -> Option<Vec<Vec2>> {+ let sh = &self.sh;+ let tq = sh.param(sh.project(at));+ let (t0, t1) = sh.range();+ let (cuts, full) = self.cuts.around(tq);+ let (a, b) = match (cuts.as_slice(), full) {+ ([], _) => (t0, t1),+ // A whole circle: the arc between the two crossings round `at`.+ ([x, y], true) => {+ if tq > x.0 && tq < y.0 {+ (x.0, y.0)+ } else {+ (y.0, x.0 + TAU)+ }}- }- (_, true) => return None,- (cuts, false) => (cuts.iter().rev().find(|c| c.0 < tq).map_or(t0, |c| c.0), cuts.iter().find(|c| c.0 > tq).map_or(t1, |c| c.0)),- };- let n = if matches!(sh, Shape::Line { .. }) { 1 } else { 64 };- Some((0..=n).map(|i| sh.point(a + (b - a) * f64::from(i) / f64::from(n))).collect())+ (_, true) => return None,+ (cuts, false) => (cuts.iter().rev().find(|c| c.0 < tq).map_or(t0, |c| c.0), cuts.iter().find(|c| c.0 > tq).map_or(t1, |c| c.0)),+ };+ let n = if matches!(sh, Shape::Line { .. }) { 1 } else { 64 };+ Some((0..=n).map(|i| sh.point(a + (b - a) * f64::from(i) / f64::from(n))).collect())+ }+}++/// The piece of `curve` a trim at `at` takes away, as points along it, for the Trim tool to show+/// under the cursor (#3052): the part between the crossings either side of `at`, as `sketch.trim`+/// cuts it, or the whole curve where nothing crosses it. `None` where trim works otherwise (a+/// free-form or infinite curve) or the curve isn't in the sketch: the tool shows the curve.+pub fn trim_piece(sk: &Sketch, curve: &str, at: Vec2) -> Option<Vec<Vec2>> {+ trim_hover(sk, curve)?.piece(at)}/// Trim and extend refuse an offset's output: its ends are recomputed from its source curves on@@ -1044,6 +1092,16 @@ pub fn extend_preview(sk: &solidcraft_sketch::Sketch, ci: usize, hover_pos: Vec2line_aim(sk, ci, hover_pos).ok().flatten().map(|aim| aim.hit)}+/// Which end of line or arc `ci` an Extend at `at` grows, as `sketch.extend` and its previews+/// choose it: `Some(true)` for its `b` end. Unless the sketch has an infinite line (which is cut+/// short about the cursor), [`extend_preview`] and [`extend_arc_preview`] depend on `at` only+/// through this choice, so a hover may keep a preview while the cursor stays nearer that end.+pub fn extend_end_at(sk: &Sketch, ci: usize, at: Vec2) -> Option<bool> {+ let (CurveKind::Line { a, b } | CurveKind::Arc { a, b, .. }) = sk.curves.get(ci)?.kind else { return None };+ let (qa, qb) = (sk.point(a)?, sk.point(b)?);+ Some(at.dist(qb) <= at.dist(qa))+}+/// One end of an arc growing along the arc's own circle, as a new arc, and what stops it.////// Arcs extend both ways: past their `b` end counter-clockwise and past their `a` end clockwise,diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rsindex 6cd1030e42..f3030ebf68 100644--- a/crates/engine/src/cmd/sketch_modify_tests.rs+++ b/crates/engine/src/cmd/sketch_modify_tests.rs@@ -4056,6 +4056,67 @@ fn trim_piece_is_what_a_trim_there_takes_away() {assert!(near(piece[0], [0.0, 0.0]) && near(piece[piece.len() - 1], [8.0, 0.0]), "{piece:?}");}+/// The hover keeps one [`super::TrimHover`] per curve while the sketch is unchanged and asks it+/// for each cursor position: it answers what working the piece out afresh there answers, and the+/// trim there takes that piece away. Lines, circles and arcs cut by each other and by a spline.+/// Extend's previews depend on the cursor only through the end it grows+/// ([`super::extend_end_at`]), which lets the hover keep them while that end stays the nearer.+#[test]+fn trim_hover_made_once_and_extend_previews_per_end_answer_as_afresh() {+ let mut s = new_sketch();+ for y in [0.0, 6.0, 13.0] {+ run(&mut s, "sketch.line", json!({"points": [[-20, y], [40, y]], "connect": false}));+ }+ for x in [-8.0, 9.0, 27.0] {+ run(&mut s, "sketch.circle.center", json!({"center": [x, 4], "radius": 5}));+ }+ run(&mut s, "sketch.arc.three_point", json!({"start": [-15, -6], "end": [35, -6], "through": [10, 18]}));+ run(&mut s, "sketch.spline.fit_point", json!({"points": [[-12, -9], [0, 20], [14, -8], [30, 19]]}));+ run(&mut s, "sketch.line", json!({"points": [[3, 3], [5, 4]], "connect": false}));+ let sk = sketch(&s);+ let (mut trimmed, mut extended) = (0, 0);+ for (ci, c) in sk.curves.iter().enumerate() {+ let Some(hover) = super::trim_hover(&sk, &c.id) else {+ assert!(c.kind.is_freeform(), "{}", c.id);+ continue;+ };+ let poly = sk.polyline(ci);+ for k in 1..12 {+ let at = poly[(poly.len() - 1) * k / 12] + Vec2::new(0.01, -0.02);+ let piece = hover.piece(at);+ assert_eq!(piece, super::trim_piece(&sk, &c.id, at), "{} at {at:?}", c.id);+ let Some(piece) = piece else { continue };+ if k % 4 == 1 {+ let mut after = sk.clone();+ super::remove_piece(&mut after, ci, at, "sketch.trim").unwrap();+ let mid = if piece.len() > 2 { piece[piece.len() / 2] } else { (piece[0] + piece[1]) * 0.5 };+ assert!(!(0..after.curves.len()).filter_map(|i| after.shape(i)).any(|sh| sh.dist(mid) < 1e-6), "{} at {at:?}", c.id);+ trimmed += 1;+ }+ }+ if !matches!(c.kind, CurveKind::Line { .. } | CurveKind::Arc { .. }) {+ continue;+ }+ let (CurveKind::Line { a, b } | CurveKind::Arc { a, b, .. }) = c.kind else { continue };+ let (qa, qb) = (sk.point(a).unwrap(), sk.point(b).unwrap());+ for k in 0..=10 {+ let at = qa.lerp(qb, f64::from(k) / 10.0) + Vec2::new(0.3, 0.2);+ let at_b = super::extend_end_at(&sk, ci, at).unwrap();+ let end = if at_b { qb } else { qa };+ let preview = |p: Vec2| {+ if matches!(c.kind, CurveKind::Arc { .. }) {+ super::extend_arc_preview(&sk, ci, p)+ } else {+ super::extend_preview(&sk, ci, p).map(|q| vec![q])+ }+ };+ assert_eq!(preview(at), preview(end), "{} at {at:?}", c.id);+ extended += usize::from(preview(at).is_some());+ }+ }+ assert!(trimmed >= 15 && extended >= 40, "{trimmed} trims, {extended} extensions");+}+/// An offset's ends follow its source curves, so trimming a piece off it or extending it is/// refused (the trim used to report success and leave the curve whole). Trimming away a whole/// offset curve still works, and once the association is broken the trim cuts it.diff --git a/crates/sketch/src/profiles.rs b/crates/sketch/src/profiles.rsindex 419c143a8d..1a36c66332 100644--- a/crates/sketch/src/profiles.rs+++ b/crates/sketch/src/profiles.rs@@ -9,11 +9,11 @@use solidcraft_geom::prelude::*;use std::f64::consts::TAU;-use std::sync::Arc;+use std::sync::{Arc, OnceLock};use serde::{Deserialize, Serialize};-use solidcore_record::{Loop2, Region2, Seg2, Vec2};-use solidcraft_geom::Ring;+use solidcore_record::{Loop2, MAX_BEZIER_DEGREE, Region2, Seg2, Vec2};+use solidcraft_geom::{Aabb2, Ring};use crate::model::{CurveKind, Sketch};use crate::shape::{Shape, intersections_within};@@ -38,6 +38,12 @@ pub struct Profile {complete_outer: Option<Vec<String>>,#[serde(skip)]complete_holes: Option<Vec<Vec<String>>>,+ // [`Profile::contains`]'s outer box and sampled loops, made on first use from `region` (a+ // profile is made once and not edited): hovering asks every profile on each mouse move.+ #[serde(skip)]+ hull: OnceLock<Option<Aabb2>>,+ #[serde(skip)]+ outline: OnceLock<RegionOutline>,}impl Profile {@@ -47,6 +53,16 @@ impl Profile {Some((self.complete_outer.clone()?, self.complete_holes.clone()?))}+ /// Whether `p` is in the profile: what `region.contains(p)` answers, from the loops sampled+ /// once. A point clearly outside the outer loop's box ([`hull_box`]) is answered without+ /// sampling anything, so the profiles away from the cursor cost a box test.+ pub fn contains(&self, p: Vec2) -> bool {+ if self.hull.get_or_init(|| hull_box(&self.region.outer)).is_some_and(|b| clearly_excludes(&b, p)) {+ return false;+ }+ self.outline.get_or_init(|| RegionOutline::new(&self.region)).contains(p)+ }+/// All curve ids bounding the profile.pub fn curve_ids(&self) -> Vec<String> {let mut v = self.outer_curves.clone();@@ -1648,7 +1664,17 @@ fn assemble(sk: &Sketch, islands: &[Arc<Island>]) -> Vec<Profile> {if let Some(holes) = &mut complete_holes {holes.sort();}- Profile { region, outer_curves: (*ids).clone(), hole_curves, area, centroid, complete_outer: (*complete_outer).clone(), complete_holes }+ Profile {+ region,+ outer_curves: (*ids).clone(),+ hole_curves,+ area,+ centroid,+ complete_outer: (*complete_outer).clone(),+ complete_holes,+ hull: OnceLock::new(),+ outline: OnceLock::new(),+ }}).collect();let index: std::collections::HashMap<&str, usize> = sk.curves.iter().enumerate().map(|(i, c)| (c.id.as_str(), i)).collect();@@ -1706,9 +1732,101 @@ pub fn profile_by_curves(profiles: &[Profile], ids: &[String]) -> Result<usize,}}+/// The chord error of the polylines `Region2Geom::contains` (in geom) tests a point against:+/// [`RegionOutline`] samples at the same, so it answers as the region does.+const CONTAINS_TOL: f64 = 1e-3;++/// Whether `p` lies clearly outside `b`: past every side by a margin that covers rounding, so no+/// closed polyline with its corners in the box contains `p` by the even-odd rule+/// ([`Ring::contains`]). False when unsure (an empty box, values too large for the margin); true+/// for a point that is not a number, which no polyline contains either.+fn clearly_excludes(b: &Aabb2, p: Vec2) -> bool {+ let big = b.min.x.abs().max(b.min.y.abs()).max(b.max.x.abs()).max(b.max.y.abs());+ if b.is_empty() || !(big < 1e150) {+ return false;+ }+ let m = 1e-9 * (1.0 + big);+ !(p.x >= b.min.x - m && p.x <= b.max.x + m && p.y >= b.min.y - m && p.y <= b.max.y + m)+}++/// A box holding the whole loop and every polyline of it (`Loop2Geom::polyline`), from its end+/// and control points (an arc's whole circle), without sampling: each curve kind stays inside its+/// control points. `None` when that is not sure: a conic with a negative weight leaves its+/// control triangle, or a value is not finite.+fn hull_box(l: &Loop2) -> Option<Aabb2> {+ let mut out = Aabb2::EMPTY;+ let mut put = |p: Vec2| {+ out.add(p);+ p.is_finite().then_some(())+ };+ for s in &l.segs {+ match s {+ Seg2::Line { a, b } => {+ put(*a)?;+ put(*b)?;+ }+ Seg2::Arc { center, radius, .. } => {+ let r = Vec2::new(radius.abs(), radius.abs());+ put(*center - r)?;+ put(*center + r)?;+ }+ Seg2::Cubic { p0, p1, p2, p3 } => {+ for q in [p0, p1, p2, p3] {+ put(*q)?;+ }+ }+ Seg2::Conic { a, apex, b, w } => {+ if !(w.is_finite() && *w >= 0.0) {+ return None;+ }+ for q in [a, apex, b] {+ put(*q)?;+ }+ }+ Seg2::Bezier { n, p } => {+ for q in &p[..usize::from(*n).clamp(1, MAX_BEZIER_DEGREE) + 1] {+ put(*q)?;+ }+ }+ }+ }+ (!out.is_empty()).then_some(out)+}++/// A region's loops as the polylines `Region2Geom::contains` tests a point against, each with its+/// box. Hovering a sketch asks every profile under the cursor on each mouse move; sampled once,+/// the curves are not sampled again, and a loop whose box is clearly away from the point is+/// passed over by the box alone. The answers are those of `contains` on the region it was made+/// from.+#[derive(Clone, Debug, Default)]+struct RegionOutline {+ /// The outer loop, then the holes; a box only when every corner is finite.+ loops: Vec<(Ring<Vec2>, Option<Aabb2>)>,+}++impl RegionOutline {+ fn new(r: &Region2) -> Self {+ let loops = r+ .loops()+ .map(|l| {+ let ring = l.polyline(CONTAINS_TOL);+ let finite = ring.iter().all(|p| p.is_finite());+ let bounds = if finite { Some(ring.bounds()) } else { None };+ (ring, bounds)+ })+ .collect();+ RegionOutline { loops }+ }++ fn contains(&self, p: Vec2) -> bool {+ let mut inside = self.loops.iter().map(|(ring, bounds)| !bounds.is_some_and(|b| clearly_excludes(&b, p)) && ring.contains(p));+ inside.next().unwrap_or(false) && !inside.any(|hole| hole)+ }+}+/// The innermost profile containing a sketch point, by index into `profiles`.pub fn profile_at_point(profiles: &[Profile], p: Vec2) -> Option<usize> {- profiles.iter().enumerate().filter(|(_, q)| q.region.contains(p)).min_by(|a, b| a.1.area.total_cmp(&b.1.area)).map(|(i, _)| i)+ profiles.iter().enumerate().filter(|(_, q)| q.contains(p)).min_by(|a, b| a.1.area.total_cmp(&b.1.area)).map(|(i, _)| i)}/// The distinct curve ids of a loop, in loop order (a curve cut into pieces is listed once).@@ -2120,4 +2238,122 @@ mod tests {assert_eq!(before.iter().zip(&after).filter(|(a, b)| a != b).count(), 1);assert_same(&find_profiles(&sk), &search(&sk, MAX_EDGES, false, false).profiles);}++ /// The profile under a point, from each profile's box and loops sampled once, is the one+ /// testing every region afresh found (the code before), over a sketch of text, circles in a+ /// plate, lines through them and arcs; asked twice, so the second answers from the samples.+ #[test]+ fn profile_at_point_from_the_sampled_loops_matches_the_regions() {+ let mut sk = Sketch::new();+ rectangle(&mut sk, -5.0, -5.0, 105.0, 85.0);+ text_into(&mut sk, "B8", Vec2::new(10.0, 62.0), 12.0);+ for i in 0..8 {+ for j in 0..5 {+ sk.add_circle(Vec2::new(8.0 + 12.0 * f64::from(i), 6.0 + 11.0 * f64::from(j)), 4.0, None, None).unwrap();+ }+ }+ for j in 0..3 {+ let y = 6.0 + 22.0 * f64::from(j);+ sk.add_line(Vec2::new(-5.0, y), Vec2::new(105.0, y), None, None, None).unwrap();+ }+ sk.add_arc(Vec2::new(80.0, 70.0), Vec2::new(90.0, 70.0), Vec2::new(70.0, 70.0), [None; 3], None).unwrap();+ sk.add_line(Vec2::new(70.0, 70.0), Vec2::new(90.0, 70.0), None, None, None).unwrap();+ let profiles = find_profiles(&sk);+ assert!(profiles.len() > 60, "{}", profiles.len());+ let old =+ |p: Vec2| profiles.iter().enumerate().filter(|(_, q)| q.region.contains(p)).min_by(|a, b| a.1.area.total_cmp(&b.1.area)).map(|(i, _)| i);+ let mut found = 0;+ for round in 0..2 {+ for j in 0..=91 {+ for i in 0..=127 {+ let p = Vec2::new(-10.0 + 120.0 * f64::from(i) / 127.0, -10.0 + 100.0 * f64::from(j) / 91.0);+ let want = old(p);+ assert_eq!(profile_at_point(&profiles, p), want, "round {round} at {p:?}");+ for q in &profiles {+ assert_eq!(q.contains(p), q.region.contains(p));+ }+ found += usize::from(want.is_some());+ }+ }+ }+ assert!(found > 15_000, "{found}");+ }++ /// The box test before sampling, and the outline sampled once, answer exactly what testing+ /// every loop's polyline answers (`Region2Geom::contains`), on regions of every segment kind:+ /// a grid over and around each, points a hair outside its box and its own polyline corners.+ #[test]+ fn outline_and_hull_box_answer_as_the_polylines() {+ let square = |x: f64, y: f64, size: f64| {+ Loop2::polygon(&[Vec2::new(x, y), Vec2::new(x + size, y), Vec2::new(x + size, y + size), Vec2::new(x, y + size)])+ };+ let solid = |l: Loop2| Region2 { outer: l, holes: Vec::new() };+ let old = |r: &Region2, p: Vec2| r.outer.polyline(CONTAINS_TOL).contains(p) && !r.holes.iter().any(|h| h.polyline(CONTAINS_TOL).contains(p));+ let (a, b, c, d) = (Vec2::new(0.0, 0.0), Vec2::new(30.0, 0.0), Vec2::new(30.0, 20.0), Vec2::new(0.0, 20.0));+ let curvy = Loop2 {+ segs: vec![+ Seg2::Cubic { p0: a, p1: Vec2::new(10.0, -8.0), p2: Vec2::new(20.0, 8.0), p3: b },+ Seg2::Conic { a: b, apex: Vec2::new(40.0, 10.0), b: c, w: 0.7 },+ Seg2::Bezier {+ n: 4,+ p: [+ c,+ Vec2::new(22.0, 30.0),+ Vec2::new(15.0, 12.0),+ Vec2::new(8.0, 30.0),+ d,+ Vec2::ZERO,+ Vec2::ZERO,+ Vec2::ZERO,+ Vec2::ZERO,+ Vec2::ZERO,+ ],+ },+ Seg2::Arc { center: Vec2::new(0.0, 10.0), radius: 10.0, start: std::f64::consts::FRAC_PI_2, sweep: std::f64::consts::PI },+ ],+ };+ let mut holes: Vec<Loop2> = (0..5).map(|k| Loop2::circle(Vec2::new(4.0 + 5.0 * f64::from(k), 8.0), 1.5).reversed()).collect();+ holes.push(square(10.0, 13.0, 4.0).reversed());+ let regions = [+ Region2 { outer: curvy.clone(), holes },+ Region2 { outer: Loop2::circle(Vec2::new(-3.0, 2.0), 7.5), holes: vec![Loop2::circle(Vec2::new(-3.0, 2.0), 3.0).reversed()] },+ solid(Loop2 { segs: vec![Seg2::Conic { a, apex: Vec2::new(5.0, 9.0), b, w: -0.4 }, Seg2::Line { a: b, b: a }] }),+ solid(square(1e6, -1e6, 1e-3)),+ Region2::default(),+ ];+ assert!(hull_box(®ions[2].outer).is_none(), "a negative weight leaves the control triangle");+ let mut inside = 0;+ for r in ®ions {+ let outline = RegionOutline::new(r);+ let hull = hull_box(&r.outer);+ let around = hull.unwrap_or_default();+ let (lo, hi) = (around.min - Vec2::new(5.0, 5.0), around.max + Vec2::new(5.0, 5.0));+ let mut points: Vec<Vec2> = Vec::new();+ for j in 0..=97 {+ for i in 0..=113 {+ points.push(Vec2::new(lo.x + (hi.x - lo.x) * f64::from(i) / 113.0, lo.y + (hi.y - lo.y) * f64::from(j) / 97.0));+ }+ }+ for l in r.loops() {+ let ring = l.polyline(CONTAINS_TOL);+ let bounds = ring.bounds();+ for e in [0.0, 1e-12, 1e-6] {+ points.extend([Vec2::new(bounds.min.x - e, bounds.center().y), Vec2::new(bounds.max.x + e, bounds.center().y)]);+ points.extend([Vec2::new(bounds.center().x, bounds.min.y - e), Vec2::new(bounds.center().x, bounds.max.y + e)]);+ }+ points.extend(ring.iter().copied());+ }+ points.extend([Vec2::new(f64::NAN, 1.0), Vec2::new(1.0, f64::NAN), Vec2::new(f64::INFINITY, 1.0), Vec2::new(f64::NEG_INFINITY, 1.0)]);+ for p in points {+ let want = old(r, p);+ assert_eq!(r.contains(p), want, "Region2::contains at {p:?}");+ assert_eq!(outline.contains(p), want, "RegionOutline::contains at {p:?}");+ if hull.is_some_and(|h| clearly_excludes(&h, p)) {+ assert!(!want, "clearly outside the box but inside at {p:?}");+ }+ inside += usize::from(want);+ }+ }+ assert!(inside > 3000, "{inside}");+ }}diff --git a/crates/ui-egui/src/pick_index_tests.rs b/crates/ui-egui/src/pick_index_tests.rsindex 5cc74e3bf8..71ae870fb1 100644--- a/crates/ui-egui/src/pick_index_tests.rs+++ b/crates/ui-egui/src/pick_index_tests.rs@@ -1,5 +1,6 @@use egui::{Rect, pos2, vec2};use serde_json::json;+use solidcraft_engine::geom::prelude::*;use crate::SolveApp;use crate::viewport::{Hit, pick, pick_all, projection};@@ -153,3 +154,105 @@ fn pick_timing_on_curved_models() {eprintln!("{name}: {} bodies, {tris} triangles, {segs} edge segments: scan {scan:.3} ms per pick, indexed {indexed:.3} ms", st.bodies.len());}}++/// Timing, not a check: mouse moves over a large sketch being edited, with no tool, with Trim and+/// with Extend (`SOLIDCRAFT_BENCH_SKETCH=out/testdaten/hover-circles.json cargo test --release -p+/// solidcraft-ui-egui --lib sketch_hover_timing -- --ignored --nocapture`; the scripts and how+/// they are made are in `out/testdaten/README.md`). Each move is one whole UI frame, as the window+/// runs it; the profile lookup under the cursor and the Trim piece are also timed on their own.+#[test]+#[ignore]+fn sketch_hover_timing() {+ use std::time::Instant;+ let Some(path) = std::env::var_os("SOLIDCRAFT_BENCH_SKETCH") else { return };+ let script: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();+ let mut h = crate::scenario::Harness::new();+ let began = Instant::now();+ for c in script["commands"].as_array().unwrap() {+ h.app.run(c["command"].as_str().unwrap(), c["params"].clone()).unwrap();+ }+ h.step(&json!({"call":"ui.view","params":{"view":"fit"}})).unwrap();+ h.settle();+ let sid = h.app.session.active_sketch.unwrap();+ let ss = h.app.session.world_state().unwrap().sketch(sid).unwrap().clone();+ eprintln!(+ "{}: {} curves, {} profiles, built in {:.1} s",+ path.to_string_lossy(),+ ss.sketch.curves.len(),+ ss.profiles.len(),+ began.elapsed().as_secs_f64()+ );+ // Points on the lines (where Trim and Extend show something), then a grid over the sketch.+ let mut at: Vec<(String, solidcore_record::Vec2)> = Vec::new();+ for c in &ss.sketch.curves {+ if let solidcraft_engine::sketch::CurveKind::Line { a, b } = c.kind+ && at.len() < 60+ {+ let (p, q) = (ss.sketch.point(a).unwrap(), ss.sketch.point(b).unwrap());+ for t in [0.31, 0.62, 0.93] {+ at.push((c.id.clone(), p.lerp(q, t)));+ }+ }+ }+ let bounds: solidcraft_engine::geom::Aabb2 = ss.sketch.points.iter().map(|p| p.pos).collect();+ for j in 0..6 {+ for i in 0..10 {+ let size = bounds.max - bounds.min;+ let r = solidcore_record::Vec2::new(size.x * (f64::from(i) + 0.5) / 10.0, size.y * (f64::from(j) + 0.5) / 6.0);+ at.push((String::new(), bounds.min + r));+ }+ }+ let screen: Vec<egui::Pos2> = at+ .iter()+ .map(|(_, q)| {+ let [x, y] = h.at(&json!({"sketch": [q.x, q.y]})).unwrap();+ egui::pos2(x as f32, y as f32)+ })+ .collect();+ let stats = |mut v: Vec<f64>| {+ v.sort_by(f64::total_cmp);+ (v[v.len() / 2], v[v.len() * 9 / 10])+ };+ for tool in [None, Some("sketch.trim"), Some("sketch.extend")] {+ if let Some(t) = tool {+ h.step(&json!({"start": t})).unwrap();+ h.frames(2);+ }+ let mut ms = Vec::new();+ for round in 0..3 {+ for p in &screen {+ let t = Instant::now();+ h.frame_with(vec![egui::Event::PointerMoved(*p)]);+ if round > 0 {+ ms.push(t.elapsed().as_secs_f64() * 1000.0);+ }+ }+ }+ let (median, p90) = stats(ms);+ eprintln!("frame per mouse move, {}: median {median:.3} ms, p90 {p90:.3} ms", tool.unwrap_or("no tool"));+ if tool.is_some() {+ h.step(&json!({"key":"Escape"})).unwrap();+ h.frames(2);+ }+ }+ let t = Instant::now();+ let mut found = 0;+ for _ in 0..10 {+ for (_, q) in &at {+ found += usize::from(std::hint::black_box(solidcraft_engine::sketch::profile_at_point(&ss.profiles, *q)).is_some());+ }+ }+ eprintln!("profile under the cursor: {:.4} ms a point ({found} found)", t.elapsed().as_secs_f64() * 100.0 / at.len() as f64);+ h.step(&json!({"start": "sketch.trim"})).unwrap();+ let mut ms = Vec::new();+ for (id, q) in at.iter().filter(|(id, _)| !id.is_empty()) {+ if let Some(tool) = h.app.tool.as_mut() {+ tool.hover = Some((*q, None));+ }+ let t = Instant::now();+ std::hint::black_box(crate::sketch_tools::trim_hover_piece(&h.app, sid, id));+ ms.push(t.elapsed().as_secs_f64() * 1000.0);+ }+ let (median, p90) = stats(ms);+ eprintln!("Trim piece per cursor move: median {median:.4} ms, p90 {p90:.4} ms");+}diff --git a/crates/ui-egui/src/sketch_corner_ui_tests.rs b/crates/ui-egui/src/sketch_corner_ui_tests.rsindex 40c1053861..3b60d4ff59 100644--- a/crates/ui-egui/src/sketch_corner_ui_tests.rs+++ b/crates/ui-egui/src/sketch_corner_ui_tests.rs@@ -796,6 +796,59 @@ fn trim_hover_shows_the_piece_a_click_takes_away() {assert!(trim_hover_piece(&h.app, sid, &line).is_none(), "only Trim shows a piece");}+/// Trim's hover keeps the cuts of the curve under the cursor while the sketch is unchanged and+/// Extend's preview while the cursor stays nearer one end: the piece follows the cursor along the+/// line, and a curve added in the way moves the piece's end and the extension's stop with it.+#[test]+fn trim_and_extend_hovers_follow_the_cursor_and_a_changed_sketch() {+ let mut h = crate::scenario::Harness::new();+ h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();+ let line = h.app.run("sketch.line", json!({"points": [[0,0],[30,0]], "connect": false})).unwrap()["curves"][0].as_str().unwrap().to_string();+ h.app.run("sketch.line", json!({"points": [[10,-5],[10,5]], "connect": false})).unwrap();+ h.app.run("sketch.line", json!({"points": [[20,-5],[20,5]], "connect": false})).unwrap();+ h.settle();+ let sid = h.app.session.active_sketch.unwrap();+ let ends = |p: &[Vec2]| {+ let mut x = [p[0].x, p[p.len() - 1].x];+ x.sort_by(f64::total_cmp);+ x+ };+ let near = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6;+ h.step(&json!({"start":"sketch.trim"})).unwrap();+ for (at, want) in [(15.0, [10.0, 20.0]), (16.0, [10.0, 20.0]), (25.0, [20.0, 30.0]), (4.0, [0.0, 10.0])] {+ h.step(&json!({"move":{"world":[at,0,0]}})).unwrap();+ let piece = trim_hover_piece(&h.app, sid, &line).unwrap();+ assert!(near(ends(&piece), want), "at {at}: {piece:?}");+ }+ h.app.run("sketch.line", json!({"points": [[24,-5],[24,5]], "connect": false})).unwrap();+ h.settle();+ h.step(&json!({"move":{"world":[27,0,0]}})).unwrap();+ let piece = trim_hover_piece(&h.app, sid, &line).unwrap();+ assert!(near(ends(&piece), [24.0, 30.0]), "the new line cuts: {piece:?}");+ let at = h.app.tool.as_ref().and_then(|t| t.hover.as_ref()).map(|h| h.0).unwrap();+ let fresh = solidcraft_engine::cmd::trim_piece(&h.app.session.world_state().unwrap().sketch(sid).unwrap().sketch, &line, at);+ assert_eq!(Some(piece), fresh, "the kept cuts are those of the sketch as it is");+ h.step(&json!({"key":"Escape"})).unwrap();++ let short = h.app.run("sketch.line", json!({"points": [[0,20],[8,20]], "connect": false})).unwrap()["curves"][0].as_str().unwrap().to_string();+ h.app.run("sketch.line", json!({"points": [[18,15],[18,25]], "connect": false})).unwrap();+ h.settle();+ h.step(&json!({"start":"sketch.extend"})).unwrap();+ for at in [7.0, 6.0, 5.0] {+ h.step(&json!({"move":{"world":[at,20,0]}})).unwrap();+ let piece = extend_preview_piece(&h.app, sid, &short).unwrap();+ assert!(near([piece[0].x, piece[1].x], [8.0, 18.0]), "at {at}: {piece:?}");+ }+ h.step(&json!({"move":{"world":[2,20,0]}})).unwrap();+ let piece = extend_preview_piece(&h.app, sid, &short).unwrap();+ assert!((piece[0].x).abs() < 1e-6 && piece[1].x < 0.0, "the other end grows: {piece:?}");+ h.app.run("sketch.line", json!({"points": [[13,15],[13,25]], "connect": false})).unwrap();+ h.settle();+ h.step(&json!({"move":{"world":[7,20,0]}})).unwrap();+ let piece = extend_preview_piece(&h.app, sid, &short).unwrap();+ assert!(near([piece[0].x, piece[1].x], [8.0, 13.0]), "the new line stops it: {piece:?}");+}+/// #3141: the 2-tangent circle tool, clicked on two sides of a rectangle drawn away from the/// origin, offers its default radius before it puts the circle in the corner between the clicks./// A typed radius reaches the command, neither path moves the rectangle, and fixed sides work.diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rsindex fb666ebe64..29b332330e 100644--- a/crates/ui-egui/src/sketch_tools.rs+++ b/crates/ui-egui/src/sketch_tools.rs@@ -1495,12 +1495,51 @@ pub fn finish(app: &mut SolveApp, tool: &mut Tool) -> bool {}}-/// The cursor's Trim piece, keyed by design revision, sketch, curve and cursor: the viewport's-/// hover and the preview both ask for it each frame, and it intersects the curve with every other.-type TrimPieceKey = (u64, u64, String, [u64; 2]);+type SolvedSketchRef = std::sync::Arc<solidcraft_engine::doc::SolvedSketch>;++/// The shown state's solve of `sketch`, shared.+fn solved_sketch(app: &SolveApp, sketch: u64) -> Option<SolvedSketchRef> {+ crate::open_meshing::session_world(&app.session).sketches.iter().find(|s| s.feature == sketch).cloned()+}++/// Which sketch state a hover cache was made from: the design revision and the solve itself,+/// held weakly so its place is not reused while the cache remembers it (a live drag swaps in a+/// new solve without a new revision).+struct SketchStateKey {+ revision: u64,+ solve: std::sync::Weak<solidcraft_engine::doc::SolvedSketch>,+ curve: String,+}++impl SketchStateKey {+ fn new(app: &SolveApp, solve: &SolvedSketchRef, curve: &str) -> SketchStateKey {+ SketchStateKey { revision: app.session.revision, solve: std::sync::Arc::downgrade(solve), curve: curve.to_string() }+ }+ fn matches(&self, app: &SolveApp, solve: &SolvedSketchRef, curve: &str) -> bool {+ self.revision == app.session.revision && std::ptr::eq(self.solve.as_ptr(), std::sync::Arc::as_ptr(solve)) && self.curve == curve+ }+}++/// Trim's hover over one curve: the cuts on it, made once per sketch state (they intersect the+/// curve with every other one), and the last piece the cursor chose (the viewport's hover and the+/// preview both ask for it each frame).+struct TrimHoverCache {+ key: SketchStateKey,+ hover: Option<solidcraft_engine::cmd::TrimHover>,+ piece: Option<([u64; 2], Option<Vec<Vec2>>)>,+}++/// Extend's preview of one curve, per sketch state and growing end (it depends on the cursor+/// only through the end, [`solidcraft_engine::cmd::extend_end_at`]).+struct ExtendPreviewCache {+ key: SketchStateKey,+ at_b: bool,+ piece: Option<Vec<Vec2>>,+}thread_local! {- static TRIM_PIECE: std::cell::RefCell<Option<(TrimPieceKey, Option<Vec<Vec2>>)>> = const { std::cell::RefCell::new(None) };+ static TRIM_HOVER: RefCell<Option<TrimHoverCache>> = const { RefCell::new(None) };+ static EXTEND_PREVIEW: RefCell<Option<ExtendPreviewCache>> = const { RefCell::new(None) };}/// With Trim active and the cursor over curve `id` of `sketch` (the active sketch): the piece a@@ -1512,14 +1551,27 @@ pub(crate) fn trim_hover_piece(app: &SolveApp, sketch: u64, id: &str) -> Option<if active_sketch(app) != Some(sketch) {return None;}- let key = (app.session.revision, sketch, id.to_string(), [at.x.to_bits(), at.y.to_bits()]);- if let Some(piece) = TRIM_PIECE.with(|c| c.borrow().as_ref().filter(|(k, _)| *k == key).map(|(_, p)| p.clone())) {- return piece;- }- let st = crate::open_meshing::session_world(&app.session);- let piece = solidcraft_engine::cmd::trim_piece(&st.sketch(sketch)?.sketch, id, *at);- TRIM_PIECE.with(|c| *c.borrow_mut() = Some((key, piece.clone())));- piece+ let solve = solved_sketch(app, sketch)?;+ let cursor = [at.x.to_bits(), at.y.to_bits()];+ TRIM_HOVER.with(|c| {+ let mut c = c.borrow_mut();+ let cache = match c.take() {+ Some(cache) if cache.key.matches(app, &solve, id) => c.insert(cache),+ _ => c.insert(TrimHoverCache {+ key: SketchStateKey::new(app, &solve, id),+ hover: solidcraft_engine::cmd::trim_hover(&solve.sketch, id),+ piece: None,+ }),+ };+ if let Some((k, piece)) = &cache.piece+ && *k == cursor+ {+ return piece.clone();+ }+ let piece = cache.hover.as_ref().and_then(|h| h.piece(*at));+ cache.piece = Some((cursor, piece.clone()));+ piece+ })}/// Extend preview: the geometry that would be added, based on the hover position over curve `id`@@ -1532,19 +1584,37 @@ fn extend_preview_piece(app: &SolveApp, sketch: u64, id: &str) -> Option<Vec<Vecif active_sketch(app) != Some(sketch) {return None;}- let st = crate::open_meshing::session_world(&app.session);- let sk = st.sketch(sketch)?;- let hover_pos = hover.0;- let ci = sk.sketch.curve_index(id)?;- let kind = sk.sketch.curves.get(ci)?.kind.clone();+ let solve = solved_sketch(app, sketch)?;+ let sk = &solve.sketch;+ let ci = sk.curve_index(id)?;+ // An infinite line in the way is cut short about the cursor, so the preview then follows it.+ let at_b = solidcraft_engine::cmd::extend_end_at(sk, ci, hover.0).filter(|_| !sk.curves.iter().any(|c| c.infinite));+ let Some(at_b) = at_b else { return extend_preview_uncached(sk, ci, hover.0) };+ EXTEND_PREVIEW.with(|c| {+ let mut c = c.borrow_mut();+ if let Some(cache) = c.as_ref()+ && cache.at_b == at_b+ && cache.key.matches(app, &solve, id)+ {+ return cache.piece.clone();+ }+ let piece = extend_preview_uncached(sk, ci, hover.0);+ *c = Some(ExtendPreviewCache { key: SketchStateKey::new(app, &solve, id), at_b, piece: piece.clone() });+ piece+ })+}++/// [`extend_preview_piece`] worked out afresh.+fn extend_preview_uncached(sk: &solidcraft_engine::sketch::Sketch, ci: usize, hover_pos: Vec2) -> Option<Vec<Vec2>> {+ let kind = sk.curves.get(ci)?.kind.clone();// Arcs extend along their circle either way round, up to the first geometry in the way.if let solidcraft_engine::sketch::CurveKind::Arc { .. } = kind {- return solidcraft_engine::cmd::extend_arc_preview(&sk.sketch, ci, hover_pos);+ return solidcraft_engine::cmd::extend_arc_preview(sk, ci, hover_pos);}let solidcraft_engine::sketch::CurveKind::Line { a, b } = kind else { return None };- let at_b = hover_pos.dist(sk.sketch.point(b)?) <= hover_pos.dist(sk.sketch.point(a)?);- let end = sk.sketch.point(if at_b { b } else { a })?;- let hit = solidcraft_engine::cmd::extend_preview(&sk.sketch, ci, hover_pos)?;+ let at_b = hover_pos.dist(sk.point(b)?) <= hover_pos.dist(sk.point(a)?);+ let end = sk.point(if at_b { b } else { a })?;+ let hit = solidcraft_engine::cmd::extend_preview(sk, ci, hover_pos)?;Some(vec![end, hit])}diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rsindex 3ac2c8bf37..9908c40c81 100644--- a/crates/ui-egui/src/viewport.rs+++ b/crates/ui-egui/src/viewport.rs@@ -2982,7 +2982,7 @@ fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool,// Show Profile off: the sketch being edited offers no profiles.let profiles = if ss.sketch.view.hide_profile && s.active_sketch == Some(sid) { &[][..] } else { &ss.profiles[..] };for (pi, p) in profiles.iter().enumerate() {- if !p.region.contains(lp) {+ if !p.contains(lp) {continue;}if all {