Skip to main content

brep_render/engine_state/
sketch_input.rs

1use super::*;
2use super::sketch_panel::{sketch_constraint_signature, sketch_perpendicular_should_swap};
3
4// Sketch picking maps camera rays to plane-space coordinates. Hit tests prefer
5// points over geometry within the grab radius. Mutators refresh the live overlay
6// and mark the engine dirty; calls outside sketch mode are no-ops.
7impl EngineState {
8    /// Re-push the sketch overlay reflecting the live hover + selection. Reads the
9    /// active `sketch_edit`'s session; a no-op when not in sketch mode. Called at
10    /// the end of every S2 mutator (the reusable counterpart of the initial
11    /// [`set_sketch_overlay`](Self::set_sketch_overlay) push).
12    pub(super) fn refresh_sketch_overlay(&mut self) {
13        let world_per_pixel = self.camera.world_per_pixel();
14        let (json, preview, leaders, glyphs, arrows) = match self.sketch_edit.as_ref() {
15            Some(edit) => (
16                edit.session.overlay_json_with_state(world_per_pixel),
17                edit.session.preview_overlay_json(
18                    world_per_pixel,
19                    &edit.pending,
20                    edit.hover_uv,
21                    &edit.handdraw_stroke,
22                ),
23                edit.session.dim_leaders_overlay_json_with_state(world_per_pixel),
24                edit.session
25                    .constraint_glyphs_overlay_json_with_state(world_per_pixel),
26                edit.session.freedom_arrows_overlay_json(world_per_pixel),
27            ),
28            None => return,
29        };
30        let _ = self.set_overlay_json(&json);
31        // The draw-tool rubber-band rides in its own `sketch-preview` group so it
32        // upserts/clears independently of the solved geometry + point groups.
33        let _ = self.set_overlay_json(&preview);
34        // The dimension leaders + arrows ride in `sketch-dim-leaders`, refreshed
35        // alongside everything else (S5).
36        let _ = self.set_overlay_json(&leaders);
37        // The geometric-constraint glyphs ride in `sketch-constraint-glyphs` (S6c).
38        let _ = self.set_overlay_json(&glyphs);
39        // The hovered entity's free directions ride in `sketch-dof-arrows`.
40        let _ = self.set_overlay_json(&arrows);
41        // Remember the zoom these groups were baked at: their construction dashes,
42        // dimension arrowheads and constraint glyphs are all screen-constant, so
43        // `ensure_sketch_overlay_current` re-bakes them when it moves.
44        self.sketch_overlay_wpp = if world_per_pixel > 0.0 {
45            world_per_pixel
46        } else {
47            f64::MIN_POSITIVE
48        };
49    }
50
51    /// Per-frame upkeep for the live SKETCH overlay (driven by
52    /// [`Self::ensure_overlays_current`]) — the sketch-mode sibling of
53    /// [`Self::ensure_feature_dimension_overlay_current`]. The dimension leaders
54    /// (draggable), constraint glyphs and construction dashes are sized in PIXELS
55    /// against the camera at bake time, so a zoom leaves them stale until
56    /// something else mutates the sketch. Re-bakes on a material
57    /// `world_per_pixel` change only, so a quiet frame stays quiet.
58    pub(super) fn ensure_sketch_overlay_current(&mut self) {
59        if !self.sketch_mode() {
60            self.sketch_overlay_wpp = 0.0;
61            return;
62        }
63        let wpp = self.camera.world_per_pixel();
64        if super::overlay_wpp_stale(self.sketch_overlay_wpp, wpp) {
65            self.refresh_sketch_overlay();
66        }
67    }
68
69    /// Map CSS-pixel `(x, y)` to the active sketch plane's `(u, v)` via the camera
70    /// pick ray ∩ the sketch plane. `None` when not in sketch mode or the ray misses
71    /// the plane (parallel / behind).
72    pub fn sketch_uv_at(&self, x: f64, y: f64) -> Option<(f64, f64)> {
73        let edit = self.sketch_edit.as_ref()?;
74        let ray = self.camera.pick_ray(x, y);
75        crate::sketch::ray_plane_uv(&edit.session.plane, ray.origin, ray.dir)
76    }
77
78    /// The world-space pick tolerance at the current zoom — the ONE radius that
79    /// drives hover-highlight, click-select, drag-grab, draw-snap AND trim, for
80    /// points AND geometry, so "what highlights" is exactly "what you can grab".
81    /// Sized at 1.5× the visualized point (`POINT_SIZE_PX`) for forgiving clicking.
82    pub(super) fn sketch_pick_radius(&self) -> f64 {
83        f64::from(crate::sketch::tessellate::POINT_SIZE_PX) * 1.5 * self.camera.world_per_pixel()
84    }
85
86    /// The entity ref under CSS-pixel `(x, y)` within the grab radius, or `None`.
87    /// Priority is points > geometry > constraint: [`pick_entity`] resolves the first
88    /// two, and only when neither is in range do we consult [`pick_constraint`] (a glyph
89    /// or dimension leader that overlaps a point/edge never shadows it).
90    ///
91    /// [`pick_entity`]: crate::sketch::SketchSession::pick_entity
92    /// [`pick_constraint`]: crate::sketch::SketchSession::pick_constraint
93    fn sketch_entity_at(&self, x: f64, y: f64) -> Option<serde_json::Value> {
94        let (u, v) = self.sketch_uv_at(x, y)?;
95        let radius = self.sketch_pick_radius();
96        let wpp = self.camera.world_per_pixel();
97        self.sketch_edit.as_ref().and_then(|edit| {
98            edit.session
99                .pick_entity(u, v, radius)
100                .or_else(|| edit.session.pick_constraint(u, v, radius, wpp))
101        })
102    }
103
104    /// Set (or clear) the sketch hover, re-pushing the overlay + marking dirty only
105    /// when it actually changed. Returns whether the hover changed.
106    pub(super) fn set_sketch_hover(&mut self, new_hover: Option<serde_json::Value>) -> bool {
107        let changed = match self.sketch_edit.as_ref() {
108            Some(edit) => {
109                !crate::sketch::entity_ref_eq(edit.session.selection.hovered.as_ref(), new_hover.as_ref())
110            }
111            None => false,
112        };
113        if changed {
114            if let Some(edit) = self.sketch_edit.as_mut() {
115                edit.session.set_hover(new_hover);
116            }
117            self.refresh_sketch_overlay();
118            self.dirty = true;
119        }
120        changed
121    }
122
123    /// Update the sketch hover to the entity under CSS-pixel `(x, y)` (S2). Returns
124    /// whether the hover changed. A no-op returning `false` when not in sketch mode.
125    pub fn sketch_hover_at(&mut self, x: f64, y: f64) -> bool {
126        if self.sketch_edit.is_none() {
127            return false;
128        }
129        // Track the live cursor uv for the S3a rubber-band. In DRAW mode with pending
130        // clicks the preview follows the cursor even when the hovered ENTITY is
131        // unchanged, so force an overlay refresh there.
132        let uv = self.sketch_uv_at(x, y);
133        let preview_live = match self.sketch_edit.as_mut() {
134            Some(edit) => {
135                edit.hover_uv = uv;
136                edit.session.tool.is_some() && !edit.pending.is_empty()
137            }
138            None => false,
139        };
140        let new_hover = self.sketch_entity_at(x, y);
141        let changed = self.set_sketch_hover(new_hover);
142        if preview_live && !changed {
143            self.refresh_sketch_overlay();
144            self.dirty = true;
145        }
146        changed
147    }
148
149    /// The sketch entities a screen box from `start` to `end` (viewport CSS
150    /// px) takes: WINDOW dragged left to right (fully inside), CROSSING right
151    /// to left (touching). Empty when a corner's ray misses the plane.
152    pub fn sketch_box_refs(&self, start: (f64, f64), end: (f64, f64)) -> Vec<serde_json::Value> {
153        let corners = [(start.0, start.1), (end.0, start.1), (end.0, end.1), (start.0, end.1)];
154        let mut quad = [(0.0, 0.0); 4];
155        for (slot, (x, y)) in quad.iter_mut().zip(corners) {
156            match self.sketch_uv_at(x, y) {
157                Some(uv) => *slot = uv,
158                None => return Vec::new(),
159            }
160        }
161        self.sketch_edit
162            .as_ref()
163            .map(|edit| edit.session.box_refs(quad, end.0 < start.0))
164            .unwrap_or_default()
165    }
166
167    /// The live box preview in a sketch: the hover lights exactly what the
168    /// release would take (owner 2026-11-26). Returns how many.
169    pub fn sketch_box_preview(&mut self, start: (f64, f64), end: (f64, f64)) -> usize {
170        let refs = self.sketch_box_refs(start, end);
171        let count = refs.len();
172        let hover = (!refs.is_empty()).then(|| serde_json::Value::Array(refs));
173        if let Some(edit) = self.sketch_edit.as_mut() {
174            edit.session.set_hover(hover);
175        }
176        self.refresh_sketch_overlay();
177        self.dirty = true;
178        count
179    }
180
181    /// Apply a sketch box to the selection: replace, add or remove (see
182    /// [`super::BoxSelectMode`]). Clears the preview. Returns how many it took.
183    pub fn sketch_box_select(&mut self, start: (f64, f64), end: (f64, f64), mode: super::BoxSelectMode) -> usize {
184        let refs = self.sketch_box_refs(start, end);
185        if let Some(edit) = self.sketch_edit.as_mut() {
186            edit.session.set_hover(None);
187            if mode == super::BoxSelectMode::Replace {
188                edit.session.clear_selection();
189            }
190            for entity_ref in &refs {
191                let selected = edit.session.selection.is_selected(entity_ref);
192                if selected != (mode != super::BoxSelectMode::Remove) {
193                    edit.session.toggle_selection(entity_ref.clone());
194                }
195            }
196        }
197        self.refresh_sketch_overlay();
198        self.dirty = true;
199        refs.len()
200    }
201
202    /// Clear the sketch hover (pointer left the viewport / moved over the ViewCube).
203    /// Returns whether a hover was cleared.
204    pub fn sketch_clear_hover(&mut self) -> bool {
205        self.set_sketch_hover(None)
206    }
207
208    /// Click-select in sketch mode: pick the entity under `(x, y)`; nothing → clear
209    /// the selection. Otherwise honor the SAME "Multi-select" setting the 3D viewport
210    /// reads (`settings.multi_select`): under `ClickToggles` a plain click toggles the
211    /// hit in the set (no modifier needed for a multi-selection); under
212    /// `CtrlClick` a plain click replaces the set with just the hit and `additive`
213    /// (Ctrl/Cmd) toggles. Re-pushes the overlay + marks dirty.
214    pub fn sketch_click_at(&mut self, x: f64, y: f64, additive: bool) {
215        // Read the setting before the mutable `sketch_edit` borrow.
216        let toggles = self.settings.multi_select == crate::style::MultiSelectMode::ClickToggles;
217        let hit = self.sketch_entity_at(x, y);
218        let Some(edit) = self.sketch_edit.as_mut() else {
219            return;
220        };
221        match hit {
222            None => edit.session.clear_selection(),
223            Some(entity_ref) => {
224                if additive || toggles {
225                    edit.session.toggle_selection(entity_ref);
226                } else {
227                    edit.session.clear_selection();
228                    edit.session.toggle_selection(entity_ref);
229                }
230            }
231        }
232        self.refresh_sketch_overlay();
233        self.dirty = true;
234    }
235
236    /// Begin a point drag if a DRAGGABLE point is under `(x, y)` (S2): remember it
237    /// (id + original `fixed` flag). Returns `true` iff a point was grabbed (the
238    /// viewport routes the drag to the sketch; otherwise it orbits the camera). A
239    /// locked / fully-constrained point is not draggable, so an empty-space or
240    /// locked-point drag falls through to a camera orbit.
241    pub fn sketch_drag_begin(&mut self, x: f64, y: f64) -> bool {
242        let Some((u, v)) = self.sketch_uv_at(x, y) else {
243            return false;
244        };
245        let radius = self.sketch_pick_radius();
246        // Grab EXACTLY what's HIGHLIGHTED: the hovered entity was picked at the exact
247        // cursor position on the last move, so it is immune to egui reporting the
248        // drag-start ~6px into the gesture (the "highlighted but won't grab"
249        // intermittency — and it's what lets a whole geometry drag). A hovered LOCKED
250        // point yields `None` → the drag falls through to a camera gesture; it must
251        // NOT positional-fall-back there (that would grab a nearby UNhighlighted
252        // point). Only an EMPTY hover (a press with no prior move) falls back to a
253        // fresh positional pick.
254        let points = self.sketch_edit.as_ref().and_then(|edit| {
255            match edit.session.selection.hovered.as_ref() {
256                Some(entity_ref) => edit.session.drag_points_from_ref(entity_ref),
257                None => edit
258                    .session
259                    .pick_draggable_point(u, v, radius)
260                    .and_then(|(id, fixed)| {
261                        edit.session
262                            .doc
263                            .point(&id)
264                            .map(|p| vec![(id, p.x, p.y, fixed)])
265                    }),
266            }
267        });
268        let Some(points) = points else {
269            return self.sketch_glyph_drag_begin(u, v);
270        };
271        if let Some(edit) = self.sketch_edit.as_mut() {
272            // Snapshot ONCE at the gesture start so the whole drag is one undo step
273            // (S6a); `sketch_drag_to` never snapshots. A grab that moves nothing is
274            // discarded in `sketch_drag_end`.
275            edit.record_undo();
276            let infer_on_drop = edit.session.selection.hovered.as_ref()
277                .and_then(|entity| entity.get("kind"))
278                .and_then(serde_json::Value::as_str) != Some("geometry");
279            edit.drag = Some(SketchDrag { points, anchor: (u, v), infer_on_drop, glyph: None });
280        }
281        true
282    }
283
284    /// Drag the grabbed target to `(x, y)` (S2): pin every grabbed point at its
285    /// ORIGINAL position plus the cursor delta (`fixed = true`) so the solver anchors
286    /// the whole shape there, re-solve, then restore each point's ORIGINAL `fixed`
287    /// flag. Absolute-from-anchor (never incremental), so a rigid geometry translate
288    /// tracks the cursor 1:1 without drifting as the solver nudges points between
289    /// frames. A resolve error rolls every grabbed point back to its pre-drag coords
290    /// (the last good state). No-op when nothing is grabbed / not in sketch mode / the
291    /// ray misses the plane.
292    pub fn sketch_drag_to(&mut self, x: f64, y: f64) {
293        let Some((u, v)) = self.sketch_uv_at(x, y) else {
294            return;
295        };
296        let Some(edit) = self.sketch_edit.as_mut() else {
297            return;
298        };
299        let Some(drag) = edit.drag.clone() else {
300            return;
301        };
302        let (du, dv) = (u - drag.anchor.0, v - drag.anchor.1);
303        if let Some((cid, shift)) = &drag.glyph {
304            use crate::sketch::constraint_glyphs::{glyph_shift_entry, GlyphShift};
305            let moved = match *shift {
306                GlyphShift::Normal { normal, n } => {
307                    GlyphShift::Normal { normal, n: n + du * normal[0] + dv * normal[1] }
308                }
309                GlyphShift::Free { offset } => GlyphShift::Free { offset: [offset[0] + du, offset[1] + dv] },
310            };
311            edit.session
312                .dim_offsets
313                .insert(crate::sketch::doc::id_key(cid), glyph_shift_entry(moved));
314            self.refresh_sketch_overlay();
315            self.dirty = true;
316            return;
317        }
318        let session = &mut edit.session;
319        let before = session.doc.clone();
320        for (id, ox, oy, _) in &drag.points {
321            if let Some(p) = session.doc.point_mut(id) {
322                p.x = *ox + du;
323                p.y = *oy + dv;
324                p.fixed = true;
325            }
326        }
327        match session.resolve_drag() {
328            Ok(()) => {
329                for (id, _, _, orig_fixed) in &drag.points {
330                    if let Some(p) = session.doc.point_mut(id) {
331                        p.fixed = *orig_fixed;
332                    }
333                }
334            }
335            Err(_) => {
336                // Unsolvable target: roll every grabbed point back to its pre-drag
337                // coords + flag (keep the last good state).
338                for (id, ox, oy, orig_fixed) in &drag.points {
339                    if let Some(p) = session.doc.point_mut(id) {
340                        p.x = *ox;
341                        p.y = *oy;
342                        p.fixed = *orig_fixed;
343                    }
344                }
345            }
346        }
347        // A drag can collapse a free radius without producing a solver error.
348        // Preserve the last valid geometry, while tolerating pre-existing broken
349        // circles in imported documents so they can still be edited/repaired.
350        if newly_collapsed_radial_geometry(&before, &session.doc) {
351            session.doc = before;
352            let _ = session.resolve();
353        }
354        self.refresh_sketch_overlay();
355        self.dirty = true;
356    }
357
358    /// End a point drag (S2): clear the grab, then one final re-solve + overlay
359    /// refresh. No-op when no drag is live.
360    pub fn sketch_drag_end(&mut self) {
361        let had_grab = self
362            .sketch_edit
363            .as_ref()
364            .map_or(false, |edit| edit.drag.is_some());
365        if !had_grab {
366            return;
367        }
368        // A glyph drag moved only its stand-off: no solve, no inference. Discard the
369        // snapshot of a grab that moved nothing.
370        if let Some(edit) = self.sketch_edit.as_mut() {
371            if edit.drag.as_ref().map_or(false, |d| d.glyph.is_some()) {
372                edit.drag = None;
373                if edit.undo_stack.last().map_or(false, |snap| {
374                    snap.doc == edit.session.doc && snap.dim_offsets == edit.session.dim_offsets
375                }) {
376                    edit.undo_stack.pop();
377                }
378                self.refresh_sketch_overlay();
379                self.dirty = true;
380                return;
381            }
382        }
383        // Drop radius for constraint inference == the point grab radius (12 px in
384        // world units) — read before the `&mut` borrow of `sketch_edit`.
385        let drop_tol = self.sketch_pick_radius();
386        if let Some(edit) = self.sketch_edit.as_mut() {
387            let before = edit.session.doc.clone();
388            // Drop-time inference (S6c): a SINGLE-point drop snaps to a coincident
389            // point / point-on-line at the release position, mirroring the previous
390            // coincident-on-drop / point-on-line-on-drop inference. A whole-
391            // geometry drag never infers, even with only one movable endpoint:
392            // inference could glue or collapse the curve in one solve.
393            let dragged_single = edit.drag.as_ref().and_then(|drag| {
394                (drag.infer_on_drop && drag.points.len() == 1).then(|| drag.points[0].0.clone())
395            });
396            edit.drag = None;
397            if let Some(point_id) = dragged_single {
398                crate::sketch::infer::infer_drop_constraint(
399                    &mut edit.session.doc,
400                    &point_id,
401                    drop_tol,
402                );
403            }
404            let _ = edit.session.resolve();
405            if newly_collapsed_radial_geometry(&before, &edit.session.doc) {
406                edit.session.doc = before;
407                let _ = edit.session.resolve();
408            }
409            // Discard the drag's undo snapshot when the doc is unchanged (a mere
410            // grab-and-release, no move and no inferred constraint), so it neither
411            // pollutes undo nor clobbers redo. An inferred constraint changes the
412            // doc, so the snapshot is kept — one Ctrl+Z then undoes move+constraint.
413            if edit
414                .undo_stack
415                .last()
416                .map_or(false, |snap| snap.doc == edit.session.doc)
417            {
418                edit.undo_stack.pop();
419            }
420        }
421        self.refresh_sketch_overlay();
422        self.dirty = true;
423    }
424
425    /// Begin a constraint GLYPH drag when the hovered entity is a geometric
426    /// constraint's glyph: the press at plane `(u, v)` grabs the glyph's stand-off,
427    /// which [`sketch_drag_to`](Self::sketch_drag_to) moves with the cursor (along the
428    /// line normal for a line glyph) and stores per constraint in `dimOffsets`, so it
429    /// saves and undoes with the sketch. Returns whether a glyph was grabbed.
430    fn sketch_glyph_drag_begin(&mut self, u: f64, v: f64) -> bool {
431        let wpp = self.camera.world_per_pixel();
432        let Some(edit) = self.sketch_edit.as_mut() else {
433            return false;
434        };
435        let Some(hovered) = edit.session.selection.hovered.clone() else {
436            return false;
437        };
438        if hovered.get("kind").and_then(serde_json::Value::as_str) != Some("constraint") {
439            return false;
440        }
441        let Some(cid) = hovered.get("id").cloned() else {
442            return false;
443        };
444        let key = crate::sketch::doc::id_key(&cid);
445        let shift = edit
446            .session
447            .doc
448            .constraints
449            .iter()
450            .find(|c| c.raw.get("id").map(crate::sketch::doc::id_key).as_deref() == Some(key.as_str()))
451            .and_then(|c| {
452                crate::sketch::constraint_glyphs::constraint_glyph_shift(
453                    c,
454                    &edit.session.doc,
455                    &edit.session.dim_offsets,
456                    wpp,
457                )
458            });
459        let Some(shift) = shift else {
460            return false;
461        };
462        edit.record_undo();
463        edit.drag = Some(SketchDrag {
464            points: Vec::new(),
465            anchor: (u, v),
466            infer_on_drop: false,
467            glyph: Some((cid, shift)),
468        });
469        true
470    }
471
472    /// The hovered point's or geometry's remaining freedoms, for the hover readout
473    /// (`"2 DOF free"`, `"Fully constrained"`), or `None` when nothing such is
474    /// hovered.
475    pub fn sketch_hover_freedom_label(&self) -> Option<String> {
476        let edit = self.sketch_edit.as_ref()?;
477        let hovered = edit.session.selection.hovered.as_ref()?;
478        crate::sketch::freedom::freedom_label(&edit.session.doc, &edit.session.diagnostics, hovered)
479    }
480
481    /// The geometric-constraint glyphs as drawn, for the verifier: per glyph its
482    /// constraint id, its centre in CSS pixels, its size (box diagonal) in pixels,
483    /// and its saved stand-off (`dimOffsets` entry, `null` when at its default place).
484    /// `[]` outside sketch mode.
485    pub fn sketch_glyphs_json(&self) -> String {
486        let Some(edit) = self.sketch_edit.as_ref() else {
487            return "[]".to_string();
488        };
489        let wpp = self.camera.world_per_pixel();
490        let session = &edit.session;
491        let glyphs: Vec<serde_json::Value> = crate::sketch::constraint_glyphs::glyph_layout_segments(
492            &session.doc,
493            &session.dim_offsets,
494            wpp,
495        )
496        .into_iter()
497        .filter_map(|(index, segments)| {
498            let c = &session.doc.constraints[index];
499            let id = c.raw.get("id")?.clone();
500            let mut lo = [f64::INFINITY; 2];
501            let mut hi = [f64::NEG_INFINITY; 2];
502            for (a, b) in &segments {
503                for p in [a, b] {
504                    let w = session.plane.to_world(p[0], p[1]);
505                    let (x, y, _) = self.camera.project(w);
506                    lo = [lo[0].min(x), lo[1].min(y)];
507                    hi = [hi[0].max(x), hi[1].max(y)];
508                }
509            }
510            let key = crate::sketch::doc::id_key(&id);
511            Some(serde_json::json!({
512                "id": id,
513                "type": c.ctype(),
514                "center": [(lo[0] + hi[0]) / 2.0, (lo[1] + hi[1]) / 2.0],
515                "sizePx": (hi[0] - lo[0]).hypot(hi[1] - lo[1]),
516                "offset": session.dim_offsets.get(&key).cloned(),
517            }))
518        })
519        .collect();
520        serde_json::Value::Array(glyphs).to_string()
521    }
522
523    /// [`sketch_reset_glyph_offset`](Self::sketch_reset_glyph_offset) for the
524    /// constraint glyph under CSS-pixel `(x, y)`, if any.
525    pub fn sketch_reset_glyph_offset_at(&mut self, x: f64, y: f64) -> bool {
526        let hit = self.sketch_entity_at(x, y);
527        match hit {
528            Some(entity) if entity.get("kind").and_then(serde_json::Value::as_str) == Some("constraint") => {
529                let id = entity.get("id").cloned().unwrap_or(serde_json::Value::Null);
530                self.sketch_reset_glyph_offset(&id)
531            }
532            _ => false,
533        }
534    }
535
536    /// Put a constraint's glyph back at its default place (double-click on the glyph):
537    /// drop its saved stand-off. One undo step; returns whether anything changed.
538    pub fn sketch_reset_glyph_offset(&mut self, constraint_id: &serde_json::Value) -> bool {
539        let key = crate::sketch::doc::id_key(constraint_id);
540        let Some(edit) = self.sketch_edit.as_mut() else {
541            return false;
542        };
543        let is_glyph = edit
544            .session
545            .doc
546            .constraints
547            .iter()
548            .find(|c| c.raw.get("id").map(crate::sketch::doc::id_key).as_deref() == Some(key.as_str()))
549            .map_or(false, |c| !matches!(c.ctype(), Some("⟺") | Some("↥") | Some("∠")) && !c.temporary());
550        if !is_glyph || !edit.session.dim_offsets.contains_key(&key) {
551            return false;
552        }
553        edit.record_undo();
554        edit.session.dim_offsets.remove(&key);
555        self.refresh_sketch_overlay();
556        self.dirty = true;
557        true
558    }
559
560    /// The number of selected sketch entities (0 when not in sketch mode) — the mode
561    /// bar / verifier readout.
562    pub fn sketch_selection_count(&self) -> usize {
563        self.sketch_edit
564            .as_ref()
565            .map_or(0, |edit| edit.session.selection.items.len())
566    }
567
568    /// The number of selected CONSTRAINTS (refs whose `kind` is `"constraint"`; 0 when
569    /// not in sketch mode) — the `__brepSketch` verifier readout for constraint
570    /// selection + delete.
571    pub fn sketch_selected_constraint_count(&self) -> usize {
572        self.sketch_edit.as_ref().map_or(0, |edit| {
573            edit.session
574                .selection.items
575                .iter()
576                .filter(|r| r.get("kind").and_then(|v| v.as_str()) == Some("constraint"))
577                .count()
578        })
579    }
580}
581
582fn radial_distance(doc: &crate::sketch::SketchDoc, points: &[serde_json::Value]) -> f64 {
583    match (doc.point(&points[0]), doc.point(&points[1])) {
584        (Some(a), Some(b)) => (b.x - a.x).hypot(b.y - a.y),
585        _ => 0.0,
586    }
587}
588
589fn newly_collapsed_radial_geometry(
590    before: &crate::sketch::SketchDoc,
591    after: &crate::sketch::SketchDoc,
592) -> bool {
593    before.geometries.iter().any(|g| {
594        matches!(g.geom_type.as_str(), "circle" | "arc")
595            && g.points.len() >= 2
596            && radial_distance(before, &g.points) > 1e-5
597            && radial_distance(after, &g.points) <= 1e-5
598    })
599}
600
601// ===========================================================================
602// Sketch draw tools (S3a) — primitive placement: point / line / rect / circle / arc.
603//
604// A click-state machine over the active `self.sketch_edit`. The active tool lives
605// on `session.tool` ("select"/None = selection mode, S2); a DRAW tool routes clicks
606// to `sketch_tool_click_at` (pixel → plane uv via the same S2 `sketch_uv_at`, then
607// `sketch_tool_place_uv`). Points/geometries are minted through `SketchDoc`
608// (`next_point_id`/`next_geometry_id` + `snap_or_add_point`, so shared vertices
609// coincide). Each placement re-solves (swallowing solve errors), re-pushes the
610// overlay (incl. the rubber-band preview), and marks dirty. The bezier tool has a
611// second mode on the same click: idle, a click ON an existing spline REFINES it
612// rather than starting a new one (`crate::sketch::spline`). Kept in ONE appended
613// block so concurrent edits to the primary impl land clean.
614// ===========================================================================
615impl EngineState {
616    /// Set (or clear) the active draw tool: `"select"`/`None` → selection mode (S2);
617    /// `"point"|"line"|"rect"|"circle"|"arc"|"bezier"` arm the corresponding draw
618    /// tool; `"handdraw"` arms the freehand stroke tool (S6b-3); `"trim"` arms the
619    /// trim tool (S6b); `"pickEdges"` arms the external-edge link tool (S6b-2). Clears
620    /// any in-progress click buffer + preview and refreshes the overlay. No-op when not
621    /// in sketch mode.
622    pub fn sketch_set_tool(&mut self, tool: Option<&str>) {
623        let normalized = normalize_sketch_tool(tool);
624        if let Some(edit) = self.sketch_edit.as_mut() {
625            edit.session.tool = normalized;
626            edit.pending.clear();
627            edit.hover_uv = None;
628            edit.handdraw_stroke.clear();
629        } else {
630            return;
631        }
632        // A context edge lit for pickEdges is only that tool's to show.
633        if self.sketch_active_tool() != Some("pickEdges") {
634            self.hover_context(None);
635        }
636        self.refresh_sketch_overlay();
637        self.dirty = true;
638    }
639
640    /// The active draw tool (`"point"|"line"|"rect"|"circle"|"arc"`), or `None` in
641    /// selection mode / when not in sketch mode.
642    pub fn sketch_active_tool(&self) -> Option<&str> {
643        self.sketch_edit
644            .as_ref()
645            .and_then(|edit| edit.session.tool.as_deref())
646    }
647
648    /// The number of in-progress draw-tool clicks buffered (0 in selection mode /
649    /// when not in sketch mode) — the UI/preview + verifier readout.
650    pub fn sketch_pending_len(&self) -> usize {
651        self.sketch_edit.as_ref().map_or(0, |edit| edit.pending.len())
652    }
653
654    /// A draw-tool click at CSS-pixel `(x, y)`: map to plane uv (the S2 pixel→plane
655    /// math) and drive the tool state machine. No-op when not in sketch mode, in
656    /// selection mode, or the ray misses the plane.
657    pub fn sketch_tool_click_at(&mut self, x: f64, y: f64) {
658        // pickEdges (S6b-2) acts on the 3D SCENE EDGE under the cursor — it needs the
659        // PIXEL coords (a scene pick), not a plane uv, so short-circuit before the
660        // pixel→plane projection (which would drop clicks that miss the plane).
661        if self.sketch_active_tool() == Some("pickEdges") {
662            self.sketch_pick_edge_at(x, y);
663            return;
664        }
665        let Some((u, v)) = self.sketch_uv_at(x, y) else {
666            return;
667        };
668        self.sketch_tool_place_uv(u, v);
669    }
670
671    /// The per-tool placement logic, in plane `(u, v)` (the headless-testable core
672    /// `sketch_tool_click_at` delegates to). Snaps to existing points within the grab
673    /// radius so shared vertices coincide; appends geometry and re-solves when a
674    /// primitive completes; carries the line chain via `pending`.
675    pub fn sketch_tool_place_uv(&mut self, u: f64, v: f64) {
676        let radius = self.sketch_pick_radius();
677        // Selection mode (no tool / "select") never places. Read the tool without
678        // holding a borrow so the trim branch can call back into `self`.
679        let tool = match self.sketch_edit.as_ref() {
680            Some(edit) => match edit.session.tool.clone() {
681                Some(tool) => tool,
682                None => return,
683            },
684            None => return,
685        };
686        // Trim (S6b) is a click tool that acts IMMEDIATELY on the geometry under the
687        // cursor — it never buffers `pending` or places a point. It owns its own undo
688        // snapshot (and pops it on a no-op), so short-circuit before the draw path.
689        if tool == "trim" {
690            self.sketch_trim_uv(u, v);
691            return;
692        }
693        // Fillet and chamfer act on the corner under the cursor at once, owning
694        // their undo snapshot like trim.
695        if tool == "fillet" || tool == "chamfer" {
696            self.sketch_corner_uv(u, v, tool == "fillet");
697            return;
698        }
699        // pickEdges is NOT a uv-placement tool — it acts on a 3D scene edge (routed via
700        // pixel coords in `sketch_tool_click_at`), so a stray uv place is a no-op here.
701        if tool == "pickEdges" {
702            return;
703        }
704        // handdraw (S6b-3) captures a DRAG as a stroke (routed via `sketch_handdraw_*`),
705        // not a click-placed point — a plain click is a no-op (and never records a dead
706        // undo step here, since we return before `record_undo`).
707        if tool == "handdraw" {
708            return;
709        }
710        let Some(edit) = self.sketch_edit.as_mut() else {
711            return;
712        };
713        // Check the SNAP RESULT, not just the cursor: a nearby radius click can
714        // reuse the center id. Keep waiting for a valid radius/end without adding
715        // points or an undo step. Arc endpoints must also be off the center.
716        if matches!(tool.as_str(), "circle" | "arc") && !edit.pending.is_empty() {
717            let doc = &edit.session.doc;
718            let Some(center) = doc.point(&edit.pending[0]) else { return; };
719            let snapped = doc.points.iter()
720                .filter(|p| (p.x - u).hypot(p.y - v) <= radius)
721                .min_by(|a, b| (a.x - u).hypot(a.y - v).total_cmp(&(b.x - u).hypot(b.y - v)));
722            let (x, y) = snapped.map_or((u, v), |p| (p.x, p.y));
723            let distance = (x - center.x).hypot(y - center.y);
724            if !distance.is_finite() || distance <= 1e-5 {
725                return;
726            }
727        }
728        if tool == "text" && !edit.pending.is_empty() {
729            if let Some(a) = edit.session.doc.point(&edit.pending[0]) {
730                if (u-a.x).abs() < 1e-5 || (v-a.y).abs() < 1e-5 { return; }
731            }
732        }
733        // A draw tool is active → this click WILL mutate the doc (a point and/or a
734        // geometry); snapshot for undo before it does (S6a).
735        edit.record_undo();
736        let doc = &mut edit.session.doc;
737        match tool.as_str() {
738            "point" => {
739                doc.snap_or_add_point(u, v, radius);
740                edit.pending.clear();
741            }
742            "line" => {
743                if edit.pending.is_empty() {
744                    let a = doc.snap_or_add_point(u, v, radius);
745                    edit.pending.push(a);
746                } else {
747                    let start = edit.pending.last().cloned().expect("pending non-empty");
748                    let end = doc.snap_or_add_point(u, v, radius);
749                    push_sketch_geometry(doc, "line", vec![start, end.clone()]);
750                    // Continue the chain: the just-placed end is the next start.
751                    edit.pending = vec![end];
752                }
753            }
754            "rect" | "text" => {
755                let radius = if tool == "text" { -1.0 } else { radius };
756                if edit.pending.is_empty() {
757                    let a = doc.snap_or_add_point(u, v, radius);
758                    edit.pending.push(a);
759                } else {
760                    let a_id = edit.pending[0].clone();
761                    let Some((ax, ay)) = doc.point(&a_id).map(|p| (p.x, p.y)) else {
762                        edit.pending.clear();
763                        return;
764                    };
765                    let (ax, ay, bx, by) = if tool == "text" {
766                        (ax.min(u), ay.min(v), ax.max(u), ay.max(v))
767                    } else { (ax, ay, u, v) };
768                    if tool == "text" {
769                        if let Some(p) = doc.point_mut(&a_id) { p.x = ax; p.y = ay; }
770                    }
771                    // Corners A=(ax,ay), (bx,ay), (bx,by), (ax,by) → 4 closed lines.
772                    let b1 = doc.snap_or_add_point(bx, ay, radius);
773                    let b2 = doc.snap_or_add_point(bx, by, radius);
774                    let b3 = doc.snap_or_add_point(ax, by, radius);
775                    push_sketch_geometry(doc, "line", vec![a_id.clone(), b1.clone()]);
776                    push_sketch_geometry(doc, "line", vec![b1.clone(), b2.clone()]);
777                    push_sketch_geometry(doc, "line", vec![b2.clone(), b3.clone()]);
778                    push_sketch_geometry(doc, "line", vec![b3.clone(), a_id.clone()]);
779                    // Keep the rectangle rectangular under drag: three ⟂ constraints on
780                    // the adjacent-edge pairs (the 4th corner's right angle follows from
781                    // the closed loop). This is the minimal rigid set — it removes 3 DOF
782                    // from the 8-DOF four-corner quad, leaving position (2) + rotation (1)
783                    // + width + height = 5 DOF, so the sketch is neither over-constrained
784                    // nor conflicting.
785                    if tool == "text" {
786                        let corners = vec![a_id.clone(), b1.clone(), b2.clone(), b3.clone()];
787                        let text_id = doc.next_geometry_id();
788                        for edge in doc.geometries.iter_mut().rev().take(4) {
789                            edge.extra.insert("construction".into(), serde_json::json!(true));
790                            edge.extra.insert("textFrame".into(), text_id.clone());
791                        }
792                        for id in &corners { if let Some(p) = doc.point_mut(id) { p.construction = true; } }
793                        doc.geometries.push(crate::sketch::text::object(text_id.clone(), corners, "Text", "Ubuntu Light").expect("bundled default font"));
794                        edit.session.selection.items = vec![crate::sketch::session::geometry_ref(&text_id)];
795                        edit.session.tool = None;
796                    }
797                    push_rect_perpendicular_constraints(doc, [a_id, b1, b2, b3]);
798                    edit.pending.clear();
799                }
800            }
801            "circle" => {
802                if edit.pending.is_empty() {
803                    let c = doc.snap_or_add_point(u, v, radius);
804                    edit.pending.push(c);
805                } else {
806                    let center = edit.pending[0].clone();
807                    let r = doc.snap_or_add_point(u, v, radius);
808                    push_sketch_geometry(doc, "circle", vec![center, r]);
809                    edit.pending.clear();
810                }
811            }
812            "arc" => {
813                // Clicks: center, start, then end completes [center, start, end].
814                if edit.pending.len() < 2 {
815                    let p = doc.snap_or_add_point(u, v, radius);
816                    edit.pending.push(p);
817                } else {
818                    let center = edit.pending[0].clone();
819                    let start = edit.pending[1].clone();
820                    let end = doc.snap_or_add_point(u, v, radius);
821                    push_sketch_geometry(doc, "arc", vec![center, start, end]);
822                    edit.pending.clear();
823                }
824            }
825            "bezier" => {
826                // Cubic Bezier: 4 clicks place end0, ctrl0, ctrl1, end1 (in order).
827                // The 4th click commits the span [p0, p1, p2, p3] PLUS two dashed
828                // construction guide lines for the control handles (end0→ctrl0 and
829                // end1→ctrl1), matching the previous basic bezier tool. One INVOCATION
830                // authors one span; a chained multi-span polygon (3n+1 ids in ONE
831                // geometry — the model the solver, tessellator and profile builder all
832                // already read) is grown by insertion instead, below.
833                //
834                // IDLE + a click on an existing spline = refine it: subdivide the
835                // clicked span so a new anchor lands under the cursor without the curve
836                // moving (see `crate::sketch::spline`). Only while `pending` is empty —
837                // mid-draw the click still means "place the next control point", so a
838                // new spline can be drawn across an old one. A refusal (nothing under
839                // the cursor, a point winning the pick, a degenerate span) falls
840                // through to that placement, which mutates the doc too, so the
841                // `record_undo` above never leaves a dead step either way.
842                let refined = edit.pending.is_empty() && spline_insert_anchor(doc, u, v, radius);
843                if !refined {
844                    if edit.pending.len() < 3 {
845                        let p = doc.snap_or_add_point(u, v, radius);
846                        edit.pending.push(p);
847                    } else {
848                        let p0 = edit.pending[0].clone();
849                        let p1 = edit.pending[1].clone();
850                        let p2 = edit.pending[2].clone();
851                        let p3 = doc.snap_or_add_point(u, v, radius);
852                        push_sketch_geometry(
853                            doc,
854                            "bezier",
855                            vec![p0.clone(), p1.clone(), p2.clone(), p3.clone()],
856                        );
857                        // Construction guide lines (dashed, non-modeling) for the two
858                        // control handles — separate freshly minted geometry ids.
859                        push_sketch_construction_line(doc, vec![p0, p1]);
860                        push_sketch_construction_line(doc, vec![p3, p2]);
861                        edit.pending.clear();
862                    }
863                }
864            }
865            _ => return,
866        }
867        // Every draw click mutates the doc (a new point and/or geometry); re-solve so
868        // coordinates + mobility stay fresh, keeping the doc if the solve fails.
869        self.resolve_active_sketch("draw-tool");
870        self.refresh_sketch_overlay();
871        self.dirty = true;
872    }
873
874    /// Abort the in-progress draw geometry (Escape / right-click): clear the pending
875    /// clicks + preview and refresh. No-op when not in sketch mode.
876    pub fn sketch_tool_cancel(&mut self) {
877        if let Some(edit) = self.sketch_edit.as_mut() {
878            edit.pending.clear();
879        } else {
880            return;
881        }
882        self.refresh_sketch_overlay();
883        self.dirty = true;
884    }
885}
886
887/// Normalize a tool name to the stored form: `None`/`"select"`/`""` → selection mode
888/// (`None`), else the tool string (`"point"|"line"|"rect"|"circle"|"arc"|"bezier"|
889/// "trim"|"pickEdges"|"handdraw"`).
890fn normalize_sketch_tool(tool: Option<&str>) -> Option<String> {
891    match tool {
892        None | Some("select") | Some("") => None,
893        Some(t) => Some(t.to_string()),
894    }
895}
896
897/// Append a geometry to a sketch doc with a freshly minted id (the caller passes the
898/// solver `type` — `rect` corners are pushed as `line`s), carrying an explicit
899/// `construction: false` so it matches the authored shape and round-trips.
900fn push_sketch_geometry(
901    doc: &mut crate::sketch::SketchDoc,
902    geom_type: &str,
903    points: Vec<serde_json::Value>,
904) {
905    let id = doc.next_geometry_id();
906    let mut extra = serde_json::Map::new();
907    extra.insert("construction".to_string(), serde_json::Value::Bool(false));
908    doc.geometries.push(crate::sketch::SketchGeometry {
909        id,
910        geom_type: geom_type.to_string(),
911        points,
912        extra,
913    });
914}
915
916/// Append a CONSTRUCTION `line` geometry (dashed, non-modeling — `construction: true`)
917/// with a freshly minted id: the bezier tool's control-handle guide lines. Mirrors
918/// [`push_sketch_geometry`] but flips the construction flag so the line renders dashed
919/// and is excluded from profiles while still being constrainable.
920fn push_sketch_construction_line(
921    doc: &mut crate::sketch::SketchDoc,
922    points: Vec<serde_json::Value>,
923) {
924    let id = doc.next_geometry_id();
925    let mut extra = serde_json::Map::new();
926    extra.insert("construction".to_string(), serde_json::Value::Bool(true));
927    doc.geometries.push(crate::sketch::SketchGeometry {
928        id,
929        geom_type: "line".to_string(),
930        points,
931        extra,
932    });
933}
934
935/// Subdivide the spline under the plane click `(u, v)` — the bezier tool's "refine
936/// what I already drew" click. Delegates the pick + de Casteljau split to
937/// [`crate::sketch::spline::insert_anchor`] (which decides whether the click is a
938/// subdivision at all) and, when it lands, hangs the SAME two dashed construction
939/// guides on the new anchor that the 4-click path hangs on the two drawn ends:
940/// anchor→handle on each side. Consistency is the whole point — after a refine every
941/// anchor of the spline, drawn or inserted, has a guide to each of its neighbouring
942/// handles, so the handles stay visible and constrainable (a tangent on a guide is
943/// how a spline is made to meet a line smoothly) and a refined curve is
944/// indistinguishable from one drawn that way. The two ORIGINAL guides still read
945/// correctly without being touched, because the split reuses the end handles' ids and
946/// they remain the handles adjacent to those same two end anchors.
947///
948/// Returns whether the click was consumed as an insertion; `false` means the caller
949/// should treat it as an ordinary control-point placement.
950fn spline_insert_anchor(doc: &mut crate::sketch::SketchDoc, u: f64, v: f64, radius: f64) -> bool {
951    let Some(added) = crate::sketch::spline::insert_anchor(doc, u, v, radius) else {
952        return false;
953    };
954    push_sketch_construction_line(doc, vec![added.anchor.clone(), added.before]);
955    push_sketch_construction_line(doc, vec![added.anchor, added.after]);
956    true
957}
958
959/// Append the three perpendicular (`⟂`) constraints that keep a freshly drawn
960/// rectangle rectangular when a corner is dragged. `corners` are the rect's four
961/// points in loop order `[a, b1, b2, b3]` (edges a→b1, b1→b2, b2→b3, b3→a); the
962/// constraints go on the adjacent-edge pairs sharing corners b1 / b2 / b3. The fourth
963/// corner (a) is left implied — a closed quad with three right angles is a rectangle —
964/// so this is the MINIMAL rigid set (3 equations, no over-constraint / redundancy).
965///
966/// Each `⟂` stores the two edges' endpoint pairs `[l1a, l1b, l2a, l2b]`, swap-oriented
967/// exactly like a palette-added perpendicular ([`sketch_build_and_add_constraint`]), and
968/// is deduped on its signature. No-op unless the four corners are all distinct (a
969/// degenerate rect whose corners snapped together would otherwise carry a `⟂` on a
970/// zero-length edge, which is meaningless and can wedge the solver).
971fn push_rect_perpendicular_constraints(
972    doc: &mut crate::sketch::SketchDoc,
973    corners: [serde_json::Value; 4],
974) {
975    use crate::sketch::doc::id_key;
976    let [a, b1, b2, b3] = corners;
977    let keys = [id_key(&a), id_key(&b1), id_key(&b2), id_key(&b3)];
978    for i in 0..keys.len() {
979        for j in (i + 1)..keys.len() {
980            if keys[i] == keys[j] {
981                return; // two corners collapsed → skip (no zero-length-edge ⟂).
982            }
983        }
984    }
985    // Adjacent edge pairs sharing corner b1 / b2 / b3.
986    let pairs = [
987        [a.clone(), b1.clone(), b1.clone(), b2.clone()],
988        [b1.clone(), b2.clone(), b2.clone(), b3.clone()],
989        [b2.clone(), b3.clone(), b3.clone(), a.clone()],
990    ];
991    for pair in pairs {
992        let mut pts = pair.to_vec();
993        if sketch_perpendicular_should_swap(doc, &pts) {
994            pts.swap(0, 1);
995        }
996        push_geometric_constraint(doc, "⟂", pts);
997    }
998}
999
1000/// Append a NON-dimensional geometric constraint (`type` + ordered `points`) with a
1001/// freshly minted id and the same base fields a palette-added constraint carries
1002/// (`labelX`/`labelY` = 0, `displayStyle` = "", `value` = null, `valueNeedsSetup` =
1003/// true — see [`sketch_build_and_add_constraint`]). Deduped on `type + sorted-points`
1004/// (the solver runs with `remove_implied_duplicates: false`, so this is the only
1005/// dedup); a no-op on a duplicate.
1006fn push_geometric_constraint(
1007    doc: &mut crate::sketch::SketchDoc,
1008    ctype: &str,
1009    points: Vec<serde_json::Value>,
1010) {
1011    let sig = sketch_constraint_signature(ctype, &points);
1012    let duplicate = doc.constraints.iter().any(|c| match c.ctype() {
1013        Some(t) => sketch_constraint_signature(t, c.points()) == sig,
1014        None => false,
1015    });
1016    if duplicate {
1017        return;
1018    }
1019    let id = doc.next_constraint_id();
1020    let mut raw = serde_json::Map::new();
1021    raw.insert("id".to_string(), id);
1022    raw.insert("type".to_string(), serde_json::Value::String(ctype.to_string()));
1023    raw.insert("points".to_string(), serde_json::Value::Array(points));
1024    raw.insert("labelX".to_string(), serde_json::Value::from(0));
1025    raw.insert("labelY".to_string(), serde_json::Value::from(0));
1026    raw.insert(
1027        "displayStyle".to_string(),
1028        serde_json::Value::String(String::new()),
1029    );
1030    raw.insert("value".to_string(), serde_json::Value::Null);
1031    raw.insert("valueNeedsSetup".to_string(), serde_json::Value::Bool(true));
1032    doc.constraints.push(crate::sketch::SketchConstraint { raw });
1033}
1034
1035// ===========================================================================
1036// Auto-constrain — infer the constraints implied by the rough-in geometry.
1037//
1038// A one-click "constrain what I drew": snap nearly-axis-aligned lines to `━`/`│` and
1039// near-coincident points to `≡`, going through the same `push_geometric_constraint`
1040// dedup the palette uses so the solver picks them up and a re-run is idempotent.
1041// ===========================================================================
1042
1043/// Auto-constrain tolerances (v1 constants; a future pass could surface them as
1044/// settings). A line whose direction is within [`AUTO_HV_ANGLE_TOL_DEG`] of an axis
1045/// gets a horizontal/vertical constraint — loose enough to catch a rough-in, far
1046/// below the slope a user clearly intended.
1047const AUTO_HV_ANGLE_TOL_DEG: f64 = 3.0;
1048/// Two points auto-snap to COINCIDENT when within this fraction of the sketch's
1049/// bounding-box diagonal (scale-invariant, so it works at any sketch size)…
1050const AUTO_COINCIDENT_FRAC: f64 = 0.01;
1051/// …floored at this absolute distance for a tiny or single-cluster sketch.
1052const AUTO_COINCIDENT_ABS: f64 = 1e-4;
1053
1054/// Infer + add the constraints implied by the current geometry: `━`/`│` on
1055/// nearly-axis-aligned lines and `≡` between near-coincident points. Conservative —
1056/// never adds an unsatisfiable constraint on two already-fixed points, never collapses
1057/// a curve by coinciding its own endpoints, never re-adds a coincident already implied
1058/// (directly or transitively), and dedups H/V via [`push_geometric_constraint`]. So a
1059/// second pass adds nothing (idempotent). Returns the number of constraints added; the
1060/// caller re-solves.
1061pub(super) fn auto_constrain_doc(doc: &mut crate::sketch::SketchDoc) -> usize {
1062    use crate::sketch::doc::id_key;
1063    use serde_json::Value;
1064    use std::collections::{HashMap, HashSet};
1065
1066    let before = doc.constraints.len();
1067
1068    // ---- Horizontal / vertical on nearly-axis-aligned lines. ----
1069    // Threshold on |unit component off the axis| = |sin(angle deviation)|.
1070    let hv_sin_tol = AUTO_HV_ANGLE_TOL_DEG.to_radians().sin();
1071    let mut hv: Vec<(&str, Vec<Value>)> = Vec::new();
1072    for g in &doc.geometries {
1073        if g.geom_type != "line" || g.points.len() < 2 {
1074            continue;
1075        }
1076        let (Some(a), Some(b)) = (doc.point(&g.points[0]), doc.point(&g.points[1])) else {
1077            continue;
1078        };
1079        // Skip a line pinned at BOTH ends (no freedom → an H/V that isn't already
1080        // exactly true is unsatisfiable). This also excludes linked reference lines,
1081        // whose endpoints are all fixed.
1082        if a.fixed && b.fixed {
1083            continue;
1084        }
1085        let (dx, dy) = (b.x - a.x, b.y - a.y);
1086        let len = dx.hypot(dy);
1087        if len < 1e-9 {
1088            continue;
1089        }
1090        // Skip a line that already carries an H or V constraint on these endpoints
1091        // (never add the opposite one; keeps the pass idempotent).
1092        let mut keys: Vec<String> = g.points[..2].iter().map(id_key).collect();
1093        keys.sort();
1094        let already_hv = doc.constraints.iter().any(|c| {
1095            if !matches!(c.ctype(), Some("━") | Some("│")) {
1096                return false;
1097            }
1098            let mut k: Vec<String> = c.points().iter().map(id_key).collect();
1099            k.sort();
1100            k == keys
1101        });
1102        if already_hv {
1103            continue;
1104        }
1105        let (ux, uy) = (dx / len, dy / len);
1106        if uy.abs() <= hv_sin_tol {
1107            hv.push(("━", vec![g.points[0].clone(), g.points[1].clone()]));
1108        } else if ux.abs() <= hv_sin_tol {
1109            hv.push(("│", vec![g.points[0].clone(), g.points[1].clone()]));
1110        }
1111    }
1112    for (ct, pts) in hv {
1113        push_geometric_constraint(doc, ct, pts);
1114    }
1115
1116    // ---- Coincident between near-coincident, mergeable point pairs. ----
1117    let n = doc.points.len();
1118    if n >= 2 {
1119        fn find(parent: &mut [usize], mut x: usize) -> usize {
1120            while parent[x] != x {
1121                parent[x] = parent[parent[x]]; // path halving
1122                x = parent[x];
1123            }
1124            x
1125        }
1126        fn union(parent: &mut [usize], a: usize, b: usize) {
1127            let (ra, rb) = (find(parent, a), find(parent, b));
1128            if ra != rb {
1129                parent[ra] = rb;
1130            }
1131        }
1132
1133        // Union-find over point indices, SEEDED with the existing coincidents so we
1134        // never re-add one (directly or transitively).
1135        let index: HashMap<String, usize> = doc
1136            .points
1137            .iter()
1138            .enumerate()
1139            .map(|(i, p)| (id_key(&p.id), i))
1140            .collect();
1141        let mut parent: Vec<usize> = (0..n).collect();
1142        for c in &doc.constraints {
1143            if c.ctype() == Some("≡") {
1144                let pts = c.points();
1145                if let (Some(p0), Some(p1)) = (pts.first(), pts.get(1)) {
1146                    if let (Some(&i), Some(&j)) = (index.get(&id_key(p0)), index.get(&id_key(p1))) {
1147                        union(&mut parent, i, j);
1148                    }
1149                }
1150            }
1151        }
1152
1153        // Distance tolerance relative to the sketch extent — the user's points only:
1154        // the part-origin reference may sit far from the drawing and must not widen it.
1155        let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
1156        for p in doc.points.iter().filter(|p| !brep_kernel::is_sketch_origin_point_id(&p.id)) {
1157            lo[0] = lo[0].min(p.x);
1158            lo[1] = lo[1].min(p.y);
1159            hi[0] = hi[0].max(p.x);
1160            hi[1] = hi[1].max(p.y);
1161        }
1162        let extent = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2)).sqrt();
1163        let tol = (extent * AUTO_COINCIDENT_FRAC).max(AUTO_COINCIDENT_ABS);
1164
1165        // Point-key set per geometry — skip a pair that are the two ends of the SAME
1166        // curve (coinciding them would collapse it).
1167        let geo_sets: Vec<HashSet<String>> = doc
1168            .geometries
1169            .iter()
1170            .map(|g| g.points.iter().map(id_key).collect())
1171            .collect();
1172
1173        let mut coincidents: Vec<Vec<Value>> = Vec::new();
1174        for i in 0..n {
1175            for j in (i + 1)..n {
1176                let (pi, pj) = (&doc.points[i], &doc.points[j]);
1177                if pi.fixed && pj.fixed {
1178                    continue; // both pinned → a coincident is unsatisfiable
1179                }
1180                let d = ((pi.x - pj.x).powi(2) + (pi.y - pj.y).powi(2)).sqrt();
1181                if d > tol {
1182                    continue;
1183                }
1184                if find(&mut parent, i) == find(&mut parent, j) {
1185                    continue; // already coincident (directly or transitively)
1186                }
1187                let (ki, kj) = (id_key(&pi.id), id_key(&pj.id));
1188                if geo_sets.iter().any(|s| s.contains(&ki) && s.contains(&kj)) {
1189                    continue; // endpoints of one curve — do not collapse it
1190                }
1191                union(&mut parent, i, j);
1192                coincidents.push(vec![pi.id.clone(), pj.id.clone()]);
1193            }
1194        }
1195        for pts in coincidents {
1196            push_geometric_constraint(doc, "≡", pts);
1197        }
1198    }
1199
1200    doc.constraints.len().saturating_sub(before)
1201}
1202
1203impl EngineState {
1204    /// Auto-constrain the active sketch (the toolbar's one-click "constrain what I
1205    /// roughed in"): infer `━`/`│` on nearly-axis-aligned lines and `≡` between
1206    /// near-coincident points, then re-solve. Records ONE undo step, popped when the
1207    /// pass adds nothing so a dead click neither pollutes undo nor clobbers redo.
1208    /// Returns the number of constraints added; a no-op (0) when not in sketch mode.
1209    pub fn sketch_auto_constrain(&mut self) -> usize {
1210        let Some(edit) = self.sketch_edit.as_mut() else {
1211            return 0;
1212        };
1213        edit.record_undo();
1214        let added = auto_constrain_doc(&mut edit.session.doc);
1215        if added == 0 {
1216            edit.undo_stack.pop();
1217            return 0;
1218        }
1219        self.resolve_active_sketch("auto-constrain");
1220        self.refresh_sketch_overlay();
1221        self.dirty = true;
1222        added
1223    }
1224}
1225
1226// ===========================================================================
1227// Sketch delete-selected (S3b) — remove the selected entities + orphan cleanup.
1228//
1229// Operates on the active `self.sketch_edit`. Rule (chosen so a remaining geometry
1230// NEVER references a missing point):
1231//   1. Partition the selection into selected geometry / point / constraint ids.
1232//   2. Drop every geometry that is SELECTED *or* references any selected point (the
1233//      remove-point cascade — deleting a vertex kills geometry that used it).
1234//   3. Drop the selected points.
1235//   4. Orphan cleanup: drop any point a dropped geometry used that NO surviving
1236//      geometry references (a shared vertex — still referenced — stays; a deleted
1237//      line's now unshared endpoints vanish). Points no geometry used before the
1238//      delete (a fillet's construction virtual sharp) are never orphaned by it.
1239//   5. Drop any constraint that is SELECTED *or* references a removed point (selected ∪
1240//      orphaned) — done LAST, over the full removed-point set, so no constraint dangles
1241//      either. A selected constraint drops ONLY itself; the geometry/points it
1242//      referenced are untouched (deleting a constraint never deletes geometry).
1243// Then clear selection + hover, re-solve (swallowing errors), refresh, mark dirty.
1244// Kept in ONE appended block so concurrent edits to the primary impl land clean.
1245// ===========================================================================
1246impl EngineState {
1247    /// Delete the selected sketch entities (S3b): the selected geometries + points,
1248    /// plus any geometry orphaned by a deleted vertex, plus orphaned points and the
1249    /// constraints referencing any removed point. Re-solves + refreshes the overlay.
1250    /// Returns `true` when something was deleted; `false` when not in sketch mode or
1251    /// the selection is empty.
1252    pub fn sketch_delete_selection(&mut self) -> bool {
1253        use crate::sketch::doc::id_key;
1254        use std::collections::HashSet;
1255
1256        let Some(edit) = self.sketch_edit.as_mut() else {
1257            return false;
1258        };
1259        if edit.session.selection.items.is_empty() {
1260            return false;
1261        }
1262        // A non-empty selection always removes something → snapshot for undo (S6a).
1263        edit.record_undo();
1264
1265        // 1. Partition the selection into selected geometry / point / constraint ids
1266        //    (keyed via `id_key`, so 4 / 4.0 / "4" all match).
1267        let mut sel_geo: HashSet<String> = HashSet::new();
1268        let mut sel_pt: HashSet<String> = HashSet::new();
1269        let mut sel_constraint: HashSet<String> = HashSet::new();
1270        for r in &edit.session.selection.items {
1271            match (r.get("kind").and_then(|v| v.as_str()), r.get("id")) {
1272                (Some("geometry"), Some(id)) => {
1273                    sel_geo.insert(id_key(id));
1274                }
1275                (Some("point"), Some(id)) => {
1276                    sel_pt.insert(id_key(id));
1277                }
1278                (Some("constraint"), Some(id)) => {
1279                    sel_constraint.insert(id_key(id));
1280                }
1281                _ => {}
1282            }
1283        }
1284
1285        // The part-origin reference and its ground are permanent: never deleted,
1286        // selected or orphaned.
1287        let origin_key = id_key(&serde_json::Value::String(
1288            brep_kernel::SKETCH_ORIGIN_POINT_ID.to_string(),
1289        ));
1290        sel_pt.remove(&origin_key);
1291        sel_constraint.remove(&origin_key);
1292
1293        let doc = &mut edit.session.doc;
1294
1295        let deleted_texts: HashSet<String> = doc.geometries.iter().filter(|g| g.geom_type == "text")
1296            .filter(|g| sel_geo.contains(&id_key(&g.id)) || g.points.iter().any(|p| sel_pt.contains(&id_key(p))) || doc.geometries.iter().any(|edge| edge.extra.get("textFrame") == Some(&g.id) && sel_geo.contains(&id_key(&edge.id))))
1297            .map(|g| id_key(&g.id)).collect();
1298        for g in &doc.geometries {
1299            if deleted_texts.contains(&id_key(&g.id)) || g.extra.get("textFrame").is_some_and(|id| deleted_texts.contains(&id_key(id))) {
1300                sel_geo.insert(id_key(&g.id));
1301            }
1302        }
1303
1304        // 2. Drop geometries that are selected OR reference any selected point (so a
1305        //    deleted vertex never leaves a geometry dangling). Remember every point a
1306        //    dropped geometry used: only those can be orphaned by this delete.
1307        let mut released: HashSet<String> = HashSet::new();
1308        doc.geometries.retain(|g| {
1309            let keep = !sel_geo.contains(&id_key(&g.id)) && !g.points.iter().any(|pid| sel_pt.contains(&id_key(pid)));
1310            if !keep {
1311                released.extend(g.points.iter().map(id_key));
1312            }
1313            keep
1314        });
1315
1316        // 3. Drop the explicitly-selected points.
1317        doc.points.retain(|p| !sel_pt.contains(&id_key(&p.id)));
1318
1319        // 4. Orphan cleanup: drop points a dropped geometry used that no surviving
1320        //    geometry references. A point no geometry used before the delete is
1321        //    left alone: a fillet's or chamfer's virtual sharp (the construction
1322        //    corner its trimmed lines and the width/height dimensions still hang
1323        //    on) is held only by constraints, and deleting an unrelated
1324        //    constraint must not take it, and every constraint on it, along.
1325        //    Accumulate every removed point
1326        //    id (selected ∪ orphaned).
1327        let referenced: HashSet<String> = doc
1328            .geometries
1329            .iter()
1330            .flat_map(|g| g.points.iter().map(id_key))
1331            .collect();
1332        let mut removed_pts = sel_pt;
1333        doc.points.retain(|p| {
1334            let key = id_key(&p.id);
1335            if referenced.contains(&key) || key == origin_key || !released.contains(&key) {
1336                true
1337            } else {
1338                removed_pts.insert(key);
1339                false
1340            }
1341        });
1342
1343        // 5. Drop constraints that are EXPLICITLY selected OR reference ANY removed
1344        //    point (done last, over the full removed set, so no constraint dangles onto
1345        //    a missing point). A selected constraint drops ONLY itself — the geometry /
1346        //    points it references are left intact (deleting a constraint never deletes
1347        //    geometry).
1348        doc.constraints.retain(|c| {
1349            if let Some(id) = c.raw.get("id") {
1350                if sel_constraint.contains(&id_key(id)) {
1351                    return false;
1352                }
1353            }
1354            !c.points().iter().any(|pid| removed_pts.contains(&id_key(pid)))
1355        });
1356
1357        // Drop any external-reference bookkeeping whose materialized entities this
1358        // delete removed — otherwise its stale entry (keyed by edge name, now holding
1359        // dangling point ids) permanently blocks RE-LINKING the same edge.
1360        crate::sketch::external_ref::prune_dead_refs(&edit.session.doc, &mut edit.external_refs);
1361
1362        // Clear the interaction state, re-solve (keep the doc on failure), refresh.
1363        edit.session.clear_selection();
1364        edit.session.set_hover(None);
1365        self.resolve_active_sketch("delete");
1366        self.refresh_sketch_overlay();
1367        self.dirty = true;
1368        true
1369    }
1370}