BREP_render 0.1.0

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! Per-entity + group visibility for a solid's faces / edges / vertices.
//!
//! The whole-solid + whole-scene toggles already live on
//! [`SolidDisplay::visible`](crate::scene::SolidDisplay) /
//! [`RenderScene::set_visible`]. THIS module adds the finer grain the Scene tree
//! needs: an INDIVIDUAL face, edge or vertex can be hidden, and a WHOLE GROUP
//! (all faces / all edges / all vertices of a solid) toggled — with a tristate
//! ([`GroupState`]) group readout for the UI checkbox.
//!
//! # Where the state lives
//!
//! Each [`SolidDisplay`] carries an [`EntityVisibility`] — a set of HIDDEN
//! indices per kind (default-visible: an empty set = everything shown). The key
//! is the entity's INDEX in the solid's `faces` / `edges` / `vertices` list, the
//! exact index the render pass and the Scene tree already enumerate by (so a
//! hidden face maps straight onto a mesh triangle-range skip — see
//! [`crate::render`]). Reused solids keep their sets across history reruns (the
//! pipeline clones the `SolidDisplay`); a freshly re-tessellated solid resets to
//! all-visible, mirroring how the per-solid `visible` flag behaves.
//!
//! # How faces actually hide (the render mechanism)
//!
//! A solid's mesh emits each face's triangles as one contiguous run (the kernel
//! groups by `face_ids`), and the renderer already keeps a per-face
//! `first_index/index_count` range. The face pass, instead of one whole-mesh
//! draw, walks the faces and coalesces CONTIGUOUS VISIBLE ranges into draw
//! calls, breaking (flushing) the run at every hidden face — so a hidden face's
//! triangles are simply never submitted. Edges/vertices skip their line
//! segments / point sprites the same way. No mesh is rebuilt; visibility is
//! purely a draw-time mask, so toggling is free of any re-tessellation.

use crate::engine_state::EngineState;
use crate::scene::{RenderScene, SolidDisplay};
use std::collections::HashSet;

/// Which sub-entity list of a solid a visibility toggle addresses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EntityKind {
    Face,
    Edge,
    Vertex,
}

impl EntityKind {
    /// Parse the Scene-tree / verifier kind token (`"face"` / `"edge"` /
    /// `"vertex"`, case-insensitive). `None` for anything else.
    pub fn parse(kind: &str) -> Option<Self> {
        match kind.to_ascii_lowercase().as_str() {
            "face" => Some(Self::Face),
            "edge" => Some(Self::Edge),
            "vertex" => Some(Self::Vertex),
            _ => None,
        }
    }

    /// The lowercase token (round-trips with [`parse`](Self::parse)).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Face => "face",
            Self::Edge => "edge",
            Self::Vertex => "vertex",
        }
    }
}

/// A group checkbox's tristate: every entity of the kind shown, none shown, or a
/// mix. An empty group reads [`All`](GroupState::All) — nothing to hide.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GroupState {
    All,
    Partial,
    None,
}

impl GroupState {
    /// The lowercase token the verifier asserts against (`"all"` / `"partial"` /
    /// `"none"`).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::All => "all",
            Self::Partial => "partial",
            Self::None => "none",
        }
    }
}

/// The hidden-entity sets of ONE solid (empty = all visible). Indices are into
/// the owning [`SolidDisplay`]'s `faces` / `edges` / `vertices`.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct EntityVisibility {
    hidden_faces: HashSet<usize>,
    hidden_edges: HashSet<usize>,
    hidden_vertices: HashSet<usize>,
}

impl EntityVisibility {
    fn set_of(&self, kind: EntityKind) -> &HashSet<usize> {
        match kind {
            EntityKind::Face => &self.hidden_faces,
            EntityKind::Edge => &self.hidden_edges,
            EntityKind::Vertex => &self.hidden_vertices,
        }
    }

    fn set_mut(&mut self, kind: EntityKind) -> &mut HashSet<usize> {
        match kind {
            EntityKind::Face => &mut self.hidden_faces,
            EntityKind::Edge => &mut self.hidden_edges,
            EntityKind::Vertex => &mut self.hidden_vertices,
        }
    }

    /// Whether entity `index` of `kind` is currently shown.
    pub fn is_visible(&self, kind: EntityKind, index: usize) -> bool {
        !self.set_of(kind).contains(&index)
    }

