axiolid-brep 0.3.2

Exact analytic B-rep result contracts over neutral topology
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
#![forbid(unsafe_code)]

//! Strict exact B-rep results over neutral analytic curve and surface values.
//!
//! [`axiolid_topology::BRep`] remains generic so graph/import clients can link
//! their own handles. [`ExactBRep`] binds that graph to owned `Curve3`, `Curve2`,
//! and `Surface` catalogs, then requires every support and trim span explicitly.
//! It does not evaluate, intersect, or tessellate geometry.

use std::collections::HashMap;
use std::fmt;

use axiolid_core::Interval;
use axiolid_curve::{Curve2, Curve3};
use axiolid_surface::Surface;
use axiolid_topology::{audit_brep, BRep, BRepHealth, EdgeId, FaceId, LoopId, ShellId};

/// Persistent structural names for faces and edges.
pub mod name;

pub use name::{EdgeName, FaceName, Operand, SweptFace};

macro_rules! geometry_id {
    ($name:ident, $label:literal) => {
        #[doc = concat!("Typed handle into the exact B-rep ", $label, " catalog.")]
        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub struct $name(u32);

        impl $name {
            fn from_index(index: usize) -> Self {
                Self(u32::try_from(index).expect("exact B-rep catalog exceeds u32 capacity"))
            }

            /// Zero-based catalog index.
            pub const fn index(self) -> usize {
                self.0 as usize
            }
        }
    };
}

geometry_id!(Curve3Id, "3D curve");
geometry_id!(Curve2Id, "2D pcurve");
geometry_id!(SurfaceId, "surface");

/// Topology whose supports are typed references into [`ExactBRep`] catalogs.
pub type ExactTopology = BRep<Curve3Id, Curve2Id, SurfaceId>;

/// Owned, analytic boundary representation.
///
/// Every edge and pcurve use has a finite, non-zero native parameter span. An
/// interval is deliberately owned here rather than inferred from endpoints:
/// periodic supports, reversed pcurves, and parameter re-mapping are not
/// recoverable from coordinates. The result may be an open sheet; an eventual
/// exact-solid contract will additionally require a selected closed shell.
#[derive(Debug, Clone, PartialEq)]
pub struct ExactBRep {
    topology: ExactTopology,
    curves3: Vec<Curve3>,
    curves2: Vec<Curve2>,
    surfaces: Vec<Surface>,
    edge_intervals: HashMap<EdgeId, Interval>,
    pcurve_intervals: HashMap<(LoopId, usize), Interval>,
    face_names: HashMap<FaceId, FaceName>,
    edge_names: HashMap<EdgeId, EdgeName>,
}

impl ExactBRep {
    /// Persistent structural name for a face, when the producer supplied one.
    ///
    /// Absence means the producing operation did not track provenance, not
    /// that the face is invalid. Callers that require a name should treat
    /// `None` as a refusal rather than substituting an index.
    pub fn face_name(&self, face: FaceId) -> Option<&FaceName> {
        self.face_names.get(&face)
    }

    /// Persistent structural name for an edge, when the producer supplied one.
    pub fn edge_name(&self, edge: EdgeId) -> Option<&EdgeName> {
        self.edge_names.get(&edge)
    }

    /// Find the face carrying `name`.
    ///
    /// This is the lookup that makes names useful across operations: a caller
    /// holding a name from before an edit resolves it against the new result
    /// instead of hoping an arena index still points at the same face.
    pub fn face_by_name(&self, name: &FaceName) -> Option<FaceId> {
        self.face_names
            .iter()
            .find(|(_, candidate)| *candidate == name)
            .map(|(id, _)| *id)
    }

    /// Find the edge carrying `name`.
    pub fn edge_by_name(&self, name: &EdgeName) -> Option<EdgeId> {
        self.edge_names
            .iter()
            .find(|(_, candidate)| *candidate == name)
            .map(|(id, _)| *id)
    }
    /// Name the two cap faces of a swept solid after assembly.
    ///
    /// The caps are identified by construction order -- a sweep adds the
    /// start cap then the end cap before any wall -- rather than by
    /// geometry, because a cap that shares a plane with a wall would be
    /// ambiguous geometrically. Passing `None` leaves that cap unnamed.
    pub fn name_caps(&mut self, start: Option<FaceName>, end: Option<FaceName>) {
        let start_id = self.topology.face_id_at(0);
        let end_id = self.topology.face_id_at(1);
        if let (Some(name), Some(id)) = (start, start_id) {
            self.face_names.insert(id, name);
        }
        if let (Some(name), Some(id)) = (end, end_id) {
            self.face_names.insert(id, name);
        }
    }

    /// Structural topology with typed support handles.
    pub fn topology(&self) -> &ExactTopology {
        &self.topology
    }

