Skip to main content

brep_render/engine_state/
committed_sketches.rs

1use super::*;
2
3/// The committed-sketch SHEET base color (dim cyan, matching the retired overlay
4/// `COMMITTED_COLOR` 0x67c7d4) — a sketch sheet reads distinctly from a real solid.
5const SKETCH_SHEET_COLOR: [f32; 3] = [
6    0x67 as f32 / 255.0,
7    0xc7 as f32 / 255.0,
8    0xd4 as f32 / 255.0,
9];
10
11/// The wire-harness PORT sheet colour: red, so a port reads apart from every
12/// sketch (cyan) and solid at a glance.
13const PORT_TERMINATION_COLOR: [f32; 3] = [
14    0xe5 as f32 / 255.0,
15    0x32 as f32 / 255.0,
16    0x2d as f32 / 255.0,
17];
18/// The open edges a refused Sew to Solid draws: orange, so the gap reads apart
19/// from sketches (cyan), ports (red) and every solid.
20const SEW_GAP_COLOR: [f32; 3] = [
21    0xff as f32 / 255.0,
22    0x9f as f32 / 255.0,
23    0x1a as f32 / 255.0,
24];
25/// A WAYPOINT port: a lighter red, so a pass-through reads apart from an end.
26const PORT_WAYPOINT_COLOR: [f32; 3] = [
27    0xff as f32 / 255.0,
28    0x8a as f32 / 255.0,
29    0x80 as f32 / 255.0,
30];
31
32/// The feature types whose committed display is a synthesized SKETCH-LIKE
33/// sheet (an `is_sketch` scene solid drawn from the paths the feature
34/// published), and the prefix of the path names that are that feature's own
35/// drawable segments:
36///   * `S` — a sketch draws one segment per model geometry, `{id}:G{gid}`;
37///   * `HX` — a helix draws its single fitted edge, `{id}:HelixEdge`;
38///   * `SP` — a spline draws its exact chain, `{id}:SplineEdge`;
39///   * `WP` — a routing waypoint draws its line, `{id}:PortLine`;
40///   * `PORTS` — a declared connection point, which is not a feature at all:
41///     its address stands in for the id and it draws the same line.
42///   * `S3D` — a 3D sketch draws one curve per model geometry, `{id}:G{gid}`,
43///     like a planar sketch (it never has a sheet: nothing closes a region).
44///   * `SEW` — a Sew to Solid whose faces did not close draws the open edges
45///     it refused on, `{id}:GAP[n]`, so the user sees which edge to fix, as
46///     the display `{id}:GAP`. A sew that closed publishes none and draws
47///     (and lists) nothing.
48/// Anything else (a solid feature) has no sheet here. Only `S` and `S3D` are
49/// ever ENTERABLE — the sketch-mode guards check the type separately.
50fn curve_feature_segment_prefix(feature_type: &str, id: &str) -> Option<String> {
51    match feature_type {
52        "S" => Some(format!("{id}:G")),
53        "HX" => Some(format!("{id}:HelixEdge")),
54        "SP" => Some(format!("{id}:SplineEdge")),
55        brep_kernel::SKETCH3D_FEATURE_TYPE => Some(format!("{id}:G")),
56        "WP" | brep_kernel::PORTS_FEATURE_TYPE => Some(format!("{id}:PortLine")),
57        "SEW" => Some(format!("{id}:GAP")),
58        _ => None,
59    }
60}
61
62/// The prefix of the published POINT names a sketch-like feature draws as
63/// standalone vertices: a sketch publishes every solved point as `{id}:P{pid}`,
64/// and the ones no segment covers (a points-only hole-placement sketch) are
65/// otherwise invisible; a spline publishes its anchors as `{id}:P{index}`, drawn
66/// so the anchors are visible and pickable; a port publishes its base point
67/// as `{id}:Base`. A helix publishes only its two ends, which its edge already
68/// draws, so it has no point prefix.
69fn curve_feature_point_prefix(feature_type: &str, id: &str) -> Option<String> {
70    match feature_type {
71        "S" | "SP" | brep_kernel::SKETCH3D_FEATURE_TYPE => Some(format!("{id}:P")),
72        "WP" | brep_kernel::PORTS_FEATURE_TYPE => Some(format!("{id}:Base")),
73        _ => None,
74    }
75}
76
77impl EngineState {
78
79    /// The committed sketches present at the CURRENT rollback: every sketch-like
80    /// feature (see [`curve_feature_segment_prefix`]) at index `0..=rollback`,
81    /// EXCEPT the one being edited (it displays via the live editing overlay) and
82    /// EXCEPT any sketch a downstream feature within the current rollback CONSUMED
83    /// (see [`consumed_feature_names`](Self::consumed_feature_names)). Hidden ids
84    /// are still returned (the Scene tree lists them); visibility is filtered by
85    /// the caller against [`hidden_sketches`].
86    fn committed_sketch_ids(&self) -> Vec<String> {
87        self.committed_curve_features()
88            .into_iter()
89            .map(|(id, _, _)| id)
90            .collect()
91    }
92
93    /// [`committed_sketch_ids`](Self::committed_sketch_ids) with each id's
94    /// segment-name prefix and (for a sketch) its point-name prefix — the
95    /// `(id, segment prefix, point prefix)` triples the sheet refresh draws.
96    fn committed_curve_features(&self) -> Vec<(String, String, Option<String>)> {
97        self.committed_curve_features_typed()
98            .into_iter()
99            .map(|(id, _, prefix, point_prefix)| (id, prefix, point_prefix))
100            .collect()
101    }
102
103    /// [`committed_curve_features`](Self::committed_curve_features) with each
104    /// feature's TYPE beside its id — the sheet refresh colours a port sheet
105    /// by type.
106    fn committed_curve_features_typed(&self) -> Vec<(String, String, String, Option<String>)> {
107        let editing = self
108            .sketch_edit
109            .as_ref()
110            .map(|edit| edit.feature_id.as_str())
111            .or_else(|| self.sketch3d_edit.as_ref().map(|edit| edit.feature_id.as_str()));
112        let rollback = self.history.rollback();
113        let mut ids = Vec::new();
114        for index in 0..=rollback {
115            let Some(feature_type) = self.history.feature_type(index) else {
116                continue;
117            };
118            let Some(id) = self.history.feature_id(index) else {
119                continue;
120            };
121            let Some(prefix) = curve_feature_segment_prefix(&feature_type, &id) else {
122                continue;
123            };
124            if Some(id.as_str()) == editing {
125                continue;
126            }
127            // A Sew to Solid is listed only while it has open edges to show,
128            // and under `{id}:GAP`, never its id: the solid it builds once the
129            // faces close is the scene solid `{id}`, which the refresh that
130            // retires this display must not remove.
131            let id = if feature_type == "SEW" {
132                if !self.sketch_paths.iter().any(|(name, _)| name.starts_with(prefix.as_str())) {
133                    continue;
134                }
135                prefix.clone()
136            } else {
137                id
138            };
139            let point_prefix = curve_feature_point_prefix(&feature_type, &id);
140            ids.push((id, feature_type, prefix, point_prefix));
141        }
142        // Drop any sketch a downstream feature CONSUMED: extrude/revolve (gated by
143        // `consumeProfileSketch`) and the sheet-metal consumers push the consumed
144        // sketch id into their `result.removed`, so a consumed sketch must vanish
145        // from the scene — no sheet, no tree row — exactly like a consumed solid.
146        // Only replay when there is a candidate to test, so a sketch-less scene pays
147        // nothing for the check.
148        if !ids.is_empty() {
149            let consumed = self.consumed_feature_names();
150            ids.retain(|(id, _, _, _)| !consumed.contains(id));
151        }
152        // The document's OWN declared connection points: not features, so the
153        // ports tail published them under their ADDRESS with the same
154        // `{id}:PortLine` / `{id}:Base` names a waypoint uses.
155        let declare = |address: String, ids: &mut Vec<(String, String, String, Option<String>)>| {
156            if ids.iter().any(|(id, _, _, _)| *id == address) {
157                return;
158            }
159            let ty = brep_kernel::PORTS_FEATURE_TYPE;
160            let Some(prefix) = curve_feature_segment_prefix(ty, &address) else {
161                return;
162            };
163            let point_prefix = curve_feature_point_prefix(ty, &address);
164            ids.push((address, ty.to_string(), prefix, point_prefix));
165        };
166        for point in self.history.declared_points() {
167            declare(point.address(), &mut ids);
168        }
169        // The points placed components carry, namespaced by the ACOMP that
170        // published them. Shown per workbench.
171        if self.component_ports_visible {
172            let addresses: Vec<String> = self
173                .assembly_components()
174                .iter()
175                .flat_map(|component| component.ports.clone())
176                .collect();
177            for address in addresses {
178                declare(address, &mut ids);
179            }
180        }
181        ids
182    }
183
184    /// Whether the ports placed components carry draw their sheets.
185    pub fn component_ports_visible(&self) -> bool {
186        self.component_ports_visible
187    }
188
189    /// Show or hide the sheets of the ports placed components carry (the app
190    /// drives this from the active workbench). A change refreshes the sheets.
191    pub fn set_component_ports_visible(&mut self, visible: bool) {
192        if self.component_ports_visible == visible {
193            return;
194        }
195        self.component_ports_visible = visible;
196        self.refresh_committed_sketches();
197    }
198
199    /// The sheet colour for a committed curve feature: connection points are
200    /// red, routing waypoints a lighter red, everything else the sketch cyan.
201    fn curve_feature_color(&self, _id: &str, feature_type: &str) -> [f32; 3] {
202        match feature_type {
203            "WP" => PORT_WAYPOINT_COLOR,
204            "SEW" => SEW_GAP_COLOR,
205            ty if ty == brep_kernel::PORTS_FEATURE_TYPE => PORT_TERMINATION_COLOR,
206            _ => SKETCH_SHEET_COLOR,
207        }
208    }
209
210    /// The set of output names CONSUMED (removed) by some feature within the
211    /// rollback prefix the last applied run executed — a solid absorbed by a
212    /// boolean, or a sketch absorbed by a downstream extrude / revolve /
213    /// sheet-metal consumer. The SAME per-feature `removed` signal the scene
214    /// build honors, unioned by the runner and shipped in the reply
215    /// ([`crate::pipeline::RunOutput::consumed`]).
216    ///
217    /// This used to replay the prefix on the UI thread. It was never the clean
218    /// cache hit its old comment claimed: the kernel's incremental cache is per
219    /// thread, so the first main-side replay of a document executed it in full,
220    /// and every later one re-executed whatever the edit had dirtied — plus the
221    /// uncached wire-harness tail, which swept every bundle a second time.
222    ///
223    /// Because [`prefix_request`](crate::history::History::prefix_request) stops
224    /// at the rolled-to feature, a consumer ABOVE the rollback never runs, so its
225    /// removed names are (correctly) absent — a sketch consumed above the
226    /// rollback point still shows. Empty before the first run.
227    fn consumed_feature_names(&self) -> &std::collections::HashSet<String> {
228        &self.consumed_names
229    }
230
231    /// (Re)build the persistent committed-sketch SHEET SOLIDS. For every committed
232    /// sketch that should show — `committed_sketch_ids`
233    /// minus `hidden_sketches` — synthesize its display from the run's solved
234    /// profile AND its own model segments, and insert it as a scene solid (keyed by
235    /// the sketch id, dim-cyan, flagged `is_sketch`); remove any sheet inserted on
236    /// the PREVIOUS refresh but not this one (rolled back, deleted, hidden, or
237    /// became the active edit). A sketch that closes a region gets its planar sheet;
238    /// one that closes NOTHING (an open chain — the single line of the 2026-09-02
239    /// report) still draws its segments as named edges, so it is visible and
240    /// pickable instead of vanishing; one holding ONLY points (a hole-placement
241    /// sketch) draws them as vertices, so it too is visible, listed and pickable
242    /// (a vertex hit carries its owning sketch, which the `SKETCH` pick lane
243    /// admits). Only a sketch with no drawable geometry at all (empty /
244    /// construction-only) is skipped. Marks dirty.
245    pub fn refresh_committed_sketches(&mut self) {
246        let visible: Vec<(String, String, String, Option<String>)> = self
247            .committed_curve_features_typed()
248            .into_iter()
249            .filter(|(id, _, _, _)| !self.hidden_sketches.contains(id))
250            .collect();
251
252        // Phase 1 (immutable borrow of the surfaced profiles + paths + points):
253        // build a display payload per visible sketch — its closed profile's sheet
254        // (when it has one), every model segment that sheet does not already
255        // draw, and every model point no segment covers. A sketch with nothing to
256        // draw (no face + no edges + no points) is skipped.
257        let payloads: Vec<(String, [f32; 3], brep_kernel::DisplaySolidPayload)> = visible
258            .iter()
259            .filter_map(|(id, feature_type, prefix, point_prefix)| {
260                let profile = self
261                    .sketch_profiles
262                    .iter()
263                    .find(|(name, _)| name == id)
264                    .map(|(_, profile)| profile);
265                // The feature's own model segments, published under its segment
266                // prefix (a sketch: one per geometry, `{id}:G{gid}`; a helix: its
267                // one `{id}:HelixEdge`). The whole-chain `{id}` path duplicates
268                // them and `{id}:REF:{source}` is projected reference geometry,
269                // so neither is drawn here.
270                let segments: Vec<(String, Vec<brep_kernel::NurbsCurve>)> = self
271                    .sketch_paths
272                    .iter()
273                    .filter(|(name, _)| name.starts_with(prefix.as_str()))
274                    .cloned()
275                    .collect();
276                // The sketch's own MODEL points, published under `{id}:P{pid}`.
277                // Construction points constrain and never model, so — like
278                // construction geometry — they do not draw.
279                let points: Vec<brep_kernel::Vec3> = match point_prefix {
280                    Some(point_prefix) => self
281                        .sketch_points
282                        .iter()
283                        .filter(|(name, point)| {
284                            name.starts_with(point_prefix.as_str()) && !point.construction
285                        })
286                        .map(|(_, point)| point.position)
287                        .collect(),
288                    None => Vec::new(),
289                };
290                let payload = brep_kernel::sketch_display_payload(profile, &segments, &points);
291                if payload.mesh.indices.is_empty()
292                    && payload.edges.is_empty()
293                    && payload.vertices.is_empty()
294                {
295                    return None;
296                }
297                Some((id.clone(), self.curve_feature_color(id, feature_type), payload))
298            })
299            .collect();
300
301        // Phase 2 (mutable borrow of the scene): insert each sheet as a scene solid.
302        let mut fed: Vec<String> = Vec::with_capacity(payloads.len());
303        for (id, color, payload) in payloads {
304            let mut solid = crate::scene::solid_display_from_payload(&id, payload);
305            solid.is_sketch = true;
306            solid.color_override = Some(color);
307            // A refused Sew to Solid's open edges are the message: drawn in
308            // its colour, not the theme's edge colour.
309            if color == SEW_GAP_COLOR {
310                solid.edge_color_base = Some(color);
311                for edge in &mut solid.edges {
312                    edge.color_override = Some(color);
313                }
314            }
315            self.scene.insert_solid(solid);
316            fed.push(id);
317        }
318
319        // Remove any sketch sheet inserted last time but not now.
320        let fed_set: std::collections::HashSet<&str> = fed.iter().map(String::as_str).collect();
321        let stale: Vec<String> = self
322            .shown_sketch_ids
323            .iter()
324            .filter(|id| !fed_set.contains(id.as_str()))
325            .cloned()
326            .collect();
327        for id in stale {
328            self.scene.remove_solid(&id);
329        }
330
331        self.shown_sketch_ids = fed;
332        self.dirty = true;
333        // A freshly synthesized sheet arrives with no face colours; re-derive
334        // the sketch's `color` attribute onto it here, since this rebuild also
335        // runs outside a history apply (sketch mode exit, show/hide).
336        self.sync_colors_from_metadata();
337    }
338
339    /// Whether the committed sketch `id`'s persistent overlay is shown (absent from
340    /// `hidden_sketches` = visible).
341    pub fn sketch_visible(&self, id: &str) -> bool {
342        !self.hidden_sketches.contains(id)
343    }
344
345    /// Whether `name` is a committed sketch (shown as an `is_sketch` sheet, or
346    /// hidden through `hidden_sketches`): its visibility is the sketch's, never
347    /// the sheet solid's own flag.
348    pub(crate) fn is_committed_sketch_name(&self, name: &str) -> bool {
349        self.scene.solid(name).is_some_and(|solid| solid.is_sketch)
350            || (self.hidden_sketches.contains(name) && self.committed_sketch_ids().iter().any(|id| id == name))
351    }
352
353    /// Show/hide the committed sketch `id`'s persistent overlay (the Scene-tree
354    /// checkbox). Toggles `hidden_sketches`, rebuilds the committed overlays (so the
355    /// group is fed or cleared immediately), and marks dirty.
356    pub fn set_sketch_visible(&mut self, id: &str, visible: bool) {
357        if visible {
358            self.hidden_sketches.remove(id);
359        } else {
360            self.hidden_sketches.insert(id.to_string());
361        }
362        self.refresh_committed_sketches();
363    }
364
365    /// The committed sketches to list in the Scene tree: every `"S"` feature at the
366    /// current rollback (minus the active edit), each with its live visibility — the
367    /// ordered `(id, visible)` list the Scene panel snapshots.
368    pub fn committed_sketches(&self) -> Vec<(String, bool)> {
369        crate::visibility::named_visibility(self.committed_sketch_ids(), &self.hidden_sketches)
370    }
371
372    /// The committed sketches as JSON (`[{"name":<id>,"visible":<bool>}]`) — the
373    /// sibling of [`scene_entities_json`](Self::scene_entities_json) the Scene panel
374    /// publishes for the headed verifier (kept a SEPARATE method so the solids array's
375    /// shape is unchanged).
376    pub fn sketch_entities_json(&self) -> String {
377        crate::visibility::named_visibility_json(self.committed_sketches())
378    }
379}
380
381