    /// Whether ANY entity of `kind` is hidden — the render pass's fast-path
    /// guard (nothing hidden ⇒ keep the single whole-buffer draw).
    pub fn any_hidden(&self, kind: EntityKind) -> bool {
        !self.set_of(kind).is_empty()
    }

    /// Show/hide a single entity of `kind`.
    pub fn set_visible(&mut self, kind: EntityKind, index: usize, visible: bool) {
        if visible {
            self.set_mut(kind).remove(&index);
        } else {
            self.set_mut(kind).insert(index);
        }
    }

    /// Show/hide EVERY entity of `kind`. `count` is the number of entities of
    /// that kind, so "hide all" enumerates them (and "show all" clears).
    pub fn set_group_visible(&mut self, kind: EntityKind, count: usize, visible: bool) {
        let set = self.set_mut(kind);
        set.clear();
        if !visible {
            set.extend(0..count);
        }
    }

    /// The group tristate for `count` entities of `kind`. O(1): the hidden set
    /// satisfies `hidden ⊆ 0..count` (see [`all_hidden`](Self::all_hidden)), so its
    /// `len()` IS the hidden count — no per-entity scan. Called per solid per egui
    /// frame by the Scene panel, so the O(1) matters on point/edge-heavy models.
    pub fn group_state(&self, kind: EntityKind, count: usize) -> GroupState {
        if count == 0 {
            return GroupState::All;
        }
        let hidden = self.set_of(kind).len();
        if hidden == 0 {
            GroupState::All
        } else if hidden >= count {
            GroupState::None
        } else {
            GroupState::Partial
        }
    }

    // Render-pass conveniences (kept terse — called per solid per frame).
    pub fn is_face_visible(&self, index: usize) -> bool {
        self.is_visible(EntityKind::Face, index)
    }
    pub fn is_edge_visible(&self, index: usize) -> bool {
        self.is_visible(EntityKind::Edge, index)
    }
    pub fn is_vertex_visible(&self, index: usize) -> bool {
        self.is_visible(EntityKind::Vertex, index)
    }
    pub fn any_face_hidden(&self) -> bool {
        self.any_hidden(EntityKind::Face)
    }
    pub fn any_edge_hidden(&self) -> bool {
        self.any_hidden(EntityKind::Edge)
    }
    pub fn any_vertex_hidden(&self) -> bool {
        self.any_hidden(EntityKind::Vertex)
    }

    /// Whether EVERY entity of `kind` is hidden — O(1). A solid's hidden set is
    /// always paired with the entity counts it was built against: geometry changes
    /// replace the whole `SolidDisplay` (fresh, empty visibility), and a reused
    /// display keeps its counts AND its hidden set together — so `hidden ⊆ 0..count`
    /// holds universally and `len() == count` ⇔ the whole group is off (individual
    /// hides leave `len() < count`). `>=` rather than `==` is defensive only. The
    /// render pass uses this to skip a fully-hidden group's per-vertex draw loop.
    pub fn all_hidden(&self, kind: EntityKind, count: usize) -> bool {
        count > 0 && self.set_of(kind).len() >= count
    }
    pub fn all_vertices_hidden(&self, count: usize) -> bool {
        self.all_hidden(EntityKind::Vertex, count)
    }
}

/// The count of entities of `kind` on a solid (group toggles / tristate).
fn entity_count(solid: &SolidDisplay, kind: EntityKind) -> usize {
    match kind {
        EntityKind::Face => solid.faces.len(),
        EntityKind::Edge => solid.edges.len(),
        EntityKind::Vertex => solid.vertices.len(),
    }
}

// --- RenderScene: per-entity / group visibility (kept here, not in scene.rs, so
//     the visibility surface stays in one module) ------------------------------
impl RenderScene {
    /// Show/hide ONE face/edge/vertex of a solid. False if the solid is unknown.
    pub fn set_entity_visible(
        &mut self,
        solid: &str,
        kind: EntityKind,
        index: usize,
        visible: bool,
    ) -> bool {
        match self.solid_mut(solid) {
            Some(s) => {
                s.visibility.set_visible(kind, index, visible);
                true
            }
            None => false,
        }
    }

    /// Show/hide a whole group (all faces / all edges / all vertices) of a solid.
    /// False if the solid is unknown.
    pub fn set_group_visible(&mut self, solid: &str, kind: EntityKind, visible: bool) -> bool {
        let Some(count) = self.solid(solid).map(|s| entity_count(s, kind)) else {
            return false;
        };
        // The solid exists (count resolved above), so `solid_mut` is Some.
        if let Some(s) = self.solid_mut(solid) {
            s.visibility.set_group_visible(kind, count, visible);
        }
        true
    }