    /// Owned exact 3D curve supports.
    pub fn curves3(&self) -> &[Curve3] {
        &self.curves3
    }

    /// Owned exact 2D trim-curve supports.
    pub fn curves2(&self) -> &[Curve2] {
        &self.curves2
    }

    /// Owned exact support surfaces.
    pub fn surfaces(&self) -> &[Surface] {
        &self.surfaces
    }

    /// Native parameter span oriented from an edge's start vertex to its end.
    pub fn edge_interval(&self, edge: EdgeId) -> Option<Interval> {
        self.edge_intervals.get(&edge).copied()
    }

    /// Native parameter span for an edge use's pcurve in loop traversal order.
    pub fn pcurve_interval(&self, loop_id: LoopId, use_index: usize) -> Option<Interval> {
        self.pcurve_intervals.get(&(loop_id, use_index)).copied()
    }
}

/// Mutable assembly state that can only yield an [`ExactBRep`] after validation.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ExactBRepBuilder {
    topology: ExactTopology,
    curves3: Vec<Curve3>,
    curves2: Vec<Curve2>,
    surfaces: Vec<Surface>,
    edge_intervals: HashMap<EdgeId, Interval>,
    pcurve_intervals: HashMap<(LoopId, usize), Interval>,
    face_names: HashMap<FaceId, FaceName>,
    edge_names: HashMap<EdgeId, EdgeName>,
}

impl ExactBRepBuilder {
    /// Record the persistent structural name of a face.
    ///
    /// Naming is opt-in per producer: an operation that cannot honestly say
    /// where a face came from simply does not call this, and the face reports
    /// no name rather than a misleading one.
    pub fn set_face_name(&mut self, face: FaceId, name: FaceName) {
        self.face_names.insert(face, name);
    }

    /// Record the persistent structural name of an edge.
    pub fn set_edge_name(&mut self, edge: EdgeId, name: EdgeName) {
        self.edge_names.insert(edge, name);
    }
    /// Fallibly reserve owned support and interval catalogs for bounded assembly.
    pub fn try_reserve(
        &mut self,
        curves3: usize,
        curves2: usize,
        surfaces: usize,
        edge_intervals: usize,
        pcurve_intervals: usize,
    ) -> Result<(), std::collections::TryReserveError> {
        self.curves3.try_reserve_exact(curves3)?;
        self.curves2.try_reserve_exact(curves2)?;
        self.surfaces.try_reserve_exact(surfaces)?;
        self.edge_intervals.try_reserve(edge_intervals)?;
        self.pcurve_intervals.try_reserve(pcurve_intervals)?;
        Ok(())
    }

    /// Store an exact 3D curve support.
    pub fn add_curve3(&mut self, curve: Curve3) -> Curve3Id {
        let id = Curve3Id::from_index(self.curves3.len());
        self.curves3.push(curve);
        id
    }

    /// Store an exact 2D pcurve support.
    pub fn add_curve2(&mut self, curve: Curve2) -> Curve2Id {
        let id = Curve2Id::from_index(self.curves2.len());
        self.curves2.push(curve);
        id
    }

    /// Store an exact surface support.
    pub fn add_surface(&mut self, surface: Surface) -> SurfaceId {
        let id = SurfaceId::from_index(self.surfaces.len());
        self.surfaces.push(surface);
        id
    }

    /// Mutable typed topology under construction. [`Self::finish`] validates it.
    pub fn topology_mut(&mut self) -> &mut ExactTopology {
        &mut self.topology
    }

    /// State an edge's finite native curve span.
    pub fn set_edge_interval(&mut self, edge: EdgeId, interval: Interval) {
        self.edge_intervals.insert(edge, interval);
    }

    /// State an edge use's finite native pcurve span in its loop traversal order.
    pub fn set_pcurve_interval(&mut self, loop_id: LoopId, use_index: usize, interval: Interval) {
        self.pcurve_intervals.insert((loop_id, use_index), interval);
    }

