Skip to main content

brep_render/engine_state/
sketch_mode.rs

1use super::*;
2
3/// One in-flight sketch drag (S2): the grabbed points and the anchor uv. A single
4/// entry for a point grab; a geometry's movable (deduped) points for a geometry
5/// grab. Locked endpoints stay anchored. Each point tracks the cursor by an ABSOLUTE
6/// `orig + (uv - anchor)` (never incremental — the solver moves points between
7/// frames, so incremental deltas would drift).
8#[derive(Clone)]
9pub struct SketchDrag {
10    /// Per grabbed point: `(id, orig_x, orig_y, orig_fixed)` captured once at grab.
11    pub(super) points: Vec<(serde_json::Value, f64, f64, bool)>,
12    /// The plane `(u, v)` where the grab started — the anchor for the delta.
13    pub(super) anchor: (f64, f64),
14    /// Only point grabs infer constraints on release, even if an edge has one free end.
15    pub(super) infer_on_drop: bool,
16    /// A constraint GLYPH grab instead of a point grab (`points` is then empty): the
17    /// constraint id and its stand-off at the grab, which the drag moves by the
18    /// cursor's motion (along the glyph's line normal, or freely).
19    pub(super) glyph: Option<(serde_json::Value, crate::sketch::constraint_glyphs::GlyphShift)>,
20}
21
22/// The active engine-native sketch edit — the live session plus the state to
23/// restore when sketch mode exits.
24pub struct SketchEdit {
25    /// The live solved sketch session (the doc being edited + its plane).
26    pub session: crate::sketch::SketchSession,
27    /// The id of the `"S"` feature this edit belongs to.
28    pub feature_id: String,
29    /// The rolled-to step to restore on exit (the model state before entering).
30    prev_rollback: usize,
31    /// The camera to restore on exit (the vantage before the plane orient).
32    prev_camera: crate::view::ViewCamera,
33    /// Whether this sketch was created THIS edit (so a cancel deletes it).
34    is_new: bool,
35    /// For a sketch created by this session: the undo step its creation took
36    /// (`History::undo_top` right after the push). Finish writes into that
37    /// step and Cancel retracts it, while nothing else has taken a step since,
38    /// so a new sketch is one undo step and a cancelled one is none.
39    creation_step: Option<u64>,
40    /// The in-flight drag (S2): the grabbed points + anchor, or `None` when no drag
41    /// is live. Grabs a point OR a whole geometry (rigid translate). See [`SketchDrag`].
42    pub(super) drag: Option<SketchDrag>,
43    /// The in-progress draw-tool click buffer (S3a): the point ids placed so far for
44    /// the geometry being drawn (a line-chain's running start, a rect/circle/arc's
45    /// first clicks). Cleared when a geometry lands, the tool changes, or on cancel.
46    pub(super) pending: Vec<serde_json::Value>,
47    /// The last hovered plane `(u, v)` (S3a) — the anchor for the rubber-band preview
48    /// so it follows the cursor while a tool has pending clicks.
49    pub(super) hover_uv: Option<(f64, f64)>,
50    /// Per-session UNDO stack (S6a): snapshots of the visible edit state taken at the
51    /// START of each discrete mutating op. Separate from the model-level undo (which
52    /// owns the FEATURE document). Cleared implicitly on enter/exit (a fresh
53    /// `SketchEdit` starts empty; exit drops the whole struct).
54    pub(super) undo_stack: Vec<SketchSnapshot>,
55    /// Per-session REDO stack (S6a): states popped by `sketch_undo`, restored by
56    /// `sketch_redo`. Cleared whenever a new mutation records an undo snapshot.
57    pub(super) redo_stack: Vec<SketchSnapshot>,
58    /// First-move guard for a dimension-label DRAG (S6a): set when the drag's single
59    /// undo snapshot has been taken, reset at the gesture end
60    /// ([`sketch_dimension_drag_end`](EngineState::sketch_dimension_drag_end)) so the
61    /// whole drag is ONE undo step, not one per motion frame.
62    pub(super) dim_drag_snapshotted: bool,
63    /// The external-reference edge links (S6b-2): one [`crate::sketch::ExternalRef`]
64    /// per linked scene edge (by name), mapping it to the materialized sketch points +
65    /// construction geometry. Loaded from `persistentData.externalRefs` on enter,
66    /// written back on commit, and captured in the undo snapshot so undo restores it
67    /// alongside the doc.
68    pub(super) external_refs: Vec<crate::sketch::ExternalRef>,
69    /// Names the feature's `projectedEdges` list carried at enter that had
70    /// nothing to materialize: the edge did not resolve in the backdrop scene
71    /// (a downstream edge, a typo). They are not links, so they are not in
72    /// `external_refs`, but Finish keeps them listed for the kernel to report
73    /// as unresolved — the editor never silently drops a dialog entry.
74    pub(super) listed_unlinked: Vec<String>,
75    /// The in-progress freehand stroke (S6b-3): raw plane `(u, v)` samples captured
76    /// during a handdraw drag, recognized into geometry on drag-end. Empty when no
77    /// stroke is live. Transient interaction state — NOT part of the undo snapshot.
78    pub(super) handdraw_stroke: Vec<(f64, f64)>,
79}
80
81/// One reversible sketch-edit state (S6a): a clone of everything the visible edit
82/// carries — the solved [`SketchDoc`](crate::sketch::SketchDoc), the dimension label
83/// offsets, and the selection — enough to fully restore the session on undo/redo.
84/// Transient interaction state (in-flight drag, draw pending buffer) is deliberately
85/// NOT captured; undo/redo clears it instead.
86#[derive(Clone)]
87pub(super) struct SketchSnapshot {
88    pub(super) doc: crate::sketch::SketchDoc,
89    pub(super) dim_offsets: serde_json::Map<String, serde_json::Value>,
90    pub(super) selection: Vec<serde_json::Value>,
91    /// The external-reference mapping (S6b-2) — captured so undoing a pickEdges link
92    /// also drops its `ExternalRef` entry, keeping the mapping consistent with the doc.
93    pub(super) external_refs: Vec<crate::sketch::ExternalRef>,
94}
95
96impl SketchEdit {
97    /// A snapshot of the CURRENT visible edit state (doc + dim offsets + selection +
98    /// external refs).
99    pub(super) fn snapshot(&self) -> SketchSnapshot {
100        SketchSnapshot {
101            doc: self.session.doc.clone(),
102            dim_offsets: self.session.dim_offsets.clone(),
103            selection: self.session.selection.items.clone(),
104            external_refs: self.external_refs.clone(),
105        }
106    }
107
108    /// Push the current state onto the undo stack and clear redo — the discrete-op
109    /// undo primitive. Callers invoke this at the START of a mutation (before the doc
110    /// changes) so one Ctrl+Z reverts that op.
111    pub(super) fn record_undo(&mut self) {
112        let snap = self.snapshot();
113        self.undo_stack.push(snap);
114        self.redo_stack.clear();
115    }
116}
117
118/// Convert a kernel [`brep_kernel::Frame`] into the sketch module's
119/// [`crate::sketch::PlaneFrame`]. Kept HERE (not in `sketch/mod.rs`, which is
120/// deliberately kernel-free) so a sketch's kernel-resolved plane frame — the exact
121/// frame the committed sheet is materialized against — can seed the live session.
122fn plane_frame_from_kernel(frame: &brep_kernel::Frame) -> crate::sketch::PlaneFrame {
123    crate::sketch::PlaneFrame {
124        origin: [frame.origin.x, frame.origin.y, frame.origin.z],
125        x_axis: [frame.x_axis.x, frame.x_axis.y, frame.x_axis.z],
126        y_axis: [frame.y_axis.x, frame.y_axis.y, frame.y_axis.z],
127        z_axis: [frame.z_axis.x, frame.z_axis.y, frame.z_axis.z],
128    }
129}
130
131impl EngineState {
132    /// True while a sketch is being edited (the shell hides the normal side panel
133    /// and shows the sketch-mode bar).
134    pub fn sketch_mode(&self) -> bool {
135        self.sketch_edit.is_some()
136    }
137
138    /// The live sketch session while in sketch mode (for the DOF readout / overlay
139    /// / the headless verifier), else `None`.
140    pub fn sketch_edit_session(&self) -> Option<&crate::sketch::SketchSession> {
141        self.sketch_edit.as_ref().map(|edit| &edit.session)
142    }
143
144    /// The id of the feature being edited while in sketch mode, else `None`.
145    pub fn sketch_edit_feature_id(&self) -> Option<&str> {
146        self.sketch_edit.as_ref().map(|edit| edit.feature_id.as_str())
147    }
148
149    /// Whether the sketch camera is locked flat to the plane (only panning). On by
150    /// default every sketch entry; the sketch-mode bar's checkbox reflects this.
151    pub fn sketch_camera_locked(&self) -> bool {
152        self.sketch_camera_locked
153    }
154
155    /// Toggle the sketch camera lock. Turning it ON re-faces the camera to the
156    /// current sketch plane (so "off → spin around → on" snaps back flat); turning
157    /// it OFF just frees orbiting. No-op outside sketch mode.
158    pub fn toggle_sketch_camera_lock(&mut self) {
159        if !self.sketch_mode() {
160            return;
161        }
162        self.sketch_camera_locked = !self.sketch_camera_locked;
163        if self.sketch_camera_locked {
164            // `PlaneFrame` is `Copy`, so this ends the `&self` borrow before the
165            // `&mut self` re-orient.
166            if let Some(plane) = self.sketch_edit_session().map(|s| s.plane) {
167                self.face_camera_to_plane(&plane);
168                self.dirty = true;
169            }
170        }
171    }
172
173    /// Orient the camera flat-on to a sketch plane: look along the NEGATIVE normal
174    /// with the plane's +y as up, so the plane faces the viewer. Shared by sketch
175    /// entry and the lock toggle.
176    fn face_camera_to_plane(&mut self, plane: &crate::sketch::PlaneFrame) {
177        let dir = [
178            -(plane.z_axis[0] as f32),
179            -(plane.z_axis[1] as f32),
180            -(plane.z_axis[2] as f32),
181        ];
182        let up = [
183            plane.y_axis[0] as f32,
184            plane.y_axis[1] as f32,
185            plane.y_axis[2] as f32,
186        ];
187        self.apply_look_direction(dir, up);
188    }
189
190    /// Enter sketch mode for the `"S"` feature with id `feature_id`: snapshot the
191    /// camera + rolled-to step, roll to the step BEFORE the sketch (its backdrop),
192    /// read the persisted plane `basis` + `sketch` doc off the history JSON, solve
193    /// a live session, orient the camera onto the plane, and push the read-only
194    /// overlay. Returns the session's diagnostics JSON. Errors when the feature is
195    /// absent or is not a sketch.
196    pub fn enter_sketch_mode(&mut self, feature_id: &str) -> Result<String, String> {
197        let index = self
198            .history
199            .index_of(feature_id)
200            .ok_or_else(|| format!("no feature with id '{feature_id}'"))?;
201        if self.history.feature_type(index).as_deref() != Some("S") {
202            return Err(format!("feature '{feature_id}' is not a sketch (type \"S\")"));
203        }
204
205        // The frame the kernel resolved for THIS sketch on the last full run is
206        // published under the sketch's own id in `construction_frames` (see
207        // `feature_pipeline::features::sketch::execute` → `result.frames`). It is, by
208        // construction, the EXACT frame the committed sheet was materialized against
209        // (the sheet's world curves come from the same `SketchProfile` frame). Capture
210        // it NOW, before the roll below drops the sketch from `construction_frames` —
211        // seeding the live session with it keeps the editing overlay on the same plane
212        // the committed sheet lands on. This fixes the off-location sheet for
213        // face/datum-attached sketches whose live-resolved frame differs from the
214        // persisted `basis` (which the kernel only uses as a missing-reference fallback).
215        let resolved_frame = self
216            .construction_frames
217            .iter()
218            .find(|(name, _)| name == feature_id)
219            .map(|(_, frame)| plane_frame_from_kernel(frame));
220
221        // Snapshot the pre-entry view + roll, then roll to the step just before the
222        // sketch so the model up to (not including) it is the sketching backdrop.
223        let prev_camera = self.camera.clone();
224        let prev_rollback = self.history.rollback();
225        self.history.set_rollback(index.saturating_sub(1));
226        self.rerun_history();
227
228        // Read the persisted plane + doc straight off the history JSON (headless).
229        // The plane is the kernel-resolved frame when available (live-first, matching
230        // the SKETCH feature's `resolve_frame`), else the persisted `basis`, else XY.
231        let persistent = self.history.feature_persistent_data(index);
232        let plane = resolved_frame
233            .or_else(|| {
234                persistent
235                    .as_ref()
236                    .and_then(|p| p.get("basis"))
237                    .map(crate::sketch::PlaneFrame::from_basis_json)
238            })
239            .unwrap_or_else(crate::sketch::PlaneFrame::xy);
240        let doc_value = persistent
241            .as_ref()
242            .and_then(|p| p.get("sketch"))
243            .cloned()
244            .unwrap_or_else(|| {
245                serde_json::json!({ "points": [], "geometries": [], "constraints": [] })
246            });
247        let mut doc: crate::sketch::SketchDoc = serde_json::from_value(doc_value)
248            .map_err(|error| format!("sketch doc parse: {error}"))?;
249        // Every sketch carries the part origin projected onto its plane, as a
250        // fixed reference to constrain to (added on first entry, re-projected
251        // when the plane moved).
252        crate::sketch::external_ref::ensure_origin_point(&mut doc, &plane);
253        let mut session = crate::sketch::SketchSession::new(doc, plane)?;
254        // Seed the overlay palette from the live display settings so the sketch colors
255        // are managed there like the rest of the display (kept in sync by
256        // `apply_settings_json` whenever the user edits a sketch color).
257        session.colors = self.settings.sketch_colors();
258        // Load the persisted per-dimension label offsets (S5) — plane-space
259        // `{du, dv}` keyed by constraint id, written back on commit below.
260        if let Some(offsets) = persistent
261            .as_ref()
262            .and_then(|p| p.get("dimOffsets"))
263            .and_then(serde_json::Value::as_object)
264        {
265            session.dim_offsets = offsets.clone();
266        }
267        // Load the persisted external-reference edge links (S6b-2) — the mapping from
268        // linked scene edges to their materialized points/geometry, round-tripped on
269        // commit below. A malformed array degrades to no refs.
270        let mut external_refs: Vec<crate::sketch::ExternalRef> = persistent
271            .as_ref()
272            .and_then(|p| p.get("externalRefs"))
273            .and_then(|v| serde_json::from_value(v.clone()).ok())
274            .unwrap_or_default();
275        // Heal docs poisoned by the pre-fix delete: drop any linked-edge entry whose
276        // materialized points/geometry are gone, so its edge can be RE-LINKED (a stale
277        // entry's dead dedup path would otherwise block the re-link forever). Reproject
278        // (below) then only touches live refs.
279        crate::sketch::external_ref::prune_dead_refs(&session.doc, &mut external_refs);
280        // The feature's `projectedEdges` list is the one record of the linked
281        // edges: every listed edge the backdrop resolves is materialized below
282        // (a dialog entry shows up in the editor), and a link the list no
283        // longer names was removed from the dialog — but only once a unified
284        // Finish stamped the marker; before that the entries were never
285        // listed, so they are adopted, not released.
286        let listed = brep_kernel::reference_names(
287            self.history
288                .feature_params(index)
289                .as_ref()
290                .and_then(|p| p.get("projectedEdges")),
291        );
292        let links_listed = persistent
293            .as_ref()
294            .and_then(|p| p.get(crate::sketch::external_ref::LINKS_LISTED_KEY))
295            .and_then(serde_json::Value::as_bool)
296            == Some(true);
297
298        // Drop any MODEL selection carried in from picking the sketch plane, so no
299        // faces/edges stay highlighted inside the sketch — the only highlight the
300        // user should see there is the sketch's own geometry (or an entity they
301        // pick to link in). Covers the new-sketch path too (`new_sketch` enters
302        // through here).
303        self.clear_selection();
304
305        // Every sketch entry starts with the camera LOCKED flat to the plane (the
306        // default): face it now, and `face_camera_to_plane` re-does this when the
307        // user toggles the lock back on.
308        self.sketch_camera_locked = true;
309        self.face_camera_to_plane(&plane);
310
311        // Push the overlay + capture diagnostics BEFORE moving the session into the
312        // edit (both are borrows of the local `session`).
313        self.set_sketch_overlay(&session);
314        let diagnostics =
315            serde_json::to_string(&session.diagnostics).unwrap_or_else(|_| "{}".to_string());
316
317        self.sketch_edit = Some(SketchEdit {
318            session,
319            feature_id: feature_id.to_string(),
320            prev_rollback,
321            prev_camera,
322            is_new: false,
323            creation_step: None,
324            drag: None,
325            pending: Vec::new(),
326            hover_uv: None,
327            // A fresh session starts with empty undo/redo history (S6a).
328            undo_stack: Vec::new(),
329            redo_stack: Vec::new(),
330            dim_drag_snapshotted: false,
331            external_refs,
332            listed_unlinked: Vec::new(),
333            handdraw_stroke: Vec::new(),
334        });
335        // Sync the links with the list against the CURRENT backdrop model: every
336        // loaded ref re-projects so a linked edge tracks upstream geometry edits,
337        // a listed edge without a ref is linked, and (once unified) a ref the
338        // list dropped is released. Best-effort on a missing edge — the
339        // persisted coords stand as the fallback; the regenerate fold, which
340        // has the kernel's word on what resolves, is what releases those. This
341        // may move the ref points + re-solve, so re-read diagnostics afterward.
342        let reprojected = self.sketch_sync_external_refs(&listed, links_listed);
343        let diagnostics = if reprojected {
344            self.sketch_edit
345                .as_ref()
346                .map(|edit| {
347                    serde_json::to_string(&edit.session.diagnostics)
348                        .unwrap_or_else(|_| "{}".to_string())
349                })
350                .unwrap_or(diagnostics)
351        } else {
352            diagnostics
353        };
354        // Clear the now-active sketch's committed overlay: the mid-enter rerun above
355        // (rolled to the step before the sketch, `sketch_edit` not yet set) may have
356        // fed it; now `sketch_edit` is armed, so it is excluded and cleared — the live
357        // editing overlay is its only display while editing (no double display).
358        self.refresh_committed_sketches();
359        self.dirty = true;
360        Ok(diagnostics)
361    }
362
363    /// Exit sketch mode. `commit` writes the edited doc back to the feature's
364    /// `persistentData.sketch`; a non-commit exit of a brand-new sketch DELETES the
365    /// feature (a fresh sketch nobody kept). Restores the snapshotted camera +
366    /// rolled-to step, clears the overlay, re-runs the history, and returns the
367    /// build report. A no-op (returns `"{}"`) when not in sketch mode.
368    pub fn exit_sketch_mode(&mut self, commit: bool) -> String {
369        let Some(edit) = self.sketch_edit.take() else {
370            return "{}".to_string();
371        };
372        if commit {
373            if let Some(index) = self.history.index_of(&edit.feature_id) {
374                let mut sketch_value = serde_json::to_value(&edit.session.doc).unwrap_or_else(|_| {
375                    serde_json::json!({ "points": [], "geometries": [], "constraints": [] })
376                });
377                // Stamp each closed loop's STABLE id onto its geometries. The
378                // kernel derives the same ids when it reads the sketch, so this
379                // changes no name — it persists the id against the one edit
380                // deriving cannot survive: deleting the edge the id came from.
381                // Per-loop face names (extrude/sweep/revolve/loft caps) embed it.
382                brep_kernel::assign_sketch_loop_ids(&mut sketch_value);
383                // The dimension label offsets persist alongside the doc (S5) so a
384                // re-enter restores each dimension's dragged label position, and
385                // the external-reference edge links (S6b-2) so a re-enter reloads
386                // (and re-projects) each linked scene edge.
387                let refs_value = serde_json::to_value(&edit.external_refs)
388                    .unwrap_or_else(|_| serde_json::Value::Array(Vec::new()));
389                // One write, so Finish is ONE undo step (and none when the
390                // session changed nothing). A sketch this session created
391                // writes into its creation's step, so the whole new sketch is
392                // one step.
393                // The linked edges are the feature's `projectedEdges` list:
394                // listed order kept, dropped links gone, unmaterialized entries
395                // kept, new links appended.
396                let current = self.history.feature_params(index);
397                let listed = brep_kernel::reference_names(
398                    current.as_ref().and_then(|p| p.get("projectedEdges")),
399                );
400                let names = crate::sketch::external_ref::listed_edge_names(
401                    &listed,
402                    &edit.external_refs,
403                    &edit.listed_unlinked,
404                );
405                let mut fields = vec![
406                    ("sketch", sketch_value),
407                    ("dimOffsets", serde_json::Value::Object(edit.session.dim_offsets.clone())),
408                    ("externalRefs", refs_value),
409                ];
410                // From the first Finish that has a link on, the list names every
411                // link (see `enter_sketch_mode`'s adopt-or-release rule). A
412                // sketch that never linked anything is left unstamped, so a
413                // Finish that changed nothing still writes nothing.
414                if !names.is_empty() || !edit.external_refs.is_empty() {
415                    fields.push((
416                        crate::sketch::external_ref::LINKS_LISTED_KEY,
417                        serde_json::Value::Bool(true),
418                    ));
419                }
420                match edit.creation_step {
421                    Some(step) => {
422                        self.history.set_feature_persistent_fields_in_step(index, fields, step);
423                    }
424                    None => {
425                        self.history.set_feature_persistent_fields(index, fields);
426                    }
427                }
428                // Write the links into the list. Folded without a checkpoint so
429                // Finish stays ONE undo step — the snapshot above already holds
430                // the pre-Finish list — and skipped when the names already match,
431                // so an unchanged Finish does not tick the revision.
432                if names != listed {
433                    self.history.fold_param_no_undo(
434                        &edit.feature_id,
435                        "projectedEdges",
436                        serde_json::Value::Array(names.into_iter().map(serde_json::Value::String).collect()),
437                    );
438                }
439            }
440        } else if edit.is_new {
441            // Retract the creation's step, so the cancel leaves nothing to
442            // undo; only if something else took a step since, delete the
443            // feature as a step of its own.
444            if edit.creation_step.is_some_and(|step| self.history.retract(step)) {
445                self.reinstall_rewound_parts_library();
446            } else if let Some(index) = self.history.index_of(&edit.feature_id) {
447                self.history.remove_feature(index);
448            }
449        }
450        self.history.set_rollback(edit.prev_rollback);
451        self.clear_sketch_overlay();
452        self.camera = edit.prev_camera;
453        self.dirty = true;
454        self.rerun_history()
455    }
456
457    /// Create a NEW engine-native sketch on a base plane (`"XY" | "XZ" | "YZ"`) and
458    /// enter sketch mode on it. The feature persists an analytic `basis` (computed
459    /// via [`crate::sketch::PlaneFrame`]) and an empty `sketch` doc; a cancel exit
460    /// deletes it. Returns the new session's diagnostics JSON. Errors on an unknown
461    /// plane name.
462    pub fn new_sketch(&mut self, plane: &str) -> Result<String, String> {
463        let frame = match plane {
464            "XY" => crate::sketch::PlaneFrame::xy(),
465            "XZ" => crate::sketch::PlaneFrame::xz(),
466            "YZ" => crate::sketch::PlaneFrame::yz(),
467            other => {
468                return Err(format!("unknown base plane '{other}' (expected XY|XZ|YZ)"));
469            }
470        };
471        self.new_sketch_on(plane, frame)
472    }
473
474    /// A new sketch on the named `plane` (a base plane, or a datum's
475    /// `<id>:XY`), its basis seeded with `frame`; enters sketch mode.
476    pub fn new_sketch_on(&mut self, plane: &str, frame: crate::sketch::PlaneFrame) -> Result<String, String> {
477        let id = self
478            .history
479            .next_feature_id(&crate::features::feature_short_name("S"));
480        let feature = serde_json::json!({
481            "type": "S",
482            "inputParams": { "id": id, "sketchPlane": plane },
483            "persistentData": {
484                "basis": {
485                    "origin": frame.origin,
486                    "x": frame.x_axis,
487                    "y": frame.y_axis,
488                    "z": frame.z_axis,
489                },
490                "sketch": { "points": [], "geometries": [], "constraints": [] }
491            }
492        });
493        self.history.push_feature(feature);
494        let creation_step = self.history.undo_top();
495        let diagnostics = self.enter_sketch_mode(&id)?;
496        if let Some(edit) = self.sketch_edit.as_mut() {
497            edit.is_new = true;
498            edit.creation_step = creation_step;
499        }
500        Ok(diagnostics)
501    }
502}