    /// Whether entity `index` of `kind` on `solid` is shown (`None` if unknown).
    pub fn entity_visible(&self, solid: &str, kind: EntityKind, index: usize) -> Option<bool> {
        self.solid(solid).map(|s| s.visibility.is_visible(kind, index))
    }

    /// The group tristate for `solid`'s `kind` (`None` if the solid is unknown).
    pub fn group_visibility(&self, solid: &str, kind: EntityKind) -> Option<GroupState> {
        self.solid(solid)
            .map(|s| s.visibility.group_state(kind, entity_count(s, kind)))
    }
}

// --- EngineState: the UI-facing visibility API (marks dirty; the Scene panel
//     drives these and reads the queries back) ---------------------------------
impl EngineState {
    /// Show/hide ONE face/edge/vertex of a solid, by its index in the solid's
    /// face/edge/vertex list — the same index the Scene tree enumerates. Marks
    /// dirty. Returns false if the solid is unknown.
    pub fn set_entity_visible(
        &mut self,
        solid: &str,
        kind: EntityKind,
        index: usize,
        visible: bool,
    ) -> bool {
        let ok = self.scene.set_entity_visible(solid, kind, index, visible);
        if ok {
            self.dirty = true;
        }
        ok
    }

    /// Show/hide a WHOLE group (all faces / all edges / all vertices of a solid).
    /// Marks dirty. Returns false if the solid is unknown.
    pub fn set_group_visible(&mut self, solid: &str, kind: EntityKind, visible: bool) -> bool {
        let ok = self.scene.set_group_visible(solid, kind, visible);
        if ok {
            self.dirty = true;
        }
        ok
    }

    /// Whether entity `index` of `kind` on `solid` is shown (`None` if unknown).
    pub fn entity_visible(&self, solid: &str, kind: EntityKind, index: usize) -> Option<bool> {
        self.scene.entity_visible(solid, kind, index)
    }

    /// The group tristate for `solid`'s `kind` (`None` if the solid is unknown).
    pub fn group_visibility(&self, solid: &str, kind: EntityKind) -> Option<GroupState> {
        self.scene.group_visibility(solid, kind)
    }

