From 8fb046aaa84d6f2b7145d709b7e7cbfbbb88a92b Mon Sep 17 00:00:00 2001 From: Daniel Date: Wed, 4 Nov 2026 21:34:23 +0000 Subject: [PATCH] Sketch: the whole sketch updates while you type a dimension's value (#11584) (#11585) * claim: #11584 Co-Authored-By: Claude Opus 5.5 * Sketch: the sketch follows a dimension's value while it is typed (#11584) While a new dimension's value was typed, only the dimension moved: the sketch's curves, points, constraint glyphs and other dimensions stayed at the old size until Enter. The typed value was already solved in a scratch session; it is now solved in the frame it is typed, and the open sketch is drawn from that solve, for every kind of curve, within the display cache's limits per sketch. Esc draws the design again. Picking and snapping of curves and points stay on the design, and no hover highlight of the design is painted while a value is typed. A value that does not solve keeps the last one that did. Co-Authored-By: Claude Opus 5.5 * Dimension: the sketch scene follows each solve of a typed value, not its address (#11584) The sketch scene was keyed on the preview's address, which a later solve can have once the drawn one is freed; the scene would then stay at the old value. Each solve now has a number, and the scene is keyed on it. Co-Authored-By: Claude Opus 5.5 * Dimension: while a value is typed, no design profile is lit over the sketch, and its curves are sampled before its fills (#11584) The profile under the pointer was lit where the design has it, over the sketch drawn at the typed value; it is no longer, and the highlight is built again when the value is let go. The typed sketch's profiles were sampled before its curves from the one budget, so a sketch whose fills used it up lost its curves; the curves now go first. Co-Authored-By: Claude Opus 5.5 * Dimension: a selected profile is not lit over the sketch while a value is typed either (#11584) Co-Authored-By: Claude Opus 5.5 * Dimension: the view goes to the typed preview only once a value is typed (#11584) A picked dimension's value box opened with a draft that is the design as it is, and the view already treated it as the typed preview: the profile under the pointer, the selection and the hover went dark before anything was typed. The preview now starts with the first key, completion or reference. Co-Authored-By: Claude Opus 5.5 * Dimension: a reference picked into the value is solved at once (#11584) The overlays read the preview before the editor solves a changed value, so for the click's frame they drew the solve before the reference. Co-Authored-By: Claude Opus 5.5 * Dimension: a selected sketch curve is not lit where the design has it while a value is typed (#11584) Co-Authored-By: Claude Opus 5.5 * Dimension: the pointer's x, y readout is not drawn while a value is typed, as the hover is not (#11584) Co-Authored-By: Claude Opus 5.5 * Dimension: curvature combs, the design's teeth, are not drawn while a value is typed (#11584) Co-Authored-By: Claude Opus 5.5 * Dimension: while a value is typed only the open sketch loses its hover and profile highlights; other sketches keep theirs (#11584) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/dim_view.rs | 96 +++++- .../ui-egui/src/dimension_create_ui_tests.rs | 319 +++++++++++++++++- crates/ui-egui/src/sketch_display.rs | 66 +++- crates/ui-egui/src/sketch_tools.rs | 7 +- crates/ui-egui/src/tools.rs | 19 +- crates/ui-egui/src/viewport.rs | 133 ++++++-- 6 files changed, 591 insertions(+), 49 deletions(-) diff --git a/crates/ui-egui/src/dim_view.rs b/crates/ui-egui/src/dim_view.rs index c499ed3ba..e19bdc452 100644 --- a/crates/ui-egui/src/dim_view.rs +++ b/crates/ui-egui/src/dim_view.rs @@ -65,6 +65,9 @@ struct Edit { /// or a reference, or pressed into the field. Until then every frame starts with the whole /// value selected, so the first key replaces it whatever else moved the caret (#11204). owned: bool, + /// A value was typed, completed or given a reference: until then the draft is the design as + /// it is, and the view is not put in its preview (see [`preview_world`]). + typed: bool, /// Where the box sat last frame: a press only takes the value over once the box stayed put /// under it, so the click that placed or pinned the value does not. shown: Option, @@ -103,6 +106,8 @@ struct DimensionDraft { checked_expr: String, preview_doc: Arc, preview: Arc, + /// Which solve `preview` is (see [`next_solve`]). + solve: u64, error: Option, /// A dimension that would over-constrain the sketch, placed as a driven (reference) one: /// it has no parameter and no value to edit (#320). @@ -231,6 +236,7 @@ pub fn begin_dimension(app: &mut SolveApp, entities: Vec, at: Vec2) -> R live: None, selection: None, owned: false, + typed: false, shown: None, picked: None, sketch: None, @@ -270,6 +276,7 @@ pub fn begin_live(app: &mut SolveApp, entities: Vec, pointer: Option { draft.preview = crate::open_meshing::session_world(&scratch); + draft.solve = next_solve(); draft.preview_doc = scratch.doc.clone(); draft.error = None; } @@ -391,6 +399,7 @@ fn draft_of(app: &SolveApp, sketch: u64, entities: &[String], at: Option, at, checked_expr: expr.clone(), preview: crate::open_meshing::session_world(&scratch), + solve: next_solve(), preview_doc: scratch.doc.clone(), error: None, driven, @@ -451,6 +460,8 @@ thread_local! { /// A text being dragged: dimension id, undo depth at the start, grab offset (sketch). static DRAG: RefCell> = const { RefCell::new(None) }; static EDIT: RefCell> = const { RefCell::new(None) }; + /// Solves made for drafts so far: each preview's number, which the sketch scene is keyed on. + static SOLVES: std::cell::Cell = const { std::cell::Cell::new(0) }; 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`). @@ -509,6 +520,7 @@ pub fn model_double_click(app: &mut SolveApp, pos: Pos2) -> bool { live: None, selection: None, owned: false, + typed: false, shown: None, picked: None, sketch: Some(d.sketch), @@ -610,6 +622,7 @@ fn open_editor(app: &mut SolveApp, id: Option) -> bool { live: None, selection: None, owned: false, + typed: false, shown: None, picked: None, sketch: None, @@ -773,8 +786,11 @@ pub fn show(app: &mut SolveApp, ui: &egui::Ui, painter: &egui::Painter, proj: &P Some((e.param.clone(), draft.clone())) }); let placing = !editing(); + // While a value is typed the whole sketch, its other dimensions included, is drawn as the + // value would leave it (#11584); placing one only measures, so nothing moves. + let typed = preview_world(app); let draft = editor_draft.or_else(|| placing.then(|| placement_preview(app)).flatten()); - let st = crate::open_meshing::session_world(&app.session); + let st = typed.clone().unwrap_or_else(|| crate::open_meshing::session_world(&app.session)); let Some(ss) = app.session.active_sketch.and_then(|s| st.sketch(s)) else { DRAWN.with(|d| d.borrow_mut().clear()); // Only a finished sketch's dimension edited from the model view stays open, at its text. @@ -816,11 +832,15 @@ pub fn show(app: &mut SolveApp, ui: &egui::Ui, painter: &egui::Painter, proj: &P let centres = chain_centres(sk); let draft_sketch = draft.as_ref().and_then(|(_, d)| d.preview.sketch(d.sketch)); let draft_centres = draft_sketch.map(|solved| chain_centres(&solved.sketch)); - let mut constraints = sk.constraints.iter().map(|c| (ss, c, false)).collect::>(); - if let (Some(source), Some((param, _))) = (draft_sketch, draft.as_ref()) { - // A driven draft is keyed by its constraint id (it has no parameter). - let ours = |c: &&solidcraft_engine::sketch::Constraint| c.param.as_deref() == Some(param.as_str()) || (c.driven && c.id == *param); - constraints.extend(source.sketch.constraints.iter().filter(ours).map(|c| (source, c, true))); + // A driven draft is keyed by its constraint id (it has no parameter). + let ours = |c: &solidcraft_engine::sketch::Constraint| { + draft.as_ref().is_some_and(|(param, _)| c.param.as_deref() == Some(param.as_str()) || (c.driven && c.id == *param)) + }; + // Drawn from the typed value's solve, the sketch already holds the draft: it is told apart + // by its parameter, as below. + let mut constraints = sk.constraints.iter().filter(|c| typed.is_none() || !ours(c)).map(|c| (ss, c, false)).collect::>(); + if let Some(source) = draft_sketch { + constraints.extend(source.sketch.constraints.iter().filter(|c| ours(c)).map(|c| (source, c, true))); } // Text boxes already drawn this frame, in draw order: a later dimension that would land // on one of them steps clear of it (#44). @@ -965,6 +985,7 @@ pub fn edit_param(app: &SolveApp, param: &str) { live: None, selection: None, owned: false, + typed: false, shown: None, picked: None, sketch: None, @@ -992,6 +1013,7 @@ fn is_plain_value(text: &str) -> bool { /// /// The cursor ends just after the name and the field keeps the keyboard. fn insert_reference(ctx: &egui::Context, edit: &mut Edit, name: &str) { + edit.typed = true; let id = egui::Id::new("sc_dim_edit"); let mut state = egui::TextEdit::load_state(ctx, id).unwrap_or_default(); let len = edit.expr.chars().count(); @@ -1024,7 +1046,7 @@ fn insert_reference(ctx: &egui::Context, edit: &mut Edit, name: &str) { /// Consume dimension clicks while editing: a click on another driving dimension inserts its /// name at the cursor (replacing selected text), keeping what was typed. The second click of a /// double-click on the same dimension does not insert it again. -pub fn pick_reference(ctx: &egui::Context, pos: Pos2, double: bool) -> bool { +pub fn pick_reference(app: &SolveApp, ctx: &egui::Context, pos: Pos2, double: bool) -> bool { EDIT.with(|editor| { let mut editor = editor.borrow_mut(); let Some(edit) = editor.as_mut() else { return false }; @@ -1043,6 +1065,12 @@ pub fn pick_reference(ctx: &egui::Context, pos: Pos2, double: bool) -> bool { if !repeat { insert_reference(ctx, edit, ¶m); edit.picked = Some((param, now)); + // Solved now, as a typed value is: the overlays read the preview before the + // editor runs this frame. + if let Some(draft) = edit.draft.as_mut() { + let expr = edit.expr.clone(); + reevaluate(app, draft, &expr); + } } } edit.fresh = FRESH - 1; @@ -1140,6 +1168,14 @@ fn edit_box(app: &mut SolveApp, ctx: &egui::Context) { live.typed |= r.changed() || completed; } e.owned |= r.changed() || completed; + e.typed |= r.changed() || completed; + // Solved now, so the next frame draws the sketch at the new value from its start. + if (r.changed() || completed) + && let Some(draft) = e.draft.as_mut() + { + let expr = e.expr.clone(); + reevaluate(app, draft, &expr); + } if let Some(error) = e.draft.as_ref().and_then(|d| d.error.as_ref()) { crate::ui_kit::text(ui, error, crate::ui_kit::Text::Report("dimension_error", true)); } @@ -1219,11 +1255,57 @@ fn clear_picks(app: &mut SolveApp) { } } +/// While a new dimension's value is typed: the design solved with that value (the last value +/// that solved), so the open sketch is drawn as Enter would leave it. None otherwise. +pub fn preview_world(app: &SolveApp) -> Option> { + EDIT.with(|e| e.try_borrow().ok()?.as_ref().filter(|e| e.typed)?.draft.as_ref().filter(|d| !d.driven && d.valid(app)).map(|d| d.preview.clone())) +} + +/// A number for a new solve, never one an earlier solve had: a preview's address can be an earlier +/// one's once that is freed, so the sketch scene is keyed on this instead. +fn next_solve() -> u64 { + SOLVES.with(|n| { + n.set(n.get() + 1); + n.get() + }) +} + +/// Which solve [`preview_world`] is, while there is one. +pub fn preview_solve(app: &SolveApp) -> Option { + EDIT.with(|e| e.try_borrow().ok()?.as_ref().filter(|e| e.typed)?.draft.as_ref().filter(|d| !d.driven && d.valid(app)).map(|d| d.solve)) +} + +/// The sketch drawn at a typed value (the open one), while there is one: its design curves are +/// not where they are drawn, the other sketches' are. +pub fn previewed_sketch(app: &SolveApp) -> Option { + preview_solve(app).and(app.session.active_sketch) +} + /// Is the inline editor open (it has the keyboard)? pub fn editing() -> bool { EDIT.with(|e| e.borrow().is_some()) } +/// The open draft's typed text and the text its preview was solved for (tests). +#[cfg(test)] +pub fn solved_for() -> Option<(String, String)> { + EDIT.with(|edit| { + let edit = edit.borrow(); + let e = edit.as_ref()?; + Some((e.expr.clone(), e.draft.as_ref()?.checked_expr.clone())) + }) +} + +/// Solve the open draft again for `expr`, as a typed value or a moved text does (tests). +#[cfg(test)] +pub fn resolve(app: &SolveApp, expr: &str) { + EDIT.with(|edit| { + if let Some(draft) = edit.borrow_mut().as_mut().and_then(|e| e.draft.as_mut()) { + reevaluate(app, draft, expr); + } + }); +} + /// The open draft: its expression, the dimension it adds and the sketch it previews (tests). #[cfg(test)] pub fn draft_preview() -> Option<(String, solidcraft_engine::sketch::Constraint, solidcraft_engine::sketch::Sketch)> { diff --git a/crates/ui-egui/src/dimension_create_ui_tests.rs b/crates/ui-egui/src/dimension_create_ui_tests.rs index 7693c18a1..869b3585b 100644 --- a/crates/ui-egui/src/dimension_create_ui_tests.rs +++ b/crates/ui-egui/src/dimension_create_ui_tests.rs @@ -668,8 +668,10 @@ fn dimension_to_fillet_virtual_sharp_keeps_the_arc_and_fixed_origin() { assert_eq!(h.app.session.doc.to_json(), baseline); } +/// While a new dimension's value is typed, a committed dimension moves with the sketch drawn at +/// that value and is picked where it is drawn; the draft is no hit target, and Esc puts it back. #[test] -fn draft_annotation_does_not_move_committed_dimension_hitboxes() { +fn a_committed_dimension_moves_with_the_typed_preview_and_is_picked_where_drawn() { crate::dim_view::cancel(); let mut h = Harness::new(); h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); @@ -685,8 +687,14 @@ fn draft_annotation_does_not_move_committed_dimension_hitboxes() { place(&mut h, &[[0., 0.], [0., 10.]], [-5., 5.]); type_value(&mut h, "12 mm"); h.settle(); - assert_eq!(crate::dim_view::text_at(&width), Some(at)); - assert_eq!(crate::dim_view::drawn(), drawn, "draft annotations must not become committed hit targets"); + // The sketch is drawn at the typed height, so the width on the top side is drawn, and + // picked, 2 mm higher; the draft itself is no hit target. + let [_, top] = h.at(&json!({"world":[10,12,0]})).unwrap(); + let [_, was] = h.at(&json!({"world":[10,10,0]})).unwrap(); + let moved = crate::dim_view::text_at(&width).unwrap() - at; + assert!(moved.x.abs() < 0.5 && (f64::from(moved.y) - (top - was)).abs() < 0.5, "the width follows its side: {moved:?}"); + let ids = |d: Vec<(String, egui::Pos2)>| d.into_iter().map(|(id, _)| id).collect::>(); + assert_eq!(ids(crate::dim_view::drawn()), ids(drawn.clone()), "draft annotations must not become committed hit targets"); assert_eq!(h.app.session.doc.to_json(), baseline); h.step(&json!({"key":"Escape"})).unwrap(); assert_eq!(crate::dim_view::drawn(), drawn); @@ -1032,6 +1040,253 @@ fn type_first_escape_cancels_with_no_change() { crate::dim_view::cancel(); } +/// The open sketch's lines as the next frame paints them (the viewport's sketch scene, rebuilt +/// only when its key changes, before the frame's dimensions are drawn; the harness has no GPU, +/// so the test does it): their bounds, [min x, min y, max x, max y]. +fn drawn_extent(h: &mut Harness) -> [f32; 4] { + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + let proj = crate::viewport::projection(&h.app, rect); + crate::viewport::refresh_sketch_scene(&mut h.app, &proj); + let slot = h.app.viewport.sketch_slot.lock().unwrap(); + let scene = slot.as_ref().expect("a sketch scene"); + let ends = scene.overlay.as_chunks::<32>().0.iter().flat_map(|l| [&l[0..12], &l[12..24]]); + ends.map(|b| [0, 4].map(|i| b.get(i..i + 4).and_then(|x| x.try_into().ok()).map(f32::from_le_bytes))) + .filter_map(|[x, y]| Some([x?, y?])) + .fold([f32::MAX, f32::MAX, f32::MIN, f32::MIN], |m, [x, y]| [m[0].min(x), m[1].min(y), m[2].max(x), m[3].max(y)]) +} + +fn near(a: [f32; 4], b: [f32; 4]) -> bool { + a.iter().zip(b).all(|(a, b)| (a - b).abs() < 0.6) +} + +fn bounds(sk: &solidcraft_engine::sketch::Sketch) -> [f32; 4] { + let (lo, hi) = sk.bounds().unwrap_or_default(); + [lo.x, lo.y, hi.x, hi.y].map(|v| v as f32) +} + +/// While a value is typed the sketch is drawn as the value leaves it, not only the dimension +/// (#11584), whatever the shape; Esc draws it as it is again. +#[test] +fn typing_a_value_draws_the_sketch_at_that_value_and_escape_restores_it() { + let fix = |entity: &str| ("sketch.constraint.fix", json!({"entity": entity})); + let rectangle = vec![("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[40,20]}))]; + let circle = vec![("sketch.circle.center", json!({"center":[10,0],"radius":5})), fix("c1.center")]; + let slot = vec![("sketch.slot.center_to_center", json!({"p0":[-20,0],"p1":[20,0],"width":20}))]; + let arc = vec![("sketch.arc.center_point", json!({"center":[10,0],"start":[18,0],"sweep":90})), fix("a1.center")]; + let spline = vec![ + ("sketch.spline.fit_point", json!({"points": [[-30, 0], [-10, 18], [10, 6], [30, 20]]})), + ("sketch.line", json!({"points":[[30,20],[30,-10]],"infer":true})), + ]; + let mixed = vec![ + ("sketch.circle.center", json!({"center":[0,0],"radius":10})), + ("sketch.circle.center", json!({"center":[40,0],"radius":10})), + ("sketch.line", json!({"points":[[0,10],[40,10]],"infer":false})), + ("sketch.constraint.tangent", json!({"a":"l1","b":"c1"})), + ("sketch.constraint.tangent", json!({"a":"l1","b":"c2"})), + ("sketch.constraint.equal", json!({"a":"c1","b":"c2"})), + fix("c1.center"), + fix("c2.center"), + ]; + let half = std::f64::consts::FRAC_1_SQRT_2 * 8.0; + let cases: [(&str, &[(&str, serde_json::Value)], [f64; 2], Vec<[f64; 2]>, &str); 6] = [ + ("rectangle side", &rectangle, [20., 10.], vec![[20., 0.]], "60"), + ("circle diameter", &circle, [10., 0.], vec![[15., 0.]], "20"), + ("slot side", &slot, [0., 0.], vec![[0., 10.]], "60"), + ("arc radius", &arc, [10., 0.], vec![[10. + half, half]], "12"), + ("spline end", &spline, [0., 5.], vec![[30., 5.]], "50"), + ("tangent equal circles", &mixed, [20., 0.], vec![[-10., 0.]], "30"), + ]; + for (name, setup, centre, picks, typed) in cases { + let mut h = sketch_with(setup, centre); + // Far enough out that the grown shapes stay in view (the drawn lines stop at its edge). + h.app.cam.distance = 200.0; + h.settle(); + let real = bounds(&solved(&h)); + let before = drawn_extent(&mut h); + assert!(near(before, real), "{name}: drawn {before:?}, sketch {real:?}"); + for p in &picks { + h.step(&json!({"click":{"world":[p[0],p[1],0]}})).unwrap(); + } + assert_live(&h); + keys(&mut h, typed); + // What the frame after the last key paints, against the typed value's solve a frame later. + let shown = drawn_extent(&mut h); + h.frames(1); + let (_, _, preview) = crate::dim_view::draft_preview().expect("the draft is open"); + let target = bounds(&preview); + assert!(!near(target, real), "{name}: the typed value changes the sketch: {target:?}"); + assert!(near(shown, target), "{name}: the sketch follows the typed value: drawn {shown:?}, solved {target:?}"); + assert!(near(bounds(&solved(&h)), real), "{name}: nothing changes until Enter"); + // A value that does not solve (here half typed) keeps the last one that did. + keys(&mut h, "*"); + assert_eq!(crate::dim_view::draft_preview().map(|(expr, _, _)| expr), Some(format!("{typed}*"))); + let kept = drawn_extent(&mut h); + assert!(near(kept, target), "{name}: an unsolved value keeps the last drawn: {kept:?}"); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(!crate::dim_view::editing()); + let after = drawn_extent(&mut h); + assert!(near(after, real), "{name}: Esc draws the sketch as it is: {after:?}"); + crate::dim_view::cancel(); + } +} + +/// Each solve of a typed value redraws the sketch, also two between frames (a moved text and a +/// typed value in one frame), and a solve back to an earlier value: the scene is keyed on the +/// solve, not on where its result happens to be in memory. +#[test] +fn every_solve_of_a_typed_value_redraws_the_sketch() { + let mut h = sketch_with(&[("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[40,20]}))], [20., 10.]); + h.app.cam.distance = 300.0; + h.settle(); + h.step(&json!({"click":{"world":[20,0,0]}})).unwrap(); + assert_live(&h); + keys(&mut h, "60"); + let sixty = drawn_extent(&mut h); + let mut solves = std::collections::BTreeSet::new(); + for _ in 0..4 { + crate::dim_view::resolve(&h.app, "70"); + crate::dim_view::resolve(&h.app, "80"); + assert!(solves.insert(crate::dim_view::preview_solve(&h.app).expect("a preview")), "a new solve has a new number"); + let (_, _, preview) = crate::dim_view::draft_preview().expect("the draft is open"); + let drawn = drawn_extent(&mut h); + assert!(!near(drawn, sixty) && near(drawn, bounds(&preview)), "drawn {drawn:?}, solved {:?}", bounds(&preview)); + crate::dim_view::resolve(&h.app, "60"); + assert!(near(drawn_extent(&mut h), sixty)); + } + crate::dim_view::cancel(); +} + +/// While a value is typed the sketch is drawn at it, so a profile under the pointer is not lit +/// where the design has it (over the resized one); it is again once the value is let go. +#[test] +fn a_typed_value_does_not_light_the_design_s_profile_under_the_pointer() { + let mut h = sketch_with(&[("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[40,20]}))], [20., 10.]); + h.step(&json!({"click":{"world":[20,0,0]}})).unwrap(); + assert_live(&h); + keys(&mut h, "60"); + let sketch = h.app.session.active_sketch.unwrap(); + h.app.viewport.hover = Some(crate::viewport::Hit::Profile { sketch, index: 0 }); + let key = crate::viewport::highlight_key(&h.app); + assert!(crate::viewport::build_highlight(&h.app).merged().trans.is_empty(), "no profile lit while the value is typed"); + h.step(&json!({"key":"Escape"})).unwrap(); + h.app.viewport.hover = Some(crate::viewport::Hit::Profile { sketch, index: 0 }); + assert_ne!(crate::viewport::highlight_key(&h.app), key, "letting the value go lights it again"); + assert!(!crate::viewport::build_highlight(&h.app).merged().trans.is_empty(), "lit as before"); + crate::dim_view::cancel(); +} + +/// Until a value is typed the sketch is drawn as the design has it, so a picked dimension's +/// value box alone does not put the view in the typed preview: the profile under the pointer +/// stays lit. The first key does. +#[test] +fn a_dimension_only_picked_keeps_the_design_view_until_a_value_is_typed() { + let mut h = sketch_with(&[("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[40,20]}))], [20., 10.]); + h.step(&json!({"click":{"world":[20,0,0]}})).unwrap(); + assert_live(&h); + assert!(crate::dim_view::preview_solve(&h.app).is_none(), "nothing typed yet: no preview"); + let sketch = h.app.session.active_sketch.unwrap(); + h.app.viewport.hover = Some(crate::viewport::Hit::Profile { sketch, index: 0 }); + assert!(!crate::viewport::build_highlight(&h.app).merged().trans.is_empty(), "the profile is lit while only picked"); + keys(&mut h, "6"); + assert!(crate::dim_view::preview_solve(&h.app).is_some(), "a key starts the preview"); + crate::dim_view::cancel(); +} + +/// A selected profile is not lit where the design has it while a value is typed either. +#[test] +fn a_typed_value_does_not_light_a_selected_design_profile() { + let mut h = sketch_with(&[("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[40,20]}))], [20., 10.]); + h.step(&json!({"click":{"world":[20,0,0]}})).unwrap(); + assert_live(&h); + keys(&mut h, "60"); + let sketch = h.app.session.active_sketch.unwrap(); + h.app.session.selection = vec![solidcraft_engine::Sel::Profile { sketch, index: 0 }]; + assert!(crate::dim_view::preview_solve(&h.app).is_some(), "the value is still typed"); + assert!(crate::viewport::build_highlight(&h.app).merged().trans.is_empty(), "no profile lit while the value is typed"); + crate::dim_view::cancel(); + assert!(!crate::viewport::build_highlight(&h.app).merged().trans.is_empty(), "lit once the value is let go"); +} + +/// While a value is typed the sketch's curves are sampled before its profiles: a sketch whose +/// profiles would use up the sampling budget still has its curves drawn (its fills go first). +#[test] +fn a_typed_value_draws_the_curves_before_the_profiles_use_up_the_budget() { + let mut h = sketch_with( + &[("sketch.circle.center", json!({"center":[10,0],"radius":5})), ("sketch.constraint.fix", json!({"entity": "c1.center"}))], + [10., 0.], + ); + h.step(&json!({"click":{"world":[15,0,0]}})).unwrap(); + assert_live(&h); + keys(&mut h, "20"); + let (_, _, preview) = crate::dim_view::draft_preview().expect("the draft is open"); + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + let proj = crate::viewport::projection(&h.app, rect); + let plane = h.app.session.world_state().unwrap().sketch(h.app.session.active_sketch.unwrap()).unwrap().plane; + let mut all = solidcraft_engine::render::SamplingBudget::new(131_072, 1_048_576); + let need = crate::sketch_display::curve_with_budget(&preview, 0, &plane, &proj, h.app.viewport.pixels_per_point(), &mut all).vertex_count; + assert!(need > 4, "the circle takes some vertices: {need}"); + crate::sketch_display::UNCACHED_VERTICES.with(|v| v.set(Some(need))); + let drawn = drawn_extent(&mut h); + crate::sketch_display::UNCACHED_VERTICES.with(|v| v.set(None)); + assert!(near(drawn, bounds(&preview)), "the circle is drawn at the typed value: drawn {drawn:?}, solved {:?}", bounds(&preview)); + crate::dim_view::cancel(); +} + +/// Is a sketch point drawn at `world` this frame (its filled square)? +fn point_drawn(h: &mut Harness, world: [f64; 2]) -> bool { + let [x, y] = h.at(&json!({"world":[world[0], world[1], 0]})).unwrap(); + let at = egui::pos2(x as f32, y as f32); + h.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.rect.width() == 5.0 && r.rect.center().distance(at) < 0.5)) +} + +/// Is a sketch curve's hover highlight painted this frame? +fn hover_painted(h: &Harness) -> bool { + let col = egui::epaint::ColorMode::Solid(crate::theme::Tokens::get().hover_profile_edge); + h.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Path(p) if p.stroke.width == 3.0 && p.stroke.color == col)) +} + +/// While a value is typed, the sketch's points and constraint glyphs are drawn where the value +/// puts them as well as its curves, the next frame already (the value is solved when typed), and +/// no hover highlight traces a curve of the design; Esc puts everything back. +#[test] +fn typing_a_value_draws_points_and_glyphs_there_and_no_hover_of_the_design() { + let rectangle = [("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[40,20]}))]; + let mut h = sketch_with(&rectangle, [30., 15.]); + h.app.cam.distance = 200.0; + h.settle(); + let glyphs = crate::sketch_tools::glyph_positions(); + assert!(!glyphs.is_empty()); + assert!(point_drawn(&mut h, [40., 20.])); + h.step(&json!({"click":{"world":[20,0,0]}})).unwrap(); + assert_live(&h); + keys(&mut h, "60"); + // The frame after the last key, as the app draws it. + h.frames(1); + assert!(point_drawn(&mut h, [60., 30.]), "the corner is drawn where 60 puts it"); + assert!(!point_drawn(&mut h, [40., 20.]), "no point where the design has it"); + // The right side's glyph moves with its middle, from (40, 10) to (60, 15). + let [x0, y0] = h.at(&json!({"world":[40,10,0]})).unwrap(); + let [x1, y1] = h.at(&json!({"world":[60,15,0]})).unwrap(); + let shift = egui::vec2((x1 - x0) as f32, (y1 - y0) as f32); + let typed = crate::sketch_tools::glyph_positions(); + let moved = |id: &String, at: egui::Pos2| glyphs.iter().any(|(was_id, was)| was_id == id && (at - *was - shift).length() < 1.5); + assert!(typed.iter().any(|(id, at)| moved(id, *at)), "a glyph follows the right side: {glyphs:?} -> {typed:?}, shift {shift:?}"); + // Over where the design's right side is, nothing is drawn, so nothing lights up. + h.step(&json!({"move":{"world":[40,10,0]}})).unwrap(); + h.frames(1); + assert!(!hover_painted(&h), "no hover highlight of the design's curve"); + // One more key and one frame: the value is solved in the frame it is typed, so the next + // frame's sketch scene, built before the dimensions are drawn, is already at that value. + h.frame_with(vec![egui::Event::Text("5".into())]); + let (text, solved) = crate::dim_view::solved_for().expect("the draft is open"); + assert_eq!((text.as_str(), solved.as_str()), ("605", "605")); + h.step(&json!({"key":"Escape"})).unwrap(); + h.frames(1); + assert!(point_drawn(&mut h, [40., 20.])); + assert_eq!(crate::sketch_tools::glyph_positions(), glyphs); + crate::dim_view::cancel(); +} + /// Place first still works: a click before typing puts the text there and keeps the value /// (selected, so typing replaces it); Tab leaves the picks for a click to place, as before. #[test] @@ -1733,3 +1988,61 @@ fn the_status_after_a_dimension_is_in_the_interface_language() { } crate::dim_view::cancel(); } + +/// A selected curve of the sketch is not lit where the design has it while a value is typed, as +/// a selected profile is not. +#[test] +fn a_typed_value_does_not_light_a_selected_design_curve() { + let mut h = sketch_with(&[("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[40,20]}))], [20., 10.]); + h.step(&json!({"click":{"world":[20,0,0]}})).unwrap(); + assert_live(&h); + keys(&mut h, "60"); + let sketch = h.app.session.active_sketch.unwrap(); + let id = solved(&h).curves[0].id.clone(); + for sel in [ + solidcraft_engine::Sel::SketchCurve { id: id.clone(), sketch: None }, + solidcraft_engine::Sel::SketchCurve { id: id.clone(), sketch: Some(sketch) }, + solidcraft_engine::Sel::ExternalSketchCurve { sketch, id: id.clone() }, + ] { + h.app.session.selection = vec![sel.clone()]; + assert!(crate::viewport::build_highlight(&h.app).overlay.is_empty(), "{sel:?}: no curve lit while the value is typed"); + } + crate::dim_view::cancel(); + assert!(!crate::viewport::build_highlight(&h.app).overlay.is_empty(), "lit once the value is let go"); +} + +/// The Dimension tool's "x, y" readout gives the design's coordinates: while a value is typed it +/// is not drawn, as the hover highlight is not. +#[test] +fn a_typed_value_hides_the_pointer_readout() { + let mut h = sketch_with(&[("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[40,20]}))], [20., 10.]); + h.step(&json!({"move":{"world":[10,5,0]}})).unwrap(); + h.frames(1); + assert!(crate::scenario::rect_of("viewport:readout").is_some(), "the readout is drawn while only pointing"); + h.step(&json!({"click":{"world":[20,0,0]}})).unwrap(); + assert_live(&h); + keys(&mut h, "60"); + h.step(&json!({"move":{"world":[12,6,0]}})).unwrap(); + h.frames(1); + assert!(crate::scenario::rect_of("viewport:readout").is_none(), "no readout while the value is typed"); + crate::dim_view::cancel(); +} + +/// A curvature comb's teeth are the design's: while a value is typed they are not drawn. +#[test] +fn a_typed_value_hides_the_curvature_combs() { + let mut h = sketch_with(&[("sketch.circle.center", json!({"center":[20,10],"radius":5}))], [20., 10.]); + let id = solved(&h).curves[0].id.clone(); + h.app.run("inspect.curvature_comb", json!({"curves":[id]})).unwrap(); + h.step(&json!({"start":"sketch.dimension"})).unwrap(); + let teeth = egui::epaint::Stroke::new(1.0, crate::theme::Tokens::get().comb_teeth); + let comb_drawn = |h: &Harness| h.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::LineSegment { stroke, .. } if *stroke == teeth)); + h.frames(1); + assert!(comb_drawn(&h), "the comb is drawn"); + h.step(&json!({"click":{"world":[25,10,0]}})).unwrap(); + assert_live(&h); + keys(&mut h, "8"); + h.frames(1); + assert!(!comb_drawn(&h), "no comb of the design while the value is typed"); + crate::dim_view::cancel(); +} diff --git a/crates/ui-egui/src/sketch_display.rs b/crates/ui-egui/src/sketch_display.rs index 3c186af8f..82ec84e07 100644 --- a/crates/ui-egui/src/sketch_display.rs +++ b/crates/ui-egui/src/sketch_display.rs @@ -190,6 +190,60 @@ impl Default for SketchBudget { } } +impl SketchBudget { + fn sampling_left(&self) -> bool { + self.sampling.remaining_vertices > 0 && self.sampling.remaining_nodes > 0 + } + + fn room_for_curve(&self) -> bool { + self.curves < SKETCH_CURVES && self.sampling_left() + } + + fn room_for_profile(&self) -> bool { + self.profiles < SKETCH_PROFILES && self.sampling_left() + } +} + +/// One sketch sampled past the cache (the open sketch at a dimension's typed value), within the +/// limits the cache gives one sketch: past them a curve or profile is not drawn, as there. +pub(crate) struct Uncached(SketchBudget); + +#[cfg(test)] +thread_local! { + /// A smaller sampling budget for [`Uncached`] (vertices), so a test can run out of it. + pub(crate) static UNCACHED_VERTICES: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +impl Default for Uncached { + fn default() -> Self { + #[allow(unused_mut)] + let mut budget = SketchBudget::default(); + #[cfg(test)] + if let Some(vertices) = UNCACHED_VERTICES.with(std::cell::Cell::get) { + budget.sampling = SamplingBudget::new(vertices, 1_048_576); + } + Self(budget) + } +} + +impl Uncached { + pub(crate) fn curve(&mut self, sketch: &Sketch, index: usize, plane: &Plane, proj: &Proj, ppp: f32) -> Vec> { + if !self.0.room_for_curve() { + return Vec::new(); + } + self.0.curves += 1; + curve_with_budget(sketch, index, plane, proj, ppp, &mut self.0.sampling).parts + } + + pub(crate) fn profile(&mut self, region: &Region2, plane: &Plane, proj: &Proj, ppp: f32) -> Option { + if !self.0.room_for_profile() { + return None; + } + self.0.profiles += 1; + display_region_with_budget(region, plane, proj, ppp, &mut self.0.sampling) + } +} + /// The most curves and profiles one sketch caches per model state and view. const SKETCH_CURVES: usize = 4096; const SKETCH_PROFILES: usize = 1024; @@ -237,11 +291,7 @@ impl DisplayCache { return path.clone(); } let budget = self.budgets.entry(sketch).or_default(); - if budget.curves >= SKETCH_CURVES - || self.curves.len() >= CACHED_CURVES - || budget.sampling.remaining_vertices == 0 - || budget.sampling.remaining_nodes == 0 - { + if !budget.room_for_curve() || self.curves.len() >= CACHED_CURVES { return Arc::new(SampledPath { parts: Vec::new(), quality: SamplingQuality::BudgetLimited, vertex_count: 0 }); } let path = Arc::new(state.sketch(sketch).map_or_else( @@ -262,11 +312,7 @@ impl DisplayCache { return region.clone(); } let budget = self.budgets.entry(sketch).or_default(); - if budget.profiles >= SKETCH_PROFILES - || self.profiles.len() >= CACHED_PROFILES - || budget.sampling.remaining_vertices == 0 - || budget.sampling.remaining_nodes == 0 - { + if !budget.room_for_profile() || self.profiles.len() >= CACHED_PROFILES { return Arc::new(None); } let region = Arc::new( diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index 04ba29e90..fb666ebe6 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -486,6 +486,10 @@ fn comb_options_card(app: &mut SolveApp, ctx: &egui::Context, proj: &Proj) { /// Curvature combs (`Session::comb`): teeth and the envelope through their tips. fn combs(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { let Some(shown) = &app.session.comb else { return }; + // The teeth are the design's: not while a value is typed and the sketch is drawn at it. + if crate::dim_view::preview_world(app).is_some() { + return; + } let tk = crate::theme::Tokens::get(); for comb in &shown.teeth { let mut tips: Vec = Vec::new(); @@ -1704,7 +1708,8 @@ fn sketch_px_per_mm(plane: &Plane, proj: &Proj) -> Option { fn glyphs(app: &SolveApp, painter: &egui::Painter, proj: &Proj, hover: Option) { let Some(sid) = active_sketch(app) else { return }; - let st = crate::open_meshing::session_world(&app.session); + // While a dimension's value is typed, the glyphs sit where that value puts their geometry. + let st = crate::dim_view::preview_world(app).unwrap_or_else(|| crate::open_meshing::session_world(&app.session)); let Some(ss) = st.sketch(sid) else { return }; if ss.sketch.view.hide_constraints { GLYPHS.with(|g| g.borrow_mut().clear()); diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index ad75a2282..8471634c2 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -1178,14 +1178,17 @@ pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) { if snap.as_deref() == Some("Midpoint") && t.kind == Kind::HorizontalVertical { painter.circle_stroke(sp, 8.0, Stroke::new(2.0, tk.accent)); } - let readout = painter.text( - crate::tool_cursor::readout_at(painter, proj.rect, sp), - egui::Align2::LEFT_TOP, - format!("{}, {}", crate::prefs::show_mm(app, hp.x, 1), crate::prefs::show_mm(app, hp.y, 1)), - egui::FontId::proportional(crate::theme::Tokens::get().font_small), - tk.text_dim, - ); - crate::scenario::publish_rect("viewport:readout", readout); + // The design's coordinates: not while a value is typed and the sketch is drawn at it. + if crate::dim_view::preview_world(app).is_none() { + let readout = painter.text( + crate::tool_cursor::readout_at(painter, proj.rect, sp), + egui::Align2::LEFT_TOP, + format!("{}, {}", crate::prefs::show_mm(app, hp.x, 1), crate::prefs::show_mm(app, hp.y, 1)), + egui::FontId::proportional(crate::theme::Tokens::get().font_small), + tk.text_dim, + ); + crate::scenario::publish_rect("viewport:readout", readout); + } } if matches!(t.kind, Kind::HorizontalVertical | Kind::Dimension) { for target in &t.point_picks { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index aa818af2e..3ac2c8bf3 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -152,7 +152,7 @@ pub struct ViewportState { pub(crate) key: u64, /// Ground geometry is reused independently of the camera-dependent sketch/grid scene. shadow: std::sync::Mutex>, - sketch_slot: SceneSlot, + pub(crate) sketch_slot: SceneSlot, sketch_key: u64, physical_scale: f32, pub(crate) display: std::sync::Mutex, @@ -660,6 +660,8 @@ fn sketch_scene_key(app: &SolveApp, proj: &Proj) -> u64 { // Conflicting curves in their own colour, or as before (#7244). app.preferences.sketch_conflict_colour.hash(&mut h); (std::sync::Arc::as_ptr(&crate::open_meshing::shown_world(app)) as usize).hash(&mut h); + // The open sketch follows a dimension's typed value. + crate::dim_view::preview_solve(app).hash(&mut h); crate::sketch_display::projection_key(proj, app.viewport.pixels_per_point()).hash(&mut h); h.finish() } @@ -1832,6 +1834,18 @@ pub(crate) fn seam_width(order: Option) - 2.6 + past_g2 as f32 } +/// Rebuild the sketch scene when what it shows has changed. +pub(crate) fn refresh_sketch_scene(app: &mut SolveApp, proj: &Proj) { + let sk = sketch_scene_key(app, proj); + if sk != app.viewport.sketch_key { + let scene = build_sketch_scene(app, proj); + if let Ok(mut slot) = app.viewport.sketch_slot.lock() { + *slot = Some(scene); + } + app.viewport.sketch_key = sk; + } +} + /// View-dependent geometry: grid, sketch feedback and the ground shadow's visibility. pub(crate) fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene { let tk = Tokens::get(); @@ -1924,16 +1938,38 @@ pub(crate) fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene { } } } + // While a dimension's value is typed, the open sketch as that value leaves it. Sampled past + // the display cache, which holds the design's own solve for picking. + let typed = crate::dim_view::preview_world(app); + let ppp = app.viewport.pixels_per_point(); + let mut uncached = crate::sketch_display::Uncached::default(); for sid in visible_sketches(app) { - let Some(ss) = st.sketch(sid) else { continue }; let active = s.active_sketch == Some(sid); + let typed = typed.as_ref().filter(|_| active); + let Some(ss) = typed.unwrap_or(&st).sketch(sid) else { continue }; + // Its curves are sampled before its profiles, which share their budget: past it a fill + // goes missing rather than a curve. + let mut typed_curves: std::collections::HashMap>> = match typed { + Some(_) => (0..ss.sketch.curves.len()) + .filter(|i| solidcraft_engine::view::sketch_curve_visible(&ss.sketch, *i)) + .map(|i| (i, uncached.curve(&ss.sketch, i, &ss.plane, proj, ppp))) + .collect(), + None => std::collections::HashMap::new(), + }; // Closed profiles are shaded (lifted off a face they may lie on). let lift = ss.plane.normal() * 0.01; let profiles = if app.session.visibility.hidden_profiles.contains(&sid) || ss.sketch.view.hide_profile { &[][..] } else { &ss.profiles[..] }; let profile_fill = sc.color(c4(tk.profile_fill)); - for (index, _) in profiles.iter().enumerate() { - let display = crate::sketch_display::profile_region(app, sid, index, &ss.plane, proj); - for tri in display.as_ref().as_ref().map_or_else(Vec::new, |region| crate::sketch_display::fill_triangles(region, &mut fill_budget)) { + for (index, profile) in profiles.iter().enumerate() { + let (sampled, cached); + let display = if typed.is_some() { + sampled = uncached.profile(&profile.region, &ss.plane, proj, ppp); + &sampled + } else { + cached = crate::sketch_display::profile_region(app, sid, index, &ss.plane, proj); + cached.as_ref() + }; + for tri in display.as_ref().map_or_else(Vec::new, |region| crate::sketch_display::fill_triangles(region, &mut fill_budget)) { for q in tri { sc.trans_tri((ss.plane.to_world(q) + lift).to_f32(), [0.0; 3], profile_fill); } @@ -1951,7 +1987,10 @@ pub(crate) fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene { let conflict = if active { Conflict::of(app, &ss.sketch, &ss.report) } else { Conflict::default() }; let mut owners = Vec::new(); let lines = sketch_lines_with_sampler(&ss.sketch, &ss.plane, active, &ss.report.curve_determined, |_, index, plane| { - let parts = crate::sketch_display::curve_sample(app, sid, index, plane, proj).parts.clone(); + let parts = match typed { + Some(_) => typed_curves.remove(&index).unwrap_or_default(), + None => crate::sketch_display::curve_sample(app, sid, index, plane, proj).parts.clone(), + }; owners.extend(std::iter::repeat_n(index, parts.len())); parts }); @@ -3807,6 +3846,8 @@ pub(crate) fn highlight_key(app: &SolveApp) -> u64 { highlight_geometry_key(app).hash(&mut h); let selected = app.highlighted(); app.cam.half_height().to_bits().hash(&mut h); + // A typed dimension value hides the hovered profile (see `build_highlight`). + crate::dim_view::preview_solve(app).is_some().hash(&mut h); // Body triangles and outlines live in world space; the GPU applies the new camera. // Only sketch feedback needs projected tessellation and the profile's lift toward the eye. let projected = selected.iter().any(|s| matches!(s, Sel::Profile { .. } | Sel::SketchCurve { .. } | Sel::ExternalSketchCurve { .. })) @@ -4264,7 +4305,12 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { } } } - Sel::Profile { sketch, index } => profile_fill(&mut feedback, app, *sketch, *index, t.sel_profile, t.sel_profile_edge), + // Not while a dimension's value is typed: the design's profile would show over the + // sketch drawn at it (as for the hovered one below). Other sketches are drawn where + // they are. + Sel::Profile { sketch, index } if crate::dim_view::previewed_sketch(app) != Some(*sketch) => { + profile_fill(&mut feedback, app, *sketch, *index, t.sel_profile, t.sel_profile_edge) + } // A 3D sketch curve, in the sketch it names, or whichever sketch has it. Sel::SketchCurve { id, sketch } if st.sketches.iter().any(|ss| ss.sketch.wire_index(id).is_some()) => { let sel_edge = feedback.color(c4(t.sel_edge)); @@ -4277,7 +4323,10 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { } } // A curve picked into a dialog from another sketch than the active one names it. - Sel::ExternalSketchCurve { sketch, id } | Sel::SketchCurve { id, sketch: Some(sketch) } => { + // Not the curves of the sketch drawn at a typed value: the design has them elsewhere. + Sel::ExternalSketchCurve { sketch, id } | Sel::SketchCurve { id, sketch: Some(sketch) } + if crate::dim_view::previewed_sketch(app) != Some(*sketch) => + { let sel_edge = feedback.color(c4(t.sel_edge)); if let Some(ss) = st.sketch(*sketch) && let Some(ci) = ss.sketch.curve_index(id) @@ -4295,7 +4344,7 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { } } } - Sel::SketchCurve { id, .. } => { + Sel::SketchCurve { id, .. } if crate::dim_view::previewed_sketch(app).is_none() => { if let Some(ss) = app.session.active_sketch.and_then(|sid| st.sketch(sid)) && let Some(ci) = ss.sketch.curve_index(id) { @@ -4425,8 +4474,11 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { } } } + // While a dimension's value is typed the sketch is drawn at it: the design's profile + // would show over the resized one. Some(Hit::Profile { sketch, index }) - if !sel.iter().any(|x| matches!(x, Sel::Profile { sketch: s2, index: i2 } if s2 == sketch && i2 == index)) => + if !sel.iter().any(|x| matches!(x, Sel::Profile { sketch: s2, index: i2 } if s2 == sketch && i2 == index)) + && crate::dim_view::previewed_sketch(app) != Some(*sketch) => { profile_fill(&mut feedback, app, *sketch, *index, t.hover_profile, t.hover_profile_edge); } @@ -4713,14 +4765,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { app.viewport.build_ms = crate::now_ms() - t0; crate::frame_watch::step(app, "model scene"); } - let sk = sketch_scene_key(app, &proj); - if sk != app.viewport.sketch_key { - let scene = build_sketch_scene(app, &proj); - if let Ok(mut slot) = app.viewport.sketch_slot.lock() { - *slot = Some(scene); - } - app.viewport.sketch_key = sk; - } + refresh_sketch_scene(app, &proj); let hk = highlight_key(app); if hk != app.viewport.hl_key { let hl = build_highlight(app); @@ -4959,7 +5004,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { && !midpoint_geometry && !held && app.dialog.is_none() - && crate::dim_view::pick_reference(ui.ctx(), p, resp.double_clicked()); + && crate::dim_view::pick_reference(app, ui.ctx(), p, resp.double_clicked()); // Capture the press too: text editors lose focus before the click is released. A // running tool keeps the keyboard for its own typed values. if !held @@ -6578,9 +6623,16 @@ fn grid_centre(tf: Vec3, back: Vec3, n: Vec3, ext: f64) -> Vec3 { /// Hover feedback for the active sketch's points and curves (drawn on top of everything). fn hover_highlight(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { + // While a dimension's value is typed the open sketch is drawn at that value, but hover follows + // the design: a highlight there would trace a curve where none is drawn. Other sketches are + // drawn where they are. + let previewed = crate::dim_view::previewed_sketch(app); let col = Tokens::get().hover_profile_edge; let st = crate::open_meshing::shown_world(app); - match &app.viewport.hover { + let hover = app.viewport.hover.as_ref().filter(|h| { + !matches!(h, Hit::SketchCurve { sketch, .. } | Hit::SketchMidpoint { sketch, .. } | Hit::SketchPoint { sketch, .. } if previewed == Some(*sketch)) + }); + match hover { // Trim shows the piece it would take away instead (`sketch_tools::preview`, #3052). Some(Hit::SketchCurve { sketch, id, .. }) if crate::sketch_tools::trim_hover_piece(app, *sketch, id).is_some() => {} Some(Hit::SketchCurve { sketch, id, .. }) => { @@ -6611,6 +6663,7 @@ fn hover_highlight(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { } // The centre of the circle or arc hovered last: a cross in a ring, where a click takes it. if let Some((sketch, id)) = &app.viewport.woken_centre + && previewed != Some(*sketch) && !matches!(&app.viewport.hover, Some(Hit::SketchPoint { id: h, .. }) if h == id) && let Some(ss) = st.sketch(*sketch) && let Some(at) = ss.sketch.resolve_point(id).and_then(|i| ss.sketch.point(i)) @@ -6724,6 +6777,8 @@ fn overlays(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { } } let Some(sid) = app.session.active_sketch else { return }; + // While a dimension's value is typed, its points where that value puts them. + let st = crate::dim_view::preview_world(app).unwrap_or(st); let Some(ss) = st.sketch(sid) else { return }; let sk = &ss.sketch; let locked = sk.locked_points(); @@ -8112,6 +8167,44 @@ mod tests { ); } + /// While a dimension's value is typed only the open sketch, drawn at that value, loses its + /// hover highlight: another sketch's curve is drawn where it is, so its hover still shows. + #[test] + fn a_typed_value_keeps_the_hover_of_another_sketch() { + crate::dim_view::cancel(); + 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,30],[40,30]]})).unwrap()["curves"][0].as_str().unwrap().to_string(); + let other = h.app.session.active_sketch.unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + let own = h.app.run("sketch.line", json!({"points":[[0,0],[40,0]]})).unwrap()["curves"][0].as_str().unwrap().to_string(); + let open = h.app.session.active_sketch.unwrap(); + h.call("ui.view", json!({"view":"top"})); + h.app.cam.distance = 80.0; + h.app.cam.target = Vec3::new(20.0, 15.0, 0.0); + h.settle(); + h.step(&json!({"start":"sketch.dimension"})).unwrap(); + h.step(&json!({"click":{"world":[20,0,0]}})).unwrap(); + h.step(&json!({"text":"60"})).unwrap(); + h.settle(); + assert!(crate::dim_view::preview_solve(&h.app).is_some(), "the value is typed"); + let proj = display_proj(&h.app); + let drawn = |h: &crate::scenario::Harness| { + let ctx = crate::fonts::test_context(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + hover_highlight(&h.app, &ui.ctx().layer_painter(egui::LayerId::background()), &proj); + }); + output.textures_delta.clear(); + !output.shapes.is_empty() + }; + h.app.viewport.hover = Some(Hit::SketchCurve { sketch: other, id: line, straight: true, point: Vec3::ZERO }); + assert!(drawn(&h), "the other sketch's curve is lit under the pointer"); + h.app.viewport.hover = Some(Hit::SketchCurve { sketch: open, id: own, straight: true, point: Vec3::ZERO }); + assert!(!drawn(&h), "the open sketch's design curve is not"); + crate::dim_view::cancel(); + } + #[test] fn construction_drawing_and_hover_overlays_preserve_visible_gaps() { fn length(shape: &Shape) -> f32 {