    /// Copy every vertex, edge, loop, face and shell of `other` into this
    /// builder, with its curves, surfaces, intervals and names, and return
    /// the new handles of `other`'s shells in order.
    ///
    /// Solids are NOT copied: the caller says what the shells are -- the
    /// outer shell of another solid, or a void of one already here. With
    /// `reverse`, every face is used reversed in its shell, which turns a
    /// solid's outer shell into the boundary of the same region seen from
    /// outside it: a void.
    pub fn append(&mut self, other: &ExactBRep, reverse: bool) -> Vec<ShellId> {
        use axiolid_topology::{Edge, EdgeUse, Face, Loop, Orientation, Shell, Vertex};

        let curves3: Vec<Curve3Id> = other
            .curves3
            .iter()
            .map(|curve| self.add_curve3(curve.clone()))
            .collect();
        let curves2: Vec<Curve2Id> = other
            .curves2
            .iter()
            .map(|curve| self.add_curve2(curve.clone()))
            .collect();
        let surfaces: Vec<SurfaceId> = other
            .surfaces
            .iter()
            .map(|surface| self.add_surface(surface.clone()))
            .collect();
        let source = &other.topology;
        let vertices: Vec<_> = source
            .vertices()
            .iter()
            .map(|vertex| {
                self.topology.add_vertex(Vertex {
                    position: vertex.position,
                })
            })
            .collect();
        let mut edges = Vec::with_capacity(source.edges().len());
        for (index, edge) in source.edges().iter().enumerate() {
            let id = self.topology.add_edge(Edge {
                start: vertices[edge.start.index()],
                end: vertices[edge.end.index()],
                curve: edge.curve.map(|curve| curves3[curve.index()]),
            });
            if let Some(old) = source.edge_id_at(index) {
                if let Some(interval) = other.edge_intervals.get(&old) {
                    self.edge_intervals.insert(id, *interval);
                }
                if let Some(name) = other.edge_names.get(&old) {
                    self.edge_names.insert(id, name.clone());
                }
            }
            edges.push(id);
        }
        let mut loops = Vec::with_capacity(source.loops().len());
        for (index, wire) in source.loops().iter().enumerate() {
            let id = self.topology.add_loop(Loop {
                edges: wire
                    .edges
                    .iter()
                    .map(|use_| EdgeUse {
                        edge: edges[use_.edge.index()],
                        orientation: use_.orientation,
                        pcurve: use_.pcurve.map(|curve| curves2[curve.index()]),
                    })
                    .collect(),
            });
            if let Some(old) = source.loop_id_at(index) {
                for use_index in 0..wire.edges.len() {
                    if let Some(interval) = other.pcurve_intervals.get(&(old, use_index)) {
                        self.pcurve_intervals.insert((id, use_index), *interval);
                    }
                }
            }
            loops.push(id);
        }
        let mut faces = Vec::with_capacity(source.faces().len());
        for (index, face) in source.faces().iter().enumerate() {
            let id = self.topology.add_face(Face {
                surface: face.surface.map(|surface| surfaces[surface.index()]),
                bounds: face
                    .bounds
                    .iter()
                    .map(|bound| axiolid_topology::FaceBound {
                        loop_id: loops[bound.loop_id.index()],
                        ..*bound
                    })
                    .collect(),
                orientation: face.orientation,
            });
            if let Some(name) = source
                .face_id_at(index)
                .and_then(|old| other.face_names.get(&old))
            {
                self.face_names.insert(id, name.clone());
            }
            faces.push(id);
        }
        source
            .shells()
            .iter()
            .map(|shell| {
                self.topology.add_shell(Shell {
                    faces: shell
                        .faces
                        .iter()
                        .map(|&(face, sense)| {
                            let sense = match (sense, reverse) {
                                (sense, false) => sense,
                                (Orientation::Forward, true) => Orientation::Reversed,
                                (Orientation::Reversed, true) => Orientation::Forward,
                            };
                            (faces[face.index()], sense)
                        })
                        .collect(),
                    closed: shell.closed,
                })
            })
            .collect()
    }

    /// Validate and freeze the exact B-rep result.
    ///
    /// Refuses a result with no faces, topology that fails
    /// [`axiolid_topology::audit_brep`], and any edge, edge use or face whose
    /// support or finite non-zero interval is missing or does not resolve in
    /// its catalog (see [`ExactBRepError`]). Closure is not required: an open
    /// sheet is a valid exact result.
    pub fn finish(self) -> Result<ExactBRep, ExactBRepError> {
        validate(&self)?;
        Ok(ExactBRep {
            topology: self.topology,
            curves3: self.curves3,
            curves2: self.curves2,
            surfaces: self.surfaces,
            edge_intervals: self.edge_intervals,
            pcurve_intervals: self.pcurve_intervals,
            face_names: self.face_names,
            edge_names: self.edge_names,
        })
    }
}

/// Why exact B-rep assembly was refused.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExactBRepError {
    /// A result without faces is not a boundary representation.
    Empty,
    /// Generic topology has unresolved handles or invalid loop/face structure.
    Topology(BRepHealth),
    /// An edge did not state its exact three-dimensional support.
    MissingEdgeCurve { edge_index: usize },
    /// An edge support handle does not resolve in the 3D curve catalog.
    UnknownCurve3 { edge_index: usize },
    /// An edge did not state its native support-curve interval.
    MissingEdgeInterval { edge_index: usize },
    /// An edge support interval was non-finite or zero-length.
    InvalidEdgeInterval { edge_index: usize },
    /// An edge use did not state its trim curve in the owning face's parameters.
    MissingPcurve { loop_index: usize, use_index: usize },
    /// A pcurve support handle does not resolve in the 2D curve catalog.
    UnknownCurve2 { loop_index: usize, use_index: usize },
    /// A pcurve did not state its native interval.
    MissingPcurveInterval { loop_index: usize, use_index: usize },
    /// A pcurve interval was non-finite or zero-length.
    InvalidPcurveInterval { loop_index: usize, use_index: usize },
    /// A face did not state its exact support surface.
    MissingFaceSurface { face_index: usize },
    /// A face support handle does not resolve in the surface catalog.
    UnknownSurface { face_index: usize },
}