    /// Per-entity + group visibility as JSON — the readout the headed verifier
    /// asserts against (a companion to
    /// [`scene_entities_json`](EngineState::scene_entities_json), which lists the
    /// entities but not their per-entity visibility):
    /// `[{name, visible, faces:{group, states:[bool;n]}, edges:{…}, vertices:{…}}]`
    /// where `states[i]` is entity `i`'s visibility and `group` is
    /// `"all"|"partial"|"none"`.
    pub fn scene_visibility_json(&self) -> String {
        let kinds = [
            ("faces", EntityKind::Face),
            ("edges", EntityKind::Edge),
            ("vertices", EntityKind::Vertex),
        ];
        let solids: Vec<serde_json::Value> = self
            .scene
            .solids()
            .iter()
            .map(|solid| {
                let mut obj = serde_json::Map::new();
                obj.insert("name".into(), serde_json::json!(solid.name));
                obj.insert("visible".into(), serde_json::json!(solid.visible));
                for (key, kind) in kinds {
                    let count = entity_count(solid, kind);
                    let states: Vec<bool> =
                        (0..count).map(|i| solid.visibility.is_visible(kind, i)).collect();
                    obj.insert(
                        key.into(),
                        serde_json::json!({
                            "group": solid.visibility.group_state(kind, count).as_str(),
                            "states": states,
                        }),
                    );
                }
                serde_json::Value::Object(obj)
            })
            .collect();
        serde_json::Value::Array(solids).to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cube_history(name: &str) -> String {
        serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [{
                "type": "P.CU",
                "inputParams": {
                    "id": name,
                    "sizeX": 10.0, "sizeY": 10.0, "sizeZ": 10.0,
                    "transform": {
                        "position": [0.0, 0.0, 0.0],
                        "rotationEuler": [0.0, 0.0, 0.0],
                        "scale": [1.0, 1.0, 1.0]
                    },
                    "boolean": { "targets": [], "operation": "NONE" }
                },
                "persistentData": {}
            }]
        })
        .to_string()
    }

    #[test]
    fn entity_visibility_hide_show_and_group_tristate() {
        let mut vis = EntityVisibility::default();
        // Default: all visible, group reads All.
        assert!(vis.is_visible(EntityKind::Face, 0));
        assert!(!vis.any_hidden(EntityKind::Face));
        assert_eq!(vis.group_state(EntityKind::Face, 6), GroupState::All);

        // Hide one → Partial, only that index hidden.
        vis.set_visible(EntityKind::Face, 2, false);
        assert!(!vis.is_visible(EntityKind::Face, 2));
        assert!(vis.is_visible(EntityKind::Face, 3));
        assert!(vis.any_hidden(EntityKind::Face));
        assert_eq!(vis.group_state(EntityKind::Face, 6), GroupState::Partial);

        // Re-show it → back to All.
        vis.set_visible(EntityKind::Face, 2, true);
        assert_eq!(vis.group_state(EntityKind::Face, 6), GroupState::All);

        // Hide the whole group → None, every index hidden.
        vis.set_group_visible(EntityKind::Face, 6, false);
        assert_eq!(vis.group_state(EntityKind::Face, 6), GroupState::None);
        assert!(!vis.is_visible(EntityKind::Face, 5));
        // Show one back → Partial.
        vis.set_visible(EntityKind::Face, 5, true);
        assert_eq!(vis.group_state(EntityKind::Face, 6), GroupState::Partial);
        // Kinds are independent: edges untouched.
        assert_eq!(vis.group_state(EntityKind::Edge, 12), GroupState::All);
    }

    #[test]
    fn engine_per_entity_and_group_visibility_through_scene() {
        let mut engine = EngineState::new();
        engine.set_history_json(&cube_history("Box")).unwrap();

        // Individual: hide face 0.
        assert!(engine.set_entity_visible("Box", EntityKind::Face, 0, false));
        assert_eq!(engine.entity_visible("Box", EntityKind::Face, 0), Some(false));
        assert_eq!(engine.entity_visible("Box", EntityKind::Face, 1), Some(true));
        assert_eq!(
            engine.group_visibility("Box", EntityKind::Face),
            Some(GroupState::Partial)
        );

        // Group: hide all faces → None; edges/vertices unaffected.
        assert!(engine.set_group_visible("Box", EntityKind::Face, false));
        assert_eq!(
            engine.group_visibility("Box", EntityKind::Face),
            Some(GroupState::None)
        );
        assert_eq!(
            engine.group_visibility("Box", EntityKind::Edge),
            Some(GroupState::All)
        );

        // Group: show all faces back → All.
        assert!(engine.set_group_visible("Box", EntityKind::Face, true));
        assert_eq!(
            engine.group_visibility("Box", EntityKind::Face),
            Some(GroupState::All)
        );

        // Unknown solid → false / None.
        assert!(!engine.set_entity_visible("Nope", EntityKind::Edge, 0, false));
        assert_eq!(engine.entity_visible("Nope", EntityKind::Edge, 0), None);
        assert_eq!(engine.group_visibility("Nope", EntityKind::Edge), None);
    }

    #[test]
    fn scene_visibility_json_reports_states_and_group() {
        let mut engine = EngineState::new();
        engine.set_history_json(&cube_history("Box")).unwrap();
        engine.set_entity_visible("Box", EntityKind::Edge, 3, false);

        let json: serde_json::Value =
            serde_json::from_str(&engine.scene_visibility_json()).unwrap();
        let solid = &json.as_array().unwrap()[0];
        assert_eq!(solid["name"], "Box");
        assert_eq!(solid["visible"], true);
        // A cube: 6 faces / 12 edges / 8 vertices, all faces still shown.
        assert_eq!(solid["faces"]["group"], "all");
        assert_eq!(solid["faces"]["states"].as_array().unwrap().len(), 6);
        // Edge 3 is hidden → group partial, states[3] == false.
        assert_eq!(solid["edges"]["group"], "partial");
        assert_eq!(solid["edges"]["states"][3], false);
        assert_eq!(solid["edges"]["states"][2], true);
    }

    #[test]
    fn entity_kind_token_roundtrips() {
        for k in [EntityKind::Face, EntityKind::Edge, EntityKind::Vertex] {
            assert_eq!(EntityKind::parse(k.as_str()), Some(k));
        }
        assert_eq!(EntityKind::parse("FACE"), Some(EntityKind::Face));
        assert_eq!(EntityKind::parse("solid"), None);
    }
}