impl fmt::Display for ExactBRepError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => f.write_str("exact B-rep requires at least one face"),
            Self::Topology(_) => f.write_str("exact B-rep topology is structurally invalid"),
            Self::MissingEdgeCurve { edge_index } => {
                write!(f, "edge {edge_index} lacks a 3D curve")
            }
            Self::UnknownCurve3 { edge_index } => {
                write!(f, "edge {edge_index} has an unknown 3D curve")
            }
            Self::MissingEdgeInterval { edge_index } => {
                write!(f, "edge {edge_index} lacks a curve interval")
            }
            Self::InvalidEdgeInterval { edge_index } => {
                write!(f, "edge {edge_index} has an invalid curve interval")
            }
            Self::MissingPcurve {
                loop_index,
                use_index,
            } => write!(f, "loop {loop_index} use {use_index} lacks a pcurve"),
            Self::UnknownCurve2 {
                loop_index,
                use_index,
            } => write!(f, "loop {loop_index} use {use_index} has an unknown pcurve"),
            Self::MissingPcurveInterval {
                loop_index,
                use_index,
            } => write!(
                f,
                "loop {loop_index} use {use_index} lacks a pcurve interval"
            ),
            Self::InvalidPcurveInterval {
                loop_index,
                use_index,
            } => write!(
                f,
                "loop {loop_index} use {use_index} has an invalid pcurve interval"
            ),
            Self::MissingFaceSurface { face_index } => {
                write!(f, "face {face_index} lacks a support surface")
            }
            Self::UnknownSurface { face_index } => {
                write!(f, "face {face_index} has an unknown support surface")
            }
        }
    }
}

impl std::error::Error for ExactBRepError {}

fn validate(value: &ExactBRepBuilder) -> Result<(), ExactBRepError> {
    if value.topology.faces().is_empty() {
        return Err(ExactBRepError::Empty);
    }
    let health = audit_brep(&value.topology);
    if !health.is_tessellable() {
        return Err(ExactBRepError::Topology(health));
    }
    for (edge_index, edge) in value.topology.edges().iter().enumerate() {
        let Some(curve) = edge.curve else {
            return Err(ExactBRepError::MissingEdgeCurve { edge_index });
        };
        if curve.index() >= value.curves3.len() {
            return Err(ExactBRepError::UnknownCurve3 { edge_index });
        }
        let Some(edge_id) = value.topology.edge_id_at(edge_index) else {
            return Err(ExactBRepError::MissingEdgeInterval { edge_index });
        };
        let Some(interval) = value.edge_intervals.get(&edge_id) else {
            return Err(ExactBRepError::MissingEdgeInterval { edge_index });
        };
        if !valid_interval(*interval) {
            return Err(ExactBRepError::InvalidEdgeInterval { edge_index });
        }
    }
    for (loop_index, loop_) in value.topology.loops().iter().enumerate() {
        let Some(loop_id) = value.topology.loop_id_at(loop_index) else {
            return Err(ExactBRepError::Topology(health));
        };
        for (use_index, use_) in loop_.edges.iter().enumerate() {
            let Some(curve) = use_.pcurve else {
                return Err(ExactBRepError::MissingPcurve {
                    loop_index,
                    use_index,
                });
            };
            if curve.index() >= value.curves2.len() {
                return Err(ExactBRepError::UnknownCurve2 {
                    loop_index,
                    use_index,
                });
            }
            let Some(interval) = value.pcurve_intervals.get(&(loop_id, use_index)) else {
                return Err(ExactBRepError::MissingPcurveInterval {
                    loop_index,
                    use_index,
                });
            };
            if !valid_interval(*interval) {
                return Err(ExactBRepError::InvalidPcurveInterval {
                    loop_index,
                    use_index,
                });
            }
        }
    }
    for (face_index, face) in value.topology.faces().iter().enumerate() {
        let Some(surface) = face.surface else {
            return Err(ExactBRepError::MissingFaceSurface { face_index });
        };
        if surface.index() >= value.surfaces.len() {
            return Err(ExactBRepError::UnknownSurface { face_index });
        }
    }
    Ok(())
}

fn valid_interval(interval: Interval) -> bool {
    interval.start.is_finite() && interval.end.is_finite() && interval.length() > 0.0
}